mardi 30 juin 2015

How to create a mutual map for every websocket session on a server side?

I make an application using websockets and Singleton from javax-inject. However for every new websocket session new hash map is created. What should I do to create a mutual map for all sessions?

import javax.inject.Singleton;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@ServerEndpoint(value = "/game_endpoint")
@Singleton
public class WaterWorldGame {
    Map<Session, Player> players = new HashMap<>();
    ...
}

Is there any annotations in javax-inject or it would be easier to make it with Spring?

How I write with the EntityManager in MySQL Database?

hi i have a java ee application and use JPA. (EJB). I have two Entities.

The Ticket and the User Class.

My Problem is that I dont can write the User in the Database :( The Ticket works...!

here is the user class:

@Entity
@NamedQueries({
    @NamedQuery(name=User.QUERY_GETALL,query="SELECT c FROM User c"),
    @NamedQuery(name=User.QUERY_GETALLTICKETS,query="SELECT c FROM Ticket c WHERE c.username LIKE :userUsername"),
})
public class User implements Serializable{

...

}

here is the UserDAO Interface:

public interface UserDAO {

    public User create(User user);

    public User update(User user);

    public void remove(int id);

    public User getUser(int id);

    public List<User> getAllUsers();

    public List<Ticket> getAllUserTickets(String username);
}

here is the UserBean that implements the UserDAO:

@Stateless
@Remote(UserDAO.class)
public class UserBean implements UserDAO{

    @PersistenceContext
    private EntityManager em;

    @Override
    public User create(User user) {
        em.persist(user);   
        return user;
    }
...

}

here is the class for creating the User and the Ticket:

@Singleton
@Startup
public class InitializationBean {

    @EJB
    private TicketDAO ticketDAO;

    @EJB
    private UserDAO userDAO;

    @PostConstruct
    private void initialize(){

        if(ticketDAO.getAllTickets().size() == 0){

            //User Dummy anlegen

            User user = new User();

            user.setFirstname("Wladimir");
            ...

            userDAO.create(user);

            //Ticket Dummy anlegen

            Ticket ticket = new Ticket();

            ticket.setName("DummyTicket");
            ...

            ticketDAO.create(ticket);
        }

    }
}

If I start the Application I can see in the MySQL Database that the Ticket was create but not the User :(

The Errors in the console:

00:07:52,486 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (ServerService Thread Pool -- 59) Data truncation: Data too long for column 'user' at row 1

00:07:52,579 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 59) MSC000001: Failed to start service jboss.deployment.subunit."TaraTicket.ear"."TaraTicketEJB.jar".component.InitializationBean.START: org.jboss.msc.service.StartException in service jboss.deployment.subunit."TaraTicket.ear"."TaraTicketEJB.jar".component.InitializationBean.START: java.lang.IllegalStateException: JBAS011048: Failed to construct component instance

How I get a @NamedQuery Query with WERE Command in Java EE?

hi i have a java ee application and I want to create a Query to get all Tickets from a User.

I have a Ticket class, TicketDAO Interface and TicketBean class I have a User class, UserDAO interface and UserBean class

Here is my User class:

  @Entity
    @NamedQueries({
        @NamedQuery(name=User.QUERY_GETALL,query="SELECT c FROM User c"),
        @NamedQuery(name=User.QUERY_GETALLTICKETS,query="SELECT c FROM Ticket c ...????"),
    })
    public class User implements Serializable{

        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        public static final String QUERY_GETALL = "User.GetAll";

        public static final String QUERY_GETALLTICKETS = "User.GetAllTickets";
...

here is my UserBean class:

@Override
public List<Ticket> getAllUserTickets() {

    return em.createNamedQuery(User.QUERY_GETALLTICKETS,Ticket.class).getResultList();
}

My Ticket Table have the column username.

running a class with main from a servlet in j2EE

How to (or can i) run a class with main() from a servlet??

i want to take input from a html page and insert data into a database using hibernate.

-i have an annotated class.

-a class having main(), running which inserts the data into the database.

-and a servlet with post method code:

String input_from_html=request.getParameter("input_from_html");

I need to put the data 'input_from_html' to the class with main() and run the class,which should happen once the submit button in the html page is pressed.

Scalable server side applications troubleshooting

I am looking for engineers that want to on the latest Java in Los Angeles. Needed ASAP. Do you know anyone? No resume needed, just a LinkedIn profile.

ConcurrentModificationException thrown by GlassFish 3.1.2.2 on commit of XA transaction

We have a Singleton EJB bean deployed in GlassFish 3.1.2.2 server with the following annotations:

@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
@Singleton
@Startup
@Local(XXX.class)
@TransactionAttribute(TransactionAttributeType.NEVER)

The bean is injected into a servlet which calls several methods on it. Randomly, the server.log shows that there are ConcurrentModificationException thrown by random methods of the bean on commit of XA transaction.

javax.transaction.xa.XAException: java.util.ConcurrentModificationException
    at com.sun.enterprise.resource.ConnectorXAResource.handleResourceException(ConnectorXAResource.java:115)
    at com.sun.enterprise.resource.ConnectorXAResource.resetAssociation(ConnectorXAResource.java:287)
    at com.sun.enterprise.resource.ConnectorXAResource.commit(ConnectorXAResource.java:128)
    at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:501)
    at com.sun.enterprise.transaction.JavaEETransactionManagerSimplified.commit(JavaEETransactionManagerSimplified.java:855)
    at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5136)
    at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4901)
    at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2045)
    at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1994)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:222)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:89)
    at com.sun.proxy.$Proxy258.getHostMonitorRecord(Unknown Source)
    at ...XProtocolHostServletBase.handleDocument(XProtocolHostServletBase.java:174)
    at ...TransactionHandlerServletBase.doPost(TransactionHandlerServletBase.java:44)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:688)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:724)

Apparently, the method calls are attached to the container managed transaction, even though the bean is annotated with TransactionAttributeType.NEVER. My question is why is the bean still transactional and what may be causing the random occurrence of this exception.

JDBC Connection pool - persistence.xml and GlassFish 4.1

I'm having an issue creating an EJBContainer for my EclipseLink/Derby/GlassFish setup. I am getting the following exception

java.lang.RuntimeException: Invalid resource : jdbc/users__pm
    at com.sun.enterprise.connectors.ConnectorRuntime.lookupDataSourceInDAS(ConnectorRuntime.java:593)
    at com.sun.enterprise.connectors.ConnectorRuntime.lookupPMResource(ConnectorRuntime.java:517)
    at org.glassfish.persistence.common.PersistenceHelper.lookupPMResource(PersistenceHelper.java:63)
    at org.glassfish.persistence.jpa.ProviderContainerContractInfoBase.lookupDataSource(ProviderContainerContractInfoBase.java:71)
    at org.glassfish.persistence.jpa.PersistenceUnitInfoImpl.<init>(PersistenceUnitInfoImpl.java:108)
    at org.glassfish.persistence.jpa.PersistenceUnitLoader.loadPU(PersistenceUnitLoader.java:142)
    at org.glassfish.persistence.jpa.PersistenceUnitLoader.<init>(PersistenceUnitLoader.java:107)
    at org.glassfish.persistence.jpa.JPADeployer$1.visitPUD(JPADeployer.java:223)
    at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:510)
    at org.glassfish.persistence.jpa.JPADeployer.createEMFs(JPADeployer.java:230)
    at org.glassfish.persistence.jpa.JPADeployer.prepare(JPADeployer.java:168)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:925)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:434)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:356)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:356)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
    at com.sun.enterprise.admin.cli.embeddable.DeployerImpl.deploy(DeployerImpl.java:133)
    at com.sun.enterprise.admin.cli.embeddable.DeployerImpl.deploy(DeployerImpl.java:109)
    at org.glassfish.ejb.embedded.EJBContainerImpl.deploy(EJBContainerImpl.java:138)
    at org.glassfish.ejb.embedded.EJBContainerProviderImpl.createEJBContainer(EJBContainerProviderImpl.java:134)
    at javax.ejb.embeddable.EJBContainer.createEJBContainer(EJBContainer.java:127)
    at javax.ejb.embeddable.EJBContainer.createEJBContainer(EJBContainer.java:102)
    at feature.user.UserSearchSteps.setup(UserSearchSteps.java:71)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at cucumber.runtime.Utils$1.call(Utils.java:37)
    at cucumber.runtime.Timeout.timeout(Timeout.java:13)
    at cucumber.runtime.Utils.invoke(Utils.java:31)
    at cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:59)
    at cucumber.runtime.Runtime.runHookIfTagsMatch(Runtime.java:222)
    at cucumber.runtime.Runtime.runHooks(Runtime.java:210)
    at cucumber.runtime.Runtime.runBeforeHooks(Runtime.java:200)
    at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44)
    at cucumber.runtime.junit.ExecutionUnitRunner.run(ExecutionUnitRunner.java:91)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:63)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:18)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:70)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:93)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:37)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.api.junit.Cucumber.run(Cucumber.java:98)
    at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: com.sun.appserv.connectors.internal.api.ConnectorRuntimeException: Invalid resource : jdbc/users__pm
    at org.glassfish.jdbcruntime.service.JdbcDataSource.validateResource(JdbcDataSource.java:81)
    at org.glassfish.jdbcruntime.service.JdbcDataSource.setResourceInfo(JdbcDataSource.java:62)
    at org.glassfish.jdbcruntime.JdbcRuntimeExtension.lookupDataSourceInDAS(JdbcRuntimeExtension.java:136)
    at com.sun.enterprise.connectors.ConnectorRuntime.lookupDataSourceInDAS(ConnectorRuntime.java:589)
    ... 78 more

This is thrown when I call the following

EJBContainer.createEJBContainer();

