Stateful Bean using #PreDestroy to close database connection - ejb-3.1

I have a Stateful bean that is used to make a couple database queries. I open the connection in the first method I call, but I only really want to close the connection after the EJB Client is really done with the Stateful bean. I thought that I could put the logic that closes the database connection in the #PreDestroy method.
This seems to be working, but I'm curious as to the implications. When, specifically, does the EJB session complete? This is container managed transactions, so I would assume that when the EJB client method completes, so does the EJB transaction. When, specifically, does the PreDestroy method get called? Is the transaction still around? Or did it already commit and put itself back into the pool? Thanks!

Below are the excerpt from specification, which might clarify the statefull session bean lifecycle.
At the end of the lifecycle, the client invokes a method annotated
#Remove, and the EJB container calls the method annotated #PreDestroy,
if any. The bean’s instance is then ready for garbage collection.
it would be wrong to perform database operations within a session
bean’s PostConstruct or PreDestroy lifecycle callback interceptor
methods and to assume that the operations are part of the client’s
transaction. The PostConstruct and PreDestroy methods are not
controlled by a transaction attribute because handling rollbacks in
these methods would greatly complicate the session instance’s state
diagram.
PreDestroy methods are invoked in an unspecified transaction and security context.
The PrePassivate callback notification signals the intent of the container to passivate the instance. The PostActivate notification signals the instance it has just been reactivated. Because containers automatically maintain the conversational state of a stateful session bean instance when it is passivated, these notifications are not needed for most session beans. Their purpose is to allow stateful session beans to maintain those open resources that need to be closed prior to an instance’s passivation and then reopened during an instance’s activation.

Related

Reactjs background processing

Couple of questions:
I have list of components on the client app which has some near real time info e.g. status, which I want to display.
I have server app, which can pull the status info from a third party REST endpoint.
My question is, should I cycle through all the components in the client app and request the server app for the status?
Or should I have a server worker thread, which pulls the status info and publishes on the websocket, which the client can then update the state of the component.
Or is there background thread which I can run on the client app, which will update the status and the state. How will this conflict with the dispatch/queuing of events from user interactions.
I think I might be asking some of the architectural questions and the answers might be "it depends" ambiguous, but anyone who has done this before and any guidance is appreciated.
Thanks, Rajesh
It depends :) But it's safe to go with server-side approach since with client-side you would have to deal with CORS and cross-domain ajax calls in general. Most of the 3rd party API do not allow to make arbitrary AJAX calls from other domains. Those that do allow that usually have API quota which is again easier to manage since you can keep your keys secret on the server and throttle and cache requests.
Server side approach requires more effort though. So it's a prototype and 3rd party API allows cross-domain requests – go for it, it's easier, for production app, consider doing this on the server.
For client-side approach if 3rd party API doesn't offer subscriptions, yes you would have to poll, but you don't have to cycle through components. You can abstract this polling in one, root component and then just pass props down.
You are right, the answer is "it depends".
Basically, you have two options:
Poll the server for the current status.
I believe you do not have to cycle through all the components and query their status. You could just have an API that provides the server the timestamp when you last queried the status, and the server will respond with just the information that has changed since the last query.
This is simple and will work fine if the updates are not huge, and you can afford to be a little late.
You could have a dedicated websocket connection with the server
In this case, the server will push any new updates to your front-end whenever any new update is available. This is a little cumbersome to implement, but is the right approach if the updates are near real-time.
To answer your question about having a background-thread on the front-end: no, you cannot have background-threads on the front-end. Javascript doesn't work that way. What you do have are callbacks. Whenever the server pushes you any new information, a callback, that you define, will be called and you can do whatever UI changes you need from here.
My question is, should I cycle through all the components in the client app and request the server app for the status?
No, this sounds very inefficient to me.
However, if you decide to poll from the client, it should be done only from a single component that is parent to all children that need the information. The parent then passes its state to the children and they update on each poll.
Or should I have a server worker thread, which pulls the status info and publishes on the websocket, which the client can then update the state of the component.
Absolutely. Let this socket be in your top-level application component which holds the real-time info in its state and passes down to its children. Whenever information gets published to the socket, update the top-level application state with the new real-time info and all children will rerender displaying the most current information.

How to tie signalR to IoC

I am writing web app in angular, using Nancy as my backend. I have setup signalR websockets as my primary communication mechanism. It works great, with one exception. I can't figure out how to attach state to my socket connection and make it easily available to my code. To be more specific, I can create and maintain state, I am finding it difficult to make that state available to everything on the back end that needs it, without passing a state data object around through every call.
I was hoping to tie to Nancy's IoC, but that is based off of the session, not off of a websocket. I looked at other IoC systems, but I cannot grok how to tie them to the socket.
Does anyone have any insight on how to maintain state non-obtrusively with signalR?
EDIT: This may explain it. When the user connects via signalR, I want to create an IGame instance with a life cycle that is tied to the signalR session and inject it throughout my code as needed. for that particular user.
Is that any clearer?

Stop Grails from opening a connection to the database in a Controller method

