vendredi 31 juillet 2015

ForkJoinPool exit without processing all elements in the ParallelStream

I am executing a parallel stream with n number of elements; however the the forJoin finish before my collection 'records' processes all elements in parallel stream.

Below my code:

//Created my own ForkJoinPool in order to avoid the common pool
   final ForkJoinPool forJoinPool = new ForkJoinPool(commonPool.getParallelism() * 2);

   final AtomicInteger at = new AtomicInteger();


   forJoinPool.execute(() -> records.parallelStream().forEach(
       e -> logger.info("Finished:{}, id:{} ", myService.convert(e, at.incrementAndGet()),
           at.get())));

Am I missing something in Parallel Stream? I was expecting ForJoinPool to be closed after all elements in forEach(... are executed.

How can I test specific field of entity by JUnit if using validator?

I have some entity which stored in db.
For example:

@Pattern(regexp = "male|female")
@Column(name = "sex")
private String sex;


Now I have some JUnit test codebut its test all fields.

Set<ConstraintViolation<Candidate>> violations = this.validator.validate(this.validCandidate, Candidate.class);
assertTrue(violations.isEmpty());

How can I test only sex for example?

Local stateless EJBs vs Remote

I'm kind of a newbie in EJBs,but I've been given an EJB tier to improve.
This tier consists of an EJB wich exposes the operations available:

@Stateless(name = "myejb")
public class Facade implements FacadeRemote
{
    @EJB
    private EntityAHomeLocal entityAHome;

    @EJB
    private EntityBHomeLocal entityBHome;

// methods signatures and implementations
}

As you can see this EJB use other local EJBs that manage operations on entities.

@Stateless
public class EntityAHome implements EntityAHomeLocal
{
    @PersistenceContext(name="myUnit")
    private EntityManager manager;


    // methods signatures and implementations
}

I'm having hard time to fully understand the architecture of this tier.

  • Is this kind of architrcture common ?
  • Are local stateless EJB managed throught a pool of instances just like remote stateless EJBs ?

JUnit Test runs on Local but not on Jenkins

I've got strange error with Jenkins.

The Jenkins server is on the same computer as the local test, but here is what I've got :

When I run 4 tests about a class named CarStatusDao on Local, here in the output :

Running net.****.****.dao.carstatus.CarStatusDaoTest

Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.032 sec

The tests run without any problem.

When I execute the exact same code, but on Jenkins (who get the exact same code from a SVN):

Running net.****.****.dao.carstatus.CarStatusDaoTest

2015-07-31 15:29:21,497 ERROR [org.springframework.test.context.TestContextManager] - Caught exception while allowing TestExecutionListener 
[org.springframework.test.context.support.DependencyInjectionTestExecutionListener@c316b9] to prepare test instance [net.****.****.dao.carstatus.CarStatusDaoTest@1121079]
org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'net.****.****.dao.carstatus.CarStatusDaoTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: net.****.****.dao.CarStatusDao net.****.****.dao.carstatus.CarStatusDaoTest.carStatusDAO; 
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No matching bean of type [net.****.****.dao.CarStatusDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1120)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:379)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75) 
    at [...]

Tests run: 4, Failures: 0, Errors: 4, Skipped: 0, Time elapsed: 0.011 sec <<< FAILURE!

From theses logs, the important part is :

Error creating bean with name 'net.****.****.dao.carstatus.CarStatusDaoTest': 
Injection of autowired dependencies failed; 
nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field: net.****.****.dao.CarStatusDao net.****.****.dao.carstatus.CarStatusDaoTest.carStatusDAO; 

So basically, in local Maven is able to autowired my attribute carStatusDAO in the class CarStatusDaoTest, but when I run it on Jenkins, it is not able... :/

I don't understand why such differents behaviors whereas the Maven is the same and the code is the same also.... :/

I assume it's a classpath problem, because that's the only different thing :/

but I don't know how to fix it.

For the context, here is my /META-INF/spring/carfleet-dao-test-context.xml :

<context:component-scan base-package="net.****.****" />

<jd:embedded-database id="dataSource" type="HSQL">
    <jd:script location="classpath:sql/hsql-schema.sql" />
    <jd:script location="classpath:sql/test-data.sql" />
</jd:embedded-database>

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
    </property>
    <property name="persistenceUnitName" value="testunit" />
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" >
        <list>
            <value>net.****.****.domain</value>
        </list>
    </property>
</bean>

<bean
    class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<tx:annotation-driven />

Here is the definition of my class CarStatusDaoTest :

public class CarStatusDaoTest extends AbstractDaoTest {

    @Autowired
    CarStatusDao carStatusDAO;

    @Test
    public void getCurrentStatusOfCarTesting() {

        carStatus = carStatusDAO.getCurrentStatusOfCar(-1L);
        assertEquals(carStatus, null);
    }

    [...]
}

And here is the Mother Class for all my tests :

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath*:/META-INF/spring/carfleet-dao-test-context.xml")
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
public class AbstractDaoTest {

    @Autowired
    private EntityFactory entityFactory;

    public EntityFactory getEntityFactory() {
        return entityFactory;
    }

    @Test
    public void shouldEntityFactoryBeNotNull() {

        assertNotNull(entityFactory);
    }
}

Thanks in advance, Best Regards.

How to make simple JAAS login module work (EJBs, Tomcat, WebLogic)?

I want to create a simple login module which authenticates users so they can, through a servlet using the weblogic client, access EJB's methods annotated with @RolesAllowed. As you probably noted, I have two seperate tiers - one with a webapp (Tomcat) and one containing business logic (WebLogic).

Generally speaking, I followed this JAAS tutorial (setting things accordingly).

According to the answer to this question, the principals should be propaged to the business tier (even having the tiers on separate machines?)

However, what I'm getting is an error page with following header: HTTP Status 500 - [EJB:010160]Security violation: User <anonymous> has insufficient permission to access EJB type=<ejb>

Also, I created corresponding roles in the WebLogic console.

Some tests from the servlet's GET method (without calling Bean's annotaed method):

request.getUserPrincipal().getName(): ADMIN
request.getParameter("role"): null
request.isUserInRole("admins"): true

(request is obtained from the argument @Context HttpServletRequest request)

Is there any additional thing to do to make it work? Or is it sufficient but there may be an error somewhere?

Let me also point I'm quite new in creating Java EE applications.

Help appreciated

During conversion getting arrayindexoutofboundsexception

I am trying to convert String to byte using below code.

ec = "some html contents";
private String MyMethod(String ec){
  byte[] ecByte = DatatypeConverter.parseBase64Binary(ec);
  return new String(ecByte, "iso-8859-1");
}

while calling MyMethod, Getting arrayindexoutofboundsexception Error.

