package org.gcube.vremanagement.vremodeler.impl.util; import java.io.StringWriter; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.List; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.axis.message.addressing.EndpointReferenceType; import org.gcube.common.core.contexts.GCUBERemotePortTypeContext; import org.gcube.common.core.contexts.GHNContext; import org.gcube.common.core.informationsystem.client.ISClient; import org.gcube.common.core.informationsystem.client.queries.GCUBERIQuery; import org.gcube.common.core.resources.GCUBERunningInstance; import org.gcube.common.core.scope.GCUBEScope; import org.gcube.common.core.utils.handlers.GCUBEServiceHandler.NoQueryResultException; import org.gcube.common.core.utils.logging.GCUBELog; import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.ResourceManagerPortType; import org.gcube.vremanagement.resourcemanager.stubs.resourcemanager.service.ResourceManagerServiceAddressingLocator; import org.gcube.vremanagement.vremodeler.db.DBInterface; import org.gcube.vremanagement.vremodeler.impl.ModelerService; import org.gcube.vremanagement.vremodeler.impl.ServiceContext; import org.gcube.vremanagement.vremodeler.stubs.CollectionType; import org.gcube.vremanagement.vremodeler.stubs.CollectionTypeInfo; import org.gcube.vremanagement.vremodeler.stubs.FunctionalityItem; import org.gcube.vremanagement.vremodeler.stubs.GHNType; import org.gcube.vremanagement.vremodeler.stubs.GHNTypeMemory; import org.gcube.vremanagement.vremodeler.stubs.GHNTypeSite; import org.gcube.vremanagement.vremodeler.stubs.Report; import org.gcube.vremanagement.vremodeler.stubs.RunningInstance; import org.gcube.vremanagement.vremodeler.stubs.VREDescription; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * * @author Lucio Lelii * */ public class Util { private static final GCUBELog logger = new GCUBELog(ModelerService.class.getName()); /** * it creates the XML output for VDLGenerator * * @param res the result set of the query on database * @return String the XML */ public static List prepareCollections(ResultSet res, ArrayList relatedCollection){ List collectionList= new ArrayList(); try{ while (res.next()){ CollectionType collection= new CollectionType(); collection.setId(res.getString(1)); collection.setName(res.getString(2)); Calendar creationTime = Calendar.getInstance(); creationTime.setTimeInMillis(Long.parseLong(res.getString(5))); Calendar lastUpdateTime = Calendar.getInstance(); lastUpdateTime.setTimeInMillis(Long.parseLong(res.getString(6))); collection.setInfo(new CollectionTypeInfo(creationTime, res.getString(3),lastUpdateTime, Integer.parseInt(res.getString(4)))); collection.setSelected(relatedCollection.contains(res.getString(1))); collectionList.add(collection); } }catch(SQLException e){ logger.error("database error "+e.getMessage()); e.printStackTrace(); } return collectionList; } /** * * @param res * @param relatedGHNs * @param candidateGHN * @return */ public static List prepareGHNs(ResultSet res, ArrayList relatedGHNs, String candidateGHN){ List ghnTypeList= new ArrayList(); try{ ResultSet riRes; while (res.next()){ //controlling all the RIs on the GHN riRes= DBInterface.queryDB("select RI.id, RI.name, RI.class from RUNNINGINSTANCE as RI, GHNRELATEDRI as REL where REL.GHNID='"+res.getString("ID")+"' and REL.RIID=RI.ID"); int risNum=0; List riList= new ArrayList(); while (riRes.next()){ if (!ServiceContext.getContext().getBaseServiceForGhn().contains(new ServicePair(riRes.getString(2),riRes.getString(3)))) risNum++; riList.add(new RunningInstance(riRes.getString(3),riRes.getString(2))); } GHNType ghn= new GHNType(); ghn.setId(res.getString(1)); ghn.setSelectable(!(risNum>0)); ghn.setSelected(relatedGHNs.contains(res.getString(1))); ghn.setVreManagerUse(candidateGHN.compareTo(res.getString("ID"))==0); ghn.setHost(res.getString(2)); ghn.setSecurity(res.getString(3)); ghn.setUpTime(res.getString(4)); ghn.setMemory(new GHNTypeMemory(res.getString(7),res.getString(5),res.getString(6))); ghn.setSite(new GHNTypeSite(res.getString(9),res.getString(10),res.getString(8))); ghn.setRelatedRIs(riList.toArray(new RunningInstance[riList.size()])); ghnTypeList.add(ghn); } }catch(SQLException e){ logger.error("exception reised getting data from database",e); } return ghnTypeList; } private static List getDistinctObjects(Collection list){ List tmpList= new ArrayList(); for (T el: list) if (!tmpList.contains(el)) tmpList.add(el); return tmpList; } /** * * @return the XML representing the quality string */ public static String prepareQualityXML(){ StringBuilder qualityString=new StringBuilder(); qualityString.append(""); qualityString.append("Response TimeThis quality parameter indicates the importance of response time (i.e., the delay from a function request to the reception of the response) "); qualityString.append("in selecting the resource (both in number and type) needed to satisfy the Digital Library definition criteria. E.g., the specification of a 100% response time will result in a maximization of the resources "); qualityString.append("allocated as to minimise the response time. *"); qualityString.append("RobustnessThis quality parameter indicates the importance of robustness (i.e., the resilience to faults) in selecting the resource (both in number and type)"); qualityString.append(" needed to satisfy the Digital Library definition criteria. E.g., the specification of a 100% robustness will result in a maximisation of the resources allocated as to minimise service unavailability.*"); qualityString.append("ScalabilityThis quality parameter indicates the importance of scalability (i.e., the capability to increase Digital Library Capacity as much as needed) in selecting the resource "); qualityString.append("(both in number and type) needed to satisfy the Digital Library definition criteria. E.g., the specification of a 100% scalability will result in a maximisztion of the resources allocated as to minimise the response time."); qualityString.append("*"); qualityString.append("Re-useThis quality parameter indicates the willingness to re-use existing resources (running instances, indexes, etc.) across various Digital Libraries. The specified "); qualityString.append("percentage represents the degree of re-use of existing assets in concretely implementing the Digital Library.*"); qualityString.append("CapacityThis quality parameter indicates the importance of capacity (i.e., the amount of resources allocated to the Digital Library) in selecting the resource (both in number and type) "); qualityString.append("needed to satisfy the Digital Library definition criteria. E.g., the specification of a 100% capacity will result in a maximization of the amount of resources allocated to the Digital Library."); qualityString.append(" *"); qualityString.append("SecurityA true/false quality parameter indicates whether the operations have to be executed in a fully authorised and authenticated environment (true value) or "); qualityString.append("not (false value)YesNo"); qualityString.append(""); return qualityString.toString(); } /** * * @param res * @param selectedFunct * @param selectedCS * @return */ public static List prepareFunctionalities(ResultSet res, ArrayList selectedFunct, ArrayList selectedCS){ List functionalityItemList= new ArrayList(); try { while(res.next()){ FunctionalityItem functionlityItem= new FunctionalityItem(); functionlityItem.setId(res.getInt(1)); functionlityItem.setName(res.getString(2)); functionlityItem.setSelected(selectedFunct.contains(res.getInt(1))); functionlityItem.setDescription(res.getString(3)); List subFunctionalities= new ArrayList(); ResultSet subFunctRes=DBInterface.queryDB("select * from FUNCTIONALITY where father='"+res.getInt(1)+"';"); while(subFunctRes.next()){ FunctionalityItem subFunctionalityItem= new FunctionalityItem(); subFunctionalityItem.setId(subFunctRes.getInt(1)); subFunctionalityItem.setName(subFunctRes.getString(2)); subFunctionalityItem.setDescription(subFunctRes.getString(3)); subFunctionalityItem.setSelected(selectedFunct.contains(subFunctRes.getInt(1))); subFunctionalities.add(subFunctionalityItem); } functionlityItem.setChilds(subFunctionalities.toArray(new FunctionalityItem[subFunctionalities.size()])); functionalityItemList.add(functionlityItem); } } catch (SQLException e) { logger.error("DB error preparing Functionalities",e); } return functionalityItemList; } /** * * @param res * @return a String representing the message * @throws Exception */ public static VREDescription prepareVREDescription(ResultSet res) throws Exception{ VREDescription vreDescription= new VREDescription(); if (res.next()){ vreDescription.setName(res.getString(2)); vreDescription.setDescription(res.getString(3)); vreDescription.setDesigner(res.getString(4)); vreDescription.setManager(res.getString(5)); Calendar calendarStart= Calendar.getInstance(); calendarStart.setTime(res.getDate(6)); vreDescription.setStartTime(calendarStart); Calendar calendarEnd= Calendar.getInstance(); calendarEnd.setTime(res.getDate(7)); vreDescription.setEndTime(calendarEnd); }else{ Calendar calendarStart= Calendar.getInstance(); Calendar calendarEnd= Calendar.getInstance(); calendarEnd.add(Calendar.YEAR, 1); vreDescription.setName(null); vreDescription.setDescription(null); vreDescription.setDesigner(null); vreDescription.setManager(null); vreDescription.setStartTime(calendarStart); vreDescription.setEndTime(calendarEnd); } return vreDescription; } /** * * @param res * @return * @throws Exception */ public static List prepareVREsList(ResultSet res) throws Exception{ List reportList= new ArrayList(); while (res.next()){ Report reportItem= new Report(); reportItem.setId(res.getString(4)); reportItem.setDescription(res.getString(2)); reportItem.setName(res.getString(1)); reportItem.setState(res.getString(3)); reportList.add(reportItem); } return reportList; } /** * transform a Document into string * * @param doc Document * @return a String */ public static String docToString(Document doc){ String temp= null; try{ DOMSource domSource = new DOMSource(doc); TransformerFactory tf = TransformerFactory.newInstance(); Transformer serializer = tf.newTransformer(); serializer.setOutputProperty("encoding", "UTF-8"); serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes" ); StringWriter sw= new StringWriter(); StreamResult sr= new StreamResult(sw); serializer.transform(domSource, sr); temp=sr.getWriter().toString(); }catch(Exception e){ logger.error("transformation to String Error"); e.printStackTrace(); } return temp; } /** * * @param doc the root Document * @param root the element tag name * @param elements elements to add * @return the result element */ public static Element addElements(Document doc, String root, Element[] elements){ Element returnEl= doc.createElement(root); for (Element el: elements){ returnEl.appendChild(el); } return returnEl; } /** * * @param doc the root Document * @param Tag the element tag name * @param text the text to add at the element * @return the result element */ public static Element createTextElement(Document doc, String tag, String text){ Element returnEl= doc.createElement(tag); if (text!=null) returnEl.appendChild(doc.createTextNode(text)); return returnEl; } public static ResourceManagerPortType getResourceMangerPT(GCUBEScope scope) throws Exception{ ResourceManagerPortType rmPortType = null; int attempt=0; do{ try{ try{ Thread.sleep(30000); }catch (Exception et){} ISClient client = GHNContext.getImplementation(ISClient.class); GCUBERIQuery query = client.getQuery(GCUBERIQuery.class); query.setExpression("declare namespace is = 'http://gcube-system.org/namespaces/informationsystem/registry';" + " for $outer in collection(\"/db/Profiles/RunningInstance\")//Document/Data/is:Profile/Resource " + " let $scope:= $outer/Scopes/Scope[string() eq '"+scope.toString()+"'] " + " where count($scope)>0 " + " and $outer/Profile/ServiceName/string() eq 'ResourceManager' " + " and $outer/Profile/DeploymentData/Status/string() eq 'ready'"+ " return $outer"); List eprs = new ArrayList(); for (GCUBERunningInstance instance : client.execute(query, scope)) eprs.add(instance.getAccessPoint().getEndpoint("gcube/vremanagement/ResourceManager")); if(eprs.size()==0) throw new NoQueryResultException(); ResourceManagerServiceAddressingLocator vmsal= new ResourceManagerServiceAddressingLocator(); logger.trace("trying to contact instance at "+eprs.get(0).getAddress()); rmPortType= vmsal.getResourceManagerPortTypePort(eprs.get(0)); rmPortType = GCUBERemotePortTypeContext.getProxy(rmPortType,scope, Integer.parseInt((String)ServiceContext.getContext().getProperty("resourceManagerTimeout", true))); }catch(Exception e){ logger.warn(e); logger.warn("the query for resourceManager returned no result, re-trying in 30 secs ("+attempt+")"); }finally {attempt++;} }while(rmPortType==null && attempt<10); if (attempt>=10) throw new Exception("no ResourceMaanger can be retrieved for scope "+scope); return rmPortType; } }