How do I get Keycloak to connect to MySQL DB? - mysql

I've been crawling a number of sites like this trying to get Keycloak working with a MySQL persistence layer. I am using docker, but I'm using my own images so it pulls passwords and other sensitive data from a secrets manager instead of environment variables or Docker secrets. The images are pretty close to stock besides that however.
Anyway, I have a MySQL 8 container up and running, and from within the Keycloak 12.0.3 container I can connect to the MySQL container fine:
# mysql -h mysql -u keycloak --password=somethingtochangelater -D keycloak -e "SHOW DATABASES;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database |
+--------------------+
| information_schema |
| keycloak |
+--------------------+
So there's no problems of connectivity between the instances, and that username/password has access to the keycloak database fine.
So then I ran several commands to configure the Keycloak instance (keycloak is installed at /opt/myco/bin/keycloak):
/opt/myco/bin/keycloak/bin/standalone.sh &
# Pausing for server startup
sleep 20
# Add mysql module - JDBC driver unpacked at /opt/myco/bin/keycloak-install/mysql-connector-java-8.0.23/mysql-connector-java-8.0.23.jar
/opt/myco/bin/keycloak/bin/jboss-cli.sh --connect --command="module add --name=com.mysql --dependencies=javax.api,javax.transaction.api --resources=/opt/myco/bin/keycloak-install/mysql-connector-java-8.0.23/mysql-connector-java-8.0.23.jar --module-root-dir=/opt/myco/bin/keycloak/modules/system/layers/keycloak/"
# Removing h2 datasource
/opt/myco/bin/keycloak/bin/jboss-cli.sh --connect --command="/subsystem=datasources/data-source=KeycloakDS:remove"
# Adding MySQL datasource
/opt/myco/bin/keycloak/bin/jboss-cli.sh --connect --command="/subsystem=datasources/jdbc-driver=mysql:add(driver-name=mysql,driver-module-name=com.mysql,driver-class-name=com.mysql.cj.jdbc.Driver)"
# TODO - add connection pooling options here...
# Configuring data source
/opt/myco/bin/keycloak/bin/jboss-cli.sh --connect --command="data-source add --name=KeycloakDS --jndi-name=java:jboss/datasources/KeycloakDS --enabled=true --password=somethingtochangelater --user-name=keycloak --driver-name=com.mysql --use-java-context=true --connection-url=jdbc:mysql://mysql:3306/keycloak?useSSL=false&characterEncoding=UTF-8"
# Testing connection
/opt/myco/bin/keycloak/bin/jboss-cli.sh --connect --command="/subsystem=datasources/data-source=KeycloakDS:test-connection-in-pool"
# Creating admin user
/opt/myco/bin/keycloak/bin/add-user-keycloak.sh -r master -u "admin" -p "somethingelse"
# Shutting down initial server
/opt/myco/bin/keycloak/bin/jboss-cli.sh --connect command=":shutdown"
This all appears to run fine. Note especially the test-connection-in-pool has no problems:
{
"outcome" => "success",
"result" => [true],
"response-headers" => {"process-state" => "reload-required"}
}
However, when I go to start the server back up again, it crashes with several exceptions, starting with:
22:31:52,484 FATAL [org.keycloak.services] (ServerService Thread Pool -- 56) Error during startup: java.lang.RuntimeException: Failed to connect to database
at org.keycloak.keycloak-model-jpa#12.0.3//org.keycloak.connections.jpa.DefaultJpaConnectionProviderFactory.getConnection(DefaultJpaConnectionProviderFactory.java:377)
at org.keycloak.keycloak-model-jpa#12.0.3//org.keycloak.connections.jpa.updater.liquibase.lock.LiquibaseDBLockProvider.lazyInit(LiquibaseDBLockProvider.java:65)
...
it keeps going, though I suspect that Exception ultimately to be fatal, and it eventually dies with:
22:31:53,114 ERROR [org.jboss.as.controller.management-operation] (ServerService Thread Pool -- 40) WFLYCTL0190: Step handler org.jboss.as.controller.AbstractAddStepHandler$1#33063168 for operation add at address [
("subsystem" => "jca"),
("workmanager" => "default"),
("short-running-threads" => "default")
] failed -- java.util.concurrent.RejectedExecutionException: java.util.concurrent.RejectedExecutionException
at org.jboss.threads#2.4.0.Final//org.jboss.threads.RejectingExecutor.execute(RejectingExecutor.java:37)
at org.jboss.threads#2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor.rejectShutdown(EnhancedQueueExecutor.java:2029)
...
The module at /opt/myco/bin/keycloak/modules/system/layers/keycloak/com/mysql/main has the jar file and module.xml:
# ls
module.xml mysql-connector-java-8.0.23.jar
# cat module.xml
<?xml version='1.0' encoding='UTF-8'?>
<module xmlns="urn:jboss:module:1.1" name="com.mysql">
<resources>
<resource-root path="mysql-connector-java-8.0.23.jar"/>
</resources>
<dependencies>
<module name="javax.api"/>
<module name="javax.transaction.api"/>
</dependencies>
The standalone.xml file looks reasonable to me:
...
<subsystem xmlns="urn:jboss:domain:datasources:6.0">
<datasources>
...
<datasource jndi-name="java:jboss/datasources/KeycloakDS" pool-name="KeycloakDS" enabled="true" use-java-context="true">
<connection-url>jdbc:mysql://mysql:3306/keycloak?useSSL=false&characterEncoding=UTF-8</connection-url>
<driver>com.mysql</driver>
<security>
<user-name>keycloak</user-name>
<password>somethingtochangelater</password>
</security>
</datasource>
<drivers>
<driver name="h2" module="com.h2database.h2">
<xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
</driver>
<driver name="mysql" module="com.mysql">
<driver-class>com.mysql.cj.jdbc.Driver</driver-class>
</driver>
</drivers>
</datasources>
...
So.... anyone have any idea what's going on? What else do I need to do to get Keycloak talking properly to MySQL? Anything else I can do to debug what the issue is?