java.lang.ArrayIndexOutOfBoundsException: 146
    at javax.xml.bind.DatatypeConverterImpl._parseBase64Binary(DatatypeConverterImpl.java:576)
    at javax.xml.bind.DatatypeConverterImpl.parseBase64Binary(DatatypeConverterImpl.java:323)
    at javax.xml.bind.DatatypeConverter.parseBase64Binary(DatatypeConverter.java:296)

I don't know what to do. Please help me on fixing this error.

Thanks in advance.

Maven: javax.enterprise.context.ContextNotActiveException while running tests with openejb

I've created some unit- and integration tests for mine Java-ee project with the help of OpenEjb and Junit with an embedded container. The tests are running fine in Eclipse, beans(CDI/EJB) are injected and working fine. But when I start the tests with maven and surefire, I get the following error:

WARNING: Handling the following exception
Throwable occurred: javax.enterprise.context.ContextNotActiveException: WebBeans context with scope type annotation @RequestScoped does not exist within current thread
at org.apache.webbeans.container.BeanManagerImpl.getContext(BeanManagerImpl.java:330)
at org.apache.webbeans.intercept.NormalScopedBeanInterceptorHandler.getContextualInstance(NormalScopedBeanInterceptorHandler.java:88)
at org.apache.webbeans.intercept.NormalScopedBeanInterceptorHandler.get(NormalScopedBeanInterceptorHandler.java:70)
at org.apache.webbeans.conversation.ConversationImpl$$OwbNormalScopeProxy0.isTransient(org/apache/webbeans/conversation/ConversationImpl.java)
at org.apache.wicket.cdi.ConversationPropagator.onUrlMapped(ConversationPropagator.java:322)
at org.apache.wicket.request.cycle.RequestCycleListenerCollection$9.notify(RequestCycleListenerCollection.java:208)

What could be wrong? It looks like a classpath issue or something, but explicit adding openwebbeans-spi and openwebbeans-impl didn't work.

I use the following lines in the testclass:

@ClassRule
public static final EJBContainerRule CONTAINER_RULE = new EJBContainerRule();

@Rule
public final InjectRule rule = new InjectRule(this, CONTAINER_RULE);

And I've the following openejb-junit.properties:

openejb.validation.output.level=VERBOSE
openejb.deployments.classpath.include=.*org.mine.*
openejb.descriptors.output=true
openejb.ejbcontainer.close=single-jvm
java.naming.factory.initial=com.ibm.websphere.naming.WsnInitialContextFactory

Thanks for any help.

Greetings, Huls.

How can I create a Java EE 7 application using eclipse and gradle?

I want to setup a simple Java EE 7 application in eclipse that gets built with gradle. My current tool stack is:

  • Eclipse JEE 4.5 with Buildship
  • Gradle 2.5
  • Websphere Liberty Profile

Using Maven and Wildfly before, I did basically following steps:

  1. mvn archetype:generate -DarchetypeGroupId=com.airhacks -DarchetypeArtifactId=javaee7-essentials-archetype -DarchetypeVersion=1.2
  2. Create index.xhtml (facelet) in src/main/webapp
  3. Add faces-config.xml to src/main/webapp/WEB-INF
  4. In eclipse: Configure application server (wildfly)
  5. In eclipse: Import existing Maven project into workspace
  6. In eclipse: Deploy new application to server

How can I do the same using gradle?

java.lang.StackOverflowError when creating a list querry

Hi i want to compare two date in a querry i got the following error

EJB Exception: : java.lang.StackOverflowError at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1603) at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1625) at sun.reflect.GeneratedMethodAccessor523.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at weblogic.persistence.BasePersistenceContextProxyImpl.invoke(BasePersistenceContextProxyImpl.java:110) at weblogic.persistence.TransactionalEntityManagerProxyImpl.invoke(TransactionalEntityManagerProxyImpl.java:79) at weblogic.persistence.BasePersistenceContextProxyImpl.invoke(BasePersistenceContextProxyImpl.java:91) at com.sun.proxy.$Proxy218.createQuery(Unknown Source) at model.Services.SessionEJBDossierBean.getDossierFindAllParDepartementDBTECHandUrgen(SessionEJBDossierBean.java:67) at model.Services.SessionEJBDossierBean.getDossierFindAllParDepartementDBTECHandUrgen(SessionEJBDossierBean.java:73) at model.Services.SessionEJBDossierBean.getDossierFindAllParDepartementDBTECHandUrgen(SessionEJBDossierBean.java:73) at model.Services.SessionEJBDossierBean.getDossierFindAllParDepartementDBTECHandUrgen(SessionEJBDossierBean.java:73) at model.Services.SessionEJBDossierBean.getDossierFindAllParDepartementDBTECHandUrgen(SessionEJBDossierBean.java:73) at model.Services.SessionEJBDossierBean.getDossierFindAllParDepartementDBTECHandUrgen(SessionEJBDossierBean.java:73) model.Services.SessionEJBDossierBean.getDossierFindAllParDepartementDBTECHandUrgen(SessionEJBDossierBean.java:73) at model.Services.SessionEJBDossierBean.getDossierFindAllParDepartementDBTECHandUrgen(SessionEJBDossierBean.java:73) at model.Services.SessionEJBDossierBean.getDossierFindAllParDepartementDBTECHandUrgen(SessionEJBDossierBean.java:73) at model.Services.SessionEJBDossierBean.getDossierFindAllParDepartementDBTECHandUrgen(SessionEJBDossierBean.java:73) at model.Services.SessionEJBDossierBean.getDossierFindAllParDepartementDBTECHandUrgen(SessionEJBDossierBean.java:73)

here is my code

public List<Dossier> getDossierFindAllParDepartementDBTECHandUrgen() {
    Calendar myFiveDaysAhead;
    myFiveDaysAhead = Calendar.getInstance();
    myFiveDaysAhead.add(Calendar.DATE, 5);

    TypedQuery<Dossier> query;
    query =
        em.createQuery("SELECT d FROM Dossier d WHERE d.depid=1 AND d.typeDossier = :tpd AND " +
                       "d.dateCreation < :fiveDaysAhead", Dossier.class);

    query.setParameter("tpd", "Urgent");
    query.setParameter("fiveDaysAhead", myFiveDaysAhead, TemporalType.TIMESTAMP);
    return getDossierFindAllParDepartementDBTECHandUrgen();
}

Memory footprint of anonymous objects in Hibernate

I am current working on a project which was built with struts and hibernate .

All DAO classes in the project has the following code

Inside constructor

hibernateSession = HibernateUtil.currentSession();
tx=hibernateSession.beginTransaction();

Inside finally clause of all methods

HibernateUtil.closeSession();

What this effectively means is that, in my business code , I have to initialize the reference variable or create an anonymous object every time I want to access data from the database. ie

