Issues With JAX-RS - java

I'm new to JAX-RS and having a number of issues (which oddly make me miss SOAP). Here is a snippet of my code. The getMergedPDFReport method should take a file and return a file after some processing. After which I would worry about the client
#GET
#Produces("application/pdf")
#Path("merge-service")
public Response getMergedPDFReport(#QueryParam(ApiParameters.WORD_DOCUMENT) File wordDocument,
#QueryParam(ApiParameters.MERGE_FIELDS)Object[] fieldNames,
#QueryParam(ApiParameters.MERGE_VALUES) Object [] fieldValues) {
ResponseBuilder builder =null;
try {
File product = DocumentUtil.generatePDF(wordDocument, fieldNames, fieldValues);
builder = Response.ok(product);
builder.header("Content-Disposition", "attachment; filename=\\\"report.pdf\\\"");
} catch (Exception e) {
e.printStackTrace();
}
return builder.build();
}
I get a warning on my server log that says "No injection source found for a parameter of type public javax.ws.rs.core.Response". I can't seem to know why.
2. Am I using the #QueryParam annotation right? Should I be using it for types of File, and arrays? I saw a lot of debates online over #BeanParam, #MatrixParam and #QueryParam. Since I didn't know what the first two do, I decided to Keep It Simple.
Any help would be appreciated.

I think you can't use queryParam for files. You must use a #Consumes with a multipart form.
Check this :
http://www.javatpoint.com/jax-rs-file-upload-example

Related

How to test a HTTP request

