Hot questions for Using GlassFish in glassfish 4

Question:

I need to access some images with this URL http://localhost:8080/static/img1.jpg

The images are in "/home/andrea/Documents", the application context is "/". I'm using GlassFish 4.1.1.

In the /WEB-INF directory of project I've got the following: (glassfish-web.xml)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app>
    <parameter-encoding default-charset="UTF-8" />
    <property name="alternatedocroot_1" value="from=/static/* dir=/home/andrea/Documents" />
</glassfish-web-app>

The problem is that, the file is not found. What did I miss?

Is there another way to define alternatedocroot` or map a virtual directory outside the project?


Answer:

I've resolved the problem reading this post: http://glassfish.10926.n7.nabble.com/unable-to-get-working-alternate-docroots-td40978.html

Unfortunately the documentation is not so clear, I try to explain how I solved my problem

The dir value is the base directory of your alternatedocroot, so you must put full path specified for the value frominto the base dir of alternatedocroot. Therefore in my case the real structure is /home/andrea/Documents/static (Remember to insert "/" at the end of dir value).

glassfish-web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app>
    <parameter-encoding default-charset="UTF-8" />
    <property name="alternatedocroot_1" value="from=/static/* dir=/home/andrea/Documents/" />
</glassfish-web-app>
My exigence

My exigence is to have a separate directory to upload images separated from the ".war" archive. The solution I've found is insert the images in docroot directory of glassfish domain1 directory

glassfish-web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app>
    <parameter-encoding default-charset="UTF-8" />
    <property name="alternatedocroot_1" value="from=/static/* dir=./docroot/" />
</glassfish-web-app>

Remember that the real path must contain static directory: [...]/glassfish/domains/domain1/docroot/static/

Question:

I have a glassfish 4 installation (DAS). One remote (SSH) node and one cluster with one instance on that node. Also i have defined a connection pool and the datasource for it.

My test application is very simple - it is a web application with one servlet, in that i load the datasource in the following way:

@Resource(lookup = "jdbc/vadsacRootSource")
private Datasource datasource;

What does not work - the datasource on the cluster instance (remote) cannot be instantiated, because the underlying pool cannot be found - stacktrace see at the end of the message.

What does work:

  • The same application on the local DAS node (defaul node)
  • The Loading of a string saved as custom JNDI resource on both - remote and local
  • The whole application (the datasource, too) on the glassfish 3.1 - remote and local

So, there is something wrong with the current glassfish 4 version - Datasources (or its pool) does not get instantiated (or found per JNDI?) on some remote SSH instance. I have tested the official release 4.0 and the nightly build version 4.1-bl3 - the same problem

Do you have any idea?

GlassFish Server Open Source Edition 4.0 - Error report

HTTP Status 500 - Internal Server Error

type Exception report

messageInternal Server Error

descriptionThe server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: Error instantiating servlet class
com.sedo.webtesty.HelloWorld

root cause

com.sun.enterprise.container.common.spi.util.InjectionException:
Error creating managed object for class: class
com.sedo.webtesty.HelloWorld

root cause

com.sun.enterprise.container.common.spi.util.InjectionException:
Exception attempting to inject Res-Ref-Env-Property:
com.sedo.webtesty.HelloWorld/datasource@javax.sql.DataSource@ resolved
as: jndi: jdbc/vadsacRootSource@res principal: null@mail: null No
Runtime properties Database Vendor : null Create Tables at Deploy :
false Delete Tables at Undeploy : false into class
com.sedo.webtesty.HelloWorld: Lookup failed for
'java:comp/env/com.sedo.webtesty.HelloWorld/datasource' in
SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory,
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl,
java.naming.factory.url.pkgs=com.sun.enterprise.naming}

root cause

javax.naming.NamingException: Lookup failed for
'java:comp/env/com.sedo.webtesty.HelloWorld/datasource' in
SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory,
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl,
java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root
exception is javax.naming.NamingException: Lookup failed for
'jdbc/vadsacRootSource' in
SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory,
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl,
java.naming.factory.url.pkgs=com.sun.enterprise.naming,
com.sun.enterprise.naming.logicalName=java:comp/env/com.sedo.webtesty.HelloWorld/datasource}
[Root exception is javax.naming.NamingException: Unable to lookup
resource : jdbc/vadsacRootSource [Root exception is
com.sun.appserv.connectors.internal.api.ConnectorRuntimeException:
Lookup failed for '__SYSTEM/pools/mysqlRootVadsacPool' in
SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory,
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl,
java.naming.factory.url.pkgs=com.sun.enterprise.naming,
com.sun.enterprise.naming.logicalName=java:comp/env/com.sedo.webtesty.HelloWorld/datasource}]]]

root cause

javax.naming.NamingException: Lookup failed for
'jdbc/vadsacRootSource' in
SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory,
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl,
java.naming.factory.url.pkgs=com.sun.enterprise.naming,
com.sun.enterprise.naming.logicalName=java:comp/env/com.sedo.webtesty.HelloWorld/datasource}
[Root exception is javax.naming.NamingException: Unable to lookup
resource : jdbc/vadsacRootSource [Root exception is
com.sun.appserv.connectors.internal.api.ConnectorRuntimeException:
Lookup failed for '__SYSTEM/pools/mysqlRootVadsacPool' in
SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory,
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl,
java.naming.factory.url.pkgs=com.sun.enterprise.naming,
com.sun.enterprise.naming.logicalName=java:comp/env/com.sedo.webtesty.HelloWorld/datasource}]]

root cause

javax.naming.NamingException: Unable to lookup resource
: jdbc/vadsacRootSource [Root exception is
com.sun.appserv.connectors.internal.api.ConnectorRuntimeException:
Lookup failed for '__SYSTEM/pools/mysqlRootVadsacPool' in
SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory,
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl,
java.naming.factory.url.pkgs=com.sun.enterprise.naming,
com.sun.enterprise.naming.logicalName=java:comp/env/com.sedo.webtesty.HelloWorld/datasource}]

root cause

com.sun.appserv.connectors.internal.api.ConnectorRuntimeException:
Lookup failed for '__SYSTEM/pools/mysqlRootVadsacPool' in
SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory,
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl,
java.naming.factory.url.pkgs=com.sun.enterprise.naming,
com.sun.enterprise.naming.logicalName=java:comp/env/com.sedo.webtesty.HelloWorld/datasource}

root cause

javax.naming.NamingException: Lookup failed for
'__SYSTEM/pools/mysqlRootVadsacPool' in
SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory,
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl,
java.naming.factory.url.pkgs=com.sun.enterprise.naming,
com.sun.enterprise.naming.logicalName=java:comp/env/com.sedo.webtesty.HelloWorld/datasource}
[Root exception is javax.naming.NameNotFoundException:
pools]

root cause

javax.naming.NameNotFoundException: pools

note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 4.0 logs.


GlassFish Server Open Source Edition 4.0


Answer:

The problem is fixed in the current 4.1 version - everything is working now

Question:

On the GlassFish homepage it is stated that

Java EE 7 requires JDK 7 or above, JDK 8 u20 or above is recommended for GlassFish 4.1.

So I am wondering, why it is recommended to use it under the JDK 8, as GlassFish 4.1 is a Java EE 7 application server?

Is it just because that I will be able to use the new Java 8 functionalities? Or are there deeper reasons for this like stability, know bugs etc. So does the GlassFish really runs better on the JDK 8 than on the JDK 7, or may I ignore this statement and just install it under JDK 7, if I do not use the new functionalities provided under Java SE 8?


Answer:

So I am wondering, why it is recommended to use it under the JDK 8, as GlassFish 4.1 is a Java EE 7 application server?

I guess they just recommend to use the newest compatible non-beta Java version which in this case is Java 8. The Java EE specs version (in this case Java EE 7) which is implemented by Glassfish 4 and the JDK version which is required (or which can be used) to run the server are two different things.

Also note that Java 7 has its EOL (End of Life) in April, 2015. There will be no further updates for Java 7 so at some point you'll have to switch to Java 8 anyway.

Is it just because that I will be able to use the new Java 8 functionalities?

This could be one reason for you to use JDK 8.

Or are there deeper reasons for this like stability, know bugs etc.

I guess there may be some bugs in JDK 7 which are fixed or do not occur in JDK 8, but this shouldn't be anything critical. In terms of stability I think the values are similar when not the same.

So does the GlassFish really runs better on the JDK 8 than on the JDK 7, or may I ignore this statement and just install it under JDK 7, if I do not use the new functionalities provided under Java SE 8?

I wouldn't say that Glassfish runs better, but I would also recommend to use the latest compatible Java version. But you can currently also safely ignore the statement and use JDK 7.

For some additional information, this spring.io blog post contains a nice summary about Java 8 in enterprise projects and with various application servers.

Question:

How can the connection keep-alive be disabled for glassfish 4.1.

Meaning: clients connecting to my glassfish http port won't be allowed to keep their connections alive.

According to the migration manual, the configuration key for that changed from glassfish 3.0 to glassfish 4.0 but I can't figure out the new configuration.


Answer:

I'm not sure why you want to do this, keep-alive is not enabled by default in Glassfish 4. Maybe you have something in front of it like Apache, which is adding the keep-alive header?

According to the Glassfish 4 Migration Guide, the element was moved from

server-config.http-service.keep-alive.timeout-in-seconds

to

server-config.network-config.protocols.protocol.http-listener-1.http.timeout-seconds

But changing this setting doesn't have any effect for me, I can't get Glassfish to send the keep-alive header, this would be very weird if you had the opposite problem.

Question:

The Scenario goes as follows :

i'm coding a java enterprise application

first i created entity classes from database table "Derby" then i made a helper classes in a java library project then i created a session bean in the enterprise application bean and created a bean facade remote in the java library project

here is the important code part of the session bean :

@Stateless(mappedName = "officefacade")
public class OfficeFacade implements OwnerFacadeRemote {
        @PersistenceContext
        private EntityManager em;

and then i coded a simple client to test the methods

client code :

public class Client {

private OwnerFacadeRemote request;
public static void main(String[] args) {
    // TODO code application logic here
    Client x = new Client();

}

public Object getEJBBean(String beanName)
{
        try
        {
            InitialContext ctx = new InitialContext();
            return ctx.lookup(beanName);
        }
        catch(Exception ex)
        {
            System.err.println("Error : " + ex.getMessage() + "\n\n\n");
        }
        return null;
 }

private void insert()
{
    request.createOwner(new OwnerDetails("1","M","444","M","afcdv"));
}

private void display()
{
    List<OwnerDetails> xx = request.getAllOwner();

}

public Client() 
{
    request = (OwnerFacadeRemote) getEJBBean("officefacade");

    insert();
    display();
}

the problem is every time i run the client i get the error that Lookup failed for 'officefacade'

here is the complete error text

> Error : Lookup failed for 'officefacade' in SerialContext[myEnv{java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFac   tory, java.naming.factory.url.pkgs=com.sun.enterprise.naming, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl}

how to make sure the mapped name is being available and how to fix it so the it can be found by the lookup even if it means hard coding the mapped name in the serial context "i don't know what this is but it seem as the problem is coming from it"

any help is much appreciated and thanks in advance for your efforts and i'm pretty sure everything is implemented correctly so it's a mapped name related problem

tools of development is netbeans 8.0.2 and glassfish 4.1


Answer:

Try to replace @Stateless(mappedName = "officefacade") with @Stateless(name = "officefacade"), the lookup method of the InitialContext seems to work with the bean name

See the related JavaDoc section and the related method for more details

UPDATE

Just checked Oracle's documentation on this topic - according to the information available there you might need to actually lookup for "java:module/officefacade" instead of pure "officefacade", depending on the bean context.

Question:

GlassFish 4.1 provides EclipseLink 2.5.x in glassfish/modules. I want to use 2.6.4 in my application and am including it when packaging it with maven-ear-plugin:2.10.1 with

<configuration>
    <finalName>linuxtracker2</finalName>
    <version>7</version>
    <defaultLibBundleDir>lib</defaultLibBundleDir>
    <archive>
        <manifest>
            <addClasspath>true</addClasspath>
        </manifest>
    </archive>
</configuration>

and the EJB and WAR module as dependency (and default values otherwise). The application deploys and works fine, but I suspect that EclipseLink 2.5 has an issue and I want to overwrite it anyway because I don't want to (double) configure the server to provide dependencies.

I figured out so far that GlassFish has a classloader hierarchy and that load requests are delegated to the topmost parent which can satisfy it, but the docs fail of course to explain how to use that. There's Circumventing Class Loader Isolation which I'd say from my understanding does the opposite of what I want to acchieve (isolate the class loader to use my packaged dependencies).

My application setup is the standard: entity classes and EJB interfaces, EJB implemetations, web frontend and EAR maven module.

Related troubles:


Answer:

GlassFish is no longer supported by Oracle, and therefore just an open source project now. The documentation can be found at https://glassfish.java.net/documentation.html - you will need to download the "Administration Guide" PDF, though the others are quite useful too.

What you're trying to do here isn't possible in GlassFish, but is a feature added to Payara Server, which is derived from GlassFish (disclaimer: I work for them).

For EAR files, Payara Server has added the option to add <classloading-delegate>false</classloading-delegate> in your META-INF/glassfish-application.xml file. This should stop your application using libraries from Payara Server when you have your own versions packaged in your EAR.

For your specific use-case, though, you would not need to use this since Payara Server already comes with EclipseLink 2.6.4 in the latest build, 171.1

Question:

I've read that GlassFish provides custom events for Java Flight Recorder (JFR) / Java Mission Control (JMC).

I tried viewing in JMC 5.4 a JFR 5.3 recording obtained from GlassFish 4.1 running in Java 7u67. The recording was setup from the command line using jcmd. I did not use JMX or MBeans.

I saw the standard JFR events, but no custom events for GlassFish.

Are there actually custom JFR events for GlassFish? If so, what are they, how do I record them, and how do I view them?

Thanks.

Here's an article that mentions GlassFish JFR events:

http://www.infoq.com/news/2013/10/misson-control-flight-recorder


Answer:

If I’ve understood things correctly, this was something that the GlassFish team wanted to address in the commercial version of GlassFish. Then it was decided to not do a commercial version of GlassFish.

Note that there are JFR events for the WebLogic Server.

Question:

I use GlassFish 4.1 - final release (downloaded from java.net). I have two domains - domain1 and domain2

The problem is that I can't work simultaneously with web admin console of two domains of the same GF server. I open admin of domain1 - everything is ok, at the same browser (firefox) but different tab I open admin console of domain2 - at this time server closes my access for the admin of domain1. What is the reason? How can it be fixed?


Answer:

That is simply because you're accessing the two domains via URLs with the same host.

192.168.1.10:X
192.168.1.10:Y

Recall that the host portion is 192.168.1.10 and as with many other web-app, glassfish admin console use session cookies, which is unique per host. So what happen when you login to the second domain is, the session info from the first domain is lost / overwritten.

Easiest solution for this is use a different browser for each domain (eg: firefox for domain 1 and IE for domain 2) or open another window in incognito mode (if using google chrome)

Question:

I want to use JavaMelody to monitor the SQL requested by a Glassfish Application Server. There are step-by-step instructions on https://github.com/javamelody/javamelody/wiki/UserGuideAdvanced#monitoring-of-sql-requests-and-of-jdbc-connections-in-glassfish-v3, but the second step does not work for me.

The instruction is:

In the GlassFish admin console, rename your JDBC Resource (DataSource) from "jdbc/MyDataSource" to "jdbc/MyDataSource_uncached" for example

I can't find any way to edit rename the JDBC Resource.

The following screenshot shows the JDBC data source tab of the Glassfish Admin console: Edit JNDI Name of a JDBC Resource

Do you know how to rename JNDI Name of a JDBC Resource?


Answer:

Indeed, there is no command in the Glassfish UI to rename the JDBC Resource.

I have added more precision in the doc:

In the GlassFish admin console, rename your JDBC Resource (DataSource) from "jdbc/MyDataSource" to "jdbc/MyDataSource_uncached" for example, by creating a new identical JDBC Resource then deleting the old one

Question:

I downloaded the latest version (4.1.1) of GlassFish, unzipped to a local folder, started the domain with command asadmin start-domain from the bin directory.

I Opened the admin console of the server on web browser and clicked the new button on resources-> jms resources -> connection factories which resulted in a runtimeexception.

I then clicked the new button on resources->JDBC Resources which also resulted in a runtimexception. In short, clicking on any 'new' button results in a runtimexception.

I didn't find any answer to this problem online. If anybody know the reason, please let me know.

Here is the log:

2015-12-10T23:03:25.558-0500] [glassfish 4.1] [INFO] [] [org.glassfish.admingui] [tid: _ThreadID=51 _ThreadName=admin-listener(1)] [timeMillis: 1449806605558] [levelValue: 800] [[
  Redirecting to /index.jsf]]

[2015-12-10T23:03:26.392-0500] [glassfish 4.1] [INFO] [] [org.glassfish.admingui] [tid: _ThreadID=53 _ThreadName=admin-listener(3)] [timeMillis: 1449806606392] [levelValue: 800] [[
  Admin Console: Initializing Session Attributes...]]

[2015-12-10T23:03:36.527-0500] [glassfish 4.1] [INFO] [] [javax.enterprise.resource.webcontainer.jsf.context] [tid: _ThreadID=53 _ThreadName=admin-listener(3)] [timeMillis: 1449806616527] [levelValue: 800] [[
  Exception when handling error trying to reset the response.
java.io.IOException: Connection is closed
    at org.glassfish.grizzly.nio.NIOConnection.assertOpen(NIOConnection.java:432)
    at org.glassfish.grizzly.http.io.OutputBuffer.write(OutputBuffer.java:653)
    at org.apache.catalina.connector.OutputBuffer.writeBytes(OutputBuffer.java:355)
    at org.apache.catalina.connector.OutputBuffer.write(OutputBuffer.java:342)
    at org.apache.catalina.connector.CoyoteOutputStream.write(CoyoteOutputStream.java:161)
    at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
    at sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:282)
    at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:125)
    at java.io.OutputStreamWriter.write(OutputStreamWriter.java:207)
    at com.sun.faces.renderkit.html_basic.HtmlResponseWriter.flushAttributes(HtmlResponseWriter.java:1211)
    at com.sun.faces.renderkit.html_basic.HtmlResponseWriter.endElement(HtmlResponseWriter.java:582)

Answer:

Glassfish allowes creation of Resources only through asadmin console for v4.1.1

   Eg : 
     asadmin> create-jms-resource --restype javax.jms.ConnectionFactory              
     --description "connection factory for durable subscriptions" --property   
     ClientId=MyID jms/DurableConnectionFactory

     asadmin> create-jms-resource --restype javax.jms.Queue --property 
              Name=MyQueue jms/MyQueue

Though updating and deleting is allowed through admin web console, creation is disabled. Alternatively, these resources can also be created by adding them manually in domain.xml file under glassfish/domain-name/config

<resources><connector-connection-pool max-pool-size="250" resource-adapter-name="jmsra" steady-pool-size="1" name="jms/MyConnectionFactory-Connection-Pool" description="MyConnectionFactory" connection-definition-name="javax.jms.ConnectionFactory" transaction-support=""></connector-connection-pool>
<connector-resource pool-name="jms/MyConnectionFactory-Connection-Pool" jndi-name="jms/MyConnectionFactory"></connector-resource>
<admin-object-resource res-adapter="jmsra" description="myQueue" res-type="javax.jms.Queue" jndi-name="jms/myQueue">
  <property name="Name" value="myQueue"></property>
</admin-object-resource>  </resources>

Question:

I am getting the following errors when I try to run a web app in eclipse using glassfish server.

I have 3 folder namely; Testdb, TestdbEJB and TestdbWeb. Can someone help me to resolve this issue please?

cannot Deploy Testdb deploy is failing=Error occurred during deployment: Application Testdb is trying to use the same repository directory as application TestDb, please choose a different application name to deploy.


Answer:

It looks like you deployed an application named TestDb before and now you are trying to deploy an application named Testdb, but you didn't properly undeploy the first one.

It isn't possible to deploy two applications with the same name (it doesn't matter that the case is not matching) at the same time...the reason is obvious.

How to fix it:

  1. Try to log in to Glassfish Admin UI (http://localhost:4848), go to Applications und undeploy the first application. You may also use asadmin instead. Try to redeploy your application then.
  2. If nothing is listed under "Applications", check the folder glassfish/domains/domain1/applications/ of your Glassfish installation, if there is a folder named "TestDb" (or anything like this), delete it, you may also check the "__internal" folder. Restart Glassfish afterwards.
  3. If you deleted something in step 2 and it still doesn't work, open /glassfish/domains/domain1/config/domain.xml of your Glassfish installation and search for the section beginning with <application> which represents your application. Delete the part from (inclusive) <application> to </application>, save the file and restart Glassfish.

Question:

Please see the code below:

try {
            //InitialContext ic = new InitialContext();
            Hashtable env = new Hashtable();
            env.put(Context.INITIAL_CONTEXT_FACTORY,  
             "com.sun.enterprise.naming.SerialInitContextFactory");
            Context ctx = new InitialContext(env);      

            MySessionRemote hb = (MySessionRemote) ctx.lookup("MySessionRemote");
            System.out.println(hb.getResult());
        } catch (NamingException ex) {
            ex.printStackTrace();
        }

The error I get from a Swing app is:(javax.naming.NoInitialContextException) javax.naming.NoInitialContextException: Cannot instantiate class: com.sun.enterprise.naming.SerialInitContextFactory [Root exception is java.lang.ClassNotFoundException: com.sun.enterprise.naming.SerialInitContextFactory]

I have not worked with Java for a while so this could be quite straightforward.

Update

I am using version 4.1 of Glassfish. I have added references to the following jars inside the NetBeans project:

appserv-rt.jar
gf-client.jar
javaee.jar

I can now get an InitialContext. However, I cannot lookup the bean i.e. this line fails:

MySessionRemote hb = (MySessionRemote) ctx.lookup("ejb.MySessionRemote");

The exception is a NamingException i.e. Lookup Failed. I believe the name of the bean may be wrong. Here is the bean:

package ejb;

import javax.annotation.Resource;
import javax.ejb.Remote;
@Resource(name = "MySessionRemote")
@Remote
public interface MySessionRemote {
    public String getResult();
}

What should the name of the bean be?


Answer:

Which application server are you using? E.g. when using Glassfish that class can be found in the glassfish-naming.jar file. That JAR needs to be on your classpath. I assume other application servers have a similar JAR file.

In fact, when you have that JAR on your classpath you could simply use the no-args constructor of InitialContext since the JAR already contains a jndi.properties file with the following content:

java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory
java.naming.factory.url.pkgs=com.sun.enterprise.naming
# Required to add a javax.naming.spi.StateFactory for CosNaming that
# supports dynamic RMI-IIOP.
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl

Question:

I tried to deploy play framework 2.4 application on glassfish. I used maven play2 plugin and made war file with the following instruction.

https://play2-maven-plugin.github.io/play2-maven-plugin/1.0.0-beta4/war-packaging.html

After that, I tried to deploy my war from glassfish console, but it returned the following error.

  Error occurred during deployment: Exception while loading the app : 
  CDI deployment failure:Exception List with 3 exceptions: 
  Exception 0 : org.jboss.weld.exceptions.DeploymentException: 
  WELD-001408: Unsatisfied dependencies for type Environment with qualifiers @Default
   at injection point [BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedConstructor] @Inject public play.api.db.BoneConnectionPool(Environment)
   at play.api.db.BoneConnectionPool.<init>(BoneConnectionPool.java:0)
   at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:370)
   at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:291)
   at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:134)
   at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:165)
   at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:529)
   at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:515)
   at org.jboss.weld.bootst .... msg.seeServerLog


  Error occurred during deployment: Exception while loading the app : 
  CDI deployment failure:
  WELD-001408: Unsatisfied dependencies for type Database with qualifiers @Default 
   at injection point [BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedConstructor] @Inject public modules.MyBatisModule$PlayDataSourceProvider(Database) 
   at modules.MyBatisModule$PlayDataSourceProvider.<init>(PlayDataSourceProvider.java:0) . 
   Please see server.log for more details.

And MyBatisModule is like this.

public class MyBatisModule extends org.mybatis.guice.MyBatisModule {

    @Override
    protected void initialize() {
        environmentId("development");
        bindConstant().annotatedWith(Names.named("mybatis.configuration.failFast")).to(true);
        bindDataSourceProviderType(PlayDataSourceProvider.class);
        bindTransactionFactoryType(JdbcTransactionFactory.class);
        addMapperClasses();
    }

    @Singleton
    public static class PlayDataSourceProvider implements Provider<DataSource> {
        final Database db;

        @Inject
        public PlayDataSourceProvider(final Database db) {
            this.db = db;
        }

        public DataSource get() {
            return db.getDataSource();
        }
    }

I think the application can't read application.conf that containts DB setting. But I'm not sure.

Could you give me any advices?

Update 2015/01/13

I disabled "Implicit CDI" option on glassfish console when I deployed application. I don't get the first error now, but I get another error...

Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: 
ContainerBase.addChild: start: org.apache.catalina.LifecycleException: com.google.inject.CreationException: 
Unable to create injector, see the following errors: 
1) Error in custom provider, Configuration error: Configuration error
[Cannot connect to database [default]] while locating play.api.db.DBApiProvider while locating play.api.db.DBApi for parameter 0 
at play.db.DefaultDBApi.<init>(DefaultDBApi.java:28) 
at play.db.DefaultDBApi.class(DefaultDBApi.java:28) while locating play.db.DefaultDBApi while locating play.db.DBApi for field 
at play.db.DBModule$NamedDatabaseProvider.dbApi(DBModule.java:61) while locating play.db.DBModule$NamedDatabaseProvider 
at com.google.inject.util.Providers$GuicifiedProviderWithDependencies.initialize(Providers.java:149) 
at play.db.DBModule.bindings(DBModule.java:40): Binding(interface play.db.Database qualified with QualifierInstanc .... msg.seeServerLog

My conf/application.conf is here:

db.default.driver=oracle.jdbc.driver.OracleDriver
db.default.url="jdbc:oracle:thin:@url..."
db.default.username=username
db.default.password=password

And it works on local environment. I think glassfish can't read application.conf in war file.

I'm sorry. Could you give me the advice again?

Update 2015/01/14

The following is the part of full log.

Caused by: Configuration error: Configuration error[Exception during pool initialization]
    at play.api.Configuration$.configError(Configuration.scala:178)
    at play.api.PlayConfig.reportError(Configuration.scala:1048)
    at play.api.db.HikariCPConnectionPool.create(HikariCPModule.scala:69)
    at play.api.db.PooledDatabase.createDataSource(Databases.scala:199)
    at play.api.db.DefaultDatabase.dataSource$lzycompute(Databases.scala:124)
    at play.api.db.DefaultDatabase.dataSource(Databases.scala:122)
    at play.api.db.DefaultDatabase.getConnection(Databases.scala:143)
    at play.api.db.DefaultDatabase.getConnection(Databases.scala:139)
    at play.api.db.DefaultDBApi$$anonfun$connect$1.apply(DefaultDBApi.scala:44)
    ... 130 more
Caused by: com.zaxxer.hikari.pool.PoolInitializationException: Exception during pool initialization
    at com.zaxxer.hikari.pool.BaseHikariPool.initializeConnections(BaseHikariPool.java:542)
    at com.zaxxer.hikari.pool.BaseHikariPool.<init>(BaseHikariPool.java:171)
    at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:60)
    at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:48)
    at com.zaxxer.hikari.HikariDataSource.<init>(HikariDataSource.java:80)
    at play.api.db.HikariCPConnectionPool$$anonfun$1.apply(HikariCPModule.scala:58)
    at play.api.db.HikariCPConnectionPool$$anonfun$1.apply(HikariCPModule.scala:54)
    at scala.util.Try$.apply(Try.scala:191)
    at play.api.db.HikariCPConnectionPool.create(HikariCPModule.scala:54)
    ... 136 more
Caused by: java.sql.SQLException: JDBC4 Connection.isValid() method not supported, connection test query must be configured
    at com.zaxxer.hikari.pool.BaseHikariPool.addConnection(BaseHikariPool.java:441)
    at com.zaxxer.hikari.pool.BaseHikariPool.initializeConnections(BaseHikariPool.java:540)
    ... 144 more

3) Error in custom provider, java.lang.NullPointerException
  at play.db.DBModule.bindings(DBModule.java:40):
Binding(interface play.db.Database qualified with QualifierInstance(@play.db.NamedDatabase(value=default)) to ProviderTarget(play.db.DBModule$NamedDatabaseProvider@34850279)) (vi
a modules: com.google.inject.util.Modules$OverrideModule -> play.api.inject.guice.GuiceableModuleConversions$$anon$1)
  while locating play.db.Database annotated with @play.db.NamedDatabase(value=default)

Answer:

Some thoughts (it should be comment, but I cannot write comments on SO yet).

  1. If your application.conf file is inside WEB-INF/classes directory, it should be found (more info - https://www.playframework.com/documentation/2.4.x/ProductionConfiguration#Specifying-an-alternate-configuration-file).

  2. Does war file contain JDBC driver?

  3. Maybe you should configure JNDI - https://www.playframework.com/documentation/2.4.x/ScalaDatabaseOthers#Exposing-the-datasource-through-JNDI