If I have to access method1 and method2 of class A

A a= new A();

a.method1(); // access method 1 

a = new A();  
a.method2(); //access method 2

I now mostly use anonymous objects to get this done ie

new A().method1(); //access method 1
new B().method2(); //access method 2 

Now my questions are.

  1. Are anonymous objects garbage collected just after usage ? In my project, since every access to methods in dao class is via anonymous object , will it adversely affect the memory footprint ? if yes any alternative way ?

  2. Am I doing it correctly or is there a better way ?

  3. Is this the best/correct way of implementation using hibernate ?

  4. Is my usage of the term "anonymous object" for "new A();" correct ? While searching for the same in google , I noticed many comments saying this is not called anonymous object in java, but also came across some articles explaining this as anonymous objects.

Stop Executing the Drool rules if one rule got fired

I am new to Drools. I am using Drools version 6.2. I have a .drl file which has more than 200 rules and for each request it fires one corresponding rule but it will execute all the rules to check for the evaluation criteria. It is causing the performance issue for me. So I want if any of the rule satisfies the evaluation criteria then the execution for other rules stops.

I have tried to search on that and somewhere I found that the rules are getting executed parallely, but in documentation I have seen in drools 6 the rules got fired sequentially.

Second solution that I tried was using the below code :

final KieSession kSession = RulesLoader
                    .getStatefulSession(getDrlFileName());
            kSession.fireAllRules(1);

But it didn't worked. I have tested it by giving 2 rules same evaluation criteria, but unfortunately both the rules get fired instead of only one.

I am giving the rules format for Reference as given:

rule "Rule 1"
    salience 1000
    no-loop true
  when
    eval1
    eval2
 then
    setRequest1
end


rule "Rule 2"
    salience 1000
    no-loop true
  when
    eval1
    eval2
 then
    setRequest2
end

So is it possible that we can stop execution of other rules if one rule gets fired? Any help or discussion will be appreciated.

How to delete useless JSP

On the website that I'm developping, I'm using a lot of Ajax calls to display informations.

Theses Ajax Call are as follow :

function deleteBookingAjax(rowId) {

$.ajax({
    url : "deleteRent.htm", 
    type : "GET",   
    data : {
        "rentId" : rowId
    },
    dataType : 'json',
    cache : false,
    success : function(response) {

        if(response.error) {
            showPopupMessage(response.error, true);
        } 

    },
    statusCode : {
        500 : function() {
            loggingMessage('Error 500');
            reloadBookingTable();
        },
        404 : function() {
            loggingMessage('Error 404');
            reloadBookingTable();
        }

    }
  });
}

To perform this call, I have also Controllers as follow :

@RequestMapping(value = "/deleteRent.htm")
public String deleteRent(Long rentId, HttpServletRequest request, HttpServletResponse response) {

    if (rentId == null) {
        return null;
    }

    try {

        rentService.deleteRent(rentId);

    } catch (Exception e) {

        LOGGER.error(e);
    }

    response.setStatus(HttpStatus.SUCCESS);

    return ViewNames.BOOKINGS_PAGE;
}

But my problem is that : to perform this Ajax call, I need to create a useless JSP file :

<%@page import="net.****.****.web.controllers.RentControllers"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://ift.tt/QfKAz6" prefix="c"%>
<%@ taglib uri="http://ift.tt/18bwTB1" prefix="spring"%>

If I don't create theses files, the Ajax call is not working...

When the file is not in the WEB-INF/ The Ajax call returns :

GET http://ift.tt/1IwR5gM 404 (Not Found)

How can I make it work without theses files (I assume it will be in configurations... but where exactly and how ?), because it's not convinient to have a lot of JSP files but when only few of them have contents...

Thanks in advance. :)

Changing JAX-WS RI of Jboss server to use JAX-WS RI 2.1.6 in JDK 6

I am using Jboss-eap-5.1.2 where my web services(SOAP) services are deployed. When I try access them immediately after the server started, I am getting the following exception:

java.lang.LinkageError: loader constraint violation: when resolving overridden method "com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(Ljavax/xml/stream/XMLStreamReader;Ljava/lang/Class;)Ljavax/xml/bind/JAXBElement;" the class loader (instance of org/jboss/classloader/spi/base/BaseClassLoader) of the current class, com/sun/xml/bind/v2/runtime/unmarshaller/UnmarshallerImpl, and its superclass loader (instance of <bootloader>), have different Class objects for the type javax/xml/stream/XMLStreamReader used in the signature
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl.createUnmarshaller(JAXBContextImpl.java:738)

When I try to access the web services after that, I am getting the following exception:

The exception contained within MappableContainerException could not be mapped to a response, re-throwing to the HTTP container
java.lang.NoClassDefFoundError: Could not initialize class com.sun.xml.ws.transport.http.client.HttpClientTransport
    at com.sun.xml.ws.transport.http.client.HttpTransportPipe.process(HttpTransportPipe.java:110)

I have added a Junit test case to find the root cause. Only one difference I could identify.

JAX-WS RI 2.1.4-b01- is used by the client to generate the stub when I try to access the web services deployed in Jboss from another application.

JAX-WS RI 2.1.4-b01-: Stub for http://ift.tt/1UbpK7R

JAX-WS RI 2.1.6 in JDK 6 is been used by the client when I try to access the same web services from JUNIT test case.

JAX-WS RI 2.1.6 in JDK 6: Stub for http://ift.tt/1UbpK7R

Anybody has any idea on why it is happening like that?

Not loading the persistence provider class in runtime

I have created RestService enabled with JPA(Generic 2.0 version). Using jersey jars and hibernate entity manager jar as dependencies.

Deployment is successfull in tomcat. But when any transaction is processed, getting below exception in runtime.

java.lang.ClassNotFoundException: javax.persistence.spi.PersistenceProvider

What could be the issue, not loading the persistence provider class even it is in the classpath ?

Hessian not workin in wildfly 8.2.0

I am deploying an EAR application in Wildfly 8.2.0 in linux machine. Application contains webstart and hessian protocol.

ERROR [io.undertow.request] (default task-23) UT005023: Exception handling request to /hessian/app: java.lang.RuntimeException: 11 is an unknown object type

This happens during deserialization in Hessian protocol. When I checked the logs, I am getting the below exception.

Caused by: java.io.EOFException: readObject: unexpected end of file
at com.caucho.hessian.io.CollectionDeserializer.readLengthList(CollectionDeserializer.java:93)
at com.caucho.hessian.io.UnsafeDeserializer$ObjectFieldDeserializer.deserialize(UnsafeDeserializer.java:417)
... 74 more

Is it related to configuration for wildfly remote access ? Have any one faced this issue ? Please help.

