Hot questions for Using GlassFish in ant

Question:

I've a lot of jee7 maven projects (ears with web and ejb modules) with RestFul services that run well on Glassfish v 4.0 but as soon as I try to run these projects on Glassfish v. 4.1 the RestFul services don't work anymore and they throw this exception:

javax.servlet.ServletException: A MultiException has 1 exceptions.  They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=TestBean,parent=GenericResource,qualifiers={},position=-1,optional=false,self=false,unqualified=null,82785107)

I've double checked the problem and definitively Glassfish 4.1 probably has a broken library (maybe cdi implementation ?), Glassfish v. 4.0 and Wildfly 8.1.0.Final are working well...

I can't understand how can I run my RestFul web services on Glassfish v. 4.1...

Does anyone can help me ?

Many thanks in advance...

Here the stack trace:

Avvertenza:   An instance of EJB class, test.rest.GenericResource, could not be looked up using simple form name. Attempting to look up using the fully-qualified form name.
javax.naming.NamingException: Lookup failed for 'java:app/TestEjb/GenericResource' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: No object bound to name java:app/TestEjb/GenericResource]
    at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:491)
    at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:438)
    at javax.naming.InitialContext.lookup(InitialContext.java:417)
    at javax.naming.InitialContext.lookup(InitialContext.java:417)
    at org.glassfish.jersey.gf.ejb.internal.EjbComponentProvider.lookupSimpleForm(EjbComponentProvider.java:378)
    at org.glassfish.jersey.gf.ejb.internal.EjbComponentProvider.lookup(EjbComponentProvider.java:360)
    at org.glassfish.jersey.gf.ejb.internal.EjbComponentProvider.access$000(EjbComponentProvider.java:100)
    at org.glassfish.jersey.gf.ejb.internal.EjbComponentProvider$EjbFactory.provide(EjbComponentProvider.java:123)
    at org.jvnet.hk2.internal.FactoryCreator.create(FactoryCreator.java:124)
    at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:461)
    at org.jvnet.hk2.internal.PerLookupContext.findOrCreate(PerLookupContext.java:69)
    at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2258)
    at org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:690)
    at org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:655)
    at org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:172)
    at org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:185)
    at org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:74)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:94)
    at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:63)
    at org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:263)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:297)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:254)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1028)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:372)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
    at java.lang.Thread.run(Thread.java:745)
Caused by: javax.naming.NameNotFoundException: No object bound to name java:app/TestEjb/GenericResource
    at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:741)
    at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:715)
    at com.sun.enterprise.naming.impl.JavaURLContext.lookup(JavaURLContext.java:167)
    at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:471)
    ... 64 more

Grave:   javax.naming.NamingException: Lookup failed for 'java:app/TestEjb/GenericResource!test.rest.GenericResource' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: No object bound to name java:app/TestEjb/GenericResource!test.rest.GenericResource]
    at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:491)
    at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:438)
    at javax.naming.InitialContext.lookup(InitialContext.java:417)
    at javax.naming.InitialContext.lookup(InitialContext.java:417)
    at org.glassfish.jersey.gf.ejb.internal.EjbComponentProvider.lookupFullyQualifiedForm(EjbComponentProvider.java:400)
    at org.glassfish.jersey.gf.ejb.internal.EjbComponentProvider.lookup(EjbComponentProvider.java:364)
    at org.glassfish.jersey.gf.ejb.internal.EjbComponentProvider.access$000(EjbComponentProvider.java:100)
    at org.glassfish.jersey.gf.ejb.internal.EjbComponentProvider$EjbFactory.provide(EjbComponentProvider.java:123)
    at org.jvnet.hk2.internal.FactoryCreator.create(FactoryCreator.java:124)
    at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:461)
    at org.jvnet.hk2.internal.PerLookupContext.findOrCreate(PerLookupContext.java:69)
    at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2258)
    at org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:690)
    at org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:655)
    at org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:172)
    at org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:185)
    at org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:74)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:94)
    at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:63)
    at org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:263)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:297)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:254)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1028)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:372)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
    at java.lang.Thread.run(Thread.java:745)
Caused by: javax.naming.NameNotFoundException: No object bound to name java:app/TestEjb/GenericResource!test.rest.GenericResource
    at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:741)
    at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:715)
    at com.sun.enterprise.naming.impl.JavaURLContext.lookup(JavaURLContext.java:167)
    at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:471)
    ... 64 more

Avvertenza:   StandardWrapperValve[test.rest.ApplicationConfig]: Servlet.service() for servlet test.rest.ApplicationConfig threw exception
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=TestBean,parent=GenericResource,qualifiers={},position=-1,optional=false,self=false,unqualified=null,734647163)
    at org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:74)
    at org.jvnet.hk2.internal.Utilities.justInject(Utilities.java:947)
    at org.jvnet.hk2.internal.ServiceLocatorImpl.inject(ServiceLocatorImpl.java:902)
    at org.jvnet.hk2.internal.ServiceLocatorImpl.createAndInitialize(ServiceLocatorImpl.java:977)
    at org.jvnet.hk2.internal.ServiceLocatorImpl.createAndInitialize(ServiceLocatorImpl.java:968)
    at org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:173)
    at org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:185)
    at org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:74)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:94)
    at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:63)
    at org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:263)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:297)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:254)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1028)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:372)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
    at java.lang.Thread.run(Thread.java:745)

I've an ear with one ejb module and one web module (the web module add ejb module as library).

The ejb module has this class:

package test.session;
import javax.ejb.Stateless;
import javax.inject.Named;
@Stateless
@Named
public class TestBean {
  public String getValue() {
    return "value";
  }
}

The web module has this classes:

package test.rest;
import java.util.Set;
import javax.ws.rs.core.Application;
@javax.ws.rs.ApplicationPath("webresources")
public class ApplicationConfig extends Application {
  @Override
  public Set<Class<?>> getClasses() {
    Set<Class<?>> resources = new java.util.HashSet<>();
    addRestResourceClasses(resources);
    return resources;
  }
  private void addRestResourceClasses(Set<Class<?>> resources) {
    resources.add(test.rest.GenericResource.class);
  }
}

and:

package test.rest;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import test.session.TestBean;
@Path("generic")
@Stateless
public class GenericResource {
  @Context
  private UriInfo context;
  @Inject
  TestBean testBean;
  public GenericResource() {
  }
  @GET
  @Produces("application/json")
  public String getXml() {
    //TODO return proper representation object
    return testBean.getValue();
 }
}

If I try to navigate:

http://localhost:8080/TestRest/webresources/generic

Glassfish 4.1 raise exception and Glassfish 4.0 works well...


Answer:

I had a similar problem. It's a bug as mentioned by @user993553, it tries to instantiate the EJB (GenericResource) of WAR Module from within the EJB Module.

A workaround is to convert your EJB from WAR Module to CDI. Just change @javax.ejb.Stateless to @javax.enterprise.context.RequestScoped or any other scope.

@Path("generic")
@javax.enterprise.context.RequestScoped
public class GenericResource 
{
    @Context
    private UriInfo context;

    @Inject
    TestBean testBean;

    public GenericResource() {}

    @GET
    @Produces("application/json")
    public String getXml() {
        // TODO return proper representation object
        return testBean.getValue();
    }
}

Question:

I want to use jersey framework. I´m running a web Service, using an ant app, on Java EE7. My application server is Glassfish

My method look like this:

 package mypackage.service;
        ...
         import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
        import org.glassfish.jersey.media.multipart.FormDataParam;

        @POST
        @Path("createSomething")
        @Consumes(MULTIPART_FORM_DATA)
        @Produces(APPLICATION_XML)
        public Response createSomething(@FormDataParam("upload") InputStream is, @FormDataParam("upload") FormDataContentDisposition formData, @QueryParam("some") String some,  @Context HttpServletRequest request) {

            String fileLocation = "C:\\UploadFile\\" + formData.getFileName();

        //more things, do not matter

            try {
                ctrl.saveFile(is, fileLocation);
                String result = "Successfully File Uploaded on the path " + fileLocation;
                return Response.status(Response.Status.OK).entity(result).build();
            } catch (IOException e) {
                e.printStackTrace();
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();

            }

I also have an application config:

package mypackage.service;

import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
import org.glassfish.jersey.media.multipart.MultiPartFeature;

@javax.ws.rs.ApplicationPath("")
public class ApplicationConfig extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        final Set<Class<?>> resources = new HashSet<>();
        addRestResourceClasses(resources);
        resources.add(MultiPartFeature.class);

        return resources;

    }

    /**
     * Do not modify addRestResourceClasses() method. It is automatically
     * populated with all resources defined in the project. If required, comment
     * out calling this method in getClasses().
     */
    private void addRestResourceClasses(Set<Class<?>> resources) {
        resources.add(mypackage.service.MYSERVICE.class);


    }

}