Here is my persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://ift.tt/1cKbVbQ" xmlns:xsi="http://ift.tt/ra1lAU" xsi:schemaLocation="http://ift.tt/1cKbVbQ http://ift.tt/1kMb4sd">
    <persistence-unit name="UsersJSFApplicationPU" transaction-type="JTA">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <jta-data-source>jdbc/users</jta-data-source>
        <class>uk.co.bas.model.entity.User</class>
        <class>uk.co.bas.model.entity.Location</class>
        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/users" />
            <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver" />
            <property name="javax.persistence.jdbc.password" value="paul" />
            <property name="javax.persistence.jdbc.user" value="paul" />
            <property name="eclipselink.logging.level" value="FINEST" />
            <property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
        </properties>
    </persistence-unit>
</persistence>

And this is my glassfish-resources.xml

I'm not sure what's wrong here?

Cannot inject bean of non-serializable type into bean of passivating scope

I'm learning Java EE 7.

I'm trying to store the user session in a @SessionScoped Backing Bean but my IDE is telling me that I have an error because "Cannot inject bean of non-serializable type into bean of passivating scope".

The @SessionScoped bean:

import negocio.Autenticacion;

import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.Serializable;

@Named
@SessionScoped
public class UserSesion implements Serializable{

    @Inject
    private Autenticacion auth; // Error by IDE


}

@Stateless EJB code:

import modelo.Usuario;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.security.MessageDigest;

@Stateless
public class AutenticacionBean implements Autenticacion{

    @PersistenceContext(unitName = "Banco-PU")
    private EntityManager em;
...

Why can't I Inject the EJB in the backing bean?

Difference between apache commons file upload and servlet 3.0 file upload

I wanna know advantages and disadvantages on apache file upload and servlet 3.0 file upload

updating jars in WEB-INF\lib folder are not recognize

I am new to this blog. Really i am having a problem. I replaced the old jars with my new jars in WEB-INF\lib folder. We are using Tomcat5 server. After moving my jars, i restarted the tomcat5 server. While testing the module, it is throwing exception. Because the updated jars are not taking effect.

Kindly help me ASAP. Thanks in advance.

lundi 29 juin 2015

JPA+EJB not managed entity in websocket communication

  1. Browser and server connected with websocket
  2. After connected, browser will send data, and handled in server by method 'firstMessage'. This method will store Player entity to variable named 'player' and change its data (it work fine, the database is change )
  3. Next, the browser send data again handled in server by method 'secondMessage'. It change the Player entity data that already stored before. the data is change, but the problem is the database not changing

    @Singleton
    @Startup
    public class Engine {
    
    @Inject DaoPlayer daoPlayer;
    Player player;    
    
    public void firstMessage(clientId){
        player = daoPlayer.findById(clientId);
        player.coin = 3;
    }
    
    public void secondMessage(){
        player.coin = 999;
    
    

    }

Problem :

Change in Player entity inside method 'secondMessage' not updating the database

What i try so far :

  • I already check class Engine, DaoPlayer and Player is the same instance (by generating random number when they created)
  • i do this in secondMessage and it work fine. but i dont want to this.

    public void secondMessage(){
        player.coin = 999;
        daoPlayer.getEntityManager().merge(player);
    
    

    }

    i expecting

    player.coin = 999; should be enough to update the database

Best practice to build a CD pipeline to deploy application to different environments

Currently I'm trying to build a CD pipeline for our application, which is a typical Maven J2EE project and we'll deploy a war to Tomcat container.

Our plan for the CD pipeline looks like this:

CI(Run UT and build the WAR) -> Deploy to DEV -> Deploy to SIT -> Deploy UAT -> Deploy PROD

To follow the best practices of CD, we only build the binary(war) once in the CI phase, but we have some configuration files which are different for each environment, so what's the best way to put the related configuration files for each environment during the deployment phase?

We're using Jenkins and the build-pipe-line plugin to build the pipeline, are there any recommended plugins to make this happen?

Thanks.

wizard style application with cdi, ejb and jsp

I am new to Java EE and trying to create a wizard step application using pure Java EE. I have a index servlet that has a button to launch the wizard. I have been reading about the conversationScoped annotation and would like to use it here. Can somebody give me a starting point?

  1. user requests url/index
  2. IndexServlet is called. It display index.jsp with a table. The last column in the table is "launch". It launches the wizard for the given project. It is an "" element with href="wizard?id=#{project.id}" where id will be used to prepopulate wizard with appropriate data for the give instance id
  3. this is where I confused. Does the wizard servlet start a conversation scope that is maintained until the user closes the tab or signs out?
  4. I want to keep current page user is on, next and previous pages at any given time along with the model for the wizard content. Do these go into conversation scope?
  5. Finally, how does the jsp know about model stored in the conversation scope? I am confused with servlet which is requestscope and conversationscope that I want to maintain over multiple requests.

Thank you much !

IllegalArgumentException: Invalid ejb jar: it contains zero ejb

I've seem plenty of questions regarding this issue and I still couldn't get it fixed, I'm aware that this exception is thrown when one tries to deploy an ejb module without any classes annotated with @Stateless, @Stateful, @MessageDriven or @Singleton. But that isn't my case, I have several classes annotated like this:

@Stateless
@Remote(TestServiceInterface.class)
public class TestService extends TestSuperclass implements TestServiceInterface<Test>, Serializable{
}

and here is the interface:

public interface TestServiceInterface<T> extends AnotherInterface<T>{
}

All of my interfaces are located in another project, which have its jar added to my ejb module as a lib.

When I try to deploy I get the following exception:

1. A valid ejb jar requires at least one session, entity (1.x/2.x style), or message-driven bean. 
2. EJB3+ entity beans (@Entity) are POJOs and please package them as library jar. 
3. If the jar file contains valid EJBs which are annotated with EJB component level annotations (@Stateless, @Stateful, @MessageDriven, @Singleton), please check server.log to see whether the annotations were processed properly.
    at com.sun.enterprise.deployment.util.EjbBundleValidator.accept(EjbBundleValidator.java:76)
    at com.sun.enterprise.deployment.util.ApplicationValidator.accept(ApplicationValidator.java:128)
    at com.sun.enterprise.deployment.EjbBundleDescriptor.visit(EjbBundleDescriptor.java:730)
    at com.sun.enterprise.deployment.Application.visit(Application.java:1765)
    at com.sun.enterprise.deployment.archivist.ApplicationFactory.openArchive(ApplicationFactory.java:195)
    at org.glassfish.javaee.core.deployment.DolProvider.load(DolProvider.java:185)
    at org.glassfish.javaee.core.deployment.DolProvider.load(DolProvider.java:94)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.loadDeployer(ApplicationLifecycle.java:827)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.setupContainerInfos(ApplicationLifecycle.java:769)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:368)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:389)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:348)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:363)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1085)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:95)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1291)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1259)
    at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:461)
    at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:212)
    at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:179)
    at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$Hk2DispatcherCallable.call(ContainerMapper.java:354)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:745).

UPDATE:

It also prints this line just before throwing the exception:

