Hot questions for Using GlassFish in jar

Question:

I have a very simple REST API which uses jersey 2.x (Glassfish). It works when I do nothing but output hello world string. but when I add a few jars and use them in 1 line of code it throws lots of class java.lang.NoClassDefFoundError errors. I get no compile or syntax errors. The error is very long so excuse me if i posed lots of rubbish in it.

I see lots of solution to this problem, but I don't understand their terminology e.g. your classpath needs to be fixed etc.

Can anybody tell me how to add a jar file which is imported in code?

Code

package com.rest.example;

import java.io.File;

    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.PathParam;
    import javax.ws.rs.core.Response;

    import com.infineon.essence_210.api.Component;
    import com.infineon.essence_210.api.EssenceDBMgr;

    @Path("/testEssence") public class HelloWorld {
        @GET
        @Path("/{param}")
        public Response getMsg(@PathParam("param") String msg){
            String output = "Welcome to the world of Rest : "+msg;

            Component comp = null;
            File file = new File("C:\\MYFILE.xml");
            try {
                          comp = EssenceDBMgr.getInstance().lookupComponent(file); //<---ISSUE HERE!
                } catch (Exception e1) {
                          // TODO Auto-generated catch block
                          e1.printStackTrace();
                } 
            return Response.status(200).entity(output).build(); 
        }

    }

Error in the eclipse console (cut short but ask if you want all)

SEVERE: Servlet.service() for servlet [exampleServlet] in context with path [/RestApi] threw exception [org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: com/sun/xml/bind/marshaller/NamespacePrefixMapper] with root cause java.lang.ClassNotFoundException: com.sun.xml.bind.marshaller.NamespacePrefixMapper at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1320) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1173) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2477) at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:880) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1290) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1173) at com.infineon.essence.jaxb.Unmarshaller.unmarshal(Unmarshaller.java:108) at com.infineon.essence.jaxb.Unmarshaller.unmarshal(Unmarshaller.java:88) at com.infineon.essence_210.api.Essence.unmarshal(Essence.java:201) at com.infineon.essence_210.api.Essence.unmarshal(Essence.java:223) at com.infineon.essence_210.api.Essence.unmarshal(Essence.java:229) at com.infineon.essence_210.api.Essence.(Essence.java:80) at com.infineon.essence_210.api.EssenceDBMgr.unmarshal(EssenceDBMgr.java:223) at com.infineon.essence_210.api.EssenceDBMgr.lookupComponent(EssenceDBMgr.java:1331) at com.rest.example.HelloWorld.getMsg(HelloWorld.java:23) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161) at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99) at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102) at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:317) 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:317) at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:298) at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154) at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:471) at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:534) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658) at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source)


Answer:

You can add the jar to your lib folder of your project. If you want to add the jars to your project simply,

Right click your project > Build path > Configure Build path > Add External jars

Also based on the console message java.lang.NoClassDefFoundError: com/sun/xml/bind/marshaller/NamespacePrefixMapper, you are missing the jaxb-impl-jar file.

And you need to have all the jars right under the lib folder and don't keep it in the subfolders.

Question:

I have written a soap client application running on glassfish server.

For soap security reason I had to update a class (SecurityHeather.java) part of Metro project which is provided through webservices-osgi.jar glassfish's module.

Is there anyway to override the class inside the glassfish\modules\webservices-osgi.jar ?

The easiest way is to update the class inside the jar file and save it. but im not sure its the best way or not.


Answer:

After searching through a lot of similar posts and reading through tons of glassfish docs I was able to find out the solution for this problem. There is a glassfish-web.xml deployment descriptor which defines the element class-loader. By default the classloader delegates all the class loading functionality to its parent classloader which looks for the jars in the modules folder of glassfish installation directory. If we set the delegate attribute of the class-loader element to false, the delegation model is inverted and the child classloader does the class loading, loading the classes available in the war libraries first and then looking at glassfish modules folder.

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish 
 Application Server 3.1 Servlet 3.0//EN" 
"http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app error-url="">
  <context-root>/SampleApp</context-root>
  <class-loader delegate="false"/>
 <jsp-config>
   <property name="keepgenerated" value="true">
     <description>Keep a copy of the generated servlet class' java code.
     </description>
     </property>
   </jsp-config>
  </glassfish-web-app>

Question:

I have an embedded GlassFish server, which works well if I run the main file direclty from my IDE (IntelliJ IDEA Ultimate). When I try to export a jar using maven and run the jar from command line, I get the following error:

jul 07, 2018 11:48:43 AM org.glassfish.internal.data.ModuleInfo start
SEVERE: Exception while invoking class com.sun.enterprise.web.WebApplication start method
java.lang.Exception: java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: java.lang.NoSuchMethodError: javax.ws.rs.core.Application.getProperties()Ljava/util/Map;
        at com.sun.enterprise.web.WebApplication.start(WebApplication.java:138)
        at org.glassfish.internal.data.EngineRef.start(EngineRef.java:130)
        at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:269)
        at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:301)
        at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:461)
        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.admin.cli.embeddable.DeployerImpl.deploy(DeployerImpl.java:129)
        at com.sun.enterprise.admin.cli.embeddable.DeployerImpl.deploy(DeployerImpl.java:105)
        at app.App.main(App.java:25)

