Hot questions for Using Enterprise JavaBeans in jersey

Question:


Answer:

You have multiple dependencies in your classpath that contains javax.ws.rs.core.UriBuilder, two of JAX-RS 1.1:

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

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-core</artifactId>
    <version>1.18</version>
</dependency>

And one of JAX-RS 2.0:

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

Since JAX-RS 2.0 is from Java EE 7, probably you need downgrade javaee-api to version 6, using like this:

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

Other way is upgrade Jersey version, like in this answer: AbstractMethodError using UriBuilder on JAX-RS

In runtime UriBuilder#uri(String) is called, so you need to verify the dependencies in the servlet container.

Question:

I was able to use the jersey test framework to test my JAX-RS restful api. However, I cannot get my EJB's to properly be mocked no matter what I try.

Using the example provided by @peeskillet, the point at which my EJB is referenced in the Resource remains null.

So I know it's not my dependencies. I believe the issue is that I have nested EJB's going on. There are a couple of factors that I'm sure may be influencing how this code is behaving, but I'm not sure how to address: 1. My ApplicationService that I am trying to mock is an interface and I have an ApplicationServiceImpl class which has the actual logic in it. Since my test is NOT focused on that logic, my thought process was mocking the interface should be sufficient. 2. However, the implementation of the interface also contains an EJB which connects to a MongoDB singleton.

So my questions: Could either of those factors be playing a role here in why the interface reference in my resource class is always null thus clearly failing to be mocked and injected? If so, how do I fix that?

If I need to switch to mocking the implementation directly instead of the interface, do I then also need to mock the DAO ejb?

To be clear, the test frame work works absolutely fine as long as I don't call any methods which rely on fields/objects injected via EJB.

My Resource Class


    @Path("/stats")
@Api(value = "stats", authorizations = {
    @Authorization(value = "apiKey", scopes = {})
})
@Stateless
@Produces({MediaType.APPLICATION_JSON})
public class StatsResource {

    private final static Logger LOG = Logger.getLogger(StatsResource.class.getName());

    @EJB
    ApplicationService applicationService;

    public void setApplicationService(ApplicationService applicationService) {
        this.applicationService = applicationService;
    }

    @GET
    public String getHere(){
        return "Got Here!";
    }

    @GET
    @Path("test")
    @ApiOperation(value = "Finds all applications",
            notes = "Returns brief display which uses a limited subset of Application.class fields",
            response = Application.class,
            responseContainer = "List<Application>"
    )
    @JsonView(Views.Brief.class)
    @Asynchronous
    public void getApplications(@Suspended
    final AsyncResponse asyncResponse) throws Exception {        
        asyncResponse.resume(doGetApplications());
    }

    private ApplicationList doGetApplications() throws Exception {
        return new ApplicationList(applicationService.getAll());
    }

}

My Test Case


    public class StatsResourceNGTest extends JerseyTestNg.ContainerPerMethodTest {
    @Mock
    private ApplicationService applicationService;

    @Override
    protected Application configure() {
        enable(TestProperties.LOG_TRAFFIC);
        enable(TestProperties.DUMP_ENTITY);

        MockitoAnnotations.initMocks(this);        
        Logger.getLogger(StatsResourceNGTest.class.getName()).log(Level.INFO, "Mock App Service: {0}", applicationService.toString());
        AbstractBinder binder = new AbstractBinder() {
            @Override
            protected void configure() {
                bindFactory(MockApplicationServiceFactory.class)
                        .to(ApplicationResource.class);
            }
        };

        ResourceConfig config = new IdentityRestApplication(true);
        config.register(binder);
        config.register(StatsResource.class);

        return config;
    }

    @Test
    public void assertMockInjectionWorked() throws Exception {
        Response response = target("/stats/test").request(MediaType.APPLICATION_JSON).get();

        verify(applicationService, times(1)).getAll();
        Logger.getLogger(ApplicationResourceNGTest.class.getName()).log(Level.INFO, "Status: {0}", response.getStatus());
        String msg = response.readEntity(String.class);
        Logger.getLogger(ApplicationResourceNGTest.class.getName()).log(Level.INFO, "Response: {0}", msg);

        Assert.assertNotNull(msg);
        response.close();

    }

}