On myweb.xml I have:

<servlet>
    <servlet-name>ServletAdaptor</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>mypackage.service.ApplicationConfig</param-value>
    </init-param>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>mypackage.service</param-value>
    </init-param>
    <init-param>
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>org.glassfish.jersey.filter.LoggingFilter;org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
    </init-param>

    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>ServletAdaptor</servlet-name>
    <url-pattern>/createSomething/*</url-pattern>
</servlet-mapping>

I still get the same message:

Caused by: org.apache.catalina.LifecycleException: org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization. [[FATAL] No injection source found for a parameter of type public javax.ws.rs.core.Response

What I´m doing wrong??


Answer:

It works fine for me. Though I would completely get rid of the Application subclass. It is not needed, and may cause conflict/confusion. Your xml is sufficient configuration, just get rid of the javax.ws.rs.Application <init-param>. I would also look into making the multipart jars only compile-time jars (meaning not built into the war - they might conflict with Glassfish's version). I don't work much with Ant, so I'm not sure how you can do that, but I know it's possible.

Question:

I have a Glassfish 4 server running on a headless Debian VM. I can access the application just fine, but I cannot seem to access the admin port from anything other than localhost. I'd like to be able to access it so I can remotely deploy/debug from an IDE on another machine.

I've tried the asamin enable-secure-admin command, which completes but after restarting there is no change.

I've checked with netstat and Glassfish is only listening on port 4848 from localhost. Is there any other place remote admin is controlled from? Or something I'm missing?


Answer:

You need the following to administer Glassfish remotely:

  • set a non-blank password for all admin logins
  • enable secure admin
  • ensure the network listener is listening on the correct IP addresses (it could be set to listen only on the loopback interface)

Question:

I have a Java project that uses Java EE 7 and Glassfish 4.1

When I add a new Glassfish Descriptor to the project (via the right-click menu), it doesn't give me the ability to change the name of the xml file. It forces it to be sun-web.xml which is an old legacy format. I'm trying to use glassfish-web.xml.

How can I make it add the correct file?


Answer:

This should work if you are using Netbeans 8. If you are using an older version of Netbeans you should update to the latest version.

You can manually create a new xml file named glassfish-web.xml (or rename the sun-web.xml) and insert the following content:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app error-url="">
  <class-loader delegate="true"/>
  <jsp-config>
    <property name="keepgenerated" value="true">
    </property>
  </jsp-config>
</glassfish-web-app>

This is the content Netbeans creates by default.

Question:

I've search far and long and can't find the answer.

I'm using Glassfish and want to send an email via our smtp server.

I've obtained the server's certificate:

openssl s_client -connect mail.example.com:587 -starttls smtp > our.cer

I've cleaned up the cer file to only contain the certificate data. I've import it everywhere:

keytool -import -alias mail.example.com -file our.cer -keystore c:\Progra~1\Java\jre7\lib\security\cacerts
keytool -import -alias mail.example.com -file our.cer -keystore c:\Progra~1\Java\JDK17~1.0_4\jre\lib\security\cacerts
keytool -import -alias mail.example.com -file our.cer -keystore c:\PROGRA~1\GLASSF~1.0\GLASSF~1\domains\domain1\config\cacerts.jks

But I get the following error:

javax.mail.MessagingException: Could not convert socket to TLS;
    nested exception is:
        javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    ...
    Caused by...
    ...
    Caused by...
    ...
    Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

My code snippet:

...
Properties properties = System.getProperties();
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "mail.example.com");
properties.put("mail.smtp.user", "example@example.com");
properties.put("mail.smtp.password", "some.password");
properties.put("mail.smtp.port", "587"));
properties.put("mail.smtp.auth", "true"));
properties.put("mail.smtp.from", "example@example.com"));
properties.put("mail.transport", "smtp"));

...

Authenticator mailAuthenticator = new Authenticator()
{
    @Override
    protected PasswordAuthentication getPasswordAuthentication()
    {
        return new PasswordAuthentication(properties.getProperty("mail.smtp.user"),
                        properties.getProperty("mail.smtp.password"));
    }
};
try
{
    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties, mailAuthenticator);
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setSubject("Hallo world!");
    mimeMessage.setFrom(new InternetAddress(properties.getProperty("mail.smtp.from")));
    mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("example@example.com"));
    mimeMessage.setText("Some text message...");

    Transport transport = session.getTransport(properties.getProperty("mail.transport"));//"smtp"

    int port = Integer.parseInt(properties.getProperty("mail.smtp.port"));//587
    transport.connect(properties.getProperty("mail.smtp.host"),//"mail.example.com"
                    port,
                    properties.getProperty("mail.smtp.user"),//"example@example.com"
                    properties.getProperty("mail.smtp.password"));//Clear text password
    transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
    LOG.info("...done sending email");
}
catch (AddressException e)
{
    LOG.log(Level.SEVERE, "Error while sending email", e);
}
catch (MessagingException e)
{
    LOG.log(Level.SEVERE, "Error while sending email", e);
}
catch (Exception e)
{
    LOG.log(Level.SEVERE, "Error while sending email", e);
}

I've also tried Mkyong's suggestion to run InstallCert (source) against the mail server but I get:

javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?

UPDATE 1

I've loaded the certificate in the following additional places:

keytool -import -alias mail.example.com -file our.cer -keystore c:\PROGRA~1\GLASSF~1.0\GLASSF~1\domains\domain1\config\keystore.jks
keytool -import -alias mail.example.com -file our.cer -keystore c:\GLASSFISH\config\keystore.jks
keytool -import -alias mail.example.com -file our.cer -keystore c:\GLASSFISH\config\cacerts.jks

I've also set these properties:

System.setProperty("javax.net.ssl.keyStore", "c:\\GLASSFISH\\config\\keystore.jks");
System.setProperty("javax.net.ssl.keyStorePassword", "changeit");
System.setProperty("javax.net.ssl.trustStore", "c:\\GLASSFISH\\config\\cacerts.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");

I've also switched on debugging for ssl (Glassfish console, server, properties) javax.net.debug=ssl.

It works in a standalone test application (Java SE) but not in Glassfish.

UPDATE 2

Using the javax.net.debug=ssl and examining the log out put I can see that even-though I've loaded the certificate "everywhere" or if I point Glassfish to the java keystore, Glassfish is missing this certificate. The stand alone test app has it:

adding as trusted cert:
    Subject: CN=avast! Web/Mail Shield Root, O=avast! Web/Mail Shield, OU=generated by avast! antivirus for SSL/TLS scanning
    Issuer:  CN=avast! Web/Mail Shield Root, O=avast! Web/Mail Shield, OU=generated by avast! antivirus for SSL/TLS scanning
    Algorithm: RSA; Serial number: 0x14128fa09c50b64ba6d5c99875872673
    Valid from Wed Feb 04 08:56:17 CAT 2015 until Sat Feb 01 08:56:17 CAT 2025

(Note the Serial number...)

It seems to be the certificate missing from Glassfish; because the stand alone test app finds it:

Found trusted certificate:
[
[
    Version: V3
    Subject: CN=avast! Web/Mail Shield Root, O=avast! Web/Mail Shield, OU=generated by avast! antivirus for SSL/TLS scanning
    Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5

    Key:  Sun RSA public key, 2048 bits
    modulus: ---8<---
    public exponent: 65537
    Validity: [From: Wed Feb 04 08:56:17 CAT 2015, : Sat Feb 01 08:56:17 CAT 2025]
    Issuer: CN=avast! Web/Mail Shield Root, O=avast! Web/Mail Shield, OU=generated by avast! antivirus for SSL/TLS scanning
    SerialNumber: [    14128fa0 9c50b64b a6d5c998 75872673]

    ...

(Look at the SerialNumber...)

Please help


Answer:

Okey dokey! I've figured it out. Here is how my 5 day journey ended today, in brief...

First I dumped all the certificates from the Java keystore, as it was working using that keystore:

keytool -list -v -keystore c:\Progra~1\Java\jre7\lib\security\cacerts > allJavaCerts.txt

Then I dumped all the certificates from the Glassfish keystore, to see if the certificate was correctly imported:

keytool -list -v -keystore c:\WORKSP~1\GLASS\config\cacerts.jks > allGFCerts.txt

In the Java keystore list I notice that the mail server's certificate was issued by Avast... weird, right?

Issuer: CN=avast! Web/Mail Shield Root, O=avast! Web/Mail Shield, OU=generated by avast! antivirus for SSL/TLS scanning

And in the Java keystore list there is a certificate for Alias name: avastsslscannerroot but not in the Glassfish keystore list - Thank you Beyond Compare v3

So I exported the avastsslscannerroot certificate from the Java keystore and import it into the Glassfish keystore:

keytool -export -keystore c:\Progra~1\Java\jre7\lib\security\cacerts -alias avastsslscannerroot -file avastsslscannerroot.cer
keytool -import -alias avastsslscannerroot -file avastsslscannerroot.cer -keystore c:\WORKSP~1\GLASS\config\keystore.jks
keytool -import -alias avastsslscannerroot -file avastsslscannerroot.cer -keystore c:\WORKSP~1\GLASS\config\cacerts.jks

And now it works...

And then it didn't on the server... After some search I came across this:

mail.smtp.ssl.trust="*"

Property and it works for us as we are connection from our web server to our mail server...

Question:

The instructions for the Java EE tutorial specify to download and install the following :

Java SE SDK Java EE SDK Netbeans

I downloaded SE 8, EE 7 & Netbeans 8.0.2

Installed SE ok, and EE ok - it's essentially glassfish4. While installing Netbeans I'm instructed in the tutorial to NOT install glassfish and, when done with Netbeans to add glassfish to the Netbeans installation.

When I do so, I get the following message (I'm pointing @ c:\glassfish4\glassfish which is the correct path AFAIK)

Not a valid GlassFish Server installation.

I've seen another person in the last week with this same error, I looked into that problem and it said that there should be a file in a directory to solve the problem (C:\glassfish4\glassfish\config\glassfish.container). That file does exist on my system.

How does netbeans determine a valid Glassfish installation?

ETA: I followed zapl's advice below, reinstalled Netbeans with it's default Glassfish and, when I right click on Glassfish 4.1 Server, all options are greyed except Refresh and Remove (so, no start/stop, no view of Admin Console, Server Log or Update Center)


Answer:

I ran into the same problem. It is a known Netbeans-Bug: https://netbeans.org/bugzilla/show_bug.cgi?id=253008

There appear to be two solutions:

  1. Use a nightly Build Netbeans Version equal or higher than 201506180001

  2. In /glassfish/lib/install/applications/__admingui/WEB-INF/lib link (or copy) console-core-4.2-SNAPSHOT.jar to console-core-4.1.jar. After that netbeans is able to find the JAR file and add Glassfish nightly as a Glassfish 4.1 server.

I renamed the JAR as in solution 2 and now it works fine...

Hope this helps!

Question:

i use eclipse for my JavaEE project

its working fine, then my computer shutdown unexpectedly

then when i start glassfish server from eclipse

i receive following error

   Unable to start server due following issues:
   org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; 
   Content is not allowed in prolog.

how to fix it?

before my computer shutdown unexpectedly, everything is working fine with glassfish


Answer:

This error pops up when there are unexpected spaces or characters in xml file, it seems like your xml file(s) got corrupted. Most probably this one: -glassfish3/glassfish/domains/domain1/config/domain.xml

Referring solution provided on this link , the most appropriate thing that can be done seems to be, to create a new instance of the server and try deploying on it.

Question:

I have set my firewall setting for port 80, 8080, 4848. If on Glassfish I active listener for 80 it can't start and throws an error:

 Permission denied: 80=com.sun.enterprise.v3.services...

Answer:

The ports 0 up to 1023 are called well-known ports. Glassfish would have to be executed with root privileges in order to bind to this port.

Let Glassfish bind to 127.0.0.1:8080 or any other unprivileged port instead and use NGINX as a reverse proxy to map incoming requests on port 80 to your Glassfish server.

Question:

EJB application is deployed to Glassfish 3.1.2.2 on server A and servlet is deployed to Tomcat 7 on server B. Lookup from standalone app works fine, lookup from servlet throws NameNotFoundException. Set of libraries (from Glassfish modules directory) used in both cases is exactly the same. So we assume some additional configuration for Tomcat is required.

Relevant code from servlet deployed to Tomcat:

InitialContext ctx;
try {
   Properties props = new Properties();
   props.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");
   props.setProperty("org.omg.CORBA.ORBInitialPort", "3700");
   System.setProperty("java.security.auth.login.config", "jaas.config");
   ProgrammaticLogin pl = new ProgrammaticLogin();
   pl.login("user", "s3cret".toCharArray(), "file", true);
   ctx = new InitialContext(props);
   HelloBean helloBean = (HelloBean) ctx.lookup("java:global/HelloApp/HelloBeanImpl!app.hello.HelloBean");
} catch (Exception e) {
   e.printStackTrace(System.err);
}

Exception is always the same and there is no usefull information in getCause:

javax.naming.NameNotFoundException: Name [global/HelloApp/HelloBeanImpl!app.hello.HelloBean] is not bound in this Context. Unable to find [global].
   at org.apache.naming.NamingContext.lookup(NamingContext.java:819)
   at org.apache.naming.NamingContext.lookup(NamingContext.java:167)
   at org.apache.naming.SelectorContext.lookup(SelectorContext.java:156)
   at javax.naming.InitialContext.lookup(InitialContext.java:411)
   at app.servlet.HelloServlet.doGet(HelloServlet.java:28)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
   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:505)
   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:956)
   at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
   at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
   at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
   at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
   at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
   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)

Answer:

OK, we are able to lookup secured beans from Tomcat now. You will need to put a lot of Glassfish specific jars to classpath for this to work. We have used shared loader in catalina.properties to define path to jars from Glassfish modules directory (you will probably need to exclude all servlet and jsp jars to avoid conflict with Tomcat own lib). Also make sure you don't accidentally put two security.jar to classpath. The working config looks like this:

InitialContext ctx;
try {
    Properties props = new Properties();
    props.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");
    props.setProperty("org.omg.CORBA.ORBInitialPort", "3700");
    props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory");
    props.setProperty(Context.STATE_FACTORIES, "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
    props.setProperty(Context.URL_PKG_PREFIXES, "com.sun.enterprise.naming");
    System.setProperty("java.security.auth.login.config", "./jaas.config");
    ProgrammaticLogin pl = new ProgrammaticLogin();
    boolean loginSuccessfull = pl.login("username", "password".toCharArray());
    ctx = new InitialContext(props);
    HelloBean helloBean = (HelloBean) ctx.lookup("java:global/HelloApp/HelloBeanImpl!app.hello.HelloBean");
    resp.getOutputStream().print(helloBean.sayHelloTo("user"));
} catch (Exception e) {
    e.printStackTrace(System.err);
}

Question:

I can't understand why i can't up my REST service. The exception tell something about JPA, but doesn't give much info about what causes it.

If a type in the address bar the url: localhost:8080/UsersControl/api/all, GlassFish returns an 404 error.

User entity:

@Entity
@Table(name="users")
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="user_id")
    private Short id;
    @Column(name="names")
    private String names;
    @Column(name="surnames")
    private String surnames;
    @Column(name="dni")
    private String dni;
    @Column(name="birth_date")
    @Temporal(TemporalType.DATE)
    private Date birthDate;
    @Column(name="address")
    private String address;
    @Column(name="state")
    private Boolean state;

    public User() {

    }
    public User(Short id, String names, String surnames, String dni, Date birthDate, String address) {
        this.id = id;
        this.names = names;
        this.surnames = surnames;
        this.dni = dni;
        this.birthDate = birthDate;
        this.address = address;
    }
    public Short getId() {
        return id;
    }
    public void setId(Short id) {
        this.id = id;
    }
    public String getNames() {
        return names;
    }
    public void setNames(String names) {
        this.names = names;
    }
    public String getSurnames() {
        return surnames;
    }
    public void setSurnames(String surnames) {
        this.surnames = surnames;
    }
    public String getDni() {
        return dni;
    }
    public void setDni(String dni) {
        this.dni = dni;
    }
    public Date getBirthDate() {
        return birthDate;
    }
    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public Boolean getState() {
        return state;
    }
    public void setState(Boolean state) {
        this.state = state;
    }
    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }
    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof User)) {
            return false;
        }
        User other = (User) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

}

User login entity

@Entity
@Table(name="user_login")
public class UserLogin implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="user_login_id")
    private Short id;
    @ManyToOne
    @JoinColumn(name="user_id")
    private User user;
    @Column(name="username")
    private String username;
    @Column(name="password")
    private String password;

    public Short getId() {
        return id;
    }
    public void setId(Short id) {
        this.id = id;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }
    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof UserLogin)) {
            return false;
        }
        UserLogin other = (UserLogin) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

}

Abstract GenericDao implementation

public abstract class GenericDaoImpl<T, PK extends Serializable> implements GenericDao<T, PK> {

    @PersistenceContext(unitName="ControlUsuarios-ServidorPU")
    protected EntityManager em;
    protected Class<T> clazz;

    public GenericDaoImpl() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass()
            .getGenericSuperclass();
       this.clazz = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
    }
    @Override
    public T save(T t) {
        em.persist(t);
        return t;
    }
    @Override
    public T update(T t) {
        em.persist(t);
        return t;
    }
    @Override
    public T remove(T t) {
        em.remove(t);
        return t;
    }
    @Override
    public T find(PK id) {
        T t = (T) em.find(clazz, id);
        return t;
    }
    public abstract List<T> findAll();

}

User DAO

@RequestScoped
public class UserDao extends GenericDaoImpl<User, Short> implements Serializable {

    public UserDao() {
        super();
    }    
    @Override
    public List<User> findAll() {
        Query query = em.createNamedQuery("SELECT u FROM u");
        List<User> users = (List<User>) query.getResultList();
        return users;
    }

}

My WebService

@Path("/api")
public class UserService {   
    @Inject
    UserDao userDao;

    @POST
    @Path("/save")
    @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public void save(JSONObject user) {
        /*List<Object> userData = (List<Object>) user.get("user");
        for(Object o : userData) {
            System.out.println(o.getClass().getName());
        }*/
        System.out.println(user == null);
    }
    @PUT
    @Path("/update")
    @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public void update(JSONObject user) {

    }
    @DELETE
    @Path("/remove/{id}")
    public void delete(@PathParam("id") Short id) {

    }
    @GET
    @Produces(MediaType.TEXT_HTML)
    @Path("/all")
    public String findAll() {
        System.out.println("Recuperar todos!");
        return "<p>Accediendo a todos los usuarios...</p>";
    }
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/find/{i}")
    public void find(@PathParam("id") Short id) {

    }

}