jeudi 30 juillet 2015

Restful with java security

I have to secure my restful web services so that if any one will get uri of my restful web services then also with the help of that uri any one cant access my restful web services . I want to design a restful web services in such a way that only my dynamic web application running in different server can access my restful web services . I am doing this by setting authentication header , I am putting username of the user in authentication header and in restful web services i am checking these value from the data base , this is like session management , i am confuse whether this is good approach , because we should not mention session in restful web services .

second thing is that i am putting some encoded string in authentication header and we will also check these value in the filter of restful web services , for protecting from third party , is this approach is good , if not can you tell me the good approach , Thanks

Programmatically loading resources using Spring MVC after context init?

I've been using Spring to assist me with developing an internal tool for a company. I've never used Spring before until a couple weeks ago. Work is breezing by with how great it is! But I came to a screeching halt about three days ago on a question that I cannot seem to find any documentation on. I don't even know if you could do it without using hacks of some sort?

How can you programmatically load resources say CSS, JavaScript, and a collection of various media files using the Spring MVC framework after the context has been initialized?

Thank you kindly for all your help and time!

EntityManager injection crashes - Hibernate & MySQL & J2EE 7.0 application

I'm developing a small web application, like a REST service for something else. For now it should handle registration and add users to database.

Anyways, I'm new to Java EE and I can't get EntityManager injection to work. I'm using GlassFish 4.1.0 to deploy this application and Hibernate for database handling as well as a MySQL database(XAMPP if its important).

I'm getting crashes when accessing

http://localhost:8080/.../api/users/reg?nr=value&gcmId=value

The GlassFish log is at the bottom. When I comment the line

em.persist(user);

it doesn't crash. So I'm pretty sure it has to do with injecting with EntityManager.

All files of the project:

RegisterController.java

@Path("/users")
public class RegisterController {

    @Inject
    private RegisterService service;

    @Path("/reg")
    @GET
    public String register(@QueryParam("nr") String nr,
                           @QueryParam("gcmId") String gcmId){
        service.register(nr,gcmId);
        return nr +" " +gcmId;
        //service.register(nr,gcmId);
    }
}

User.java

@Entity
public class User {
    @Id
    @GeneratedValue
    private long id;
    private String number;
    private String gcmId;

    public User(){

    }
    public User(String number, String gcmId){
        this.number = number;
        this.gcmId = gcmId;
    }

    public long getId() {
        return id;
    }

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

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getGcmId() {
        return gcmId;
    }

    public void setGcmId(String gcmId) {
        this.gcmId = gcmId;
    }
}

RegisterService.java

@Stateless
public class RegisterService {
    @PersistenceContext(unitName = "database")
    private EntityManager em;

    public void register(String nr, String gcmId){
        User user = new User(nr,gcmId);
        em.persist(user);
    }
}

Application.java

@ApplicationPath("/api")
public class Application extends javax.ws.rs.core.Application{

}

Persistence.xml

<persistence xmlns="http://ift.tt/UICAJV"
             xmlns:xsi="http://ift.tt/ra1lAU"
             xsi:schemaLocation="http://ift.tt/UICAJV http://ift.tt/O9YdEP"
             version="2.0">

    <persistence-unit name="database" transaction-type="JTA">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.user" value="value"/>
            <property name="javax.persistence.jdbc.password" value="value"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/value"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
        </properties>
    </persistence-unit>
</persistence>

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans
        xmlns="http://ift.tt/19L2NlC"
        xmlns:xsi="http://ift.tt/ra1lAU"
        xsi:schemaLocation="http://ift.tt/19L2NlC
                      http://ift.tt/18tV3H8"
        bean-discovery-mode="all">
</beans>

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://ift.tt/IH78KX"
         xmlns:xsi="http://ift.tt/ra1lAU"
         xsi:schemaLocation="http://ift.tt/IH78KX http://ift.tt/VE5zRx">
    <modelVersion>4.0.0</modelVersion>

    <groupId>somevalue</groupId>
    <artifactId>somevalue</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.36</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.10.Final</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>somevalue</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
            </plugin>
        </plugins>
    </build>

</project>

GLASSFISH LOG

[2015-07-30T20:01:56.614+0200] [glassfish 4.1] [WARNING] [AS-EJB-00056] [javax.enterprise.ejb.container] [tid: _ThreadID=30 _ThreadName=http-listener-1(3)] [timeMillis: 1438279316614] [levelValue: 900] [[
  A system exception occurred during an invocation on EJB RegisterService, method: public void services.RegisterService.register(java.lang.String,java.lang.String)]]

[2015-07-30T20:01:56.615+0200] [glassfish 4.1] [WARNING] [] [javax.enterprise.ejb.container] [tid: _ThreadID=30 _ThreadName=http-listener-1(3)] [timeMillis: 1438279316615] [levelValue: 900] [[

javax.ejb.EJBException
    at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:748)
    at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:698)
    at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:503)
    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.$Proxy184.register(Unknown Source)
    at services.__EJB31_Generated__RegisterService__Intf____Bean__.register(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.jboss.weld.util.reflection.Reflections.invokeAndUnwrap(Reflections.java:414)
    at org.jboss.weld.bean.proxy.EnterpriseBeanProxyMethodHandler.invoke(EnterpriseBeanProxyMethodHandler.java:127)
    at org.jboss.weld.bean.proxy.EnterpriseTargetBeanInstance.invoke(EnterpriseTargetBeanInstance.java:56)
    at org.jboss.weld.bean.proxy.InjectionPointPropagatingEnterpriseTargetBeanInstance.invoke(InjectionPointPropagatingEnterpriseTargetBeanInstance.java:65)
    at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:100)
    at services.RegisterService$Proxy$_$$_Weld$EnterpriseProxy$.register(Unknown Source)
    at controllers.RegisterController.register(RegisterController.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:151)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:171)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:195)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:104)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:387)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:331)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:103)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:271)
    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: 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:338)
    at com.sun.enterprise.container.common.impl.EntityManagerWrapper._getDelegate(EntityManagerWrapper.java:197)
    at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:287)
    at services.RegisterService.register(RegisterService.java:19)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
    at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
    at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
    at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
    at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
    at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
    at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
    at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
    ... 67 more
]]