Not sure what is wrong with your particular case, but I used jboss/ keycloak image and it connects to MySQL just fine. Maybe you can derive your custom image from there. The full setup in my blog post https://link.medium.com/eK6IRducpeb

For standalone keycloak server you can try this command.
kc.bat start-dev --db postgres --db-url jdbc:postgresql://localhost:5432/keycloak-server --db-username postgres --db-password root

Related

Connecting solr with aws RDS Mysql through data import handler

I recently started implementing solr-cloud on AWS EC2 for search applications. I have created 2 AWS Ec2 instances with the following configurations ---
EC2 Type - t2.medium
ram - 4GB
Disk Space - 8GB
OS - ubuntu 18.04
For the 2 EC2 instances, I have created a security group which allows all inbound traffic. NACL has default settings that allows all inbound traffic as well.
Steps Followed to install Apache Solr -
ssh into ec2 :
ssh -i "pem_file" ubuntu#ec2-public-ipv4-address
cd to /opt directory
run --> sudo apt-update
run --> sudo apt-get openjdk-11
Check java -version
run --> wget https://archive.apache.org/dist/lucene/solr/8.3.0/solr-8.3.0.tgz
run --> tar -xvzf solr-8.3.0.tgz
export SOLR_HOME=/opt/solr-8.3.0
Add /opt/solr-8.3.0 to Path environment variable
Update the sudo vim /etc/hosts file with the hosts --
a. public-ip-v4-address-of-ec2 solr-node-1
Started Solr using the following command -->
sudo bin/solr start -c -p 8983 -h solr-node-1 -force
Checked the opened ports using --> sudo lsof -i -P -n | grep LISTEN
Created collections, shards and replicas using --->
bin/solr create -c travasko -d sample_techproducts_configs -n travasko_configs -shards 2 -rf 2 -p 8983
I repeated the same process on the other EC2 machine and ran solr on it.
Now, to use the data import handler in solr, I edited the following files:
solrconfig.xml
<requestHandler name="/dataimport" class="org.apache.solr.handler.dataimport.DataImportHandler">
<lst name="defaults">
<str name="config">data-config.xml</str>
</lst>
</requestHandler>
data-config.xml
<dataConfig>
<dataSource type="JdbcDataSource"
driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://examplerds.cuhj86yfdpid.us-east-1.rds.amazonaws.com:3306/TRAVASKODB1"
user="examplerds"
password="examplerds#123"/>
<document>
<entity name="MOMENTS"
pk="MOMENT_ID"
query="SELECT MOMENT_ID,MOMENT_TEXT FROM MOMENTS"
deltaImportQuery="SELECT MOMENT_ID,MOMENT_TEXT FROM MOMENTS WHERE MOMENT_ID='${dih.delta.MOMENT_ID}'"
deltaQuery="SELECT MOMENT_ID FROM MOMENTS WHERE LAST_MODIFIED > '${dih.last_index_time}'"
>
<field column="MOMENT_ID" name="MOMENT_ID"/>
<field column="MOMENT_TEXT" name="MOMENT_TEXT"/>
</entity>
</document>
</dataConfig>
managed_schema
<schema name="MOMENTS" version="1.5">
<field name="_version_" type="long" indexed="true" stored="true"/>
<field name="MOMENT_ID" type="integer" indexed="true" stored="true" required="true" multiValued="false" />
<field name="MOMENT_TEXT" type="string" indexed="true" stored="true" multiValued="false" />
</schema>
Downloaded mysql jdbc using the following command:
wget -q "http://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/5.1.32/mysql-connector-java-5.1.32.jar" -O mysql-connector-java.jar
Add to solrconfig.xml:
<lib dir="${solr.install.dir:../../../..}/dist/" regex="solr-dataimporthandler-.*\.jar" />
<lib dir="${solr.install.dir:../../../..}/dist/" regex="mysql-connector-java.jar" />
After editing the files above, I uploaded them to the solr-cloud using the following zookeper command -->
bin/solr zk -n travasko_config -z solr-node-1:9983 cp /opt/solr-8.3.0/server/solr/configsets/_default/conf/managed-schema zk:/configs/travasko_config/managed-schema
I then checked all the above files in the solr-cloud and could notice the changes i added.
The current issue is that when I select the collection I created above, and click on Dataimport, It throws an error as below --->
The solrconfig.xml file for this index does not have an operational DataImportHandler defined!
Note: The AWS RDS and EC2 instances are in the same VPC sharing the same Security Group.
So why is solrconfig.xml file throwing an error during dataimport ? What am i missing here?
The solution to the above issue was basically setting the java system property for solr versions greater than 8.2.0 as below:
-Denable.dih.dataConfigParam=true
This parameter can be set either in solr.in.cmd or solr.in.sh which can be found inside the directory below: ,
/opt/solr-8.3.0/bin
If, /opt/solr-8.3.0 is the installation directory of solr.
The other method was to pass this parameter as command line parameter while starting solr as below:
sudo bin/solr start -c -p 8983 -h solr-node-1 -Denable.dih.dataConfigParam=true -force
solr-node-1 is the public IPv4 address of the AWS Ec2 instance on which solr is configured.

