From 83b3f755d52fc10507cf2352d26b7e8549d41ebc Mon Sep 17 00:00:00 2001 From: tworrall Date: Mon, 30 Sep 2013 09:30:34 -0400 Subject: [PATCH] VIVO-285: visualization updates for ISF --- .../config/listViewConfig-advisorIn.xml | 29 +- .../individual-visualizationFoafPerson.ftl | 12 +- .../entityComparisonErrorCommonBody.ftl | 2 +- .../freemarker/visualization/tools.ftl | 2 +- rdf/display/everytime/PropertyConfig.n3 | 19 +- ...ManagePeopleForOrganizationController.java | 10 +- .../PersonHasAwardOrHonorGenerator.java | 16 +- .../PersonHasEducationalTraining.java | 4 + .../coauthorship/CoAuthorshipQueryRunner.java | 887 ++++---- .../CoPIGrantCountConstructQueryRunner.java | 94 +- .../CoPIGrantCountQueryRunner.java | 144 +- ...ciatedPeopleModelWithTypesConstructor.java | 5 +- ...OrganizationModelWithTypesConstructor.java | 6 +- ...tsForSubOrganizationsModelConstructor.java | 393 ++-- ...nsForSubOrganizationsModelConstructor.java | 15 +- .../PeopleToGrantsModelConstructor.java | 348 +-- .../PeopleToPublicationsModelConstructor.java | 7 +- .../PersonToGrantsModelConstructor.java | 354 ++-- .../PersonToPublicationsModelConstructor.java | 6 +- ...SubOrganizationWithinModelConstructor.java | 6 +- .../PersonPublicationCountQueryRunner.java | 325 +-- .../OrganizationUtilityFunctions.java | 6 +- .../utilities/UtilitiesRequestHandler.java | 27 +- .../visutils/AllPropertiesQueryRunner.java | 272 +-- .../visutils/GenericQueryRunner.java | 202 +- .../visutils/GenericQueryRunnerOnModel.java | 200 +- .../visutils/SelectOnModelUtilities.java | 1876 +++++++++-------- 27 files changed, 2743 insertions(+), 2524 deletions(-) diff --git a/productMods/config/listViewConfig-advisorIn.xml b/productMods/config/listViewConfig-advisorIn.xml index 30f83e1e..8fb1498c 100644 --- a/productMods/config/listViewConfig-advisorIn.xml +++ b/productMods/config/listViewConfig-advisorIn.xml @@ -25,11 +25,14 @@ ?dateTimeEnd WHERE { - ?subject ?property ?advisory + ?subject ?property ?advisory . + ?advisory core:relates ?advisor . + ?advisor <http://purl.obolibrary.org/obo/RO_0000053> ?advisorRole . LET ( ?localName := afn:localname(?advisory) ) OPTIONAL { ?advisory rdfs:label ?advisoryLabel } OPTIONAL { ?advisory core:relates ?advisee . ?advisee a foaf:Person . + ?advisee <http://purl.obolibrary.org/obo/RO_0000053> ?adviseeRole OPTIONAL { ?advisee rdfs:label ?adviseeLabel } } OPTIONAL { ?advisory core:relates ?degree . @@ -74,7 +77,10 @@ ?subject ?property ?advisory . ?advisory a core:AdvisingRelationship . ?advisory ?advisoryProperty ?advisoryValue . - ?advisory rdfs:label ?advisoryLabel + ?advisory rdfs:label ?advisoryLabel . + ?advisory core:relates ?advisor . + ?advisor <http://purl.obolibrary.org/obo/RO_0000053> ?advisorRole . + ?advisorRole a core:AdvisorRole } WHERE { { ?subject ?property ?advisory . @@ -88,10 +94,23 @@ ?advisory a core:AdvisingRelationship . ?advisory ?advisoryProperty ?advisoryValue . ?advisory rdfs:label ?advisoryLabel + } UNION { + ?subject ?property ?advisory . + ?advisory a core:AdvisingRelationship . + ?advisory ?advisoryProperty ?advisoryValue . + ?advisory core:relates ?advisor . + ?advisor <http://purl.obolibrary.org/obo/RO_0000053> ?advisorRole . + ?advisorRole a core:AdvisorRole } } + OPTIONAL { ?advisory core:relates ?advisee . + ?advisee a foaf:Person . + ?advisee <http://purl.obolibrary.org/obo/RO_0000053> ?adviseeRole + + + PREFIX bibo: <http://purl.org/ontology/bibo/> PREFIX core: <http://vivoweb.org/ontology/core#> @@ -104,6 +123,8 @@ ?advisory core:relates ?advisee . ?advisee a foaf:Person . ?advisee rdfs:label ?adviseeLabel . + ?advisee <http://purl.obolibrary.org/obo/RO_0000053> ?adviseeRole . + ?adviseeRole a core:AdviseeRole . ?advisory core:relates ?degree . ?degree a core:AcademicDegree . ?degree rdfs:label ?degreeLabel . @@ -117,11 +138,15 @@ ?advisory a core:AdvisingRelationship . ?advisory core:relates ?advisee . ?advisee a foaf:Person . + ?advisee <http://purl.obolibrary.org/obo/RO_0000053> ?adviseeRole . + ?adviseeRole a core:AdviseeRole } UNION { ?subject ?property ?advisory . ?advisory a core:AdvisingRelationship . ?advisory core:relates ?advisee . ?advisee a foaf:Person . + ?advisee <http://purl.obolibrary.org/obo/RO_0000053> ?adviseeRole . + ?adviseeRole a core:AdviseeRole . ?advisee rdfs:label ?adviseeLabel } UNION { ?subject ?property ?advisory . diff --git a/productMods/templates/freemarker/body/partials/individual/individual-visualizationFoafPerson.ftl b/productMods/templates/freemarker/body/partials/individual/individual-visualizationFoafPerson.ftl index 2a2b7a6a..aefa6c28 100644 --- a/productMods/templates/freemarker/body/partials/individual/individual-visualizationFoafPerson.ftl +++ b/productMods/templates/freemarker/body/partials/individual/individual-visualizationFoafPerson.ftl @@ -3,12 +3,14 @@ <#-- Template for sparkline visualization on individual profile page --> <#-- Determine whether this person is an author --> -<#assign isAuthor = p.hasStatements(propertyGroups, "${core}authorInAuthorship") /> +<#assign isAuthor = p.hasVisualizationStatements(propertyGroups, "${core}relatedBy", "${core}Authorship") /> <#-- Determine whether this person is involved in any grants --> -<#assign isInvestigator = ( p.hasStatements(propertyGroups, "${core}hasInvestigatorRole") || - p.hasStatements(propertyGroups, "${core}hasPrincipalInvestigatorRole") || - p.hasStatements(propertyGroups, "${core}hasCo-PrincipalInvestigatorRole") ) > +<#assign obo_RO53 = "http://purl.obolibrary.org/obo/RO_0000053"> + +<#assign isInvestigator = ( p.hasVisualizationStatements(propertyGroups, "${obo_RO53}", "${core}InvestigatorRole") || + p.hasVisualizationStatements(propertyGroups, "${obo_RO53}", "${core}PrincipalInvestigatorRole") || + p.hasVisualizationStatements(propertyGroups, "${obo_RO53}", "${core}CoPrincipalInvestigatorRole") ) > <#if (isAuthor || isInvestigator)> @@ -70,4 +72,4 @@ - \ No newline at end of file + diff --git a/productMods/templates/freemarker/visualization/entitycomparison/entityComparisonErrorCommonBody.ftl b/productMods/templates/freemarker/visualization/entitycomparison/entityComparisonErrorCommonBody.ftl index 707f6c7d..111df210 100644 --- a/productMods/templates/freemarker/visualization/entitycomparison/entityComparisonErrorCommonBody.ftl +++ b/productMods/templates/freemarker/visualization/entitycomparison/entityComparisonErrorCommonBody.ftl @@ -16,7 +16,7 @@

${organizationLabel}

${textForCurrentEntityComparisonType?capitalize} ${i18n().temporal_graph_capitalized} - ${i18n().view} ${textForOtherEntityComparisonType} ${i18n().temporal_graph} + ${i18n().view} ${textForOtherEntityComparisonType} ${i18n().temporal_graph}

${i18n().entity_comp_error_text1} diff --git a/productMods/templates/freemarker/visualization/tools.ftl b/productMods/templates/freemarker/visualization/tools.ftl index d4758760..3555885e 100644 --- a/productMods/templates/freemarker/visualization/tools.ftl +++ b/productMods/templates/freemarker/visualization/tools.ftl @@ -5,7 +5,7 @@

${i18n().visualization_tools}

-${i18n().refresh_cached_vis_model} +${i18n().refresh_cached_vis_models}

${i18n().why_needed}

${i18n().vis_tools_note_one}

diff --git a/rdf/display/everytime/PropertyConfig.n3 b/rdf/display/everytime/PropertyConfig.n3 index 764cfbec..26d55afc 100644 --- a/rdf/display/everytime/PropertyConfig.n3 +++ b/rdf/display/everytime/PropertyConfig.n3 @@ -453,7 +453,7 @@ local:eventWithinConfig a :ObjectPropertyDisplayConfig ; local:includesEventContext a :ConfigContext ; :hasConfiguration local:includesEventConfig ; - :configContextFor ; + :configContextFor ; :qualifiedByDomain ; :qualifiedBy . @@ -467,11 +467,11 @@ local:includesEventConfig a :ObjectPropertyDisplayConfig ; local:inEventSeriesContext a :ConfigContext ; :hasConfiguration local:inEventSeriesConfig ; - :configContextFor ; + :configContextFor ; :qualifiedByDomain ; :qualifiedBy . -local:includesEventConfig a :ObjectPropertyDisplayConfig ; +local:inEventSeriesConfig a :ObjectPropertyDisplayConfig ; :listViewConfigFile "listViewConfig-default.xml"^^xsd:string ; :displayName "in event series" ; vitro:displayRankAnnot 3; @@ -479,3 +479,16 @@ local:includesEventConfig a :ObjectPropertyDisplayConfig ; vitro:prohibitedFromUpdateBelowRoleLevelAnnot role:public ; :propertyGroup . +local:awardAssignedByContext a :ConfigContext ; + :hasConfiguration local:awardAssignedByConfig ; + :configContextFor ; + :qualifiedByDomain ; + :qualifiedBy . + +local:awardAssignedByConfig a :ObjectPropertyDisplayConfig ; + :listViewConfigFile "listViewConfig-default.xml"^^xsd:string ; + :displayName "award conferred by" ; + vitro:displayRankAnnot 3; + vitro:hiddenFromDisplayBelowRoleLevelAnnot role:public ; + vitro:prohibitedFromUpdateBelowRoleLevelAnnot role:public ; + :propertyGroup . diff --git a/src/edu/cornell/mannlib/vitro/webapp/controller/freemarker/ManagePeopleForOrganizationController.java b/src/edu/cornell/mannlib/vitro/webapp/controller/freemarker/ManagePeopleForOrganizationController.java index b5ec8247..b6e068ce 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/controller/freemarker/ManagePeopleForOrganizationController.java +++ b/src/edu/cornell/mannlib/vitro/webapp/controller/freemarker/ManagePeopleForOrganizationController.java @@ -65,12 +65,14 @@ public class ManagePeopleForOrganizationController extends FreemarkerHttpServlet + "PREFIX rdfs: \n" + "PREFIX vitro: \n" + "PREFIX afn: \n" + + "PREFIX foaf: \n" + "SELECT DISTINCT ?subclass ?position (str(?label) as ?name) ?person ?hideThis WHERE { \n" - + " ?subject core:organizationForPosition ?position . \n" - + " OPTIONAL { ?position core:positionForPerson ?person . " + + " ?subject core:relatedBy ?position . \n" + + " ?position a core:Position . \n" + + " OPTIONAL { ?position core:relates ?person . " + + " ?person a foaf:Person . \n" + " ?person rdfs:label ?label } \n" - + " OPTIONAL { ?position vitro:mostSpecificType ?subclass . \n" - + " ?subclass rdfs:subClassOf core:Position } \n" + + " OPTIONAL { ?position vitro:mostSpecificType ?subclass } \n" + " OPTIONAL { ?position core:hideFromDisplay ?hideThis } \n " + "} ORDER BY ?subclass ?name"; diff --git a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/PersonHasAwardOrHonorGenerator.java b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/PersonHasAwardOrHonorGenerator.java index 862bceb4..af2abc33 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/PersonHasAwardOrHonorGenerator.java +++ b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/PersonHasAwardOrHonorGenerator.java @@ -209,25 +209,25 @@ public class PersonHasAwardOrHonorGenerator extends VivoBaseGenerator implements "?awardReceipt <"+ descriptionPred +"> ?description ."; final static String n3ForExistingOrgNewAwardAssertion = - "?award <" + awardConferredByPred +"> ?existingOrg . \n" + - "?existingOrg <" + awardConferredPred + "> ?award . \n" + + "?awardReceipt <" + awardConferredByPred +"> ?existingOrg . \n" + + "?existingOrg <" + awardConferredPred + "> ?awardReceipt . \n" + "?award <"+ label + "> ?awardLabel ."; final static String n3ForExistingOrgExistingAwardAssertion = - "?existingAward <" + awardConferredByPred +"> ?existingOrg . \n" + - "?existingOrg <" + awardConferredPred + "> ?existingAward . "; + "?awardReceipt <" + awardConferredByPred +"> ?existingOrg . \n" + + "?existingOrg <" + awardConferredPred + "> ?awardReceipt . "; final static String n3ForNewOrgNewAwardAssertion = "?newOrg a <" + orgClass + "> . \n" + - "?award <" + awardConferredByPred +"> ?newOrg . \n" + - "?newOrg <" + awardConferredPred + "> ?award . \n" + + "?awardReceipt <" + awardConferredByPred +"> ?newOrg . \n" + + "?newOrg <" + awardConferredPred + "> ?awardReceipt . \n" + "?award <"+ label + "> ?awardLabel . \n" + "?newOrg <"+ label + "> ?orgLabel ."; final static String n3ForNewOrgExistingAwardAssertion = "?newOrg a <" + orgClass + "> . \n" + - "?existingAward <" + awardConferredByPred +"> ?newOrg . \n" + - "?newOrg <" + awardConferredPred + "> ?existingAward . \n" + + "?awardReceipt <" + awardConferredByPred +"> ?newOrg . \n" + + "?newOrg <" + awardConferredPred + "> ?awardReceipt . \n" + "?newOrg <"+ label + "> ?orgLabel ."; final static String n3ForYearAwarded = diff --git a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/PersonHasEducationalTraining.java b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/PersonHasEducationalTraining.java index 880dd0f8..33f38c3e 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/PersonHasEducationalTraining.java +++ b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/PersonHasEducationalTraining.java @@ -240,6 +240,8 @@ public class PersonHasEducationalTraining extends VivoBaseGenerator implements "?newOrg ?newAwardedDegree . \n" + "?newOrg a ?orgType . \n" + "?newOrg <"+ label +"> ?orgLabel . \n" + + "?edTraining ?newOrg . \n" + + "?newOrg ?edTraining . \n" + "?newAwardedDegree ?degreeType .\n"+ "?degreeType ?newAwardedDegree . \n"+ "?newAwardedDegree a core:AwardedDegree ."; @@ -254,6 +256,8 @@ public class PersonHasEducationalTraining extends VivoBaseGenerator implements "?existingOrg ?newAwardedDegree . \n" + "?newAwardedDegree ?existingOrg . \n" + "?newAwardedDegree ?degreeType .\n"+ + "?edTraining ?existingOrg . \n" + + "?existingOrg ?edTraining . \n" + "?degreeType ?newAwardedDegree . \n"+ "?newAwardedDegree a core:AwardedDegree ."; diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/coauthorship/CoAuthorshipQueryRunner.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/coauthorship/CoAuthorshipQueryRunner.java index 9c108c6a..485cb532 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/coauthorship/CoAuthorshipQueryRunner.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/coauthorship/CoAuthorshipQueryRunner.java @@ -1,442 +1,445 @@ -/* $This file is distributed under the terms of the license in /doc/license.txt$ */ - -package edu.cornell.mannlib.vitro.webapp.visualization.coauthorship; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; - -import com.hp.hpl.jena.iri.IRI; -import com.hp.hpl.jena.iri.IRIFactory; -import com.hp.hpl.jena.iri.Violation; -import com.hp.hpl.jena.query.Dataset; -import com.hp.hpl.jena.query.Query; -import com.hp.hpl.jena.query.QueryExecution; -import com.hp.hpl.jena.query.QueryExecutionFactory; -import com.hp.hpl.jena.query.QueryFactory; -import com.hp.hpl.jena.query.QuerySolution; -import com.hp.hpl.jena.query.ResultSet; -import com.hp.hpl.jena.query.Syntax; -import com.hp.hpl.jena.rdf.model.RDFNode; - -import edu.cornell.mannlib.vitro.webapp.visualization.collaborationutils.CoAuthorshipData; -import edu.cornell.mannlib.vitro.webapp.visualization.collaborationutils.CollaborationData; -import edu.cornell.mannlib.vitro.webapp.visualization.collaborationutils.CollaboratorComparator; -import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryConstants; -import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryFieldLabels; -import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; -import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Activity; -import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Collaboration; -import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Collaborator; -import edu.cornell.mannlib.vitro.webapp.visualization.visutils.QueryRunner; -import edu.cornell.mannlib.vitro.webapp.visualization.visutils.UniqueIDGenerator; - -/** - * This query runner is used to execute a sparql query to get all the publications - * for a particular individual. It will also fetch all the authors that worked - * on that particular publication. - * - * @author cdtank - */ -public class CoAuthorshipQueryRunner implements QueryRunner { - - private static final int MAX_AUTHORS_PER_PAPER_ALLOWED = 100; - - protected static final Syntax SYNTAX = Syntax.syntaxARQ; - - private String egoURI; - - private Dataset dataset; - - private Log log; - - private UniqueIDGenerator nodeIDGenerator; - - private UniqueIDGenerator edgeIDGenerator; - - public CoAuthorshipQueryRunner(String egoURI, - Dataset dataset, Log log) { - - this.egoURI = egoURI; - this.dataset = dataset; - this.log = log; - - this.nodeIDGenerator = new UniqueIDGenerator(); - this.edgeIDGenerator = new UniqueIDGenerator(); - - } - - private CollaborationData createQueryResult(ResultSet resultSet) { - - Set nodes = new HashSet(); - - Map biboDocumentURLToVO = new HashMap(); - Map> biboDocumentURLToCoAuthors = - new HashMap>(); - Map nodeURLToVO = new HashMap(); - Map edgeUniqueIdentifierToVO = new HashMap(); - - Collaborator egoNode = null; - - Set edges = new HashSet(); - - while (resultSet.hasNext()) { - QuerySolution solution = resultSet.nextSolution(); - - /* - * We only want to create only ONE ego node. - * */ - RDFNode egoAuthorURLNode = solution.get(QueryFieldLabels.AUTHOR_URL); - if (nodeURLToVO.containsKey(egoAuthorURLNode.toString())) { - - egoNode = nodeURLToVO.get(egoAuthorURLNode.toString()); - - } else { - - egoNode = new Collaborator(egoAuthorURLNode.toString(), nodeIDGenerator); - nodes.add(egoNode); - nodeURLToVO.put(egoAuthorURLNode.toString(), egoNode); - - RDFNode authorLabelNode = solution.get(QueryFieldLabels.AUTHOR_LABEL); - if (authorLabelNode != null) { - egoNode.setCollaboratorName(authorLabelNode.toString()); - } - } - - RDFNode documentNode = solution.get(QueryFieldLabels.DOCUMENT_URL); - Activity biboDocument; - - if (biboDocumentURLToVO.containsKey(documentNode.toString())) { - biboDocument = biboDocumentURLToVO.get(documentNode.toString()); - } else { - biboDocument = createDocumentVO(solution, documentNode.toString()); - biboDocumentURLToVO.put(documentNode.toString(), biboDocument); - } - - egoNode.addActivity(biboDocument); - - /* - * After some discussion we concluded that for the purpose of this visualization - * we do not want a co-author node or Collaboration if the publication has only one - * author and that happens to be the ego. - * */ - if (solution.get(QueryFieldLabels.AUTHOR_URL).toString().equalsIgnoreCase( - solution.get(QueryFieldLabels.CO_AUTHOR_URL).toString())) { - continue; - } - - Collaborator coAuthorNode; - - RDFNode coAuthorURLNode = solution.get(QueryFieldLabels.CO_AUTHOR_URL); - if (nodeURLToVO.containsKey(coAuthorURLNode.toString())) { - - coAuthorNode = nodeURLToVO.get(coAuthorURLNode.toString()); - - } else { - - coAuthorNode = new Collaborator(coAuthorURLNode.toString(), nodeIDGenerator); - nodes.add(coAuthorNode); - nodeURLToVO.put(coAuthorURLNode.toString(), coAuthorNode); - - RDFNode coAuthorLabelNode = solution.get(QueryFieldLabels.CO_AUTHOR_LABEL); - if (coAuthorLabelNode != null) { - coAuthorNode.setCollaboratorName(coAuthorLabelNode.toString()); - } - } - - coAuthorNode.addActivity(biboDocument); - - Set coAuthorsForCurrentBiboDocument; - - if (biboDocumentURLToCoAuthors.containsKey(biboDocument.getActivityURI())) { - coAuthorsForCurrentBiboDocument = biboDocumentURLToCoAuthors - .get(biboDocument.getActivityURI()); - } else { - coAuthorsForCurrentBiboDocument = new HashSet(); - biboDocumentURLToCoAuthors.put(biboDocument.getActivityURI(), - coAuthorsForCurrentBiboDocument); - } - - coAuthorsForCurrentBiboDocument.add(coAuthorNode); - - Collaboration egoCoAuthorEdge = - getExistingEdge(egoNode, coAuthorNode, edgeUniqueIdentifierToVO); - - /* - * If "egoCoAuthorEdge" is null it means that no Collaboration exists in between the - * egoNode & current coAuthorNode. Else create a new Collaboration, add it to the edges - * set & add the collaborator document to it. - * */ - if (egoCoAuthorEdge != null) { - egoCoAuthorEdge.addActivity(biboDocument); - } else { - egoCoAuthorEdge = - new Collaboration(egoNode, coAuthorNode, biboDocument, edgeIDGenerator); - edges.add(egoCoAuthorEdge); - edgeUniqueIdentifierToVO.put( - getEdgeUniqueIdentifier(egoNode.getCollaboratorID(), - coAuthorNode.getCollaboratorID()), - egoCoAuthorEdge); - } - - - } - - - - /* - * This method takes out all the authors & edges between authors that belong to documents - * that have more than 100 authors. We conjecture that these papers do not provide much - * insight. However, we have left the documents be. - * - * This method side-effects "nodes" & "edges". - * */ - removeLowQualityNodesAndEdges(nodes, - biboDocumentURLToVO, - biboDocumentURLToCoAuthors, - edges); - - /* - * We need to create edges between 2 co-authors. E.g. On a paper there were 3 authors - * ego, A & B then we have already created edges like, - * ego - A - * ego - B - * The below sub-routine will take care of, - * A - B - * - * We are side-effecting "edges" here. The only reason to do this is because we are adding - * edges en masse for all the co-authors on all the publications considered so far. The - * other reason being we dont want to compare against 2 sets of edges (edges created before - * & co-author edges created during the course of this method) when we are creating a new - * Collaboration. - * */ - createCoAuthorEdges(biboDocumentURLToVO, - biboDocumentURLToCoAuthors, - edges, - edgeUniqueIdentifierToVO); - - - return new CoAuthorshipData(egoNode, nodes, edges); - } - - private void removeLowQualityNodesAndEdges( - Set nodes, - Map biboDocumentURLToVO, - Map> biboDocumentURLToCoAuthors, - Set edges) { - - Set nodesToBeRemoved = new HashSet(); - for (Map.Entry> currentBiboDocumentEntry - : biboDocumentURLToCoAuthors.entrySet()) { - - if (currentBiboDocumentEntry.getValue().size() > MAX_AUTHORS_PER_PAPER_ALLOWED) { - - Activity currentBiboDocument = biboDocumentURLToVO - .get(currentBiboDocumentEntry.getKey()); - - Set edgesToBeRemoved = new HashSet(); - - for (Collaboration currentEdge : edges) { - Set currentCollaboratorDocuments = - currentEdge.getCollaborationActivities(); - - if (currentCollaboratorDocuments.contains(currentBiboDocument)) { - currentCollaboratorDocuments.remove(currentBiboDocument); - if (currentCollaboratorDocuments.isEmpty()) { - edgesToBeRemoved.add(currentEdge); - } - } - } - - edges.removeAll(edgesToBeRemoved); - - for (Collaborator currentCoAuthor : currentBiboDocumentEntry.getValue()) { - currentCoAuthor.getCollaboratorActivities().remove(currentBiboDocument); - if (currentCoAuthor.getCollaboratorActivities().isEmpty()) { - nodesToBeRemoved.add(currentCoAuthor); - } - } - } - } - nodes.removeAll(nodesToBeRemoved); - } - - private void createCoAuthorEdges( - Map biboDocumentURLToVO, - Map> biboDocumentURLToCoAuthors, Set edges, - Map edgeUniqueIdentifierToVO) { - - for (Map.Entry> currentBiboDocumentEntry - : biboDocumentURLToCoAuthors.entrySet()) { - - /* - * If there was only one co-author (other than ego) then we dont have to create any - * edges. so the below condition will take care of that. - * - * We are restricting edges between co-author if a particular document has more than - * 100 co-authors. Our conjecture is that such edges do not provide any good insight - * & causes unnecessary computations causing the server to time-out. - * */ - if (currentBiboDocumentEntry.getValue().size() > 1 - && currentBiboDocumentEntry.getValue().size() - <= MAX_AUTHORS_PER_PAPER_ALLOWED) { - - - Set newlyAddedEdges = new HashSet(); - - /* - * In order to leverage the nested "for loop" for making edges between all the - * co-authors we need to create a list out of the set first. - * */ - List coAuthorNodes = - new ArrayList(currentBiboDocumentEntry.getValue()); - - Collections.sort(coAuthorNodes, new CollaboratorComparator()); - - int numOfCoAuthors = coAuthorNodes.size(); - - for (int ii = 0; ii < numOfCoAuthors - 1; ii++) { - for (int jj = ii + 1; jj < numOfCoAuthors; jj++) { - - Collaborator coAuthor1 = coAuthorNodes.get(ii); - Collaborator coAuthor2 = coAuthorNodes.get(jj); - - Collaboration coAuthor1_2Edge = getExistingEdge(coAuthor1, - coAuthor2, - edgeUniqueIdentifierToVO); - - Activity currentBiboDocument = biboDocumentURLToVO - .get(currentBiboDocumentEntry - .getKey()); - - if (coAuthor1_2Edge != null) { - coAuthor1_2Edge.addActivity(currentBiboDocument); - } else { - coAuthor1_2Edge = new Collaboration(coAuthor1, - coAuthor2, - currentBiboDocument, - edgeIDGenerator); - newlyAddedEdges.add(coAuthor1_2Edge); - edgeUniqueIdentifierToVO.put( - getEdgeUniqueIdentifier(coAuthor1.getCollaboratorID(), - coAuthor2.getCollaboratorID()), - coAuthor1_2Edge); - } - } - } - edges.addAll(newlyAddedEdges); - } - - } - } - - private Collaboration getExistingEdge( - Collaborator collaboratingNode1, - Collaborator collaboratingNode2, - Map edgeUniqueIdentifierToVO) { - - String edgeUniqueIdentifier = getEdgeUniqueIdentifier( - collaboratingNode1.getCollaboratorID(), - collaboratingNode2.getCollaboratorID()); - - return edgeUniqueIdentifierToVO.get(edgeUniqueIdentifier); - - } - - private String getEdgeUniqueIdentifier(int nodeID1, int nodeID2) { - - String separator = "*"; - - if (nodeID1 < nodeID2) { - return nodeID1 + separator + nodeID2; - } else { - return nodeID2 + separator + nodeID1; - } - - } - - private Activity createDocumentVO(QuerySolution solution, String documentURL) { - - Activity biboDocument = new Activity(documentURL); - - RDFNode publicationDateNode = solution.get(QueryFieldLabels.DOCUMENT_PUBLICATION_DATE); - if (publicationDateNode != null) { - biboDocument.setActivityDate(publicationDateNode.toString()); - } - - return biboDocument; - } - - private ResultSet executeQuery(String queryText, - Dataset dataset) { - - QueryExecution queryExecution = null; - Query query = QueryFactory.create(queryText, SYNTAX); - - queryExecution = QueryExecutionFactory.create(query, dataset); - return queryExecution.execSelect(); - } - - private String generateEgoCoAuthorshipSparqlQuery(String queryURI) { - - String sparqlQuery = QueryConstants.getSparqlPrefixQuery() - + "SELECT \n" - + " (str(<" + queryURI + ">) as ?" + QueryFieldLabels.AUTHOR_URL + ") \n" - + " (str(?authorLabel) as ?" + QueryFieldLabels.AUTHOR_LABEL + ") \n" - + " (str(?coAuthorPerson) as ?" + QueryFieldLabels.CO_AUTHOR_URL + ") \n" - + " (str(?coAuthorPersonLabel) as ?" + QueryFieldLabels.CO_AUTHOR_LABEL + ") \n" - + " (str(?document) as ?" + QueryFieldLabels.DOCUMENT_URL + ") \n" - + " (str(?publicationDate) as ?" - + QueryFieldLabels.DOCUMENT_PUBLICATION_DATE + ") \n" - + "WHERE { \n" - + "<" + queryURI + "> rdf:type foaf:Person ;" - + " rdfs:label ?authorLabel ;" - + " core:authorInAuthorship ?authorshipNode . \n" - + "?authorshipNode rdf:type core:Authorship ;" - + " core:linkedInformationResource ?document . \n" - + "?document core:informationResourceInAuthorship ?coAuthorshipNode . \n" - + "?coAuthorshipNode core:linkedAuthor ?coAuthorPerson . \n" - + "?coAuthorPerson rdfs:label ?coAuthorPersonLabel . \n" - + "OPTIONAL { ?document core:dateTimeValue ?dateTimeValue . \n" - + " ?dateTimeValue core:dateTime ?publicationDate } .\n" - + "} \n" - + "ORDER BY ?document ?coAuthorPerson\n"; - - log.debug("COAUTHORSHIP QUERY - " + sparqlQuery); - - return sparqlQuery; - } - - - public CollaborationData getQueryResult() - throws MalformedQueryParametersException { - - if (StringUtils.isNotBlank(this.egoURI)) { - /* - * To test for the validity of the URI submitted. - * */ - IRIFactory iRIFactory = IRIFactory.jenaImplementation(); - IRI iri = iRIFactory.create(this.egoURI); - if (iri.hasViolation(false)) { - String errorMsg = ((Violation) iri.violations(false).next()).getShortMessage(); - log.error("Ego Co-Authorship Vis Query " + errorMsg); - throw new MalformedQueryParametersException( - "URI provided for an individual is malformed."); - } - } else { - throw new MalformedQueryParametersException("URI parameter is either null or empty."); - } - - ResultSet resultSet = executeQuery(generateEgoCoAuthorshipSparqlQuery(this.egoURI), - this.dataset); - return createQueryResult(resultSet); - } - -} +/* $This file is distributed under the terms of the license in /doc/license.txt$ */ + +package edu.cornell.mannlib.vitro.webapp.visualization.coauthorship; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; + +import com.hp.hpl.jena.iri.IRI; +import com.hp.hpl.jena.iri.IRIFactory; +import com.hp.hpl.jena.iri.Violation; +import com.hp.hpl.jena.query.Dataset; +import com.hp.hpl.jena.query.Query; +import com.hp.hpl.jena.query.QueryExecution; +import com.hp.hpl.jena.query.QueryExecutionFactory; +import com.hp.hpl.jena.query.QueryFactory; +import com.hp.hpl.jena.query.QuerySolution; +import com.hp.hpl.jena.query.ResultSet; +import com.hp.hpl.jena.query.Syntax; +import com.hp.hpl.jena.rdf.model.RDFNode; + +import edu.cornell.mannlib.vitro.webapp.visualization.collaborationutils.CoAuthorshipData; +import edu.cornell.mannlib.vitro.webapp.visualization.collaborationutils.CollaborationData; +import edu.cornell.mannlib.vitro.webapp.visualization.collaborationutils.CollaboratorComparator; +import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryConstants; +import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryFieldLabels; +import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; +import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Activity; +import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Collaboration; +import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Collaborator; +import edu.cornell.mannlib.vitro.webapp.visualization.visutils.QueryRunner; +import edu.cornell.mannlib.vitro.webapp.visualization.visutils.UniqueIDGenerator; + +/** + * This query runner is used to execute a sparql query to get all the publications + * for a particular individual. It will also fetch all the authors that worked + * on that particular publication. + * + * @author cdtank + */ +public class CoAuthorshipQueryRunner implements QueryRunner { + + private static final int MAX_AUTHORS_PER_PAPER_ALLOWED = 100; + + protected static final Syntax SYNTAX = Syntax.syntaxARQ; + + private String egoURI; + + private Dataset dataset; + + private Log log; + + private UniqueIDGenerator nodeIDGenerator; + + private UniqueIDGenerator edgeIDGenerator; + + public CoAuthorshipQueryRunner(String egoURI, + Dataset dataset, Log log) { + + this.egoURI = egoURI; + this.dataset = dataset; + this.log = log; + + this.nodeIDGenerator = new UniqueIDGenerator(); + this.edgeIDGenerator = new UniqueIDGenerator(); + + } + + private CollaborationData createQueryResult(ResultSet resultSet) { + + Set nodes = new HashSet(); + + Map biboDocumentURLToVO = new HashMap(); + Map> biboDocumentURLToCoAuthors = + new HashMap>(); + Map nodeURLToVO = new HashMap(); + Map edgeUniqueIdentifierToVO = new HashMap(); + + Collaborator egoNode = null; + + Set edges = new HashSet(); + + while (resultSet.hasNext()) { + QuerySolution solution = resultSet.nextSolution(); + + /* + * We only want to create only ONE ego node. + * */ + RDFNode egoAuthorURLNode = solution.get(QueryFieldLabels.AUTHOR_URL); + if (nodeURLToVO.containsKey(egoAuthorURLNode.toString())) { + + egoNode = nodeURLToVO.get(egoAuthorURLNode.toString()); + + } else { + + egoNode = new Collaborator(egoAuthorURLNode.toString(), nodeIDGenerator); + nodes.add(egoNode); + nodeURLToVO.put(egoAuthorURLNode.toString(), egoNode); + + RDFNode authorLabelNode = solution.get(QueryFieldLabels.AUTHOR_LABEL); + if (authorLabelNode != null) { + egoNode.setCollaboratorName(authorLabelNode.toString()); + } + } + + RDFNode documentNode = solution.get(QueryFieldLabels.DOCUMENT_URL); + Activity biboDocument; + + if (biboDocumentURLToVO.containsKey(documentNode.toString())) { + biboDocument = biboDocumentURLToVO.get(documentNode.toString()); + } else { + biboDocument = createDocumentVO(solution, documentNode.toString()); + biboDocumentURLToVO.put(documentNode.toString(), biboDocument); + } + + egoNode.addActivity(biboDocument); + + /* + * After some discussion we concluded that for the purpose of this visualization + * we do not want a co-author node or Collaboration if the publication has only one + * author and that happens to be the ego. + * */ + if (solution.get(QueryFieldLabels.AUTHOR_URL).toString().equalsIgnoreCase( + solution.get(QueryFieldLabels.CO_AUTHOR_URL).toString())) { + continue; + } + + Collaborator coAuthorNode; + + RDFNode coAuthorURLNode = solution.get(QueryFieldLabels.CO_AUTHOR_URL); + if (nodeURLToVO.containsKey(coAuthorURLNode.toString())) { + + coAuthorNode = nodeURLToVO.get(coAuthorURLNode.toString()); + + } else { + + coAuthorNode = new Collaborator(coAuthorURLNode.toString(), nodeIDGenerator); + nodes.add(coAuthorNode); + nodeURLToVO.put(coAuthorURLNode.toString(), coAuthorNode); + + RDFNode coAuthorLabelNode = solution.get(QueryFieldLabels.CO_AUTHOR_LABEL); + if (coAuthorLabelNode != null) { + coAuthorNode.setCollaboratorName(coAuthorLabelNode.toString()); + } + } + + coAuthorNode.addActivity(biboDocument); + + Set coAuthorsForCurrentBiboDocument; + + if (biboDocumentURLToCoAuthors.containsKey(biboDocument.getActivityURI())) { + coAuthorsForCurrentBiboDocument = biboDocumentURLToCoAuthors + .get(biboDocument.getActivityURI()); + } else { + coAuthorsForCurrentBiboDocument = new HashSet(); + biboDocumentURLToCoAuthors.put(biboDocument.getActivityURI(), + coAuthorsForCurrentBiboDocument); + } + + coAuthorsForCurrentBiboDocument.add(coAuthorNode); + + Collaboration egoCoAuthorEdge = + getExistingEdge(egoNode, coAuthorNode, edgeUniqueIdentifierToVO); + + /* + * If "egoCoAuthorEdge" is null it means that no Collaboration exists in between the + * egoNode & current coAuthorNode. Else create a new Collaboration, add it to the edges + * set & add the collaborator document to it. + * */ + if (egoCoAuthorEdge != null) { + egoCoAuthorEdge.addActivity(biboDocument); + } else { + egoCoAuthorEdge = + new Collaboration(egoNode, coAuthorNode, biboDocument, edgeIDGenerator); + edges.add(egoCoAuthorEdge); + edgeUniqueIdentifierToVO.put( + getEdgeUniqueIdentifier(egoNode.getCollaboratorID(), + coAuthorNode.getCollaboratorID()), + egoCoAuthorEdge); + } + + + } + + + + /* + * This method takes out all the authors & edges between authors that belong to documents + * that have more than 100 authors. We conjecture that these papers do not provide much + * insight. However, we have left the documents be. + * + * This method side-effects "nodes" & "edges". + * */ + removeLowQualityNodesAndEdges(nodes, + biboDocumentURLToVO, + biboDocumentURLToCoAuthors, + edges); + + /* + * We need to create edges between 2 co-authors. E.g. On a paper there were 3 authors + * ego, A & B then we have already created edges like, + * ego - A + * ego - B + * The below sub-routine will take care of, + * A - B + * + * We are side-effecting "edges" here. The only reason to do this is because we are adding + * edges en masse for all the co-authors on all the publications considered so far. The + * other reason being we dont want to compare against 2 sets of edges (edges created before + * & co-author edges created during the course of this method) when we are creating a new + * Collaboration. + * */ + createCoAuthorEdges(biboDocumentURLToVO, + biboDocumentURLToCoAuthors, + edges, + edgeUniqueIdentifierToVO); + + + return new CoAuthorshipData(egoNode, nodes, edges); + } + + private void removeLowQualityNodesAndEdges( + Set nodes, + Map biboDocumentURLToVO, + Map> biboDocumentURLToCoAuthors, + Set edges) { + + Set nodesToBeRemoved = new HashSet(); + for (Map.Entry> currentBiboDocumentEntry + : biboDocumentURLToCoAuthors.entrySet()) { + + if (currentBiboDocumentEntry.getValue().size() > MAX_AUTHORS_PER_PAPER_ALLOWED) { + + Activity currentBiboDocument = biboDocumentURLToVO + .get(currentBiboDocumentEntry.getKey()); + + Set edgesToBeRemoved = new HashSet(); + + for (Collaboration currentEdge : edges) { + Set currentCollaboratorDocuments = + currentEdge.getCollaborationActivities(); + + if (currentCollaboratorDocuments.contains(currentBiboDocument)) { + currentCollaboratorDocuments.remove(currentBiboDocument); + if (currentCollaboratorDocuments.isEmpty()) { + edgesToBeRemoved.add(currentEdge); + } + } + } + + edges.removeAll(edgesToBeRemoved); + + for (Collaborator currentCoAuthor : currentBiboDocumentEntry.getValue()) { + currentCoAuthor.getCollaboratorActivities().remove(currentBiboDocument); + if (currentCoAuthor.getCollaboratorActivities().isEmpty()) { + nodesToBeRemoved.add(currentCoAuthor); + } + } + } + } + nodes.removeAll(nodesToBeRemoved); + } + + private void createCoAuthorEdges( + Map biboDocumentURLToVO, + Map> biboDocumentURLToCoAuthors, Set edges, + Map edgeUniqueIdentifierToVO) { + + for (Map.Entry> currentBiboDocumentEntry + : biboDocumentURLToCoAuthors.entrySet()) { + + /* + * If there was only one co-author (other than ego) then we dont have to create any + * edges. so the below condition will take care of that. + * + * We are restricting edges between co-author if a particular document has more than + * 100 co-authors. Our conjecture is that such edges do not provide any good insight + * & causes unnecessary computations causing the server to time-out. + * */ + if (currentBiboDocumentEntry.getValue().size() > 1 + && currentBiboDocumentEntry.getValue().size() + <= MAX_AUTHORS_PER_PAPER_ALLOWED) { + + + Set newlyAddedEdges = new HashSet(); + + /* + * In order to leverage the nested "for loop" for making edges between all the + * co-authors we need to create a list out of the set first. + * */ + List coAuthorNodes = + new ArrayList(currentBiboDocumentEntry.getValue()); + + Collections.sort(coAuthorNodes, new CollaboratorComparator()); + + int numOfCoAuthors = coAuthorNodes.size(); + + for (int ii = 0; ii < numOfCoAuthors - 1; ii++) { + for (int jj = ii + 1; jj < numOfCoAuthors; jj++) { + + Collaborator coAuthor1 = coAuthorNodes.get(ii); + Collaborator coAuthor2 = coAuthorNodes.get(jj); + + Collaboration coAuthor1_2Edge = getExistingEdge(coAuthor1, + coAuthor2, + edgeUniqueIdentifierToVO); + + Activity currentBiboDocument = biboDocumentURLToVO + .get(currentBiboDocumentEntry + .getKey()); + + if (coAuthor1_2Edge != null) { + coAuthor1_2Edge.addActivity(currentBiboDocument); + } else { + coAuthor1_2Edge = new Collaboration(coAuthor1, + coAuthor2, + currentBiboDocument, + edgeIDGenerator); + newlyAddedEdges.add(coAuthor1_2Edge); + edgeUniqueIdentifierToVO.put( + getEdgeUniqueIdentifier(coAuthor1.getCollaboratorID(), + coAuthor2.getCollaboratorID()), + coAuthor1_2Edge); + } + } + } + edges.addAll(newlyAddedEdges); + } + + } + } + + private Collaboration getExistingEdge( + Collaborator collaboratingNode1, + Collaborator collaboratingNode2, + Map edgeUniqueIdentifierToVO) { + + String edgeUniqueIdentifier = getEdgeUniqueIdentifier( + collaboratingNode1.getCollaboratorID(), + collaboratingNode2.getCollaboratorID()); + + return edgeUniqueIdentifierToVO.get(edgeUniqueIdentifier); + + } + + private String getEdgeUniqueIdentifier(int nodeID1, int nodeID2) { + + String separator = "*"; + + if (nodeID1 < nodeID2) { + return nodeID1 + separator + nodeID2; + } else { + return nodeID2 + separator + nodeID1; + } + + } + + private Activity createDocumentVO(QuerySolution solution, String documentURL) { + + Activity biboDocument = new Activity(documentURL); + + RDFNode publicationDateNode = solution.get(QueryFieldLabels.DOCUMENT_PUBLICATION_DATE); + if (publicationDateNode != null) { + biboDocument.setActivityDate(publicationDateNode.toString()); + } + + return biboDocument; + } + + private ResultSet executeQuery(String queryText, + Dataset dataset) { + + QueryExecution queryExecution = null; + Query query = QueryFactory.create(queryText, SYNTAX); + + queryExecution = QueryExecutionFactory.create(query, dataset); + return queryExecution.execSelect(); + } + + private String generateEgoCoAuthorshipSparqlQuery(String queryURI) { + + String sparqlQuery = QueryConstants.getSparqlPrefixQuery() + + "SELECT \n" + + " (str(<" + queryURI + ">) as ?" + QueryFieldLabels.AUTHOR_URL + ") \n" + + " (str(?authorLabel) as ?" + QueryFieldLabels.AUTHOR_LABEL + ") \n" + + " (str(?coAuthorPerson) as ?" + QueryFieldLabels.CO_AUTHOR_URL + ") \n" + + " (str(?coAuthorPersonLabel) as ?" + QueryFieldLabels.CO_AUTHOR_LABEL + ") \n" + + " (str(?document) as ?" + QueryFieldLabels.DOCUMENT_URL + ") \n" + + " (str(?publicationDate) as ?" + + QueryFieldLabels.DOCUMENT_PUBLICATION_DATE + ") \n" + + "WHERE { \n" + + "<" + queryURI + "> rdf:type foaf:Person ;" + + " rdfs:label ?authorLabel ;" + + " core:relatedBy ?authorshipNode . \n" + + "?authorshipNode rdf:type core:Authorship ;" + + " core:relates ?document . \n" + + "?document rdf:type bibo:Document . \n" + + "?document core:relatedBy ?coAuthorshipNode . \n" + + "?coAuthorshipNode rdf:type core:Authorship . \n" + + "?coAuthorshipNode core:relates ?coAuthorPerson . \n" + + "?coAuthorPerson rdf:type foaf:Person . \n" + + "?coAuthorPerson rdfs:label ?coAuthorPersonLabel . \n" + + "OPTIONAL { ?document core:dateTimeValue ?dateTimeValue . \n" + + " ?dateTimeValue core:dateTime ?publicationDate } .\n" + + "} \n" + + "ORDER BY ?document ?coAuthorPerson\n"; + + log.debug("COAUTHORSHIP QUERY - " + sparqlQuery); + + return sparqlQuery; + } + + + public CollaborationData getQueryResult() + throws MalformedQueryParametersException { + + if (StringUtils.isNotBlank(this.egoURI)) { + /* + * To test for the validity of the URI submitted. + * */ + IRIFactory iRIFactory = IRIFactory.jenaImplementation(); + IRI iri = iRIFactory.create(this.egoURI); + if (iri.hasViolation(false)) { + String errorMsg = ((Violation) iri.violations(false).next()).getShortMessage(); + log.error("Ego Co-Authorship Vis Query " + errorMsg); + throw new MalformedQueryParametersException( + "URI provided for an individual is malformed."); + } + } else { + throw new MalformedQueryParametersException("URI parameter is either null or empty."); + } + + ResultSet resultSet = executeQuery(generateEgoCoAuthorshipSparqlQuery(this.egoURI), + this.dataset); + return createQueryResult(resultSet); + } + +} diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/coprincipalinvestigator/CoPIGrantCountConstructQueryRunner.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/coprincipalinvestigator/CoPIGrantCountConstructQueryRunner.java index c1ab3a09..07bcfc66 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/coprincipalinvestigator/CoPIGrantCountConstructQueryRunner.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/coprincipalinvestigator/CoPIGrantCountConstructQueryRunner.java @@ -38,9 +38,9 @@ public class CoPIGrantCountConstructQueryRunner implements ModelConstructor { .getLog(CoPIGrantCountConstructQueryRunner.class.getName()); private static final String SPARQL_QUERY_COMMON_CONSTRUCT_AND_WHERE_STRING = - "?Role core:roleContributesTo ?Grant . " -// + "?Grant rdfs:label ?GrantLabel . " - + "?Grant core:contributingRole ?RelatedRole . "; + "?Role core:relatedBy ?Grant . " + + "?Grant rdf:type core:Grant ." + + "?Grant core:relates ?RelatedRole . "; public CoPIGrantCountConstructQueryRunner(String egoURI, Dataset dataset, Log log) { @@ -59,23 +59,31 @@ public class CoPIGrantCountConstructQueryRunner implements ModelConstructor { } private String generateConstructQueryForInvestigatorRoleOfProperty( - String queryURI, String preboundProperty) { + String queryURI, String preboundProperty, String preboundRoleType) { String sparqlQuery = "CONSTRUCT { " + "<" + queryURI + ">" + preboundProperty + " ?Role . " + + "?Role rdf:type " + preboundRoleType + " . " + SPARQL_QUERY_COMMON_CONSTRUCT_AND_WHERE_STRING - + "?RelatedRole core:investigatorRoleOf ?coInvestigator ." + + "?RelatedRole rdf:type core:InvestigatorRole ." + + "?RelatedRole ?coInvestigator ." + + "?coInvestigator rdf:type foaf:Person ." + "?coInvestigator rdfs:label ?coInvestigatorLabel . " + "}" - + "WHERE { " + "<" + queryURI + ">" + preboundProperty - + " ?Role . " + SPARQL_QUERY_COMMON_CONSTRUCT_AND_WHERE_STRING - + "?RelatedRole core:investigatorRoleOf ?coInvestigator ." - + "?coInvestigator rdfs:label ?coInvestigatorLabel . " + "}"; + + "WHERE { " + "<" + queryURI + ">" + preboundProperty + " ?Role . " + + "?Role rdf:type " + preboundRoleType + " . " + + SPARQL_QUERY_COMMON_CONSTRUCT_AND_WHERE_STRING + + "?RelatedRole rdf:type core:InvestigatorRole ." + + "?RelatedRole vitro:mostSpecificType ?subclass ." + + "?RelatedRole ?coInvestigator ." + + "?coInvestigator rdf:type foaf:Person ." + + "?coInvestigator rdfs:label ?coInvestigatorLabel . " + + "FILTER (?subclass != core:PrincipalInvestigatorRole && ?subclass != core:CoPrincipalInvestigatorRole)}"; return sparqlQuery; } private String generateConstructQueryForPrincipalInvestigatorRoleOfProperty( - String queryURI, String preboundProperty) { + String queryURI, String preboundProperty, String preboundRoleType) { String sparqlQuery = "CONSTRUCT { " + "<" @@ -83,8 +91,11 @@ public class CoPIGrantCountConstructQueryRunner implements ModelConstructor { + ">" + preboundProperty + " ?Role . " + + "?Role rdf:type " + preboundRoleType + " . " + SPARQL_QUERY_COMMON_CONSTRUCT_AND_WHERE_STRING - + "?RelatedRole core:principalInvestigatorRoleOf ?coInvestigator ." + + "?RelatedRole rdf:type core:PrincipalInvestigatorRole ." + + "?RelatedRole ?coInvestigator ." + + "?coInvestigator rdf:type foaf:Person ." + "?coInvestigator rdfs:label ?coInvestigatorLabel . " + "}" + "WHERE { " @@ -93,15 +104,18 @@ public class CoPIGrantCountConstructQueryRunner implements ModelConstructor { + ">" + preboundProperty + " ?Role . " + + "?Role rdf:type " + preboundRoleType + " . " + SPARQL_QUERY_COMMON_CONSTRUCT_AND_WHERE_STRING - + "?RelatedRole core:principalInvestigatorRoleOf ?coInvestigator ." + + "?RelatedRole rdf:type core:PrincipalInvestigatorRole ." + + "?RelatedRole ?coInvestigator ." + + "?coInvestigator rdf:type foaf:Person ." + "?coInvestigator rdfs:label ?coInvestigatorLabel . " + "}"; return sparqlQuery; } private String generateConstructQueryForCoPrincipalInvestigatorRoleOfProperty( - String queryURI, String preboundProperty) { + String queryURI, String preboundProperty, String preboundRoleType) { String sparqlQuery = "CONSTRUCT { " + "<" @@ -109,8 +123,11 @@ public class CoPIGrantCountConstructQueryRunner implements ModelConstructor { + ">" + preboundProperty + " ?Role . " + + "?Role rdf:type " + preboundRoleType + " . " + SPARQL_QUERY_COMMON_CONSTRUCT_AND_WHERE_STRING - + "?RelatedRole core:co-PrincipalInvestigatorRoleOf ?coInvestigator ." + + "?RelatedRole rdf:type core:CoPrincipalInvestigatorRole ." + + "?RelatedRole ?coInvestigator ." + + "?coInvestigator rdf:type foaf:Person ." + "?coInvestigator rdfs:label ?coInvestigatorLabel . " + "}" + "WHERE { " @@ -119,18 +136,22 @@ public class CoPIGrantCountConstructQueryRunner implements ModelConstructor { + ">" + preboundProperty + " ?Role . " + + "?Role rdf:type " + preboundRoleType + " . " + SPARQL_QUERY_COMMON_CONSTRUCT_AND_WHERE_STRING - + "?RelatedRole core:co-PrincipalInvestigatorRoleOf ?coInvestigator ." + + "?RelatedRole rdf:type core:CoPrincipalInvestigatorRole ." + + "?RelatedRole ?coInvestigator ." + + "?coInvestigator rdf:type foaf:Person ." + "?coInvestigator rdfs:label ?coInvestigatorLabel . " + "}"; return sparqlQuery; } private String generateConstructQueryForDateTimeValueofRole( - String queryURI, String preboundProperty) { + String queryURI, String preboundProperty, String preboundRoleType) { String sparqlQuery = "CONSTRUCT { " + "<" + queryURI + ">" + preboundProperty + " ?Role . " + + "?Role rdf:type " + preboundRoleType + " . " + "?Role core:dateTimeInterval ?dateTimeIntervalValue . " + "?dateTimeIntervalValue core:start ?startDate . " + "?startDate core:dateTime ?startDateTimeValue . " @@ -139,6 +160,7 @@ public class CoPIGrantCountConstructQueryRunner implements ModelConstructor { + "}" + "WHERE { " + "{" + "<" + queryURI + ">" + preboundProperty + " ?Role . " + + "?Role rdf:type " + preboundRoleType + " . " + "?Role core:dateTimeInterval ?dateTimeIntervalValue . " + "?dateTimeIntervalValue core:start ?startDate . " + "?startDate core:dateTime ?startDateTimeValue . " @@ -153,14 +175,16 @@ public class CoPIGrantCountConstructQueryRunner implements ModelConstructor { } private String generateConstructQueryForDateTimeValueofGrant( - String queryURI, String preboundProperty) { + String queryURI, String preboundProperty, String preboundRoleType) { String sparqlQuery = "CONSTRUCT { " + "<" + queryURI + ">" + preboundProperty + " ?Role . " - + "?Role core:roleContributesTo ?Grant ." + + "?Role rdf:type " + preboundRoleType + " . " + + "?Role core:relatedBy ?Grant ." + + "?Grant rdf:type core:Grant ." + "?Grant core:dateTimeInterval ?dateTimeIntervalValueForGrant . " + "?dateTimeIntervalValueForGrant core:start ?startDateForGrant . " + "?startDateForGrant core:dateTime ?startDateTimeValueForGrant . " @@ -174,7 +198,9 @@ public class CoPIGrantCountConstructQueryRunner implements ModelConstructor { + ">" + preboundProperty + " ?Role . " - + "?Role core:roleContributesTo ?Grant ." + + "?Role rdf:type " + preboundRoleType + " . " + + "?Role core:relatedBy ?Grant ." + + "?Grant rdf:type core:Grant ." + "?Grant core:dateTimeInterval ?dateTimeIntervalValueForGrant . " + "?dateTimeIntervalValueForGrant core:start ?startDateForGrant . " + "?startDateForGrant core:dateTime ?startDateTimeValueForGrant . " @@ -268,45 +294,45 @@ public class CoPIGrantCountConstructQueryRunner implements ModelConstructor { .add(generateConstructQueryForInvestigatorLabel(this.egoURI)); constructQueries .add(generateConstructQueryForInvestigatorRoleOfProperty( - this.egoURI, "core:hasInvestigatorRole")); + this.egoURI, "", "core:InvestigatorRole")); constructQueries .add(generateConstructQueryForCoPrincipalInvestigatorRoleOfProperty( - this.egoURI, "core:hasInvestigatorRole")); + this.egoURI, "", "core:InvestigatorRole")); constructQueries .add(generateConstructQueryForPrincipalInvestigatorRoleOfProperty( - this.egoURI, "core:hasInvestigatorRole")); + this.egoURI, "", "core:InvestigatorRole")); constructQueries.add(generateConstructQueryForDateTimeValueofRole( - this.egoURI, "core:hasInvestigatorRole")); + this.egoURI, "", "core:InvestigatorRole")); constructQueries.add(generateConstructQueryForDateTimeValueofGrant( - this.egoURI, "core:hasInvestigatorRole")); + this.egoURI, "", "core:InvestigatorRole")); constructQueries .add(generateConstructQueryForInvestigatorRoleOfProperty( - this.egoURI, "core:hasPrincipalInvestigatorRole")); + this.egoURI, "", "core:PrincipalInvestigatorRole")); constructQueries .add(generateConstructQueryForCoPrincipalInvestigatorRoleOfProperty( - this.egoURI, "core:hasPrincipalInvestigatorRole")); + this.egoURI, "", "core:PrincipalInvestigatorRole")); constructQueries .add(generateConstructQueryForPrincipalInvestigatorRoleOfProperty( - this.egoURI, "core:hasPrincipalInvestigatorRole")); + this.egoURI, "", "core:PrincipalInvestigatorRole")); constructQueries.add(generateConstructQueryForDateTimeValueofRole( - this.egoURI, "core:hasPrincipalInvestigatorRole")); + this.egoURI, "", "core:PrincipalInvestigatorRole")); constructQueries.add(generateConstructQueryForDateTimeValueofGrant( - this.egoURI, "core:hasPrincipalInvestigatorRole")); + this.egoURI, "", "core:PrincipalInvestigatorRole")); constructQueries .add(generateConstructQueryForInvestigatorRoleOfProperty( - this.egoURI, "core:hasCo-PrincipalInvestigatorRole")); + this.egoURI, "", "core:CoPrincipalInvestigatorRole")); constructQueries .add(generateConstructQueryForCoPrincipalInvestigatorRoleOfProperty( - this.egoURI, "core:hasCo-PrincipalInvestigatorRole")); + this.egoURI, "", "core:CoPrincipalInvestigatorRole")); constructQueries .add(generateConstructQueryForPrincipalInvestigatorRoleOfProperty( - this.egoURI, "core:hasCo-PrincipalInvestigatorRole")); + this.egoURI, "", "core:CoPrincipalInvestigatorRole")); constructQueries.add(generateConstructQueryForDateTimeValueofRole( - this.egoURI, "core:hasCo-PrincipalInvestigatorRole")); + this.egoURI, "", "core:CoPrincipalInvestigatorRole")); constructQueries.add(generateConstructQueryForDateTimeValueofGrant( - this.egoURI, "core:hasCo-PrincipalInvestigatorRole")); + this.egoURI, "", "core:CoPrincipalInvestigatorRole")); } } \ No newline at end of file diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/coprincipalinvestigator/CoPIGrantCountQueryRunner.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/coprincipalinvestigator/CoPIGrantCountQueryRunner.java index a33dba55..61b0f701 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/coprincipalinvestigator/CoPIGrantCountQueryRunner.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/coprincipalinvestigator/CoPIGrantCountQueryRunner.java @@ -113,13 +113,21 @@ public class CoPIGrantCountQueryRunner implements QueryRunner + "<" + queryURI + "> rdfs:label ?PILabel . " + "{ " - + "<" + queryURI + "> core:hasCo-PrincipalInvestigatorRole ?Role . " + + "<" + queryURI + "> ?Role . " - + "?Role core:roleContributesTo ?Grant . " + + "?Role rdf:type core:CoPrincipalInvestigatorRole . " - + "?Grant core:contributingRole ?RelatedRole . " + + "?Role core:relatedBy ?Grant . " - + "?RelatedRole core:principalInvestigatorRoleOf ?CoPI . " + + "?Grant rdf:type core:Grant . " + + + "?Grant core:relates ?RelatedRole . " + + + "?RelatedRole rdf:type core:PrincipalInvestigatorRole . " + + + "?RelatedRole ?CoPI . " + + + "?CoPI rdf:type foaf:Person . " + "?CoPI rdfs:label ?CoPILabel . " @@ -133,13 +141,21 @@ public class CoPIGrantCountQueryRunner implements QueryRunner + "{ " - + "<" + queryURI + "> core:hasCo-PrincipalInvestigatorRole ?Role . " + + "<" + queryURI + "> ?Role . " - + "?Role core:roleContributesTo ?Grant . " + + "?Role rdf:type core:CoPrincipalInvestigatorRole . " - + "?Grant core:contributingRole ?RelatedRole . " + + "?Role core:relatedBy ?Grant . " - + "?RelatedRole core:investigatorRoleOf ?CoPI . " + + "?Grant rdf:type core:Grant . " + + + "?Grant core:relates ?RelatedRole . " + + + "?RelatedRole rdf:type core:InvestigatorRole . " + + + "?RelatedRole ?CoPI . " + + + "?CoPI rdf:type foaf:Person . " + "?CoPI rdfs:label ?CoPILabel . " @@ -154,13 +170,21 @@ public class CoPIGrantCountQueryRunner implements QueryRunner + "{ " - + "<" + queryURI + "> core:hasCo-PrincipalInvestigatorRole ?Role . " + + "<" + queryURI + "> ?Role . " - + "?Role core:roleContributesTo ?Grant . " + + "?Role rdf:type core:CoPrincipalInvestigatorRole . " - + "?Grant core:contributingRole ?RelatedRole . " + + "?Role core:relatedBy ?Grant . " - + "?RelatedRole core:co-PrincipalInvestigatorRoleOf ?CoPI . " + + "?Grant rdf:type core:Grant . " + + + "?Grant core:relates ?RelatedRole . " + + + "?RelatedRole rdf:type core:CoPrincipalInvestigatorRole . " + + + "?RelatedRole ?CoPI . " + + + "?CoPI rdf:type foaf:Person . " + "?CoPI rdfs:label ?CoPILabel . " @@ -176,13 +200,21 @@ public class CoPIGrantCountQueryRunner implements QueryRunner + "{ " - + "<" + queryURI + "> core:hasPrincipalInvestigatorRole ?Role . " + + "<" + queryURI + "> ?Role . " - + "?Role core:roleContributesTo ?Grant . " + + "?Role rdf:type core:PrincipalInvestigatorRole . " - + "?Grant core:contributingRole ?RelatedRole . " + + "?Role core:relatedBy ?Grant . " - + "?RelatedRole core:principalInvestigatorRoleOf ?CoPI . " + + "?Grant rdf:type core:Grant . " + + + "?Grant core:relates ?RelatedRole . " + + + "?RelatedRole rdf:type core:PrincipalInvestigatorRole . " + + + "?RelatedRole ?CoPI . " + + + "?CoPI rdf:type foaf:Person . " + "?CoPI rdfs:label ?CoPILabel . " @@ -197,13 +229,21 @@ public class CoPIGrantCountQueryRunner implements QueryRunner + "{ " - + "<" + queryURI + "> core:hasPrincipalInvestigatorRole ?Role . " + + "<" + queryURI + "> ?Role . " - + "?Role core:roleContributesTo ?Grant . " + + "?Role rdf:type core:PrincipalInvestigatorRole . " - + "?Grant core:contributingRole ?RelatedRole . " + + "?Role core:relatedBy ?Grant . " - + "?RelatedRole core:investigatorRoleOf ?CoPI . " + + "?Grant rdf:type core:Grant . " + + + "?Grant core:relates ?RelatedRole . " + + + "?RelatedRole rdf:type core:InvestigatorRole . " + + + "?RelatedRole ?CoPI . " + + + "?CoPI rdf:type foaf:Person . " + "?CoPI rdfs:label ?CoPILabel . " @@ -218,13 +258,21 @@ public class CoPIGrantCountQueryRunner implements QueryRunner + "{ " - + "<" + queryURI + "> core:hasPrincipalInvestigatorRole ?Role . " + + "<" + queryURI + "> ?Role . " - + "?Role core:roleContributesTo ?Grant . " + + "?Role rdf:type core:PrincipalInvestigatorRole . " - + "?Grant core:contributingRole ?RelatedRole . " + + "?Role core:relatedBy ?Grant . " - + "?RelatedRole core:co-PrincipalInvestigatorRoleOf ?CoPI . " + + "?Grant rdf:type core:Grant . " + + + "?Grant core:relates ?RelatedRole . " + + + "?RelatedRole rdf:type core:CoPrincipalInvestigatorRole . " + + + "?RelatedRole ?CoPI . " + + + "?CoPI rdf:type foaf:Person . " + "?CoPI rdfs:label ?CoPILabel . " @@ -239,13 +287,21 @@ public class CoPIGrantCountQueryRunner implements QueryRunner + "{ " - + "<" + queryURI + "> core:hasInvestigatorRole ?Role . " + + "<" + queryURI + "> ?Role . " - + "?Role core:roleContributesTo ?Grant . " + + "?Role rdf:type core:InvestigatorRole . " - + "?Grant core:contributingRole ?RelatedRole . " + + "?Role core:relatedBy ?Grant . " - + "?RelatedRole core:investigatorRoleOf ?CoPI . " + + "?Grant rdf:type core:Grant . " + + + "?Grant core:relates ?RelatedRole . " + + + "?RelatedRole rdf:type core:InvestigatorRole . " + + + "?RelatedRole ?CoPI . " + + + "?CoPI rdf:type foaf:Person . " + "?CoPI rdfs:label ?CoPILabel . " @@ -260,13 +316,21 @@ public class CoPIGrantCountQueryRunner implements QueryRunner + "{ " - + "<" + queryURI + "> core:hasInvestigatorRole ?Role . " + + "<" + queryURI + "> ?Role . " - + "?Role core:roleContributesTo ?Grant . " + + "?Role rdf:type core:InvestigatorRole . " - + "?Grant core:contributingRole ?RelatedRole . " + + "?Role core:relatedBy ?Grant . " - + "?RelatedRole core:co-PrincipalInvestigatorRoleOf ?CoPI . " + + "?Grant rdf:type core:Grant . " + + + "?Grant core:relates ?RelatedRole . " + + + "?RelatedRole rdf:type core:CoPrincipalInvestigatorRole . " + + + "?RelatedRole ?CoPI . " + + + "?CoPI rdf:type foaf:Person . " + "?CoPI rdfs:label ?CoPILabel . " @@ -281,13 +345,21 @@ public class CoPIGrantCountQueryRunner implements QueryRunner + "{ " - + "<" + queryURI + "> core:hasInvestigatorRole ?Role . " + + "<" + queryURI + "> ?Role . " - + "?Role core:roleContributesTo ?Grant . " + + "?Role rdf:type core:InvestigatorRole . " - + "?Grant core:contributingRole ?RelatedRole . " + + "?Role core:relatedBy ?Grant . " - + "?RelatedRole core:principalInvestigatorRoleOf ?CoPI . " + + "?Grant rdf:type core:Grant . " + + + "?Grant core:relates ?RelatedRole . " + + + "?RelatedRole rdf:type core:PrincipalInvestigatorRole . " + + + "?RelatedRole ?CoPI . " + + + "?CoPI rdf:type foaf:Person . " + "?CoPI rdfs:label ?CoPILabel . " diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/OrganizationAssociatedPeopleModelWithTypesConstructor.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/OrganizationAssociatedPeopleModelWithTypesConstructor.java index c0aa78e9..21485879 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/OrganizationAssociatedPeopleModelWithTypesConstructor.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/OrganizationAssociatedPeopleModelWithTypesConstructor.java @@ -53,8 +53,9 @@ public class OrganizationAssociatedPeopleModelWithTypesConstructor implements Mo + " <" + organizationURI + "> rdf:type foaf:Organization . " + " <" + organizationURI + "> rdfs:label ?organizationLabel . " + " OPTIONAL { " - + " <" + organizationURI + "> core:organizationForPosition ?Position . " - + " ?Position core:positionForPerson ?Person . " + + " <" + organizationURI + "> core:relatedBy ?Position . " + + " ?Position rdf:type core:Position . " + + " ?Position core:relates ?Person . " + " ?Person rdfs:label ?personLabel. " + " ?Person rdf:type ?personType . " + " ?personType rdfs:label ?personTypeLabel . " diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/OrganizationModelWithTypesConstructor.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/OrganizationModelWithTypesConstructor.java index 90a76439..7720e9ae 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/OrganizationModelWithTypesConstructor.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/OrganizationModelWithTypesConstructor.java @@ -50,7 +50,8 @@ public class OrganizationModelWithTypesConstructor implements ModelConstructor { + " CONSTRUCT { " + " ?organization rdf:type foaf:Organization . " + " ?organization rdfs:label ?organizationLabel . " - + " ?organization core:hasSubOrganization ?subOrganization . " + + " ?organization ?subOrganization . " + + " ?subOrganization rdf:type foaf:Organization . " + " ?subOrganization rdfs:label ?subOrganizationLabel . " + " ?subOrganization rdf:type ?subOrganizationType . " + " ?subOrganizationType rdfs:label ?subOrganizationTypeLabel . " @@ -60,7 +61,8 @@ public class OrganizationModelWithTypesConstructor implements ModelConstructor { + " ?organization rdfs:label ?organizationLabel . " + " " + " OPTIONAL { " - + " ?organization core:hasSubOrganization ?subOrganization . " + + " ?organization ?subOrganization . " + + " ?subOrganization rdf:type foaf:Organization . " + " ?subOrganization rdfs:label ?subOrganizationLabel . " + " ?subOrganization rdf:type ?subOrganizationType . " + " ?subOrganizationType rdfs:label ?subOrganizationTypeLabel . " diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/OrganizationToGrantsForSubOrganizationsModelConstructor.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/OrganizationToGrantsForSubOrganizationsModelConstructor.java index 4a8f238a..75403b07 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/OrganizationToGrantsForSubOrganizationsModelConstructor.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/OrganizationToGrantsForSubOrganizationsModelConstructor.java @@ -1,189 +1,204 @@ -/* $This file is distributed under the terms of the license in /doc/license.txt$ */ -package edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor; - -import java.util.HashSet; -import java.util.Set; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.hp.hpl.jena.query.Dataset; -import com.hp.hpl.jena.query.Query; -import com.hp.hpl.jena.query.QueryExecution; -import com.hp.hpl.jena.query.QueryExecutionFactory; -import com.hp.hpl.jena.query.QueryFactory; -import com.hp.hpl.jena.query.Syntax; -import com.hp.hpl.jena.rdf.model.Model; -import com.hp.hpl.jena.rdf.model.ModelFactory; - -import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryConstants; -import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; -import edu.cornell.mannlib.vitro.webapp.visualization.visutils.ModelConstructor; - -public class OrganizationToGrantsForSubOrganizationsModelConstructor implements ModelConstructor { - - protected static final Syntax SYNTAX = Syntax.syntaxARQ; - - private Dataset dataset; - - public static final String MODEL_TYPE = "ORGANIZATION_TO_GRANTS_FOR_SUBORGANIZATIONS"; - public static final String MODEL_TYPE_HUMAN_READABLE = "Grants for specific organization via all descendants"; - - private String organizationURI; - - private Log log = LogFactory.getLog(OrganizationToGrantsForSubOrganizationsModelConstructor.class.getName()); - - private long before, after; - - public OrganizationToGrantsForSubOrganizationsModelConstructor(String organizationURI, Dataset dataset) { - this.organizationURI = organizationURI; - this.dataset = dataset; - } - - private Set constructOrganizationGrantsQueryTemplate(String constructProperty, String roleTypeProperty) { - - Set differentPerspectiveQueries = new HashSet(); - - String justGrantsQuery = "" - + " CONSTRUCT { " - + " <" + organizationURI + "> rdfs:label ?organizationLabel . " - + " <" + organizationURI + "> vivosocnet:lastCachedAt ?now . " - + " <" + organizationURI + "> vivosocnet:" + constructProperty + " ?Grant . " - + " " - + " ?Grant rdf:type core:Grant . " - + " ?Grant rdfs:label ?grantLabel . " - + " " - + " } " - + " WHERE { " - + " <" + organizationURI + "> rdfs:label ?organizationLabel . " - + " <" + organizationURI + "> core:hasSubOrganization* ?subOrganization . " - + " ?subOrganization core:organizationForPosition ?Position . " - + " ?Position core:positionForPerson ?Person . " - + " ?Person core:" + roleTypeProperty + " ?Role . " - + " ?Role core:roleContributesTo ?Grant . " - + " ?Grant rdfs:label ?grantLabel . " - + " " - + " LET(?now := afn:now()) " - + " } "; - - String justDateTimeOnGrantsQuery = "" - + " CONSTRUCT { " - + " <" + organizationURI + "> rdfs:label ?organizationLabel . " - + " <" + organizationURI + "> vivosocnet:lastCachedAt ?now . " - + " " - + " ?Grant vivosocnet:startDateTimeOnGrant ?startDateTimeValueForGrant . " -// + " ?Grant vivosocnet:endDateTimeOnGrant ?endDateTimeValueForGrant . " - + " " - + " } " - + " WHERE { " - + " <" + organizationURI + "> rdfs:label ?organizationLabel . " - + " <" + organizationURI + "> core:hasSubOrganization* ?subOrganization . " - + " ?subOrganization core:organizationForPosition ?Position . " - + " ?Position core:positionForPerson ?Person . " - + " ?Person core:" + roleTypeProperty + " ?Role . " - + " ?Role core:roleContributesTo ?Grant . " - + " " - + " ?Grant core:dateTimeInterval ?dateTimeIntervalValueForGrant . " -// + " OPTIONAL { " - + " ?dateTimeIntervalValueForGrant core:start ?startDateForGrant . " - + " ?startDateForGrant core:dateTime ?startDateTimeValueForGrant . " -// + " } " -// + " OPTIONAL { " -// + " ?dateTimeIntervalValueForGrant core:end ?endDateForGrant . " -// + " ?endDateForGrant core:dateTime ?endDateTimeValueForGrant " -// + " } " - + " " - + " LET(?now := afn:now()) " - + " } "; - - String justDateTimeOnRolesQuery = "" - + " CONSTRUCT { " - + " <" + organizationURI + "> rdfs:label ?organizationLabel . " - + " <" + organizationURI + "> vivosocnet:lastCachedAt ?now . " - + " " - + " ?Grant vivosocnet:startDateTimeOnRole ?startDateTimeValue . " -// + " ?Grant vivosocnet:endDateTimeOnRole ?endDateTimeValue . " - + " } " - + " WHERE { " - + " <" + organizationURI + "> rdfs:label ?organizationLabel . " - + " <" + organizationURI + "> core:hasSubOrganization* ?subOrganization . " - + " ?subOrganization core:organizationForPosition ?Position . " - + " ?Position core:positionForPerson ?Person . " - + " ?Person core:" + roleTypeProperty + " ?Role . " - + " ?Role core:roleContributesTo ?Grant . " - + " " - + " ?Role core:dateTimeInterval ?dateTimeIntervalValue . " -// + " OPTIONAL { " - + " ?dateTimeIntervalValue core:start ?startDate . " - + " ?startDate core:dateTime ?startDateTimeValue . " -// + " } " -// + " " -// + " OPTIONAL { " -// + " ?dateTimeIntervalValue core:end ?endDate . " -// + " ?endDate core:dateTime ?endDateTimeValue . " -// + " } " - + " " - + " LET(?now := afn:now()) " - + " } "; - - differentPerspectiveQueries.add(justGrantsQuery); - differentPerspectiveQueries.add(justDateTimeOnGrantsQuery); - differentPerspectiveQueries.add(justDateTimeOnRolesQuery); - - return differentPerspectiveQueries; - } - - private Set constructOrganizationToGrantsQuery() { - - Set differentInvestigatorTypeQueries = new HashSet(); - - Set investigatorRoleQuery = constructOrganizationGrantsQueryTemplate("hasInvestigatorWithGrant", "hasInvestigatorRole"); - Set piRoleQuery = constructOrganizationGrantsQueryTemplate("hasPIWithGrant", "hasPrincipalInvestigatorRole"); - Set coPIRoleQuery = constructOrganizationGrantsQueryTemplate("hascoPIWithGrant", "hasCo-PrincipalInvestigatorRole"); - - differentInvestigatorTypeQueries.addAll(investigatorRoleQuery); - differentInvestigatorTypeQueries.addAll(piRoleQuery); - differentInvestigatorTypeQueries.addAll(coPIRoleQuery); - - return differentInvestigatorTypeQueries; - } - - private Model executeQuery(Set constructQueries) { - - Model constructedModel = ModelFactory.createDefaultModel(); - - before = System.currentTimeMillis(); - log.debug("CONSTRUCT query string : " + constructQueries); - - for (String currentQuery : constructQueries) { - - Query query = null; - - try { - query = QueryFactory.create(QueryConstants.getSparqlPrefixQuery() + currentQuery, SYNTAX); - } catch (Throwable th) { - log.error("Could not create CONSTRUCT SPARQL query for query " - + "string. " + th.getMessage()); - log.error(currentQuery); - } - - QueryExecution qe = QueryExecutionFactory.create(query, dataset); - - try { - qe.execConstruct(constructedModel); - } finally { - qe.close(); - } - } - - after = System.currentTimeMillis(); - log.debug("Time taken to execute the CONSTRUCT queries is in milliseconds: " - + (after - before)); - - return constructedModel; - } - - public Model getConstructedModel() throws MalformedQueryParametersException { - return executeQuery(constructOrganizationToGrantsQuery()); - } -} +/* $This file is distributed under the terms of the license in /doc/license.txt$ */ +package edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor; + +import java.util.HashSet; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.hp.hpl.jena.query.Dataset; +import com.hp.hpl.jena.query.Query; +import com.hp.hpl.jena.query.QueryExecution; +import com.hp.hpl.jena.query.QueryExecutionFactory; +import com.hp.hpl.jena.query.QueryFactory; +import com.hp.hpl.jena.query.Syntax; +import com.hp.hpl.jena.rdf.model.Model; +import com.hp.hpl.jena.rdf.model.ModelFactory; + +import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryConstants; +import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; +import edu.cornell.mannlib.vitro.webapp.visualization.visutils.ModelConstructor; + +public class OrganizationToGrantsForSubOrganizationsModelConstructor implements ModelConstructor { + + protected static final Syntax SYNTAX = Syntax.syntaxARQ; + + private Dataset dataset; + + public static final String MODEL_TYPE = "ORGANIZATION_TO_GRANTS_FOR_SUBORGANIZATIONS"; + public static final String MODEL_TYPE_HUMAN_READABLE = "Grants for specific organization via all descendants"; + + private String organizationURI; + + private Log log = LogFactory.getLog(OrganizationToGrantsForSubOrganizationsModelConstructor.class.getName()); + + private long before, after; + + public OrganizationToGrantsForSubOrganizationsModelConstructor(String organizationURI, Dataset dataset) { + this.organizationURI = organizationURI; + this.dataset = dataset; + } + + private Set constructOrganizationGrantsQueryTemplate(String constructProperty, String roleType) { + + Set differentPerspectiveQueries = new HashSet(); + + String justGrantsQuery = "" + + " CONSTRUCT { " + + " <" + organizationURI + "> rdfs:label ?organizationLabel . " + + " <" + organizationURI + "> vivosocnet:lastCachedAt ?now . " + + " <" + organizationURI + "> vivosocnet:" + constructProperty + " ?Grant . " + + " " + + " ?Grant rdf:type core:Grant . " + + " ?Grant rdfs:label ?grantLabel . " + + " " + + " } " + + " WHERE { " + + " <" + organizationURI + "> rdfs:label ?organizationLabel . " + + " <" + organizationURI + "> * ?subOrganization . " + + " ?subOrganization rdf:type foaf:Organization . " + + " ?subOrganization core:relatedBy ?Position . " + + " ?Position rdf:type core:Position . " + + " ?Position core:relates ?Person . " + + " ?Person rdf:type foaf:Person . " + + " ?Person ?Role . " + + " ?Role rdf:type core:" + roleType + " . " + + " ?Role core:relatedBy ?Grant . " + + " ?Grant rdf:type core:Grant . " + + " ?Grant rdfs:label ?grantLabel . " + + " " + + " LET(?now := afn:now()) " + + " } "; + + String justDateTimeOnGrantsQuery = "" + + " CONSTRUCT { " + + " <" + organizationURI + "> rdfs:label ?organizationLabel . " + + " <" + organizationURI + "> vivosocnet:lastCachedAt ?now . " + + " " + + " ?Grant vivosocnet:startDateTimeOnGrant ?startDateTimeValueForGrant . " +// + " ?Grant vivosocnet:endDateTimeOnGrant ?endDateTimeValueForGrant . " + + " " + + " } " + + " WHERE { " + + " <" + organizationURI + "> rdfs:label ?organizationLabel . " + + " <" + organizationURI + "> * ?subOrganization . " + + " ?subOrganization rdf:type foaf:Organization . " + + " ?subOrganization core:relatedBy ?Position . " + + " ?Position rdf:type core:Position . " + + " ?Position core:relates ?Person . " + + " ?Person rdf:type foaf:Person . " + + " ?Person ?Role . " + + " ?Role rdf:type core:" + roleType + " . " + + " ?Role core:relatedBy ?Grant . " + + " ?Grant rdf:type core:Grant . " + + " " + + " ?Grant core:dateTimeInterval ?dateTimeIntervalValueForGrant . " +// + " OPTIONAL { " + + " ?dateTimeIntervalValueForGrant core:start ?startDateForGrant . " + + " ?startDateForGrant core:dateTime ?startDateTimeValueForGrant . " +// + " } " +// + " OPTIONAL { " +// + " ?dateTimeIntervalValueForGrant core:end ?endDateForGrant . " +// + " ?endDateForGrant core:dateTime ?endDateTimeValueForGrant " +// + " } " + + " " + + " LET(?now := afn:now()) " + + " } "; + + String justDateTimeOnRolesQuery = "" + + " CONSTRUCT { " + + " <" + organizationURI + "> rdfs:label ?organizationLabel . " + + " <" + organizationURI + "> vivosocnet:lastCachedAt ?now . " + + " " + + " ?Grant vivosocnet:startDateTimeOnRole ?startDateTimeValue . " +// + " ?Grant vivosocnet:endDateTimeOnRole ?endDateTimeValue . " + + " } " + + " WHERE { " + + " <" + organizationURI + "> rdfs:label ?organizationLabel . " + + " <" + organizationURI + "> * ?subOrganization . " + + " ?subOrganization rdf:type foaf:Organization . " + + " ?subOrganization core:relatedBy ?Position . " + + " ?Position rdf:type core:Position . " + + " ?Position core:relates ?Person . " + + " ?Person rdf:type foaf:Person . " + + " ?Person ?Role . " + + " ?Role rdf:type core:" + roleType + " . " + + " ?Role core:relatedBy ?Grant . " + + " ?Grant rdf:type core:Grant . " + + " " + + " ?Role core:dateTimeInterval ?dateTimeIntervalValue . " +// + " OPTIONAL { " + + " ?dateTimeIntervalValue core:start ?startDate . " + + " ?startDate core:dateTime ?startDateTimeValue . " +// + " } " +// + " " +// + " OPTIONAL { " +// + " ?dateTimeIntervalValue core:end ?endDate . " +// + " ?endDate core:dateTime ?endDateTimeValue . " +// + " } " + + " " + + " LET(?now := afn:now()) " + + " } "; + + differentPerspectiveQueries.add(justGrantsQuery); + differentPerspectiveQueries.add(justDateTimeOnGrantsQuery); + differentPerspectiveQueries.add(justDateTimeOnRolesQuery); + + return differentPerspectiveQueries; + } + + private Set constructOrganizationToGrantsQuery() { + + Set differentInvestigatorTypeQueries = new HashSet(); + + Set investigatorRoleQuery = constructOrganizationGrantsQueryTemplate("hasInvestigatorWithGrant", "InvestigatorRole"); + Set piRoleQuery = constructOrganizationGrantsQueryTemplate("hasPIWithGrant", "PrincipalInvestigatorRole"); + Set coPIRoleQuery = constructOrganizationGrantsQueryTemplate("hascoPIWithGrant", "CoPrincipalInvestigatorRole"); + + differentInvestigatorTypeQueries.addAll(investigatorRoleQuery); + differentInvestigatorTypeQueries.addAll(piRoleQuery); + differentInvestigatorTypeQueries.addAll(coPIRoleQuery); + + return differentInvestigatorTypeQueries; + } + + private Model executeQuery(Set constructQueries) { + + Model constructedModel = ModelFactory.createDefaultModel(); + + before = System.currentTimeMillis(); + log.debug("CONSTRUCT query string : " + constructQueries); + + for (String currentQuery : constructQueries) { + + Query query = null; + + try { + query = QueryFactory.create(QueryConstants.getSparqlPrefixQuery() + currentQuery, SYNTAX); + } catch (Throwable th) { + log.error("Could not create CONSTRUCT SPARQL query for query " + + "string. " + th.getMessage()); + log.error(currentQuery); + } + + QueryExecution qe = QueryExecutionFactory.create(query, dataset); + + try { + qe.execConstruct(constructedModel); + } finally { + qe.close(); + } + } + + after = System.currentTimeMillis(); + log.debug("Time taken to execute the CONSTRUCT queries is in milliseconds: " + + (after - before)); + + return constructedModel; + } + + public Model getConstructedModel() throws MalformedQueryParametersException { + return executeQuery(constructOrganizationToGrantsQuery()); + } +} diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/OrganizationToPublicationsForSubOrganizationsModelConstructor.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/OrganizationToPublicationsForSubOrganizationsModelConstructor.java index 6a1399cf..47a46649 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/OrganizationToPublicationsForSubOrganizationsModelConstructor.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/OrganizationToPublicationsForSubOrganizationsModelConstructor.java @@ -53,11 +53,16 @@ public class OrganizationToPublicationsForSubOrganizationsModelConstructor imple + " } " + " WHERE { " + " <" + organizationURI + "> rdfs:label ?organizationLabel . " - + " <" + organizationURI + "> core:hasSubOrganization* ?subOrganization . " - + " ?subOrganization core:organizationForPosition ?Position . " - + " ?Position core:positionForPerson ?Person . " - + " ?Person core:authorInAuthorship ?Resource . " - + " ?Resource core:linkedInformationResource ?Document . " + + " <" + organizationURI + "> * ?subOrganization . " + + " ?subOrganization rdf:type foaf:Organization . " + + " ?subOrganization core:relatedBy ?Position . " + + " ?Position rdf:type core:Position . " + + " ?Position core:relates ?Person . " + + " ?Person rdf:type foaf:Person . " + + " ?Person core:relatedBy ?Resource . " + + " ?Resource rdf:type core:Authorship . " + + " ?Resource core:relates ?Document . " + + " ?Document rdf:type bibo:Document . " + " ?Document rdfs:label ?DocumentLabel . " + " " + " OPTIONAL { " diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/PeopleToGrantsModelConstructor.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/PeopleToGrantsModelConstructor.java index f4d7f869..e1bb07f4 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/PeopleToGrantsModelConstructor.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/PeopleToGrantsModelConstructor.java @@ -1,171 +1,177 @@ -/* $This file is distributed under the terms of the license in /doc/license.txt$ */ -package edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor; - -import java.util.HashSet; -import java.util.Set; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.hp.hpl.jena.query.Dataset; -import com.hp.hpl.jena.query.Query; -import com.hp.hpl.jena.query.QueryExecution; -import com.hp.hpl.jena.query.QueryExecutionFactory; -import com.hp.hpl.jena.query.QueryFactory; -import com.hp.hpl.jena.query.Syntax; -import com.hp.hpl.jena.rdf.model.Model; -import com.hp.hpl.jena.rdf.model.ModelFactory; - -import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryConstants; -import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; -import edu.cornell.mannlib.vitro.webapp.visualization.visutils.ModelConstructor; - -public class PeopleToGrantsModelConstructor implements ModelConstructor { - - protected static final Syntax SYNTAX = Syntax.syntaxARQ; - - private Dataset dataset; - - public static final String MODEL_TYPE = "PEOPLE_TO_GRANTS"; - public static final String MODEL_TYPE_HUMAN_READABLE = "Grants for all people via all roles"; - - private Log log = LogFactory.getLog(PeopleToGrantsModelConstructor.class.getName()); - - private long before, after; - - public PeopleToGrantsModelConstructor(Dataset dataset) { - this.dataset = dataset; - } - -private Set constructPersonGrantsQueryTemplate(String constructProperty, String roleTypeProperty) { - - Set differentPerspectiveQueries = new HashSet(); - - String justGrantsQuery = "" - + " CONSTRUCT { " - + " ?person vivosocnet:lastCachedAt ?now . " - + " ?person vivosocnet:" + constructProperty + " ?Grant . " - + " " - + " ?Grant rdf:type core:Grant . " - + " ?Grant rdfs:label ?grantLabel . " - + " " - + " } " - + " WHERE { " - + " ?person core:" + roleTypeProperty + " ?Role . " - + " ?Role core:roleContributesTo ?Grant . " - + " ?Grant rdfs:label ?grantLabel . " - + " " - + " LET(?now := afn:now()) " - + " } "; - - String justDateTimeOnGrantsQuery = "" - + " CONSTRUCT { " - + " ?person vivosocnet:lastCachedAt ?now . " - + " ?Grant vivosocnet:startDateTimeOnGrant ?startDateTimeValueForGrant . " -// + " ?Grant vivosocnet:endDateTimeOnGrant ?endDateTimeValueForGrant . " - + " " - + " } " - + " WHERE { " - + " ?person core:" + roleTypeProperty + " ?Role . " - + " ?Role core:roleContributesTo ?Grant . " - + " " - + " ?Grant core:dateTimeInterval ?dateTimeIntervalValueForGrant . " -// + " OPTIONAL { " - + " ?dateTimeIntervalValueForGrant core:start ?startDateForGrant . " - + " ?startDateForGrant core:dateTime ?startDateTimeValueForGrant . " -// + " } " -// + " OPTIONAL { " -// + " ?dateTimeIntervalValueForGrant core:end ?endDateForGrant . " -// + " ?endDateForGrant core:dateTime ?endDateTimeValueForGrant " -// + " } " - + " " - + " LET(?now := afn:now()) " - + " } "; - - String justDateTimeOnRolesQuery = "" - + " CONSTRUCT { " - + " ?person vivosocnet:lastCachedAt ?now . " - + " ?Grant vivosocnet:startDateTimeOnRole ?startDateTimeValue . " -// + " ?Grant vivosocnet:endDateTimeOnRole ?endDateTimeValue . " - + " } " - + " WHERE { " - + " ?person core:" + roleTypeProperty + " ?Role . " - + " ?Role core:roleContributesTo ?Grant . " - + " " - + " ?Role core:dateTimeInterval ?dateTimeIntervalValue . " -// + " OPTIONAL { " - + " ?dateTimeIntervalValue core:start ?startDate . " - + " ?startDate core:dateTime ?startDateTimeValue . " -// + " } " -// + " " -// + " OPTIONAL { " -// + " ?dateTimeIntervalValue core:end ?endDate . " -// + " ?endDate core:dateTime ?endDateTimeValue . " -// + " } " - + " " - + " LET(?now := afn:now()) " - + " } "; - - differentPerspectiveQueries.add(justGrantsQuery); - differentPerspectiveQueries.add(justDateTimeOnGrantsQuery); - differentPerspectiveQueries.add(justDateTimeOnRolesQuery); - - return differentPerspectiveQueries; - } - - private Set constructPeopleToGrantsQuery() { - - Set differentInvestigatorTypeQueries = new HashSet(); - - Set investigatorRoleQuery = constructPersonGrantsQueryTemplate("hasGrantAsAnInvestigator", "hasInvestigatorRole"); - Set piRoleQuery = constructPersonGrantsQueryTemplate("hasGrantAsPI", "hasPrincipalInvestigatorRole"); - Set coPIRoleQuery = constructPersonGrantsQueryTemplate("hasGrantAsCoPI", "hasCo-PrincipalInvestigatorRole"); - - differentInvestigatorTypeQueries.addAll(investigatorRoleQuery); - differentInvestigatorTypeQueries.addAll(piRoleQuery); - differentInvestigatorTypeQueries.addAll(coPIRoleQuery); - - return differentInvestigatorTypeQueries; - } - - private Model executeQuery(Set constructQueries) { - - Model constructedModel = ModelFactory.createDefaultModel(); - - before = System.currentTimeMillis(); - log.debug("CONSTRUCT query string : " + constructQueries); - - for (String currentQuery : constructQueries) { - - - Query query = null; - - try { - query = QueryFactory.create(QueryConstants.getSparqlPrefixQuery() + currentQuery, SYNTAX); - } catch (Throwable th) { - log.error("Could not create CONSTRUCT SPARQL query for query " - + "string. " + th.getMessage()); - log.error(currentQuery); - } - - - QueryExecution qe = QueryExecutionFactory.create(query, dataset); - - try { - qe.execConstruct(constructedModel); - } finally { - qe.close(); - } - } - - after = System.currentTimeMillis(); - log.debug("Time taken to execute the CONSTRUCT queries is in milliseconds: " - + (after - before)); - - return constructedModel; - } - - public Model getConstructedModel() throws MalformedQueryParametersException { - return executeQuery(constructPeopleToGrantsQuery()); - } -} +/* $This file is distributed under the terms of the license in /doc/license.txt$ */ +package edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor; + +import java.util.HashSet; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.hp.hpl.jena.query.Dataset; +import com.hp.hpl.jena.query.Query; +import com.hp.hpl.jena.query.QueryExecution; +import com.hp.hpl.jena.query.QueryExecutionFactory; +import com.hp.hpl.jena.query.QueryFactory; +import com.hp.hpl.jena.query.Syntax; +import com.hp.hpl.jena.rdf.model.Model; +import com.hp.hpl.jena.rdf.model.ModelFactory; + +import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryConstants; +import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; +import edu.cornell.mannlib.vitro.webapp.visualization.visutils.ModelConstructor; + +public class PeopleToGrantsModelConstructor implements ModelConstructor { + + protected static final Syntax SYNTAX = Syntax.syntaxARQ; + + private Dataset dataset; + + public static final String MODEL_TYPE = "PEOPLE_TO_GRANTS"; + public static final String MODEL_TYPE_HUMAN_READABLE = "Grants for all people via all roles"; + + private Log log = LogFactory.getLog(PeopleToGrantsModelConstructor.class.getName()); + + private long before, after; + + public PeopleToGrantsModelConstructor(Dataset dataset) { + this.dataset = dataset; + } + +private Set constructPersonGrantsQueryTemplate(String constructProperty, String roleType) { + + Set differentPerspectiveQueries = new HashSet(); + + String justGrantsQuery = "" + + " CONSTRUCT { " + + " ?Person vivosocnet:lastCachedAt ?now . " + + " ?Person vivosocnet:" + constructProperty + " ?Grant . " + + " " + + " ?Grant rdf:type core:Grant . " + + " ?Grant rdfs:label ?grantLabel . " + + " " + + " } " + + " WHERE { " + + " ?Person ?Role . " + + " ?Role rdf:type core:" + roleType + " . " + + " ?Role core:relatedBy ?Grant . " + + " ?Grant rdf:type core:Grant . " + + " ?Grant rdfs:label ?grantLabel . " + + " " + + " LET(?now := afn:now()) " + + " } "; + + String justDateTimeOnGrantsQuery = "" + + " CONSTRUCT { " + + " ?Person vivosocnet:lastCachedAt ?now . " + + " ?Grant vivosocnet:startDateTimeOnGrant ?startDateTimeValueForGrant . " +// + " ?Grant vivosocnet:endDateTimeOnGrant ?endDateTimeValueForGrant . " + + " " + + " } " + + " WHERE { " + + " ?Person ?Role . " + + " ?Role rdf:type core:" + roleType + " . " + + " ?Role core:relatedBy ?Grant . " + + " ?Grant rdf:type core:Grant . " + + " " + + " ?Grant core:dateTimeInterval ?dateTimeIntervalValueForGrant . " +// + " OPTIONAL { " + + " ?dateTimeIntervalValueForGrant core:start ?startDateForGrant . " + + " ?startDateForGrant core:dateTime ?startDateTimeValueForGrant . " +// + " } " +// + " OPTIONAL { " +// + " ?dateTimeIntervalValueForGrant core:end ?endDateForGrant . " +// + " ?endDateForGrant core:dateTime ?endDateTimeValueForGrant " +// + " } " + + " " + + " LET(?now := afn:now()) " + + " } "; + + String justDateTimeOnRolesQuery = "" + + " CONSTRUCT { " + + " ?Person vivosocnet:lastCachedAt ?now . " + + " ?Grant vivosocnet:startDateTimeOnRole ?startDateTimeValue . " +// + " ?Grant vivosocnet:endDateTimeOnRole ?endDateTimeValue . " + + " } " + + " WHERE { " + + " ?Person ?Role . " + + " ?Role rdf:type core:" + roleType + " . " + + " ?Role core:relatedBy ?Grant . " + + " ?Grant rdf:type core:Grant . " + + " " + + " ?Role core:dateTimeInterval ?dateTimeIntervalValue . " +// + " OPTIONAL { " + + " ?dateTimeIntervalValue core:start ?startDate . " + + " ?startDate core:dateTime ?startDateTimeValue . " +// + " } " +// + " " +// + " OPTIONAL { " +// + " ?dateTimeIntervalValue core:end ?endDate . " +// + " ?endDate core:dateTime ?endDateTimeValue . " +// + " } " + + " " + + " LET(?now := afn:now()) " + + " } "; + + differentPerspectiveQueries.add(justGrantsQuery); + differentPerspectiveQueries.add(justDateTimeOnGrantsQuery); + differentPerspectiveQueries.add(justDateTimeOnRolesQuery); + + return differentPerspectiveQueries; + } + + private Set constructPeopleToGrantsQuery() { + + Set differentInvestigatorTypeQueries = new HashSet(); + + Set investigatorRoleQuery = constructPersonGrantsQueryTemplate("hasGrantAsAnInvestigator", "InvestigatorRole"); + Set piRoleQuery = constructPersonGrantsQueryTemplate("hasGrantAsPI", "PrincipalInvestigatorRole"); + Set coPIRoleQuery = constructPersonGrantsQueryTemplate("hasGrantAsCoPI", "CoPrincipalInvestigatorRole"); + + differentInvestigatorTypeQueries.addAll(investigatorRoleQuery); + differentInvestigatorTypeQueries.addAll(piRoleQuery); + differentInvestigatorTypeQueries.addAll(coPIRoleQuery); + + return differentInvestigatorTypeQueries; + } + + private Model executeQuery(Set constructQueries) { + + Model constructedModel = ModelFactory.createDefaultModel(); + + before = System.currentTimeMillis(); + log.debug("CONSTRUCT query string : " + constructQueries); + + for (String currentQuery : constructQueries) { + + + Query query = null; + + try { + query = QueryFactory.create(QueryConstants.getSparqlPrefixQuery() + currentQuery, SYNTAX); + } catch (Throwable th) { + log.error("Could not create CONSTRUCT SPARQL query for query " + + "string. " + th.getMessage()); + log.error(currentQuery); + } + + + QueryExecution qe = QueryExecutionFactory.create(query, dataset); + + try { + qe.execConstruct(constructedModel); + } finally { + qe.close(); + } + } + + after = System.currentTimeMillis(); + log.debug("Time taken to execute the CONSTRUCT queries is in milliseconds: " + + (after - before)); + + return constructedModel; + } + + public Model getConstructedModel() throws MalformedQueryParametersException { + return executeQuery(constructPeopleToGrantsQuery()); + } +} diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/PeopleToPublicationsModelConstructor.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/PeopleToPublicationsModelConstructor.java index 50ee11c3..bd572789 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/PeopleToPublicationsModelConstructor.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/PeopleToPublicationsModelConstructor.java @@ -48,8 +48,11 @@ public class PeopleToPublicationsModelConstructor implements ModelConstructor { + " ?journal rdfs:label ?journalLabel . " + " } " + " WHERE { " - + " ?person core:authorInAuthorship ?Resource . " - + " ?Resource core:linkedInformationResource ?Document . " + + " ?person core:relatedBy ?Resource . " + + " ?person rdf:type foaf:Person . " + + " ?Resource rdf:type core:Authorship . " + + " ?Resource core:relates ?Document . " + + " ?Document rdf:type bibo:Document . " + " ?Document rdfs:label ?DocumentLabel . " + " " + " OPTIONAL { " diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/PersonToGrantsModelConstructor.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/PersonToGrantsModelConstructor.java index 74f80558..88a7b168 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/PersonToGrantsModelConstructor.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/PersonToGrantsModelConstructor.java @@ -1,174 +1,180 @@ -/* $This file is distributed under the terms of the license in /doc/license.txt$ */ -package edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor; - -import java.util.HashSet; -import java.util.Set; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.hp.hpl.jena.query.Dataset; -import com.hp.hpl.jena.query.Query; -import com.hp.hpl.jena.query.QueryExecution; -import com.hp.hpl.jena.query.QueryExecutionFactory; -import com.hp.hpl.jena.query.QueryFactory; -import com.hp.hpl.jena.query.Syntax; -import com.hp.hpl.jena.rdf.model.Model; -import com.hp.hpl.jena.rdf.model.ModelFactory; - -import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryConstants; -import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; -import edu.cornell.mannlib.vitro.webapp.visualization.visutils.ModelConstructor; - -public class PersonToGrantsModelConstructor implements ModelConstructor { - - protected static final Syntax SYNTAX = Syntax.syntaxARQ; - - private Dataset dataset; - - public static final String MODEL_TYPE = "PERSON_TO_GRANTS"; - public static final String MODEL_TYPE_HUMAN_READABLE = "Grants for specific person via all roles"; - - private String personURI; - - private Log log = LogFactory.getLog(PersonToGrantsModelConstructor.class.getName()); - - private long before, after; - - public PersonToGrantsModelConstructor(String personURI, Dataset dataset) { - this.personURI = personURI; - this.dataset = dataset; - } - -private Set constructPersonGrantsQueryTemplate(String constructProperty, String roleTypeProperty) { - - Set differentPerspectiveQueries = new HashSet(); - - String justGrantsQuery = "" - + " CONSTRUCT { " - + " <" + personURI + "> vivosocnet:lastCachedAt ?now . " - + " <" + personURI + "> vivosocnet:" + constructProperty + " ?Grant . " - + " " - + " ?Grant rdf:type core:Grant . " - + " ?Grant rdfs:label ?grantLabel . " - + " " - + " } " - + " WHERE { " - + " <" + personURI + "> core:" + roleTypeProperty + " ?Role . " - + " ?Role core:roleContributesTo ?Grant . " - + " ?Grant rdfs:label ?grantLabel . " - + " " - + " LET(?now := afn:now()) " - + " } "; - - String justDateTimeOnGrantsQuery = "" - + " CONSTRUCT { " - + " <" + personURI + "> vivosocnet:lastCachedAt ?now . " - + " ?Grant vivosocnet:startDateTimeOnGrant ?startDateTimeValueForGrant . " -// + " ?Grant vivosocnet:endDateTimeOnGrant ?endDateTimeValueForGrant . " - + " " - + " } " - + " WHERE { " - + " <" + personURI + "> core:" + roleTypeProperty + " ?Role . " - + " ?Role core:roleContributesTo ?Grant . " - + " " - + " ?Grant core:dateTimeInterval ?dateTimeIntervalValueForGrant . " -// + " OPTIONAL { " - + " ?dateTimeIntervalValueForGrant core:start ?startDateForGrant . " - + " ?startDateForGrant core:dateTime ?startDateTimeValueForGrant . " -// + " } " -// + " OPTIONAL { " -// + " ?dateTimeIntervalValueForGrant core:end ?endDateForGrant . " -// + " ?endDateForGrant core:dateTime ?endDateTimeValueForGrant " -// + " } " - + " " - + " LET(?now := afn:now()) " - + " } "; - - String justDateTimeOnRolesQuery = "" - + " CONSTRUCT { " - + " <" + personURI + "> vivosocnet:lastCachedAt ?now . " - + " ?Grant vivosocnet:startDateTimeOnRole ?startDateTimeValue . " -// + " ?Grant vivosocnet:endDateTimeOnRole ?endDateTimeValue . " - + " } " - + " WHERE { " - + " <" + personURI + "> core:" + roleTypeProperty + " ?Role . " - + " ?Role core:roleContributesTo ?Grant . " - + " " - + " ?Role core:dateTimeInterval ?dateTimeIntervalValue . " -// + " OPTIONAL { " - + " ?dateTimeIntervalValue core:start ?startDate . " - + " ?startDate core:dateTime ?startDateTimeValue . " -// + " } " -// + " " -// + " OPTIONAL { " -// + " ?dateTimeIntervalValue core:end ?endDate . " -// + " ?endDate core:dateTime ?endDateTimeValue . " -// + " } " - + " " - + " LET(?now := afn:now()) " - + " } "; - - differentPerspectiveQueries.add(justGrantsQuery); - differentPerspectiveQueries.add(justDateTimeOnGrantsQuery); - differentPerspectiveQueries.add(justDateTimeOnRolesQuery); - - return differentPerspectiveQueries; - } - - private Set constructPersonToGrantsQuery() { - - Set differentInvestigatorTypeQueries = new HashSet(); - - Set investigatorRoleQuery = constructPersonGrantsQueryTemplate("hasGrantAsAnInvestigator", "hasInvestigatorRole"); - Set piRoleQuery = constructPersonGrantsQueryTemplate("hasGrantAsPI", "hasPrincipalInvestigatorRole"); - Set coPIRoleQuery = constructPersonGrantsQueryTemplate("hasGrantAsCoPI", "hasCo-PrincipalInvestigatorRole"); - - differentInvestigatorTypeQueries.addAll(investigatorRoleQuery); - differentInvestigatorTypeQueries.addAll(piRoleQuery); - differentInvestigatorTypeQueries.addAll(coPIRoleQuery); - - return differentInvestigatorTypeQueries; - } - - private Model executeQuery(Set constructQueries) { - - Model constructedModel = ModelFactory.createDefaultModel(); - - before = System.currentTimeMillis(); - log.debug("CONSTRUCT query string : " + constructQueries); - - for (String currentQuery : constructQueries) { - - - Query query = null; - - try { - query = QueryFactory.create(QueryConstants.getSparqlPrefixQuery() + currentQuery, SYNTAX); - } catch (Throwable th) { - log.error("Could not create CONSTRUCT SPARQL query for query " - + "string. " + th.getMessage()); - log.error(currentQuery); - } - - - QueryExecution qe = QueryExecutionFactory.create(query, dataset); - - try { - qe.execConstruct(constructedModel); - } finally { - qe.close(); - } - } - - after = System.currentTimeMillis(); - log.debug("Time taken to execute the CONSTRUCT queries is in milliseconds: " - + (after - before)); - - return constructedModel; - } - - public Model getConstructedModel() throws MalformedQueryParametersException { - return executeQuery(constructPersonToGrantsQuery()); - } -} +/* $This file is distributed under the terms of the license in /doc/license.txt$ */ +package edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor; + +import java.util.HashSet; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.hp.hpl.jena.query.Dataset; +import com.hp.hpl.jena.query.Query; +import com.hp.hpl.jena.query.QueryExecution; +import com.hp.hpl.jena.query.QueryExecutionFactory; +import com.hp.hpl.jena.query.QueryFactory; +import com.hp.hpl.jena.query.Syntax; +import com.hp.hpl.jena.rdf.model.Model; +import com.hp.hpl.jena.rdf.model.ModelFactory; + +import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryConstants; +import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; +import edu.cornell.mannlib.vitro.webapp.visualization.visutils.ModelConstructor; + +public class PersonToGrantsModelConstructor implements ModelConstructor { + + protected static final Syntax SYNTAX = Syntax.syntaxARQ; + + private Dataset dataset; + + public static final String MODEL_TYPE = "PERSON_TO_GRANTS"; + public static final String MODEL_TYPE_HUMAN_READABLE = "Grants for specific person via all roles"; + + private String personURI; + + private Log log = LogFactory.getLog(PersonToGrantsModelConstructor.class.getName()); + + private long before, after; + + public PersonToGrantsModelConstructor(String personURI, Dataset dataset) { + this.personURI = personURI; + this.dataset = dataset; + } + +private Set constructPersonGrantsQueryTemplate(String constructProperty, String roleType) { + + Set differentPerspectiveQueries = new HashSet(); + + String justGrantsQuery = "" + + " CONSTRUCT { " + + " <" + personURI + "> vivosocnet:lastCachedAt ?now . " + + " <" + personURI + "> vivosocnet:" + constructProperty + " ?Grant . " + + " " + + " ?Grant rdf:type core:Grant . " + + " ?Grant rdfs:label ?grantLabel . " + + " " + + " } " + + " WHERE { " + + " <" + personURI + "> ?Role . " + + " ?Role rdf:type core:" + roleType + " . " + + " ?Role core:relatedBy ?Grant . " + + " ?Grant rdf:type core:Grant . " + + " ?Grant rdfs:label ?grantLabel . " + + " " + + " LET(?now := afn:now()) " + + " } "; + + String justDateTimeOnGrantsQuery = "" + + " CONSTRUCT { " + + " <" + personURI + "> vivosocnet:lastCachedAt ?now . " + + " ?Grant vivosocnet:startDateTimeOnGrant ?startDateTimeValueForGrant . " +// + " ?Grant vivosocnet:endDateTimeOnGrant ?endDateTimeValueForGrant . " + + " " + + " } " + + " WHERE { " + + " <" + personURI + "> ?Role . " + + " ?Role rdf:type core:" + roleType + " . " + + " ?Role core:relatedBy ?Grant . " + + " ?Grant rdf:type core:Grant . " + + " " + + " ?Grant core:dateTimeInterval ?dateTimeIntervalValueForGrant . " +// + " OPTIONAL { " + + " ?dateTimeIntervalValueForGrant core:start ?startDateForGrant . " + + " ?startDateForGrant core:dateTime ?startDateTimeValueForGrant . " +// + " } " +// + " OPTIONAL { " +// + " ?dateTimeIntervalValueForGrant core:end ?endDateForGrant . " +// + " ?endDateForGrant core:dateTime ?endDateTimeValueForGrant " +// + " } " + + " " + + " LET(?now := afn:now()) " + + " } "; + + String justDateTimeOnRolesQuery = "" + + " CONSTRUCT { " + + " <" + personURI + "> vivosocnet:lastCachedAt ?now . " + + " ?Grant vivosocnet:startDateTimeOnRole ?startDateTimeValue . " +// + " ?Grant vivosocnet:endDateTimeOnRole ?endDateTimeValue . " + + " } " + + " WHERE { " + + " <" + personURI + "> ?Role . " + + " ?Role rdf:type core:" + roleType + " . " + + " ?Role core:relatedBy ?Grant . " + + " ?Grant rdf:type core:Grant . " + + " " + + " ?Role core:dateTimeInterval ?dateTimeIntervalValue . " +// + " OPTIONAL { " + + " ?dateTimeIntervalValue core:start ?startDate . " + + " ?startDate core:dateTime ?startDateTimeValue . " +// + " } " +// + " " +// + " OPTIONAL { " +// + " ?dateTimeIntervalValue core:end ?endDate . " +// + " ?endDate core:dateTime ?endDateTimeValue . " +// + " } " + + " " + + " LET(?now := afn:now()) " + + " } "; + + differentPerspectiveQueries.add(justGrantsQuery); + differentPerspectiveQueries.add(justDateTimeOnGrantsQuery); + differentPerspectiveQueries.add(justDateTimeOnRolesQuery); + + return differentPerspectiveQueries; + } + + private Set constructPersonToGrantsQuery() { + + Set differentInvestigatorTypeQueries = new HashSet(); + + Set investigatorRoleQuery = constructPersonGrantsQueryTemplate("hasGrantAsAnInvestigator", "InvestigatorRole"); + Set piRoleQuery = constructPersonGrantsQueryTemplate("hasGrantAsPI", "PrincipalInvestigatorRole"); + Set coPIRoleQuery = constructPersonGrantsQueryTemplate("hasGrantAsCoPI", "CoPrincipalInvestigatorRole"); + + differentInvestigatorTypeQueries.addAll(investigatorRoleQuery); + differentInvestigatorTypeQueries.addAll(piRoleQuery); + differentInvestigatorTypeQueries.addAll(coPIRoleQuery); + + return differentInvestigatorTypeQueries; + } + + private Model executeQuery(Set constructQueries) { + + Model constructedModel = ModelFactory.createDefaultModel(); + + before = System.currentTimeMillis(); + log.debug("CONSTRUCT query string : " + constructQueries); + + for (String currentQuery : constructQueries) { + + + Query query = null; + + try { + query = QueryFactory.create(QueryConstants.getSparqlPrefixQuery() + currentQuery, SYNTAX); + } catch (Throwable th) { + log.error("Could not create CONSTRUCT SPARQL query for query " + + "string. " + th.getMessage()); + log.error(currentQuery); + } + + + QueryExecution qe = QueryExecutionFactory.create(query, dataset); + + try { + qe.execConstruct(constructedModel); + } finally { + qe.close(); + } + } + + after = System.currentTimeMillis(); + log.debug("Time taken to execute the CONSTRUCT queries is in milliseconds: " + + (after - before)); + + return constructedModel; + } + + public Model getConstructedModel() throws MalformedQueryParametersException { + return executeQuery(constructPersonToGrantsQuery()); + } +} diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/PersonToPublicationsModelConstructor.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/PersonToPublicationsModelConstructor.java index d4206cbc..37f11d35 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/PersonToPublicationsModelConstructor.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/PersonToPublicationsModelConstructor.java @@ -51,8 +51,10 @@ public class PersonToPublicationsModelConstructor implements ModelConstructor { + " ?journal rdfs:label ?journalLabel . " + " } " + " WHERE { " - + " <" + personURI + "> core:authorInAuthorship ?Resource . " - + " ?Resource core:linkedInformationResource ?Document . " + + " <" + personURI + "> core:relatedBy ?Resource . " + + " ?Resource rdf:type core:Authorship . " + + " ?Resource core:relates ?Document . " + + " ?Document rdf:type bibo:Document . " + " ?Document rdfs:label ?DocumentLabel . " + " " + " OPTIONAL { " diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/SubOrganizationWithinModelConstructor.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/SubOrganizationWithinModelConstructor.java index 6bb4ead5..d1b39913 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/SubOrganizationWithinModelConstructor.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/modelconstructor/SubOrganizationWithinModelConstructor.java @@ -50,7 +50,8 @@ public class SubOrganizationWithinModelConstructor implements ModelConstructor { + " CONSTRUCT { " + " ?organization rdf:type foaf:Organization . " + " ?organization rdfs:label ?organizationLabel . " - + " ?organization core:subOrganizationWithin ?parentOrganization . " + + " ?organization ?parentOrganization . " + + " ?parentOrganization rdf:type foaf:Organization . " + " ?parentOrganization rdfs:label ?parentOrganizationLabel . " + " } " + " WHERE { " @@ -58,7 +59,8 @@ public class SubOrganizationWithinModelConstructor implements ModelConstructor { + " ?organization rdfs:label ?organizationLabel . " + " " + " OPTIONAL { " - + " ?organization core:subOrganizationWithin ?parentOrganization . " + + " ?organization ?parentOrganization . " + + " ?parentOrganization rdf:type foaf:Organization . " + " ?parentOrganization rdfs:label ?parentOrganizationLabel . " + " } " + " } "; diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/personpubcount/PersonPublicationCountQueryRunner.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/personpubcount/PersonPublicationCountQueryRunner.java index 1631cc2c..b1bd1ff7 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/personpubcount/PersonPublicationCountQueryRunner.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/personpubcount/PersonPublicationCountQueryRunner.java @@ -1,162 +1,163 @@ -/* $This file is distributed under the terms of the license in /doc/license.txt$ */ - -package edu.cornell.mannlib.vitro.webapp.visualization.personpubcount; - -import java.util.HashSet; -import java.util.Set; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; - -import com.hp.hpl.jena.iri.IRI; -import com.hp.hpl.jena.iri.IRIFactory; -import com.hp.hpl.jena.iri.Violation; -import com.hp.hpl.jena.query.Dataset; -import com.hp.hpl.jena.query.Query; -import com.hp.hpl.jena.query.QueryExecution; -import com.hp.hpl.jena.query.QueryExecutionFactory; -import com.hp.hpl.jena.query.QueryFactory; -import com.hp.hpl.jena.query.QuerySolution; -import com.hp.hpl.jena.query.ResultSet; -import com.hp.hpl.jena.query.Syntax; -import com.hp.hpl.jena.rdf.model.RDFNode; - -import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryConstants; -import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryFieldLabels; -import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; -import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Activity; -import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Individual; -import edu.cornell.mannlib.vitro.webapp.visualization.visutils.QueryRunner; - - - -/** - * This query runner is used to execute a sparql query that will fetch all the publications - * defined by bibo:Document property for a particular individual. - * - * @author cdtank - */ -public class PersonPublicationCountQueryRunner implements QueryRunner> { - - protected static final Syntax SYNTAX = Syntax.syntaxARQ; - - private String personURI; - private Dataset dataset; - - private Individual author; - - public Individual getAuthor() { - return author; - } - - private Log log; - - private static final String SPARQL_QUERY_COMMON_SELECT_CLAUSE = "" - + "SELECT (str(?authorLabel) as ?" + QueryFieldLabels.AUTHOR_LABEL + ") \n" - + " (str(?document) as ?" + QueryFieldLabels.DOCUMENT_URL + ") \n" - + " (str(?publicationDate) as ?" + QueryFieldLabels.DOCUMENT_PUBLICATION_DATE + ")\n"; - - private static final String SPARQL_QUERY_COMMON_WHERE_CLAUSE = "" - + "?document rdfs:label ?documentLabel .\n" - + "OPTIONAL { ?document core:dateTimeValue ?dateTimeValue . \n" - + " ?dateTimeValue core:dateTime ?publicationDate } .\n"; - - public PersonPublicationCountQueryRunner(String personURI, - Dataset dataset, Log log) { - - this.personURI = personURI; - this.dataset = dataset; - this.log = log; - - } - - private Set createJavaValueObjects(ResultSet resultSet) { - Set authorDocuments = new HashSet(); - - while (resultSet.hasNext()) { - QuerySolution solution = resultSet.nextSolution(); - - Activity biboDocument = new Activity( - solution.get(QueryFieldLabels.DOCUMENT_URL) - .toString()); - - RDFNode publicationDateNode = solution.get(QueryFieldLabels.DOCUMENT_PUBLICATION_DATE); - if (publicationDateNode != null) { - biboDocument.setActivityDate(publicationDateNode.toString()); - } - - /* - * Since we are getting publication count for just one author at a time we need - * to create only one "Individual" instance. We test against the null for "author" to - * make sure that it has not already been instantiated. - * */ - RDFNode authorURLNode = solution.get(QueryFieldLabels.AUTHOR_URL); - if (authorURLNode != null && author == null) { - author = new Individual(authorURLNode.toString()); - RDFNode authorLabelNode = solution.get(QueryFieldLabels.AUTHOR_LABEL); - if (authorLabelNode != null) { - author.setIndividualLabel(authorLabelNode.toString()); - } - } - - authorDocuments.add(biboDocument); - } - return authorDocuments; - } - - private ResultSet executeQuery(String queryURI, - Dataset dataset) { - - QueryExecution queryExecution = null; - Query query = QueryFactory.create(getSparqlQuery(queryURI), SYNTAX); - queryExecution = QueryExecutionFactory.create(query, dataset); - return queryExecution.execSelect(); - } - - private String getSparqlQuery(String queryURI) { - - String sparqlQuery = QueryConstants.getSparqlPrefixQuery() - + SPARQL_QUERY_COMMON_SELECT_CLAUSE - + "(str(<" + queryURI + ">) as ?authPersonLit)\n " - + "WHERE { \n" - + "<" + queryURI + "> rdf:type foaf:Person ;\n" - + " rdfs:label ?authorLabel \n;" - + " core:authorInAuthorship ?authorshipNode . \n" - + " ?authorshipNode rdf:type core:Authorship ;" - + " core:linkedInformationResource ?document . \n" - + SPARQL_QUERY_COMMON_WHERE_CLAUSE - + "}\n"; - - log.debug(sparqlQuery); - - return sparqlQuery; - } - - public Set getQueryResult() - throws MalformedQueryParametersException { - - if (StringUtils.isNotBlank(this.personURI)) { - - /* - * To test for the validity of the URI submitted. - * */ - IRIFactory iRIFactory = IRIFactory.jenaImplementation(); - IRI iri = iRIFactory.create(this.personURI); - if (iri.hasViolation(false)) { - String errorMsg = ((Violation) iri.violations(false).next()).getShortMessage(); - log.error("Pub Count vis Query " + errorMsg); - throw new MalformedQueryParametersException( - "URI provided for an individual is malformed."); - } - - } else { - throw new MalformedQueryParametersException("URL parameter is either null or empty."); - } - - ResultSet resultSet = executeQuery(this.personURI, - this.dataset); - - return createJavaValueObjects(resultSet); - } - -} +/* $This file is distributed under the terms of the license in /doc/license.txt$ */ + +package edu.cornell.mannlib.vitro.webapp.visualization.personpubcount; + +import java.util.HashSet; +import java.util.Set; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; + +import com.hp.hpl.jena.iri.IRI; +import com.hp.hpl.jena.iri.IRIFactory; +import com.hp.hpl.jena.iri.Violation; +import com.hp.hpl.jena.query.Dataset; +import com.hp.hpl.jena.query.Query; +import com.hp.hpl.jena.query.QueryExecution; +import com.hp.hpl.jena.query.QueryExecutionFactory; +import com.hp.hpl.jena.query.QueryFactory; +import com.hp.hpl.jena.query.QuerySolution; +import com.hp.hpl.jena.query.ResultSet; +import com.hp.hpl.jena.query.Syntax; +import com.hp.hpl.jena.rdf.model.RDFNode; + +import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryConstants; +import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryFieldLabels; +import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; +import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Activity; +import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Individual; +import edu.cornell.mannlib.vitro.webapp.visualization.visutils.QueryRunner; + + + +/** + * This query runner is used to execute a sparql query that will fetch all the publications + * defined by bibo:Document property for a particular individual. + * + * @author cdtank + */ +public class PersonPublicationCountQueryRunner implements QueryRunner> { + + protected static final Syntax SYNTAX = Syntax.syntaxARQ; + + private String personURI; + private Dataset dataset; + + private Individual author; + + public Individual getAuthor() { + return author; + } + + private Log log; + + private static final String SPARQL_QUERY_COMMON_SELECT_CLAUSE = "" + + "SELECT (str(?authorLabel) as ?" + QueryFieldLabels.AUTHOR_LABEL + ") \n" + + " (str(?document) as ?" + QueryFieldLabels.DOCUMENT_URL + ") \n" + + " (str(?publicationDate) as ?" + QueryFieldLabels.DOCUMENT_PUBLICATION_DATE + ")\n"; + + private static final String SPARQL_QUERY_COMMON_WHERE_CLAUSE = "" + + "?document rdfs:label ?documentLabel .\n" + + "OPTIONAL { ?document core:dateTimeValue ?dateTimeValue . \n" + + " ?dateTimeValue core:dateTime ?publicationDate } .\n"; + + public PersonPublicationCountQueryRunner(String personURI, + Dataset dataset, Log log) { + + this.personURI = personURI; + this.dataset = dataset; + this.log = log; + + } + + private Set createJavaValueObjects(ResultSet resultSet) { + Set authorDocuments = new HashSet(); + + while (resultSet.hasNext()) { + QuerySolution solution = resultSet.nextSolution(); + + Activity biboDocument = new Activity( + solution.get(QueryFieldLabels.DOCUMENT_URL) + .toString()); + + RDFNode publicationDateNode = solution.get(QueryFieldLabels.DOCUMENT_PUBLICATION_DATE); + if (publicationDateNode != null) { + biboDocument.setActivityDate(publicationDateNode.toString()); + } + + /* + * Since we are getting publication count for just one author at a time we need + * to create only one "Individual" instance. We test against the null for "author" to + * make sure that it has not already been instantiated. + * */ + RDFNode authorURLNode = solution.get(QueryFieldLabels.AUTHOR_URL); + if (authorURLNode != null && author == null) { + author = new Individual(authorURLNode.toString()); + RDFNode authorLabelNode = solution.get(QueryFieldLabels.AUTHOR_LABEL); + if (authorLabelNode != null) { + author.setIndividualLabel(authorLabelNode.toString()); + } + } + + authorDocuments.add(biboDocument); + } + return authorDocuments; + } + + private ResultSet executeQuery(String queryURI, + Dataset dataset) { + + QueryExecution queryExecution = null; + Query query = QueryFactory.create(getSparqlQuery(queryURI), SYNTAX); + queryExecution = QueryExecutionFactory.create(query, dataset); + return queryExecution.execSelect(); + } + + private String getSparqlQuery(String queryURI) { + + String sparqlQuery = QueryConstants.getSparqlPrefixQuery() + + SPARQL_QUERY_COMMON_SELECT_CLAUSE + + "(str(<" + queryURI + ">) as ?authPersonLit)\n " + + "WHERE { \n" + + "<" + queryURI + "> rdf:type foaf:Person ;\n" + + " rdfs:label ?authorLabel \n;" + + " core:relatedBy ?authorshipNode . \n" + + " ?authorshipNode rdf:type core:Authorship ;" + + " core:relates ?document . \n" + + " ?document rdf:type bibo:Document . \n" + + SPARQL_QUERY_COMMON_WHERE_CLAUSE + + "}\n"; + + log.debug(sparqlQuery); + + return sparqlQuery; + } + + public Set getQueryResult() + throws MalformedQueryParametersException { + + if (StringUtils.isNotBlank(this.personURI)) { + + /* + * To test for the validity of the URI submitted. + * */ + IRIFactory iRIFactory = IRIFactory.jenaImplementation(); + IRI iri = iRIFactory.create(this.personURI); + if (iri.hasViolation(false)) { + String errorMsg = ((Violation) iri.violations(false).next()).getShortMessage(); + log.error("Pub Count vis Query " + errorMsg); + throw new MalformedQueryParametersException( + "URI provided for an individual is malformed."); + } + + } else { + throw new MalformedQueryParametersException("URL parameter is either null or empty."); + } + + ResultSet resultSet = executeQuery(this.personURI, + this.dataset); + + return createJavaValueObjects(resultSet); + } + +} diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/temporalgraph/OrganizationUtilityFunctions.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/temporalgraph/OrganizationUtilityFunctions.java index 830c0e33..5e133e9b 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/temporalgraph/OrganizationUtilityFunctions.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/temporalgraph/OrganizationUtilityFunctions.java @@ -80,8 +80,10 @@ public class OrganizationUtilityFunctions { String whereClause = "?organization rdf:type foaf:Organization ;" + " rdfs:label ?organizationLabel . \n" - + "OPTIONAL { ?organization core:hasSubOrganization ?subOrg } . \n" - + "OPTIONAL { ?organization core:subOrganizationWithin ?parent } . \n" + + "OPTIONAL { ?organization ?subOrg . \n" + + " ?subOrg rdf:type foaf:Organization } . \n" + + "OPTIONAL { ?organization ?parent . \n" + + " ?parent rdf:type foaf:Organization } . \n" + "FILTER ( !bound(?parent) ). \n"; String groupOrderClause = "GROUP BY ?organization ?organizationLabel \n" diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/utilities/UtilitiesRequestHandler.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/utilities/UtilitiesRequestHandler.java index 76c0abd1..b2f5d42c 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/utilities/UtilitiesRequestHandler.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/utilities/UtilitiesRequestHandler.java @@ -123,9 +123,10 @@ public class UtilitiesRequestHandler implements VisualizationRequestHandler { String whereClause = "<" + individualURI + "> rdf:type foaf:Person ;" - + " core:authorInAuthorship ?authorshipNode . \n" + + " core:relatedBy ?authorshipNode . \n" + "?authorshipNode rdf:type core:Authorship ;" - + " core:linkedInformationResource ?document ."; + + " core:relates ?document . \n" + + "?document rdf:type bibo:Document ."; String groupOrderClause = "GROUP BY ?" + QueryFieldLabels.AUTHOR_URL + " \n"; @@ -152,16 +153,22 @@ public class UtilitiesRequestHandler implements VisualizationRequestHandler { ObjectProperty predicate = ModelUtils.getPropertyForRoleInClass(grantType, vitroRequest.getWebappDaoFactory()); String roleToGrantPredicate = "<" + predicate.getURI() + ">"; String whereClause = "{ <" + individualURI + "> rdf:type foaf:Person ;" - + " core:hasCo-PrincipalInvestigatorRole ?Role . \n" + + " ?Role . \n" + + "?Role rdf:type core:PrincipalInvestigatorRole . \n" + "?Role " + roleToGrantPredicate + " ?Grant . }" + "UNION \n" + "{ <" + individualURI + "> rdf:type foaf:Person ;" - + " core:hasPrincipalInvestigatorRole ?Role . \n" + + " ?Role . \n" + + "?Role rdf:type core:CoPrincipalInvestigatorRole . \n" + "?Role " + roleToGrantPredicate + " ?Grant . }" + "UNION \n" + "{ <" + individualURI + "> rdf:type foaf:Person ;" - + " core:hasInvestigatorRole ?Role . \n" - + "?Role " + roleToGrantPredicate + " ?Grant . }"; + + " ?Role . \n" + + "?Role rdf:type core:InvestigatorRole. \n" + + "?Role vitro:mostSpecificType ?subclass . \n" + + "?Role " + roleToGrantPredicate + " ?Grant . \n" + + "FILTER (?subclass != core:PrincipalInvestigatorRole && " + + "?subclass != core:CoPrincipalInvestigatorRole)}"; QueryRunner numberOfGrantsQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, @@ -302,9 +309,11 @@ public class UtilitiesRequestHandler implements VisualizationRequestHandler { String whereClause = "?organization rdf:type foaf:Organization ;" + " rdfs:label ?organizationLabel . \n" - + "OPTIONAL { ?organization core:hasSubOrganization ?subOrg } . \n" - + "OPTIONAL { ?organization core:subOrganizationWithin ?parent } . \n" - + "FILTER ( !bound(?parent) ). \n"; + + "OPTIONAL { ?organization core:http://purl.obolibrary.org/obo/BFO_0000051 ?subOrg . \n" + + " ?subOrg rdf:type foaf:Organization } . \n" + + "OPTIONAL { ?organization core:http://purl.obolibrary.org/obo/BFO_0000050 ?parent } . \n" + + " ?parent rdf:type foaf:Organization } . \n" + + "FILTER ( !bound(?parent) ). \n"; String groupOrderClause = "GROUP BY ?organization ?organizationLabel \n" + "ORDER BY DESC(?numOfChildren)\n" diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/visutils/AllPropertiesQueryRunner.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/visutils/AllPropertiesQueryRunner.java index 1f3d0aef..c12d67b5 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/visutils/AllPropertiesQueryRunner.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/visutils/AllPropertiesQueryRunner.java @@ -1,134 +1,138 @@ -/* $This file is distributed under the terms of the license in /doc/license.txt$ */ - -package edu.cornell.mannlib.vitro.webapp.visualization.visutils; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; - -import com.hp.hpl.jena.iri.IRI; -import com.hp.hpl.jena.iri.IRIFactory; -import com.hp.hpl.jena.iri.Violation; -import com.hp.hpl.jena.query.Dataset; -import com.hp.hpl.jena.query.Query; -import com.hp.hpl.jena.query.QueryExecution; -import com.hp.hpl.jena.query.QueryExecutionFactory; -import com.hp.hpl.jena.query.QueryFactory; -import com.hp.hpl.jena.query.QuerySolution; -import com.hp.hpl.jena.query.ResultSet; -import com.hp.hpl.jena.query.Syntax; -import com.hp.hpl.jena.rdf.model.RDFNode; - -import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryConstants; -import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryFieldLabels; -import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; -import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.GenericQueryMap; - - - -/** - * This query runner is used to execute a sparql query that will fetch all the - * properties available for the provided individual URI. - * - * @author cdtank - */ -public class AllPropertiesQueryRunner implements QueryRunner { - - protected static final Syntax SYNTAX = Syntax.syntaxARQ; - - private String filterRule, individualURI; - private Dataset dataset; - - private Log log; - - public AllPropertiesQueryRunner(String individualURI, - String filterRule, - Dataset dataset, - Log log) { - - this.individualURI = individualURI; - this.filterRule = filterRule; - this.dataset = dataset; - this.log = log; - - } - - private GenericQueryMap createJavaValueObjects(ResultSet resultSet) { - - GenericQueryMap queryResult = new GenericQueryMap(); - - while (resultSet.hasNext()) { - QuerySolution solution = resultSet.nextSolution(); - - - RDFNode predicateNode = solution.get(QueryFieldLabels.PREDICATE); - RDFNode objectNode = solution.get(QueryFieldLabels.OBJECT); - - if (predicateNode != null && objectNode != null) { - queryResult.addEntry(predicateNode.toString(), - objectNode.toString()); - } - - } - - return queryResult; - } - - private ResultSet executeQuery(String queryText, - Dataset dataset) { - - QueryExecution queryExecution = null; - Query query = QueryFactory.create(queryText, SYNTAX); - - queryExecution = QueryExecutionFactory.create(query, dataset); - return queryExecution.execSelect(); - } - - private String generateGenericSparqlQuery(String queryURI, String filterRule) { -// Resource uri1 = ResourceFactory.createResource(queryURI); - String filterClause; - - if (StringUtils.isNotBlank(filterRule)) { - filterClause = "FILTER ( " + filterRule + " ) . "; - } else { - filterClause = ""; - } - - String sparqlQuery = QueryConstants.getSparqlPrefixQuery() - + "SELECT " - + " (str(?predicate) as ?" + QueryFieldLabels.PREDICATE + ") " - + " (str(?object) as ?" + QueryFieldLabels.OBJECT + ") " - + "WHERE { " - + "<" + queryURI + "> ?predicate ?object. " - + filterClause - + "}"; - - return sparqlQuery; - } - - public GenericQueryMap getQueryResult() - throws MalformedQueryParametersException { - if (StringUtils.isNotBlank(this.individualURI)) { - /* - * To test for the validity of the URI submitted. - * */ - IRIFactory iRIFactory = IRIFactory.jenaImplementation(); - IRI iri = iRIFactory.create(this.individualURI); - if (iri.hasViolation(false)) { - String errorMsg = ((Violation) iri.violations(false).next()).getShortMessage(); - log.error("Generic Query " + errorMsg); - throw new MalformedQueryParametersException( - "URI provided for an individual is malformed."); - } - - } else { - throw new MalformedQueryParametersException("URI parameter is either null or empty."); - } - - ResultSet resultSet = executeQuery(generateGenericSparqlQuery( - this.individualURI, - this.filterRule), - this.dataset); - - return createJavaValueObjects(resultSet); - } -} +/* $This file is distributed under the terms of the license in /doc/license.txt$ */ + +package edu.cornell.mannlib.vitro.webapp.visualization.visutils; + +import org.apache.commons.lang.StringUtils; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.hp.hpl.jena.iri.IRI; +import com.hp.hpl.jena.iri.IRIFactory; +import com.hp.hpl.jena.iri.Violation; +import com.hp.hpl.jena.query.Dataset; +import com.hp.hpl.jena.query.Query; +import com.hp.hpl.jena.query.QueryExecution; +import com.hp.hpl.jena.query.QueryExecutionFactory; +import com.hp.hpl.jena.query.QueryFactory; +import com.hp.hpl.jena.query.QuerySolution; +import com.hp.hpl.jena.query.ResultSet; +import com.hp.hpl.jena.query.Syntax; +import com.hp.hpl.jena.rdf.model.RDFNode; + +import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryConstants; +import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryFieldLabels; +import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; +import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.GenericQueryMap; + + + +/** + * This query runner is used to execute a sparql query that will fetch all the + * properties available for the provided individual URI. + * + * @author cdtank + */ +public class AllPropertiesQueryRunner implements QueryRunner { + + protected static final Syntax SYNTAX = Syntax.syntaxARQ; + + private String filterRule, individualURI; + private Dataset dataset; + + private Log log = LogFactory.getLog(AllPropertiesQueryRunner.class.getName()); + + public AllPropertiesQueryRunner(String individualURI, + String filterRule, + Dataset dataset, + Log log) { + + this.individualURI = individualURI; + this.filterRule = filterRule; + this.dataset = dataset; + this.log = log; + + } + + private GenericQueryMap createJavaValueObjects(ResultSet resultSet) { + + GenericQueryMap queryResult = new GenericQueryMap(); + + while (resultSet.hasNext()) { + QuerySolution solution = resultSet.nextSolution(); + + + RDFNode predicateNode = solution.get(QueryFieldLabels.PREDICATE); + RDFNode objectNode = solution.get(QueryFieldLabels.OBJECT); + + if (predicateNode != null && objectNode != null) { + queryResult.addEntry(predicateNode.toString(), + objectNode.toString()); + } + + } + + return queryResult; + } + + private ResultSet executeQuery(String queryText, + Dataset dataset) { + + QueryExecution queryExecution = null; + Query query = QueryFactory.create(queryText, SYNTAX); + + queryExecution = QueryExecutionFactory.create(query, dataset); + return queryExecution.execSelect(); + } + + private String generateGenericSparqlQuery(String queryURI, String filterRule) { +// Resource uri1 = ResourceFactory.createResource(queryURI); + String filterClause; + + if (StringUtils.isNotBlank(filterRule)) { + filterClause = "FILTER ( " + filterRule + " ) . "; + } else { + filterClause = ""; + } + + String sparqlQuery = QueryConstants.getSparqlPrefixQuery() + + "SELECT " + + " (str(?predicate) as ?" + QueryFieldLabels.PREDICATE + ") " + + " (str(?object) as ?" + QueryFieldLabels.OBJECT + ") " + + "WHERE { " + + "<" + queryURI + "> ?predicate ?object. " + + filterClause + + "}"; + + log.debug("sparqlQuery = " + sparqlQuery.toString()); + + return sparqlQuery; + } + + public GenericQueryMap getQueryResult() + throws MalformedQueryParametersException { + if (StringUtils.isNotBlank(this.individualURI)) { + /* + * To test for the validity of the URI submitted. + * */ + IRIFactory iRIFactory = IRIFactory.jenaImplementation(); + IRI iri = iRIFactory.create(this.individualURI); + if (iri.hasViolation(false)) { + String errorMsg = ((Violation) iri.violations(false).next()).getShortMessage(); + log.error("Generic Query " + errorMsg); + throw new MalformedQueryParametersException( + "URI provided for an individual is malformed."); + } + + } else { + throw new MalformedQueryParametersException("URI parameter is either null or empty."); + } + + ResultSet resultSet = executeQuery(generateGenericSparqlQuery( + this.individualURI, + this.filterRule), + this.dataset); + + return createJavaValueObjects(resultSet); + } +} diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/visutils/GenericQueryRunner.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/visutils/GenericQueryRunner.java index 11fa1e13..3c53918b 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/visutils/GenericQueryRunner.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/visutils/GenericQueryRunner.java @@ -1,98 +1,104 @@ -/* $This file is distributed under the terms of the license in /doc/license.txt$ */ - -package edu.cornell.mannlib.vitro.webapp.visualization.visutils; - -import java.util.Map; - - -import com.hp.hpl.jena.query.Dataset; -import com.hp.hpl.jena.query.Query; -import com.hp.hpl.jena.query.QueryExecution; -import com.hp.hpl.jena.query.QueryExecutionFactory; -import com.hp.hpl.jena.query.QueryFactory; -import com.hp.hpl.jena.query.ResultSet; -import com.hp.hpl.jena.query.Syntax; - -import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryConstants; -import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; - - - -/** - * This query runner is used to run a generic sparql query based on the "select", - * "where" & "filter" rules provided to it. - * - * @author cdtank - */ -public class GenericQueryRunner implements QueryRunner { - - protected static final Syntax SYNTAX = Syntax.syntaxARQ; - - private String whereClause; - private Dataset dataset; - - private Map fieldLabelToOutputFieldLabel; - - private String groupOrderClause; - - private String aggregationRules; - - public GenericQueryRunner(Map fieldLabelToOutputFieldLabel, - String aggregationRules, - String whereClause, - String groupOrderClause, - Dataset dataset) { - - this.fieldLabelToOutputFieldLabel = fieldLabelToOutputFieldLabel; - this.aggregationRules = aggregationRules; - this.whereClause = whereClause; - this.groupOrderClause = groupOrderClause; - this.dataset = dataset; - } - - private ResultSet executeQuery(String queryText, - Dataset dataset) { - - QueryExecution queryExecution = null; - Query query = QueryFactory.create(queryText, SYNTAX); - queryExecution = QueryExecutionFactory.create(query, dataset); - return queryExecution.execSelect(); - } - - private String generateGenericSparqlQuery() { - - StringBuilder sparqlQuery = new StringBuilder(); - sparqlQuery.append(QueryConstants.getSparqlPrefixQuery()); - - sparqlQuery.append("SELECT\n"); - - for (Map.Entry currentfieldLabelToOutputFieldLabel - : this.fieldLabelToOutputFieldLabel.entrySet()) { - - sparqlQuery.append("\t(str(?" + currentfieldLabelToOutputFieldLabel.getKey() + ") as ?" - + currentfieldLabelToOutputFieldLabel.getValue() + ")\n"); - - } - - sparqlQuery.append("\n" + this.aggregationRules + "\n"); - - sparqlQuery.append("WHERE {\n"); - - sparqlQuery.append(this.whereClause); - - sparqlQuery.append("}\n"); - - sparqlQuery.append(this.groupOrderClause); - - return sparqlQuery.toString(); - } - - public ResultSet getQueryResult() - throws MalformedQueryParametersException { - - ResultSet resultSet = executeQuery(generateGenericSparqlQuery(), - this.dataset); - - return resultSet; - } -} +/* $This file is distributed under the terms of the license in /doc/license.txt$ */ + +package edu.cornell.mannlib.vitro.webapp.visualization.visutils; + +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.hp.hpl.jena.query.Dataset; +import com.hp.hpl.jena.query.Query; +import com.hp.hpl.jena.query.QueryExecution; +import com.hp.hpl.jena.query.QueryExecutionFactory; +import com.hp.hpl.jena.query.QueryFactory; +import com.hp.hpl.jena.query.ResultSet; +import com.hp.hpl.jena.query.Syntax; + +import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryConstants; +import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; + + + +/** + * This query runner is used to run a generic sparql query based on the "select", + * "where" & "filter" rules provided to it. + * + * @author cdtank + */ +public class GenericQueryRunner implements QueryRunner { + + protected static final Syntax SYNTAX = Syntax.syntaxARQ; + + private String whereClause; + private Dataset dataset; + + private Map fieldLabelToOutputFieldLabel; + + private Log log = LogFactory.getLog(GenericQueryRunner.class.getName()); + + private String groupOrderClause; + + private String aggregationRules; + + public GenericQueryRunner(Map fieldLabelToOutputFieldLabel, + String aggregationRules, + String whereClause, + String groupOrderClause, + Dataset dataset) { + + this.fieldLabelToOutputFieldLabel = fieldLabelToOutputFieldLabel; + this.aggregationRules = aggregationRules; + this.whereClause = whereClause; + this.groupOrderClause = groupOrderClause; + this.dataset = dataset; + } + + private ResultSet executeQuery(String queryText, + Dataset dataset) { + + QueryExecution queryExecution = null; + Query query = QueryFactory.create(queryText, SYNTAX); + queryExecution = QueryExecutionFactory.create(query, dataset); + return queryExecution.execSelect(); + } + + private String generateGenericSparqlQuery() { + + StringBuilder sparqlQuery = new StringBuilder(); + sparqlQuery.append(QueryConstants.getSparqlPrefixQuery()); + + sparqlQuery.append("SELECT\n"); + + for (Map.Entry currentfieldLabelToOutputFieldLabel + : this.fieldLabelToOutputFieldLabel.entrySet()) { + + sparqlQuery.append("\t(str(?" + currentfieldLabelToOutputFieldLabel.getKey() + ") as ?" + + currentfieldLabelToOutputFieldLabel.getValue() + ")\n"); + + } + + sparqlQuery.append("\n" + this.aggregationRules + "\n"); + + sparqlQuery.append("WHERE {\n"); + + sparqlQuery.append(this.whereClause); + + sparqlQuery.append("}\n"); + + sparqlQuery.append(this.groupOrderClause); + + log.debug("sparqlQuery = " + sparqlQuery.toString()); + + return sparqlQuery.toString(); + } + + public ResultSet getQueryResult() + throws MalformedQueryParametersException { + + ResultSet resultSet = executeQuery(generateGenericSparqlQuery(), + this.dataset); + + return resultSet; + } +} diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/visutils/GenericQueryRunnerOnModel.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/visutils/GenericQueryRunnerOnModel.java index 2a6ff9f7..8443f9b1 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/visutils/GenericQueryRunnerOnModel.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/visutils/GenericQueryRunnerOnModel.java @@ -1,97 +1,103 @@ -/* $This file is distributed under the terms of the license in /doc/license.txt$ */ - -package edu.cornell.mannlib.vitro.webapp.visualization.visutils; - -import java.util.Map; - -import com.hp.hpl.jena.query.Query; -import com.hp.hpl.jena.query.QueryExecution; -import com.hp.hpl.jena.query.QueryExecutionFactory; -import com.hp.hpl.jena.query.QueryFactory; -import com.hp.hpl.jena.query.ResultSet; -import com.hp.hpl.jena.query.Syntax; -import com.hp.hpl.jena.rdf.model.Model; - -import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryConstants; -import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; - - - -/** - * This query runner is used to run a generic sparql query based on the "select", - * "where" & "filter" rules provided to it. - * - * @author cdtank - */ -public class GenericQueryRunnerOnModel implements QueryRunner { - - protected static final Syntax SYNTAX = Syntax.syntaxARQ; - - private String whereClause; - private Model model; - - private Map fieldLabelToOutputFieldLabel; - - private String groupOrderClause; - - private String aggregationRules; - - public GenericQueryRunnerOnModel(Map fieldLabelToOutputFieldLabel, - String aggregationRules, - String whereClause, - String groupOrderClause, - Model model) { - - this.fieldLabelToOutputFieldLabel = fieldLabelToOutputFieldLabel; - this.aggregationRules = aggregationRules; - this.whereClause = whereClause; - this.groupOrderClause = groupOrderClause; - this.model = model; - } - - private ResultSet executeQuery(String queryText, - Model dataset) { - - QueryExecution queryExecution = null; - Query query = QueryFactory.create(queryText, SYNTAX); - queryExecution = QueryExecutionFactory.create(query, dataset); - return queryExecution.execSelect(); - } - - private String generateGenericSparqlQuery() { - - StringBuilder sparqlQuery = new StringBuilder(); - sparqlQuery.append(QueryConstants.getSparqlPrefixQuery()); - - sparqlQuery.append("SELECT\n"); - - for (Map.Entry currentfieldLabelToOutputFieldLabel - : this.fieldLabelToOutputFieldLabel.entrySet()) { - - sparqlQuery.append("\t(str(?" + currentfieldLabelToOutputFieldLabel.getKey() + ") as ?" - + currentfieldLabelToOutputFieldLabel.getValue() + ")\n"); - - } - - sparqlQuery.append("\n" + this.aggregationRules + "\n"); - - sparqlQuery.append("WHERE {\n"); - - sparqlQuery.append(this.whereClause); - - sparqlQuery.append("}\n"); - - sparqlQuery.append(this.groupOrderClause); - - return sparqlQuery.toString(); - } - - public ResultSet getQueryResult() - throws MalformedQueryParametersException { - - ResultSet resultSet = executeQuery(generateGenericSparqlQuery(), - this.model); - - return resultSet; - } -} +/* $This file is distributed under the terms of the license in /doc/license.txt$ */ + +package edu.cornell.mannlib.vitro.webapp.visualization.visutils; + +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.hp.hpl.jena.query.Query; +import com.hp.hpl.jena.query.QueryExecution; +import com.hp.hpl.jena.query.QueryExecutionFactory; +import com.hp.hpl.jena.query.QueryFactory; +import com.hp.hpl.jena.query.ResultSet; +import com.hp.hpl.jena.query.Syntax; +import com.hp.hpl.jena.rdf.model.Model; + +import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryConstants; +import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; + + + +/** + * This query runner is used to run a generic sparql query based on the "select", + * "where" & "filter" rules provided to it. + * + * @author cdtank + */ +public class GenericQueryRunnerOnModel implements QueryRunner { + + protected static final Syntax SYNTAX = Syntax.syntaxARQ; + + private String whereClause; + private Model model; + + private Map fieldLabelToOutputFieldLabel; + + private Log log = LogFactory.getLog(GenericQueryRunnerOnModel.class.getName()); + + private String groupOrderClause; + + private String aggregationRules; + + public GenericQueryRunnerOnModel(Map fieldLabelToOutputFieldLabel, + String aggregationRules, + String whereClause, + String groupOrderClause, + Model model) { + + this.fieldLabelToOutputFieldLabel = fieldLabelToOutputFieldLabel; + this.aggregationRules = aggregationRules; + this.whereClause = whereClause; + this.groupOrderClause = groupOrderClause; + this.model = model; + } + + private ResultSet executeQuery(String queryText, + Model dataset) { + + QueryExecution queryExecution = null; + Query query = QueryFactory.create(queryText, SYNTAX); + queryExecution = QueryExecutionFactory.create(query, dataset); + return queryExecution.execSelect(); + } + + private String generateGenericSparqlQuery() { + + StringBuilder sparqlQuery = new StringBuilder(); + sparqlQuery.append(QueryConstants.getSparqlPrefixQuery()); + + sparqlQuery.append("SELECT\n"); + + for (Map.Entry currentfieldLabelToOutputFieldLabel + : this.fieldLabelToOutputFieldLabel.entrySet()) { + + sparqlQuery.append("\t(str(?" + currentfieldLabelToOutputFieldLabel.getKey() + ") as ?" + + currentfieldLabelToOutputFieldLabel.getValue() + ")\n"); + + } + + sparqlQuery.append("\n" + this.aggregationRules + "\n"); + + sparqlQuery.append("WHERE {\n"); + + sparqlQuery.append(this.whereClause); + + sparqlQuery.append("}\n"); + + sparqlQuery.append(this.groupOrderClause); + + log.debug("sparqlQuery = " + sparqlQuery.toString()); + return sparqlQuery.toString(); + } + + public ResultSet getQueryResult() + throws MalformedQueryParametersException { + + ResultSet resultSet = executeQuery(generateGenericSparqlQuery(), + this.model); + + return resultSet; + } +} diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/visutils/SelectOnModelUtilities.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/visutils/SelectOnModelUtilities.java index a78d7370..213e1820 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/visutils/SelectOnModelUtilities.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/visutils/SelectOnModelUtilities.java @@ -1,937 +1,939 @@ -/* $This file is distributed under the terms of the license in /doc/license.txt$ */ -package edu.cornell.mannlib.vitro.webapp.visualization.visutils; - -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.lang.StringUtils; - -import com.hp.hpl.jena.query.Dataset; -import com.hp.hpl.jena.query.QuerySolution; -import com.hp.hpl.jena.query.ResultSet; -import com.hp.hpl.jena.rdf.model.Model; -import com.hp.hpl.jena.rdf.model.RDFNode; - -import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryFieldLabels; -import edu.cornell.mannlib.vitro.webapp.visualization.constants.VOConstants; -import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; -import edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.ModelConstructorUtilities; -import edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.OrganizationAssociatedPeopleModelWithTypesConstructor; -import edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.OrganizationModelWithTypesConstructor; -import edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.OrganizationToGrantsForSubOrganizationsModelConstructor; -import edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.OrganizationToPublicationsForSubOrganizationsModelConstructor; -import edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.PeopleToGrantsModelConstructor; -import edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.PeopleToPublicationsModelConstructor; -import edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.PersonToGrantsModelConstructor; -import edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.PersonToPublicationsModelConstructor; -import edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.SubOrganizationWithinModelConstructor; -import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Activity; -import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Entity; -import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Individual; -import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.MapOfScienceActivity; -import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.SubEntity; - -public class SelectOnModelUtilities { - - public static Entity getSubjectOrganizationHierarchy(Dataset dataset, - String subjectEntityURI) throws MalformedQueryParametersException { - Model organizationModel = ModelConstructorUtilities - .getOrConstructModel( - null, - OrganizationModelWithTypesConstructor.MODEL_TYPE, - dataset); - - Map fieldLabelToOutputFieldLabel = new HashMap(); - fieldLabelToOutputFieldLabel.put("organizationLabel", QueryFieldLabels.ORGANIZATION_LABEL); - fieldLabelToOutputFieldLabel.put("subOrganization", QueryFieldLabels.SUBORGANIZATION_URL); - fieldLabelToOutputFieldLabel.put("subOrganizationLabel", QueryFieldLabels.SUBORGANIZATION_LABEL); - fieldLabelToOutputFieldLabel.put("subOrganizationTypeLabel", QueryFieldLabels.SUBORGANIZATION_TYPE_LABEL); - - String whereClause = "" - + " <" + subjectEntityURI + "> rdfs:label ?organizationLabel . " - + " <" + subjectEntityURI + "> core:hasSubOrganization ?subOrganization . " - + " ?subOrganization rdfs:label ?subOrganizationLabel . " - + " ?subOrganization rdf:type ?subOrgType . " - + " ?subOrgType rdfs:label ?subOrganizationTypeLabel . "; - - QueryRunner subOrganizationsWithTypesQuery = - new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel, - "", - whereClause, - "", - organizationModel); - - Entity entityWithSubOrganizations = getEntityWithSubOrganizations(subjectEntityURI, - subOrganizationsWithTypesQuery.getQueryResult()); - - Entity entityWithParentOrganizations = getAllParentOrganizations(dataset, subjectEntityURI); - - entityWithSubOrganizations.addParents(entityWithParentOrganizations.getParents()); - - return entityWithSubOrganizations; - } - - public static Entity getSubjectPersonEntity(Dataset dataset, - String subjectEntityURI) throws MalformedQueryParametersException { - - Map fieldLabelToOutputFieldLabel = new HashMap(); - fieldLabelToOutputFieldLabel.put("authorLabel", QueryFieldLabels.AUTHOR_LABEL); - - String whereClause = "" - + " <" + subjectEntityURI + "> rdfs:label ?authorLabel . "; - - QueryRunner personQuery = - new GenericQueryRunner(fieldLabelToOutputFieldLabel, - "", - whereClause, - "", - dataset); - - Entity personEntity = new Entity(subjectEntityURI); - - ResultSet queryResult = personQuery.getQueryResult(); - - while (queryResult.hasNext()) { - - QuerySolution solution = queryResult.nextSolution(); - - RDFNode personLabelNode = solution.get(QueryFieldLabels.AUTHOR_LABEL); - if (personLabelNode != null) { - personEntity.setEntityLabel(personLabelNode.toString()); - } - - } - - /* - * We are adding A person as it's own subentity in order to make our code for geenrating csv, json - * & other data as streamlined as possible between entities of type Organization & Person. - * */ - SubEntity subEntity = new SubEntity(subjectEntityURI, personEntity.getEntityLabel()); - subEntity.setEntityClass(VOConstants.EntityClassType.PERSON); - - personEntity.addSubEntity(subEntity); - -// Entity entityWithParentOrganizations = getAllParentOrganizations(dataset, subjectEntityURI); -// -// personEntity.addParents(entityWithParentOrganizations.getParents()); - - return personEntity; - } - - public static Entity getAllParentOrganizations(Dataset dataset, - String subjectEntityURI) throws MalformedQueryParametersException { - Model organizationModel = ModelConstructorUtilities - .getOrConstructModel( - null, - SubOrganizationWithinModelConstructor.MODEL_TYPE, - dataset); - - Map fieldLabelToOutputFieldLabel = new HashMap(); - fieldLabelToOutputFieldLabel.put("organizationLabel", QueryFieldLabels.ORGANIZATION_LABEL); - fieldLabelToOutputFieldLabel.put("parentOrganization", QueryFieldLabels.PARENT_ORGANIZATION_URL); - fieldLabelToOutputFieldLabel.put("parentOrganizationLabel", QueryFieldLabels.PARENT_ORGANIZATION_LABEL); - - String whereClause = "" - + " <" + subjectEntityURI + "> rdfs:label ?organizationLabel . " - + " <" + subjectEntityURI + "> core:subOrganizationWithin ?parentOrganization . " - + " ?parentOrganization rdfs:label ?parentOrganizationLabel . "; - - QueryRunner parentOrganizationsQuery = - new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel, - "", - whereClause, - "", - organizationModel); - - return getEntityWithParentOrganizations(subjectEntityURI, - parentOrganizationsQuery.getQueryResult()); - } - - private static Entity getEntityWithParentOrganizations(String subjectEntityURI, ResultSet queryResult) { - - Entity entity = new Entity(subjectEntityURI); - Map parentOrganizationURIToVO = new HashMap(); - - while (queryResult.hasNext()) { - - QuerySolution solution = queryResult.nextSolution(); - - if (StringUtils.isEmpty(entity.getEntityLabel())) { - - RDFNode organizationLabelNode = solution.get(QueryFieldLabels.ORGANIZATION_LABEL); - if (organizationLabelNode != null) { - entity.setIndividualLabel(organizationLabelNode.toString()); - } - } - - RDFNode parentOrganizationNode = solution.get(QueryFieldLabels.PARENT_ORGANIZATION_URL); - - Individual parent; - - if (!parentOrganizationURIToVO.containsKey(parentOrganizationNode.toString())) { - - parent = new Individual(parentOrganizationNode.toString()); - - parentOrganizationURIToVO.put(parentOrganizationNode.toString(), parent); - - RDFNode parentOrganizationLabelNode = solution.get(QueryFieldLabels.PARENT_ORGANIZATION_LABEL); - if (parentOrganizationLabelNode != null) { - parent.setIndividualLabel(parentOrganizationLabelNode.toString()); - } - } - } - - entity.addParents(parentOrganizationURIToVO.values()); - - return entity; - } - - private static Entity getEntityWithSubOrganizations(String subjectEntityURI, ResultSet queryResult) { - - Entity entity = new Entity(subjectEntityURI); - Map subOrganizationURIToVO = new HashMap(); - - while (queryResult.hasNext()) { - - QuerySolution solution = queryResult.nextSolution(); - - if (StringUtils.isEmpty(entity.getEntityLabel())) { - - RDFNode organizationLabelNode = solution.get(QueryFieldLabels.ORGANIZATION_LABEL); - if (organizationLabelNode != null) { - - entity.setEntityLabel(organizationLabelNode.toString()); - } - } - - RDFNode subOrganizationNode = solution.get(QueryFieldLabels.SUBORGANIZATION_URL); - - SubEntity subEntity; - - if (subOrganizationURIToVO.containsKey(subOrganizationNode.toString())) { - - subEntity = subOrganizationURIToVO.get(subOrganizationNode.toString()); - - } else { - - subEntity = new SubEntity(subOrganizationNode.toString()); - - subEntity.setEntityClass(VOConstants.EntityClassType.ORGANIZATION); - - subOrganizationURIToVO.put(subOrganizationNode.toString(), subEntity); - - RDFNode subOrganizationLabelNode = solution.get(QueryFieldLabels.SUBORGANIZATION_LABEL); - if (subOrganizationLabelNode != null) { - subEntity.setIndividualLabel(subOrganizationLabelNode.toString()); - } - } - - RDFNode subOrganizationTypeLabelNode = solution.get(QueryFieldLabels.SUBORGANIZATION_TYPE_LABEL); - if (subOrganizationTypeLabelNode != null) { - subEntity.addEntityTypeLabel(subOrganizationTypeLabelNode.toString()); - } - } - - entity.addSubEntitities(subOrganizationURIToVO.values()); - - return entity; - } - - public static Entity getSubjectOrganizationAssociatedPeople(Dataset dataset, - String subjectEntityURI) throws MalformedQueryParametersException { - Model associatedPeopleModel = ModelConstructorUtilities - .getOrConstructModel( - subjectEntityURI, - OrganizationAssociatedPeopleModelWithTypesConstructor.MODEL_TYPE, - dataset); - - Map fieldLabelToOutputFieldLabel = new HashMap(); - fieldLabelToOutputFieldLabel.put("organizationLabel", QueryFieldLabels.ORGANIZATION_LABEL); - fieldLabelToOutputFieldLabel.put("person", QueryFieldLabels.PERSON_URL); - fieldLabelToOutputFieldLabel.put("personLabel", QueryFieldLabels.PERSON_LABEL); - fieldLabelToOutputFieldLabel.put("personTypeLabel", QueryFieldLabels.PERSON_TYPE_LABEL); - - String whereClause = "" - + " <" + subjectEntityURI + "> rdfs:label ?organizationLabel . " - + " <" + subjectEntityURI + "> vivosocnet:hasPersonWithActivity ?person . " - + " ?person rdfs:label ?personLabel . " - + " ?person rdf:type ?personType . " - + " ?personType rdfs:label ?personTypeLabel . "; - - QueryRunner associatedPeopleWithTypesQuery = - new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel, - "", - whereClause, - "", - associatedPeopleModel); - - return getEntityWithAssociatedPeopleSubEntitities(subjectEntityURI, associatedPeopleWithTypesQuery.getQueryResult()); - } - - private static Entity getEntityWithAssociatedPeopleSubEntitities( - String subjectEntityURI, ResultSet queryResult) { - - Entity entity = new Entity(subjectEntityURI); - Map associatedPeopleURIToVO = new HashMap(); - - while (queryResult.hasNext()) { - - QuerySolution solution = queryResult.nextSolution(); - - if (StringUtils.isEmpty(entity.getEntityLabel())) { - - RDFNode organizationLabelNode = solution.get(QueryFieldLabels.ORGANIZATION_LABEL); - if (organizationLabelNode != null) { - entity.setIndividualLabel(organizationLabelNode.toString()); - } - } - - RDFNode personNode = solution.get(QueryFieldLabels.PERSON_URL); - - SubEntity subEntity; - - if (associatedPeopleURIToVO.containsKey(personNode.toString())) { - - subEntity = associatedPeopleURIToVO.get(personNode.toString()); - - } else { - - subEntity = new SubEntity(personNode.toString()); - subEntity.setEntityClass(VOConstants.EntityClassType.PERSON); - associatedPeopleURIToVO.put(personNode.toString(), subEntity); - - RDFNode personLabelNode = solution.get(QueryFieldLabels.PERSON_LABEL); - if (personLabelNode != null) { - subEntity.setIndividualLabel(personLabelNode.toString()); - } - } - - RDFNode personTypeLabelNode = solution.get(QueryFieldLabels.PERSON_TYPE_LABEL); - if (personTypeLabelNode != null) { - subEntity.addEntityTypeLabel(personTypeLabelNode.toString()); - } - } - - entity.addSubEntitities(associatedPeopleURIToVO.values()); - return entity; - } - - public static Map getPublicationsForAllSubOrganizations( - Dataset dataset, Entity organizationEntity) - throws MalformedQueryParametersException { - Map allDocumentURIToVOs = new HashMap(); - - for (SubEntity subOrganization : organizationEntity.getSubEntities()) { - - Model subOrganizationPublicationsModel = ModelConstructorUtilities - .getOrConstructModel( - subOrganization.getIndividualURI(), - OrganizationToPublicationsForSubOrganizationsModelConstructor.MODEL_TYPE, - dataset); - -// System.out.println("getting publications for " + subOrganization.getIndividualLabel()); - - Map fieldLabelToOutputFieldLabel = new HashMap(); - fieldLabelToOutputFieldLabel.put("document", QueryFieldLabels.DOCUMENT_URL); - fieldLabelToOutputFieldLabel.put("documentLabel", QueryFieldLabels.DOCUMENT_LABEL); - fieldLabelToOutputFieldLabel.put("documentPublicationDate", QueryFieldLabels.DOCUMENT_PUBLICATION_DATE); - - String whereClause = "" - + " <" + subOrganization.getIndividualURI() + "> vivosocnet:hasPersonWithPublication ?document . " - + " ?document rdfs:label ?documentLabel . " - + " OPTIONAL { " - + " ?document core:dateTimeValue ?dateTimeValue . " - + " ?dateTimeValue core:dateTime ?documentPublicationDate } . "; - - QueryRunner subOrganizationPublicationsQuery = - new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel, - "", - whereClause, - "", - subOrganizationPublicationsModel); - - getPublicationForEntity(subOrganizationPublicationsQuery.getQueryResult(), - subOrganization, - allDocumentURIToVOs); - - String lastCachedAtForEntity = getLastCachedAtDateTimeForEntityInModel( - subOrganization, - subOrganizationPublicationsModel); - - subOrganization.setLastCachedAtDateTime(lastCachedAtForEntity); - - } - return allDocumentURIToVOs; - } - - public static Map getPublicationsWithJournalForAllSubOrganizations( - Dataset dataset, Entity organizationEntity) - throws MalformedQueryParametersException { - Map allDocumentURIToVOs = new HashMap(); - - for (SubEntity subOrganization : organizationEntity.getSubEntities()) { - - Model subOrganizationPublicationsModel = ModelConstructorUtilities - .getOrConstructModel( - subOrganization.getIndividualURI(), - OrganizationToPublicationsForSubOrganizationsModelConstructor.MODEL_TYPE, - dataset); - -// System.out.println("getting publications for " + subOrganization.getIndividualLabel()); - - Map fieldLabelToOutputFieldLabel = new HashMap(); - fieldLabelToOutputFieldLabel.put("document", QueryFieldLabels.DOCUMENT_URL); - fieldLabelToOutputFieldLabel.put("documentLabel", QueryFieldLabels.DOCUMENT_LABEL); - fieldLabelToOutputFieldLabel.put("documentPublicationDate", QueryFieldLabels.DOCUMENT_PUBLICATION_DATE); - fieldLabelToOutputFieldLabel.put("journalLabel", QueryFieldLabels.DOCUMENT_JOURNAL_LABEL); - - String whereClause = "" - + " <" + subOrganization.getIndividualURI() + "> vivosocnet:hasPersonWithPublication ?document . " - + " ?document rdfs:label ?documentLabel . " - + " OPTIONAL { " - + " ?document core:dateTimeValue ?dateTimeValue . " - + " ?dateTimeValue core:dateTime ?documentPublicationDate } . " - + " OPTIONAL { " - + " ?document core:hasPublicationVenue ?journal . " - + " ?journal rdfs:label ?journalLabel . } "; - - QueryRunner subOrganizationPublicationsQuery = - new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel, - "", - whereClause, - "", - subOrganizationPublicationsModel); - - getPublicationWithJournalForEntity(subOrganizationPublicationsQuery.getQueryResult(), - subOrganization, - allDocumentURIToVOs); - - String lastCachedAtForEntity = getLastCachedAtDateTimeForEntityInModel( - subOrganization, - subOrganizationPublicationsModel); - - subOrganization.setLastCachedAtDateTime(lastCachedAtForEntity); - - } - return allDocumentURIToVOs; - } - - private static void getPublicationForEntity( - ResultSet queryResult, - SubEntity subEntity, - Map allDocumentURIToVOs) { - - Set currentEntityPublications = new HashSet(); - - while (queryResult.hasNext()) { - - QuerySolution solution = queryResult.nextSolution(); - - if (StringUtils.isEmpty(subEntity.getLastCachedAtDateTime())) { - - RDFNode lastCachedAtNode = solution.get(QueryFieldLabels.LAST_CACHED_AT_DATETIME); - if (lastCachedAtNode != null) { - subEntity.setLastCachedAtDateTime(lastCachedAtNode.toString()); - } - } - - RDFNode documentNode = solution.get(QueryFieldLabels.DOCUMENT_URL); - Activity biboDocument; - - if (allDocumentURIToVOs.containsKey(documentNode.toString())) { - biboDocument = allDocumentURIToVOs.get(documentNode.toString()); - - } else { - - biboDocument = new Activity(documentNode.toString()); - allDocumentURIToVOs.put(documentNode.toString(), biboDocument); - - RDFNode publicationDateNode = solution.get(QueryFieldLabels - .DOCUMENT_PUBLICATION_DATE); - if (publicationDateNode != null) { - biboDocument.setActivityDate(publicationDateNode.toString()); - } - } - currentEntityPublications.add(biboDocument); - } - subEntity.addActivities(currentEntityPublications); - } - - private static void getPublicationWithJournalForEntity( - ResultSet queryResult, - SubEntity subEntity, - Map allDocumentURIToVOs) { - - Set currentEntityPublications = new HashSet(); - - while (queryResult.hasNext()) { - - QuerySolution solution = queryResult.nextSolution(); - - if (StringUtils.isEmpty(subEntity.getLastCachedAtDateTime())) { - - RDFNode lastCachedAtNode = solution.get(QueryFieldLabels.LAST_CACHED_AT_DATETIME); - if (lastCachedAtNode != null) { - subEntity.setLastCachedAtDateTime(lastCachedAtNode.toString()); - } - } - - RDFNode documentNode = solution.get(QueryFieldLabels.DOCUMENT_URL); - Activity biboDocument; - - if (allDocumentURIToVOs.containsKey(documentNode.toString())) { - biboDocument = allDocumentURIToVOs.get(documentNode.toString()); - - } else { - - biboDocument = new MapOfScienceActivity(documentNode.toString()); - allDocumentURIToVOs.put(documentNode.toString(), biboDocument); - - RDFNode publicationDateNode = solution.get(QueryFieldLabels - .DOCUMENT_PUBLICATION_DATE); - if (publicationDateNode != null) { - biboDocument.setActivityDate(publicationDateNode.toString()); - } - - RDFNode publicationJournalNode = solution.get(QueryFieldLabels - .DOCUMENT_JOURNAL_LABEL); - - if (publicationJournalNode != null) { - ((MapOfScienceActivity) biboDocument).setPublishedInJournal(publicationJournalNode.toString()); - } - } - currentEntityPublications.add(biboDocument); - - } - subEntity.addActivities(currentEntityPublications); - } - - public static String getLastCachedAtForEntity(ResultSet queryResult) { - - String lastCachedAtDateTime = null; - - while (queryResult.hasNext()) { - - QuerySolution solution = queryResult.nextSolution(); - - RDFNode lastCachedAtNode = solution.get(QueryFieldLabels.LAST_CACHED_AT_DATETIME); - if (lastCachedAtNode != null) { - lastCachedAtDateTime = lastCachedAtNode.toString(); - } - } - - return lastCachedAtDateTime; - } - - private static void getGrantForEntity( - ResultSet queryResult, - SubEntity subEntity, - Map allGrantURIToVO) { - - Set currentEntityGrants = new HashSet(); - - while (queryResult.hasNext()) { - - QuerySolution solution = queryResult.nextSolution(); - - if (StringUtils.isEmpty(subEntity.getLastCachedAtDateTime())) { - - RDFNode lastCachedAtNode = solution.get(QueryFieldLabels.LAST_CACHED_AT_DATETIME); - if (lastCachedAtNode != null) { - subEntity.setLastCachedAtDateTime(lastCachedAtNode.toString()); - } - } - - RDFNode grantNode = solution.get(QueryFieldLabels.GRANT_URL); - Activity coreGrant; - - if (allGrantURIToVO.containsKey(grantNode.toString())) { - coreGrant = allGrantURIToVO.get(grantNode.toString()); - - } else { - - coreGrant = new Activity(grantNode.toString()); - allGrantURIToVO.put(grantNode.toString(), coreGrant); - - RDFNode grantStartDateNode = solution.get(QueryFieldLabels.ROLE_START_DATE); - - if (grantStartDateNode != null) { - coreGrant.setActivityDate(grantStartDateNode.toString()); - } else { - grantStartDateNode = solution - .get(QueryFieldLabels.GRANT_START_DATE); - if (grantStartDateNode != null) { - coreGrant.setActivityDate(grantStartDateNode.toString()); - } - } - } - currentEntityGrants.add(coreGrant); - } - - subEntity.addActivities(currentEntityGrants); - } - - public static Map getGrantsForAllSubOrganizations( - Dataset dataset, Entity organizationEntity) - throws MalformedQueryParametersException { - Map allGrantURIToVO = new HashMap(); - - for (SubEntity subOrganization : organizationEntity.getSubEntities()) { - -// System.out.println("constructing grants for " + subOrganization.getIndividualLabel() + " :: " + subOrganization.getIndividualURI()); - - long before = System.currentTimeMillis(); - - Model subOrganizationGrantsModel = ModelConstructorUtilities - .getOrConstructModel( - subOrganization.getIndividualURI(), - OrganizationToGrantsForSubOrganizationsModelConstructor.MODEL_TYPE, - dataset); - -// System.out.println("\t construct -> " + (System.currentTimeMillis() - before)); - - before = System.currentTimeMillis(); - - Map fieldLabelToOutputFieldLabel = new HashMap(); - fieldLabelToOutputFieldLabel.put("grant", QueryFieldLabels.GRANT_URL); - fieldLabelToOutputFieldLabel.put("grantLabel", QueryFieldLabels.GRANT_LABEL); - fieldLabelToOutputFieldLabel.put("grantStartDate", QueryFieldLabels.GRANT_START_DATE); - fieldLabelToOutputFieldLabel.put("roleStartDate", QueryFieldLabels.ROLE_START_DATE); - - String whereClause = "" - + "{" - + " <" + subOrganization.getIndividualURI() + "> vivosocnet:hasInvestigatorWithGrant ?grant . " - + " ?grant rdfs:label ?grantLabel . " - + " OPTIONAL { " - + " ?grant vivosocnet:startDateTimeOnGrant ?grantStartDate } . " - + " OPTIONAL { " - + " ?grant vivosocnet:startDateTimeOnRole ?roleStartDate } . " - + "}" - + "UNION" - + "{" - + " <" + subOrganization.getIndividualURI() + "> vivosocnet:hasPIWithGrant ?grant . " - + " ?grant rdfs:label ?grantLabel . " - + " OPTIONAL { " - + " ?grant vivosocnet:startDateTimeOnGrant ?grantStartDate } . " - + " OPTIONAL { " - + " ?grant vivosocnet:startDateTimeOnRole ?roleStartDate } . " - + "}" - + "UNION" - + "{" - + " <" + subOrganization.getIndividualURI() + "> vivosocnet:hascoPIWithGrant ?grant . " - + " ?grant rdfs:label ?grantLabel . " - + " OPTIONAL { " - + " ?grant vivosocnet:startDateTimeOnGrant ?grantStartDate } . " - + " OPTIONAL { " - + " ?grant vivosocnet:startDateTimeOnRole ?roleStartDate } . " - + "}"; - - QueryRunner subOrganizationGrantsQuery = - new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel, - "", - whereClause, - "", - subOrganizationGrantsModel); - - /* - * This method side-affects the subOrganization entity & the map containing all the grants for - * the subject organization. - * */ - getGrantForEntity(subOrganizationGrantsQuery.getQueryResult(), subOrganization, allGrantURIToVO); - - String lastCachedAtForEntity = getLastCachedAtDateTimeForEntityInModel( - subOrganization, - subOrganizationGrantsModel); - - subOrganization.setLastCachedAtDateTime(lastCachedAtForEntity); - -// System.out.println("\t select -> " + (System.currentTimeMillis() - before)); - } - return allGrantURIToVO; - } - - private static String getLastCachedAtDateTimeForEntityInModel( - SubEntity entity, Model subOrganizationGrantsModel) - throws MalformedQueryParametersException { - - Map fieldLabelToOutputFieldLabel = new HashMap(); - fieldLabelToOutputFieldLabel.put("lastCachedAtDateTime", QueryFieldLabels.LAST_CACHED_AT_DATETIME); - - String whereClause = "" - + "{" - + " <" + entity.getIndividualURI() + "> vivosocnet:lastCachedAt ?lastCachedAtDateTime . " - + "}"; - - QueryRunner entityLastCachedAtQuery = - new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel, - "", - whereClause, - "", - subOrganizationGrantsModel); - - String lastCachedAtForEntity = getLastCachedAtForEntity(entityLastCachedAtQuery.getQueryResult()); - return lastCachedAtForEntity; - } - - public static Map getGrantsForAssociatedPeople( - Dataset dataset, Collection people) - throws MalformedQueryParametersException { - Map allGrantURIToVOs = new HashMap(); - - Model peopleGrantsModel = ModelConstructorUtilities - .getOrConstructModel( - null, - PeopleToGrantsModelConstructor.MODEL_TYPE, - dataset); - - for (SubEntity person : people) { - updateGrantsForPerson(person, allGrantURIToVOs, peopleGrantsModel); - } - return allGrantURIToVOs; - } - - /** - * This method side-effects person and the central grants map. - * @param person - * @param allGrantURIToVOs - * @param personGrantsModel - * @throws MalformedQueryParametersException - */ - private static void updateGrantsForPerson(SubEntity person, - Map allGrantURIToVOs, Model personGrantsModel) - throws MalformedQueryParametersException { - - Map fieldLabelToOutputFieldLabel = new HashMap(); - fieldLabelToOutputFieldLabel.put("grant", QueryFieldLabels.GRANT_URL); - fieldLabelToOutputFieldLabel.put("grantLabel", QueryFieldLabels.GRANT_LABEL); - fieldLabelToOutputFieldLabel.put("grantStartDate", QueryFieldLabels.GRANT_START_DATE); - fieldLabelToOutputFieldLabel.put("roleStartDate", QueryFieldLabels.ROLE_START_DATE); - - String whereClause = "" - + "{" - + " <" + person.getIndividualURI() + "> vivosocnet:hasGrantAsAnInvestigator ?grant . " - + " ?grant rdfs:label ?grantLabel . " - + " OPTIONAL { " - + " ?grant vivosocnet:startDateTimeOnGrant ?grantStartDate } . " - + " OPTIONAL { " - + " ?grant vivosocnet:startDateTimeOnRole ?roleStartDate } . " - + "}" - + "UNION" - + "{" - + " <" + person.getIndividualURI() + "> vivosocnet:hasGrantAsPI ?grant . " - + " ?grant rdfs:label ?grantLabel . " - + " OPTIONAL { " - + " ?grant vivosocnet:startDateTimeOnGrant ?grantStartDate } . " - + " OPTIONAL { " - + " ?grant vivosocnet:startDateTimeOnRole ?roleStartDate } . " - + "}" - + "UNION" - + "{" - + " <" + person.getIndividualURI() + "> vivosocnet:hasGrantAsCoPI ?grant . " - + " ?grant rdfs:label ?grantLabel . " - + " OPTIONAL { " - + " ?grant vivosocnet:startDateTimeOnGrant ?grantStartDate } . " - + " OPTIONAL { " - + " ?grant vivosocnet:startDateTimeOnRole ?roleStartDate } . " - + "}"; - - QueryRunner personGrantsQuery = - new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel, - "", - whereClause, - "", - personGrantsModel); - - getGrantForEntity(personGrantsQuery.getQueryResult(), person, allGrantURIToVOs); - - String lastCachedAtForEntity = getLastCachedAtDateTimeForEntityInModel( - person, - personGrantsModel); - - person.setLastCachedAtDateTime(lastCachedAtForEntity); - } - - public static Map getGrantsForPerson( - Dataset dataset, SubEntity person, boolean doCache) - throws MalformedQueryParametersException { - - Map allGrantURIToVOs = new HashMap(); - - Model personGrantsModel = null; - - - /* - * If we dont want to cache the results then create the model directly without - * using the ModelConstructorUtilities. Use case is the co-pi ego-centric - * visualization. - * */ - if (doCache) { - personGrantsModel = ModelConstructorUtilities - .getOrConstructModel( - person.getIndividualURI(), - PersonToGrantsModelConstructor.MODEL_TYPE, - dataset); - } else { - - ModelConstructor model = new PersonToGrantsModelConstructor(person.getIndividualURI(), dataset); - personGrantsModel = model.getConstructedModel(); - } - - - updateGrantsForPerson(person, allGrantURIToVOs, personGrantsModel); - - - return allGrantURIToVOs; - } - - - public static Map getPublicationsForPerson( - Dataset dataset, SubEntity person, boolean doCache) - throws MalformedQueryParametersException { - - Map allPublicationURIToVOs = new HashMap(); - - Model personPublicationsModel = null; - - - /* - * If we dont want to cache the results then create the model directly without - * using the ModelConstructorUtilities. Use case is the co-author ego-centric - * visualization. - * */ - if (doCache) { - personPublicationsModel = ModelConstructorUtilities - .getOrConstructModel( - person.getIndividualURI(), - PersonToPublicationsModelConstructor.MODEL_TYPE, - dataset); - } else { - - ModelConstructor model = new PersonToPublicationsModelConstructor(person.getIndividualURI(), dataset); - personPublicationsModel = model.getConstructedModel(); - } - - - updatePublicationsForPerson(person, allPublicationURIToVOs, personPublicationsModel); - - return allPublicationURIToVOs; - } - - public static Map getPublicationsForAssociatedPeople( - Dataset dataset, Collection people) - throws MalformedQueryParametersException { - Map allDocumentURIToVOs = new HashMap(); - - Model peoplePublicationsModel = ModelConstructorUtilities - .getOrConstructModel( - null, - PeopleToPublicationsModelConstructor.MODEL_TYPE, - dataset); - - for (SubEntity person : people) { - - updatePublicationsForPerson(person, allDocumentURIToVOs, - peoplePublicationsModel); - - } - return allDocumentURIToVOs; - } - - /** - * This method side-effects the person and the central documents map. - * @param person - * @param allDocumentURIToVOs - * @param peoplePublicationsModel - * @throws MalformedQueryParametersException - */ - private static void updatePublicationsForPerson(SubEntity person, - Map allDocumentURIToVOs, - Model peoplePublicationsModel) - throws MalformedQueryParametersException { - - Map fieldLabelToOutputFieldLabel = new HashMap(); - fieldLabelToOutputFieldLabel.put("document", QueryFieldLabels.DOCUMENT_URL); - fieldLabelToOutputFieldLabel.put("documentLabel", QueryFieldLabels.DOCUMENT_LABEL); - fieldLabelToOutputFieldLabel.put("documentPublicationDate", QueryFieldLabels.DOCUMENT_PUBLICATION_DATE); - - String whereClause = "" - + " <" + person.getIndividualURI() + "> vivosocnet:hasPublication ?document . " - + " ?document rdfs:label ?documentLabel . " - + " OPTIONAL { " - + " ?document core:dateTimeValue ?dateTimeValue . " - + " ?dateTimeValue core:dateTime ?documentPublicationDate } . "; - - QueryRunner personPublicationsQuery = - new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel, - "", - whereClause, - "", - peoplePublicationsModel); - - getPublicationForEntity(personPublicationsQuery.getQueryResult(), - person, - allDocumentURIToVOs); - - String lastCachedAtForEntity = getLastCachedAtDateTimeForEntityInModel( - person, - peoplePublicationsModel); - - person.setLastCachedAtDateTime(lastCachedAtForEntity); - } - - public static Map getPublicationsWithJournalForAssociatedPeople( - Dataset dataset, Collection people) - throws MalformedQueryParametersException { - Map allDocumentURIToVOs = new HashMap(); - - Model peoplePublicationsModel = ModelConstructorUtilities - .getOrConstructModel( - null, - PeopleToPublicationsModelConstructor.MODEL_TYPE, - dataset); - - for (SubEntity person : people) { - -// System.out.println("getting publications for " + person.getIndividualLabel()); - - Map fieldLabelToOutputFieldLabel = new HashMap(); - fieldLabelToOutputFieldLabel.put("document", QueryFieldLabels.DOCUMENT_URL); - fieldLabelToOutputFieldLabel.put("documentLabel", QueryFieldLabels.DOCUMENT_LABEL); - fieldLabelToOutputFieldLabel.put("documentPublicationDate", QueryFieldLabels.DOCUMENT_PUBLICATION_DATE); - fieldLabelToOutputFieldLabel.put("journalLabel", QueryFieldLabels.DOCUMENT_JOURNAL_LABEL); - - String whereClause = "" - + " <" + person.getIndividualURI() + "> vivosocnet:hasPublication ?document . " - + " ?document rdfs:label ?documentLabel . " - + " OPTIONAL { " - + " ?document core:dateTimeValue ?dateTimeValue . " - + " ?dateTimeValue core:dateTime ?documentPublicationDate } . " - + " OPTIONAL { " - + " ?document core:hasPublicationVenue ?journal . " - + " ?journal rdfs:label ?journalLabel . } "; - - QueryRunner personPublicationsQuery = - new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel, - "", - whereClause, - "", - peoplePublicationsModel); - - getPublicationWithJournalForEntity(personPublicationsQuery.getQueryResult(), - person, - allDocumentURIToVOs); - - String lastCachedAtForEntity = getLastCachedAtDateTimeForEntityInModel( - person, - peoplePublicationsModel); - - person.setLastCachedAtDateTime(lastCachedAtForEntity); - - } - return allDocumentURIToVOs; - } - -} +/* $This file is distributed under the terms of the license in /doc/license.txt$ */ +package edu.cornell.mannlib.vitro.webapp.visualization.visutils; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.lang.StringUtils; + +import com.hp.hpl.jena.query.Dataset; +import com.hp.hpl.jena.query.QuerySolution; +import com.hp.hpl.jena.query.ResultSet; +import com.hp.hpl.jena.rdf.model.Model; +import com.hp.hpl.jena.rdf.model.RDFNode; + +import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryFieldLabels; +import edu.cornell.mannlib.vitro.webapp.visualization.constants.VOConstants; +import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; +import edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.ModelConstructorUtilities; +import edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.OrganizationAssociatedPeopleModelWithTypesConstructor; +import edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.OrganizationModelWithTypesConstructor; +import edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.OrganizationToGrantsForSubOrganizationsModelConstructor; +import edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.OrganizationToPublicationsForSubOrganizationsModelConstructor; +import edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.PeopleToGrantsModelConstructor; +import edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.PeopleToPublicationsModelConstructor; +import edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.PersonToGrantsModelConstructor; +import edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.PersonToPublicationsModelConstructor; +import edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.SubOrganizationWithinModelConstructor; +import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Activity; +import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Entity; +import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Individual; +import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.MapOfScienceActivity; +import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.SubEntity; + +public class SelectOnModelUtilities { + + public static Entity getSubjectOrganizationHierarchy(Dataset dataset, + String subjectEntityURI) throws MalformedQueryParametersException { + Model organizationModel = ModelConstructorUtilities + .getOrConstructModel( + null, + OrganizationModelWithTypesConstructor.MODEL_TYPE, + dataset); + + Map fieldLabelToOutputFieldLabel = new HashMap(); + fieldLabelToOutputFieldLabel.put("organizationLabel", QueryFieldLabels.ORGANIZATION_LABEL); + fieldLabelToOutputFieldLabel.put("subOrganization", QueryFieldLabels.SUBORGANIZATION_URL); + fieldLabelToOutputFieldLabel.put("subOrganizationLabel", QueryFieldLabels.SUBORGANIZATION_LABEL); + fieldLabelToOutputFieldLabel.put("subOrganizationTypeLabel", QueryFieldLabels.SUBORGANIZATION_TYPE_LABEL); + + String whereClause = "" + + " <" + subjectEntityURI + "> rdfs:label ?organizationLabel . " + + " <" + subjectEntityURI + "> ?subOrganization . " + + " ?subOrganization rdf:type foaf:Organization . " + + " ?subOrganization rdfs:label ?subOrganizationLabel . " + + " ?subOrganization rdf:type ?subOrgType . " + + " ?subOrgType rdfs:label ?subOrganizationTypeLabel . "; + + QueryRunner subOrganizationsWithTypesQuery = + new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel, + "", + whereClause, + "", + organizationModel); + + Entity entityWithSubOrganizations = getEntityWithSubOrganizations(subjectEntityURI, + subOrganizationsWithTypesQuery.getQueryResult()); + + Entity entityWithParentOrganizations = getAllParentOrganizations(dataset, subjectEntityURI); + + entityWithSubOrganizations.addParents(entityWithParentOrganizations.getParents()); + + return entityWithSubOrganizations; + } + + public static Entity getSubjectPersonEntity(Dataset dataset, + String subjectEntityURI) throws MalformedQueryParametersException { + + Map fieldLabelToOutputFieldLabel = new HashMap(); + fieldLabelToOutputFieldLabel.put("authorLabel", QueryFieldLabels.AUTHOR_LABEL); + + String whereClause = "" + + " <" + subjectEntityURI + "> rdfs:label ?authorLabel . "; + + QueryRunner personQuery = + new GenericQueryRunner(fieldLabelToOutputFieldLabel, + "", + whereClause, + "", + dataset); + + Entity personEntity = new Entity(subjectEntityURI); + + ResultSet queryResult = personQuery.getQueryResult(); + + while (queryResult.hasNext()) { + + QuerySolution solution = queryResult.nextSolution(); + + RDFNode personLabelNode = solution.get(QueryFieldLabels.AUTHOR_LABEL); + if (personLabelNode != null) { + personEntity.setEntityLabel(personLabelNode.toString()); + } + + } + + /* + * We are adding A person as it's own subentity in order to make our code for geenrating csv, json + * & other data as streamlined as possible between entities of type Organization & Person. + * */ + SubEntity subEntity = new SubEntity(subjectEntityURI, personEntity.getEntityLabel()); + subEntity.setEntityClass(VOConstants.EntityClassType.PERSON); + + personEntity.addSubEntity(subEntity); + +// Entity entityWithParentOrganizations = getAllParentOrganizations(dataset, subjectEntityURI); +// +// personEntity.addParents(entityWithParentOrganizations.getParents()); + + return personEntity; + } + + public static Entity getAllParentOrganizations(Dataset dataset, + String subjectEntityURI) throws MalformedQueryParametersException { + Model organizationModel = ModelConstructorUtilities + .getOrConstructModel( + null, + SubOrganizationWithinModelConstructor.MODEL_TYPE, + dataset); + + Map fieldLabelToOutputFieldLabel = new HashMap(); + fieldLabelToOutputFieldLabel.put("organizationLabel", QueryFieldLabels.ORGANIZATION_LABEL); + fieldLabelToOutputFieldLabel.put("parentOrganization", QueryFieldLabels.PARENT_ORGANIZATION_URL); + fieldLabelToOutputFieldLabel.put("parentOrganizationLabel", QueryFieldLabels.PARENT_ORGANIZATION_LABEL); + + String whereClause = "" + + " <" + subjectEntityURI + "> rdfs:label ?organizationLabel . " + + " <" + subjectEntityURI + "> ?parentOrganization . " + + " ?parentOrganization rdf:type foaf:Organization . " + + " ?parentOrganization rdfs:label ?parentOrganizationLabel . "; + + QueryRunner parentOrganizationsQuery = + new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel, + "", + whereClause, + "", + organizationModel); + + return getEntityWithParentOrganizations(subjectEntityURI, + parentOrganizationsQuery.getQueryResult()); + } + + private static Entity getEntityWithParentOrganizations(String subjectEntityURI, ResultSet queryResult) { + + Entity entity = new Entity(subjectEntityURI); + Map parentOrganizationURIToVO = new HashMap(); + + while (queryResult.hasNext()) { + + QuerySolution solution = queryResult.nextSolution(); + + if (StringUtils.isEmpty(entity.getEntityLabel())) { + + RDFNode organizationLabelNode = solution.get(QueryFieldLabels.ORGANIZATION_LABEL); + if (organizationLabelNode != null) { + entity.setIndividualLabel(organizationLabelNode.toString()); + } + } + + RDFNode parentOrganizationNode = solution.get(QueryFieldLabels.PARENT_ORGANIZATION_URL); + + Individual parent; + + if (!parentOrganizationURIToVO.containsKey(parentOrganizationNode.toString())) { + + parent = new Individual(parentOrganizationNode.toString()); + + parentOrganizationURIToVO.put(parentOrganizationNode.toString(), parent); + + RDFNode parentOrganizationLabelNode = solution.get(QueryFieldLabels.PARENT_ORGANIZATION_LABEL); + if (parentOrganizationLabelNode != null) { + parent.setIndividualLabel(parentOrganizationLabelNode.toString()); + } + } + } + + entity.addParents(parentOrganizationURIToVO.values()); + + return entity; + } + + private static Entity getEntityWithSubOrganizations(String subjectEntityURI, ResultSet queryResult) { + + Entity entity = new Entity(subjectEntityURI); + Map subOrganizationURIToVO = new HashMap(); + + while (queryResult.hasNext()) { + + QuerySolution solution = queryResult.nextSolution(); + + if (StringUtils.isEmpty(entity.getEntityLabel())) { + + RDFNode organizationLabelNode = solution.get(QueryFieldLabels.ORGANIZATION_LABEL); + if (organizationLabelNode != null) { + + entity.setEntityLabel(organizationLabelNode.toString()); + } + } + + RDFNode subOrganizationNode = solution.get(QueryFieldLabels.SUBORGANIZATION_URL); + + SubEntity subEntity; + + if (subOrganizationURIToVO.containsKey(subOrganizationNode.toString())) { + + subEntity = subOrganizationURIToVO.get(subOrganizationNode.toString()); + + } else { + + subEntity = new SubEntity(subOrganizationNode.toString()); + + subEntity.setEntityClass(VOConstants.EntityClassType.ORGANIZATION); + + subOrganizationURIToVO.put(subOrganizationNode.toString(), subEntity); + + RDFNode subOrganizationLabelNode = solution.get(QueryFieldLabels.SUBORGANIZATION_LABEL); + if (subOrganizationLabelNode != null) { + subEntity.setIndividualLabel(subOrganizationLabelNode.toString()); + } + } + + RDFNode subOrganizationTypeLabelNode = solution.get(QueryFieldLabels.SUBORGANIZATION_TYPE_LABEL); + if (subOrganizationTypeLabelNode != null) { + subEntity.addEntityTypeLabel(subOrganizationTypeLabelNode.toString()); + } + } + + entity.addSubEntitities(subOrganizationURIToVO.values()); + + return entity; + } + + public static Entity getSubjectOrganizationAssociatedPeople(Dataset dataset, + String subjectEntityURI) throws MalformedQueryParametersException { + Model associatedPeopleModel = ModelConstructorUtilities + .getOrConstructModel( + subjectEntityURI, + OrganizationAssociatedPeopleModelWithTypesConstructor.MODEL_TYPE, + dataset); + + Map fieldLabelToOutputFieldLabel = new HashMap(); + fieldLabelToOutputFieldLabel.put("organizationLabel", QueryFieldLabels.ORGANIZATION_LABEL); + fieldLabelToOutputFieldLabel.put("person", QueryFieldLabels.PERSON_URL); + fieldLabelToOutputFieldLabel.put("personLabel", QueryFieldLabels.PERSON_LABEL); + fieldLabelToOutputFieldLabel.put("personTypeLabel", QueryFieldLabels.PERSON_TYPE_LABEL); + + String whereClause = "" + + " <" + subjectEntityURI + "> rdfs:label ?organizationLabel . " + + " <" + subjectEntityURI + "> vivosocnet:hasPersonWithActivity ?person . " + + " ?person rdfs:label ?personLabel . " + + " ?person rdf:type ?personType . " + + " ?personType rdfs:label ?personTypeLabel . "; + + QueryRunner associatedPeopleWithTypesQuery = + new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel, + "", + whereClause, + "", + associatedPeopleModel); + + return getEntityWithAssociatedPeopleSubEntitities(subjectEntityURI, associatedPeopleWithTypesQuery.getQueryResult()); + } + + private static Entity getEntityWithAssociatedPeopleSubEntitities( + String subjectEntityURI, ResultSet queryResult) { + + Entity entity = new Entity(subjectEntityURI); + Map associatedPeopleURIToVO = new HashMap(); + + while (queryResult.hasNext()) { + + QuerySolution solution = queryResult.nextSolution(); + + if (StringUtils.isEmpty(entity.getEntityLabel())) { + + RDFNode organizationLabelNode = solution.get(QueryFieldLabels.ORGANIZATION_LABEL); + if (organizationLabelNode != null) { + entity.setIndividualLabel(organizationLabelNode.toString()); + } + } + + RDFNode personNode = solution.get(QueryFieldLabels.PERSON_URL); + + SubEntity subEntity; + + if (associatedPeopleURIToVO.containsKey(personNode.toString())) { + + subEntity = associatedPeopleURIToVO.get(personNode.toString()); + + } else { + + subEntity = new SubEntity(personNode.toString()); + subEntity.setEntityClass(VOConstants.EntityClassType.PERSON); + associatedPeopleURIToVO.put(personNode.toString(), subEntity); + + RDFNode personLabelNode = solution.get(QueryFieldLabels.PERSON_LABEL); + if (personLabelNode != null) { + subEntity.setIndividualLabel(personLabelNode.toString()); + } + } + + RDFNode personTypeLabelNode = solution.get(QueryFieldLabels.PERSON_TYPE_LABEL); + if (personTypeLabelNode != null) { + subEntity.addEntityTypeLabel(personTypeLabelNode.toString()); + } + } + + entity.addSubEntitities(associatedPeopleURIToVO.values()); + return entity; + } + + public static Map getPublicationsForAllSubOrganizations( + Dataset dataset, Entity organizationEntity) + throws MalformedQueryParametersException { + Map allDocumentURIToVOs = new HashMap(); + + for (SubEntity subOrganization : organizationEntity.getSubEntities()) { + + Model subOrganizationPublicationsModel = ModelConstructorUtilities + .getOrConstructModel( + subOrganization.getIndividualURI(), + OrganizationToPublicationsForSubOrganizationsModelConstructor.MODEL_TYPE, + dataset); + +// System.out.println("getting publications for " + subOrganization.getIndividualLabel()); + + Map fieldLabelToOutputFieldLabel = new HashMap(); + fieldLabelToOutputFieldLabel.put("document", QueryFieldLabels.DOCUMENT_URL); + fieldLabelToOutputFieldLabel.put("documentLabel", QueryFieldLabels.DOCUMENT_LABEL); + fieldLabelToOutputFieldLabel.put("documentPublicationDate", QueryFieldLabels.DOCUMENT_PUBLICATION_DATE); + + String whereClause = "" + + " <" + subOrganization.getIndividualURI() + "> vivosocnet:hasPersonWithPublication ?document . " + + " ?document rdfs:label ?documentLabel . " + + " OPTIONAL { " + + " ?document core:dateTimeValue ?dateTimeValue . " + + " ?dateTimeValue core:dateTime ?documentPublicationDate } . "; + + QueryRunner subOrganizationPublicationsQuery = + new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel, + "", + whereClause, + "", + subOrganizationPublicationsModel); + + getPublicationForEntity(subOrganizationPublicationsQuery.getQueryResult(), + subOrganization, + allDocumentURIToVOs); + + String lastCachedAtForEntity = getLastCachedAtDateTimeForEntityInModel( + subOrganization, + subOrganizationPublicationsModel); + + subOrganization.setLastCachedAtDateTime(lastCachedAtForEntity); + + } + return allDocumentURIToVOs; + } + + public static Map getPublicationsWithJournalForAllSubOrganizations( + Dataset dataset, Entity organizationEntity) + throws MalformedQueryParametersException { + Map allDocumentURIToVOs = new HashMap(); + + for (SubEntity subOrganization : organizationEntity.getSubEntities()) { + + Model subOrganizationPublicationsModel = ModelConstructorUtilities + .getOrConstructModel( + subOrganization.getIndividualURI(), + OrganizationToPublicationsForSubOrganizationsModelConstructor.MODEL_TYPE, + dataset); + +// System.out.println("getting publications for " + subOrganization.getIndividualLabel()); + + Map fieldLabelToOutputFieldLabel = new HashMap(); + fieldLabelToOutputFieldLabel.put("document", QueryFieldLabels.DOCUMENT_URL); + fieldLabelToOutputFieldLabel.put("documentLabel", QueryFieldLabels.DOCUMENT_LABEL); + fieldLabelToOutputFieldLabel.put("documentPublicationDate", QueryFieldLabels.DOCUMENT_PUBLICATION_DATE); + fieldLabelToOutputFieldLabel.put("journalLabel", QueryFieldLabels.DOCUMENT_JOURNAL_LABEL); + + String whereClause = "" + + " <" + subOrganization.getIndividualURI() + "> vivosocnet:hasPersonWithPublication ?document . " + + " ?document rdfs:label ?documentLabel . " + + " OPTIONAL { " + + " ?document core:dateTimeValue ?dateTimeValue . " + + " ?dateTimeValue core:dateTime ?documentPublicationDate } . " + + " OPTIONAL { " + + " ?document core:hasPublicationVenue ?journal . " + + " ?journal rdfs:label ?journalLabel . } "; + + QueryRunner subOrganizationPublicationsQuery = + new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel, + "", + whereClause, + "", + subOrganizationPublicationsModel); + + getPublicationWithJournalForEntity(subOrganizationPublicationsQuery.getQueryResult(), + subOrganization, + allDocumentURIToVOs); + + String lastCachedAtForEntity = getLastCachedAtDateTimeForEntityInModel( + subOrganization, + subOrganizationPublicationsModel); + + subOrganization.setLastCachedAtDateTime(lastCachedAtForEntity); + + } + return allDocumentURIToVOs; + } + + private static void getPublicationForEntity( + ResultSet queryResult, + SubEntity subEntity, + Map allDocumentURIToVOs) { + + Set currentEntityPublications = new HashSet(); + + while (queryResult.hasNext()) { + + QuerySolution solution = queryResult.nextSolution(); + + if (StringUtils.isEmpty(subEntity.getLastCachedAtDateTime())) { + + RDFNode lastCachedAtNode = solution.get(QueryFieldLabels.LAST_CACHED_AT_DATETIME); + if (lastCachedAtNode != null) { + subEntity.setLastCachedAtDateTime(lastCachedAtNode.toString()); + } + } + + RDFNode documentNode = solution.get(QueryFieldLabels.DOCUMENT_URL); + Activity biboDocument; + + if (allDocumentURIToVOs.containsKey(documentNode.toString())) { + biboDocument = allDocumentURIToVOs.get(documentNode.toString()); + + } else { + + biboDocument = new Activity(documentNode.toString()); + allDocumentURIToVOs.put(documentNode.toString(), biboDocument); + + RDFNode publicationDateNode = solution.get(QueryFieldLabels + .DOCUMENT_PUBLICATION_DATE); + if (publicationDateNode != null) { + biboDocument.setActivityDate(publicationDateNode.toString()); + } + } + currentEntityPublications.add(biboDocument); + } + subEntity.addActivities(currentEntityPublications); + } + + private static void getPublicationWithJournalForEntity( + ResultSet queryResult, + SubEntity subEntity, + Map allDocumentURIToVOs) { + + Set currentEntityPublications = new HashSet(); + + while (queryResult.hasNext()) { + + QuerySolution solution = queryResult.nextSolution(); + + if (StringUtils.isEmpty(subEntity.getLastCachedAtDateTime())) { + + RDFNode lastCachedAtNode = solution.get(QueryFieldLabels.LAST_CACHED_AT_DATETIME); + if (lastCachedAtNode != null) { + subEntity.setLastCachedAtDateTime(lastCachedAtNode.toString()); + } + } + + RDFNode documentNode = solution.get(QueryFieldLabels.DOCUMENT_URL); + Activity biboDocument; + + if (allDocumentURIToVOs.containsKey(documentNode.toString())) { + biboDocument = allDocumentURIToVOs.get(documentNode.toString()); + + } else { + + biboDocument = new MapOfScienceActivity(documentNode.toString()); + allDocumentURIToVOs.put(documentNode.toString(), biboDocument); + + RDFNode publicationDateNode = solution.get(QueryFieldLabels + .DOCUMENT_PUBLICATION_DATE); + if (publicationDateNode != null) { + biboDocument.setActivityDate(publicationDateNode.toString()); + } + + RDFNode publicationJournalNode = solution.get(QueryFieldLabels + .DOCUMENT_JOURNAL_LABEL); + + if (publicationJournalNode != null) { + ((MapOfScienceActivity) biboDocument).setPublishedInJournal(publicationJournalNode.toString()); + } + } + currentEntityPublications.add(biboDocument); + + } + subEntity.addActivities(currentEntityPublications); + } + + public static String getLastCachedAtForEntity(ResultSet queryResult) { + + String lastCachedAtDateTime = null; + + while (queryResult.hasNext()) { + + QuerySolution solution = queryResult.nextSolution(); + + RDFNode lastCachedAtNode = solution.get(QueryFieldLabels.LAST_CACHED_AT_DATETIME); + if (lastCachedAtNode != null) { + lastCachedAtDateTime = lastCachedAtNode.toString(); + } + } + + return lastCachedAtDateTime; + } + + private static void getGrantForEntity( + ResultSet queryResult, + SubEntity subEntity, + Map allGrantURIToVO) { + + Set currentEntityGrants = new HashSet(); + + while (queryResult.hasNext()) { + + QuerySolution solution = queryResult.nextSolution(); + + if (StringUtils.isEmpty(subEntity.getLastCachedAtDateTime())) { + + RDFNode lastCachedAtNode = solution.get(QueryFieldLabels.LAST_CACHED_AT_DATETIME); + if (lastCachedAtNode != null) { + subEntity.setLastCachedAtDateTime(lastCachedAtNode.toString()); + } + } + + RDFNode grantNode = solution.get(QueryFieldLabels.GRANT_URL); + Activity coreGrant; + + if (allGrantURIToVO.containsKey(grantNode.toString())) { + coreGrant = allGrantURIToVO.get(grantNode.toString()); + + } else { + + coreGrant = new Activity(grantNode.toString()); + allGrantURIToVO.put(grantNode.toString(), coreGrant); + + RDFNode grantStartDateNode = solution.get(QueryFieldLabels.ROLE_START_DATE); + + if (grantStartDateNode != null) { + coreGrant.setActivityDate(grantStartDateNode.toString()); + } else { + grantStartDateNode = solution + .get(QueryFieldLabels.GRANT_START_DATE); + if (grantStartDateNode != null) { + coreGrant.setActivityDate(grantStartDateNode.toString()); + } + } + } + currentEntityGrants.add(coreGrant); + } + + subEntity.addActivities(currentEntityGrants); + } + + public static Map getGrantsForAllSubOrganizations( + Dataset dataset, Entity organizationEntity) + throws MalformedQueryParametersException { + Map allGrantURIToVO = new HashMap(); + + for (SubEntity subOrganization : organizationEntity.getSubEntities()) { + +// System.out.println("constructing grants for " + subOrganization.getIndividualLabel() + " :: " + subOrganization.getIndividualURI()); + + long before = System.currentTimeMillis(); + + Model subOrganizationGrantsModel = ModelConstructorUtilities + .getOrConstructModel( + subOrganization.getIndividualURI(), + OrganizationToGrantsForSubOrganizationsModelConstructor.MODEL_TYPE, + dataset); + +// System.out.println("\t construct -> " + (System.currentTimeMillis() - before)); + + before = System.currentTimeMillis(); + + Map fieldLabelToOutputFieldLabel = new HashMap(); + fieldLabelToOutputFieldLabel.put("grant", QueryFieldLabels.GRANT_URL); + fieldLabelToOutputFieldLabel.put("grantLabel", QueryFieldLabels.GRANT_LABEL); + fieldLabelToOutputFieldLabel.put("grantStartDate", QueryFieldLabels.GRANT_START_DATE); + fieldLabelToOutputFieldLabel.put("roleStartDate", QueryFieldLabels.ROLE_START_DATE); + + String whereClause = "" + + "{" + + " <" + subOrganization.getIndividualURI() + "> vivosocnet:hasInvestigatorWithGrant ?grant . " + + " ?grant rdfs:label ?grantLabel . " + + " OPTIONAL { " + + " ?grant vivosocnet:startDateTimeOnGrant ?grantStartDate } . " + + " OPTIONAL { " + + " ?grant vivosocnet:startDateTimeOnRole ?roleStartDate } . " + + "}" + + "UNION" + + "{" + + " <" + subOrganization.getIndividualURI() + "> vivosocnet:hasPIWithGrant ?grant . " + + " ?grant rdfs:label ?grantLabel . " + + " OPTIONAL { " + + " ?grant vivosocnet:startDateTimeOnGrant ?grantStartDate } . " + + " OPTIONAL { " + + " ?grant vivosocnet:startDateTimeOnRole ?roleStartDate } . " + + "}" + + "UNION" + + "{" + + " <" + subOrganization.getIndividualURI() + "> vivosocnet:hascoPIWithGrant ?grant . " + + " ?grant rdfs:label ?grantLabel . " + + " OPTIONAL { " + + " ?grant vivosocnet:startDateTimeOnGrant ?grantStartDate } . " + + " OPTIONAL { " + + " ?grant vivosocnet:startDateTimeOnRole ?roleStartDate } . " + + "}"; + + QueryRunner subOrganizationGrantsQuery = + new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel, + "", + whereClause, + "", + subOrganizationGrantsModel); + + /* + * This method side-affects the subOrganization entity & the map containing all the grants for + * the subject organization. + * */ + getGrantForEntity(subOrganizationGrantsQuery.getQueryResult(), subOrganization, allGrantURIToVO); + + String lastCachedAtForEntity = getLastCachedAtDateTimeForEntityInModel( + subOrganization, + subOrganizationGrantsModel); + + subOrganization.setLastCachedAtDateTime(lastCachedAtForEntity); + +// System.out.println("\t select -> " + (System.currentTimeMillis() - before)); + } + return allGrantURIToVO; + } + + private static String getLastCachedAtDateTimeForEntityInModel( + SubEntity entity, Model subOrganizationGrantsModel) + throws MalformedQueryParametersException { + + Map fieldLabelToOutputFieldLabel = new HashMap(); + fieldLabelToOutputFieldLabel.put("lastCachedAtDateTime", QueryFieldLabels.LAST_CACHED_AT_DATETIME); + + String whereClause = "" + + "{" + + " <" + entity.getIndividualURI() + "> vivosocnet:lastCachedAt ?lastCachedAtDateTime . " + + "}"; + + QueryRunner entityLastCachedAtQuery = + new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel, + "", + whereClause, + "", + subOrganizationGrantsModel); + + String lastCachedAtForEntity = getLastCachedAtForEntity(entityLastCachedAtQuery.getQueryResult()); + return lastCachedAtForEntity; + } + + public static Map getGrantsForAssociatedPeople( + Dataset dataset, Collection people) + throws MalformedQueryParametersException { + Map allGrantURIToVOs = new HashMap(); + + Model peopleGrantsModel = ModelConstructorUtilities + .getOrConstructModel( + null, + PeopleToGrantsModelConstructor.MODEL_TYPE, + dataset); + + for (SubEntity person : people) { + updateGrantsForPerson(person, allGrantURIToVOs, peopleGrantsModel); + } + return allGrantURIToVOs; + } + + /** + * This method side-effects person and the central grants map. + * @param person + * @param allGrantURIToVOs + * @param personGrantsModel + * @throws MalformedQueryParametersException + */ + private static void updateGrantsForPerson(SubEntity person, + Map allGrantURIToVOs, Model personGrantsModel) + throws MalformedQueryParametersException { + + Map fieldLabelToOutputFieldLabel = new HashMap(); + fieldLabelToOutputFieldLabel.put("grant", QueryFieldLabels.GRANT_URL); + fieldLabelToOutputFieldLabel.put("grantLabel", QueryFieldLabels.GRANT_LABEL); + fieldLabelToOutputFieldLabel.put("grantStartDate", QueryFieldLabels.GRANT_START_DATE); + fieldLabelToOutputFieldLabel.put("roleStartDate", QueryFieldLabels.ROLE_START_DATE); + + String whereClause = "" + + "{" + + " <" + person.getIndividualURI() + "> vivosocnet:hasGrantAsAnInvestigator ?grant . " + + " ?grant rdfs:label ?grantLabel . " + + " OPTIONAL { " + + " ?grant vivosocnet:startDateTimeOnGrant ?grantStartDate } . " + + " OPTIONAL { " + + " ?grant vivosocnet:startDateTimeOnRole ?roleStartDate } . " + + "}" + + "UNION" + + "{" + + " <" + person.getIndividualURI() + "> vivosocnet:hasGrantAsPI ?grant . " + + " ?grant rdfs:label ?grantLabel . " + + " OPTIONAL { " + + " ?grant vivosocnet:startDateTimeOnGrant ?grantStartDate } . " + + " OPTIONAL { " + + " ?grant vivosocnet:startDateTimeOnRole ?roleStartDate } . " + + "}" + + "UNION" + + "{" + + " <" + person.getIndividualURI() + "> vivosocnet:hasGrantAsCoPI ?grant . " + + " ?grant rdfs:label ?grantLabel . " + + " OPTIONAL { " + + " ?grant vivosocnet:startDateTimeOnGrant ?grantStartDate } . " + + " OPTIONAL { " + + " ?grant vivosocnet:startDateTimeOnRole ?roleStartDate } . " + + "}"; + + QueryRunner personGrantsQuery = + new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel, + "", + whereClause, + "", + personGrantsModel); + + getGrantForEntity(personGrantsQuery.getQueryResult(), person, allGrantURIToVOs); + + String lastCachedAtForEntity = getLastCachedAtDateTimeForEntityInModel( + person, + personGrantsModel); + + person.setLastCachedAtDateTime(lastCachedAtForEntity); + } + + public static Map getGrantsForPerson( + Dataset dataset, SubEntity person, boolean doCache) + throws MalformedQueryParametersException { + + Map allGrantURIToVOs = new HashMap(); + + Model personGrantsModel = null; + + + /* + * If we dont want to cache the results then create the model directly without + * using the ModelConstructorUtilities. Use case is the co-pi ego-centric + * visualization. + * */ + if (doCache) { + personGrantsModel = ModelConstructorUtilities + .getOrConstructModel( + person.getIndividualURI(), + PersonToGrantsModelConstructor.MODEL_TYPE, + dataset); + } else { + + ModelConstructor model = new PersonToGrantsModelConstructor(person.getIndividualURI(), dataset); + personGrantsModel = model.getConstructedModel(); + } + + + updateGrantsForPerson(person, allGrantURIToVOs, personGrantsModel); + + + return allGrantURIToVOs; + } + + + public static Map getPublicationsForPerson( + Dataset dataset, SubEntity person, boolean doCache) + throws MalformedQueryParametersException { + + Map allPublicationURIToVOs = new HashMap(); + + Model personPublicationsModel = null; + + + /* + * If we dont want to cache the results then create the model directly without + * using the ModelConstructorUtilities. Use case is the co-author ego-centric + * visualization. + * */ + if (doCache) { + personPublicationsModel = ModelConstructorUtilities + .getOrConstructModel( + person.getIndividualURI(), + PersonToPublicationsModelConstructor.MODEL_TYPE, + dataset); + } else { + + ModelConstructor model = new PersonToPublicationsModelConstructor(person.getIndividualURI(), dataset); + personPublicationsModel = model.getConstructedModel(); + } + + + updatePublicationsForPerson(person, allPublicationURIToVOs, personPublicationsModel); + + return allPublicationURIToVOs; + } + + public static Map getPublicationsForAssociatedPeople( + Dataset dataset, Collection people) + throws MalformedQueryParametersException { + Map allDocumentURIToVOs = new HashMap(); + + Model peoplePublicationsModel = ModelConstructorUtilities + .getOrConstructModel( + null, + PeopleToPublicationsModelConstructor.MODEL_TYPE, + dataset); + + for (SubEntity person : people) { + + updatePublicationsForPerson(person, allDocumentURIToVOs, + peoplePublicationsModel); + + } + return allDocumentURIToVOs; + } + + /** + * This method side-effects the person and the central documents map. + * @param person + * @param allDocumentURIToVOs + * @param peoplePublicationsModel + * @throws MalformedQueryParametersException + */ + private static void updatePublicationsForPerson(SubEntity person, + Map allDocumentURIToVOs, + Model peoplePublicationsModel) + throws MalformedQueryParametersException { + + Map fieldLabelToOutputFieldLabel = new HashMap(); + fieldLabelToOutputFieldLabel.put("document", QueryFieldLabels.DOCUMENT_URL); + fieldLabelToOutputFieldLabel.put("documentLabel", QueryFieldLabels.DOCUMENT_LABEL); + fieldLabelToOutputFieldLabel.put("documentPublicationDate", QueryFieldLabels.DOCUMENT_PUBLICATION_DATE); + + String whereClause = "" + + " <" + person.getIndividualURI() + "> vivosocnet:hasPublication ?document . " + + " ?document rdfs:label ?documentLabel . " + + " OPTIONAL { " + + " ?document core:dateTimeValue ?dateTimeValue . " + + " ?dateTimeValue core:dateTime ?documentPublicationDate } . "; + + QueryRunner personPublicationsQuery = + new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel, + "", + whereClause, + "", + peoplePublicationsModel); + + getPublicationForEntity(personPublicationsQuery.getQueryResult(), + person, + allDocumentURIToVOs); + + String lastCachedAtForEntity = getLastCachedAtDateTimeForEntityInModel( + person, + peoplePublicationsModel); + + person.setLastCachedAtDateTime(lastCachedAtForEntity); + } + + public static Map getPublicationsWithJournalForAssociatedPeople( + Dataset dataset, Collection people) + throws MalformedQueryParametersException { + Map allDocumentURIToVOs = new HashMap(); + + Model peoplePublicationsModel = ModelConstructorUtilities + .getOrConstructModel( + null, + PeopleToPublicationsModelConstructor.MODEL_TYPE, + dataset); + + for (SubEntity person : people) { + +// System.out.println("getting publications for " + person.getIndividualLabel()); + + Map fieldLabelToOutputFieldLabel = new HashMap(); + fieldLabelToOutputFieldLabel.put("document", QueryFieldLabels.DOCUMENT_URL); + fieldLabelToOutputFieldLabel.put("documentLabel", QueryFieldLabels.DOCUMENT_LABEL); + fieldLabelToOutputFieldLabel.put("documentPublicationDate", QueryFieldLabels.DOCUMENT_PUBLICATION_DATE); + fieldLabelToOutputFieldLabel.put("journalLabel", QueryFieldLabels.DOCUMENT_JOURNAL_LABEL); + + String whereClause = "" + + " <" + person.getIndividualURI() + "> vivosocnet:hasPublication ?document . " + + " ?document rdfs:label ?documentLabel . " + + " OPTIONAL { " + + " ?document core:dateTimeValue ?dateTimeValue . " + + " ?dateTimeValue core:dateTime ?documentPublicationDate } . " + + " OPTIONAL { " + + " ?document core:hasPublicationVenue ?journal . " + + " ?journal rdfs:label ?journalLabel . } "; + + QueryRunner personPublicationsQuery = + new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel, + "", + whereClause, + "", + peoplePublicationsModel); + + getPublicationWithJournalForEntity(personPublicationsQuery.getQueryResult(), + person, + allDocumentURIToVOs); + + String lastCachedAtForEntity = getLastCachedAtDateTimeForEntityInModel( + person, + peoplePublicationsModel); + + person.setLastCachedAtDateTime(lastCachedAtForEntity); + + } + return allDocumentURIToVOs; + } + +}