[2015-07-30T20:01:56.620+0200] [glassfish 4.1] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=30 _ThreadName=http-listener-1(3)] [timeMillis: 1438279316620] [levelValue: 900] [[
  StandardWrapperValve[controllers.Application]: Servlet.service() for servlet controllers.Application threw exception
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:338)
    at com.sun.enterprise.container.common.impl.EntityManagerWrapper._getDelegate(EntityManagerWrapper.java:197)
    at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:287)
    at services.RegisterService.register(RegisterService.java:19)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
    at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
    at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
    at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
    at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
    at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
    at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
    at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
    at com.sun.proxy.$Proxy184.register(Unknown Source)
    at services.__EJB31_Generated__RegisterService__Intf____Bean__.register(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.jboss.weld.util.reflection.Reflections.invokeAndUnwrap(Reflections.java:414)
    at org.jboss.weld.bean.proxy.EnterpriseBeanProxyMethodHandler.invoke(EnterpriseBeanProxyMethodHandler.java:127)
    at org.jboss.weld.bean.proxy.EnterpriseTargetBeanInstance.invoke(EnterpriseTargetBeanInstance.java:56)
    at org.jboss.weld.bean.proxy.InjectionPointPropagatingEnterpriseTargetBeanInstance.invoke(InjectionPointPropagatingEnterpriseTargetBeanInstance.java:65)
    at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:100)
    at services.RegisterService$Proxy$_$$_Weld$EnterpriseProxy$.register(Unknown Source)
    at controllers.RegisterController.register(RegisterController.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:151)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:171)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:195)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:104)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:387)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:331)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:103)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:271)
    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)
]]

Forward results from servlet to jsp in java EE 7

I am developing a small web application using jsps and servlets. I upload a file from welcome page and process it in a servlet. Late I forward the result to another page using the following code.

