Hot questions for Using GlassFish in session

Question:

When I try to use okhttp or javax.ws.rs.client.Client the following error occur

java.lang.NoSuchMethodError: sun.security.ssl.SSLSessionImpl.(Lsun/security/ssl/ProtocolVersion;Lsun/security/ssl/CipherSuite;Ljava/util/Collection;Lsun/security/ssl/SessionId;Ljava/lang/String;I)V

Searching in the sun.security.ssl package, there is no SSLSessionImpl class

Im using Mac OS 10.13.3 (17D102)

java -version
java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)

And running my war on Glassfish 5.0

build.gradle

buildscript {
    ext.kotlin_version = '1.2.30'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version"
    }
}

group 'invoice-administration-api'
version '1.0-SNAPSHOT'

apply plugin: 'idea'
apply plugin: 'war'
apply plugin: 'kotlin'
apply plugin: 'kotlin-jpa'
apply plugin: 'kotlin-allopen'

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    compileOnly group: 'javax', name: 'javaee-api', version: '8.0'
    compile group: 'org.hibernate', name: 'hibernate-core', version: '5.2.13.Final'
    compile group: 'org.glassfish.jersey.media', name: 'jersey-media-json-jackson', version: '2.26'
}

allOpen {
    annotation('javax.ejb.Stateless')
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

Answer:

The issue appears because Glassfish embeds native sun.* classes into [glassfish5_home]/glassfish/modules/endorsed/grizzly-npn-bootstrap.jar, so it conflicts with others classes included into [JDK_HOME]/jre/lib/jsse.jar

So edit the grizzly-npn-bootstrap.jar (make a copy before) file and remove the sun folder.

Question:

I am trying to build a WebSocket Server in Java, and to connect with a simple javascript WebSocketClient. Now i want to "give" every incoming session an unique instance of an object which is created on onopen, their methods called on onmessage and destroyed on onclose. How can i manage these object ? is there a way to store it in the sessions? or does the server itself handle such things, and i can just define a private variable in the "Endpoint class"?

package com.xxx.server;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.glassfish.tyrus.server.Server;

public class TestWebSocketServer {
    public static void main(String[] args) {
        runServer();
    }

    public static void runServer() {
        Server server = new Server("localhost", 21212, "/xxx", TestServerEndpoint.class);

        try {
            server.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            System.out.print("Please press a key to stop the server.");
            reader.readLine();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            server.stop();
        }
    }
}

package com.xxx.server;

import java.io.IOException;
import java.util.logging.Logger;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.CloseReason.CloseCodes;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint(value = "/TEST")
public class TestServerEndpoint {

    private Logger logger = Logger.getLogger(this.getClass().getName());

    @OnOpen
    public void onOpen(Session session) {
        logger.info("Connected ... " + session.getId());
    }

    @OnMessage
    public String onMessage(String message, Session session) {
        switch (message) {
        case "quit":
            try {
                session.close(new CloseReason(CloseCodes.NORMAL_CLOSURE, "Test ended"));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            break;
        }
        return message;
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        logger.info(String.format("Session %s closed because of %s", session.getId(), closeReason));
    }
}

Answer:

You don't need to handle these objects yourself, the Java EE server handles it. Your just need to create an instance variable in the endpoint class. For example,

@ServerEndpoint(value = "/test-server/")
public class TestWebSocketServer {
  private YourObject yourObject = new YourObject();
  //or instantiate it in constructor    
}

The Java EE server will create a new yourObject whenever you open a new websocket connection to the server and will make it ready for garbage collection when you close the connection.

Question:

I have a war file deployed in glassfish. We have some stateless session beans and we have 1 synchronized method in it.

However, I am noticing that more than 1 thread is able to enter the synchronized method concurrently. Is it possible that glassfish is instantiating 2 instances of this bean class? Is there any way around this?


Answer:

Yes, of course it's possible. The spec even mandates that concurrent calls are handled by different instances.: this is one of the services offered by the container: it makes sure that concurrent calls are handled concurrently, and not sequentially, and you're free to implement your sesssion bean without caring about thread-safety (for example, by using instance variables), because the container takes care of it.

What you want is a singleton.

Question:

I have a war file deployed in glassfish. We have a Singleton bean and we have 1 synchronized method in it.

@TransactionAttribute (TransactionAttributeType.REQUIRED)
public synchronized void do()
{
    ...
}

However, I am noticing that transaction is started before the method is called. How do I start a transaction after the caller obtains the lock on the bean class' monitor?

Thank you.

Update: We are just trying to have a bean method that can only be called by one thread at a time. We do not want any other thread to call this method until the previous thread is completely done with it. I had created another thread where I got the idea of using a singleton bean: synchronized method in stateless session bean not working as expected in glassfish

Update: After doing some reading, it seems I can create my own transactions UserTransaction. Will that be supported? Never mind. I got this error message:

Only session beans with bean-managed transactions can obtain UserTransaction

Answer:

I think one way would be to move the synchronization out of the bean by wrapping the call to the method inside another bean (YourBean would be the interface of your bean class):

public class WrapperBeanImpl implements WrapperBean {

  private YourBean yb;

  private final Object lock;

  @Resource
  private SessionContext ctx;

  @PostConstruct
  public void init() {
    yb = ctx.getBusinessObject(YourBean.class);
  }

  @TransactionAttribute(TransactionAttributeType.NEVER)
  public void synchronizedDo() {
    synchronized(lock) {
      yb.do();
    }
  } 
}

(Example slightly modified from http://www.javahelp.info/2009/11/01/using-transactionattribute-in-submethods-on-same-ejb3-beans/ )

Of course, this does not really stop anyone from calling the do() method directly bypassing this extra synchronization, although that may not be a problem. You also have the option of leaving the synchronization in your bean as an extra safeguard.

Question:

I am running a J2EE website on a GlassFish 4.0 server. I want to destroy all sessions of an application from the GlassFish Administration Panel (Accessed from the web, by default on port 4848). How can I accomplish that? I looked through the panel, and haven't found that feature on it myself.


Answer:

I guess you mean HTTP sessions. There is no direct way to accomplish what you want.

However, you can simply restart your web application in the Administration Panel under Applications by hitting either Reload or Redeploy.

This will destroy all sessions, but also has some disadvantages. It can be a lengthy process depending on the "size" of your web application. It may also clear caches built up by your application and things like established database connections. You should make sure that restarting the application doesn't cause any undesired side effects.

Question:

I'm developing a RESTful Web Service in Java with Jersey and JBoss and I need to store "Session variables" like in PHP. To mantain the session of a client but without using coockies.

@Context
private UriInfo context;

@Context
private HttpServletRequest httpRequest;

@Path("/firstPage")
@GET
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public String createInstance(@QueryParam("instance") String inst) 
        throws JSONException 
{
    // Here I "declare" the session variable
    HttpSession session = httpRequest.getSession(true);
    session.setAttribute("instance", inst);

    // Creation of the DTO (Data Transfer Object)
    JSONObject innerObj = new JSONObject();
    JSONObject outterObj = new JSONObject();

    innerObj.put("ContactID", "{{Contact.Id}}");
    innerObj.put("EmailAddress", "{{Contact.Field(C_EmailAddress)}}");
    outterObj.put("recordDefinition", innerObj);

    return outterObj.toString();
}

@Path("/secondPage")
@GET
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public String validateInstance(@QueryParam("instance") String inst) 
        throws JSONException 
{
    // Here I "validate" the session variable
    HttpSession session = httpRequest.getSession(true);
    if ((String)session.getAttribute("instance") == inst) {
        JSONObject obj= new JSONObject();

        outterObj.put("status", 200);
        outterObj.put("instance", inst);

        return obj.toString();
    } else {
        JSONObject obj = new JSONObject();
        obj.put("error", 401);
        return obj.toString();
    }
}

Here is what I did but it's not working as I expected. Any solution?


Answer:

As somone already pointed out: Sessions are handled with a cookie that contains the session id which php uses to connect clients to sessions.

For your java rest service. per definition sessions are not part of rest services and even discouraged.

Please refer to the original document from field about the rest architecture: https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm

5.1.3 Stateless

We next add a constraint to the client-server interaction: communication must be stateless in nature, ... ach request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client.

Is there any reason against taking the created data along between requests and attach them to the second request?

Question:

LogonServlet gets user data and saves them as session variable (or an object that needs these data for creation) that all other servlets can restore and use it. These other servlets get called independently by the same app.

Do I need to forward something to them? I can't forward the request I send to one servlet to another because I send different datatypes to different servlets. I have no idea what I am doing wrong or how I could do it better.


Answer:

I didn't know that I have to manage the session cookies in my Application that communicates with the servlets manually and add them to every http request to inform the server that I am user X which also initiated the session.

So it is necessary to save the cookies I receive from the first HTTP response and add them to all follow up HTTP requests that should happen during the same session.

When you just want your application to communicate with your own webservice via HTTP you can set the cookie store to accept all cookies.

Question:

I have two application deployed in single glassfish server with 2 different domains(port 8080,9090) with same context path. Its creating issue when two application are open in single browser with in different tabs.What i found is due to JSESSIONID are getting interchange. Is there a way to avoid or generate JSESSIONID specific to application?

Note: i didn't find any solution . I am using glassfish,servlet 2.3 api.


Answer:

Manage to solve the above issue by generating Unique JSESSIONID name for both application

Added cookie-config under session-config

 <session-config>
    <session-timeout>30</session-timeout>
    <cookie-config>
    <name>JSESSIONID_APPLICATION_NAME</name><!-- default is jsessionid -->
    </cookie-config>
  </session-config>

with the above configuration, application will have unique jsessionid name example : JSESSIONID_APP1:xybo89aoa3fhjasdf ,JSESSIONID_APP2:abc1234hjadkf

Question:

I'm having trouble to get a connection to a MySQL database in my web application using Glassfish / Payarus and Hibernate.

I've created a JDBC Connection Pool "test_db" and a JDBC Resource "jdbc/TestDB" and can successfully ping it.

<jdbc-connection-pool datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" steady-pool-size="1" name="test_db" res-type="javax.sql.DataSource">
      <property name="password" value="test" />
      <property name="username" value="testUser" />
      <property name="url" value="jdbc:mysql://localhost:3306/test_db" />
</jdbc-connection-pool>
<jdbc-resource pool-name="test_db" jndi-name="jdbc/TestDB" />

I have a "mysql-connector-java-5.1.39" in following folders:

payaras/glassfish/domains/myDomain/lib
payaras/glassfish/domains/myDomain/lib/ext
payaras/glassfish/lib

Here's my persistence.xml file

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" version="2.1">
    <persistence-unit name="test" transaction-type="JTA">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <jta-data-source>jdbc/TestDB</jta-data-source>
        <properties>
            <!-- Does not work without these properties either -->
            <!-- Configuring JDBC properties -->
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test_db" />
            <property name="javax.persistence.jdbc.user" value="testUser" />
            <property name="javax.persistence.jdbc.password" value="test" />
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform" />

            <!-- Hibernate properties -->
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
            <property name="hibernate.hbm2ddl.auto" value="validate" />
        </properties>
    </persistence-unit>
</persistence>

But every time I try to deploy my app I get following error causes by a NullPointerException.

[2016-11-26T12:58:20.333+0100] [Payara 4.1] [SEVERE] [NCLS-CORE-00026] [javax.enterprise.system.core] [tid: _ThreadID=65 _ThreadName=admin-thread-pool(2)] [timeMillis: 1480161500333] [levelValue: 1000] [[
  Exception during lifecycle processing
javax.persistence.PersistenceException: [PersistenceUnit: capaz] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:951)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:881)
    at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:151)
    at org.glassfish.persistence.jpa.PersistenceUnitLoader.loadPU(PersistenceUnitLoader.java:207)
    at org.glassfish.persistence.jpa.PersistenceUnitLoader.<init>(PersistenceUnitLoader.java:114)
    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:926)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:435)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:220)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:487)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
    at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
    at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
    at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:189)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:466)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:169)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:526)
    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:593)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at org.hibernate.tool.schema.internal.exec.ImprovedExtractionContextImpl.getJdbcDatabaseMetaData(ImprovedExtractionContextImpl.java:67)
    at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.locateTableInNamespace(InformationExtractorJdbcDatabaseMetaDataImpl.java:337)
    at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.getTable(InformationExtractorJdbcDatabaseMetaDataImpl.java:239)
    at org.hibernate.tool.schema.internal.exec.ImprovedDatabaseInformationImpl.getTableInformation(ImprovedDatabaseInformationImpl.java:110)
    at org.hibernate.tool.schema.internal.SchemaValidatorImpl.performValidation(SchemaValidatorImpl.java:92)
    at org.hibernate.tool.schema.internal.SchemaValidatorImpl.doValidation(SchemaValidatorImpl.java:62)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:65)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:307)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:490)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:878)
    ... 47 more
]]

