JSF polling a database from an application bean at timed intervals - java

Hey all, I'm pretty new to jsf so if this is a poor question then I apologize. I'm currently working on a school project where I need to access a database through a web service to get some basic application data. I have a class that accesses this data through a method and then returns the newest results from the database.
What I want to do is to either spawn a thread that calls the update method on the database. The run method looks similar to this, where i get my application bean and then I call the refresh method on it.
theFacesContext = FacesContext.getCurrentInstance();
ApplicationBean app = (ApplicationBean)theFacesContext.getELContext().getELResolver().getValue(theFacesContext.getELContext(), null, applicationbean);
app.getDBValues();
The thread would then loop based on a variable that would be set to false when the application bean was destroyed. My error is that the thread looses the facescontext. I've seen some posts where people say something allong the lines that you have to keep the thread in a request, but I'm not sure what that means. Any suggestions would be extremely helpful.

If you want to display actual data, you should use polling or server-side push. There are a lot of ajax components that may help. Look at
PrimeFaces poll component
RichFaces push
RichFaces poll
ICEfaces

It is indeed true that FacesContext is not available in a new thread. This is because it is stored in a ThreadLocal, and is initiated per request.
You can get your desired bean and pass it to the new thread, so that you no longer rely on the faces context there.

Related

Recommended approach when restoring a Spring State Machine instance

I am planning to use Spring State Machine to control an execution workflow. The system is expected to receive requests from multiple users and each user may be assigned to multiple workflows. My initial idea was to have one instance of SM per workflow and every time an user perform a step in the workflow, I would use its identifier to restore the machine from a persistent storage, input the new event and store the updated SM.
I've read around that initialising a SM is an expensive operation and some people recommend having a single instance of it, but "rehydrate" that instance with some data. My understanding is that this would be more effective, but I think it would become a "blocking" operation, in other words, one workflow would need to wait for the previous one to be finished/released before-hand. Since I'm newbie on this topic, can anyone shed some light on the best alternatives for my use case and perhaps pieces of code to illustrate the differences? (PS: I'm using v2.4.0)
I was first implementing the "rehydrate" mechanism because as you said, it made sense and was also used in the "persist" example of spring-statemachine.
Howewer, running performance tests against my API showed that using a single instance fails when using the StateMachine as an #Autowired Bean with the prototype scope as it is described in that example. What happens is that simultaneous requests against my API override that Statemachine Bean and the first request fails as the statemachine changes when writing back to the DB (i used redis).
So now I actually build a fresh statemachine everytime a request comes in and rehydrate that object:
public String getStatesGuest(HttpServletRequest httpServletRequest) throws Exception {
StateMachine<States, Events> stateMachine = stateMachineConfig.stateMachine();
resetStateMachineFromStore(httpServletRequest.getSession().getId(), stateMachine);
return convertToJson(buildGetStateResponse(stateMachine));
}
It still is very performant, I was testing with around 30 reqs/s and still got a median of 12ms. (Docker with 2 Cores for spring boot, 1 Core for redis).

Vaadin Push not working in 10 (flow)

In Vaadin 8, I am able to asynchronously update a Grid with incoming websocket data using the access method of UI, which locks the thread and performs the updates, then pushes them without the client having to request it.
access(() -> addMessage(message));
I am trying to use vaadin 10 now, and since the main class you start with doesn't extend UI, I am trying to do it like this:
UI.getCurrent().access((Command) () -> addTrade(message))
However it is not working, and you have to click somewhere on the page for the update to happen. I have the #Push annotation on the class, so I believe server push should work.. thank you so much guys!
in my servlet:
asyncSupported = true
have also tried this.getUI().get().access(), still not updating.
This is most likely caused by https://github.com/vaadin/flow/issues/3256 that is currently being fixed.
The tickets also suggests a workaround: grid.getElement().getNode().markAsDirty();. If the workaround solves the issue, then it's very likely caused by that bug. If not, then there's some other issue that would require further investigation.

Global Resource Object in Spring

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.

Lifetime and Initialization for Java REST service

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");
}

Servlet control multiple request

When i click a link im calling a servlet.
When i click that link multiple time the servlet throws an error (error details not important)
Though there are other work around for this fix (Like disable the link once clicked, etc)
I am curious is there any way to control this thru request/response Object.
the error is relevant, having multiple calls to a servlet acting different then one means you have thread safety issues probably due to the way you implemented the servlet
The details of the servlet's error are potentially interesting. The servlet APIs in general should not be throwing errors, my guess is that this is an application error of some kind.
The general principle I try to apply is:
1). We construct the UI to make it difficlut for the user to inadvertantly submit the same request twice (eg. debit my account £100, really don't want to send two such requests. This is where some nift javascript can help.
2). We construct the application to defend against inadvertant double requests, for example by including some kind of identifier on the requests that allow is to spot duplicates.
We do not assume that the UI is perfect, our business application layer has final responsibility for preventing double actions.
The error is really, really relevant.
You could have thread safety issues but you can also have a "race-condition", that is, the result of the process depends on the execution order, one of them could give you an error.
(race condition : http://en.wikipedia.org/wiki/Race_condition)
Set a flag in the servlet session scope when entering the servlet and reset it when leaving. If the flag is set when entering, then silently ignore.
You will need error handling in your servlet so a ServletException does not leave the flag set.

Categories

Resources