Javax Jersey client processingException - java

I have a Maven jersey server that sends json objects to my JavaFX client, in my server I have model classes that have strings and int and in the client model class I tried to use Stringproperty and IntegerProperty (for the bind use and I have proper getter and setters(setter = name.set("example"),
getter = return name.get)) but when I do I get
Both front and backend have JSON as mediatype and when I change client modelclass variables to String and Int everything works as expected.I want to find a way to keep the property of strings and int for the bind method, I tried to google but no one else seems to have had this problem, does anyone know what can solve this and let me use property of variables
I caught the exception as
processingException e
e.getCause(): null
e.getMessage():
MessageBodyReader not found for media type=application/json, type=interface java.util.List, genericType=java.util.List<models.Users>.
[org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:207), org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:139), org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1109), org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:853), org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:812), org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:309), org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:813), org.glassfish.jersey.client.JerseyInvocation.access$600(JerseyInvocation.java:90), org.glassfish.jersey.client.JerseyInvocation$3.call(JerseyInvocation.java:693), org.glassfish.jersey.internal.Errors.process(Errors.java:315), org.glassfish.jersey.internal.Errors.process(Errors.java:297), org.glassfish.jersey.internal.Errors.process(Errors.java:228), org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:422), org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:689), org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:405), org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:301), Repository.UserRepo.getUsers(UserRepo.java:55), cleaner.Cleaner.start(Cleaner.java:35), com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863), com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326), com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295), java.security.AccessController.doPrivileged(Native Method), com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294), com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95), com.sun.glass.ui.win.WinApplication._runLoop(Native Method), com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191), java.lang.Thread.run(Thread.java:745)]
When I run get method with postman the backend works, so that tells me it something with client.
client:
glassfish 4.1
Jersey 2.5.1 (JAX-RS RI)
javax.ws.rs-api-2.0.1
server:
glassfish 4.1
jersey 2.26-b03
Thanks in advance!

Add the following dependency to your client to provide a MessageBodyReader implementation that knows how to deserialize an incoming JSON string to an instance of Users.
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.4.4</version>
</dependency>

Related

How to customize CXF+Aegis to generate xsd:string type?

After upgrading my service from CXF 2.4.10 to CXF 3.2.1 my client throws an exception when trying to process SOAP response because CXF+Aegis generates different type for string values.
I cannot change the client.
Currently generated type "ns3:string":
<ns2:value xmlns:ns3='http://www.w3.org/2001/XMLSchema' xsi:type='ns3:string'>myValue</ns2:value>
I need type "xsd:string":
<ns2:value xmlns:xsd='http://www.w3.org/2001/XMLSchema' xsi:type='xsd:string'>myValue</ns2:value>

How to register jackson json provider for cxf jax-rs 2.0 client?