[2016-11-26T12:58:20.344+0100] [Payara 4.1] [SEVERE] [] [javax.enterprise.system.core] [tid: _ThreadID=65 _ThreadName=admin-thread-pool(2)] [timeMillis: 1480161500344] [levelValue: 1000] [[
  Exception while preparing the app : [PersistenceUnit: capaz] Unable to build Hibernate SessionFactory
java.lang.NullPointerException
    at org.hibernate.tool.schema.internal.exec.ImprovedExtractionContextImpl.getJdbcDatabaseMetaData(ImprovedExtractionContextImpl.java:67)
    at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.locateTableInNamespace(InformationExtractorJdbcDatabaseMetaDataImpl.java:337)
    at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.getTable(InformationExtractorJdbcDatabaseMetaDataImpl.java:239)
    at org.hibernate.tool.schema.internal.exec.ImprovedDatabaseInformationImpl.getTableInformation(ImprovedDatabaseInformationImpl.java:110)
    at org.hibernate.tool.schema.internal.SchemaValidatorImpl.performValidation(SchemaValidatorImpl.java:92)
    at org.hibernate.tool.schema.internal.SchemaValidatorImpl.doValidation(SchemaValidatorImpl.java:62)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:65)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:307)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:490)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:878)
    at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:151)
    at org.glassfish.persistence.jpa.PersistenceUnitLoader.loadPU(PersistenceUnitLoader.java:207)
    at org.glassfish.persistence.jpa.PersistenceUnitLoader.<init>(PersistenceUnitLoader.java:114)
    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:926)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:435)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:220)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:487)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
    at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
    at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
    at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:189)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:466)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:169)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:526)
    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:593)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
    at java.lang.Thread.run(Thread.java:745)
]]