Connect SpringBoot to MySQL hosted in the cloud requires SSL

I am successful using MySQL Workbench to do full crud on a Bluemix hosted MySQL Compose service.
I then built a simple Microservice with SpringBoot on my local laptop with Apache Derby... successful.
My next step was to use the MySQL Compose hosted in Bluemix.
I edited application.properties and ran into this error
"PKIX path building failed: ...."
"SunCertPathBuilderException: unable to find valid certification path to request target"
application.properties file
spring.jpa.hibernate.ddl-auto=create
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.datasource.url=jdbc:mysql://somedomain:port/compose?useSSL=true?requireSSL=true
spring.datasource.username=myname
spring.datasource.password=mypassword
Bluemix provided me these credentials in json:
{
"db_type": "mysql",
"name": "bmix-dal-yp-xxxxxxx-",
"uri_cli": "mysql -u myname -p --host somedomain.com --port 5555 --ssl-mode=REQUIRED",
"ca_certificate_base64": "LS0tLS1CRUd......",
"deployment_id": "58fexxxxxxxxxxx",
"uri": "mysql://myname:mypassword#somedomain.com:55555/compose"
}
Am I supposed to use the ca certificate somewhere in my application.properties?
Do I need to enable ssl on my embedded tomcat server running by default with springBoot?
How can I configure my springBoot application to connect to my cloud providers MySQL instance with SSL with the json they provided?
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Add the following to your pom.xml (or equivalent):
...
<repositories>
<repository>
<id>jcenter</id>
<url>http://jcenter.bintray.com </url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
<checksumPolicy>warn</checksumPolicy>
</snapshots>
<releases>
<enabled>true</enabled>
<checksumPolicy>warn</checksumPolicy>
</releases>
</repository>
</repositories>
...
<dependency>
<groupId>com.orange.clara.cloud.boot.ssl-truststore-gen</groupId>
<artifactId>spring-boot-ssl-truststore-gen</artifactId>
<version>2.0.21</version>
</dependency>
...
Add the following to your manifest.yml
env:
# Add the certificate from VCAP_SERVICES ca_certificate_base64
# You need to base64 decode the certificate and add it below
# E.g. echo '<<ca_certificate_base64>>' | base64 -D
TRUSTED_CA_CERTIFICATE: |-
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
For more information, see https://github.com/orange-cloudfoundry/spring-boot-ssl-truststore-gen
Also see a minimal app here: https://github.com/snowch/hello-spring-cloud/tree/8b9728a826dcc1995a7ccb19a852ac8face21147
This is my first answer - this did not work. Ignore this section.
One option is:
Import the cert to Java truststore file, pack the file into Java
application and specify its path via JAVA_OPTS environment variable;
the truststore file can be placed under resource directory. This can
be used for single applications:
By using the 'cf set-env' command:
cf set-env <app> JAVA_OPTS '-Djavax.net.ssl.TrustStore=classpath:resources/config/truststore -Djavax.net.ssl.trustStorePassword=changeit'
or, by using manifest.yml
applications:
- name: java-app
...
env:
JAVA_OPTS: '-Djavax.net.ssl.TrustStore=classpath:resources/config/truststore -Djavax.net.ssl.trustStorePassword=changeit'
Note that the certificate in the field ca_certificate_base64 is base64 encoded so you will need to decode it before adding it to your truststore, e.g.
Decode the certificate:
echo '<<ca_certificate_base64>>' | base64 -D > ca_certificate.pem
Create a truststore:
keytool -import -trustcacerts -file ca_certificate.pem -alias compose_cert -keystore resources/config/truststore -storepass changeit -noprompt
Note that the keystore location (resources/config/truststore) and the storepass (changeit) are set in the JAVA_OPTS.
There are a few different options you can try. See this documentation for more information: https://discuss.pivotal.io/hc/en-us/articles/223454928-How-to-tell-application-containers-running-Java-apps-to-trust-self-signed-certs-or-a-private-or-internal-CA

