restTemplate multi response structure - json

I need to call Rest web service using the GET method, the server will send 2 kind of response. when the request is processed with no business error it will send an object of type T. in case of business exception it will send an object of type E.
How can i call this web service using the restTemplate.getForEntity(url, responseType) method and receive a response with T type or E Type dynamically. because as you can see the method accept only one type.

In case of exception, the REST web service would be sending an error response, i.e. the code would not be 200, but 4** or 5**? If so, RestTemplate would use a DefaultResponseErrorHandler and throw an instance of HttpStatusCodeException with a method getResponseBodyAsString(). You can then use some converter to convert the string to a Java object.

Related

#Produces({"application/json"}) not generating json

Looks like JAX-RS uses standard providers to transform Rest API Response into the type specified in #Produces.
I have an API which works fine in successful cases(returns a JSON). In cases where i use response builder to generate response out of exception message(as below) , it does not come as a JSON, comes as a plain string. Why is the appropriate provider not throwing an exception or not writing it as a JSON?
return Response.status(Response.Status.UNAUTHORIZED).entity(e.getMessage()).build();

REST proxy for a SOAP Web Service: can I reuse the JAXB classes for the input/output JSON?

I'm creating a proxy service for translating an existing SOAP Web Service to REST. I mean, to create a REST Controller based on Spring for creating the REST interface that will call the existing SOAP Web Service.
The SOAP response must be translated into JSON on the REST service's response.
The steps I followed were:
I have generated the SOAP WebService classes thanks to CXF
(wsdl2java). OK.
I have created the REST Controller for invoking the existing SOAP WS with the previous classes. OK.
The input JSON parameter corresponds to the SOAP input parameter. Can I reuse the JAXB classes I generated on the wsdl2java process?
So I tried to define the REST controller as:
public #ResponseBody WebServiceJAXBOutput service(#RequestBody WebServiceJAXBInput input){
...
}
Nevertheless, the REST call always returns 400 (Bad request) if I specify the data values. Although it works if the input JSON fields are null:
{
"application":null,
"center":null,
"language":null
}
I guess the JAXB getter/setters are failing because of the JAXBElement (public JAXBElement getApplication()).
Should this approach work? Did I miss something?
Many thanks!!
Sergi

why use http.route() method use type="json" in openerp

