1. java
  2. android
  3. c#
  4. .net
  5. javascript
  6. php
  7. jquery
  8. html
  9. sql

Injeção de EntityManeger em Web service, via filter

Olá pessoal,

Estou com o seguinte problema, estou tentando injetar o entityManager na requisição feita ao meu web service.

Erro:

2014/04/24 10:43:20,043 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/]] (MSC service thread 1-4) Exception sending context initialized event to listener instance of class org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap: java.lang.RuntimeException: Unable to find a constructor that takes a String param or a valueOf() or fromString() method for javax.ws.rs.FormParam("entityManager") on public java.lang.String br.com.serverchattcc.resources.UsuarioResource.add(javax.persistence.EntityManager,br.com.serverchattcc.json.elements.UsuarioJson) for basetype: javax.persistence.EntityManager
    at org.jboss.resteasy.core.StringParameterInjector.initialize(StringParameterInjector.java:207) [resteasy-jaxrs-2.3.2.Final.jar:]
    at org.jboss.resteasy.core.StringParameterInjector.<init>(StringParameterInjector.java:57) [resteasy-jaxrs-2.3.2.Final.jar:]
    at org.jboss.resteasy.core.FormParamInjector.<init>(FormParamInjector.java:22) [resteasy-jaxrs-2.3.2.Final.jar:]
    at org.jboss.resteasy.core.InjectorFactoryImpl.createParameterExtractor(InjectorFactoryImpl.java:90) [resteasy-jaxrs-2.3.2.Final.jar:]
    at org.jboss.resteasy.core.InjectorFactoryImpl.createParameterExtractor(InjectorFactoryImpl.java:61) [resteasy-jaxrs-2.3.2.Final.jar:]
    at org.jboss.resteasy.core.MethodInjectorImpl.<init>(MethodInjectorImpl.java:81) [resteasy-jaxrs-2.3.2.Final.jar:]
    at org.jboss.resteasy.core.InjectorFactoryImpl.createMethodInjector(InjectorFactoryImpl.java:55) [resteasy-jaxrs-2.3.2.Final.jar:]
    at org.jboss.resteasy.core.ResourceMethod.<init>(ResourceMethod.java:71) [resteasy-jaxrs-2.3.2.Final.jar:]
    at org.jboss.resteasy.core.ResourceMethodRegistry.processMethod(ResourceMethodRegistry.java:233) [resteasy-jaxrs-2.3.2.Final.jar:]
    at org.jboss.resteasy.core.ResourceMethodRegistry.addResourceFactory(ResourceMethodRegistry.java:125) [resteasy-jaxrs-2.3.2.Final.jar:]
    at org.jboss.resteasy.core.ResourceMethodRegistry.addResourceFactory(ResourceMethodRegistry.java:107) [resteasy-jaxrs-2.3.2.Final.jar:]
    at org.jboss.resteasy.core.ResourceMethodRegistry.addResourceFactory(ResourceMethodRegistry.java:84) [resteasy-jaxrs-2.3.2.Final.jar:]
    at org.jboss.resteasy.core.ResourceMethodRegistry.addPerRequestResource(ResourceMethodRegistry.java:73) [resteasy-jaxrs-2.3.2.Final.jar:]
    at org.jboss.resteasy.spi.ResteasyDeployment.registration(ResteasyDeployment.java:367) [resteasy-jaxrs-2.3.2.Final.jar:]
    at org.jboss.resteasy.spi.ResteasyDeployment.start(ResteasyDeployment.java:225) [resteasy-jaxrs-2.3.2.Final.jar:]
    at org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap.contextInitialized(ResteasyBootstrap.java:28) [resteasy-jaxrs-2.3.2.Final.jar:]
    at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:3392) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:3850) [jbossweb-7.0.13.Final.jar:]
    at org.jboss.as.web.deployment.WebDeploymentService.start(WebDeploymentService.java:90) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_55]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_55]
    at java.lang.Thread.run(Thread.java:744) [rt.jar:1.7.0_55]
