How to access #SessionScoped beans from #WebFilter - cdi

I am working on an AuthenticationFilter to redirect the user when he's not logged in. I am using TomEE 7.0.0-M2, so with Java-EE7 support.
AuthenticationFilter
#WebFilter(urlPatterns = "/*", dispatcherTypes = {DispatcherType.FORWARD, DispatcherType.REQUEST})
public class AuthenticationFilter implements Filter {
#Inject
private LoginBean loginBean;
...
LoginBean
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import java.io.Serializable;
#Named
#SessionScoped
public class LoginBean implements Serializable {
The problem is that the injected LoginBean is not the instance from the login.xhtml. So i can not verify if the user is successfully logged in.
The LoginBean is not in the session attributes, but i found the right loginBean here, but i have no idea how i can access it. But it looks like that the bean is in CDI but how can i access it from the WebFilter?

I still don't have an answer but an another solution that BalusC mentioned here:
When the user is successfully logged i just add the loginBean manually to the sessionMap
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("loginBean", this);
In the WebFilter i access the loginBean with
session.getAttribute("loginBean")
Is this a good solution? I mean.. sounds like a workaround.

Related

How to set #ManagedProperty in CDI

recently I was migrating JSF managed beans to CDI managed beans, but now I need to set a property from one bean to another in CDI, I mean how to adapt the annotation #ManagedProperty(value="#{articleBean.cverev}") using CDI. A fragment of my code is:
#Named
#SessionScoped
public class UserBean implements Serializable{
#Inject #Named
private ArticleBean articleBean;
/*In this part*/
#ManagedProperty(value="#{articleBean.cverev}")
private long cverev;
How can I do it?

Cannot inject bean of non-serializable type into bean of passivating scope

I'm learning Java EE 7.
I'm trying to store the user session in a #SessionScoped Backing Bean but my IDE is telling me that I have an error because "Cannot inject bean of non-serializable type into bean of passivating scope".
The #SessionScoped bean:
import negocio.Autenticacion;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.Serializable;
#Named
#SessionScoped
public class UserSesion implements Serializable{
#Inject
private Autenticacion auth; // Error by IDE
}
#Stateless EJB code:
import modelo.Usuario;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.security.MessageDigest;
#Stateless
public class AutenticacionBean implements Autenticacion{
#PersistenceContext(unitName = "Banco-PU")
private EntityManager em;
...
Why can't I Inject the EJB in the backing bean?
IDE: Intellij IDEA 14.1.4
This is a false error. The IDE in question apparently isn't smart enough to detect that it's actually an EJB, not a "simple" CDI (or JSF) managed bean. EJBs are always implicitly serializable.
You've 4 options:
Ignore it. It'll run perfectly fine.
Bow for the false error and let EJB class implement Serializable anyway.
Use #javax.ejb.EJB instead of #javax.inject.Inject to inject it. It'll also inject the EJB, but the average IDE must be smart enough to not complain about serialization this way, because the IDE now knows for sure that it's actually an EJB, not a CDI managed bean.
Upgrade IDE to a newer version where this is fixed, if any. The ability to use #Inject instead of #EJB on EJBs is new since Java EE 7 (althouth the support is less complete; e.g. referencing self in #Asynchronous won't work when using #Inject). If still not fixed in latest IDE version, even though it claims to be Java EE 7 compatible, report a bug to them.

Re-create session scoped JSF managed bean programmatically

I'm using Mojarra 2.1.29 and have a session scoped JSF managed bean
#ManagedBean
#SessionScoped
public class UserContext{
//staff
}
and a spring bean:
public class UserReproducer{
private User user;
public void reporoduce(){
if(user == null){
//Here I need to recreate the userContext managed bean
//do some other staff
}
}
}
In fact, I need some kind of custom scope in JSF, i.e. to re-create the userContext bean from scratch when the condition is satisfied. Is it possible to do in some way? By recreating, I mean cleaning all its properties down as it was created for the first time.
Invalidate the session, to destroy a session scoped bean:
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
Another option to log out from Spring Security is to clear the context:
SecurityContextHolder.clearContext();

how is the #RequestScoped bean instance provided to #SessionScoped bean in runtime here?

I am reading through this example in JBoss where a #RequestScoped bean backing up JSF page is used to pass the user credential information which is then saved in a #sessionScoped bean.
Here is the example take from JBoss docs.
#Named #RequestScoped
public class Credentials {
private String username;
private String password;
#NotNull #Length(min=3, max=25)
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
#NotNull #Length(min=6, max=20)
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
}
JSF form:
<h:form>
<h:panelGrid columns="2" rendered="#{!login.loggedIn}">
<f:validateBean>
<h:outputLabel for="username">Username:</h:outputLabel>
<h:inputText id="username" value="#{credentials.username}"/>
<h:outputLabel for="password">Password:</h:outputLabel>
<h:inputSecret id="password" value="#{credentials.password}"/>
</f:validateBean>
</h:panelGrid>
<h:commandButton value="Login" action="#{login.login}" rendered="#{!login.loggedIn}"/>
<h:commandButton value="Logout" action="#{login.logout}" rendered="#{login.loggedIn}"/>
</h:form>
User Entity:
#Entity
public class User {
private #NotNull #Length(min=3, max=25) #Id String username;
private #NotNull #Length(min=6, max=20) String password;
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String setPassword(String password) { this.password = password; }
}
SessionScoped bean
#SessionScoped #Named
public class Login implements Serializable {
#Inject Credentials credentials;
#Inject #UserDatabase EntityManager userDatabase;
private User user;
public void login() {
List<User> results = userDatabase.createQuery(
"select u from User u where u.username = :username and u.password = :password")
.setParameter("username", credentials.getUsername())
.setParameter("password", credentials.getPassword())
.getResultList();
if (!results.isEmpty()) {
user = results.get(0);
}
else {
// perhaps add code here to report a failed login
}
}
public void logout() {
user = null;
}
public boolean isLoggedIn() {
return user != null;
}
#Produces #LoggedIn User getCurrentUser() {
return user;
}
}
My questions are
1) The #RequestScoped bean gets injected into #SessionScoped bean. What is the guarantee that the credential information set on one instance of RequestScoped is the same that is injected into #SessionScopedbean. why not a different #RequestScoped from pool gets injected or even a new instance?
2)why is the bean given #SessionScoped but not #Stateful. I guess #Stateful will work here.
3)how is the lifecycle of #sessionScoped bean managed? That is when does it gets destroyed ?. If I navigate to a different JSF page in which if I pull the information such as currentUser.userName, will I retrieve the same information I set on my first JSF page used to log in. (step 1 above)
4) If I don't specify #RequestScoped, then the Credentials bean get the #Dependent scope which is the defualt scope. It is mentioned in the docs that setting any instance variables of a #Dependent gets lost immediately. But I don't understand why? In fact, this prompts me the question of what use of #Dependent scope will be ?
Thanks
EDIT
Thanks kolossus for detailed and excellent answer. I need a little more clarifications on some of your points for better understanding
For a #requestScoped bean, there are is a pool of instances available which gets handed over to clients. Now if I have two clients accessing a JSF which is backed by a #RequestScoped bean, each client gets to work on one instance of #RequestScoped bean from the pool. In fact, both the clients do not actually work on the direct instance, but an indirect reference to the that single instance which is the proxy here. clients do all method calls or transactions using this proxy. so how long does the proxy holds this indirect reference? That is, in my example above, instance variables of #RequestScoped bean (Credentials) are set in JSF. but the true fact is that, this setting of instance variables happen to one instance of #RequestScoped bean indirectly through proxy. But when this instance is injected into SessionScoped bean, is it the proxy that gets injected? Since the lifecycle of SessionScoped is for a session established between client and application, does the proxy also live during this lifetime. Does that mean this single instance of #RequestScoped bean is bound to SessionScoped and the lifecycle of #RequestScoped bean instance or its proxy is determined by the lifecycle of SessionScoped bean?
The #RequestScoped bean gets injected into #SessionScoped bean. What is the guarantee that the credential information set on one instance of RequestScoped is the same that is injected into #SessionScopedbean. why not a different #RequestScoped from pool gets injected or even a new instance?
This is legal, thanks to the means by which CDI actually obtains references to a requested bean: client proxies. From the CDI spec
An injected reference, or reference obtained by programmatic lookup, is usually a contextual reference.A contextual reference to a bean with a normal scope[...], is not a direct reference to a contextual instance of the bean[...].Instead, the contextual reference is a client proxy object
A client proxy implements/extends some or all of the bean types of the bean and delegates all method calls to the current instance of the bean...
There are a number of reasons for this indirection:
The container must guarantee that when any valid injected reference to a bean of normal scope is invoked, the invocation is always processed by the current instance of the injected bean. In certain scenarios, for example if a request scoped bean is injected into a session scoped bean, or into a servlet, this rule requires an indirect reference
Also from this DZone CDI article:
CDI handles the injection of beans with mismatched scopes through the use of proxies. Because of this you can inject a request scoped bean into a session scoped bean and the reference will still be valid on each request because for each request, the proxy re-connects to a live instance of the request scoped bean
What this means is that, a proxy is substituted for the real thing at each injection point. The proxy mimics the type declared at the injection point by extending/implementing the ancestor tree of the type it's supposed to be mimicking. At the time you now actually require use of the object, the proxy performs a context-based lookup for an existing instance of the requested bean within the current conversation. This being a request-scoped object, you're guaranteed to have exactly one instance within the current conversation/context.
why is the bean given #SessionScoped but not #Stateful. I guess #Stateful will work here.
#Stateful would not work here, like I stated here, they are not cheap; unless you really need to, stick with vanilla HttpSession. Not to mention the fact that once the client of the SFSB releases the bean it's destroyed, i.e. the SFSB is not tied to the current session,#SessionScoped is.
how is the lifecycle of #sessionScoped bean managed? That is when does it gets destroyed ?. If I navigate to a different JSF page in which if I pull the information such as currentUser.userName, will I retrieve the same information I set on my first JSF page used to log in. (step 1 above)
Depends on which #SessionScoped you're referring to: javax.faces.bean.SessionScoped is tied directly to the current HttpSession/browser session, so it's terminated whenever that dies; JBoss however implies that javax.enterprise.context.* scoped beans don't actually go anywhere until the "context" dies
There's actually no way to remove a bean from a context until the entire context is destroyed
Think of #Dependent as you would any method-local variable: it's only useful as long as it's parent construct is around. That being said, it's best use is not for backing a JSF view. It's most useful application is overriding the scope that's specified on a bean, ad-hoc. Using your current example, I can have the following somewhere else in my application:
#Inject #New Login aDependentLoginBean; //implicit #Dependent scope applied
#Inject Login aSessionScopedLoginBean; //standard Login bean's scope applied
Together with #New, you could repurpose any other bean to be #Dependent
Related:
Is it possible to #Inject a #RequestScoped bean into a #Stateless EJB?

