Hot questions for Using GlassFish in server

Question:

I just downloaded the GlassFish 5.0 archive - Full Platform, unzipped it, I run it through the command line.

asadmin start-domain

problem:

Exception in thread "main" java.lang.NullPointerException
at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.initializeServiceLocator(AbstractModulesRegistryImpl.java:152)
at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.newServiceLocator(AbstractModulesRegistryImpl.java:144)
at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.createServiceLocator(AbstractModulesRegistryImpl.java:218)
at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.createServiceLocator(AbstractModulesRegistryImpl.java:224)
at com.sun.enterprise.module.single.StaticModulesRegistry.createServiceLocator(StaticModulesRegistry.java:88)
at com.sun.enterprise.admin.cli.CLIContainer.getServiceLocator(CLIContainer.java:217)
at com.sun.enterprise.admin.cli.CLIContainer.getLocalCommand(CLIContainer.java:255)
at com.sun.enterprise.admin.cli.CLICommand.getCommand(CLICommand.java:231)
at com.sun.enterprise.admin.cli.AdminMain.executeCommand(AdminMain.java:371)
at com.sun.enterprise.admin.cli.AdminMain.doMain(AdminMain.java:306)
at org.glassfish.admin.cli.AsadminMain.main(AsadminMain.java:57)

I tried to set the path in the file asenv.bat -> set path = C:/.../Java/bin - did not help. Tried so to launch: asadmin start-domain domain1 - did not help.

Installed: jdk-9.0.1 Also tried on the 8th, did not help. What to do???


Answer:

OK, Glassfish 5.1 doesn't exist for the moment. Continue with Glassfish 5.0 with this solution:

Just set the AS_JAVA variable in your asenv.bat file located here: C:\DEVENV\glassfish5\glassfish\config.

File to edit: add last line

Relaunch your server....enjoy :

Question:

I am trying to test my web application in GlassFish 4 from eclipse. When I am starting GlassFish 4 with a file (startserv.bat), it works fine, but when I am trying to run it from Eclipse, it starts loading, but then the startup process gets stuck at 69%, on a message Launching Delegate...

After several minutes in that condition, it gives me an error message:

After a few re-tries, I got this message:

Even though nothing is running on the port 8080 (GlassFish's port) and 4848 (GlassFIsh's admin port)

It worked fine for me before, but now for some reason, it just doesn't, I haven't done anything to it's settings or anything. How can I resolve this problem?

Here is my startup console log: http://pastebin.com/XL0Lh5zw (using pastebin to avoid making the post to big)


Answer:

I had the same problem, with the same messages.

After a long search, I gave up and I removed the server.

And I removed the Server Runtime Environment

The Glassfish files were not removed only the eclipse configurations, and then I re-created the Server Runtime and the Server using the existent glassfish server and the problem was fixed :D.

Question:

I've been trying to create a simple Restful WebService, using NetBeans Ide. My Java EE Version is: Java EE 7 Web.

I created a new Java Web Application, setting this ContexPath: /DukesAgeService.

Now, running my application, browser display my Index.html page at:

http://localhost:8080/DukesAgeService/

so, everything works fine.

Then, I tried to create a simple restful resource using the RESTful Web Service Wizard.

So, I created this class:

package firstcup.webservice;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;

/**
 * REST Web Service
*
* @author nolanof
*/
@Path("dukesAge")
public class DukesAgeResource {

@Context
private UriInfo context;

/**
 * Creates a new instance of DukesAgeResource
 */
public DukesAgeResource() {
}

/**
 * Retrieves representation of an instance of firstcup.webservice.DukesAgeResource
 * @return an instance of java.lang.String
 */
@GET
@Produces("text/plain")
public String getText() {        
    return "hello world";
}
}

But running my application, at url: http://localhost:8080/DukesAgeService/dukesAge I get a 404-not found page.

I exptected that any incoming get request that has the url of "/dukesAge" was handled by DukesAgeResource class getText method. Whats' wrong?

Thanks


Answer:

You're probably missing the JAX-RS application servlet. You can either define it in the web.xml or if you want to go xml-less, you can use a Application subclass. The easiest way IMO is just to use the Application subclass annotated with @ApplicationPath. A servlet will be created and the servlet path will be set the value in the annotation. Something like

@ApplicationPath("/rest")
public class RestApplication extends Application {
    // All request scoped resources and providers
    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> classes = new HashSet<>();
        classes.add(DukesAgeResource.class);
        return classes;
    }

    // all singleton resources and providers
    @Override
    public Set<Object> getSingletons() {
        Set<Object> singletons = new HashSet<>();
        return singletons;
    }
}

Then the resource should be access the resource via

http://localhost:8080/DukesAgeService/rest/dukesAge.

There are other ways, but this is the portable way. Glassfish uses Jersey, but creating a Java EE web application from scratch in Netbeans will only import compile time Java EE standard classes (no Jersey dependencies). So the above is really your bet to start off with.

You can see other deployment options at the Jersey Documentation. For some of the options, you may need to add some Jersey compile-time dependencies. That's why I just mentioned the above. No other jars needed.

