1
votes

I'm implementing a JAX-RS that use Jersey, Hibernate, and DataSources, but after a lot of corrected errors, I faced one that I couldn't find a solution

Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type ServiceLocator with qualifiers @Default at injection point [UnbackedAnnotatedField] @Inject private org.glassfish.jersey.server.mvc.internal.ViewableMessageBodyWriter.serviceLocator at org.glassfish.jersey.server.mvc.internal.ViewableMessageBodyWriter.serviceLocator(ViewableMessageBodyWriter.java:0)

at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:362) at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:284) at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:137) at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:158) at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:501) at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:61) at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:59) at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:62) at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:55) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) at org.jboss.threads.JBossThread.run(JBossThread.java:320)

Controller
I tried withou Stateless, RequestScoped... But don't worked.

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

@Path("ejb/notificacao")
@Stateless
@LocalBean
@RequestScoped
public class NotificacaoControladorEJB {


    SmartJava smartjava = new SmartJava();
    @EJB
    NotificacaoDAOEJB notificacaoDAO;


    @GET
    @Produces("application/json; charset=UTF-8")
    @Path("/contador/{id}")
    public Notificacao contadorGet(@PathParam("id") int id) {
        long quantidade;
        try {
            quantidade = notificacaoDAO.contador(id);

            return new Notificacao(quantidade);
        } catch(Exception e) {
            quantidade = 0;
            System.err.println(smartjava.getFullStackTrace(e));

            return new Notificacao(quantidade);
        }
    }
    @GET
    @Produces("application/json; charset=UTF-8")
    @Path("/marcarcomolida/{id}")
    public Notificacao marcarcomolida(@PathParam("id") int id) {
        try {

            Notificacao entidade = notificacaoDAO.GetNotificacao(id);

            if(entidade != null) {
                entidade.setVisualizado(true);
                entidade.setDtvisualizado(new Timestamp(System.currentTimeMillis()));
                notificacaoDAO.Alterar(entidade);
                return new Notificacao(entidade.getNrseq());
            } else {
                return new Notificacao();
            }


        } catch(Exception e) {
            System.err.println(smartjava.getFullStackTrace(e));
            return null;
        }
    }

    @GET
    @Produces("application/json; charset=UTF-8")
    @Path("/listar/{id}/{quantidade}")
    public List<Notificacao> listar(@PathParam("id") int id, @PathParam("quantidade") int quantidade) {
        List<Notificacao> notificacoes = new ArrayList<Notificacao>();
        List<Notificacao> listaDeNotificacoes;

        try {

            if(quantidade < 1) {
                listaDeNotificacoes = notificacaoDAO.listarTodosPorUsuarioNrseq(id);
            } else {
                listaDeNotificacoes = notificacaoDAO.listarQuantidadePorUsuarioNrseq(id, quantidade);
            }

            if(listaDeNotificacoes != null) {

                for (Notificacao notificacao : listaDeNotificacoes) {
                    Usuario u = construtorUsuario(notificacao.getUseralvo());
                    notificacoes.add(new Notificacao(notificacao.getNrseq(), notificacao.getTitulo(), notificacao.getConteudo(),
                            notificacao.getImg(), notificacao.getLink(), notificacao.isAtivo(), notificacao.isVisualizado(),
                            notificacao.getDtcad(), notificacao.getDtvisualizado(), u));
                }
            }

            return notificacoes;
        } catch(Exception e) {

            return new ArrayList<Notificacao>();
        }
    }


    @POST
    @Consumes("application/json; charset=UTF-8")
    @Produces("application/json; charset=UTF-8")
    @Path("/cadastrar/um")
    public Notificacao cadastrarUm(Notificacao notificacao) {

        try {

            Notificacao entidade = notificacaoParaEntidade(notificacao, notificacao.getUseralvo());

            notificacaoDAO.Salvar(entidade);

            return new Notificacao(entidade.getNrseq());
        } catch(Exception e) {
            System.err.println(smartjava.getFullStackTrace(e));

            return new Notificacao();
        }
    }

    public Notificacao cadastrar(Notificacao notificacao) {

        try {

            Notificacao entidade = notificacaoParaEntidade(notificacao, notificacao.getUseralvo());

            notificacaoDAO.Salvar(entidade);
            return new Notificacao(entidade.getNrseq());
        } catch(Exception e) {
            System.err.println(smartjava.getFullStackTrace(e));
            return new Notificacao();
        }
    }

    public Notificacao notificacaoParaEntidade(Notificacao notificacao, Usuario usuario) {
        Notificacao entidade = new Notificacao();

        entidade.setTitulo(notificacao.getTitulo());
        entidade.setConteudo(notificacao.getConteudo());
        entidade.setImg(notificacao.getImg());
        entidade.setDtcad(new Timestamp(System.currentTimeMillis()));
        entidade.setUsercad(notificacao.getUsercad());
        entidade.setLink(notificacao.getLink());
        entidade.setAtivo(true);
        entidade.setUseralvo(usuario);
        return entidade;
    }

    private Usuario construtorUsuario(Usuario u) {
        try {
            return new Usuario(u.getNrseq(), u.getNome(), u.getEmail());
        } catch (Exception e) {
            return new Usuario();
        }
    }

}

DAO

import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;


@Stateless
@LocalBean
public class NotificacaoDAOEJB {

    //private EntityManagerFactory entityManagerFactory;
    @PersistenceContext
    private EntityManager entityManager;

    SmartJava sj = new SmartJava();