Accessing Application Scoped Bean Causes NullPointerException [duplicate]

This question already has answers here:
NullPointerException while trying to access #Inject bean in constructor
(2 answers)
Closed 7 years ago.
What is an Application Scoped Bean? I understand it to be a bean which will exist for the life of the application, but that doesn't appear to be the correct interpretation. I have an application which creates an application scoped bean on startup (eager=true) and then a session bean that tries to access the application scoped bean's objects (which are also application scoped). But when I try to access the application scoped bean from the session scoped bean, I get a null pointer exception. Here's excerpts from my code:
Application Scoped Bean:
#ManagedBean(eager=true)
#ApplicationScoped
public class Bean1 implements Serializable{
private static final long serialVersionUID = 12345L;
protected ArrayList<App> apps;
// construct apps so they are available for the session scoped bean
// do time consuming stuff...
// getters + setters
Session Scoped Bean:
#ManagedBean
#SessionScoped
public class Bean2 implements Serializable{
private static final long serialVersionUID = 123L;
#Inject
private Bean1 bean1;
private ArrayList<App> apps = bean1.getApps(); // null pointer exception
What appears to be happening is, Bean1 is created, does it's stuff, then is destroyed before Bean2 can access it. I was hoping using application scoped would keep Bean1 around until the container was shutdown, or the application was killed, but this doesn't appear to be the case.
Your first line is correct:
a bean which will exist for the life of the application.
However, you cannot access an injected resource in a constructor, as it may not be available yet. Your initialization line: private ArrayList<App> apps = bean1.getApps(); is run during object construction.
Instead, access the resource in a method marked by a #PostConstruct annotation:
#ManagedBean
#SessionScoped
public class Bean2 implements Serializable{
private static final long serialVersionUID = 123L;
#Inject
private Bean1 bean1;
private ArrayList<App> apps;
#PostConstruct
private void init() {
apps = bean1.getApps();
}
}

Resources