Committing the following changes

1) Added entry for entity_grant_count in visualizations-beans-injection-fm.xml
2) Styling changes in layout.css -- changed the styling for buttons.
3) util.js -- Removed hardcoding of URLs see NIH VIVO 1618 and 1619
4) Made queries for EntityGrantCount, EntityPubCount and EntitySubOrganizationTypes more generic. Added Export as CSV functionailty for EntityGrantCount
This commit is contained in:
bkoniden 2011-01-07 21:59:59 +00:00
parent 1425b33e04
commit a740497bb6
13 changed files with 804 additions and 263 deletions

View file

@ -15,7 +15,6 @@
<bean id="utilities" <bean id="utilities"
class="edu.cornell.mannlib.vitro.webapp.visualization.freemarker.utilities.UtilitiesRequestHandler" /> class="edu.cornell.mannlib.vitro.webapp.visualization.freemarker.utilities.UtilitiesRequestHandler" />
<bean id="coauthorship" <bean id="coauthorship"
class="edu.cornell.mannlib.vitro.webapp.visualization.freemarker.coauthorship.CoAuthorshipRequestHandler" /> class="edu.cornell.mannlib.vitro.webapp.visualization.freemarker.coauthorship.CoAuthorshipRequestHandler" />
@ -31,6 +30,10 @@
<bean id="entity_comparison" <bean id="entity_comparison"
class="edu.cornell.mannlib.vitro.webapp.visualization.freemarker.entitycomparison.EntityPublicationCountRequestHandler" /> class="edu.cornell.mannlib.vitro.webapp.visualization.freemarker.entitycomparison.EntityPublicationCountRequestHandler" />
<bean id="entity_grant_count"
class="edu.cornell.mannlib.vitro.webapp.visualization.freemarker.entitygrantcount.EntityGrantCountRequestHandler" />
<bean id="visualizationInjector" <bean id="visualizationInjector"
class="edu.cornell.mannlib.vitro.webapp.controller.visualization.freemarker.VisualizationInjector"> class="edu.cornell.mannlib.vitro.webapp.controller.visualization.freemarker.VisualizationInjector">
<property name="visualizations"> <property name="visualizations">
@ -63,6 +66,9 @@
<ref bean="coprincipalinvestigator"></ref> <ref bean="coprincipalinvestigator"></ref>
</entry> </entry>
<entry key="entity_grant_count">
<ref bean="entity_grant_count"></ref>
</entry>
</map> </map>
</property> </property>

View file

@ -26,9 +26,17 @@ h2 {
margin-bottom: 5px; margin-bottom: 5px;
} }
button{ a.temporalGraphLinks {
margin-top: 10px; margin-top: 10px;
float:right; float:right;
height: 20px;
text-decoration: none;
width: 30%;
margin: 0 1% 0 1%;
background-color: #EAEAEA;
text-align: center;
padding: 3px;
padding-top: 4px;
} }
#reset-search { #reset-search {
@ -191,12 +199,6 @@ li{
margin: 20px 0 20px 0; margin: 20px 0 20px 0;
} }
button.green-button{
width: 31%;
margin: 0 1% 0 1%;
}
#stopwordsdiv{ #stopwordsdiv{
margin-top: 10px; margin-top: 10px;
margin-left: 10px; margin-left: 10px;

View file

