Why does my FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal() code runs to NullPointer? - jsf

I have a stateless bean which has a method, where I want to get the current/logged user.
My code to get it:
Principal p1 = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
But I am getting nullpointer exception on this. Why is that?
Or is there any other way to get the logged user?
I am using weblogic.

You're not supposed to grab the FacesContext in an EJB. Even more, your EJBs should be completely free from any JSF dependencies. In other words, you should not have any code imported from javax.faces.* package inside your EJBs. Your EJBs should be designed that way that they are reusable across all different front-ends you can think of such as JSF, JAX-RS, Struts, Spring-MVC and even "plain vanilla" Servlets.
If you're using container managed security or a security framework like Apache Shiro, then you're supposed to use the API-provided facilities for that. In case of "plain vanilla" container managed security (JAAS via web.xml and so on), you're supposed to obtain it form SessionContext (which is rightfully from javax.ejb package) which can be injected as #Resource.
#Resource
private SessionContext context;
public void doSomething() {
Principal principal = context.getCallerPrincipal();
// ...
}
An alternative would be to pass the JPA entity representation of the logged-in user as method argument.

verify the import of the following library:
javax.faces.bean.SessionScoped;
Try again

Related

How to call EJB in PhaseListener

I use JSF 2 and EJB 3.1, all of them are deployed on Glassfish 3.1.
When i setup a class named MyInterceptor which is implemented PhaseListener, i can not revoke remote EJB interface inside it.
It notice "NullPointerException ..."
public class MyInterceptor implements PhaseListener {
#EJB(name="AuthorizationEJB",
beanInterface=AuthorizationService.class,
mappedName="corbaname:iiop:localhost:3700#ejb/AuthorizationEJB")
public AuthorizationService authorizationService;
....
}
When I call authorizationService.dosomestuff(), it raise error NullPointerException
How can i do to fix it?
Thank in advance
In JSF 2.1 and earlier, PhaseListeners are unfortunately no injection targets (meaning you can't use injection in them). You can do your lookup programmatically via JNDI instead though.
In JSF 2.2 all JSF artifacts (including PhaseListeners) will be injection targets, but this will probably not help you now.
Unrelated to your question, but I'm not sure what you're trying to achieve by specifying the beanInterface in your annotation. Most likely you'll also don't need the name attribute and if your bean is a local bean you'll also don't need mappedName.
Use a servlet filter instead of a JSF phase listener to do authorization. You can inject an #EJB in a #WebFilter.
Yeah in web filter you could have just used plain #EJB. Maximimum you needed to add beanName if you had two beans implement same AuthorizationService interface.
Servlet filter is per request, I don't think you need to do security stuff at a certain phase from JSF's lifecycle (which is a more granular level than the whole http request).
For normal lookup you can do:
AuthorizationService.class.cast(new InitialContext().lookup("corbaname:iiop:localhost:3700#ejb/AuthorizationEJB")).dosomestuff();
in a try catch javax.naming.NamingException

does this JSF pattern break dependency injection?

I have a JSF2 project (Mojarra on GlassFish 3.1).
I have a ViewScoped bean that references services through a utility class like so:
#ManagedBean
#ApplicationScoped
public static class ServicesUtil {
#EJB
UserService userService;
#EJB
EmailService emailService;
/** getters/setters **/
}
and
#ManagedBean
#ViewScoped
public class UserHandler {
public String method() {
ServicesUtil.getUserService().doUserStuff();
return "newPage";
}
}
My question is, since the ServicesUtil is ApplicationScoped, does that mean there is only one instance of each service for the entire application? And is this bad practice? If done correctly, would the CDI in GlassFish actually create new instances as they are needed?
Similarly, if the Services were injected into the UserHandler instead would the application be more scalable?
The reason we added the ServicesUtil layer is one of my coworkers said that he occasionally had problems getting the injection to work in the Handler when it is ViewScope. Should there be any difficulty using #EJB in a ViewScoped bean?
Any help is greatly appreciated!
Rob
The pattern you're using doesn't seem to make a lot of sense. There should be no problem with injecting EJBs into a view scoped bean.
Depending on the type of EJB you are using (stateless, stateful or singleton) different things hold.
If the userService and emailService are stateless (they most likely should be), you gain nothing by using a bean that's injected into an application scoped bean first. Namely, what's injected is not the bean itself but a proxy and every request to that is routed to a different real bean instance anyway (see http://en.wikipedia.org/wiki/Enterprise_JavaBean#Stateless_Session_Beans).
If the userService and emailService are stateful, you do get a single instance here, but I highly doubt you need to share actual between every user in your application. But even if you would want that, only a single user (thread) can access the stateful bean at a time.
If those services are singleton, you can just inject them right away into the view scoped bean. There is absolutely no reason to go via an application scoped bean.
Furthermore, ServicesUtil.getUserService() is a static method, so using this to get an injected service is brittle. If you want to use this (you shouldn't, but suppose) ServicesUtil should be injected into UserHandler.
Then, it seems you are confusing CDI and JSF managed beans. I agree this is confusing, but it's currently the way it is. #ViewScoped does not work in combination met CDI beans. From your code it's not clear if #ManagedBean is the JSF variant or the Java EE/CDI one. In this case it should be javax.faces.bean.ManagedBean if you want to use the view scope.

Inject EJBs into a Seam Component

guys. I have a Seam project running on Tomcat 6.0.20 (webapp.war) and an EJB project running on JBoss 4.2.3 (ejbapp.ear).
I can access my EJBs in my Seam components using JNDI lookup [initialContext.lookup(...)].
I'd like to have them injected in my Seam components instead.
My Seam components ARE NOT EJBs, so I can't use #EJB annotation. I'd like to have something like this in my Tomcat (Web) app.
#Name("customerAction")
public class CustomerAction {
#In // even with (autoCreate=true) or the EJB name if necessary
private CustomerEJB customerEJB;
...
}
And this in the JBoss (EJB) app.
#Stateless(name="customerEJB")
public class CustomerEJBImpl implements CustomerEJB {
...
}
#Remote
public interface CustomerEJB {
...
}
In my components.xml I have the jndiPattern=ejbapp/#jndiPattern/remote specified just like I currently use to lookup the EJBs (ex: ejbapp/CustomerEJB/remote).
I'm probably missing something in my configuration to make this work.
PS: I'd like NOT HAVE to annotate my EJBs as #Name (Seam) components.
Any suggestions? Thanks in advance.
Thanks for your reply, but it didn't work.
When I declared the EJBs in components.xml, it did inject the object in my Action (Seam component), but as a POJO. I mean, the EntityManager and other EJB injections I had in the injected object didn't work.
I also tried to define the EJB as a Seam component, but, once they are in the webproject inside a JAR file, it didn't load automatically, and trying the scenario above, I got the same error.
Just an FYI, I also declared the Seam interceptor in ejb-jar.xml file.
I have no idea why this is happening, BTW I thought it would be quite a simple thing for Seam to handle.
Anyway..., any other suggestions, guys?
Define your EJB as Seam components in your components.xml

How do I force an application-scoped bean to instantiate at application startup?

I can't seem to find a way to force an application-scoped managed bean to be instantiated/initialized when the web app is started. It seems that application-scoped beans get lazy-instantiated the first time the bean is accessed, not when the web app is started up. For my web app this happens when the first user opens a page in the web app for the first time.
The reason I want to avoid this is because a number of time-consuming database operations happen during the initialization of my application-scoped bean. It has to retrieve a bunch of data from persistent storage and then cache some of it that will be frequently displayed to the user in the form of ListItem elements, etc. I don't want all that to happen when the first user connects and thus cause a long delay.
My first thought was to use an old style ServletContextListener contextInitialized() method and from there use an ELResolver to manually request the instance of my managed bean (thus forcing the initialization to happen). Unfortunately, I can't use an ELResolver to trigger the initialization at this stage because the ELResolver needs a FacesContext and the FacesContext only exists during the lifespan of a request.
Does anyone know of an alternate way to accomplish this?
I am using MyFaces 1.2 as the JSF implementation and cannot upgrade to 2.x at this time.
My first thought was to use an old style ServletContextListener contextInitialized() method and from there use an ELResolver to manually request the instance of my managed bean (thus forcing the initialization to happen). Unfortunately, I can't use an ELResolver to trigger the initialization at this stage because the ELResolver needs a FacesContext and the FacesContext only exists during the lifespan of a request.
It doesn't need to be that complicated. Just instantiate the bean and put it in the application scope with the same managed bean name as key. JSF will just reuse the bean when already present in the scope. With JSF on top of Servlet API, the ServletContext represents the application scope (as HttpSession represents the session scope and HttpServletRequest represents the request scope, each with setAttribute() and getAttribute() methods).
This should do,
public void contextInitialized(ServletContextEvent event) {
event.getServletContext().setAttribute("bean", new Bean());
}
where "bean" should be the same as the <managed-bean-name> of the application scoped bean in faces-config.xml.
Just for the record, on JSF 2.x all you need to do is to add eager=true to #ManagedBean on an #ApplicationScoped bean.
#ManagedBean(eager=true)
#ApplicationScoped
public class Bean {
// ...
}
It will then be auto-instantiated at application startup.
Or, when you're managing backing beans by CDI #Named, then grab OmniFaces #Eager:
#Named
#Eager
#ApplicationScoped
public class Bean {
// ...
}
Romain Manni-Bucau posted a neat solution to this that uses CDI 1.1 on his blog.
The trick is to let the bean observe the initialization of the built-in lifecycle scopes, i.e. ApplicationScoped in this case. This can also be used for shutdown cleanup. So an example looks like this:
#ApplicationScoped
public class ApplicationScopedStartupInitializedBean {
public void init( #Observes #Initialized( ApplicationScoped.class ) Object init ) {
// perform some initialization logic
}
public void destroy( #Observes #Destroyed( ApplicationScoped.class ) Object init ) {
// perform some shutdown logic
}
}
As far as I know, you can't force a managed bean to be instantiated at application startup.
Maybe you could use a ServletContextListener which, instead of instantiating your managed bean, will perform all the database operations itself?
Another solution might be to instantiate your bean manually at application startup, and then set the bean as an attribute of your ServletContext.
Here is a code sample:
public class MyServletListener extends ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
ServletContext ctx = sce.getServletContext();
MyManagedBean myBean = new MyManagedBean();
ctx.setAttribute("myManagedBean", myManagedBean);
}
}
In my opinion, this is far from clean code, but it seems like it does the trick.
Additionally to BalusC's answer above you could use #Startup and #Singleton (CDI), e.g.
//#Named // javax.inject.Named: only needed for UI publishing
//#Eager // org.omnifaces.cdi.Eager: seems non-standard like taken #Startup below
#Startup // javax.ejb.Startup: like Eager, but more standard
#Singleton // javax.ejb.Singleton: maybe not needed if Startup is there
//#Singleton( name = "myBean" ) // useful for providing it with a defined name
#ApplicationScoped
public class Bean {
// ...
}
which is nicely explained here.
Works in JPA 2.1 at least.

Jsf custom managed bean instantination handler

Which JSF 1.2 component is responsible for instantiating managed bean specified in faces-config.xml?
I'd like to replace this component with my custom-made version which will perform some additional tasks after bean instance is successfully created.
No one component is responsible for that. It is just EL which is responsible for that. If the expression #{beanname} returns null, it will create one which is associated with the managed bean name.
In your specific case, the normal way to solve this problem is just making use of the constructor of the bean or a public method of the bean annotated with #PostConstruct.
public class Bean {
public Bean() {
// Put code here which is to be executed during construction, but before
// setting of the managed properties (<managed-property> declarations).
}
#PostConstruct
public void init() {
// Put code here which is to be executed AFTER construction
// and the setting of managed properties.
}
}
If you really want to take the EL resolving in your own hands, then best what you can do is to implement a custom ELResolver. You can find here an article about that.
Here is the JSP resolver structure detailed in the JSF 1.2 spec:
Faces ELResolver for JSP
|_ faces.ImplicitObjectELResolverForJSP
|_ faces.ManagedBeanELResolver
|_ faces.ResourceBundleELResolver
|_ ELResolvers in application configuration resources
|_ faces.VariableResolverChainWrapper (wraps deprecated API)
|_ faces.PropertyResolverChainWrapper (wraps deprecated API)
|_ ELResolvers from Application.addELResolver()
Managed beans will be instantiated by the faces.ManagedBeanELResolver (which is just a label developers can refer to it by, not the name of a public class).
The top-level ELResolver is provided via the Application (which you can provide via an ApplicationFactory). But, although the JSF specification details behaviour, the API does not expose the means by which the managed beans will be instantiated. It would be difficult to decorate the implementation to disambiguate between a newly instantiated bean and a bean that was returned from the request/session/application scope.
BalusC's post gives a couple of good strategies for approaching this problem.
Although JSF 2.0 brings changes to the managed bean facility, it does not, to the best of my knowledge, change this aspect of the API.
#PostConstruct is the way to go for JSF 1.2.
If you are using JavaEE 6 then you can also use #Produces annotation on a method to create custom factory method.
public class CustomBeanFactory {
#Produces
public Bean getBean() {
Bean bean = new Bean();
System.out.println("Created new bean.");
return bean;
}
}

Resources