Jersey Java Webservice XML - java

I've built up a Webservice in Java using Jersey.
The Webservice consumes XML and takes a POJO (CoResponse) as MethodParameters.
I.E.
#PUT
#Consumes(MediaType.APPLICATION_XML)
public CoResponse test(CoResponse obj){
//...do something....
return obj;
}
On Client side I would do a Put Request like this...
CoResponse rO = service.path("path")
.type(MediaType.APPLICATION_XML_TYPE)
.accept(MediaType.APPLICATION_XML)
.put(CoResponse.class, new CoResponse());
Actually everything is working fine in our environment. But now I would like to know what the xml-string sent to the Server looks like. The reason why is to use the webservice also in other environments by creating a custom Serializer / Deserializer (i.e. for windows mobile) that is compatible to our jersey webservice.
Is there a way of looking into the put method to see the final xmlstring? Or some other possibilities?

Use a LoggingFilter.
Just add it to your client:
client.add(new LoggingFilter(System.out));

Related

Jersey client testing

I have a Jersey client which performs post request to some black box service.
Also I have POJO mapping feature enabled.
I have integration tests already, they are calling real black box service.
Now I need to test my application without calling real black box service.
My question is: how can I test this Jersey client? I mean: how can I test Jersey client without calling real black box service?Maybe there is some possibility to mock JSON response in tests?
Environment: jersey-client and jersey-json versions - 1.19.1.
You can log the request using LoggingFilter to make sure your requests are according to your estimate. For running your test, you can use http://mockable.io/.
P.S. Do not forget to replace the Webtarget URL with MockableIO's URL.
You can try Karate which has recently introduced a way to create simple mocks for JSON responses. Here is an example:
https://gist.github.com/ptrthomas/35ef9d40623cbeade7388b2cbb29a3b1
While the above example is a "smart" mock, it is very easy to create hard-coded mocks, here is an example: https://github.com/intuit/karate/blob/master/karate-netty/src/test/java/com/intuit/karate/mock/_mock.feature
You can easily read files from JSON by using the read keyword.
I have performed an investigation concerning my question. Mentioned investigation resulted in such facts:
I haven't found features/mechanisms/etc. to test Jersey client without real calls to the server (in my case - black box service).
Jersey test framework provides features for testing Jersey server, but there are no features for testing Jersey client
The only one solution for testing client without server is to refactor my code in following way: split logic into two phazes. First phaze: get JSON response using Jersey. Second phaze: get JSON response (which we get in first phaze) and transform it into desired object. In general you'll have next code as a result:
Class< String > jsonResposeClass = String.class;
String jsonResponse = post( yourRequest, jsonResposeClass );
ObjectMapper mapper = new ObjectMapper();
YourResponseBean bean = mapper.readValue( jsonResponse , responseClass );
The solution above will give you a possibility to use mocking libraries like Mockito and mock method which performs post request.
If you have found any other solution/feature/special mechanism/etc which can also help in such kind of situation - please share :)

Produce and Consume data in Java RESTful with Jersey and JSON

Folks,
I am newbie to Java RESTful,
I need to pass the data from my java application to the RESTful service. I am able to add the RESTful to my application but not able to send any data back to the service.
I used #GET and #Consumes at service. Please help me to get connect and data exchange between the same
As RESTful acts as server in my application
RESTful defined
#GET
#Consumes("application/json")
#Path("{strID}")
public String getJson(#PathParam("strID")String strID){
return strID;
}
Imported RESTful method
public String getJson(String strID) throws UniformInterfaceException {
WebResource resource = webResource;
resource = resource.path(java.text.MessageFormat.format("{0}", new Object[]{strID}));
return resource.get(String.class);
}
inside the java application
static RESTful objRFIDService = new RESTful();
objRFIDService.getJson("RESTfultest");
What you are trying to achieve is not really clear. However, to consume a REST webservice, you can use the JAX-RS Client API, which is part of the JAX-RS 2.0 specification and the reference implementation is Jersey.
For instance, to perform a GET request to a resource available in http://example.com/api/foo/{id}, you can use the following code:
String id = ...
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://example.com").path("api").path("foo").path(id);
String result = target.request(MediaType.APPLICATION_JSON_TYPE).get(String.class);
For more details, have a look at the Jersey Client API documentation.

Sharing objects with jersey json REST client

