I can't seem to connect a database using c3p0 when I use:
DriverManager.getConnection("jdbc:mysql://localhost:3306/rdmssql", "root", "");
no exception is thrown.
However, when I try to connection using the c3p0 connection pool:
private ComboPooledDataSource connectionPool;
...other code
/**
*
* #return
* #throws Exception
*/
public Connection getConnection() throws Exception {
return getInstance().connectionPool.getConnection();
}
/**
*
* #param driver
* #param hostname
* #param databaseName
* #param username
* #param pwd
* #throws Exception
* #throws PropertyVetoException
*/
private void setConnectionDetails(String driver, String hostname, String databaseName, String username, String pwd) throws Exception, PropertyVetoException {
connectionPool.setDriverClass("com.mysql.jdbc.Driver");
connectionPool.setJdbcUrl(driver + "://" + hostname + "/" + databaseName);
connectionPool.setUser(username);
connectionPool.setPassword(pwd);
// the settings below are optional -- c3p0 can work with defaults
// will work on this in the future
connectionPool.setInitialPoolSize(5);
connectionPool.setMinPoolSize(5);
connectionPool.setAcquireIncrement(5);
connectionPool.setMaxPoolSize(20);
connectionPool.setMaxStatements(180);
}
an java.sql.SQLException: Access denied for user: 'root#127.0.0.1' (Using password: YES) is thrown. I'm not sure if I missed some configurations for my c3p0.
The exception says it ('using password': YES).
The driver manager version does not use a password (and succeeds), whereas the connection pool version DOES (and fails).
Check the argument value passed to pwd (and make it send "").
Related
I'm trying to connect to a Sql Server database called "Shipworks1". This installation of SQL Server was installed by a shipping software called Shipworks. I cannot get the authentication to work for some reason. Here is my code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package daily.sales.report;
/**
*
* #author Line Computer
*/
import java.sql.*;
public class DailySalesReport {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Connection con = null;
String conUrl = "jdbc:sqlserver://LINECOMPUTER\\SHIPWORKS; databaseName=ShipWorks1; user=sa; password=XXXXXXXXXXXXXXX;";
try {
// ...
con = DriverManager.getConnection(conUrl);
// ...
} catch (Exception e) { e.printStackTrace(); }
finally {
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
}
And my error:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'sa'. ClientConnectionId:916f2fe6-49c3-475f-bb09-f2ff14cd92c9
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:279)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:99)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:4346)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:3160)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$100(SQLServerConnection.java:43)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:3123)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7505)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2445)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1981)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1628)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1459)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:773)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1168)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at daily.sales.report.DailySalesReport.main(DailySalesReport.java:27)
BUILD SUCCESSFUL (total time: 0 seconds)
I can connect to the DB in my db manger like so:
Any help would be appreciated. Thanks!
You should decide, which type of authentication you want to use: Windows authentication or SQL authentication.
Perhaps it will work for you:
String userName ="username";
String password ="password";
String url ="jdbc:sqlserver://myDB\\SQLServer;databaseName=name";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url, userName, password);
Also, take a look on this - https://thusithamabotuwana.wordpress.com/2012/07/19/connecting-to-sql-server-from-java/
I am trying to clean up the Cassandra connection resources for my application and my application hangs after some time. I keep getting this exception below.
I don't know how to resolve this issue. My stack trace is below.
What is the best practice on Cassandra resources clean up? The application is deployed on Tomcat server.
SEVERE: RuntimeException while executing runnable com.google.common.util.concurrent.Futures$ChainingListenableFuture#7c435ce7 with executor com.google.common.util.concurrent.MoreExecutors$ListeningDecorator#6358d4ec
java.util.concurrent.RejectedExecutionException: Task com.google.common.util.concurrent.Futures$ChainingListenableFuture#7c435ce7 rejected from java.util.concurrent.ThreadPoolExecutor#96203d77[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 2]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2059)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1383)
at com.google.common.util.concurrent.MoreExecutors$ListeningDecorator.execute(MoreExecutors.java:484)
at com.google.common.util.concurrent.ExecutionList.executeListener(ExecutionList.java:156)
at com.google.common.util.concurrent.ExecutionList.add(ExecutionList.java:101)
at com.google.common.util.concurrent.AbstractFuture.addListener(AbstractFuture.java:170)
at com.google.common.util.concurrent.Futures.transform(Futures.java:608)
at com.google.common.util.concurrent.Futures.transform(Futures.java:717)
at com.datastax.driver.core.SessionManager.toPreparedStatement(SessionManager.java:185)
at com.datastax.driver.core.SessionManager.prepareAsync(SessionManager.java:126)
at com.datastax.driver.core.SessionManager.prepare(SessionManager.java:109)
at com.bofa.ecom.search.dao.ConfigPropertyDao.readProperties(ConfigPropertyDao.java:87)
My code
public class CassandraDao implements Dao, AutoCloseable {
private final Session session;
private final Cluster cluster;
private final String keyspace;
private final String host;
/**
* Initializes and validates the session for a given keyspace.
*
* <p>
* It is the responsibility of the invoking function to close the session and
* any other resources associated with the database.
*
* #param host host
* #param keyspace keyspace to connect to and validate
* #throws UnavailableHostException if the host can not be reached
*/
public ConfigPropertyDao(String host, String keyspace) throws DatabaseException {
this.host = Objects.requireNonNull(host, "Cassandra host can not be null.");
this.keyspace = Objects.requireNonNull(keyspace, "Cassandra keyspace can not be null.");
LOGGER.debug(
String.format("Initializing the cluster and session for host :%s and keyspace:%s",
host, keyspace));
if (this.cluster == null) {
this.cluster = Cluster.builder().addContactPoint(Objects.requireNonNull(this.host)).build();
}
this.session = cluster.connect(this.keyspace);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
String.format(
"The session has been initialized for host: %s and keyspace %s", host, keyspace));
}
}
}
#Override
public void close() throws Exception {
//**UPDATE**: Check if not closed. Bad Copy paste on my part.
if (!this.session.isClosed()) {
this.session.close();
}
if (!this.cluster.isClosed()) {
this.cluter.close();
}
}
I tried copying a folder from network to a local system using apache VFS2. I added all dependency from maven given in their pom.xml. But still im getting this error "Caused by: org.apache.commons.vfs2.FileSystemException:
Expecting / to follow the hostname in URI "Caused by: org.apache.commons.vfs2.FileSystemException: Expecting / to follow the hostname in URI "sftp://user:*****#network/opt/file.txt"**
I searched SO site, stackexchange,superuser and found this issue topic, and remedy suggested was jar missing.
Somebody please throw some light on this issue and please provide me exact list of jars to be downloaded with intellij.
Im using this code.
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;
import java.io.File;
/**
* The class SFTPUtil containing uploading, downloading, checking if file exists
* and deleting functionality using Apache Commons VFS (Virtual File System)
* Library
*
* #author Ashok
*
*/
public class SFTPUtility {
public static void main(String[] args) {
String hostName = "10.2.55.66";
String username = "user";
String password = "password#network";
String localFilePath = "/opt/FakeFile.txt";
String remoteFilePath = "/opt/file.txt";
String remoteTempFilePath = "/tmp";
//upload(hostName, username, password, localFilePath, remoteFilePath);
exist(hostName, username, password, remoteFilePath);
download(hostName, username, password, localFilePath,remoteFilePath);
//move(hostName, username, password, remoteFilePath, remoteTempFilePath);
//delete(hostName, username, password, remoteFilePath);
}
/**
* Method to upload a file in Remote server
*
* #param hostName
* HostName of the server
* #param username
* UserName to login
* #param password
* Password to login
* #param localFilePath
* LocalFilePath. Should contain the entire local file path -
* Directory and Filename with \\ as separator
* #param remoteFilePath
* remoteFilePath. Should contain the entire remote file path -
* Directory and Filename with / as separator
*/
public static void upload(String hostName, String username, String password, String localFilePath, String remoteFilePath) {
File file = new File(localFilePath);
if (!file.exists())
throw new RuntimeException("Error. Local file not found");
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
manager.init();
// Create local file object
FileObject localFile = manager.resolveFile(file.getAbsolutePath());
// Create remote file object
FileObject remoteFile = manager.resolveFile(createConnectionString(hostName, username, password, remoteFilePath), createDefaultOptions());
/*
* use createDefaultOptions() in place of fsOptions for all default
* options - Ashok.
*/
// Copy local file to sftp server
remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
System.out.println("File upload success");
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
manager.close();
}
}
public static boolean move(String hostName, String username, String password, String remoteSrcFilePath, String remoteDestFilePath){
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
manager.init();
// Create remote object
FileObject remoteFile = manager.resolveFile(createConnectionString(hostName, username, password, remoteSrcFilePath), createDefaultOptions());
FileObject remoteDestFile = manager.resolveFile(createConnectionString(hostName, username, password, remoteDestFilePath), createDefaultOptions());
if (remoteFile.exists()) {
remoteFile.moveTo(remoteDestFile);;
System.out.println("Move remote file success");
return true;
}
else{
System.out.println("Source file doesn't exist");
return false;
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
manager.close();
}
}
/**
* Method to download the file from remote server location
*
* #param hostName
* HostName of the server
* #param username
* UserName to login
* #param password
* Password to login
* #param localFilePath
* LocalFilePath. Should contain the entire local file path -
* Directory and Filename with \\ as separator
* #param remoteFilePath
* remoteFilePath. Should contain the entire remote file path -
* Directory and Filename with / as separator
*/
public static void download(String hostName, String username, String password, String localFilePath, String remoteFilePath) {
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
manager.init();
// Append _downlaod_from_sftp to the given file name.
//String downloadFilePath = localFilePath.substring(0, localFilePath.lastIndexOf(".")) + "_downlaod_from_sftp" + localFilePath.substring(localFilePath.lastIndexOf("."), localFilePath.length());
// Create local file object. Change location if necessary for new downloadFilePath
FileObject localFile = manager.resolveFile(localFilePath);
// Create remote file object
FileObject remoteFile = manager.resolveFile(createConnectionString(hostName, username, password, remoteFilePath), createDefaultOptions());
// Copy local file to sftp server
localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);
System.out.println("File download success");
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
manager.close();
}
}
/**
* Method to delete the specified file from the remote system
*
* #param hostName
* HostName of the server
* #param username
* UserName to login
* #param password
* Password to login
* #param localFilePath
* LocalFilePath. Should contain the entire local file path -
* Directory and Filename with \\ as separator
* #param remoteFilePath
* remoteFilePath. Should contain the entire remote file path -
* Directory and Filename with / as separator
*/
public static void delete(String hostName, String username, String password, String remoteFilePath) {
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
manager.init();
// Create remote object
FileObject remoteFile = manager.resolveFile(createConnectionString(hostName, username, password, remoteFilePath), createDefaultOptions());
if (remoteFile.exists()) {
remoteFile.delete();
System.out.println("Delete remote file success");
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
manager.close();
}
}
// Check remote file is exist function:
/**
* Method to check if the remote file exists in the specified remote
* location
*
* #param hostName
* HostName of the server
* #param username
* UserName to login
* #param password
* Password to login
* #param remoteFilePath
* remoteFilePath. Should contain the entire remote file path -
* Directory and Filename with / as separator
* #return Returns if the file exists in the specified remote location
*/
public static boolean exist(String hostName, String username, String password, String remoteFilePath) {
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
manager.init();
// Create remote object
FileObject remoteFile = manager.resolveFile(createConnectionString(hostName, username, password, remoteFilePath), createDefaultOptions());
System.out.println("File exist: " + remoteFile.exists());
return remoteFile.exists();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
manager.close();
}
}
/**
* Generates SFTP URL connection String
*
* #param hostName
* HostName of the server
* #param username
* UserName to login
* #param password
* Password to login
* #param remoteFilePath
* remoteFilePath. Should contain the entire remote file path -
* Directory and Filename with / as separator
* #return concatenated SFTP URL string
*/
public static String createConnectionString(String hostName, String username, String password, String remoteFilePath) {
if(remoteFilePath.startsWith("/")||remoteFilePath.startsWith("\\"))
remoteFilePath=remoteFilePath.substring(1);
return "sftp://" + username + ":" + password + "#" + hostName + "/" + remoteFilePath;
}
/**
* Method to setup default SFTP config
*
* #return the FileSystemOptions object containing the specified
* configuration options
* #throws FileSystemException
*/
public static FileSystemOptions createDefaultOptions() throws FileSystemException {
// Create SFTP options
FileSystemOptions opts = new FileSystemOptions();
// SSH Key checking
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
/*
* Using the following line will cause VFS to choose File System's Root
* as VFS's root. If I wanted to use User's home as VFS's root then set
* 2nd method parameter to "true"
*/
// Root directory set to user home
SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, false);
// Timeout is count by Milliseconds
SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
return opts;
}
}
Please specify the file location as following and check
If it is local file,
file:///home/someuser/somedir
file:///C:/DocumentsandSettings
file://///somehost/test/text.xml
Or if it is ftp,
> ftp://myusername:mypassword#hostname/test/test.tar.gz
Your password has "#".
You need escape, try replace "#" to "%40".
Your password contains a #, thus concatenation creates an invalid connection string: sftp://username:p#ssword#hostName
It must be encoded as sftp://username:p%40ssword#hostName
Instead of concatenation, create a java.net.URI to handle proper password encoding
String userInfo = user + ":" + passwd;
URI uri = new URI("sftp", userInfo, host, -1, path, null, null);
Detail: https://stackoverflow.com/a/29568361/912046
I need a pure Apache Commons VFS solution/code/example for
Uploading a local file to Remote Host Location
Check if a File exists in Remote Host Location
Downloading a Remote Host File to Local file location
Move a file from one Remote Location to another in the same Host
Delete a file from the Remote Host Location
via SFTP calls.
The solution should only use Apache Commons VFS api and shouldn't refer to the underlying JSCH library.
The below SFTP Utility gives an example of Upload, Exist, Download, Move and Delete operations. I have used this in several of my projects. The below code uses api calls from Apache Commons VFS library only.
Please make sure that you put the following JAR's in your project's build path:
commons-logging-1.1.3.jar
commons-vfs2-2.0.jar
hamcrest-core-1.3.jar
jsch-0.1.50.jar
Any other compatible versions would do as well.
import java.io.File;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;
/**
* The class SFTPUtil containing uploading, downloading, checking if file exists
* and deleting functionality using Apache Commons VFS (Virtual File System)
* Library
*
* #author Ashok
*
*/
public class SFTPUtility {
public static void main(String[] args) {
String hostName = "PutYourHostNameHere";
String username = "PutYourUserNameForHostHere";
String password = "PutYourPasswordForHostHere";
String localFilePath = "C:\\FakePath\\FakeFile.txt";
String remoteFilePath = "/FakeRemotePath/FakeRemoteFile.txt";
String remoteTempFilePath = "/FakeRemoteTempPath/FakeRemoteTempFile.txt";
upload(hostName, username, password, localFilePath, remoteFilePath);
exist(hostName, username, password, remoteFilePath);
download(hostName, username, password, localFilePath,remoteFilePath);
move(hostName, username, password, remoteFilePath, remoteTempFilePath);
delete(hostName, username, password, remoteFilePath);
}
/**
* Method to upload a file in Remote server
*
* #param hostName
* HostName of the server
* #param username
* UserName to login
* #param password
* Password to login
* #param localFilePath
* LocalFilePath. Should contain the entire local file path -
* Directory and Filename with \\ as separator
* #param remoteFilePath
* remoteFilePath. Should contain the entire remote file path -
* Directory and Filename with / as separator
*/
public static void upload(String hostName, String username, String password, String localFilePath, String remoteFilePath) {
File file = new File(localFilePath);
if (!file.exists())
throw new RuntimeException("Error. Local file not found");
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
manager.init();
// Create local file object
FileObject localFile = manager.resolveFile(file.getAbsolutePath());
// Create remote file object
FileObject remoteFile = manager.resolveFile(createConnectionString(hostName, username, password, remoteFilePath), createDefaultOptions());
/*
* use createDefaultOptions() in place of fsOptions for all default
* options - Ashok.
*/
// Copy local file to sftp server
remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
System.out.println("File upload success");
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
manager.close();
}
}
public static boolean move(String hostName, String username, String password, String remoteSrcFilePath, String remoteDestFilePath){
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
manager.init();
// Create remote object
FileObject remoteFile = manager.resolveFile(createConnectionString(hostName, username, password, remoteSrcFilePath), createDefaultOptions());
FileObject remoteDestFile = manager.resolveFile(createConnectionString(hostName, username, password, remoteDestFilePath), createDefaultOptions());
if (remoteFile.exists()) {
remoteFile.moveTo(remoteDestFile);;
System.out.println("Move remote file success");
return true;
}
else{
System.out.println("Source file doesn't exist");
return false;
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
manager.close();
}
}
/**
* Method to download the file from remote server location
*
* #param hostName
* HostName of the server
* #param username
* UserName to login
* #param password
* Password to login
* #param localFilePath
* LocalFilePath. Should contain the entire local file path -
* Directory and Filename with \\ as separator
* #param remoteFilePath
* remoteFilePath. Should contain the entire remote file path -
* Directory and Filename with / as separator
*/
public static void download(String hostName, String username, String password, String localFilePath, String remoteFilePath) {
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
manager.init();
// Append _downlaod_from_sftp to the given file name.
//String downloadFilePath = localFilePath.substring(0, localFilePath.lastIndexOf(".")) + "_downlaod_from_sftp" + localFilePath.substring(localFilePath.lastIndexOf("."), localFilePath.length());
// Create local file object. Change location if necessary for new downloadFilePath
FileObject localFile = manager.resolveFile(localFilePath);
// Create remote file object
FileObject remoteFile = manager.resolveFile(createConnectionString(hostName, username, password, remoteFilePath), createDefaultOptions());
// Copy local file to sftp server
localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);
System.out.println("File download success");
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
manager.close();
}
}
/**
* Method to delete the specified file from the remote system
*
* #param hostName
* HostName of the server
* #param username
* UserName to login
* #param password
* Password to login
* #param localFilePath
* LocalFilePath. Should contain the entire local file path -
* Directory and Filename with \\ as separator
* #param remoteFilePath
* remoteFilePath. Should contain the entire remote file path -
* Directory and Filename with / as separator
*/
public static void delete(String hostName, String username, String password, String remoteFilePath) {
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
manager.init();
// Create remote object
FileObject remoteFile = manager.resolveFile(createConnectionString(hostName, username, password, remoteFilePath), createDefaultOptions());
if (remoteFile.exists()) {
remoteFile.delete();
System.out.println("Delete remote file success");
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
manager.close();
}
}
// Check remote file is exist function:
/**
* Method to check if the remote file exists in the specified remote
* location
*
* #param hostName
* HostName of the server
* #param username
* UserName to login
* #param password
* Password to login
* #param remoteFilePath
* remoteFilePath. Should contain the entire remote file path -
* Directory and Filename with / as separator
* #return Returns if the file exists in the specified remote location
*/
public static boolean exist(String hostName, String username, String password, String remoteFilePath) {
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
manager.init();
// Create remote object
FileObject remoteFile = manager.resolveFile(createConnectionString(hostName, username, password, remoteFilePath), createDefaultOptions());
System.out.println("File exist: " + remoteFile.exists());
return remoteFile.exists();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
manager.close();
}
}
/**
* Generates SFTP URL connection String
*
* #param hostName
* HostName of the server
* #param username
* UserName to login
* #param password
* Password to login
* #param remoteFilePath
* remoteFilePath. Should contain the entire remote file path -
* Directory and Filename with / as separator
* #return concatenated SFTP URL string
*/
public static String createConnectionString(String hostName, String username, String password, String remoteFilePath) {
return "sftp://" + username + ":" + password + "#" + hostName + "/" + remoteFilePath;
}
/**
* Method to setup default SFTP config
*
* #return the FileSystemOptions object containing the specified
* configuration options
* #throws FileSystemException
*/
public static FileSystemOptions createDefaultOptions() throws FileSystemException {
// Create SFTP options
FileSystemOptions opts = new FileSystemOptions();
// SSH Key checking
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
/*
* Using the following line will cause VFS to choose File System's Root
* as VFS's root. If I wanted to use User's home as VFS's root then set
* 2nd method parameter to "true"
*/
// Root directory set to user home
SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, false);
// Timeout is count by Milliseconds
SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
return opts;
}
}
/**
*
*/
package ORM;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* #author Gwilym
* #version 0.0
*/
public class DatabaseConnection {
private String userName="";
private String password="";
private String host="";
Connection conn;
/**
* #param userName
* #param password
* #param host
*/
public DatabaseConnection(String userName, String password, String host) {
this.userName = userName;
this.password = password;
this.host = host;
}
public DatabaseConnection(String userName, String password, String host,boolean autoConnect) {
this.userName = userName;
this.password = password;
this.host = host;
if (autoConnect)
{
try {
Connect();
} catch (DatabaseConnectionException e) {
e.printStackTrace();
}
}
}
/**
* #return the connection
*/
public Connection getConn() {
return conn;
}
/**
* #param userName the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* #param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* #param host the host to set
*/
public void setHost(String host) {
this.host = host;
}
/**
* Connect, attempts to connect to the MySQL database
* with sun JDBC
* & MySQL driver
* #param none
* #return True iff connected;
* #return False for all else;
* #throws DatabaseConnectionException
*/
public boolean Connect() throws DatabaseConnectionException
{
// Attempt to load database driver
try
{
String url = "jdbc:mysql:"+host;
System.out.println(url);
//Load driver
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);
}
catch (ClassNotFoundException cnfe) // driver not found
{
conn=null;
System.err.println ("Unable to load database driver");
throw new DatabaseConnectionException(cnfe);
}
catch(InstantiationException ie)
{
conn=null;
System.err.println ("Unable to Create database driver");
throw new DatabaseConnectionException(ie);
}
catch (IllegalAccessException iae)
{
conn=null;
System.err.println ("Unable to Create database driver");
throw new DatabaseConnectionException(iae);
} catch (SQLException sqle) {
conn=null;
System.err.println ("SQL error");
throw new DatabaseConnectionException(sqle);
}
if (conn!=null)
{
System.out.println ("Database connection established");
return true;
}
else
{
System.out.println ("Database connection Failed");
return false;
}
}
/**
* Disconnects the System from the mySQL database
*
* #param none
* #return true, if successful
* #return false if not connection in existance
*/
public boolean Disconnect()
{
if (conn != null)
{
try
{
conn.close ();
conn=null;
System.out.println ("Database connection terminated normally");
return true;
}
catch (Exception e) {
//Ignore these errors as they all result in conn.close anyway
}
finally
{
conn=null;
System.gc();
// my removing the refrance to conncetion all calling the Garbage collecter we insure it is destoryed.
}
System.out.println ("Database connection terminated with errors");
return true;
}
else
{
System.out.println ("No Database connection present");
return true;
}
}
}
The above code is called by
DatabaseConnection db =new DatabaseConnection("USERNAME","PASSWORD","//tel2.dur.ac.uk:3306/dcs8s07_SEG",true);
for obvious reasons I have removed the user name and password , but they can be aassumed to be correct.
Right down to the problem its self I get a com.mysql.jdbc.exceptions.jdbc4.CommunicationsException when ever this code is run with the details "The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server."
My main problem at the moment is trying to discover what is actually going wrong.
In so far as I can tell the driver is being loaded correctly as my code does not throw a ClassNotFoundException, rather a SQLException of some kind.
So the problem is almost certainly the connection in some way. I can connect and query this database though a phpMyadmin located on the same server so I can assume that
1)The server is online
2)mySQL is working
3)the Username and password are correct
4) the database is present and i have the name correct
From this and "The driver has not received any packets from the server." I am wondering if the URL malformed?
URL= jdbc:mysql://tel2.dur.ac.uk:3306/dcs8s07_SEG
or there a simple setting that is incorrect on the server whihc is not allowing me to connect?
I have pondered on this problem and attempted several googles to no avail, so any idea would be of great help
thanks in advance SO!
This is a wrapped exception. What's the root cause of this exception? Look further in the stacktrace.
A very common root cause is java.net.ConnectException: Connection refused. I've seen this in almost 99% of the cases. If this is true in your case as well, then all the possible causes are:
IP address or hostname in JDBC URL is wrong.
Hostname in JDBC URL is not recognized by local DNS server.
Port number is missing or wrong in JDBC URL.
DB server is down.
DB server doesn't accept TCP/IP connections.
Something in between Java and DB is blocking connections, e.g. a firewall or proxy.
To solve the one or the either, follow the following advices:
Verify and test them with ping.
Refresh DNS or use IP address in JDBC URL instead.
Verify it based on my.cnf of MySQL DB.
Start it.
Verify if mysqld is started without the --skip-networking option.
Disable firewall and/or configure firewall/proxy to allow/forward the port.
The username and password are irrelevant in this problem. At this point the DB can't even be reached. You would have gotten a "Login failed" or "Not authorized" SQLException otherwise.
In addition to the last post you should also do a low-level telnet test, this is the best way to verify connectivity. This test will tell you if there is a firewall or other software blocking access to that port.
telnet tel2.dur.ac.uk 3306