My HK2 MockFactory


public class MockApplicationServiceFactory implements Factory<ApplicationService> {

private List<Application> appList;

@Override
public ApplicationService provide() {
    appList = new ArrayList<>();
    for (int i = 1; i < 6; i++) {
        String appname = "App " + i;
        Application app = new ApplicationBuilder()
                .setName(appname)
                .setDescription(appname + " Description")
                .setTenantId(new ObjectId())
                .createApplication();
        appList.add(app);
    }
    try {
        final ApplicationService mockedService = Mockito.mock(ApplicationService.class);
        Mockito.when(mockedService.getAll()).thenReturn(appList);
        return mockedService;
    } catch (ApplicationException ex) {
        Logger.getLogger(ApplicationResourceNGTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(ApplicationResourceNGTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

@Override
public void dispose(ApplicationService t) {
}

}


Answer:

I didn't really give the best example. Though, Lars Juel Jensen's answer uses TestNG, and not JUnit, the set up it much cleaner and provides for better testability

Here's what you can do. As juherr mentioned, the ApplicationServices are different instances. What you can do instead, is forget the Factory altogether. Just use the mocked field

@Mock
private ApplicationService applicationService;

@Override
protected Application configure() {
    MockitoAnnotations.initMocks(this);
    ...
}

Then forget the AbstractBinder. The reason is that it only works for annotations it knows (i.e. it doesn't know @EJB), unless you create some other components to make the annotation know (but that is too much). So just use your setter to inject it

StatsResource resource = new StatsResource(applicationService);
config.register(resource);

Now in each @Test case, you can provide a completely different mock implementation, meaning your wheh(..).then(..)s can be different for each test case. It's more flexible than keeping the same implementation in the factory anyway.

So in your @Test methods, just work off the test class' applicationService.

Question:

I am a rookie in services and now I am finding an issue when injecting my EJB on it, it always comes null. I saw people with this issue in several posts as well, new or olds, but the solutions that was proposed by them either didn't work or I didn't know how to implement it.

I am using tomcat v7 + jersey implementation v1.8.

The solutions that I tried so far:

  1. Use spi injection, as result, the instance was there, but the my EntityManager was always null;

  2. Making the service @Stateless, always got null as well;

  3. Add transaction attribute like this post suggests, still null coming;

  4. Last one I didn't knew how to implement, it is in this post in here, to implement a provider

The Facade that I am trying inject is this one that I made:

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

@LocalBean
@Stateless
public class AutoEntityFacade extends EntityFacade {

    @PersistenceContext(unitName = "myauto-unit")
    private EntityManager manager;

    @PostConstruct
    public void setup() {
        setEntityManager(manager);
    }

}

My service class is also quite simple, but the injection is not working properly:

import br.com.aes.myauto.model.exception.HttpBusinessException;
import br.com.aes.myauto.model.person.Person;
import br.com.aes.myauto.service.facade.AutoEntityFacade;
import br.com.aes.myauto.service.facade.EntityFacade;
import br.com.aes.myauto.service.rest.CrudService;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import org.apache.commons.lang3.StringUtils;

@Path("/person")
@Stateless
public class PersonService extends CrudService<Person> {

    @QueryParam(value = "name")
    private String name;
    @QueryParam(value = "lastName")
    private String lastName;
    @QueryParam(value = "email")
    private String email;

    @Override
    protected void setup() throws HttpBusinessException {
        if (StringUtils.isNotBlank(name)) {
            addParameter("name", "%" + name + "%");
        }
        if (StringUtils.isNotBlank(lastName)) {
            addParameter("lastName", "%" + lastName + "%");
        }
        if (StringUtils.isNotBlank(email)) {
            addParameter("email", "%" + email + "%");
        }
    }

    @Override
    protected String buildQuery() {
        return "select obj from Person obj " + getQuery();
    }

    @Override
    protected String buildCountQuery() {
        return "select count(obj) from Priority obj " + getQuery();
    }

    private String getQuery() {
        boolean firstClause = true;
        String result = "";
        String connector = "and";

        if (StringUtils.isNotBlank(name)) {
            if (firstClause) {
                result += "where ";
                firstClause = false;
            } else {
                result += connector;
            }
            result += " obj.name like :name ";
        }
        if (StringUtils.isNotBlank(lastName)) {
            if (firstClause) {
                result += "where ";
                firstClause = false;
            } else {
                result += connector;
            }
            result += " obj.lastName like :lastName ";
        }
        if (StringUtils.isNotBlank(email)) {
            if (firstClause) {
                result += "where ";
                firstClause = false;
            } else {
                result += connector;
            }
            result += " obj.email like :email ";
        }

        return result;
    }

    @PersistenceContext(unitName = "myauto-unit")
    private EntityManager manager;

    @EJB
    private AutoEntityFacade entityFacade;

    @Override
    protected EntityFacade getEntityFacade() {
        return entityFacade;
    }

    @Override
    public EntityManager getEntityManager() {
        return manager;
    }

}

Is there anything that I am missing? This is my project structure:

project structure

As you can see, I also provided the beans on both web and service layer. In my service I have a test class, so I know that jersey is working properly and accepting the parameters.

What am I missing here?


I changed the container to see if I could have any more detailed exception, since tomcat wasn't being that helpful, these are the results, which I still can't find out.

Warning: javax.ejb.EJBException: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
    at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:454)
    at com.sun.ejb.containers.BaseContainer.getContext(BaseContainer.java:2547)
    at com.sun.ejb.containers.BaseContainer.preInvoke(BaseContainer.java:1899)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:89)
    at com.sun.proxy.$Proxy253.getBusinessObjectById(Unknown Source)
    at br.com.aes.myauto.service.crud.__EJB31_Generated__PersonService__Intf____Bean__.getBusinessObjectById(Unknown Source)
    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:601)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:708)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:722)