I have a service that is communicating to another machine. Since it's a simple Controller method Grails automatically grabs a DB connection from the pool while my controller is communicating with the other server. I'd like to prevent it from doing that, and manually open up the database connection when I'm ready so that it doesn't suck up a connection during a long period like doing network calls. How do I prevent Grails from automatically grabbing a connection from the pool in a controller method?
When you create a controller it has the Transactional annotation on it, something like:
#Transactional(readOnly=true)
class FooController { ..
If you remove that annotation (and any method level annotations) then Grails will no longer connect to the database to start the transaction.
Open Session In View should not come into play since we use a lazy init approach for obtaining the connection with OSIV
Note my answer above assumes you are using a recent version of Grails (2.3.x or above)
Updated
For MongoDB you can disable automatically connection for all controllers by defining the following bean (which overrides the default) in grails-app/conf/spring/resources.groovy:
mongoPersistenceInterceptor(org.codehaus.groovy.grails.support.NullPersistentCon‌​textInterceptor)
However there is no way to disable on a per controller basis at the moment

Hibernate Ehcache Operations and Event Handlers

I currently have my application integrated with Hibernate. It saves/retrieves data from the database successfully. Next, I would like to configure ehcache such that my application does not have to hit the database every time.
That being said, I was wondering if there are any ehcache event handlers that would allow me to run some custom piece of code before (or after) a cache operation (i.e. put, remove, get, etc.)?
Also, when my application is about to save a DAO, my understanding is hibernate will push that to the database. What I would like to know whether the db operation will be performed before, during or after the event handler (above) is triggered?
Perhaps you could create a CacheEventListener which would allow you to receive notifications of put/update/remove events - and then you could perform some action accordingly. The notification occurs after the event has happened.
You configure a listener in the ehcache.xml file on a per-cache basis:
<cache ...>
<cacheEventListenerFactory class="your.listener.FactoryClass" />
...
</cache>
Where the cacheEventListenerFactory is a class that you create which in turn creates your listener. See the EHCache docs for more detailed info.
For integration of EHCache with Hibernate, you should look at the EhCacheRegionFactory. Again see the docs for step by step instructions of how this is set up.

EF4 + STE: Reattaching via a WCF Service? Using a new objectcontext each and every time?

I am planning to use WCF (not ria) in conjunction with Entity Framework 4 and STE (Self tracking entitites). If I understand this correctly my WCF should return an entity or collection of entities (using LIST for example and not IQueryable) to the client (in my case Silverlight).
The client then can change the entity or update it. At this point I believe it is self tracking? This is where I sort of get a bit confused as there are a lot of reported problems with STEs not tracking.
Anyway, then to update I just need to send back the entity to my WCF service on another method to do the update. I should be creating a new OBJECTCONTEXT every time? In every method?
If I am creating a new objectcontext every time in every method on my WCF then don't I need to re-attach the STE to the objectcontext?
So basically this alone wouldn't work??
using(var ctx = new MyContext())
{
ctx.Orders.ApplyChanges(order);
ctx.SaveChanges();
}
Or should I be creating the object context once in the constructor of the WCF service so that 1 call and every additional call using the same WCF instance uses the same objectcontext?
I could create and destroy the WCF service in each method call from the client - hence creating in effect a new objectcontext each time.
I understand that it isn't a good idea to keep the objectcontext alive for very long.
You are asking several questions so I will try to answer them separately:
Returning IQueryable:
You can't return IQueryalbe. IQueryable describes query which should be executed. When you try to return IQueryable from service it is being executed during serialization of service response. It usually causes exception because ObjectContext is already closed.
Tracking on client:
Yes STEs can track changes on a client if client uses STEs! Assembly with STEs should be shared between service and client.
Sharing ObjectContext:
Never share ObjectContext in server environment which updates data. Always create new ObjectContext instance for every call. I described reasons here.
Attaching STE
You don't need to attach STE. ApplyChanges will do everything for you. Also if you want to returen order back from your service operation you should call AcceptChanges on it.
Creating object context in service constructor:
Be aware that WCF has its own rules how to work with service instances. These rules are based on InstanceContextMode and used binding (and you can implement your own rules by implement IInstanceProvider). For example if you use BasicHttpBinding, default instancing will be PerCall which means that WCF will create new service instance for each request. But if you use NetTcpBinding instead, default instancing will be PerSession and WCF will reuse single service instance for all request comming from single client (single client proxy instance).
Reusing service proxy on a client:
This also depends on used binding and service instancing. When session oriented binding is used client proxy is related to single service instance. Calling methods on that proxy will always execute operations on the same service instance so service instance can be stateful (can contains data shared among calls). This is not generally good idea but it is possible. When using session oriented connection you have to deal with several problems which can arise (it is more complex). BasicHttpBinding does not allow sessions so even with single client proxy, each call is processed by new service instance.
You can attach an entity to a new object context, see http://msdn.microsoft.com/en-us/library/bb896271.aspx.
But, it will then have the state unchanged.
The way I would do it is:
to requery the database for the information
compare it with the object being sent in
Update the entity from the database with the changes
Then do a normal save changes
Edit
The above was for POCO, as pointed out in the comment
For STE, you create a new context each time but use "ApplyChanges", see: http://msdn.microsoft.com/en-us/library/ee789839.aspx

Resources