diff --git a/productMods/js/visualization/entitycomparison/gui-event-manager.js b/productMods/js/visualization/entitycomparison/gui-event-manager.js index 749dac63..4bf0fd52 100644 --- a/productMods/js/visualization/entitycomparison/gui-event-manager.js +++ b/productMods/js/visualization/entitycomparison/gui-event-manager.js @@ -1,288 +1,289 @@ -/* $This file is distributed under the terms of the license in /doc/license.txt$ */ - -$(document).ready(function() { - - /* - * This will set intitial values of the constants present in constants.js - * */ - initConstants(); - /* This is used to cache the current state whether the user is allowed to select more entities from - the datatable or not. Once Max number of entity selection is reached the user can no longer select - more & this variable will be set to false. */ - $("#datatable").data("isEntitySelectionAllowed", true); - - $notificationContainer = $("#notification-container").notify(); - - graphContainer = $("#graphContainer"); - tableDiv = $('#paginatedTable'); - - //temporalGraphProcessor.initiateTemporalGraphRenderProcess(graphContainer, jsonString); - - /* - * When the intra-entity parameters are clicked, - * update the status accordingly. - */ - - $("select.comparisonValues").change(function(){ - - var selectedValue = $("select.comparisonValues option:selected").val(); - - var selectedParameter; - - $.each(COMPARISON_PARAMETERS_INFO, function(index, parameter) { - - if (parameter.value === selectedValue) { - selectedParameter = parameter; - window.location = parameter.viewLink; - } - - }); - - //$("#body").empty().html("
Loading " + selectedValue + "  
"); - - /* - * This piece of code is not executed at all because the redirect happens before there is a chance - * to render the below contents. - * */ - - /* - - $("#comparisonParameter").text("Total Number of " + selectedValue); - $('#yaxislabel').html("Number of " + selectedValue).mbFlipText(false); - $('#yaxislabel').css("color", "#595B5B"); - $('#comparisonHeader').html(selectedValue).css('font-weight', 'bold'); - - - */ - - }); - -}); - -//click event handler for clear button -$("a.clear-selected-entities").live('click', function(){ - clearRenderedObjects(); -}); - -$("input[type=checkbox].easyDeselectCheckbox").live('click', function(){ - - var checkbox = $(this); - var checkboxValue = $(this).attr("value"); - var linkedCheckbox = labelToCheckedEntities[checkboxValue]; - var entityToBeRemoved = labelToEntityRecord[checkboxValue]; - - if(!checkbox.is(':checked')){ - //console.log("Easy deselect checkbox is unclicked!"); - updateRowHighlighter(linkedCheckbox); - removeUsedColor(entityToBeRemoved); - removeEntityUnChecked(renderedObjects, entityToBeRemoved); - removeLegendRow(linkedCheckbox); - removeCheckBoxFromGlobalSet(linkedCheckbox); - $(linkedCheckbox).attr('checked', false); - checkIfColorLimitIsReached(); - displayLineGraphs(); - updateCounter(); - } -}); - - -$(".disabled-checkbox-event-receiver").live("click", function () { - - if ($(this).next().is(':disabled')) { - - createNotification("warning-notification", { - title: 'Error', - text: 'A Maximum 10 entities can be compared. Please remove some & try again.' - }, { - custom: true, - expires: false - }); - - } - -}); - -function performEntityCheckboxUnselectedActions(entity, checkboxValue, checkbox) { - - removeUsedColor(entity); - removeEntityUnChecked(renderedObjects, entity); - removeLegendRow(checkbox); - removeCheckBoxFromGlobalSet(checkbox); - - checkbox.closest("tr").removeClass('datatablerowhighlight'); - -} - -function performEntityCheckboxSelectedActions(entity, checkboxValue, checkbox) { - - getNextFreeColor(entity); - - //Generate the bar, checkbox and label for the legend. - createLegendRow(entity, $("#bottom")); - - renderLineGraph(renderedObjects, entity); - labelToCheckedEntities[checkboxValue] = checkbox; - labelToCheckedEntities[checkboxValue].entity = entity; - -// console.log(labelToCheckedEntities[checkboxValue], entity); - - /* - * To highlight the rows belonging to selected entities. - * */ - checkbox.closest("tr").addClass('datatablerowhighlight'); - -} - -function performEntityCheckboxClickedRedrawActions() { - - setTickSizeOfAxes(); - checkIfColorLimitIsReached(); - displayLineGraphs(); - updateCounter(); - -} - -/* - * function to populate the labelToEntityRecord object with the - * values from the json file and - * dynamically generate checkboxes - */ -function loadData(jsonData, dataTableParams) { - - $.each(jsonData, function (index, val) { - setOfLabels.push(val.label); - labelToEntityRecord[val.label] = val; - }); - - prepareTableForDataTablePagination(jsonData, dataTableParams); - setEntityLevel(getEntityVisMode(jsonData)); - - entityCheckboxOperatedOnEventListener(); - -} - -function entityCheckboxOperatedOnEventListener() { - - /* - * When the elements in the paginated div - * are clicked this event handler is called - */ - $("input." + entityCheckboxSelectorDOMClass).live('click', function () { - - var checkbox = $(this); - var checkboxValue = $(this).attr("value"); - var entity = labelToEntityRecord[checkboxValue]; - - if (checkbox.is(':checked')) { - - performEntityCheckboxSelectedActions(entity, checkboxValue, checkbox); - - } else { - - performEntityCheckboxUnselectedActions(entity, checkboxValue, checkbox); - - } - - performEntityCheckboxClickedRedrawActions(); - - }); - -} - -/* - * This method will setup the options for loading screen & then activate the - * loading screen. - * */ -function setupLoadingScreen(visContainerDIV) { - - $.blockUI.defaults.overlayCSS = { - backgroundColor: '#fff', - opacity: 1.0 - }; - - $.blockUI.defaults.css.width = '500px'; - $.blockUI.defaults.css.border = '0px'; - $.blockUI.defaults.css.top = '15%'; - - visContainerDIV.block({ - message: '

 Loading data for ' - + organizationLabel - + '

' - }); - -} - -/* - * This function gets json data for temporal graph & after rendering removes the - * loading message. It will also display the error container in case of any error. - * */ -function getTemporalGraphData(temporalGraphDataURL, - graphBodyDIV, - errorBodyDIV, - visContainerDIV) { - - $.ajax({ - url: temporalGraphDataURL, - dataType: "json", - success: function (data) { - - if (data.error) { - graphBodyDIV.remove(); - errorBodyDIV.show(); - visContainerDIV.unblock(); - - } else { - graphBodyDIV.show(); - errorBodyDIV.remove(); - temporalGraphProcessor.initiateTemporalGraphRenderProcess(graphContainer, data); - visContainerDIV.unblock(); - } - } - }); - -} - -temporalGraphProcessor = { - - initiateTemporalGraphRenderProcess: function(givenGraphContainer, jsonData) { - - this.dataTableParams = { - searchBarParentContainerDIVClass : "searchbar", - paginationContainerDIVClass : "paginatedtabs" - }; - - - /* - * initial display of the grid when the page loads - * */ - init(givenGraphContainer); - - /* - * render the temporal graph per the sent content. - * */ - loadData(jsonData, this.dataTableParams); - - /* - * This will make sure that top 3 entities are selected by default when the page loads. - */ - $.each($("input." + entityCheckboxSelectorDOMClass), function(index, checkbox) { - - if (index > 2) { - return false; - } - - $(this).attr('checked', true); - - var checkboxValue = $(this).attr("value"); - var entity = labelToEntityRecord[checkboxValue]; - - performEntityCheckboxSelectedActions(entity, checkboxValue, $(this)); - - performEntityCheckboxClickedRedrawActions(); - - }); - - } - +/* $This file is distributed under the terms of the license in /doc/license.txt$ */ + +$(document).ready(function() { + + /* + * This will set intitial values of the constants present in constants.js + * */ + initConstants(); + /* This is used to cache the current state whether the user is allowed to select more entities from + the datatable or not. Once Max number of entity selection is reached the user can no longer select + more & this variable will be set to false. */ + $("#datatable").data("isEntitySelectionAllowed", true); + + $notificationContainer = $("#notification-container").notify(); + + graphContainer = $("#graphContainer"); + tableDiv = $('#paginatedTable'); + + //temporalGraphProcessor.initiateTemporalGraphRenderProcess(graphContainer, jsonString); + + /* + * When the intra-entity parameters are clicked, + * update the status accordingly. + */ + + $("select.comparisonValues").change(function(){ + + var selectedValue = $("select.comparisonValues option:selected").val(); + + var selectedParameter; + + $.each(COMPARISON_PARAMETERS_INFO, function(index, parameter) { + + if (parameter.value === selectedValue) { + selectedParameter = parameter; + window.location = parameter.viewLink; + } + + }); + + //$("#body").empty().html("
Loading " + selectedValue + "  
"); + + /* + * This piece of code is not executed at all because the redirect happens before there is a chance + * to render the below contents. + * */ + + /* + + $("#comparisonParameter").text("Total Number of " + selectedValue); + $('#yaxislabel').html("Number of " + selectedValue).mbFlipText(false); + $('#yaxislabel').css("color", "#595B5B"); + $('#comparisonHeader').html(selectedValue).css('font-weight', 'bold'); + + + */ + + }); + +}); + +//click event handler for clear button +$("a.clear-selected-entities").live('click', function(){ + clearRenderedObjects(); +}); + +$("input[type=checkbox].easyDeselectCheckbox").live('click', function(){ + + var checkbox = $(this); + var checkboxValue = $(this).attr("value"); + var linkedCheckbox = labelToCheckedEntities[checkboxValue]; + var entityToBeRemoved = labelToEntityRecord[checkboxValue]; + + if(!checkbox.is(':checked')){ + //console.log("Easy deselect checkbox is unclicked!"); + updateRowHighlighter(linkedCheckbox); + removeUsedColor(entityToBeRemoved); + removeEntityUnChecked(renderedObjects, entityToBeRemoved); + removeLegendRow(linkedCheckbox); + removeCheckBoxFromGlobalSet(linkedCheckbox); + $(linkedCheckbox).attr('checked', false); + checkIfColorLimitIsReached(); + displayLineGraphs(); + updateCounter(); + } +}); + + +$(".disabled-checkbox-event-receiver").live("click", function () { + + if ($(this).next().is(':disabled')) { + + createNotification("warning-notification", { + title: 'Error', + text: 'A Maximum 10 entities can be compared. Please remove some & try again.' + }, { + custom: true, + expires: false + }); + + } + +}); + +function performEntityCheckboxUnselectedActions(entity, checkboxValue, checkbox) { + + removeUsedColor(entity); + removeEntityUnChecked(renderedObjects, entity); + removeLegendRow(checkbox); + removeCheckBoxFromGlobalSet(checkbox); + + checkbox.closest("tr").removeClass('datatablerowhighlight'); + +} + +function performEntityCheckboxSelectedActions(entity, checkboxValue, checkbox) { + + getNextFreeColor(entity); + + //Generate the bar, checkbox and label for the legend. + createLegendRow(entity, $("#bottom")); + + renderLineGraph(renderedObjects, entity); + labelToCheckedEntities[checkboxValue] = checkbox; + labelToCheckedEntities[checkboxValue].entity = entity; + +// console.log(labelToCheckedEntities[checkboxValue], entity); + + /* + * To highlight the rows belonging to selected entities. + * */ + checkbox.closest("tr").addClass('datatablerowhighlight'); + +} + +function performEntityCheckboxClickedRedrawActions() { + + setTickSizeOfAxes(); + checkIfColorLimitIsReached(); + displayLineGraphs(); + updateCounter(); + +} + +/* + * function to populate the labelToEntityRecord object with the + * values from the json file and + * dynamically generate checkboxes + */ +function loadData(jsonData, dataTableParams) { + + $.each(jsonData, function (index, val) { + setOfLabels.push(val.label); + labelToEntityRecord[val.label] = val; + }); + + prepareTableForDataTablePagination(jsonData, dataTableParams); + setEntityLevel(getEntityVisMode(jsonData)); + + entityCheckboxOperatedOnEventListener(); + +} + +function entityCheckboxOperatedOnEventListener() { + + /* + * When the elements in the paginated div + * are clicked this event handler is called + */ + $("input." + entityCheckboxSelectorDOMClass).live('click', function () { + + var checkbox = $(this); + var checkboxValue = $(this).attr("value"); + var entity = labelToEntityRecord[checkboxValue]; + + if (checkbox.is(':checked')) { + + performEntityCheckboxSelectedActions(entity, checkboxValue, checkbox); + + } else { + + performEntityCheckboxUnselectedActions(entity, checkboxValue, checkbox); + + } + + performEntityCheckboxClickedRedrawActions(); + + }); + +} + +/* + * This method will setup the options for loading screen & then activate the + * loading screen. + * */ +function setupLoadingScreen(visContainerDIV) { + + $.blockUI.defaults.overlayCSS = { + backgroundColor: '#fff', + opacity: 1.0 + }; + + $.blockUI.defaults.css.width = '500px'; + $.blockUI.defaults.css.border = '0px'; + $.blockUI.defaults.css.top = '15%'; + + visContainerDIV.block({ + message: '

 Loading data for ' + + organizationLabel + + '

' + }); + +} + +/* + * This function gets json data for temporal graph & after rendering removes the + * loading message. It will also display the error container in case of any error. + * */ +function getTemporalGraphData(temporalGraphDataURL, + graphBodyDIV, + errorBodyDIV, + visContainerDIV) { + + $.ajax({ + url: temporalGraphDataURL, + dataType: "json", + timeout: 5 * 60 * 1000, + success: function (data) { + + if (data.error) { + graphBodyDIV.remove(); + errorBodyDIV.show(); + visContainerDIV.unblock(); + + } else { + graphBodyDIV.show(); + errorBodyDIV.remove(); + temporalGraphProcessor.initiateTemporalGraphRenderProcess(graphContainer, data); + visContainerDIV.unblock(); + } + } + }); + +} + +temporalGraphProcessor = { + + initiateTemporalGraphRenderProcess: function(givenGraphContainer, jsonData) { + + this.dataTableParams = { + searchBarParentContainerDIVClass : "searchbar", + paginationContainerDIVClass : "paginatedtabs" + }; + + + /* + * initial display of the grid when the page loads + * */ + init(givenGraphContainer); + + /* + * render the temporal graph per the sent content. + * */ + loadData(jsonData, this.dataTableParams); + + /* + * This will make sure that top 3 entities are selected by default when the page loads. + */ + $.each($("input." + entityCheckboxSelectorDOMClass), function(index, checkbox) { + + if (index > 2) { + return false; + } + + $(this).attr('checked', true); + + var checkboxValue = $(this).attr("value"); + var entity = labelToEntityRecord[checkboxValue]; + + performEntityCheckboxSelectedActions(entity, checkboxValue, $(this)); + + performEntityCheckboxClickedRedrawActions(); + + }); + + } + } \ No newline at end of file diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/entitycomparison/cached/TemporalGrantVisualizationRequestHandler.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/entitycomparison/cached/TemporalGrantVisualizationRequestHandler.java index b2918425..3170dc8b 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/entitycomparison/cached/TemporalGrantVisualizationRequestHandler.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/entitycomparison/cached/TemporalGrantVisualizationRequestHandler.java @@ -1,332 +1,354 @@ -/* $This file is distributed under the terms of the license in /doc/license.txt$ */ - -package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.entitycomparison.cached; - -import java.util.ArrayList; -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.StringEscapeUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; - -import com.google.gson.Gson; -import com.hp.hpl.jena.query.Dataset; -import com.hp.hpl.jena.rdf.model.Model; - -import edu.cornell.mannlib.vitro.webapp.beans.Portal; -import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; -import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues; -import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues; -import edu.cornell.mannlib.vitro.webapp.controller.visualization.freemarker.DataVisualizationController; -import edu.cornell.mannlib.vitro.webapp.controller.visualization.freemarker.VisualizationFrameworkConstants; -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.freemarker.entitycomparison.EntityComparisonUtilityFunctions; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.Activity; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.ConstructedModelTracker; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.Entity; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.JsonObject; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.SubEntity; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.SelectOnModelUtilities; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.UtilityFunctions; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.VisualizationRequestHandler; - - -public class TemporalGrantVisualizationRequestHandler implements - VisualizationRequestHandler { - - @Override - public ResponseValues generateStandardVisualization( - VitroRequest vitroRequest, Log log, Dataset dataset) - throws MalformedQueryParametersException { - - String entityURI = vitroRequest - .getParameter(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY); - - if (StringUtils.isBlank(entityURI)) { - - entityURI = EntityComparisonUtilityFunctions - .getStaffProvidedOrComputedHighestLevelOrganization( - log, - dataset, - vitroRequest); - - } - - System.out.println("current models in the system are"); - for (Map.Entry entry : ConstructedModelTracker.getAllModels().entrySet()) { - System.out.println(entry.getKey() + " -> " + entry.getValue().size()); - } - - return prepareStandaloneMarkupResponse(vitroRequest, entityURI); - } - - @Override - public Map generateDataVisualization( - VitroRequest vitroRequest, Log log, Dataset dataset) - throws MalformedQueryParametersException { - - String entityURI = vitroRequest - .getParameter(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY); - - /* - * This will provide the data in json format mainly used for standalone temporal vis. - * */ - if (VisualizationFrameworkConstants.TEMPORAL_GRAPH_JSON_DATA_VIS_MODE - .equalsIgnoreCase(vitroRequest - .getParameter(VisualizationFrameworkConstants.VIS_MODE_KEY))) { - - if (StringUtils.isNotBlank(entityURI)) { - - return getSubjectEntityAndGenerateDataResponse( - vitroRequest, - log, - dataset, - entityURI, - EntityComparisonConstants.DataVisMode.JSON); - } else { - - return getSubjectEntityAndGenerateDataResponse( - vitroRequest, - log, - dataset, - EntityComparisonUtilityFunctions - .getStaffProvidedOrComputedHighestLevelOrganization( - log, - dataset, - vitroRequest), - EntityComparisonConstants.DataVisMode.JSON); - } - - } else { - /* - * This provides csv download files for the content in the tables. - * */ - return getSubjectEntityAndGenerateDataResponse( - vitroRequest, - log, - dataset, - entityURI, - EntityComparisonConstants.DataVisMode.CSV); - } - } - - private Map prepareDataErrorResponse() { - - String outputFileName = "no-organization_grants-per-year.csv"; - - Map fileData = new HashMap(); - - fileData.put(DataVisualizationController.FILE_NAME_KEY, - outputFileName); - fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY, - "application/octet-stream"); - fileData.put(DataVisualizationController.FILE_CONTENT_KEY, ""); - return fileData; - } - - @Override - public Object generateAjaxVisualization(VitroRequest vitroRequest, Log log, - Dataset dataset) throws MalformedQueryParametersException { - - throw new UnsupportedOperationException("Entity Grant Count " - + "does not provide Ajax response."); - } - - private Map getSubjectEntityAndGenerateDataResponse( - VitroRequest vitroRequest, Log log, Dataset dataset, - String subjectEntityURI, EntityComparisonConstants.DataVisMode visMode) - throws MalformedQueryParametersException { - - Entity organizationEntity = SelectOnModelUtilities - .getSubjectOrganizationHierarchy(dataset, subjectEntityURI); - - if (organizationEntity.getSubEntities() == null) { - - if (EntityComparisonConstants.DataVisMode.JSON.equals(visMode)) { - return prepareStandaloneDataErrorResponse(); - } else { - return prepareDataErrorResponse(); - } - } - - Map grantURIForAssociatedPeopleToVO = new HashMap(); - Map allGrantURIToVO = new HashMap(); - - allGrantURIToVO = SelectOnModelUtilities.getGrantsForAllSubOrganizations(dataset, organizationEntity); - - if (allGrantURIToVO.isEmpty() && grantURIForAssociatedPeopleToVO.isEmpty()) { - - if (EntityComparisonConstants.DataVisMode.JSON.equals(visMode)) { - return prepareStandaloneDataErrorResponse(); - } else { - return prepareDataErrorResponse(); - } - - } else { - - if (EntityComparisonConstants.DataVisMode.JSON.equals(visMode)) { - return prepareStandaloneDataResponse(vitroRequest, organizationEntity); - } else { - return prepareDataResponse(organizationEntity); - } - } - } - - private Map prepareStandaloneDataErrorResponse() { - - Map fileData = new HashMap(); - - fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY, - "application/octet-stream"); - fileData.put(DataVisualizationController.FILE_CONTENT_KEY, - "{\"error\" : \"No Grants for this Organization found in VIVO.\"}"); - return fileData; - } - - - private Map prepareStandaloneDataResponse( - VitroRequest vitroRequest, - Entity entity) { - - Map fileData = new HashMap(); - - fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY, - "application/octet-stream"); - fileData.put(DataVisualizationController.FILE_CONTENT_KEY, - writeGrantsOverTimeJSON(vitroRequest, - entity.getSubEntities())); - return fileData; - } - - /** - * Provides response when json file containing the grant count over the - * years is requested. - * - * @param entity - * @param subentities - * @param subOrganizationTypesResult - */ - private Map prepareDataResponse(Entity entity) { - - String entityLabel = entity.getEntityLabel(); - - /* - * To make sure that null/empty records for entity names do not cause any mischief. - * */ - if (StringUtils.isBlank(entityLabel)) { - entityLabel = "no-organization"; - } - - String outputFileName = UtilityFunctions.slugify(entityLabel) - + "_grants-per-year" + ".csv"; - - - Map fileData = new HashMap(); - - fileData.put(DataVisualizationController.FILE_NAME_KEY, - outputFileName); - fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY, - "application/octet-stream"); - fileData.put(DataVisualizationController.FILE_CONTENT_KEY, - getEntityGrantsPerYearCSVContent(entity)); - return fileData; - } - - - private TemplateResponseValues prepareStandaloneMarkupResponse(VitroRequest vreq, - String entityURI) { - - Portal portal = vreq.getPortal(); - String standaloneTemplate = "entityComparisonOnGrantsStandalone.ftl"; - - String organizationLabel = EntityComparisonUtilityFunctions.getEntityLabelFromDAO(vreq, - entityURI); - - Map body = new HashMap(); - body.put("portalBean", portal); - body.put("title", organizationLabel + " - Temporal Graph Visualization"); - body.put("organizationURI", entityURI); - body.put("organizationLabel", organizationLabel); - - return new TemplateResponseValues(standaloneTemplate, body); - } - - /** - * Function to generate a json file for year <-> grant count mapping. - * @param vreq - * @param subentities - * @param subOrganizationTypesResult - */ - private String writeGrantsOverTimeJSON(VitroRequest vreq, - Set subentities) { - - Gson json = new Gson(); - Set subEntitiesJson = new HashSet(); - - for (SubEntity subentity : subentities) { - JsonObject entityJson = new JsonObject( - subentity.getIndividualLabel()); - - List> yearGrantCount = new ArrayList>(); - - for (Map.Entry grantEntry : UtilityFunctions - .getYearToActivityCount(subentity.getActivities()) - .entrySet()) { - - List currentGrantYear = new ArrayList(); - if (grantEntry.getKey().equals( - VOConstants.DEFAULT_GRANT_YEAR)) { - currentGrantYear.add(-1); - } else { - currentGrantYear.add(Integer.parseInt(grantEntry.getKey())); - } - - currentGrantYear.add(grantEntry.getValue()); - yearGrantCount.add(currentGrantYear); - } - - entityJson.setYearToActivityCount(yearGrantCount); - - entityJson.setOrganizationTypes(subentity.getEntityTypeLabels()); - - entityJson.setEntityURI(subentity.getIndividualURI()); - - if (subentity.getEntityClass().equals(VOConstants.EntityClassType.PERSON)) { - entityJson.setVisMode("PERSON"); - } else if (subentity.getEntityClass().equals(VOConstants.EntityClassType.ORGANIZATION)) { - entityJson.setVisMode("ORGANIZATION"); - } - - subEntitiesJson.add(entityJson); - } - - return json.toJson(subEntitiesJson); - } - - private String getEntityGrantsPerYearCSVContent(Entity entity) { - - StringBuilder csvFileContent = new StringBuilder(); - - csvFileContent.append("Entity Name, Grant Count, Entity Type\n"); - - for (SubEntity subEntity : entity.getSubEntities()) { - - csvFileContent.append(StringEscapeUtils.escapeCsv(subEntity.getIndividualLabel())); - csvFileContent.append(", "); - csvFileContent.append(subEntity.getActivities().size()); - csvFileContent.append(", "); - - String allTypes = StringUtils.join(subEntity.getEntityTypeLabels(), "; "); - - csvFileContent.append(StringEscapeUtils.escapeCsv(allTypes)); - csvFileContent.append("\n"); - } - - return csvFileContent.toString(); - } -} +/* $This file is distributed under the terms of the license in /doc/license.txt$ */ + +package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.entitycomparison.cached; + +import java.util.ArrayList; +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.StringEscapeUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; + +import com.google.gson.Gson; +import com.hp.hpl.jena.query.Dataset; +import com.hp.hpl.jena.rdf.model.Model; + +import edu.cornell.mannlib.vitro.webapp.beans.Portal; +import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; +import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues; +import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues; +import edu.cornell.mannlib.vitro.webapp.controller.visualization.freemarker.DataVisualizationController; +import edu.cornell.mannlib.vitro.webapp.controller.visualization.freemarker.VisualizationFrameworkConstants; +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.freemarker.entitycomparison.EntityComparisonUtilityFunctions; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.Activity; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.ConstructedModelTracker; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.Entity; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.JsonObject; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.SubEntity; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.SelectOnModelUtilities; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.UtilityFunctions; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.VisualizationRequestHandler; + + +public class TemporalGrantVisualizationRequestHandler implements + VisualizationRequestHandler { + + @Override + public ResponseValues generateStandardVisualization( + VitroRequest vitroRequest, Log log, Dataset dataset) + throws MalformedQueryParametersException { + + String entityURI = vitroRequest + .getParameter(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY); + + if (StringUtils.isBlank(entityURI)) { + + entityURI = EntityComparisonUtilityFunctions + .getStaffProvidedOrComputedHighestLevelOrganization( + log, + dataset, + vitroRequest); + + } + + System.out.println("current models in the system are"); + for (Map.Entry entry : ConstructedModelTracker.getAllModels().entrySet()) { + System.out.println(entry.getKey() + " -> " + entry.getValue().size()); + } + + return prepareStandaloneMarkupResponse(vitroRequest, entityURI); + } + + @Override + public Map generateDataVisualization( + VitroRequest vitroRequest, Log log, Dataset dataset) + throws MalformedQueryParametersException { + + String entityURI = vitroRequest + .getParameter(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY); + + /* + * This will provide the data in json format mainly used for standalone temporal vis. + * */ + if (VisualizationFrameworkConstants.TEMPORAL_GRAPH_JSON_DATA_VIS_MODE + .equalsIgnoreCase(vitroRequest + .getParameter(VisualizationFrameworkConstants.VIS_MODE_KEY))) { + + if (StringUtils.isNotBlank(entityURI)) { + + return getSubjectEntityAndGenerateDataResponse( + vitroRequest, + log, + dataset, + entityURI, + EntityComparisonConstants.DataVisMode.JSON); + } else { + + return getSubjectEntityAndGenerateDataResponse( + vitroRequest, + log, + dataset, + EntityComparisonUtilityFunctions + .getStaffProvidedOrComputedHighestLevelOrganization( + log, + dataset, + vitroRequest), + EntityComparisonConstants.DataVisMode.JSON); + } + + } else { + /* + * This provides csv download files for the content in the tables. + * */ + return getSubjectEntityAndGenerateDataResponse( + vitroRequest, + log, + dataset, + entityURI, + EntityComparisonConstants.DataVisMode.CSV); + } + } + + private Map prepareDataErrorResponse() { + + String outputFileName = "no-organization_grants-per-year.csv"; + + Map fileData = new HashMap(); + + fileData.put(DataVisualizationController.FILE_NAME_KEY, + outputFileName); + fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY, + "application/octet-stream"); + fileData.put(DataVisualizationController.FILE_CONTENT_KEY, ""); + return fileData; + } + + @Override + public Object generateAjaxVisualization(VitroRequest vitroRequest, Log log, + Dataset dataset) throws MalformedQueryParametersException { + + throw new UnsupportedOperationException("Entity Grant Count " + + "does not provide Ajax response."); + } + + private Map getSubjectEntityAndGenerateDataResponse( + VitroRequest vitroRequest, Log log, Dataset dataset, + String subjectEntityURI, EntityComparisonConstants.DataVisMode visMode) + throws MalformedQueryParametersException { + + Entity organizationEntity = SelectOnModelUtilities + .getSubjectOrganizationHierarchy(dataset, subjectEntityURI); + + if (organizationEntity.getSubEntities() == null) { + + if (EntityComparisonConstants.DataVisMode.JSON.equals(visMode)) { + return prepareStandaloneDataErrorResponse(); + } else { + return prepareDataErrorResponse(); + } + } + + Map grantURIForAssociatedPeopleToVO = new HashMap(); + Map allGrantURIToVO = new HashMap(); + +/** + * TODO: Change this to use DataSet when an optimum solution is reached. Currently grant constructs are causing + * endless wait times on a large dataset like UFl. When I tried to add all the datasets manually to the Datasource + * it responded in an order of magnitude higher than with just the defaultOntModel. + * Brian Lowe is looking into this weird behavior see http://issues.library.cornell.edu/browse/NIHVIVO-2275 + */ +// DataSource dataSource = DatasetFactory.create(); +// dataSource.setDefaultModel(vitroRequest.getJenaOntModel()); + + allGrantURIToVO = SelectOnModelUtilities.getGrantsForAllSubOrganizations(dataset, organizationEntity); + + Entity organizationWithAssociatedPeople = SelectOnModelUtilities + .getSubjectOrganizationAssociatedPeople(dataset, subjectEntityURI); + + if (organizationWithAssociatedPeople.getSubEntities() != null) { + + grantURIForAssociatedPeopleToVO = SelectOnModelUtilities + .getPublicationsForAssociatedPeople(dataset, organizationWithAssociatedPeople.getSubEntities()); + + organizationEntity = EntityComparisonUtilityFunctions.mergeEntityIfShareSameURI( + organizationEntity, + organizationWithAssociatedPeople); + } + + if (allGrantURIToVO.isEmpty() && grantURIForAssociatedPeopleToVO.isEmpty()) { + + if (EntityComparisonConstants.DataVisMode.JSON.equals(visMode)) { + return prepareStandaloneDataErrorResponse(); + } else { + return prepareDataErrorResponse(); + } + + } else { + + if (EntityComparisonConstants.DataVisMode.JSON.equals(visMode)) { + return prepareStandaloneDataResponse(vitroRequest, organizationEntity); + } else { + return prepareDataResponse(organizationEntity); + } + } + } + + private Map prepareStandaloneDataErrorResponse() { + + Map fileData = new HashMap(); + + fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY, + "application/octet-stream"); + fileData.put(DataVisualizationController.FILE_CONTENT_KEY, + "{\"error\" : \"No Grants for this Organization found in VIVO.\"}"); + return fileData; + } + + + private Map prepareStandaloneDataResponse( + VitroRequest vitroRequest, + Entity entity) { + + Map fileData = new HashMap(); + + fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY, + "application/octet-stream"); + fileData.put(DataVisualizationController.FILE_CONTENT_KEY, + writeGrantsOverTimeJSON(vitroRequest, + entity.getSubEntities())); + return fileData; + } + + /** + * Provides response when json file containing the grant count over the + * years is requested. + * + * @param entity + * @param subentities + * @param subOrganizationTypesResult + */ + private Map prepareDataResponse(Entity entity) { + + String entityLabel = entity.getEntityLabel(); + + /* + * To make sure that null/empty records for entity names do not cause any mischief. + * */ + if (StringUtils.isBlank(entityLabel)) { + entityLabel = "no-organization"; + } + + String outputFileName = UtilityFunctions.slugify(entityLabel) + + "_grants-per-year" + ".csv"; + + + Map fileData = new HashMap(); + + fileData.put(DataVisualizationController.FILE_NAME_KEY, + outputFileName); + fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY, + "application/octet-stream"); + fileData.put(DataVisualizationController.FILE_CONTENT_KEY, + getEntityGrantsPerYearCSVContent(entity)); + return fileData; + } + + + private TemplateResponseValues prepareStandaloneMarkupResponse(VitroRequest vreq, + String entityURI) { + + Portal portal = vreq.getPortal(); + String standaloneTemplate = "entityComparisonOnGrantsStandalone.ftl"; + + String organizationLabel = EntityComparisonUtilityFunctions.getEntityLabelFromDAO(vreq, + entityURI); + + Map body = new HashMap(); + body.put("portalBean", portal); + body.put("title", organizationLabel + " - Temporal Graph Visualization"); + body.put("organizationURI", entityURI); + body.put("organizationLabel", organizationLabel); + + return new TemplateResponseValues(standaloneTemplate, body); + } + + /** + * Function to generate a json file for year <-> grant count mapping. + * @param vreq + * @param subentities + * @param subOrganizationTypesResult + */ + private String writeGrantsOverTimeJSON(VitroRequest vreq, + Set subentities) { + + Gson json = new Gson(); + Set subEntitiesJson = new HashSet(); + + for (SubEntity subentity : subentities) { + JsonObject entityJson = new JsonObject( + subentity.getIndividualLabel()); + + List> yearGrantCount = new ArrayList>(); + + for (Map.Entry grantEntry : UtilityFunctions + .getYearToActivityCount(subentity.getActivities()) + .entrySet()) { + + List currentGrantYear = new ArrayList(); + if (grantEntry.getKey().equals( + VOConstants.DEFAULT_GRANT_YEAR)) { + currentGrantYear.add(-1); + } else { + currentGrantYear.add(Integer.parseInt(grantEntry.getKey())); + } + + currentGrantYear.add(grantEntry.getValue()); + yearGrantCount.add(currentGrantYear); + } + + entityJson.setYearToActivityCount(yearGrantCount); + + entityJson.setOrganizationTypes(subentity.getEntityTypeLabels()); + + entityJson.setEntityURI(subentity.getIndividualURI()); + + if (subentity.getEntityClass().equals(VOConstants.EntityClassType.PERSON)) { + entityJson.setVisMode("PERSON"); + } else if (subentity.getEntityClass().equals(VOConstants.EntityClassType.ORGANIZATION)) { + entityJson.setVisMode("ORGANIZATION"); + } + + subEntitiesJson.add(entityJson); + } + + return json.toJson(subEntitiesJson); + } + + private String getEntityGrantsPerYearCSVContent(Entity entity) { + + StringBuilder csvFileContent = new StringBuilder(); + + csvFileContent.append("Entity Name, Grant Count, Entity Type\n"); + + for (SubEntity subEntity : entity.getSubEntities()) { + + csvFileContent.append(StringEscapeUtils.escapeCsv(subEntity.getIndividualLabel())); + csvFileContent.append(", "); + csvFileContent.append(subEntity.getActivities().size()); + csvFileContent.append(", "); + + String allTypes = StringUtils.join(subEntity.getEntityTypeLabels(), "; "); + + csvFileContent.append(StringEscapeUtils.escapeCsv(allTypes)); + csvFileContent.append("\n"); + } + + return csvFileContent.toString(); + } +} diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/entitycomparison/cached/TemporalPublicationVisualizationRequestHandler.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/entitycomparison/cached/TemporalPublicationVisualizationRequestHandler.java index 686a0d1d..b478310b 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/entitycomparison/cached/TemporalPublicationVisualizationRequestHandler.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/entitycomparison/cached/TemporalPublicationVisualizationRequestHandler.java @@ -1,350 +1,347 @@ -/* $This file is distributed under the terms of the license in /doc/license.txt$ */ - -package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.entitycomparison.cached; - -import java.util.ArrayList; -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.StringEscapeUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; - -import com.google.gson.Gson; -import com.hp.hpl.jena.query.Dataset; -import com.hp.hpl.jena.rdf.model.Model; - -import edu.cornell.mannlib.vitro.webapp.beans.Portal; -import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; -import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues; -import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues; -import edu.cornell.mannlib.vitro.webapp.controller.visualization.freemarker.DataVisualizationController; -import edu.cornell.mannlib.vitro.webapp.controller.visualization.freemarker.VisualizationFrameworkConstants; -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.freemarker.entitycomparison.EntityComparisonUtilityFunctions; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.Activity; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.ConstructedModelTracker; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.Entity; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.JsonObject; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.SubEntity; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.SelectOnModelUtilities; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.UtilityFunctions; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.VisualizationRequestHandler; - -public class TemporalPublicationVisualizationRequestHandler implements - VisualizationRequestHandler { - - @Override - public ResponseValues generateStandardVisualization( - VitroRequest vitroRequest, Log log, Dataset dataset) - throws MalformedQueryParametersException { - - - String entityURI = vitroRequest - .getParameter(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY); - - if (StringUtils.isBlank(entityURI)) { - - entityURI = EntityComparisonUtilityFunctions - .getStaffProvidedOrComputedHighestLevelOrganization( - log, - dataset, - vitroRequest); - - } - - - System.out.println("current models in the system are"); - for (Map.Entry entry : ConstructedModelTracker.getAllModels().entrySet()) { - System.out.println(entry.getKey() + " -> " + entry.getValue().size()); - } - - return prepareStandaloneMarkupResponse(vitroRequest, entityURI); - } - - private Map getSubjectEntityAndGenerateDataResponse( - VitroRequest vitroRequest, Log log, Dataset dataset, - String subjectEntityURI, EntityComparisonConstants.DataVisMode visMode) - throws MalformedQueryParametersException { - - - Entity organizationEntity = SelectOnModelUtilities - .getSubjectOrganizationHierarchy(dataset, subjectEntityURI); - - if (organizationEntity.getSubEntities() == null) { - - if (EntityComparisonConstants.DataVisMode.JSON.equals(visMode)) { - return prepareStandaloneDataErrorResponse(); - } else { - return prepareDataErrorResponse(); - } - - } - - Map documentURIForAssociatedPeopleTOVO = new HashMap(); - Map allDocumentURIToVOs = new HashMap(); - - allDocumentURIToVOs = SelectOnModelUtilities.getPublicationsForAllSubOrganizations(dataset, organizationEntity); - - Entity organizationWithAssociatedPeople = SelectOnModelUtilities - .getSubjectOrganizationAssociatedPeople(dataset, subjectEntityURI); - - - if (organizationWithAssociatedPeople.getSubEntities() != null) { - - documentURIForAssociatedPeopleTOVO = SelectOnModelUtilities - .getPublicationsForAssociatedPeople(dataset, organizationWithAssociatedPeople.getSubEntities()); - - organizationEntity = EntityComparisonUtilityFunctions.mergeEntityIfShareSameURI( - organizationEntity, - organizationWithAssociatedPeople); - } - - if (allDocumentURIToVOs.isEmpty() && documentURIForAssociatedPeopleTOVO.isEmpty()) { - - if (EntityComparisonConstants.DataVisMode.JSON.equals(visMode)) { - return prepareStandaloneDataErrorResponse(); - } else { - return prepareDataErrorResponse(); - } - - } else { - - if (EntityComparisonConstants.DataVisMode.JSON.equals(visMode)) { - return prepareStandaloneDataResponse(vitroRequest, organizationEntity); - } else { - return prepareDataResponse(organizationEntity); - } - } - } - - /** - * Provides response when json file containing the publication count over the - * years is requested. - * - * @param entity - * @param subentities - * @param subOrganizationTypesResult - */ - private Map prepareDataResponse(Entity entity) { - - String entityLabel = entity.getEntityLabel(); - - /* - * To make sure that null/empty records for entity names do not cause any mischief. - * */ - if (StringUtils.isBlank(entityLabel)) { - entityLabel = "no-organization"; - } - - String outputFileName = UtilityFunctions.slugify(entityLabel) - + "_publications-per-year" + ".csv"; - - - Map fileData = new HashMap(); - - fileData.put(DataVisualizationController.FILE_NAME_KEY, - outputFileName); - fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY, - "application/octet-stream"); - fileData.put(DataVisualizationController.FILE_CONTENT_KEY, - getEntityPublicationsPerYearCSVContent(entity)); - return fileData; - } - - private Map prepareDataErrorResponse() { - - String outputFileName = "no-organization_publications-per-year.csv"; - - Map fileData = new HashMap(); - - fileData.put(DataVisualizationController.FILE_NAME_KEY, - outputFileName); - fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY, - "application/octet-stream"); - fileData.put(DataVisualizationController.FILE_CONTENT_KEY, ""); - return fileData; - } - - private Map prepareStandaloneDataErrorResponse() { - - Map fileData = new HashMap(); - - fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY, - "application/octet-stream"); - fileData.put(DataVisualizationController.FILE_CONTENT_KEY, - "{\"error\" : \"No Publications for this Organization found in VIVO.\"}"); - return fileData; - } - - @Override - public Map generateDataVisualization( - VitroRequest vitroRequest, Log log, Dataset dataset) - throws MalformedQueryParametersException { - - String entityURI = vitroRequest - .getParameter(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY); - - /* - * This will provide the data in json format mainly used for standalone tmeporal vis. - * */ - if (VisualizationFrameworkConstants.TEMPORAL_GRAPH_JSON_DATA_VIS_MODE - .equalsIgnoreCase(vitroRequest.getParameter( - VisualizationFrameworkConstants.VIS_MODE_KEY))) { - - if (StringUtils.isNotBlank(entityURI)) { - - return getSubjectEntityAndGenerateDataResponse( - vitroRequest, - log, - dataset, - entityURI, - EntityComparisonConstants.DataVisMode.JSON); - } else { - - return getSubjectEntityAndGenerateDataResponse( - vitroRequest, - log, - dataset, - EntityComparisonUtilityFunctions - .getStaffProvidedOrComputedHighestLevelOrganization( - log, - dataset, - vitroRequest), - EntityComparisonConstants.DataVisMode.JSON); - } - - } else { - /* - * This provides csv download files for the content in the tables. - * */ - - return getSubjectEntityAndGenerateDataResponse( - vitroRequest, - log, - dataset, - entityURI, - EntityComparisonConstants.DataVisMode.CSV); - - } - - } - - - @Override - public Object generateAjaxVisualization(VitroRequest vitroRequest, Log log, - Dataset dataset) throws MalformedQueryParametersException { - throw new UnsupportedOperationException("Entity Pub Count does not provide Ajax Response."); - } - - private Map prepareStandaloneDataResponse( - VitroRequest vitroRequest, - Entity entity) { - - Map fileData = new HashMap(); - - fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY, - "application/octet-stream"); - fileData.put(DataVisualizationController.FILE_CONTENT_KEY, - writePublicationsOverTimeJSON(vitroRequest, - entity.getSubEntities())); - return fileData; - } - - private TemplateResponseValues prepareStandaloneMarkupResponse(VitroRequest vreq, - String entityURI) { - - Portal portal = vreq.getPortal(); - String standaloneTemplate = "entityComparisonOnPublicationsStandalone.ftl"; - - String organizationLabel = EntityComparisonUtilityFunctions - .getEntityLabelFromDAO(vreq, - entityURI); - - Map body = new HashMap(); - body.put("portalBean", portal); - body.put("title", organizationLabel + " - Temporal Graph Visualization"); - body.put("organizationURI", entityURI); - body.put("organizationLabel", organizationLabel); - - return new TemplateResponseValues(standaloneTemplate, body); - } - - /** - * Function to generate a json file for year <-> publication count mapping. - * @param vreq - * @param subentities - * @param subOrganizationTypesResult - */ - private String writePublicationsOverTimeJSON(VitroRequest vreq, - Set subentities) { - - Gson json = new Gson(); - Set subEntitiesJson = new HashSet(); - - for (SubEntity subentity : subentities) { - - System.out.println("in write json current sub entity " + subentity.getIndividualLabel()); - - JsonObject entityJson = new JsonObject( - subentity.getIndividualLabel()); - - List> yearPubCount = new ArrayList>(); - - for (Map.Entry pubEntry : UtilityFunctions - .getYearToActivityCount(subentity.getActivities()) - .entrySet()) { - - List currentPubYear = new ArrayList(); - if (pubEntry.getKey().equals(VOConstants.DEFAULT_PUBLICATION_YEAR)) { - currentPubYear.add(-1); - } else { - currentPubYear.add(Integer.parseInt(pubEntry.getKey())); - } - - currentPubYear.add(pubEntry.getValue()); - yearPubCount.add(currentPubYear); - } - - entityJson.setYearToActivityCount(yearPubCount); - - entityJson.setOrganizationTypes(subentity.getEntityTypeLabels()); - - entityJson.setEntityURI(subentity.getIndividualURI()); - - if (subentity.getEntityClass().equals(VOConstants.EntityClassType.PERSON)) { - entityJson.setVisMode("PERSON"); - } else if (subentity.getEntityClass().equals(VOConstants.EntityClassType.ORGANIZATION)) { - entityJson.setVisMode("ORGANIZATION"); - } - - subEntitiesJson.add(entityJson); - } - return json.toJson(subEntitiesJson); - } - - private String getEntityPublicationsPerYearCSVContent(Entity entity) { - - StringBuilder csvFileContent = new StringBuilder(); - - csvFileContent.append("Entity Name, Publication Count, Entity Type\n"); - - for (SubEntity subEntity : entity.getSubEntities()) { - - csvFileContent.append(StringEscapeUtils.escapeCsv(subEntity.getIndividualLabel())); - csvFileContent.append(", "); - csvFileContent.append(subEntity.getActivities().size()); - csvFileContent.append(", "); - - String allTypes = StringUtils.join(subEntity.getEntityTypeLabels(), "; "); - - csvFileContent.append(StringEscapeUtils.escapeCsv(allTypes)); - csvFileContent.append("\n"); - } - return csvFileContent.toString(); - } +/* $This file is distributed under the terms of the license in /doc/license.txt$ */ + +package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.entitycomparison.cached; + +import java.util.ArrayList; +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.StringEscapeUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; + +import com.google.gson.Gson; +import com.hp.hpl.jena.query.Dataset; +import com.hp.hpl.jena.rdf.model.Model; + +import edu.cornell.mannlib.vitro.webapp.beans.Portal; +import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; +import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues; +import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues; +import edu.cornell.mannlib.vitro.webapp.controller.visualization.freemarker.DataVisualizationController; +import edu.cornell.mannlib.vitro.webapp.controller.visualization.freemarker.VisualizationFrameworkConstants; +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.freemarker.entitycomparison.EntityComparisonUtilityFunctions; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.Activity; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.ConstructedModelTracker; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.Entity; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.JsonObject; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.SubEntity; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.SelectOnModelUtilities; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.UtilityFunctions; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.VisualizationRequestHandler; + +public class TemporalPublicationVisualizationRequestHandler implements + VisualizationRequestHandler { + + @Override + public ResponseValues generateStandardVisualization( + VitroRequest vitroRequest, Log log, Dataset dataset) + throws MalformedQueryParametersException { + + + String entityURI = vitroRequest + .getParameter(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY); + + if (StringUtils.isBlank(entityURI)) { + + entityURI = EntityComparisonUtilityFunctions + .getStaffProvidedOrComputedHighestLevelOrganization( + log, + dataset, + vitroRequest); + + } + + + System.out.println("current models in the system are"); + for (Map.Entry entry : ConstructedModelTracker.getAllModels().entrySet()) { + System.out.println(entry.getKey() + " -> " + entry.getValue().size()); + } + + return prepareStandaloneMarkupResponse(vitroRequest, entityURI); + } + + private Map getSubjectEntityAndGenerateDataResponse( + VitroRequest vitroRequest, Log log, Dataset dataset, + String subjectEntityURI, EntityComparisonConstants.DataVisMode visMode) + throws MalformedQueryParametersException { + + + Entity organizationEntity = SelectOnModelUtilities + .getSubjectOrganizationHierarchy(dataset, subjectEntityURI); + + if (organizationEntity.getSubEntities() == null) { + + if (EntityComparisonConstants.DataVisMode.JSON.equals(visMode)) { + return prepareStandaloneDataErrorResponse(); + } else { + return prepareDataErrorResponse(); + } + } + + Map documentURIForAssociatedPeopleTOVO = new HashMap(); + Map allDocumentURIToVOs = new HashMap(); + + allDocumentURIToVOs = SelectOnModelUtilities.getPublicationsForAllSubOrganizations(dataset, organizationEntity); + + Entity organizationWithAssociatedPeople = SelectOnModelUtilities + .getSubjectOrganizationAssociatedPeople(dataset, subjectEntityURI); + + + if (organizationWithAssociatedPeople.getSubEntities() != null) { + + documentURIForAssociatedPeopleTOVO = SelectOnModelUtilities + .getPublicationsForAssociatedPeople(dataset, organizationWithAssociatedPeople.getSubEntities()); + + organizationEntity = EntityComparisonUtilityFunctions.mergeEntityIfShareSameURI( + organizationEntity, + organizationWithAssociatedPeople); + } + + if (allDocumentURIToVOs.isEmpty() && documentURIForAssociatedPeopleTOVO.isEmpty()) { + + if (EntityComparisonConstants.DataVisMode.JSON.equals(visMode)) { + return prepareStandaloneDataErrorResponse(); + } else { + return prepareDataErrorResponse(); + } + + } else { + + if (EntityComparisonConstants.DataVisMode.JSON.equals(visMode)) { + return prepareStandaloneDataResponse(vitroRequest, organizationEntity); + } else { + return prepareDataResponse(organizationEntity); + } + } + } + + /** + * Provides response when json file containing the publication count over the + * years is requested. + * + * @param entity + * @param subentities + * @param subOrganizationTypesResult + */ + private Map prepareDataResponse(Entity entity) { + + String entityLabel = entity.getEntityLabel(); + + /* + * To make sure that null/empty records for entity names do not cause any mischief. + * */ + if (StringUtils.isBlank(entityLabel)) { + entityLabel = "no-organization"; + } + + String outputFileName = UtilityFunctions.slugify(entityLabel) + + "_publications-per-year" + ".csv"; + + + Map fileData = new HashMap(); + + fileData.put(DataVisualizationController.FILE_NAME_KEY, + outputFileName); + fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY, + "application/octet-stream"); + fileData.put(DataVisualizationController.FILE_CONTENT_KEY, + getEntityPublicationsPerYearCSVContent(entity)); + return fileData; + } + + private Map prepareDataErrorResponse() { + + String outputFileName = "no-organization_publications-per-year.csv"; + + Map fileData = new HashMap(); + + fileData.put(DataVisualizationController.FILE_NAME_KEY, + outputFileName); + fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY, + "application/octet-stream"); + fileData.put(DataVisualizationController.FILE_CONTENT_KEY, ""); + return fileData; + } + + private Map prepareStandaloneDataErrorResponse() { + + Map fileData = new HashMap(); + + fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY, + "application/octet-stream"); + fileData.put(DataVisualizationController.FILE_CONTENT_KEY, + "{\"error\" : \"No Publications for this Organization found in VIVO.\"}"); + return fileData; + } + + @Override + public Map generateDataVisualization( + VitroRequest vitroRequest, Log log, Dataset dataset) + throws MalformedQueryParametersException { + + String entityURI = vitroRequest + .getParameter(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY); + + /* + * This will provide the data in json format mainly used for standalone tmeporal vis. + * */ + if (VisualizationFrameworkConstants.TEMPORAL_GRAPH_JSON_DATA_VIS_MODE + .equalsIgnoreCase(vitroRequest.getParameter( + VisualizationFrameworkConstants.VIS_MODE_KEY))) { + + if (StringUtils.isNotBlank(entityURI)) { + + return getSubjectEntityAndGenerateDataResponse( + vitroRequest, + log, + dataset, + entityURI, + EntityComparisonConstants.DataVisMode.JSON); + } else { + + return getSubjectEntityAndGenerateDataResponse( + vitroRequest, + log, + dataset, + EntityComparisonUtilityFunctions + .getStaffProvidedOrComputedHighestLevelOrganization( + log, + dataset, + vitroRequest), + EntityComparisonConstants.DataVisMode.JSON); + } + + } else { + /* + * This provides csv download files for the content in the tables. + * */ + + return getSubjectEntityAndGenerateDataResponse( + vitroRequest, + log, + dataset, + entityURI, + EntityComparisonConstants.DataVisMode.CSV); + + } + + } + + + @Override + public Object generateAjaxVisualization(VitroRequest vitroRequest, Log log, + Dataset dataset) throws MalformedQueryParametersException { + throw new UnsupportedOperationException("Entity Pub Count does not provide Ajax Response."); + } + + private Map prepareStandaloneDataResponse( + VitroRequest vitroRequest, + Entity entity) { + + Map fileData = new HashMap(); + + fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY, + "application/octet-stream"); + fileData.put(DataVisualizationController.FILE_CONTENT_KEY, + writePublicationsOverTimeJSON(vitroRequest, + entity.getSubEntities())); + return fileData; + } + + private TemplateResponseValues prepareStandaloneMarkupResponse(VitroRequest vreq, + String entityURI) { + + Portal portal = vreq.getPortal(); + String standaloneTemplate = "entityComparisonOnPublicationsStandalone.ftl"; + + String organizationLabel = EntityComparisonUtilityFunctions + .getEntityLabelFromDAO(vreq, + entityURI); + + Map body = new HashMap(); + body.put("portalBean", portal); + body.put("title", organizationLabel + " - Temporal Graph Visualization"); + body.put("organizationURI", entityURI); + body.put("organizationLabel", organizationLabel); + + return new TemplateResponseValues(standaloneTemplate, body); + } + + /** + * Function to generate a json file for year <-> publication count mapping. + * @param vreq + * @param subentities + * @param subOrganizationTypesResult + */ + private String writePublicationsOverTimeJSON(VitroRequest vreq, + Set subentities) { + + Gson json = new Gson(); + Set subEntitiesJson = new HashSet(); + + for (SubEntity subentity : subentities) { + + JsonObject entityJson = new JsonObject( + subentity.getIndividualLabel()); + + List> yearPubCount = new ArrayList>(); + + for (Map.Entry pubEntry : UtilityFunctions + .getYearToActivityCount(subentity.getActivities()) + .entrySet()) { + + List currentPubYear = new ArrayList(); + if (pubEntry.getKey().equals(VOConstants.DEFAULT_PUBLICATION_YEAR)) { + currentPubYear.add(-1); + } else { + currentPubYear.add(Integer.parseInt(pubEntry.getKey())); + } + + currentPubYear.add(pubEntry.getValue()); + yearPubCount.add(currentPubYear); + } + + entityJson.setYearToActivityCount(yearPubCount); + + entityJson.setOrganizationTypes(subentity.getEntityTypeLabels()); + + entityJson.setEntityURI(subentity.getIndividualURI()); + + if (subentity.getEntityClass().equals(VOConstants.EntityClassType.PERSON)) { + entityJson.setVisMode("PERSON"); + } else if (subentity.getEntityClass().equals(VOConstants.EntityClassType.ORGANIZATION)) { + entityJson.setVisMode("ORGANIZATION"); + } + + subEntitiesJson.add(entityJson); + } + return json.toJson(subEntitiesJson); + } + + private String getEntityPublicationsPerYearCSVContent(Entity entity) { + + StringBuilder csvFileContent = new StringBuilder(); + + csvFileContent.append("Entity Name, Publication Count, Entity Type\n"); + + for (SubEntity subEntity : entity.getSubEntities()) { + + csvFileContent.append(StringEscapeUtils.escapeCsv(subEntity.getIndividualLabel())); + csvFileContent.append(", "); + csvFileContent.append(subEntity.getActivities().size()); + csvFileContent.append(", "); + + String allTypes = StringUtils.join(subEntity.getEntityTypeLabels(), "; "); + + csvFileContent.append(StringEscapeUtils.escapeCsv(allTypes)); + csvFileContent.append("\n"); + } + return csvFileContent.toString(); + } } \ No newline at end of file diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/modelconstructor/ModelConstructorUtilities.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/modelconstructor/ModelConstructorUtilities.java index a6678c76..ec6466f3 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/modelconstructor/ModelConstructorUtilities.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/modelconstructor/ModelConstructorUtilities.java @@ -1,33 +1,35 @@ -/* $This file is distributed under the terms of the license in /doc/license.txt$ */ -package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor; - -import java.util.HashMap; -import java.util.Map; - -import com.hp.hpl.jena.query.Dataset; -import com.hp.hpl.jena.rdf.model.Model; - -import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.factory.ModelFactoryInterface; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.factory.OrganizationAssociatedPeopleModelWithTypesFactory; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.factory.OrganizationModelWithTypesFactory; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.factory.OrganizationToGrantsForSubOrganizationsFactory; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.factory.OrganizationToPublicationsForSubOrganizationsFactory; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.factory.PersonToPublicationsFactory; - -public class ModelConstructorUtilities { - - @SuppressWarnings("serial") - private static final Map modelTypeIdentifierToFactory = new HashMap() {{ - put(PersonToPublicationsModelConstructor.MODEL_TYPE, new PersonToPublicationsFactory()); - put(OrganizationToPublicationsForSubOrganizationsModelConstructor.MODEL_TYPE, new OrganizationToPublicationsForSubOrganizationsFactory()); - put(OrganizationToGrantsForSubOrganizationsModelConstructor.MODEL_TYPE, new OrganizationToGrantsForSubOrganizationsFactory()); - put(OrganizationAssociatedPeopleModelWithTypesConstructor.MODEL_TYPE, new OrganizationAssociatedPeopleModelWithTypesFactory()); - put(OrganizationModelWithTypesConstructor.MODEL_TYPE, new OrganizationModelWithTypesFactory()); - }}; - - public static Model getOrConstructModel(String uri, String modelType, Dataset dataset) - throws MalformedQueryParametersException { - return modelTypeIdentifierToFactory.get(modelType).getOrCreateModel(uri, dataset); - } -} +/* $This file is distributed under the terms of the license in /doc/license.txt$ */ +package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor; + +import java.util.HashMap; +import java.util.Map; + +import com.hp.hpl.jena.query.Dataset; +import com.hp.hpl.jena.rdf.model.Model; + +import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.factory.ModelFactoryInterface; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.factory.OrganizationAssociatedPeopleModelWithTypesFactory; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.factory.OrganizationModelWithTypesFactory; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.factory.OrganizationToGrantsForSubOrganizationsFactory; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.factory.OrganizationToPublicationsForSubOrganizationsFactory; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.factory.PersonToGrantsFactory; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.factory.PersonToPublicationsFactory; + +public class ModelConstructorUtilities { + + @SuppressWarnings("serial") + private static final Map modelTypeIdentifierToFactory = new HashMap() {{ + put(PersonToPublicationsModelConstructor.MODEL_TYPE, new PersonToPublicationsFactory()); + put(PersonToGrantsModelConstructor.MODEL_TYPE, new PersonToGrantsFactory()); + put(OrganizationToPublicationsForSubOrganizationsModelConstructor.MODEL_TYPE, new OrganizationToPublicationsForSubOrganizationsFactory()); + put(OrganizationToGrantsForSubOrganizationsModelConstructor.MODEL_TYPE, new OrganizationToGrantsForSubOrganizationsFactory()); + put(OrganizationAssociatedPeopleModelWithTypesConstructor.MODEL_TYPE, new OrganizationAssociatedPeopleModelWithTypesFactory()); + put(OrganizationModelWithTypesConstructor.MODEL_TYPE, new OrganizationModelWithTypesFactory()); + }}; + + public static Model getOrConstructModel(String uri, String modelType, Dataset dataset) + throws MalformedQueryParametersException { + return modelTypeIdentifierToFactory.get(modelType).getOrCreateModel(uri, dataset); + } +} \ No newline at end of file diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/modelconstructor/OrganizationToGrantsForSubOrganizationsModelConstructor.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/modelconstructor/OrganizationToGrantsForSubOrganizationsModelConstructor.java index e4dc522f..3c9abdcf 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/modelconstructor/OrganizationToGrantsForSubOrganizationsModelConstructor.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/modelconstructor/OrganizationToGrantsForSubOrganizationsModelConstructor.java @@ -1,133 +1,188 @@ -/* $This file is distributed under the terms of the license in /doc/license.txt$ */ -package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor; - -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.freemarker.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"; - - 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 String constructOrganizationToGrantsQuery() { - - return "" - + " CONSTRUCT { " - + " <" + organizationURI + "> rdfs:label ?organizationLabel . " - + " <" + organizationURI + "> vivosocnet:lastCachedAt ?now . " - + " <" + organizationURI + "> vivosocnet:hasPersonWithGrant ?Grant . " - + " " - + " ?Grant rdf:type core:Grant . " - + " ?Grant rdfs:label ?grantLabel . " - + " " - + " ?Grant vivosocnet:startDateTimeOnGrant ?startDateTimeValueForGrant . " - + " ?Grant vivosocnet:endDateTimeOnGrant ?endDateTimeValueForGrant . " - + " " - + " ?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:hasInvestigatorRole ?Role . " - + " ?Role core:roleIn ?Grant . " - + " ?Grant rdfs:label ?grantLabel . " - + " " - + " OPTIONAL { " - + " ?Grant core:dateTimeInterval ?dateTimeIntervalValueForGrant . " - + " OPTIONAL { " - + " ?dateTimeIntervalValueForGrant core:start ?startDateForGrant . " - + " ?startDateForGrant core:dateTime ?startDateTimeValueForGrant . " - + " } " - + " OPTIONAL { " - + " ?dateTimeIntervalValueForGrant core:end ?endDateForGrant . " - + " ?endDateForGrant core:dateTime ?endDateTimeValueForGrant " - + " } " - + " } " - + " " - + " OPTIONAL { " - + " ?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()) " - + " } "; - - } - - private Model executeQuery(String constructQuery) { - - System.out.println("in execute query - org to grants for - " + organizationURI); - - Model constructedModel = ModelFactory.createDefaultModel(); - - before = System.currentTimeMillis(); - log.debug("CONSTRUCT query string : " + constructQuery); - - Query query = null; - - try { - query = QueryFactory.create(QueryConstants.getSparqlPrefixQuery() - + constructQuery, SYNTAX); - } catch (Throwable th) { - log.error("Could not create CONSTRUCT SPARQL query for query " - + "string. " + th.getMessage()); - log.error(constructQuery); - } - - 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.freemarker.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.freemarker.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"; + + 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:roleIn ?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:roleIn ?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:roleIn ?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()); + } +} diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/modelconstructor/PersonToGrantsModelConstructor.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/modelconstructor/PersonToGrantsModelConstructor.java new file mode 100644 index 00000000..1df93e3f --- /dev/null +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/modelconstructor/PersonToGrantsModelConstructor.java @@ -0,0 +1,171 @@ +/* $This file is distributed under the terms of the license in /doc/license.txt$ */ +package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.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.freemarker.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"; + + 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 { " + + " ?Person core:" + roleTypeProperty + " ?Role . " + + " ?Role core:roleIn ?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 { " + + " ?Person core:" + roleTypeProperty + " ?Role . " + + " ?Role core:roleIn ?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 { " + + " ?Person core:" + roleTypeProperty + " ?Role . " + + " ?Role core:roleIn ?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()); + } +} diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/modelconstructor/factory/PersonToGrantsFactory.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/modelconstructor/factory/PersonToGrantsFactory.java new file mode 100644 index 00000000..d674b895 --- /dev/null +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/modelconstructor/factory/PersonToGrantsFactory.java @@ -0,0 +1,43 @@ +/* $This file is distributed under the terms of the license in /doc/license.txt$ */ +package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.factory; + +import com.hp.hpl.jena.query.Dataset; +import com.hp.hpl.jena.rdf.model.Model; + +import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.PersonToGrantsModelConstructor; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.ConstructedModelTracker; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.ModelConstructor; + +public class PersonToGrantsFactory implements ModelFactoryInterface { + + @Override + public Model getOrCreateModel(String uri, Dataset dataset) + throws MalformedQueryParametersException { + + Model candidateModel = ConstructedModelTracker.getModel( + ConstructedModelTracker + .generateModelIdentifier( + uri, + PersonToGrantsModelConstructor.MODEL_TYPE)); + + if (candidateModel != null) { + + return candidateModel; + + } else { + + ModelConstructor model = new PersonToGrantsModelConstructor(uri, dataset); + + Model constructedModel = model.getConstructedModel(); + ConstructedModelTracker.trackModel( + ConstructedModelTracker + .generateModelIdentifier( + uri, + PersonToGrantsModelConstructor.MODEL_TYPE), + constructedModel); + + return constructedModel; + } + } +} \ No newline at end of file diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/visutils/SelectOnModelUtilities.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/visutils/SelectOnModelUtilities.java index 6725e419..371c4070 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/visutils/SelectOnModelUtilities.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/freemarker/visutils/SelectOnModelUtilities.java @@ -1,396 +1,481 @@ -/* $This file is distributed under the terms of the license in /doc/license.txt$ */ -package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.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.freemarker.modelconstructor.ModelConstructorUtilities; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.OrganizationAssociatedPeopleModelWithTypesConstructor; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.OrganizationModelWithTypesConstructor; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.OrganizationToGrantsForSubOrganizationsModelConstructor; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.OrganizationToPublicationsForSubOrganizationsModelConstructor; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.PersonToPublicationsModelConstructor; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.Activity; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.Entity; -import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.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); - - return getEntityWithSubOrganizations(subjectEntityURI, - subOrganizationsWithTypesQuery.getQueryResult()); - } - - 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.setIndividualLabel(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); - - subOrganization.addActivities(getPublicationForEntity( - subOrganizationPublicationsQuery.getQueryResult(), - allDocumentURIToVOs)); - - } - return allDocumentURIToVOs; - } - - private static Collection getPublicationForEntity( - ResultSet queryResult, - Map allDocumentURIToVOs) { - - Set currentEntityPublications = new HashSet(); - - while (queryResult.hasNext()) { - - QuerySolution solution = queryResult.nextSolution(); - - 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); - - } - - return currentEntityPublications; - } - - - private static Collection getGrantForEntity( - ResultSet queryResult, - Map allGrantURIToVO) { - - Set currentEntityGrants = new HashSet(); - - while (queryResult.hasNext()) { - - QuerySolution solution = queryResult.nextSolution(); - - 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); - } - return currentEntityGrants; - } - - public static Map getGrantsForAllSubOrganizations( - Dataset dataset, Entity organizationEntity) - throws MalformedQueryParametersException { - Map allGrantURIToVO = new HashMap(); - - for (SubEntity subOrganization : organizationEntity.getSubEntities()) { - - Model subOrganizationGrantsModel = ModelConstructorUtilities - .getOrConstructModel( - subOrganization.getIndividualURI(), - OrganizationToGrantsForSubOrganizationsModelConstructor.MODEL_TYPE, - dataset); - - System.out.println("getting grants for " + subOrganization.getIndividualLabel()); - - 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:hasPersonWithGrant ?grant . " - + " ?grant rdfs:label ?grantLabel . " - + " OPTIONAL { " - + " ?grant vivosocnet:startDateTimeOnGrant ?grantStartDate } . " - + " OPTIONAL { " - + " ?grant vivosocnet:startDateTimeOnRole ?roleStartDate } . "; - - QueryRunner subOrganizationGrantsQuery = - new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel, - "", - whereClause, - "", - subOrganizationGrantsModel); - - subOrganization.addActivities(getGrantForEntity( - subOrganizationGrantsQuery.getQueryResult(), - allGrantURIToVO)); - - } - return allGrantURIToVO; - } - - public static Map getPublicationsForAssociatedPeople( - Dataset dataset, Collection people) - throws MalformedQueryParametersException { - Map allDocumentURIToVOs = new HashMap(); - - for (SubEntity person : people) { - - Model personPublicationsModel = ModelConstructorUtilities - .getOrConstructModel( - person.getIndividualURI(), - PersonToPublicationsModelConstructor.MODEL_TYPE, - dataset); - - 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); - - 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, - "", - personPublicationsModel); - - person.addActivities(getPublicationForEntity( - personPublicationsQuery.getQueryResult(), - allDocumentURIToVOs)); - - } - return allDocumentURIToVOs; - } - -} +/* $This file is distributed under the terms of the license in /doc/license.txt$ */ +package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.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.freemarker.modelconstructor.ModelConstructorUtilities; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.OrganizationAssociatedPeopleModelWithTypesConstructor; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.OrganizationModelWithTypesConstructor; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.OrganizationToGrantsForSubOrganizationsModelConstructor; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.OrganizationToPublicationsForSubOrganizationsModelConstructor; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.PersonToGrantsModelConstructor; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.modelconstructor.PersonToPublicationsModelConstructor; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.Activity; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.Entity; +import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.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); + + return getEntityWithSubOrganizations(subjectEntityURI, + subOrganizationsWithTypesQuery.getQueryResult()); + } + + 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.setIndividualLabel(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); + + subOrganization.addActivities(getPublicationForEntity( + subOrganizationPublicationsQuery.getQueryResult(), + allDocumentURIToVOs)); + + } + return allDocumentURIToVOs; + } + + private static Collection getPublicationForEntity( + ResultSet queryResult, + Map allDocumentURIToVOs) { + + Set currentEntityPublications = new HashSet(); + + while (queryResult.hasNext()) { + + QuerySolution solution = queryResult.nextSolution(); + + 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); + + } + + return currentEntityPublications; + } + + + private static Collection getGrantForEntity( + ResultSet queryResult, + Map allGrantURIToVO) { + + Set currentEntityGrants = new HashSet(); + + while (queryResult.hasNext()) { + + QuerySolution solution = queryResult.nextSolution(); + + 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); + } + return 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()); + + Model subOrganizationGrantsModel = ModelConstructorUtilities + .getOrConstructModel( + subOrganization.getIndividualURI(), + OrganizationToGrantsForSubOrganizationsModelConstructor.MODEL_TYPE, + dataset); + + 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); + + subOrganization.addActivities(getGrantForEntity( + subOrganizationGrantsQuery.getQueryResult(), + allGrantURIToVO)); + + } + return allGrantURIToVO; + } + + public static Map getGrantForAssociatedPeople( + Dataset dataset, Collection people) + throws MalformedQueryParametersException { + Map allGrantURIToVOs = new HashMap(); + + for (SubEntity person : people) { + + System.out.println("constructing grants for " + person.getIndividualLabel() + " :: " + person.getIndividualURI()); + + Model personGrantsModel = ModelConstructorUtilities + .getOrConstructModel( + person.getIndividualURI(), + PersonToGrantsModelConstructor.MODEL_TYPE, + dataset); + + 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); + + person.addActivities(getGrantForEntity( + personGrantsQuery.getQueryResult(), + allGrantURIToVOs)); + + } + return allGrantURIToVOs; + } + + public static Map getPublicationsForAssociatedPeople( + Dataset dataset, Collection people) + throws MalformedQueryParametersException { + Map allDocumentURIToVOs = new HashMap(); + + for (SubEntity person : people) { + + Model personPublicationsModel = ModelConstructorUtilities + .getOrConstructModel( + person.getIndividualURI(), + PersonToPublicationsModelConstructor.MODEL_TYPE, + dataset); + + 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); + + 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, + "", + personPublicationsModel); + + person.addActivities(getPublicationForEntity( + personPublicationsQuery.getQueryResult(), + allDocumentURIToVOs)); + + } + return allDocumentURIToVOs; + } + +}