send XML string to web service in Jersery - java

I am new to web service in jersey. I have created a web service the code is below
#Path("/remotedb")
public class RemoteDb {
#GET
#Path("/save/{xmlData}")
#Produces(MediaType.TEXT_XML)
public String saveData(#PathParam("xmlData") String xml) {
return xml;
}
}
I have this code at client side
public class WebServiceClient {
public static void callWebService() {
String xml = "<data>" +
"<table><test_id>t4</test_id><dateprix>2013-06-06 22:50:40.252</dateprix><nomtest>NOMTEST</nomtest><prixtest>12.70</prixtest><webposted>N</webposted><posteddate>2013-06-06 21:51:42.252</posteddate></table>" +
"</data>";
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
System.out.println(service.path("restful").path("remotedb").path("save").path(xml).accept(MediaType.TEXT_XML).get(String.class));
}
private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost:8080/WebServiceModule").build();
}
}
Now when i called the web service i got the following exception
Exception in thread "main" com.sun.jersey.api.client.UniformInterfaceException: GET http://localhost:8080/WebServiceModule/restful/remotedb/save/%3Cdata%3E%3Ctable%3E%3Ctest_id%3Et4%3C/test_id%3E%3Cdateprix%3E2013-06-06%2022:50:40.252%3C/dateprix%3E%3Cnomtest%3ENOMTEST%3C/nomtest%3E%3Cprixtest%3E12.70%3C/prixtest%3E%3Cwebposted%3EN%3C/webposted%3E%3Cposteddate%3E2013-06-06%2021:51:42.252%3C/posteddate%3E%3C/table%3E%3C/data%3E returned a response status of 404 Not Found
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:686)
at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
at com.sun.jersey.api.client.WebResource$Builder.get(WebResource.java:507)
at com.main.WebServiceClient.callWebService(WebServiceClient.java:25)
at com.main.Test.main(Test.java:7)

Passing XML data in a path segment is very unorthodox and likely to raise all kind of issues. You should pass it as a query parameter, e.g. /WebServiceModule/restful/remotedb/save?xmlData=
%3Cdata...
#GET
#Path("/save")
#Produces(MediaType.TEXT_XML)
public String saveData(#QueryParam("xmlData") String xml) {
return xml;
}
}
or even better if it is a write operation as the name suggests then it should be a POST /WebServiceModule/restful/remotedb/save with the xmlData passed in the request body.
#POST
#Path("/save")
#Produces(MediaType.TEXT_XML)
public String saveData(String xml) {
return xml;
}
}
or even better yet, if you can map your xmlData to a POJO with JAXB's #XmlRootElement annotation, then you can get jersey to parse it for you:
#POST
#Path("/save")
#Consumes(MediaType.APPLICATION_XML)
public String saveData(YourXmlDataObject obj) {
return obj.getField();
}
}

Related

Send clikable url from java

I want to send clickable URL from java code to UI where it return type initially was String
#POST
#Path("/crd")
#Produces(MediaType.TEXT_PLAIN)
#Consumes(MediaType.APPLICATION_JSON)
public String isValid(SomeDTO SomeDTO)
throws Exception {
// business logic
catch(Exceptioin e){
return "notvalid"
}
}
Now i want send to ui url along with text(like notvalid.Click below link to
user guide)
#POST
#Path("/crd")
#Produces(MediaType.TEXT_PLAIN)
#Consumes(MediaType.APPLICATION_JSON)
public String isValid(SomeDTO SomeDTO)
throws Exception {
// business logic
catch(Exceptioin e){
return "notvalid"+url
}
}
before i was notvalid
---expected is notvalid.Cilck below link to user guide.
return "notvalid"+"Click here for more info";

How do I map JSON parameters to Jersey parameters?

I've been struggling all day, trying to bind a very simple JSON request to a method using Jersey. I can't seem to find what's wrong, any help is very appreciated.
My JSON request is as simple as this:
{"user":"xyz","pwd":"123"}
My Jersey class looks like this:
#Path("/rest")
public class JerseyService {
#POST
#Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
#Consumes(MediaType.APPLICATION_JSON)
#Path("authenticate.svc")
#Transactional(readOnly = true)
public Response authenticate(
String user,
String pwd) throws IOException {
Response.ResponseBuilder responseBuilder = Response.ok();
responseBuilder.entity(JsonSerializer.serialize(Status.SUCCESS));
return responseBuilder.build();
}
}
When I send the JSON request to the service as it is, the "user" parameter is set with the entire JSON request as a String (user = "{\"user\":\"xyz\",\"pwd\":\"123\"}"), while pwd remains null.
I've tried using #QueryParam, #FormParam among another annotations with both "user" and "pwd", but I can't find a way for Jersey to bind the JSON values to the Java parameters.
Any ideas of what I'm doing wrong?
Thanks!
You could use low level JSONObject or create your own Class to accept the json parameter.
The following is the example with JSONObject.
```
#Path("/rest")
public class JerseyService {
#POST
#Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
#Consumes(MediaType.APPLICATION_JSON)
#Path("authenticate.svc")
#Transactional(readOnly = true)
public Response authenticate(final JSONObject login) throws IOException {
System.out.println(login.getString("user"));
System.out.println(login.getString("pwd"));
//^^^^^^^^^^^^^^^^^
Response.ResponseBuilder responseBuilder = Response.ok();
responseBuilder.entity(JsonSerializer.serialize(Status.SUCCESS));
return responseBuilder.build();
}
}
```