persistence.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.1" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="ControlUsuarios-ServidorPU" transaction-type="JTA">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <jta-data-source>jdbc/userscontrol</jta-data-source>

    <class>com.company.userscontrol.model.entities.User</class>
    <class>com.company.userscontrol.model.entities.UserLogin</class>  

    <properties>
      <property name="javax.persistence.schema-generation.database.action" value="none"/>
    </properties>
  </persistence-unit>
</persistence>

web.xml

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

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">
    <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>com.company.userscontrol.rest</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey REST Service</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>

</web-app>

When run the application, GlassFish throw the follow exception:

Advertencia:   Exception while dispatching an event
java.lang.NullPointerException
    at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.getStatus(JtaStatusHelper.java:76)
    at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.isActive(JtaStatusHelper.java:118)
    at org.hibernate.engine.transaction.internal.jta.CMTTransaction.join(CMTTransaction.java:149)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.joinTransaction(AbstractEntityManagerImpl.java:1602)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.postInit(AbstractEntityManagerImpl.java:210)
    at org.hibernate.jpa.internal.EntityManagerImpl.<init>(EntityManagerImpl.java:91)
    at org.hibernate.jpa.internal.EntityManagerFactoryImpl.internalCreateEntityManager(EntityManagerFactoryImpl.java:345)
    at org.hibernate.jpa.internal.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:313)
    at org.glassfish.persistence.jpa.JPADeployer$2.visitPUD(JPADeployer.java:451)
    at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:510)
    at org.glassfish.persistence.jpa.JPADeployer.iterateInitializedPUsAtApplicationPrepare(JPADeployer.java:492)
    at org.glassfish.persistence.jpa.JPADeployer.event(JPADeployer.java:398)
    at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:131)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:487)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
    at org.glassfish.deployment.admin.ReDeployCommand.execute(ReDeployCommand.java:131)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
    at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
    at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
    at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:189)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
    at java.lang.Thread.run(Thread.java:745)