[#|2015-06-25T08:43:22.256-0300|WARNING|glassfish3.1.2|global|_ThreadID=126;_ThreadName=Thread-2;|Error in annotation processing: java.lang.NoClassDefFoundError: com/packageName/TestServiceInterface|#]

UPDATE 2

It seems like netbeans is somehow being able to deploy it! But if I try to deploy directly on the glassfish admin page or via command line("asadmin deploy") I get the exception.

I'm probably missing something, any help would be appreciated.

What is the scope of @Stateless EJB 3 bean? When are dependency injections processed?

I read the following question below, but have some follow-up questions and confirmations:

Scope of Stateless Bean

This is really confusing point and reading the WELD documentation doesn't seem to explicitly mention how these situations are handled, which is kind of frustrating. It has a lot of verbiage but doesn't seem to provide any simple code examples that basically illustrate WHEN the equivalent of the new XXX() and setXXX() methods are called by the container within different contexts, which is basically all this CDI nightmare is doing for us (and for some reason this is a good idea?). I guess it is even more confusing when you throw JSF managed beans into the mix, which is in itself another disaster since JSF has it's own managed beans that came before CDI.

Q: What is the scope of a bean declared @Stateless? When when the @Inject annotations be processed (and thus when will @PostConstruct be called)?

My understanding is that it is basically @ApplicationScoped as described in the answer above, in so far as the container will pool instances and re-use them when possible. When the container retrieves a pooled instance that is already created, it will not re-inject the @Inject dependencies and thus will not call @PostConstruct again. However, I thought if no scope was declared, each bean should be considered @Dependent scoped, which means at each Injection point a new object is created and thus dependencies re-injected, but this seems not to be the case. Is this different because this an EJB bean and not a pure CDI bean?

Additional questions, assuming the above is correct:

  1. Is there a way to force it to re-inject all of these dependencies before each method call in a client, which is for example a JSF ViewScoped bean?

  2. Does it matter if the client who itself injected the @Stateless EJB used @Inject or @EJB before calling any of its methods?

Take the following example:

@Stateless
public class MyEJB implements MyEjbInterface {
    @Inject MyOtherObject myotherObject;

    void setMyOtherObject(MyOtherObject myotherObject) { ... }
    void method() { ... }
}

@ViewScoped
public class MyViewScopedBean {
   @Inject MyEjbInterface a;
   @EJB MyEjbInterface b;

   void a() {
      a.method();
   }

   void b {
     b.method();
   }
}

So in this example, when will an actual new MyEJB be created (not the proxy object)? When will setMyOtherObject be invoked? How can I force setMyOtherObject to be invoked before every method call by the container without explicitly invoking it myself?

And finally, how does this change MyOtherObject is created by a CDI producer and is not a CDI managed bean. Does the scope of the producer matter?

Jndi lookup throws naming exception

I'm using Jndi lookup for getting object of a class defined in a third party jar file.Jar is included in library and in lookup i have given correct path of class for which i want to create object by jndi lookup

jndiname-"abc-core-1.0/com.cmpny.service.Abcservice" and I have abc-core-1.0 in my library that has a class file Abcservice in the same path (com.cmpny.service.Abcservice)

    jndiname="abc-core-1.0/com.cmpny.service.Abcservice";Properties properties=new Properties();
properties.put(Context.URL_PKG_PREFIXES,PKG_INTERFACES)
InitialContext obj=new IntialContext(properties);
obj.lookup(jndiname);

please let me know what else could be reason NamingException

Thanks & Regards

Why should i add state?

Hi, I get this error and i don't know why ??

Start state is missing. Add at least one state to the flow

File : main-flow.xml
<?xml version="1.0" encoding="UTF-8"?>
<flow xmlns="http://ift.tt/1jwD1YA"
xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://ift.tt/1jwD1YA
    http://ift.tt/1Jk0LtK">

<view-state id="start" view="start.xhtml">

</view-state>

File pom.xml
 <dependency>
        <groupId>org.springframework.webflow</groupId>
        <artifactId>spring-webflow</artifactId>
        <version>2.3.1.RELEASE</version>
    </dependency>

Clip Path coordinates programmatically

I've some paths and I would like to clip these paths to a specific region (green) resulting in the remaining paths (red):

enter image description here

What is the best way/approach to do this commonly with manually cutting the paths?

JUnit using Mockito for Servlet Test Case

I am try to do a basic mock of my servlet for a JUnit test case. However, I am receiving 0 code coverage from this particular test case. Here is my test case:

    @Test
    public void testServlet() throws ServletException, IOException {
        HttpServletRequest request = mock(HttpServletRequest.class);       
        HttpServletResponse response = mock(HttpServletResponse.class); 

        DownloadServlet servlet = new DownloadServlet();
        servlet.doGet(request, response);
        assertEquals("text/html", response.getContentType());
    }

I am testing my doGet method in the servlet in which I am pretty sure the only code that is testable is the response.setContentType("text/html"). However, my test case isn't doing anything. Here is my DownloadServlet class:

package downloadsupport;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ibm.ws.security.spnego.Context;

import downloadsupport.LogRead;

/**
 * Servlet implementation class DownloadServlet
 * @author Gabe
 * @version 1.0
 */
@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */
public DownloadServlet() {
    super();
}

private LogRead getInstance(){
    return new LogRead();
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Download Servlet Invoked");
    response.setContentType("text/html");

    PrintWriter out = response.getWriter();
    LogRead log = getInstance();
    // Test if each log file in the folder is success or fail
    for (String emailName : log.getEmails()) {
        if (log.canReadLog(emailName)) {
            System.out.println("Log Successful: " + emailName);
            // Create HTML button to download a successful file
            out.println("<div class='viewButton'>");
            out.println("<form method='get' action=" + emailName +">"); // emailName is the file to download
            out.println("<button type='submit' class='successButton'>"
                    + "Success: " + emailName + "</button>");
            out.println("</form>");
            out.println("</div>");
        } 
        else {
            System.out.println("Log Failed: " + emailName);
            // Create HTML button to download a failed file
            out.println("<div class='viewButton'>");
            out.println("<form method='get' action=" + emailName +">"); // emailName is the file to download
            out.println("<button type='submit' class='failButton'>"
                    + "Fail: " + emailName + "</button>");
            out.println("</form>");
            out.println("</div>");
        }
    }
    out.println("<br>");

    System.out.println(log.getEmails());
}

}

DataSources in WebSphere

There is a data source with JNDI name "jdbc/project/SimpleDS" defined in WebSphere 7. In admin console I changed the data source properties: db_name, db_port, db_host , login and password.

Whereby the deployed applications which references to "jdbc/project/SimpleDS" data source throws the exception:

java.sql.SQLInvalidAuthorizationSpecException: [jcc][t4][2013][11249]
[4.8.87] Connection authorization failure occurred.  Reason: User ID or Password invalid. ERRORCODE=-4214, SQLSTATE=28000DSRA0010E: 
SQL State = 28000, Error Code = -4,214
    at com.ibm.db2.jcc.am.gd.a(gd.java:674)
    at com.ibm.db2.jcc.am.gd.a(gd.java:60)
    at com.ibm.db2.jcc.am.gd.a(gd.java:120)
    at com.ibm.db2.jcc.t4.b.p(b.java:2060)
    at com.ibm.db2.jcc.t4.b.c(b.java:1649)
    at com.ibm.db2.jcc.t4.db.r(db.java:799)
    at com.ibm.db2.jcc.t4.db.k(db.java:353)
    at com.ibm.db2.jcc.t4.db.c(db.java:133)
    at com.ibm.db2.jcc.t4.b.Wc(b.java:1263)
    at com.ibm.db2.jcc.t4.b.b(b.java:1184)
    at com.ibm.db2.jcc.t4.b.a(b.java:5175)
    at com.ibm.db2.jcc.t4.b.d(b.java:743)
    at com.ibm.db2.jcc.t4.b.c(b.java:685)
    at com.ibm.db2.jcc.t4.b.a(b.java:368)
    at com.ibm.db2.jcc.t4.b.<init>(b.java:308)
    at com.ibm.db2.jcc.t4.c.<init>(c.java:32)
    at com.ibm.db2.jcc.DB2PooledConnection.<init>(DB2PooledConnection.java:192)
    at com.ibm.db2.jcc.DB2XAConnection.<init>(DB2XAConnection.java:56)
    at com.ibm.db2.jcc.DB2XADataSource.getXAConnection(DB2XADataSource.java:168)
    at com.ibm.ws.rsadapter.spi.InternalGenericDataStoreHelper$1.run(InternalGenericDataStoreHelper.java:1338)
    at com.ibm.ws.security.util.AccessController.doPrivileged(AccessController.java:118)
    at com.ibm.ws.rsadapter.spi.InternalGenericDataStoreHelper.getPooledConnection(InternalGenericDataStoreHelper.java:1375)
    at com.ibm.ws.rsadapter.spi.InternalDB2UniversalDataStoreHelper.getPooledConnection(InternalDB2UniversalDataStoreHelper.java:1855)
    at com.ibm.ws.rsadapter.spi.WSRdbDataSource.getPooledConnection(WSRdbDataSource.java:2624)
    at com.ibm.ws.rsadapter.spi.WSManagedConnectionFactoryImpl.createManagedConnection(WSManagedConnectionFactoryImpl.java:1695)
    at com.ibm.ejs.j2c.FreePool.createManagedConnectionWithMCWrapper(FreePool.java:2086)
    at com.ibm.ejs.j2c.FreePool.createOrWaitForConnection(FreePool.java:1761)
    at com.ibm.ejs.j2c.PoolManager.reserve(PoolManager.java:2636)
    at com.ibm.ejs.j2c.ConnectionManager.allocateMCWrapper(ConnectionManager.java:1064)
    at com.ibm.ejs.j2c.ConnectionManager.allocateConnection(ConnectionManager.java:701)
    at com.ibm.ws.rsadapter.jdbc.WSJdbcDataSource.getConnection(WSJdbcDataSource.java:668)
    at com.ibm.ws.rsadapter.jdbc.WSJdbcDataSource.getConnection(WSJdbcDataSource.java:635)

How can I replace the data source properties in runtime?

JEE / Objectify get a list filtered by another using ofy()

I don't get why this is not working:

ofy().load().type(Log.class).filter("license in",ofy().load().type(License.class).filter("name",licName)).list();

or this too:

ofy().load().type(Log.class).filter("license in",ofy().load().type(License.class).filter("name",licName).list()).list();

My License is a reference in my Log. Can I do it using ofy() ?

Can anyone explain me?

Task not serializable exception in spark while used in JEE project

