1. Development related to a prototype of Temporal vis for publications that will leverage the caching feature. Currently it uses the temporary cached models that are saved in a map.

This commit is contained in:
cdtank 2011-03-16 16:04:57 +00:00
parent 88aafb7dec
commit af0f3e5a3a
26 changed files with 1732 additions and 50 deletions

View file

@ -31,6 +31,9 @@
<bean id="entity_comparison"
class="edu.cornell.mannlib.vitro.webapp.visualization.freemarker.entitycomparison.EntityPublicationCountRequestHandler" />
<bean id="pub_temporal"
class="edu.cornell.mannlib.vitro.webapp.visualization.freemarker.entitycomparison.cached.EntityPublicationRequestHandler" />
<bean id="entity_grant_count"
class="edu.cornell.mannlib.vitro.webapp.visualization.freemarker.entitygrantcount.EntityGrantCountRequestHandler" />
@ -58,10 +61,21 @@
<entry key="person_level">
<ref bean="person_level"></ref>
</entry>
<entry key="entity_comparison">
<ref bean="entity_comparison"></ref>
</entry>
<entry key="entity_comparison">
<ref bean="entity_comparison"></ref>
</entry>
<!--
<entry key="entity_comparison">
<ref bean="pub_temporal"></ref>
</entry>
-->
<entry key="pub_temporal">
<ref bean="pub_temporal"></ref>
</entry>
<entry key="coprincipalinvestigator">
<ref bean="coprincipalinvestigator"></ref>

View file

