diff --git a/src/org/gcube/vremanagement/vremodeler/db/DBInterface.java b/src/org/gcube/vremanagement/vremodeler/db/DBInterface.java new file mode 100644 index 0000000..f074172 --- /dev/null +++ b/src/org/gcube/vremanagement/vremodeler/db/DBInterface.java @@ -0,0 +1,151 @@ +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 org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.diligentproject.vdlgeneratorservice.model.impl.ModelService; + +/** + * + * @author lucio + * + */ +public class DBInterface { + + + private static Log logger =LogFactory.getLog(ModelService.class.getName()); + + private static Connection conn; + + private static String dbFile = System.getenv("GLOBUS_LOCATION") + File.separator + "etc" + File.separator + "org_diligentproject_vdlgeneratorservice_model" + File.separator + "hsqldb" + File.separator + "vdldb"; + + + /** + * + * @return + * @throws SQLException + */ + public static Connection connect() throws SQLException{ + + if(conn==null) + { + // Load the HSQL Database Engine JDBC driver + // hsqldb.jar should be in the class path or made part of the current jar + 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 + conn = DriverManager.getConnection("jdbc:hsqldb:file:" + + dbFile, // filenames + "sa", // username + ""); // password + } + return conn; + + } + + + /** + * + * @param query + */ + public static synchronized void ExecuteUpdate(String query) throws RemoteException{ + Statement st = null; + + try{ + st = conn.createStatement(); // statement objects can be reused with + st.executeUpdate(query); + st.close(); + }catch(SQLException e){logger.error("error executing Query");throw new RemoteException("error creating SQL statement",e);} + } + + /** + * + * @param table + * @param values + * @throws RemoteException + */ + public static synchronized void InsertInto(String table, String[][] values, boolean deleteOne) throws RemoteException { + + if (values==null) return; + Statement st = null; + ResultSet rs = null; + try{ + st = conn.createStatement(); // statement objects can be reused with + }catch(SQLException e){logger.error("error creating SQL statement");throw new RemoteException("error creating SQL statement",e);} + String insertQuery=""; + + for (String[] row: values) + { + insertQuery="INSERT INTO "+table.toUpperCase()+" VALUES("; + try{ + + int decr=0; + if (deleteOne) decr=-1; + for (int i=0; i returnedValues= new ArrayList(); + ArrayList tempArray; + + + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + + DocumentBuilder builder; + try { + builder = factory.newDocumentBuilder(); + + + StringReader reader = new StringReader(results); + InputSource source = new InputSource(reader); + Document domDoc; + domDoc = builder.parse(source); + Element child, subChild; + Element root= domDoc.getDocumentElement(); + NodeList childRoot= root.getElementsByTagName(tag); + if (childRoot.getLength()==0) return null; + for (int i=0; i(); + for (int k=0; k{$CollectionProfile/UniqueID/string()}{$CollectionProfile/Profile/Name/string()}{$CollectionProfile/Profile/Description/string()}{$CollectionProfile/Profile/NumberOfMembers/string()}{$CollectionProfile/Profile/CreationTime/string()}{$CollectionProfile/Profile/LastUpdateTime/string()}"; + String results=makeQueryDIS(epr, cred, collectionQuery); + logger.debug(results); + String[][] resultsParsed= parseResults(results, "r"); + //test + + try{ + DBInterface.connect(); + DBInterface.InsertInto("collection", resultsParsed, false); + }catch (SQLException e){logger.error("VDLModel: DB error "+e.getMessage()); throw new RemoteException(e.getMessage(),e); } + } + + + private static String[] ParseTP(String[] tp){ + logger.debug("ParseTP start"); + + String[] schemaNameURI=tp[1].split("="); + String lng="anylanguage"; + logger.debug("MetadataFormatParsed: "+schemaNameURI[0]+ ", "+schemaNameURI[1]+", "+lng); + return new String[]{tp[0],schemaNameURI[0],schemaNameURI[1],lng}; + } + + /** + * + * @param item + * @param container + * @return + */ + private static String ContainsControl(String[] item, ArrayList container){ + for(String[] cont: container){ + logger.debug("MDFormat: "+cont[1]+" "+cont[2]); + logger.debug("MDFormat: confr "+cont[1]+" "+cont[2]); + if((cont[1].compareTo(item[1])==0) && (cont[2].compareTo(item[2])==0)) //&& ((cont[3].compareTo("anylanguage")==0) || cont[3].compareTo(item[3])==0) + return cont[0]; + + } + logger.debug("MDFormat: not yet present"); + return null; + } + + /** + * + * @param epr + * @throws RemoteException + */ + private static void insertMetadataCollection(EndpointReferenceType epr, ExtendedGSSCredential cred) throws RemoteException { + ResultSet res=null; + String tempQuery=""; + try { + DBInterface.connect(); + res = DBInterface.queryDB("select id from collection"); + while(res.next()) + tempQuery+=" $CollectionProfile/Profile/RelatedCollection/CollectionID/string() eq '"+res.getString(1)+"' or "; + tempQuery=tempQuery.substring(0, tempQuery.length()-4); + } catch (SQLException e1) { + logger.error("VDLModel: initialization error on inserMetadataCollection"); + throw new RemoteException("VDLModel: initialization error on inserMetadataCollection",e1); + } + + + String MDcollectionQuery= "for $CollectionProfile in collection(\"/db/Profiles/MetadataCollection\")//Document/Data/child::*[local-name()='Profile']/DILIGENTResource where "+tempQuery+" return {$CollectionProfile/UniqueID/string()}{$CollectionProfile/Profile/Name/string()}{$CollectionProfile/Profile/Description/string()}{$CollectionProfile/Profile/RelatedCollection/CollectionID/string()}"; + String results=makeQueryDIS(epr, cred, MDcollectionQuery); + ArrayList MDFormatArray=new ArrayList(); + ArrayList MDNativeArray=new ArrayList(); + ArrayList MDDerivableArray=new ArrayList(); + String[][] resultsParsed= parseResults(results, "r"); + String uuid; + String metadataFormatQuery; + String[] singleNativeMDF; + String[] singleDerivableMDF; + /* + MetadataBrokerPortType metadataBroker=null; + MetadataBrokerServiceAddressingLocator mbLoc; + boolean brokerConnected=true; + + //connecting to metadata broker service + try{ + RunningInstanceManager ri=DISHLSClient.getRunningInstanceManager(cred, epr); + + String[] eprs= ri.getEPRsRIFromClassAndName("MetadataManagement", "MetadataBrokerService", "diligentproject/metadatamanagement/metadatabrokerservice", cred, epr); + + + + EndpointReferenceType eprTemp= new EndpointReferenceType(); + eprTemp.setAddress(new AttributedURI(eprs[0])); + + //metadata Broker Service connection + mbLoc = new MetadataBrokerServiceAddressingLocator() ; + + metadataBroker=mbLoc.getMetadataBrokerPortTypePort(eprTemp); + + if (ModelFactoryService.isSecurityEnabled){ + ConfigureSecurity.setSecurity(((javax.xml.rpc.Stub) metadataBroker), true, cred, GSIConstants.GSI_MODE_FULL_DELEG ); + } + + + + }catch(Exception e){ + logger.error("error contacting metadata broker Service "+e.getMessage()); + //e.printStackTrace(); + brokerConnected=false; + } + */ + for(String[] singleColl: resultsParsed) + { + //generate the uid for MetadataFormat + uuid=uuidMFGEN.nextUUID(); + String existID; + //retriving the metadataFormat for the current MDCollection + metadataFormatQuery="for $MetadataFormat in collection(\"/db/Profiles/MetadataCollection\")//Document/Data/child::*[local-name()='Profile']/DILIGENTResource where $MetadataFormat/UniqueID/string() eq '"+singleColl[0]+"' return "+uuid+"{$MetadataFormat/Profile/MetadataFormat/Name/string()}{$MetadataFormat/Profile/MetadataFormat/SchemaURI/string()}{$MetadataFormat/Profile/MetadataFormat/Language/string()}"; + results=makeQueryDIS(epr, cred, metadataFormatQuery); + String[][] resultsMDFParsed= parseResults(results, "r"); + if((existID=ContainsControl(resultsMDFParsed[0], MDFormatArray))==null) + { + MDFormatArray.add(resultsMDFParsed[0]); + existID=uuid; + } + //keep the CollectionID and the MDFID to insert into NAtiveMDF + singleNativeMDF=new String[3]; + singleNativeMDF[0]=singleColl[0]; + singleNativeMDF[1]=existID; + singleNativeMDF[2]=singleColl[3]; //i need it to evaluate doble results + MDNativeArray.add(singleNativeMDF); + + /* + //Retrive Derivable MDF + if (brokerConnected){ + try{ + FindPossibleTransformationPrograms request= new FindPossibleTransformationPrograms(); + TPIOType tpin= TPIOType.fromParams("collection", resultsMDFParsed[0][3],resultsMDFParsed[0][1]+"="+resultsMDFParsed[0][2] , ""); + request.setInputFormat(tpin.toXMLString()); + request.setOutputFormat(null); + FindPossibleTransformationProgramsResponse response=metadataBroker.findPossibleTransformationPrograms(request); + String[] tp=response.getTransformationProgram(); + String[] parsedTP; + logger.debug("VDLModel Derivable : "+tp.length); + for(String singleTP: tp){ + try{ + logger.debug("MDF Derivable : Single tp is parsing "); + parsedTP=ParseTP(singleTP); + if (parsedTP!=null){ + String temp; + //temp will contains the MDF id if it exists + if((temp=ContainsControl(parsedTP, MDFormatArray))==null){ + logger.debug("MDF Derivable : not exist "); + // if it doesn't exists, insert it into database else + //add it only on DerivableMDF with MDFuid + uuid=uuidMFGEN.nextUUID(); + parsedTP[0]=uuid; + MDFormatArray.add(parsedTP); + MDDerivableArray.add(new String[]{singleColl[0], uuid, "nothing"}); + }else{ + MDDerivableArray.add(new String[]{singleColl[0], temp , "nothing"}); + logger.debug("MDF Derivable : exist "); + } + + } + + + }catch(Exception e) {logger.error("error in Derivable MDF parsing "+e.getMessage()); e.printStackTrace();} + } + }catch (Exception e1){logger.error("error retreiving metadataBroker "+e1.getMessage()); + e1.printStackTrace(); + } + } + */ + + //trying to parse TransformationProgram from DIS-IC + existID=null; + String queryDerivableMDF=""; + try{ + queryDerivableMDF="for $tp in collection(\"/db/Profiles/TransformationProgram\")//Document/Data/child::*[local-name()='Profile']/DILIGENTResource where $tp/Profile/TransformationProgram/Input/Type/string() eq 'collection' and $tp/Profile/TransformationProgram/Input/Schema/string() eq '"+resultsMDFParsed[0][1]+"="+resultsMDFParsed[0][2]+"' and $tp/Profile/TransformationProgram/Output/Type/string() eq 'collection' return " + + "{$tp/UniqueID/string()}{$tp/Profile/TransformationProgram/Output/Schema/string()}anylanguage"; + results=makeQueryDIS(epr, cred, queryDerivableMDF); + String[][] resultsDerivableMDFParsed= parseResults(results, "r"); + for (String[] singleMDFDerived: resultsDerivableMDFParsed){ + try{ + String tpID=singleMDFDerived[0]; + uuid=uuidMFGEN.nextUUID(); + singleMDFDerived[0]=uuid; + String[] parsedTP=ParseTP(singleMDFDerived); + if((existID=ContainsControl(parsedTP, MDFormatArray))==null) + { + MDFormatArray.add(parsedTP); + existID=uuid; + } + + singleDerivableMDF=new String[4]; + singleDerivableMDF[0]=singleColl[0]; + singleDerivableMDF[1]=existID; + singleDerivableMDF[2]=tpID; + singleDerivableMDF[3]=singleColl[3]; + MDDerivableArray.add(singleDerivableMDF); + }catch(Exception e1){logger.error("VDLModel: error parsing derivable"); e1.printStackTrace();} + + } + }catch(Exception e){logger.error("VDLModel: error retriving Derivable MDF for collection "+singleColl[0]); e.printStackTrace();} + + } + + //da cambiare (scandaloso) + ArrayList tempRemove= new ArrayList(); + for(String[] tempDeriv:MDDerivableArray ){ + for (String[] tempNative: MDNativeArray){ + if (tempDeriv[3].compareTo(tempNative[2])==0 && (tempDeriv[1].compareTo(tempNative[1])==0)){ + tempRemove.add(tempDeriv); + logger.debug("removed Doubled value"); + } + } + } + for (String[] toRemove:tempRemove ) MDDerivableArray.remove(toRemove); + + try{ + DBInterface.connect(); + DBInterface.InsertInto("mdcollection", resultsParsed, false); + DBInterface.InsertInto("mdformat", MDFormatArray.toArray(new String[0][0]), false); + DBInterface.InsertInto("nativemdf", MDNativeArray.toArray(new String[0][0]), true); + DBInterface.InsertInto("derivablemdf",MDDerivableArray.toArray(new String[0][0]), true); + }catch (SQLException e){logger.error("error DB"); e.printStackTrace(); throw new RemoteException(e.getMessage(),e); } + + } + + /** + * + * @param epr + * @throws RemoteException + */ + private static void insertCS(EndpointReferenceType epr, ExtendedGSSCredential cred) throws RemoteException { + String csQuery= "for $CS in collection(\"/db/Profiles/CS\")//Document/Data/child::*[local-name()='Profile']/DILIGENTResource return {$CS/UniqueID/string()}{$CS/Profile/ProcessName/string()}{$CS/Profile/Description/string()}"; + String results=makeQueryDIS(epr, cred, csQuery); + + String[][] resultsParsed= parseResults(results, "r"); + try{ + DBInterface.connect(); + DBInterface.InsertInto("cs", resultsParsed, false); + }catch (SQLException e){logger.error("error DB"); e.printStackTrace(); throw new RemoteException(e.getMessage(),e); } + } + + + private static void insertQuality(EndpointReferenceType epr) throws RemoteException { + + } + + + + private static void insertDHN(EndpointReferenceType epr, ExtendedGSSCredential cred) throws RemoteException { + String dhnQuery="for $DHN in collection(\"/db/Profiles/DHN\")//Document/Data/child::*[local-name()='Profile']/DILIGENTResource where $DHN/Profile/DHNDescription/Type/string() eq 'Dynamic' or $DHN/Profile/DHNDescription/Type/string() eq 'SelfCleaning' return {$DHN/UniqueID/string()}{$DHN/Profile/DHNDescription/Name/string()}" + + "{$DHN/Profile/DHNDescription/SecurityEnabled/string(@value)}{$DHN/Profile/DHNDescription/Uptime/string()}{$DHN/Profile/DHNDescription/MainMemory/string(@VirtualAvailable)}{string($DHN/Profile/DHNDescription/MainMemory/string(@VirtualSize))}" + + "{$DHN/Profile/DHNDescription/LocalAvailableSpace/string()}{$DHN/Profile/Site/Location/string()}{$DHN/Profile/Site/Country/string()}{$DHN/Profile/Site/Domain/string()}"; + + String results=makeQueryDIS(epr, cred, dhnQuery); + String[][] resultsDHNParsed= parseResults(results, "r"); + String RIQuery="for $RI in collection(\"/db/Profiles/RunningInstance\")//Document/Data/child::*[local-name()='Profile']/DILIGENTResource return {$RI/UniqueID/string()}{$RI/Profile/ServiceName/string()}"; + results=makeQueryDIS(epr, cred, RIQuery); + + String[][] resultsRIParsed= parseResults(results, "r"); + + + ArrayList DNHRelatedRIArray= new ArrayList(); + for (String[] singleDHN:resultsDHNParsed) + { + String[] riID; + try { + riID=DISHLSClient.getRunningInstanceManager(cred,epr).getAllRunningInstancesOnDHN(singleDHN[0], cred, epr); + } catch (DISHLSClientException e) { + logger.error("VDLModel: Error initializing DB with DHN and RI (DISHLSClient error)"); + throw new RemoteException("Error querying DIS-IP (DISHLSClient error)", e); + } catch (DISHLSCredentialException e) { + logger.error("VDLModel: Error initializing DB with DHN and RI (Credential error)"); + throw new RemoteException("Error querying DIS-IP (Credential error)", e); + } + + //retreiving related RIID with DHNID + String[] temp; + for (String id: riID){ + temp=new String[2]; + temp[0]=singleDHN[0]; + temp[1]=id; + DNHRelatedRIArray.add(temp); + } + + } + + /* + ArrayList RIRelatedPKGArray= new ArrayList(); + for (String[] singleRI: resultsRIParsed){ + + } + */ + + try{ + DBInterface.connect(); + DBInterface.InsertInto("dhn", resultsDHNParsed, false); + DBInterface.InsertInto("runninginstance", resultsRIParsed, false); + DBInterface.InsertInto("dhnrelatedri", DNHRelatedRIArray.toArray(new String[0][0]), false); + }catch (SQLException e){logger.error("error DB"); e.printStackTrace(); throw new RemoteException(e.getMessage(),e); } + + } + + + private static void insertServices(EndpointReferenceType epr, ExtendedGSSCredential cred) throws RemoteException { + + String csQuery= "for $SERVICE in collection(\"/db/Profiles/Service\")//Document/Data/child::*[local-name()='Profile']/DILIGENTResource return {$SERVICE/UniqueID/string()}{$SERVICE/Profile/Name/string()}{$SERVICE/Profile/Class/string()}"; + String results=makeQueryDIS(epr, cred, csQuery); + + String[][] resultsParsed= parseResults(results, "r"); + try{ + DBInterface.connect(); + DBInterface.InsertInto("relatedserviceid", resultsParsed, false); + }catch (SQLException e){logger.error("error DB"); e.printStackTrace(); throw new RemoteException(e.getMessage(),e); } + } + + public static void updateServices(EndpointReferenceType epr, ExtendedGSSCredential cred, String resourceID, int op) throws RemoteException { + switch (op){ + case 0: + { + String serviceUpdateQuery="for $SERVICE in collection(\"/db/Profiles/Service\")//Document/Data/child::*[local-name()='Profile']/DILIGENTResource where $SERVICE/UniqueID/string() eq '"+op+"' return {$SERVICE/UniqueID/string()}{$SERVICE/Profile/Name/string()}{$SERVICE/Profile/Class/string()}"; + String results=makeQueryDIS(epr, cred, serviceUpdateQuery); + String[][] resultsParsed= parseResults(results, "r"); + try{ + DBInterface.connect(); + DBInterface.InsertInto("relatedserviceid", resultsParsed, false); + }catch (SQLException e){logger.error("error DB"); e.printStackTrace(); throw new RemoteException(e.getMessage(),e); } + break; + } + case 1: + { + try{ + DBInterface.connect(); + DBInterface.ExecuteUpdate("Delete from relatedserviceid where id='"+resourceID+"'"); + }catch (SQLException e){logger.error("error DB"); e.printStackTrace(); throw new RemoteException(e.getMessage(),e); } + break; + } + } + } + + public static void updateCollection(EndpointReferenceType epr, ExtendedGSSCredential cred, String resourceID, int op) throws RemoteException { + switch (op){ + case 0: + { + String collectionQuery= "for $CollectionProfile in collection(\"/db/Profiles/Collection\")//Document/Data/child::*[local-name()='Profile']/DILIGENTResource where $CollectionProfile/Profile/IsUserCollection[string(@value) eq \"true\"] and $CollectionProfile/UniqueID/string() eq '"+resourceID+"' return {$CollectionProfile/UniqueID/string()}{$CollectionProfile/Profile/Name/string()}{$CollectionProfile/Profile/Description/string()}{$CollectionProfile/Profile/NumberOfMembers/string()}{$CollectionProfile/Profile/CreationTime/string()}{$CollectionProfile/Profile/LastUpdateTime/string()}"; + String results=makeQueryDIS(epr, cred, collectionQuery); + String[][] resultsParsed= parseResults(results, "r"); + + try{ + DBInterface.connect(); + DBInterface.InsertInto("collection", resultsParsed, false); + }catch (SQLException e){logger.error("error updating collection on DB"); e.printStackTrace(); throw new RemoteException(e.getMessage(),e); } + break; + } + case 1: + { + try{ + DBInterface.connect(); + DBInterface.ExecuteUpdate("Delete from collection where id='"+resourceID+"'"); + }catch (SQLException e){logger.error("error updating collection on DB"); e.printStackTrace(); throw new RemoteException(e.getMessage(),e); } + break; + } + } + } + + public static void updateDHN(EndpointReferenceType epr, ExtendedGSSCredential cred, String resourceID, int op) throws RemoteException { + switch (op){ + case 0: + { + String dhnQuery="for $DHN in collection(\"/db/Profiles/DHN\")//Document/Data/child::*[local-name()='Profile']/DILIGENTResource where ($DHN/Profile/DHNDescription/Type/string() eq 'Dynamic' or $DHN/Profile/DHNDescription/Type/string() eq 'SelfCleaning') and $DHN/UniqueID/string() eq '"+resourceID+"' return {$DHN/UniqueID/string()}{$DHN/Profile/DHNDescription/Name/string()}" + + "{$DHN/Profile/DHNDescription/SecurityEnabled/string(@value)}{$DHN/Profile/DHNDescription/Uptime/string()}{$DHN/Profile/DHNDescription/MainMemory/string(@VirtualAvailable)}{string($DHN/Profile/DHNDescription/MainMemory/string(@VirtualSize))}" + + "{$DHN/Profile/DHNDescription/LocalAvailableSpace/string()}{$DHN/Profile/Site/Location/string()}{$DHN/Profile/Site/Country/string()}{$DHN/Profile/Site/Domain/string()}"; + + String results=makeQueryDIS(epr, cred, dhnQuery); + String[][] resultsDHNParsed= parseResults(results, "r"); + ArrayList DNHRelatedRIArray= new ArrayList(); + + String RIQuery="for $RI in collection(\"/db/Profiles/RunningInstance\")//Document/Data/child::*[local-name()='Profile']/DILIGENTResource return {$RI/UniqueID/string()}{$RI/Profile/ServiceName/string()}"; + results=makeQueryDIS(epr, cred, RIQuery); + + String[][] resultsRIParsed= parseResults(results, "r"); + + String[] riID; + try { + riID=DISHLSClient.getRunningInstanceManager(cred,epr).getAllRunningInstancesOnDHN(resourceID, cred, epr); + } catch (DISHLSClientException e) { + logger.error("VDLModel: Error initializing DB with DHN and RI (DISHLSClient error)"); + throw new RemoteException("Error querying DIS-IP (DISHLSClient error)", e); + } catch (DISHLSCredentialException e) { + logger.error("VDLModel: Error initializing DB with DHN and RI (Credential error)"); + throw new RemoteException("Error querying DIS-IP (Credential error)", e); + } + + + //retreiving related RIID with DHNID + String[] temp; + for (String id: riID){ + temp=new String[2]; + temp[0]=resourceID; + temp[1]=id; + DNHRelatedRIArray.add(temp); + } + + try{ + DBInterface.connect(); + DBInterface.InsertInto("dhn", resultsDHNParsed, false); + DBInterface.InsertInto("runninginstance", resultsRIParsed, false); + DBInterface.InsertInto("dhnrelatedri", DNHRelatedRIArray.toArray(new String[0][0]), false); + }catch (SQLException e){logger.error("error updating DHN on DB"); e.printStackTrace(); throw new RemoteException(e.getMessage(),e); } + break; + } + case 1: + { + try{ + DBInterface.connect(); + DBInterface.ExecuteUpdate("Delete from dhn where id='"+resourceID+"'"); + DBInterface.ExecuteUpdate("Delete from dhnrelatedri where DHNID='"+resourceID+"'"); + }catch (SQLException e){logger.error("error updating DHN on DB"); e.printStackTrace(); throw new RemoteException(e.getMessage(),e); } + break; + } + } + } + + public static void updateCS(EndpointReferenceType epr, ExtendedGSSCredential cred, String resourceID, int op) throws RemoteException { + switch (op){ + case 0: + { + String csQuery= "for $CS in collection(\"/db/Profiles/CS\")//Document/Data/child::*[local-name()='Profile']/DILIGENTResource where $CS/UniqueID/string() eq '"+resourceID+"' return {$CS/UniqueID/string()}{$CS/Profile/ProcessName/string()}{$CS/Profile/Description/string()}"; + String results=makeQueryDIS(epr, cred, csQuery); + + String[][] resultsParsed= parseResults(results, "r"); + try{ + DBInterface.connect(); + DBInterface.InsertInto("cs", resultsParsed, false); + }catch (SQLException e){logger.error("error updating CS on DB"); e.printStackTrace(); throw new RemoteException(e.getMessage(),e); } + break; + } + case 1: + { + try{ + DBInterface.connect(); + DBInterface.ExecuteUpdate("Delete from cs where id='"+resourceID+"'"); + }catch (SQLException e){logger.error("error updating CS on DB"); e.printStackTrace(); throw new RemoteException(e.getMessage(),e); } + break; + } + } + } + + public static void updateRI(EndpointReferenceType epr, ExtendedGSSCredential cred, String resourceID, int op) throws RemoteException { + switch (op){ + case 0: + { + String RIQuery="for $RI in collection(\"/db/Profiles/RunningInstance\")//Document/Data/child::*[local-name()='Profile']/DILIGENTResource where $RI/UniqueID/string() eq '"+resourceID+"' return {$RI/UniqueID/string()}{$RI/Profile/ServiceName/string()}"; + String relatedDHNQuery="for $RI in collection(\"/db/Profiles/RunningInstance\")//Document/Data/child::*[local-name()='Profile']/DILIGENTResource where $RI/UniqueID/string() eq '"+resourceID+"' return {$RI/Profile/DHN/string(@UniqueID)}{$RI/UniqueID/string()}"; + String results=makeQueryDIS(epr, cred, RIQuery); + String resultsRelatedDhn=makeQueryDIS(epr, cred, relatedDHNQuery); + String[][] resultsRIParsed= parseResults(results, "r"); + String[][] resultRelatedDhn= parseResults(resultsRelatedDhn, "r"); + try{ + DBInterface.connect(); + DBInterface.InsertInto("runninginstance", resultsRIParsed, false); + DBInterface.InsertInto("dhnrelatedri", resultRelatedDhn, false); + }catch (SQLException e){logger.error("error updating RI on DB"); e.printStackTrace(); throw new RemoteException(e.getMessage(),e); } + break; + } + case 1: + { + try{ + DBInterface.connect(); + DBInterface.ExecuteUpdate("Delete from runninginstance where id='"+resourceID+"'"); + DBInterface.ExecuteUpdate("Delete from dhnrelatedri where RIID='"+resourceID+"'"); + }catch (SQLException e){logger.error("error updating RI on DB"); e.printStackTrace(); throw new RemoteException(e.getMessage(),e); } + break; + } + } + } + + + +} diff --git a/src/org/gcube/vremanagement/vremodeler/impl/ModelFactoryService.java b/src/org/gcube/vremanagement/vremodeler/impl/ModelFactoryService.java new file mode 100644 index 0000000..f75d7e8 --- /dev/null +++ b/src/org/gcube/vremanagement/vremodeler/impl/ModelFactoryService.java @@ -0,0 +1,215 @@ +package org.gcube.vremanagement.vremodeler.impl; + +import java.io.StringReader; +import java.net.URL; +import java.rmi.RemoteException; +import java.sql.ResultSet; +import java.util.ArrayList; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NameNotFoundException; +import javax.naming.NamingException; +import javax.xml.namespace.QName; +import javax.xml.rpc.server.ServiceLifecycle; + +import org.apache.axis.message.addressing.AttributedURI; +import org.apache.axis.message.addressing.EndpointReferenceType; +import org.gcube.common.core.contexts.GCUBEServiceContext; +import org.gcube.common.core.porttypes.GCUBEStartupPortType; +import org.globus.wsrf.Constants; +import org.globus.wsrf.NoResourceHomeException; +import org.globus.wsrf.ResourceContext; +import org.globus.wsrf.ResourceContextException; +import org.globus.wsrf.ResourceHome; +import org.globus.wsrf.ResourceKey; +import org.globus.wsrf.container.ServiceHost; +import org.globus.wsrf.encoding.ObjectDeserializer; +import org.globus.wsrf.impl.SimpleResourceKey; +import org.globus.wsrf.tests.basic.CreateResource; +import org.globus.wsrf.tests.basic.CreateResourceResponse; +import org.globus.wsrf.utils.AddressingUtils; +import org.gridforum.jgss.ExtendedGSSCredential; +import org.oasis.wsrf.lifetime.Destroy; +import org.xml.sax.InputSource; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + + + +public class ModelFactoryService extends GCUBEStartupPortType{ + + @Override + protected GCUBEServiceContext getServiceContext() { + // TODO Auto-generated method stub + return null; + } + + /* Implementation of createResource Operation */ + public CreateResourceResponse createResource(CreateResource request) throws RemoteException { + + + + return null; + } + + + /** + * return the existing DL Name + * + * @param request void + * @return array of string qith exististin dl names + * @throws RemoteException - + */ + public GetExistingNamesResponseMessage getExistingNamesDLs(GetExistingNamesRequestMessage request) throws RemoteException { + GetExistingNamesResponseMessage response=new GetExistingNamesResponseMessage(); + ArrayList toReturn= new ArrayList(); + ResultSet res=null; + ExtendedGSSCredential cred; + if (isSecurityEnabled){ + try { + cred=credentialsListener.getCredentials(new NAL().getDefaultVO()); + if (cred==null) logger.debug("null cerdentials"); + logger.debug("VDLModel - initDB - with credential"); + } catch (Exception e) { + logger.debug("VDLModel - initDB - null credential"); + cred=null; + } + }else cred=null; + try{ + DBInterface.connect(); + res= DBInterface.queryDB("select DL.name from DL;"); + while (res.next()) toReturn.add(res.getString(1)); + String customXquery="for $query in collection(\"/db/Profiles/VDL\")//Document/Data/child::*[local-name()='Profile']/DILIGENTResource return $query/Profile/Name/string()"; + String queryResult= DISHLSClient.getGeneralQueryManager(cred, factoryEPR).queryDISIC(customXquery,cred, factoryEPR); + logger.debug("VDL get Name QUERY: "+queryResult); + }catch(Exception e) {logger.error("VDL Model: error on DB"); throw new RemoteException("VDLModel: error on DB",e);} + response.setNames(toReturn.toArray(new String[0])); + return response; + } + + + + + /** + * Initialize the DB + * + * @param request void + * @return void + * @throws RemoteException remote exception + */ + public VoidType initDB(VoidType request) throws RemoteException { + logger.debug("initDB method"); + ExtendedGSSCredential cred; + if (isSecurityEnabled){ + try { + cred=credentialsListener.getCredentials(new NAL().getDefaultVO()); + if (cred==null) logger.debug("null cerdentials"); + logger.debug("VDLModel - initDB - with credential"); + } catch (Exception e) { + logger.debug("VDLModel - initDB - null credential"); + cred=null; + } + }else cred=null; + + new InitThread(factoryEPR, cred).start(); + + return new VoidType(); + } + + + /** + * + * @param request void + * @return String + * @throws RemoteException - + */ + public String getAllDLs(GetAllDLsMessageRequest request) throws RemoteException{ + String toReturn = null; + ResultSet res=null; + try{ + DBInterface.connect(); + res= DBInterface.queryDB("select DL.name, DL.description, DL.status, DL.epr from DL;"); + }catch(Exception e) {logger.error("VDL Model: error on DB"); throw new RemoteException("VDLModel: error on DB",e);} + try { + toReturn=XMLUtil.PrepareAllDLsXML(res); + } catch (Exception e) { + logger.error("VDLModel parsing error in function getAllDLs "+e.getMessage()); + throw new RemoteException("VDLModel parsing error in function getAllDLs",e); + } + return toReturn; + + } + + protected ResourceHome getInstanceResourceHome() throws NoResourceHomeException, ResourceContextException { + ResourceHome home; + + ResourceContext ctx; + + logger.debug("DILIGENT: getInstanceResourceHome on ModelFactoryService"); + + ctx = ResourceContext.getResourceContext(); + + logger.debug("DILIGENT: Resource Context = " + ctx.toString() + "on getInstanceResourceHome on ModelFactoryService"); + + String homeLoc = Constants.JNDI_SERVICES_BASE_NAME + ctx.getService() + "/instanceHome"; + + try { + Context initialContext = new InitialContext(); + home = (ResourceHome) initialContext.lookup(homeLoc); + } catch (NameNotFoundException e) { + throw new NoResourceHomeException(); + } catch (NamingException e) { + throw new ResourceContextException("", e); + } + + return home; + } + + + /** + * + * remove the DL instance + * + * @param request the id of DL to remove + * @return void + * @throws RemoteException - + */ + public RemoveDLResponseMessage removeDL(String request) throws RemoteException{ + + + ResourceManager rMan; + try{ + ResultSet res=DBInterface.queryDB("Select DL.epr from DL where DL.id='"+request+"';"); + EndpointReferenceType dlEpr; + + + if (res.next()){ + StringReader stringReader = new StringReader(res.getString(1)); + InputSource inputSource = new InputSource(stringReader); + dlEpr = (EndpointReferenceType) ObjectDeserializer.deserialize(inputSource, EndpointReferenceType.class); + }else throw new Exception("DL not retreived in DB"); + + ModelServiceAddressingLocator msal=new ModelServiceAddressingLocator(); + ModelPortType vdlModelPT=msal.getModelPortTypePort(dlEpr); + + if (ModelFactoryService.isSecurityEnabled){ + ExtendedGSSCredential cred=org.gcube.vremanagement.vremodeler.impl.credentialsListener.getCredentials((new NAL()).getDefaultVO()); + rMan= DISIP.getResourceManager(cred,dlEpr); + ConfigureSecurity.setSecurity(((javax.xml.rpc.Stub) vdlModelPT), cred); + }else rMan= DISIP.getResourceManager(null,dlEpr); + + rMan.remove(dlEpr); + vdlModelPT.destroy(new Destroy()); + DBInterface.ExecuteUpdate("DELETE FROM DL where DL.id='"+request+"';"); + + }catch(Exception e){ + logger.error("VDLModel: "+e.getMessage()); + throw new RemoteException(e.getMessage(), e);} + return new RemoveDLResponseMessage(); + } + + + + +} diff --git a/src/org/gcube/vremanagement/vremodeler/impl/ModelerContext.java b/src/org/gcube/vremanagement/vremodeler/impl/ModelerContext.java new file mode 100644 index 0000000..57916cd --- /dev/null +++ b/src/org/gcube/vremanagement/vremodeler/impl/ModelerContext.java @@ -0,0 +1,25 @@ +package org.gcube.vremanagement.vremodeler.impl; + +import org.gcube.common.core.contexts.GCUBEPortTypeContext; +import org.gcube.common.core.contexts.GCUBEServiceContext; + +public class ModelerContext extends GCUBEPortTypeContext{ + + @Override + public String getJNDIName() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getNamespace() { + // TODO Auto-generated method stub + return null; + } + + @Override + public GCUBEServiceContext getServiceContext() { + return null; + } + +} diff --git a/src/org/gcube/vremanagement/vremodeler/impl/ModelerHome.java b/src/org/gcube/vremanagement/vremodeler/impl/ModelerHome.java new file mode 100644 index 0000000..0c04ec6 --- /dev/null +++ b/src/org/gcube/vremanagement/vremodeler/impl/ModelerHome.java @@ -0,0 +1,14 @@ +package org.gcube.vremanagement.vremodeler.impl; + +import org.gcube.common.core.contexts.GCUBEStatefulPortTypeContext; +import org.gcube.common.core.state.GCUBEWSHome; + +public class ModelerHome extends GCUBEWSHome{ + + @Override + public GCUBEStatefulPortTypeContext getPortTypeContext() { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/src/org/gcube/vremanagement/vremodeler/impl/ModelerResource.java b/src/org/gcube/vremanagement/vremodeler/impl/ModelerResource.java new file mode 100644 index 0000000..b2c615d --- /dev/null +++ b/src/org/gcube/vremanagement/vremodeler/impl/ModelerResource.java @@ -0,0 +1,5 @@ +package org.gcube.vremanagement.vremodeler.impl; + +public class ModelerResource { + +} diff --git a/src/org/gcube/vremanagement/vremodeler/impl/ServiceContext.java b/src/org/gcube/vremanagement/vremodeler/impl/ServiceContext.java new file mode 100644 index 0000000..d8b7354 --- /dev/null +++ b/src/org/gcube/vremanagement/vremodeler/impl/ServiceContext.java @@ -0,0 +1,13 @@ +package org.gcube.vremanagement.vremodeler.impl; + +import org.gcube.common.core.contexts.GCUBEServiceContext; + +public class ServiceContext extends GCUBEServiceContext{ + + @Override + protected String getJNDIName() { + // TODO Auto-generated method stub + return null; + } + +}