Following code is working fine when used in java console application. A and C classes both are serialable. When same code is used in JEE aRDD and bRDD are working good but performing the flatMap transformation on aRDD is throwing Task not serialable exception.

            JavaPairRDD<String,Iterable<A>> aRDD= CassandraJavaUtil.javaFunctions(sc).
                    cassandraTable("testing", "cf_taxlots",CassandraJavaUtil.mapRowTo(DailyTaxlot.class, colMap)).
                    where("openclosetag=? and rundate IN ?","Open",dates).groupBy(row -> row.getTaxlotId());

            JavaPairRDD<String,Iterable<A>> bRDD = CassandraJavaUtil.javaFunctions(sc).
                    cassandraTable("testing", "cf_taxlots",CassandraJavaUtil.mapRowTo(DailyTaxlot.class, colMap)).
                    where("openclosetag=? and rundate IN ?","Close",dateRange).groupBy(row -> row.getTaxlotId());

            JavaRDD<C> finalRDD = aRDD.flatMap( new FlatMapFunction<Tuple2<String,Iterable<A>>, C>() {
                public Iterable<C> call(Tuple2<String,Iterable<C>> tuple) throws Exception
                { ....... });

What is wrong with flatMap transformation on aRDD? Why its working on the java console application? Any pointers??

Irregular error 404 when java EE application deployed

I made a small webapp using java EE and tomcat 6. Everything works #1 when tested on localhost. I packaged my webapp and deployed it on our test server. Sometimes it works as intended and sometimes I get 404 error while accessing the url.

Some infos:

I'm using tomcat 7 on the server (could the change in version be the problem?). Server uses https. My index page is in WEB-INF and is mapped to a servlet. The webapp is actually deployed on 2 servers which toggles (I show the hostname at the top of my app and I can confirm both works).

Other note : When I get the 404 error, refreshing doesn't work right away, it can take a few minutes before it works again. While I'm getting 404 error when I call the URL mapped to my servlet, I can still call test.html which is outside of WEB-INF and it will display properly. It feels as if the mapping isn't done properly sometimes. Could it be a problem with web.xml ?

how to combine data from different resultsets into one?

I am currently working on a j2ee project to implement an online shopping website using jsp and servlets. I have stored product ids in a string array and wish to fetch all the rows corresponding to these ids from another table into a single reultset. what could be the possible logic for this? need suggestions ASAP. thanks in advance.

Is it mandatory to use start() and stop() methods while implementing JBoss MBean service?

I am trying to learn JMX provided by JBoss with this example: ExampleHelloWorldService

After deploying the SAR file, I am able to see the operation and attributes in JConsole.

In the example, start() and stop() methods are used in the MBean implementation class as a purpose of service lifecycle callback.

Is it really necessary, to include these methods? I tried by removing these methods and I didn't see any difference in the result i.e. I am still able to access both the attribute and operation in the JConsole.

EJB java.lang.ClassCastException

I'm using Eclipse with Glassfish for my first steps in Java EE. I've created three eclipse projects (JPA project, EJB project Web project). I've created a local EJB bean TestBean with a local interface TestBeanLocal:

@Stateless
@LocalBean
class TestBean implements TestBeanLocal {
  @Override
  public void doSomething(List<JPAEntity> myEntities) {
    for(JPAEntity a : myEntities) {

    }
  }
}

and a ManagedBean that uses the EJB:

@MangagedBean
public class MyBean {
    @EJB
    private TestBeanLocal testBean;

    @PostConstruct
    private void init() {
       //load JPAEntity from Database
       List<JPAEntity> myEntities = ....
       testBean.doSomething(myEntities);
    }
}

My problem is that I get a ClassCastException at the for loop in the TestBean.

java.lang.ClassCastException: us.mypackage.jpa.JPAEntity cannot be cast to us.mypackage.jpa.JPAEntity

I found another stackoverflow question that says that this error message is because of two different classloaders. How can I fix this? Can I tell EJB to use the same classloader that my webproject uses?

JBoss Server - Apache Tomcat get Client Ip using J2EE

I am using JBoss Server version 5.x with Apache tomcat 7. I am trying to get the client IP address using following code in my Jsp file :

request.getRemoteAddr();

But it is always returning me the server's IP.I am not using any load balancer.In my Jboss access logs , I can see the client IP Address.

Please help me to know where am I making mistake?

SQL Server connection in Wildfly using JTDS driver

What is the correct way to setup a SQL Server datasource on Widlfly?

I need to access a SQL Server database from my web application which runs on Wildfly.

I have setup the datasource as follows:

<datasource jta="false" jndi-name="java:jboss/db" pool-name="db" enabled="true" use-ccm="false">
    <connection-url>jdbc:jtds:http://sqlserverIP_ADDRESS;instance=SQLEXPRESS;DatabaseName=DB</connection-url>
    <driver-class>net.sourceforge.jtds.jdbc.Driver</driver-class>
    <driver>jtds-1.3.1.jar</driver>
</datasource>

This works fine except that when the SQL Server is restarted, the connection is lost and the datasource doesn't manage to recreate one. So I get errors like:

Invalid state, the Connection object is closed.

This post suggests adding some validation, so I did this:

<validation>
    <check-valid-connection-sql>SELECT 1</check-valid-connection-sql>
    <validate-on-match>false</validate-on-match>
    <background-validation>false</background-validation>
</validation>

But that does not solve the problem and I still get the same "connection closed" error from time to time.

This other post suggests using a DataSource instead of a Driver, so I have added this to my configuration:

    <datasource-class>net.sourceforge.jtds.jdbcx.JtdsDataSource</datasource-class>

But when I test the connection I get an exception:

java.sql.SQLException: The serverName property has not been set.
at net.sourceforge.jtds.jdbcx.JtdsDataSource.getConnection(JtdsDataSource.java:150)

Is HttpServletRequest.getRequestURL() spoofable?

The question is self explanatory, I hope. I am setting up a Spring Security enviroment with a CAS-server. Because the exact same application is deployed on the same server, but the server is accessible via different host names (.de domain, .com domain, possibly more than that) and we want to deploy the same application on test systems and the local one as well, I built a dynamic service, where the service URL is derived from request URL.

public static String makeDynamicUrlFromRequest(ServiceProperties serviceProperties, HttpServletRequest request) {
        String serviceUrl = "http://ift.tt/1FJUxOX";
        URI uri = null;
        try {
            uri = new URI(request.getRequestURL().toString());
        } catch (URISyntaxException e) {
            logger.error("Someone tried accessing a disallowed service!", e);
        }

        if(uri != null){
            serviceUrl = uri.getScheme() + "://" + uri.getHost() + "/login";
        }

        return serviceUrl;
    }

Is it possible to spoof this? If it is, does an additional regex-check provide me with the necessary security against this?

dimanche 28 juin 2015

sorting on map based on values

How to sort a hash map based on values and if the values are same then the sorting should be on the key.

I tried to use a comparator, but its not giving expected results.

I want the result to be like this

results: {Bajaj=8.0, Tata=7.99, Maruthi=6.34, Kmart=5.99, Honda=5.78, Adidas=4.99,Ford=3.99, Nike=3.99, Sears=3.99, Suzuki=3.99, Apple=2.99, Puma=1.99}

public class Test {

public static void main(String[] args) {

    HashMap<String,Double> map = new HashMap<String,Double>();
    ValueComparator bvc =  new ValueComparator(map);
    TreeMap<String,Double> sorted_map = new TreeMap<String,Double>(bvc);

    map.put("Adidas",4.99);
    map.put("Nike",3.99);
    map.put("Puma",1.99);
    map.put("Ford",3.99);
    map.put("Apple",2.99);
    map.put("Sears",3.99);
    map.put("Kmart",5.99);
    map.put("Tata",7.99);
    map.put("Maruthi",6.34);
    map.put("Honda",5.78);
    map.put("Bajaj",8.0);
    map.put("Suzuki",3.99);

    System.out.println("unsorted map: "+map);

    sorted_map.putAll(map);

    System.out.println("results: "+sorted_map);
}
}

class ValueComparator implements Comparator<String> {

Map<String, Double> base;
public ValueComparator(Map<String, Double> base) {
    this.base = base;
}

// Note: this comparator imposes orderings that are inconsistent with equals.    
public int compare(String a, String b) {
    if (base.get(a) > base.get(b)) {
        return -1;
    } 
    else if(base.get(a) == base.get(b))
    {
        System.out.println();
        if(a.compareTo(b) == -1)
        {

            return -1;
        }
        else if(a.compareTo(b) == 1)
        {

        return 1;
        }
        else
        {

            return 0;
        }
    }
    else {
        return 1;
    } // returning 0 would merge keys
}
}

jstl importing not work in linux

im trying to work with spring mvc and run my project in windows correctly :

<%@ taglib prefix="c" uri="http://ift.tt/QfKAz6"%>

and add dependency in pom.xml

<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

this code work correctly work but when i use war file in linux and deploy it , not working.when i comment jst/core importing , it work !!

any solotion ?

Openshift - deploying simple Java EE app on Wildfly fails

I'm trying to deploy a very simple application on Openshift. It's an EAR project with a single WAR and EJB module. Inside the WAR there's a REST service that calls an EJB defined in EJB module. Locally and on Openshift I'm using Wildfly 9.0.0 CR2 and PostgreSQL 9.2. When deploying locally everything works fine. When the same code is deployed on Openshift I'm getting following errors in logs:

2015-06-28 18:23:04,574 WARN  [org.jboss.as.clustering.jgroups] (MSC service thread 1-1) WFLYCLJG0006: property bind_addr for protocol org.jgroups.protocols.TCP attempting to override socket binding value 127.12.77.1 : property value 127.12.77.1 will be ignored
2015-06-28 18:23:04,574 WARN  [org.jboss.as.clustering.jgroups] (MSC service thread 1-1) WFLYCLJG0006: property bind_port for protocol org.jgroups.protocols.TCP attempting to override socket binding value 7600 : property value 7600 will be ignored
2015-06-28 18:23:06,252 INFO  [org.jboss.as.jpa] (ServerService Thread Pool -- 70) WFLYJPA0010: Starting Persistence Unit (phase 2 of 2) Service 'http://ift.tt/1TYvqCX'
2015-06-28 18:23:08,165 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-1) MSC000001: Failed to start service jboss.jgroups.channel.ee: org.jboss.msc.service.StartException in service jboss.jgroups.channel.ee: java.security.PrivilegedActionException: java.net.BindException: [TCP] /127.12.77.1 is not a valid address on any local network interface
        at org.wildfly.clustering.jgroups.spi.service.ChannelBuilder.start(ChannelBuilder.java:79)
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948)
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: java.security.PrivilegedActionException: java.net.BindException: [TCP] /127.12.77.1 is not a valid address on any local network interface
        at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:638)
        at org.jboss.as.clustering.jgroups.JChannelFactory.createChannel(JChannelFactory.java:99)
        at org.wildfly.clustering.jgroups.spi.service.ChannelBuilder.start(ChannelBuilder.java:77)
        ... 5 more
Caused by: java.net.BindException: [TCP] /127.12.77.1 is not a valid address on any local network interface
        at org.jgroups.util.Util.checkIfValidAddress(Util.java:3480)
        at org.jgroups.stack.Configurator.ensureValidBindAddresses(Configurator.java:902)
        at org.jgroups.stack.Configurator.setupProtocolStack(Configurator.java:118)
        at org.jgroups.stack.Configurator.setupProtocolStack(Configurator.java:57)
        at org.jgroups.stack.ProtocolStack.setup(ProtocolStack.java:477)
        at org.jgroups.JChannel.init(JChannel.java:854)
        at org.jgroups.JChannel.<init>(JChannel.java:159)
        at org.jboss.as.clustering.jgroups.JChannelFactory$1.run(JChannelFactory.java:96)
        at org.jboss.as.clustering.jgroups.JChannelFactory$1.run(JChannelFactory.java:93)
        at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:634)
        ... 7 more