protected void doPost(HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException
{
    processRequest(request, response); // data is processed in this method

    RequestDispatcher oRD = request.getServletContext().getRequestDispatcher("/displayResult.jsp");
    oRD.forward(request, response);
}

My servlet is located in a folder named "Main" in source package and the jsp is located in Web Pages folder outside the WEB-INF folder.

This does not show any error and the control is not transferred to the jsp page as well. I have tried by using different paths but it does not show anything.

There is no web.xml file, as I am using JAVA-EE-7

Thanks in advance.

why does me Object become null in JSF 2.2 using primefaces when going from bean to .xhtml

I am building a JSF 2.0 Application using primfaces. I have a managed bean that has several objects for different scenarios. In this particular portion of the application I move from a data table/form to a managed bean with an identification number. I pull the information from the database and even have it in the log. However when I make it to the JSF xhtml page the object values are null and I can't seem to figure out why, any help would be great as I am getting no errors, exceptions, or warnings in the logs and all information seems to point to the loading of the data including the log.

JSF Page that I am coming from... jobs.xhtml (I am using jsf 2.2 and primefaces to build this application) From this page the link specifies a job number to be retrieved and the next bean will retrieve that job based on the job number I have it down to just a button that will take you to the primary method and get the information to the next page...

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://ift.tt/mOIMeg">
<html xmlns="http://ift.tt/lH0Osb"
xmlns:h="http://ift.tt/HjFrZb"
xmlns:f="http://ift.tt/HcrI1S"
xmlns:ui="http://ift.tt/KsEgXx"
xmlns:p="http://ift.tt/HjFrZc">
<body>
    <div style="margin-bottom:350px;">
        <p:column>
            <h:form>
                <h:commandButton id="editProject" action="#{editProjects.getProjectForm()}" value="Edit" />
            </h:form>
        </p:column>
    </div>
</body>
</html>

the mailerproject object class so that you have it for retesting

package objects;

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


public class MailerProject extends Project implements Serializable {

    private static final long serialVersionUID = -2033356999891677741L;
    private String size;
    private String color;
    private String quantity;
    private Date proofDue;
    private Date in_home;
    private Date press_deadline;
    private Date begin;
    private Date end;
    private boolean hosted;
    private String calls_to;
    private String leads_to;
    private String postage;
    private double price = 0;
    private String data;
    private String data_instructions;
    private String mail_house;
    private String notes;

    public MailerProject() {

    }

    public MailerProject(String jobNumber, Date openDate,
            boolean projectClosed, String salesMan, String campaign,
            String status, boolean co_op, boolean compliance, String jobType,
            int medium, int userId, int dealerID, String desc_id, String size, String color,
            String quantity, Date proofDue, Date in_home, Date press_dealine,
            Date begin, Date end, boolean hosted, String calls_to,
            String leads_to, String postage, double price, String data,
            String data_instructions, String mail_house, String notes) {

        super(jobNumber, openDate, projectClosed, salesMan, campaign, status, co_op,
                compliance, jobType, medium, userId, dealerID);

        this.size = size;
        this.color = color;
        this.quantity = quantity;
        this.proofDue = proofDue;
        this.in_home = in_home;
        this.press_deadline = press_dealine;
        this.begin = begin;
        this.end = end;
        this.hosted = hosted;
        this.calls_to = calls_to;
        this.leads_to = leads_to;
        this.postage = postage;
        this.price = price;
        this.data = data;
        this.data_instructions = data_instructions;
        this.mail_house = mail_house;
        this.notes = notes;
    }

}

Super class Project for mailerProject

package  objects;

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

public class Project implements Serializable{

    private static final long serialVersionUID = 3468591497012564082L;
    private int projectId;
    private String jobNumber;
    private Date openDate;
    private boolean projectClosed;
    private String salesMan;
    private String campaign;
    private String status;
    private String jobType;
    private boolean co_op;
    private boolean compliance;
    private int medium;
    private int userId;
    private int dealerID;

    public Project() {
    }

    public Project(String jobNumber, Date openDate, boolean projectClosed,
            String salesMan, String campaign, String status, boolean co_op,
            boolean compliance, String jobType, int medium, int userId,
            int dealerID) {
        this.jobNumber = jobNumber;
        this.openDate = openDate;
        this.projectClosed = projectClosed;
        this.salesMan = salesMan;
        this.campaign = campaign;
        this.status = status;
        this.jobType = jobType;
        this.medium = medium;
        this.userId = userId;
        this.dealerID = dealerID;
    }
}

EditProjects.java the backing bean for the editMailerJob.xhtml which will take in the medium id and the job number the medium id will be used to direct the application to the next page and the job number will be used to retrieve a specific job

package beans;

import java.io.Serializable;
import java.util.Map.Entry;

import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.RossProjectManagement.rpm.dao.DescriptionDao;
import com.RossProjectManagement.rpm.dao.ProjectDao;
import com.RossProjectManagement.rpm.objects.MailerProject;

@ManagedBean
@ViewScoped
public class EditProjects implements Serializable{

/**
 * 
 */
private static final long serialVersionUID = 8453455174655946403L;
private final Log LOG = LogFactory.getLog(this.getClass().getName());

//Editable projects
private MailerProject edit_mailer = new MailerProject();

public int getProjectForm() {
    ProjectDao pdao = new ProjectDao();
    DescriptionDao ddao = new DescriptionDao();

    loadEditMailer(jobNumber, pdao, ddao);

    return 1;
}

public void loadEditMailer() {
    this.edit_mailer = new Mailer("REDJ15061005", new java.util.Date("2015-06-29"),
        false, "RickD", "RickD and the Gang", "new", true, true, "SPEC", 1, 1, 1, 
        "REDJ15061005", "11X17", "SPOT_COLOR", "20,000", new java.util.Date("2015-06-30"), 
        new java.util.Date("2015-07-13"), new java.util.Date("2015-07-06"), new java.util.Date("2015-07-06"), 
        new java.util.Date("2015-07-15"), true, "BDC", "RichardDavy42@gmail.com", "STANDARD", 7500.00, "CONQUEST",
        "NONE", "JS DIRECT", "NONE");
}

public MailerProject getEdit_mailer() {
    return edit_mailer;
}

public void setEdit_mailer(MailerProject edit_mailer) {
    this.edit_mailer = edit_mailer;
}

}

JSF page that I am redirecting to editMailerJob.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://ift.tt/kkyg93">
<html xmlns="http://ift.tt/lH0Osb"
xmlns:h="http://ift.tt/HjFrZb"
xmlns:f="http://ift.tt/HcrI1S"
xmlns:ui="http://ift.tt/KsEgXx"
xmlns:p="http://ift.tt/HjFrZc">
<body>
    <div style="margin-bottom: 350px;">
        <h:outputLabel>#{editProjects.edit_mailer}</h:outputLabel>
    </div>
</body>
</html>

The faces-config.xml as minimal as possible...

<?xml version='1.0' encoding='UTF-8'?>
    <faces-config version="2.2"
              xmlns="http://ift.tt/19L2NlC"
              xmlns:xsi="http://ift.tt/ra1lAU"
              xsi:schemaLocation="http://ift.tt/19L2NlC http://ift.tt/1mXF9WB">
    <!-- Here is where we are selecting jobs to edit -->
     <navigation-rule>
        <description>Edit Project</description>
        <from-view-id>/main/jobs.xhtml</from-view-id>
        <navigation-case>
            <from-action>#{editProjects.getProjectForm()}</from-action>
            <from-outcome>1</from-outcome>
            <to-view-id>/main/forms/editMailerJob.xhtml</to-view-id>
            <redirect />
        </navigation-case>
    </navigation-rule>
    <managed-bean>
        <managed-bean-name>currentDate</managed-bean-name>
        <managed-bean-class>java.util.Date</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>

</faces-config>

The log shows that all of the information has been received and loaded but shows no where that the information has been cleaned or the object made anew. I have tried instantiating the object in different places at different times but that didn't work.

Before I leave the bean the object has value, when I get to the page the object has no value, I don't understand why

I then tried loading the information from different places. I have tried changing the scope of the bean from request to view back to request but no luck, (I thought about doing session but I didn't see the benefit as well as I just couldn't see reasoning to put all of that information into the session).

The problem seems to be revolving directly around the bean itself and the getProjectForm Method because at one point the object is loaded and then it just loses all of its information.

All of my values seem to be correct as far as I can tell but none of the information is loading.

I can't seem to wrap my head around the issue so any help would be greatly appreciated. if any more information is needed just let me know.

I hope all of this helps Let me know if I have forgotten anything.

Injecting EntityManager doesn't work - Hibernate + J2EE

I'm making a simple application and below is what I have right now. I'm getting errors when trying to access:

http://localhost:8080/SampleApp/api/users/reg?nr=test&gcmId=test

Also I've added logs of the error and the bottom.

I'm using GlassFish server 4.1.0 to deploy this application.

CODE:

Application class

    @ApplicationPath("/api")
    public class Application extends javax.ws.rs.core.Application{

    }

Register controller

    @Path("/users")
    public class RegisterController {

        @Inject
        private RegisterService service;


        @Path("/reg")
        @GET
        public String register(@QueryParam("nr") String nr,
                @QueryParam("gcmId") String gcmId){
            service.register(nr,gcmId);
            return nr +" " +gcmId;
        }
    }

Register service

    @Stateless
        public class RegisterService {
        @PersistenceContext(unitName = "database")
        private EntityManager em;

        public void register(String nr, String gcmId){
            User user = new User(nr,gcmId);
            em.persist(user);
        }
    }

User

@Entity
public class User {
    @Id
    @GeneratedValue
    private long id;
    private String number;
    private String gcmId;

    public User(){

    }
    public User(String number, String gcmId){
        this.number = number;
        this.gcmId = gcmId;
    }

    public long getId() {
        return id;
    }

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

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getGcmId() {
        return gcmId;
    }

    public void setGcmId(String gcmId) {
        this.gcmId = gcmId;
    }
}

Persistence.xml

    <persistence xmlns="http://ift.tt/UICAJV"
             xmlns:xsi="http://ift.tt/ra1lAU"
             xsi:schemaLocation="http://ift.tt/UICAJV
     http://ift.tt/O9YdEP"
             version="2.0">

    <persistence-unit name="database" transaction-type="JTA">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.user" value="value"/>
            <property name="javax.persistence.jdbc.password" value="value"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/value"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
        </properties>
    </persistence-unit>
</persistence>

POM.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://ift.tt/IH78KX"
     xmlns:xsi="http://ift.tt/ra1lAU"
     xsi:schemaLocation="http://ift.tt/IH78KX http://ift.tt/VE5zRx">
<modelVersion>4.0.0</modelVersion>

<groupId>Test</groupId>
<artifactId>Test</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<dependencies>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>7.0</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.36</version>
    </dependency>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20140107</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-io</artifactId>
        <version>1.3.2</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.3.10.Final</version>
    </dependency>

</dependencies>

<build>
    <finalName>SampleApp</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.4</version>
        </plugin>
    </plugins>
</build>

beans.xml (don't know if it's needed, i've added it while trying to get it to work)

<?xml version="1.0" encoding="UTF-8"?>
<beans
        xmlns="http://ift.tt/19L2NlC"
        xmlns:xsi="http://ift.tt/ra1lAU"
        xsi:schemaLocation="http://ift.tt/19L2NlC 
                      http://ift.tt/18tV3H8"
        bean-discovery-mode="all">
</beans>

ejb-jar.xml(This also added to check if it was the problem but unfortunately not)

<ejb-jar/>

GLASSFISH ERROR LOG:

[2015-07-30T17:25:41.701+0200] [glassfish 4.1] [WARNING] [] [javax.enterprise.ejb.container] [tid: _ThreadID=31 _ThreadName=http-listener-1(5)] [timeMillis: 1438269941701] [levelValue: 900] [[

javax.ejb.EJBException
    at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:748)
    at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:698)
    at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:503)
    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.$Proxy228.register(Unknown Source)
    at services.__EJB31_Generated__RegisterService__Intf____Bean__.register(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.jboss.weld.util.reflection.Reflections.invokeAndUnwrap(Reflections.java:414)
    at org.jboss.weld.bean.proxy.EnterpriseBeanProxyMethodHandler.invoke(EnterpriseBeanProxyMethodHandler.java:127)
    at org.jboss.weld.bean.proxy.EnterpriseTargetBeanInstance.invoke(EnterpriseTargetBeanInstance.java:56)
    at org.jboss.weld.bean.proxy.InjectionPointPropagatingEnterpriseTargetBeanInstance.invoke(InjectionPointPropagatingEnterpriseTargetBeanInstance.java:65)
    at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:100)
    at services.RegisterService$Proxy$_$$_Weld$EnterpriseProxy$.register(Unknown Source)
    at controllers.RegisterController.register(RegisterController.java:30)
    at controllers.RegisterController$Proxy$_$$_WeldClientProxy.register(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:151)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:171)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:195)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:104)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:387)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:331)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:103)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:271)
    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: 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:338)
    at com.sun.enterprise.container.common.impl.EntityManagerWrapper._getDelegate(EntityManagerWrapper.java:197)
    at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:287)
    at services.RegisterService.register(RegisterService.java:19)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
    at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
    at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
    at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
    at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
    at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
    at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
    at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
    ... 68 more
]]