Info extra: I put this libraries into my project:

¿What i'm doing wrong? I appreciate your help and time.


Answer:

I guess this is only half an answer, as it doesn't solve the exception problem, but apparently the REST app still runs, with the following fix.

From comment:

Not sure about the exception, put your path is wrong. You define /api/ as the root application path in the web.xml. Then you define /api again in the @Path for the UserService. So it should be /api/api. But you most likely want to change the @Path to /users and use /api/users

Question:

I'm trying to implement Java EE websockets with a Glassfish server, and I've got the basics down already.

As for my current project, I want to implement server "ticks" like in a game, that update the server every few milliseconds so that all sessions connected to the server see the same thing.

However, I don't know where to start to make this work with Glassfish. I know that I create a server from scratch and implement a timer method, but I'd rather save myself some work here if possible.

Simply put, is it easy to implement a timer/tick mechanism in the glassfish server (assuming it is running)?

For example, I want to make the server periodically send the word "hello" to a client HTML page once they are connected via websocket.


Answer:

Short Version

We solved it with three classes:

  1. Scheduler class: the clock which send an Event
  2. Websocket endpoint: the basic websocket session handler
  3. Websocket session handler: the conductor which catches the Event and manages all the websocket sessions

Long version with code

Now for the code, 1) is the one Mike mentioned in comment: a classic Scheduler which fires some event. This class is basically a clock which knocks whoever is listening to its event. We have a EAR=EJB+WAR project. Our timer is in the EJB module but if you have a single WAR, you can put it there.

// some import
import javax.enterprise.event.Event;

@Singleton
@Startup
public class TimerBean {

    @Inject
    private Event<TickEvent> tickEvent;

    @Schedule(hour = "*", minute = "*", second = "*/5")
    public void printSchedule() {
        tickEvent.fire(new TickEvent(/*...your initialization...*/));
    }

    public class TickEvent{
        // we have some info here but you can 
        // leave it empty.
    }

}

For the 2) websocket endpoint, this is a very academic endpoint. Don't forget that one connection = one endpoint instance. You can find all opened sessions from a given session with session.getOpenedSessions() but I'll explain why I use a handler in the next part.

// some import
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;

@ServerEndPoint(value = "/myEndPointPath")
public class TickEndPoint{

    @Inject
    private TickSessionHandler sessionHandler;

    @OnOpen
    public void onOpen(Session session){
        sessionHandler.addSession(session);
    }

    @OnClose
    public void onClose(Session session, CloseReason reason){
         sessionHandler.removeSession(session);
    }

}

And now the keystone: the session handler. The session handler is an ApplicationScoped bean, so it's always available. The reason I used it:

  1. When TickEvent is fired, you don't know if a TickEndPoint instance exists or not so the event catching may raise some stupid errors. We fixed it with @Observes(notifyObserver = Reception.IF_EXISTS) but we met other EJB problems which I'll detail in 2.
  2. For a reason I haven't identified yet, when I used @Observes in my @ServerEndPoint, all my @EJB injection failed so I switched @EJB injection to @Inject. But as the ApplicationScoped is a CDI bean, @EJB and @Observes work very well together in the session handler class. We didn't really need the @EJB annotation by itself but for design consistency with other bean, we wanted all our EJB to be annotated with @EJB.
  3. Monitoring: you can do monitoring such as how many "hello" you sent at time T, giving you a time vs number of connected sessions graph.