@ -11,6 +11,7 @@
*/ */
function init(graphContainer) { function init(graphContainer) {
$('#yaxislabel').css("color", "#595B5B");
var optionSelected = $("select.comparisonValues option:selected").val(); var optionSelected = $("select.comparisonValues option:selected").val();
// TODO: make use of the id on the select field instead of a generic one. // TODO: make use of the id on the select field instead of a generic one.
$("#comparisonParameter").text("Total Number of " + $("select.comparisonValues option:selected").val()); $("#comparisonParameter").text("Total Number of " + $("select.comparisonValues option:selected").val());
@ -382,7 +383,7 @@ function createGraphic(entity, bottomDiv) {
} }
function getVIVOURL(entity){ /*function getVIVOURL(entity){
var result = "/vivo1/individual?uri="+entity.entityURI+"&home=1"; var result = "/vivo1/individual?uri="+entity.entityURI+"&home=1";
return result; return result;
@ -398,12 +399,36 @@ function getEntityURL(entity) {
var home = "&home=1"; var home = "&home=1";
result = (path + uri + home); result = (path + uri + home);
}else{ }else{
path = "/vivo1/visualization?"; path = "/vivo1/visualizationfm?";
var visAndRenderMode = "vis=entity_comparison&render_mode=standalone&"; var visAndRenderMode = "vis=entity_comparison&render_mode=standalone&";
var visMode = "vis_mode=" + entity.visMode + "&"; var visMode = "vis_mode=" + entity.visMode + "&";
uri = "uri=" + entity.entityURI; uri = "uri=" + entity.entityURI;
result = (path + visAndRenderMode + visMode + uri); result = (path + visAndRenderMode + visMode + uri);
} }
return result;
}*/
function getVIVOURL(entity){
var result = subOrganizationVivoProfileURL + "uri="+entity.entityURI;
return result;
}
function getEntityURL(entity) {
var result = '';
if(entity.visMode == "PERSON"){
result = subOrganizationVivoProfileURL + "uri="+ entity.entityURI;
}else{
result = subOrganizationTemporalGraphURL+ "&vis_mode=" + entity.visMode + "&" +
"uri=" + entity.entityURI ;
}
return result; return result;
} }
@ -547,10 +572,11 @@ function generateBarAndLabel(entity, divBar, divLabel,checkbox, spanElement){
divBar.css("width", normalizedWidth); divBar.css("width", normalizedWidth);
divLabel.children("a#entityURL").html(checkboxValue + " ").css("color", "#333"); divLabel.children("a#entityURL").html(checkboxValue + " ").css("color", "#333");
// divLabel.children("a#entityURL").css("color", "#333").css("text-decoration", none); // divLabel.children("a#entityURL").css("color", "#333").css("text-decoration", none);
divLabel.children("a#entityURL").autoEllipsis(); // divLabel.children("a#entityURL").autoEllipsis();
divLabel.children("a#entityURL");
createVIVOProfileImage(divLabel.children("a#`")); createVIVOProfileImage(divLabel.children("a#`"));
divLabel.children("a").css("font-size", "0.8em"); divLabel.children("a").css("font-size", "0.8em");
spanElement.text(sum); spanElement.text(sum).css("font-size", "0.8em").css("color", "#595B5B");
checkbox.next('a').css("font-weight", "bold"); checkbox.next('a').css("font-weight", "bold");
} }
@ -718,7 +744,7 @@ function prepareTableForDataTablePagination(jsonData){
publicationCountTH.html('Publication Count'); publicationCountTH.html('Publication Count');
var entityTypeTH = $('<th>'); var entityTypeTH = $('<th>');
entityTypeTH.html('Entity Type*'); entityTypeTH.html('Entity Type');
tr.append(checkboxTH); tr.append(checkboxTH);
tr.append(entityLabelTH); tr.append(entityLabelTH);

View file

@ -8,17 +8,25 @@
<#assign jsonContent ="${jsonContent}"> <#assign jsonContent ="${jsonContent}">
<#assign organizationLabel = "${organizationLabel}"> <#assign organizationLabel = "${organizationLabel}">
<#assign organizationVivoProfileURL = "${urls.base}/individual?uri=${organizationURI}"> <#assign organizationVivoProfileURL = "${urls.base}/individual?uri=${organizationURI}">
<#assign subOrganizationTemporalGraphURL = "${urls.base}${standardVisualizationURLRoot}?vis=entity_comparison">
<#assign subOrganizationVivoProfileURL = "${urls.base}/individual?">
<#assign temporalGraphSmallIcon = '${urls.images}/visualization/temporal_vis_small_icon.jpg'> <#assign temporalGraphSmallIcon = '${urls.images}/visualization/temporal_vis_small_icon.jpg'>
<#assign TemporalGraphDownloadFile = '${urls.base}${dataVisualizationURLRoot}?vis=entitycomparison&uri=${organizationURI}&labelField=label'> <#assign TemporalGraphDownloadFile = '${urls.base}${dataVisualizationURLRoot}?vis=entity_comparison&uri=${organizationURI}&labelField=label&vis_mode=UNIVERSITY'>
<#-- Javascript files --> <#-- Javascript files -->
<#assign flot = '${urls.base}/js/visualization/entitycomparison/jquery_plugins/flot/jquery.flot.js'> <#assign flot = '${urls.base}/js/visualization/entitycomparison/jquery_plugins/flot/jquery.flot.js'>
<#assign excanvas = '${urls.base}/js/visualization/entitycomparison/jquery_plugins/flot/excanvas.js'>
<!--[if IE]><script type="text/javascript" src="${excanvas}"></script><![endif]-->
<#assign fliptext = '${urls.base}/js/visualization/entitycomparison/jquery_plugins/fliptext/jquery.mb.flipText.js'> <#assign fliptext = '${urls.base}/js/visualization/entitycomparison/jquery_plugins/fliptext/jquery.mb.flipText.js'>
<#assign jqueryNotify = '${urls.base}/js/jquery_plugins/jquery.notify.min.js'> <#assign jqueryNotify = '${urls.base}/js/jquery_plugins/jquery.notify.min.js'>
@ -72,6 +80,8 @@
var contextPath = "${urls.base}"; var contextPath = "${urls.base}";
var temporalGraphDownloadFile = "${TemporalGraphDownloadFile}" var temporalGraphDownloadFile = "${TemporalGraphDownloadFile}"
var temporalGraphSmallIcon = "${temporalGraphSmallIcon}"; var temporalGraphSmallIcon = "${temporalGraphSmallIcon}";
var subOrganizationVivoProfileURL = "${subOrganizationVivoProfileURL}";
var subOrganizationTemporalGraphURL = "${subOrganizationTemporalGraphURL}";
</script> </script>
@ -113,19 +123,15 @@ var temporalGraphSmallIcon = "${temporalGraphSmallIcon}";
var selectedValue = $("select.comparisonValues option:selected").val(); var selectedValue = $("select.comparisonValues option:selected").val();
$("#comparisonParameter").text("Total Number of " + selectedValue); $("#comparisonParameter").text("Total Number of " + selectedValue);
$('#yaxislabel').html("Number of " + selectedValue).mbFlipText(false); $('#yaxislabel').html("Number of " + selectedValue).mbFlipText(false);
$('#yaxislabel').css("color", "#595B5B");
$('#comparisonHeader').html(selectedValue).css('font-weight', 'bold'); $('#comparisonHeader').html(selectedValue).css('font-weight', 'bold');
}); });
//click event handler for clear button //click event handler for clear button
$("button#clear").click(function(){ $("a#clear").click(function(){
clearRenderedObjects(); clearRenderedObjects();
}); });
//click event handler for download file
$("button#csv").click(function(){
alert("${TemporalGraphDownloadFile}");
});
$("input[type=checkbox].easyDeselectCheckbox").live('click', function(){ $("input[type=checkbox].easyDeselectCheckbox").live('click', function(){
var checkbox = $(this); var checkbox = $(this);
@ -196,8 +202,6 @@ var temporalGraphSmallIcon = "${temporalGraphSmallIcon}";
*/ */
$("input.if_clicked_on_school").live('click', function(){ $("input.if_clicked_on_school").live('click', function(){
var checkbox = $(this); var checkbox = $(this);
var checkboxValue = $(this).attr("value"); var checkboxValue = $(this).attr("value");
var entity = labelToEntityRecord[checkboxValue]; var entity = labelToEntityRecord[checkboxValue];
@ -288,9 +292,11 @@ var temporalGraphSmallIcon = "${temporalGraphSmallIcon}";
<div id="paginatedTable"> <div id="paginatedTable">
</div> </div>
</div> </div>
<#--
<div id = "stopwordsdiv"> <div id = "stopwordsdiv">
* The entity types core:Person, foaf:Organization have been excluded as they are too general. * The entity types core:Person, foaf:Organization have been excluded as they are too general.
</div> </div>
-->
</div> </div>
<div id="rightblock"> <div id="rightblock">
@ -302,10 +308,10 @@ var temporalGraphSmallIcon = "${temporalGraphSmallIcon}";
<div id="xaxislabel">Year</div> <div id="xaxislabel">Year</div>
<div id="bottomButtons"> <div id="bottomButtons">
<button id="clear" class="green-button" type ="button">Remove All</button> <a id="clear" style="cursor:pointer;" class="temporalGraphLinks" >Remove All</a>
<button id="csv" class="green-button" class="green-button" type ="button">Save as CSV</button> <a id="csv" href="${TemporalGraphDownloadFile}" class="temporalGraphLinks" >Save as CSV</a>
<button id="image" class="green-button" type="button" onClick="window.print()"> Save as Image</button> <#-- <a id="image" href = "" class="temporalGraphLinks" onClick="window.print()"> Save as Image</a>
</div><br/> --> </div><br/>
<h4><span id="comparisonParameter"></span></h4> <h4><span id="comparisonParameter"></span></h4>
@ -315,5 +321,4 @@ var temporalGraphSmallIcon = "${temporalGraphSmallIcon}";
</div> </div>
</div> </div>
</div> </div>

View file

@ -35,6 +35,7 @@ import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.QueryR
* publications defined by bibo:Document property for a particular * publications defined by bibo:Document property for a particular
* department/school/university. * department/school/university.
* *
* Deepak Konidena.
* @author bkoniden * @author bkoniden
*/ */
public class EntityPublicationCountQueryRunner implements QueryRunner<Entity> { public class EntityPublicationCountQueryRunner implements QueryRunner<Entity> {
@ -44,7 +45,6 @@ public class EntityPublicationCountQueryRunner implements QueryRunner<Entity> {
private String entityURI; private String entityURI;
private DataSource dataSource; private DataSource dataSource;
private Log log; private Log log;
private String visMode;
private static final String SPARQL_QUERY_COMMON_SELECT_CLAUSE = "" private static final String SPARQL_QUERY_COMMON_SELECT_CLAUSE = ""
+ " (str(?Person) as ?personLit) " + " (str(?Person) as ?personLit) "
@ -72,12 +72,11 @@ public class EntityPublicationCountQueryRunner implements QueryRunner<Entity> {
private static String SUBENTITY_URL; private static String SUBENTITY_URL;
public EntityPublicationCountQueryRunner(String entityURI, public EntityPublicationCountQueryRunner(String entityURI,
DataSource dataSource, Log log, String visMode) { DataSource dataSource, Log log) {
this.entityURI = entityURI; this.entityURI = entityURI;
this.dataSource = dataSource; this.dataSource = dataSource;
this.log = log; this.log = log;
this.visMode = visMode;
} }
@ -86,6 +85,8 @@ public class EntityPublicationCountQueryRunner implements QueryRunner<Entity> {
Entity entity = null; Entity entity = null;
Map<String, BiboDocument> biboDocumentURLToVO = new HashMap<String, BiboDocument>(); Map<String, BiboDocument> biboDocumentURLToVO = new HashMap<String, BiboDocument>();
Map<String, SubEntity> subentityURLToVO = new HashMap<String, SubEntity>(); Map<String, SubEntity> subentityURLToVO = new HashMap<String, SubEntity>();
Map<String, SubEntity> personURLToVO = new HashMap<String, SubEntity>();
while (resultSet.hasNext()) { while (resultSet.hasNext()) {
@ -158,9 +159,36 @@ public class EntityPublicationCountQueryRunner implements QueryRunner<Entity> {
subEntity.addPublications(biboDocument); subEntity.addPublications(biboDocument);
} }
RDFNode personURLNode = solution.get(QueryFieldLabels.PERSON_URL);
if(personURLNode != null){
SubEntity person ;
if(personURLToVO.containsKey(personURLNode.toString())) {
person = personURLToVO.get(personURLNode.toString());
} else {
person = new SubEntity(personURLNode.toString());
personURLToVO.put(personURLNode.toString(), person);
}
RDFNode personLabelNode = solution.get(QueryFieldLabels.PERSON_LABEL);
if (personLabelNode != null) {
person.setIndividualLabel(personLabelNode.toString());
}
// entity.addSubEntity(person);
person.addPublications(biboDocument);
}
entity.addPublications(biboDocument); entity.addPublications(biboDocument);
} }
if(subentityURLToVO.size() == 0){
for(SubEntity person : personURLToVO.values()){
entity.addSubEntity(person);
}
}
//TODO: return non-null value
return entity; return entity;
} }
@ -168,79 +196,25 @@ public class EntityPublicationCountQueryRunner implements QueryRunner<Entity> {
QueryExecution queryExecution = null; QueryExecution queryExecution = null;
Query query = QueryFactory.create( Query query = QueryFactory.create(
getSparqlQuery(queryURI, this.visMode), SYNTAX); getSparqlQuery(queryURI), SYNTAX);
queryExecution = QueryExecutionFactory.create(query, dataSource); queryExecution = QueryExecutionFactory.create(query, dataSource);
return queryExecution.execSelect(); return queryExecution.execSelect();
} }
private String getSparqlQuery(String queryURI) {
private String getSparqlQuery(String queryURI, String visMode) {
String result = ""; String result = "";
if (visMode.equals("DEPARTMENT")) { ENTITY_URL = QueryFieldLabels.ORGANIZATION_URL;
// result = getSparqlQueryForDepartment(queryURI); ENTITY_LABEL = QueryFieldLabels.ORGANIZATION_LABEL;
ENTITY_URL = QueryFieldLabels.DEPARTMENT_URL; SUBENTITY_URL = QueryFieldLabels.SUBORGANIZATION_URL;
ENTITY_LABEL = QueryFieldLabels.DEPARTMENT_LABEL; SUBENTITY_LABEL = QueryFieldLabels.SUBORGANIZATION_LABEL;
SUBENTITY_URL = QueryFieldLabels.PERSON_URL;
SUBENTITY_LABEL = QueryFieldLabels.PERSON_LABEL;
} else {
// result = getSparqlQueryForOrganization(queryURI);
ENTITY_URL = QueryFieldLabels.ORGANIZATION_URL;
ENTITY_LABEL = QueryFieldLabels.ORGANIZATION_LABEL;
SUBENTITY_URL = QueryFieldLabels.SUBORGANIZATION_URL;
SUBENTITY_LABEL = QueryFieldLabels.SUBORGANIZATION_LABEL;
}
result = getSparqlQueryForOrganization(queryURI); result = getSparqlQueryForOrganization(queryURI);
return result; return result;
} }
// private String getSparqlQueryForDepartment(String queryURI) {
//
// String sparqlQuery = QueryConstants.getSparqlPrefixQuery()
// + "SELECT (str(?DepartmentLabel) as ?departmentLabelLit) "
// + SPARQL_QUERY_COMMON_SELECT_CLAUSE + " (str(<" + queryURI
// + ">) as ?" + QueryFieldLabels.DEPARTMENT_URL + ") "
// + "WHERE { " + "<" + queryURI + "> rdf:type core:Department ;"
// + " rdfs:label ?DepartmentLabel ;"
// + " core:organizationForPosition ?Position . "
// + " ?Position rdf:type core:Position ;"
// + " core:positionForPerson ?Person . "
// + " ?Person core:authorInAuthorship ?Resource ; "
// + " rdfs:label ?PersonLabel ; core:personInPosition ?SecondaryPosition . "
// + " ?Resource core:linkedInformationResource ?Document ."
// + " ?SecondaryPosition rdfs:label ?SecondaryPositionLabel ."
// + SPARQL_QUERY_COMMON_WHERE_CLAUSE + "}"
// + " ORDER BY ?DocumentLabel";
// System.out.println("\nThe sparql query is :\n" + sparqlQuery);
// return sparqlQuery;
//
// }
// private String getSparqlQueryForOrganization(String queryURI) {
//
// String sparqlQuery = QueryConstants.getSparqlPrefixQuery()
// + "SELECT (str(?organizationLabel) as ?organizationLabelLit) "
// + " (str(?subOrganization) as ?subOrganizationLit) "
// + " (str(?subOrganizationLabel) as ?subOrganizationLabelLit) "
// + SPARQL_QUERY_COMMON_SELECT_CLAUSE + " (str(<" + queryURI
// + ">) as ?" + QueryFieldLabels.ORGANIZATION_URL + ") "
// + "WHERE { " + "<" + queryURI + "> rdf:type foaf:Organization ;"
// + " rdfs:label ?organizationLabel ;"
// + " core:hasSubOrganization ?subOrganization ."
// + " ?subOrganization rdfs:label ?subOrganizationLabel ;"
// + " core:organizationForPosition ?Position . "
// + " ?Position rdf:type core:Position ;"
// + " core:positionForPerson ?Person . "
// + " ?Person core:authorInAuthorship ?Resource ; "
// + " rdfs:label ?PersonLabel ; core:personInPosition ?SecondaryPosition . "
// + " ?Resource core:linkedInformationResource ?Document ."
// + " ?SecondaryPosition rdfs:label ?SecondaryPositionLabel ."
// + SPARQL_QUERY_COMMON_WHERE_CLAUSE + "}"
// + " ORDER BY ?DocumentLabel";
// System.out.println("\nThe sparql query is :\n" + sparqlQuery);
// return sparqlQuery;
//
// }
private String getSparqlQueryForOrganization(String queryURI){ private String getSparqlQueryForOrganization(String queryURI){
@ -248,7 +222,6 @@ public class EntityPublicationCountQueryRunner implements QueryRunner<Entity> {
+ "SELECT (str(?organizationLabel) as ?organizationLabelLit) " + "SELECT (str(?organizationLabel) as ?organizationLabelLit) "
+ " (str(?subOrganization) as ?subOrganizationLit) " + " (str(?subOrganization) as ?subOrganizationLit) "
+ " (str(?subOrganizationLabel) as ?subOrganizationLabelLit) " + " (str(?subOrganizationLabel) as ?subOrganizationLabelLit) "
+ " (str(?DepartmentLabel) as ?departmentLabelLit) "
+ SPARQL_QUERY_COMMON_SELECT_CLAUSE + " (str(<" + queryURI + SPARQL_QUERY_COMMON_SELECT_CLAUSE + " (str(<" + queryURI
+ ">) as ?" + ENTITY_URL + ") " + ">) as ?" + ENTITY_URL + ") "
+ "WHERE { " + "<" + queryURI + "> rdf:type foaf:Organization ;" + "WHERE { " + "<" + queryURI + "> rdf:type foaf:Organization ;"
@ -263,7 +236,7 @@ public class EntityPublicationCountQueryRunner implements QueryRunner<Entity> {
+ SPARQL_QUERY_COMMON_WHERE_CLAUSE + "}" + SPARQL_QUERY_COMMON_WHERE_CLAUSE + "}"
+ "UNION " + "UNION "
+ "{ " + "{ "
+ "<" + queryURI + "> rdf:type core:Department ; rdfs:label ?DepartmentLabel ; core:organizationForPosition ?Position ." + "<" + queryURI + "> core:organizationForPosition ?Position ."
+ " ?Position rdf:type core:Position ; core:positionForPerson ?Person ." + " ?Position rdf:type core:Position ; core:positionForPerson ?Person ."
+ " ?Person core:authorInAuthorship ?Resource ; rdfs:label ?PersonLabel ; core:personInPosition ?SecondaryPosition . " + " ?Person core:authorInAuthorship ?Resource ; rdfs:label ?PersonLabel ; core:personInPosition ?SecondaryPosition . "
+ " ?Resource core:linkedInformationResource ?Document ." + " ?Resource core:linkedInformationResource ?Document ."
@ -271,6 +244,7 @@ public class EntityPublicationCountQueryRunner implements QueryRunner<Entity> {
+ SPARQL_QUERY_COMMON_WHERE_CLAUSE + "}" + SPARQL_QUERY_COMMON_WHERE_CLAUSE + "}"
+ "}"; + "}";
//System.out.println("\n\nEntity Pub Count query is: "+ sparqlQuery);
log.debug("\nThe sparql query is :\n" + sparqlQuery); log.debug("\nThe sparql query is :\n" + sparqlQuery);
return sparqlQuery; return sparqlQuery;
@ -289,7 +263,7 @@ public class EntityPublicationCountQueryRunner implements QueryRunner<Entity> {
if (iri.hasViolation(false)) { if (iri.hasViolation(false)) {
String errorMsg = ((Violation) iri.violations(false).next()) String errorMsg = ((Violation) iri.violations(false).next())
.getShortMessage(); .getShortMessage();
log.error("Entity Comparison vis Query " + errorMsg); log.error("Entity Pub Count Query Query " + errorMsg);
throw new MalformedQueryParametersException( throw new MalformedQueryParametersException(
"URI provided for an entity is malformed."); "URI provided for an entity is malformed.");
} }

View file

@ -2,8 +2,6 @@
package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.entitycomparison; package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.entitycomparison;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
@ -11,11 +9,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -24,7 +17,6 @@ import com.google.gson.Gson;
import com.hp.hpl.jena.query.DataSource; import com.hp.hpl.jena.query.DataSource;
import edu.cornell.mannlib.vitro.webapp.beans.Portal; import edu.cornell.mannlib.vitro.webapp.beans.Portal;
import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; 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.ResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
@ -42,10 +34,6 @@ import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.Visual
public class EntityPublicationCountRequestHandler implements public class EntityPublicationCountRequestHandler implements
VisualizationRequestHandler { VisualizationRequestHandler {
/*
* Vis container holds the "id" of the div on the final response html page
* that the visualization actually appears on.
*/
public static String ENTITY_VIS_MODE; public static String ENTITY_VIS_MODE;
public static String SUB_ENTITY_VIS_MODE; public static String SUB_ENTITY_VIS_MODE;
@ -61,21 +49,20 @@ public class EntityPublicationCountRequestHandler implements
ENTITY_VIS_MODE = vitroRequest ENTITY_VIS_MODE = vitroRequest
.getParameter(VisualizationFrameworkConstants.VIS_MODE_KEY); .getParameter(VisualizationFrameworkConstants.VIS_MODE_KEY);
String visContainer = vitroRequest
.getParameter(VisualizationFrameworkConstants.VIS_CONTAINER_KEY);
QueryRunner<Entity> queryManager = new EntityPublicationCountQueryRunner( QueryRunner<Entity> queryManager = new EntityPublicationCountQueryRunner(
entityURI, dataSource, log, ENTITY_VIS_MODE); entityURI, dataSource, log);
Entity entity = queryManager.getQueryResult(); Entity entity = queryManager.getQueryResult();
setVisModes(); setVisModes();
QueryRunner<Map<String, Set<String>>> queryManagerForsubOrganisationTypes = new EntitySubOrganizationTypesQueryRunner( QueryRunner<Map<String, Set<String>>> queryManagerForsubOrganisationTypes = new EntitySubOrganizationTypesQueryRunner(
entityURI, dataSource, log, ENTITY_VIS_MODE); entityURI, dataSource, log);
Map<String, Set<String>> subOrganizationTypesResult = queryManagerForsubOrganisationTypes.getQueryResult(); Map<String, Set<String>> subOrganizationTypesResult = queryManagerForsubOrganisationTypes
.getQueryResult();
return prepareStandaloneResponse(vitroRequest, return prepareStandaloneResponse(vitroRequest, entity, entityURI,
entity,entityURI, subOrganizationTypesResult); subOrganizationTypesResult);
} }
@ -88,14 +75,17 @@ public class EntityPublicationCountRequestHandler implements
String entityURI = vitroRequest String entityURI = vitroRequest
.getParameter(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY); .getParameter(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY);
ENTITY_VIS_MODE = vitroRequest
.getParameter(VisualizationFrameworkConstants.VIS_MODE_KEY);
QueryRunner<Entity> queryManager = new EntityPublicationCountQueryRunner( QueryRunner<Entity> queryManager = new EntityPublicationCountQueryRunner(
entityURI, dataSource, log, ENTITY_VIS_MODE); entityURI, dataSource, log);
Entity entity = queryManager.getQueryResult(); Entity entity = queryManager.getQueryResult();
setVisModes(); setVisModes();
QueryRunner<Map<String, Set<String>>> queryManagerForsubOrganisationTypes = new EntitySubOrganizationTypesQueryRunner( QueryRunner<Map<String, Set<String>>> queryManagerForsubOrganisationTypes = new EntitySubOrganizationTypesQueryRunner(
entityURI, dataSource, log, ENTITY_VIS_MODE); entityURI, dataSource, log);
Map<String, Set<String>> subOrganizationTypesResult = queryManagerForsubOrganisationTypes.getQueryResult(); Map<String, Set<String>> subOrganizationTypesResult = queryManagerForsubOrganisationTypes.getQueryResult();
@ -107,7 +97,7 @@ public class EntityPublicationCountRequestHandler implements
@Override @Override
public Object generateAjaxVisualization(VitroRequest vitroRequest, Log log, public Object generateAjaxVisualization(VitroRequest vitroRequest, Log log,
DataSource dataSource) throws MalformedQueryParametersException { DataSource dataSource) throws MalformedQueryParametersException {
throw new UnsupportedOperationException("Temporal Graph does not provide Ajax Response."); throw new UnsupportedOperationException("Entity Pub Count does not provide Ajax Response.");
} }
/** /**
@ -131,7 +121,7 @@ public class EntityPublicationCountRequestHandler implements
} }
String outputFileName = UtilityFunctions.slugify(entityLabel) String outputFileName = UtilityFunctions.slugify(entityLabel)
+ "_publications-per-year" + ".json"; + "_publications-per-year" + ".csv";
Map<String, String> fileData = new HashMap<String, String>(); Map<String, String> fileData = new HashMap<String, String>();
@ -141,7 +131,7 @@ public class EntityPublicationCountRequestHandler implements
fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY, fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY,
"application/octet-stream"); "application/octet-stream");
fileData.put(DataVisualizationController.FILE_CONTENT_KEY, fileData.put(DataVisualizationController.FILE_CONTENT_KEY,
writePublicationsOverTimeJSON(subentities, subOrganizationTypesResult)); getEntityPublicationsPerYearCSVContent(subentities, subOrganizationTypesResult));
return fileData; return fileData;
} }
@ -185,23 +175,23 @@ public class EntityPublicationCountRequestHandler implements
} }
} }
private void setEntityVisMode(JsonObject entityJson) {
if(entityJson.getOrganizationType().contains("Department")){
entityJson.setVisMode("DEPARTMENT");
}else if(entityJson.getOrganizationType().contains("School")){
entityJson.setVisMode("SCHOOL");
}else{
entityJson.setVisMode(SUB_ENTITY_VIS_MODE);
}
}
/** /**
* function to generate a json file for year <-> publication count mapping * function to generate a json file for year <-> publication count mapping
* @param subentities
* @param subOrganizationTypesResult * @param subOrganizationTypesResult
* @param log
*
* @param yearToPublicationCount
* @param responseWriter
* @param visMode
*/ */
private String writePublicationsOverTimeJSON(Set<SubEntity> subentities, Map<String, Set<String>> subOrganizationTypesResult) { private String writePublicationsOverTimeJSON(Set<SubEntity> subentities, Map<String, Set<String>> subOrganizationTypesResult) {
// System.out.println("\nsub entity vis mode ------>"
// + SUB_ENTITY_VIS_MODE + "\n");
Gson json = new Gson(); Gson json = new Gson();
Set<JsonObject> subEntitiesJson = new HashSet<JsonObject>(); Set<JsonObject> subEntitiesJson = new HashSet<JsonObject>();
@ -226,29 +216,44 @@ public class EntityPublicationCountRequestHandler implements
yearPubCount.add(currentPubYear); yearPubCount.add(currentPubYear);
} }
entityJson.setYearToPublicationCount(yearPubCount); entityJson.setYearToActivityCount(yearPubCount);
entityJson.getOrganizationType().addAll(subOrganizationTypesResult.get(entityJson.getLabel())); entityJson.getOrganizationType().addAll(subOrganizationTypesResult.get(entityJson.getLabel()));
entityJson.setEntityURI(subentity.getIndividualURI()); entityJson.setEntityURI(subentity.getIndividualURI());
setEntityVisMode(entityJson); setEntityVisMode(entityJson);
//entityJson.setVisMode(SUB_ENTITY_VIS_MODE);
subEntitiesJson.add(entityJson); subEntitiesJson.add(entityJson);
} }
// System.out.println("\nStopWords are "+ EntitySubOrganizationTypesQueryRunner.stopWords.toString() + "\n");
return json.toJson(subEntitiesJson); return json.toJson(subEntitiesJson);
} }
private void setEntityVisMode(JsonObject entityJson) { private String getEntityPublicationsPerYearCSVContent(Set<SubEntity> subentities, Map<String, Set<String>> subOrganizationTypesResult) {
if(entityJson.getOrganizationType().contains("Department")){
entityJson.setVisMode("DEPARTMENT"); StringBuilder csvFileContent = new StringBuilder();
}else if(entityJson.getOrganizationType().contains("School")){
entityJson.setVisMode("SCHOOL"); csvFileContent.append("Entity Name, Publication Count, Entity Type\n");
}else{
entityJson.setVisMode(SUB_ENTITY_VIS_MODE); for(SubEntity subEntity : subentities){
csvFileContent.append(StringEscapeUtils.escapeCsv(subEntity.getIndividualLabel()));
csvFileContent.append(", ");
csvFileContent.append(subEntity.getDocuments().size());
csvFileContent.append(", ");
StringBuilder joinedTypes = new StringBuilder();
for(String subOrganizationType : subOrganizationTypesResult.get(subEntity.getIndividualLabel())){
joinedTypes.append(subOrganizationType + "; ");
}
csvFileContent.append(StringEscapeUtils.escapeCsv(joinedTypes.toString()));
csvFileContent.append("\n");
} }
return csvFileContent.toString();
} }
} }

View file

@ -40,36 +40,23 @@ public class EntitySubOrganizationTypesQueryRunner implements QueryRunner<Map<St
private String entityURI; private String entityURI;
private DataSource dataSource; private DataSource dataSource;
private Log log; private Log log;
private String visMode;
static String SUBORGANISATION_LABEL;
static String SUBORGANISATION_TYPE_LABEL;
// public static Map<String, Integer> subOrganizationTypesToCount = new HashMap<String, Integer>();
// public static Set<String> stopWords = new HashSet<String>();
// public static Set<String> subOrganizations = new HashSet<String>();
// public static Set<String> STOP_WORDS = new HashSet<String>() {
// {
// add("Person");
// add("Organization");
// }
// };
private static final String SPARQL_QUERY_SELECT_CLAUSE = "" private static final String SPARQL_QUERY_SELECT_CLAUSE = ""
+ " (str(?organizationLabel) as ?"+QueryFieldLabels.ORGANIZATION_LABEL+") " + " (str(?organizationLabel) as ?"+QueryFieldLabels.ORGANIZATION_LABEL+") "
+ " (str(?subOrganizationLabel) as ?"+QueryFieldLabels.SUBORGANIZATION_LABEL+") " + " (str(?subOrganizationLabel) as ?"+QueryFieldLabels.SUBORGANIZATION_LABEL+") "
+ " (str(?subOrganizationType) as ?"+QueryFieldLabels.SUBORGANIZATION_TYPE +")" + " (str(?subOrganizationType) as ?"+QueryFieldLabels.SUBORGANIZATION_TYPE +")"
+ " (str(?subOrganizationTypeLabel) as ?"+QueryFieldLabels.SUBORGANIZATION_TYPE_LABEL+") "; + " (str(?subOrganizationTypeLabel) as ?"+QueryFieldLabels.SUBORGANIZATION_TYPE_LABEL+") "
+ " (str(?Person) as ?personLit) "
+ " (str(?PersonLabel) as ?personLabelLit) "
+ " (str(?PersonTypeLabel) as ?personTypeLabelLit) ";
public EntitySubOrganizationTypesQueryRunner(String entityURI, public EntitySubOrganizationTypesQueryRunner(String entityURI,
DataSource dataSource, Log log, String visMode){ DataSource dataSource, Log log){
this.entityURI = entityURI; this.entityURI = entityURI;
this.dataSource = dataSource; this.dataSource = dataSource;
this.log = log; this.log = log;
this.visMode = visMode;
// stopWords.clear();
// subOrganizations.clear();
// subOrganizationTypesToCount.clear();
} }
private ResultSet executeQuery(String queryURI, DataSource dataSource) { private ResultSet executeQuery(String queryURI, DataSource dataSource) {
@ -82,49 +69,35 @@ public class EntitySubOrganizationTypesQueryRunner implements QueryRunner<Map<St
} }
private String getSparqlQuery(String queryURI) { private String getSparqlQuery(String queryURI) {
String sparqlQuery = ""; String sparqlQuery = "";
if (!this.visMode.equals("DEPARTMENT")) { sparqlQuery = QueryConstants.getSparqlPrefixQuery()
+ "SELECT "
+ SPARQL_QUERY_SELECT_CLAUSE
+ " WHERE { "
+ "<"
+ queryURI
+ "> rdf:type foaf:Organization ;"
+ " rdfs:label ?organizationLabel . "
+ "{ "
+ "<"+ queryURI + "> core:hasSubOrganization ?subOrganization . "
+ "?subOrganization rdfs:label ?subOrganizationLabel ; rdf:type ?subOrganizationType . "
+ "?subOrganizationType rdfs:label ?subOrganizationTypeLabel . "
+ "}"
+ "UNION "
+ "{ "
+ "<"+ queryURI + "> core:organizationForPosition ?Position . "
+ "?Position rdf:type core:Position ; core:positionForPerson ?Person . "
+ "?Person rdfs:label ?PersonLabel ; rdf:type ?PersonType . "
+ "?PersonType rdfs:label ??PersonTypeLabel . "
+ "}"
+ "}";
SUBORGANISATION_LABEL = QueryFieldLabels.SUBORGANIZATION_LABEL;
SUBORGANISATION_TYPE_LABEL = QueryFieldLabels.SUBORGANIZATION_TYPE_LABEL;
sparqlQuery = QueryConstants.getSparqlPrefixQuery()
+ "SELECT "
+ SPARQL_QUERY_SELECT_CLAUSE
+ " WHERE { "
+ "<"
+ queryURI
+ "> rdf:type foaf:Organization ;"
+ " rdfs:label ?organizationLabel ;"
+ " core:hasSubOrganization ?subOrganization . "
+ " ?subOrganization rdfs:label ?subOrganizationLabel ;"
+ " rdf:type ?subOrganizationType . "
+ " ?subOrganizationType rdfs:label ?subOrganizationTypeLabel ."
+ "}";
} else{ //System.out.println("\n\nEntity SubOrganizationTypes query is: "+ sparqlQuery);
SUBORGANISATION_LABEL = QueryFieldLabels.PERSON_LABEL;
SUBORGANISATION_TYPE_LABEL = QueryFieldLabels.PERSON_TYPE_LABEL;
sparqlQuery = QueryConstants.getSparqlPrefixQuery()
+ "SELECT "
+ " (str(?departmentLabel) as ?"+QueryFieldLabels.DEPARTMENT_LABEL+") "
+ " (str(?personLabel) as ?"+QueryFieldLabels.PERSON_LABEL+") "
+ " (str(?personType) as ?"+QueryFieldLabels.PERSON_TYPE +")"
+ " (str(?personTypeLabel) as ?"+QueryFieldLabels.PERSON_TYPE_LABEL+") "
+ " WHERE { "
+ "<"
+ queryURI
+ "> rdf:type core:Department ;"
+ " rdfs:label ?departmentLabel ;"
+ " core:organizationForPosition ?position . "
+ " ?position rdf:type core:Position ; core:positionForPerson ?person . "
+ " ?person rdfs:label ?personLabel ;"
+ " rdf:type ?personType . "
+ " ?personType rdfs:label ?personTypeLabel ."
+ "}";;
}
log.debug("\nThe sparql query is :\n" + sparqlQuery); log.debug("\nThe sparql query is :\n" + sparqlQuery);
return sparqlQuery; return sparqlQuery;
} }
@ -132,57 +105,53 @@ public class EntitySubOrganizationTypesQueryRunner implements QueryRunner<Map<St
private Map<String, Set<String>> createJavaValueObjects(ResultSet resultSet) { private Map<String, Set<String>> createJavaValueObjects(ResultSet resultSet) {
Map<String, Set<String>> subOrganizationLabelToTypes = new HashMap<String, Set<String>>(); Map<String, Set<String>> subOrganizationLabelToTypes = new HashMap<String, Set<String>>();
Map<String, Set<String>> personLabelToTypes = new HashMap<String, Set<String>>();
while(resultSet.hasNext()){ while(resultSet.hasNext()){
QuerySolution solution = resultSet.nextSolution(); QuerySolution solution = resultSet.nextSolution();
RDFNode subOrganizationLabel = solution.get(SUBORGANISATION_LABEL); RDFNode subOrganizationLabel = solution.get(QueryFieldLabels.SUBORGANIZATION_LABEL);
if(subOrganizationLabelToTypes.containsKey(subOrganizationLabel.toString())){ if(subOrganizationLabel != null){
RDFNode subOrganizationType = solution.get(SUBORGANISATION_TYPE_LABEL); if(subOrganizationLabelToTypes.containsKey(subOrganizationLabel.toString())){
if(subOrganizationType != null){ RDFNode subOrganizationType = solution.get(QueryFieldLabels.SUBORGANIZATION_TYPE_LABEL);
subOrganizationLabelToTypes.get(subOrganizationLabel.toString()).add(subOrganizationType.toString()); if(subOrganizationType != null){
// updateSubOrganizationTypesToCount(subOrganizationType.toString()); subOrganizationLabelToTypes.get(subOrganizationLabel.toString()).add(subOrganizationType.toString());
// subOrganizations.add(subOrganizationLabel.toString()); }
}else{
RDFNode subOrganizationType = solution.get(QueryFieldLabels.SUBORGANIZATION_TYPE_LABEL);
if(subOrganizationType != null){
subOrganizationLabelToTypes.put(subOrganizationLabel.toString(), new HashSet<String>());
subOrganizationLabelToTypes.get(subOrganizationLabel.toString()).add(subOrganizationType.toString());
}
} }
}else{ }
RDFNode subOrganizationType = solution.get(SUBORGANISATION_TYPE_LABEL);
if(subOrganizationType != null){ RDFNode personLabel = solution.get(QueryFieldLabels.PERSON_LABEL);
subOrganizationLabelToTypes.put(subOrganizationLabel.toString(), new HashSet<String>());
subOrganizationLabelToTypes.get(subOrganizationLabel.toString()).add(subOrganizationType.toString()); if(personLabel != null){
// updateSubOrganizationTypesToCount(subOrganizationType.toString()); if(personLabelToTypes.containsKey(personLabel.toString())){
// subOrganizations.add(subOrganizationLabel.toString()); RDFNode personType = solution.get(QueryFieldLabels.PERSON_TYPE_LABEL);
if(personType != null && ! personType.toString().startsWith("http")){
personLabelToTypes.get(personLabel.toString()).add(personType.toString());
}
}else{
RDFNode personType = solution.get(QueryFieldLabels.PERSON_TYPE_LABEL);
if(personType != null && ! personType.toString().startsWith("http")){
personLabelToTypes.put(personLabel.toString(), new HashSet<String>());
personLabelToTypes.get(personLabel.toString()).add(personType.toString());
}
} }
} }
} }
// collectStopWords(); //System.out.println("\n\nSub Organization Label Types Size --> " + subOrganizationLabelToTypes.size());
//System.out.println("\n\nPeople Label Types Size --> " + personLabelToTypes.size());
return subOrganizationLabelToTypes; return (subOrganizationLabelToTypes.size() != 0 )? subOrganizationLabelToTypes : personLabelToTypes ;
} }
// private void collectStopWords() {
// System.out.println("Inside collectStopWords \n-----------------------------\n");
// for(Map.Entry<String, Integer> typesCount : subOrganizationTypesToCount.entrySet()){
// System.out.println(typesCount.getKey() + ": "+ typesCount.getValue());
// if(typesCount.getValue() >= subOrganizations.size()){
// stopWords.add(typesCount.getKey());
// }
// }
// }
//
// private void updateSubOrganizationTypesToCount(String typeLabel) {
// int count = 0;
// if(subOrganizationTypesToCount.containsKey(typeLabel)){
// count = subOrganizationTypesToCount.get(typeLabel);
// subOrganizationTypesToCount.put(typeLabel, ++count);
// }else{
// subOrganizationTypesToCount.put(typeLabel, 1);
// }
// }
public Map<String, Set<String>> getQueryResult() throws MalformedQueryParametersException { public Map<String, Set<String>> getQueryResult() throws MalformedQueryParametersException {
if (StringUtils.isNotBlank(this.entityURI)) { if (StringUtils.isNotBlank(this.entityURI)) {

View file

@ -0,0 +1,262 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.entitygrantcount;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import com.hp.hpl.jena.iri.IRI;
import com.hp.hpl.jena.iri.IRIFactory;
import com.hp.hpl.jena.iri.Violation;
import com.hp.hpl.jena.query.DataSource;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.Syntax;
import com.hp.hpl.jena.rdf.model.RDFNode;
import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryFieldLabels;
import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.Grant;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.Entity;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.SubEntity;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.QueryRunner;
/**
* This query runner is used to execute a sparql query that will fetch all the
* grants defined by core:Grant property for a particular
* department/school/university.
*
* Deepak Konidena
*
* @author bkoniden
*/
public class EntityGrantCountQueryRunner implements QueryRunner<Entity> {
protected static final Syntax SYNTAX = Syntax.syntaxARQ;
private String entityURI;
private DataSource dataSource;
private Log log;
private static final String SPARQL_QUERY_COMMON_SELECT_CLAUSE = "SELECT "
+ " (str(?organizationLabel) as ?organizationLabelLit) "
+ " (str(?subOrganization) as ?subOrganizationLit) "
+ " (str(?subOrganizationLabel) as ?subOrganizationLabelLit) "
+ " (str(?Person) as ?personLit) "
+ " (str(?PersonLabel) as ?personLabelLit) "
+ " (str(?SecondaryPositionLabel) as ?SecondaryPositionLabelLit)"
+ " (str(?Grant) as ?grantLit) "
+ " (str(?GrantLabel) as ?grantLabelLit) "
+ " (str(?GrantStartDate) as ?grantStartDateLit) "
+ " (str(?GrantEndDate) as ?grantEndDateLit) ";
private static final String SPARQL_QUERY_COMMON_WHERE_CLAUSE = " "
+ " ?SecondaryPosition rdfs:label ?SecondaryPositionLabel . "
+ " ?Role core:roleIn ?Grant . "
+ " ?Grant rdfs:label ?GrantLabel . "
+ " OPTIONAL { ?Grant core:startDate ?GrantStartDate } . "
+ " OPTIONAL { ?Grant core:endDate ?GrantEndDate } .";
private static String ENTITY_LABEL = QueryFieldLabels.ORGANIZATION_LABEL;
private static String ENTITY_URL = QueryFieldLabels.ORGANIZATION_URL;
private static String SUBENTITY_LABEL = QueryFieldLabels.SUBORGANIZATION_LABEL ;
private static String SUBENTITY_URL = QueryFieldLabels.SUBORGANIZATION_URL;
public EntityGrantCountQueryRunner(String entityURI,
DataSource dataSource, Log log) {
this.entityURI = entityURI;
this.dataSource = dataSource;
this.log = log;
}
private Entity createJavaValueObjects(ResultSet resultSet) {
Entity entity = null;
Map<String, Grant> grantURIToVO = new HashMap<String, Grant>();
Map<String, SubEntity> subentityURLToVO = new HashMap<String, SubEntity>();
Map<String, SubEntity> personURLToVO = new HashMap<String, SubEntity>();
while (resultSet.hasNext()) {
QuerySolution solution = resultSet.nextSolution();
if (entity == null) {
entity = new Entity(solution.get(ENTITY_URL).toString(),
solution.get(ENTITY_LABEL).toString());
}
RDFNode grantNode = solution.get(QueryFieldLabels.GRANT_URL);
Grant grant;
if (grantURIToVO.containsKey(grantNode.toString())) {
grant = grantURIToVO.get(grantNode.toString());
} else {
grant = new Grant(grantNode.toString());
grantURIToVO.put(grantNode.toString(), grant);
RDFNode grantLabelNode = solution
.get(QueryFieldLabels.GRANT_LABEL);
if (grantLabelNode != null) {
grant.setGrantLabel(grantLabelNode.toString());
}
RDFNode grantStartDateNode = solution.get(QueryFieldLabels.GRANT_START_DATE);
if(grantStartDateNode != null){
grant.setGrantStartDate(grantStartDateNode.toString());
}
RDFNode grantEndDateNode = solution.get(QueryFieldLabels.GRANT_END_DATE);
if(grantEndDateNode != null){
grant.setGrantEndDate(grantEndDateNode.toString());
}
}
RDFNode subEntityURLNode = solution.get(SUBENTITY_URL);
if (subEntityURLNode != null) {
SubEntity subEntity;
if (subentityURLToVO.containsKey(subEntityURLNode.toString())) {
subEntity = subentityURLToVO.get(subEntityURLNode
.toString());
} else {
subEntity = new SubEntity(subEntityURLNode.toString());
subentityURLToVO
.put(subEntityURLNode.toString(), subEntity);
}
RDFNode subEntityLabelNode = solution.get(SUBENTITY_LABEL);
if (subEntityLabelNode != null) {
subEntity.setIndividualLabel(subEntityLabelNode.toString());
}
entity.addSubEntity(subEntity);
subEntity.addGrants(grant);
}
RDFNode personURLNode = solution.get(QueryFieldLabels.PERSON_URL);
if(personURLNode != null){
SubEntity person ;
if(personURLToVO.containsKey(personURLNode.toString())) {
person = personURLToVO.get(personURLNode.toString());
} else {
person = new SubEntity(personURLNode.toString());
personURLToVO.put(personURLNode.toString(), person);
}
RDFNode personLabelNode = solution.get(QueryFieldLabels.PERSON_LABEL);
if (personLabelNode != null) {
person.setIndividualLabel(personLabelNode.toString());
}
// entity.addSubEntity(person);
person.addGrants(grant);
}
entity.addGrants(grant);
}
if(subentityURLToVO.size() == 0){
for(SubEntity person : personURLToVO.values()){
entity.addSubEntity(person);
}
}
return entity;
}
private ResultSet executeQuery(String queryURI, DataSource dataSource) {
QueryExecution queryExecution = null;
Query query = QueryFactory.create(
getSparqlQuery(queryURI), SYNTAX);
queryExecution = QueryExecutionFactory.create(query, dataSource);
return queryExecution.execSelect();
}
private String getSparqlQuery(String queryURI){
String sparqlQuery = QueryConstants.getSparqlPrefixQuery()
+ SPARQL_QUERY_COMMON_SELECT_CLAUSE + " (str(<" + queryURI
+ ">) as ?" + ENTITY_URL + ") "
+ "WHERE { " + "<" + queryURI + "> rdf:type foaf:Organization ;"
+ " rdfs:label ?organizationLabel ."
+ "{ "
+ "<" + queryURI + "> core:hasSubOrganization ?subOrganization ."
+ " ?subOrganization rdfs:label ?subOrganizationLabel ; core:organizationForPosition ?Position . "
+ " ?Position rdf:type core:Position ; core:positionForPerson ?Person ."
+ " ?Person core:hasCo-PrincipalInvestigatorRole ?Role ; rdfs:label ?PersonLabel ; core:personInPosition ?SecondaryPosition . "
+ SPARQL_QUERY_COMMON_WHERE_CLAUSE + "}"
+ "UNION "
+ "{ "
+ "<" + queryURI + "> core:hasSubOrganization ?subOrganization . "
+ " ?subOrganization rdfs:label ?subOrganizationLabel ; core:organizationForPosition ?Position . "
+ " ?Position rdf:type core:Position ; core:positionForPerson ?Person ."
+ " ?Person core:hasPrincipalInvestigatorRole ?Role ; rdfs:label ?PersonLabel ; core:personInPosition ?SecondaryPosition . "
+ SPARQL_QUERY_COMMON_WHERE_CLAUSE + "}"
+ "UNION "
+ "{ "
+ "<" + queryURI + "> core:organizationForPosition ?Position . "
+ " ?Position rdf:type core:Position ; core:positionForPerson ?Person ."
+ " ?Person core:hasCo-PrincipalInvestigatorRole ?Role ; rdfs:label ?PersonLabel ; core:personInPosition ?SecondaryPosition . "
+ SPARQL_QUERY_COMMON_WHERE_CLAUSE + "}"
+ "UNION "
+ "{ "
+ "<" + queryURI + "> core:organizationForPosition ?Position . "
+ " ?Position rdf:type core:Position ; core:positionForPerson ?Person ."
+ " ?Person core:hasPrincipalInvestigatorRole ?Role ; rdfs:label ?PersonLabel ; core:personInPosition ?SecondaryPosition . "
+ SPARQL_QUERY_COMMON_WHERE_CLAUSE + "}"
+ " } ";
//System.out.println("\n\nEntity Grant Count query is: "+ sparqlQuery);
log.debug("\nThe sparql query is :\n" + sparqlQuery);
return sparqlQuery;
}
public Entity getQueryResult() throws MalformedQueryParametersException {
if (StringUtils.isNotBlank(this.entityURI)) {
/*
* To test for the validity of the URI submitted.
*/
IRIFactory iRIFactory = IRIFactory.jenaImplementation();
IRI iri = iRIFactory.create(this.entityURI);
if (iri.hasViolation(false)) {
String errorMsg = ((Violation) iri.violations(false).next())
.getShortMessage();
log.error("Entity Grant Count Query " + errorMsg);
throw new MalformedQueryParametersException(
"URI provided for an entity is malformed.");
}
} else {
throw new MalformedQueryParametersException(
"URL parameter is either null or empty.");
}
ResultSet resultSet = executeQuery(this.entityURI, this.dataSource);
return createJavaValueObjects(resultSet);
}
}

View file

@ -0,0 +1,270 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.entitygrantcount;
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.DataSource;
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.VisualizationFrameworkConstants;
import edu.cornell.mannlib.vitro.webapp.controller.visualization.freemarker.DataVisualizationController;
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.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.QueryRunner;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.entitycomparison.EntitySubOrganizationTypesQueryRunner;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.UtilityFunctions;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.VisualizationRequestHandler;
public class EntityGrantCountRequestHandler implements
VisualizationRequestHandler {
public static String ENTITY_VIS_MODE;
public static String SUB_ENTITY_VIS_MODE;
@Override
public ResponseValues generateStandardVisualization(
VitroRequest vitroRequest, Log log, DataSource dataSource)
throws MalformedQueryParametersException {
String entityURI = vitroRequest
.getParameter(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY);
QueryRunner<Entity> queryManager = new EntityGrantCountQueryRunner(
entityURI, dataSource, log);
Entity entity = queryManager.getQueryResult();
ENTITY_VIS_MODE = vitroRequest
.getParameter(VisualizationFrameworkConstants.VIS_MODE_KEY);
setVisModes();
// for(SubEntity se : entity.getSubEntities()){
// System.out.println("se key -->" + se.getIndividualLabel());
// }
QueryRunner<Map<String, Set<String>>> queryManagerForsubOrganisationTypes = new EntitySubOrganizationTypesQueryRunner(
entityURI, dataSource, log);
Map<String, Set<String>> subOrganizationTypesResult = queryManagerForsubOrganisationTypes.getQueryResult();
// for(Map.Entry soTR : subOrganizationTypesResult.entrySet()){
// System.out.println("soTR key -->" + soTR.getKey());
// }
//
// System.out.println();
return prepareStandaloneResponse(vitroRequest,
entity,entityURI, subOrganizationTypesResult);
}
@Override
public Map<String, String> generateDataVisualization(
VitroRequest vitroRequest, Log log, DataSource dataSource)
throws MalformedQueryParametersException {
String entityURI = vitroRequest
.getParameter(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY);
ENTITY_VIS_MODE = vitroRequest
.getParameter(VisualizationFrameworkConstants.VIS_MODE_KEY);
setVisModes();
QueryRunner<Entity> queryManager = new EntityGrantCountQueryRunner(
entityURI, dataSource, log);
Entity entity = queryManager.getQueryResult();
QueryRunner<Map<String, Set<String>>> queryManagerForsubOrganisationTypes = new EntitySubOrganizationTypesQueryRunner(
entityURI, dataSource, log);
Map<String, Set<String>> subOrganizationTypesResult = queryManagerForsubOrganisationTypes.getQueryResult();
return prepareDataResponse(entity, entity.getSubEntities(),subOrganizationTypesResult);
}
@Override
public Object generateAjaxVisualization(VitroRequest vitroRequest, Log log,
DataSource dataSource) throws MalformedQueryParametersException {
throw new UnsupportedOperationException("Entity Grant Count does not provide Ajax Response.");
}
/**
* 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, Set<SubEntity> subentities,
Map<String, Set<String>> subOrganizationTypesResult) {
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(subentities, subOrganizationTypesResult));
return fileData;
}
/**
*
* @param vreq
* @param valueObjectContainer
* @return
*/
private TemplateResponseValues prepareStandaloneResponse(VitroRequest vreq,
Entity entity, String entityURI, Map<String, Set<String>> subOrganizationTypesResult) {
Portal portal = vreq.getPortal();
String standaloneTemplate = "entityComparisonStandaloneActivator.ftl";
String jsonContent = "";
jsonContent = writeGrantsOverTimeJSON(entity.getSubEntities(), subOrganizationTypesResult);
Map<String, Object> body = new HashMap<String, Object>();
body.put("portalBean", portal);
body.put("title", "Temporal Graph Visualization");
body.put("organizationURI", entityURI);
body.put("organizationLabel", entity.getEntityLabel());
body.put("jsonContent", jsonContent);
return new TemplateResponseValues(standaloneTemplate, body);
}
private void setVisModes() {
if (ENTITY_VIS_MODE.equalsIgnoreCase("DEPARTMENT")) {
SUB_ENTITY_VIS_MODE = "PERSON";
}else if (ENTITY_VIS_MODE.equalsIgnoreCase("SCHOOL")) {
SUB_ENTITY_VIS_MODE = "DEPARTMENT";
}else {
SUB_ENTITY_VIS_MODE = "SCHOOL";
}
}
/**
* function to generate a json file for year <-> grant count mapping
* @param subentities
* @param subOrganizationTypesResult
*/
private String writeGrantsOverTimeJSON(Set<SubEntity> subentities, Map<String, Set<String>> subOrganizationTypesResult) {
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
.getYearToGrantCount(subentity.getGrants())
.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.getOrganizationType().addAll(subOrganizationTypesResult.get(entityJson.getLabel()));
entityJson.setEntityURI(subentity.getIndividualURI());
setEntityVisMode(entityJson);
subEntitiesJson.add(entityJson);
}
// System.out.println("\nStopWords are "+ EntitySubOrganizationTypesQueryRunner.stopWords.toString() + "\n");
return json.toJson(subEntitiesJson);
}
private void setEntityVisMode(JsonObject entityJson) {
if(entityJson.getOrganizationType().contains("Department")){
entityJson.setVisMode("DEPARTMENT");
}else if(entityJson.getOrganizationType().contains("School")){
entityJson.setVisMode("SCHOOL");
}else{
entityJson.setVisMode(SUB_ENTITY_VIS_MODE);
}
}
private String getEntityGrantsPerYearCSVContent(Set<SubEntity> subentities, Map<String, Set<String>> subOrganizationTypesResult) {
StringBuilder csvFileContent = new StringBuilder();
csvFileContent.append("Entity Name, Grant Count, Entity Type\n");
for(SubEntity subEntity : subentities){
csvFileContent.append(StringEscapeUtils.escapeCsv(subEntity.getIndividualLabel()));
csvFileContent.append(", ");
csvFileContent.append(subEntity.getGrants().size());
csvFileContent.append(", ");
StringBuilder joinedTypes = new StringBuilder();
for(String subOrganizationType : subOrganizationTypesResult.get(subEntity.getIndividualLabel())){
joinedTypes.append(subOrganizationType + "; ");
}
csvFileContent.append(StringEscapeUtils.escapeCsv(joinedTypes.toString()));
csvFileContent.append("\n");
}
return csvFileContent.toString();
}
}

View file

@ -14,6 +14,7 @@ public class Entity extends Individual{
Set<BiboDocument> publications = new HashSet<BiboDocument>(); Set<BiboDocument> publications = new HashSet<BiboDocument>();
Set<SubEntity> children = new LinkedHashSet<SubEntity>(); Set<SubEntity> children = new LinkedHashSet<SubEntity>();
Set<Grant> grants = new HashSet<Grant>();
public Entity(String departmentURI, String departmentLabel){ public Entity(String departmentURI, String departmentLabel){
super(departmentURI, departmentLabel); super(departmentURI, departmentLabel);
@ -48,4 +49,8 @@ public class Entity extends Individual{
} }
public void addGrants(Grant grant) {
this.grants.add(grant);
}
} }

View file

@ -33,6 +33,10 @@ public class Grant extends Individual {
public String getGrantLabel(){ public String getGrantLabel(){
return this.getIndividualLabel(); return this.getIndividualLabel();
} }
public void setGrantLabel(String grantLabel) {
this.setIndividualLabel(grantLabel);
}
/** /**
* This method will be called when there is no usable core:year value found * This method will be called when there is no usable core:year value found
* for the bibo:Document. It will first check & parse core:yearMonth failing * for the bibo:Document. It will first check & parse core:yearMonth failing

View file

@ -59,18 +59,21 @@ public class JsonObject {
this.label = label; this.label = label;
} }
public List<List<Integer>> getYearToPublicationCount() { public List<List<Integer>> getYearToActivityCount() {
return data; return data;
} }
public JsonObject(String label){ public JsonObject(String label){
this.label = label; this.label = label;
} }
public void setYearToPublicationCount(List<List<Integer>> yearToPublicationCount){ public void setYearToActivityCount(List<List<Integer>> yearToPublicationCount){
this.data = yearToPublicationCount; this.data = yearToPublicationCount;
} }
public void setYearToGrantCount(List<List<Integer>> yearGrantCount) {
}
} }

View file

@ -14,12 +14,13 @@ public class SubEntity extends Individual {
Set<BiboDocument> publications = new HashSet<BiboDocument>(); Set<BiboDocument> publications = new HashSet<BiboDocument>();
Map<String, Map<String, String>> personToPositionAndStartYear = new HashMap<String, Map<String, String>>(); Map<String, Map<String, String>> personToPositionAndStartYear = new HashMap<String, Map<String, String>>();
Set<Grant> grants = new HashSet<Grant>();
public SubEntity(String individualURI) { public SubEntity(String individualURI) {
super(individualURI); super(individualURI);
} }
public Map<String, Map<String, String>> getPersonToPositionAndStartYear() { public Map<String, Map<String, String>> getPersonToPositionAndStartYear() {
return personToPositionAndStartYear; return personToPositionAndStartYear;
} }
@ -33,6 +34,10 @@ public class SubEntity extends Individual {
return publications; return publications;
} }
public Set<Grant> getGrants() {
return grants;
}
public SubEntity(String individualURI, String individualLabel) { public SubEntity(String individualURI, String individualLabel) {
super(individualURI, individualLabel); super(individualURI, individualLabel);
} }
@ -56,4 +61,9 @@ public class SubEntity extends Individual {
public void addPublications(BiboDocument biboDocument) { public void addPublications(BiboDocument biboDocument) {
this.publications.add(biboDocument); this.publications.add(biboDocument);
} }
public void addGrants(Grant grant) {
this.grants.add(grant);
}
} }