2014-06-04 16:13:44 +02:00
package org.gcube.dataaccess.databases.utils ;
2014-06-04 15:56:35 +02:00
2014-07-25 10:13:25 +02:00
import java.io.ByteArrayInputStream ;
import java.io.IOException ;
import java.net.MalformedURLException ;
2014-09-02 15:14:58 +02:00
import java.sql.Connection ;
import java.sql.DriverManager ;
import java.sql.ResultSet ;
import java.sql.Statement ;
import java.util.ArrayList ;
import java.util.LinkedHashMap ;
2014-07-25 10:13:25 +02:00
import java.util.List ;
import javax.xml.parsers.DocumentBuilderFactory ;
2014-06-04 15:56:35 +02:00
import org.gcube.contentmanagement.lexicalmatcher.utils.AnalysisLogger ;
import org.gcube.contentmanagement.lexicalmatcher.utils.FileTools ;
import org.gcube.dataanalysis.ecoengine.configuration.AlgorithmConfiguration ;
import org.hibernate.Query ;
import org.hibernate.Session ;
import org.hibernate.SessionFactory ;
import org.hibernate.cfg.Configuration ;
/ * *
* Class that allows to manage a database selected from a user . It performs to
* set the database configuration , to connect to the database and finally to
* execute a query .
* /
public class ConnectionManager {
// private org.gcube.dataanalysis.ecoengine.utils.DatabaseFactory df;
// Constructor
public ConnectionManager ( ) {
// org.gcube.dataanalysis.ecoengine.utils.DatabaseFactory df = new
// org.gcube.dataanalysis.ecoengine.utils.DatabaseFactory();
// df = new org.gcube.dataanalysis.ecoengine.utils.DatabaseFactory();
}
2014-07-25 10:13:25 +02:00
public static SessionFactory initDBSession ( AlgorithmConfiguration config ) {
SessionFactory dbHibConnection = null ;
try {
if ( ( config ! = null ) & & ( config . getConfigPath ( ) ! = null ) ) {
2014-07-25 15:49:09 +02:00
String defaultDatabaseFile = config . getConfigPath ( )
2014-09-10 09:57:17 +02:00
+ " DestinationDBHibernateDBManager.cfg.xml " ;
2014-07-25 10:13:25 +02:00
config . setDatabaseDriver ( config . getParam ( " DatabaseDriver " ) ) ;
config . setDatabaseUserName ( config . getParam ( " DatabaseUserName " ) ) ;
config . setDatabasePassword ( config . getParam ( " DatabasePassword " ) ) ;
config . setDatabaseURL ( config . getParam ( " DatabaseURL " ) ) ;
2014-07-25 15:49:09 +02:00
dbHibConnection = org . gcube . dataaccess . databases . utils . DatabaseFactory
. initDBConnection ( defaultDatabaseFile , config ) ;
2014-07-25 10:13:25 +02:00
}
} catch ( Exception e ) {
2014-07-25 15:49:09 +02:00
System . out . println ( " ERROR IN DB INITIALIZATION : "
+ e . getLocalizedMessage ( ) ) ;
2014-08-01 17:21:17 +02:00
// e.printStackTrace();
2014-07-25 10:13:25 +02:00
// AnalysisLogger.getLogger().trace(e);
}
return dbHibConnection ;
}
2014-07-25 15:49:09 +02:00
2014-06-04 15:56:35 +02:00
// create the database's connection without using the configuration file but
// using the data input
public SessionFactory initDBConnection ( AlgorithmConfiguration config ) {
2014-07-25 10:13:25 +02:00
SessionFactory dbconnection = initDBSession ( config ) ;
2014-06-04 15:56:35 +02:00
return dbconnection ;
}
// create the database's connection using the configuration file
2014-09-10 09:57:17 +02:00
// Note that this method is not called actually.
2014-06-04 15:56:35 +02:00
public SessionFactory initDBConnection ( String configurationFile )
throws Exception {
String xml = FileTools . readXMLDoc ( configurationFile ) ;
SessionFactory DBSessionFactory = null ;
Configuration cfg = new Configuration ( ) ;
cfg = cfg . configure ( DocumentBuilderFactory . newInstance ( )
. newDocumentBuilder ( )
. parse ( new ByteArrayInputStream ( xml . getBytes ( ) ) ) ) ;
DBSessionFactory = cfg . buildSessionFactory ( ) ;
return DBSessionFactory ;
}
/** Method that allows to set the configuration */
public AlgorithmConfiguration setconfiguration ( String ConfigPath ,
String DatabaseUserName , String DatabasePassword ,
String DatabaseDriver , String DatabaseDialect , String DatabaseURL ,
String DatabaseName ) throws IOException {
AlgorithmConfiguration config = new AlgorithmConfiguration ( ) ;
if ( DatabaseName . equals ( " " ) ) {
throw new MalformedURLException (
" Invalid Url: the database's name is not present " ) ;
// return null;
}
if ( ! ConfigPath . equals ( " " ) )
config . setConfigPath ( ConfigPath ) ;
if ( ! DatabaseUserName . equals ( " " ) ) {
config . setParam ( " DatabaseUserName " , DatabaseUserName ) ;
}
if ( ! DatabasePassword . equals ( " " ) )
config . setParam ( " DatabasePassword " , DatabasePassword ) ;
if ( ! DatabaseDriver . equals ( " " ) )
config . setParam ( " DatabaseDriver " , DatabaseDriver ) ;
if ( ! DatabaseDialect . equals ( " " ) )
config . setParam ( " DatabaseDialect " , DatabaseDialect ) ;
if ( ! DatabaseURL . equals ( " " ) )
config . setParam ( " DatabaseURL " , DatabaseURL ) ;
return config ;
}
2014-09-02 15:14:58 +02:00
/** Method that execute a query */
public List < Object > executeQueryJDBC ( String query , Connection conn )
throws Exception {
List < Object > result = null ;
// Get a statement from the connection
Statement stmt = conn . createStatement ( ) ;
// Execute the query
ResultSet rs = stmt . executeQuery ( query ) ;
//get columns
List < Object > rows = new ArrayList < Object > ( ) ;
while ( rs . next ( ) ) {
LinkedHashMap < String , Object > map = new LinkedHashMap < String , Object > ( ) ;
int colNum = rs . getMetaData ( ) . getColumnCount ( ) ;
for ( int i = 1 ; i < colNum + 1 ; i + + ) {
String columnName = rs . getMetaData ( ) . getColumnLabel ( i ) ;
// System.out.println("column Name: "+columnName);
Object columnValue = rs . getObject ( i ) ;
// System.out.println("value: "+columnValue);
int j = 1 ;
String newcolumnName = columnName ;
//rename a column if the same name is already present
while ( map . get ( newcolumnName ) ! = null ) {
newcolumnName = columnName + " _ " + j ;
j + + ;
}
map . put ( newcolumnName , columnValue ) ;
}
rows . add ( map ) ;
}
result = rows ;
if ( result = = null | | result . size ( ) = = 0 ) {
AnalysisLogger . getLogger ( ) . debug (
" ConnectionManager->Error: Result not available " ) ;
throw new Exception ( " Result not available " ) ;
}
stmt . close ( ) ;
2014-09-05 12:02:23 +02:00
AnalysisLogger . getLogger ( ) . debug (
" In ConnectionManager-> result's size: " + result . size ( ) ) ;
2014-09-02 15:14:58 +02:00
// conn.close();
return result ;
}
2014-06-04 15:56:35 +02:00
/** Method that execute a query */
public List < Object > executeQuery ( String query ,
SessionFactory DBSessionFactory ) throws Exception {
List < Object > obj = null ;
Session ss = null ;
try {
ss = DBSessionFactory . getCurrentSession ( ) ;
2014-08-01 17:21:17 +02:00
// print check added to measure the timeout
// AnalysisLogger.getLogger().debug(
// "In ConnectionManager-> beginTransaction: ");
2014-06-04 15:56:35 +02:00
2014-07-25 15:49:09 +02:00
ss . beginTransaction ( ) ;
2014-08-01 17:21:17 +02:00
2014-06-04 15:56:35 +02:00
Query qr = null ;
// statement to check if the query is a "show create table"
String keyword = " show create table " ;
String regex = " .* \\ b " + keyword . replaceAll ( " + " , " [ ] \\ + " )
+ " \\ b.* " ;
if ( ( ! ( query . toLowerCase ( ) . contains ( " explain " ) ) )
& & ( ! ( query . toLowerCase ( ) . matches ( regex ) ) ) ) { // it does not
// work if the
// query
// performs an
// explain
// operation
// Wrapper for a query. It allows the query to operate in a
// proper
// way
// query check in order to remove the character ";" if the query
// contains it
query = query . trim ( ) ;
if ( query . endsWith ( " ; " ) ) {
int endIndex = query . indexOf ( " ; " ) ;
query = query . substring ( 0 , endIndex ) ;
}
query = " select * from ( " + query + " ) as query " ;
}
AnalysisLogger . getLogger ( ) . debug (
" In ConnectionManager-> executing query: " + query ) ;
qr = ss . createSQLQuery ( query ) ;
qr . setResultTransformer ( AliasToEntityOrderedMapResultTransformer . INSTANCE ) ;
// @SuppressWarnings("unchecked")
List < Object > result = qr . list ( ) ;
AnalysisLogger . getLogger ( ) . debug (
" In ConnectionManager-> result's size: " + result . size ( ) ) ;
ss . getTransaction ( ) . commit ( ) ;
/ *
* if ( result = = null ) System . out . println (
* " Hibernate doesn't return a valid object when org.gcube.contentmanagement.lexicalmatcher retrieve UserState Object "
* ) ;
*
* if ( result ! = null & & result . size ( ) = = 0 )
* System . out . println ( String . format ( " found nothing in database " ) ) ;
* /
if ( result ! = null & & result . size ( ) ! = 0 ) {
obj = result ;
} else {
AnalysisLogger . getLogger ( ) . debug (
" ConnectionManager->Error: Result not available " ) ;
throw new Exception ( " Result not available " ) ;
}
} catch ( Exception e ) {
2014-09-02 15:14:58 +02:00
// e.printStackTrace();
2014-06-04 15:56:35 +02:00
// System.out.println(String.format("Error while executing query: %1$s %2$s",
// query, e.getMessage()));
// e.printStackTrace();
// System.out.println(String.format("Error while executing query: %1$s %2$s",
// query, e.getMessage()));
2014-07-25 15:49:09 +02:00
if ( e instanceof org . hibernate . MappingException ) {
2014-06-04 15:56:35 +02:00
// e.printStackTrace();
// System.out.println(e.getClass().toString());
2014-08-01 17:21:17 +02:00
// AnalysisLogger
// .getLogger()
// .debug("In ConnectionManager-> ERROR The query could not be executed: Error in retrieving a user defined type. Try to use a store procedure to convert the type");
//
// throw new Exception(
// "The query could not be executed: Error in retrieving a user defined type. Try to use a store procedure to convert the type");
2014-07-25 15:49:09 +02:00
AnalysisLogger . getLogger ( ) . debug (
2014-08-01 17:21:17 +02:00
" In ConnectionManager-> " + e . getLocalizedMessage ( ) ) ;
2014-07-25 15:49:09 +02:00
throw new Exception ( e . getLocalizedMessage ( ) ) ;
2014-08-01 17:21:17 +02:00
2014-06-04 15:56:35 +02:00
}
2014-07-25 15:49:09 +02:00
if ( e instanceof org . hibernate . exception . SQLGrammarException ) {
2014-06-04 15:56:35 +02:00
2014-08-01 17:21:17 +02:00
String cause = " " ;
if ( e . getCause ( ) ! = null ) {
cause = e . getCause ( ) . getLocalizedMessage ( ) ;
// System.out.println(e.getCause().getLocalizedMessage());
}
2014-06-04 15:56:35 +02:00
// System.out.println(e.getCause().getMessage());
// AnalysisLogger.getLogger().debug("In ConnectionManager-> ERROR The query could not be executed: SQL grammar error in the query");
// throw new
// Exception("The query could not be executed: SQL grammar error in the query");
2014-08-01 17:21:17 +02:00
// AnalysisLogger.getLogger().debug(
// "In ConnectionManager-> "
// + e.getCause().getLocalizedMessage());
//
// throw new Exception(e.getCause().getMessage());
2014-07-25 15:49:09 +02:00
AnalysisLogger . getLogger ( ) . debug (
2014-08-01 17:21:17 +02:00
" In ConnectionManager-> " + e . getLocalizedMessage ( )
+ " . " + cause ) ;
throw new Exception ( e . getLocalizedMessage ( ) + " . " + cause ) ;
2014-07-25 15:49:09 +02:00
}
if ( e instanceof org . hibernate . exception . GenericJDBCException ) {
2014-08-01 17:21:17 +02:00
// AnalysisLogger.getLogger().debug(
// "In ConnectionManager-> "
// + e.getCause().toString());
// e.printStackTrace();
2014-06-04 15:56:35 +02:00
AnalysisLogger . getLogger ( ) . debug (
2014-08-01 17:21:17 +02:00
" In ConnectionManager-> " + e . getLocalizedMessage ( ) ) ;
2014-07-25 15:49:09 +02:00
throw new Exception ( e . getLocalizedMessage ( ) ) ;
2014-06-04 15:56:35 +02:00
}
else {
throw e ;
}
// throw e;
}
return obj ;
}
2014-09-02 15:14:58 +02:00
// //to cancel the execution of the current query
// public void removeQueryExecution(SessionFactory DBSessionFactory) throws
// Exception{
//
// try{
//
// Session ss = DBSessionFactory.getCurrentSession();
//
// ss.beginTransaction();
//
// ss.cancelQuery();
//
// ss.getTransaction().commit();
//
// }
// catch (Exception e) {
// throw e;
// }
//
// }
2014-06-04 15:56:35 +02:00
// /** Method that creates the connection */
// public SessionFactory createConnection(AlgorithmConfiguration config) {
//
// SessionFactory dbconnection = DatabaseUtils.initDBSession(config);
//
// return dbconnection;
//
// }
}