As far as I known Hibernate is unable to get a connection to mysql but I don't understand why.

Mapping is fine. At least it works with an H2 DB in my unit tests. I also tried it with test app with just one simple entity.

I hope you guys can help me with this.

Thanks in advance

____ EDIT _____

following line in the persitence.xml file caused the error:

<property name="hibernate.hbm2ddl.auto" value="validate" />

Answer:

Apparently following line in my "persistence.xml" causes the error:

<property name="hibernate.hbm2ddl.auto" value="validate" />

Question:

As titled, the GlassFish 4.1 server decided to mess my head up with some random re-deployment to my web-application, which removes all my attributes within the session but somehow keeping the session ID intact.

This problem mostly occurs when I'm trying to select a combo-box which triggers the form submit where it will be sent to a Servlet to gathers the necessary information from the database to populate necessary text fields in the same form (done by JSP), the reason why I'm unable to root the problem because it happens on the third or fourth select attempt, sometimes it doesn't even happen at all.

The server logs doesn't help much at all, as these are the only messages that pops up whenever it decides to redeploy.

Server Logs:

Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   WebModule[null] ServletContext.log():filter_user:Initializing filter
Info:   Loading application [IMS_Test] at [/IMS_Test]
Info:   IMS_Test was successfully deployed in 558 milliseconds.