[2015-07-30T17:25:41.705+0200] [glassfish 4.1] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=31 _ThreadName=http-listener-1(5)] [timeMillis: 1438269941705] [levelValue: 900] [[
  StandardWrapperValve[controllers.Application]: Servlet.service() for servlet controllers.Application threw exception
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:338)
    at com.sun.enterprise.container.common.impl.EntityManagerWrapper._getDelegate(EntityManagerWrapper.java:197)
    at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:287)
    at services.RegisterService.register(RegisterService.java:19)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
    at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
    at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
    at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
    at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
    at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
    at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
    at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
    at com.sun.proxy.$Proxy228.register(Unknown Source)
    at services.__EJB31_Generated__RegisterService__Intf____Bean__.register(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.jboss.weld.util.reflection.Reflections.invokeAndUnwrap(Reflections.java:414)
    at org.jboss.weld.bean.proxy.EnterpriseBeanProxyMethodHandler.invoke(EnterpriseBeanProxyMethodHandler.java:127)
    at org.jboss.weld.bean.proxy.EnterpriseTargetBeanInstance.invoke(EnterpriseTargetBeanInstance.java:56)
    at org.jboss.weld.bean.proxy.InjectionPointPropagatingEnterpriseTargetBeanInstance.invoke(InjectionPointPropagatingEnterpriseTargetBeanInstance.java:65)
    at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:100)
    at services.RegisterService$Proxy$_$$_Weld$EnterpriseProxy$.register(Unknown Source)
    at controllers.RegisterController.register(RegisterController.java:30)
    at controllers.RegisterController$Proxy$_$$_WeldClientProxy.register(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:151)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:171)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:195)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:104)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:387)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:331)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:103)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:271)
    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)
]]

Java EE UriInfo: append Query parameters

I want to append the query parameters list of a received UriInfo in a Rest service. The query comes from the client with some parameters and I need to add some more in server side.

I tried with:

uriInfo.getQueryParameters().add("Param", "value");

but when I display the URI, it doesn't has the new parameter.

On the other hand, if I do it like this:

URI uri = uriInfo.getRequestUriBuilder().queryParam("Param", "value").build();

when I display the URI, it contains the new parameter. The problem in this second case is to reconstruct a UriInfo object to give to the next functions, they require it.

I've seen that it cannot be instantiated, it has no constructors, it has to be added with @Context, its value can be updated by another UriInfo... but how to create this UriInfo with the URI I modified?

How to find length/size of a key in a MultivaluedMap?

MultivaluedMap map= new MultivaluedMapImpl();
map.add("Accept-Encoding", "compress;q=0.5");
map.add("Accept-Encoding", "gzip;q=1.1");
map.add("Accept-Encoding", "gzip;q=1.2");
map.add("Accept-Encoding", "gzip;q=1.3");

How can I find the size of the key "Accept-Encoding"?

Convert relational data into JSON Efficiently

I have following table People

enter image description here

I want to get relational records and make the JSON Array like following:

{ "Person":[
    {"ID":1, 
     "FirstName":"James", 
     "LastName":"Donovan",
     "Child":[
         {"ID":6, "FirstName":"Nikolai", "LastName":"Donovan"}
     ]
    },
    {"ID":2, 
     "FirstName":"Jeffrey", 
     "LastName":"Williams",
     "Child":[
         {"ID":4, "FirstName":"Carol", "LastName":"Williams"},
         {"ID":5, "FirstName":"Sarah", "LastName":"Williams"}
     ]
    },
    .... and so on
  ]
}

What I use following approach; short summary of below code: I perform db operation twice in loop and put node into JSON Object is match certain conditions.

preparedStatement = con.prepareStatement("SELECT * FROM PEOPLE");
rs = preparedStatement.executeQuery(); // ResultSet Object

