Starting point for converting jersey project to standard servlet app - java

I am trying to implement the example shown here.
The example seems to be for a jersey setup, which I am not using or familiar. How hard would it be to convert this to a standard java servlet project(idk how to name this)
What steps should I take. It seems most of the # annotations need to be changed to servlets.
This also seems very differnt from the standard appengine upload setup which all takes place in one servlet.

This would be a lot of work to rework the code to standard servlet and remove jersey. Jersey takes away so much boilerplate code. For example the JSON conversion is done by jersey, which otherwise would have to be custom implemented.
And you can for sure deploy more than one servlet to gae, in which way should this be standard?
Just look at the first method:
#GET
#Path("/url")
public Response getCallbackUrl() {
String url = blobstoreService.createUploadUrl("/rest/file");
return Response.ok(new FileUrl(url)).build();
}
When using only standard servlet you would need to do:
Servlet Definition and Mapping in web.xml to /url
Implement a HttpServlet, override doGet() method
Send Response Code 200 OK
Set appropriate HTTP Response Headers
Convert Response to JSON and write it to response

Related

Filter, get url before controller (Spring MVC)

I want to write filter, and get client httprequest before controller and make some code, depends on URL.
Request can be: HttpRequest, MultipartHttpServletRequest, can be POST or GET. I need to make request to another REST API, if the URL of this request starts with api.
You should use Spring org.springframework.web.servlet.HandlerInterceptor
(hopefully this answer explain how to use it)
(or you could use an simple Servlet-Filter - see also this question Spring HandlerInterceptor vs Servlet Filters it discuss the difference between them)

Application/JSON is Unsupported Media Type in restful webservice

I am trying to create a restful-jersey webservice. I have to pass JSON object to the webservice.
#POST
#Path("/saveVehicleTrackingData")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.TEXT_PLAIN)
public String saveVehicleTrackingData(VehicleTracking vehicleTracking) {
return vehicleTracking.toString();
}
When I try try to make request to the service, it says HTTP Status 415 - Unsupported Media Type. Please help. Also, what should be the type of single argument of the method saveVehicleTrackingData.
PS: I am using POSTMAN to make http request. http://goo.gl/vwXNXQ
UPDATE :
As pointed out by peeskillet, the missing thing here is JSON Provider. The next challenge that I have is, how to integrate the JSON Provider in my project. After researching a little, I found FasterXML jackson as one of the JSON provider.
This image is just for reference. I just had it from another post.
Basically when you use raw, it will default to text/plain. The JSON in the drop down, is simply to select syntax highlighting. You still need to set the Content-Type header to application/json. You can click on the Headers button and add it.
For your first question:
What kind of hosting (Tomcat, GlassFish or whatever...) are you using, and what is the Java version of the host? I know from experience that different version of Tomcat in combination with Jersey sometimes gives problems with #Consumes(MediaType.APPLICATION_JSON).
About your second question:
You want to build a RESTful webservice, the right name for a path should be; VehicleTrackingData (or whatever you like). This path will work (request/response) with the known HTTP verbs; GET, POST, PUT or DELETE.

REST API invocation in Java

Suppose I need to write a Java client, which calls a REST API (with HTTP GET). I know it returns the data in JSON by default and I do not need to supply any headers.
Now I can use either Apache HttpClient to invoke the API or read the URL directly (get a stream from the URL with url.openStream and read the data). The second approach seems to me much simpler. Which one would you suggest and why ?
All the REST clients provide a wrapper over basic java URL based APIs. These clients are easy to use and provide all the necessary functionality. Your code will be much cleaner in case you use Apache HttpClient. And Apache's API are quite reliable.
I would use special libraries for that, like Jersey client or Apache CXF client.
https://jersey.java.net/documentation/latest/client.html
http://cxf.apache.org/docs/jax-rs.html
These ones are part of Java EE standard, a well defined specification which is widely used.
For JSON, consider https://github.com/FasterXML/jackson. Depending on what client you use, you will find information about how to make it work.
If you are not a big fan of JavaEE, and you look for neat and elegant API, and you are interested in working with a language on top of Java, Groovy HTTPBuilder is such a library that works like a charm!
twitter = new RESTClient( 'https://twitter.com/statuses/' )
resp = twitter.post( path : 'update.xml',
body : [ status:msg, source:'httpbuilder' ],
requestContentType : URLENC )
assert resp.status == 200
assert resp.data.user.screen_name == userName
You can use spring-data-rest and Spring's RestTemplate. No need to write a webapp as you can bootstrap Spring easily into a standalone java application putting AnnotationConfigApplicationContext in the Main(). It's quite simple.
For example, suppose you have a Restful URL, http://localhost:8080/croot/books/ that returns a list of books (deserialized into objects of type Book).
Using Spring's RestTemplate you can do the following:
public Resource<List<Resource<Book>>> findAll() {
return restTemplate
.exchange(
"http://localhost:8080/croot/books/",
HttpMethod.GET,
null,
new ParameterizedTypeReference<Resource<List<Resource<Book>>>>() {
}).getBody();
}
You can also process this using spring-data-hateoas allowing you to further decouple the client from the server and helps process what to do next, say in pagination.
This is a very simplified/contrived example but the REST support in Spring 3 combined with the spring-data framework is quite elegant.
Using Spring you also get the advantage of Jackson for JSON processing as the RestTemplate will have one of the flavors of Jackson's message converters (provided through MappingJackson2HttpMessageConverter for example) in it's list of default converters used for processing.