Another thing that would cause a 404, is if you specify the JAX-RS servlet path as /*. This will conflict with the default servlet that serves the static resources like your html pages. That's why I set it to /rest.


UPDATE

It is also stated in the JAX-RS spec that if there are empty sets returned in the getClasses() and getSingletons(), implicit package scanning should occur. (provider) Classes annotated withe @Provider will by default be added as singletons and a resource classes annotated with @Path will be per-request objects (meaning a new object is created each request). So you could alternatively just have

@ApplicationPath("/rest")
public class RestApplication extends Application {
    // Left empty
}

And it should work just the same.

Question:

I developed a breakout alike game with a friend using HTML5 WebSockets and java as backend and recently deployed my game on a Glassfish server that's running on the 20$ Digitalocean droplet (3GB ram, 2cpu's).

When developing the game I worked with IntelliJ and a co-worker with Netbeans, when deploying our WAR file on the Glassfish servers running on our PC everything is working as expected. But when deploying the exact same WAR file on the droplet, the ball seems to be moving 3 times as fast.

I have tried reproducing the issue by installing the same Ubuntu server as the droplet on a virtual machine and executing the same steps I used to install OpenJDK, Glassfish, ... but on the VM it was working fine as well.

Other droplets with 1 CPU (tried ubuntu and centos) produces the same issues. I wonder what might be the cause of this issue that I'm missing?

Below is the code that I'm using for the connection/game:

WebSocket:

@ServerEndpoint("/singleplayer")
public class SingleplayerSocket {

    private static final Set<Session> PLAYERS = Collections.synchronizedSet(new HashSet<Session>());

    private Session session;
    private Gson gson;
    private Game game;

    private void sendMessage(String message) {
        try {
            for (Session player: PLAYERS) {
                if (player == session) {
                    player.getBasicRemote().sendText(message);
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void gameStart() {
        game.start();
        sendMessage("Game started");
    }

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        gson = new Gson();
        PLAYERS.add(session);

        sendMessage("Connection established");
    }

    @OnMessage
    public void onMessage(String message) {
        if (session != null && session.isOpen()) {
            String messageType = gson.fromJson(message, MessageType.class).getMessage();

            switch (messageType) {

                case "gameSetup":
                    gameSetup(message);
                    break;

                case "gameStart":
                    gameStart();
                    break;
            }
        }
    }

    @OnClose
    public void onClose(Session session) {
        PLAYERS.remove(session);
        this.session = null;
    }
}

Game class with the ball move method underneath:

        public class Game implements Runnable {

        private final int TARGET_FPS = 60;
        private final long OPTIMAL_TIME = 1000000000 / TARGET_FPS;

        private volatile boolean gameRunning;
        private volatile boolean gamePaused;

        private Session session;
        private Thread thread;
        private Gson gson;

        public Game(Session session, int width, int height, String difficulty) {
            this.session = session;
            this.WIDTH = width;
            this.HEIGHT = height;
            gson = new Gson();
            timer = new Timer();

            setup(difficulty);
        }

        private void setGameRunning(boolean gameRunning) {
            this.gameRunning = gameRunning;
        }

        private void update(double delta) {
            ball.move(delta);
            collisionDetectionWalls();
            collisionDetectionPaddle();
            collisionDetectionBricks();
        }

        public void start() {
            thread = new Thread(this);
            thread.start();
            setGameRunning(true);
        }

        public void stop() {
            setGameRunning(false);
        }

        private void end(boolean won) {
            updateScore();
            sendGameEnd(won);
            stop();
        }

        private void sendMessage(String message) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        private void sendGameUpdate() {
            GameUpdateData data = new GameUpdateData(paddle, ball, bricks);
            GameUpdateResponse response = new GameUpdateResponse("gameUpdate", data);
            sendMessage(gson.toJson(response));
        }

        @Override
        public void run() {
            long lastLoopTime = System.nanoTime();
            long lastFpsTime = 0;

            while (gameRunning) {
                long currentTime = System.nanoTime();
                long updateLength = currentTime - lastLoopTime;
                lastLoopTime = currentTime;
                double delta = updateLength / ((double) OPTIMAL_TIME);

                lastFpsTime += updateLength;
                if (lastFpsTime >= 1000000000) {
                    lastFpsTime = 0;
                }

                if (!gamePaused) {
                    update(delta);
                    sendGameUpdate();
                }

                try {
                    long sleepTime = (System.nanoTime() - lastLoopTime + OPTIMAL_TIME) / 1000000;
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                }
            }
        }
    }

public class Ball {
    public void move(double delta) {
        if (isLaunched()){
            double trigoX = Math.cos(angle);
            double trigoY = Math.sin(angle);

            x += trigoX * velocity * delta;
            y += trigoY * velocity * delta;
        }
    }
}

Answer:

While working on the multi player game I stumbled on a couple of issues and decided to check a couple of variables with console.log() in Javascript. I noticed the game was being started twice when clicking on the button and solved the issue by adding a server side check to prevent starting the game multiple times when clicking on the 'Play' button.

private void gameStart() {
    if (!game.isGameRunning()) {
        game.start();
        sendMessage("Game started");
    }
}

The ball speed is working fine now.

Question:

Glassfish Server is running in background and I am not able to stop, start or restart the process. I know, restarting the system will do the job. Is there any other process to stop the process?

Here is the details:

  1. When I try to stop, it says it is domain1 is not running:

    C:\Server\glassfish4\glassfish\bin>asadmin stop-domain CLI306: Warning - The server located at C:\Server\glassfish4\glassfish\domains\domain1 is not running. Command stop-domain executed successfully.

  2. However I am able to open admin console in web browser for http://localhost:4848/common/index.jsf

  3. When I am trying to start or restart it throws error:

    C:\Server\glassfish4\glassfish\bin>asadmin start-domain There is a process already using the admin port 4848 -- it probably is another instance of a GlassFish server. Command start-domain failed.

    C:\Server\glassfish4\glassfish\bin>asadmin restart-domain Server is not running, will attempt to start it... There is a process already using the admin port 4848 -- it probably is another instance of a GlassFish server. Command restart-domain failed.

  4. I tried to find PID with netstat -a -n -o command for the port 4848. I got two entries but not localhost id:

    TCP    0.0.0.0:4848           0.0.0.0:0              LISTENING       9116 
    TCP    [::]:4848              [::]:0                 LISTENING       9116
    

Answer:

Try this

taskkill /F /PID 9116

Also find the PIDs of processes which hold port 8080 and kill them. (If above solution don't work)

netstat -aon | find "LISTENING" | find ":8080"
taskkill /F /PID process_id_here

Question:

I have problem about importing Java EE glassfish server to my IntelliJ. I have searched nothing on the web.

When I want to create a new glassfish project, I don't have option for it.

I can't add image cause I don't have reputation for it. I add direct link to image below text.

Screenshots:


Answer:

It appears you have a community version of IntelliJ. Tools to support enterprise frameworks, like JavaEE or Grails, are only available in paid version. If need a free JavaEE IDE, I recommend Netbeans,which is similar to IntelliJ but free, or Eclipse, which is also great, but more different

Question:

The Glassfish4 server installed on my machine has Maximum Pool Size = 32 connections. Two cron jobs are scheduled from my application after every 10 and 15 mins on this server. The server crashed after 2 hours with the exception "java.sql.SQLException: Error in allocating a connection. Cause: In-use connections equal max-pool-size and expired max-wait-time. Cannot allocate more connections."

So, I altered the JDBC Connection pool settings and put in really large numbers just to see what would happen.

Maximum Pool Size: 1000000000 (1 billion) Max Wait Time: 300000 (5 minutes)

Now my cron jobs are running fine.

Do you think having set the JDBC Connection pool attributes this high could cause issues? Please advise what values will be optimum.


Answer:

I have resolved this issue with below settings in Glassfish4

Initial and Minimum Pool Size:16

Maximum Pool Size:64

Pool Resize Quantity:4

Idle Timeout:60

Max Wait Time:3000

I enabled connection leak monitoring in Glassfish4.

After enabling connection leak monitoring, when I checked the monitored data after some time, I could see ConnectionLeak exception in logs in some of my java classes. I closed the connections in these classes as they were being made directly from Connection object and JPA Entity Manager was not used in them.

Now all my cron jobs are running without Server crash.

Question:

i am trying to debug my project but its showing error message as such :

"cannot Deploy WebForm Deployment Error for module: WebForm: Error occurred during deployment: Exception while preparing the app : Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect. Error Code: 0."

i have done every possible step with the persistence.xml as well as the JPA tables but still it's not deploying. Help!


Answer:

You have some sort of DB-connection configured in your app. The message "Error connecting to server localhost on port 1527 with message Connection refused: connect. Error Code: 0" says, your program tries to reach a DB on port 1527. The possibilities are:

  • on the production server is no DB running: install and configure DB
  • the program does not have the rights to access DB
  • the DB-connection on production-server is reached differently than in development - adjust your configuration

Question:

I want to set up glassfish server (Java EE 8) downloaded from https://www.oracle.com/technetwork/java/javaee/overview/index.html, but I don't see glassfish nor do I see "Download additional server adapters" when I try to add a new server to a project.

What should I do now?


Answer:

For seeing them you must have installed Eclipse WTP

Or you can also download the glassfish tools (you can also download them from eclipse marketplace)

Question:

I can start Payara v5.192 with JDK11 via command line, but it breaks after trying to start it via IntelliJ with the following error:

-Xbootclasspath/p is no longer a supported option

And I can't even start it via terminal any longer.

This is part of the IntelliJ log:

C:\Program Files\Java\jdk-11.0.3\bin\java.exe
-cp
D:/Program Files/payara-5.192/glassfish/modules/glassfish.jar
-XX:+UnlockDiagnosticVMOptions
-XX:NewRatio=2
-Xbootclasspath/p:D:\Program Files\payara-5.192\glassfish/lib/grizzly-npn-bootstrap-1.8.1.jar
[...]

My project is configured to use JDK 11.0.3, what might the issue be?

EDIT: I'm using IntelliJ 2019.1.3 on Windows, I don't get this issue on Debian

EDIT2: apparently the configuration changes after starting the domain with IntelliJ, here's domain.xml respectively before and after: https://pastebin.com/HAzFgkGn -> https://pastebin.com/F3r3nWet


Answer:

I've encountered the same error myself, on macOS High Sierra. The reason for me was a conflict between the JDK version I'm running asadmin by default (1.8), and what IntelliJ put in the domain.xml (11.0.1).

One workaround, besides updating your domain.xml, is to fix the JDK used by asadmin, e.g. by setting the AS_JAVA parameter in glassfish/config/asenv.conf.

EDIT: Since IntelliJ ships with a bundled JDK 1.8, I believe asadmin is run using that instead of the configured JDK 11 causing the conflict -- asadmin appears to check the JDK it was run with and make some (in this case) wrong assumptions.

EDIT 2: JB SDK is not related. The asadmin command is run using the JDK that's in path, instead of the one configured to the domain. You will get this error if your default (in path) JDK is <9, and your JDK configured to your domain is >=9, as the parameters for bootclasspath of npn are parameterized on the running JDK version.

EDIT 3: Reported and confirmed as a bug: https://github.com/payara/Payara/issues/4025

EDIT 4: The fix is merged to the repository, and is on track for the 5.193 release next month.

Question:

I have 2 amazon ec2 instances. On the first one I have my application running on a Glassfish4 application server, while on the second instance I have mysql installed. I have to connect the to tier. I have configured mysql as a remote server, setting the bind-address=0.0.0.0 in etc/mysql/my.conf and restarting mysql. Then I create a user@ in mysql and granted all the privilegies on the created database to this user.

On the application tier I create the jdbc connection pool using the following glassfish command:

create-jdbc-connection-pool --datasourceclassname com.mysql.jdbc.jdbc2.optional.MysqlDataSource --restype javax.sql.DataSource --property portNumber=3306:password=<PASSWORD>:user=<USER>:serverName=<MYSQL-SERVER-IP>:databaseName=<DATABASE-NAME> <CONNECTION-POOL-NAME>    

Then I deploy my application on Glassfish4.

In my application I use the following method:

public Connection getConnection() {
    Connection c = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        c = (Connection) DriverManager.getConnection(connectionString,username,password);
    } catch (SQLException e) {
        e.printStackTrace();
    }catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return c;
}    

Also my application has a particular feature. I handle some database entities using JPA 2.0 while some others directly using SQL. So I also have a persistence.xml in which I specify the following property:

<property name="javax.persistence.url" value="jdbc:mysql://<MYSQL-SERVER-IP>:3306/<DATABASE-NAME>"/>    

The url in the persistence.xml property is the same connectionString user in the getConnection() method. In the persistence.xml I also specify the username and password to access the database.

My application home shows two button, one to initialize the database with the entities managed by the JPA and another to inizialize the database with the remaining entities using SQL. The first one works successfully and the database tables are created on the remote mysql server. But when I click the second button it throws the CommunicationsException.

I read a lot on the web and also on stackoverflow about this problem and I see there may be multiple causes. In particupar I read the following discussion:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

and tried to fix almost all the possible causes, but anything seems to work.

In my opinion it should be something with the JDBC driver. I also tried to put the mysql JDBC connector in the glassfish4/glassfish/lib folder but doesn't work. Also putting it in the application classpath doesn't work.

Excuse me for my english and if I forgot to specify something in the question. I hope my question is in accordance with the rules of stackoverflow since I have just signed up and this is my first post.

Thanks in advance for your help.


Answer:

Just few tips based on your question:

Then I create a user@ in mysql and granted all the privilegies on the created database to this user.

MySQL authentication mechanism validates the combination of both user+host, so you need to be sure the host you are tryining to connect from is allowed to do so. For example, a very common mistake is to create the user like this:

CREATE USER 'user'@'localhost' IDENTIFIED BY 'password';

If you try to connect to MySQL from other host then you won't succeed. See MySQL - Adding user account for further details.


On the application tier I create the jdbc connection pool [...]

It looks ok, but you should also make this pool available as a JDBC resource with a proper JNDI name (i.e.: jdbc/ConnectionPoolName, so then you can use a DataSource directly in your application by using injection. See Administering JDBC Resources. This is valid if you use both JPA and JDBC.


Also my application has a particular feature. I handle some database entities using JPA 2.0 while some others directly using SQL.

If you use JPA the resource must be set in persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="MyPU" transaction-type="JTA">
    <jta-data-source>jdbc/ConnectionPoolName</jta-data-source>
    <properties />
  </persistence-unit>
</persistence>

If you use plain JDBC API then a DataSource can be injected by using @Resource in a bean like this:

@Stateless
public class MyJdbcBean {

    @Resource(lookup = "jdbc/ConnectionPoolName")
    private DataSource dataSource;

    public Connection getConnection() {
        if (dataSource != null) {
            return dataSource.getConnection();
        } else {
            Exception ex = new ExceptionInInitializerError("Couldn't initialize data source!");
            Logger.getLogger(MyJdbcBean.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
            throw ex;
        }
    }
}

I also tried to put the mysql JDBC connector in the glassfish4/glassfish/lib folder but doesn't work. Also putting it in the application classpath doesn't work.

In my experience JDBC connector must be placed in domain's lib/ext folder, i.e.: glassfish-4.0/glassfish/domains/domain1/lib/ext.

Question:

While coding a servlet I found a method that says

Since:
    Servlet 3.1

I guess that if I have the autohint from NetBeans to use it is because I have that Servlet version. But I cannot find a place to confirm that. I'm using glassfish4.1 as container. If I go to mypathtoglassfish4.1\glassfish\modules there I can see javax.servlet-api.jar and inside a manifest that says:

Implementation-Version: 3.1.0

Is that the proper way to check that? I'm especially interested in being able to tell my colleagues "go to that jar and check that property" so I'm sure that my code will run on their server.

As alternative, I found a webpage Oracle GlassFish Server 3.1 Application Development Guide that says: "GlassFish Server supports the Java Servlet Specification version 3.0." but obviously for Glassfish 3.1, and I couldn't find one of those for every glassfish version (not even for mine -4.1 )


Answer:

Look at Java EE version. Servlet (and JSP, JSF, EJB, JPA, etc) version goes hand in hand with Java EE version.

  • Java EE 8 = Servlet 4.0
  • Java EE 7 = Servlet 3.1
  • Java EE 6 = Servlet 3.0
  • Java EE 5 = Servlet 2.5
  • J2EE 1.4 = Servlet 2.4
  • J2EE 1.3 = Servlet 2.3
  • J2EE 1.2 = Servlet 2.2

Look at the server homepage/documentation how it presents itself. For GlassFish, that is currently (with 4.1):

World's first Java EE 7 Application Server

So, it's Servlet 3.1.

But, with a big but, that's one thing. The second thing is, the webapp's web.xml version also plays a role. Not everyone knows that.

If your webapp's web.xml is declared conform Servlet 3.1 like below,

<?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">

    <!-- Config here. -->
</web-app>

then your webapp will also really run in Servlet 3.1 modus.

However, if it's declared conform Servlet 3.0 like below or even older,

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">

    <!-- Config here. -->
</web-app>

then your webapp will run in Servlet 3.0 compatibility modus, even when deployed to a Servlet 3.1 compatible container! The above influences the ServletContext#getMajorVersion() and getMinorVersion(), so they actually say nothing about the container, but only about the webapp itself.

If your webapp's web.xml contains a <!DOCTYPE>, regardless of the DTD and the version, then it will run in Servlet 2.3 compatibility modus, even when there's a newer XSD declared!

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "java.sun.com/dtd/web-app_2_3.dtd">
<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">

    <!-- This is WRONG! The DOCTYPE must be removed! -->
</web-app>

Question:

I referred to Coreservlets

My question is when i run following program, it starts to download(which shows nothing inside it) rather than displaying as Excel sheet on the browser as what book shows.No Exceptions happened

This is the program,

protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       // processRequest(request, response);
        response.setContentType("application/vnd.ms-excel");
        PrintWriter out= response.getWriter();
        out.println("\tQ1 \tQ2 \tQ3 \tQ4 \tQ5");
        out.println("Apples \t1 \t2 \t3 \t4 \t5");
        out.println("Oranges \t1 \t2 \t3 \t4 \t5");       
    }

I'm using Netbeans IDE with Glassfish 4.1 server which comes with Netbeans itself.Same time i' can't even build PDF's too.Am i missing plugin or something else?


Answer:

The behavior you desire is only possible, if browser is able to open the file inside the browser window. The browser needs MS Excel installed and a plugin to open MS Excel inside the browser window (this is similar to running flash in browser - it does not work until you install the flash plugin). I don't know if such a plugin is available for chrome or firefox, as applications from Microsoft are not behaving friendly to other applications.

If all this is in place, there is a high chance you will get desired behavior. If not, you might need to add a Content-Disposition: inline into the HTTP header in the response, as described here: How to force files to open in browser instead of download (pdf)?

Like this:

response.addHeader("Content-Disposition", "inline; filename='apples_oranges.xls'");

Question:

I have Glassfish server v4.1 with the default port configuration, debug mode suddenly stopped working with the following error message ::

The server exited prematurely with exit code 134.
Before it died, it produced the following output:

FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)
ERROR: transport error 202: connect failed: Connection refused
ERROR: JDWP Transport dt_socket failed to initialize, TRANSPORT_INIT(510)
JDWP exit error AGENT_ERROR_TRANSPORT_INIT(197): No transports initialized [../../../src/share/back/debugInit.c:750]

I listed all the open ports on my machine, but couldn't find the debug port used anywhere. I tried to changed the port but the same error still there.

I used the following commands to list open ports::

sockstat -l | grep 9009 
lsof -l | grep 9009
ss -l | grep 9009

I have java 1.7 (Oracle JDK) installed on OpenSuse tumbleweed.

Appreciate any help.


Answer:

After searching for other clues, seems the problem wasn't in the port but the other debug options in the domain.xml file, specifically the following line

<java-config debug-options="-Xdebug -Xrunjdwp:transport=dt_socket,server=n,suspend=y,address=9009" system-classpath="" classpath-suffix="">

Changed to

<java-config debug-options="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=9009" system-classpath="" classpath-suffix="">

fixed the problem, Thanks to the answer of the following question :: Impossible to run web application in debug mode with intelliJ on ubuntu with glassfish server

Question:

I developed a JavaEE 7.0 Web Application using NetBeans (IDE) and GlassFish 4.1.0 (web server).

The application is working like a charm when I deploy it on the localhost. Now, I would like to deploy it on a Red Hat Enterprise Edition Linux Server 5.11 using GlassFish 4.1.0.

Therefore, I installed GlassFish on my Red Hat server and I followed these steps:

  1. Opened GlassFish administration console and went to the "Applications" node:
  2. Clicked on the "Deploy" button and selected the war file (stored in the Red Hat server) of the application I wanted to deploy:
  3. Clicked on "Choose File". The following window appeared:
  4. My application needs some JAR files in order to work properly. All of them are saved in the following folder:
  5. Then I inserted all the paths in the "Libraries" entry of the GlassFish Administration Console:
  6. Deployed the application and restarted the NetBeans Server

However, each time I run my web application I get the following error:

[2016-07-08T21:20:15.226+0200] [glassfish 4.1] [SEVERE] [NCLS-CORE-00026] [javax.enterprise.system.core] [tid: _ThreadID=22 _ThreadName=RunLevelControllerThread-1468005611695] [timeMillis: 1468005615226] [levelValue: 1000] [[

  Exception during lifecycle processing

java.lang.IllegalArgumentException: Specified library jar android-7.jar does not exist: /opt/glassfish4/glassfish/domains/domain1/lib/android-7.jar

    at org.glassfish.deployment.common.DeploymentContextImpl.getAppLibs(DeploymentContextImpl.java:458)

    at org.glassfish.deployment.common.DeploymentContextImpl.createClassLoader(DeploymentContextImpl.java:244)

    at org.glassfish.deployment.common.DeploymentContextImpl.createDeploymentClassLoader(DeploymentContextImpl.java:229)

    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:365)

    at com.sun.enterprise.v3.server.ApplicationLoaderService.processApplication(ApplicationLoaderService.java:406)

    at com.sun.enterprise.v3.server.ApplicationLoaderService.postConstruct(ApplicationLoaderService.java:243)

    at org.jvnet.hk2.internal.ClazzCreator.postConstructMe(ClazzCreator.java:329)

    at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:377)

    at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:461)

    at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:227)

    at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:84)

    at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2258)

    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:105)

    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:87)

    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:1162)

    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:1147)

    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)

    at java.lang.Thread.run(Thread.java:745)

]]

I really do not understand what is going on, Could you help me please ?


Answer:

Then I inserted all the paths in the "Libraries" entry of the GlassFish Administration Console:

You don't need to do this, I guess this is causing the problem.

Glassfish is searching for libs in the lib folder automatically, if this doesn't work you can also try the server global lib folder in /opt/glassfish4/glassfish/lib

If it still doesn't work there maybe a problem with the access rights, but on your screenshot it looks ok (world-readable).

Question:

I'm currently developing an JavaEE application and I have to implement a feature, were users can define their own SMTP servers as a sender for notification mails. I already have an application which does the same task but in a standard JavaSE application. I did some research and found out, that the application server we are using (Glassfish 3.X) has a configuration menu in the admin panel for mail servers. So my question is: What is the difference between sending an mail from a JavaEE and a normal JavaSE application and if my working sources from the JavaSE application should also work in my enterprise app?

Best regards


Answer:

Consider the definition of javamail sessions in the appserver as a convenience, a feature that helps standardize the configuration of application instances by pulling the configuration of services out of the application, and into the application server.

However, nothing will stop you from using a manually and dynamically defined javamail session in the appserver.

So, where in your SE program you'd configure a mail session, ending in

// typically a set of
properties.put("mail.smtp.port", "25");
// that are used to configure the Session
Session session = Session.getDefaultInstance(properties);

you'll typically find

@Resource(lookup = "sessionAsDefinedInGF")
private Session session;

in an EE application. From that point on both programs can be identical, in the latter the entire intialization and management of the session object will be performed by the appserver.

But as stated above, although the latter is a whole lot more convenient in most situations because the configuration is outside of the application, nothing will hold you back if you do the former, ie the SE style manual configuration of a Session.

Question:

In a clean eclipse environment payara5 will not deploy. I have downloaded the correct version of the server, using java 1.8 and simply added it with new server to start it. I cannot get rid of this error. The payara landing page works, however administrative console timeouts. Any help aprreciated.

    2019-10-23T13:13:32.432+0200|INFORMATION: Running Payara Version: Payara Server  5.193.1 #badassfish (build 275)
2019-10-23T13:13:32.438+0200|INFORMATION: Server log file is using Formatter class: com.sun.enterprise.server.logging.ODLLogFormatter
2019-10-23T13:13:33.015+0200|INFORMATION: Registered fish.payara.ha.hazelcast.store.HazelcastBackingStoreFactoryProxy for persistence-type = hazelcast in BackingStoreFactoryRegistry
2019-10-23T13:13:33.173+0200|INFORMATION: Network Listener http-listener-1 started in: 18ms - bound to [/0.0.0.0:8080]
2019-10-23T13:13:33.202+0200|INFORMATION: Network Listener http-listener-2 started in: 4ms - bound to [/0.0.0.0:8181]
2019-10-23T13:13:33.213+0200|INFORMATION: Network Listener admin-listener started in: 3ms - bound to [/0.0.0.0:4848]
2019-10-23T13:13:33.215+0200|INFORMATION: Grizzly 2.4.3 started in: 352ms - bound to [http-listener-1:8080, http-listener-2:8181, admin-listener:4848]
2019-10-23T13:13:33.305+0200|INFORMATION: Network Listener iiop-service started in: 3ms - bound to [/0.0.0.0:3700]
2019-10-23T13:13:33.404+0200|INFO: HV000001: Hibernate Validator 6.0.16.Final
2019-10-23T13:13:35.437+0200|WARNUNG: [172.30.241.97]:4900 [development] [3.12] Connection[id=3, /172.30.241.97:53016->/172.30.241.97:5900, qualifier=null, endpoint=[172.30.241.97]:5900, alive=false, type=NONE] closed. Reason: Exception in Connection[id=3, /172.30.241.97:53016->/172.30.241.97:5900, qualifier=null, endpoint=[172.30.241.97]:5900, alive=true, type=NONE], thread=hz._hzInstance_1_development.IO.thread-out-1
java.io.IOException: Eine vorhandene Verbindung wurde vom Remotehost geschlossen
    at sun.nio.ch.SocketDispatcher.write0(Native Method)
    at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:51)
    at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93)
    at sun.nio.ch.IOUtil.write(IOUtil.java:65)
    at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:471)
    at com.hazelcast.internal.networking.nio.NioOutboundPipeline.flushToSocket(NioOutboundPipeline.java:273)
    at com.hazelcast.internal.networking.nio.NioOutboundPipeline.process(NioOutboundPipeline.java:207)
    at com.hazelcast.internal.networking.nio.NioPipeline.run(NioPipeline.java:227)
    at com.hazelcast.internal.networking.nio.NioThread.processTaskQueue(NioThread.java:341)
    at com.hazelcast.internal.networking.nio.NioThread.selectLoop(NioThread.java:276)
    at com.hazelcast.internal.networking.nio.NioThread.run(NioThread.java:235)

2019-10-23T13:13:35.437+0200|WARNUNG: [172.30.241.97]:4900 [development] [3.12] Connection[id=1, /10.82.9.38:53013->/10.82.9.38:5900, qualifier=null, endpoint=[10.82.9.38]:5900, alive=false, type=NONE] closed. Reason: Exception in Connection[id=1, /10.82.9.38:53013->/10.82.9.38:5900, qualifier=null, endpoint=[10.82.9.38]:5900, alive=true, type=NONE], thread=hz._hzInstance_1_development.IO.thread-out-2
java.io.IOException: Eine vorhandene Verbindung wurde vom Remotehost geschlossen
    at sun.nio.ch.SocketDispatcher.write0(Native Method)
    at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:51)
    at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93)
    at sun.nio.ch.IOUtil.write(IOUtil.java:65)
    at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:471)
    at com.hazelcast.internal.networking.nio.NioOutboundPipeline.flushToSocket(NioOutboundPipeline.java:273)
    at com.hazelcast.internal.networking.nio.NioOutboundPipeline.process(NioOutboundPipeline.java:207)
    at com.hazelcast.internal.networking.nio.NioPipeline.run(NioPipeline.java:227)
    at com.hazelcast.internal.networking.nio.NioThread.processTaskQueue(NioThread.java:341)
    at com.hazelcast.internal.networking.nio.NioThread.selectLoop(NioThread.java:276)
    at com.hazelcast.internal.networking.nio.NioThread.run(NioThread.java:235)

2019-10-23T13:13:35.437+0200|WARNUNG: [172.30.241.97]:4900 [development] [3.12] Connection[id=4, /10.0.75.1:53015->/10.0.75.1:5900, qualifier=null, endpoint=[10.0.75.1]:5900, alive=false, type=NONE] closed. Reason: Exception in Connection[id=4, /10.0.75.1:53015->/10.0.75.1:5900, qualifier=null, endpoint=[10.0.75.1]:5900, alive=true, type=NONE], thread=hz._hzInstance_1_development.IO.thread-out-0
java.io.IOException: Eine vorhandene Verbindung wurde vom Remotehost geschlossen
    at sun.nio.ch.SocketDispatcher.write0(Native Method)
    at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:51)
    at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93)
    at sun.nio.ch.IOUtil.write(IOUtil.java:65)
    at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:471)
    at com.hazelcast.internal.networking.nio.NioOutboundPipeline.flushToSocket(NioOutboundPipeline.java:273)
    at com.hazelcast.internal.networking.nio.NioOutboundPipeline.process(NioOutboundPipeline.java:207)
    at com.hazelcast.internal.networking.nio.NioPipeline.run(NioPipeline.java:227)
    at com.hazelcast.internal.networking.nio.NioThread.processTaskQueue(NioThread.java:341)
    at com.hazelcast.internal.networking.nio.NioThread.selectLoop(NioThread.java:276)
    at com.hazelcast.internal.networking.nio.NioThread.run(NioThread.java:235)

and

2019-10-23T13:13:39.427+0200|WARNUNG: [172.30.241.97]:4900 [development] [3.12] Connection[id=18, /192.168.56.1:53035->/192.168.56.1:5900, qualifier=null, endpoint=[192.168.56.1]:5900, alive=false, type=NONE] closed. Reason: Exception in Connection[id=18, /192.168.56.1:53035->/192.168.56.1:5900, qualifier=null, endpoint=[192.168.56.1]:5900, alive=true, type=NONE], thread=hz._hzInstance_1_development.IO.thread-in-1
java.lang.IllegalStateException: Unknown protocol: RFB
    at com.hazelcast.nio.tcp.UnifiedProtocolDecoder.onRead(UnifiedProtocolDecoder.java:107)
    at com.hazelcast.internal.networking.nio.NioInboundPipeline.process(NioInboundPipeline.java:135)
    at com.hazelcast.internal.networking.nio.NioThread.processSelectionKey(NioThread.java:369)
    at com.hazelcast.internal.networking.nio.NioThread.processSelectionKeys(NioThread.java:354)
    at com.hazelcast.internal.networking.nio.NioThread.selectLoop(NioThread.java:280)
    at com.hazelcast.internal.networking.nio.NioThread.run(NioThread.java:235)

Answer:

This is a known issue. See here: https://github.com/payara/Payara/issues/3995

Edit: if you don't need Hazelcast you can disable it as follows:

./bin/asadmin set-hazelcast-configuration --enabled=false

(or change the Hazelcast port if you need VNC)

Edit2: for the next version of Payara you will be able to change the Hazelcast port directly on creation of the domain: https://github.com/payara/Payara/pull/4270

Question:

I am using GlassFish 4.1, using REST services within my web.xml (using JAX-RS,) and running queries on my temporary ObjectDB database. I need the input to by checked and return a JSON object with my desired information.

I have tested the entire program off of the server, and it works perfectly. However, while I am hosting it on the local port 8080 and I enter a valid search entry, when it attempts to add to the list, I get an error:

Warning: StandardWrapperValve[DataSearch2]: Servlet.service() for servlet DataSearch2 threw exception
javax.persistence.PersistenceException: No Persistence provider for EntityManager named $objectdb/db/customerDetails.odb
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:85)

If I run the HTML and submit a search that will return 0 results I DO get a blank JSON file back!

But if I run a valid search that would return actual information, I get the "no persistence" error.

This is happening when I have the driver update its own list. I AM sure that I have the correct .jar in the web.inf folder.

Any idea why this would be happening?

I did find a resource outlining a similar problem in No Persistence provider for EntityManager named, but since it is not the same framework, the answers don't really help me.


Answer:

The error message indicates that objectdb-jee.jar is missing.

Question:

I have a Tomcat server and a Glassfish4 server. My Servlet launches perfectly fine with the Tomcat server BUT gives me an "HTTP Status 404" error for the Glassfish4 server. Here is all I have in the Tomcat ROOT directory:

WEB-INF

  • classes (folder)
  • lib (folder)
  • web.xml

Here are the contents for the "web.xml" file...

<web-app>
    <servlet>
        <servlet-name>HelloWorld</servlet-name>
        <servlet-class>HelloWorld</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>HelloWorld</servlet-name>
        <url-pattern>/HelloWorld</url-pattern>
    </servlet-mapping>
</web-app>

This is the output I get using the Tomcat server ( when I run --> localhost:8080/HelloWorld ):

For Glassfish4, I added the "WEB-INF" folder ( which is all I had in the Tomcat server ) into the "C:\glassfish4\glassfish\domains\domain1\docroot" folder ( ROOT equivalent of Tomcat server ) and used the same url ( localhost:8080/HelloWorld ). Which is when I got the 404 error.

I know the Glassfish4 server works because I put an ordinary index.html and it pulled it up just fine. I understand Glassfish4 is more than just a servlet container, maybe I am missing something?

Any answers will be appreciated. Please let me know if you need anything else.

Thanks.


Answer:

For manuall deployment without IDE there are few examples in the official documentation:

Excerpt:

Use the asadmin deploy command. The general form for the command is: as-install/bin/asadmin deploy war-name

To deploy the hello.war sample, the command is: as-install/bin/asadmin deploy sample-dir/hello.war

Question:

I have a working web-application that I built, successfully deployed to Heroku, and is functioning well. However, I'm trying to tune the server/servlet config, and that's when I realized that I don't know what my application is actually doing.

For glassfish, this is the config that's needed.

However, for Jetty, this is the config that's needed.

I realized I have no idea which of the above my application is actually using, so I started digging in my code and found the following:

The main method being called by Heroku is instantiating the following Jetty server/webappcontext.

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;

However, the jetty config seems to rely on a number of files (such as etc/jetty.xml, webapps folder or war files) which my project does not have at all.

In addition, my web.xml file defines the following servlet:

<servlet>
    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

The fact that my application is defining a Jetty server but Glassfish servlet concerned me quite a bit. In an effort to standardize everything around Jetty, I tried adding the jetty servlet to my pom.xml dependencies and changed the above to:

<servlet-class>org.eclipse.jetty.servlet.DefaultServlet</servlet-class>

However, this change caused my application to break. It still compiles successfully and all my jerset-test based integration tests still succeed locally. But when I actually run the server, none of the routes work.

Some questions:

  1. Is it a ill-advised to use a Jetty server along with a Glassfish servlet (container)?

  2. If yes, what servlet (container?) should I replace Glassfish with, and what do I need to do to get the new Jetty servlet working?

  3. If no, what config should I be using for my current setup? Should I be implementing the Glassfish config or the Jersey config?

I've spent many hours trying to read through various documentations, tutorials and stack-overflow threads, but they all either assume prior knowledge about servlets, JavaEE and related topics (none of which I'm familiar with), or they are oriented towards building brand new hello-world apps from scratch (as opposed to porting an existing working app over, which is what I'm trying to do). Any explanations you could give, without assuming prior knowledge, relevant to the context described above, would be much appreciated.


Edit: I think I'm starting to understand now that a Servlet is the code that generates the response for a request, and the ServletContainer is what provides the infrastructure for the Servlet. I've never had to deal with Servlets directly in building my web-app. Here's an example of what a route looks like in my app:

@Path(Ping.REST_PREFIX)
public class Ping {
    static final String REST_PREFIX = "/ping";

    @GET
    public static Response get(@DefaultValue("getPing") @QueryParam("param") String param) {
        return Response.ok().entity(param).build();
    }

    @Path("/pong")
    @GET
    public static Response getPong(@DefaultValue("getPong") @QueryParam("param") String param) {
        return Response.ok().entity(param).build();
    }
}

How can I port code like the above into a Jetty ServletContainer, without rewriting vast sections of my application?


Answer:

You are not using a "Glassfish Servlet Container", you are using a "Jersey Servlet Container".

Jersey is the project you are using.

Glassfish was the umbrella organization (sometimes called "a forge") that helps manage/maintain the Jersey project (along with dozens of other projects).

Difference com.sun.jersey and org.glassfish.jersey

The Jersey project can now be found at the java.net organization.

https://jersey.java.net/

Question:

I just started to learn about java server programing and I was wondering - I know that there is a Java server program code, and I tried it with GlassFish through the GlassFish port, and it worked.

Now- where exactly do I need to insert the client code? I want for example to write a web app that gets a num and double it but if I have a server code that I can access to via url with port, what more do need?

Does the browser is the client in that case? If so, does web application doesn't have Java client code?

Thanks in advance!


Answer:

Yes, in a general sense the browser is the client. If you want this to be accessible on a browser, you will need to add an html and/or javascript document (the actual client code) to communicate with the java server.

Browsers don't generally support Java applets anymore due to security issues, so writing a Java client to be displayed in the browser is not a great way to go about it. Web app clients are written pretty much exclusively in html/javascript, but you could also write a standalone Java application (not in the browser) to communicate with the server using java.net.HttpRequest.

Question:

I'm building a websocket application using glassfish I need in a given event my server to send message to all connected clients. I can send and receive messages from both, but I am not able to use the class server to send messages.

My server class has the following body:

@ApplicationScoped @ServerEndpoint("/actions") public class DeviceWebSocketServer {

@Inject
private DeviceSessionHandler sessionHandler;

@OnOpen
public void open(Session session) {
    sessionHandler.addSession(session);
}

@OnClose
public void close(Session session) {
    sessionHandler.removeSession(session);
}

@OnError
public void onError(Throwable error) {
    Logger.getLogger(DeviceWebSocketServer.class.getName()).log(Level.SEVERE, null, error);
}

@OnMessage
public void handleMessage(String message, Session session) {

    System.out.println("Chegou uma mensagem: " + message);
    System.out.println("Na sessao: " + session.getId());

    try (JsonReader reader = Json.createReader(new StringReader(message))) {
        JsonObject jsonMessage = reader.readObject();

        if ("add".equals(jsonMessage.getString("action"))) {
            Device device = new Device();
            device.setName(jsonMessage.getString("name"));
            device.setDescription(jsonMessage.getString("description"));
            device.setType(jsonMessage.getString("type"));
            device.setStatus("Off");
            sessionHandler.addDevice(device);
        }

        if ("remove".equals(jsonMessage.getString("action"))) {
            int id = (int) jsonMessage.getInt("id");
            sessionHandler.removeDevice(id);
        }

        if ("toggle".equals(jsonMessage.getString("action"))) {
            int id = (int) jsonMessage.getInt("id");
            sessionHandler.toggleDevice(id);
        }
    }

}

How do I send messages to customers after receiving an event? Should I instantiate my class server?


Answer:

Theres a example on howto send messages to all connected clients in this whiteboard app: https://netbeans.org/kb/docs/javaee/maven-websocketapi.html

@ServerEndpoint(value="/whiteboardendpoint", encoders = {FigureEncoder.class}, decoders = {FigureDecoder.class})
public class MyWhiteboard {

    private static Set<Session> peers = Collections.synchronizedSet(new HashSet<Session>());

   @OnMessage
   public void broadcastFigure(Figure figure, Session session) throws IOException, EncodeException {
    System.out.println("broadcastFigure: " + figure);
    for (Session peer : peers) {
        if (!peer.equals(session)) {
            peer.getBasicRemote().sendObject(figure);
        }
    }
}

Question:

I want to use Glassfish Server on AIX machine. I installed the Glassfish Software and I don't want to use System Java Version with Glassfish.

So I installed the java on another location and edited the asenv_bk.conf file to set JAVA_HOME with "AS_JAVA"

after firing command "./asadmin start-domain" I am receiving error

./asadmin: /appltech/glassfish/jdk1.8.0_121/bin/java: 0403-006 Execute permission denied.

Need guidance here.


Answer:

Run the command ls -l /appltech/glassfish/jdk1.8.0_121/bin/java to see the permissions for the java binary.

On my Linux system, I get this:

➜ ~ ls -l /usr/lib/jvm/java-8-oracle/bin/java -rwxr-xr-x 1 root root 7734 Jan 20 08:10 /usr/lib/jvm/java-8-oracle/bin/java

The important bit is the first few letters and dashes (-rwxr-xr-x) and the root root part.

This is telling you the following:

  1. the first dash tells you that the target is a file, not a directory (the first - would be a d if it was a directory)
  2. the next 3 characters are rwx which mean the owner of the file has permissions to read, write (modify) and execute the file
  3. the next 3 characters are r-x, meaning that users in the right group can read and execute, but not write or modify
  4. the last 3 characters are r-x and give the same permissions to the current user as are given to the group.
  5. Finally, the root root part tells you that the owner of the file is root and the group is root.

I expect that the x flag will be missing from your java binary, so to add that for all users you will need to run:

chmod +x /appltech/glassfish/jdk1.8.0_121/bin/java

You will probably need to run the chmod command as a user with elevated permissions (e.g. root)

Question:

Payara server not boot after a power failure. how I can fix and save payaradomain, I have many configurations there. domain1 works well.


Answer:

Check for a domain.xml.bak file in the same directory as the domain.xml. You may be able to overwrite the corrupted domain.xml with the autogenerated backup.

This link describes it more for an older version of GlassFish in the "backup" section:

http://docs.oracle.com/cd/E19798-01/821-1753/abhar/index.html

Question:

I am completely new to java and now I need your help.

The different between JavaSE and JavaEE is clear to me. But why do I need for JavaEE coding an application server. Or lets say, I try to code a websocket server in java and i did it with this tutorial: http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html

But do I need an application server like in this case glassfish???


Answer:

Java EE is the specification, and Glassfish is Oracle's implementation of Java EE. Glassfish can run the byte code that is generated from compiling your source code. You must have some implementation of Java EE in order to actually run the code that you write using Java EE. An alternative server for WebSocket capabilities is Tomcat from Apache.

It's similar to how a JRE is an implementation of Java SE. You must have a JRE in order to run the code that you write using the Java SE specification.

Question:

I tried to run my war application on port 80 instead of 8080. However when I change port number of Glassfish to 80 it cannot start because apache uses that port. My website is working on that port and I want to run my application in a subdomain of my website. What should I do to get rid of 8080 port in URL?


Answer:

Two applications cannot share a TCP port on different subdomains since the concept of a subdomain/domain is specific to DNS and HTTP, not TCP itself. However, you can either keep both Apache and Glassfish on alternate ports (perhaps listening on 127.0.0.1 only) and use nginx or another reverse proxy. Alternatively, you can keep Apache on port 80 and instruct it to reverse-proxy requests on the subdomain to Glassfish, or the other way around.

Question:

My maven project is configured to run on a local glassfish server. When I make any change on a Java class or a JSP file, it get automatically deployed.

However, if I configure the same project to run on a remote server, it does not automatically deploy anything when I hit the save button, I have to manually hit the "Run" button.

Is there anything I'm doing wrong ?

Thanks !


Answer:

No this it the way it is.

Hot-Code replacement works within an IDE because it can control the java process and the class loading. Once on a remote machine the process can no longer be controlled by your IDE.

Depending on the frameworks you are using (Spring, JPA, ...) even hot-code replacement might not have the intended effect as these frameworks need to initialize during startup.

The JDK itself only supports some sort of changes. Often signature changes will not reload or adding static methods.

If you need a better hot-code reloading support you may try JRebel. It a commercial tool but it supports more variations of reloading and also has some framework support.

I've read about companies using it on production servers as well.

Related to maven you only need to notice that if maven deploys the .war or .ear file it's also not under control of your IDE (or with even stronger limitations). It's usually the best way to let the IDE do the work locally.

Question:

I've got an aplication that allows users to download some files. I run it on VMware vFabric tc Server Developer Edition v2.9 (default server in STS) and everything is fine. But now my server is GlassFish, so file name becomes wrong. For example - 30-60 от 19.01.2015.txt

Firefox:30-60_ (with no extension)

Chrome: 30-60_ _19.01.2015.txt

What is wrong? The code:

response.setHeader(
                "Content-disposition",
                "attachment;filename="
                        + BufferUtil.getEncoded(distributionService.get(id)
                                .getTitle(), request) + ".txt");
response.setContentType("text/xml, text/plain");    

BufferUtil.getEncoded:

public static String getEncoded(String text, HttpServletRequest request) {
        String userAgent = request.getHeader("user-agent");
        boolean isInternetExplorer = (userAgent.indexOf("MSIE") > -1);
        text=text.replace(' ', '_');

        try {
            byte[] fileNameBytes = text
                    .getBytes((isInternetExplorer) ? ("windows-1250")
                            : ("utf-8"));
            String dispositionFileName = "";
            for (byte b : fileNameBytes) {
                dispositionFileName += (char) (b & 0xff);
            }
            return dispositionFileName;
        } catch (UnsupportedEncodingException ence) {
            ence.printStackTrace();
            return null;
        }
    }

Answer:

Please try:

java.net.URLEncoder.encode(distributionService.get(id).getTitle() + ".txt", "UTF-8")

instead of

BufferUtil.getEncoded(distributionService.get(id)
                            .getTitle(), request) + ".txt");

Question:

I have created the restful web service with netbeans and glassfish, but when I am trying to hit the rest service my browser shows 404 not found exception.

here is my web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.pps.rest.service</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>TestServlet</servlet-name>
        <servlet-class>com.pps.servlet.TestServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>TestServlet</servlet-name>
        <url-pattern>/TestServlet</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

and here is the rest service:

@Path("/todo")
public class TodoResource {

    // This method is called if XMLis request
    @GET
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public Todo getXML() {
        Todo todo = new Todo();
        todo.setSummary("This is my first todo");
        todo.setDescription("This is my first todo");
        return todo;
    }

    // This can be used to test the integration with the browser
    @Path("/todo1")
    @GET
    @Produces({MediaType.TEXT_XML})
    public Todo getHTML() {
        Todo todo = new Todo();
        todo.setSummary("This is my first todo");
        todo.setDescription("This is my first todo");
        return todo;
    }

    @Path("greet")
    @GET
    public String doGreet() {
        return "Hello Stranger, the time is " + new Date();
    }

}

when I am hitting the url :

http://localhost:8080/pps/rest/todo/greet 

I am getting 404 on glassfish, I have ensured my glassfish is running by hitting the url of the testservlet.


Answer:

Probably your problem is related to the Jersey version that is bundled with GAS 4.

Depends on exact version of your GAS you use some of Jersey 2.x version. As I can assume from your code you are initializing jersey the way it should be done for version 1.x. Take a look at Arun's example here. You can download sources for the example on that page. His example is too basic though and does not even have web.xml file at all(because it is a very basic example and web.xml is now optional). That's why you might also want to take a look at jersey sample applications code. For instance bookstore could be a good example.

In two words you have to extend org.glassfish.jersey.server.ResourceConfig

@ApplicationPath("/")
public class MyApplication extends ResourceConfig {
       public MyApplication() {
          registerClasses(UsersResource.class);
          register(new JettisonFeature());
       }
}

and provide it as javax.ws.rs.Application parameter for Jersey Servlet or Filter based on your choice. It is going to be filter in bookstore example. You will see in the code. There are plenty examples in the maven repo explaining more advanced stuff

    <filter>
        <filter-name>org.glassfish.jersey.examples.bookstore.webapp.MyApplication</filter-name>
        <filter-class>org.glassfish.jersey.servlet.ServletContainer</filter-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>org.glassfish.jersey.examples.bookstore.webapp.MyApplication</param-value>
        </init-param>
        <!-- pass to next filter if Jersey/App returns 404 -->
        <init-param>
            <param-name>jersey.config.servlet.filter.forwardOn404</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>org.glassfish.jersey.examples.bookstore.webapp.MyApplication</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Question:

I would like to build and deploy my war file directly to the domain of appserver. The below snippet is working fine for this,

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${version.maven.war.plugin}</version>
<configuration>
<outputDirectory>
C:\Program Files\glassfish\glassfish5\glassfish\domains\domain1\autodeploy
</outputDirectory>
</configuration>
</plugin>

I don't want to hard code the path. So, I set the system variable GLASSFISH_HOME : C:\Program Files\glassfish and used it in the POM file like this:

<outputDirectory>                    
 ${GLASSFISH_HOME}\glassfish5\glassfish\domains\domain1\autodeploy
</outputDirectory>

but its not working. maven is creating a directory in the current path of the project like below:

[INFO] Building war: C:\Workspaces\Workspace- Restful\moviedirectory\${GLASSFISH_HOME}\glassfish5\glassfish\domains\domain1\autodeploy\moviedirectory.war

any suggestions how to avoid hard coding path but deploy the war to appserver while building it with maven?


Answer:

Have a look at How to refer environment variable in POM.xml?

So the following should do what you want.

<outputDirectory>                    
  ${env.GLASSFISH_HOME}\glassfish5\glassfish\domains\domain1\autodeploy
</outputDirectory>

Question:

I'm using Eclipse Java EE IDE for Web Developers Version: Oxygen.2 Release (4.7.2)

When I want to create new server in Eclipse, first I did download it from Eclipse Marketplace. After rebooting Eclipse, entered link below the servers section to create new server. On the opening window I selected GlassFish and proceeded, then it asked GlassFish Location and Java Location. When I try to paste Java's installation location, C:\Program Files\Java\jdk-9.0.1 it gives me an error about Java Location. It says Java Development Kit (JDK) is required rather than a JRE. I checked my installed Java on windows > preferences > Java > installed JREs but it's alright. I did actually research this on net but couldn't find anything useful.


Answer:

I suppose you are using Glassfish 5. It is not supported by Java 9 so you will need to install JDK8 and point the "Java's installation location" of your server to the JDK 8 path.

Note: Remember that you need the full JDK, not only the JRE to run your server.

Question:

I am creating a desktop application in Java with NetBean and I want to connect with glassfish server. This is my code to get the DataSource:

private DataSource getDataSourceFromJNDI(String jndiDataSourceName) {
    try {
        Properties p = new Properties();
        p.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory");
        p.setProperty(Context.STATE_FACTORIES, "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
        p.setProperty(Context.URL_PKG_PREFIXES, "com.sun.enterprise.naming");
        InitialContext ic = new InitialContext(p);
        return (DataSource) ic.lookup(jndiDataSourceName);
    } catch (NamingException e) {
        log.error("JNDI error while retrieving " + jndiDataSourceName, e);
        throw new AuthorizationException(e);
    }
}

My resource name is: pooljdnibd. In my code I set jdniDataSourceName in different ways like:

java:comp/env/pooljdnibd
java:global/pooljdnibd
java:jdbc/pooljdnibd
jdbc/pooljdnibd
pooljdnibd

and all give me an exception:

javax.naming.NoInitialContextException: Cannot instantiate class: com.sun.enterprise.naming.SerialInitContextFactory [Root exception is java.lang.ClassNotFoundException: com.sun.enterprise.naming.SerialInitContextFactory]

Answer:

It is not possible to access Glassfish resources registered in JNDI outside of the Glassfish server in general (that applies to any other Java EE server).

The only resources in JNDI, which you may access, are EJB components, if they have a remote interface. Another option is to create a service over HTTP protocol (any kind of service, such as SOAP or REST), and connect to it. The technique to connect to each kind of service is of course different.

Once you access an EJB or a service running on the server, you may retrieve data from Datasource registered in JNDI. But you need to retrieve data from the datasource, not the datasource itself. You would do that by issuing query from within the EJB or service running inside Glassfish, and then return result to the desktop application, which called the service.

Question:

Here it is my folder project

I would like to read the file book-form.html which is in the directory web of my project and put it in a String.

This is how I call my function 'getFileContent':

String content = getFileContent("web/book-form.html");

And this is the function:

public String getFileContent(String filePath){
        String line, content = new String();
        try {
                File file = new File(filePath);
                FileReader fr = new FileReader(file);
                BufferedReader br = new BufferedReader(fr);
                while((line = br.readLine()) != null){
                        content += line;
                }
                br.close();
            fr.close();
        } catch(IOException e){
                System.out.println(e.getMessage());
        }

        return content;
    }

My problem is that netbeans tell me that it cannot find my file book-form.html

Any ideas ?


Answer:

File path to resource in our war/WEB-INF folder?

Also you should close stream in a final block or use try-with-resource if you use jdk 7+

Question:

Exception in server.log when I entered start-domain command:

    Shutting down server due to startup exception
java.net.SocketException: Permission denied: listen
    at sun.nio.ch.Net.listen(Native Method)
    at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:200)
    at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
    at org.glassfish.grizzly.nio.transport.TCPNIOBindingHandler.bindToChannelAndAddress(TCPNIOBindingHandler.java:131)
    at org.glassfish.grizzly.nio.transport.TCPNIOBindingHandler.bind(TCPNIOBindingHandler.java:87)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.bind(TCPNIOTransport.java:450)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.bind(TCPNIOTransport.java:439)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.bind(TCPNIOTransport.java:95)
    at org.glassfish.grizzly.config.GenericGrizzlyListener.start(GenericGrizzlyListener.java:168)
    at com.sun.enterprise.v3.services.impl.GlassfishNetworkListener.start(GlassfishNetworkListener.java:94)
    at com.sun.enterprise.v3.services.impl.GrizzlyProxy.start(GrizzlyProxy.java:230)
    at com.sun.enterprise.v3.services.impl.GrizzlyService.createNetworkProxy(GrizzlyService.java:470)
    at com.sun.enterprise.v3.services.impl.GrizzlyService.postConstruct(GrizzlyService.java:393)
    at org.jvnet.hk2.internal.ClazzCreator.postConstructMe(ClazzCreator.java:281)
    at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:328)
    at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:448)
    at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:163)
    at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2204)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:93)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:673)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:660)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$UpOneJob.run(CurrentTaskFuture.java:490)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$UpAllTheWay.go(CurrentTaskFuture.java:362)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$UpAllTheWay.access$100(CurrentTaskFuture.java:279)
    at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture.go(CurrentTaskFuture.java:113)
    at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.proceedTo(AsyncRunLevelContext.java:296)
    at org.glassfish.hk2.runlevel.internal.RunLevelControllerImpl.proceedTo(RunLevelControllerImpl.java:66)
    at com.sun.enterprise.v3.server.AppServerStartup.proceedTo(AppServerStartup.java:532)
    at com.sun.enterprise.v3.server.AppServerStartup.run(AppServerStartup.java:329)
    at com.sun.enterprise.v3.server.AppServerStartup.doStart(AppServerStartup.java:226)
    at com.sun.enterprise.v3.server.AppServerStartup.start(AppServerStartup.java:217)
    at com.sun.enterprise.glassfish.bootstrap.GlassFishImpl.start(GlassFishImpl.java:79)
    at com.sun.enterprise.glassfish.bootstrap.GlassFishDecorator.start(GlassFishDecorator.java:63)
    at com.sun.enterprise.glassfish.bootstrap.osgi.EmbeddedOSGiGlassFishImpl.start(EmbeddedOSGiGlassFishImpl.java:75)
    at com.sun.enterprise.glassfish.bootstrap.GlassFishDecorator.start(GlassFishDecorator.java:63)
    at com.sun.enterprise.glassfish.bootstrap.osgi.OSGiGlassFishImpl.start(OSGiGlassFishImpl.java:71)
    at com.sun.enterprise.glassfish.bootstrap.GlassFishMain$Launcher.launch(GlassFishMain.java:117)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.sun.enterprise.glassfish.bootstrap.GlassFishMain.main(GlassFishMain.java:97)
    at com.sun.enterprise.glassfish.bootstrap.ASMain.main(ASMain.java:54)
]]

Attempted approaches: 1)Added 127.0.0.1 hostname entry in etc/hosts file 2)Changed default port number 4848 to other port numbers in domain.xml 3)Uninstall and reinstall GlassFish

Unfortunately none of the above works.


Answer:

Sometimes it helps to add the following JVM option: -Djava.net.preferIPv4Stack=true

To set it, open your domain.xml and search for the part with <jvm-options>...</jvm-options> inside of <config name="server-config">.

Add a new JVM option like this:

<jvm-options>-Djava.net.preferIPv4Stack=true</jvm-options>

Save the file and try to start the server.

Question:

I have been using Eclipse Indigo and would like to deploy my projects to the new Glassfish 4.1 server downloaded recently.

The Glassfish Tool for Indigo plugin does not allow me to add a Glassfish 4.0 (and plus) server runtime and it only allows a Glassfish Server up to 3.1.

Is there a way to add Glassfish Server 4.1 to Eclipse?


Answer:

Please see this link:https://glassfish.java.net/ide.html

This should answer your question.

Question:

It it possible to package .exe file inside java jar and add this jar to deployment assembly of a project than run this exe by the use of :

Runtime.getRuntime().exec(); I was trying to run this exe after getting it's path inside glassfish domain by the use of class loader but actually this exe is packaged inside the jar which prevent windows from executing it.


Answer:

You will have to extract it from the jar first:

    FileOutputStream fos=null;
    InputStream is = null;
    try
    {

        is = this.getClass().getResourceAsStream("path to your exe inside the jar");
        fos = new FileOutputStream("destination path on host file system");
        byte[] buffer = new byte[1024];
        int read;
        while ((read = is.read(buffer)) > -1)
            fos.write(buffer, 0, read);

    }
    finally
    {

        if (is != null)
            is.close();
        if (fos != null)
            fos.close();
    }

Then, run it on the host file system with Runtime.getRuntime().exec().

Question:

[2019-10-12T11:06:32.875+0300] [glassfish 5.0] [SEVERE] [] [javax.enterprise.system.core] [tid: _ThreadID=45 _ThreadName=admin-listener(4)] [timeMillis: 1570867592875] [levelValue: 1000] [[
  Exception while deploying the app [web_war_exploded]]]

[2019-10-12T11:06:32.876+0300] [glassfish 5.0] [SEVERE] [NCLS-CORE-00026] [javax.enterprise.system.core] [tid: _ThreadID=45 _ThreadName=admin-listener(4)] [timeMillis: 1570867592876] [levelValue: 1000] [[
  Exception during lifecycle processing
java.io.IOException: org.xml.sax.SAXParseExceptionpublicId: file:/home/vladimir/Downloads/glassfish-5.0/glassfish5/glassfish/lib/schemas/web-app_4_0.xsd; lineNumber: 8; columnNumber: 27; Deployment descriptor file WEB-INF/web.xml in archive [web_war_exploded].  TargetNamespace.1: Expecting namespace 'http://java.sun.com/xml/ns/javaee', but the target namespace of the schema document is 'http://xmlns.jcp.org/xml/ns/javaee'.
    at org.glassfish.javaee.core.deployment.DolProvider.processDOL(DolProvider.java:215)
    at org.glassfish.javaee.core.deployment.DolProvider.load(DolProvider.java:231)
    at org.glassfish.javaee.core.deployment.DolProvider.load(DolProvider.java:97)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.loadDeployer(ApplicationLifecycle.java:881)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:396)
    at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.reportSchemaErr(XSDHandler.java:4154)
    at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.reportSchemaError(XSDHandler.java:4137)
    at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.constructTrees(XSDHandler.java:828)
    at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.parseSchema(XSDHandler.java:625)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.loadSchema(XMLSchemaLoader.java:610)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.findSchemaGrammar(XMLSchemaValidator.java:2447)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1768)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:741)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:374)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:613)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3132)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:852)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:602)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:112)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:505)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:842)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:771)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:643)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(SAXParserImpl.java:327)
    at com.sun.enterprise.deployment.io.DeploymentDescriptorFile.read(DeploymentDescriptorFile.java:318)
    ... 51 more
]]

[2019-10-12T11:06:32.903+0300] [glassfish 5.0] [SEVERE] [] [javax.enterprise.system.core] [tid: _ThreadID=45 _ThreadName=admin-listener(4)] [timeMillis: 1570867592903] [levelValue: 1000] [[
  Exception while deploying the app [web_war_exploded] : org.xml.sax.SAXParseExceptionpublicId: file:/home/vladimir/Downloads/glassfish-5.0/glassfish5/glassfish/lib/schemas/web-app_4_0.xsd; lineNumber: 8; columnNumber: 27; Deployment descriptor file WEB-INF/web.xml in archive [web_war_exploded].  TargetNamespace.1: Expecting namespace 'http://java.sun.com/xml/ns/javaee', but the target namespace of the schema document is 'http://xmlns.jcp.org/xml/ns/javaee'.
org.xml.sax.SAXParseExceptionpublicId: file:/home/vladimir/Downloads/glassfish-5.0/glassfish5/glassfish/lib/schemas/web-app_4_0.xsd; lineNumber: 8; columnNumber: 27; Deployment descriptor file WEB-INF/web.xml in archive [web_war_exploded].  TargetNamespace.1: Expecting namespace 'http://java.sun.com/xml/ns/javaee', but the target namespace of the schema document is 'http://xmlns.jcp.org/xml/ns/javaee'.
    at com.sun.enterprise.deployment.io.DeploymentDescriptorFile.read(DeploymentDescriptorFile.java:328)
    at com.sun.enterprise.deployment.io.DeploymentDescriptorFile.read(DeploymentDescriptorFile.java:245)
    at com.sun.enterprise.deployment.archivist.Archivist.readStandardDeploymentDescriptor(Archivist.java:679)
    at com.sun.enterprise.deployment.archivist.Archivist.readDeploymentDescriptors(Archivist.java:391)
    at com.sun.enterprise.deployment.archivist.Archivist.open(Archivist.java:271)
    at com.sun.enterprise.deployment.archivist.Archivist.open(Archivist.java:280)
    at com.sun.enterprise.deployment.archivist.Archivist.open(Archivist.java:241)
    at com.sun.enterprise.deployment.archivist.ApplicationFactory.openArchive(ApplicationFactory.java:161)
    at org.glassfish.javaee.core.deployment.DolProvider.processDOL(DolProvider.java:207)
    at org.glassfish.javaee.core.deployment.DolProvider.load(DolProvider.java:231)
    at org.glassfish.javaee.core.deployment.DolProvider.load(DolProvider.java:97)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.loadDeployer(ApplicationLifecycle.java:881)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:396)
    at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.reportSchemaErr(XSDHandler.java:4154)
    at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.reportSchemaError(XSDHandler.java:4137)
    at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.constructTrees(XSDHandler.java:828)
    at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.parseSchema(XSDHandler.java:625)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.loadSchema(XMLSchemaLoader.java:610)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.findSchemaGrammar(XMLSchemaValidator.java:2447)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1768)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:741)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:374)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:613)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3132)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:852)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:602)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:112)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:505)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:842)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:771)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:643)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(SAXParserImpl.java:327)
    at com.sun.enterprise.deployment.io.DeploymentDescriptorFile.read(DeploymentDescriptorFile.java:318)
    ... 51 more
]]

Answer:

The long error message preceding the stack trace (reformatted for clarity) explains the problem:

java.io.IOException: org.xml.sax.SAXParseException
publicId: 
file:/home/vladimir/Downloads/glassfish-5.0/glassfish5/glassfish/lib/schemas/web-app_4_0.xsd;
lineNumber: 8; columnNumber: 27; 
Deployment descriptor file  in archive [web_war_exploded].  
TargetNamespace.1: 
Expecting namespace
'http://java.sun.com/xml/ns/javaee'
, but the target namespace of the schema document is 
'http://xmlns.jcp.org/xml/ns/javaee'.

So there is a mismatch between the namespace specified in Glassfish's schema definition (web-app_4_0.xsd) and the one you provided in your deployment descriptor (WEB-INF/web.xml) for your application.

This is the top level content of Glassfish's web-app_4_0.xsd:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns="http://www.w3.org/2001/XMLSchema"
            targetNamespace="http://xmlns.jcp.org/xml/ns/javaee"
            xmlns:javaee="http://xmlns.jcp.org/xml/ns/javaee"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            elementFormDefault="qualified"
            attributeFormDefault="unqualified"
            version="4.0">
...

</xsd:schema>

Note that the value specified for targetNamespace and xmlns:javaee is "http://xmlns.jcp.org/xml/ns/javaee" so that is the value you should be specifying in your application's web.xml instead of "http://java.sun.com/xml/ns/javaee". To fix:

  • Stop Glassfish
  • In your application's web.xml replace all occurrences of http://java.sun.com/xml/ns/javaee with http://xmlns.jcp.org/xml/ns/javaee.
  • Clean, build and redeploy your application.
  • Restart your Glassfish server.

I'm guessing that your problem has arisen because you have an existing application that you are migrating to use EE 8. Oracle has a useful article on schema definitions for the different EE versions titled Java EE: XML Schemas for Java EE Deployment Descriptors, and it points out that for EE 8:

All new schemas are in the http://xmlns.jcp.org/xml/ns/javaee/ namespace. Most older schemas remain in the http://java.sun.com/xml/ns/javaee/ namespace.

Question:

I created a restful webservice using netbeans created a entity class from the database and restful web services from entity class using jpa but i used tomcat as my server now the post method below wont insert the following json into the database but when i use glassfish as my server it works. Do you think I am missing any dependencies ? How can I emulate the glassfish?

I am trying to insert

{
"acceptedGender":"both",
"price":123123.00,
"type":"apartment"
"vacantNum":13,
"hadID":4
}

I have the following dependencies: javaee-api-7.0.jar javax.ejb-api.jar mysql-connector-java-5.1.42-bin.jar

 @POST
 @Override
 @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
 public void create(Students entity) {
    super.create(entity);
 }`

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "hatID")
private Integer hatID;
@Basic(optional = false)
@Column(name = "type")
private String type;
@Basic(optional = false)
@Column(name = "acceptedGender")
private String acceptedGender;
@Basic(optional = false)
@Column(name = "vacantNum")
private int vacantNum;
// @Max(value=?)  @Min(value=?)//if you know range of your decimal fields 
consider using these annotations to enforce field validation
@Basic(optional = false)
@Column(name = "price")
private BigDecimal price;
//    @OneToMany(cascade = CascadeType.ALL, mappedBy = "hatID")
//    private Collection<Reservation> reservationCollection;
@JoinColumn(name = "hadID", referencedColumnName = "hadID")
@ManyToOne(optional = false)
private HaDetails hadID;

public HaTypes(Integer hatID, String type, String acceptedGender, int 
vacantNum, BigDecimal price) {
    this.hatID = hatID;
    this.type = type;
    this.acceptedGender = acceptedGender;
    this.vacantNum = vacantNum;
    this.price = price;`

Or if you dont have a solution to my problem could you recommend any provider aside from aws(dont have the time to study the docker), openshift and jelastic that could deploy a glassfish restful webservice on cloud easily.


Answer:

Glassfish is an application server, therefore it supports JAX-RS out of the box. Tomcat is just a web container and you cannot deploy a JAX-RS app and have it work without wiring it by yourself (see this: In which container do JAX-RS web services run?).

If you want to run a Jersey server inside tomcat, you will need to configure it in your application's deployment descriptor. You can see answers on the following posts if you need details:

  • How to use Jersey as JAX-RS implementation without web.xml?

  • Create RESTful Web Service with JAX-RS and deploy it to tomcat

Question:

I'm using Glassfish 4.1 to deploy a RESTful webapp using jersey 2.23.2.

What I'm trying to do is run a method at the server's startup

my web.xml

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
    <display-name>XYZ</display-name>
    <servlet>
      <servlet-name>MyApplication</servlet-name>
      <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
      <init-param>
          <param-name>javax.ws.rs.Application</param-name>
          <param-value>MyApplication</param-value>
      </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyApplication</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app> 

and MyApplication.java

import javax.annotation.PostConstruct;
import org.glassfish.jersey.server.ResourceConfig;

public class MyApplication extends ResourceConfig {
    public MyApplication() {
        packages("services");
    }

    @PostConstruct
    public void post_construct () {
        //The method I want to run
    }
}

Answer:

I guess your solution is not working because your class is not managed by the container and therefore the @PostConstruct doesn't get evaluated.

You can try the following:

import javax.annotation.PostConstruct;
import org.glassfish.jersey.server.ResourceConfig;

public class MyApplication extends ResourceConfig {
    public MyApplication() {
        packages("services");
        post_construct();   // <-- here is the call
    }

    @PostConstruct
    public void post_construct () {
        //The method I want to run
    }
}

If this isn't working here is a "real" solution:

@Singleton
@Startup
public class InitializerBean {

   @PostConstruct
   public void onStartup() {
        // do your method-call here
   }

}

See also:

Question:

I have a question. I have 2 servers which have connection to each other and have an applications to send and recieve messeges into JMS queue. But despite everything written here client for remote JMS queue I can't send message from one server to another, it is either goes back to same server or not being displayed anywhere. Here is the code which I use to send message, any ideas what I'm doing wrong?:

com.sun.messaging.ConnectionFactory connFactory = new com.sun.messaging.ConnectionFactory();
connFactory.setProperty(ConnectionConfiguration.imqAddressList, "10.241.5.51:7676");
com.sun.messaging.Queue     queue = new com.sun.messaging.Queue("jms/tQueue");//(com.sun.messaging.Queue)client.lookup("jms/tQueue");
try (Connection connection = connFactory.createConnection();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer producer = session.createProducer(queue)) {
      for (int i = 0; i < 5; i++) {
      TextMessage message = session.createTextMessage("It is a message from main class " + ": " + i);
      System.out.println("It come from main class:" + message.getText());
      producer.send(message);
       }
     }

Answer:

turns out I got lost in terminology or something. That code was working, only the other server should've been sending messages.

Question:

Here's what I've done so far:

  1. Did a fresh build of project (web service project).
  2. Redeployed project war file to Glassfish server.
  3. Restarted server with --debug=true.
  4. Attached debugger from Netbeans.

Debugger attaches to the server without an error (responds "User Program Running"), however the Debug tab (in the Projects/Files/Services window) with all the different services that are supposed to get attached fails to show up as it did when everything was working.

When I try to start debugging the project, the server dropdown doesn't have any servers in it, and it won't let me start debugging without selecting a server.

Glassfish version is 2.1.1. Netbeans version is 7.4 Patch 3. JRE version is 1.7.0_79-b15.

I'm a bit of a Netbeans newbie, so I apologize if I've left out any information that's important. Can someone see what I'm doing wrong?


Answer:

Check if the netbeans,jdk and glassfish server are installed in the same folder Program Files(x86) or Program Files.If not then re-install them. I use netbeans 7.0.1 ,glassfish 3.1.1 and jdk 1.7 and it runs fine.

If your problem is something else if I am not clear with your question, look at this https://netbeans.org/bugzilla/show_bug.cgi?id=195166

Question:

I am getting an error while executing a glassfish server with use of MongoDB:

java.lang.NoClassDefFoundError: com/mongodb/client/MongoCollection

I have the following dependencies :

<dependencies>
<!-- 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</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-json-jackson -->
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.26</version>
</dependency>

    <!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-client -->
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-client</artifactId>
        <version>1.19.4</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.mongodb/mongodb-driver -->
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongodb-driver</artifactId>
        <version>3.6.1</version>
    </dependency>







</dependencies>

The specific jars are definitly imported, and while compilation there is also occurring no error. I have looked up for solutions here already but none of them helped me. So if anyone might see the error, pleaser tell me. Thanks in advance.


Answer:

It looks like you should use this dependency:

<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.6.1</version>
</dependency>

If this doesn't work alternatively you can put the mongodb-driver JAR into /glassfish/glassfish4/lib/.

Question:


Answer:

Take a look at the Spring Webserver example here for an example of a Spring Boot webserver that interacts with a Corda node. The design will be similar for a GlassFish webserver.

Communicating with the node:

The key file is https://github.com/corda/samples/blob/release-V3/spring-webserver/src/main/kotlin/net/corda/server/NodeRPCConnection.kt. Here, we create a long-lived CordaRPCClient instance. The webserver's controllers use this client to send messages to and from the node, as shown here: https://github.com/corda/samples/blob/release-V3/spring-webserver/src/main/kotlin/net/corda/server/controllers/StandardController.kt.

Dependencies:

The webserver requires dependencies on Corda itself (for the core classes and the RPC client classes). See https://github.com/corda/samples/blob/release-V3/spring-webserver/build.gradle#L47. The webserver will also require dependencies on any CorDapps that contain classes that will be used by the controllers. For example, if you have a controller with an endpoint that extracts IOUStates from the vault, then the IOUCorDapp will be a dependency of your webserver.