how to send json output through Servlet using JACKSON Streaming api - json

I am trying to call the servlet which suppose sends the data in jSON format as response. I am using JACKSON libraries for this, i can write the output to a file using jfactory.createJsonGenerator(file); if i use other than that i cannot get output. Let me know if i am missing something here.
doGet method from servlet
JsonFactory jfactory = new JsonFactory();
/*** write to file ***/
try {
out = response.getWriter();
JsonGenerator jGenerator = jfactory.createJsonGenerator(out);
jGenerator.writeStartObject(); // {
jGenerator.writeStringField("title", title); // "title" : title
jGenerator.writeStringField("Description", desc); // "desc" : Description
jGenerator.writeFieldName("images");
jGenerator.writeStartArray(); // [
for(String img: imageArray){
jGenerator.writeString(img); // "msg 1"
}
jGenerator.writeEndArray(); // ]
jGenerator.writeEndObject(); // }
//jGenerator.close();
out.flush();
System.out.println(jGenerator.getOutputContext().toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HTML page
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.getJSON("http://localhost:8080/JsoupPrj/JasonGen",function(data){
$("#content").html(data);
$('.log').html('it is called');
});
});
</script>
</head>
<body>
<div id="content"></div>
<div class="log"></div>

this may be late. but i thought i will share my experiences in case it helps someone.
here is a sample of my pom.xml:
<dependency>
<groupId> org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>
here is what i have in my servlet:
List<String> ooErrors = new ArrayList<String>();
//serialize the errors object.
ObjectMapper mapper = new ObjectMapper();
String errorsJson = mapper.writeValueAsString(ooErrors);
response.setContentType("application/json");
response.getOutputStream().print(errorsJson);
hopefully, this helps someone.

Related

Read a text file containing json objects in .jsp file and populate it in HTML table

I want to extract a json data from a text file and want to populate that data in a HTML table .These and operations I have to inside a .jsp file. Is it possible.Can any one give me a sample code?
You can read the JSON file using JSONParse API below is the code to read that :
<% public void loadJSON() {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("f:\\test.json"));
JSONObject jsonObject = (JSONObject) obj;
System.out.println(jsonObject);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}%>
from above code you will able to get JSON Object store into Some variable like String myVar=jsonObject .toString();//which returns String then use same into ajax function to iterate through each json element and create the table like below and import this script too : <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table id="records_table" border='1'>
<tr>
<th>Rank</th>
<th>Content</th>
<th>UID</th>
</tr>
</table>
<script>
var response=<%=myVar%>//let see this is variable where JSON String is stored
response = $.parseJSON(response);
$(function() {
$.each(response, function(i, item) {
$('<tr>').append(
$('<td>').text(item.rank),
$('<td>').text(item.content),
$('<td>').text(item.UID)
).appendTo('#records_table');
// $('#records_table').append($tr);
//console.log($tr.wrap('<p>').html());
});
});
</script>
For more details : Fill html table based on JSON and try to debug line by line & good luck

Unexpected token in JSON at position 0 - Angular2 - Spring API