The address mentioned - 127.12.77.1 is $OPENSHIFT_WILDFLY_IP. I have no idea what is causing this issue. First I thought it's a database connectivity issue because it happens when 2nd phase of starting persistence unit happens. I connected to DB on Openshift and saw that it was created successfully so maybe that's not it, but here's the persistence.xml I'm using:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://ift.tt/UICAJV" xmlns:xsi="http://ift.tt/ra1lAU"
    xsi:schemaLocation="http://ift.tt/UICAJV http://ift.tt/O9YdEP">
    <persistence-unit name="cookingPU">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <jta-data-source>java:jboss/datasources/PostgreSQLDS</jta-data-source>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL9Dialect" />
        </properties>
    </persistence-unit>
</persistence>

The datasource used is the default one. I didn't change anything in standalone.xml.

Another thing I noticed is that the deploy problem happens when I add any EJB to the project. This is a simple one I tried to use:

@Stateless
public class AnyEjb {
    public String hello() {
        return "Hi there!";
    }
}

This is defined in EJB module. Then in web module I have this class calling it:

@Path("anything")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class AnyEndpoint {

    @EJB
    private AnyEjb anyEjb;

    @GET
    public String sayHi() {
        return anyEjb.hello();
    }
}

I'm not sure if and how it can be connected with this BindException. I've tried running this application locally with both standalone and standalone-full-ha profile and it works in both cases. I just feel it has to be some issue with Openshift configuration but I have no idea where to look anymore. I'm very new to Openshift and Java EE. Please point me in a right direction. Any help will be much appreciated.

Can I embbed a Java EE web page inside a webview in android?

I want to make certain reports in Java EE using the library primefaces for generating reports and then, showing them, just the table, inside a webview in an android app.

Has someone did that?

Does all the funcionality of html5, javaEE, jpa, work fine inside a webview in android, like they work in a browser, let's say, Chrome?

Valid cannot be resolved to a type Spring 4.0.3

I am facing the issue that @Valid annotation cannot be resolved, though i have added the dependency , configured pom.xml and Default-servlet.xml

Please find the codes below:

@RequestMapping(value = "/", method = RequestMethod.POST)
    public String loginProcess(@ModelAttribute("user") @Valid User userToBeValidated,BindingResult result , HttpServletRequest request){

pom.xml

<dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>4.3.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.0.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.0.0.GA</version>
    </dependency>   

DefaultServlet-servlet.xml

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

Any help is highly appreciated. Thanks in advanceenter image description here

JAAS get User information

I used JAAS and I don't know how to get the information about the user id, username .. should I set the values using a ManagedBean, or the JAAS it self provides it.

Java Custom Contraint - Validate only if other annotation is passed

Situation: I have a basic custom validation setup as below:

@NotNullOrEmpty(message="{err.msg.required}", fieldName="Email")
@ValidEmail(message="{err.msg.validEmail}", fieldName="Email")
private String email;

However, if the email is empty, BOTH are triggered because of course, an empty email is not a valid email.

Question: How do I trigger only @NotNullOrEmpty if its empty and only trigger @ValidEmail if it's non-empty?

Or is it possible to like

@Annotation1
@Annotation2 //trigger only if value has passed @Annotation1

What I have in mind is to edit my ValidEmailValidator.isValid() to return true if email is empty, but what if I want to validate empty emails in the future?

@Inject and @PostConstruct not worked in singleton pattern

I have a class as below:

public class UserAuthenticator {

    private static UserAuthenticator authenticator = 

    @Inject
    private UserRepository userRepository;

    @PostConstruct
    public void init() {
        List<User> allUsers = userRepository.findAll();
        for (User user : allUsers) {
            users.put(user.getEmail(), user.getPassword());
            serviceKeys.put(user.getServiceKey(), user.getEmail());
        }
    }

    public static UserAuthenticator getInstance() {
        if (authenticator == null) {
            authenticator = new UserAuthenticator();
        }
        return authenticator;
    }
}

When I call

UserAuthenticator authenticator = UserAuthenticator.getInstance();

init() method isn't called and userRepository is null

My web application run in JBOSS EAP 6.3

Can somebody help me!!

i cann't import my css into project java web

i'm beginner in java web.. so i can't import file css into project java web, please help me fix it, thanks so much this is my code

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://ift.tt/kTyqzh">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Demo Form Angular</title>
<script src="lib/angular.min.js"></script>
<link type="text/css" rel="stylesheet" href="<c:url value="/css/formAngular.css"" />
</head>
<body>
<div>
<p class="contain">Hello Angular</p>
</div>
</body>
</html>

`

Wildfly local jndi property

I am currently migrating my maven ear from glassfish 4 to wildfly 8.2. The problem i am facing right now are the jndi properties. In my ejb package i have in the META-INF folder following file:

ejb-jar.xml:

<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns = "http://ift.tt/nSRXKP" 
         version = "3.1"
         xmlns:xsi = "http://ift.tt/ra1lAU" 
         xsi:schemaLocation = "http://ift.tt/nSRXKP http://ift.tt/1zK8E6E">
    <enterprise-beans>
        <session>
            <ejb-name>HelloWorldEJB</ejb-name>
            <env-entry>
                <description>Some description</description>
                <env-entry-name>HelloWorld</env-entry-name>
                <env-entry-type>java.lang.String</env-entry-type>
                <env-entry-value>testvalue</env-entry-value>
            </env-entry>
        </session>
    </enterprise-beans>
</ejb-jar>

And i inject the property in my ejb like that:

@Stateless
@LocalBean
public class HelloWorldEJB {

    @Resource(name = "HelloWorld")
    private String helloWorld;

}

Anybody an idea?

samedi 27 juin 2015

How to Integrates a new functionality code to Java-EE application?

I have built a simple java-ee system and I want users to extends its functionality by developing an independent java application and upload it to my server as a .jar file.

My system is using EJB-3.2 to implement the business logic which is a list of services where each service is represented by a stateless session bean.

Is it a good practice to integrate a .jar files to the system like here, here, or here? What are the best practices used to integrate new code to a java system?

Thanks in advance.

Bean : Target unreachable , identifier bean resolved to null - JSF

Target unreachable error is coming, somehow my bean is not initializing and the value of the bean is coming null. My helloBean reference is coming null.

POM.xml

<project xmlns="http://ift.tt/IH78KX"           xmlns:xsi="http://ift.tt/ra1lAU"
  xsi:schemaLocation="http://ift.tt/IH78KX    http://ift.tt/HBk9RF">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.rout.sagar</groupId>
 <artifactId>DemoMavenJAVAEE</artifactId>
 <packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>DemoMavenJAVAEE Maven Webapp</name>
<url>http://ift.tt/19pvvEY;
<dependencies>
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>3.8.1</version>
  <scope>test</scope>
</dependency>
<dependency>
    <groupId>com.sun.faces</groupId>
    <artifactId>jsf-api</artifactId>
    <version>2.1.7</version>
</dependency>
<dependency>
    <groupId>com.sun.faces</groupId>
    <artifactId>jsf-impl</artifactId>
    <version>2.1.7</version>
</dependency>

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


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

    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.1</version>
    </dependency>
            <!-- Tomcat 6 need this -->
    <dependency>
        <groupId>com.sun.el</groupId>
        <artifactId>el-ri</artifactId>
        <version>1.0</version>
    </dependency>

 </dependencies>
 <build>
<finalName>DemoMavenJAVAEE</finalName>

    </build>
</project>

HelloBean.java

package com.rout.sagar;

   import javax.faces.bean.ManagedBean;
   import javax.faces.bean.SessionScoped;
   import java.io.Serializable;

   @ManagedBean
   @SessionScoped
   public class HelloBean implements Serializable{
private static final long serialVersionUID = 1L ; 
private HelloBean hello ;

private String name ; 
public String getName() {
    return name ;
}

public void setName(String name) {
    this.name = name ;
}}

Web.XML

<?xml version="1.0" encoding="UTF-8"?>
 <web-app xmlns:xsi="http://ift.tt/ra1lAU"
xmlns="http://ift.tt/nSRXKP" 
    xmlns:web="http://ift.tt/LU8AHS"
xsi:schemaLocation="http://ift.tt/nSRXKP 
http://ift.tt/LU8AHS"
id="WebApp_ID" version="2.5">

<display-name>DemoMavenJAVAEE</display-name>

<!-- Change to "Production" when you are ready to deploy -->



<context-param>
<param-name>org.apache.myfaces.annotation.SCAN_PACKAGES</param-name>
 <param-value>com.rout.sagar.HelloBean</param-value>
</context-param>
<!-- Welcome page -->
<welcome-file-list>
    <welcome-file>faces/hello.xhtml</welcome-file>
</welcome-file-list>

<!-- JSF mapping -->
<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<!-- Map these files with JSF -->
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
</web-app>

faces-config.xml

<?xml version="1.0"?>
    <faces-config xmlns="http://ift.tt/nSRXKP"
    xmlns:xsi="http://ift.tt/ra1lAU"
    xsi:schemaLocation="http://ift.tt/nSRXKP
    http://ift.tt/1cpkFEe"
    version="2.0">

    <navigation-rule>
<from-view-id>/hello.xhtml</from-view-id>
<navigation-case>
    <from-outcome>success</from-outcome>
    <to-view-id>/welcome.xhtml</to-view-id>
</navigation-case>
</navigation-rule>

</faces-config>

hello.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:f="http://ift.tt/HcrI1S"
xmlns:h="http://ift.tt/HjFrZb">

 <h:head>
<title>JSF 2.0 Hello World</title>
</h:head>
<h:body>
<h3>JSF 2.0 Hello World Example - hello.xhtml</h3>
<h:form>
    <h:inputText value="#{helloBean.name}"></h:inputText>
    <h:commandButton value="Welcome Me" action="welcome"></h:commandButton>
</h:form>
</h:body>
 </html>

Welcome.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">


<h:head>
  <title>JSF2.0 hello World    </title>
</h:head>     
  <h:body bgcolor = "red">
  <h2>JSF 2.0 Hello World Example welcome.xhtml</h2>
  <h2>Welcome #{helloBean.name}</h2>
  </h:body>
  </html>

Folder Structure in Eclipse

Hibernate SQL Grammar Exception JPA 2.1

I am having a problem when I test my application and try to insert in a table.

In more detail, I get this exception:

http://ift.tt/1CB4QF3

Im using Hibernate as persistence provider and JPA 2.1, Java EE 7, WildFly 8.2.0 and JSF 2.2.

In JBoss 7.1.1 and Java EE 6 I have the same application and works fine, but not now...

persistence.xml

    <?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://ift.tt/1cKbVbQ"
             version="2.1"
             xmlns:xsi="http://ift.tt/ra1lAU"
             xsi:schemaLocation="http://ift.tt/1cKbVbQ http://ift.tt/1kMb4sd">

    <persistence-unit name="Agenda-PU" transaction-type="JTA">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <jta-data-source>java:jboss/datasources/MySQLDS</jta-data-source>
        <properties>
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/test_app"/>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.password" value="root"/>
            <property name="hibernate.archive.autodetection" value="class"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hbm2ddl.auto" value="create"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
        </properties>
    </persistence-unit>
</persistence>

Im injecting the EJB in the ManagedBean with @EJB annotation, aparently all of the code works fine...

Here's the code of the ManagedBean:

import modelo.Usuario;
import negocio.Negocio;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@RequestScoped
public class Registro {

    @EJB
    private Negocio negocio;

    private Usuario usuario;
    private String repass;

    private String cuenta;

    private boolean registroOK;

    @PostConstruct
    public void init(){
        usuario = new Usuario();
    }

    public Usuario getUsuario() {
        return usuario;
    }

    public void setUsuario(Usuario usuario) {
        this.usuario = usuario;
    }

    public String getRepass() {
        return repass;
    }

    public void setRepass(String repass) {
        this.repass = repass;
    }

    public String getCuenta() {
        return cuenta;
    }

    public void setCuenta(String cuenta) {
        this.cuenta = cuenta;
    }

    public boolean isRegistroOK() {
        return registroOK;
    }

    public void setRegistroOK(boolean registroOK) {
        this.registroOK = registroOK;
    }

    public String registrarUsuario() {
        if (!usuario.getPassword().equals(repass)) {
            FacesMessage fm = new FacesMessage("Las contraseñas deben coincidir");
            FacesContext.getCurrentInstance().addMessage("registro:repass", fm);
            return null;
        }

        Negocio.Error e = negocio.registrarUsuario(usuario);

        switch (e) {
            case CUENTA_REPETIDA:
                FacesMessage fm = new FacesMessage("Existe un usuario con la misma cuenta");
                FacesContext.getCurrentInstance().addMessage("registro:user", fm);
                return null;
        }

        registroOK=true;

        return "exitoRegistro.xhtml";
    }
}

Thanks in advance

custom ServerAuthModule (loginModule), where to hash the password? JASPIC

I'm trying to implement a loginmodule so I can perform a "remember me" feature on my web app as well as hash my password with bcrypt. To build the class I used this tutorial. However I didn't manage to connect after implementing this. The passwords in db are hashed via SHA-256 at the moment and I suspect it is the reason why.

  public class TestAuthModule implements
        javax.security.auth.message.module.ServerAuthModule {

    @SuppressWarnings("rawtypes")
    protected static final Class[] supportedMessageTypes = new Class[] {
            HttpServletRequest.class, HttpServletResponse.class };

    private CallbackHandler handler;

    public void initialize(MessagePolicy requestPolicy,
            MessagePolicy responsePolicy, CallbackHandler handler,
            @SuppressWarnings("rawtypes") Map options) throws AuthException {
        System.out.println("initialize called.");
        this.handler = handler;
    }

    @SuppressWarnings("rawtypes")
    public Class[] getSupportedMessageTypes() {
        return supportedMessageTypes;
    }

    public AuthStatus validateRequest(MessageInfo messageInfo,
            Subject clientSubject, Subject serverSubject) throws AuthException {
        HttpServletRequest request = (HttpServletRequest) messageInfo
                .getRequestMessage();

        String user = request.getParameter("user");
        String group = request.getParameter("group");

        System.out.println("validateRequest called.");
        System.out.println("User = " + user);
        System.out.println("Group = " + group);

        authenticateUser(user, group, clientSubject, serverSubject);

        return AuthStatus.SUCCESS;
    }

    public AuthStatus secureResponse(MessageInfo msgInfo, Subject service)
            throws AuthException {
        System.out.println("secureResponse called.");
        return AuthStatus.SEND_SUCCESS;
    }

    public void cleanSubject(MessageInfo msgInfo, Subject subject)
            throws AuthException {
        if (subject != null) {
            subject.getPrincipals().clear();
        }
    }

    private void authenticateUser(String user, String group,
            Subject clientSubject, Subject serverSubject) {
        System.out
                .println("Authenticating user " + user + " in group " + group);

        CallerPrincipalCallback callerPrincipalCallback = new CallerPrincipalCallback(
                clientSubject, user);

        GroupPrincipalCallback groupPrincipalCallback = new GroupPrincipalCallback(
                clientSubject, new String[] { group });

        try {
            handler.handle(new Callback[] { callerPrincipalCallback,
                    groupPrincipalCallback });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

and I login like this (which did work before implementing a custom loginmodule):

private String username;
private Password password;
//....
try {
    request.login(username, password + salt);
    } catch (ServletException e)

Also on my pages I used to have a register and a sign in button that were displayed only if the user was null if not I had the username at the top. Now that I implemented this it's like the user is connected as "ANONYMOUS" (so there is "you are connected as ANONYMOUS" at the top of the page. To prevent this I did a temporary fix:

    if (username == null || username.equals("ANONYMOUS")) {
        this.isUserConnected = false;
    } else {
        this.isUserConnected = true;
    }

I tried :

isUserInGroup("ANONYMOUS"); 

but there is no user so I'm getting a npe. I'm not sure how to go about this as well.

I have a @POST rest method and i want to make filter for it, so only the person who is logged in in the application to be able to have access to it. Here is my @POST method :

@POST
@Path("/buy")
public Response buyTicket(@QueryParam("projectionId") String projectionId, @QueryParam("place") String place){
    Projection projection = projectionDAO.findById(Long.parseLong(projectionId));
    if(projection != null){
        System.out.println(projection.getMovieTitle());
        System.out.println(place);
        projectionDAO.buyTicket(projection, userContext.getCurrentUser(), place);
    }

    return Response.noContent().build();
}

And here is the filter i write for this method :

@WebFilter("rest/projection/buy")
public class ProtectedBuyFunction implements Filter {
@Inject
UserContext userContext;

public void init(FilterConfig fConfig) throws ServletException {
}

public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    if (!isHttpCall(request, response)) {
        return;
    }
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    User currentUser = userContext.getCurrentUser();
    if (currentUser == null) {
        String loginUrl = httpServletRequest.getContextPath()
                + "/login.html";
        httpServletResponse.sendRedirect(loginUrl);
        return;
    }
    chain.doFilter(request, response);
}

private boolean isHttpCall(ServletRequest request, ServletResponse response) {
    return (request instanceof HttpServletRequest)
            && (response instanceof HttpServletResponse);
}

public void destroy() {
}}

The problem is that i always get an exception and the server refuse to start, the exception is :

Invalid <url-pattern> rest/projection/buy in filter mapping

I am using TomEE server with Jax-RS. Is there some way I can solve this problem ?

WrapperDataSource instead of OracleDatasource in JBoss AS7

I have defined oracle datasource in JBoss standalone.xml as mentioned below:

<datasource jndi-name="java:jboss/datasources/DefaultDS" pool-name="DefaultDS_pool" enabled="true" use-java-context="true">
                    <connection-url>jdbc:oracle:thin:@localhost:1521:C3S</connection-url>
                    <driver>oracle</driver>
                    <security>
                        <user-name>jboss</user-name>
                        <password>sysadm</password>
                    </security>
                </datasource>
                <drivers>
                    <driver name="oracle" module="com.oracle.jdbc">
                        <xa-datasource-class>oracle.jdbc.xa.client.OracleXADataSource</xa-datasource-class>
                        <datasource-class>oracle.jdbc.OracleDriver</datasource-class>
                    </driver>

and i am using this datasource in bean class using below code:

@Resource(mappedName="java:jboss/datasources/DefaultDS")
DataSource driver;

But i am not able to get oracle datasource instead only getting wrapperdatasource object. I was under impression as i have defined oracle datasource so i will get the same.

So please let me know how can i get oracle datasource instead of wrapperdatasource in jboss as7?

Tomcat server makes 3 requests to the servlet

Below is my doGet method

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    int page;
    try {
        page = Integer.parseInt(request.getParameter("page"));
    } catch (NumberFormatException e) {
        page = 1;
    }
    String sortBy = request.getParameter("sortBy");
    if (sortBy == null || sortBy.isEmpty())
        sortBy = this.getInitParameter("sortBy");

    String query = getQuery(sortBy);
    Object[] params = {
            (page - 1) * Constants.RESULTS_PER_PAGE,
            Constants.RESULTS_PER_PAGE
    };

    JDBCService service = new JDBCService(pool);
    service.setQuery(query);
    service.setParams(params);
    List<Book> books = service.getBookDetails();


    System.out.println("Hello");

    RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/index.jsp");
    dispatcher.forward(request, response);
}

When I start the server (Tomcat) the doGet method gets called 3 times. It prints 'Hello' 3 times.

This only happen when I first start the server.

Any idea why this happens?

Hibernate update is sometimes not working

I have a requirement where I am updating rows according to uuid's where one uuid may be associated to more than one rows.

Here's the scenario: 4a90558c-4a5b-4af7-8c68-60ff81f74ef3 is my uuid and it exists in 8 columns in my DB.

and my java code is as follows:

    try{
        session = sessionFactory.getCurrentSession();
        tx = session.getTransaction();
        criteria = session.createCriteria(Archive.class);
        criteria.add(Restrictions.eq("bagUuid",  "4a90558c-4a5b-4af7-8c68-60ff81f74ef3"));
        ScrollableResults items = criteria.scroll();

         while ( items.next() ) {
             Archive archive = (Archive)items.get(0);
             archive.setDecision(1);
             archive.setOperatorAssigned("test");
             session.saveOrUpdate(archive);
             session.flush();
             session.clear();
         }
         tx.commit();
        LOGGER.info("Archive Record is updated: "+archive.getFilePath());
    }catch(Exception e){
        recordUpdated = false;
        tx.rollback();
        LOGGER.error("Archive Record failed to update due to exception in updateArchiveRecord method: "+e.getMessage());
    }

Here sometimes all records associated to UUID is updating but sometimes failing. I think it may be a issue with the Hibernate API. Does anybody else has faced the same issue.

Cannot log in Tomcat

Operating System: OS X, Tomcat version: 8.0.23 Browser:Chrome;

I have setting the user in the file"tomcat-users.xml" as directed and restart Tomcat, but I still cannot log in. Why? And how can I slove this problem?

here is my configuration in "tomcat-users.xml" enter image description here

And once after I enter the user name and password and click "log in" ,this window show out again enter image description here

If I click "cancel", the page shows this : enter image description here

vendredi 26 juin 2015

Requested resource isn't available (Servlet)

I created a dynamic web project in Eclipse 4.5, called HelloServlet and modified web.xml. I also added Apache 8 in Eclipse. I think I did everything right, but I still can't run the servlet.

In Project explorer: /src/HelloServlet/HelloWorldServlet.java.

HelloWorldServlet.java:

package HelloServlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloWorldServlet
 */
@WebServlet("/HelloWorldServlet")
public class HelloWorldServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().println("Hello world.");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

Web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://ift.tt/ra1lAU" xmlns="http://ift.tt/19L2NlC" xsi:schemaLocation="http://ift.tt/19L2NlC http://ift.tt/1drxgYl" id="WebApp_ID" version="3.1">
  <display-name>HelloServlet</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
    <servlet-name>HelloWorldServlet</servlet-name>
    <servlet-class>HelloServlet.HelloWorldServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>HelloWorldServlet</servlet-name>
    <url-pattern>/HelloWorldServlet</url-pattern>
  </servlet-mapping>
</web-app>

Sometimes, I get class not found without /HelloWorldServlet. I searched and knew how to set servlet-class correctly, but it still doesn't run.

FacesServlet returning Null pointer exception

I have tried all the solutions but I can´t fix this problem.

The classes that I have are:

-User (Entity)

-Negocio (Local interface EJB)

-NegocioImpl (Stateless EJB with PersistenceContext)

-Registro (Little @ManagedBean @RequestScoped to insert Users in DB with @PostConstruct init() method and @Inject atributte of Negocio and another atributte of User)

Here's the code of Registro:

import modelo.User;
import negocio.Negocio;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.inject.Inject;

@ManagedBean
@RequestScoped
public class Registro {

@Inject
private Negocio negocio;

private User usuario;

@PostConstruct
public void init(){
    usuario = new User();
}

public User getUsuario() {

    return usuario;
}

public void setUsuario(User usuario) {

    this.usuario = usuario;
}

public void insertarUsuario(){
    negocio.sayHelloFromServiceBean(usuario);
}

public void saluda(){
    negocio.hola();
  }
}

Everything is apparently right. But when I test the application I have this exception:

http://ift.tt/1REjqm5

Here is my web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://ift.tt/19L2NlC"
     xmlns:xsi="http://ift.tt/ra1lAU"
     xsi:schemaLocation="http://ift.tt/19L2NlC http://ift.tt/1drxgYl"
     version="3.1">
<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
</web-app>

Here is my faces-config.xml file:

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

<faces-config xmlns="http://ift.tt/nSRXKP"
          xmlns:xsi="http://ift.tt/ra1lAU"
          xsi:schemaLocation="http://ift.tt/nSRXKP http://ift.tt/1cpkFEe"
          version="2.0">
</faces-config>

Im using JSF 2.0, EJB 3.1, JBoss 7.1.1 Final, Java EE 6 with Intellij IDEA as IDE.

Thanks in advance

NameNotFoundException doing JNDI lookup to remote EJB in production JBoss (works locally)

An application (e.g app.EAR) is deployed to a JBoss in my own machine and works fine. When I deploy it to a remote JBoss it is deployed, but when I try to access a functionality that needs a JNDI lookup to a remote EJB I get NameNotFoundException. So, it seems that it was unable to find the requested service. How come? If it works locally?

The dependency with the remote EJB interface is in the lib folder inside the EAR and of course is annotated with @Remote. The JBoss is exactly the same as the production one (I copied the whole JBoss from production to my machine to check if there is any configuration missing).

My lookup code is like this:

private Object lookup(String resourceName, String loginData) {
        if (isPropagateUserCredentials() && (loginData == null || loginData.trim().equals(""))) {
            throw new MyInfraConfigException("somemessage");
        }
        Properties envProperties = new Properties();
        envProperties.putAll(this.jndiProperties);
        if (loginData != null && !loginData.equals("")) {
            envProperties.put(Context.SECURITY_PRINCIPAL, loginData);           
            envProperties.remove(Context.SECURITY_CREDENTIALS);
        }
        Context context = null;
        try {
            context = new InitialContext(envProperties);
            return context.lookup(resourceName);            
        } catch (NameNotFoundException e){
            String message = "Resource "+resourceName+" not found.";
            LoggerFactory.getInstance(this.getClass().getName()).error(message, e);
            throw new com.mypackage.NameNotFoundException(message, e);
        } catch (NamingException e) {
            String message = "Failed to find resource with JNDI: "+e.getMessage();
            LoggerFactory.getInstance(this.getClass().getName()).error(message, e);
            throw new com.mypackage.NamingException(message, e);
        } finally{
            if(context!=null){
                try {
                    context.close();
                } catch (NamingException e) {
                    e.printStackTrace();
                }
            }
        }
    }

The resourceName is ExternalResource.

Any clues?

Arquillian integration tests fail with Glassfish container but work with Wildfly container

I'm working on a project that makes use of Arquillian and Maven to perform integration tests against a remote Glassfish 4.1 container and a remote Wildfly 8.2 container. When the tests are running against the remote Wildfly container everything works fine, however when running against the remote Glassfish container the tests fail with a series of errors.

The Maven output reports an internal server error and also shows that the test failed due to a NullPointerException but I believe this is actually a result of the Shrinkwrap deployment not being deployed to the Glassfish container rather than an error in the code itself.

The Glassfish server log shows no sign of anything being deployed to the container but there is a TimeoutException recorded in the log file when the integration test is run.

What I don't understand is what I'm doing wrong that prevents the test running against a remote Glassfish 4.1 container. Given that the same test passes without any problems on a remote Wildfly 8.2 container, I believe the problem lies with the Arquillian configuration in my project rather than the code being tested.

The relevant section of the arquillian.xml file is as follows:

<container qualifier="arquillian-glassfish-remote">
  <configuration>
    <property name="adminUser">xxxx</property>
    <property name="adminPassword">xxxx</property>
    <property name="adminHttps">true</property>
    <property name="adminHost">xxxx</property>
    <property name="adminPort">4848</property>
    <property name="target">server</property>
  </configuration>
  <protocol type="Servlet 3.0">
    <property name="host">xxxx</property>
    <property name="port">8080</property>
  </protocol>
</container>

The relevant section of the pom.xml file is as follows:

<dependencies>
  <!-- Java EE Dependencies -->
  <dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>7.0</version>
  </dependency>

  <!-- Internal Dependencies -->
  <dependency>
    <groupId>${project.groupId}</groupId>
    <artifactId>project-ejb</artifactId>
    <version>${project.version}</version>
  </dependency>

  <!-- Test Dependencies -->
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.jboss.arquillian.junit</groupId>
    <artifactId>arquillian-junit-container</artifactId>
    <scope>test</scope>
  </dependency>
</dependencies>

...

<profile>
  <id>arquillian-glassfish-remote</id>
  <dependencies>
    <dependency>
      <groupId>org.jboss.arquillian.container</groupId>
      <artifactId>arquillian-glassfish-remote-3.1</artifactId>
      <version>1.0.0.CR4</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <testResources>
      <testResource>
        <directory>src/test/resources</directory>
      </testResource>
    </testResources>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-failsafe-plugin</artifactId>
        <configuration>
          <encoding>UTF-8</encoding>
          <includes>
            <include>**/IT*.java</include>
            <include>**/*IT.java</include>
            <include>**/*ITCase.java</include>
          </includes>
          <systemPropertyVariables>
            <arquillian.launch>arquillian-glassfish-remote</arquillian.launch>
          </systemPropertyVariables>
        </configuration>
        <executions>
          <execution>
            <goals>
              <goal>integration-test</goal>
              <goal>verify</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</profile>

The relevant section of the parent pom.xml is as follows:

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.jboss.arquillian</groupId>
      <artifactId>arquillian-bom</artifactId>
      <version>1.1.8.Final</version>
      <scope>import</scope>
      <type>pom</type>
    </dependency>
  </dependencies>
</dependencyManagement>

The relevent section of the Maven output is as follows:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running myproject.test.whitebox.ejb.MyServiceIT
Jun 26, 2015 7:45:42 PM org.jboss.arquillian.container.glassfish.clientutils.GlassFishClientUtil getResponseMap
SEVERE:  [status: SERVER_ERROR reason: Internal Server Error]
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 101.582 sec <<< FAILURE! - in myproject.test.whitebox.ejb.MyServiceIT
myproject.test.whitebox.ejb.MyServiceIT  Time elapsed: 101.582 sec  <<< ERROR!
java.lang.NullPointerException: null
    at org.jboss.arquillian.container.glassfish.clientutils.GlassFishClientUtil.getResponseMap(GlassFishClientUtil.java:163)
    at org.jboss.arquillian.container.glassfish.clientutils.GlassFishClientUtil.POSTMultiPartRequest(GlassFishClientUtil.java:131)
    at org.jboss.arquillian.container.glassfish.clientutils.GlassFishClientService.doDeploy(GlassFishClientService.java:245)
    at org.jboss.arquillian.container.glassfish.CommonGlassFishManager.deploy(CommonGlassFishManager.java:101)
    at org.jboss.arquillian.container.glassfish.remote_3_1.GlassFishRestDeployableContainer.deploy(GlassFishRestDeployableContainer.java:71)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController$3.call(ContainerDeployController.java:161)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController$3.call(ContainerDeployController.java:128)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController.executeOperation(ContainerDeployController.java:271)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController.deploy(ContainerDeployController.java:127)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
    at org.jboss.arquillian.container.impl.client.container.DeploymentExceptionHandler.verifyExpectedExceptionDuringDeploy(DeploymentExceptionHandler.java:50)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
    at org.jboss.arquillian.container.impl.client.ContainerDeploymentContextHandler.createDeploymentContext(ContainerDeploymentContextHandler.java:78)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
    at org.jboss.arquillian.container.impl.client.ContainerDeploymentContextHandler.createContainerContext(ContainerDeploymentContextHandler.java:57)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:145)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:116)
    at org.jboss.arquillian.core.impl.EventImpl.fire(EventImpl.java:67)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController$1.perform(ContainerDeployController.java:95)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController$1.perform(ContainerDeployController.java:80)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController.forEachDeployment(ContainerDeployController.java:263)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController.forEachManagedDeployment(ContainerDeployController.java:239)
    at org.jboss.arquillian.container.impl.client.container.ContainerDeployController.deployManaged(ContainerDeployController.java:79)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:145)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:116)
    at org.jboss.arquillian.core.impl.EventImpl.fire(EventImpl.java:67)
    at org.jboss.arquillian.container.test.impl.client.ContainerEventController.execute(ContainerEventController.java:101)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
    at org.jboss.arquillian.test.impl.TestContextHandler.createClassContext(TestContextHandler.java:92)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
    at org.jboss.arquillian.test.impl.TestContextHandler.createSuiteContext(TestContextHandler.java:73)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:145)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:116)
    at org.jboss.arquillian.test.impl.EventTestRunnerAdaptor.beforeClass(EventTestRunnerAdaptor.java:87)
    at org.jboss.arquillian.junit.Arquillian$2.evaluate(Arquillian.java:201)
    at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:422)
    at org.jboss.arquillian.junit.Arquillian.access$200(Arquillian.java:54)
    at org.jboss.arquillian.junit.Arquillian$3.evaluate(Arquillian.java:218)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:166)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:283)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:173)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:128)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)


Results :

Tests in error: 
  MyServiceIT.myproject.test.whitebox.ejb.MyServiceIT » NullPointer

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0

The relevant section of the Glassfish server.log file is as follows:

[2015-06-26T19:52:25.713+0100] [glassfish 4.1] [INFO] [NCLS-REST-00003] [javax.enterprise.admin.rest] [tid: _ThreadID=225 _ThreadName=admin-listener(18)] [timeMillis: 1435344745713] [levelValue: 800] [[
  An error occurred while processing the request. Please see the server logs for details.
org.glassfish.jersey.server.ContainerException: java.io.IOException: java.util.concurrent.TimeoutException
        at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer$ResponseWriter.rethrow(GrizzlyHttpContainer.java:317)
        at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer$ResponseWriter.failure(GrizzlyHttpContainer.java:299)
        at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:439)
        at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:277)
        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.grizzly2.httpserver.GrizzlyHttpContainer.service(GrizzlyHttpContainer.java:365)
        at org.glassfish.admin.rest.adapter.RestAdapter$2.service(RestAdapter.java:316)
        at org.glassfish.admin.rest.adapter.RestAdapter.service(RestAdapter.java:179)
        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.portunif.PUFilter.handleRead(PUFilter.java:231)
        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.portunif.PUFilter.handleRead(PUFilter.java:231)
        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.io.IOException: java.util.concurrent.TimeoutException
        at org.glassfish.grizzly.nio.transport.TCPNIOTransportFilter.handleRead(TCPNIOTransportFilter.java:90)
        at org.glassfish.grizzly.filterchain.TransportFilter.handleRead(TransportFilter.java:173)
        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.read(DefaultFilterChain.java:351)
        at org.glassfish.grizzly.filterchain.FilterChainContext.read(FilterChainContext.java:695)
        at org.glassfish.grizzly.portunif.BackChannelFilter.handleRead(BackChannelFilter.java:80)
        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.read(DefaultFilterChain.java:351)
        at org.glassfish.grizzly.filterchain.FilterChainContext.read(FilterChainContext.java:695)
        at org.glassfish.grizzly.portunif.BackChannelFilter.handleRead(BackChannelFilter.java:80)
        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.read(DefaultFilterChain.java:351)
        at org.glassfish.grizzly.filterchain.FilterChainContext.read(FilterChainContext.java:695)
        at org.glassfish.grizzly.http.io.InputBuffer.blockingRead(InputBuffer.java:1119)
        at org.glassfish.grizzly.http.server.io.ServerInputBuffer.blockingRead(ServerInputBuffer.java:95)
        at org.glassfish.grizzly.http.io.InputBuffer.fill(InputBuffer.java:1143)
        at org.glassfish.grizzly.http.io.InputBuffer.read(InputBuffer.java:353)
        at org.glassfish.grizzly.http.server.NIOInputStreamImpl.read(NIOInputStreamImpl.java:83)
        at org.glassfish.jersey.message.internal.EntityInputStream.read(EntityInputStream.java:101)
        at org.jvnet.mimepull.MIMEParser.fillBuf(MIMEParser.java:440)
        at org.jvnet.mimepull.MIMEParser.readBody(MIMEParser.java:216)
        at org.jvnet.mimepull.MIMEParser.access$600(MIMEParser.java:68)
        at org.jvnet.mimepull.MIMEParser$MIMEEventIterator.next(MIMEParser.java:165)
        at org.jvnet.mimepull.MIMEParser$MIMEEventIterator.next(MIMEParser.java:132)
        at org.jvnet.mimepull.MIMEMessage.makeProgress(MIMEMessage.java:198)
        at org.jvnet.mimepull.MIMEMessage.parseAll(MIMEMessage.java:181)
        at org.jvnet.mimepull.MIMEMessage.getAttachments(MIMEMessage.java:106)
        at org.glassfish.jersey.media.multipart.internal.MultiPartReaderClientSide.readMultiPart(MultiPartReaderClientSide.java:225)
        at org.glassfish.jersey.media.multipart.internal.MultiPartReaderServerSide.readMultiPart(MultiPartReaderServerSide.java:89)
        at org.glassfish.jersey.media.multipart.internal.MultiPartReaderClientSide.readFrom(MultiPartReaderClientSide.java:179)
        at org.glassfish.jersey.media.multipart.internal.MultiPartReaderClientSide.readFrom(MultiPartReaderClientSide.java:91)
        at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:251)
        at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:229)
        at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:149)
        at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundReadFrom(MappableExceptionWrapperInterceptor.java:73)
        at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:149)
        at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1124)
        at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:851)
        at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:783)
        at org.glassfish.jersey.server.ContainerRequest.readEntity(ContainerRequest.java:233)
        at org.glassfish.jersey.media.multipart.internal.FormDataParamValueFactoryProvider.getEntity(FormDataParamValueFactoryProvider.java:369)
        at org.glassfish.jersey.media.multipart.internal.FormDataParamValueFactoryProvider.access$000(FormDataParamValueFactoryProvider.java:86)
        at org.glassfish.jersey.media.multipart.internal.FormDataParamValueFactoryProvider$FormDataMultiPartValueFactory.provide(FormDataParamValueFactoryProvider.java:309)
        at org.glassfish.jersey.server.spi.internal.ParameterValueHelper.getParameterValues(ParameterValueHelper.java:81)
        at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$AbstractMethodParamInvoker.getParamValues(JavaResourceMethodDispatcherProvider.java:121)
        at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:152)
        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)
        ... 44 more
Caused by: java.util.concurrent.TimeoutException
        at org.glassfish.grizzly.nio.tmpselectors.TemporarySelectorReader.read(TemporarySelectorReader.java:126)
        at org.glassfish.grizzly.nio.tmpselectors.TemporarySelectorReader.read(TemporarySelectorReader.java:75)
        at org.glassfish.grizzly.AbstractReader.read(AbstractReader.java:72)
        at org.glassfish.grizzly.nio.transport.TCPNIOTransportFilter.handleRead(TCPNIOTransportFilter.java:77)
        ... 100 more
]]