I have a JAX-RS client that's making a simple GET request. I'm using the CXF implementation and Spring for DI. The call is successfull and I get a response code of 200 back. But I'm getting an error when reading the response into my POJO.
Exception:
[2015-05-08 16:11:55,457][ERROR][org.apache.cxf.jaxrs.utils.JAXRSUtils]: No message body reader has been found for class com.voya.refapp.domain.Customer, ContentType: application/json
[2015-05-08 16:11:55,468][ERROR][com.voya.refapp.service.CustomerServiceImpl]: filterByName() - Exception occurred
javax.ws.rs.client.ResponseProcessingException: No message body reader has been found for class com.voya.refapp.domain.Customer, ContentType: application/json
at org.apache.cxf.jaxrs.impl.ResponseImpl.reportMessageHandlerProblem(ResponseImpl.java:433) ~[cxf-rt-frontend-jaxrs-3.0.4.jar:3.0.4]
at org.apache.cxf.jaxrs.impl.ResponseImpl.doReadEntity(ResponseImpl.java:384) ~[cxf-rt-frontend-jaxrs-3.0.4.jar:3.0.4]
Code:
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8080/rest").path("customers/1");
Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON_TYPE);
Response response = builder.get(); // Successful
Customer customer = response.readEntity(Customer.class); // Fails
I have the below dependency as suggested in this answer in my classpath, it doesn't seem to be picked up automatically.
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
</dependency>
I also tried registering the json provider when creating the client:
Client client = ClientBuilder.newClient().register(new JacsksonJsonProvider());
and
Client client = ClientBuilder.newClient().register(JacsksonJsonProvider.class);
But none of these options worked too. I got a different exception when I registered the json provider using one of the options above:
javax.ws.rs.client.ResponseProcessingException: Problem with reading the data
Update:
Registering the json provider worked fine using ClientBuilder.newClient().register(JacsksonJsonProvider.class). The issue was with the data (like the exception above clearly states.. I feel silly now :(). I had boolean field in the json named "active", but it was called "isActive" in the POJO. Once I added the annotation #JsonProperty("active") to the field in POJO, it started working fine
AFAIK CXF does not support autodiscovery of MessageBodyReader classes. But registering manually JacksonJsonProvider should work for you.
Please check my example that works perfectly well. It is almost exactly the same as yours, I just used different service. Maybe you can spot a difference that prevents your version from working correctly.
Client client = ClientBuilder.newClient().register(JacksonJsonProvider.class);
WebTarget target = client.target("http://jsonplaceholder.typicode.com").path("posts/1");
Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON_TYPE);
Response response = builder.get(); // Successful
Post post = response.readEntity(Post.class);

Glassfish :MessageBodyProviderNotFoundException in Jersy Client

Hi All I was trying to create a rest web-service from scratch. Here is my Service part
#Path("/Phones")
public class PhonessResource {
#GET
#Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
public Response getAllNumbers(){
List<PhoneDetail> list = PhoneDirectoryDao.getInstance().getAllNumbers();
GenericEntity<List<PhoneDetail>> entity = new GenericEntity<List<PhoneDetail>>(list) {};
Response response =Response.ok(entity).status(200).build();
return response;//PhoneDirectoryDao.getInstance().getAllNumbers();
}
}
My data Model : I a had my getters and setters along with another constructor that take all property ,I didn't paste it to less the question length ,I use the same data model in client and server
#XmlRootElement(name="PhoneDetail")
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(propOrder={"id","firstName","lastName","address","phoneNo","timeStamp"})
public class PhoneDetail {
private int id;
private String firstName;
private String lastName;
private String address;
private String phoneNo;
private Timestamp timeStamp;
public PhoneDetail() {}
}
Then I create a java client to test the service .I am using NETBEANS IDE ,so I choose default option in IDE to create it
Thus I create a Jersey Client
public class PhoneCLient {
private WebTarget webTarget;
private Client client;
private static final String BASE_URI = "http://localhost:8080/Phones/webresources";
public PhoneCLient() {
client = javax.ws.rs.client.ClientBuilder.newClient();
webTarget = client.target(BASE_URI).path("Items");
}
public <T> T getAllNumbers_XML(Class<T> responseType) throws ClientErrorException {
WebTarget resource = webTarget;
return resource.request(javax.ws.rs.core.MediaType.APPLICATION_XML).get(responseType);
}
public <T> T getAllNumbers_JSON(Class<T> responseType) throws ClientErrorException {
WebTarget resource = webTarget;
return resource.request(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(responseType);
}
}
But It gives me this error
Exception in thread "main" org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=application/xml, type=class org.glassfish.jersey.client.ClientResponse, genericType=class org.glassfish.jersey.client.ClientResponse.
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:173)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:134)
at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:988)
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:833)
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:768)
at org.glassfish.jersey.client.InboundJaxrsResponse.readEntity(InboundJaxrsResponse.java:96)
at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:740)
at org.glassfish.jersey.client.JerseyInvocation.access$500(JerseyInvocation.java:88)
at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:650)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:421)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:646)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:375)
at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:275)
at PhoneDirectoryClient.rest.PhoneCLient.getAllNumbers_XML(PhoneCLient.java:45)
But when I test the service in Browser or RestClient Browser plugin it works fine .
Can anybody tell me what went wrong ??
For Xml, if you have all the dependencies that come with Jersey, it should work out the box for the client API. You might not have added all of them. I see you aren't using Maven, which I would strongly advise doing. But I'll provide both way to handle this.
XML
Maven:
Only dependencies you'll nee to get the client up and running (with JAXB xml support)
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.13</version>
</dependency>
Doesn't get much simpler :-)
Non-Maven:
So using a Maven project, I added the above dependency, and these are all the transitive dependencies it pulled in. In your non Maven project, you will need to manually add all these jars.
If you go to the Jersey Hompage, go to Downloads, and download the "Jersey JAX-RS 2.0 RI bundle. You should find all these dependencies in there. You should add all the ones needed, into your project
Note: Netbeans already comes with the Jersey 2.0 (JAX-RS RI) library. You could instead simply add that library to your project. Just right click on the [Libraries] node in your project, and select [Add Library]. You should see the Jersey in the dialog. This solution is probably the easiest, but it will import all the Jersey dependencies, more than is required for the client API
JSON
JSON requires another dependency:
Maven:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.13</version>
</dependency>
Non-Maven
Have a look at this post for an image and further explanation.
Just having these dependencies on the classpath should work, without any special configuration.
UPDATE
In newer versions of the Jersey client, jersey-media-jaxb is not pulled in anymore and you will need to manually add it for XML/JAXB support.