Caused by: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
    at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:726)
    at com.sun.ejb.containers.util.pool.NonBlockingPool.getObject(NonBlockingPool.java:247)
    at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:449)
    ... 50 more
Caused by: javax.ejb.CreateException: Could not create stateless EJB
    at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:534)
    at com.sun.ejb.containers.StatelessSessionContainer.access$000(StatelessSessionContainer.java:95)
    at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:724)
    ... 52 more
Caused by: com.sun.jersey.spi.inject.Errors$ErrorMessagesException
    at com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
    at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)
    at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
    at com.sun.jersey.server.impl.application.WebApplicationImpl$ComponentProcessorFactoryImpl.get(WebApplicationImpl.java:499)
    at com.sun.jersey.server.impl.ejb.EJBInjectionInterceptor.get(EJBInjectionInterceptor.java:104)
    at com.sun.jersey.server.impl.ejb.EJBInjectionInterceptor.init(EJBInjectionInterceptor.java:71)
    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:601)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCallback(SystemInterceptorProxy.java:133)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.init(SystemInterceptorProxy.java:120)
    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:601)
    at com.sun.ejb.containers.interceptors.CallbackInterceptor.intercept(InterceptorManager.java:964)
    at com.sun.ejb.containers.interceptors.CallbackChainImpl.invokeNext(CallbackChainImpl.java:65)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:393)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:376)
    at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:526)
    ... 54 more

Warning: StandardWrapperValve[MyAuto REST Service]: PWC1406: Servlet.service() for servlet MyAuto REST Service threw exception
com.sun.jersey.spi.inject.Errors$ErrorMessagesException
    at com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
    at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)
    at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
    at com.sun.jersey.server.impl.application.WebApplicationImpl$ComponentProcessorFactoryImpl.get(WebApplicationImpl.java:499)
    at com.sun.jersey.server.impl.ejb.EJBInjectionInterceptor.get(EJBInjectionInterceptor.java:104)
    at com.sun.jersey.server.impl.ejb.EJBInjectionInterceptor.init(EJBInjectionInterceptor.java:71)
    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:601)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCallback(SystemInterceptorProxy.java:133)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.init(SystemInterceptorProxy.java:120)
    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:601)
    at com.sun.ejb.containers.interceptors.CallbackInterceptor.intercept(InterceptorManager.java:964)
    at com.sun.ejb.containers.interceptors.CallbackChainImpl.invokeNext(CallbackChainImpl.java:65)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:393)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:376)
    at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:526)
    at com.sun.ejb.containers.StatelessSessionContainer.access$000(StatelessSessionContainer.java:95)
    at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:724)
    at com.sun.ejb.containers.util.pool.NonBlockingPool.getObject(NonBlockingPool.java:247)
    at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:449)
    at com.sun.ejb.containers.BaseContainer.getContext(BaseContainer.java:2547)
    at com.sun.ejb.containers.BaseContainer.preInvoke(BaseContainer.java:1899)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:89)
    at com.sun.proxy.$Proxy253.getBusinessObjectById(Unknown Source)
    at br.com.aes.myauto.service.crud.__EJB31_Generated__PersonService__Intf____Bean__.getBusinessObjectById(Unknown Source)
    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:601)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:708)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:722)