My REST API which has been written in SpringBoot has following method for the purpose of uploading a photo.
#RequestMapping(method = RequestMethod.POST, value = "/save-photo")
public ResponseEntity<?> uploadPhoto(#RequestPart("file") MultipartFile file){
if (file.isEmpty()) {
System.out.println("Attached file is empty");
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setMessage("Attached file is empty");
return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
String returnPath = null;
try {
byte[] bytes = file.getBytes();
String saveDate = new SimpleDateFormat("yyMMddHHmmssSSS").format(new Date());
Path path = Paths.get(UPLOAD_FOLDER + saveDate + "___" + file.getOriginalFilename());
Files.write(path, bytes);
returnPath = String.valueOf(path);
} catch (IOException e) {
//e.printStackTrace();
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setMessage(e.getMessage());
return new ResponseEntity<ErrorResponse> (errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
System.out.println("Before returning, return path = "+returnPath);
return new ResponseEntity<String>(returnPath, HttpStatus.OK);
}
Following is the code I have written to call the above method.
savePhoto(photoToSave: File) {
let formData: FormData = new FormData();
formData.append("file", photoToSave);
let savedPath = this._http
.post(this._endpointUrl + "/save-photo", formData)
.map(
res => {
return res.json();
}
)
.catch(handleError);
return savedPath;
}
File uploading process is fine. But Angular2 gives me the following error.
Unexpected token F in JSON at position 0
Note that the F is the starting letter of the path the server returns.
Why this happens? I think the server response is not a JSON. But why? Usually RestControllers return JSON. All other controller methods in my server works fine.
How to resolve this?
Response Captured from Browser console
Header:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:3000
Content-Length:88
Content-Type:application/json;charset=UTF-8
Date:Fri, 26 May 2017 04:33:05 GMT
Vary:Origin
Response:
F:\Work\Images\170526100305388___2.jpg
EDIT
Screen shots from the brwoser
Response:
Posting as a answer the workaround I used to get over the issue. Hope it might help somebody.
What I did was instead of returning a String ResponseEntity, I created a JSON object which encapsulates the string I want to return and returned as the response.
JSONObject obj = new JSONObject();
obj.put("savedPath", returnPath);
return new ResponseEntity<>(obj, HttpStatus.OK);
In the front end, I just return the response.json()
let savedPath = this._http
.post(this._endpointUrl + "tender/save-new/save-photo", formData)
.map(
res => {
return res.json();
}
)
.catch(handleError);
Now in the controller class, I can access the saved path in following way.
this._tendersService.savePhoto(files[0])
.subscribe(res => {
console.log("saved path = " + res.savedPath);
}
);

Spring MVC either sending JSON or Redirecting to another page

Hello I have been using Spring 3 for my project, I have been stuck in on point.
if(ajax){
User user = userTemplate.getUser(form.getCreator_id());
int isPremium = user.getPremium();
if ( isPremium == 1 ){
Map<String,String> resultMap = new HashMap<String,String>();
response.setHeader("Access-Control-Allow-Headers", "*");
response.addHeader("Access-Control-Allow-Origin", "*");
resultMap.put("result", "success");
return new Gson().toJson(resultMap);
}else{
return "redirect:/f/redirectedUrl?url="+form.getWeb_page();
}
}
redirectedUrl controller is just for redirecting, but if the request is ajax request then i want to response the request as json.
How can I achieve this, thanks.
Edit : I can understand if request is ajax or not. My problem is if it is ajax i want to response json, if it is not then i want to redirect.
Use this code in your controller to identify if request is ajax or not and based on that you can add your logic.
boolean ajax = "XMLHttpRequest".equals(
getRequest().getHeader("X-Requested-With"));
You can decide it from header("X-Requested-With") of your httpRequest object.
public ModelAndView getDetails(HttpServletRequest request, HttpServletRespone response) {
if(ajax) {
try {
new MappingJacksonHttpMessageConverter().write(object, MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response));
} catch(Exception e) {
logger.error("Error when converting to json");
}
return null;
} else {
return new ModelAndView("viewName");
}
}

how to insert JSON array into MySQL using mvc spring

Hi I am new in spring And developing a module of POST.
How to insert JSON array in db.
can you please give me the idea how to solve this issue.
I have also an example to show you this.
link:- http://hello-angularjs.appspot.com/angularjs-http-service-ajax-post-json-data-code-example
Here the controller code
#RequestMapping(value = "/create1", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody
BillingModel addbillingmodel(#RequestBody BillingModel billingmodel) {
try {
billingmodel.getItemid();
billingmodel.getQuantity();
dataServices.addEntity(billingmodel);
return billingmodel;
} catch (Exception e) {
e.printStackTrace();
return billingmodel;
}
}
}
Here is my html page with JSON.
<!DOCTYPE html>
<html data-ng-app="serviceModule">
<head>
<meta charset="ISO-8859-1">
<title>AngularJS POST Spring MVC</title>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js">
</script>
<script type="text/javascript">
var serviceModule = angular.module('serviceModule', []);
serviceModule.controller("AngularJSPostController", function($scope, $http) {
$scope.variable = "AngularJS POST Spring MVC Example:";
var dataObj = {
"itemid" : "11",
"quantity" : "22",
};
var response =
$http.post('/CRUDWebAppMavenized/billing_bakery/create1', dataObj);
response.success(function(data, status, headers, config) {
$scope.responseData = data;
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
});
</script>
</head>
<body data-ng-controller="AngularJSPostController">
<div>
<h4>{{variable}}</h4>
<b>You had sent below data through post:</b>
<p>Response: {{responseData}}</p>
</div>
</body>
</html>
I have to multiple data in a row.
1.In your BillingModel class create following methods -
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public String toJson() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(this);
return json;
}
2.You should have blob types of columns to store JSON
3.And in Your DAO class when you call addEntity , do something like this -
final MapSqlParameterSource sqlParams = new MapSqlParameterSource()
.addValue("item_json",billingModel.toJson().getBytes("UTF-8"));
You can also refer.
Converting Java objects to JSON with Jackson

respond to http request with json object in portlet

I am a beginner in liferay portlet development and I am developing a portlet that receives a http get request, processes some information and than it has to return a json object. My problem is that my portlet sends a whole html page instead of just the json object.
This is my code:
HttpServletResponse servletResponse = PortalUtil.getHttpServletResponse((renderResponse));
servletResponse.setHeader("Content-type", "application/json");
servletResponse.setCharacterEncoding("application/json");
PrintWriter out = servletResponse.getWriter();
out.write(EntityUtils.toString(responseEntity));
out.flush();
out.close();
I execute this in the doView() method I know that this is not the best practice, but I am not concerned with that at the moment. Can someone explain to me how to return just the json object I read something about serveResponse, but I couldn't figure out how to invoke it.
Well, one thing to notice, that the doView() is mostly responsible for rendering of your portlet. Your requirement can better achieved by
1 - processAction(Portlet Action) or
2 - serveResource(Portlet AJAX service).
To my view, AJAX request-response will be the most suitable case; for that you just need to create a resource URL on your portlet view. Like:
<portlet:resourceURL var="ajaxResourceURL" />
Add a JavaScript method to the page, from where you can generate AJAX request to your portlet. The method will look something like this,
<script type="text/javascript">
function _callAjax(val1, val2){
var url = '<%=ajaxResourceURL %>'; // pass resource URL you created using scriplet / EL.
jQuery.ajax({
type : "POST",
url : url,
cache:false,
dataType: "json",
data: {
value1: val1, // extra parameters if you want to pass
value2: val2
},
success : function(data){
// do whatever you want with your response data
},
error : function(XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
alert(textStatus);
}
});
};
</script>
Call that ajax method on a button / link click event:
<input type="button" onclick="_callAjax('val1', 'val2')" value="Send" />
And finally, in your portlet's action listener class add the following serveResource method, responsible for handling AJAX based request(s).
Here you can get your request parameters and generate a response in the sense you want:
#Override
public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException,IOException {
String value1 = ParamUtil.getString(request , "value1", "default"); // request parameters
String value2 = ParamUtil.getString(request , "value2", "");
PrintWriter writer = response.getWriter();
JSONObject jsonObject = new JSONObject();
jsonObject.put(String key, boolean/long/Collection/double/Map/Object value);
writer.write(jsonObject.toString());
}
Thats it! Hope, this will be helpful for you :)