Question about multi-threading and EntityManager - jsf-2

I have been developing my web-app using JPA 2.0 implementation EclipseLink 2.2.0. I finally got around to running multi-threaded code and I got this exception:
java.lang.IllegalStateException: Attempting to execute an operation on a closed EntityManager.
The objects that have all the javax.persistence calls in my application are defined as application scoped, like this:
#Model
#ApplicationScoped
public class LocationControl implements Serializable {
#PersistenceContext private EntityManager em;
#Resource private UserTransaction utx;
// etc
And of course all the managed beans (usually RequestScoped or ConversationScoped) that want to access the data base do so like this:
#Inject private LocationControl lc;
So my question is this: Did I get that Exception through the use of #ApplicationScoped DAO? I had thought that it would be more efficient that way, since the container would not have to be continually re-creating this object on every request if it did not have a scope, and the DAO has no state of its own. However if the EntityManager and UserTransaction object have to be separate instances for each user, then that would be a problem.
Alternatively, I could use syncrhonized on the DAO methods, but I think that would cause thread lockups in the container (GlassFish).
Any advice appreciated.

#Model annotation was originally created to annotate request scoped beans, here is how it's defined:
#Named
#RequestScoped
#Stereotype
#Target({TYPE, METHOD, FIELD})
#Retention(RUNTIME)
public #interface Model {}
You can of course override '#RequestScoped' with another annotation but '#ApplicationScoped' it's not a good choice as everyone in the application would modify the state of the same injected EntityManager. I think it would be best to leave it #RequestScoped in most cases, sometimes, for example for a login/logout data bean '#SessionScoped' could be an option but I cannot see a scenario for '#ApplicationScoped' dao.
If you don't want to use #Model at all and you use full Java EE container, then the stateless EJB ,as BalusC said, would be a great option for Dao too.

Related

JSF 2 ManagedProperty is null

I know there are loads of questions on SO regarding this exact issue, but I couldn't find a solution to my problem. I'm trying to use a #ManagedProperty in JSF 2. I used the example from this page, but mine's not working:
#ManagedProperty("#{userSession}")
private UserSession userSession;
public void setUserSession(UserSession userSession) {
this.userSession = userSession;
}
Both the parent bean and the bean injected are session scoped. Both beans have the #ManagedBean attribute. No faces-config.xml declarations, no EJBs, no use of Spring. One thing I noticed from that example is that both the bean classes implement Serializable. Mine do not, and I'm not sure if that is making the difference.
When I use this code, I get a NullPointerException when I try to operate on userSession. However, I know a session exists, because when I use #BalusC's findBean convenience method, it works. One thing with this though, is that my code only works if I call userSession = findBean("userSession") inside the same method where I'm "doing stuff". If I initialize userSession in the bean's constructor, I get another NPE. Any ideas?

Accessing IAuthSession in non-controller classes in ServiceStack/MVC4

I am new to ServiceStack, so this is probably a noob question:
I am working on an ASP.NET MVC4 application that uses ServiceStack and am trying to figure out how I could get a hold of the current IAuthSession from within a class (either a EF context or a PetaPoco Database) used by my MVC4 controllers derived from ServiceStackController.
The class in question is registered with Funq with the ReuseScope.Request scope (i.e. on the per-HTTP request basis), and ideally I'd like every instance of it to be autowired with the current IAuthSession using either a constructor parameter or a public property.
How do I do that?
UPDATE
After some digging I came up with what I think might work.
In my AppHost.Configure I register a lambda that returns a session from the current request:
container.Register<IAuthSession>(c =>
HttpContext.Current.Request.ToRequest().GetSession());
Also:
container.RegisterAutoWired<EFCatalogDb>();
where EFCatalogDb is my EF context that takes IAuthSession as a constructor argument:
public class EFCatalogDb : DbContext
{
public EFCatalogDb(IAuthSession session) : base()
{ }
// ...etc....
}
Unfortunately I am not at the point in my development when I can test this workaround, so have to ask others if it makes sense at all.
My first suggestion would be to try to keep IAuthSession out of your database classes since that creates a dependency on ServiceStack that seems unnecessary.
That being said, I think you could go the route of registering IAuthSession and having the container automatically inject IAuthSession. A better way might be creating your own 'wrapper class' around IAuthSession and injecting that into your database classes. That would then break the dependency on ServiceStack.
If you have no issue keeping a dependency on ServiceStack another possibility would be using the SessionFeature class and doing something like
var key = SessionFeature.GetSessionKey();
authSession = AppHost.Resolve<ICacheClient>().Get<IAuthSession>(key);

JSF Serialization/Deserialization

We use JSF within our presentation layer. Most classes looks like this:
#Named
#SessionScoped
public class MyHandler implements Serializable {
#Inject
private MyHelper helper;
#EJB
private transient MyFacade myFacade;
...
}
In general an JSF handler has one transient reference to an facade. The facade connects the presentation layer with our service layer. Helper classes will almost be injected through cdi.
JSF serializes the state of an handler but what happens on deserialization? Are the references automagically be restored? How could I check this or tell JSF to serialize/deserialize an managed jsf bean(testing)?
As per spec all (relevant) CDI-managed dependencies are proxied and the proxies are required to be passivable, so there is no problem with de-/serialization :)
[...] Finally, client proxies may be passivated [...]

JSF 2.0 pass data between beans (or pages?)

I'm working with JSF 2.0
I have a form in my admin section where I am going to select some users in a list.
The form (selectusers.xhtml) is adding these users to a list in a bean (SelectUsers.java).
After I have selected some user(s), I will pass the list of the user(s) from SelectUsers.java to another bean (AddAddressBean.java) and continue add information in another form (addadress.xhtml) which set other properties related to AddAddressBean for each user.
I do not know how to implement it. I would like that AddAddressBean.java shall be independent (so I can use it together with other beans), so I prefer that AddAddressBean.java shall not know about other beans.
Can you please help me? =)
B.R Carl
Several quick things come to mind :
Perhaps you could have a single bean only for those related pages, using #SessionScoped or the shorter CDI's #ConversationScope, or and this is the best of the three, the DeltaSpike #ViewAccessScoped
When clicking the button on page 1 where it'll take you to page 2, in the 1st bean, you can make use of Flash object to store objects you want to pass, and in the second bean's #PostConstruct method, you could get all the objects from the Flash object
If you dont mind using session scope, you can still have 2 beans, and one bean can refer to another bean using the jsf way(#ManagedProperty), or the Java EE inject way(#Inject) or the spring way if you use spring (#Autowired)
This how i implemented (used ConversationScoped as #bertie said ).
bean 1:
#Named("conversationBean1")
#ConversationScoped
public class ConversationBean1 implements Serializable {
//---start conversation----
}
bean 2:
#Named("conversationBean2")
#ConversationScoped
public class ConversationBean2 implements Serializable
{
#Inject
private ConversationBean1 conversationBean1;
}

Injecting entity manager into managed bean

It is possible to inject entity manager (or its factory) into jsf managed bean using #PersistenceContext (or #PersistenceUnit)?
I Tried it but nothing, I obtain a NullPointerException.
Yes it is possible. This is the syntax.
#PersistenceContext
EntityManager em;
You need to have a persistence.xml in your project. Btw: I'm running Glassfish 3.
After this you can then use methods like em.createNamedQuery.
Also remember the injection takes place after the constructor so if your trying to do database functions in the constructor this will not work. You will have to add the #PostConstruct annotation to a method. This is probably the problem your having.

Resources