2014/04/24 10:43:20,735 ERROR [org.apache.catalina.core.StandardContext] (MSC service thread 1-4) Error listenerStart
2014/04/24 10:43:20,738 ERROR [org.apache.catalina.core.StandardContext] (MSC service thread 1-4) Context [] startup failed due to previous errors
2014/04/24 10:43:20,937 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-4) MSC00001: Failed to start service jboss.web.deployment.default-host./ROOT: org.jboss.msc.service.StartException in service jboss.web.deployment.default-host./ROOT: JBAS018040: Failed to start context
    at org.jboss.as.web.deployment.WebDeploymentService.start(WebDeploymentService.java:95)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_55]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_55]
    at java.lang.Thread.run(Thread.java:744) [rt.jar:1.7.0_55]

Esse é meu filtro

package br.com.serverchattcc.filter;

import java.io.IOException;

import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

@WebFilter(servletNames={"Faces Servlets"})
public class JPAFilter implements Filter {

    private EntityManagerFactory factory;

    @Override
    public void destroy() {
        this.factory.close();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        EntityManager entityManager = this.factory.createEntityManager();
        request.setAttribute("entityManager", entityManager);

        try {
            entityManager.getTransaction().begin();
        } catch (Exception e) {
            System.out.println("-------------------Erro ao abrir transação--------------------");
        }

        chain.doFilter(request, response);

        try {
            entityManager.getTransaction().commit();
        } catch (Exception e) {
            entityManager.getTransaction().rollback();
        } finally{
            entityManager.close();
        }

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        this.factory = Persistence.createEntityManagerFactory("projetotcc");
    }

}

Esse é meu Webservice

package br.com.serverchattcc.resources;

import javax.persistence.EntityManager;
import javax.ws.rs.Consumes;
import javax.ws.rs.Encoded;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import br.com.serverchattcc.adapter.UsuarioEntityJsonAdapter;
import br.com.serverchattcc.enuns.Charset;
import br.com.serverchattcc.json.elements.UsuarioJson;
import br.com.serverchattcc.repository.UsuarioRepository;

@Path("/usuario")
public class UsuarioResource {

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.TEXT_PLAIN)
    @Path("/add")
    public String add(@FormParam("entityManager") EntityManager entityManager, 
                    @FormParam("usuario") UsuarioJson usuario) {

        try{
            UsuarioRepository usuarioRepository = new UsuarioRepository(entityManager);
            UsuarioEntityJsonAdapter usuarioAdapter = new UsuarioEntityJsonAdapter();
            usuarioRepository.persist(usuarioAdapter.convertJsonToEntity(usuario));
            return "ok";
        } catch(Exception e){
            return "erro##@@"+e.getMessage();
        }
    }

}

E meu web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.0"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         metadata-complete="false">

         <welcome-file-list>
             <welcome-file>index.html</welcome-file>
         </welcome-file-list>

        <filter>
            <filter-name>JPAFilter</filter-name>
            <filter-class>br.com.serverchattcc.filter.JPAFilter</filter-class>
        </filter>

        <filter-mapping>
            <filter-name>JPAFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>

         <context-param>
            <param-name>resteasy.servlet.mapping.prefix</param-name>
            <param-value>/services</param-value>
         </context-param>

         <context-param>
            <param-name>resteasy.scan</param-name>
            <param-value>true</param-value>
         </context-param>

         <listener>
            <listener-class>
             org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
            </listener-class>
         </listener>

        <servlet>
            <servlet-name>Resteasy</servlet-name>
            <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
        </servlet>

        <servlet-mapping>
            <servlet-name>Resteasy</servlet-name>
            <url-pattern>/services/*</url-pattern>
        </servlet-mapping>

</web-app>
  1. Você vai ver essas setas em qualquer página de pergunta. Com elas, você pode dizer se uma pergunta ou uma resposta foram relevantes ou não.
  2. Edite sua pergunta ou resposta caso queira alterar ou adicionar detalhes.
  3. Caso haja alguma dúvida sobre a pergunta, adicione um comentário. O espaço de respostas deve ser utilizado apenas para responder a pergunta.
  4. Se o autor da pergunta marcar uma resposta como solucionada, esta marca aparecerá.
  5. Clique aqui para mais detalhes sobre o funcionamento do GUJ!

0 resposta

Não é a resposta que estava procurando? Procure outras perguntas com as tags webservices jboss java-ee jaxws rest ou faça a sua própria pergunta.