1. Completed the caching-like version for temporal graph for grants.

2. Changed the timeout for front-end getter for temporal vis data since the first time a user requests grant comparison it might take a long time.
This commit is contained in:
cdtank 2011-03-19 00:11:58 +00:00
parent b1950352e8
commit c49e8d1d75
8 changed files with 1906 additions and 1530 deletions

View file

@ -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("<div id='loading-comparisons'>Loading " + selectedValue + "&nbsp;&nbsp;<img src='" + loadingImageLink + "' /></div>");
/*
* 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: '<h3><img src="' + loadingImageLink
+ '" />&nbsp;Loading data for <i>'
+ organizationLabel
+ '</i></h3>'
});
}
/*
* 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("<div id='loading-comparisons'>Loading " + selectedValue + "&nbsp;&nbsp;<img src='" + loadingImageLink + "' /></div>");
/*
* 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: '<h3><img src="' + loadingImageLink
+ '" />&nbsp;Loading data for <i>'
+ organizationLabel
+ '</i></h3>'
});
}
/*
* 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();
});
}
}

View file

@ -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<String, Model> entry : ConstructedModelTracker.getAllModels().entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue().size());
}
return prepareStandaloneMarkupResponse(vitroRequest, entityURI);
}
@Override
public Map<String, String> 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<String, String> prepareDataErrorResponse() {
String outputFileName = "no-organization_grants-per-year.csv";
Map<String, String> fileData = new HashMap<String, String>();
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<String, String> 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<String, Activity> grantURIForAssociatedPeopleToVO = new HashMap<String, Activity>();
Map<String, Activity> allGrantURIToVO = new HashMap<String, Activity>();
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<String, String> prepareStandaloneDataErrorResponse() {
Map<String, String> fileData = new HashMap<String, String>();
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<String, String> prepareStandaloneDataResponse(
VitroRequest vitroRequest,
Entity entity) {
Map<String, String> fileData = new HashMap<String, String>();
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<String, String> 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<String, String> fileData = new HashMap<String, String>();
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<String, Object> body = new HashMap<String, Object>();
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<SubEntity> subentities) {
Gson json = new Gson();
Set<JsonObject> subEntitiesJson = new HashSet<JsonObject>();
for (SubEntity subentity : subentities) {
JsonObject entityJson = new JsonObject(
subentity.getIndividualLabel());
List<List<Integer>> yearGrantCount = new ArrayList<List<Integer>>();
for (Map.Entry<String, Integer> grantEntry : UtilityFunctions
.getYearToActivityCount(subentity.getActivities())
.entrySet()) {
List<Integer> currentGrantYear = new ArrayList<Integer>();
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<String, Model> entry : ConstructedModelTracker.getAllModels().entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue().size());
}
return prepareStandaloneMarkupResponse(vitroRequest, entityURI);
}
@Override
public Map<String, String> 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<String, String> prepareDataErrorResponse() {
String outputFileName = "no-organization_grants-per-year.csv";
Map<String, String> fileData = new HashMap<String, String>();
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<String, String> 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<String, Activity> grantURIForAssociatedPeopleToVO = new HashMap<String, Activity>();
Map<String, Activity> allGrantURIToVO = new HashMap<String, Activity>();
/**
* 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<String, String> prepareStandaloneDataErrorResponse() {
Map<String, String> fileData = new HashMap<String, String>();
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<String, String> prepareStandaloneDataResponse(
VitroRequest vitroRequest,
Entity entity) {
Map<String, String> fileData = new HashMap<String, String>();
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<String, String> 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<String, String> fileData = new HashMap<String, String>();
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<String, Object> body = new HashMap<String, Object>();
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<SubEntity> subentities) {
Gson json = new Gson();
Set<JsonObject> subEntitiesJson = new HashSet<JsonObject>();
for (SubEntity subentity : subentities) {
JsonObject entityJson = new JsonObject(
subentity.getIndividualLabel());
List<List<Integer>> yearGrantCount = new ArrayList<List<Integer>>();
for (Map.Entry<String, Integer> grantEntry : UtilityFunctions
.getYearToActivityCount(subentity.getActivities())
.entrySet()) {
List<Integer> currentGrantYear = new ArrayList<Integer>();
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();
}
}

View file

@ -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<String, Model> entry : ConstructedModelTracker.getAllModels().entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue().size());
}
return prepareStandaloneMarkupResponse(vitroRequest, entityURI);
}
private Map<String, String> 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<String, Activity> documentURIForAssociatedPeopleTOVO = new HashMap<String, Activity>();
Map<String, Activity> allDocumentURIToVOs = new HashMap<String, Activity>();
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<String, String> 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<String, String> fileData = new HashMap<String, String>();
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<String, String> prepareDataErrorResponse() {
String outputFileName = "no-organization_publications-per-year.csv";
Map<String, String> fileData = new HashMap<String, String>();
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<String, String> prepareStandaloneDataErrorResponse() {
Map<String, String> fileData = new HashMap<String, String>();
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<String, String> 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<String, String> prepareStandaloneDataResponse(
VitroRequest vitroRequest,
Entity entity) {
Map<String, String> fileData = new HashMap<String, String>();
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<String, Object> body = new HashMap<String, Object>();
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<SubEntity> subentities) {
Gson json = new Gson();
Set<JsonObject> subEntitiesJson = new HashSet<JsonObject>();
for (SubEntity subentity : subentities) {
System.out.println("in write json current sub entity " + subentity.getIndividualLabel());
JsonObject entityJson = new JsonObject(
subentity.getIndividualLabel());
List<List<Integer>> yearPubCount = new ArrayList<List<Integer>>();
for (Map.Entry<String, Integer> pubEntry : UtilityFunctions
.getYearToActivityCount(subentity.getActivities())
.entrySet()) {
List<Integer> currentPubYear = new ArrayList<Integer>();
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<String, Model> entry : ConstructedModelTracker.getAllModels().entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue().size());
}
return prepareStandaloneMarkupResponse(vitroRequest, entityURI);
}
private Map<String, String> 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<String, Activity> documentURIForAssociatedPeopleTOVO = new HashMap<String, Activity>();
Map<String, Activity> allDocumentURIToVOs = new HashMap<String, Activity>();
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<String, String> 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<String, String> fileData = new HashMap<String, String>();
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<String, String> prepareDataErrorResponse() {
String outputFileName = "no-organization_publications-per-year.csv";
Map<String, String> fileData = new HashMap<String, String>();
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<String, String> prepareStandaloneDataErrorResponse() {
Map<String, String> fileData = new HashMap<String, String>();
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<String, String> 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<String, String> prepareStandaloneDataResponse(
VitroRequest vitroRequest,
Entity entity) {
Map<String, String> fileData = new HashMap<String, String>();
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<String, Object> body = new HashMap<String, Object>();
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<SubEntity> subentities) {
Gson json = new Gson();
Set<JsonObject> subEntitiesJson = new HashSet<JsonObject>();
for (SubEntity subentity : subentities) {
JsonObject entityJson = new JsonObject(
subentity.getIndividualLabel());
List<List<Integer>> yearPubCount = new ArrayList<List<Integer>>();
for (Map.Entry<String, Integer> pubEntry : UtilityFunctions
.getYearToActivityCount(subentity.getActivities())
.entrySet()) {
List<Integer> currentPubYear = new ArrayList<Integer>();
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();
}
}

View file

@ -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<String, ModelFactoryInterface> modelTypeIdentifierToFactory = new HashMap<String, ModelFactoryInterface>() {{
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<String, ModelFactoryInterface> modelTypeIdentifierToFactory = new HashMap<String, ModelFactoryInterface>() {{
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);
}
}

View file

@ -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<String> constructOrganizationGrantsQueryTemplate(String constructProperty, String roleTypeProperty) {
Set<String> differentPerspectiveQueries = new HashSet<String>();
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<String> constructOrganizationToGrantsQuery() {
Set<String> differentInvestigatorTypeQueries = new HashSet<String>();
Set<String> investigatorRoleQuery = constructOrganizationGrantsQueryTemplate("hasInvestigatorWithGrant", "hasInvestigatorRole");
Set<String> piRoleQuery = constructOrganizationGrantsQueryTemplate("hasPIWithGrant", "hasPrincipalInvestigatorRole");
Set<String> coPIRoleQuery = constructOrganizationGrantsQueryTemplate("hascoPIWithGrant", "hasCo-PrincipalInvestigatorRole");
differentInvestigatorTypeQueries.addAll(investigatorRoleQuery);
differentInvestigatorTypeQueries.addAll(piRoleQuery);
differentInvestigatorTypeQueries.addAll(coPIRoleQuery);
return differentInvestigatorTypeQueries;
}
private Model executeQuery(Set<String> 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());
}
}

View file

@ -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<String> constructPersonGrantsQueryTemplate(String constructProperty, String roleTypeProperty) {
Set<String> differentPerspectiveQueries = new HashSet<String>();
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<String> constructPersonToGrantsQuery() {
Set<String> differentInvestigatorTypeQueries = new HashSet<String>();
Set<String> investigatorRoleQuery = constructPersonGrantsQueryTemplate("hasGrantAsAnInvestigator", "hasInvestigatorRole");
Set<String> piRoleQuery = constructPersonGrantsQueryTemplate("hasGrantAsPI", "hasPrincipalInvestigatorRole");
Set<String> coPIRoleQuery = constructPersonGrantsQueryTemplate("hasGrantAsCoPI", "hasCo-PrincipalInvestigatorRole");
differentInvestigatorTypeQueries.addAll(investigatorRoleQuery);
differentInvestigatorTypeQueries.addAll(piRoleQuery);
differentInvestigatorTypeQueries.addAll(coPIRoleQuery);
return differentInvestigatorTypeQueries;
}
private Model executeQuery(Set<String> 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());
}
}

View file

@ -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;
}
}
}

View file

@ -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<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>();
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<ResultSet> 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<String, SubEntity> subOrganizationURIToVO = new HashMap<String, SubEntity>();
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<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>();
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<ResultSet> 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<String, SubEntity> associatedPeopleURIToVO = new HashMap<String, SubEntity>();
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<String, Activity> getPublicationsForAllSubOrganizations(
Dataset dataset, Entity organizationEntity)
throws MalformedQueryParametersException {
Map<String, Activity> allDocumentURIToVOs = new HashMap<String, Activity>();
for (SubEntity subOrganization : organizationEntity.getSubEntities()) {
Model subOrganizationPublicationsModel = ModelConstructorUtilities
.getOrConstructModel(
subOrganization.getIndividualURI(),
OrganizationToPublicationsForSubOrganizationsModelConstructor.MODEL_TYPE,
dataset);
System.out.println("getting publications for " + subOrganization.getIndividualLabel());
Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>();
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<ResultSet> subOrganizationPublicationsQuery =
new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel,
"",
whereClause,
"",
subOrganizationPublicationsModel);
subOrganization.addActivities(getPublicationForEntity(
subOrganizationPublicationsQuery.getQueryResult(),
allDocumentURIToVOs));
}
return allDocumentURIToVOs;
}
private static Collection<Activity> getPublicationForEntity(
ResultSet queryResult,
Map<String, Activity> allDocumentURIToVOs) {
Set<Activity> currentEntityPublications = new HashSet<Activity>();
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<Activity> getGrantForEntity(
ResultSet queryResult,
Map<String, Activity> allGrantURIToVO) {
Set<Activity> currentEntityGrants = new HashSet<Activity>();
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<String, Activity> getGrantsForAllSubOrganizations(
Dataset dataset, Entity organizationEntity)
throws MalformedQueryParametersException {
Map<String, Activity> allGrantURIToVO = new HashMap<String, Activity>();
for (SubEntity subOrganization : organizationEntity.getSubEntities()) {
Model subOrganizationGrantsModel = ModelConstructorUtilities
.getOrConstructModel(
subOrganization.getIndividualURI(),
OrganizationToGrantsForSubOrganizationsModelConstructor.MODEL_TYPE,
dataset);
System.out.println("getting grants for " + subOrganization.getIndividualLabel());
Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>();
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<ResultSet> subOrganizationGrantsQuery =
new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel,
"",
whereClause,
"",
subOrganizationGrantsModel);
subOrganization.addActivities(getGrantForEntity(
subOrganizationGrantsQuery.getQueryResult(),
allGrantURIToVO));
}
return allGrantURIToVO;
}
public static Map<String, Activity> getPublicationsForAssociatedPeople(
Dataset dataset, Collection<SubEntity> people)
throws MalformedQueryParametersException {
Map<String, Activity> allDocumentURIToVOs = new HashMap<String, Activity>();
for (SubEntity person : people) {
Model personPublicationsModel = ModelConstructorUtilities
.getOrConstructModel(
person.getIndividualURI(),
PersonToPublicationsModelConstructor.MODEL_TYPE,
dataset);
System.out.println("getting publications for " + person.getIndividualLabel());
Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>();
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<ResultSet> 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<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>();
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<ResultSet> 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<String, SubEntity> subOrganizationURIToVO = new HashMap<String, SubEntity>();
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<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>();
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<ResultSet> 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<String, SubEntity> associatedPeopleURIToVO = new HashMap<String, SubEntity>();
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<String, Activity> getPublicationsForAllSubOrganizations(
Dataset dataset, Entity organizationEntity)
throws MalformedQueryParametersException {
Map<String, Activity> allDocumentURIToVOs = new HashMap<String, Activity>();
for (SubEntity subOrganization : organizationEntity.getSubEntities()) {
Model subOrganizationPublicationsModel = ModelConstructorUtilities
.getOrConstructModel(
subOrganization.getIndividualURI(),
OrganizationToPublicationsForSubOrganizationsModelConstructor.MODEL_TYPE,
dataset);
System.out.println("getting publications for " + subOrganization.getIndividualLabel());
Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>();
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<ResultSet> subOrganizationPublicationsQuery =
new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel,
"",
whereClause,
"",
subOrganizationPublicationsModel);
subOrganization.addActivities(getPublicationForEntity(
subOrganizationPublicationsQuery.getQueryResult(),
allDocumentURIToVOs));
}
return allDocumentURIToVOs;
}
private static Collection<Activity> getPublicationForEntity(
ResultSet queryResult,
Map<String, Activity> allDocumentURIToVOs) {
Set<Activity> currentEntityPublications = new HashSet<Activity>();
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<Activity> getGrantForEntity(
ResultSet queryResult,
Map<String, Activity> allGrantURIToVO) {
Set<Activity> currentEntityGrants = new HashSet<Activity>();
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<String, Activity> getGrantsForAllSubOrganizations(
Dataset dataset, Entity organizationEntity)
throws MalformedQueryParametersException {
Map<String, Activity> allGrantURIToVO = new HashMap<String, Activity>();
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<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>();
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<ResultSet> subOrganizationGrantsQuery =
new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel,
"",
whereClause,
"",
subOrganizationGrantsModel);
subOrganization.addActivities(getGrantForEntity(
subOrganizationGrantsQuery.getQueryResult(),
allGrantURIToVO));
}
return allGrantURIToVO;
}
public static Map<String, Activity> getGrantForAssociatedPeople(
Dataset dataset, Collection<SubEntity> people)
throws MalformedQueryParametersException {
Map<String, Activity> allGrantURIToVOs = new HashMap<String, Activity>();
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<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>();
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<ResultSet> personGrantsQuery =
new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel,
"",
whereClause,
"",
personGrantsModel);
person.addActivities(getGrantForEntity(
personGrantsQuery.getQueryResult(),
allGrantURIToVOs));
}
return allGrantURIToVOs;
}
public static Map<String, Activity> getPublicationsForAssociatedPeople(
Dataset dataset, Collection<SubEntity> people)
throws MalformedQueryParametersException {
Map<String, Activity> allDocumentURIToVOs = new HashMap<String, Activity>();
for (SubEntity person : people) {
Model personPublicationsModel = ModelConstructorUtilities
.getOrConstructModel(
person.getIndividualURI(),
PersonToPublicationsModelConstructor.MODEL_TYPE,
dataset);
System.out.println("getting publications for " + person.getIndividualLabel());
Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>();
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<ResultSet> personPublicationsQuery =
new GenericQueryRunnerOnModel(fieldLabelToOutputFieldLabel,
"",
whereClause,
"",
personPublicationsModel);
person.addActivities(getPublicationForEntity(
personPublicationsQuery.getQueryResult(),
allDocumentURIToVOs));
}
return allDocumentURIToVOs;
}
}