The weird thing is that this error only occurs when I export a jar using maven. This is my pom:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>myGroup</groupId>
    <artifactId>myArt</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>

            <plugin>
                <!-- Build an executable JAR -->
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>dependency/</classpathPrefix>
                            <mainClass>app.App</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <!-- Build an executable JAR with runtime dependencies so that this program can be executed from command line using java -jar command -->
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.10</version>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/dependency</outputDirectory>
                            <overWriteReleases>false</overWriteReleases>
                            <overWriteSnapshots>false</overWriteSnapshots>
                            <overWriteIfNewer>true</overWriteIfNewer>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>app.App</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>

            <plugin>
                <groupId>com.google.appengine</groupId>
                <artifactId>appengine-maven-plugin</artifactId>
                <version>1.9.64</version>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <skipTests>true</skipTests>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>

        <dependency>
            <groupId>org.glassfish.main.extras</groupId>
            <artifactId>glassfish-embedded-all</artifactId>
            <version>3.1.2.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.glassfish/javax.json -->
        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>javax.json</artifactId>
            <version>1.0.4</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.glassfish.jersey/jax-rs-ri -->
        <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.containers/jersey-container-servlet -->
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>2.26-b03</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.test-framework/jersey-test-framework-core -->
        <dependency>
            <groupId>org.glassfish.jersey.test-framework</groupId>
            <artifactId>jersey-test-framework-core</artifactId>
            <version>2.26-b03</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.test-framework.providers/jersey-test-framework-provider-grizzly2 -->
        <dependency>
            <groupId>org.glassfish.jersey.test-framework.providers</groupId>
            <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
            <version>2.26-b03</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>simple-jndi</groupId>
            <artifactId>simple-jndi</artifactId>
            <version>0.11.4.1</version>
            <scope>test</scope>
        </dependency>

    </dependencies>
</project>

And my web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

</web-app>

I tried googling and I read that this is generally caused by incompatible Jersey versions (1.x vs 2.x), however, I could not find an incompatibility. Any help out there?

EDIT: Also, this is my list of exported jars (by maven dependency plugin):


Answer:

You can add this to your pom:

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <compilerArgs>
                        <arg>-verbose</arg>
                    </compilerArgs>
                </configuration>
            </plugin>
        </plugins>
    </build>

this will make it log which jar the javax.ws.rs.core.Application class is loaded from.

Question:

I am trying to learn ejb 3 and facing an issue in the below mentioned scenario which I am not able to figure out.

  1. I am having one Entity (Book) to store book related data.
  2. I have created Stateless Bean and Remote interfaces and deployed the jar in glassfish 4.
  3. The basic application connects to a main method where I need to get the details of the book using appclient. Here I am getting an error "javax.ejb.EJBException: java.rmi.MarshalException:"

Please look into the below snippets for more details.

Book.java:

package bookstore.model;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQuery;

@Entity
@NamedQuery(name = "findAllBooks", query = "select b from Book b")
public class Book {

@Id
@GeneratedValue
private long id;
@Column(nullable = false)
private String title;
private Float price;
@Column(length = 2000)
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "tag")
@Column(name = "Value")
private List<String> tags;

public List<String> getTags() {
    return tags;
}

public void setTags(List<String> tags) {
    this.tags = tags;
}

public long getId() {
    return id;
}

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

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public Float getPrice() {
    return price;
}

public void setPrice(Float price) {
    this.price = price;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getIsbn() {
    return isbn;
}

public void setIsbn(String isbn) {
    this.isbn = isbn;
}

public Integer getNbOfPage() {
    return nbOfPage;
}

public void setNbOfPage(Integer nbOfPage) {
    this.nbOfPage = nbOfPage;
}

public Boolean getIllustrations() {
    return illustrations;
}

public void setIllustrations(Boolean illustrations) {
    this.illustrations = illustrations;
}
}

BookEJBRemote.java:

package bookstore.controller;

import java.util.List;

import javax.ejb.Remote;

import bookstore.model.Book;

@Remote
public interface BookEJBRemote {

    public List<Book> findBooks();

    public Book findBookById(long id);

    public Book createBook(Book book);

    public Book deleteBook(Book book);

    public Book updateBook(Book book);

}

BookEJB.java: package bookstore.controller;

import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import bookstore.model.Book;

@Stateless
@LocalBean
public class BookEJB implements BookEJBRemote {

    @PersistenceContext(unitName = "bookstore_persistence")
    private EntityManager em;

    /* (non-Javadoc)
     * @see bookstore.controller.BookEJBRemote#findBooks()
     */
    public List<Book> findBooks() {
        TypedQuery<Book> query = em
                .createNamedQuery("findAllBooks", Book.class);
        return query.getResultList();
    }

    /* (non-Javadoc)
     * @see bookstore.controller.BookEJBRemote#findBookById(long)
     */
    public Book findBookById(long id) {
        return em.find(Book.class, id);
    }