I have written a REST service using jersey which maps a object-structure to a json-result, like:
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/orders/{id}")
public Order getById(#PathParam("id") String orderId) {
return orderService.getById(id); // Simplified
}
It works perfectly and returns the Order object structure as a JSON structure.
Now a (jersey) client accesses this REST service and gets those JSON structure back. It can parse it as a JSON structure, but it would be nice to map it back to (the server's) object structure.
But the server's objects contain many JPA-Annotations and other imports the client does not know about.
How can I share anyway my server object structure as (unannotated?) POJOs to my client? TIA!
Try a java generator from json https://javafromjson.dashingrocket.com/

Any simple way to test a #RequestBody method?

If I have a #Controller method whose parameter is a #RequestBody param, I usually have to write some jQuery script or something similar to perform an AJAX request with JSON object in order to call that method. If I tried calling that method via a web browser directly, it returns with a Error 415 Unsupported Media Type.
Is there any alternative to just quickly call such method using browser without having to write some jQuery code? Like perhaps a way to write the JSON object in the URL/address bar?
code:
#RequestMapping("testCall")
#ResponseBody
public List<TestObject> getTestCall (#RequestBody TestParams testParams) {
return stuff;
}
public class TestParams {
private Integer testNumber;
//getter/setter for testNumber
}
I thought maybe I could just do:
http://localhost/testCall?testNumber=1
maybe Spring would auto populate a new TestParams instance with that property set to 1 but that didnt work...
maybe I need to do something extra for that?
The whole point of a #RequestBody annotated parameters is for the Spring MVC stack to use the HTTP request body to produce an argument that will be bound to the parameter. As such, you need to provide a request body. Sending a request body is very atypical for a GET request. As such, browsers don't typically support it, at least not when simply entering an address in the address bar and submitting the request.
You'll need to use a different HTTP client, like jQuery. I typically have a small Java project in Eclipse that's setup with an Apache HTTP components client which can send HTTP requests to whatever server. It takes a few seconds/minutes to setup the correct request body and run.
I have spent the last year building a REST API, and by far the best way to exercise that API manually is using the Chrome Extension, Postman. I cannot recommend this tool enough.
https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en
To test your simple example you'll need to invoke a POST (I assume that as you have a request body, but your controller method doesn't define a HTTP Verb) using POSTMAN to your Url (like the following example):
POST /contextRoot/testCall
{
"testNumber": 1
}
If you want to test your API automatically (which I recommend), you can use the excellent Spring Mvc Test project. This allows your to call your API via a rest-like DSL and assert that the response is in the shape you want. More details can be found here:
http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/testing.html#spring-mvc-test-framework
you can add request params to the getTestCall method:
#RequestParam(value = "testNumber", required = false, defaultValue = "") String testNumber
There is a chrome app called Advanced REST client. You can pass the data in form of json to your controller using this chrome app. For eg. json data is
id:1,
name:"xyz"
whereas the controller can have #RequestBody Person form.
The Person class would be a POJO having id and name as instance variables. The Spring would automatically map the json data to the form.
I think this is the easiest and simplest way of checking your spring controller.
Check the extension Advanced REST client here
From what I know You can send JSON object to the webbrowser and it will be displayed without further need of AJAX.
useful tutorial:
http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/

How can i send object in HTTP request

I am creating a Web Service that will handle incoming request properly (I knew, it is a description) I found some sample code which present SOAP WS and looks like:
#SoapAction("some fine url")
#ResponsePayload
public CertResponse getCert(#RequestPayload Cert param)
{...}
It takes Cert object from request and manages it properly. I want to do it in the REST approach and I changed this class to look like:
#RequestMapping(value="getCert", method = RequestMethod.POST)
#ResponseBody
public CertResponse getCert(#RequestBody Cert param)
{...}
But I have no idea how or even if it is possible to write a client that can send object through HTTP Post.
Can anyone give me a hint how can i send object Cert? Or if i have to stay with #SoapAction what should I do to make it work? I guess removing #Controller is not enough.
In SOAP approach, there is a well defined way to convert each class object to SOAP formatted XML. Thus, there is no effort.
If you will use RESTful approach, you have to describe how your Cert or CertResponse objects will be written to/read from the response/request.
Basically you have three options:
Use JSON or XML or plain String. Convert your Web service descriptor so that the request and response are one of those (JSON, XML, String). Then your getCert method should convert the request to Cert object, prepare your response as CertResponse object and convert it to an appropriate response type.
Leave your getCert method as is. But you need to specify "how Cert objects are read from request" and "how CertResponse objects are written to response" You need to define classes that extend interfaces MessageBodyReader and MessageBodyWriter. In these classes a similar conversion logic should be implemented that converts your objects to/from JSON or XML or String.
In any of these two options you need to implement two things : A method that converts JSON/XML/String to Cert, a method that converts CertResponse object to JSON/XML/String.
You can do a text based implementation, which parses/constructs the request/response by text processing and uses String class only. Or you can use some library such as JSON library with JSONObject class, or Java SAX or DOM based XML libraries that come with the Java bundle.
Check out for application frameworks such as Spring. They might provide ways to automatically convert your objects to JSON or XML, reducing the programming effort necessary.
Spring allows you to pass JSON objects from the client as a request parameters, it will convert them into your objects automatically. This discussion have some examples.
SOAP services are not really compatible with REST semantics. And it's not clear what SOAP framework do you use. Typically most SOAP frameworks offer you one way or another to generate a SOAP client code for you WSDL. You can check cxf.apache.org.
For REST services use something like Jersey or Spring MVC

Categories