I am designing REST API of simple file storage where one of the operations is file upload that goes together with some file metadata (using "multipart/form-data").
For some cases I need the file ID to be generated out of my application so I use PUT Http method. When ID goes from outside the best practice is to use PUT method instead of POST. The reason is that PUT operation is idempotent. POST is not idempotent and is used when ID is generated internally.
Do you think that going with PUT is correct for file upload? (I have also POST because ID is sometimes generated internally)
Assuming that it is correct I have an issue with automated integration testing in Spring. The problem is with MockMvc support class called MockMultipartHttpServletRequestBuilder when writing integration test. It does not allow to change POST to PUT. Http method is constructor parameter somewhere higher in inheritence hierarchy and the filed is "private final". All the constructors of these classes are with default visibility modifier so when I extend it I am not able to call super constructors. It is completly sealed.
Any idea how to achieve this call with PUT method? (I can use Java or Groovy for this)
ResultActions response= mockMvc.perform(
fileUpload("/files")
.file(file)
.param("origin", origin)
)
Related
I have a folder /controllers with controllers and another /models where i put my models with get/sets.
Now, where is the usual place to put the methods to get data from the db,etc...?
In my last project I put it under the get/sets and it was a bit confusing.
Any helP?
For database you can have a DTO folder, but you could also have a intermediate Service folder where you put all the business rules. I like having a separate DTO object to make mocking easier too.
For strictly data access, spring boot handles most of CRUD. You just need to config spring to know you have a data access layer. #JpaRepository does this. This is probably where you should start looking. For custom data calls you're going to have to write custom methods inside the classes that make up the data access laters.
Your question is extremely broad but I hope I've given you enough to look at.
https://spring.io/guides/gs/accessing-data-jpa/
I've used both Play1.x and Play2.x, but I didn't find how Play distributes its request to different actions in its source code.
e.g.
http://HOST:9000/Application/index
Play could find the controller Application, and then invoke its index method.
I thought Play works this way:
Get URI's first part Application and init Application using reflection.
Get the second part of URI, index, invoke index() of Application using reflection.
But I don't know where's the code exactly.
And, If it using a lot of reflection, how could it handle millions of request ? I think reflection is a lot of slower than direct method call(Or Play make some magic optimize ?).
Route file get compiled into target/scala-2.10/src_managed/main/routes_routing.scala file.
Even if reflection would be involved why should it be slow? File need to be reflected once at app startup.
The route file points each uri to a specific method.
For example:
GET /clients/:id controllers.Clients.show(id: Long)
If you don't care about routes type-safety incorporated in Play 2.x you can easily write custom resolver which will catch all unhandled routes with Dynamic parts spanning several / so using simple string operations + reflections you can access any controller/action combination you want...
Anyway consider if your app's security is worth of this sacrifice.
PS.: hard believing that samples are not required to this approach, in other case let me know, I'll write something in free time
I am trying to use axis2-wsdl2code-maven-plugin for auto generating the server side class files from a wsdl.
I am not sure how to implement the SkeletonInterface to call the business logic. There is an auto-generated Skeleton file which implements the interface, but it has a un-implemented method in it.
The problem is that I am not allowed to modify auto-gen files hence not sure on how to implement the method.
Below are the things that I have tried:
Few issues that I am facing:
i. Tried to rename the interface implementation class and call it through service.xml, but the new impl was not being called. (AuthenticatedServicesValidSkeletonImpl.java)
ii. Tried to extend the Skeleton class, but got null pointer exception while deploying the application and there was nothing much which I could get from the logs.
iii. Tried with cfx plugin for auto-generation of classes as well, but getting similar issues in it.
Please help regarding this.
You need to put your business logic in the un-implemented method in the AuthenticatedServicesValidSkeletonImpl.java. This will provide you a POJO of Request, and at the end, you need to return back a POJO of Response which will then be serialized into the WebService Response. The Request and Response objects are already created by WSDL2java, you just need to use them.
I want to write a unit test for a servlet class that makes a call to a web service through java.net.URL.
I can create mock request and response objects to send to the servlet's doGet method easily (using the techniques from the pragmatic programmer text on junit), i.e., creating MockHttpServletRequest, MockHttpServletResponse, and passing these to doGet.
The part I'm having trouble with is the URL open in the servlet.
Right now, i'm just choosing between a call to a function that opens the URL and returns a string (the production code) and a call to a function that returns that directly returns a string for a fixed URL (the test code)
Ideally i'd like to have a doGet method in which the testing code is invisible - the choice between the function that makes the network access, and the one that directly returns a string should be transparent to doGet.
i can think of a number of ways of achieving this, but none feel right.
Example 1: wrap the function in a class that has a testOn boolean, and a setTestMode method; junit init can set the testMode to true, default is false. the testOn decides which method to call. negative is that i need a new class, seems like it could get out of hand.
Example 2: have two classes implementing the network access, one of which is the mock; have junit reload the mock class, production code load the regular class (or somehow remap the production class to the mock class). negative: not sure how this would be done; seems clumsy.
Example 3: have a class with static fields indicating if i want to use mocks, and condition the URL access in the servlet based on the field values. negative: feels like global variables.
Example 4: extend URL, so that the production code will work fine if i switch to URL only (but java.net.URL is final).
I couldn't find quite the right answer through a morning of searches, hence my turning to the collective wisdom of SO.
Thanks,
Adnan
ps - I should mention that I don't have to use java.net.URL, anything that's equivalent will work.
Your second option is the "right" option. The call to the external URL should be encapsulated in a service. The service, then, is injected into the servlet that uses it. This is one place where Inversion of Control comes in handy.
In your unit test you'd inject the test implementation, in real life you'd inject a real implementation. It can be as simple as providing a setter for the service and defaulting the implementation to the "real" one.
This kind of thing is a canonical example for IoC/DI.
Looks like you are reinventing the wheel - and you invented it yet again in Example 2. This is typically implemented using dependency injection and is actually the best solution software developers came up with so far.
Hide your web service call behind an interface. One implementation does the actual call while the other is a mock that you can configure. If you are not using any DI framework (Spring, Guice, EJB/CDI), replace production implementation with mock manually in the test.
I am interested in creating a web app that uses JSP, Servlets and XML.
At the moment I have the following:
JSP - Form input.
Servlet - Retrieving Form data and sending that data to a java object.
Java object (1) - Converts data into XML file....instantiates java object (2).
Java object (2) - Sends that file to a database.
On the returning side the database will send back another XML file that I will then process using XSLT to display back to the user.
Can I place that XSLT code in the orignial Servlets doPost() method? So my doPost()` method would:
Retrieve user inputted data from the form on my JSP page.
Instantiate a java object to convert that data to XML, in-turn that object will instantiates another object to send the XML file to a database.
Converts the resulting XML file sent from the database and displays it for the user.
Can one servlet doPost() method handle all of this? If not, how would I set up my application and classes to handle this work flow?
Thank you in advance
I wouldn't load the XSLT in POST, because every method has to do it.
Read that XSTL in the init method, precompile and cache it. Just make sure that you keep it thread safe.
Once you have the XSLT, you've got to apply it to every XML response, so those steps do belong in POST.
All your doPost() method has to do is generate a suitable servlet response (some form of content, and a suitable HTTP response structure). So it can do anything you want (including the above).
However it sounds like your rendering requirement is distinct from your form submission and storage requirement. So I would make your doPost() method delegate to a suitable method for rendering the output. That way you can generate output from stored data separately from submitting data to the database.
Well, this is not really specific to servlets, but more to Java/OOP (object oriented programming) in general. You can in fact do everything in a single method, even in a main() method. But hundreds or more of lines in a single method isn't really readable, maintainable, reuseable nor testable in long terms. Right now, you're probably just starting with Java and you probably don't need to do anything else than this, but if you ever need to duplicate (almost) the same lines of code, then it's time to refactor. Extract the variables from the duplicate code lines and wrap those lines in a new method which takes those variables as arguments and does a simple one-step task.
In general, you'd like to already split the big task in separate subtasks beforehand, using separate and reuseable classes and methods. In your case, you can for example have a single DAO class for all the DB interaction task, a generic XML helper class to convert Javabeans to XML and vice versa with help of XSL and (maybe) a domain object to manage the input/output processing (conversion/validation/errorhandling/response) and executing actions. Write down in paper how the big picture is to be accomplished in small single tasks. Each task can be often as good done by a single method. Group the methods with the same responsibilities and/or the same shared data in the same class.
To go a step further, for several tasks there may be 3rd party tools available which eases the task. I can think of for example XMLBeans and/or XStream to do the Javabean <--> XML conversion. That would already save a lot of boilerplate code and likely also the XSL step.
That said, duffymo's suggestion to load the XSL only once is a very good one. You don't need to re-execute exactly the same task which isn't dependent on request parameters at all again and again on every request, that's only inefficient.