    /* (non-Javadoc)
     * @see bookstore.controller.BookEJBRemote#createBook(bookstore.model.Book)
     */
    public Book createBook(Book book) {
        em.persist(book);
        return book;
    }

    /* (non-Javadoc)
     * @see bookstore.controller.BookEJBRemote#deleteBook(bookstore.model.Book)
     */
    public Book deleteBook(Book book) {
        em.remove(book);
        return book;
    }

    /* (non-Javadoc)
     * @see bookstore.controller.BookEJBRemote#updateBook(bookstore.model.Book)
     */
    public Book updateBook(Book book) {

        return em.merge(book);
    }
}

persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
 http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">
    <persistence-unit name="bookstore_persistence"
        transaction-type="JTA">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <jta-data-source>jdbc/mysqlPool</jta-data-source>
        <class>bookstore.model.Book</class>
        <properties>
            <property name="eclipselink.target-database" value="MYSQL" />
            <property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
            <property name="eclipselink.logging-level" value="INFO" />
            <!--  property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/testdb" />
            <property name="javax.persistence.jdbc.user" value="test_user" />
            <property name="javax.persistence.jdbc.password" value="password" /-->
        </properties>
    </persistence-unit>
</persistence>

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.sambaran</groupId>
    <artifactId>bookstore</artifactId>
    <version>1.0.1-SNAPSHOT</version>
    <name>sample-bookstore</name>
    <dependencies>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.0.0</version>
        </dependency>
        <!-- <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>eclipselink</artifactId> 
            <scope>runtime</scope> <version>2.6.0</version> </dependency> <dependency> 
            <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> 
            </dependency> -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>javax.ejb</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.extras</groupId>
            <artifactId>glassfish-embedded-all</artifactId>
            <version>3.0.1</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>bookstore.client.BookStoreMain</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Main class BookstoreMain.java

package bookstore.client;

import java.util.ArrayList;

import javax.ejb.EJB;

import bookstore.controller.BookEJBRemote;
import bookstore.model.Book;


public class BookStoreMain {
    @EJB
    private static BookEJBRemote bookEJB;
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Book book = new Book();
        book.setTitle("Head First Servlets and JSP");
        book.setDescription("A brain friendly guide.");
        book.setIllustrations(true);
        book.setIsbn("1-3244-3237676");
        book.setPrice(new Float(400.00));
        book.setNbOfPage(865);
        ArrayList<String> tags = new ArrayList<String>();
        tags.add("java");
        tags.add("J2SE");
        book.setTags(tags);
        bookEJB.createBook(book);
        book.setTitle("Hear First SQL");
        bookEJB.updateBook(book);
        //bookEJB
    }

}

Deployment of ejb was successful using asadmin command. Please check the details below.

sambaran@sambaran-home:~/glassfish-4.1/glassfish/bin$ ./asadmin list-applications --type ejb
bookstore-1.0.1-SNAPSHOT  <ejb>


Command list-applications executed successfully.

When I try to use appclient to install the client it is having the mentioned error. PFB details.

sambaran@sambaran-home:~/glassfish-4.1/glassfish/bin$ ./appclient -client  /home/sambaran/workspace/bookstore/target/bookstore-1.0.1-SNAPSHOT.jar 
Exception in thread "main" javax.ejb.EJBException: java.rmi.MarshalException: CORBA MARSHAL 1330446343 No; nested exception is: 
    org.omg.CORBA.MARSHAL: ----------BEGIN server-side stack trace----------
org.omg.CORBA.MARSHAL: FINE: 00810007: Underflow in BufferManagerReadStream after last fragment in message  vmcid: OMG  minor code: 7  completed: No
    at com.sun.proxy.$Proxy167.endOfStream(Unknown Source)
    at com.sun.corba.ee.impl.encoding.BufferManagerReadStream.underflow(BufferManagerReadStream.java:122)
    at com.sun.corba.ee.impl.encoding.CDRInputStream_1_1.grow(CDRInputStream_1_1.java:111)
    at com.sun.corba.ee.impl.encoding.CDRInputStream_1_2.alignAndCheck(CDRInputStream_1_2.java:126)
    at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.read_long(CDRInputStream_1_0.java:433)
    at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.readValueTag(CDRInputStream_1_0.java:1672)
    at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.read_value(CDRInputStream_1_0.java:918)
    at com.sun.corba.ee.impl.encoding.CDRInputObject.read_value(CDRInputObject.java:518)
    at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl$14.read(DynamicMethodMarshallerImpl.java:383)
    at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl.readArguments(DynamicMethodMarshallerImpl.java:450)
    at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:171)
    at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
    at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
    at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
    at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
    at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
    at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
    at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
    at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
    at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
    at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
    at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)

----------END server-side stack trace----------  vmcid: OMG  minor code: 7  completed: No
    at bookstore.controller._BookEJBRemote_Wrapper.createBook(bookstore/controller/_BookEJBRemote_Wrapper.java)
    at bookstore.client.BookStoreMain.main(BookStoreMain.java:28)