@ -0,0 +1,220 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.visualization.cacheintercept;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Scanner;
import java.util.regex.Matcher;
import com.hp.hpl.jena.query.ARQ;
import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.sparql.ARQConstants;
import com.hp.hpl.jena.tdb.TDB;
import com.hp.hpl.jena.tdb.TDBFactory;
import com.hp.hpl.jena.util.FileManager;
import com.hp.hpl.jena.vocabulary.VCARD;
public class TDBResearch {
static final String directory = "testdb/" ;
public static void getModelInformation() {
// Direct way: Make a TDB-back Jena model in the named directory.
// String inputFileName = "query/entitygrants/select-all-grants.sparql";
// String inputFileName = "query/entitypublications/select-all-publications-f.sparql";
// String inputFileName = "query/organization/select-org-suborg.sparql";
String inputFileName = "query/test.sparql";
// String inputFileName = "query/subentitytypes/select-all-types.sparql";
InputStream in = FileManager.get().open( inputFileName );
if (in == null) {
throw new IllegalArgumentException( "File: " + inputFileName + " not found");
}
Scanner scanner =
new Scanner(FileManager.get().open( inputFileName )).useDelimiter("\\Z");
String contents = scanner.next();
// System.out.println(contents);
scanner.close();
Dataset ds = TDBFactory.createDataset(directory);
Model model = ds.getNamedModel("publication");
// organization publication
// Model model = ds.getDefaultModel();
// List<Statement> listStatements = model.listStatements().toList();
//
// for (Statement stmt : listStatements) {
//
// System.out.println(stmt);
//
// }
// System.out.println(listStatements);
// Potentially expensive query.
String sparqlQueryString;
// sparqlQueryString = "SELECT (count(*) AS ?count) { ?s ?p ?o }" ;
sparqlQueryString = contents.replaceAll(Matcher.quoteReplacement("$URI$"), "http://vivo.ufl.edu/individual/CollegeofDentistry");
// String sparqlQueryString = "SELECT * { GRAPH ?g { ?s ?p ?o } }" ;
// See http://www.openjena.org/ARQ/app_api.html
// String sparqlQueryString = "SELECT ?sub ?pre ?obj " + " { ?sub ?pre ?obj . }" ;
Query query = QueryFactory.create(sparqlQueryString) ;
// QueryExecution qexec = QueryExecutionFactory.create(query, ds);
QueryExecution qexec = QueryExecutionFactory.create(query, model);
ResultSet results = qexec.execSelect() ;
// try {
// OutputStream outputStream = new FileOutputStream("output/test.txt");
// ResultSetFormatter.out(outputStream, results) ;
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
//
ResultSetFormatter.out(results) ;
//
// while (results.hasNext()) {
////
// QuerySolution solution = results.nextSolution();
//
// System.out.println("solution: " + solution.toString());
//// System.out.println("------");
// //System.out.println(solution.get("count"));
//// System.out.println(solution.getResource("sub"));
//// System.out.println(solution.get("pre"));
//// System.out.println(solution.get("obj"));
// }
//
qexec.close() ;
ds.close();
}
public static void createModel() {
// String commonFilePath = "data/entitygrants/"; entitypublications organization
String commonFilePath = "data/organization/";
String ontologyFilePath = "data/common/prefixes.n3";
String[] inputFileName = {
commonFilePath + "test-custom-props.n3",
// commonFilePath + "college-education-pubs.n3",
// commonFilePath + "college-pediatric-dentistry-pubs.n3",
// commonFilePath + "college-dentistry-pubs.n3",
// college-education-pubs.n3 test-custom-props.n3 ufl-orgs-types.n3
};
String organizationModel = "";
Dataset ds = TDBFactory.createDataset(directory) ;
// Model model = ds.getDefaultModel();
// Model model = ds.getNamedModel("entitygrants"); organization publication
Model model = ds.getNamedModel("publication");
long before, after;
// Iterator it = model.listStatements();
//
// while (it.hasNext()) {
// System.out.println("org - " + it.next());
// }
//
System.out.println("model size " + model.size());
before = System.currentTimeMillis();
InputStream in = FileManager.get().open(ontologyFilePath);
if (in == null) {
throw new IllegalArgumentException( "File: " + ontologyFilePath + " not found");
}
// read the RDF/XML file
// model.read(in, null, "N3");
for (String nm : inputFileName) {
in = FileManager.get().open( nm );
if (in == null) {
throw new IllegalArgumentException( "File: " + nm + " not found");
}
// read the RDF/XML file
model.read(in, null, "N3");
// Resource johnSmith = model.createResource(personURI)
// .addProperty(VCARD.FN, fullName)
// .addProperty(VCARD.N,
// model.createResource()
// .addProperty(VCARD.Given, givenName)
// .addProperty(VCARD.Family, familyName));
//
// System.out.println("create model: " + johnSmith);
model.commit();
}
model.close();
// it = model.listStatements();
//
// while (it.hasNext()) {
// System.out.println("org deux - " + it.next());
// }
//
System.out.println("model empty - " + model.isEmpty());
System.out.println("read in model in tdb - " + (System.currentTimeMillis() - before));
ds.close();
}
public static void printCurrentModels() {
Dataset ds = TDBFactory.createDataset(directory) ;
Iterator<String> listNames = ds.listNames();
for (;listNames.hasNext();) {
System.out.println(listNames.next());
}
ds.close();
}
}

View file

@ -4,6 +4,7 @@ package edu.cornell.mannlib.vitro.webapp.controller.visualization.freemarker;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -38,6 +39,8 @@ public class AjaxVisualizationController extends FreemarkerHttpServlet {
private static final Log log = LogFactory.getLog(AjaxVisualizationController.class.getName());
protected static final Syntax SYNTAX = Syntax.syntaxARQ;
public static ServletContext servletContext;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)

View file

