vre-modeler/src/org/gcube/vremanagement/vremodeler/db/DBInterface.java

247 lines
7.3 KiB
Java

package org.gcube.vremanagement.vremodeler.db;
import java.io.File;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Hashtable;
import org.gcube.common.core.faults.GCUBEFault;
import org.gcube.common.core.utils.logging.GCUBELog;
import org.gcube.vremanagement.vremodeler.impl.ServiceContext;
import org.gcube.vremanagement.vremodeler.impl.util.Listable;
/**
*
* @author lucio
*
*/
public class DBInterface {
private static Hashtable< String, Connection> connectionMapping= new Hashtable<String, Connection>();
private static String dbFile = ServiceContext.getContext().getPersistenceRoot()+ File.separator + "vreModelerDB";
private static GCUBELog logger = new GCUBELog(DBInterface.class);
/**
*
* @return
* @throws SQLException
*/
public static boolean dbAlreadyCreated(){
File file= new File(dbFile+ServiceContext.getContext().getScope().toString().replace("/", "-")+".data");
logger.trace("the db "+file.getName()+" exists ?"+ file.exists());
return file.exists();
}
public static Connection connect() throws SQLException{
if(connectionMapping.get(ServiceContext.getContext().getScope().toString())==null)
{
// Load the HSQL Database Engine JDBC driver
// hsqldb.jar should be in the class path or made part of the current jar
logger.info(dbFile);
try{
Class.forName("org.hsqldb.jdbcDriver");
}catch(ClassNotFoundException e){throw new SQLException(e.getMessage());}
// connect to the database. This will load the db files and start the
// database if it is not alread running.
// db_file_name_prefix is used to open or create files that hold the state
// of the db.
// It can contain directory names relative to the
// current working directory
Connection conn = DriverManager.getConnection("jdbc:hsqldb:file:"
+ dbFile+ServiceContext.getContext().getScope().toString().replace("/", "-"), // filenames
"sa", // username
""); // password
connectionMapping.put(ServiceContext.getContext().getScope().toString(), conn);
}
return connectionMapping.get(ServiceContext.getContext().getScope().toString());
}
public static Connection getConnection(){
return connectionMapping.get(ServiceContext.getContext().getScope().toString());
}
/**
*
* @param query
*/
public static synchronized void ExecuteUpdate(String query) throws Exception{
Statement st = null;
Connection conn= getConnection();
try{
st = conn.createStatement(); // statement objects can be reused with
st.executeUpdate(query);
st.close();
}catch(SQLException e){throw e;}
}
public static synchronized void insertIntoListable(String table, Listable... values) throws GCUBEFault {
if (values==null) throw new GCUBEFault();
Statement st = null;
Connection conn= getConnection();
try{
st = conn.createStatement(); // statement objects can be reused with
}catch(SQLException e){//logger.error("error creating SQL statement");
throw new GCUBEFault(e);}
StringBuffer insertQuery;
for (Listable row: values)
{
insertQuery=new StringBuffer();
insertQuery.append("INSERT INTO ").append(table.toUpperCase()).append(" VALUES(");
try{
for(String value: row.getAsStringList()){
insertQuery.append("'").append(value.replaceAll("'", " ")).append("',");
}
insertQuery.deleteCharAt(insertQuery.length()-1).append(");");
logger.trace("Query for inserting in hsqldb "+insertQuery);
st.executeUpdate(insertQuery.toString()); // run the query
}catch(SQLException e){
logger.warn("HSQLDB ERROR: Problem inserting data "+insertQuery,e);
}
catch(Exception e){
logger.error("VDLModelService error: Problem inserting data ",e);
}
}
try{
st.close();
}catch(SQLException e){
logger.error("error closing SQL statement",e);
throw new GCUBEFault(e);}
}
/**
*
* @param table
* @param values
* @throws RemoteException
*/
public static synchronized void insertInto(String table, String[]... rows) throws GCUBEFault {
Connection conn= getConnection();
Statement st = null;
try{
st = conn.createStatement(); // statement objects can be reused with
}catch(SQLException e){//logger.error("error creating SQL statement");
throw new GCUBEFault(e);}
StringBuffer insertQuery;
for (String[] row: rows)
{
insertQuery=new StringBuffer();
insertQuery.append("INSERT INTO ").append(table.toUpperCase()).append(" VALUES(");
try{
for(String value: row){
insertQuery.append("'").append(value.replaceAll("'", " ")).append("',");
}
insertQuery.deleteCharAt(insertQuery.length()-1).append(");");
logger.trace("Query for inserting in hsqldb "+insertQuery);
st.executeUpdate(insertQuery.toString()); // run the query
}catch(SQLException e){
logger.warn("HSQLDB ERROR: Problem inserting data "+ insertQuery,e);
}
catch(Exception e){
logger.error("VDLModelService error: Problem inserting data ",e);
}
}
try{
st.close();
}catch(SQLException e){
logger.error("error closing SQL statement");
throw new GCUBEFault(e);}
}
/**
*
* @param query
* @return
* @throws SQLException
*/
public static synchronized ResultSet queryDB(String query) throws SQLException {
Statement st = null;
ResultSet rs = null;
Connection conn= getConnection();
st = conn.createStatement(); // statement objects can be reused with
rs = st.executeQuery(query); // run the query
st.close();
return rs;
}
/**
*
* @param table
* @throws SQLException
*/
public static void deleteAll(String table) throws SQLException{
String query="DELETE FROM "+table.toUpperCase();
Connection conn= getConnection();
Statement st=conn.createStatement();
st.executeUpdate(query);
st.close();
}
public static void deleteElement(String table, String whereClause) throws SQLException{
String query="DELETE FROM "+table.toUpperCase()+" WHERE "+whereClause;
Connection conn= getConnection();
Statement st=conn.createStatement();
st.executeUpdate(query);
st.close();
}
public static void close() throws SQLException{
Connection conn= getConnection();
if (conn!=null){
conn.close();
conn=null;
}
}
}