How to access JSON request body of POST/PUT Request in Apache Camel/CXF REST webservice

I am trying to pass a JSON request body to a REST Webservice which is made using CXFRS in my Apache Camel application.
I want to access the request JSON passed in my Processor.
REST URL:
http://localhost:8181/mywebservice/Hello/name/{request_param}
Though i am posting a JSON in request body, still in my processor exchange.getIn().getBody() always return the {request_param} not the Request JSON.
My REST webservice is as follows:
#Path("/name/")
#Consumes({"application/json" ,"application/xml"})
public class HelloRest {
#POST
#Path("/{name}")
public TestPojo sayHi(#PathParam("name") String name) {
return new TestPojo(name);
}
}
Server part:
#POST
#Path("/")
#Produces(MediaType.TEXT_PLAIN)
#Consumes(MediaType.APPLICATION_JSON)
public String add(MappingUser newUser){
UserEntity userEntity = new UserEntity(newUser.getNickname(), newUser.getPassword());
boolean ret = myDB.addUser(userEntity);
//sends the return value (primitive type) as plain text over network
return String.valueOf(ret);
}
Client part:
public boolean addUser(User user){
WebResource resource = client.resource(url).path("/");
String response = resource
//type of response
.accept(MediaType.TEXT_PLAIN_TYPE)
//type of request
.type(MediaType.APPLICATION_JSON_TYPE)
//method
.post(String.class, user);
return Boolean.valueOf(response);
}

JAX-RS CXF Exception wrapping

I would like to add an ExceptionMapper to CXF (2.6.1) which not only communicates the Response code, but also ships the exception in the payload format (I'm using JSON for now).
#Provider
public class CustomExceptionMapper
implements
ExceptionMapper<MyException>
{
...
#Override
public Response toResponse(MyException mex)
{
//I need something here which can convert mex object to JSON and ship it in response
// I want this to be de-serialized on client
//the following returns the status code
return Response.status(Response.Status.BAD_REQUEST).build();
}
...
}
Is there a way to do this ?
You may need to use #Produces to serialize your object to JSON like:
#Produces(MediaType.APPLICATION_JSON)
And then return Response.ok().entity(OBJECT).build();
The way that you can test your service:
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
ClientResponse response = service.path(ADDRESS).type("application/json").get(ClientResponse.class);
String s = response.getEntity(String.class);
System.out.println(s);
private static URI getBaseURI() {
return UriBuilder.fromUri(SERVER ADDRESS).build();
}

Java consume JSON list from Rest service GET

The error I receive:
SEVERE: A message body reader for Java class java.util.List,
and Java type java.util.List<com.testapp.Category>,
and MIME media type text/html; charset=utf-8 was not found
Trying to consume a JSON response from a Rest service using the GET method with Jersey. The response from the server looks like this when I use curl:
[{"category":{"id":"4d9c5dfc8ddfd90828000002","description":"Cows"}},
{"category":{"id":"4d9c5dfc8ddfd90828000023","description":"Dogs"}},
...
{"category":{"id":"4d9c5dfc8ddfd90828000024","description":"Mules"}}]
Consuming the service with:
public List<Category> getAnimalCategories(Cookie cookie) {
Client client = Client.create(new DefaultClientConfig());
ClientResponse response = client
.resource(Constants.BASE_URL)
.path(Constants.CATEGORIES_ANIMALS)
.accept(MediaType.APPLICATION_JSON)
.type(MediaType.APPLICATION_JSON)
.cookie(cookie)
.get(ClientResponse.class);
return response.getEntity(new GenericType<List<Category>>(){});
}
Where Category.java is:
public class Category {
public String id;
public String description;
public Category() {
}
public Category(String id, String description) {
super();
this.id = id;
this.description = description;
}
The service uses cookie based authentication - that part works and I have other service calls working with the cookie.
Used the Jackson 1.9.6 lib to resolve the issue - see the 2nd line below:
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getClasses().add(JacksonJsonProvider.class);
Client client = Client.create(clientConfig);
return client
.resource(Constants.BASE_URL)
.path(Constants.CATEGORIES_ANIMALS)
.type(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.cookie(cookie)
.get(new GenericType<List<AnimalCategoryResponse>>(){});
Also needed to use a new response class:
public class AnimalCategoryResponse {
public Category[] category;
public AnimalCategoryReponse() { }
}

Categories

Resources