0

Hello I'm stucked for a while in a problem using CDI with JSF and Tomcat.

Basically the @Inject does not work, and it keeps given me a NullPointerException because the object its still null.

Here is my generic dao:

package dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import model.AbstractEntity;

public abstract class GenericDao<T extends AbstractEntity, PK extends Number> {

    /**
     * Classe da entidade, necessário para o método
     * <code>EntityManager.find</code>.
     */
    private Class<T> entityClass;

    public GenericDao(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    public T save(T e) {
        if (e.getId() != 0)
            return getEntityManager().merge(e);
        else {
            getEntityManager().persist(e);
            return e;
        }
    }

    public void remove(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    public T find(PK id) {
        return getEntityManager().find(entityClass, id);
    }

    public List<T> findAll() {
        CriteriaQuery cq = getEntityManager().getCriteriaBuilder()
            .createQuery();
        cq.select(cq.from(entityClass));
        return getEntityManager().createQuery(cq).getResultList();
    }

    public List<T> findRange(int[] range) {
        CriteriaQuery cq = getEntityManager().getCriteriaBuilder()
            .createQuery();
        cq.select(cq.from(entityClass));
        Query q = getEntityManager().createQuery(cq);
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int count() {
        CriteriaQuery cq = getEntityManager().getCriteriaBuilder()
            .createQuery();
        Root<T> rt = cq.from(entityClass);
        cq.select(getEntityManager().getCriteriaBuilder().count(rt));
        Query q = getEntityManager().createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }

    /**
     * Exige a definição do <code>EntityManager</code> responsável pelas
     * operações de persistência.
     */
    protected abstract EntityManager getEntityManager();
}

DeputyDao:

package dao;

import javax.inject.Inject;
import javax.persistence.EntityManager;

import model.Deputy;

public class DeputyDao extends GenericDao<Deputy, Long> {
    @Inject
    private EntityManager em;

    public DeputyDao() {
        super(Deputy.class);
    }

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

}

EntityManagerCreator:

package dao;

import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class EntityManagerCreator {
    private final String PERSISTENCE_UNIT_NAME = "ChamadaParlamentar";

    private EntityManagerFactory factory = Persistence
        .createEntityManagerFactory(PERSISTENCE_UNIT_NAME);

    private EntityManager entityManager;

    @Produces
    @RequestScoped
    public EntityManager createEntityManager() {
        this.entityManager = factory.createEntityManager();
        return entityManager;
    }

    public void finaliza(@Disposes EntityManager manager) {
        manager.close();
    }
}

the caller method. Where it is giving me the null pointer exception:

package dataParser;

import java.net.MalformedURLException;
import java.rmi.RemoteException;
import java.util.List;

import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.xml.rpc.ServiceException;

import model.Deputy;
import model.PoliticalParty;
import webServiceConnector.DeputyConnector;
import dao.DeputyDao;
import dao.PoliticalPartyDao;
import exception.DeputyNotFoundException;
import exception.WebServiceNotAvailable;

@Named
@SessionScoped
public class DeputyDataParser {
    @Inject
    DeputyDao deputyDao;

    public Deputy getOneDeputy(int idParliamentary) {
        Deputy deputy;

        try {
            deputy = this.getOneDeputyFromWebService(idParliamentary);
        } catch (WebServiceNotAvailable e) {
            deputy = this.getOneDeputyFromDataBase(idParliamentary);
        }

        assert (deputy != null);
        return deputy;
    }

    public List<PoliticalParty> getAllPoliticalParties() {
        List<PoliticalParty> politicalParties;

        try {
            politicalParties = this.getAllPoliticalPartiesFromWebService();
        } catch (WebServiceNotAvailable e) {
            politicalParties = this.getAllPoliticalPartiesFromDataBase();
        }
        assert (politicalParties != null);
        assert (politicalParties.size() > 0);

        return politicalParties;
    }

    public List<PoliticalParty> getAllPoliticalPartiesFromDataBase() {
        PoliticalPartyDao politicaPartyDao = new PoliticalPartyDao();
        List<PoliticalParty> politicalParties = politicaPartyDao
            .getAllPoliticalParties();

        assert (politicalParties != null);
        assert (politicalParties.size() > 0);
        return politicalParties;
    }

    public List<Deputy> getAllDeputies() {
        List<Deputy> listWithAllDeputies;

        try {
            listWithAllDeputies = this.getAllDeputiesFromWebService();
        } catch (WebServiceNotAvailable e) {
            listWithAllDeputies = this.getAllDeputiesFromDataBase();
        }

        assert (listWithAllDeputies != null);
        assert (listWithAllDeputies.size() != 0);
        return listWithAllDeputies;
    }

    public Deputy getOneDeputy(String deputyName)
        throws DeputyNotFoundException {
        List<Deputy> deputies = this.getAllDeputies();
        Deputy deputyComplete = null;

        for (Deputy deputy : deputies) {
            boolean exists = deputy.getCivilName().equalsIgnoreCase(deputyName)
                             || deputy.getTreatmentName().equalsIgnoreCase(deputyName);
            if (exists) {
                deputyComplete = deputy;
            }
        }

        if (deputyComplete == null) {
            throw new DeputyNotFoundException("Invalid username");
        } else {
            return deputyComplete;
        }
    }

    public List<Deputy> getAllDeputiesFromDB() {
        List<Deputy> deputies = this.getAllDeputiesFromDataBase();

        assert (deputies.size() != 0);
        return deputies;
    }

    /***********************************************************
     * Private methods of the class
     ***********************************************************/

    private List<PoliticalParty> getAllPoliticalPartiesFromWebService()
        throws WebServiceNotAvailable {
        DeputyConnector deputyConnector = new DeputyConnector();
        List<PoliticalParty> politicalParties;
        try {
            politicalParties = deputyConnector.getAllPoliticalParties();
        } catch (RemoteException e) {
            throw new WebServiceNotAvailable(
                "The method threw a RemoteException");
        } catch (MalformedURLException e) {
            throw new WebServiceNotAvailable(
                "The method threw a MalformedURLException");
        } catch (ServiceException e) {
            throw new WebServiceNotAvailable(
                "The method threw a ServiceException");
        }
        return politicalParties;
    }

    private Deputy getOneDeputyFromWebService(int idParliamentary)
        throws WebServiceNotAvailable {
        DeputyConnector deputyConnector = new DeputyConnector();
        Deputy deputy;
        try {
            deputy = deputyConnector.getOneDeputy(idParliamentary);
        } catch (RemoteException e) {
            throw new WebServiceNotAvailable(
                "The method threw a RemoteException");
        } catch (MalformedURLException e) {
            throw new WebServiceNotAvailable(
                "The method threw a MalformedURLException");
        } catch (ServiceException e) {
            throw new WebServiceNotAvailable(
                "The method threw a ServiceException");
        }
        return deputy;
    }

    private Deputy getOneDeputyFromDataBase(long idParliamentary) {
        DeputyDao deputyDao = new DeputyDao();
        Deputy deputy = deputyDao.getById(idParliamentary);
        return deputy;
    }

    private List<Deputy> getAllDeputiesFromDataBase() {
        List<Deputy> listWithAllDeputies;

        listWithAllDeputies = deputyDao.findAll();
        return listWithAllDeputies;
    }

    private List<Deputy> getAllDeputiesFromWebService()
        throws WebServiceNotAvailable {
        List<Deputy> listWithAllDeputies;

        try {
            DeputyConnector deputyConnector = new DeputyConnector();
            listWithAllDeputies = deputyConnector.getAllDeputies();
            return listWithAllDeputies;
        } catch (RemoteException e) {
            throw new WebServiceNotAvailable(
                "The method threw a RemoteException");
        } catch (MalformedURLException e) {
            throw new WebServiceNotAvailable(
                "The method threw a MalformedURLException");
        } catch (ServiceException e) {
            throw new WebServiceNotAvailable(
                "The method threw a ServiceException");
        }
    }

}

and here is the stack trace:

javax.el.ELException: /templates/default/header.xhtml @31,59 completeMethod="#{autoComplete.completeDeputies}": java.lang.NullPointerException
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:111)
    at org.primefaces.component.autocomplete.AutoComplete.broadcast(AutoComplete.java:379)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
    at javax.faces.component.UIViewRoot.processDecodes(UIViewRoot.java:935)
    at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:78)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at dataParser.DeputyDataParser.getAllDeputiesFromDataBase(DeputyDataParser.java:155)
    at dataParser.DeputyDataParser.getAllDeputiesFromDB(DeputyDataParser.java:98)
    at control.DeputyControl.getAllNameOfAllDeputies(DeputyControl.java:44)
    at jsfConnection.AutoComplete.completeDeputies(AutoComplete.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    ... 27 more

I've already done lots of research but none of the solutions online solved my problem.

Can some one help me?

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452

1 Answers1

0

Tomcat is not an Application Server and it doesn't support CDI. You can use JBOSS or TomEE or Glassfish server whichever suits your need.

  • 2
    Welcome to Stack Overflow. It would be appreciated if you give more details with your answer, like how it actually answers the question asked. – Pac0 Sep 10 '17 at 01:30