Post data Spring web services Restful

I am trying to save data on my database with a web service POST wich serializes a HTML form to save a object. The rest client firefox says this:
"The server refused this request because the requested entity is in a format not supported by the requested resource for the requested method"
The eclipse console shows the message:
org.jasig.cas.client.util.CommonUtils - safeGetParameter called on a POST HttpServletRequest for LogoutRequest. Cannot complete check safely. Reverting to standard behavior for this Parameter
I understand that the object that i want to save is not valid, but I don't see what the problem is.
#RequestMapping(value="/solicitudCita", method = RequestMethod.POST)
public #ResponseBody String putSolicitud(#ModelAttribute("Solicitud") Solicitud solicitud) throws Exception{
System.out.println(solicitud.toString());
solicitudCitaAppMService.createOrUpdate(solicitud);
String solicitudAdded = "Solicitud de cita -> {" + solicitud.toString() + "} aƱadida";
System.out.println(solicitud);
return solicitudAdded;
}
Help me please
Thanks
If you want to call this controller in a RESTful manner, you have to annotate the solicitud parameter as #RequestBody. Second, you have to have the Jackson libraries in you classpath so Spring can pick them up and use them for unmarshalling the object.
If you use Maven, use these dependencies:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.12</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>
BTW, why do you have to serialize the HTML form and sent it across? I would suggest you use a REST client, for instance this one, that is available in the Chrome WebStore.

Axis2 with JSON Support

I have an Axis2 web service that's already deployed, and which communicates with clients using SOAP. There's a new requirement now to enable REST calls by sending JSON requests and receiving JSON formatted responses.
Following this small tutorial: http://code.google.com/p/jsonp-support-for-axis2/wiki/OneStopPage
I was able to configure my Axis 2 web service correctly. Using my browser, I used the following URL to return a Student object:
http://localhost:8181/Axis2Json/services/StudentService/getStudent?response=application/json&value=3
OUTPUT :
{"return":{"#type":"ax21:Student","age":25,"firstName":"Mouhammed","lastName":"Soueidane"}}
The problem is that the returned JSON, doesn't look like a standard JSON representation (Not even in badgerfish format). So for instance, if I want to call a method called "setStudent" which takes in a Student object, I really have no clue of the JSON string that I need to pass to it.
I tried so many stuff, most of which resulted in a casting exception (java.lang.ClassCastException: java.lang.String cannot be cast to org.codehaus.jettison.json.JSONObject)
Does anyone have an idea about how to allow an Axis 2 web service to use both SOAP and JSON, based on the content type of the client?

Categories