Plus, in our particular situation, we have some point that you may meet later.

  1. We need to select a particular subset of SESSIONS, not all of them. Having a static Set in the @ServerEndPoint led to some-stuff-which-turned-me-into-Hulk behavior especially when you have EJB dependencies. In an example of a game, let's you have capture the flag scenario with blue team and red team. If red team capture the flag, you need to send "Oops, we lost the flag" to the blue team and "Yeah we got it" to the red team.
  2. Monitoring: apart from connection time and stuff, we need info such as "last activity time" and stuff. To properly put it in a JSF datatable, a list/set in a CDI bean is the best option
  3. I encountered some tutorial/detail where the @ServerEndPoint is annotated @ApplicationScoped. By design (one server endpoint = one websocket connection), I don't feel comfortable with it so I refused to implement this solution

    @Named
    @ApplicationScoped
    public class TickSessionHandler{
    
        // There is no need to have a static Set, worst,
        // containers don't like it
        public Set<Session> SESSIONS;
    
        // let's initialize the set
        public TickSessionHandler{
            this.SESSIONS = new HashSet<>();
        }
    
        // ---------- sessions management
        public void addSession(Session session){
            this.SESSIONS.add(session);
        }
    
        public void removeSession(Sesssion session){
            this.SESSIONS.remove(session);
        }
    
        // ---------- Listen to the timer
        public void onTick(@Observes TickEvent event){
    
            // if required, get the event attribute
            // and proceed
    
            // your request:
            this.SESSIONS.forEach(session -> {
                session.getBasicRemote().sendText("hello");
            });
        }
    
    }
    

Hope this help. The explanation seems long but the core implementation is actually very light. AFAIK, there is no shortcut for such requirement.

Question:

I am trying to make a web application that listens to a websocket and when a message arrives it receives it and send it again on a "normal" socket java.net.Socket so another server application would listen and receive it.

Here is the code for my Web Application

@ServerEndpoint("/messageendpoint")
public class WebListener {
    private static Set<Session> peers = Collections.synchronizedSet(new HashSet<Session>());
    public static Session thisPeer;
    public static Socket socket;
    public static PrintWriter writer;
    public static OutputStream output1;


    @OnOpen
    public void onOpen (Session peer) {
        peers.add(peer);
        try {
            socket = new Socket("localhost", 9003);
            output1 = socket.getOutputStream();
            writer = new PrintWriter(output1);

        } catch (IOException e) {
            e.printStackTrace();
        }
        sendMessage("hello",peer);
        System.out.println("an opening");

    }