I have set up this simple http request, which simply returns a "hello world" response to my IDE terminal. I have been looking into testing and I am not quite sure how i would test what this method is returning.
Currently i have done my own research into JUnit, but again i am not even sure if this would be the correct tool to use for this problem. I only researched this as it is a Java tool.
public static void newRequest() throws IOException {
URL helloServer = new URL("http://localhost:5050/");
HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(helloServer));
HttpResponse rawResponse = request.execute();
String responseString = rawResponse.parseAsString();
logger.debug(responseString);
}
Any guidance on this would be greatly appreciated.
Does the function even need to be tested?
Does the function even need to be tested? Well, that is entirely up to you. Does this function contain code that is critical to your application? If so then yes. If the impact of a bug in this function is minimal then probably not.
Assuming that you want to test this, then:
The method in question is not returning anything void before the function name says this. You will need to look at testing the logic of the function. In this case you need to check that the correct response is received. There are two ways that I can think of to do this:
Modify the code to return the response.
You could change the function to return a String and then return rawResponse.parseAsString(); (which is the same thing you are logging.
Then you can call the function from the test and check the String that is returned.
Get the log message from your logger.
Depending on the logging that you are using, you could get the log message that was written by the function. Assuming log4j then there are some posts on how to do this:
log4j: how to get the last inserted log message?
Personally, I prefer the first option as it is less effort. I would also consider returning the body of the response rather than the raw response.

Parsing a string with multiple variations

I am curious as to what a better way to deal with this is, I wanted to challenge my self and see if I could break up, in a HashMap of key,value (or String, String), a string that could come back in almost any format.
the string in question is:
/user/2/update?updates=success
Thats right, a url request for a server. The issue - as we all know this could be any thing, it could come back in any form. I wanted to break it up so that it would look like:
Controller => user
action => update
params => ??? (theres a 2, a update=success ... )
Obviously The above is not a real java object.
But you get the idea.
What do you need? what have you done? what are you trying to do?
What I want to do is map this to a controller and action while passing in the parameters along the way. But i need to separate this up making sure to specify each step what is what.
What I have done is:
private Filter parseRoute(String route){
String[] parsedRoute = route.split("[?:/=]");
Filter filter = new Filter(parsedRoute);
return filter;
}
Splits on any thing that is in the url (note, : would be something like /user:id/update
so: user/2/update ... )
I then attempted to do:
public class Filter {
private HashMap<String, String> filterInfo;
public Filter(String[] filteredRoute){
if(filteredRoute.length > 0){
filterInfo.put("Controller", filteredRoute[0]);
}else{
throw new RoutingException("routes must not be empty.");
}
}
}
But this is not going to work as I expected it to...As there are too many variables at play.
including parameters before the action (those would just be used to search for that user), their could be nested routes, so multiple controller/action/controller/action ..
How would you deal with this? What would you suggest? How could you get around this? Should you just do something like:
route(controller, action, params, template); ? (template lets you render a jsp). if so how do you deal with the ?update=success
I am using HttpServer to set up the basics. But I am now lost. I am trying to keep routing as generic and "do what ever you want we will map it to the right controller, action and pass in the parameters" but I think I bit off more then I can chew.
I have looked at both spark and spring framework, and decided that the route you pass, we will map to a xml file to find the controller and action, I just need the data structure in place to do that ...
So I am looking to back up and still go with "pass me something, ill map it out."
I would probably use the URL from apache,
org.apache.tomcat.util.net.URL url = null;
try {
url = new org.apache.tomcat.util.net.URL("/user/2/update?updates=success");
// ... do some stuff with it...
} catch (Exception e) {
e.printStackTrace();
}
java.net.URI may help you.
you can get your path by getPath()
and get all of your query by getQuery(),then you can split the query by = to name value pairs.
URI uri = new URI("/user/2/update?updates=success");
// /user/2/update
System.out.println("path is " + uri.getPath());
// updates=success
System.out.println("query is " + uri.getQuery());

Play! 2+ Adding JSON support in a RESTfull way

I'm used to do ROR, but I need to make a RESTfull WebService in a Java environnement. So I decided to try it with Play! since it really look like a great idea.
So I'm trying to find a way to add JSON to my already existing firstapp done following those instruction : http://www.playframework.org/documentation/2.0.3/JavaTodoList
What I want is something working similarly to ROR. At least, I want to be able to ask for JSON support by :
calling a .json URL
using "Accept: application/json" Header
So I tried some dirty thing like that :
JsonNode json = request().body().asJson();
if(json != null) {
return ok(Json.toJson(Task.all()));
}
return ok(
views.html.index.render(Task.all(), taskForm)
);
And it's obviously not working right now...
I need to detect wich type the client is requiring. I saw some people were adding dirty routes like that :
POST /bars BarController.index()
GET /bars.json BarController.indexJSON()
But it will clearly not support client using header to specify json request...
So, what I need is some kind of way to find out if there is any Header specifing content-type or Accept application/json. If it is so, BarController.index() would return BarController.indexJSON()...
All in all, it would be pretty much similar to ROR wich do :
respond_to do |format|
format.html # index.html.erb
format.json { render json: #bars }
end
All in all :
Does anyone have gone through the same reasoning than me and had reach an end ?
So I resolved my problem by using to function in controller, like this :
public static Result index()
public static Result indexJSON()
Then I added routes :
GET /tasks controllers.TaskController.index()
GET /tasks/json controllers.TaskController.indexJSON()
I would have preferred task.json but it wouldn't have allowed /tasks/:id.json ...
And for Header support, you need to check in your classic function if there is no header :
public static Result index() {
if (request().getHeader(play.mvc.Http.HeaderNames.ACCEPT).equalsIgnoreCase("application/json") || request().getHeader(Http.HeaderNames.CONTENT_TYPE).equalsIgnoreCase("application/json")) {
return indexJSON();
}
else {
return ok(
views.html.index.render(Task.all(), taskForm)
);
}
}
End that's all folks !
Does anybody have a better solution ? I don't like this one very much... Because I'm going to repeat many code ...

GWT file upload

I have a following problem - we are using FormPanel which sends file to the Servlet which takes the arguments and tries to parse XML from this file. This works fine.
Problem is when the user uploaded a wrong file, so parsing ends with SAXException which I would like to propagate (or the exception's message) to client. I tried something like
catch (SAXException ex) {
response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
response.flushBuffer();
}
but it's not working, I always get empty tag pre (<pre></pre>). I am trying to catch this with
formPanel.addSubmitCompleteHandler(new SubmitCompleteHandler() {
#Override
public void onSubmitComplete(SubmitCompleteEvent event) {
String s = event.getResults();
});
I can use response.getWriter().write("Error"); in my Servlet but how the client will know if the error really occured or not?Using something like event.getResults().contains("error") doesn't seem to me as a correct solution.
So I am thinking about using RequestBuilder but I don't see a way how could I get the the uploaded file and push it to my servlet. Or maybe converting my message to JSON would help?
You should refer to this thread on the google gwt discussion group. The way you described, parsing the event.getResults() to determine if there was an error or the result in case of a success is the correct way to do it, even though it might seem barbaric.
As suggested in the linked discussion, you can look into GWT Upload for cleaner code, as well as upload progress information. I believe your only two options to upload files to a server from a web page are forms or Flash.

How to parse a malformed xml (ofx) with ofx4j?

i am desperatly trying to use the following library : ofx4j. But the documentation relative to parsing an ofx file is a bit lite. It says : If you've got a file or other stream resource, you can read it using an instance of net.sf.ofx4j.io.OFXReader
Ok but how do i do ?
It also states the following: if you want to unmarshal the OFX directly to a Java object, use the net.sf.ofx4j.io.AggregateUnmarshaller.
Fine, but that's a bit complicated for me. Is there something obvious that i missed ? When i try to use the unmarshaller, it asks me to implement an interface.
Could someone point me to an online resource explaining the bits that i am missing ? Or the best, what do you understand from the previous statements relative to the ofxreader and the unmarshaller ?
Please, don't bash me, I am learning java with the playframework and i would really appreciate to be able to parse those ofx files.
thanks in advance.
I don't see a plain old tutorial, but there's sample code in the test directory that illustrates OFXReader and AggregateUnmarshaller.
The phrase "an instance of net.sf.ofx4j.io.OFXReader" means one of the known implementing classes", such as NanoXMLOFXReader, which is tested here. A test for AggregateUnmarshaller is here.
The API and mail archives are good resources, too. It looks like a lot of institutions participate.
For those that stumble on this like I did when I couldn't get the expected results from the AggregateUnmarshaller... Here is an example.
//Using a multipart file, but using a regular file is similar.
public void parse(MultipartFile file) throws IOException {
//Use ResponseEnvelope to start.
AggregateUnmarshaller<ResponseEnvelope> unmarshaller = new AggregateUnmarshaller<ResponseEnvelope>(
ResponseEnvelope.class);
try {
ResponseEnvelope envelope = unmarshaller.unmarshal(file.getInputStream());
//Assume we are just interested in the credit card info. Make sure to cast.
CreditCardResponseMessageSet messageSet = (CreditCardResponseMessageSet) envelope
.getMessageSet(MessageSetType.creditcard);
List<CreditCardStatementResponseTransaction> responses = messageSet.getStatementResponses();
for (CreditCardStatementResponseTransaction response : responses) {
CreditCardStatementResponse message = response.getMessage();
String currencyCode = message.getCurrencyCode();
List<Transaction> transactions = message.getTransactionList().getTransactions();
for (Transaction transaction : transactions) {
System.out.println(transaction.getName() + " " + transaction.getAmount() + " "
+ currencyCode);
}
}
}
catch (OFXParseException e) {
e.printStackTrace();
}
}

Categories

Resources