    public Notificacao Salvar(Notificacao notificacao) {

        try {
            this.entityManager.getTransaction().begin();
            this.entityManager.persist(notificacao);
            this.entityManager.getTransaction().commit();
        } catch (Exception e) {
            System.out.println(sj.getFullStackTrace(e));

        } finally {
            //this.entityManager.close();
        }

        return notificacao;
    }

    public void Alterar(Notificacao notificacao){

        this.entityManager.getTransaction().begin();
        this.entityManager.merge(notificacao);
        this.entityManager.getTransaction().commit();
        //this.entityManager.close();

    }

    @SuppressWarnings("unchecked")
    public List<Notificacao> Listar(){
        return this.entityManager.createQuery("SELECT a FROM Notificacao a ORDER BY a.dtcad").getResultList();
    }

    public Notificacao GetNotificacao(int nrseq) {
        return this.entityManager.find(Notificacao.class, nrseq);
    }
    @SuppressWarnings("unchecked")
    public long contador(int nrsequsuario) {
        try {
            return (long) this.entityManager.createQuery("SELECT COUNT(a) FROM Notificacao a "
                    + "WHERE a.visualizado = false AND a.useralvo.nrseq = :usuario ORDER BY a.dtcad")
                    .setParameter("usuario", nrsequsuario).getSingleResult();
        } catch(Exception e) {
            System.err.println(sj.getFullStackTrace(e));
            return 0;
        }
    }

    @SuppressWarnings("unchecked")
    public List<Notificacao> listarTodosPorUsuarioNrseq(int id) {
        try {
            return this.entityManager.createQuery("SELECT a FROM Notificacao a "
                    + "WHERE a.useralvo.nrseq = :usuario ORDER BY a.dtcad DESC")
                    .setParameter("usuario", id).getResultList();
        } catch(Exception e) {
            System.err.println(sj.getFullStackTrace(e));
            return null;
        }
    }
    @SuppressWarnings("unchecked")
    public List<Notificacao> listarQuantidadePorUsuarioNrseq(int id, int quantidade) {
        try {
            return this.entityManager.createQuery("SELECT a FROM Notificacao a "
                    + "WHERE a.useralvo.nrseq = :usuario ORDER BY a.dtcad DESC")
                    .setParameter("usuario", id).setMaxResults(quantidade).getResultList();
        } catch(Exception e) {
            System.err.println(sj.getFullStackTrace(e));
            return null;
        }
    }




}

WEB.XML

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>jersey.config.server.provider.packages</param-name>
      <param-value>br.com.souvizinho.controlador</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/webapi/*</url-pattern>
  </servlet-mapping>

  <!-- 
  <resource-ref>
    <description>DB Connection</description>
    <res-ref-name>java:/dbsouvizinho</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref> -->

  <!--  COMENTAR AO GLASSFISH -->
  <!--   
  <filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping> -->

</web-app>

PERSISTENCE.XML

       <!--  JBOS AS 7.11 E WildFly-->
   <!-- --> <persistence-unit name="persistence_unit_souvizinho" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
      <jta-data-source>java:/dbsouvizinho</jta-data-source>
      <properties>
         <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
         <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
       <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform" />
      <!--  -->   <!--   <property name="hibernate.connection.datasource" value="java:comp/env/jdbc/dbsouvizinho"/> -->
      <!-- --> 
      <!-- <property name="jboss.as.jpa.providerModule" value="org.hibernate:5.2"/>  -->
        <!--   <property name="hibernate.classloading.use_current_tccl_as_parent" value="false" /> -->
         <property name="hibernate.show_sql" value="true"/>
         <property name="hibernate.format_sql" value="true"/>
         <property name="hibernate.hbm2ddl.auto" value="update"/>
      </properties>
   </persistence-unit> <!--   -->

POM.XML

  <dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey</groupId>
            <artifactId>jersey-bom</artifactId>
            <version>${jersey.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.4</version>
    </dependency>

    <dependency> 
        <groupId>org.slf4j</groupId>
         <artifactId>slf4j-api</artifactId>
         <version>1.5.6</version> 
      </dependency> 

    <dependency>
        <groupId>org.glassfish.jersey.ext</groupId>
        <artifactId>jersey-mvc-jsp</artifactId>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet-core</artifactId>
    </dependency>


    <!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

<!-- https://mvnrepository.com/artifact/org.glassfish.grizzly/grizzly-http-server -->
<dependency>
    <groupId>org.glassfish.grizzly</groupId>
    <artifactId>grizzly-http-server</artifactId>
    <version>2.4.2</version>
</dependency>


    <dependency>
        <groupId>javax.ws.rs</groupId>
        <artifactId>javax.ws.rs-api</artifactId>
        <version>2.0.1</version>
    </dependency>

 <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
        </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-moxy</artifactId>
    </dependency>
    <!--  TOMCAT  -->
    <!-- 
        <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.1.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.1.Final</version>
    </dependency>  -->

 <!--  WILDFLY 11 -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.1.10.Final</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.1.10.Final</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.5.6</version>
</dependency>
 <!-- https://mvnrepository.com/artifact/org.jboss.logging/jboss-logging -->
<dependency>
    <groupId>org.jboss.logging</groupId>
    <artifactId>jboss-logging</artifactId>
    <version>3.3.0.Final</version>
</dependency>


    <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.37</version>
    </dependency>

  </dependencies>
1

1 Answers

0
votes

Worked for me:

Remove:
<dependency> <groupId>org.glassfish.jersey.ext</groupId> <artifactId>jersey-mvc-jsp</artifactId> </dependency>

And put the bellow tag on my persistence

<class>br.com.souvizinho.modelo.Notificacao</class>