package org.gcube.vremanagement.vremodeler.impl; import java.rmi.RemoteException; import java.sql.Date; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import javax.xml.namespace.QName; import javax.xml.rpc.ServiceException; import org.gcube.common.core.contexts.GHNContext; import org.gcube.common.core.faults.GCUBEFault; import org.gcube.common.core.informationsystem.client.AtomicCondition; import org.gcube.common.core.informationsystem.client.ISClient; import org.gcube.common.core.informationsystem.client.queries.GCUBERIQuery; import org.gcube.common.core.resources.GCUBECollection; import org.gcube.common.core.resources.GCUBEMCollection; import org.gcube.common.core.resources.GCUBERunningInstance; import org.gcube.common.core.resources.impl.kxml.KGCUBEResource; import org.gcube.common.core.types.VOID; import org.gcube.common.core.utils.logging.GCUBELog; import org.gcube.vremanagement.vremanager.stubs.vremanager.AddResourcesParameters; import org.gcube.vremanagement.vremanager.stubs.vremanager.ResourceItem; import org.gcube.vremanagement.vremanager.stubs.vremanager.ResourceList; import org.gcube.vremanagement.vremanager.stubs.vremanager.ScopeOption; import org.gcube.vremanagement.vremanager.stubs.vremanager.ServiceItem; import org.gcube.vremanagement.vremanager.stubs.vremanager.VREManagerPortType; import org.gcube.vremanagement.vremanager.stubs.vremanager.service.VREManagerServiceAddressingLocator; import org.gcube.vremanagement.vremodeler.db.DBInterface; import org.gcube.vremanagement.vremodeler.stubs.CollectionArray; import org.gcube.vremanagement.vremodeler.stubs.FunctionalityIDArray; import org.gcube.vremanagement.vremodeler.stubs.GHNArray; import org.gcube.vremanagement.vremodeler.stubs.SetMDFormatArgs; import org.gcube.vremanagement.vremodeler.stubs.VRERequest; import org.gcube.vremanagement.vremanager.stubs.vremanager.OptionsParameters; import org.globus.wsrf.ResourceException; import org.globus.wsrf.encoding.ObjectSerializer; import org.globus.wsrf.encoding.SerializationException; public class ModelerService { private static final GCUBELog logger = new GCUBELog(ModelerService.class.getName()); protected ModelerResource getResource() throws ResourceException{ return (ModelerResource) ModelerContext.getPortTypeContext().getWSHome().find(); } /** * * @param request void * @return VoidType * @throws RemoteException - * */ public void setVREModel(VRERequest request) throws GCUBEFault{ Date dateFrom=null, dateTo=null; ResultSet res=null; try { res=DBInterface.queryDB("select * from VRE where VRE.id='"+getResource().getId()+"'; "); if(res.next()) { dateFrom=new Date(request.getStartTime()); dateTo=new Date(request.getEndTime()); DBInterface.queryDB("update VRE set name='"+request.getVREName()+"', description='"+request.getVREDescription()+"', vredesigner='"+request.getVREDesigner()+"', vremanager= '"+request.getVREManager()+"', intervalfrom='"+dateFrom+"', intervalto='"+dateTo+"' where VRE.id='"+getResource().getID()+"'; "); }else{ dateFrom=new Date(request.getStartTime()); dateTo=new Date(request.getEndTime()); String eprToString; try { eprToString = ObjectSerializer.toString(getResource().getEPR(), new QName(ModelerContext.getPortTypeContext().getNamespace(), "ModelResourceReference")); //logger.debug("EPR: "+eprToString); } catch (SerializationException e) { //logger.error("VDL Model Service: error serializing EPR"); logger.error("VDL Model Service: error serializing EPR",e); throw new GCUBEFault(e); } DBInterface.ExecuteUpdate("insert into VRE values('"+getResource().getID()+"','"+request.getVREName()+"','"+request.getVREDescription()+"','"+request.getVREDesigner()+"','"+request.getVREManager()+"','"+dateFrom+"','"+dateTo+"','"+eprToString+"','In Progress'); "); } } catch (Exception e) { logger.error(" "+e.getMessage()); throw new GCUBEFault(e); } } /** * * * @param request void * @return VoidType * @throws RemoteException - */ public String getVREModel(VOID var) throws GCUBEFault{ String toReturn =null; ResultSet res=null; //logger.debug("Request DL with ID "+ID); try { String ID=getResource().getId(); DBInterface.connect(); res=DBInterface.queryDB("select * from VRE where VRE.id='"+ID+"';"); toReturn=XMLUtil.PrepareVREModelXML(res); } catch (Exception e) { //logger.error("VDLModel parsing error in function getDLModel "+e.getMessage()); throw new GCUBEFault(e); } return toReturn; } /** * return an XML containing the DHN list * * @param request void * @return a XML String * @throws RemoteException - */ public String getGHNs(VOID var) throws GCUBEFault{ logger.info("getGHNs method"); ResultSet res; ArrayList relatedGHN=new ArrayList(); try{ DBInterface.connect(); res= DBInterface.queryDB("select * from GHN;"); ResultSet resRelated= DBInterface.queryDB("select ghnid from VRERELATEDGHN where VRERELATEDGHN.vreid='"+getResource().getId()+"';"); while(resRelated.next()) relatedGHN.add(resRelated.getString(1)); }catch(Exception e) { logger.error("VDL Model: error retreiving GHNs"+e); throw new GCUBEFault(e);} return XMLUtil.PrepareGHNsXML(res, relatedGHN); } /** * Set the selected DHN * * @param request array of dhn id * @return VoidType * @throws RemoteException - */ public void setGHNs(GHNArray request) throws GCUBEFault{ try{ String instanceID=(String) getResource().getId(); DBInterface.ExecuteUpdate("DELETE FROM VRERELATEDDHN WHERE VRERELATEDDHN.vreid='"+instanceID+"';"); String dlKey=instanceID; ArrayList> values= new ArrayList>(request.getGHNElement().length); ArrayList row=null; for (int i=0; i(2); row.add(dlKey); row.add(request.getGHNElement()[i]); values.add(row); } DBInterface.InsertInto("VRERELATEDGHN", values); }catch(Exception e){throw new GCUBEFault(e);} } /** * * Return an XML with all the collection selectable * * @param request void * @return the collection retreived from the database * @throws RemoteException - */ public String getCollection(VOID var) throws GCUBEFault{ ResultSet res; ArrayList relatedCollection=new ArrayList(); try{ DBInterface.connect(); res= DBInterface.queryDB("select * from COLLECTION;"); ResultSet resRelated= DBInterface.queryDB("select collid from VRERELATEDCOLLECTION where VRERELATEDCOLLECTION.vreid='"+getResource().getId()+"';"); while(resRelated.next()){ relatedCollection.add(resRelated.getString(1)); } }catch(Exception e) { logger.error("VDL Model: error on DB"); e.printStackTrace(); throw new GCUBEFault(e);} String toReturn= XMLUtil.PrepareCollectionXML(res, relatedCollection); System.out.println(toReturn); return toReturn; } /** * * Insert in the DB the selected collection * * @param request An Array that contains the selected collections ids * @return void * @throws RemoteException - */ public void setCollection(CollectionArray request) throws GCUBEFault{ try{ DBInterface.connect(); DBInterface.ExecuteUpdate("DELETE FROM VRERELATEDCOLLECTION WHERE VRERELATEDCOLLECTION.vreid='"+getResource().getID()+"';"); String dlKey=(String) getResource().getId(); ArrayList> values= new ArrayList>(request.getCollectionElement().length); ArrayList row=null; for (int i=0; i(2); row.add(dlKey); row.add(request.getCollectionElement()[i]); } DBInterface.connect(); DBInterface.InsertInto("VRERELATEDCOLLECTION", values); }catch(Exception e){throw new GCUBEFault(e);} } /** * Return the possibles metadata format for selected collection * * @param request void * @return a XML format string * @throws RemoteException - */ public String getMetadataRelatedToCollection(VOID var) throws GCUBEFault { ResultSet resDerivable, resNative, collectionRelated, totalMF; String preparedWhere=""; Hashtable> selectedMetadataStructure= new Hashtable>(); boolean enter=false; try{ DBInterface.connect(); collectionRelated= DBInterface.queryDB("select VRERELATEDCOLLECTION.collid from VRERELATEDCOLLECTION where DLRELATEDCOLLECTION.dlid='"+getResource().getId()+"';"); //select only the resuls related with selected collection preparedWhere= " and ( "; while (collectionRelated.next()){ enter=true; preparedWhere+= " mdc.collid='"+collectionRelated.getString(1)+"' or "; } ResultSet metadataSelected= DBInterface.queryDB("select collid, mfid from VRERELATEDMETADATAFORMAT where vreid='"+getResource().getID()+"';"); //recovering possible previsious selection for metadataFormat while (metadataSelected.next()){ if(selectedMetadataStructure.containsKey(metadataSelected.getString(1))) selectedMetadataStructure.get(metadataSelected.getString(1)).add(metadataSelected.getString(2)); else { ArrayList temp= new ArrayList(); temp.add(metadataSelected.getString(2)); selectedMetadataStructure.put(metadataSelected.getString(1), temp); } } if(!enter) throw new RemoteException("no collection selected for this DL"); else preparedWhere=preparedWhere.substring(0, preparedWhere.length()-4)+") "; totalMF = DBInterface.queryDB("select MDFORMAT.id, MDFORMAT.name, MDFORMAT.schemauri, MDFORMAT.language from MDFORMAT;"); resDerivable= DBInterface.queryDB("select mdc.collid, mdc.collname, mdc.colldesc , collmdf.id as mdfid from (select * from DERIVABLEMDF INNER JOIN MDFORMAT on DERIVABLEMDF.mdfid= MDFORMAT.id) " + "as COLLMDF,(select COLLECTION.id as collid, COLLECTION.name as collname, COLLECTION.description as colldesc, MDCOLLECTION.id as mdid from COLLECTION INNER JOIN MDCOLLECTION " + "ON COLLECTION.id = MDCOLLECTION.relatedcollectionid) as MDC where COLLMDF.mdcollid= MDC.mdid "+preparedWhere+";"); resNative= DBInterface.queryDB("select mdc.collid, mdc.collname, mdc.colldesc , collmdf.id as mdfid from (select * from NATIVEMDF INNER JOIN MDFORMAT on NATIVEMDF.mdfid= MDFORMAT.id) " + "as COLLMDF,(select COLLECTION.id as collid, COLLECTION.name as collname, COLLECTION.description as colldesc, MDCOLLECTION.id as mdid from COLLECTION INNER JOIN MDCOLLECTION " + "ON COLLECTION.id = MDCOLLECTION.relatedcollectionid) as MDC where COLLMDF.mdcollid= MDC.mdid "+preparedWhere+";"); }catch(Exception e) {//logger.error("ModelService: "+e.getMessage()); throw new GCUBEFault(e); } return XMLUtil.PrepareMCFormatXML(null, null, null, selectedMetadataStructure); } /** * * Sets selected Metadata Format * * @param request * @return void * @throws RemoteException - */ public void setMetadataRelatedToCollection(SetMDFormatArgs request) throws GCUBEFault { try{ DBInterface.ExecuteUpdate("DELETE FROM VRERELATEDMETADATAFORMAT WHERE VRERELATEDMETADATAFORMAT.vreid='"+getResource().getId()+"';"); //String[] singleElement; String key=(String) getResource().getId(); //logger.debug(request.getCollectionIDArray().length+" "+request.getMdFormatIDArray().length+" "+request.getCheckedArray().length+" "+request.getCheckedArray(0).getCheckedRowElement().length); ArrayList> values= new ArrayList>(request.getCollectionIDArray().length); ArrayList row=null; for (int i=0; i(3); row.add(key); row.add(request.getCollectionIDArray(i)); row.add(request.getMdFormatIDArray(j)); values.add(row); } } DBInterface.InsertInto("VRERELATEDMETADATAFORMAT", values); }catch(Exception e){throw new GCUBEFault(e);} } /** * Return an xml with the selectable functionalities * String * * @param request void * @return an xml String containing selectable functionalities * @throws RemoteException - */ public String getFunctionality(VOID var) throws GCUBEFault { ResultSet resFunct=null; ResultSet selectedFuncRes=null; ResultSet selectedCSRes=null; ArrayList selectedFunctionality= new ArrayList(); ArrayList selectedCS= new ArrayList(); try { DBInterface.connect(); resFunct= DBInterface.queryDB("select * from functionality where father is null;"); selectedFuncRes= DBInterface.queryDB("select funcid from VRERELATEDFUNCT where vreid='"+getResource().getID()+"';"); while (selectedFuncRes.next()) selectedFunctionality.add(selectedFuncRes.getInt(1)); selectedCSRes= DBInterface.queryDB("select csid from VRERELATEDCS where vreid='"+getResource().getID()+"';"); while (selectedCSRes.next()) selectedCS.add(selectedCSRes.getString(1)); } catch (Exception e) { //logger.error("VDLModel Service: error retreiving functionality"); e.printStackTrace(); throw new GCUBEFault(e); } return XMLUtil.PrepareFunctionalityXML(resFunct, selectedFunctionality, selectedCS); } /** * * * * @return void * @throws RemoteException - */ public void setFunctionality(FunctionalityIDArray request) throws GCUBEFault { try{ DBInterface.ExecuteUpdate("DELETE FROM VRERELATEDFUNCT WHERE VRERELATEDFUNCT.vreid='"+getResource().getId()+"';"); DBInterface.ExecuteUpdate("DELETE FROM VRERELATEDCS WHERE VRERELATEDCS.vreid='"+getResource().getId()+"';"); String dlKey=(String) getResource().getId(); //logger.debug("KEY: "+dlKey); if (request.getFunctionalityIDElement()!=null){ ArrayList> values= new ArrayList>(request.getFunctionalityIDElement().length); ArrayList row=null; for (int i=0; i(2); row.add(dlKey); row.add(request.getFunctionalityIDElement()[i]); values.add(row); } DBInterface.InsertInto("VRERELATEDFUNCT", values); } if (request.getCsIDElement()!=null) { ArrayList> values= new ArrayList>(request.getCsIDElement().length); ArrayList row=null; for (int i=0; i(2); row.add(dlKey); row.add(request.getCsIDElement()[i]); values.add(row); } DBInterface.InsertInto("VRERELATEDCS", values); } }catch(Exception e){throw new GCUBEFault(e);} } /** * Return an XML with Quality parameter to insert * * @param request void * @return a XML format String * @throws RemoteException - */ public String getQuality(VOID var) throws GCUBEFault{ return XMLUtil.PrepareQualityXML(); } /** * Sets Quality parameters * * @param request * @throws RemoteException - */ public void setQuality(String request) throws GCUBEFault{ } /** * * set the DL state to Pending * * @param request * @return * @throws RemoteException - */ public void setVREtoPendingState(VOID var) throws GCUBEFault{ try{ DBInterface.ExecuteUpdate("UPDATE VRE SET STATUS='Pending' WHERE VRE.id='"+getResource().getId()+"';"); }catch(Exception e){throw new GCUBEFault(e);} } /** * * @param request * @return * @throws RemoteException - */ public void deployVRE(VOID var) throws GCUBEFault{ boolean contactedVRE= false; try { DBInterface.ExecuteUpdate("UPDATE VRE SET STATUS='Deploying' WHERE VRE.id='"+getResource().getId()+"';"); } catch (ResourceException e1) { throw new GCUBEFault(e1); } VREManagerServiceAddressingLocator vreManAL= new VREManagerServiceAddressingLocator(); VREManagerPortType vreManagerPT= null; List ris= null; try{ ISClient client= GHNContext.getImplementation(ISClient.class); GCUBERIQuery query=client.getQuery(GCUBERIQuery.class); query.addAtomicConditions(new AtomicCondition("//ServiceName", "VREManager")); query.addAtomicConditions(new AtomicCondition("//ServiceClass", "VREManagement")); ris = client.execute(query, ServiceContext.getContext().getScope()); }catch (Exception e) { logger.error("Error Excecuting Query"); throw new GCUBEFault(e);} String resourceID; try { resourceID = getResource().getId(); } catch (ResourceException e) { logger.error("Error retrieving the Resource Query"); throw new GCUBEFault(e); } for (GCUBERunningInstance ri: ris){ try{ vreManagerPT=vreManAL.getVREManagerPortTypePort(ri.getAccessPoint().getEndpoint("gcube/vremanagement/VREManager")); OptionsParameters ops; try{ ResultSet resGenericInfo=DBInterface.queryDB("select * from VRE where VRE.id='"+resourceID+"'; "); if (!resGenericInfo.next()) throw new GCUBEFault("The VRE with ID "+resourceID+" cannot be retrieved"); //TODO: set properties values ops=new OptionsParameters(); ScopeOption[] scopeOptionList= new ScopeOption[6]; ScopeOption soDesigner= new ScopeOption(); soDesigner.setName("DESIGNER"); soDesigner.setValue(resGenericInfo.getString("vredesigner")); scopeOptionList[0]= soDesigner; ScopeOption soCreator= new ScopeOption(); soCreator.setName("CREATOR"); soCreator.setValue(resGenericInfo.getString("vremanager")); scopeOptionList[1]= soCreator; ScopeOption soEndtime= new ScopeOption(); soEndtime.setName("ENDTIME"); soEndtime.setValue(KGCUBEResource.toXMLDateAndTime(resGenericInfo.getDate("IntervalTo"))); scopeOptionList[2]= soEndtime; ScopeOption soStarttime= new ScopeOption(); soStarttime.setName("STARTTIME"); soStarttime.setValue(KGCUBEResource.toXMLDateAndTime(resGenericInfo.getDate("IntervalFrom"))); scopeOptionList[3]= soStarttime; ScopeOption soDescription= new ScopeOption(); soDescription.setName("DESCRIPTION"); soDescription.setValue(resGenericInfo.getString("description")); scopeOptionList[4]= soDescription; ScopeOption soDisplayname= new ScopeOption(); soDisplayname.setName("DISPLAYNAME"); soDisplayname.setValue(resGenericInfo.getString("name")); scopeOptionList[5]= soDisplayname; ops.setScopeOptionList(scopeOptionList); }catch(SQLException e) {logger.error("cannot retreive the VRE"); throw new GCUBEFault(e);} //sending scope options vreManagerPT.setScopeOptions(ops); AddResourcesParameters arp= new AddResourcesParameters(); ResourceList rl= new ResourceList(); List resItemList= new ArrayList(); ResourceItem resItem= null; //retrieving Collection try{ ResultSet resRelatedCol =DBInterface.queryDB("select VRERELATEDCOLLECTION.collid from VRERELATEDCOLLECTION where VRERELATEDCOLLECTION.dlid='"+resourceID+"';"); while (resRelatedCol.next()){ resItem= new ResourceItem(); resItem.setID(resRelatedCol.getString(1)); resItem.setType(GCUBECollection.TYPE); resItemList.add(resItem); } }catch(SQLException sqle){logger.error("Error contacting HSQLDB");} /* ResultSet resRelatedMetadataCol =DBInterface.queryDB("select VRERELATEDCOLLECTION.collid from DLRELATEDCOLLECTION where VRERELATEDCOLLECTION.dlid='"+getResource().getId()+"';"); while (resRelatedCol.next()){ resItem= new ResourceItem(); resItem.setID(resRelatedCol.getString(1)); resItem.setType(GCUBEMCollection.TYPE); } */ contactedVRE= true; }catch(RemoteException re){logger.warn("Error Contacting VREManager, trying next RI"); contactedVRE= false;} catch(ServiceException se1){logger.warn("Error Contacting VREManager, trying next RI"); contactedVRE= false;} } if (!contactedVRE) { logger.error("Error Contacting VREManager"); throw new GCUBEFault("Error Contacting VREManager"); } /* DLManagementFactoryServiceAddressingLocator dlMan=new DLManagementFactoryServiceAddressingLocator(); try { //retreive and connect to the DLManagement EndpointReferenceType eprDLMan= new EndpointReferenceType(new AttributedURI(DISHLSClient.getRunningInstanceManager(null, getMyEPR()).getEPRsRIFromClassAndName("Keeper", "DLManagement", "diligentproject/keeperservice/dlmanagement/DLManagementFactoryService", null, getMyEPR())[0])); DLManagementFactoryPortType dlManagementFactory= dlMan.getDLManagementFactoryPortTypePort(eprDLMan); // authorization control (if in the container the security is enabled) if (ModelFactoryService.isSecurityEnabled){ CredentialManager cred= new CredentialManager(); ConfigureSecurity.setSecurity(((javax.xml.rpc.Stub)dlManagementFactory), cred.getCredentials()); } logger.debug("DLManagement retreived"); String dlId=(String)getResource().getId(); CreateDLMessage createDLMessage= new CreateDLMessage(); createDLMessage.setVDLUniqueID(dlId); ResultSet dlGenRes= DBInterface.queryDB("select name, description, dldesigner, dlmanager, intervalto, id from DL where DL.id='"+dlId+"';"); if (dlGenRes.next()){ createDLMessage.setDLName((new NAL().getDefaultVO())+"/"+dlGenRes.getString(1)); createDLMessage.setDescription(dlGenRes.getString(2)); createDLMessage.setDLDesigner(dlGenRes.getString(3)); createDLMessage.setDLManager(dlGenRes.getString(4)); Calendar terminationTime=Calendar.getInstance(); terminationTime.setTime(dlGenRes.getDate(5)); createDLMessage.setDLTerminationTime(terminationTime); createDLMessage.setVDLUniqueID(dlGenRes.getString(6)); createDLMessage.setIsSecurityEnabled(ModelFactoryService.isSecurityEnabled); }else throw new RemoteException("VDLModel Service: impossible to retreive specific DL"); //logger.debug("Setted first parameters"); ArrayList tempArray= new ArrayList(); //retreive and set collection ids ResultSet dlCollRes= DBInterface.queryDB("select collid from DLRELATEDCOLLECTION where DLRELATEDCOLLECTION.dlid='"+dlId+"';"); for (int i=0; dlCollRes.next(); i++) tempArray.add(dlCollRes.getString(1)); createDLMessage.setColIDsList(tempArray.toArray(new String[0])); tempArray= new ArrayList(); //retreive Metadata IDs ResultSet dlMetadataRes=DBInterface.queryDB("select DISTINCT NATIVEMDF.MDCOLLID from DLRELATEDMETADATAFORMAT, NATIVEMDF where DLRELATEDMETADATAFORMAT.mfid=NATIVEMDF.mdfid and DLRELATEDMETADATAFORMAT.dlid='"+dlId+"';"); for (int i=0; dlMetadataRes.next(); i++) tempArray.add(dlMetadataRes.getString(1)); createDLMessage.setMcIDsList(tempArray.toArray(new String[0])); //TODO: TP retriving is a mistery :) //adding functionality to DLManagement request tempArray= new ArrayList(); ResultSet dlRelatedFunctionality=DBInterface.queryDB("select RELATEDSERVICEID.id from RELATEDSERVICEID, SERVICES, DLRELATEDFUNCT where DLRELATEDFUNCT.dlid='"+dlId+"' and SERVICES.id=DLRELATEDFUNCT.funcid and SERVICES.class=RELATEDSERVICEID.class and SERVICES.name=RELATEDSERVICEID.name;"); for (int i=0; dlRelatedFunctionality.next(); i++){ tempArray.add(dlRelatedFunctionality.getString(1)); logger.debug("ServiceID: "+dlRelatedFunctionality.getString(1)); } createDLMessage.setServiceIDsList(tempArray.toArray(new String[0])); //adding DHN to DLManagement request tempArray= new ArrayList(); ResultSet dlRelatedDHN=DBInterface.queryDB("select DLRELATEDDHN.dhnid from DLRELATEDDHN where DLRELATEDDHN.dlid='"+dlId+"'"); for (int i=0; dlRelatedDHN.next(); i++) tempArray.add(dlRelatedDHN.getString(1)); createDLMessage.setDhnIDsList(tempArray.toArray(new String[0])); //adding cs to DLManagement request tempArray= new ArrayList(); ResultSet dlCSRes= DBInterface.queryDB("select csid from DLRELATEDCS where DLRELATEDCS.dlid='"+getResource().getId()+"';"); for (int i=0; dlCSRes.next(); i++) tempArray.add(dlCSRes.getString(1)); createDLMessage.setCsIDsList(tempArray.toArray(new String[0])); //DLManagement invocation dlManagementFactory.createDL(createDLMessage); } catch (Exception e) { logger.error("VDLModel Service: Error Deploying DL "+e.getMessage()); e.printStackTrace(); DBInterface.ExecuteUpdate("UPDATE DL SET STATUS='Failed' WHERE DL.id='"+getResource().getId()+"';"); throw new RemoteException("VDLModel Service: Error Deploying DL" ,e); } */ } }