GlassFish ManagedBeanCreationException and NullPointerException - jsf

I have written an EJB and a dynamic web project Eclipse on GlassFish server. I used DAO , Facade and JPA. Normally I am calling a method from my service it is giving these errors ;
kitapOduncVerme.xhtml]com.sun.faces.mgbean.ManagedBeanCreationException
PWC1406: Servlet.service() for servlet Faces Servlet threw exceptionjava.lang.NullPointerException
at com.mesutemre.kitapislemleri.KitapOduncVermeBean.initList(KitapOduncVermeBean.java:47)
at com.mesutemre.kitapislemleri.KitapOduncVermeBean.initialize(KitapOduncVermeBean.java:43)
My codes are below;
#ManagedBean(name = "oduncKitapVerBean")
#ViewScoped
public class KitapOduncVermeBean implements Serializable{
private static final long serialVersionUID = 1L;
private List<Kitaplar> entityList = new ArrayList<Kitaplar>();
private Kitaplar selectedEntity;
private Kitaplar entity;
private String kullaniciadi;
private KitaplarFacade service;
public KitapOduncVermeBean() {
entity = new Kitaplar();
selectedEntity = new Kitaplar();
}
#PostConstruct
public void initialize(){
HttpSession session = Util.getSession();
kullaniciadi = Util.getUserName();
initList();
}
private void initList(){
entityList = service.findAllKitaplar();
}
DaoImpl
#SuppressWarnings("unchecked")
public List<Kitaplar> findAllKitaplar(){
return em.createNamedQuery("tumkitaplarigetir").getResultList();
}
Dao
#Stateless
#LocalBean
public class KitaplarDAO extends KitaplarDaoImpl<Kitaplar> implements Serializable{
private static final long serialVersionUID = 1L;
#Override
public List<Kitaplar> findAllKitaplar() {
return super.findAllKitaplar();
}
FacadeImpl
#Stateless
#LocalBean
public class KitaplarFacadeImpl implements KitaplarFacade,Serializable {
private static final long serialVersionUID = 1L;
#EJB
KitaplarDAO kitapDao;
#Override
public List<Kitaplar> findAllKitaplar() {
return kitapDao.findAllKitaplar();
}
}
Facade
#Local
public interface KitaplarFacade {
public abstract List<Kitaplar> findAllKitaplar();
}
I can't see any problem in this codes? But Why am I getting that errors?

ManagedBeanCrearionException is simply wrapping and rethrowing the NullPointerException, that is very easy to debug: you have a null variable at the exact line that appears in the stack trace.
In KitapOduncVermeBean class, you are declaring service property, but you are not initializing it, therefore it's null when invoked in initList() method. Since it's an EJB, annotate it as such and the EJB container will instantiate it automatically:
#EJB
private KitaplarFacade service;
Unrelated to the concrete problem, your code is too complicated: with EJB 3.x, in most web applications, you don't need EJBs to implement or expose interfaces.

Related

How to inject beans with AspectJ and CDI

I've coded this aspect:
#Aspect
public class LoggingCacheAspect {
#Pointcut("call * javax.cache.integration.CacheLoader.load(*)")
void cacheLoadCalls() {};
#Before("cacheLoadCalls")
public void beforeCacheCalls() {}
}
Also, I'm using CDI, and I'm looking forward to figure out how to inject a bean into this aspect.
I guess that adding #Inject annotation will not be enought.
Is it possible?
How could I get it?
You need to use an interceptor instead of the aspect
Here is an example:
#InterceptorBinding
#Target({TYPE, METHOD })
#Retention(RUNTIME)
public #interface CacheLog{
}
#Interceptor
#CacheLog
public class CacheLogInterceptor implements Serializable {
private static final long serialVersionUID = 1L;
#Inject
private YourBean yourBean;
#AroundInvoke
public Object cacheLogMethodCall(InvocationContext ctx) throws Exception {
//#Before
yourBean.method();
...
return ctx.proceed();
}
}
#CacheLog
public void cacheLoadCalls() {
...
...
}

No EJB found with interface of type when I try to inject a Bean

I try to make a simple login with JSF and Managed Beans, but when start the server returns the following error.
WFLYEJB0406: No EJB found with interface of type 'Controlador.UsuarioSessionBean' for binding Controlador.AlmacenVirtualBean/usuarioSession"}
This is the class to save the data...
#ManagedBean
#RequestScoped
public class UsuarioSessionBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#EJB
private UsuarioSessionDAO usuarioSession;
//private Usuario usuario;
private int usuarioId;
private String nick;
private String pass;
And in other Managed Bean I try to inject the first.
#ManagedBean(name="AlmacenVirtualBean")
#RequestScoped
public class AlmacenVirtualBean {
private AlmacenVirtual almacenVirtual;
private String nombre;
private int usuarioId;
public AlmacenVirtualBean(){}
#EJB
private AlmacenVirtualDAO almacenVirtualDAO;
#ManagedProperty("#{UsuarioSessionBean}")
private UsuarioSessionBean usuarioSession;
That's what I'm doing wrong?
You may get that error, if you change the AlmacenVirtualBean to have:
#EJB
private UsuarioSessionBean usuarioSession;
Your question code can't produce that error.
But you can get usuarioSession=null. You should replace #{UsuarioSessionBean} by #{usuarioSessionBean}.

Resource injection issue JSF 2.2

I try to achieve resource injection for a long time but couldn't succeeded.
I use JSF 2.2, JDK 1.7. And my ide is eclipse luna.
I have a session scoped bean called UserBean and view scoped bean called SettingsBean.
I set them in faces-config.xml UserBean as session scoped and SettingsBean as view scoped with their bean name "settingsBean" and "userBean"
public class SettingsBean implements Serializable {
private static final long serialVersionUID = 1L;
#Inject // I also tried #ManagedProperty but didn't work
private UserBean userBean;
#PostConstruct
public void init(){
System.out.println(userBean.getUser().getFullName());
}
public UserBean getUserBean() {
return userBean;
}
public void setUserBean(UserBean userBean) {
this.userBean = userBean;
}
}
The problem is I get userBean as null. What is the problem here?
Thanks for help.
I removed ManagedBean and ViewScoped definitions in faces-config.xml for settingsBean and added them in SettingsBean.java file manually.
And added this also:
#ManagedProperty(value="#{userBean}")
private UserBean userBean;
So finally, it works:
#ManagedBean
#ViewScoped
public class SettingsBean implements Serializable{
private static final long serialVersionUID = 1L;
#ManagedProperty(value="#{userBean}")
private UserBean userBean;
//...
#PostConstruct
public void init(){
System.out.println(userBean.getUser().getFullName());
}
public UserBean getUserBean() {
return userBean;
}
public void setUserBean(UserBean userBean) {
this.userBean = userBean;
}
}

picketlink, envers and cdi injection

I am using picketlink to authenticate a user on project. I also created a #produces annotated method, so I would be able to inject the authenticated user in other places. Now, I am using envers and besides the default information, I would like to store the user that performed the action, but I cannot inject it in the envers listener. It is always null. How can I make this injection, or retrieve this information?
The producer class:
#SessionScoped
public class Resources implements Serializable {
private static final long serialVersionUID = 1L;
#EJB
private AuthenticationManagerBean authenticator;
#Inject
private Identity credentials;
#CurrentUser
private AuthenticatedUser currentUser;
#Produces
#CurrentUser
#SessionScoped
private AuthenticatedUser createAuthenticatedUser() {
AuthenticatedUser user = new AuthenticatedUser();
org.picketlink.idm.model.basic.User loggedInUser = (org.picketlink.idm.model.basic.User) credentials.getAccount();
User pu = authenticator.getUserRoles(loggedInUser.getLoginName());
if (pu != null) {
user.setUser(pu.getName());
for (Role role : pu.getRoles()) {
user.getRoles().add(role.getName());
}
}
return user;
}
#Produces
public Logger produceLog(InjectionPoint injectionPoint) {
return LoggerFactory.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
}
and the envers listener:
public class AuditListener implements RevisionListener, Serializable {
private static final long serialVersionUID = 1L;
#Inject
#CurrentUser
private AuthenticatedUser identity; //this is always null
public void newRevision(Object revisionEntity) {
System.out.println(identity.getUser());
}
}
I had a similiar problem. The injection does not work because RevisionListener is not managed by CDI. That way, you have to lookup for the bean yourself. This is the way you could do it:
public AuthenticatedUser getAuthenticatedUser() {
BeanManager beanManager = (BeanManager) new InitialContext().lookup("java:comp/BeanManager");
Bean<AuthenticatedUser> bean = (Bean<AuthenticatedUser>) beanManager.getBeans(AuthenticatedUser.class, new AnnotationLiteral<CurrentUser>() {
}).iterator().next();
CreationalContext<AuthenticatedUser> ctx = beanManager.createCreationalContext(bean);
return (AuthenticatedUser) beanManager.getReference(bean, AuthenticatedUser.class, ctx);
}

Injection of ManagedBean to another bean is failed

I tried to inject a Managed Bean to another bean, but failed. That is the first bean:
#ManagedBean(name = "sucBean")
#SessionScoped
public class SucBean implements Serializable {
private static final long serialVersionUID = 1L;
private MapModel advancedModel;
private MapModel advancedModel2;
private Marker marker;
private Suc suc;
private List<Suc> sucDefteri;
private List<Suc> searchResult;
private Suc[] selectedSuc;
private SucService sucService;
private String aramaKriteri;
private String arananKelime;
private SucDataModel sucModel;
// other getters/setters methods
When I run the web application, I'm getting the
Caused by: java.lang.NullPointerException
at org.primefaces.component.chart.CartesianChart.getCategories(CartesianChart.java:32)
at org.primefaces.component.chart.bar.BarChartRenderer.encodeData(BarChartRenderer.java:121)
at org.primefaces.component.chart.bar.BarChartRenderer.encodeScript(BarChartRenderer.java:51)
at org.primefaces.component.chart.bar.BarChartRenderer.encodeEnd(BarChartRenderer.java:36)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1786)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
The second bean is following:
#ManagedBean(name="chartBean")
#SessionScoped
public class ChartBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private CartesianChartModel categoryModel;
#ManagedProperty("#{sucBean}")
private SucBean sucBean;
private int[] sucSayilari=new int[9];
public ChartBean()
{
createCategoryModel();
}
I think this is the problem:
public ChartBean()
{
createCategoryModel();
}
Your dependencies are not set at this point because the JSF implementation first instantiates your bean (and that means that the constructor must finish) and then injects its dependencies, so if you are using the injected bean in createCategoryModel() it will be a null reference.
If you need to do something with your bean AFTER dependencies are set use a method anotated with #PostConstruct:
public ChartBean(){
}
#PostConstruct
public void init(){
createCategoryModel();
}

Resources