Caused by: java.rmi.MarshalException: CORBA MARSHAL 1330446343 No; nested exception is: 
    org.omg.CORBA.MARSHAL: ----------BEGIN server-side stack trace----------
org.omg.CORBA.MARSHAL: FINE: 00810007: Underflow in BufferManagerReadStream after last fragment in message  vmcid: OMG  minor code: 7  completed: No
    at com.sun.proxy.$Proxy167.endOfStream(Unknown Source)
    at com.sun.corba.ee.impl.encoding.BufferManagerReadStream.underflow(BufferManagerReadStream.java:122)
    at com.sun.corba.ee.impl.encoding.CDRInputStream_1_1.grow(CDRInputStream_1_1.java:111)
    at com.sun.corba.ee.impl.encoding.CDRInputStream_1_2.alignAndCheck(CDRInputStream_1_2.java:126)
    at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.read_long(CDRInputStream_1_0.java:433)
    at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.readValueTag(CDRInputStream_1_0.java:1672)
    at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.read_value(CDRInputStream_1_0.java:918)
    at com.sun.corba.ee.impl.encoding.CDRInputObject.read_value(CDRInputObject.java:518)
    at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl$14.read(DynamicMethodMarshallerImpl.java:383)
    at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl.readArguments(DynamicMethodMarshallerImpl.java:450)
    at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:171)
    at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
    at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
    at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
    at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
    at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
    at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
    at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
    at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
    at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
    at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
    at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)

----------END server-side stack trace----------  vmcid: OMG  minor code: 7  completed: No
    at com.sun.corba.ee.impl.javax.rmi.CORBA.Util.mapSystemException(Util.java:266)
    at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.privateInvoke(StubInvocationHandlerImpl.java:211)
    at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.invoke(StubInvocationHandlerImpl.java:150)
    at com.sun.corba.ee.impl.presentation.rmi.codegen.CodegenStubBase.invoke(CodegenStubBase.java:226)
    at bookstore.controller.__BookEJBRemote_Remote_DynamicStub.createBook(bookstore/controller/__BookEJBRemote_Remote_DynamicStub.java)
    ... 2 more
Caused by: org.omg.CORBA.MARSHAL: ----------BEGIN server-side stack trace----------
org.omg.CORBA.MARSHAL: FINE: 00810007: Underflow in BufferManagerReadStream after last fragment in message  vmcid: OMG  minor code: 7  completed: No
    at com.sun.proxy.$Proxy167.endOfStream(Unknown Source)
    at com.sun.corba.ee.impl.encoding.BufferManagerReadStream.underflow(BufferManagerReadStream.java:122)
    at com.sun.corba.ee.impl.encoding.CDRInputStream_1_1.grow(CDRInputStream_1_1.java:111)
    at com.sun.corba.ee.impl.encoding.CDRInputStream_1_2.alignAndCheck(CDRInputStream_1_2.java:126)
    at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.read_long(CDRInputStream_1_0.java:433)
    at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.readValueTag(CDRInputStream_1_0.java:1672)
    at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.read_value(CDRInputStream_1_0.java:918)
    at com.sun.corba.ee.impl.encoding.CDRInputObject.read_value(CDRInputObject.java:518)
    at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl$14.read(DynamicMethodMarshallerImpl.java:383)
    at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl.readArguments(DynamicMethodMarshallerImpl.java:450)
    at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:171)
    at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
    at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
    at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
    at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
    at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
    at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
    at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
    at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
    at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
    at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
    at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)

----------END server-side stack trace----------  vmcid: OMG  minor code: 7  completed: No
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at com.sun.corba.ee.impl.protocol.giopmsgheaders.MessageBase.getSystemException(MessageBase.java:813)
    at com.sun.corba.ee.impl.protocol.giopmsgheaders.ReplyMessage_1_2.getSystemException(ReplyMessage_1_2.java:131)
    at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.getSystemExceptionReply(MessageMediatorImpl.java:594)
    at com.sun.corba.ee.impl.protocol.ClientRequestDispatcherImpl.processResponse(ClientRequestDispatcherImpl.java:518)
    at com.sun.corba.ee.impl.protocol.ClientRequestDispatcherImpl.marshalingComplete(ClientRequestDispatcherImpl.java:392)
    at com.sun.corba.ee.impl.protocol.ClientDelegateImpl.invoke(ClientDelegateImpl.java:258)
    at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.privateInvoke(StubInvocationHandlerImpl.java:198)
    ... 5 more

Answer:

it looks like your entity class is not serialize, implement Serializable interface in your Book class

@Entity
@NamedQuery(name = "findAllBooks", query = "select b from Book b")
public class Book implements Serializable {

@Id
@GeneratedValue
private long id;

...

}

hope it will help.

Question:

I've created a dynamic web application and i'd like to deploy it with glassfish. I've successed build my sources to MyProject.jar. But when i deployed it, the following error displayed:

remote failure: Archive type of /home/davenlin/MyProject/build/MyProject.jar was not recognized