if (rs != null && rs.next()) {
    Roles = new JSONObject();
    parentNode = new JSONObject();
    childNode = new JSONObject();

    while(rs.next()) {
        parentNode.put("ID", rs.getInt("Id"));
        parentNode.put("FirstName", rs.getString("firstname"));
        parentNode.put("LastName", rs.getString("lastname"));

        if(rs.getInt("parent") > 0) { // Equal 0 Mean it has not child
            // Perform again database operation and get record related to parent id
            preparedStatement = con.prepareStatement("SELECT * FROM PEOPLE WHERE parent=?");
            preparedStatement.setString(1, rs.getInt("id");
            resultSet2 = preparedStatement.executeQuery();

            while(resultSet2.next()) {
                childNode.put("ID", rs.getInt("Id"));
                childNode.put("FirstName", rs.getString("firstname"));
                childNode.put("LastName", rs.getString("lastname"));

                parentNode.put("Child":childRole); // put child into parent node
            }
       }
    }
}

What I want? Performing db select query in loop is too much expensive for server side.

Is there any better solution which generate desired JSON of relational data and save me from additional SELECT operations!

I am thankful for your attention!

What does this lookup addresses mean in Wildfly 8?

I have tested my first sessoin bean using Wildfly 8. I use the following code to obtain a proxy for the bean

InitialContext ctx = new InitialContext();
Object obj = ctx.lookup("java:global/EJBDemo/FirstDemoEJB");

When I print the object out I get the following output

Proxy for remote EJB StatelessEJBLocator{appName='', moduleName='EJBDemo', distinctName='', beanName='FirstDemoEJB', view='interface com.demo.ejb.FirstDemoEJBRemote'}

I can proceed with the RMI with the above lookup and get the desired result.

However, I observed that there are other lookup paths as listed by Wildfly at the time of deployment.

java:global/EJBDemo/FirstDemoEJB!com.demo.ejb.FirstDemoEJBRemote
java:app/EJBDemo/FirstDemoEJB!com.demo.ejb.FirstDemoEJBRemote
java:module/FirstDemoEJB!com.demo.ejb.FirstDemoEJBRemote
java:jboss/exported/EJBDemo/FirstDemoEJB!com.demo.ejb.FirstDemoEJBRemote

When I use the other lookup names names (part before the ! mark), I get the following output

EJBDemo/FirstDemoEJB -- service jboss.naming.context.java.app.TestEJB.EJBDemo.FirstDemoEJB

But I cannot RMI and get the desired result as in the java:global lookup.

My question is what does these other lookup paths listed by Wildfly mean? and can they be used for JNDI lookup as well? If so how to do it?

Disable URL rewriting for specific URLs in J2EE

How to disable url rewriting only to specific urls in webapplication ?

does control come back to the webapp which forwarded request to another webapp?

I have 2 web apps.

  1. A.war
  2. B.war

both have been deployed in same app server. A request comes to A.war and it forwards the request to B.war via

context.getServletContext("appname of B").getRequestDispatcher("uri").forward(request, response);

once the request is forwarded from A to B and then once the processing is completed on B, does the control come back to web app A or web app B directly sends the request to the client (browser)?

In other words , is it a separate Thread that would be executed in web app B in this case and it sends the response directly to the user?

How can I set sql driver for Oracle Adf Application module browser

I'm using JDeveloper 11g and I've created an ADF ApplicationModule that connects to SQL Server. When I want to run the application module browser, it shows an error that it can not find the appropriate driver. What should I do?

Configuration of glassfish on eclipse ? ( server runtime environment )

I have problem with glassfish I instaled the web version and I try with the full version but in server runtime environment I did not find Glassfish.

for more details I have Jdk 1.8 u 32

Ejb 2.0 Handles for Stateful bean

How EJB 2.0 Object handles (retrieved from getHandle() )help resuming after a disconnect from the server for Stateful Beans ??

In our application architecture, we are keeping the Handle of the stateful bean in a cache at the client side. If the the node in the cluster on which the Stateful bean was created goes down due to some reason, will the handle redirect the next call on the stateful to a new node ?? Is there any configuration that we can do if a Node goes down then reroute the calls on the Stateful Bean to another node in the cluster ??

mercredi 29 juillet 2015

Tomcat Custom Error Servlet

I have a custom error handling servlet which catch all throwables :

    <error-page>
      <exception-type>java.lang.Throwable</exception-type>
      <location>/Exception</location>
    </error-page>

The thing is, this servlet will do the forward request of the resolution and set some custom response headers. I want it to also set the http status code appropriately but it seems like if I set the http status code to the response, then I call forward, the response code automatically goes to 500.

why?

Database Poller Java EE/Spring/Hibernate

I am using Java EE with the Spring Framework and Hibernate. I want to write a very simple database poller that does the following

  1. Poll the DB every second
  2. If a certain column in a certain row has the value that I want, stop polling and return success.
  3. If polling has gone on for 10 or more seconds, return failure

I have already looked into Java's ScheduledExecutorService and ExecutorService, and I think that I may be able to do what I want with these. My question is, is there something built into Spring/Hibernate that can do this more elegantly?

Spring Security custom fitler chain map

I am developing a spring web mvc application, which makes use of spring security. For my application I found that the standard authorization process does not fit my needs. To continue development I have created some custom spring security classes, and augmented my spring-security.xml

Everything is going fine, except when trying to use the <security:filter-chain-map> I receive a dependency error that I can't seem to resolve.

The classes from the spring-security-web jar (or one of its dependencies) are not available. You need these to use <filter-chain-map>

The most common solutions found on stackoverflow included adding javax.servlet api jar, and the jstl-1.2 jar. I have had those already. This is killing me. I've been adding different jars in-and-out and it's not comming together.

I have found this http://ift.tt/1OPddE4 but I'm not sure I understand the answer.

dependencies

<dependencies>
    <!-- spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
        <exclusions>
            <!-- exclude commons-logging in favor of slf4j and logback -->
            <exclusion>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>${spring.security.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>${spring.security.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>${spring.security.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
        <version>${spring.security.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <!-- aop -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>1.8.6</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.6</version>
    </dependency>

    <!-- thymeleaf -->
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring4</artifactId>
        <version>2.1.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-tiles2-spring4</artifactId>
        <version>2.1.1.RELEASE</version>
    </dependency>

    <!-- j2ee -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
        <scope>provided</scope>
    </dependency>

spring-security.xml

<!-- config -->
<security:http pattern="/css/**" security="none"/>
<security:http pattern="/js/**" security="none"/>
<security:http pattern="/img/**" security="none"/>

<!-- custom security chain filter -->
<security:filter-chain-map>
    <security:filter-chain pattern="/**"
        filters="
            ConcurrentSessionFilterAdmin, 
            securityContextPersistenceFilter, 
            logoutFilterAdmin, 
            basicAuthenticationFilterAdmin, 
            requestCacheAwareFilter, 
            securityContextHolderAwareRequestFilter, 
            anonymousAuthenticationFilter, 
            sessionManagementFilterAdmin, 
            exceptionTranslationFilter, 
            filterSecurityInterceptorAdmin
            springSecurityFilterChain"
    />
</security:filter-chain-map>

<!-- user roles security -->
<security:http auto-config="true" use-expressions="true">
    <security:intercept-url pattern="/user/**" access="hasRole('USER_ROLE')"/>
    <security:intercept-url pattern="/oauth/callback**" access="permitAll"/>
    <security:access-denied-handler error-page="/"/>
    <security:form-login login-page="/"/>
    <security:session-management invalid-session-url="/"/>
    <security:csrf/>
</security:http>

<!-- spring security config -->
<security:authentication-manager id="authManager">
    <security:authentication-provider user-service-ref="PUEUserDetailsService"/>
</security:authentication-manager>

<!-- method security -->
<bean id="pueMethodSecurity" class="org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor">
    <property name="authenticationManager" ref="authManager"/>
    <property name="securityMetadataSource">
        <!-- method security -->
        <security:method-security-metadata-source>
            <security:protect access="permitAll" method="abnd.pue.controller.UserController.index*"/>
            <security:protect access="USER_ROLE" method="abnd.pue.controller.UserController.user*"/>
        </security:method-security-metadata-source>
    </property>
</bean>

relevant web.xml

<!-- spring security filter -->
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>abnd.pue.auth.PUEUsernameAuthFilterAdmin</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>