Hot questions for Using GlassFish in mysql

Question:

Can anyone tell me how to kill a Glassfish instance using the port 4848 and 8080.

I installed Glassfish, and found that the Glassfish installation isn't working properly, so deleted all the Glassfish files from my ubuntu machine with stopping the Glassfish server (./asadmin stop-domain).

Now I downloaded other Glassfish version (nightly build 5.0, because JDBC MySQL doesn't work) and tried to start the server (./asadmin start-domain). I get the following error.

There is a process already using the admin port 4848 -- it probably is another instance of a GlassFish server.


Answer:

Can anyone tell me how to kill a Glassfish instance using the port 4848 and 8080.

There is probably running only one instance of Glassfish on this ports, but you can kill it like this:

pkill -f glassfish

If you don't have a root shell you might have to use sudo in front of the cmd.

Question:

I'm trying to create JDBC Connection Pool and JDBC Resource using glassfish-resources.xml with code below. I've tried to do it with Glassfish 4.0, 4.1, 4.1.1 and Payara. I know there was a problem with 4.1.1, but it doesnt create to any of them. I've been trying to solve this problem for several hours, but without a success. PLZ HELP.

<resources>
  <jdbc-resource enabled="true"
                 jndi-name="jdbc/affablebean"
                 object-type="user"
                 pool-name="AffableBeanPool">
  </jdbc-resource>

  <jdbc-connection-pool allow-non-component-callers="false"
                        associate-with-thread="false"
                        connection-creation-retry-attempts="0"
                        connection-creation-retry-interval-in-seconds="10"
                        connection-leak-reclaim="false"
                        connection-leak-timeout-in-seconds="0"
                        connection-validation-method="auto-commit"
                        datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource"
                        fail-all-connections="false"
                        idle-timeout-in-seconds="300"
                        is-connection-validation-required="false"
                        is-isolation-level-guaranteed="true"
                        lazy-connection-association="false"
                        lazy-connection-enlistment="false"
                        match-connections="false"
                        max-connection-usage-count="0"
                        max-pool-size="32"
                        max-wait-time-in-millis="60000"
                        name="AffableBeanPool"
                        non-transactional-connections="false"
                        pool-resize-quantity="2"
                        res-type="javax.sql.ConnectionPoolDataSource"
                        statement-timeout-in-seconds="-1"
                        steady-pool-size="8"
                        validate-atmost-once-period-in-seconds="0"
                        wrap-jdbc-objects="false">

    <description>Connects to the affablebean database</description>
    <property name="URL" value="jdbc:mysql://localhost:3306/affablebean"/>
    <property name="User" value="root"/>
    <property name="Password" value="nbuser"/>
  </jdbc-connection-pool>
</resources>

Answer:

Ok, problem solved... the newest NetBeans 8.1 creates glassfish-resources.xml in the wrong folder. If you have the same problem, just move your glassfish-resources.xml from Configuration Files to Server Resources...

Question:

I spent a good part of my evening setting up a Glassfish 5.0.1 server configuring a JDBC Connection Pool and deploying an application. The issue I keep running into: Unable to Connect to JDBC Connection Pool from Glassfish and GlassFish connection pool

In Glassfish for MySQL everywhere states to use the Resource Type: javax.sql.DataSource and Datasource Classname: com.mysql.jdbc.jdbc2.optional.MysqlDataSource

The above never worked no matter where I put the MySQL Connector jar glassfish/lib or domain/domain1/bin/lib. All times I deleted the pool I had, cleared the cache and restarted the servers.

I ended up switching to java.sql.Driver and Driver Classname: com.mysql.jdbc.Driver

Question are how do I make the Datasource work?

Also, what is the difference between Driver and Datasource?

Edit

Same issue with Payara-5. I am putting the jar in lib/ext but the Driver failed in the same way and was resolved with it there.

Ping Connection Pool failed for MySQLConnPool2. Class name is wrong or classpath is not set for : com.mysql.jdbc.jdbc2.optional.MysqlDataSource Please check the server.log for more details.


Answer:

In the 5.0 to 8.0 release notes there is a reference to a change in the package name from com.mysql.jdbc to com.mysql.cj. Looking at mysql-connector-java-8.0.12.jar, there appears to be an undocumented change in the package for the data source to com.mysql.cj.jdbc.MysqlDataSource.

I have tested using com.mysql.cj.jdbc.MysqlDataSource in Payara 5 from the admin console, and it works :-)

Question:

I have a preparedStatement for select query in mySQL.

this is what I wrote:

 String sQuery = "SELECT Password FROM test WHERE Email = ?";
 st = DB.prepareStatement(sQuery);
 st.setString(1, email);
 ResultSet rs =  st.executeQuery(sQuery);