    @OnMessage
    public String onMessage(String message, Session session) {
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>"+message);
        try {
                writer.println("vvvvvvvvvvvvvv");
            } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @OnClose
    public void onClose (Session peer) {
        peers.remove(peer);

    }
}

and This is the code of the the other server which listens to the socket on port 9003

public class Buffer {
    public static void main(String []args){

        DataInputStream dis;
        PrintStream ps;
        BufferedReader in;
        try {
            ServerSocket serverSocket = new ServerSocket(9003);
            Socket socket = serverSocket.accept();
            //dis = new DataInputStream(socket.getInputStream());
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while(true) {
                String str = dis.readLine();
                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

What i expect from the code is that the server application should receive the message and print it on the screen. What happens is the second application receives nothing (not even null)

The same code runs perfectly and the message is received if i replaced the Web Socket Application with this simple code.

public class TestSender {
    public static void main(String []args){
        Socket socket = null;
        try {
            socket = new Socket("localhost", 9003);
            OutputStream output1 = socket.getOutputStream();
            PrintWriter writer =  new PrintWriter(output1);
            while (true) {
                writer.println("hello");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

which led me to think that the problem is in my understanding of javax.websocket library.


Answer:

As mentioned in the comment above, PrintWriter is buffered by default and the default buffer size is typically fairly large (8192 bytes). In addition to that, automatic flushing (on newline) of the PrintWriter is off by default.

Since you never flush() the writer and thus force output to be written, the PrintWriter probably has your data still hidden in its buffer. This is also evidenced by the fact that continuous output seems to work.

Hence:

writer.println("vvvvvvvvvvvvvv");
writer.flush();
// ^^^^^^^ add this

Question:

When GreeterEJB builds as a JAR, it doesn't build with a libs folder for dependencies:

thufir@doge:~$ 
thufir@doge:~$ ll NetBeansProjects/GreeterEJB/dist/
total 20
drwxrwxr-x 2 thufir thufir 4096 Feb 25 14:34 ./
drwxrwxr-x 6 thufir thufir 4096 Feb 25 14:34 ../
-rw-rw-r-- 1 thufir thufir 2802 Feb 25 14:34 GreeterEJB.jar
thufir@doge:~$ 

However, when it deploys, Glassfish gives the following error:

Error in annotation processing: {0}.
java.lang.NoClassDefFoundError: net/bounceme/doge/greeter/ejb/GreeterRemote

because, I think, it can't find the GreeterRemote class, as that class is in a different JAR:

thufir@doge:~$ 
thufir@doge:~$ jar -tf NetBeansProjects/GreeterLibrary/dist/GreeterLibrary.jar | grep class
net/bounceme/doge/greeter/ejb/GreeterRemote.class
thufir@doge:~$ 

What's the nature of this dependency? How is this different from adding a class to the classpath of project? At least in Netbeans, when, for example, a JDBC driver is added to the classpath, that driver will show up in the libs folder alongside the JAR which was built.

the ejb:

package net.bounceme.doge.greeter.ejb;

import javax.ejb.Stateless;

@Stateless
public class GreeterBean implements GreeterRemote {

    @Override
    public String greeting() {
        return "hello remote world";
    }

}

greeter remote interface:

package net.bounceme.doge.greeter.ejb;

import javax.ejb.Remote;

@Remote
public interface GreeterRemote {

    String greeting();

}

The GreeterLibrary JAR file added to glassfish:

thufir@doge:~$ 
thufir@doge:~$ ll glassfish-4.1/glassfish/lib/*.jar
-rw-r--r-- 1 thufir thufir    2694 Feb 22 18:56 glassfish-4.1/glassfish/lib/appserv-rt.jar
-rw-rw-r-- 1 thufir thufir   20020 Feb 25 06:06 glassfish-4.1/glassfish/lib/EJBRemoteInterface.jar
-rw-r--r-- 1 thufir thufir   22189 Feb 22 18:56 glassfish-4.1/glassfish/lib/gf-client.jar
-rw-r--r-- 1 thufir thufir    3193 Feb 22 18:56 glassfish-4.1/glassfish/lib/javaee.jar
-rw-r--r-- 1 thufir thufir    1398 Feb 22 18:56 glassfish-4.1/glassfish/lib/jndi-properties.jar
-rw-r--r-- 1 thufir thufir 1006015 Feb 23 16:58 glassfish-4.1/glassfish/lib/mysql-connector-java.jar
thufir@doge:~$ 
thufir@doge:~$ ll glassfish-4.1/glassfish/domains/domain1/lib/*.jar
-rw-rw-r-- 1 thufir thufir 20020 Feb 25 06:06 glassfish-4.1/glassfish/domains/domain1/lib/EJBRemoteInterface.jar
thufir@doge:~$ 
thufir@doge:~$ ll glassfish-4.1/glassfish/domains/domain1/lib/classes/*.jar
-rw-rw-r-- 1 thufir thufir 20020 Feb 25 06:06 glassfish-4.1/glassfish/domains/domain1/lib/classes/EJBRemoteInterface.jar
thufir@doge:~$ 

I recall doing something like this before with remote interfaces, but I seem to have forgotten a key step with the remote interface, and, at the moment, cannot find the right Google terms. I'm sure somewhere in the Glassfish manual there's a section on EJB dependencies and where they go...

Right now, I just want to know the nature or type of dependency this is so that I at least know what to Google for.


Answer:

You don't want to place the dependencies you developed on your own inside the Glassfish lib folder. This may be sufficient for productive usage, but not for development.

To do it right, you need an EAR.

Inside the EAR, you can create a lib folder for your dependencies.

The EAR structure will look similar to this:

/EAR
/EAR/GreeterEJB.jar
/EAR/lib
/EAR/lib/GreeterLibrary.jar

Question:

First i had to suffer to make the icalcs grant full permissions to everyone in a folder as i didn't know that i should write "Tout le monde" instead of "everyone" as my windows 7 language is french and actually i needed this command for that i can unzip a zip file in the same permissions altered folder.

the code of my batch file is the following :

call xcopy glassfish-4.1.zip C:\Users\Feki\Desktop\vvv2
icacls C:\Users\Feki\Desktop\vvv2 /grant "Tout le monde":f
call C:\Program Files\Java\jdk1.7.0_40\bin>jar xf C:\Users\Feki\Desktop\vvv2\glassfish-4.1.zip
ECHO.
ECHO Press any key to exit. 
pause>null

the log indicated that the icalcs was successful but when the extraction starts i got an ' access denied' message

---- EDIT ----

i've tried to make sure that i have all permission granted on the zip file to extract so i added

icacls C:\Users\Feki\Desktop\vvv2\* /grant "Tout le monde":f

after the first icacls but the extraction still didn't work


Answer:

First I want to say that I think your script looks a little bit weired.

In the first line

call xcopy glassfish-4.1.zip C:\Users\Feki\Desktop\vvv2

you are copying the zip file to a folder on the Desktop, this already requires write access rights in C:\Users\Feki\Desktop\vvv2 or it won't work.

In the next line you try to set the access rights for this folder:

icacls C:\Users\Feki\Desktop\vvv2 /grant "Tout le monde":f

As described, this doesn't make much sense because you already have written the zip file to this folder, therefore you must have at least write access rights.

Now to the problem, the call:

call C:\Program Files\Java\jdk1.7.0_40\bin>jar xf C:\Users\Feki\Desktop\vvv2\glassfish-4.1.zip

is something which shouldn't work anyway because there is a space between Program and Files. I don't know what this bin>jar should be but if this works for you, then you may use it in this way.

I would write it like this:

call "%ProgramFiles%\Java\jdk1.7.0_40\bin\jar.exe" xf C:\Users\Feki\Desktop\vvv2\glassfish-4.1.zip

If this call gives you an Access denied. message then you probably don't have write access rights in the current path of the command line.

Note that the jar utility will extract the content of the zip file to the current path of the command line. That means if you are in c:\ then it will extract the content to c:\ and if you are in c:\bla\ then it will extract the content to c:\bla\. (It doesn't make a difference if you call it with the full path or only jar when it is in your PATH var.)

So this looks like you don't have the right access rights in the path where your glassfish-4.1.zip is, because this is the current path of your command line. I guess you want to extract the content to the folder on the Desktop. To do this, just change the current path to this folder before issuing the extract call.

I guess the script could look like this:

call xcopy glassfish-4.1.zip C:\Users\Feki\Desktop\vvv2
cd C:\Users\Feki\Desktop\vvv2\
call "%ProgramFiles%\Java\jdk1.7.0_40\bin\jar.exe" xf glassfish-4.1.zip

See also:

  • creating batch script to unzip a file without additional zip tools
  • Unjar to a specific destination
  • Extracting .jar file with command line

Question:

How do I run the appclient outside of the IDE? While it seems possible to run stand-alone JNDI lookup apps from the CLI with appclient, it doesn't appear to work for ACC clients. However, it should be possible:

Running an Application Client

Using the appclient Script To run an application client, you can launch the ACC using the appclient script, whether or not Java Web Start is enabled.

GlassFish Server Open Source Edition Application Development Guide Release 4.0 Developing Java Clients 10-15 page 186

Steps:

1.) created an @Remote interface as a Java SE library API

2.) created an Enterprise Application with an ejb module; add the interface API

3.) in the ejb module, implement the @Remote interface

4.) create an ACC app; add the interface API; add to the Enterprise Application

5.) insert the ejb from the IDE

6.) deploy the EAR and then run the ACC client from the IDE

This is adapted from Creating and Running an Application Client on the GlassFish Server.

running with ant, "ant run" from the CLI:

-run:
     [java] 2

run:

BUILD SUCCESSFUL
Total time: 28 seconds
thufir@dur:~/NetBeansProjects/SingletonACC$ 

which is the correct output, in this case. (Each time the client runs, the integer increases by one.)

I've looked through the ant files, but wasn't able to decipher what "ant run" does in this case:

   <!--
                =================
                EXECUTION SECTION
                =================
            -->
    <target depends="dist,run-deploy,-as-retrieve-option-workaround,-init-run-macros,-run-pregfv3,-run" description="Run a main class." name="run"/>
    <target if="j2ee.appclient.tool.args" name="-run-pregfv3">
        <carproject:run-appclient-pregfv3/>
    </target>
    <target name="-run" unless="j2ee.appclient.tool.args">
        <carproject:run-appclient/>
    </target>
    <target depends="dist,run-deploy,-as-retrieve-option-workaround,-init-run-macros,-run-single-pregfv3,-run-single" description="Run a single class." name="run-single"/>
    <target depends="dist,run-deploy,-as-retrieve-option-workaround,-init-run-macros" name="-run-single" unless="j2ee.appclient.tool.args">
        <fail unless="run.class">Must select one file in the IDE or set run.class</fail>
        <carproject:run-appclient serverparams="${j2ee.appclient.tool.jvmoptions.class}${run.class}"/>
    </target>
    <target depends="dist,run-deploy,-as-retrieve-option-workaround,-init-run-macros" if="j2ee.appclient.tool.args" name="-run-single-pregfv3">
        <fail unless="run.class">Must select one file in the IDE or set run.class</fail>
        <carproject:run-appclient-pregfv3/>
    </target>
    <target depends="init" name="-init-run-macros">
        <macrodef name="run-appclient" uri="http://www.netbeans.org/ns/car-project/1">
            <attribute default="${application.args.param}" name="args"/>
            <attribute default="${j2ee.appclient.tool.jvmoptions}${client.jar}" name="serverparams"/>
            <element name="customize" optional="true"/>
            <sequential>
                <java dir="${basedir}" fork="true" jar="${client.jar}">
                    <jvmarg line="${endorsed.classpath.cmd.line.arg}"/>
                    <jvmarg line="@{serverparams}"/>
                    <jvmarg line="${run.jvmargs.param}"/>
                    <arg line="@{args}"/>
                    <syspropertyset>
                        <propertyref prefix="run-sys-prop."/>
                        <mapper from="run-sys-prop.*" to="*" type="glob"/>
                    </syspropertyset>
                    <env key="APPCPATH" path="${javac.classpath}"/>
                    <sysproperty key="java.system.class.loader" value="org.glassfish.appclient.client.acc.agent.ACCAgentClassLoader"/>
                    <customize/>
                </java>
            </sequential>
        </macrodef>
        <macrodef name="run-appclient-pregfv3" uri="http://www.netbeans.org/ns/car-project/1">
            <element name="customize" optional="true"/>
            <sequential>
                <java classname="${j2ee.appclient.tool.mainclass}" fork="true">
                    <jvmarg line="${endorsed.classpath.cmd.line.arg}"/>
                    <jvmarg line="${j2ee.appclient.tool.jvmoptions}"/>
                    <jvmarg line="${run.jvmargs.param}"/>
                    <arg line="${j2ee.appclient.tool.args}"/>
                    <arg line="-client ${client.jar}"/>
                    <arg line="${application.args.param}"/>
                    <classpath>
                        <path path="${j2ee.platform.classpath}:${j2ee.appclient.tool.runtime}"/>
                    </classpath>
                    <syspropertyset>
                        <propertyref prefix="run-sys-prop."/>
                        <mapper from="run-sys-prop.*" to="*" type="glob"/>
                    </syspropertyset>
                    <customize/>
                </java>
            </sequential>
        </macrodef>
    </target>
    <target if="j2ee.appclient.mainclass.args" name="-as-retrieve-option-workaround" unless="j2ee.clientName">
        <property name="client.jar" value="${dist.dir}/SingletonACCClient.jar"/>
        <sleep seconds="3"/>
        <copy failonerror="false" file="${wa.copy.client.jar.from}/SingletonACC/SingletonACCClient.jar" todir="${dist.dir}"/>
        <copy failonerror="false" flatten="true" todir="${dist.dir}/">
            <fileset dir="${wa.copy.client.jar.from}/SingletonACC" includes="**/SingletonACCClient.jar"/>
        </copy>
        <copy flatten="true" todir="${dist.dir}/SingletonACCClient">
            <fileset dir="${wa.copy.client.jar.from}/SingletonACC" includes="**/*.*ar"/>
        </copy>
        <copy failonerror="false" flatten="false" todir="${dist.dir}/SingletonACCClient">
            <fileset dir="${dist.dir}/gfdeploy/SingletonACC" includes="**/*.jar"/>
        </copy>
    </target>
    <target name="pre-run-deploy">
        <!-- Empty placeholder for easier customization. -->
        <!-- You can override this target in the ../build.xml file. -->
    </target>
    <target name="post-run-deploy">
        <!-- Empty placeholder for easier customization. -->
        <!-- You can override this target in the ../build.xml file. -->
    </target>
    <target name="-pre-nbmodule-run-deploy">
        <!-- Empty placeholder for easier customization. -->
        <!-- This target can be overriden by NetBeans modules. Don't override it directly, use -pre-run-deploy task instead. -->
    </target>
    <target name="-post-nbmodule-run-deploy">
        <!-- Empty placeholder for easier customization. -->
        <!-- This target can be overriden by NetBeans modules. Don't override it directly, use -post-run-deploy task instead. -->
    </target>
    <target name="-run-deploy-am">
        <!-- Task to deploy to the Access Manager runtime. -->
    </target>
    <target depends="init,compile,dist,pre-run-deploy,-pre-nbmodule-run-deploy,-run-deploy-nb,-init-deploy-ant,-deploy-ant,-run-deploy-am,-post-nbmodule-run-deploy,post-run-deploy,-do-update-breakpoints" name="run-deploy"/>
    <target if="netbeans.home" name="-run-deploy-nb">
        <nbdeploy clientUrlPart="${client.urlPart}" debugmode="false" forceRedeploy="${forceRedeploy}"/>
    </target>
    <target name="-init-deploy-ant" unless="netbeans.home">
        <property name="deploy.ant.archive" value="${dist.jar}"/>
        <property name="deploy.ant.resource.dir" value="${resource.dir}"/>
        <property name="deploy.ant.enabled" value="true"/>
    </target>
    <target depends="init,-run-undeploy-nb,-init-deploy-ant,-undeploy-ant" name="run-undeploy"/>
    <target if="netbeans.home" name="-run-undeploy-nb">
        <fail message="Undeploy is not supported from within the IDE"/>
    </target>
    <target depends="run-deploy,-init-display-browser,-display-browser-nb,-display-browser-cl" name="run-display-browser"/>
    <target if="do.display.browser" name="-init-display-browser">
        <condition property="do.display.browser.nb">
            <isset property="netbeans.home"/>
        </condition>
        <condition property="do.display.browser.cl">
            <and>
                <isset property="deploy.ant.enabled"/>
                <isset property="deploy.ant.client.url"/>
            </and>
        </condition>
    </target>
    <target if="do.display.browser.nb" name="-display-browser-nb">
        <nbbrowse url="${client.url}"/>
    </target>
    <target if="do.display.browser.cl" name="-get-browser" unless="browser">
        <condition property="browser" value="rundll32">
            <os family="windows"/>
        </condition>
        <condition else="" property="browser.args" value="url.dll,FileProtocolHandler">
            <os family="windows"/>
        </condition>
        <condition property="browser" value="/usr/bin/open">
            <os family="mac"/>
        </condition>
        <property environment="env"/>
        <condition property="browser" value="${env.BROWSER}">
            <isset property="env.BROWSER"/>
        </condition>
        <condition property="browser" value="/usr/bin/firefox">
            <available file="/usr/bin/firefox"/>
        </condition>
        <condition property="browser" value="/usr/local/firefox/firefox">
            <available file="/usr/local/firefox/firefox"/>
        </condition>
        <condition property="browser" value="/usr/bin/mozilla">
            <available file="/usr/bin/mozilla"/>
        </condition>
        <condition property="browser" value="/usr/local/mozilla/mozilla">
            <available file="/usr/local/mozilla/mozilla"/>
        </condition>
        <condition property="browser" value="/usr/sfw/lib/firefox/firefox">
            <available file="/usr/sfw/lib/firefox/firefox"/>
        </condition>
        <condition property="browser" value="/opt/csw/bin/firefox">
            <available file="/opt/csw/bin/firefox"/>
        </condition>
        <condition property="browser" value="/usr/sfw/lib/mozilla/mozilla">
            <available file="/usr/sfw/lib/mozilla/mozilla"/>
        </condition>
        <condition property="browser" value="/opt/csw/bin/mozilla">
            <available file="/opt/csw/bin/mozilla"/>
        </condition>
    </target>
    <target depends="-get-browser" if="do.display.browser.cl" name="-display-browser-cl">
        <fail unless="browser">
                    Browser not found, cannot launch the deployed application. Try to set the BROWSER environment variable.
                </fail>
        <property name="browse.url" value="${deploy.ant.client.url}${client.urlPart}"/>
        <echo>Launching ${browse.url}</echo>
        <exec executable="${browser}" spawn="true">
            <arg line="${browser.args} ${browse.url}"/>
        </exec>
    </target>
    <target depends="dist" name="verify">
        <nbverify file="${dist.jar}"/>
    </target>
    <target depends="init,compile-single" name="run-main">
        <fail unless="run.class">Must select one file in the IDE or set run.class</fail>
        <carproject:java classname="${run.class}"/>
    </target>
    <target depends="init" if="netbeans.home" name="-do-update-breakpoints">
        <carproject:nbjpdaappreloaded/>
    </target>

How can I replicate "ant run" outside of the IDE?

note that SingletonAcc is deployed individually, even though it's also part of the SingletonQueue Enterprise Application, which also has an appclient.

thufir@dur:~/NetBeansProjects/SingletonACC$ 
thufir@dur:~/NetBeansProjects/SingletonACC$ /home/thufir/glassfish-4.1/glassfish/bin/asadmin list-applications
SingletonQueue  <ear, appclient, ejb>  
SingletonACC    <appclient>            
Command list-applications executed successfully.
thufir@dur:~/NetBeansProjects/SingletonACC$ 

Answer:

You can enable verbose logging in ant so you can see what it is actually executing:

In NetBeans go to Options -> Tools -> Java -> Ant and set the Verbosity Level to Debug.

It looks like ant just deploys the appclient (EntAppClient.jar) on GlassFish and then runs the file EntAppClientClient.jar (notice the double Client) with some parameters similar to this:

/java/jdk1.7.0/jre/bin/java.exe 
-Xbootclasspath/p:/NetBeans/enterprise/modules/ext/javaee6-endorsed/javax.annotation.jar;/NetBeans/enterprise/modules/ext/javaee6-endorsed/jaxb-api-osgi.jar;/NetBeans/enterprise/modules/ext/javaee6-endorsed/webservices-api-osgi.jar 
-Djava.endorsed.dirs=/glassfish410/glassfish/lib/endorsed;/glassfish410/glassfish/modules/endorsed 
-javaagent:/glassfish410/glassfish/lib/gf-client.jar=mode=acscript,arg=-configxml,arg=/glassfish410/glassfish/domains/domain1/config/glassfish-acc.xml,client=jar=dist/EntAppClientClient.jar 
-Djava.system.class.loader=org.glassfish.appclient.client.acc.agent.ACCAgentClassLoader 
-jar /EntAppClient/dist/EntAppClientClient.jar

Hope this helps :)

Question:

When I try to ping Oracle 11g from Glassfish 3 admin console I get the following exception:

Caused by: java.security.AccessControlException: access denied ("java.util.PropertyPermission" "javax.net.ssl.keyStorePassword" "read")
       at com.sun.enterprise.security.ssl.SSLUtils.checkPermission(SSLUtils.java:336)
       at com.sun.enterprise.security.J2EESecurityManager.checkProperty(J2EESecurityManager.java:146)
       at com.sun.enterprise.security.J2EESecurityManager.checkPropertyAccess(J2EESecurityManager.java:131)
       at java.lang.System.getProperty(System.java:744)
       at oracle.jdbc.driver.PhysicalConnection$1.run(PhysicalConnection.java:3117)
       at java.security.AccessController.doPrivileged(Native Method)
       at oracle.jdbc.driver.PhysicalConnection.getSystemProperty(PhysicalConnection.java:3113)
       at oracle.jdbc.driver.PhysicalConnection.readConnectionProperties(PhysicalConnection.java:1300)
       at oracle.jdbc.driver.PhysicalConnection.(PhysicalConnection.java:517)
       at oracle.jdbc.driver.T4CConnection.(T4CConnection.java:228)
       at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
       at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:521)
       at oracle.jdbc.pool.OracleDataSource.getPhysicalConnection(OracleDataSource.java:280)
       at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:207)
       at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:157)
       at com.sun.gjc.spi.DSManagedConnectionFactory.createManagedConnection(DSManagedConnectionFactory.java:115)
       at com.sun.enterprise.resource.allocator.LocalTxConnectorAllocator.createResource(LocalTxConnectorAllocator.java:87)
       at com.sun.enterprise.resource.pool.ConnectionPool.createSingleResource(ConnectionPool.java:907)
       ... 61 more

Standalone app with the same JDBC driver works just fine. I am running Glassfish 3.1.2 on my local Ubuntu 12.04 box with Oracle 11g XE deployed as Docker image. I have AppArmor stopped, no firewalls active and no idea what it has to do with SSL. I also try to add javax.net.ssl.keyStorePassword permission to Glassfish server.policy and JDK java.policy files but it didn't fix the issue.

The same Glassfish instance has a MySQL pool and there is no such error. May be I need to configure something on the Oracle server to make it work?


Answer:

This error was resolved by putting Oracle JDBC driver jar file to ../glassfish/lib instead of ../domain1/lib.

Question:

I'm working using OAuth 2.0 to authenticate to a Google's API and everything works just fine in my local GlassFish. The problem begins when I'm deploying to the DEV's GlassFish, which throws me the following exception:

com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request { "error" : "invalid_grant" }

This is my code:

        transport = GoogleNetHttpTransport.newTrustedTransport();
        jsonFactory = JacksonFactory.getDefaultInstance();

        credential = new GoogleCredential.Builder()
                .setTransport(transport)
                .setJsonFactory(jsonFactory)
                .setServiceAccountUser(googleAdminEmail)
                .setServiceAccountId(googleAdminAccount)
                .setServiceAccountScopes(Arrays.asList(
                                DirectoryScopes.ADMIN_DIRECTORY_USER,
                                DirectoryScopes.ADMIN_DIRECTORY_GROUP,
                                DirectoryScopes.ADMIN_DIRECTORY_GROUP_MEMBER))
                .setServiceAccountPrivateKeyFromP12File(new File(googleAdminKeyPath))
                .build();           

        credential.refreshToken();

The exact line that throws me the exception is:

 credential.refreshToken();

If I get the Access Token from my local run, let's say the token value is "usghiudblk", and I set that value when running on DEV's GlasshFish: credential.setAcessToken("usghiudblk"); it will let me access normally but still this won't work: credential.refreshToken();

I truly can't tell why everything works just fine in local but doesn't works in DEV's GlassFish.


Answer:

Solved it by the answer on this post:

Invalid grant when accessing Google API

The problem was that the server's clock was not synchronized with NTP.

That was it...

Question:

I'm using:

  • GlassFish 4.1
  • Hibernate (see pom.xml)
  • Java EE 7
  • Eclipse Luna

I don't know why GlassFish can't inject an EntityManager. If i get the EntityManager from EntityManagerFactory, i don't have problems:

protected EntityManager em = Persistence.createEntityManagerFactory("CustomersPU").createEntityManager();

In other hand, if i try to say that GlassFish inject it, get an Exception.:

@PersistenceContext(unitName="CustomersPU")
protected EntityManager em;

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>me.localtest</groupId>
    <artifactId>customersapp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <maven_compiler_source>1.8</maven_compiler_source>
        <maven_compiler_target>1.8</maven_compiler_target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.8.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.1.3.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.common</groupId>
            <artifactId>hibernate-commons-annotations</artifactId>
            <version>4.0.5.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.8.Final</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

GenericService

package me.localtest.customersapp.services;

import java.io.Serializable;
import java.util.List;

public interface GenericService<T, PK extends Serializable> {
    public T save(T t) throws Throwable;
    public T update(T t) throws Throwable;
    public T remove(T t) throws Throwable;
    public T find(PK pk) throws Throwable;
    public List<T> findAll(String namedQuery) throws Throwable;
}

GenericServiceImpl

package me.localtest.customersapp.services;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

public abstract class GenericServiceImpl<T, PK extends Serializable> implements GenericService<T, PK> {
    //@PersistenceContext(unitName="CustomersPU")
    protected EntityManager em = Persistence.createEntityManagerFactory("CustomersPU").createEntityManager();
    protected Class<T> clazz;

    public GenericServiceImpl(Class<T> clazz) {
        this.clazz = clazz;
    }
    @Override
    public T save(T t) throws Throwable {
        em.persist(t);
        em.flush();
        return t;
    }
    @Override
    public T remove(T t) throws Throwable {
        em.remove(t);
        em.flush();
        return t;
    }
    @Override
    public T update(T t) throws Throwable {
        em.merge(t);
        em.flush();
        return t;
    }
    @Override
    public T find(PK pk) throws Throwable {
        return (T) em.find(clazz, pk);
    }
    @SuppressWarnings("unchecked")
    @Override
    public List<T> findAll(String aQuery) throws Throwable {
        Query query = em.createQuery(aQuery);
        return (List<T>) query.getResultList();
    }
}

CustomerServiceBean

package me.localtest.customersapp.services;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.Query;

import me.localtest.customersapp.domain.entities.Customer;

@LocalBean
@Stateless
public class CustomerServiceBean extends GenericServiceImpl<Customer, Integer> {

    public CustomerServiceBean() {
        super(Customer.class);
    }
    public Customer findByDni(String dni) {
        Query query = em.createNamedQuery("Customer.findByDni");
        query.setParameter("dni", dni);
        return (Customer) query.getSingleResult();
    }
}

Customer

package me.localtest.customersapp.domain.entities;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@Entity
@Table(name="customers")
@XmlRootElement(name="customer")
@XmlAccessorType(XmlAccessType.FIELD)
@NamedQueries({
    @NamedQuery(name="Customer.findByDni", query="SELECT c FROM Customer c WHERE c.dni = :dni")
})
@SuppressWarnings("serial")
public class Customer implements Serializable {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id")
    @XmlElement(name="id")
    private Integer id;
    @Column(name="names")
    @XmlElement(name="names")
    private String names;
    @Column(name="surnames")
    @XmlElement(name="surnames")
    private String surnames;
    @Column(name="dni")
    @XmlElement(name="dni")
    private String dni;
    @Column(name="birth_date")
    @XmlElement(name="birth-date")
    @Temporal(TemporalType.DATE)
    private Date birthDate;
    @Column(name="address")
    @XmlElement(name="address")
    private String address;
    @Column(name="email")
    @XmlElement(name="email")
    private String email;
    @Column(name="creation_date")
    @Temporal(TemporalType.DATE)
    @XmlElement(name="creation-date")
    private Date creationDate;
    @Column(name="state")
    @XmlElement(name="state")
    private Boolean state;

    public Customer() {

    }
    public Customer(Integer id, String names, String surnames, String dni,
            Date birthDate, String address, String email, Date creationDate,
            Boolean state) {
        this.id = id;
        this.names = names;
        this.surnames = surnames;
        this.dni = dni;
        this.birthDate = birthDate;
        this.address = address;
        this.email = email;
        this.creationDate = creationDate;
        this.state = state;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getNames() {
        return names;
    }
    public void setNames(String names) {
        this.names = names;
    }
    public String getSurnames() {
        return surnames;
    }
    public void setSurnames(String surnames) {
        this.surnames = surnames;
    }
    public String getDni() {
        return dni;
    }
    public void setDni(String dni) {
        this.dni = dni;
    }
    public Date getBirthDate() {
        return birthDate;
    }
    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public Date getCreationDate() {
        return creationDate;
    }
    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }
    public Boolean getState() {
        return state;
    }
    public void setState(Boolean state) {
        this.state = state;
    }
}

persistence.xml

<persistence-unit name="CustomersPU" transaction-type="JTA">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <jta-data-source>jdbc/__customers</jta-data-source>
    <properties>
        <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform" />
    </properties>
</persistence-unit>

Stage 1

Try to find Customer with DNI 'A' (RESTful):

http://localhost:8080/customersapp/api/customers/find/A

This is a piece stack trace:

2015-04-06T09:19:31.088-0500|Advertencia: A system exception occurred during an invocation on EJB CustomerServiceBean, method: public me.localtest.customersapp.domain.entities.Customer me.localtest.customersapp.services.CustomerServiceBean.findByDni(java.lang.String)
2015-04-06T09:19:31.089-0500|Advertencia: javax.ejb.TransactionRolledbackLocalException: Exception thrown from bean
    at com.sun.ejb.containers.EJBContainerTransactionManager.checkExceptionClientTx(EJBContainerTransactionManager.java:662)
    at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:507)
    at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4566)
    at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2074)
    at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2044)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:220)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
    at com.sun.proxy.$Proxy267.findByDni(Unknown Source)
    at me.localtest.customersapp.services.__EJB31_Generated__CustomerServiceBean__Intf____Bean__.findByDni(Unknown Source)

And this is the cause:

Caused by: java.lang.ClassCastException: me.localtest.customersapp.domain.entities.Customer cannot be cast to me.localtest.customersapp.domain.entities.Customer

I found this stupid, how is possible can't cast to the same class?

Thanks.


Answer:

Appeared to be the result of classloder problems GF 4.x is having with the hibernate version 4.3.8.Final

Most probably it relates to HHH-9446 Also it looks like it was fixed 2 days ago. Have not yet had a chance to try it though