Pass object as arument in RESTful web service

I am creating a simple RESTful web service with simple types successfully. Now I want to pass an object as argument for web service and get the object as response. My scenario is, Parse the XML message as object by using Jaxb and send the object as request for web service. After that in server side it process the requested object and generates the response xml file and send back it as object.
In URL path i give
"http://localhost:8080/SampleWS/rest/checkXML/username=visolve&password=visolve"
for simple type. But in object I don't know how to give the object reference in URL. Please help me how to solve my problem..
Regards
Bathakarai
Just define a very good-looking domain object. JAXB and JAX-RS will do the rest.
JAXB.
#XmlRootElement
class Regards {
#XmlElement
private long sincerely;
}
JAX-RS.
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#POST
#Path("/sincerely")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response sincerely(final Regards regards) {
regards.setSincerely(System.currentTimeMillis());
return Response.ok(regards).build();
}
Though you could certainly include the entire XML content in your URL, I would probably shy away from it.
Think of it this way: if you encode the XML in the URL you're potentially adding more work on both ends. Now the server and client will both need to know how to build the URL properly, and check to make sure everything lines up correctly. What if, in the future, you need to offer a JSON or YAML view of the same content? Now your URL might need to include the content-type as well. What about character-encoding?
All this to say, HTTP provides a terrific transport mechanism which already addresses these concerns. Include the XML as the entity body of the HTTP message, and use the HTTP header to identify what content-type you're sending, character-encoding, etc. This will work both ways (the server and client both can send the XML back/forth), and makes better use of HTTP.
Here's a related link which might help with some of the details. And another.
On a side note, please, please, please tell me you don't plan on sending user-credentials in plain text across an unencrypted link.

ServletRequestWrapper or ServletResponseWrapper in production?

Hi have you seen anything really useful extending HttpServletResponseWrapper/HttpServletRequestWrapper or ServletRequestWrapper/ ServletResponseWrapper in production environment?
Trim whitespace from generated HTML, can save over 50% of bandwidth. I've had a project which displays large tabular data (with nicely indented HTML source), response size went from ~200KB to ~70KB by just trimming all whitespace away.
Process multipart/form-data requests transparently by putting multipart form data back in request parameter map so that you can use request.getParameter() and consorts the usual way again (Servlet <=2.5 example, Servlet >=3.0 example).
Capture the outputstream, either to have a copy or to MD5-hash it.
Disabling URL rewriting.
Etcetera.. Etcetera.. All just to override and change the default behaviour of certain HttpServletRequest/HttpServletResponse methods.
I've used it to "capture" the output of a JSP, so that it can be transformed by the forwarding controller. This was done by overriding the getWriter() / getOutputStream() methods.
SiteMesh does a similar thing, capturing the "target" in order to decorate the response.
We use it to
overwrite getRemoteAddr() to return values from X-Forwarded-For or X-Real-IP (set by our nginx proxy)
filter certain headers, e.g. to avoid content negotiation in 3rd party servlets
gzip response
Many frameworks (richfaces, myfaces on my current classpath at least) use a request wrapper to handle multipart requests
Spring has ContextExposingHttpServletRequest so that spring beans are accessible as request attributes.
myfaces orchestra uses the response wrapper to rewrite the URL in order to ensure multiple-window conversation context
I've used it just recently to capture outgoing response headers for debugging purposes (getHeaderNames() and getHeader() were only added on the response side in the Servlet 3.0 spec.
We've also used it for gathering metrics on our servlets, by overriding getOutputStream() to return an OutputStream implementation which increases a counter on every byte that passes through it so we can tell what our high-network-traffic servlets are.

Categories

Resources