I have server written in Java, where I create JSON objects like this:
#Override
public void serialize(Net net, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException {
try {
Set<Place> places = net.getPlaces();
Set<Transition> transitions = net.getTransitions();
JSONObject jsonPlaces = new JSONObject();
for (Place p : places)
{
String id = p.getId();
double xCoord = p.getxCoord();
double yCoord = p.getyCoord();
JSONObject jsonPosition = new JSONObject();
jsonPosition.put("x", xCoord);
jsonPosition.put("y", yCoord);
JSONObject jsonPlace = new JSONObject();
jsonPlace.put("position", jsonPosition);
jsonPlaces.put(id, jsonPlace);
}
jg.writeRawValue(jsonPlaces.toString());
} catch (Exception ex) {
throw new IOException("...", ex);
}
}
The resulting object as string (jsonPlaces.toString()) looks like this:
{"id01":{"position":{"x":220,"y":90}},"id02":{"position":{"x":210,"y":250}}}
I send it to my web application using the code below, it uses the serialize() method..
#POST
#Path("/blindLayout")
#Consumes(MediaType.APPLICATION_JSON)
public Net blindLayout(Net net) throws Exception {
.
.
return net;
}
And here is the angularjs code that should recieve the response
.factory('Layout', function ($http, Notification, AnalysisConfig) {
layoutPrototype.performLayout = function (net, options, defered) {
if (net) {
var address = AnalysisConfig.serverAddress + AnalysisConfig.resourceURI + AnalysisConfig.resources.blindLayout;
$http.post(address, JSON.stringify(net), {timeout: AnalysisConfig.timeout})
.then(function (response) {
var data = response;
},
function (response) {
Notification.error({
title: 'Communication error',
...
});
});
};
};
My problem is that I canĀ“t get data from the response. No matter what I tried, the result is always undefined or [object Object]. So how should I get data from response so I can for example use alert() and write something like
id01 (value of x, value of y)
id02 (value of x, value of y)
...
so I can also use it in my app?
the $http returns a promise that's resolved with an object that contains more than just the body but also headers and status. So to retrieve the JSON you created on a backend you can do:
$http.post(address, JSON.stringify(net), {timeout: AnalysisConfig.timeout})
.then(function (response) {
var data = response.data;
},
and then if you want to iterate over object keys you can do few things
for(var id in data){
console.log(data[id]) //{"position":{"x":220,"y":90}}
console.log(data[id].position) //{"x":220,"y":90}
}
or
var arrayOfObjects = Object.keys(data).map(function(id){
return data[id].position;
});
console.log(arrayOfObjects) // [{"x":220,"y":90}, {"x":210,"y":250}]
Related
Can't handle exceptions occurs on server side by flash (flex) application.
Server on java, spring-boot-web, for handling exceptions uses org.zalando library.
On server, for example:
#ExceptionHandler(value = SecurityException.class)
public ResponseEntity securityViolation(Throwable e, NativeWebRequest request) {
log.error(e.getMessage(), e);
HttpServletRequest httpServletRequest = ((ServletWebRequest) request).getRequest();
ThrowableProblem problem = createBaseProblemBuilder(Error.SECURITY_ERROR, httpServletRequest)
.withStatus(Status.FORBIDDEN)
.withTitle("Unauthorized")
.withDetail(e.getMessage())
.build();
return create(problem, request);
}
private ProblemBuilder createBaseProblemBuilder(Error error, HttpServletRequest httpServletRequest) {
return Problem.builder()
.withType(URI.create(Error.BASE_ERROR_URL + error.getCode()))
.with("httpMethod", httpServletRequest.getMethod())
.withInstance(URI.create(httpServletRequest.getRequestURI()))
.with("requestTraceId", Long.toString(Thread.currentThread().getId()))
.with("timestamp", LocalDateTime.now());
}
On client (flex):
public function invokeCommand(url: String, requestBody: String = null): IThenable {
return new Promise(function (fulfill: Function = null, reject: Function = null): * {
invokeService(requestBody, _serverInfo.serviceUrl + url,
function (event: ResultEvent): void {
fulfill(event.result);
}, function (event: FaultEvent): void {
var response: Object = event.fault.content;
handleFault(response);
reject(response);
});
});
}
private function handleFault(response: Object): void {
var faultResponseDto: FaultResponseDto = new FaultResponseDto(response ? JSON.parse(response.toString()) : null);
... some code, but response already is empty
}
Expects, that event.fault.content contains data from server, but it always empty.
In browser network console response has payload, and contains all data from server in json.
Main question - how i can read fault payload in flash?
In debug I browse all in FaultEvent, but can't find nothing about needed data.
P.S. sorry for bad english...
I am currently converting a node project to DW. The node project currently stores JSON from the client as a string and then returns application/JSON when the client gets the same resource. This is basically a Key/value store reset endpoint.
I want to implement the same with dropwizard, but I do not want to map out the entire structure and it's nested structures in POJOs. Is there a way to allow for this? I just want to save the JSON as a string in the db with the key, I do not want to work with the data at all in the java application.
Since the APIs require that I return an object, what should the object be? Here is the function I have for DW, as you can see it is expecting to return an object.
#GET
#UnitOfWork
#Timed
#ApiOperation(value="Find value by ID", notes="Get a value object from the DAO using ID as the sole criterion")
#ApiResponses(value={
#ApiResponse(code=400, message="Invalid ID"),
#ApiResponse(code=404, message="No object found by specified ID")
})
public SomeJavaOjbectMustGoHere getSample(
#ApiParam(value="id of object to get", required=true)
#QueryParam("id")
Long id
) throws WebApplicationException {
SomeJavaOjbectMustGoHere returned = dao.get(id);
if (returned == null) throw new WebApplicationException(Response.Status.NOT_FOUND);
else return returned;
}
Here is most of the code from node:
module.exports = function (server) {
function createResponse(req, res, next) {
var key = req.params.name;
console.log("Creating Response for key: '" + req.params.name + "'");
// ...some validation...
if (..blah..) {
// fail out.
res.send(403, "response can not be saved without a valid key and structure.");
return next();
}
var data = JSON.stringify(req.body);
// ... store the stuff in the db...
res.send(201, "Saved");
return next();
}
function getResponse(req, res, next) {
try {
var payload = {};
// ... get the data matching the key...
res.header("Content-Type", "application/json");
res.send(200, JSON.parse(payload.toString()));
}
catch(err) {
console.log('Data not found.' + err);
res.send(200,
{
"id": Math.random().toString(36).substr(3, 8),
// ... default structure ...
});
}
return next();
}
function send(req, res, next) {
res.send('response ' + req.params.name);
return next();
}
server.post('/response/:name', createResponse);
server.put('/response', send);
server.get('/response/:name', getResponse);
server.head('/response/:name', send);
server.del('/response/:name', function rm(req, res, next) {
res.send(204);
return next();
});
}
If you don't want to create your own Object model then Jackson has a JsonNode class.
If you don't want to do anything with the data you could just return a String and add the following annotation to your method:
#Produces(MediaType.APPLICATION_JSON)
I am following this tutorial on uploading files to a server from android, but I cannot seem to get the code right on the server side. Can somebody please help me code the Web Api post method that would work with that android java uploader? My current web api controller class looks like this:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace WSISWebService.Controllers
{
public class FilesController : ApiController
{
// GET api/files
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/files/5
public string Get(int id)
{
return "value";
}
// POST api/files
public string Post([FromBody]string value)
{
var task = this.Request.Content.ReadAsStreamAsync();
task.Wait();
Stream requestStream = task.Result;
try
{
Stream fileStream = File.Create(HttpContext.Current.Server.MapPath("~/" + value));
requestStream.CopyTo(fileStream);
fileStream.Close();
requestStream.Close();
}
catch (IOException)
{
// throw new HttpResponseException("A generic error occured. Please try again later.", HttpStatusCode.InternalServerError);
}
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.Created;
return response.ToString();
}
// PUT api/files/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/files/5
public void Delete(int id)
{
}
}
}
I am pretty desperate to get this working as the deadline is tuesday. If anybody could help that would be much appreciated.
you can post a files as multipart/form-data
// POST api/files
public async Task<HttpResponseMessage> Post()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
string value;
try
{
// Read the form data and return an async data.
var result = await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the form data.
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
// return multiple value from FormData
if (key == "value")
value = val;
}
}
if (result.FileData.Any())
{
// This illustrates how to get the file names for uploaded files.
foreach (var file in result.FileData)
{
FileInfo fileInfo = new FileInfo(file.LocalFileName);
if (fileInfo.Exists)
{
//do somthing with file
}
}
}
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, value);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = files.Id }));
return response;
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
I'm trying to send a json String from an ajax call to a jersey web service. I've looked at many related questions and articles but I haven't been able to get anything to work. When I watch my calls from fiddler I can see the json in the body but when the method is hit the String is blank. Thanks for any help.
getFile: function() {
var urlXls = 'http://localhost:8080/KodiakWebS/Kodiak/KodiakXls/generateXls';
//var json = '{"xls":[{"name":"Pokemon","row":[{"data":"Lugia"},{"data":"Charzard"}]},{"name":"Types","row":[{"data":"Special"},{"data":"Fire"}]}]}'; //encodeURI();
var json = this.get('tempJSON');
urlXls = urlXls.replace(/\s/g, "");
$.ajax({
url: urlXls,
type: "POST",
data: json,
contentType: 'application/json; charset=utf-8', // ;charset=utf-8',
success: function(json, status)
window.location.assign(json.url);
alert("yay");
},
error: function(xhr, err) {
debugger;
alert(xhr+ " || " + err);
}
});
},
#POST
#Path("/generateXls")
#Consumes("application/json")
#Produces({ "application/xls" })
public Response sendWorkBook(final String json) throws Exception {
createWorkbook(json);
FileOutputStream sprdSht = new FileOutputStream("WorkBook.xls");
wb.write(sprdSht);
sprdSht.close();
System.out.println("all done");
StreamingOutput stream = new StreamingOutput() {
#Override
public void write(OutputStream outPut)
throws IOException,
WebApplicationException {
try {
wb.write(outPut);
} catch (Exception e) {
throw new WebApplicationException(e);
}
}
};
return Response.ok(stream).header("content-disposition", "attachment; filename = egisDoc.xls").build();
}
If you say you consume application/json, then I think you need to provide a Java object to model the JSON you are supplying.
If you do just want the JSON as a String, then you need to consume text/plain.
I typically have this when I use JAXRS:
#PUT
#Path("entities")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public SomeDomainObject updateSomeEntity(SomeDomainObject someDomainObject) {
// Whatever...
}
Where "SomeDomainObject" is just a POJO with getters and setters.
I normally use the JacksonJsonProvider implementation rather than the JAXB one, and the above style of controller works just fine with JSON marshalling for me. I don't even need to add any JSON annotations to the domain objects either.
I was able to get it working thanks to the suggestions from caprica and tinkering around a little bit. Not much changed in my code but here it is.
#PUT
#Path("/generateXls")
#Consumes("text/plain")
#Produces({ "application/xls" })
public Response sendWorkBook(String json) throws Exception {
System.out.println("json: " + json);
createWorkbook(json);
getFile: function() {
var urlXls = 'http://localhost:8080/KodiakWebS/Kodiak/KodiakXls/generateXls';
//var json = '{"xls":[{"name":"Pokemon","row":[{"data":"Lugia"},{"data":"Charzard"}]},{"name":"Types","row":[{"data":"Special"},{"data":"Fire"}]}]}'; //encodeURI();
var json = this.get('tempJSON');
urlXls = urlXls.replace(/\s/g, "");
$.ajax({
type: "PUT",
url: urlXls,
data: json,
contentType: 'text/plain; charset=utf-8', // ;charset=utf-8',
success: function(json, status) {
window.location.href = json.url;
//window.location.assign(json.url);
//alert("yay");
},
error: function(xhr, err) {
debugger;
alert(xhr+ " || " + err);
}
});
},
now on to trying to download xls file my service creates, hopefully I won't need to ask how to get what I have working (but if anyone has a method they're proud of and would like to share you're more than welcome too).
Thanks for the help.
I am currently using the Spring MVC, and I am trying to do some stuff with ajax. Basically what I want to do now is display the result from a controller dynamically on a webpage.
I.E. A user pushes a button it goes to the "whatever.do" controller and gets a list and displays that list without having to reload that page.
Anyway does anyone know any good tutorials or example projects?
It is very simple, I don't even think a special tutorial is needed (apart from a generic spring-mvc one).
Make a #RequestMapping("/foo") method that returns a List<Foo>
Have <mvc:annotation-driven /> in your dispatcher-servlet.xml to activate handler mappings and convertors
Put Jackson (json serializer) on your classpath
Use $.getJSON("/foo", function(data) {..}); (jquery) - you will get a JSON-encoded list of your Foo objects
Spring will detect that the browser requests a json response, and converts your objects using Jackson.
http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/
http://krams915.blogspot.com/2011/01/spring-mvc-3-and-jquery-integration.html
your controller must have in following format when you are using with spring along with ajax:
#RequestMapping(value = "/show.ajax", method = RequestMethod.POST)
public #ResponseBody List<your object type> your_method_name() {
//code logic
return list_of_your_object;
}
also your java script code on jsp page in following format:
<script>
function your_javascript_fun_name() {
$.ajax({
type : 'POST',
url : 'show.ajax',//this is url mapping for controller
success : function(response) {
alert(response);
//this response is list of object commming from server
},
error : function() {
alert("opps error occured");
}
});
}
</script>
import jquery library in jsp page
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
var id = $("#id").val();
var resourceURL = $("#contextpath").val()+"/customer/retrivebyid/"+id;
$.ajax({
url : resourceURL,
type : 'GET',
dataType : 'json',
async : false,
success: function(data) {
var successflag = data.response.successflag;
var errors = data.response.errors;
var results = data.response.result;
if(successflag == "true"){
$.each(results, function (i, result) {
$("#id").val((result.id == undefined || result.id == null || result.id.length <= 0) ? "-" : result.id);
$("#name").val((result.customername == undefined || result.customername == null || result.customername.length <= 0) ? "-" : result.customername);
});
}else{
$("#errorMsgContent").html(errors);
$.fancybox.open('#errorMsg');
}
},
error: function (xhr, ajaxOptions, thrownError) {
$("#errorMsgContent").html(thrownError);
$.fancybox.open('#errorMsg');
}
});
#RequestMapping(value = "/retrivebyid/{id}", method = RequestMethod.GET)
public #ResponseBody String retriveUser(#PathVariable long id, Model model,HttpServletRequest request) {
String jsonresp = null;
try {
List<CustomerDO> customerList = new CustomerService().retriveById(id);
jsonresp = CustomerUtil.getCustomerList(customerList).toString();
} catch (Exception e) {}
if (jsonresp != null) {
return jsonresp.toString();
} else {
return null;
}
}
public static JSONObject getCustomerList(List<CustomerDO> empList)throws AppException {
JSONObject responseJSON = new JSONObject();
JSONObject resultJSON = new JSONObject();
try {
resultJSON.put(CommonConstants.SUCCESS_FLAG, CommonConstants.TRUE);
resultJSON.put(CommonConstants.ERRORS, "");
JSONArray resultJSONArray = new JSONArray();
for (CustomerDO customer : empList) {
resultJSONArray.put(getCustomerDetailObject(customer));
}
resultJSON.put(CommonConstants.RESULTS, resultJSONArray);
responseJSON.put(CommonConstants.RESPONSE, resultJSON);
} catch (JSONException e) {
e.printStackTrace();
}
return responseJSON;
}
private static JSONObject getCustomerDetailObject(CustomerDO customer)throws JSONException, AppException {
JSONObject result = new JSONObject();
result.put(CommonConstants.ID, String.valueOf(customer.getId()));
result.put(CommonConstants.CUSTOMER_NAME, String.valueOf(customer.getName()));
return result;
}