connDesc.setDbAlias( "photovault" );
File derbyDir = new File( dbDesc.getEmbeddedDirectory(), "derby" );
System.setProperty( "derby.system.home", derbyDir.getAbsolutePath() );
if ( ( user != null && user.length() != 0 ) ||
( passwd != null && passwd.length() != 0 ) ) {
throw new PhotovaultException( "No username or password allowed for Derby database" );
}
} else {
// This is a MySQL database
String dbhost = dbDesc.getHost();
String dbname = dbDesc.getDbName();
connDesc.setDbAlias( "//" + dbhost + "/" + dbname );
connDesc.setUserName( user );
connDesc.setPassWord( passwd );
connDesc.setDriver( "com.mysql.jdbc.Driver" );
connDesc.setDbms( "MySQL" );
connDesc.setSubProtocol( "mysql" );
}
// Open the database connection
db = odmg.newDatabase();
boolean success = false;
try {
log.debug( "Opening database" );
db.open( "pv#" + user + "#" + passwd, Database.OPEN_READ_WRITE );
log.debug( "Success!!!" );
} catch ( Throwable e ) {
log.error( "Failed to get connection: " + e.getMessage() );
e.printStackTrace();
}
// Check whether the database was opened correctly
try {
PersistenceBroker broker = PersistenceBrokerFactory.createPersistenceBroker(connKey);
broker.beginTransaction();
Connection con = broker.serviceConnectionManager().getConnection();
broker.commitTransaction();
broker.close();
} catch (Exception ex) {
/*
Finding the real reason for the error needs a bit of guesswork: first
lets find the original exception
*/
Throwable rootCause = ex;
while ( rootCause.getCause() != null ) {
rootCause = rootCause.getCause();
}
log.error( rootCause.getMessage() );
if ( rootCause instanceof SQLException ) {
if ( rootCause instanceof EmbedSQLException ) {
/*
We are using Derby, the problem is likely that another
instance of the database has been started
*/
throw new PhotovaultException( "Cannot start database.\n"
+ "Do you have another instance of Photovault running?", rootCause );
}
if ( dbDesc.getInstanceType() == PVDatabase.TYPE_SERVER ) {
throw new PhotovaultException( "Cannot log in to MySQL database", rootCause );
}
}
throw new PhotovaultException( "Unknown error while starting database:\n"
+ rootCause.getMessage(), rootCause );
}
// Test the connection by fetching something
try {
DbInfo dbinfo = DbInfo.getDbInfo();
if ( dbinfo != null ) {
// PhotoFolder folder = PhotoFolder.getRoot();
// if ( folder != null ) {
success = true;
} else {
log.error( "Could not open database connection" );
try {
db.close();
} catch (ODMGException e ) {
log.error( "Error closing database" );
}
}
} catch ( Exception t ) {
log.error( "Could not open database connection" );
log.error( t.getMessage() );
t.printStackTrace();
try {
db.close();
} catch ( Exception e ) {
log.error( "Error closing database" );
}
throw new PhotovaultException( "Unknown error while starting database:\n"
+ t.getMessage(), t );
}
if ( !success ) {
throw new PhotovaultException( "Unknown exception while starting database" );
}
}