diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..82422e1 --- /dev/null +++ b/.classpath @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/.project b/.project new file mode 100644 index 0000000..5e66cd0 --- /dev/null +++ b/.project @@ -0,0 +1,17 @@ + + + applicationSupportLayerCore + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/.settings/org.eclipse.jdt.ui.prefs b/.settings/org.eclipse.jdt.ui.prefs new file mode 100644 index 0000000..18848fa --- /dev/null +++ b/.settings/org.eclipse.jdt.ui.prefs @@ -0,0 +1,3 @@ +#Mon Sep 22 12:37:04 EEST 2008 +eclipse.preferences.version=1 +org.eclipse.jdt.ui.text.custom_code_templates= diff --git a/build.xml b/build.xml new file mode 100644 index 0000000..e637b31 --- /dev/null +++ b/build.xml @@ -0,0 +1,71 @@ + + + + + + + Compiling project source code + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/etc/ehcache.xml b/etc/ehcache.xml new file mode 100644 index 0000000..38fbfe7 --- /dev/null +++ b/etc/ehcache.xml @@ -0,0 +1,538 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/etc/settings.properties b/etc/settings.properties new file mode 100644 index 0000000..8ce600a --- /dev/null +++ b/etc/settings.properties @@ -0,0 +1 @@ +sharedDir=${catalina.home}/shared/d4s \ No newline at end of file diff --git a/etc/vomsAPI.properties b/etc/vomsAPI.properties new file mode 100644 index 0000000..0c7bd2f --- /dev/null +++ b/etc/vomsAPI.properties @@ -0,0 +1,18 @@ +MYPROXY_HOST=grids04.eng.it +MYPROXY_PORT=7512 +PROXIES_DIR=#path to dir where the proxy files will be storeed# +HOST_CERT=#myproxy certificate# +HOST_KEY=#myproxy key# + +NEW_SERVLET_HOST=dl14.di.uoa.gr #hostname for voms servlet# +NEW_SERVLET_PORT=8888 #port where voms servlet is listening# +NEW_SERVLET_PATH=/VOMSServlet/VOMSServlet #voms servlet path# +NEW_SERVLET_PROTOCOL=http # protocol: http/https# + +KEY_STORE=#path to *.p12 key file# +KEY_STORE_TYPE=PKCS12 +KEY_STORE_PWD=#password for the *.p12 key file# + +TRUST_STORE=#path to trust store file# +TRUST_STORE_PWD=#password for the trust store file# +TRUST_STORE_TYPE=JKS \ No newline at end of file diff --git a/src/org/gcube/application/framework/core/cache/CachesManager.java b/src/org/gcube/application/framework/core/cache/CachesManager.java new file mode 100644 index 0000000..ef9c897 --- /dev/null +++ b/src/org/gcube/application/framework/core/cache/CachesManager.java @@ -0,0 +1,123 @@ +package org.gcube.application.framework.core.cache; + +import org.gcube.application.framework.core.cache.factories.CollectionCacheEntryFactory; +import org.gcube.application.framework.core.cache.factories.ContentInfoCacheEntryFactory; +import org.gcube.application.framework.core.cache.factories.GenericResourceCacheEntryFactory; +import org.gcube.application.framework.core.cache.factories.MetadataCacheEntryFactory; +import org.gcube.application.framework.core.cache.factories.ProfileCacheEntryFactory; +import org.gcube.application.framework.core.cache.factories.SchemaInfoCacheEntryFactory; +import org.gcube.application.framework.core.cache.factories.SearchConfigCacheEntryFactory; +import org.gcube.application.framework.core.cache.factories.ThumbnailCacheEntryFactory; + +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.Ehcache; +import net.sf.ehcache.constructs.blocking.SelfPopulatingCache; + +/** + * @author Valia Tsagkalidou (KNUA) + * + * This class is a singleton that manages the available caches + * + */ +public class CachesManager { + protected static CachesManager cacheManager = new CachesManager(); + protected CacheManager manager; + protected Ehcache profileCache; + protected Ehcache genericResourceCache; + protected Ehcache searchConfigCache; + protected Ehcache collectionCache; + protected Ehcache contentCache; + protected Ehcache thumbnailCache; + protected Ehcache schemataCache; + protected Ehcache metadataCache; + + /** + * The constructor + */ + protected CachesManager() { + + manager = CacheManager.create(CachesManager.class.getResource("/etc/ehcache.xml")); + + profileCache = manager.getEhcache("profiles"); + genericResourceCache = manager.getEhcache("genericResources"); + searchConfigCache = manager.getEhcache("searchConfiguration"); + collectionCache = manager.getEhcache("collections"); + contentCache = manager.getEhcache("content"); + thumbnailCache = manager.getEhcache("thumbnail"); + schemataCache = manager.getEhcache("schemata"); + metadataCache = manager.getEhcache("metadata"); + + profileCache = new SelfPopulatingCache(profileCache, new ProfileCacheEntryFactory()); + genericResourceCache = new SelfPopulatingCache(genericResourceCache, new GenericResourceCacheEntryFactory()); + searchConfigCache = new SelfPopulatingCache(searchConfigCache, new SearchConfigCacheEntryFactory()); + collectionCache = new SelfPopulatingCache(collectionCache, new CollectionCacheEntryFactory()); + contentCache = new SelfPopulatingCache(contentCache, new ContentInfoCacheEntryFactory()); + thumbnailCache = new SelfPopulatingCache(thumbnailCache, new ThumbnailCacheEntryFactory()); + schemataCache = new SelfPopulatingCache(schemataCache, new SchemaInfoCacheEntryFactory()); + metadataCache = new SelfPopulatingCache(metadataCache, new MetadataCacheEntryFactory()); + } + + /** + * @return the sigleton of CachesManager + */ + public static CachesManager getInstance() { + return cacheManager; + } + + /** + * @return the cache that contains the user profiles + */ + public Ehcache getProfileCache() { + return profileCache; + } + + /** + * @return the cache that contains the generic resources + */ + public Ehcache getGenericResourceCache() { + return genericResourceCache; + } + + /** + * @return the cache that contains the search configurations + */ + public Ehcache getSearchConfigCache() { + return searchConfigCache; + } + + /** + * @return the cache that contains the collections per VRE + */ + public Ehcache getCollectionCache() { + return collectionCache; + } + + /** + * @return the cache that contains information about digital objects + */ + public Ehcache getContentCache() { + return contentCache; + } + + /** + * @return the cache that contains thumbnails + */ + public Ehcache getThumbnailCache() { + return thumbnailCache; + } + + /** + * @return the cache that contains the searchable fields for each metadata schema + */ + public Ehcache getSchemataCache() { + return schemataCache; + } + + /** + * @return the cache that contains the metadata objects + */ + public Ehcache getMetadataCache() { + return metadataCache; + } + +} diff --git a/src/org/gcube/application/framework/core/cache/RIsManager.java b/src/org/gcube/application/framework/core/cache/RIsManager.java new file mode 100644 index 0000000..a6247eb --- /dev/null +++ b/src/org/gcube/application/framework/core/cache/RIsManager.java @@ -0,0 +1,77 @@ +package org.gcube.application.framework.core.cache; + +import java.util.HashMap; + +import org.gcube.common.core.scope.GCUBEScope; +import org.gcube.common.core.utils.logging.GCUBELog; +import org.gcube.informationsystem.cache.ISCache; +import org.gcube.informationsystem.cache.ISCacheManager; + + +/** + * This class manages the running harvester threads. + * + * @author Valia Tsagkalidou (KNUA) + * + */ + +public class RIsManager { + + + /** + * Defines the manager's instance + */ + private static RIsManager instance = null; + + /** + * keeps the ISCache per scope + */ + protected HashMap isCaches; + + /** Object logger. */ + protected final GCUBELog logger = new GCUBELog(this); + + /** + * Initializes RIsManager + */ + private RIsManager() { + isCaches = new HashMap(); + } + + /** + * Retrieves the singleton + * @return the only instance of RIsManager + */ + synchronized public static RIsManager getInstance() { + if (instance == null) + instance = new RIsManager(); + return instance; + } + + /** + * @param scope the GGUBEScope for which the RIs are requested + * @return the ISCache for this specific scope + */ + public synchronized ISCache getISCache(GCUBEScope scope) + { + ISCache isInfo = isCaches.get(scope); + if(isInfo == null) + { + // If the ISCache in not already created, then it creates a new instance and adds it to the HashMap + try { + ISCacheManager.addManager(scope); + isInfo = ISCacheManager.getManager(scope).getCache(); + isCaches.put(scope, isInfo); + try { + Thread.sleep(5000); + } catch (InterruptedException e1) { + logger.error("", e1); + } + } catch (Exception e) { + logger.error("", e); + } + } + return isInfo; + } + +} diff --git a/src/org/gcube/application/framework/core/cache/factories/ApplicationCredentials.java b/src/org/gcube/application/framework/core/cache/factories/ApplicationCredentials.java new file mode 100644 index 0000000..0a94361 --- /dev/null +++ b/src/org/gcube/application/framework/core/cache/factories/ApplicationCredentials.java @@ -0,0 +1,96 @@ +package org.gcube.application.framework.core.cache.factories; + +import java.util.HashMap; + +import org.gcube.application.framework.core.security.PortalSecurityManager; +import org.gcube.application.framework.core.security.VOMSAdminManager; +import org.gcube.application.framework.core.util.UserCredential; +import org.gcube.common.core.scope.GCUBEScope; +import org.gcube.common.core.security.utils.VOMSAttributesReader; +import org.gcube.common.core.utils.logging.GCUBELog; +import org.gcube.vomanagement.vomsAdmin.impl.VOMSAdminImpl; +import org.gridforum.jgss.ExtendedGSSCredential; + +/** + * This class is used for retrieving and updating the portal credential that is needed by the caches in order to retrieve information form gCube services + * @author Valia Tsagkalidou (NKUA) + * + */ +class ApplicationCredentials { + private static ApplicationCredentials applCredentials = new ApplicationCredentials(); + private HashMap creds; + protected static String userDN = "/O=Grid/OU=GlobusTest/OU=simpleCA-gauss.eng.it/OU=eng.it/CN="; + protected static String userCA = "/O=Grid/OU=GlobusTest/OU=simpleCA-gauss.eng.it/CN=Globus Simple CA"; + + + /** Object logger. */ + protected final GCUBELog logger = new GCUBELog(this); + + /** + * The basic constructor + */ + protected ApplicationCredentials() + { + creds = new HashMap(); + } + + /** + * @return the sigleton of ApplicationCredentials + */ + public static ApplicationCredentials getInstance() + { + return applCredentials; + } + + /** + * @param VREname the of the VRE for which you want to get the "portal" credential + * @return the grid credential + */ + public ExtendedGSSCredential getCredential(String VREname) + { + PortalSecurityManager secMan = new PortalSecurityManager(GCUBEScope.getScope(VREname)); + if(!secMan.isSecurityEnabled()) + return null; + ExtendedGSSCredential cred = creds.get(VREname); + if(cred == null) + { + // If the creedential is not available, it retrieves it from myProxy + cred = UserCredential.getCredential("application", VREname); + if(cred == null) + { + //user "application" does not exist on this VRE, so we add him and try to get credential again + VOMSAdminImpl vomsA; + try { + vomsA = VOMSAdminManager.getVOMSAdmin(); + String[] roles = vomsA.listRoles(); + vomsA.createUser("application", userDN+"application", userCA, "application@gcube.org"); + vomsA.addMember(VREname, userDN+"application", userCA); + vomsA.assignRole(VREname, roles[0], userDN+"application", userCA); + } + catch (Exception e) { + vomsA = null; + logger.error("", e); + } + cred = UserCredential.getCredential("application", VREname); + } + creds.put(VREname, cred); + } + else + { + // credential already available + VOMSAttributesReader vomsReader = null; + try { + vomsReader = new VOMSAttributesReader(cred); + //Check if it's gonna expire in the next minute, and refresh it + if(vomsReader.getRefreshPeriod() < 60000) + { + cred = UserCredential.getCredential("application", VREname); + creds.put(VREname, cred); + } + } catch (Exception e1) { + logger.error("", e1); + } + } + return cred; + } +} diff --git a/src/org/gcube/application/framework/core/cache/factories/CollectionCacheEntryFactory.java b/src/org/gcube/application/framework/core/cache/factories/CollectionCacheEntryFactory.java new file mode 100644 index 0000000..8f9119e --- /dev/null +++ b/src/org/gcube/application/framework/core/cache/factories/CollectionCacheEntryFactory.java @@ -0,0 +1,401 @@ +package org.gcube.application.framework.core.cache.factories; + +import org.apache.axis.message.addressing.EndpointReferenceType; +import org.xml.sax.InputSource; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.ArrayList; + +import java.io.StringReader; + +import javax.xml.parsers.DocumentBuilderFactory; + +import org.apache.xpath.XPathAPI; +import org.gcube.application.framework.core.cache.CachesManager; +import org.gcube.application.framework.core.commons.model.CollectionInfo; +import org.gcube.application.framework.core.commons.model.IndexInfo; +import org.gcube.application.framework.core.util.CacheEntryConstants; +import org.gcube.application.framework.core.util.QueryString; +import org.gcube.application.framework.core.util.SessionConstants; +import org.gcube.application.framework.core.vremanagement.model.ISGenericResource; +import org.gcube.common.core.contexts.GHNContext; +import org.gcube.common.core.informationsystem.client.ISClient; +import org.gcube.common.core.informationsystem.client.RPDocument; +import org.gcube.common.core.informationsystem.client.queries.WSResourceQuery; +import org.gcube.common.core.scope.GCUBEScope; +import org.gcube.common.core.utils.logging.GCUBELog; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import net.sf.ehcache.constructs.blocking.CacheEntryFactory; + +/** + * This cache serves the available searchable collections for each VRE + * @author Valia Tsagkalidou (NKUA) + * + */ +public class CollectionCacheEntryFactory implements CacheEntryFactory { + + + static ISClient client = null; + + /** Object logger. */ + protected final GCUBELog logger = new GCUBELog(this); + + public CollectionCacheEntryFactory() { + super(); + //Initialize static variable + if(client == null) + { + try { + client = GHNContext.getImplementation(ISClient.class); + } catch (Exception e) { + // TODO Auto-generated catch block + logger.error("Failed to get implemetation of ISClient", e); + } + } + } + + + + /** + * Document factory instance + */ + public static final DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + + /** + * whether geospatial tab should be available in Search portlet or not + */ + protected boolean geospatial; + //TODO: find a way to return also the geospatial tab boolean variable + + + /** + * @param key a String representing the VRE name. + * @return List[] an array of Lists containing CollectionInfo objects. Each List contains a Collection group. The First element of the list is the CollectionInfo containing info for the Group (name, description etc). The rest of the objects in the list are the actual collections. + */ + public Object createEntry(Object key) throws Exception { + + System.out.println("GenericResource: inside collection cache entry factory create entry"); + List collections; + String searchConfig = (String) CachesManager.getInstance().getSearchConfigCache().get(key).getValue(); + System.out.println("The search configuration returned from the search master (dynamic) is: " + searchConfig); + if(searchConfig == null || searchConfig.equals("")) { + System.out.println("The searchConfigCache returned null for the search configuration!!!!"); + return null; + } + collections = parseSearchConfig(searchConfig); + System.out.println("GenericResource - Inside collection cache entry factory calling retrieve static configuration"); + return retrieveStaticConfiguration(key.toString(), collections); + } + + + /** + * @param searchConfig the search configuration as it is returned from the SearchMaster + * @return a list of CollectionInfo, which represents the currently available collections + */ + protected List parseSearchConfig(String searchConfig) + { + + try { + // Interpreting the dynamic configuration (the one retrieved from Search Master) + logger.debug(searchConfig); + InputSource colls_in = new InputSource(new StringReader(searchConfig)); + Document colls_doc; + colls_doc = dfactory.newDocumentBuilder().parse(colls_in); + NodeList colls_res; + //Getting the info of all the available content collections: + colls_res = XPathAPI.selectNodeList(colls_doc, "/SearchConfig/collections/collection[TYPE='DATA']"); + int n = colls_res.getLength(),i; + List collections = new ArrayList(); + for (i = 0; i < n; i++) + {//For each content collection: + // Storing the information in local variables. + CollectionInfo colInfo = new CollectionInfo(); + String val; + String id = colls_res.item(i).getAttributes().getNamedItem("id").getNodeValue(); + val = id; + String colName = colls_res.item(i).getAttributes().getNamedItem("name").getNodeValue(); + + colInfo.setId(id); + colInfo.setName(colName); + NodeList contentRes = XPathAPI.selectNodeList(colls_doc, "/SearchConfig/collections/collection[@id='"+id+"']/ASSOCIATEDWITH"); + int attrNo = contentRes.getLength(); + for(int j=0; j[] retrieveStaticConfiguration(String vre, List collections) throws Exception + { + // Reading the static configuration file and initializing the parameters + System.out.println("About to retrieve the static configuration"); + List[] colHierarchy; + QueryString query = new QueryString(); + query.put(CacheEntryConstants.vre, vre); + query.put(CacheEntryConstants.name, SessionConstants.ScenarioSchemaInfo); + //Retrieving the generic resource: + List scenarioSchemaInfo = (List) CachesManager.getInstance().getGenericResourceCache().get(query).getValue(); + + if(scenarioSchemaInfo == null || scenarioSchemaInfo.size() == 0) + { + System.out.println("The scenarioSchemaInfo is null"); + colHierarchy = new ArrayList[0]; + return colHierarchy; + } + System.out.println("Printing the static configuration"); + logger.debug(scenarioSchemaInfo.get(0).getBody()); + InputSource in = new InputSource(new StringReader(scenarioSchemaInfo.get(0).getBody())); + Document doc = dfactory.newDocumentBuilder().parse(in); + + retrieveCollections(doc, collections); + colHierarchy = retrieveCollectionHierarchy(vre, doc, collections); + return colHierarchy; + } + + /** + * Retrieves the collections by joining information from static and dynamic configuration. + * @param doc document which holds the collections + * @param collections the list containing the collections + */ + protected void retrieveCollections(Document doc, List collections) + { + int i,n; + List availableCollections = new ArrayList(); + // Reading the collections and storing them in a list only if they are currently available. + NodeList res = doc.getElementsByTagName("collection"); + + n = res.getLength(); + System.out.println("CollectionCacheEntryFactory: The number of collections is: " + n); + for (i = 0; i < n; i++) + { + String val = res.item(i).getAttributes().getNamedItem("name").getNodeValue(); + CollectionInfo colInfo = null; + + colInfo = getCollectionInfo(val, collections); + if (colInfo == null) + continue;// This collection is not currently available. + + val = res.item(i).getAttributes().getNamedItem("description").getNodeValue(); + colInfo.setDescription(val); + val = res.item(i).getAttributes().getNamedItem("reference").getNodeValue(); + colInfo.setReference(val); + val = res.item(i).getAttributes().getNamedItem("shortname").getNodeValue(); + colInfo.setShortName(val); + availableCollections.add(colInfo); + } + //Copying available collections to collections + collections.clear(); + for(CollectionInfo col : availableCollections) + { + collections.add(col); + } + + //Adding the collection groups to the available collections + res = doc.getElementsByTagName("collections"); + n = res.getLength(); + for (i = 0; i < n; i++) + { + CollectionInfo colInfo = new CollectionInfo(); + + colInfo.setId("collection_id_"+i); + String val; + try{ + val = res.item(i).getAttributes().getNamedItem("name").getNodeValue(); + colInfo.setName(val); + } + catch(Exception e){} + try{ + val = res.item(i).getAttributes().getNamedItem("description").getNodeValue(); + colInfo.setDescription(val); + } + catch(Exception e){} + try{ + val = res.item(i).getAttributes().getNamedItem("reference").getNodeValue(); + colInfo.setReference(val); + } + catch(Exception e){} + try{ + val = res.item(i).getAttributes().getNamedItem("shortname").getNodeValue(); + colInfo.setShortName(val); + } + catch(Exception e){} + collections.add(colInfo); + } + logger.debug("***Number of collections:" + collections.size()); + } + + + /** + * Retrieves the hierarchical structure of the available collections. Joins the static and the dynamic search configuration and produces a hierarchical structure containing information about each collection. + * @param VREname the VRE name of the active VRE + * @param doc document which holds the collections + * @param collections the available collections + * @return an array of Lists containing CollectionInfo objects. Each List contains a Collection group. The First element of the list is the CollectionInfo containing info for the Group (name, description etc). The rest of the objects in the list are the actual collections. + * @throws Exception an Exception occurred during processing + */ + protected List[] retrieveCollectionHierarchy(String VREname, Document doc, List collections) throws Exception { + + // Retrieving the tree structure of the collection hierarchy + NodeList res = XPathAPI.selectNodeList(doc, "//DL"); + Node geo = res.item(0).getAttributes().getNamedItem("geospatial"); + if(geo != null && geo.getNodeValue().equals("true")) + geospatial = true; + res = XPathAPI.selectNodeList(doc, "//collections"); + int n = res.getLength(); + logger.debug("***** number of collection groups:" + n + "*******"); + List[] colHierachy = new List[n]; + for (int i = 0; i < n; i++) + {//for each collection group: + String val = res.item(i).getAttributes().getNamedItem("name").getNodeValue(); + NodeList res2 = XPathAPI.selectNodeList(doc, "//collections[@name=\"" + val + "\"]/collection"); + colHierachy[i] = new ArrayList(); + CollectionInfo colInfo = getCollectionInfo(val, collections); + if(colInfo != null) + { + colHierachy[i].add(colInfo); // Collection Group Name + for (int j = 0; j < res2.getLength(); j++) + {//for each collection belonging to that group, it stores its name... + colInfo = getCollectionInfo(res2.item(j).getAttributes().getNamedItem("name").getNodeValue(), collections); + if(colInfo != null) + { + findBrowseFields(colInfo, GCUBEScope.getScope(VREname)); + colHierachy[i].add(colInfo); + } + } + } + logger.debug("***collection group " + i + " contains " + (colHierachy[i].size()-1) + " collections***"); + } + return colHierachy; + } + + /** + * Finds the Browseable fields for the given collection + * @param colInfo the CollectionInfo containing info about the current collection + * @param scope the GCUBEScope of the active VRE + */ + private void findBrowseFields(CollectionInfo colInfo, GCUBEScope scope) { + + try { + getWSResourceForForward(colInfo, scope); + } catch(Exception e){ + e.printStackTrace(); + } + } + /** + * Finds the collection info object of the collection with the given name. + * @param collectionName the name of the collection + * @param collections a list containing all the collections + * @return the CollectionInfo of the collection with the corresponding name + */ + protected CollectionInfo getCollectionInfo(String collectionName, List collections) + { + CollectionInfo colInfo = null; + int i, n = collections.size(); + for(i=0; i< n; i++) + { + logger.debug("*******" + collections.get(i).getName() + " vs. " + collectionName); + if(collections.get(i).getName().equals(collectionName)) + { + colInfo = collections.get(i); + logger.debug("***collection found****"); + break; + } + } + return colInfo; + } + + + /** + * Updates the information regarding the available forward indices for the given content collection + * @param colInfo the CollectionInfo that represents the content collection + * @param scope the scope on which this collection belongs to (currently active VRE) + * @throws Exception an error occurred during execution + */ + private void getWSResourceForForward(CollectionInfo colInfo, GCUBEScope scope) throws Exception { + //Building the query to IS + String filter = "$result/child::*[local-name()='ServiceClass']/string() eq 'Index'"; + filter += " and $result/child::*[local-name()='ServiceName']/string() eq 'ForwardIndexLookup'"; + filter += " and $result/child::*[local-name()='CollectionID']/string() eq '" + colInfo.getId() + "'"; + + HashMap> results = colInfo.getForward(); + + ISClient client = GHNContext.getImplementation(ISClient.class); + WSResourceQuery gquery = client.getQuery(WSResourceQuery.class); + gquery.addGenericCondition(filter); +//For each result: + for(RPDocument d : client.execute(gquery, scope)){ + String browseField = d.evaluate("//KeyName/text()").get(0); + List ret = results.get(browseField); + if(ret == null) + { + ret = new LinkedList(); + } + ret.add(d.getEndpoint()); + results.put(browseField, ret); + } + } + +} diff --git a/src/org/gcube/application/framework/core/cache/factories/ContentInfoCacheEntryFactory.java b/src/org/gcube/application/framework/core/cache/factories/ContentInfoCacheEntryFactory.java new file mode 100644 index 0000000..c59afd1 --- /dev/null +++ b/src/org/gcube/application/framework/core/cache/factories/ContentInfoCacheEntryFactory.java @@ -0,0 +1,82 @@ +package org.gcube.application.framework.core.cache.factories; + +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.axis.message.addressing.Address; +import org.apache.axis.message.addressing.EndpointReference; +import org.apache.axis.message.addressing.EndpointReferenceType; +import org.gcube.application.framework.core.cache.RIsManager; +import org.gcube.application.framework.core.security.ServiceContextManager; +import org.gcube.application.framework.core.util.CacheEntryConstants; +import org.gcube.application.framework.core.util.QueryString; +import org.gcube.common.core.scope.GCUBEScope; +import org.gcube.common.core.utils.logging.GCUBELog; +import org.gcube.informationsystem.cache.SrvType; +import org.gcube.contentmanagement.contentlayer.contentmanagementservice.stubs.CMSPortType1PortType; +import org.gcube.contentmanagement.contentlayer.contentmanagementservice.stubs.DocumentDescription; +import org.gcube.contentmanagement.contentlayer.contentmanagementservice.stubs.DocumentPropertyDescription; +import org.gcube.contentmanagement.contentlayer.contentmanagementservice.stubs.GetDocumentParameters; +import org.gcube.contentmanagement.contentlayer.contentmanagementservice.stubs.service.CMSPortType1ServiceAddressingLocator; +import org.gcube.contentmanagement.layerindependent.descriptions.BasicInfoObjectDescription; + +import net.sf.ehcache.constructs.blocking.CacheEntryFactory; + +/** + * @author Valia Tsagkalidou (NKUA) + * + */ +public class ContentInfoCacheEntryFactory implements CacheEntryFactory { + + /** + * An atomic integer to get the CMS EPRs round-robin + */ + protected static AtomicInteger cmsId = new AtomicInteger(0); + + /** Object logger. */ + protected final GCUBELog logger = new GCUBELog(this); + + /** + * @param key a QueryString representing pairs of keys and values: needed keys are "vre" and "oid" + * @return a DocumentDescription as it is returned from the CMS. The content is not transfered for storage and efficiency reasons + */ + public Object createEntry(Object key) throws Exception { + QueryString query = (QueryString) key; + DocumentDescription docDescription = null; + if(query.containsKey(CacheEntryConstants.vre) && query.containsKey(CacheEntryConstants.oid)) + { + EndpointReference[] cmsURIs = RIsManager.getInstance().getISCache(GCUBEScope.getScope(query.get(CacheEntryConstants.vre))).getEPRsFor("ContentManagement","ContentManagementService",SrvType.SIMPLE.name()); + EndpointReferenceType serviceEPR = new EndpointReferenceType(); + GetDocumentParameters docParams = new GetDocumentParameters(); + docParams.setDocumentID(query.get(CacheEntryConstants.oid)); + docParams.setTargetFileLocation(BasicInfoObjectDescription.RAW_CONTENT_DO_NOT_TRANSFER); + docParams.setUnrollLevels(3); + + for(int i=0; i< cmsURIs.length; i++) + { + try + { + serviceEPR.setAddress(new Address(cmsURIs[cmsId.getAndIncrement()%cmsURIs.length].getAddress().toString())); + CMSPortType1ServiceAddressingLocator serviceLocator = new CMSPortType1ServiceAddressingLocator(); + CMSPortType1PortType cms = serviceLocator.getCMSPortType1PortTypePort(serviceEPR); + cms = (CMSPortType1PortType) ServiceContextManager.applySecurity(cms, GCUBEScope.getScope(query.get(CacheEntryConstants.vre)), ApplicationCredentials.getInstance().getCredential(query.get(CacheEntryConstants.vre))); + docDescription = cms.getDocument(docParams); + long size = cms.getContentLength(query.get(CacheEntryConstants.oid)); + DocumentPropertyDescription[] properties = docDescription.getProperties(); + DocumentPropertyDescription[] newProperties = new DocumentPropertyDescription[properties.length + 1]; + for(int j=0; j < properties.length; j++) + { + newProperties[j] = properties[j]; + } + logger.debug("Size of file:" + size); + newProperties[properties.length] = new DocumentPropertyDescription("LengthOfRawContent", query.get(CacheEntryConstants.oid),"","" + size); + docDescription.setProperties(newProperties); + break; + } + catch (Exception e) { + logger.error("",e); + } + } + } + return docDescription; + } +} diff --git a/src/org/gcube/application/framework/core/cache/factories/GenericResourceCacheEntryFactory.java b/src/org/gcube/application/framework/core/cache/factories/GenericResourceCacheEntryFactory.java new file mode 100644 index 0000000..6a80e48 --- /dev/null +++ b/src/org/gcube/application/framework/core/cache/factories/GenericResourceCacheEntryFactory.java @@ -0,0 +1,117 @@ + +package org.gcube.application.framework.core.cache.factories; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.gcube.application.framework.core.util.CacheEntryConstants; +import org.gcube.application.framework.core.util.QueryString; +import org.gcube.application.framework.core.util.SessionConstants; +import org.gcube.application.framework.core.vremanagement.model.ISGenericResource; +import org.gcube.common.core.contexts.GCUBEContext; +import org.gcube.common.core.contexts.GHNContext; +import org.gcube.common.core.informationsystem.client.AtomicCondition; +import org.gcube.common.core.informationsystem.client.ISClient; +import org.gcube.common.core.informationsystem.client.queries.GCUBEGenericResourceQuery; +import org.gcube.common.core.resources.GCUBEGenericResource; +import org.gcube.common.core.scope.GCUBEScope; +import org.gcube.common.core.utils.logging.GCUBELog; + +import net.sf.ehcache.constructs.blocking.CacheEntryFactory; + +/** + * @author Valia Tsagkalidou + * + */ +public class GenericResourceCacheEntryFactory implements CacheEntryFactory { + + static ISClient client = null; + + + /** Object logger. */ + protected final GCUBELog logger = new GCUBELog(this); + + /** + * Constructor to initialize the ISClient + */ + public GenericResourceCacheEntryFactory() { + super(); + if(client == null) + { + try { + client = GHNContext.getImplementation(ISClient.class); + } catch (Exception e) { + logger.error("",e); + } + } + } + + + + + /** + * @param key a QueryString representing pairs of keys and values: needed keys are "vre" and one of "id" or "name" + * @return a list containing the Generic Resources that correspond to the query + */ + public List createEntry(Object key) throws Exception { + QueryString querySt = (QueryString) key; + logger.info("query: " + querySt.toString()); + GCUBEScope scope = GCUBEScope.getScope(querySt.get(CacheEntryConstants.vre)); + GCUBEGenericResourceQuery query = client.getQuery(GCUBEGenericResourceQuery.class); + + logger.info("In generic resources cache entry factory"); + + if(querySt.containsKey(CacheEntryConstants.id)) + { //Retrieving generic resources based on their ID + query.addAtomicConditions(new AtomicCondition("/ID", querySt.get(CacheEntryConstants.id))); + + } + // else if(querySt.containsKey(CacheEntryConstants.name) && querySt.get(CacheEntryConstants.name).equals(SessionConstants.ScenarioSchemaInfo)) + // { //Retrieving the generic resource that represents the static search configuration + // query.addAtomicConditions(new AtomicCondition("/Profile/Name", querySt.get(CacheEntryConstants.name))); + // query.addAtomicConditions(new AtomicCondition("/Profile/Body/DL/attribute::name", querySt.get(CacheEntryConstants.vre))); + // } + else if(querySt.containsKey(CacheEntryConstants.name)) + { //Retrieving generic resources based on their name + query.addAtomicConditions(new AtomicCondition("/Profile/Name", querySt.get(CacheEntryConstants.name))); + } + else if(querySt.containsKey(CacheEntryConstants.vreResource)) + { + + query.addAtomicConditions(new AtomicCondition("//SecondaryType", GCUBEGenericResource.SECONDARYTYPE_VRE), new AtomicCondition("//Body/Scope", scope.toString())); + + } + + try{ + List result = client.execute(query, scope); + List res = new ArrayList(); + if (querySt.containsKey(CacheEntryConstants.name) && querySt.get(CacheEntryConstants.name).equals(SessionConstants.ScenarioSchemaInfo)) { + System.out.println("The number of generic Resources for ScenarioSchemaInfo returned is: " + result.size()); + List newResult = new ArrayList(); + for (GCUBEGenericResource resource : result) { + Map scopes = resource.getScopes(); + System.out.println("Number of scopes for ScenarioSchemaInfo: " + scopes.values().size()); + System.out.println(scopes.values().toString()); + if (scopes.containsValue(scope)) { + newResult.add(resource); + } + } + System.out.println("Number of genericResources for ScenarioSchemaInfo left after the pruning" + newResult.size()); + result = newResult; + } + logger.debug("size of results: " + result.size()); + for(GCUBEGenericResource resource : result) + { + ISGenericResource genResource = new ISGenericResource(resource.getID(), resource.getName(), resource.getDescription(), resource.getBody(), resource.getSecondaryType()); + res.add(genResource); + } + return res; + }catch (Exception e) { + logger.error("",e); + return null; + } + } + +} diff --git a/src/org/gcube/application/framework/core/cache/factories/MetadataCacheEntryFactory.java b/src/org/gcube/application/framework/core/cache/factories/MetadataCacheEntryFactory.java new file mode 100644 index 0000000..5aff00e --- /dev/null +++ b/src/org/gcube/application/framework/core/cache/factories/MetadataCacheEntryFactory.java @@ -0,0 +1,103 @@ +package org.gcube.application.framework.core.cache.factories; + +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.axis.message.addressing.Address; +import org.apache.axis.message.addressing.EndpointReference; +import org.apache.axis.message.addressing.EndpointReferenceType; +import org.gcube.application.framework.core.cache.RIsManager; +import org.gcube.application.framework.core.security.ServiceContextManager; +import org.gcube.application.framework.core.util.CacheEntryConstants; +import org.gcube.application.framework.core.util.QueryString; +import org.gcube.common.core.scope.GCUBEScope; +import org.gcube.common.core.utils.logging.GCUBELog; +import org.gcube.informationsystem.cache.SrvType; +import org.gcube.metadatamanagement.metadatamanager.stubs.CreateManagerResponse; +import org.gcube.metadatamanagement.metadatamanager.stubs.GetElementItemResponse; +import org.gcube.metadatamanagement.metadatamanager.stubs.GetElementsResponse; +import org.gcube.metadatamanagement.metadatamanager.stubs.InformationObjectIDList; +import org.gcube.metadatamanagement.metadatamanager.stubs.MetadataManagerFactoryPortType; +import org.gcube.metadatamanagement.metadatamanager.stubs.MetadataManagerPortType; +import org.gcube.metadatamanagement.metadatamanager.stubs.MetadataObjectList; +import org.gcube.metadatamanagement.metadatamanager.stubs.service.MetadataManagerFactoryServiceAddressingLocator; +import org.gcube.metadatamanagement.metadatamanager.stubs.service.MetadataManagerServiceAddressingLocator; +import org.gcube.metadatamanagement.mmlibrary.model.BaseMetadata; + +import net.sf.ehcache.constructs.blocking.CacheEntryFactory; + +/** + * @author Valia Tsagkalidou (NKUA) + * + */ +public class MetadataCacheEntryFactory implements CacheEntryFactory { + + /** + * An atomic integer to get the CMS EPRs round-robin + */ + protected static AtomicInteger mcId = new AtomicInteger(0); + + /** Object logger. */ + protected final GCUBELog logger = new GCUBELog(this); + + /** + * @param key a QueryString representing pairs of keys and values. Needed keys are "vre", "metadataColID", "oid" + * @return the metadata object of the corresponding ID + */ + public Object createEntry(Object key) throws Exception { + QueryString query = (QueryString) key; + + try { + MetadataManagerPortType metaManager = null; + EndpointReference[] mcURIs = RIsManager.getInstance().getISCache(GCUBEScope.getScope(query.get(CacheEntryConstants.vre))).getEPRsFor("MetadataManagement", "MetadataManager", SrvType.FACTORY.name()); + logger.info("Number of available mms factories: " + mcURIs.length); + for(int i=0; i < mcURIs.length; i++) + { + try { + MetadataManagerServiceAddressingLocator instanceLocator = new MetadataManagerServiceAddressingLocator(); + MetadataManagerFactoryPortType mcFactory = null; + EndpointReferenceType endpoint = new EndpointReferenceType(); + endpoint.setAddress(new Address(mcURIs[mcId.getAndIncrement()%mcURIs.length].getAddress().toString())); + MetadataManagerFactoryServiceAddressingLocator mcflocator = new MetadataManagerFactoryServiceAddressingLocator(); + mcFactory = mcflocator.getMetadataManagerFactoryPortTypePort(endpoint); + mcFactory = ServiceContextManager.applySecurity(mcFactory, GCUBEScope.getScope(query.get(CacheEntryConstants.vre)), ApplicationCredentials.getInstance().getCredential(query.get(CacheEntryConstants.vre))); + CreateManagerResponse createResponsefromcollection = mcFactory.createManagerFromCollection(query.get(CacheEntryConstants.metadataColID)); + EndpointReferenceType instanceEPR = createResponsefromcollection.getEndpointReference(); + metaManager = instanceLocator.getMetadataManagerPortTypePort(instanceEPR); + break; + } + catch (Exception e) { + logger.error("",e); + } + } + + try { + metaManager = ServiceContextManager.applySecurity(metaManager, GCUBEScope.getScope(query.get(CacheEntryConstants.vre)), ApplicationCredentials.getInstance().getCredential(query.get(CacheEntryConstants.vre))); + } catch (Exception e) { + logger.error("",e); + } + logger.info("get metadata for oid: " + query.get(CacheEntryConstants.oid) + " and metadta col ID: " + query.get(CacheEntryConstants.metadataColID)); + String[] oids = new String[1]; + oids[0] = query.get(CacheEntryConstants.oid); + InformationObjectIDList oidsList = new InformationObjectIDList(oids); + GetElementsResponse elements = metaManager.getElements(oidsList); + for(int i=0; i < elements.getGetElementsItemResponse().length; i++) + { + GetElementItemResponse element = elements.getGetElementsItemResponse(i); + MetadataObjectList moList = element.getMetadataObjectList(); + if (moList != null) { + for(int j=0; j < moList.getMetadataObject().length; j++) + { + String metadataXML = moList.getMetadataObject(0); + logger.debug("metadata:" + metadataXML); + if(metadataXML != null) + return metadataXML; + } + } + } + } catch (Exception e) { + logger.error("",e); + } + return null; + } + +} diff --git a/src/org/gcube/application/framework/core/cache/factories/ProfileCacheEntryFactory.java b/src/org/gcube/application/framework/core/cache/factories/ProfileCacheEntryFactory.java new file mode 100644 index 0000000..002d7b7 --- /dev/null +++ b/src/org/gcube/application/framework/core/cache/factories/ProfileCacheEntryFactory.java @@ -0,0 +1,61 @@ +package org.gcube.application.framework.core.cache.factories; + +import java.io.ByteArrayInputStream; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.xml.parsers.DocumentBuilderFactory; + + +import org.gcube.application.framework.core.commons.ProfileService; +import org.gcube.application.framework.core.util.CacheEntryConstants; +import org.gcube.application.framework.core.util.QueryString; +import org.gcube.common.core.scope.GCUBEScope; +import org.gcube.common.core.types.VOID; +import org.gcube.common.core.utils.logging.GCUBELog; +import org.gcube.personalization.userprofileaccess.stubs.UserProfileAccessPortType; +import org.gridforum.jgss.ExtendedGSSCredential; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; + +import net.sf.ehcache.constructs.blocking.CacheEntryFactory; + +/** + * @author Valia Tsagkalidou (NKUA) + */ +public class ProfileCacheEntryFactory implements CacheEntryFactory { + + /** + * Document factory instance + */ + protected static final DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + + /** + * An atomic integer to get the Profile EPRs round-robin + */ + protected static AtomicInteger profileId = new AtomicInteger(0); + + /** Object logger. */ + protected final GCUBELog logger = new GCUBELog(this); + + /** + * @param key a QueryString representing pairs of keys and values. Needed keys are: "vre", "username" + * @return the user profile as a DOM object (Document) + */ + public Object createEntry(Object key) throws Exception { + QueryString query = (QueryString) key; + String profile = ""; + if(query.containsKey(CacheEntryConstants.vre) && query.containsKey(CacheEntryConstants.username)) + { + ProfileService profileService = new ProfileService(query.get(CacheEntryConstants.username), GCUBEScope.getScope(query.get(CacheEntryConstants.vre))); + ExtendedGSSCredential cred = ApplicationCredentials.getInstance().getCredential(query.get(CacheEntryConstants.vre)); + UserProfileAccessPortType port = profileService.getUserProfileAccess(cred); + profile = port.getUserProfile(new VOID()); // this is the profile!!! + logger.debug(profile); + InputSource profileIn = new InputSource(new ByteArrayInputStream(profile.getBytes())); + Document profileDoc = dfactory.newDocumentBuilder().parse(profileIn); + return profileDoc; + } + return null; + } + +} diff --git a/src/org/gcube/application/framework/core/cache/factories/SchemaInfoCacheEntryFactory.java b/src/org/gcube/application/framework/core/cache/factories/SchemaInfoCacheEntryFactory.java new file mode 100644 index 0000000..4be3027 --- /dev/null +++ b/src/org/gcube/application/framework/core/cache/factories/SchemaInfoCacheEntryFactory.java @@ -0,0 +1,123 @@ +package org.gcube.application.framework.core.cache.factories; + +import java.io.StringReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import javax.xml.parsers.DocumentBuilderFactory; + +import org.apache.xpath.XPathAPI; +import org.gcube.application.framework.core.cache.CachesManager; +import org.gcube.application.framework.core.util.CacheEntryConstants; +import org.gcube.application.framework.core.util.QueryString; +import org.gcube.application.framework.core.util.SessionConstants; +import org.gcube.application.framework.core.vremanagement.model.ISGenericResource; +import org.gcube.application.framework.core.commons.model.SearchField; +import org.gcube.common.core.utils.logging.GCUBELog; +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; + +import net.sf.ehcache.constructs.blocking.CacheEntryFactory; + +/** + * @author Valia Tsagkalidou (NKUA) + * + */ +public class SchemaInfoCacheEntryFactory implements CacheEntryFactory { + + /** Object logger. */ + protected final GCUBELog logger = new GCUBELog(this); + + /** + * Document factory instance + */ + public static final DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + + /** + * @param key a String representing the VRE name. + * @return a HashMap that contains the Searchable Fields for each metadata schema + */ + public Object createEntry(Object key) throws Exception { + HashMap> SchemaHashMap = new HashMap>(); + QueryString query = new QueryString(); + query.addParameter(CacheEntryConstants.vre, key.toString()); + query.addParameter(CacheEntryConstants.name, SessionConstants.MetadataSchemaInfo); + List genericResources = ((List)CachesManager.getInstance().getGenericResourceCache().get(query).getValue()); + String schemaInfo = ""; + for(ISGenericResource res : genericResources) + schemaInfo += "" + res.getBody() + ""; + schemaInfo += ""; + retrieveMetadataSchemaInfo(schemaInfo, SchemaHashMap); + return SchemaHashMap; + } + + /** + * Retrieves the metadata schema info from DIS + * + * @param metaSchemata a serialized xml document containing the schemata together with their searchble fields + * @param SchemaHashMap a HashMap that contains the Searchable Fields for each metadata schema to be filled in + */ + protected void retrieveMetadataSchemaInfo(String metaSchemata, HashMap> SchemaHashMap) { + if(metaSchemata == null || metaSchemata.trim().equals("")) + return; + try { + InputSource metadata_in = new InputSource(new StringReader(metaSchemata)); + Document doc = dfactory.newDocumentBuilder().parse(metadata_in); + NodeList res = doc.getElementsByTagName("Record"); + + int n = res.getLength(); + int i; + for (int k = 0; k < n; k++) + { + //for each schema: + String schema = null; + List metaFields = new ArrayList(); + schema = res.item(k).getChildNodes().item(0).getNodeName(); // schema name + System.out.println("schema=" + schema); + NodeList MetaRes = XPathAPI.selectNodeList(res.item(k), "//"+schema+"/option"); + int mrLength = MetaRes.getLength(); + for (i = 0; i < mrLength; i++) + { // For each option (criterion): + + try + { + NodeList res2 = MetaRes.item(i).getChildNodes(); + int j, m; + m = res2.getLength(); + SearchField option = new SearchField(); + for (j = 0; j < m; j++) + { + String name = res2.item(j).getNodeName(); + if (name.equals("option-name")) + { + option.name = res2.item(j).getFirstChild().getNodeValue(); + } + else if (name.equals("option-value")) + { + option.value = res2.item(j).getFirstChild().getNodeValue(); + } + else if (name.equals("option-type")) + { + option.type = res2.item(j).getFirstChild().getNodeValue(); + } + else if (name.equals("option-sort")) + { + option.sort = res2.item(j).getFirstChild().getNodeValue(); + } + } + metaFields.add(option); + } + catch (Exception e) { + e.printStackTrace(); + } + } + SchemaHashMap.put(schema, metaFields); + } + } + catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/org/gcube/application/framework/core/cache/factories/SearchConfigCacheEntryFactory.java b/src/org/gcube/application/framework/core/cache/factories/SearchConfigCacheEntryFactory.java new file mode 100644 index 0000000..19d2e9d --- /dev/null +++ b/src/org/gcube/application/framework/core/cache/factories/SearchConfigCacheEntryFactory.java @@ -0,0 +1,75 @@ +package org.gcube.application.framework.core.cache.factories; + +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.axis.message.addressing.Address; +import org.apache.axis.message.addressing.EndpointReference; +import org.apache.axis.message.addressing.EndpointReferenceType; +import org.gcube.application.framework.core.cache.RIsManager; +import org.gcube.application.framework.core.security.ServiceContextManager; +import org.gcube.common.core.scope.GCUBEScope; +import org.gcube.informationsystem.cache.SrvType; +import org.gcube.searchservice.searchmasterservice.stubs.SearchMasterPortType; +import org.gcube.searchservice.searchmasterservice.stubs.service.SearchMasterServiceAddressingLocator; + +import net.sf.ehcache.constructs.blocking.CacheEntryFactory; + +/** + * @author Valia Tsagkalidou (NKUA) + */ +public class SearchConfigCacheEntryFactory implements CacheEntryFactory { + + /** + * An atomic integer to get the Search EPRs round-robin + */ + protected static AtomicInteger SMid = new AtomicInteger(); + + /** + * @param key a String representing the DL name. + * @return a String - serialized the search configuration + */ + public Object createEntry(Object key) throws Exception { + + EndpointReference[] searchMasterURIs = null; + System.out.println("GenericResource: inside search config cache create entry starting.."); + for(int count =0; count < 5 ; count++) + { + searchMasterURIs = RIsManager.getInstance().getISCache(GCUBEScope.getScope(key.toString())).getEPRsFor("Search", "SearchMaster", SrvType.SIMPLE.name()); + if(searchMasterURIs.length > 0) + break; + Thread.sleep(5000); + } + // Creating a client for Search Master. + EndpointReferenceType serviceEPR = new EndpointReferenceType(); + String collections_xml = null; + System.out.println(searchMasterURIs.length + " search masters found on IS."); + for(int counter = 0; counter < searchMasterURIs.length; counter++) + { + try + { + String search = searchMasterURIs[SMid.getAndIncrement()%searchMasterURIs.length].getAddress().toString(); + System.out.println("search Master URL: " + search); + serviceEPR.setAddress(new Address(search)); + SearchMasterServiceAddressingLocator serviceLocator = new SearchMasterServiceAddressingLocator(); + SearchMasterPortType searchMaster = serviceLocator.getSearchMasterPortTypePort(serviceEPR); + + try { + searchMaster = ServiceContextManager.applySecurity(searchMaster, GCUBEScope.getScope(key.toString()), ApplicationCredentials.getInstance().getCredential(key.toString())); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + // Retrieving dynamic configuration. E.g. which collections are + // currently available, if a Full text Index is available.... + collections_xml = searchMaster.retrieveConfiguration("collections"); + System.out.println("Search Configuration!!!" + collections_xml); + break; + } + catch (Exception e) { + e.printStackTrace(); + } + } + return collections_xml; + } + +} diff --git a/src/org/gcube/application/framework/core/cache/factories/ThumbnailCacheEntryFactory.java b/src/org/gcube/application/framework/core/cache/factories/ThumbnailCacheEntryFactory.java new file mode 100644 index 0000000..ac5c0c8 --- /dev/null +++ b/src/org/gcube/application/framework/core/cache/factories/ThumbnailCacheEntryFactory.java @@ -0,0 +1,299 @@ +package org.gcube.application.framework.core.cache.factories; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.xml.rpc.ServiceException; + +import org.apache.axis.message.addressing.Address; +import org.apache.axis.message.addressing.EndpointReference; +import org.apache.axis.message.addressing.EndpointReferenceType; +import org.apache.axis.types.URI.MalformedURIException; +import org.gcube.application.framework.core.cache.CachesManager; +import org.gcube.application.framework.core.cache.RIsManager; +import org.gcube.application.framework.core.security.ServiceContextManager; +import org.gcube.application.framework.core.util.CacheEntryConstants; +import org.gcube.application.framework.core.util.QueryString; +import org.gcube.application.framework.core.util.ThumbnailConstants; +import org.gcube.common.core.scope.GCUBEScope; +import org.gcube.common.core.scope.GCUBEScope.MalformedScopeExpressionException; +import org.gcube.common.core.utils.logging.GCUBELog; +import org.gcube.contentmanagement.contentlayer.contentmanagementservice.stubs.AlternativeRepresentationDescription; +import org.gcube.contentmanagement.contentlayer.contentmanagementservice.stubs.ArrayOfAlternativeRepresentation; +import org.gcube.contentmanagement.contentlayer.contentmanagementservice.stubs.CMSPortType1PortType; +import org.gcube.contentmanagement.contentlayer.contentmanagementservice.stubs.DocumentDescription; +import org.gcube.contentmanagement.contentlayer.contentmanagementservice.stubs.DocumentPropertyDescription; +import org.gcube.contentmanagement.contentlayer.contentmanagementservice.stubs.GetDocumentParameters; +import org.gcube.contentmanagement.contentlayer.contentmanagementservice.stubs.service.CMSPortType1ServiceAddressingLocator; +import org.gcube.contentmanagement.layerindependent.descriptions.BasicInfoObjectDescription; +import org.gcube.informationsystem.cache.SrvType; +import org.gcube.thumbnailer.stubs.ThumbnailerPortType; +import org.gcube.thumbnailer.stubs.TransformContent; +import org.gcube.thumbnailer.stubs.service.ThumbnailServiceAddressingLocator; +import org.ietf.jgss.GSSCredential; + +import net.sf.ehcache.constructs.blocking.CacheEntryFactory; + +/** + * @author Valia Tsagkalidou (NKUA) + * + */ +public class ThumbnailCacheEntryFactory implements CacheEntryFactory { + + /** Object logger. */ + protected final GCUBELog logger = new GCUBELog(this); + + protected static AtomicInteger thumbId = new AtomicInteger(0); + + /** + * @param key a QueryString representing pairs of keys and values. + * @return a Stream containing the thumbnail + */ + public Object createEntry(Object key) throws Exception { + + QueryString query = (QueryString) key; + String vre = query.get(CacheEntryConstants.vre); + String oid = query.get(CacheEntryConstants.oid); + int width = Integer.parseInt(query.get(CacheEntryConstants.width)); + int height = Integer.parseInt(query.get(CacheEntryConstants.height)); + String[] thumbOptions = query.get(CacheEntryConstants.thumbOptions).split(","); + + ArrayOfAlternativeRepresentation altRes; + List thumbs = new ArrayList(); + CMSPortType1PortType cms = null; + int k =0; + while(true) + { + cms = getCMS(vre); + try + { + altRes = cms.getAlternativeRepresentations(oid); + } + catch (Exception e) { + k++; + if(k == 5) + break; + else + continue; + } + AlternativeRepresentationDescription[] docRes = altRes.getDocumentRepresentations(); + if(docRes != null) + { + logger.debug("Found " + docRes.length + " alternative representations!!!"); + for(int i=0; i < docRes.length; i++) + { + String toid = docRes[i].getRepresentationID(); + if(docRes[i].getRepresentationRole().equals("thumbnail")) + { + logger.debug("Thumbnail Representation found: " + toid + "for object: " + oid + " description: " +docRes[i].getRepresenationDescription() + " role:" + docRes[i].getRepresentationRole()); + + QueryString newQuery = new QueryString(); + newQuery.addParameter(CacheEntryConstants.vre, vre); + newQuery.addParameter(CacheEntryConstants.oid, toid); + DocumentDescription docDescription = (DocumentDescription) CachesManager.getInstance().getContentCache().get(newQuery).getValue(); + DocumentPropertyDescription[] props = docDescription.getProperties(); + logger.debug("Properties available: " + props.length); + String[] resolution = getResolution(props); + if(resolution != null) + thumbs.add(resolution); + } + } + } + break; + } + String thoid; + String[] thumbObj = findThumbnail(thumbs, thumbOptions, height, width); + if(thumbObj == null && !containOption(thumbOptions, ThumbnailConstants.FORCE_CREATE)) + return null; + else if(thumbObj == null) + { + + while(true) + { + ThumbnailerPortType stub = getThumb(vre); + TransformContent params = new TransformContent(); + params.setOID(oid); + params.setHeight(width); + params.setWidth(height); + try + { + String tOid = stub.transformContent(params); + logger.debug("Object with id: " + oid + " was transformed to object " + tOid + "!"); + thoid = tOid; + } + catch (Exception e) { + continue; + } + break; + } + + } + else + thoid = thumbObj[2]; + + // The thumbnail existed or just created! Going to retrieve it from cms now!!! + GetDocumentParameters params = new GetDocumentParameters(); + params.setDocumentID(thoid); + params.setTargetFileLocation(BasicInfoObjectDescription.RAW_CONTENT_IN_MESSAGE); + params.setUnrollLevels(3); + + logger.debug("Calling cms to get the object"); + DocumentDescription docDescr = cms.getDocument(params ); + logger.debug("CMS call ended"); + return docDescr.getRawContent(); + + } + + private static ThumbnailerPortType getThumb(String vre) throws MalformedURIException, + ServiceException { + EndpointReference[] thumbURIs = null; + try { + + thumbURIs = RIsManager.getInstance().getISCache(GCUBEScope.getScope(vre)).getEPRsFor("Portal","Thumbnailer-service",SrvType.SIMPLE.name()); + } catch (Exception e2) { + // TODO Auto-generated catch block + e2.printStackTrace(); + } + String thumbAddress; + thumbAddress = thumbURIs[thumbId.getAndIncrement() % thumbURIs.length].getAddress().toString(); + ThumbnailerPortType thumb; + EndpointReferenceType endpoint = new EndpointReferenceType(); + endpoint.setAddress(new Address(thumbAddress)); + ThumbnailServiceAddressingLocator thumblocator = new ThumbnailServiceAddressingLocator(); + thumb = thumblocator.getThumbnailerPortTypePort(endpoint); + + GSSCredential cred = ApplicationCredentials.getInstance().getCredential(vre); + try { + thumb = ServiceContextManager.applySecurity(thumb, GCUBEScope.getScope(vre), cred); + } catch (MalformedScopeExpressionException e) { + return null; + } catch (Exception e) { + return null; + } + + return thumb; + } + + private String[] findThumbnail(List thumbs, String[] thumbOptions, int height, int width) { + if(thumbs == null || thumbs.size() == 0) + return null; + + String[] res = null; + for(int i = 0; i < thumbs.size(); i++) + { + String[] thumbnail = thumbs.get(i); + int wThumb = Integer.parseInt(thumbnail[0]); + int hThumb = Integer.parseInt(thumbnail[1]); + if(containOption(thumbOptions, ThumbnailConstants.EQUAL)) + { + if((height == hThumb && width >=wThumb)|| (height >= hThumb && width == wThumb)) + return thumbnail; + } + else if(containOption(thumbOptions, ThumbnailConstants.FLOOR)) + { + if(height >= hThumb && width >=wThumb) + { + if(res != null) + { + int w = Integer.parseInt(res[0]); + int h = Integer.parseInt(res[1]); + if(h < hThumb || w < wThumb) + res = thumbnail; + } + else + res = thumbnail; + } + } + else if(containOption(thumbOptions, ThumbnailConstants.CEIL)) + { + logger.debug("hThumb= " + hThumb + " wThumb= " + wThumb); + if(height <= hThumb && width <=wThumb) + { + if(res != null) + { + int w = Integer.parseInt(res[0]); + int h = Integer.parseInt(res[1]); + logger.debug("h= " + h + " w= " + w); + if(h > hThumb || w > wThumb) + res = thumbnail; + } + else + res = thumbnail; + } + } + } + return res; + } + + private boolean containOption(String[] thumbOptions, String option) { + for(int i=0; i < thumbOptions.length; i++) + { + if(thumbOptions[i].equals(option)) + return true; + } + return false; + } + + private String[] getResolution(DocumentPropertyDescription[] props) { + String[] resolution = new String[3]; + int x = 0; + for(int i=0; i< props.length && x < 2; i++) + { + logger.debug("Property: " + props[i].getName() + " with value: " + props[i].getValue()); + if(props[i].getName().equals("width")) + { + resolution[0] = props[i].getValue(); + x++; + } + else if(props[i].getName().equals("height")) + { + resolution[1] = props[i].getValue(); + x++; + } + } + resolution[2] = props[0].getObjectID(); + if(x < 2) + return null; + else + return resolution; + } + + protected static CMSPortType1PortType getCMS(String vre) throws MalformedURIException, + ServiceException { + + EndpointReference[] cmsURIs = null; + try { + + cmsURIs = RIsManager.getInstance().getISCache(GCUBEScope.getScope(vre)).getEPRsFor("ContentManagement","ContentManagementService",SrvType.SIMPLE.name()); + } catch (Exception e2) { + // TODO Auto-generated catch block + e2.printStackTrace(); + } + boolean excep = true; + String cmsAddress; + Random random = new Random(); + cmsAddress = cmsURIs[random.nextInt(cmsURIs.length)].getAddress().toString(); + CMSPortType1PortType cms; + EndpointReferenceType endpoint = new EndpointReferenceType(); + endpoint.setAddress(new Address(cmsAddress)); + CMSPortType1ServiceAddressingLocator cmslocator = new CMSPortType1ServiceAddressingLocator(); + cms = cmslocator.getCMSPortType1PortTypePort(endpoint); + try { + cms = ServiceContextManager.applySecurity(cms, GCUBEScope.getScope(vre), ApplicationCredentials.getInstance().getCredential(vre)); + } catch (MalformedScopeExpressionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return cms; + } + +} diff --git a/src/org/gcube/application/framework/core/commons/ProfileService.java b/src/org/gcube/application/framework/core/commons/ProfileService.java new file mode 100644 index 0000000..207761b --- /dev/null +++ b/src/org/gcube/application/framework/core/commons/ProfileService.java @@ -0,0 +1,206 @@ +package org.gcube.application.framework.core.commons; + +import java.rmi.RemoteException; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.axis.message.addressing.Address; +import org.apache.axis.message.addressing.EndpointReference; +import org.apache.axis.message.addressing.EndpointReferenceType; +import org.gcube.application.framework.core.cache.RIsManager; +import org.gcube.application.framework.core.security.ServiceContextManager; +import org.gcube.common.core.faults.GCUBEFault; +import org.gcube.common.core.scope.GCUBEScope; +import org.gcube.informationsystem.cache.SrvType; +import org.gcube.personalization.profileadministration.stubs.ProfileAdministrationPortType; +import org.gcube.personalization.profileadministration.stubs.service.ProfileAdministrationServiceAddressingLocator; +import org.gcube.personalization.userprofileaccess.stubs.UserProfileAccessFactoryPortType; +import org.gcube.personalization.userprofileaccess.stubs.UserProfileAccessPortType; +import org.gcube.personalization.userprofileaccess.stubs.service.UserProfileAccessFactoryServiceAddressingLocator; +import org.gcube.personalization.userprofileaccess.stubs.service.UserProfileAccessServiceAddressingLocator; +import org.gridforum.jgss.ExtendedGSSCredential; +import org.ietf.jgss.GSSCredential; + +/** + * @author Valia Tsagkalidou (NKUA) + * + */ +public class ProfileService { + + protected static AtomicInteger profileId = new AtomicInteger(0); + protected String username; + protected GCUBEScope scope; + + + /** + * The constructor + * @param username the user for each it will get the profile (Resource) + * @param scope the scope of the active VRE + */ + public ProfileService( String username, GCUBEScope scope) { + super(); + this.username = username; + this.scope = scope; + } + + /** + * @return UserProfileAccessFactoryPortType + */ + public UserProfileAccessFactoryPortType getUserProfileAccessFactory() + { + EndpointReference[] profileURIs; + try { + profileURIs = RIsManager.getInstance().getISCache(scope).getEPRsFor("Personalisation", "UserProfileAccess", SrvType.FACTORY.name()); //.getEndPointForPersonalizationUPAFactoryService(); + } catch (Exception e1) { + e1.printStackTrace(); + return null; + } + + System.out.println("getUserProfileAccessFactory: " + profileURIs.length); + EndpointReferenceType serviceEPR = new EndpointReferenceType(); + UserProfileAccessFactoryPortType upa = null; + + try + { + serviceEPR.setAddress(new Address(profileURIs[profileId.getAndIncrement()%profileURIs.length].getAddress().toString())); + UserProfileAccessFactoryServiceAddressingLocator upalocator = new UserProfileAccessFactoryServiceAddressingLocator(); + upa = upalocator.getUserProfileAccessFactoryPortTypePort(serviceEPR); + return upa; + + } + catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * @param cred the X509 credential + * @return UserProfileAccessPortType + */ + public UserProfileAccessPortType getUserProfileAccess(ExtendedGSSCredential cred) + { + UserProfileAccessFactoryPortType upa = getUserProfileAccessFactory(); + + + try { + upa = (UserProfileAccessFactoryPortType) ServiceContextManager.applySecurity(upa, scope, cred); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + EndpointReferenceType epr = null; + try { + System.out.println("\n\n\n\n" + username + " scope= " + scope + "\n\n\n\n"); + epr = upa.createResource(username); + } catch (GCUBEFault e) { + e.printStackTrace(); + } catch (RemoteException e) { + e.printStackTrace(); + } + if(epr != null) + { + try { + return getUserProfileAccessServicePortType(epr, scope, cred); + } catch (RemoteException e) { + e.printStackTrace(); + } + } + return null; + } + + + /** + * @param upa UserProfileAccessFactoryPortType + * @param cred an X509 credential + * @return UserProfileAccessPortType + */ + public UserProfileAccessPortType getUserProfileAccess(UserProfileAccessFactoryPortType upa, ExtendedGSSCredential cred) + { + + try { + + upa = (UserProfileAccessFactoryPortType) ServiceContextManager.applySecurity(upa, scope, cred); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + EndpointReferenceType epr = null; + try { + epr = upa.createResource(username); + } catch (GCUBEFault e) { + e.printStackTrace(); + } catch (RemoteException e) { + e.printStackTrace(); + } + if(epr != null) + { + try { + return getUserProfileAccessServicePortType(epr, scope, cred); + } catch (RemoteException e) { + e.printStackTrace(); + } + } + return null; + } + + /** + * This method returns the port type of the service User Profile Access. + * + * @param epr the endpoint reference of a WS resource of this service + * @param scope the gCube scope + * @param cred a X509 credential + * @return port for UserProfileAccess service + * @throws RemoteException an exception + */ + private UserProfileAccessPortType getUserProfileAccessServicePortType(EndpointReferenceType epr,GCUBEScope scope, GSSCredential cred) throws RemoteException { + UserProfileAccessServiceAddressingLocator instanceLocator = new UserProfileAccessServiceAddressingLocator(); + UserProfileAccessPortType port = null; + try { + port = instanceLocator.getUserProfileAccessPortTypePort(epr); + + + try { + port = (UserProfileAccessPortType) ServiceContextManager.applySecurity(port, scope, cred); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } catch (Exception e) { + throw new RemoteException("A service exception was thrown. Failed to get the port type of the service user profile access"); + } + return port; + } + + /** + * @param cred the X509 credential + * @return a port type for profile admin service + */ + public ProfileAdministrationPortType getProfileAdministration(GSSCredential cred) + { + EndpointReference[] profileURIs; + try { + profileURIs = RIsManager.getInstance().getISCache(scope).getEPRsFor("Personalisation", "ProfileAdministration", SrvType.SIMPLE.name()); //.getEndPointForPersonalizationPAService(); + } catch (Exception e1) { + e1.printStackTrace(); + return null; + } + EndpointReferenceType serviceEPR = new EndpointReferenceType(); + ProfileAdministrationPortType pa = null; + System.out.println("profile administration services: " + profileURIs.length); + try + { + serviceEPR.setAddress(new Address(profileURIs[profileId.getAndIncrement()%profileURIs.length].getAddress().toString())); + ProfileAdministrationServiceAddressingLocator palocator = new ProfileAdministrationServiceAddressingLocator(); + pa = palocator.getProfileAdministrationPortTypePort(serviceEPR); + pa = (ProfileAdministrationPortType) ServiceContextManager.applySecurity(pa, scope, cred); + return pa; + + } + catch (Exception e) { + e.printStackTrace(); + } + return null; + } +} diff --git a/src/org/gcube/application/framework/core/commons/model/CollectionInfo.java b/src/org/gcube/application/framework/core/commons/model/CollectionInfo.java new file mode 100644 index 0000000..74d0a76 --- /dev/null +++ b/src/org/gcube/application/framework/core/commons/model/CollectionInfo.java @@ -0,0 +1,189 @@ +package org.gcube.application.framework.core.commons.model; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.List; +import java.util.Vector; +import org.apache.axis.message.addressing.EndpointReferenceType; + + + +/** + * Collection's information + * @author valia, giotak, UoA + * + */ +public class CollectionInfo implements Serializable{ + + private static final long serialVersionUID = 1L; + protected String id; + protected String name; + protected String shortName; + protected String description; + protected String reference; + protected Vector schemata; + protected Vector metadataIDs; + protected Vector languages; + protected Vector indices; + protected HashMap> forward; + + /** + * @return collection's description + */ + public String getDescription() { + return description; + } + /** + * @param description collection's description + */ + public void setDescription(String description) { + this.description = description; + } + /** + * @return collection's ID + */ + public String getId() { + return id; + } + /** + * @param id collection's ID + */ + public void setId(String id) { + this.id = id; + } + /** + * @return collection's name + */ + public String getName() { + return name; + } + /** + * @param name collection's name + */ + public void setName(String name) { + this.name = name; + } + /** + * Constructor of the class + */ + public CollectionInfo() { + id = ""; + name = ""; + shortName = ""; + description = ""; + reference = ""; + schemata = new Vector(); + metadataIDs = new Vector(); + languages = new Vector(); + indices = new Vector(); + forward = new HashMap>(); + } + + /** + * @param i the position of the metadata schema + * @return the schema in the specified position. + */ + public String getSchema(int i) { + return schemata.get(i); + } + + /** + * @param i the position of the metadata schema + * @return metadata's ID + */ + public String getMetadataID(int i) { + return metadataIDs.get(i); + } + + /** + * @param i the position of the metadata schema + * @return the language for this schema + */ + public String getLanguage(int i) { + return languages.get(i); + } + + /** + * @param i the position of the metadata schema + * @return an object that contains info about the existence or not of specific indices + */ + public IndexInfo getIndexInfo(int i) { + return indices.get(i); + } + + /** + * @return the collection's short name + */ + public String getShortName() { + return shortName; + } + + /** + * @param shortName the collection's short name + */ + public void setShortName(String shortName) { + this.shortName = shortName; + } + + /** + * @param schema collection's schema name (e.g. dc, tei) + * @param metaID the ID of the metadata collection + * @param language metadata collection's language + * @param index the indices that collection has + */ + public void setMetadataCollection(String schema, String metaID, String language, IndexInfo index) + { + this.schemata.add(schema); + this.metadataIDs.add(metaID); + this.languages.add(language); + this.indices.add(index); + } + + /** + * @return the reference to this collection (usually a url) + */ + public String getReference() { + return reference; + } + + /** + * @param reference the reference to this collection (usually a url) + */ + public void setReference(String reference) { + this.reference = reference; + } + + /** + * @param schema metadata collection's schema + * @return true if this collection has a corresponding metadata collection with this schema, otherwise false. + */ + public boolean hasSchema(String schema) + { + return this.schemata.contains(schema); + } + + /** + * @param schema metadata collection's schema + * @return true if this collection has a corresponding metadata collection with this schema, otherwise false. + */ + public int getIndexOfSchema(String schema) + { + return this.schemata.indexOf(schema); + } + + /** + * @return the number of corrsponding metadata collections + */ + public int getMetadataSize() + { + return this.metadataIDs.size(); + } + + /** + * @return the forward indices stored in a hasmap. The key to the hasmap is collection together with the field, and the value is an EPR to the index. + */ + public HashMap> getForward() { + return forward; + } + +} diff --git a/src/org/gcube/application/framework/core/commons/model/IndexInfo.java b/src/org/gcube/application/framework/core/commons/model/IndexInfo.java new file mode 100644 index 0000000..4584d88 --- /dev/null +++ b/src/org/gcube/application/framework/core/commons/model/IndexInfo.java @@ -0,0 +1,73 @@ +package org.gcube.application.framework.core.commons.model; + +import java.io.Serializable; + +/** + * @author Valia Tsagkalidou (NKUA) + * + */ +public class IndexInfo implements Serializable{ + /** + * + */ + private static final long serialVersionUID = 1L; + protected boolean fts; + protected boolean geospatial; + protected boolean similarity; + + /** + * The constructor of the class + * + */ + public IndexInfo() { + super(); + fts = false; + geospatial = false; + similarity = false; + } + + /** + * @return whether an FTS index exists for this collection + */ + public boolean isFts() { + return fts; + } + + /** + * @return whether a geospatial index exists for this collection + */ + public boolean isGeospatial() { + return geospatial; + } + + /** + * @return whether a similarity index exists for this collection + */ + public boolean isSimilarity() { + return similarity; + } + + /** + * Sets the value whether a full text index exists + * @param fts true or false + */ + public void setFts(boolean fts) { + this.fts = fts; + } + + /** + * Sets the value whether a geo-spatial index exists + * @param geospatial true or false + */ + public void setGeospatial(boolean geospatial) { + this.geospatial = geospatial; + } + + /** + * Sets the value whether a similarity index exists + * @param similarity true or false + */ + public void setSimilarity(boolean similarity) { + this.similarity = similarity; + } +} diff --git a/src/org/gcube/application/framework/core/commons/model/SearchField.java b/src/org/gcube/application/framework/core/commons/model/SearchField.java new file mode 100644 index 0000000..1d2f55c --- /dev/null +++ b/src/org/gcube/application/framework/core/commons/model/SearchField.java @@ -0,0 +1,54 @@ +package org.gcube.application.framework.core.commons.model; + +import java.io.Serializable; + +/** + * + * @author Panagiota Koltsida (NKUA) + * @author Valia Tsagkalidou (NKUA) + * + */ +//TODO: Done!!! +public class SearchField implements Serializable, Cloneable{ + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Name of the criterion + */ + public String name; + + /** + * Value of the criterion + */ + public String value; + + /** + * Type of the criterion + */ + public String type; + + /** + * The x-path to apply for sorting the results + */ + public String sort; + + public SearchField() { + name = ""; + value = ""; + type = ""; + sort = ""; + } + + /* (non-Javadoc) + * @see java.lang.Object#clone() + */ + @Override + public SearchField clone() throws CloneNotSupportedException { + // TODO Auto-generated method stub + return (SearchField) super.clone(); + } + +} diff --git a/src/org/gcube/application/framework/core/security/JaasCallbackHandler.java b/src/org/gcube/application/framework/core/security/JaasCallbackHandler.java new file mode 100644 index 0000000..3704f84 --- /dev/null +++ b/src/org/gcube/application/framework/core/security/JaasCallbackHandler.java @@ -0,0 +1,43 @@ +package org.gcube.application.framework.core.security; + +import java.io.IOException; + +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.callback.UnsupportedCallbackException; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class JaasCallbackHandler implements CallbackHandler{ + + protected String username = null; + protected String password = null; + + private Log log = LogFactory.getLog(JaasCallbackHandler.class); + + public JaasCallbackHandler(String username, String password) { + super(); + this.username = username; + this.password = password; + } + + public void handle(Callback callbacks[]) + throws IOException, UnsupportedCallbackException { + for (int i = 0; i < callbacks.length; i++) { + if (callbacks[i] instanceof NameCallback) { + if (log.isDebugEnabled()) log.debug("responding to NameCallback"); + ((NameCallback) callbacks[i]).setName(username); + } else if (callbacks[i] instanceof PasswordCallback) { + if (log.isDebugEnabled()) log.debug("responding to PasswordCallback"); + ((PasswordCallback) callbacks[i]).setPassword(password != null ? password.toCharArray() : new char[0]); + } else { + if (log.isDebugEnabled()) log.debug("unsupported callback: " + callbacks[i].getClass()); + throw new UnsupportedCallbackException(callbacks[i]); + } + } + } + +} diff --git a/src/org/gcube/application/framework/core/security/LDAPAuthenticationModule.java b/src/org/gcube/application/framework/core/security/LDAPAuthenticationModule.java new file mode 100644 index 0000000..f888bfc --- /dev/null +++ b/src/org/gcube/application/framework/core/security/LDAPAuthenticationModule.java @@ -0,0 +1,72 @@ +package org.gcube.application.framework.core.security; + + +import javax.security.auth.login.AccountExpiredException; +import javax.security.auth.login.CredentialExpiredException; +import javax.security.auth.login.FailedLoginException; +import javax.security.auth.login.LoginContext; +import javax.security.auth.login.LoginException; + + + + +public class LDAPAuthenticationModule { + + public static String LDAP_HOST = "LDAP_HOST"; + public static String BASE_DN = "BASE_DN"; + + + private String contextName = "Gridsphere"; + //private String contextName = "AslLoginConf"; + + public LDAPAuthenticationModule () { + return; + } + + + + public boolean checkAuthentication(String username, String password) throws Exception { + + System.out.println("beginning authentication for " + username); + System.out.println("I am in ASL"); + + + LoginContext loginContext; + + // Create the LoginContext + try { + loginContext = new LoginContext(contextName, new JaasCallbackHandler(username, password)); + } catch (SecurityException e) { + e.printStackTrace(); + throw new Exception("key4", e); + } catch (LoginException e) { + e.printStackTrace(); + throw new Exception("key4", e); + } + + // Attempt login + try { + loginContext.login(); + } catch (FailedLoginException e) { + // throw new Exception("key4", e); + e.printStackTrace(); + return false; + } catch (AccountExpiredException e) { + //throw new Exception("key1"); + e.printStackTrace(); + return false; + } catch (CredentialExpiredException e) { + // throw new Exception("key2", e); + e.printStackTrace(); + return false; + } catch (Exception e) { + // throw new Exception("key3", e); + return false; + } + System.out.println("ASL returning value true"); + return true; + + } + + +} diff --git a/src/org/gcube/application/framework/core/security/PortalSecurityManager.java b/src/org/gcube/application/framework/core/security/PortalSecurityManager.java new file mode 100644 index 0000000..dd87934 --- /dev/null +++ b/src/org/gcube/application/framework/core/security/PortalSecurityManager.java @@ -0,0 +1,89 @@ +package org.gcube.application.framework.core.security; + +import java.io.BufferedReader; +import java.io.StringReader; +import java.util.List; + +import org.gcube.application.framework.core.cache.CachesManager; +import org.gcube.application.framework.core.session.D4ScienceSession; +import org.gcube.application.framework.core.util.CacheEntryConstants; +import org.gcube.application.framework.core.util.QueryString; +import org.gcube.application.framework.core.util.SessionConstants; +import org.gcube.application.framework.core.vremanagement.model.ISGenericResource; +import org.gcube.common.core.scope.GCUBEScope; +import org.gcube.common.core.security.GCUBESecurityManagerImpl; +import org.gcube.common.core.utils.logging.GCUBELog; +import org.kxml2.io.KXmlParser; + +/** + * @author Valia Tsagkalidou (KNUA) + * + */ +public class PortalSecurityManager extends GCUBESecurityManagerImpl { + + /** Object logger. */ + protected final GCUBELog logger = new GCUBELog(this); + + public PortalSecurityManager(GCUBEScope scope) { + super(); + this.scope = scope; + } + + public PortalSecurityManager(D4ScienceSession session) { + super(); + this.scope = session.getScope(); + } + + GCUBEScope scope; + + + @Override + public boolean isSecurityEnabled() { + QueryString query = new QueryString(); + query.put(CacheEntryConstants.vreResource, "true"); + query.put(CacheEntryConstants.vre, scope.toString()); + List res = (List)CachesManager.getInstance().getGenericResourceCache().get(query).getValue(); + if(res == null || res.size() == 0) + return false; + else + { + try { + return parseBody(res.get(0).getBody()); + } catch (Exception e) { + logger.error("",e); + return false; + } + } + } + + /** + * Loads from the Body element the resource information + * @param body the Body of the generic resource + * @throws Exception if the element is not valid or well formed + */ + private boolean parseBody(String body) throws Exception { + KXmlParser parser = new KXmlParser(); + parser.setInput(new BufferedReader(new StringReader(body))); + loop: while (true) { + try { + switch (parser.next()) { + case KXmlParser.START_TAG: + if (parser.getName().equals("SecurityEnabled")) + { + boolean res = Boolean.valueOf(parser.nextText()).booleanValue(); + logger.debug("Found value:" + res); + return res; + } + else parser.nextText();//just skip the text + break; + case KXmlParser.END_DOCUMENT: break loop; + } + } catch (Exception e) { + logger.error("",e); + throw new Exception ("Unable to parse the ScopeResource body"); + } + } + return false; + } + +} diff --git a/src/org/gcube/application/framework/core/security/ServiceContextManager.java b/src/org/gcube/application/framework/core/security/ServiceContextManager.java new file mode 100644 index 0000000..2934c6a --- /dev/null +++ b/src/org/gcube/application/framework/core/security/ServiceContextManager.java @@ -0,0 +1,37 @@ +package org.gcube.application.framework.core.security; + +import java.rmi.Remote; + +import org.gcube.application.framework.core.session.D4ScienceSession; +import org.gcube.common.core.contexts.GCUBERemotePortTypeContext; +import org.gcube.common.core.scope.GCUBEScope; +import org.gcube.common.core.scope.GCUBEScope.MalformedScopeExpressionException; +import org.gcube.common.core.security.GCUBESecurityManager; +import org.ietf.jgss.GSSCredential; + +public class ServiceContextManager { + + public static PORTTYPE applySecurity(PORTTYPE stub, D4ScienceSession session) throws MalformedScopeExpressionException, Exception + { + GCUBESecurityManager secManager = new PortalSecurityManager(session); + if(secManager.isSecurityEnabled()) + { + secManager.useCredentials(session.getCredential()); + } + return GCUBERemotePortTypeContext.getProxy(stub , session.getScope(), secManager); + + } + + + public static PORTTYPE applySecurity(PORTTYPE stub, GCUBEScope scope, GSSCredential cred) throws MalformedScopeExpressionException, Exception + { + GCUBESecurityManager secManager = new PortalSecurityManager(scope); + if(secManager.isSecurityEnabled()) + { + secManager.useCredentials(cred); + } + return GCUBERemotePortTypeContext.getProxy(stub , scope, secManager); + + } + +} diff --git a/src/org/gcube/application/framework/core/security/VOMSAdminManager.java b/src/org/gcube/application/framework/core/security/VOMSAdminManager.java new file mode 100644 index 0000000..6895425 --- /dev/null +++ b/src/org/gcube/application/framework/core/security/VOMSAdminManager.java @@ -0,0 +1,35 @@ +package org.gcube.application.framework.core.security; + +import java.io.File; + +import org.gcube.application.framework.core.util.Settings; +import org.gcube.vomanagement.vomsAdmin.impl.VOMSAdminImpl; + +/** + * @author Valia Tsagkalidou (NKUA) + * + */ +public class VOMSAdminManager { + + /** + * + */ + protected static VOMSAdminImpl vomsAdmin= null; + + /** + * @return + */ + public static VOMSAdminImpl getVOMSAdmin() + { + if(vomsAdmin == null) + { + try { + vomsAdmin = new VOMSAdminImpl(Settings.getInstance().getProperty("sharedDir")+ File.separator + "vomsAPI.properties"); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + return vomsAdmin; + } +} diff --git a/src/org/gcube/application/framework/core/session/D4ScienceSession.java b/src/org/gcube/application/framework/core/session/D4ScienceSession.java new file mode 100644 index 0000000..f9aa852 --- /dev/null +++ b/src/org/gcube/application/framework/core/session/D4ScienceSession.java @@ -0,0 +1,222 @@ +package org.gcube.application.framework.core.session; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Set; + +import org.gcube.application.framework.core.cache.CachesManager; +import org.gcube.application.framework.core.security.PortalSecurityManager; +import org.gcube.application.framework.core.util.SessionConstants; +import org.gcube.application.framework.core.util.UserCredential; +import org.gcube.common.core.scope.GCUBEScope; +import org.gridforum.jgss.ExtendedGSSCredential; + +/** + * @author Valia Tsagkalidou (NKUA) + * + */ +public class D4ScienceSession{ + + /** + * + */ + private static final long serialVersionUID = 1L; + private HashMap innerSession; + private long lastUsedTime; + private String externalSessionID; + private String username; + private ExtendedGSSCredential credential; + private GCUBEScope scope; + private HashMap notifiers; + + /** + * A constructor based on the user and an external ID + * @param externalSessionId the external id + * @param user the username + */ + D4ScienceSession(String externalSessionId, String user) + { + innerSession = new HashMap(); + notifiers = new HashMap(); + lastUsedTime = System.currentTimeMillis(); + username = user; + externalSessionID = externalSessionId; + } + + private void initializeAttributes() { + } + + /** + * @return whether the session is still valid or not + */ + public boolean isValid() + { + if((System.currentTimeMillis() - lastUsedTime) > 1800000) // 30 minutes + return false; + return true; + } + + /** + * @return whether the session is empty or not + */ + public boolean isEmpty() + { + lastUsedTime = System.currentTimeMillis(); + return innerSession.isEmpty(); + } + + /** + * @param name the name of the attribute + * @return whether the name attribute exists in the session + */ + public boolean hasAttribute(String name) + { + lastUsedTime = System.currentTimeMillis(); + return innerSession.containsKey(name); + } + + /** + * @return a set of all the attributes in the session + */ + public Set getAttributeNames() + { + lastUsedTime = System.currentTimeMillis(); + return innerSession.keySet(); + } + + /** + * @param name the name of the attribute + * @return the value of the named attribute + */ + public Object getAttribute(String name) + { + lastUsedTime = System.currentTimeMillis(); + return innerSession.get(name); + } + + /** + * @param name the name of the attribute + * @param value the value of the attribute + */ + public void setAttribute(String name, Object value) + { + lastUsedTime = System.currentTimeMillis(); + innerSession.put(name, value); + } + + /** + * Removes the named attribute from the session + * @param name the name of the attribute + * @return the removed object + */ + public Object removeAttribute(String name) + { + lastUsedTime = System.currentTimeMillis(); + return innerSession.remove(name); + } + + /** + * Removes all the attributes from the session + */ + public void removeAll() + { + lastUsedTime = System.currentTimeMillis(); + innerSession.clear(); + } + + /** + * invalidates the session + */ + public void invalidate() + { + lastUsedTime = System.currentTimeMillis() - 2000000; //more than 30 minutes + } + + /** + * @return the credential + */ + public ExtendedGSSCredential getCredential() { + return credential; + } + + /** + * @return the external session id (passed to the constructor) + */ + public String getExternalSessionID() { + return externalSessionID; + } + + /** + * @return the username + */ + public String getUsername() { + return username; + } + + /** + * @return the scope + */ + public GCUBEScope getScope() { + return scope; + } + + /** + * @return the name of the scope (VRE) + */ + public String getScopeName() + { + return scope.toString(); + } + + /** + * @param scope the scope name (VRE) + */ + public void setScope(String scope) { + lastUsedTime = System.currentTimeMillis(); + String[] split = scope.trim().substring(1).split("/",2); + String vo = "/" + split[0].toLowerCase(); + if(split.length > 1) + vo += "/" + split[1]; + System.out.println("*** VRE to be set:" + vo + " ***"); + this.scope = GCUBEScope.getScope(vo); + if(new PortalSecurityManager(this.scope).isSecurityEnabled()) + this.credential = UserCredential.getCredential(username, scope); + innerSession.clear(); + initializeAttributes(); + } + + /** + * @param notification the name of the notification to wait for + * @throws InterruptedException when the thread is interrupted + */ + public void waitNotification(String notification) throws InterruptedException + { + Notifier notifier = notifiers.get(notification); + if(notifier == null) + { + notifier = new Notifier(); + notifiers.put(notification, notifier); + } + + lastUsedTime = System.currentTimeMillis(); + notifier.waitNotification(); + } + + /** + * @param notification the name of the notification to send notification + * @throws InterruptedException when the thread is interrupted + */ + public void notifyAllWaiting(String notification) throws InterruptedException + { + Notifier notifier = notifiers.get(notification); + if(notifier == null) + { + notifier = new Notifier(); + notifiers.put(notification, notifier); + } + + lastUsedTime = System.currentTimeMillis(); + notifier.notifyAllWaiting(); + } +} diff --git a/src/org/gcube/application/framework/core/session/Notifier.java b/src/org/gcube/application/framework/core/session/Notifier.java new file mode 100644 index 0000000..904f269 --- /dev/null +++ b/src/org/gcube/application/framework/core/session/Notifier.java @@ -0,0 +1,25 @@ +package org.gcube.application.framework.core.session; + +import java.util.concurrent.Semaphore; + +class Notifier { + + Semaphore sem; + + Notifier() { + sem = new Semaphore(0, true); + } + + + public void waitNotification() throws InterruptedException + { + sem.acquire(); + System.out.println("\n\njust woke up!!!\n\n"); + } + + public void notifyAllWaiting() throws InterruptedException + { + System.out.println("Sending wake up signal to " + sem.getQueueLength() + " receivers..."); + sem.release(sem.getQueueLength()); + } +} diff --git a/src/org/gcube/application/framework/core/session/SessionManager.java b/src/org/gcube/application/framework/core/session/SessionManager.java new file mode 100644 index 0000000..200d36a --- /dev/null +++ b/src/org/gcube/application/framework/core/session/SessionManager.java @@ -0,0 +1,75 @@ +package org.gcube.application.framework.core.session; + +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Set; + + +public class SessionManager { + + protected static Thread thread = new CleanSessionThread(); + protected static SessionManager sessionManager = new SessionManager(); + protected HashMap sessions; + + protected SessionManager() { + sessions = new HashMap(); + thread.setDaemon(true); + thread.start(); + } + + public static SessionManager getInstance() { + return sessionManager; + } + + public D4ScienceSession getD4ScienceSession(String externalSessionID, String username) + { + D4ScienceSession session = sessions.get(externalSessionID + "_" + username); + if(session == null || !session.isValid() || !session.getUsername().equals(username)) + { + session = new D4ScienceSession(externalSessionID, username); + sessions.put(externalSessionID + "_" + username, session); + } + return session; + } + + @Override + protected void finalize() throws Throwable { + thread.interrupt(); + System.out.println(new Date(System.currentTimeMillis()) + " clean thread was interrupted"); + thread.join(); + System.out.println(new Date(System.currentTimeMillis()) + " clean thread was joint"); + super.finalize(); + } + + + protected static class CleanSessionThread extends Thread + { + public void run() + { + while(true) + { + try { + Thread.sleep(600000); + } catch (InterruptedException e) { + e.printStackTrace(); + System.out.println(new Date(System.currentTimeMillis()) + " clean thread was interrupted (in clean thread)"); + break; + } + //TODO: cleanup invalid sessions: add locks... + Set keys = sessionManager.sessions.keySet(); + Iterator iter = keys.iterator(); + while(iter.hasNext()) + { + String extSessionID = iter.next(); + if(!sessionManager.sessions.get(extSessionID).isValid()) + { + sessionManager.sessions.remove(extSessionID); + } + } + } + System.out.println(new Date(System.currentTimeMillis()) + " clean thread was terminated"); + } + + } +} diff --git a/src/org/gcube/application/framework/core/util/CacheEntryConstants.java b/src/org/gcube/application/framework/core/util/CacheEntryConstants.java new file mode 100644 index 0000000..d3d7f38 --- /dev/null +++ b/src/org/gcube/application/framework/core/util/CacheEntryConstants.java @@ -0,0 +1,59 @@ +package org.gcube.application.framework.core.util; + +/** + * @author Valia Tsagkalidou (KNUA) + * + */ +public class CacheEntryConstants { + + /** + * Cache constant for VRE + */ + public static final String vre = "vre"; + + /** + * Cache constant for oid + */ + public static final String oid = "oid"; + + /** + * Cache constant for metadataColID + */ + public static final String metadataColID = "metadataColID"; + + /** + * Cache constant for name + */ + public static final String name = "name"; + + /** + * Cache constant for id + */ + public static final String id = "id"; + + /** + * Cache constant for username + */ + public static final String username = "username"; + + /** + * Cache constant for width + */ + public static final String width = "width"; + + /** + * Cache constant for height + */ + public static final String height = "height"; + + /** + * thumbOptions + */ + public static final String thumbOptions = "thumbOptions"; + + /** + * vreResource + */ + public static final String vreResource = "vreResource"; + +} diff --git a/src/org/gcube/application/framework/core/util/FindInfo.java b/src/org/gcube/application/framework/core/util/FindInfo.java new file mode 100644 index 0000000..82f54cc --- /dev/null +++ b/src/org/gcube/application/framework/core/util/FindInfo.java @@ -0,0 +1,220 @@ +package org.gcube.application.framework.core.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.regex.Pattern; + +import org.gcube.application.framework.core.commons.model.CollectionInfo; +import org.gcube.application.framework.core.commons.model.SearchField; + +/** + * @author Valia Tsagkalidou (KNUA) + * + */ +public class FindInfo { + + public static final String ALL = "ALL"; + public static final String NAME = "NAME"; + public static final String DESCRIPTION = "DESCRIPTION"; + + /** + * @param colID + * @param collections + * @return + */ + public static CollectionInfo findCollectionInfo(String colID, List[] collections) + { + if (collections != null) { + for(int counter=0; counter < collections.length;counter++) + { + for(int c2=1; c2 < collections[counter].size(); c2++) + { + if(collections[counter].get(c2).getId().equals(colID)) + { + return collections[counter].get(c2); + } + } + } + } + else { + System.out.println("No collections!!"); + return null; + } + return null; + } + + /** + * @param metadataColID + * @param collections + * @return + */ + public static CollectionInfo findCollectionInfoFromMetadata(String metadataColID, List[] collections) + { + for(int counter=0; counter < collections.length;counter++) + { + for(int c2=1; c2 < collections[counter].size(); c2++) + { + for(int c3=0; c3 < collections[counter].get(c2).getMetadataSize(); c3++) + { + if(collections[counter].get(c2).getMetadataID(c3).equals(metadataColID)) + { + return collections[counter].get(c2); + } + } + } + } + return null; + } + + + + + /** + * @param term + * @param whereToSearch + * @param collections + * @return + */ + public static List searchCollectionInfo(String term, String whereToSearch, List[] collections) + { + term = term.trim().toLowerCase(); + if(term.startsWith("*")) + { + term = term.substring(1); + } + else + { + term = "(\\s|\\p{Punct})" + term; + } + if(term.endsWith("*")) + { + term = term.substring(0,term.length()-1); + } + else + { + term = term + "(\\s|\\p{Punct})"; + } + term = term.replaceAll("\\x2A", ".*"); + term = term.replaceAll("\\x3F", "."); + Pattern pattern = Pattern.compile(term); + + boolean name = false, descr = false; + if(whereToSearch.equals(FindInfo.ALL)) + { + name = true; + descr = true; + } + else if(whereToSearch.equals(FindInfo.NAME)) + { + name = true; + } + else if(whereToSearch.equals(FindInfo.DESCRIPTION)) + { + descr = true; + } + List res = new ArrayList(); + for(int counter=0; counter < collections.length;counter++) + { + for(int c2=0; c2 < collections[counter].size(); c2++) + { + if(name) + { + if(pattern.matcher(" " + collections[counter].get(c2).getName().toLowerCase() + " ").find()) + { + res.add(collections[counter].get(c2)); + continue; + } + } + if(descr) + { + if(pattern.matcher(" " + collections[counter].get(c2).getDescription().toLowerCase() + " ").find()) + { + res.add(collections[counter].get(c2)); + continue; + } + } + } + } + return res; + } + + /** + * @param schemaName + * @param collection + * @return + */ + public static int findCollectionSchema(String schemaName, CollectionInfo collection) + { + for(int counter =0; counter < collection.getMetadataSize(); counter++) + { + if(collection.getSchema(counter).equals(schemaName)) + { + return counter; + } + } + return -1; + } + + public static int findCollectionSchema(String schemaName, String schemaLanguage, CollectionInfo collection) { + for (int counter = 0; counter < collection.getMetadataSize(); counter++) { + if (collection.getSchema(counter).equals(schemaName)) + { + if (collection.getLanguage(counter).equals(schemaLanguage)) + return counter; + } + } + return -1; + } + + /** + * @param name + * @param schemaName + * @param SchemaHashMap + * @return + */ + public static int findCriterion(String name, String schemaName, HashMap> SchemaHashMap) + { + List schemaCriteria = SchemaHashMap.get(schemaName); + for(int counter = 0; counter < schemaCriteria.size(); counter++) + {// finding details regarding this criterion + if(schemaCriteria.get(counter).name.equals(name)) + { + return counter; + } + } + return -1; + } + + + /** + * @param collections the available collections in a hierarchical structure + * @return an Array of two hashmaps: + * [0] => contains pairs of + * [1] => contains pairs of + */ + public static HashMap[] getCollectionNames(List[] collections) + { + HashMap[] collectionArray = new HashMap[2]; + collectionArray[0] = new HashMap(); + collectionArray[1] = new HashMap(); + if(collections == null) + return collectionArray; + for(int i=0; i< collections.length; i++) + { + for(int k=0; k < collections[i].size(); k++) + { + for(int j=0; j< collections[i].get(k).getMetadataSize(); j++) + { + collectionArray[0].put(collections[i].get(k).getMetadataID(j), collections[i].get(k).getName()); + collectionArray[1].put(collections[i].get(k).getMetadataID(j), collections[i].get(k).getShortName()); + } + collectionArray[0].put(collections[i].get(k).getId(), collections[i].get(k).getName()); + collectionArray[1].put(collections[i].get(k).getId(), collections[i].get(k).getShortName()); + } + } + return collectionArray; + } + + +} diff --git a/src/org/gcube/application/framework/core/util/NotificationConstants.java b/src/org/gcube/application/framework/core/util/NotificationConstants.java new file mode 100644 index 0000000..77e9f72 --- /dev/null +++ b/src/org/gcube/application/framework/core/util/NotificationConstants.java @@ -0,0 +1,11 @@ +package org.gcube.application.framework.core.util; + +/** + * @author Valia Tsagkalidou (KNUA) + * + */ +public class NotificationConstants { + + public static final String CollectionsStatusChange = "CollectionsStatusChange"; + +} diff --git a/src/org/gcube/application/framework/core/util/QueryString.java b/src/org/gcube/application/framework/core/util/QueryString.java new file mode 100644 index 0000000..ddad06b --- /dev/null +++ b/src/org/gcube/application/framework/core/util/QueryString.java @@ -0,0 +1,30 @@ +package org.gcube.application.framework.core.util; + +import java.util.HashMap; + +/** + * @author Valia Tsagkalidou (KNUA) + * + */ +public class QueryString extends HashMap{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + public QueryString() { + super(); + } + + public void addParameter(String name, String value) + { + this.put(name, value); + } + + public void removeParameter(String name) + { + this.remove(name); + } + +} diff --git a/src/org/gcube/application/framework/core/util/SchemataInfos.java b/src/org/gcube/application/framework/core/util/SchemataInfos.java new file mode 100644 index 0000000..1ac8251 --- /dev/null +++ b/src/org/gcube/application/framework/core/util/SchemataInfos.java @@ -0,0 +1,55 @@ +package org.gcube.application.framework.core.util; + + +public class SchemataInfos { + + String schemaName; + String schemaLanguage; + + public SchemataInfos () { + schemaName = new String(); + schemaLanguage = new String(); + } + + public SchemataInfos (String name, String language) { + schemaName = name; + schemaLanguage = language; + } + + public String getName() { + return schemaName; + } + + + public String getLanguage() { + return schemaLanguage; + } + + public void setName(String name) { + schemaName = name; + } + + public void setLanguage (String lang) { + schemaLanguage = lang; + } + + public Boolean isEqual (SchemataInfos si) { + if ((si.getName().equals(this.getName())) && (this.getLanguage().equals(this.getLanguage()))) + return true; + else + return false; + } + + public SchemataInfos clone () { + SchemataInfos newSchInfo = new SchemataInfos(); + String name = new String(schemaName); + String schLang = new String(schemaLanguage); + newSchInfo.setName(name); + newSchInfo.setLanguage(schLang); + + return newSchInfo; + } + + } + + diff --git a/src/org/gcube/application/framework/core/util/SessionConstants.java b/src/org/gcube/application/framework/core/util/SessionConstants.java new file mode 100644 index 0000000..8dd6b12 --- /dev/null +++ b/src/org/gcube/application/framework/core/util/SessionConstants.java @@ -0,0 +1,119 @@ +package org.gcube.application.framework.core.util; + +/** + * @author Valia Tsagkalidou (KNUA) + * + */ +public class SessionConstants { + + /** + * Used for generic resource name which contains the static search configuration + */ + public static final String ScenarioSchemaInfo = "ScenarioCollectionInfo"; + + /** + * Used for a variable in the session representing a HashMap>: + * pairs: (schema, list of searchable fields for this schema) + */ + public static final String SchemataInfo = "SchemataInfo"; + + /** + * Used for generic resource name which contains info about searchable fields per schema... + */ + public static final String MetadataSchemaInfo = "MetadataSchemaInfo"; + + /** + * Used for a variable in the session representing the available collections + */ + public static final String Collections = "Collections"; + + /** + * Used for a variable in the session representing the available queries (queries that the user has created) + */ + public static final String Queries = "Queries"; + + /** + * Used for a variable in the session that contains info for the geospatial search (boundinf box, time interval, etc) + */ + public static final String Geospatial = "Geospatial"; + + /** + * Used for a variable in the session representing the number of the current page number in the results. + */ + public static final String page_no = "page_no"; + + /** + * Used for a variable in the session representing how many results were actually read from resultset last time + */ + public static final String resNo = "resNo"; + + /** + * Used for a variable in the session representing the total number of result pages... + */ + public static final String page_total = "page_total"; + + /** + * Used for a variable in the session representing the index in the current resultset part (where we stopped reading results last time) + */ + public static final String lastRes = "lastRes"; + + /** + * Used for a variable in the session representing whether we have reach the last page of results + */ + public static final String isLast = "isLast"; + + /** + * Used for a variable in the session that contains info about whether we have go beyond the edges of results... (out of index) + */ + public static final String out_of_end = "out_of_end"; + + /** + * the current resultset client + */ + public static final String rsClient = "rsClient"; + + /** + * the results objects already processed from the resultset + */ + public static final String theResultObjects = "theResultObjects"; + + /** + * the thumbnail urls for each result object (already processed from the resultset ) + */ + public static final String theThumbnails = "theThumbnails"; + + /** + * the index in the result objects from where we should start reading + */ + public static final String startingPoint = "startingPoint"; + + /** + * what type search was applied (Simple, Advanced, Browse, Quick, Google, etc) + */ + public static final String sourcePortlet = "sourcePortlet"; + + /** + * the resultset EPR (not used any more) + */ + public static final String rsEPR = "rsEPR"; /* the Result Set EPR */ + + /** + * whether to show result rank or not + */ + public static final String showRank = "showRank"; + + /** + * an exception occured during search: message to the users + */ + public static final String searchException = "searchException"; + + /** + * the id of the active query + */ + public static final String activeQueryNo = "activeQueryNo"; + + /** + * the id of the active query to be presented + */ + public static final String activePresentationQueryNo = "activePresentationQueryNo"; +} diff --git a/src/org/gcube/application/framework/core/util/Settings.java b/src/org/gcube/application/framework/core/util/Settings.java new file mode 100644 index 0000000..cc42fcc --- /dev/null +++ b/src/org/gcube/application/framework/core/util/Settings.java @@ -0,0 +1,58 @@ +package org.gcube.application.framework.core.util; + +import java.io.*; +import java.util.*; +import java.net.URISyntaxException; + +public class Settings { + + static Properties props = new Properties(); + static Settings settings = null; + + Settings() + { + try + { + props.load(Settings.class.getResourceAsStream("/etc/settings.properties")); + + } + catch (FileNotFoundException e) + { + // TODO Auto-generated catch block + e.printStackTrace(); + } + catch (IOException e) + { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public static Settings getInstance() + { + if (settings == null) + settings = new Settings(); + return settings; + } + + /** + * @return the props + */ + public String getProperty(String key) { + String value = props.getProperty(key); + if(value.contains("${")) + { + int start = 0; + int i; + while((i= value.indexOf("${", start)) != -1) + { + start = value.indexOf("}", i) +1; + String reg = value.substring(i, start); + System.out.println(reg); + System.out.println(reg.substring(2, reg.length() -1)); + value = value.replace(reg, (System.getProperty(reg.substring(2, reg.length() -1)) != null)?System.getProperty(reg.substring(2, reg.length() -1)):""); + } + } + return value; + } +} diff --git a/src/org/gcube/application/framework/core/util/ThumbnailConstants.java b/src/org/gcube/application/framework/core/util/ThumbnailConstants.java new file mode 100644 index 0000000..cf8dead --- /dev/null +++ b/src/org/gcube/application/framework/core/util/ThumbnailConstants.java @@ -0,0 +1,14 @@ +package org.gcube.application.framework.core.util; + +public class ThumbnailConstants { + + public static final String EQUAL = "EQUAL"; + + public static final String CEIL = "CEIL"; + + public static final String FLOOR = "FLOOR"; + + public static final String FORCE_CREATE = "FORCE_CREATE"; + + public static final String NO_FORCE_CREATE = "NO_FORCE_CREATE"; +} diff --git a/src/org/gcube/application/framework/core/util/TransformXSLT.java b/src/org/gcube/application/framework/core/util/TransformXSLT.java new file mode 100644 index 0000000..41b19f4 --- /dev/null +++ b/src/org/gcube/application/framework/core/util/TransformXSLT.java @@ -0,0 +1,120 @@ +package org.gcube.application.framework.core.util; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringWriter; + +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; + +import org.apache.xml.serialize.OutputFormat; +import org.apache.xml.serialize.XMLSerializer; +import org.w3c.dom.Document; + +/** + * @author Valia Tsagkalidou (KNUA) + * + */ +public class TransformXSLT { + /** + * Transforms an xml document based on the given xslt + * @param xslt the xslt for transforming the xml + * @param xml the xml to be transformed + * @return a string containing the transformed xml (output of the transformation) + */ + public static String transform(String xslt, String xml) + { + Transformer transformer; + try + {//Retrieve the XSLT from the DIS (generic resource), and create the transformer + ByteArrayInputStream xsltStream = new ByteArrayInputStream(xslt.getBytes()); + TransformerFactory tFactory = TransformerFactory.newInstance(); + transformer = tFactory.newTransformer(new StreamSource(xsltStream)); + + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + Document doc = null; + + doc = dfactory.newDocumentBuilder().parse(xml); + // Apply the transformation + ByteArrayOutputStream ba_stream = new ByteArrayOutputStream(); + OutputFormat format = new OutputFormat(doc); + format.setIndenting(false); + format.setOmitDocumentType(true); + format.setOmitXMLDeclaration(true); + StringWriter writer = new StringWriter(); + XMLSerializer serial = new XMLSerializer(writer,format); + serial.serialize(doc); + transformer.transform(new StreamSource(new ByteArrayInputStream(writer.toString().getBytes())), new StreamResult(ba_stream)); + //Prepares the object to be returned + StringBuffer buffer = new StringBuffer(); + try { + InputStreamReader isr = new InputStreamReader( new ByteArrayInputStream(ba_stream.toByteArray()), + "UTF8"); + Reader in2 = new BufferedReader(isr); + int ch; + while ((ch = in2.read()) > -1) { + buffer.append((char)ch); + } + in2.close(); + return buffer.toString(); + } catch (Exception e) { + e.printStackTrace(); + } + } + catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * Transforms an xml document based on the given transformer + * @param transformer the transformer based on which the transformation will be applied + * @param xml the xml document to be transformed + * @return a string containing the transformed xml (output of the transformation) + */ + public static String transform(Transformer transformer, String xml) + { + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + Document doc = null; + + try + { + doc = dfactory.newDocumentBuilder().parse(xml); + ByteArrayOutputStream ba_stream = new ByteArrayOutputStream(); + OutputFormat format = new OutputFormat(doc); + format.setIndenting(false); + format.setOmitDocumentType(true); + format.setOmitXMLDeclaration(true); + StringWriter writer = new StringWriter(); + XMLSerializer serial = new XMLSerializer(writer,format); + serial.serialize(doc); + transformer.transform(new StreamSource(new ByteArrayInputStream(writer.toString().getBytes())), new StreamResult(ba_stream)); + //Prepares the object to be returned + StringBuffer buffer = new StringBuffer(); + try { + InputStreamReader isr = new InputStreamReader( new ByteArrayInputStream(ba_stream.toByteArray()), + "UTF8"); + Reader in2 = new BufferedReader(isr); + int ch; + while ((ch = in2.read()) > -1) { + buffer.append((char)ch); + } + in2.close(); + return buffer.toString(); + } catch (Exception e) { + e.printStackTrace(); + } + } + catch (Exception e) { + e.printStackTrace(); + } + return null; + } +} diff --git a/src/org/gcube/application/framework/core/util/UserCredential.java b/src/org/gcube/application/framework/core/util/UserCredential.java new file mode 100644 index 0000000..7e44103 --- /dev/null +++ b/src/org/gcube/application/framework/core/util/UserCredential.java @@ -0,0 +1,42 @@ +package org.gcube.application.framework.core.util; + +import java.io.File; + +import org.gcube.vomanagement.vomsAdmin.impl.VOMSAdminImpl; +import org.gcube.vomanagement.vomsClient.impl.CredentialsManagerImpl; +import org.gridforum.jgss.ExtendedGSSCredential; + +/** + * @author Valia Tsagkalidou (NKUA) + * + */ +public class UserCredential { + /** + * Retrieves credential for users + * @param username the user name for which it will retrieve credential + * @param DLname DLname + * @return the GSS Credential + */ + public static ExtendedGSSCredential getCredential(String username, String DLname) + { + CredentialsManagerImpl man = null; + try { + String sharedDir = Settings.getInstance().getProperty("sharedDir"); + System.out.println("file " + sharedDir + "/vomsAPI.properties exists: "+ new File(sharedDir + "/vomsAPI.properties").exists()); + man = new CredentialsManagerImpl(sharedDir + "/vomsAPI.properties"); + // VOMSAdminImpl vomsAdm = new VOMSAdminImpl(sharedDir + "/vomsAPI.properties"); + // man = new CredentialsManagerImpl(vomsAdm); + } catch (Exception e1) { + e1.printStackTrace(); + } + ExtendedGSSCredential cred = null; + try { + //TODO: put a real password there... + cred = man.getCredentials(username, "", DLname); + } catch (Exception e) { + e.printStackTrace(); + } + return cred; + } + +} diff --git a/src/org/gcube/application/framework/core/vremanagement/GenericResourceInfoI.java b/src/org/gcube/application/framework/core/vremanagement/GenericResourceInfoI.java new file mode 100644 index 0000000..c6b9cb3 --- /dev/null +++ b/src/org/gcube/application/framework/core/vremanagement/GenericResourceInfoI.java @@ -0,0 +1,70 @@ +package org.gcube.application.framework.core.vremanagement; + +import java.rmi.RemoteException; +import java.util.HashMap; +import java.util.List; +import java.util.Vector; + +import org.gcube.application.framework.core.vremanagement.impl.Pair; +import org.gcube.application.framework.core.vremanagement.model.ISGenericResource; + +/** + * @author Valia Tsagkalidou (NKUA) + * + */ +public interface GenericResourceInfoI { + + /** + * @param name the name of the generic resource + * @return a list containing the generic resources that have as name the given + * @throws RemoteException when an error has occurred while communicating with IS + */ + public List getGenericResourceByName(String name) throws RemoteException ; + + /** + * @param id the id of the generic resource + * @return a list containing the corresponding generic resources + * @throws RemoteException when an error has occurred while communicating with IS + */ + public List getGenericResourceByID(String id) throws RemoteException; + + /** + * @return a list containing the generic resources that describe which collections are part of the active VRE as well as their hierarchical structure (the name of this generic resource is "ScenarioCollectionInfo") + * @throws RemoteException when an error has occurred while communicating with IS + */ + public List getGenericResourceForScenario() throws RemoteException ; + + /** + * Updates a generic resource based on it's ID + * @param genericResource the generic resource to be updated + * @throws RemoteException when an error has occurred while communicating with IS + */ + public void updateGenericResourceByID(ISGenericResource genericResource) throws RemoteException; + + /** + * Creates a new generic resource + * @param genericResource the new generic resource + * @throws RemoteException when an error has occurred while communicating with IS + */ + public String createGenericResource(ISGenericResource genericResource) throws RemoteException; + + /** + * Reomoves an existing generic resource + * @param genericResource the generic resource to be removed + * @throws RemoteException when an error has occurred while communicating with IS + */ + public void removeGenericResource(ISGenericResource genericResource) throws RemoteException; + + /** + * @return a list containing pairs of (name, id) of the available generic resources + * @throws RemoteException when an error has occurred while communicating with IS + */ + public List getAvailableGenericResourceNames() throws RemoteException; + + /** + * + * @param xsltType Presentation or Metadata. The type of the xslt + * @return A vector which contains all the generic resources, xslts of this type. The xslts are sorted by the schema. + */ + public HashMap> getAllXslts(String xsltType); +} diff --git a/src/org/gcube/application/framework/core/vremanagement/impl/GenericResource.java b/src/org/gcube/application/framework/core/vremanagement/impl/GenericResource.java new file mode 100644 index 0000000..a78d1ba --- /dev/null +++ b/src/org/gcube/application/framework/core/vremanagement/impl/GenericResource.java @@ -0,0 +1,420 @@ +package org.gcube.application.framework.core.vremanagement.impl; + +import java.io.StringReader; +import java.rmi.RemoteException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import org.gcube.application.framework.core.cache.CachesManager; +import org.gcube.application.framework.core.security.PortalSecurityManager; +import org.gcube.application.framework.core.session.D4ScienceSession; +import org.gcube.application.framework.core.session.SessionManager; +import org.gcube.application.framework.core.util.CacheEntryConstants; +import org.gcube.application.framework.core.util.QueryString; +import org.gcube.application.framework.core.util.SessionConstants; +import org.gcube.application.framework.core.vremanagement.GenericResourceInfoI; +import org.gcube.application.framework.core.vremanagement.model.ISGenericResource; +import org.gcube.common.core.contexts.GHNContext; +import org.gcube.common.core.informationsystem.client.AtomicCondition; +import org.gcube.common.core.informationsystem.client.ISClient; +import org.gcube.common.core.informationsystem.client.QueryParameter; +import org.gcube.common.core.informationsystem.client.XMLResult; +import org.gcube.common.core.informationsystem.client.queries.GCUBEGenericQuery; +import org.gcube.common.core.informationsystem.client.queries.GCUBEGenericResourceQuery; +import org.gcube.common.core.informationsystem.publisher.ISPublisher; +import org.gcube.common.core.informationsystem.publisher.ISPublisherException; +import org.gcube.common.core.resources.GCUBEGenericResource; +import org.gcube.common.core.scope.GCUBEScope; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; +import org.gcube.application.framework.core.vremanagement.impl.Pair; + +/** + * @author Valia Tsaqgkalidou (NKUA) + */ +public class GenericResource implements GenericResourceInfoI{ + + /** + * A static IS publisher in order to communicate with IS + */ + protected static ISPublisher publisher = null; + protected static ISClient client = null; + + /** + * The D4Science session to be used + */ + D4ScienceSession session; + + /** + * Constructs a GenericReosurce object + * @param extrenalSessionID the external session id which is used for the D4ScienceSession (usually the session.getId() of the HttpSession or PortletSession) + * @param username the username of the user that called this constructor + */ + public GenericResource(String extrenalSessionID, String username) + { + session = SessionManager.getInstance().getD4ScienceSession(extrenalSessionID, username); + try { + publisher = GHNContext.getImplementation(ISPublisher.class); + } catch (Exception e) { + e.printStackTrace(); + } + if(client == null) + { + try { + client = GHNContext.getImplementation(ISClient.class); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + client = null; + } + } + } + + + + /** + * Constructs a GenericReosurce object + * @param session the D4Science session to be used for retrieving information needed + */ + public GenericResource(D4ScienceSession session) { + super(); + this.session = session; + try { + publisher = GHNContext.getImplementation(ISPublisher.class); + } catch (Exception e) { + e.printStackTrace(); + } + if(client == null) + { + try { + client = GHNContext.getImplementation(ISClient.class); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + client = null; + } + } + } + + + + /** + * @return the name of the active VRE + */ + protected String getDLName() + { + return session.getScopeName(); + } + + /** + * @param query the query to retrieve generic resources from cache + * @return a list of generic resources + */ + protected List getGenericResource(QueryString query) + { + return (List) (CachesManager.getInstance().getGenericResourceCache().get(query).getValue()); + } + + + /** + * Creates a new generic resource + * @param genericResource the new generic resource + * @return the ID of the newly created resource + * @throws RemoteException when an error has occurred while communicating with IS + */ + public String createGenericResource(ISGenericResource genericResource) + throws RemoteException { + try { + GCUBEGenericResource gCubeRes = GHNContext.getImplementation(GCUBEGenericResource.class); + gCubeRes.setID(""); + gCubeRes.setName(genericResource.getName()); + gCubeRes.setDescription(genericResource.getDescription()); + gCubeRes.setBody(genericResource.getBody()); + gCubeRes.setSecondaryType(genericResource.getSecondaryType()); + gCubeRes.addScope(session.getScope()); + + String Gr = publisher.registerGCUBEResource(gCubeRes, session.getScope(), new PortalSecurityManager(session)); + Document doc = parseXMLFileToDOM(Gr); + XPath xpath = XPathFactory.newInstance().newXPath(); + try { + return (String) xpath.evaluate("/Resource/ID/text()", doc, XPathConstants.STRING); + } catch (XPathExpressionException e) { + e.printStackTrace(); + throw new RemoteException(); + } + } catch (Exception e) { + e.printStackTrace(); + throw new RemoteException(); + } + } + + + /** + * Updates a generic resource based on it's ID + * @param genericResource the generic resource to be updated + * @throws RemoteException when an error has occurred while communicating with IS + */ + public void updateGenericResourceByID(ISGenericResource genericResource) + throws RemoteException { + try { + + //GCUBEGenericResource gCubeRes = GHNContext.getImplementation(GCUBEGenericResource.class); + + System.out.println("In updateGenericResourceByID!"); + GCUBEGenericResourceQuery query = client.getQuery(GCUBEGenericResourceQuery.class); + query.addAtomicConditions(new AtomicCondition("/ID", genericResource.getId())); + List result = client.execute(query, session.getScope()); + + if (result == null || result.size() == 0) { + System.out.println("Error in updateGenericResourceByID: The generic resources list is null"); + return; + } + + + + GCUBEGenericResource gCubeRes = result.get(0); + + + // gCubeRes.setID(genericResource.getId()); + gCubeRes.setName(genericResource.getName()); + gCubeRes.setDescription(genericResource.getDescription()); + gCubeRes.setBody(genericResource.getBody()); + gCubeRes.setSecondaryType(genericResource.getSecondaryType()); + // gCubeRes.addScope(session.getScope()); + publisher.updateGCUBEResource(gCubeRes, session.getScope(), new PortalSecurityManager(session)); + + + + List genRes = new ArrayList(); + genRes.add(genericResource); + QueryString query1 = new QueryString(); + query1.addParameter(CacheEntryConstants.id, genericResource.getId()); + query1.addParameter(CacheEntryConstants.vre, session.getScopeName()); + CachesManager.getInstance().getGenericResourceCache().put(new net.sf.ehcache.Element(query1, genRes)); + + query1.clear(); + query1.put(CacheEntryConstants.name, genericResource.getName().trim()); + query1.addParameter(CacheEntryConstants.vre, session.getScopeName()); + if(CachesManager.getInstance().getGenericResourceCache().isElementInMemory(query1) || CachesManager.getInstance().getGenericResourceCache().isElementOnDisk(query1)) + { + CachesManager.getInstance().getGenericResourceCache().get(query1).setTimeToLive(-1); + } + + + + } catch (Exception e) { + e.printStackTrace(); + throw new RemoteException(); + } + } + + + /** + * @return a list containing pairs of (name, id) of the available generic resources + * @throws RemoteException when an error has occurred while communicating with IS + */ + public List getAvailableGenericResourceNames() throws RemoteException { + List pairs = new ArrayList(); + String xquery = "for $query in collection(\"/db/Profiles/GenericResource\")//Document/Data/child::*[local-name()='Profile']/Resource return {$query/ID}{$query/Profile/Name}"; // order by $query/Profile/Name + GCUBEGenericQuery queryMan; + try { + queryMan = client.getQuery(GCUBEGenericQuery.class); + queryMan.setExpression(xquery); + List res = client.execute(queryMan, session.getScope()); + String id, name; + for(XMLResult xml : res) + { + try + { + id = xml.evaluate("//ID/text()").get(0); + List var = xml.evaluate("//Name/text()"); + if(var.size() > 0) + name = var.get(0); + else + name = ""; + System.out.println(id + " " + name); + pairs.add(new Pair(name, id)); + } + catch(Exception e) + { + + } + } + return pairs; + } catch (Exception e) { + e.printStackTrace(); + throw new RemoteException(); + } + } + + + /** + * @param id the id of the generic resource + * @return a list containing the corresponding generic resources + * @throws RemoteException when an error has occurred while communicating with IS + */ + public List getGenericResourceByID(String id) + throws RemoteException { + QueryString query = new QueryString(); + query.put(CacheEntryConstants.id, id); + query.put(CacheEntryConstants.vre, getDLName()); + return getGenericResource(query); + } + + + /** + * @param name the name of the generic resource + * @return a list containing the generic resources that have as name the given + * @throws RemoteException when an error has occurred while communicating with IS + */ + public List getGenericResourceByName(String name) + throws RemoteException { + QueryString query = new QueryString(); + query.put(CacheEntryConstants.name, name); + query.put(CacheEntryConstants.vre, getDLName()); + return getGenericResource(query); + } + + + /** + * @return a list containing the generic resources that describe which collections are part of the active VRE as well as their hierarchical structure (the name of this generic resource is "ScenarioCollectionInfo") + * @throws RemoteException when an error has occurred while communicating with IS + */ + public List getGenericResourceForScenario() + throws RemoteException { + QueryString query = new QueryString(); + query.put(CacheEntryConstants.name, SessionConstants.ScenarioSchemaInfo); + query.put(CacheEntryConstants.vre, getDLName()); + return getGenericResource(query); + } + + /** + * Removes an existing generic resource + * @param genericResource the generic resource to be removed + * @throws RemoteException when an error has occurred while communicating with IS + */ + public void removeGenericResource(ISGenericResource genericResource) + throws RemoteException { + try { + publisher.removeGCUBEResource(genericResource.getId(), GCUBEGenericResource.TYPE, session.getScope(), new PortalSecurityManager(session)); + + QueryString query = new QueryString(); + query.addParameter(CacheEntryConstants.id, genericResource.getId()); + query.addParameter(CacheEntryConstants.vre, session.getScopeName()); + if(CachesManager.getInstance().getGenericResourceCache().isElementInMemory(query) || CachesManager.getInstance().getGenericResourceCache().isElementOnDisk(query)) + { + genericResource = ((List)CachesManager.getInstance().getGenericResourceCache().get(query).getValue()).get(0); + CachesManager.getInstance().getGenericResourceCache().get(query).setTimeToLive(0); + } + + query.clear(); + query.put(CacheEntryConstants.name, genericResource.getName()); + query.addParameter(CacheEntryConstants.vre, session.getScopeName()); + if(CachesManager.getInstance().getGenericResourceCache().isElementInMemory(query) || CachesManager.getInstance().getGenericResourceCache().isElementOnDisk(query)) + { + CachesManager.getInstance().getGenericResourceCache().get(query).setTimeToLive(0); + } + } catch (ISPublisherException e) { + e.printStackTrace(); + throw new RemoteException(); + } + + } + + + /** + * Parses the xml and returns it as DOM object + * @param XMLdoc the xml as a string + * @return xml parsed as a Document + */ + static Document parseXMLFileToDOM(String XMLdoc) { + DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder; + try { + builder = dbFactory.newDocumentBuilder(); + Document doc = builder.parse(new InputSource(new StringReader(XMLdoc))); + return doc; + } catch (Exception e) { + return null; + } + } + + + + /** + * + * @param xsltType Presentation or Metadata. The type of the xslt + * @return A vector which contains all the generic resources, xslts of this type. The xslts are sorted by the schema. + */ + public HashMap> getAllXslts(String xsltType) { + HashMap> schemas_xslts = new HashMap>(); + Vector xslts = null; + + + List result = null; + try { + result = retrieveGenericResourcesFromNameParts(xsltType, session.getScope()); + } catch (Exception e) { + e.printStackTrace(); + } + + if (result == null) { + return null; + } + for (int i=0; i(); + schemas_xslts.put(schemaName.replaceFirst("%5f", "_"), xslts); + } + + // add the xslt name and id + String s[] = new String[2]; + s[0] = xsltName; + s[1] = id; + xslts.add(s); + } + return schemas_xslts; + } + + private static List retrieveGenericResourcesFromNameParts(String nameParts, GCUBEScope scope) throws Exception { + + String condition = "contains($result/Profile/Name/string(), '" + nameParts + "')"; + + GCUBEGenericQuery query = client.getQuery("GCUBEResourceQuery"); + query.addParameters(new QueryParameter("FILTER", condition), + new QueryParameter("TYPE", GCUBEGenericResource.TYPE), + new QueryParameter("RESULT", "{$result/ID}{$result/Profile/Name}")); + + List result = client.execute(query, scope); + List ret = new LinkedList(); + if (result==null || result.size()==0) + throw new Exception("No generic resources were found."); + + for(XMLResult r : result){ + String[] nameAndID = { r.evaluate("//Name/text()").get(0), r.evaluate("//ID/text()").get(0) }; + ret.add(nameAndID); + } + return ret; + } + + +} diff --git a/src/org/gcube/application/framework/core/vremanagement/impl/Pair.java b/src/org/gcube/application/framework/core/vremanagement/impl/Pair.java new file mode 100644 index 0000000..84e2105 --- /dev/null +++ b/src/org/gcube/application/framework/core/vremanagement/impl/Pair.java @@ -0,0 +1,50 @@ +package org.gcube.application.framework.core.vremanagement.impl; + +/** + * @author Valia Tsaqgkalidou (NKUA) + */ +public class Pair { + protected String name; + protected String value; + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the value + */ + public String getValue() { + return value; + } + + /** + * @param value the value to set + */ + public void setValue(String value) { + this.value = value; + } + + /** + * @param name the name + * @param value the value + */ + public Pair(String name, String value) { + super(); + this.name = name; + this.value = value; + } + + +} + diff --git a/src/org/gcube/application/framework/core/vremanagement/model/ISGenericResource.java b/src/org/gcube/application/framework/core/vremanagement/model/ISGenericResource.java new file mode 100644 index 0000000..fec5b36 --- /dev/null +++ b/src/org/gcube/application/framework/core/vremanagement/model/ISGenericResource.java @@ -0,0 +1,114 @@ +package org.gcube.application.framework.core.vremanagement.model; + + +/** + * @author Valia Tsaqgkalidou (NKUA) + * + */ +public class ISGenericResource { + + protected String id; + protected String name; + protected String description; + protected String body; + protected String secondaryType; + + + /** + * @return the secondary type of the generic resource + */ + public String getSecondaryType() { + return secondaryType; + } + + + /** + * @param secondaryType the secondary type of the generic resource to be set + */ + public void setSecondaryType(String secondaryType) { + this.secondaryType = secondaryType; + } + + + /** + * Generic Constructor + */ + public ISGenericResource() { + super(); + this.id = ""; + this.name = ""; + this.description = ""; + this.body = ""; + this.secondaryType = ""; + } + + + /** + * @param id the generic resource ID + * @param name the generic resource name + * @param description the generic resource description + * @param body the generic resource body + * @param sType the generic resource secondary type + */ + public ISGenericResource(String id, String name, String description, + String body, String sType) { + super(); + this.id = id; + this.name = name; + this.description = description; + this.body = body; + this.secondaryType = sType; + } + + + /** + * @return the id + */ + public String getId() { + return id; + } + /** + * @param id the id to set + */ + public void setId(String id) { + this.id = id; + } + /** + * @return the name + */ + public String getName() { + return name; + } + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + /** + * @return the description + */ + public String getDescription() { + return description; + } + /** + * @param description the description to set + */ + public void setDescription(String description) { + this.description = description; + } + /** + * @return the body + */ + public String getBody() { + return body; + } + /** + * @param body the body to set + */ + public void setBody(String body) { + this.body = body; + } + + +}