I'm looking to implement a very simple REST web service in Java. This is not my primary line of work, so everything is new to me.
I've been researching Java and JAX-RS implementations. They do not appear to be that difficult, but I haven't been able to understand the lifetime of the service and how it is created by the web server.
I'm afraid that my service may have to do some costly initialization, such as load a bunch of setup data from a file or resource in order to be able to process the requests. I do not know if I want it to have to do that each time it has to process a request.
So, my question is, what is the lifetime of my service? Can I load a bunch of parameters for my web service from a file before responding to requests? The parameters I need to load do not change and should be the same for all requests (therefore, it is stateless), but I'll need to be able to load that data from somewhere and I'm worried that it will forced to do it for each request. So, can my web service "live" or be cached such that it only needs to do that initialization once, or once per thread, but not once per request?
edit: I haven't decided yet which JAX-RS implementation to use or which server. I'm just interested in the fact that, it can be done, and if it matters which implementation I choose.
Just give an example using Jersey which is an implementatin of JAX-RS. The default life-cycle of root resource class is each request creates its own instance as specified here. So if you have some initial setup in the service and if they are the same for all requests, then you can put them in the static field of resource class and use static block to initialize them since static variables are created on per class basis. Something like this:
private static MyParam params;
static {
params = new MyParam("/path/to/file/setup.conf");
}
Related
I generally dislike the usage of singletons or static class, since I can refactor them to something different most of the time.
However, I am currently designing my access point to a HTTP API on an Android app, and I was thinking that I have the following environment:
I need to send HTTP requests in the majority of my code modules (Activities).
The code for sending a request does not depend on the request being sent
There will always only be one specific user on the app per session (unlike the server-side that has to handle different users etc)
Therefore, I was thinking that this could be a situation where it is justifiable to use a Singleton, or even a static class, to place HTTP requests - In the rest of my code, I would then simply have to use something like:
MyHttpAccess.attemptLogin(name, pass, callback)
in order to complete the request. I'm even leaning towards using a static class, as I do not have any variable data that I can think of needing to store.
Does this seem like good or bad design, and what should I potentially change?
Http Request in kotlin using single class
https://medium.com/#umesh8346/android-kotlin-api-integration-different-method-b5b84eb4f386
I'm just getting into Spring (and Java), and despite quite a bit of research, I can't seem to even express the terminology for what I'm trying to do. I'll just explain the task, and hopefully someone can point me to the right Spring terms.
I'm writing a Spring-WS application that will act as middleware between two APIs. It receives a SOAP request, does some business logic, calls out to an external XML API, and returns a SOAP response. The external API is weird, though. I have to perform "service discovery" (make some API calls to determine the valid endpoints -- a parameter in the XML request) under a variety of situations (more than X hours since last request, more than Y requests since last discovery, etc.).
My thought was that I could have a class/bean/whatever (not sure of best terminology) that could handle all this service discovery stuff in the background. Then, the request handlers can query this "thing" to get a valid endpoint without needing to perform their own discovery and slow down request processing. (Service discovery only needs to be re-performed rarely, so it would be impactful to do it for every request.)
I thought I had found the answer with singleton beans, but every resource says those shouldn't have state and concurrency will be a problem -- both of which kill the idea.
How can I create an instance of "something" that can:
1) Wake up at a defined interval and run a method (i.e. to check if Service discovery needs to be performed after X hours and if so do it).
2) Provide something like a getter method that can return some strings.
3) Provide a way in #2 to execute a method in the background without delaying return (basically detect that an instance property exceeds a value and execute -- or I suppose, issue a request to execute -- an instance method).
I have experience with multi-threaded programming, and I have no problem using threads and mutexes. I'm just not sure that's the proper way to go in Spring.
Singletons ideally shouldn't have state because of multithreading issues. However, it sounds like what you're describing is essentially a periodic query that returns an object describing the results of the discovery mechanism, and you're implementing a cache. Here's what I'd suggest:
Create an immutable (value) object MyEndpointDiscoveryResults to hold the discovery results (e.g., endpoint address(es) or whatever other information is relevant to the SOAP consumers).
Create a singleton Spring bean MyEndpointDiscoveryService.
On the discovery service, save an AtomicReference<MyEndpointDiscoveryResults> (or even just a plain volatile variable). This will ensure that all threads see updated results, while limiting them to a single, atomically updated field containing an immutable object limits the scope of the concurrency interactions.
Use #Scheduled or another mechanism to run the appropriate discovery protocol. When there's an update, construct the entire result object, then save it into the updated field.
Is there a way to get a list of all SOAP headers in a web method with plain JAX-WS? I know this can be done by using Metro specific classes (HeaderList hl = messageContext.get(JAXWSProperties.INBOUND_HEADER_LIST_PROPERTY)). However I'm not sure if I can rely on having that implementation at runtime so I'd like to stick to JAX-WS.
I also know about the header attribute of the #WebParam annotation. I'd prefer not having to specify the header parameter there. The reason is that my web service has some IDs that are common to all web methods and this would pollute the interface. Also in case another ID comes along or one gets removed again (the spec is not final yet) I'd have to modify every single web method. Also there would be no reason anymore for using a header - it could be a normal method parameter.
The third way I know of is using a handler via #HandlerChain but then I have no way of connecting the headers with the executed web method. The IDs I mentioned are important for further processing - they are not just access control that can work independently of the method.
If you implement a request handler, you can store the headers in a thread local, static variable and implement some kind of access mechanism to it for your service method implementation.
I have two servlets A & B.
On B i intend to have a a method isAvailable() which A will call to check the status. If this method returns true then im going to pass it an object to B.
On doing a bit of reading i'm seeing a couple of options non of which im that familar with. JNDI with remote EJB , RMI or simple HTTP (not sure how youd do the last)
What do you guys think ? Any other options ?
Why not make use of the fact that your infrastructure is already talking HTTP ?
So servlet A can perform an HTTP GET on a particular path to check a status (either sending back an object or checking an HTTP response code - this latter method seems a misuse of status codes, however), and PUT/POST an object if required. I note that you're running across multiple hosts, and this will work in your scenario.
The objects can be serialised using standard Java, or via a representation such as XML - perhaps serialised using XStream).
That would seem to me a pretty straightforward way to leverage off the infrastructure you have.
Are your servlets running in the same application server? If so, you might like to use Spring to inject B into A so that the method can be called directly.
Even if the servlets are running in different containers, you can expose them (using Spring again) as Remote objects and similarly inject B into A (except that this will mean that the Spring container will inject a proxy for the remote object). This has zero footprint in your code (i.e. it's all defined by config files and Spring takes care of everything for you)
It looks like this isAvailable() method in Servlet B accesses some kind of "global" data which is stored in the Servlet. Could you extract this object to a separate Singleton which then is available for both Servlets?
There is one instance of Servlet A on a master host and many of Servlet B each on its own host with its own tomcat instances.
You can use java.net.URLConnection to programmatically fire a HTTP request. You can find here a simple tutorial.
Let A fire a HTTP request to B and have in B a servlet which listens on those requests and returns the response accordingly. This can be a simple response.getWriter().write("ok"); or so. You can even return a XML string and so on. In A you can then read this value from the InputStream of the URLConnection.
I have a servlet, and that servlet uses a .net web service to perform some function. To do this, I created the webservice client in Netbeans using the "jax-rpc" style client.
Let's say that my service name is "Tester". Then two of the generated classes are called "Tester", and "TesterSoap".
To get a reference to the web service, I need to do this:
Tester t = new Tester_Impl();
TesterSoap tsoap = t.getTesterSoap();
To use the webservice, I can then do this:
tsoap.runTest();
My question is, since this is a servlet which gets executed many times, should I store the first two lines in static variables (so they only ever get executed once), or store them locally so that they execute everytime the servlet is executed?
Another way of asking the same question: is there a performance hit everytime the first two lines are called? (I'm testing everything locally so it's hard to measure).
Thanks...
If the default constructor and any of the initialization blocks of the Tester_Impl() class and the method getTesterSoap() doesn't do anything expensive (e.g. reading file from disk, loading data from DB, connecting a socket, etc, I however suppose it doesn't) then you don't need to worry about it.
You can consider declaring them as an instance variable of the class extending from HttpServlet. But, a big but, it is going to be shared among all HTTP requests, because there will be only one instance of the particular servlet class during whole application's lifetime. So if the Tester_Impl class is supposed to have a state, then it is a very bad idea to declare it as an instance variable. It would then be shared among all requests. With other words, it's not threadsafe. If you want to ensure threadsafety in servlets, then declare everything in the very same method block.
I would not optimize prematurely here. Test this out in as close to a production environment as you can (i. e. not on your local box) and see what the performance hit is. What I've done in the past is write a small shell script that hits my server with wget n times with a delay of k milliseconds and then measured the latency, possibly instrumenting the code with some timing or profiling myself (or with jvisualvm or some other profiling tool).
If you want to protect your design from a possible performance hit without doing the testing, you could use a factory to provide instances of the service client and then you could swap out singleton service clients for many of them whenever you feel like it.