My project is just a normal Restful application, not ejb application, so i don't know if i must generate a MyProject.war instead of MyProject.jar.

Please help me. Thanks !


Answer:

Okay, because my comment was rather unexplanatory: Web applications are handled by application servers or servlet containers. Both do quiet a lot of work for you and web applications are not comparable to desktop or standalone java applications. While your standalone applications are deployed as jar - files and then executed by the JVM, web applications are executed by the container (application server / servlet container). So this does require your application to provide additional configuration and affords the archive itself to have a different structure. So even if you are just exposing some web services to build a restful application, your application server will do things for you such as forwarding requests to the right classes, translate query and post parameters into java - objects accessable by your own classes respectivly your own objects and returning your response to the clients. The interesting thing about it is: The additional files in the web - archive are usually xml - files and web - related files such as html, css, js. So this does not distinguish war's from jar's as you can also package additional resources within a jar. The basic but now obsolete requirement on a war - file is that it contains a deployment descriptor (which is again is an xml - file) to configure your application , its context and the relative url (more concrete : url - patterns) it uses , but as this requirement is obsolete someone may still think that this distinguishing is obsolete, too.

Question:

I'm trying to work with Eclipse Mars 2 and Glassfish 3.1.2, but when I use EclipseLink 2.1 to create the entitites from tables, javax.persistence is not found in the buildpath.

Is this the normal behaviour?

  1. I created the Oracle db connection with eclipse
  2. I installed JEE 6 SDK with Glassfish 3
  3. I started the glassfish server and configured the data source and connection pool.
  4. I created a JPA project and created the entities from the db connection tables.

Something I find curious is that the jee.jar that is inside glassfish/lib only contains a pom.xml

Isn't Glassfish supposed to contain all the jars needed to develop with the jee standard?

Is my project meant to be a Maven project in order to automatically download this jars? Could I fix this by configuring my project as a Maven project?


Answer:

Isn't Glassfish supposed to contain all the jars needed to develop with the jee standard?

Yes, and it contains all the jars needed but in an indirect way. Even though it is a single jar file with only one file, namely, MANIFEST.MF and a directory maven which contains the pom file you mentioned.

But if you open the MANIFEST.MF file you'll see that it is pointing to a lot of jar files in the Class-Path: entry which you need to be able develop JavaEE applications.

So everything is there and you only need to add this file into your dependency to be able to compile your JavaEE (Servlets, JSF, EJB, JPA, ...) classes and deploy on the server. But this (javaee.jar) must be a compile time dependency, i.e., should not be packaged with your application as the jars are already contained in the server.

Is my project meant to be a Maven project in order to automatically download this jars?

No. Your project can be but should not be a maven project. Let us say, for example, you have an Eclipse project where you want to develop an EJB application. Just right click on the project

  • go to the Properties -> Build Path page and change to Libraries tab

  • click on Add External Jars ...

  • go to the Glassfish lib directory and add the javaee.jar, and you are done.
  • now you can use all the JavaEE annotations and classes.

Question:

I am trying to use slf4j as the logging provider for jboss-logging which comes bundled with Glassfish 4.1. But no matter where I put the slf4j jar file, jboss-logging is not able to find the jar. It fails during the server start-up with the error below -

Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory not found by org.jboss.logging.jboss-logging [16
        at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1532)
        at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:75)
        at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1955)
        at java.lang.ClassLoader.loadClass(Unknown Source)

How can I make the slf4j jar visible to the jboss-logging?


Answer:

You can put your slf4j jar at

<glassfish installation dir>\glassfish\modules\endorsed\  

You will need to add bridge/implementation as well, otherwise , Glassfish will not be able to find the above mentioned class. You can add slf4j-log4j and log4j or slf4j-jdk jar along with slf4j in endorsed folder mentioned above depending upon what your intentions are.

Question:

I have an application which I am deploying on GlassFish. It has an EJB-tier with (JPA) Entites and EJBs to get access and write to the database and it has 3 (independent) web apps. Everything is built with Maven.

ServerApplication 
  |
  +-ServerApplication-ear
  +-ServerApplication-ejb
  |
  +-GrumpyCat (war)
  +-HummingBird (war)
  +-Koala (war)

All three war projects depend on the ejb project. When compiling/building the ear, it copies the war files to the ear project and then I can deploy the ear file on GlassFish.

This works fine, all 4 modules (the ejb, and the 3 war) get deployed without problems and I can access the 3 war projects like:

myServer.com/GrumpyCat
myServer.com/HummingBird
myServer.com/Koala

My problem is, that I can't deploy a single war project on its own. For example when I change something in the koala project, I would like to be able to build only the koala.war and deploy it on the server, without having to upload and deploy the complete ear file.

But when deploying, GlassFish tells me either :

  • there is already a project deployed on Koala (true, it was deployed together with the ear)
  • or (when I change the build-version) it doesn't "know" the ejbs and I get a number of ClassNotFound Exceptions.

Is there a way to deploy the modules of the application one by one?


Answer:

Your second approach is the way to go if you really want to deploy them individually. However, you are seeing a ClassNotFound exception because the WARs are individual projects and as such don't have access to the EAR's class path.

To make that work, you have to add the public API of your application to your WAR's classpath. The public API consists of at least the EJB's remote interfaces of the EJBS that you would like to access from the WAR and any DTOs used in your API.

The easiest way is to create a separate package (such as com.example.api) and let a build tools such as ant or Maven bundle that api package together with your EJBs and your WARs, or you create a myapp-api.jar and include it in the respective class-paths.

Then you can remove the WARs from the EAR and deploy them as separate projects.

Question:

I'm trying to run a batch script that would create a new glassfish domain (v 3.1) and right after the creation it would continue with some administrative tasks, like removing other directories or copying files to the newly-created domain. Problem is, I have to wait until the glassfish intallation script finishes its work. I have tried to create a new window with:

Start /WAIT "" asadmin --user admin --interactive=false create-domain   --adminport 4848  --instanceport 8080  --nopassword new_domain

and running some simple commands (like xcopy, rd) after it, in the same .bat file. The problem is, after the asadmin script has finished its work new window does not close, but stays opened and the whole script hangs waiting for the job to terminate. I can close it manually and the script continues its flow, but this solution is not satisfactory. I have even tried to modify the asadmin.bat script to force it to shutdown after creation in this way:

%JAVA% -jar "%~dp0..\glassfish\modules\admin-cli.jar" %* && exit
exit

But it does not help.


Answer:

As the comment already suggested you have to use call instead of Start and you don't need that /WAIT flag:

echo "Start..."
call asadmin --user admin --interactive=false create-domain   --adminport 4848  --instanceport 8080  --nopassword new_domain
xcopy something...
// more

Question:

I'm using Netbeans 8.0.2 and Glassfish 4.0 (and 4.1) to build a message driven bean. I'm not using Maven (my choice would be to use it)