Servlet Code:

List<String> list = new ArrayList<String>();
rs = stmt.executeQuery("SELECT scp_id FROM ims_db.ims_scp_list WHERE scp_name = '" + t_scp_name + "'");

if (rs.next()) {
      scp_id = rs.getString("scp_id");
}

rs = stmt.executeQuery("SELECT epicor_id FROM ims_db.ims_parts_plan "
                            + "WHERE scp_id = '" + scp_id + "'");

while (rs.next()) {
     list.add(rs.getString("epicor_id"));
}
RequestDispatcher rd = request.getRequestDispatcher("new_entryform.jsp");

session.setAttribute("epicor_list", list);                    
session.removeAttribute("scp_name");
session.setAttribute("scp_name", t_scp_name);
rd.forward(request, response);

So the question, what have I done wrong that eventually forces GlassFish to redeploy my web-app in the midst of operation? Please help me out :(

UPDATE 1: Out of desperation I've created a SessionListener to see what's wrong. During debug it shows that all the codes were executed as expected , but sometimes it'll jump to "attributeRemoved" right after that, which really makes no sense.

UPDATE 2: Last resort, split the original form into two separate forms where one uses GET method while the main form uses the POST method. It solves the problem, for now.

UPDATE 3: The issues still bothering me whenever I'm trying to submit the forms to the server, but it only happens in POST method. Tried upgrading to GlassFish 5.0 (nightly build) but the problems doesn't seems to bug off. Any guidance / suggestion will be greatly appreciated. :(


Answer:

After weeks of struggling I've finally found the answer. Apparently the random redeployments were caused by improper settings of @MultipartConfig annotations in the servlet I'm trying to access to.

Changing it to the following solved the issues :

@MultipartConfig(location="\fileDest", fileSizeThreshold=1024*1024, 
maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5)

Question:

I have created a simple Java EE program to experiment with MyBatis but I've hit a problem using the MyBatis CDI module. I have followed the instructions outlined on http://mybatis.github.io/cdi/injection.html, but when my program tries to use MyBatis a MybatisCdiConfigurationException exception is thrown with the description "There are no SqlSessionFactory producers properly configured."

The code for the SqlSessionFactory I'm using is as follow:

import javax.annotation.Resource;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.sql.DataSource;

import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

public class SqlSessionFactoryProvider {

    @Resource (name="jdbc/MyDatabase")
    DataSource dataSource;

    @Produces
    @ApplicationScoped
    public SqlSessionFactory produceFactory() {
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("development",
                transactionFactory, dataSource);
        Configuration configuration = new Configuration(environment);
        configuration.addMapper(ToDoItemMapper.class);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(configuration);
        return sqlSessionFactory;
    }
}

I've stepped through the code of the MyBatis CDI module and have found that when the follow line of code in CDIUtils findSqlSessionFactory(...) is executed it fails find any beans that return SqlSessionFactory.class.

beans = beanManager.getBeans(SqlSessionFactory.class, qualifiers.toArray(new Annotation[]{}));

I've tried running my program on GlassFish 4 and 4.1 and they both have the same problem, but it works find if I run my program on WildFly 8.1. My first thought was that it might be a problem with the version of Weld shipped with Glassfish but it turns out that GlassFish 4.1 is running Weld version 2.2.2 whereas WildFly is running Weld version 2.1.2.

Is there anything I can do in GlassFish, my code or in the MyBatis CDI module to overcome this problem when running in GlassFish? Alternatively can anyone suggest anything that I can do to investigate the problem further please?


Answer:

I ran into the same issue when trying to implement the mybatis-CDI running in Jboss wildfly. I found the solution when going through this git smaple project: https://github.com/artplastika/mybatis-cdi-example

The only thing you seem to be missing is the @Local, @Stateless and @Named annotations on your SqlSessionFactoryProvider.java class

See the SqlSessionFactoryProvider.java class in the Git example: https://github.com/artplastika/mybatis-cdi-example/blob/master/mybatis-cdi-example-ejb/src/main/java/org/mybatis/cdi/example/beans/SqlSessionFactoryProviderImpl.java

You should also ensure that you have the beans.xml in you src/main/resources/META-INF folder

EDIT

My Maven Dependency Setup:

<dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <scope>compile</scope>
        </dependency>
        <!-- Import the CDI API -->
        <dependency>
            <groupId>javax.enterprise</groupId>
            <artifactId>cdi-api</artifactId>
            <version>1.2</version>
            <scope>compile</scope>
        </dependency>
        <!-- Mybatis Dependencies -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.5</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-cdi</artifactId>
            <version>1.0.0-beta1</version>
            <scope>compile</scope>
        </dependency>
        <!-- Below Dependencies are very specific to Jboss due to class conflicts if you dont have the exclusions specified -->
        <!-- Proxy support (Mandatory) -->
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <scope>compile</scope>
            <version>2.2.2</version>
            <exclusions>
                <exclusion>
                    <groupId>asm</groupId>
                    <artifactId>asm</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- Internal dependency (Required) -->
        <dependency>
            <groupId>org.ow2.asm</groupId>
            <artifactId>asm-util</artifactId>
            <version>5.0.3</version>
            <scope>compile</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.ow2.asm</groupId>
                    <artifactId>asm</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- Internal dependency (Required) -->
        <dependency>
            <groupId>opensymphony</groupId>
            <artifactId>oscache</artifactId>
            <version>2.4</version>
            <scope>compile</scope>
            <!-- This excludes the transitive dependency on JMS -->
            <exclusions>
                <exclusion>
                    <groupId>javax.jms</groupId>
                    <artifactId>jms</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

I've got my sample Factory Producer as below:

@Stateless
@Local(SampleSqlSessionFactoryProvider.class)
public class SampleSqlSessionFactoryProvider {
    @Produces
    @ApplicationScoped
    @Named("sqlSessionFactory")
    public SqlSessionFactory produceFactory() throws Exception {        
        Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = null;
        String environment = "default";
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader, environment);
        return sqlSessionFactory;
    }
}

and to use it i inject it as follows:

@Local(DaoBean.class)
@Stateless
public class DoaBean{
     private @Inject @Named("sqlSessionFactory") SqlSession session;
     public void doStuff(){
         session.selectOne(...);
     }
     ...
}

Question:

Here is the problem. I get the session id with:

request.getRequestedSessionId();

However when site is opening first time it returns null. Only starting with second visit it returns session id. But I need to know from first time. Can I get it?


Answer:

It's null because there is no session.

Consider instead:

request.getSession(true).getId()

which will create a session if one does not exist, then provides a unique session identifier.