Answer:

Well, at last I found a way to do so that isn't that bad.

The way I did to make it work is probably known by most, (even myself, shame on me), but due the scenario, it didn't seemed to be the best approach.

I recreated some parts of my system in which I could eliminate the EJB and stay with the EntityManager only, having that done, the EJB or persistenceContext was also not viable, so I created a new entityManagerFactory and that did the trick.

private EntityManager manager;
private EntityManagerFactory emf  = null;

public PersonService() {
    if (manager == null){
        emf = Persistence.createEntityManagerFactory("myauto-unit");
        manager = emf.createEntityManager();
    }
}

Not complicated to be implement and easy to perform the test.

Cheers

Question:

i have passed a lot of time to solve a simple problem using rest, but i don't way i can't post data when i test in postman or advanced rest, this is my rest resource

@Path("/auth")
@Stateless
public class RestWs {

    @EJB 
    private UserService userService;

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public void registerRest(Users u){
        Users users = new Users();
        users.setUsername(u.getUsername());
        users.setEmail(u.getEmail());
        users.setPassword(u.getUsername());
        userService.registerService(u);
    }

}

and this is my jpa

@Override
    public Users register(Users users) {
        em.persist(users);
        return users;
    }

and this is my entity

@Entity
public class Users implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)

    private Long id;
    private String username;
    private String email;
    private String password;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "Users{" + "id=" + id + ", username=" + username + ", email=" + email + ", password=" + password + '}';
    }


}

i don't why i can't post data for register user , i need something else like parsing or ...., please help me, and thanks


Answer:

just i need to add cross filter and all work great

@Provider
public class CORSFilter implements ContainerResponseFilter{

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext response) throws IOException {
        response.getHeaders().add("Access-Control-Allow-Origin", "*");
        response.getHeaders().add("Access-Control-Allow-Headers",
                      "origin, content-type, accept, authorization");
        response.getHeaders().add("Access-Control-Allow-Credentials", "true");
        response.getHeaders().add("Access-Control-Allow-Methods",
                      "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }

}

and in web.xml

<init-param>
          <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
          <param-value>com.ress.CORSFilter</param-value>
        </init-param>

that's all

Question:

I have a very weird problem with Jersey REST services. I'm using:

  • Glassfish
  • sh4.0
  • EJB3.1
  • JDK1.7
  • Netbeans8.0

When I persist an object by GET request it normally store in database:

@Singleton
@Path("/person")
public class SampleRest {

    @EJB
    PersonFasade personFasade;

    @GET
    public Person getPerson1(
            final @QueryParam("id") String id,
            final @QueryParam("first") String first,
            final @QueryParam("last") String last) 
    {
        final Person person = this.personFasade.create(id, first, last);        
        return person;
    }

}

But when I'm using POST:

...

    @POST
    public Person getPerson3(Person person) {
        this.personFasade.create(person);    
        return person;
    }
...

Everything works but Object does not store in database (without any error)!!


Answer:

I'm pretty sure that is the parameter, you should use the @Consumes annotation to pass a Person object as JSON/XML parameter or use the same @QueryParam annotations to describe the object to persist.

@POST
@Consumes(MediaType.APPLICATION_JSON)
public Person getPerson3(Person person) {
    this.personFasade.create(person);    
    return person;
}