cant list Hadoop filesystem

I'm trying to run Hadoop on a banana pi and I don't understand why my Hadoop isn't working.
I have an exception on running the very basic command
root#bananapi:/opt/hadoop# hadoop fs -ls
14/12/17 10:27:13 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
ls: Call From bananapi/10.0.2.150 to localhost:9000 failed on connection exception:
java.net.ConnectException: Connection refused; For more details see: http://wiki.apache.org/hadoop/ConnectionRefused
root#bananapi:/opt/hadoop#
I have installed the followed jdk
root#bananapi:/opt/hadoop# java -version
java version "1.7.0_65"
OpenJDK Runtime Environment (IcedTea 2.5.3) (7u71-2.5.3-2~deb7u1)
OpenJDK Zero VM (build 24.65-b04, mixed mode)
My etc/hosts file is looking like this:
root#bananapi:/opt/hadoop# cat /etc/hosts
127.0.0.1 localhost
10.0.2.150 bananapi # wlan0
10.0.2.119 bananapi # eth0
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
The services (jps) is also running:
root#bananapi:/opt/hadoop# jps
3732 NodeManager
3317 NameNode
3644 ResourceManager
3401 DataNode
3513 SecondaryNameNode
3860 Jps
What I'm doinging wrong or why is commands not working?
P.S. I have also tried to run hdfs dfs -ls
UPDATE
my confs in the core-site.xml
<property>
<name>fs.default.name</name>
<value>hdfs://localhost:9000</value>
</property>
I also can't format the namenode
hadoop namenode -format

error in sqoop connecting with mysql