There is an article to put the revision and build number in the build.xml file (http://dragly.org/2009/10/11/revision-and-build-numbers-for-your-netbeans-apps/). This is for a SE app and I'm not sure if it will work for an EJB and how.

I have a fixed version number but need to increment the build number.

  1. Where and how do I put the version number (plus build number) in for an EJB? (It should be like 1.0.0.buildNumber) (searching for "ejb-jar.xml" plus version gives a lot of EJB version 2.x, 3.x results)
  2. How do I access this number in my EJB? (I was thinking of accessing it as a resource in my class?)

Answer:

Ok, I've figured it out: For a jar (library, SE, etc) in the build.xml file, just before the closing </project> tag insert the following; Based on http://www.jug-muenster.de/versioning-and-signing-jar-files-in-netbeans-775/ : Note: The manifest file have a very specific format!

<target name="-pre-init">
    <property name="project.name" value="MySEProject" />
    <property name="document.title" value="My SE Project Specification" />
    <property name="document.version" value="1.0" />
    <property name="version.number" value="1.7.0" />
    <buildnumber file="build.num" />
    <tstamp>
        <format property="NOW" pattern="yyyy-MM-dd HH:mm:ss z" />
    </tstamp>

    <exec outputproperty="svna.version" executable="svnversion">
        <arg value="-c" />
        <redirector>
            <outputfilterchain>
                <tokenfilter>
                    <replaceregex pattern="^[0-9]*:?" replace="" flags="g"/>
                    <replaceregex pattern="M" replace="" flags="g"/>
                </tokenfilter>
            </outputfilterchain>
        </redirector>
    </exec>

    <!-- Add the version information to the manifest file -->
    <manifest file="${manifest.file}">
        <attribute name="Package-Title" value="MyCompany/${project.name}" />
        <attribute name="Specification-Title" value="${document.title}" />
        <attribute name="Specification-Version" value="${document.version}" />
        <attribute name="Specification-Vendor" value="MyCompany" />
        <attribute name="Implementation-Title" value="${project.name}" />
        <attribute name="Implementation-Version" value="${halo.version.number}.${build.number}" />
        <attribute name="Implementation-Vendor" value="MyCompany" />
        <attribute name="Revision" value="${svna.version}" />
        <attribute name="Built-By" value="${user.name}" />
        <attribute name="Built-Date" value="${NOW}" />
    </manifest>
</target>

<target name="-post-jar">
    <delete file="${manifest.file}" />
</target>

And for an EJB. In the (ABC) Enterprise Application folder, edit the build.xml file the same as above, the target tag name change to pre-dist as well as the manifest tag <manifest file="${meta.inf}/MANIFEST.MF">.

Furthermore for EJB, to be able to programmable read the version number, edit the build.xml file in the ABC-ejb folder (where ABC is the ejb project name). The target name change to -post-init.

The code to read it out (you get all the manifest files from all the libraries you include, thus you have to hunt for your one - maybe a better way will be to look at the URL?):

import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.Manifest;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author TungstenX
 */
public class VersionInfo {
    private static final Logger LOG =    Logger.getLogger(VersionInfo.class.getName());
    private static final String PROJECT = "MySEProject";
    private static final String COMPANY = "MyCompany";
    private static Manifest MANIFEST;

    /**
     * Get the version number from the manifest file
     * @return The version number or '--'
     */
    public static String GetVersionNumber() {
        if (MANIFEST == null) {
            try {
                Enumeration<URL> resources = VersionInfo.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
                while (resources.hasMoreElements()) {
                    URL url = resources.nextElement();
                    try(InputStream is = url.openStream()) {
                        Manifest tmpManifest = new Manifest(is);
                        for (Object o : tmpManifest.getMainAttributes().keySet()) {
                            if (o.toString().equals("Package-Title") 
                                    && tmpManifest.getMainAttributes().getValue(o.toString()).startsWith(COMPANY)
                                    && tmpManifest.getMainAttributes().getValue(o.toString()).endsWith(PROJECT)) {
                                MANIFEST = tmpManifest;
                            } 
                        }
                    } catch (Exception e) {
                        LOG.log(Level.SEVERE, "Error while reading manifest files: {0}", e.toString());
                    }
                }
            } catch (Exception e) {
                LOG.log(Level.SEVERE, "Error while reading manifest files: {0}", e.toString());
            }
        }
        if(MANIFEST != null) {
            return MANIFEST.getMainAttributes().getValue("Implementation-Version");
        } else {
            return "--";
        }
    }

Note: The difference in target name and location of MANIFEST.MF file!

Question:

I'm desperate for any help on this issue as i'm stuck for a while now.

Part of my application using Glassfish JMS to transfer messages, the application works smoothly om my development machine if the jars are included, now i have the need to load the JMS jars dynamically on runtime, so i used the following code to load the jars in the classloader at runtime

public class ClassPathHack {
    private static final Class<?>[] parameters = new Class[]{URL.class};
    public static synchronized void addFile(String s) throws IOException, Exception {
        File f = new File(s);
        try {
            java.net.URLClassLoader loader = (java.net.URLClassLoader)ClassLoader.getSystemClassLoader();
            java.net.URL url = f.toURI().toURL();
            for (java.net.URL it : java.util.Arrays.asList(loader.getURLs())){
                if (it.equals(url)){
                    return;
                }
            }
            java.lang.reflect.Method method = java.net.URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{java.net.URL.class});
            method.setAccessible(true); 
            method.invoke(loader, new Object[]{url});
        } catch (final java.lang.NoSuchMethodException | 
            java.lang.IllegalAccessException | 
            java.net.MalformedURLException | 
            java.lang.reflect.InvocationTargetException e){
            throw new Exception(e);
        }
    }
}

and in the main method i've loaded all the JMS used jars before raising the thread that connect to JMS using the following code:

public static void loadGlassfishJars(){
    try {
        System.out.println("DEBUGGNG: Loading Glassfish jars");
        ClassPathHack.addFile(glassfishPath + "\\glassfish\\lib\\appserv-rt.jar");
        ClassPathHack.addFile(glassfishPath + "\\glassfish\\modules\\console-jms-plugin.jar");
        ClassPathHack.addFile(glassfishPath + "\\glassfish\\lib\\gf-client.jar");
        ClassPathHack.addFile(glassfishPath + "\\mq\\lib\\imq.jar");
        ClassPathHack.addFile(glassfishPath + "\\mq\\lib\\imqbroker.jar");            
        ClassPathHack.addFile(glassfishPath + "\\glassfish\\lib\\install\\applications\\jmsra\\imqjmsra.jar");
        ClassPathHack.addFile(glassfishPath + "\\glassfish\\lib\\javaee.jar");
        ClassPathHack.addFile(glassfishPath + "\\glassfish\\modules\\jms-admin.jar");
        ClassPathHack.addFile(glassfishPath + "\\glassfish\\modules\\jms-core.jar");
        ClassPathHack.addFile(glassfishPath + "\\mq\\lib\\jms.jar");
        ClassPathHack.addFile(glassfishPath + "\\glassfish\\modules\\jmxremote_optional-repackaged.jar");
    } catch (Exception ex) {
        Logger.getLogger(ZMQTranslator.class.getName()).log(Level.SEVERE, null, ex);
    }

and the main method is something like the following:

     public static void main(String[] args) {

        //loading glassfish jms jars

        loadGlassfishJars();

        //JMS connector thread
        System.out.println("DEBUGGNG:initiating ZMQConnectionReceiver");
        ZMQConnectionReceiver zmqCon = new ZMQConnectionReceiver();
        Thread t = new Thread(zmqCon);
        t.start();
}

the exception is thrown while calling the constructor of ZMQConnectionReceiver class, which imports the following classes

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
//NOT RELATED IMPORTS
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.Properties;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.json.Json;
import model.DeviceConnection;
import org.zeromq.ZMQ;
import javax.json.stream.*;

and it has a simple constructor as follows:

 public ZMQConnectionReceiver(){
            lostNFound = new ConcurrentLinkedDeque();
    }

The exception is thrown when calling the constructor

Exception in thread "main" java.lang.NoClassDefFoundError: javax/jms/Destination

I've checked the existence of Destination Class in jms.jar and it's there.

Note. Glassfish JMS has a weird behavior, it requires that the application connecting to it should have the JARs installed with the same Glassfish version you are trying to connect to, any other jars will fail even if it was from the same Glassfish version but other installation.

How can I solve this issue?


Answer:

I managed to work around this issue by downloading all the JMS dependencies JARs by adding the following dependency

<dependency>
    <groupId>org.glassfish.main.extras</groupId>
    <artifactId>glassfish-embedded-all</artifactId>
    <version>3.1.2</version>
</dependency>

to the pom file of a maven application and building the application.

after that I included the downloaded JARs in my application and it worked fine as a standalone application on any machine.

Question:

In my final project, i build tool testing to test JPA entity,this project based on web using JSF and primefaces UI and my server glassfish server,my tool test crud(create, read using JPQL, update, delete), and iam try to complete tesing using compile string, but iam get error from line 2, if this error means need to jars libraries or need other solution ?

and my second question, is this better solution to test any entity/ies at this way ? pls support me and thanks..... this is class test Create (insert data) ...

public boolean ReturnCompleteCreateTesting(String FilePath) {
    StringBuilder sb = new StringBuilder();

    sb.append("package Testing;\n");
    sb.append("import javax.persistence.EntityManagerFactory; \n");
    sb.append("import javax.persistence.EntityManager; \n");
    sb.append("import javax.persistence.Persistence; \n");
    sb.append("import Entities.Employ; \n");
    sb.append("public class TestCreation implements Testing.TestCreate.DoStuff {\n");
    sb.append("@Override \n");
    sb.append("public void doStuff() {\n");
    sb.append("EntityManagerFactory emfactory=Persistence.createEntityManagerFactory(\"JPATestingPU\");\n");
    sb.append("EntityManager emanager=emfactory.createEntityManager();\n");
    sb.append("long ids=3;");
    sb.append("emanager.getTransaction().begin();\n");
    sb.append("Employ emp = new Employ(); \n");
    sb.append("emp.setDegree(\"20\"); \n");
    sb.append("emp.setDepartment(\"Software Engineering\"); \n");
    sb.append("emp.setId(ids); \n");
    sb.append("System.out.print(\"Save Seccessfuly\"); \n");
    sb.append("emanager.persist(emp); \n");
    sb.append("emanager.getTransaction().commit(); \n");
    sb.append("emanager.close(); \n");
    sb.append("emfactory.close(); \n");
    sb.append(" \n");
    sb.append("    }\n");
    sb.append("}\n");

    File TestEntity = new File(FilePath);

    if (TestEntity.getParentFile()
            .exists() || TestEntity.getParentFile().mkdirs()) {

        try {
            Writer writer = null;
            try {
                writer = new FileWriter(TestEntity);
                writer.write(sb.toString());
                writer.flush();
            } finally {
                try {
                    writer.close();
                } catch (Exception e) {
                }
            }

            /**
             * Compilation Requirements
             * ********************************************************************************************
             */
            DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);

            // This sets up the class path that the compiler will use.
            // I've added the .jar file that contains the DoStuff interface within in it...
            List<String> optionList = new ArrayList<String>();
            optionList.add("-classpath");
            optionList.add(System.getProperty("java.class.path") + ";dist/TestCreate.jar");

            Iterable<? extends JavaFileObject> compilationUnit
                    = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(TestEntity));
            JavaCompiler.CompilationTask task = compiler.getTask(
                    null,
                    fileManager,
                    diagnostics,
                    optionList,
                    null,
                    compilationUnit);

            if (task.call()) {

                System.out.println("Yipe");
                // Create a new custom class loader, pointing to the directory that contains the compiled
                // classes, this should point to the top of the package structure!
                URLClassLoader classLoader = new URLClassLoader(new URL[]{new File("./").toURI().toURL()});
                // Load the class from the classloader by name....
                Class<?> loadedClass = classLoader.loadClass("Testing.TestCreation");
                // Create a new instance...
                Object obj = loadedClass.newInstance();
                // Santity check
                if (obj instanceof DoStuff) {
                    // Cast to the DoStuff interface
                    DoStuff stuffToDo = (DoStuff) obj;
                    // Run it baby
                    stuffToDo.doStuff();

                }

            } else {
                for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
                    System.out.format("Error on line %d in %s%n",
                            diagnostic.getLineNumber(),
                            diagnostic.getSource().toUri());
                }
            }
            fileManager.close();
        } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException exp) {
            exp.printStackTrace();
        }
    }
    return true;
}

public static interface DoStuff {

    public void doStuff();
}

Answer:

Regarding your base question about Glassfish, you need to do one of three things: Deploy needed jars withing your war file, put those jar files on the the classpath used by Glassfish, or put the jar files in the lib directory under your domain. Usually:

[Glassfish installation directory]\glassfish4\glassfish\domains\domain1\lib\appLib

Or alternatively you can put them here:

[Glassfish installation directory]\glassfish4\glassfish\lib

But the former is the most appropriate of the two.