above code from the website_mail module controller file email_designer.py file
class WebsiteEmailDesigner(http.Controller):
#http.route('/website_mail/email_designer/<model("email.template"):template>/', type='http', auth="user", website=True, multilang=True)
def index(self, template, **kw):
values = {
'template': template,
}
return request.website.render("website_mail.designer_index", values)
#http.route(['/website_mail/snippets'], type='json', auth="user", website=True)
def snippets(self):
return request.website._render('website_mail.email_designer_snippets')
which situation we are using type="json" and type="http" and why..??
Basically type="json" is used to pass data from controller where as type="html" is for responding over http request.
For example from your above code:
the url "/website_mail/email_designer//" will respond towards any particular http request and route to its web page where as the url "/website_mail/snippets" will just pass json data to its rendered template but there is no physical webpage related to this url.
Methods that received JSON can be defined by passing 'json' to the type argument of http.route(). The OpenERP Javascript client can contact these methods using the JSON-RPC protocol. JSON methods must return JSON. Like the HTTP methods they receive arguments as named parameters (except these arguments are JSON-RPC parameters).
#http.route('/division', type="json")
def division(self, i, j):
return i / j # returns a number
Both of them are about communication between client and server. HttpRequest communicates trough the well known GET and POST methods. That means the following:
The client send a request encoded in the url (GET method) or in the http body (POST method)
The server returns an object corresponding to the request. Could be an html page, PNG image, CSS file, JavaScript, XML encoded data or whatever.
JsonRequest is an implementation of another protocol for client/server communication - JSON-RPC 2.0. You may want lo took here form more information. It's a remote procedure call (RPC) protocol which means that it allows the client to initiate the execution of some method on the server passing some arguments to this method. In response the client gets some data as a result of the method invocation.
EDIT - some more words about the decorators #openerpweb.jsonrequest and #openerpweb.httprequest
Some methods are decorated with the #openerpweb.jsonrequest decorator, other methods - with the #openerpweb.httprequest. This means nothing else but that the first group of methods will be available for execution trough the JSON RPC protocol and the second group will be accessible trough the pure HTTP protocol.
Now, what is the difference? I do we need both jsonrequest and httprequest? Let simplify it like this: JSON is more suitable for executing methods on the server and obtain results. HTTP is simpler and easier to use when all we what is to access some resource on the server.
Let's 'decorate' this with some examples for clarity. Take a look at the following method of the web.controllers.main.Export class:
#openerpweb.jsonrequest
def formats(self, req):
""" Returns all valid export formats
:returns: for each export format, a pair of identifier and printable name
:rtype: [(str, str)]
"""
...
This method accepts some arguments and returns a list (Python list object) containing all known export formats. It will be called in a programmatic way in some python code on the client side.
On the other side are the 'http' methods - like the method css() of the web.controllers.main.Web class:
#openerpweb.httprequest
def css(self, req, mods=None):
....
All this method does is to return a CSS file to the client. It's a simple action like accessing an image, a HTML web page or whatever other resource on the server. The resource we are returning here is nothing complicated as a Python list as in the previous example. We don't need a special format to encode it additionally. So we don't need additional data encoding format as JSON and remote procedure call protocol as JSON RPC.
type="json":
it will call JSONRPC as an argument to http.route() so here , there will be only JSON data be able to pass via JSONRPC, It will only accept json data object as argument.
type="http":
As compred to JSON, http will pass http request arguments to http.route() not json data.
Examples
#http.route('demo_html', type="http") // Work Pefrect when I call this URL
def some_html(self):
return "<h1>This is a test</h1>"
#http.route('demo_json', type="json") // Not working when I call this URL
def some_json(self):
return {"sample_dictionary": "This is a sample JSON dictionary"}

REST api with HttpClient but unknown JSON response

I'm using the WebApi httpclient to build up a .net api library for use against a REST webservice.
The rest service returns JSON.
Problem i am having is that for one request, it is possible that i get diffrent JSON formats back.
If the query was successful, I get back a JSON array which I have made a strong c# type to hold it.
Using the ReadAsAsync< T > method to get it out of the content.
If the request had a bad api key in or another error happens, the rest service returns a JSON object with some properties like status=error and an explanation message etc.
I cant then just use the ReadAsAsync< T > method as I dont know what format is comming back. I don't know much about the JSON linq library but is there a way I can put the JSON response into some JSON holder object and then check if there is a status=error in it and then use the correct deserialization to my strong type.
I seem to be able to store it in a JRaw object but don't know where to go from here.
Many thanks.
If the request had a bad api key in or another error happens, the rest service returns a JSON object with some properties like status=error and an explanation message etc.
In this case, the status code returned will not be successful. You can do a check on the status code and then deserialize your response content appropriately:
if (httpResponseMessage.IsSuccessStatusCode)
{
// Deserialize your JSON array
}
else
{
// Deserialize the error
}
You can use error handling in this case
try
{
//Deserialize your JSON Array..this will throw an exception in case of type mismatch
}
catch(Exception e)
{
//Deserialize your JSON object which will give you Error code or message
}

JSON issue in Spring 3 and

I am using Spring 3.0 and ExtJS. I have been trying to send a Map object from my controller to jsp. When I putting a pojo in HashMap and sending that HashMap to view.
From controller it is returning a Map but in ExtJS it is not able to read the response and gives below error.
HTTP Error code: 406
message
description The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ().
Can anyone tell that how this can be resolved?
I dont think you can just shove any POJO into a map and return it via an HttpResponse. That's not how JSON works.
In order to send JSON from Java, you have to do the equivalent of serializing it using a JSON API (or roll your own). FlexJSON is one I use, as it ships in Spring Roo and is pretty easy.