I have downloaded the connector and saved the jar file under the sqoop/lib folder, even then I'm facing this issue.
at#ubuntu:~$ sqoop list-databases --connect "jdbc:mysql://localhost"
--username root --password root Warning: /usr/lib/hcatalog does not exist! HCatalog jobs will fail. Please set $HCAT_HOME to the root of
your HCatalog installation. 14/01/08 16:20:45 WARN tool.BaseSqoopTool:
Setting your password on the command-line is insecure. Consider using
-P instead. 14/01/08 16:20:45 INFO manager.MySQLManager: Preparing to use a MySQL streaming resultset. 14/01/08 16:20:45 ERROR sqoop.Sqoop:
Got exception running Sqoop: java.lang.RuntimeException: Could not
load db driver class: com.mysql.jdbc.Driver
java.lang.RuntimeException: Could not load db driver class:
com.mysql.jdbc.Driver at
org.apache.sqoop.manager.SqlManager.makeConnection(SqlManager.java:772)
at
org.apache.sqoop.manager.GenericJdbcManager.getConnection(GenericJdbcManager.java:52)
at
org.apache.sqoop.manager.CatalogQueryManager.listDatabases(CatalogQueryManager.java:57)
at
org.apache.sqoop.tool.ListDatabasesTool.run(ListDatabasesTool.java:49)
at org.apache.sqoop.Sqoop.run(Sqoop.java:145) at
org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:65) at
org.apache.sqoop.Sqoop.runSqoop(Sqoop.java:181) at
org.apache.sqoop.Sqoop.runTool(Sqoop.java:220) at
org.apache.sqoop.Sqoop.runTool(Sqoop.java:229) at
org.apache.sqoop.Sqoop.main(Sqoop.java:238)
The Reason For this error is sqoop is not able to connect to specified mysql driver
Try to Place mysql jars in the below libs
/opt/cloudera/parcels/CDH/lib/sqoop/lib/
/opt/cloudera/parcels/CDH-1.5.0-1../lib/sqoop/lib/
/var/lib/sqoop/
and then Restart the cluster once and run the sqoop command, then it will works.
Thanks.
Download mysql connector and place in "locationOfSqoop/sqoop/lib"
instead of placing connector folder (mysql-connector-java-5.1.41) ,place (mysql-connector-java-5.1.36-bin.jar) only jar file
"locationOfSqoop/sqoop/lib/mysql-connector-java-5.1.36-bin.jar"
First download mysql driver, you can download it from
https://dev.mysql.com/downloads/connector/j/5.1.html
then place the driver in the following location where sqoop runs (ie) in the node where sqoop runs
/var/lib/sqoop
if you didn't find the dir make one and then
place
mysql-connector-java-version-bin.jar
in
/var/lib/sqoop
than restart and complete the sqoop task
In Sqoop-1.7 mysql-connector is not present. So download the jar and copy to sqoop lib.
Download MySql connector from following link:
wget https://dev.mysql.com/get/Downloads/Connector-J/mysql-connector-java-5.1.46.tar.gz
Extract mysql-connector-java-5.1.46.tar.gz
Copy mysql-connector-java-5.1.46.jar to $SQOOP_HOME/lib directory
[ If you are using Sqoop with hadoop ]: Copy mysql-connector-java-5.1.46.jar to lib directory which is present in hdfs along with other jars present in the $SQOOP_HOME/lib/

Tomcat6 can't connect to MySql (The driver has not received any packets from the server)

