troubleshooting JAXBUnmarshalException: Unexpected end of stream (RESTeasy) - json

I would appreciate if someone could help me formulate a strategy for fixing the following error, which occurs in no discernible pattern; most of the time there is no error, and I am successful about 90% of the time:
ERROR [org.jboss.resteasy.core.SynchronousDispatcher] Failed executing POST /toys/customer25/insert
org.jboss.resteasy.plugins.providers.jaxb.JAXBUnmarshalException: Unexpected end of stream
How would I log this error simply to the console? I'd like to capture the JSON that this method is receiving and figure out what is causing this error. I would be able to see it in the server logs.
What I am doing is POSTing an array of Toy objects to the server, in JSON format. That is, on the client I transform my Toy object into a Toy JSON. The string that I am sending is like this: [{"toyName":"buzzlightyear", "toyMaker":"mattel"}]
My understanding is that when I POST JSON to a jax-rs restful service, a jax-rs implementation (I'm using RESTeasy 1.2) will somehow automagically convert that JSON string into a java Toy object.
My code on the Java JAX-RS restful service for handling a POST which inserts a Toy object is this:
#POST
#Consumes({MediaType.APPLICATION_JSON})
#Produces({MediaType.TEXT_PLAIN})
#Path("toy/{customer}/insert")
public String insertToys(#PathParam("customer") String customer, List<Toy> toys);
How do I log/capture what is wrong with the JSON string? It seems to me that the system is handling the conversion of the JSON to Toy object right when the insertToys() method is called. So it's hard form to figure out how to debug.
Can someone formulate a strategy for me? What is the likelihood that I am passing in malformed JSON, maybe from some unescaped character? Vs mapping entities wrong? Thanks!

Your JSON is incorrect.
The method accepts List, so you must send an array of Toy Objects:
[{"toyName":"buzzlightyear", "toyMaker":"mattel"}]
(note the braces).
For more objects:
[{"toyName":"buzzlightyear", "toyMaker":"mattel"},{"toyName":"rex", "toyMaker":"mattel"}]

Related

jsoncpp is having trouble reading my Gson output

I have a java application that outputs data in Json format (via Gson). I write that data to a file. That file is then read by a C++ application. The C++ application is using jsoncpp to deserialize the json. However, it appears that the C++ application cannot properly deserialize the Json (which is the whole point of using Json).
The problem seems to relate to the class name being included in the Gson output. Gson output sample:
{"nameOfClass":{"fieldName":"fieldvalue","secondFieldName":1}
As far as I can tell, "nameOfClass" is throwing off jsoncpp. Perhaps my jsoncpp deserialize method is incorrect? I have specific code to handle the different fields, but nothing that specifically handles that initial class name. Is that something I need to handle?
Short answer: user error
Longer answer:
It turns out I was serializing the wrong object. The class of this object CONTAINS a field of type "nameOfClass". What I wanted was that FIELD to be serialized, not the whole object. Because of my inexperience with Json and unfortunate choice of the field's name, I thought the output was malformed. Once I got the field from the object and serialized that, everything was fine.

Create JAX-RS Client Post Request with JSON String as Body

I am writing a REST Client for one of the Vendor REST Service. I use jersey 2.x and JSON-P, below are dependencies I add.
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-processing</artifactId>
<version>2.26</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.26</version>
</dependency>
</dependencies>
I successfully write code for GET request and received JSON output. I saved it to a file and used JSON-P to interpret and do my own logic without any issues.
But now I need to write a POST request. When I use CURL as below I am able do it. and want to implement the same using Jeresey 2.x and JSON-P.
curl -v -H "Accept:application/json" -H "Content-Type:application/json" -u user:password -X POST --databinary #./InputParameters.json https://<IP>:<PORT>/Configuration/server
InputParameters.json contents
{
"ip": "10.197.70.16",
"partNumber": 202067,
"model": "IBM P7"
}
When I tried to pass response body as String in JSON format ({"ip": "10.197.70.16", "partNumber": 202067, "model": "IBM P7"}), but didn't work. So tried as JsonObject as below still didn't work.
JsonObject jsonObj = Json.createObjectBuilder()
.add("ip", "10.197.70.16")
.add("partNumber", 202067)
.add("model", "IBM P7")
.build();
response = invocationBuilder.post(Entity.json(jsonObj));
I know core java, based on that experience I jumped into writing this program and got success with GET but not POST. I doubt I am doing something fundamentally wrong with POST.
Let's unpack what you're doing for a bit. First there's this part:
JsonObject jsonObj = Json.createObjectBuilder()
.add("ip", "10.197.70.16")
.add("partNumber", 202067)
.add("model", "IBM P7")
.build();
This creates a javax.json.JsonObject instance. JsonObject, which is part of the JSON-P Java API, is pretty much what it says: a class to represent a JSON object. A JsonObject instance contains a hierarchy of javax.json.JsonValue instances, which conform to more specific types like JsonArray, JsonString, other JsonObjects and so on. In this regard it's not unlike the classes of the DOM API for representing XML documents (let's hope Oracle keeps the API docs at that URL for a while). But JSON is fortunately a lot more straightforward than XML and DOM.
Your jsonObj instance would contain a JsonString instance with value "10.197.70.16" mapped to name "ip", a JsonNumber with value 202067 (probably represented as BigDecimal) mapped to name "partNumber" and so on.
Next your code executes this:
Entity.json(jsonObj)
javax.ws.rs.client.Entity.json(something) basically states that you want to create an entity that will provide the payload for a JAX-RS client invocation with as Content-Type application/json. In other words, the something you create it for must be transformed to a JSON representation when it's sent to the API, which should expect a JSON payload and know how to handle it. Note that Entity.json(...) has a generic type parameter. The method signature is static <T> Entity<t> json(T entity). So you're creating an instance of Entity<JsonObject> with the payload entity jsonObj.
When this is handed over to the post method of a javax.ws.rs.client.Invocation.Builder instance (the post method is actually defined in its parent interface SyncInvoker) the client implementation goes to work.
response = invocationBuilder.post(Entity.json(jsonObj));
It takes the provided Entity instance and its content (our jsonObj), checks what the desired output is of the Entity (this is application/json) and seeks a provider that can turn objects of the given type into that output. In other words, some component must be located that can be given a javax.json.JsonObject and write a representation of it as JSON to an OutputStream. The component handling this could be a javax.ws.rs.ext.MessageBodyWriter that claims it can perform this transformation and was registered to the JAX-RS runtime. Various libraries supply such providers and you can also write your own. This makes JAX-RS extensible to deal with various scenarios, handle non-standard input and output or lets you tune its behaviour. When multiple providers are capable of handling the given entity type and producing the desired output, there are rules to determine which one takes on the job. Note that this can depend on what is on your classpath. There are ways of forcing this explicitly.
The client puts together the invocation through its configuration, using the proper URL, query parameters, HTTP method, headers and so on. The payload is created by writing the entity to an OutputStream in the required format. In your example this results in a POST to the server. When the invocation has been completed you receive a javax.ws.rs.core.Response that you can use to determine the HTTP result code and retrieve a response payload, if any. The readEntity(Class<T> entityType) method of Response works like the reverse of turning an Entity into a payload. It searches for a MessageBodyReader that can interpret the response stream according to the value returned from response.getMediaType() and can create an instance of Class entityType from it.
So with all of that explained, what exactly is going wrong in your approach? Well, the issue is that the default implementations available to your JAX-RS runtime probably don't have a writer specifically for an input of type JsonObject and with expected output application/json. It may seem very logical if the server expects JSON, that you should be able to supply a JsonObject as payload. But if the JAX-RS implementation can't find something to handle that class, then at best it can just use some default approach. In that case it may try to interpret the object as a POJO and serialize it to JSON in a default manner, which could lead to weirdness like this:
{
"valueMap": {
"ip": {
"value": "10.197.70.16"
},
"partNumber": {
"num": 202067,
"integral": TRUE
},
...
}
}
That's what a literal interpretation of the JsonObject instance could look like, depending on which implementation it uses and what is used by JAX-RS to turn it into JSON output. Of course it's possible that the object can't be serialized to JSON at all, either because no suitable MessageBodyWriter can be found or it runs into an error when creating the output.
A first solution would be a very simple one. Just turn the JsonObject into a String and simply provide that as the entity:
StringWriter stringWriter = new StringWriter();
try (JsonWriter jsonWriter = Json.createWriter(stringWriter);) {
jsonWriter.writeObject(jsonObject);
} // some error handling would be needed here
String jsonPayload = stringWriter.toString();
response = invocationBuilder.post(Entity.json(jsonPayload));
It seems you had already tried that. A possible problem with this is that the MessageBodyWriter that gets used needs to just output the String's bytes in a suitable encoding (probably UTF-8) when presented with a String as output and application/json as the required content type. Some may not do that. You could try Entity.entity(jsonPayload, MediaType.TEXT_PLAIN_TYPE.withCharset("UTF-8")) but then the server might reject the call.
Other possible solutions are
Writing your own MessageBodyWriter for String objects with an #javax.ws.rs.Produces(MediaType.APPLICATION_JSON) annotation on it.
Better yet, writing such a class that accepts JsonObject instances.
Creating POJO classes for your JSON structure and letting those get used for generating JSON from instances or deserializing JSON responses to instances.
Finding an extension library that contains suitable providers for dealing with javax.json classes.
The addition of the com.owlike:genson dependency to your project is exactly the application of that last suggestion. The Genson library provides conversions between Java objects and JSON in both directions, as well as data binding. Part of its code base is dedicated to JAX-RS providers, among which a class suitable for accepting JsonObject as input.
Issue is resolved after adding below dependency. At this point I am not sure on what does it do.
Thanks to Swamy (TCS) for his support to resolve this.
<dependency>
<groupId>com.owlike</groupId>
<artifactId>genson</artifactId>
<version>1.4</version>
</dependency>
Example using genson
String serialize = new Genson().serialize(
Json.createObjectBuilder()
.add("ip", "10.197.70.16")
.add("partNumber", 202067)
.add("model", "IBM P7")
.build()
);
response = invocationBuilder.post(Entity.json(serialize));

List<Object> to JSON using annotations

OK, here goes, hopefully this makes sense! I have a small project based off of the appfuse web service only archetype. I have a business facade which has a DAO injected, through this DAO I request some data, simple example:
PersonManager.java
#GET
#Path("{people}")
List<Person> getPeople(#QueryParam("surname") String surname);
PersonManagerImpl.java (implements PersonManager)
public List<Person> getPeople(String surname) {
return personDao.getPeople(String surname);
}
I can make a request to invoke this method through a URL configured to point to "getPeople", however, as the DAO returns the list of people as an array list, I get the following error
Error serializing the response, please check the server logs, response class : ArrayList.
I know I can wrap this method and use Jackson Object Mapper to change the list to a string, but I didn't want another layer in my code, just to marshal JSON requests/responses.
I also don't want to change the interface to return a string, because the interface may be used later to return other data types, thus, I don't want to lock it in to only returning a string representing JSON.
My dilemma is that, I don't quite get how keeping the above interface and implementation, I can have Jackson convert the list of people to a json list of people, with annotations only!
Any help is greatly appreciated.
Please help!
Upgrading Jackson from 1.7.1 to 1.9.5 resolved this issue.

How can I serialize Exceptions using Json.NET on WinRT?

This works fine on classic .NET:
string json = JsonConvert.SerializeObject(new Exception("Test"));
But it fails on WinRT (RP) with:
Error getting value from 'TargetSite' on 'System.Exception'.
The API 'System.Exception.get_TargetSite()' cannot be used on the current platform. See http://go.microsoft.com/fwlink/?LinkId=248273 for more information.
EDIT:
I also need to transfer the Exception over the wire and deserialize it on the back end side.
Anyone has any workarounds?

Intercept JSON prior to RestKit

The company I'm working at is considering using RestKit. However, the JSON that our server returns is surrounded characters for security reasons. It's a pain. In another iPhone app, one that does not use RestKit and uses JSON only very little, I parse the string returned from the server, removing the characters preceding and trailing the JSON string. Once the the string is parsed, I call JSONValue on the string (we're using SBJSON) and get an NSDictionary.
I've heard that RestKit features a pluggable architecture. If that's the case is there somewhere I can intercept the strings coming back from the server prior to the point where RestKit does its parsing?
I wanted to find a fix that did not require me to change the RestKit codebase in any way and I found it. The answer was to create and register my own parser.
Parsers need to conform to the RKParser protocol. Basically what I needed to do was trim the server response and not parse the response into objects - there was already a parser that did that: RKJSONParserJSONKit. So I subclassed this class and registered my parser at start up:
[[RKParserRegistry sharedRegistry] setParserClass:[MyJSONParser class]
forMIMEType:#"application/json"];
Just wanted to note that nowadays you can implement your own retrieve/map operation by subclassing the
RKHTTPRequestOperation (doc) — for retrieving file from server
RKObjectRequestOperation (doc) — for mapping
RKManagedObjectRequestOperation (doc) — for mapping to core data objects
and registering them with [RKObjectManager registerRequestOperationClass:] (doc) method.