@ -2,6 +2,8 @@
package edu.cornell.mannlib.vitro.webapp.controller.visualization.freemarker;
import javax.servlet.ServletContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -31,6 +33,8 @@ public class StandardVisualizationController extends FreemarkerHttpServlet {
private static final Log log = LogFactory.getLog(StandardVisualizationController.class.getName());
protected static final Syntax SYNTAX = Syntax.syntaxARQ;
public static ServletContext servletContext;
@Override
protected ResponseValues processRequest(VitroRequest vreq) {
@ -42,6 +46,8 @@ public class StandardVisualizationController extends FreemarkerHttpServlet {
VisualizationRequestHandler visRequestHandler =
getVisualizationRequestHandler(vreq);
servletContext = getServletContext();
if (visRequestHandler != null) {
/*
@ -58,7 +64,6 @@ public class StandardVisualizationController extends FreemarkerHttpServlet {
vreq);
}
}

View file

@ -41,7 +41,9 @@ public class QueryConstants {
put("vivo", "http://vivo.library.cornell.edu/ns/0.1#");
put("j.1", "http://aims.fao.org/aos/geopolitical.owl#");
put("j.2", "http://vitro.mannlib.cornell.edu/ns/vitro/public#");
put("afn", "http://jena.hpl.hp.com/ARQ/function#");
put("vivosocnet", "http://vivo.cns.iu.edu/ns/#");
} };
public static String getSparqlPrefixQuery() {

View file

@ -172,7 +172,7 @@ public class EntityPublicationCountQueryRunner implements QueryRunner<Entity> {
}
entity.addActivity(biboDocument);
// entity.addActivity(biboDocument);
}
if (subentityURLToVO.size() == 0 && personURLToVO.size() == 0) {

View file

@ -53,6 +53,7 @@ public class EntityPublicationCountRequestHandler implements
vitroRequest);
}
return prepareStandaloneMarkupResponse(vitroRequest, entityURI);
}
@ -282,7 +283,7 @@ public class EntityPublicationCountRequestHandler implements
}
entityJson.setYearToActivityCount(yearPubCount);
entityJson.getOrganizationType().addAll(
entityJson.getOrganizationTypes().addAll(
subOrganizationTypesResult.get(entityJson.getLabel()));
entityJson.setEntityURI(subentity.getIndividualURI());

View file

@ -0,0 +1,633 @@
/* $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.Collection;
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.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.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.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.entitycomparison.EntityComparisonUtilityFunctions;
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.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.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.GenericQueryRunnerOnModel;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.QueryRunner;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.UtilityFunctions;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.VisualizationRequestHandler;
public class EntityPublicationRequestHandler implements
VisualizationRequestHandler {
public enum DataVisMode {
CSV, JSON
};
@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, DataVisMode visMode)
throws MalformedQueryParametersException {
Entity organizationEntity = getSubjectOrganizationHierarchy(dataset,
subjectEntityURI);
if (organizationEntity.getSubEntities() == null) {
if (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 = getPublicationsForAllSubOrganizations(dataset, organizationEntity);
Collection<SubEntity> associatedPeople = getSubjectOrganizationAssociatedPeople(dataset, subjectEntityURI);
if (!associatedPeople.isEmpty()) {
documentURIForAssociatedPeopleTOVO = getPublicationsForAssociatedPeople(dataset, associatedPeople);
organizationEntity.addSubEntitities(associatedPeople);
}
if (allDocumentURIToVOs.isEmpty() && documentURIForAssociatedPeopleTOVO.isEmpty()) {
if (DataVisMode.JSON.equals(visMode)) {
return prepareStandaloneDataErrorResponse();
} else {
return prepareDataErrorResponse();
}
} else {
if (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, 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 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;
}
private 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);
Entity organizationEntity = generateEntity(subjectEntityURI,
subOrganizationsWithTypesQuery.getQueryResult());
return organizationEntity;
}
private Collection<SubEntity> 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 getAssociatedPeopleSubEntitities(associatedPeopleWithTypesQuery.getQueryResult());
}
private Collection<SubEntity> getAssociatedPeopleSubEntitities(
ResultSet queryResult) {
Map<String, SubEntity> associatedPeopleURIToVO = new HashMap<String, SubEntity>();
while (queryResult.hasNext()) {
QuerySolution solution = queryResult.nextSolution();
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());
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());
}
}
return associatedPeopleURIToVO.values();
}
private 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 Entity generateEntity(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());
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;
}
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,
DataVisMode.JSON);
} else {
return getSubjectEntityAndGenerateDataResponse(
vitroRequest,
log,
dataset,
EntityComparisonUtilityFunctions
.getStaffProvidedOrComputedHighestLevelOrganization(
log,
dataset,
vitroRequest),
DataVisMode.JSON);
}
} else {
/*
* This provides csv download files for the content in the tables.
* */
return getSubjectEntityAndGenerateDataResponse(
vitroRequest,
log,
dataset,
entityURI,
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());
boolean isPerson = UtilityFunctions.isEntityAPerson(vreq, subentity);
if (isPerson) {
entityJson.setVisMode("PERSON");
} else {
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

@ -219,7 +219,7 @@ public class EntityGrantCountQueryRunner implements QueryRunner<Entity> {
}
entity.addActivity(grant);
// entity.addActivity(grant);
}
if (subentityURLToVO.size() == 0 && personURLToVO.size() == 0) {

View file

@ -283,7 +283,7 @@ public class EntityGrantCountRequestHandler implements
}
entityJson.setYearToActivityCount(yearGrantCount);
entityJson.getOrganizationType().addAll(
entityJson.getOrganizationTypes().addAll(
subOrganizationTypesResult.get(entityJson.getLabel()));
entityJson.setEntityURI(subentity.getIndividualURI());

View file

@ -0,0 +1,31 @@
/* $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.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(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

@ -0,0 +1,111 @@
/* $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 OrganizationAssociatedPeopleModelWithTypesConstructor implements ModelConstructor {
protected static final Syntax SYNTAX = Syntax.syntaxARQ;
public static final String MODEL_TYPE = "ORGANIZATION_ASSOCIATED_MODEL_WITH_TYPES";
private Dataset dataset;
private Model constructedModel;
private Log log = LogFactory.getLog(OrganizationAssociatedPeopleModelWithTypesConstructor.class.getName());
private long before, after;
private String organizationURI;
public OrganizationAssociatedPeopleModelWithTypesConstructor(String organizationURI, Dataset dataset) {
this.dataset = dataset;
this.organizationURI = organizationURI;
}
private String constructAssociatedPeopleForOrganizationWithTypesQuery() {
return ""
+ " CONSTRUCT { "
+ " <" + organizationURI + "> rdf:type foaf:Organization . "
+ " <" + organizationURI + "> rdfs:label ?organizationLabel . "
+ " <" + organizationURI + "> vivosocnet:hasPersonWithActivity ?Person . "
+ " ?Person rdfs:label ?personLabel. "
+ " ?Person rdf:type ?personType . "
+ " ?personType rdfs:label ?personTypeLabel . "
+ " } "
+ " WHERE { "
+ " <" + organizationURI + "> rdf:type foaf:Organization . "
+ " <" + organizationURI + "> rdfs:label ?organizationLabel . "
+ " OPTIONAL { "
+ " <" + organizationURI + "> core:organizationForPosition ?Position . "
+ " ?Position core:positionForPerson ?Person . "
+ " ?Person rdfs:label ?personLabel. "
+ " ?Person rdf:type ?personType . "
+ " ?personType rdfs:label ?personTypeLabel . "
+ " } "
+ " } ";
}
private Model executeQuery(String constructQuery) {
System.out.println("in constructed model for associated people for organization");
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 {
if (constructedModel != null && !constructedModel.isEmpty()) {
return constructedModel;
} else {
constructedModel = executeQuery(constructAssociatedPeopleForOrganizationWithTypesQuery());
return constructedModel;
}
}
}

View file

@ -0,0 +1,118 @@
/* $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.CachedModelConstructor;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.ModelConstructor;
public class OrganizationModelWithTypesConstructor implements ModelConstructor {
protected static final Syntax SYNTAX = Syntax.syntaxARQ;
public static final String MODEL_TYPE = "ORGANIZATION_MODEL_WITH_TYPES";
private Dataset dataset;
private Model constructedModel;
private Log log = LogFactory.getLog(OrganizationModelWithTypesConstructor.class.getName());
private long before, after;
public OrganizationModelWithTypesConstructor(Dataset dataset) {
this.dataset = dataset;
}
/**
* This constructor is present so that we can abstract out the model construction process.
* @param uri
* @param dataset
*/
public OrganizationModelWithTypesConstructor(String uri, Dataset dataset) {
this.dataset = dataset;
}
private String constructAllSubOrganizationsWithTypesQuery() {
return ""
+ " CONSTRUCT { "
+ " ?organization rdf:type foaf:Organization . "
+ " ?organization rdfs:label ?organizationLabel . "
+ " ?organization core:hasSubOrganization ?subOrganization . "
+ " ?subOrganization rdfs:label ?subOrganizationLabel . "
+ " ?subOrganization rdf:type ?subOrganizationType . "
+ " ?subOrganizationType rdfs:label ?subOrganizationTypeLabel . "
+ " } "
+ " WHERE { "
+ " ?organization rdf:type foaf:Organization . "
+ " ?organization rdfs:label ?organizationLabel . "
+ " "
+ " OPTIONAL { "
+ " ?organization core:hasSubOrganization ?subOrganization . "
+ " ?subOrganization rdfs:label ?subOrganizationLabel . "
+ " ?subOrganization rdf:type ?subOrganizationType . "
+ " ?subOrganizationType rdfs:label ?subOrganizationTypeLabel . "
+ " } "
+ " } ";
}
private Model executeQuery(String constructQuery) {
System.out.println("in constructed model fior organization");
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 {
if (constructedModel != null && !constructedModel.isEmpty()) {
return constructedModel;
} else {
constructedModel = executeQuery(constructAllSubOrganizationsWithTypesQuery());
return constructedModel;
}
}
}

View file

@ -0,0 +1,108 @@
/* $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 OrganizationToPublicationsForSubOrganizationsModelConstructor implements ModelConstructor {
protected static final Syntax SYNTAX = Syntax.syntaxARQ;
private Dataset dataset;
public static final String MODEL_TYPE = "ORGANIZATION_TO_PUBLICATIONS_FOR_SUBORGANIZATIONS";
private String organizationURI;
private Log log = LogFactory.getLog(OrganizationToPublicationsForSubOrganizationsModelConstructor.class.getName());
private long before, after;
public OrganizationToPublicationsForSubOrganizationsModelConstructor(String organizationURI, Dataset dataset) {
this.organizationURI = organizationURI;
this.dataset = dataset;
}
private String constructOrganizationToPublicationsPublicationInformationQuery() {
return ""
+ " CONSTRUCT { "
+ " <" + organizationURI + "> rdfs:label ?organizationLabel . "
+ " <" + organizationURI + "> vivosocnet:lastCachedAt ?now . "
+ " <" + organizationURI + "> vivosocnet:hasPersonWithPublication ?Document . "
+ " ?Document rdf:type bibo:Document . "
+ " ?Document rdfs:label ?DocumentLabel . "
+ " ?Document core:dateTimeValue ?dateTimeValue . "
+ " ?dateTimeValue core:dateTime ?publicationDate . "
+ " } "
+ " WHERE { "
+ " <" + organizationURI + "> rdfs:label ?organizationLabel . "
+ " <" + organizationURI + "> core:hasSubOrganization* ?subOrganization . "
+ " ?subOrganization core:organizationForPosition ?Position . "
+ " ?Position core:positionForPerson ?Person . "
+ " ?Person core:authorInAuthorship ?Resource . "
+ " ?Resource core:linkedInformationResource ?Document . "
+ " ?Document rdfs:label ?DocumentLabel . "
+ " "
+ " OPTIONAL { "
+ " ?Document core:dateTimeValue ?dateTimeValue . "
+ " ?dateTimeValue core:dateTime ?publicationDate . "
+ " } "
+ " "
+ " LET(?now := afn:now()) "
+ " } ";
}
private Model executeQuery(String constructQuery) {
System.out.println("in constructed model fior orgh to publications fo " + 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(constructOrganizationToPublicationsPublicationInformationQuery());
}
}

View file

@ -0,0 +1,102 @@
/* $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 PersonToPublicationsModelConstructor implements ModelConstructor {
protected static final Syntax SYNTAX = Syntax.syntaxARQ;
private Dataset dataset;
public static final String MODEL_TYPE = "PERSON_TO_PUBLICATIONS";
private String personURI;
private Log log = LogFactory.getLog(PersonToPublicationsModelConstructor.class.getName());
private long before, after;
public PersonToPublicationsModelConstructor(String personURI, Dataset dataset) {
this.personURI = personURI;
this.dataset = dataset;
}
private String constructPersonToPublicationsWithPublicationInformationQuery() {
return ""
+ " CONSTRUCT { "
+ " <" + personURI + "> vivosocnet:lastCachedAt ?now . "
+ " <" + personURI + "> vivosocnet:hasPublication ?Document . "
+ " ?Document rdf:type bibo:Document . "
+ " ?Document rdfs:label ?DocumentLabel . "
+ " ?Document core:dateTimeValue ?dateTimeValue . "
+ " ?dateTimeValue core:dateTime ?publicationDate . "
+ " } "
+ " WHERE { "
+ " <" + personURI + "> core:authorInAuthorship ?Resource . "
+ " ?Resource core:linkedInformationResource ?Document . "
+ " ?Document rdfs:label ?DocumentLabel . "
+ " "
+ " OPTIONAL { "
+ " ?Document core:dateTimeValue ?dateTimeValue . "
+ " ?dateTimeValue core:dateTime ?publicationDate . "
+ " } "
+ " "
+ " LET(?now := afn:now()) "
+ " } ";
}
private Model executeQuery(String constructQuery) {
System.out.println("in constructed model for person to publications " + personURI);
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(constructPersonToPublicationsWithPublicationInformationQuery());
}
}

View file

@ -0,0 +1,13 @@
/* $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;
public interface ModelFactoryInterface {
public Model getOrCreateModel(String uri, Dataset dataset) throws MalformedQueryParametersException;
}

View file

@ -0,0 +1,46 @@
/* $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.OrganizationAssociatedPeopleModelWithTypesConstructor;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.ConstructedModelTracker;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.ModelConstructor;
public class OrganizationAssociatedPeopleModelWithTypesFactory implements
ModelFactoryInterface {
@Override
public Model getOrCreateModel(String uri, Dataset dataset)
throws MalformedQueryParametersException {
Model candidateModel = ConstructedModelTracker.getModel(
ConstructedModelTracker
.generateModelIdentifier(
uri,
OrganizationAssociatedPeopleModelWithTypesConstructor.MODEL_TYPE));
if (candidateModel != null) {
return candidateModel;
} else {
ModelConstructor model = new OrganizationAssociatedPeopleModelWithTypesConstructor(uri, dataset);
Model constructedModel = model.getConstructedModel();
ConstructedModelTracker.trackModel(
ConstructedModelTracker
.generateModelIdentifier(
uri,
OrganizationAssociatedPeopleModelWithTypesConstructor.MODEL_TYPE),
constructedModel);
return constructedModel;
}
}
}

View file

@ -0,0 +1,42 @@
/* $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.OrganizationModelWithTypesConstructor;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.ConstructedModelTracker;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.ModelConstructor;
public class OrganizationModelWithTypesFactory implements ModelFactoryInterface {
@Override
public Model getOrCreateModel(String uri, Dataset dataset) throws MalformedQueryParametersException {
Model candidateModel = ConstructedModelTracker.getModel(
ConstructedModelTracker
.generateModelIdentifier(
null,
OrganizationModelWithTypesConstructor.MODEL_TYPE));
if (candidateModel != null) {
return candidateModel;
} else {
ModelConstructor model = new OrganizationModelWithTypesConstructor(dataset);
Model constructedModel = model.getConstructedModel();
ConstructedModelTracker.trackModel(
ConstructedModelTracker
.generateModelIdentifier(
null,
OrganizationModelWithTypesConstructor.MODEL_TYPE),
constructedModel);
return constructedModel;
}
}
}

View file

@ -0,0 +1,46 @@
/* $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.OrganizationToPublicationsForSubOrganizationsModelConstructor;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.ConstructedModelTracker;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.ModelConstructor;
public class OrganizationToPublicationsForSubOrganizationsFactory implements
ModelFactoryInterface {
@Override
public Model getOrCreateModel(String uri, Dataset dataset)
throws MalformedQueryParametersException {
Model candidateModel = ConstructedModelTracker.getModel(
ConstructedModelTracker
.generateModelIdentifier(
uri,
OrganizationToPublicationsForSubOrganizationsModelConstructor.MODEL_TYPE));
if (candidateModel != null) {
return candidateModel;
} else {
ModelConstructor model = new OrganizationToPublicationsForSubOrganizationsModelConstructor(uri, dataset);
Model constructedModel = model.getConstructedModel();
ConstructedModelTracker.trackModel(
ConstructedModelTracker
.generateModelIdentifier(
uri,
OrganizationToPublicationsForSubOrganizationsModelConstructor.MODEL_TYPE),
constructedModel);
return constructedModel;
}
}
}

View file

@ -0,0 +1,45 @@
/* $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.PersonToPublicationsModelConstructor;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects.ConstructedModelTracker;
import edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils.ModelConstructor;
public class PersonToPublicationsFactory implements ModelFactoryInterface {
@Override
public Model getOrCreateModel(String uri, Dataset dataset)
throws MalformedQueryParametersException {
Model candidateModel = ConstructedModelTracker.getModel(
ConstructedModelTracker
.generateModelIdentifier(
uri,
PersonToPublicationsModelConstructor.MODEL_TYPE));
if (candidateModel != null) {
return candidateModel;
} else {
ModelConstructor model = new PersonToPublicationsModelConstructor(uri, dataset);
Model constructedModel = model.getConstructedModel();
ConstructedModelTracker.trackModel(
ConstructedModelTracker
.generateModelIdentifier(
uri,
PersonToPublicationsModelConstructor.MODEL_TYPE),
constructedModel);
return constructedModel;
}
}
}

View file

@ -0,0 +1,33 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects;
import java.util.HashMap;
import java.util.Map;
import com.hp.hpl.jena.rdf.model.Model;
public class ConstructedModelTracker {
private static Map<String, Model> modelIdentifierToConstructedModel = new HashMap<String, Model>();
public static void trackModel(String identifier, Model model) {
modelIdentifierToConstructedModel.put(identifier, model);
}
public static Model getModel(String identifier) {
return modelIdentifierToConstructedModel.get(identifier);
}
public static String generateModelIdentifier(String uri, String modelType) {
if (uri == null) {
uri = "";
}
return modelType + "$" + uri;
}
public static Map<String, Model> getAllModels() {
return modelIdentifierToConstructedModel;
}
}

View file

@ -2,36 +2,29 @@
package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* @author bkoniden
* Deepak Konidena
*
* original @author bkoniden (Deepak Konidena)
* modified by @author cdtank (Chintan Tank)
*/
public class Entity extends Individual {
private Set<Activity> activities = new HashSet<Activity>();
private Set<SubEntity> children = new LinkedHashSet<SubEntity>();
public Entity(String departmentURI, String departmentLabel) {
super(departmentURI, departmentLabel);
public Entity(String entityURI, String entityLabel) {
super(entityURI, entityLabel);
}
public void setDepartmentLabel(String departmentURI) {
this.setIndividualLabel(departmentURI);
public Entity(String entityURI) {
super(entityURI);
}
public String getEntityURI() {
return this.getIndividualURI();
}
public Set<Activity> getActivities() {
return activities;
}
public String getEntityLabel() {
return this.getIndividualLabel();
}
@ -40,18 +33,12 @@ public class Entity extends Individual {
return children;
}
public void addActivity(Activity activity) {
this.activities.add(activity);
}
public void addSubEntity(SubEntity subEntity) {
this.children.add(subEntity);
}
public void addSubEntitities(Collection<SubEntity> subEntities) {
this.children.addAll(subEntities);
}
}

View file

@ -2,7 +2,10 @@
package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* JsonObject is used for creating data in JSON format,
@ -27,13 +30,19 @@ public class JsonObject {
this.stopWords = stopWords;
}
public List<String> getOrganizationType() {
public List<String> getOrganizationTypes() {
return organizationType;
}
public void setOrganizationType(List<String> organizationType) {
public void setOrganizationTypes(List<String> organizationType) {
this.organizationType = organizationType;
}
public void setOrganizationTypes(Set<String> givenOrganizationType) {
for (String type : givenOrganizationType) {
this.organizationType.add(type);
}
}
public String getEntityURI() {
return entityURI;

View file

@ -1,10 +1,9 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.valueobjects;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* @author bkoniden
@ -13,26 +12,12 @@ import java.util.HashSet;
public class SubEntity extends Individual {
private Set<Activity> activities = new HashSet<Activity>();
private Map<String, Map<String, String>> personToPositionAndStartYear =
new HashMap<String, Map<String, String>>();
private Set<String> entityTypes = new HashSet<String>();
public SubEntity(String individualURI) {
super(individualURI);
}
public Map<String, Map<String, String>> getPersonToPositionAndStartYear() {
return personToPositionAndStartYear;
}
public void setPersonToPositionAndStartYear(
Map<String, Map<String, String>> personToPositionAndStartYear) {
this.personToPositionAndStartYear = personToPositionAndStartYear;
}
public Set<Activity> getActivities() {
return activities;
}
public SubEntity(String individualURI, String individualLabel) {
super(individualURI, individualLabel);
}
@ -45,5 +30,21 @@ public class SubEntity extends Individual {
public void addActivity(Activity activity) {
this.activities.add(activity);
}
public void addActivities(Collection<Activity> activities) {
this.activities.addAll(activities);
}
public Set<Activity> getActivities() {
return activities;
}
public void addEntityTypeLabel(String typeLabel) {
this.entityTypes.add(typeLabel);
}
public Set<String> getEntityTypeLabels() {
return entityTypes;
}
}

View file

@ -0,0 +1,15 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.visualization.freemarker.visutils;
import com.hp.hpl.jena.rdf.model.Model;
import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException;
public interface CachedModelConstructor {
Model getConstructedModel() throws MalformedQueryParametersException;
String getModelType();
}

View file

@ -0,0 +1,97 @@
/* $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.Map;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.Syntax;
import com.hp.hpl.jena.rdf.model.Model;
import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException;
/**
* This query runner is used to run a generic sparql query based on the "select",
* "where" & "filter" rules provided to it.
*
* @author cdtank
*/
public class GenericQueryRunnerOnModel implements QueryRunner<ResultSet> {
protected static final Syntax SYNTAX = Syntax.syntaxARQ;
private String whereClause;
private Model model;
private Map<String, String> fieldLabelToOutputFieldLabel;
private String groupOrderClause;
private String aggregationRules;
public GenericQueryRunnerOnModel(Map<String, String> fieldLabelToOutputFieldLabel,
String aggregationRules,
String whereClause,
String groupOrderClause,
Model model) {
this.fieldLabelToOutputFieldLabel = fieldLabelToOutputFieldLabel;
this.aggregationRules = aggregationRules;
this.whereClause = whereClause;
this.groupOrderClause = groupOrderClause;
this.model = model;
}
private ResultSet executeQuery(String queryText,
Model dataset) {
QueryExecution queryExecution = null;
Query query = QueryFactory.create(queryText, SYNTAX);
queryExecution = QueryExecutionFactory.create(query, dataset);
return queryExecution.execSelect();
}
private String generateGenericSparqlQuery() {
StringBuilder sparqlQuery = new StringBuilder();
sparqlQuery.append(QueryConstants.getSparqlPrefixQuery());
sparqlQuery.append("SELECT\n");
for (Map.Entry<String, String> currentfieldLabelToOutputFieldLabel
: this.fieldLabelToOutputFieldLabel.entrySet()) {
sparqlQuery.append("\t(str(?" + currentfieldLabelToOutputFieldLabel.getKey() + ") as ?"
+ currentfieldLabelToOutputFieldLabel.getValue() + ")\n");
}
sparqlQuery.append("\n" + this.aggregationRules + "\n");
sparqlQuery.append("WHERE {\n");
sparqlQuery.append(this.whereClause);
sparqlQuery.append("}\n");
sparqlQuery.append(this.groupOrderClause);
return sparqlQuery.toString();
}
public ResultSet getQueryResult()
throws MalformedQueryParametersException {
ResultSet resultSet = executeQuery(generateGenericSparqlQuery(),
this.model);
return resultSet;
}
}