i'm running an Apache Tomcat 6.0.20 / MySQL 5.1.37-lubuntu / sun-java6-jdk /sun-java6-jre / sun-java6-bin on my local machine using Ubuntu 9.10 as OS.
I'm trying to get a simple DB-query example running for 2 days now, but i still get this Exception:
org.apache.jasper.JasperException: javax.servlet.ServletException: javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.)"
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:522)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:398)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
root cause
javax.servlet.ServletException: javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.)"
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:862)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:791)
org.apache.jsp.index_jsp._jspService(index_jsp.java:104)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
root cause
javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.)"
org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.getConnection(QueryTagSupport.java:285)
org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.doStartTag(QueryTagSupport.java:168)
org.apache.jsp.index_jsp._jspx_meth_sql_005fquery_005f0(index_jsp.java:274)
org.apache.jsp.index_jsp._jspx_meth_c_005fotherwise_005f0(index_jsp.java:216)
org.apache.jsp.index_jsp._jspx_meth_c_005fchoose_005f0(index_jsp.java:130)
org.apache.jsp.index_jsp._jspService(index_jsp.java:93)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
my web.xml looks like this :
<?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_2_5.xsd"
version="2.5">
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/testDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
the context.xml looks like this :
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/my1stApp" docBase="/var/www/jsp/my1stApp" debug="5" reloadable="true" crossContext="true">
<Resource name="jdbc/testDB" auth="Container" type="javax.sql.DataSource"
maxActive="5" maxIdle="5" maxWait="10000"
username="user" password="password" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/some"/>
</Context>
and the jsp file looks like this:
<%# page contentType="text/html" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<html>
<head>
<title>DroneLootTool</title>
</head>
<body bgcolor="white">
<sql:query var="res" dataSource="jdbc/testDB">
select name, othername
from mytable
</sql:query>
<h2>Results</h2>
<c:forEach var="row" items="${res.rows}">
Name ${row.name}<br/>
MoreName ${row.othername}<br/><br/>
</c:forEach>
</body>
</html>
read lots of forum entries / tried lots of different settings (always changed back to original settings when it didnt' work)
set TOMCAT6_SECURITY=no in /etc/default/tomcat6 because TOMCAT6_SECURITY=yes was causing trouble too
the skip-networking flag is not set for the DB (BIND 127.0.0.1 is set)
firewall is swiched off (sudo ufw disable)
MySQL works (tested several times with user used in this skript)
telnet localhost 3306 says
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.
The TestConnection.java produced the following output:
me#my-laptop:~/Desktop$ java -classpath '/usr/share/java/mysql.jar:./' TestConnection com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/testDB myuser mypassword
com.mysql.jdbc.CommunicationsException: Communications link failure
Last packet sent to the server was 0 ms ago.
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1070)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2103)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:718)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:298)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:282)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at TestConnection.checkConnection(TestConnection.java:40)
at TestConnection.main(TestConnection.java:21)
Caused by: com.mysql.jdbc.CommunicationsException: Communications link failure
Last packet sent to the server was 0 ms ago.
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1070)
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:666)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1069)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2031)
... 7 more
Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2431)
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:590)
... 9 more
Connection failed.
i don't know if there is a difference between the way the java driver connects to the DB and the Perl DBI module does, but this PERL skript works
#!/usr/bin/perl -w
use CGI;
use DBI;
use strict;
print CGI::header();
my $dbh = DBI->connect("dbi:mysql:some:localhost", "user", "password");
my $sSql = "SELECT * from mytable";
my $ppl = $dbh->selectall_arrayref( $sSql );
foreach my $pl (#$ppl)
{
my #array = #$pl;
print #array;
}
$dbh->disconnect;
enabled --log-warnings on the mysql, but i didn't get any new warnings.
When i was searching the logs for warnings i found this messages when i restart the tomcat, don't know if it helps to find the problem :
Feb 2 19:50:37 tobias-laptop jsvc.exec[3129]: 02.02.2010 19:50:37 org.apache.catalina.startup.HostConfig checkResources#012INFO: Undeploying context [/myapp]
Feb 2 19:50:37 tobias-laptop jsvc.exec[3129]: 02.02.2010 19:50:37 org.apache.catalina.loader.WebappClassLoader clearReferencesThreads#012SCHWERWIEGEND: A web application appears to have started a thread named [MySQL Statement Cancellation Timer] but has failed to stop it. This is very likely to create a memory leak.
Feb 2 19:50:37 tobias-laptop jsvc.exec[3129]: 02.02.2010 19:50:37 org.apache.catalina.startup.HostConfig deployDescriptor#012INFO: Deploying configuration descriptor myapp.xml
I solved this problem. The reason why this error occurs is tomcat security restrictions.
You have to add following line to your $TOMCAT-CONFIG/policy.d/04webapps.policy
permission java.net.SocketPermission "127.0.0.1:3306", "connect";
Works for me, hope it will work for you too :)
I had the same issue.
It turns out I messed up the server by running three mysqld instances, so kill the unwanted resolved my issue:
me#ubuntu:~$ ps aux | grep mysql
mysql 8149 0.1 0.4 280484 26008 ? Ssl 13:24 0:00 /usr/sbin/mysqld
me 8256 0.0 0.0 4392 836 pts/3 S+ 13:24 0:00 grep --color=auto mysql
root 26569 0.0 0.0 5952 1856 ? S 10:44 0:00 sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking
mysql 26570 0.1 0.6 323528 41936 ? Sl 10:44 0:15 /usr/sbin/mysqld --skip-grant-tables --skip-networking
me#ubuntu:~$ sudo kill 26570
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/indiadb","root","root");
Check:
the port number it must be only 3306
Add the mysql.jar in lib if you are using Tomcat6
Please try with an "official" Connector/J 5.1 i.e. distributed by MySQL, not a deb (note that I have nothing against deb).
Also please enable --log-warnings on the mysql server and see if anything is showing up in your error logs.