but i'm getting an exception from the glassfish server that says:

Severe:   com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 
You have an error in your SQL syntax; check the manual that corresponds 
to your MySQL server version for the right syntax to use near '?' at line 1

I don't understand what is the problem.. all the samples i saw, use that syntax..


Answer:

You must call st.executeQuery(), without the query as argument. The query has already been passed to the statement when it was prepared.

See http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#executeQuery%28%29

Question:

If i try to get the timeStamps (Date object) from my mySql database via Java (jdbc) i get the error: "Parameter index out of range (2 > number of parameters, which is 1)."

I canĀ“t find a solution on the internet that works for me, because (i think) the sql-query is correct and i placed the exact number of '?' needed.

PreparedStatement st = conn.prepareStatement("SELECT * FROM timestamp WHERE stampTime BETWEEN '?/0/? 00:00:00.00' AND '?/31/? 23:59:59.999' AND userid = ? ");
            st.setInt(1, month);
            st.setInt(2, year); //It crashes here
            st.setInt(3, month);
            st.setInt(4, year);
            st.setInt(5, uId);
            ResultSet rs = st.executeQuery();

I expect the statement to be prepared and executed but i am reciving the error "Parameter index out of range (2 > number of parameters, which is 1)."


Answer:

Question marks ? are not interpreted as parameter designators when they are part of a string literal. That is why question marks inside '?/0/? 00:00:00.00' and '?/31/? 23:59:59.999' are not counted as parameters of the prepared statement; only the ? inside userid = ? is counted, because it is the only one "in the open".

You can fix this problem by constructing the end dates of the range in your Java program, and binding them to parameters inside stampTime BETWEEN ? AND ? condition.

Question:

Problem:

Error when running java ee projet:

Severe: Exception while deploying the app [K2Fitness-war] : javax.resource.ResourceException: javax.resource.ResourceException: Attribute value (pool-name = java:app/k2fitness) is not found in list of jdbc connection pools.

glassfish-ressources.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
    <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="mysql_k2fitness_rootPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
        <property name="serverName" value="localhost"/>
        <property name="portNumber" value="3306"/>
        <property name="databaseName" value="k2fitness"/>
        <property name="User" value="root"/>
        <property name="Password" value="root"/>
        <property name="URL" value="jdbc:mysql://localhost:3306/k2fitness?zeroDateTimeBehavior=convertToNull"/>
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    </jdbc-connection-pool>
    <jdbc-resource enabled="true" jndi-name="java:apps/jdbc:mysql://localhost:3306/k2fitness" object-type="user" pool-name="k2fitness"/>
</resources>

On the glassfish admin panel I have the following:

JDBC RESOURCES
  -> jdbc/k2fitness (JNDI-NAME | Connected to k2fitness pool )

JDBC CONNECTION POOLS
  -> k2fitness (POOL NAME | Ping successful )

k2fitness url: jdbc:mysql://localhost:3306/k2fitness

Question:

Why is it unable to find the pool name "k2fitness" in the list of connection pools when it clearly exists. Any clarity on this would be helpful.

Additional Information:

I've attempted to change the jndi-name (unsure if it's related to the pool-name issue) without success:

  • java:app/jdbc/k2fitness
  • jdbc/k2fitness

Answer:

The name of the pool is mysql_k2fitness_rootPool, see the name attribute of the jdbc-connection-pool element.

Question:

I know this has been asked many times before, but none of the solutions worked for me.

I'm using GlassFish, try to get database from connection Pool. When trying to run, although the output is Artifact is deployed successfully, but in browser return the error page, and error logs shows:

[WARNING] [] [javax.enterprise.web.util] [tid: _ThreadID=18 _ThreadName=RunLevelControllerThread-1473348595597] [timeMillis: 1473348603791] [levelValue: 900] [[ The web application [unknown] registered the JDBC driver [com.mysql.cj.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.]] [/pre]

Yes, I already put JDBC driver jar into glassfish-installation-folder/glassfish/lib/ Still that error. Even put to glassfish-installation-folder/glasshfish/domains/domain-name/lib/. And the are no JDBC driver in web app/lib

Here are some of my settings:

jdbc-connection-pool:

datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource" name="mysql_cinema_pool" res-type="javax.sql.ConnectionPoolDataSource"

1 example of my entities (including the error): https://s9.postimg.org/wrsrysz27/Intelli_J_IDEA_Error.png

I'm struggling with this error all day :(.


Answer:

The GlassFish warning means that your application registered teh JDBC driver, but did not unregister it during undeployment. When you redeploy your application, the old version gets undeployed and the above warning is raised. It should not affect the newly deployed application.

It you undeploy all applications, restart the server and deploy your application, you should not see the warning.

Question:

So Im trying to run a Java EE project that was developed a couple years ago and Im getting this error:

Connection could not be allocated because: Identifier name 'c:\glassfish-3.0\glassfish\domains\domain1/lib/databases/ejbtimer' is too long

Trying to run it on JDK7 and GlassFish 3

Tried searching for anything similar but to no avail

Any suggestions as to what is the cause/how to solve it?

EDIT: stack trace (ext. link to not make post too long) http://pastebin.com/RzJS60aX


Answer:

It seems the documentation for the project had an error and the pool in GlassFish was set to the wrong Datasource Classname

Question:

I am trying to create a MysqlDataSource object to connect to my database. I need to do this so I can use the setRewriteBatchedStatements(boolean) method.

MysqlDataSource mysql mysql = (MysqlDataSource) context.lookup("jdbc/MySQLDataSource");

It throws the following exception:

2015-07-15T14:25:46.078+0100|Severe: java.lang.ClassCastException: com.sun.gjc.spi.jdbc40.DataSource40 cannot be cast to com.mysql.jdbc.jdbc2.optional.MysqlDataSource
at com.pododdle.dao.MySQL.mysql_conn(MySQL.java:30)
at com.pododdle.dao.MySQL.getMySQLConnection(MySQL.java:48)
at com.pododdle.dao.PodcastService.getPodcasts(PodcastService.java:112)
at com.pododdle.resources.FeedResource.getNewEpisodes(FeedResource.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)

Previously I was using a DataSource object, and everything worked superbly, but I need to set the above property and the DataSource object doesn't do this. The previous code read:

mysql = (DataSource) context.lookup("jdbc/MySQLDataSource");

I am running the code on the Glassfish 4 webserver, and connecting to a MySQL5.6 datbase.


Answer:

This classcastexception was avoided by doing the following steps:

DataSource datasource = (DataSource) context.lookup("jdbc/MySQLDataSource");
MysqlDataSource mysql_datasource = datasource.unwrap(MysqlDataSource.class);

You can now set the rewriteBatchedStatements to true with no problems!

mysql_datasource.setRewriteBatchedStatements(true);
Connection conn = mysql.getConnection();

Question:


Answer:

A user in MySQL is identified by a username AND a host.

To allow a connection, we need to create a user in MySQL that has a matching username and host. To create a user that is an exact match:

 GRANT USAGE ON *.* TO 'user'@'127.0.0.1' IDENTIFIED BY 'supersecretpassword' ;
 GRANT SELECT, INSERT, UPDATE, DELETE ON somedatabase.* TO 'user'@'127.0.0.1' ;

To replicate the privileges of an existing user, we could make use of a SHOW GRANTS statement to extract privileges for some other user

 SHOW GRANTS FOR 'user'@'localhost'

We can copy the output from that, and use that as a basis for GRANT statements for the new user, replacing 'localhost' with '127.0.0.1'.

As another option, it's also possible to create a user with a '%' wildcard for a hostname, rather than '127.0.0.1'. That would allow connections from any IP address.


If the user exists, then the password could be wrong. Verify that the password the pool configuration is using matches what is stored in the mysql.user table.

SELECT password FROM mysql.user WHERE user = 'user' and host = '127.0.0.1';

SELECT PASSWORD('supersecretpassword') ;

And compare the hash values.

The error message that is being returned looks like it is from MySQL server:

Access denied for user 'user'@'127.0.0.1' (using password: YES)

That makes is appear that a successful TCP handshake through port 3306 has happened, and MySQL Server is attempting to authenticate: user='user', host='127.0.0.1', and password=PASSWORD('XXX').

Either the user doesn't exist in the mysql.user table, the password is incorrect, or (possibly) the user doesn't have privileges on database='db'.

(If DML changes were applied to the privileges table in the mysql database, issue a FLUSH PRIVILEGES to make those changes effective. (FLUSH PRIVILEGES isn't required if changes are applied using GRANT and REVOKE syntax, only required if changes are applied using INSERT, UPDATE, DELETE.)

Question:

I want to start a JavaEE project, I've read about where to start with JavaEE and most of them were directed to Glassfish. I installed it, and was able to get to the localhost, however I don't know where to go next. Is there a complete guide or tutorial on how to use Glassfish? Also if I can use MySQL with Glassfish for the JavaEE project.


Answer:

Of course, you can use MySQL. You can find a complete guide for setting up a connection with MySQL for Glassfish here.

An IDE like Netbeans is probably the easiest way to get started with JavaEE. You only need to add your freshly installed Glassfish server to Servers (under Services tab), then you can start working on your project.

However, it may be advisable not to use IDE at the beginning, since it hides from you some essential operations. Therefore, you'd better start by making your first 'test' project manually (I mean building and deploying). There are several books for beginners to JavaEE platform and they usually start with a decent introduction on how to accomplish that. For example this one covers the topic in details: Beginning Database-Driven Application Development in Java EE by Yuli Vasiliev.

Question:

SQL query in question:

SELECT COUNT(suggestedfood.id) AS num_same, suggestedfood.place_id FROM suggestedfood WHERE suggestedfood.group_id=? AND suggestedfood.selected=? AND suggestedfood.removed=? GROUP BY suggestedfood.place_id LIMIT 1

This query is able to run within MySQL Workbench, but in production it throws this error :

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? AND suggestedfood.selected=? AND suggestedfood.removed=? GROUP BY suggestedfoo' at line 1

MySQL Error code: 1064

MySQL State: 42000

The MySQL server is on AWS RDS, if that helps, and my code running the SQL query is a Java container on Glassfish. Also many other queries are able to run, it's just this one that is giving me troubles.

If anyone can point out a simple mistake of mine that would be great. Or if anyone knows how I can better diagnose this problem, that would be much appreciated.

Edit, here is my Java code, as asked for group_id is a long

 long numSame = 0L;
 String count = "SELECT COUNT(" + SUGGESTEDFOOD_ID + ") AS num_same, " 
     + SUGGESTEDFOOD_PLACEID + " FROM " + SUGGESTEDFOOD
     + " WHERE " + SUGGESTEDFOOD_GROUP_ID + "=? AND "
     + SUGGESTEDFOOD_SELECTED + "=? AND "
     + SUGGESTEDFOOD_REMOVED + "=? "
     + "GROUP BY "
     + SUGGESTEDFOOD_PLACEID  + " LIMIT 1";
 PreparedStatement ps = conn.connection.prepareStatement(count);
 ps.setLong(1, group_id);
 ps.setBoolean(2, true);
 ps.setBoolean(3, false);
 /* Line 607 */ ResultSet rs = ps.executeQuery(count);
 while (rs.next()) {
     numSame = rs.getLong("num_same");
 }

Here is the full stack trace:

 com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? AND suggestedfood.selected=? AND suggestedfood.Removed=? GROUP BY suggestedfoo' at line 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3277)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3206)
at com.mysql.jdbc.Statement.executeQuery(Statement.java:1232)
at com.cow10.endpoints.FoodSessionHandler.togglePlace(FoodSessionHandler.java:607)
at com.cow10.endpoints.FoodSessionHandler$Proxy$_$$_WeldClientProxy.togglePlace(Unknown Source)
at com.cow10.endpoints.FoodWebSocket.handleMessage(FoodWebSocket.java:91)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.glassfish.tyrus.core.AnnotatedEndpoint.callMethod(AnnotatedEndpoint.java:477)
at org.glassfish.tyrus.core.AnnotatedEndpoint.access$100(AnnotatedEndpoint.java:87)
at org.glassfish.tyrus.core.AnnotatedEndpoint$WholeHandler$1.onMessage(AnnotatedEndpoint.java:573)
at org.glassfish.tyrus.core.TyrusSession.notifyMessageHandlers(TyrusSession.java:542)
at org.glassfish.tyrus.core.TyrusEndpointWrapper.onMessage(TyrusEndpointWrapper.java:748)
at org.glassfish.tyrus.core.TyrusWebSocket.onMessage(TyrusWebSocket.java:200)
at org.glassfish.tyrus.core.frame.TextFrame.respond(TextFrame.java:135)
at org.glassfish.tyrus.core.ProtocolHandler.process(ProtocolHandler.java:622)
at org.glassfish.tyrus.core.TyrusWebSocketEngine$TyrusReadHandler.handle(TyrusWebSocketEngine.java:394)
at org.glassfish.tyrus.servlet.TyrusHttpUpgradeHandler.onDataAvailable(TyrusHttpUpgradeHandler.java:164)
at org.apache.catalina.connector.InputBuffer$ReadHandlerImpl.processDataAvailable(InputBuffer.java:488)
at org.apache.catalina.connector.InputBuffer$ReadHandlerImpl.onDataAvailable(InputBuffer.java:453)
at org.glassfish.grizzly.http.io.InputBuffer.invokeHandler(InputBuffer.java:1101)
at org.glassfish.grizzly.http.io.InputBuffer.invokeHandlerOnProperThread(InputBuffer.java:1092)
at org.glassfish.grizzly.http.io.InputBuffer.append(InputBuffer.java:975)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:271)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:748)]]

Answer:

A typical mistake.

ResultSet rs = ps.executeQuery(count);

should be

ResultSet rs = ps.executeQuery();

as ps is a PreparedStatement extending Statement, and executeQuery(String) is an unusable Statement method.

Should one ever create a similar API, override executeQuery(String) and make it @Deprecated with a nice javadoc.