[VIVO-1690] - Remove trailing whitespace throughout project (#126)

* Remove trailing whitespace throughout project

Resolves: https://jira.duraspace.org/browse/VIVO-1690
** Along with: https://github.com/vivo-project/Vitro/pull/117
This commit is contained in:
Ben 2019-05-03 10:51:00 -06:00 committed by Andrew Woods
parent 48dcf87199
commit 87092cec9c
685 changed files with 26805 additions and 26805 deletions

View file

@ -1,397 +1,397 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.semservices.service.impl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import edu.cornell.mannlib.semservices.bo.Concept;
import edu.cornell.mannlib.semservices.service.ExternalConceptService;
import edu.cornell.mannlib.semservices.util.SKOSUtils;
import edu.cornell.mannlib.semservices.util.XMLUtils;
import edu.cornell.mannlib.vitro.webapp.utils.json.JacksonUtils;
import edu.cornell.mannlib.vitro.webapp.web.URLEncoder;
public class AgrovocService implements ExternalConceptService {
protected final Log logger = LogFactory.getLog(getClass());
private final String schemeUri = "http://aims.fao.org/aos/agrovoc/agrovocScheme";
private final String ontologyName = "agrovoc";
private final String format = "SKOS";
private final String lang = "en";
private final String searchMode = "starts with";//Used to be Exact Match, or exact word or starts with
protected final String dbpedia_endpoint = " http://dbpedia.org/sparql";
// URL to get all the information for a concept
protected final String conceptSkosMosBase = "http://agrovoc.uniroma2.it/agrovoc/rest/v1/";
protected final String conceptsSkosMosSearch = conceptSkosMosBase + "search?";
protected final String conceptSkosMosURL = conceptSkosMosBase + "data?";
@Override
public List<Concept> getConcepts(String term) throws Exception {
List<Concept> conceptList = new ArrayList<>();
//For the RDF webservices mechanism, utilize the following
/*
String result = getTermExpansion(this.ontologyName, term,
this.searchMode, this.format, this.lang);
// return empty conceptList if conceptUri is empty
if (StringUtils.isEmpty(result)) {
return conceptList;
}
// Get the list of the concept URIs in the RDF
List<String> conceptUris = getConceptURIsListFromRDF(result);
*/
//For the SKOSMos search mechanism, utilize this instead
String result = getSKOSMosSearchResults(term, this.lang);
List<String> conceptUris = getConceptURIsListFromSkosMosResult(result);
if (conceptUris.size() == 0)
return conceptList;
int conceptCounter = 0;
HashSet<String> encounteredURI = new HashSet<>();
// Loop through each of these URIs and load using the SKOSManager
for (String conceptUri : conceptUris) {
conceptCounter++;
if (StringUtils.isEmpty(conceptUri)) {
// If the conceptURI is empty, keep going
continue;
}
if(encounteredURI.contains(conceptUri)) {
//If we have already encountered this concept URI, do not redisplay or reprocess
continue;
}
encounteredURI.add(conceptUri);
// Test and see if the URI is valid
URI uri = null;
try {
uri = new URI(conceptUri);
} catch (URISyntaxException e) {
logger.error("Error occurred with creating the URI ", e);
continue;
}
// Returns concept information in the format specified, which is
// currently XML
// Utilizing Agrovoc's getConceptInfo returns alternate and
// preferred labels but
// none of the exact match or close match descriptions
String bestMatch = "false";
//Assume the first result is considered the 'best match'
//Although that is not something we are actually retrieving from the service itself explicitly
if(conceptCounter == 1) {
bestMatch = "true";
}
Concept c = this.createConcept(bestMatch, conceptUri);
if (c != null) {
// Get definition from dbpedia references stored in the close
// Match list
List<String> closeMatches = c.getCloseMatchURIList();
for (String closeMatch : closeMatches) {
if (closeMatch.startsWith("http://dbpedia.org")) {
try {
String description = getDbpediaDescription(closeMatch);
c.setDefinition(description);
} catch (Exception ex) {
logger.error("An error occurred in the process of retrieving dbpedia description", ex);
}
}
}
conceptList.add(c);
}
}
return conceptList;
}
public List<Concept> processResults(String term) throws Exception {
return getConcepts(term);
}
public Concept createConcept(String bestMatch, String skosConceptURI) {
Concept concept = new Concept();
concept.setUri(skosConceptURI);
concept.setConceptId(stripConceptId(skosConceptURI));
concept.setBestMatch(bestMatch);
concept.setDefinedBy(schemeUri);
concept.setSchemeURI(this.schemeUri);
concept.setType("");
String encodedURI = URLEncoder.encode(skosConceptURI);
String encodedFormat = URLEncoder.encode("application/rdf+xml");
String url = conceptSkosMosURL + "uri=" + encodedURI + "&format="
+ encodedFormat;
// Utilize the XML directly instead of the SKOS API
try {
concept = SKOSUtils
.createConceptUsingXMLFromURL(concept, url, "en", false);
} catch (Exception ex) {
logger.debug("Error occurred for creating concept "
+ skosConceptURI, ex);
return null;
}
return concept;
}
public List<Concept> getConceptsByURIWithSparql(String uri)
throws Exception {
// deprecating this method...just return an empty list
List<Concept> conceptList = new ArrayList<>();
return conceptList;
}
protected String getAgrovocTermCode(String rdf) throws Exception {
String termcode = "";
try {
Document doc = XMLUtils.parse(rdf);
NodeList nodes = doc.getElementsByTagName("hasCodeAgrovoc");
if (nodes.item(0) != null) {
Node node = nodes.item(0);
termcode = node.getTextContent();
}
} catch (SAXException | IOException | ParserConfigurationException e) {
// e.printStackTrace();
throw e;
}
return termcode;
}
protected String getConceptURIFromRDF(String rdf) {
String conceptUri = "";
try {
Document doc = XMLUtils.parse(rdf);
NodeList nodes = doc.getElementsByTagName("skos:Concept");
Node node = nodes.item(0);
NamedNodeMap attrs = node.getAttributes();
Attr idAttr = (Attr) attrs.getNamedItem("rdf:about");
conceptUri = idAttr.getTextContent();
} catch (IOException | ParserConfigurationException | SAXException e) {
e.printStackTrace();
System.err.println("rdf: " + rdf);
}
return conceptUri;
}
// When utilizing the getTermExpansion method, will get a list of URIs back
// and not just one URI
protected List<String> getConceptURIsListFromRDF(String rdf) {
List<String> conceptUris = new ArrayList<>();
try {
Document doc = XMLUtils.parse(rdf);
NodeList nodes = doc.getElementsByTagName("skos:Concept");
int numberNodes = nodes.getLength();
int n;
for (n = 0; n < numberNodes; n++) {
Node node = nodes.item(n);
NamedNodeMap attrs = node.getAttributes();
Attr idAttr = (Attr) attrs.getNamedItem("rdf:about");
String conceptUri = idAttr.getTextContent();
conceptUris.add(conceptUri);
}
} catch (IOException | ParserConfigurationException | SAXException e) {
e.printStackTrace();
System.err.println("rdf: " + rdf);
}
return conceptUris;
}
protected String getDbpediaDescription(String uri) throws Exception {
String descriptionSource = " (Source: DBpedia)";
String description = "";
String qs = ""
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n"
+ "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n"
+ "PREFIX foaf: <http://xmlns.com/foaf/0.1/> \n"
+ "PREFIX dbpedia-owl: <http://dbpedia.org/ontology/>\n"
+ "SELECT DISTINCT ?description WHERE { \n" + "<" + uri
+ "> rdfs:comment ?description . \n"
+ "FILTER (LANG(?description)='en' ) \n" + "}";
// System.out.println(qs);
List<HashMap> resultList = new ArrayList<>();
QueryExecution qexec = null;
try {
Query query = QueryFactory.create(qs);
qexec = QueryExecutionFactory.sparqlService(this.dbpedia_endpoint, query);
qexec.setTimeout(5000, TimeUnit.MILLISECONDS);
resultList = new ArrayList<>();
ResultSet resultSet = qexec.execSelect();
int resultSetSize = 0;
while (resultSet.hasNext()) {
resultSetSize++;
QuerySolution solution = resultSet.nextSolution();
Iterator varnames = solution.varNames();
HashMap<String, String> hm = new HashMap<>();
while (varnames.hasNext()) {
String name = (String) varnames.next();
RDFNode rdfnode = solution.get(name);
// logger.info("rdf node name, type: "+ name
// +", "+getRDFNodeType(rdfnode));
if (rdfnode.isLiteral()) {
Literal literal = rdfnode.asLiteral();
String nodeval = literal.getString();
hm.put(name, nodeval);
} else if (rdfnode.isResource()) {
Resource resource = rdfnode.asResource();
String nodeval = resource.toString();
hm.put(name, nodeval);
}
}
resultList.add(hm);
}
description = "";
for (HashMap map : resultList) {
if (map.containsKey("description")) {
description = (String) map.get("description");
}
}
} catch (Exception ex) {
throw ex;
}
// Adding source so it is clear that this description comes from DBPedia
return description + descriptionSource;
}
/**
* @param uri The URI
*/
protected String stripConceptId(String uri) {
String conceptId = "";
int lastslash = uri.lastIndexOf('/');
conceptId = uri.substring(lastslash + 1, uri.length());
return conceptId;
}
/**
* @param str The String
*/
protected String extractConceptId(String str) {
try {
return str.substring(1, str.length() - 1);
} catch (Exception ex) {
return "";
}
}
/**
* The code here utilizes the SKOSMOS REST API for Agrovoc
* This returns JSON LD so we would parse JSON instead of RDF
* The code above can still be utilized if we need to employ the web services directly
*/
//Get search results for a particular term and language code
private String getSKOSMosSearchResults(String term, String lang) {
String urlEncodedTerm = URLEncoder.encode(term);
//Utilize 'starts with' using the * operator at the end
String searchUrlString = this.conceptsSkosMosSearch + "query=" + urlEncodedTerm + "*" + "&lang=" + lang;
URL searchURL = null;
try {
searchURL = new URL(searchUrlString);
} catch (Exception e) {
logger.error("Exception occurred in instantiating URL for "
+ searchUrlString, e);
// If the url is having trouble, just return null for the concept
return null;
}
String results = null;
try {
StringWriter sw = new StringWriter();
BufferedReader in = new BufferedReader(new InputStreamReader(
searchURL.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
sw.write(inputLine);
}
in.close();
results = sw.toString();
logger.debug(results);
} catch (Exception ex) {
logger.error("Error occurred in getting concept from the URL "
+ searchUrlString, ex);
return null;
}
return results;
}
//JSON-LD array
private List<String> getConceptURIsListFromSkosMosResult(String results) {
List<String> conceptURIs = new ArrayList<>();
ObjectNode json = (ObjectNode) JacksonUtils.parseJson(results);
//Format should be: { ..."results":["uri":uri...]
if (json.has("results")) {
ArrayNode jsonArray = (ArrayNode) json.get("results");
int numberResults = jsonArray.size();
int i;
for(i = 0; i < numberResults; i++) {
ObjectNode jsonObject = (ObjectNode) jsonArray.get(i);
if(jsonObject.has("uri")) {
conceptURIs.add(jsonObject.get("uri").asText());
}
}
}
return conceptURIs;
}
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.semservices.service.impl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import edu.cornell.mannlib.semservices.bo.Concept;
import edu.cornell.mannlib.semservices.service.ExternalConceptService;
import edu.cornell.mannlib.semservices.util.SKOSUtils;
import edu.cornell.mannlib.semservices.util.XMLUtils;
import edu.cornell.mannlib.vitro.webapp.utils.json.JacksonUtils;
import edu.cornell.mannlib.vitro.webapp.web.URLEncoder;
public class AgrovocService implements ExternalConceptService {
protected final Log logger = LogFactory.getLog(getClass());
private final String schemeUri = "http://aims.fao.org/aos/agrovoc/agrovocScheme";
private final String ontologyName = "agrovoc";
private final String format = "SKOS";
private final String lang = "en";
private final String searchMode = "starts with";//Used to be Exact Match, or exact word or starts with
protected final String dbpedia_endpoint = " http://dbpedia.org/sparql";
// URL to get all the information for a concept
protected final String conceptSkosMosBase = "http://agrovoc.uniroma2.it/agrovoc/rest/v1/";
protected final String conceptsSkosMosSearch = conceptSkosMosBase + "search?";
protected final String conceptSkosMosURL = conceptSkosMosBase + "data?";
@Override
public List<Concept> getConcepts(String term) throws Exception {
List<Concept> conceptList = new ArrayList<>();
//For the RDF webservices mechanism, utilize the following
/*
String result = getTermExpansion(this.ontologyName, term,
this.searchMode, this.format, this.lang);
// return empty conceptList if conceptUri is empty
if (StringUtils.isEmpty(result)) {
return conceptList;
}
// Get the list of the concept URIs in the RDF
List<String> conceptUris = getConceptURIsListFromRDF(result);
*/
//For the SKOSMos search mechanism, utilize this instead
String result = getSKOSMosSearchResults(term, this.lang);
List<String> conceptUris = getConceptURIsListFromSkosMosResult(result);
if (conceptUris.size() == 0)
return conceptList;
int conceptCounter = 0;
HashSet<String> encounteredURI = new HashSet<>();
// Loop through each of these URIs and load using the SKOSManager
for (String conceptUri : conceptUris) {
conceptCounter++;
if (StringUtils.isEmpty(conceptUri)) {
// If the conceptURI is empty, keep going
continue;
}
if(encounteredURI.contains(conceptUri)) {
//If we have already encountered this concept URI, do not redisplay or reprocess
continue;
}
encounteredURI.add(conceptUri);
// Test and see if the URI is valid
URI uri = null;
try {
uri = new URI(conceptUri);
} catch (URISyntaxException e) {
logger.error("Error occurred with creating the URI ", e);
continue;
}
// Returns concept information in the format specified, which is
// currently XML
// Utilizing Agrovoc's getConceptInfo returns alternate and
// preferred labels but
// none of the exact match or close match descriptions
String bestMatch = "false";
//Assume the first result is considered the 'best match'
//Although that is not something we are actually retrieving from the service itself explicitly
if(conceptCounter == 1) {
bestMatch = "true";
}
Concept c = this.createConcept(bestMatch, conceptUri);
if (c != null) {
// Get definition from dbpedia references stored in the close
// Match list
List<String> closeMatches = c.getCloseMatchURIList();
for (String closeMatch : closeMatches) {
if (closeMatch.startsWith("http://dbpedia.org")) {
try {
String description = getDbpediaDescription(closeMatch);
c.setDefinition(description);
} catch (Exception ex) {
logger.error("An error occurred in the process of retrieving dbpedia description", ex);
}
}
}
conceptList.add(c);
}
}
return conceptList;
}
public List<Concept> processResults(String term) throws Exception {
return getConcepts(term);
}
public Concept createConcept(String bestMatch, String skosConceptURI) {
Concept concept = new Concept();
concept.setUri(skosConceptURI);
concept.setConceptId(stripConceptId(skosConceptURI));
concept.setBestMatch(bestMatch);
concept.setDefinedBy(schemeUri);
concept.setSchemeURI(this.schemeUri);
concept.setType("");
String encodedURI = URLEncoder.encode(skosConceptURI);
String encodedFormat = URLEncoder.encode("application/rdf+xml");
String url = conceptSkosMosURL + "uri=" + encodedURI + "&format="
+ encodedFormat;
// Utilize the XML directly instead of the SKOS API
try {
concept = SKOSUtils
.createConceptUsingXMLFromURL(concept, url, "en", false);
} catch (Exception ex) {
logger.debug("Error occurred for creating concept "
+ skosConceptURI, ex);
return null;
}
return concept;
}
public List<Concept> getConceptsByURIWithSparql(String uri)
throws Exception {
// deprecating this method...just return an empty list
List<Concept> conceptList = new ArrayList<>();
return conceptList;
}
protected String getAgrovocTermCode(String rdf) throws Exception {
String termcode = "";
try {
Document doc = XMLUtils.parse(rdf);
NodeList nodes = doc.getElementsByTagName("hasCodeAgrovoc");
if (nodes.item(0) != null) {
Node node = nodes.item(0);
termcode = node.getTextContent();
}
} catch (SAXException | IOException | ParserConfigurationException e) {
// e.printStackTrace();
throw e;
}
return termcode;
}
protected String getConceptURIFromRDF(String rdf) {
String conceptUri = "";
try {
Document doc = XMLUtils.parse(rdf);
NodeList nodes = doc.getElementsByTagName("skos:Concept");
Node node = nodes.item(0);
NamedNodeMap attrs = node.getAttributes();
Attr idAttr = (Attr) attrs.getNamedItem("rdf:about");
conceptUri = idAttr.getTextContent();
} catch (IOException | ParserConfigurationException | SAXException e) {
e.printStackTrace();
System.err.println("rdf: " + rdf);
}
return conceptUri;
}
// When utilizing the getTermExpansion method, will get a list of URIs back
// and not just one URI
protected List<String> getConceptURIsListFromRDF(String rdf) {
List<String> conceptUris = new ArrayList<>();
try {
Document doc = XMLUtils.parse(rdf);
NodeList nodes = doc.getElementsByTagName("skos:Concept");
int numberNodes = nodes.getLength();
int n;
for (n = 0; n < numberNodes; n++) {
Node node = nodes.item(n);
NamedNodeMap attrs = node.getAttributes();
Attr idAttr = (Attr) attrs.getNamedItem("rdf:about");
String conceptUri = idAttr.getTextContent();
conceptUris.add(conceptUri);
}
} catch (IOException | ParserConfigurationException | SAXException e) {
e.printStackTrace();
System.err.println("rdf: " + rdf);
}
return conceptUris;
}
protected String getDbpediaDescription(String uri) throws Exception {
String descriptionSource = " (Source: DBpedia)";
String description = "";
String qs = ""
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n"
+ "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n"
+ "PREFIX foaf: <http://xmlns.com/foaf/0.1/> \n"
+ "PREFIX dbpedia-owl: <http://dbpedia.org/ontology/>\n"
+ "SELECT DISTINCT ?description WHERE { \n" + "<" + uri
+ "> rdfs:comment ?description . \n"
+ "FILTER (LANG(?description)='en' ) \n" + "}";
// System.out.println(qs);
List<HashMap> resultList = new ArrayList<>();
QueryExecution qexec = null;
try {
Query query = QueryFactory.create(qs);
qexec = QueryExecutionFactory.sparqlService(this.dbpedia_endpoint, query);
qexec.setTimeout(5000, TimeUnit.MILLISECONDS);
resultList = new ArrayList<>();
ResultSet resultSet = qexec.execSelect();
int resultSetSize = 0;
while (resultSet.hasNext()) {
resultSetSize++;
QuerySolution solution = resultSet.nextSolution();
Iterator varnames = solution.varNames();
HashMap<String, String> hm = new HashMap<>();
while (varnames.hasNext()) {
String name = (String) varnames.next();
RDFNode rdfnode = solution.get(name);
// logger.info("rdf node name, type: "+ name
// +", "+getRDFNodeType(rdfnode));
if (rdfnode.isLiteral()) {
Literal literal = rdfnode.asLiteral();
String nodeval = literal.getString();
hm.put(name, nodeval);
} else if (rdfnode.isResource()) {
Resource resource = rdfnode.asResource();
String nodeval = resource.toString();
hm.put(name, nodeval);
}
}
resultList.add(hm);
}
description = "";
for (HashMap map : resultList) {
if (map.containsKey("description")) {
description = (String) map.get("description");
}
}
} catch (Exception ex) {
throw ex;
}
// Adding source so it is clear that this description comes from DBPedia
return description + descriptionSource;
}
/**
* @param uri The URI
*/
protected String stripConceptId(String uri) {
String conceptId = "";
int lastslash = uri.lastIndexOf('/');
conceptId = uri.substring(lastslash + 1, uri.length());
return conceptId;
}
/**
* @param str The String
*/
protected String extractConceptId(String str) {
try {
return str.substring(1, str.length() - 1);
} catch (Exception ex) {
return "";
}
}
/**
* The code here utilizes the SKOSMOS REST API for Agrovoc
* This returns JSON LD so we would parse JSON instead of RDF
* The code above can still be utilized if we need to employ the web services directly
*/
//Get search results for a particular term and language code
private String getSKOSMosSearchResults(String term, String lang) {
String urlEncodedTerm = URLEncoder.encode(term);
//Utilize 'starts with' using the * operator at the end
String searchUrlString = this.conceptsSkosMosSearch + "query=" + urlEncodedTerm + "*" + "&lang=" + lang;
URL searchURL = null;
try {
searchURL = new URL(searchUrlString);
} catch (Exception e) {
logger.error("Exception occurred in instantiating URL for "
+ searchUrlString, e);
// If the url is having trouble, just return null for the concept
return null;
}
String results = null;
try {
StringWriter sw = new StringWriter();
BufferedReader in = new BufferedReader(new InputStreamReader(
searchURL.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
sw.write(inputLine);
}
in.close();
results = sw.toString();
logger.debug(results);
} catch (Exception ex) {
logger.error("Error occurred in getting concept from the URL "
+ searchUrlString, ex);
return null;
}
return results;
}
//JSON-LD array
private List<String> getConceptURIsListFromSkosMosResult(String results) {
List<String> conceptURIs = new ArrayList<>();
ObjectNode json = (ObjectNode) JacksonUtils.parseJson(results);
//Format should be: { ..."results":["uri":uri...]
if (json.has("results")) {
ArrayNode jsonArray = (ArrayNode) json.get("results");
int numberResults = jsonArray.size();
int i;
for(i = 0; i < numberResults; i++) {
ObjectNode jsonObject = (ObjectNode) jsonArray.get(i);
if(jsonObject.has("uri")) {
conceptURIs.add(jsonObject.get("uri").asText());
}
}
}
return conceptURIs;
}
}

View file

@ -1,360 +1,360 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.semservices.service.impl;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import edu.cornell.mannlib.semservices.bo.Concept;
import edu.cornell.mannlib.semservices.exceptions.ConceptsNotFoundException;
import edu.cornell.mannlib.semservices.service.ExternalConceptService;
import edu.cornell.mannlib.vitro.webapp.utils.json.JacksonUtils;
public class GemetService implements ExternalConceptService {
protected final Log logger = LogFactory.getLog(getClass());
private final String GemetWS_address = "https://www.eionet.europa.eu/gemet/";
private final String narrowerUri = "http://www.w3.org/2004/02/skos/core%23narrower";
private final String broaderUri = "http://www.w3.org/2004/02/skos/core%23broader";
private final String relatedUri = "http://www.w3.org/2004/02/skos/core%23related";
private final String definitionUri = "http://www.w3.org/2004/02/skos/core%23definition";
private final String prefLabelUri = "http://www.w3.org/2004/02/skos/core%23prefLabel";
private final String scopeNoteUri = "http://www.w3.org/2004/02/skos/core%23scopeNote";
private final String altLabelUri = "http://www.w3.org/2004/02/skos/core%23altLabel";
private final String exampleUri = "http://www.w3.org/2004/02/skos/core%23example";
private final String acronymLabelUri = "http://www.w3.org/2004/02/skos/core%23acronymLabel";
private final String endpoint = "http://cr.eionet.europa.eu/sparql";
private final String schemeURI = "http://www.eionet.europa.eu/gemet/gemetThesaurus";
@Override
public List<Concept> getConcepts(String term) throws Exception {
List<Concept> conceptList = new ArrayList<Concept>();
try {
String results = getConceptsMatchingKeyword(term);
//System.out.println(results);
conceptList = processOutput(results);
} catch (Exception ex) {
return new ArrayList<Concept>();
//ex.printStackTrace();
//throw ex;
}
return conceptList;
}
public List<Concept> processResults(String term) throws Exception {
List<Concept> conceptList = new ArrayList<Concept>();
try {
String results = getConceptsMatchingKeyword(term);
conceptList = processOutput(results);
} catch (Exception ex) {
//ex.printStackTrace();
throw ex;
}
return conceptList;
}
public List<Concept> getConceptsByURIWithSparql(String uri)
throws Exception {
// deprecating this method...just return an empty list
List<Concept> conceptList = new ArrayList<Concept>();
return conceptList;
}
/**
* @param results Results to process
*/
private List<Concept> processOutput(String results) throws Exception {
List<Concept> conceptList = new ArrayList<Concept>();
try {
ArrayNode jsonArray = (ArrayNode) JacksonUtils.parseJson(results);
if (jsonArray.size() == 0) {
throw new ConceptsNotFoundException();
}
for (int i = 0; i < jsonArray.size(); i++) {
Concept concept = new Concept();
concept.setDefinedBy(schemeURI);
concept.setBestMatch("true");
ObjectNode json = (ObjectNode) jsonArray.get(i);
String uri = getJsonValue(json, "uri");
concept.setUri(uri);
concept.setConceptId(stripConceptId(uri));
concept.setSchemeURI(schemeURI);
concept.setType("");
if (json.has("preferredLabel")) {
ObjectNode preferredLabelObj = (ObjectNode) json.get("preferredLabel");
if (preferredLabelObj.has("string")) {
concept.setLabel(getJsonValue(preferredLabelObj,
"string"));
}
}
if (json.has("definition")) {
ObjectNode definitionObj = (ObjectNode) json.get("definition");
if (definitionObj.has("string")) {
concept.setDefinition(getJsonValue(definitionObj,
"string"));
}
}
String narrower = getRelatedConcepts(uri, "narrower");
List<String> narrowerURIList = getRelatedUris(narrower);
concept.setNarrowerURIList(narrowerURIList);
String broader = getRelatedConcepts(uri, "broader");
List<String> broaderURIList = getRelatedUris(broader);
concept.setBroaderURIList(broaderURIList);
/*String related = getRelatedConcepts(uri, "related");
List<String> relatedURIList = getRelatedUris(related);
for (String s: relatedURIList) {
System.out.println("related uri: "+s);
}*/
//String altLabels = getAllTranslationsForConcept(uri, "nonPreferredLabels");
conceptList.add(concept);
}
} catch (Exception ex ) {
//ex.printStackTrace();
logger.error("Could not get concepts", ex);
throw ex;
}
return conceptList;
}
/**
* Get a string from a json object or an empty string if there is no value for the given key
* @param obj JSON Object
* @param key Key to retrieve
*/
protected String getJsonValue(ObjectNode obj, String key) {
if (obj.has(key)) {
return obj.get(key).asText();
} else {
return "";
}
}
/**
* @param concept_uri Concept URI
* @throws Exception
*/
protected String getAvailableLangs(String concept_uri) throws Exception {
String result = "";
String serviceUrl = GemetWS_address + "getAvailableLanguages" +
"?concept_uri=" + concept_uri;
try {
result = getGemetResults(serviceUrl);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return result;
}
/**
* @param concept_uri concept URI
* @throws Exception
*/
protected String getConcept(String concept_uri) throws Exception {
String result = "";
String serviceUrl = GemetWS_address + "getConcept" +
"?concept_uri=" + concept_uri +
"&language=en";
try {
result = getGemetResults(serviceUrl);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return result;
}
/**
* @param concept_uri Concept URI
* @param property Property
* @throws Exception
*/
protected String getAllTranslationsForConcept(String concept_uri, String property) throws Exception {
String result = "";
String property_uri = "";
switch (property) {
case "definition":
property_uri = definitionUri;
break;
case "preferredLabel":
property_uri = prefLabelUri;
break;
case "scopeNote":
property_uri = scopeNoteUri;
break;
case "nonPreferredLabels":
property_uri = altLabelUri;
break;
case "example":
property_uri = exampleUri;
break;
case "acronymLabel":
property_uri = acronymLabelUri;
break;
}
String serviceUrl = GemetWS_address + "getAllTranslationsForConcept" +
"?concept_uri=" + concept_uri +
"&property_uri=" + property_uri +
"&language=en";
try {
result = getGemetResults(serviceUrl);
List<String> props = getPropertyFromJson(result);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return result;
}
/**
* @param concept_uri Concept URI
* @param relation Relations
* @throws Exception
*/
protected String getRelatedConcepts(String concept_uri, String relation) throws Exception {
String result = "";
String relation_uri = "";
switch (relation) {
case "broader":
relation_uri = broaderUri;
break;
case "narrower":
relation_uri = narrowerUri;
break;
case "related":
relation_uri = relatedUri;
break;
}
String serviceUrl = GemetWS_address + "getRelatedConcepts" +
"?concept_uri=" + concept_uri +
"&relation_uri=" + relation_uri +
"&language=en";
try {
result = getGemetResults(serviceUrl);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return result;
}
/**
* @param keyword Keyword
* @throws Exception
*/
protected String getConceptsMatchingKeyword(String keyword) throws Exception {
String result = "";
String encodedKeyword = URLEncoder.encode(keyword, "UTF-8");
String serviceUrl = GemetWS_address + "getConceptsMatchingKeyword" +
"?keyword=" + encodedKeyword +
"&search_mode=0" +
"&thesaurus_uri=http://www.eionet.europa.eu/gemet/concept/" +
"&language=en";
try {
result = getGemetResults(serviceUrl);
} catch (Exception ex) {
throw ex;
}
return result;
}
/**
* @param url URI
*/
protected String getGemetResults(String url) throws Exception {
String results = "";
//System.out.println("url: "+url);
try {
StringWriter sw = new StringWriter();
URL serviceUrl = new URL(url);
BufferedReader in = new BufferedReader(new InputStreamReader(serviceUrl.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
sw.write(inputLine);
}
in.close();
results = sw.toString();
} catch (Exception ex) {
logger.error("error occurred in servlet", ex);
ex.printStackTrace();
throw ex;
}
return results;
}
protected List<String> getRelatedUris(String json) {
List<String> uriList = new ArrayList<String>();
String uri = "";
ArrayNode jsonArray = (ArrayNode) JacksonUtils.parseJson(json);
if (jsonArray.size() == 0) {
return new ArrayList<String>();
}
for (int i = 0; i < jsonArray.size(); i++) {
ObjectNode jsonObj = (ObjectNode) jsonArray.get(i);
uri = getJsonValue(jsonObj, "uri");
uriList.add(uri);
}
return uriList;
}
protected List<String> getPropertyFromJson(String json) {
List<String> props = new ArrayList<String>();
ArrayNode jsonArray = (ArrayNode) JacksonUtils.parseJson(json);
if (jsonArray.size() == 0) {
return new ArrayList<String>();
}
for (int i = 0; i < jsonArray.size(); i++) {
System.out.println((jsonArray.get(i)).toString());
}
return props;
}
protected String stripConceptId(String uri) {
String conceptId = "";
int lastslash = uri.lastIndexOf('/');
conceptId = uri.substring(lastslash + 1, uri.length());
return conceptId;
}
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.semservices.service.impl;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import edu.cornell.mannlib.semservices.bo.Concept;
import edu.cornell.mannlib.semservices.exceptions.ConceptsNotFoundException;
import edu.cornell.mannlib.semservices.service.ExternalConceptService;
import edu.cornell.mannlib.vitro.webapp.utils.json.JacksonUtils;
public class GemetService implements ExternalConceptService {
protected final Log logger = LogFactory.getLog(getClass());
private final String GemetWS_address = "https://www.eionet.europa.eu/gemet/";
private final String narrowerUri = "http://www.w3.org/2004/02/skos/core%23narrower";
private final String broaderUri = "http://www.w3.org/2004/02/skos/core%23broader";
private final String relatedUri = "http://www.w3.org/2004/02/skos/core%23related";
private final String definitionUri = "http://www.w3.org/2004/02/skos/core%23definition";
private final String prefLabelUri = "http://www.w3.org/2004/02/skos/core%23prefLabel";
private final String scopeNoteUri = "http://www.w3.org/2004/02/skos/core%23scopeNote";
private final String altLabelUri = "http://www.w3.org/2004/02/skos/core%23altLabel";
private final String exampleUri = "http://www.w3.org/2004/02/skos/core%23example";
private final String acronymLabelUri = "http://www.w3.org/2004/02/skos/core%23acronymLabel";
private final String endpoint = "http://cr.eionet.europa.eu/sparql";
private final String schemeURI = "http://www.eionet.europa.eu/gemet/gemetThesaurus";
@Override
public List<Concept> getConcepts(String term) throws Exception {
List<Concept> conceptList = new ArrayList<Concept>();
try {
String results = getConceptsMatchingKeyword(term);
//System.out.println(results);
conceptList = processOutput(results);
} catch (Exception ex) {
return new ArrayList<Concept>();
//ex.printStackTrace();
//throw ex;
}
return conceptList;
}
public List<Concept> processResults(String term) throws Exception {
List<Concept> conceptList = new ArrayList<Concept>();
try {
String results = getConceptsMatchingKeyword(term);
conceptList = processOutput(results);
} catch (Exception ex) {
//ex.printStackTrace();
throw ex;
}
return conceptList;
}
public List<Concept> getConceptsByURIWithSparql(String uri)
throws Exception {
// deprecating this method...just return an empty list
List<Concept> conceptList = new ArrayList<Concept>();
return conceptList;
}
/**
* @param results Results to process
*/
private List<Concept> processOutput(String results) throws Exception {
List<Concept> conceptList = new ArrayList<Concept>();
try {
ArrayNode jsonArray = (ArrayNode) JacksonUtils.parseJson(results);
if (jsonArray.size() == 0) {
throw new ConceptsNotFoundException();
}
for (int i = 0; i < jsonArray.size(); i++) {
Concept concept = new Concept();
concept.setDefinedBy(schemeURI);
concept.setBestMatch("true");
ObjectNode json = (ObjectNode) jsonArray.get(i);
String uri = getJsonValue(json, "uri");
concept.setUri(uri);
concept.setConceptId(stripConceptId(uri));
concept.setSchemeURI(schemeURI);
concept.setType("");
if (json.has("preferredLabel")) {
ObjectNode preferredLabelObj = (ObjectNode) json.get("preferredLabel");
if (preferredLabelObj.has("string")) {
concept.setLabel(getJsonValue(preferredLabelObj,
"string"));
}
}
if (json.has("definition")) {
ObjectNode definitionObj = (ObjectNode) json.get("definition");
if (definitionObj.has("string")) {
concept.setDefinition(getJsonValue(definitionObj,
"string"));
}
}
String narrower = getRelatedConcepts(uri, "narrower");
List<String> narrowerURIList = getRelatedUris(narrower);
concept.setNarrowerURIList(narrowerURIList);
String broader = getRelatedConcepts(uri, "broader");
List<String> broaderURIList = getRelatedUris(broader);
concept.setBroaderURIList(broaderURIList);
/*String related = getRelatedConcepts(uri, "related");
List<String> relatedURIList = getRelatedUris(related);
for (String s: relatedURIList) {
System.out.println("related uri: "+s);
}*/
//String altLabels = getAllTranslationsForConcept(uri, "nonPreferredLabels");
conceptList.add(concept);
}
} catch (Exception ex ) {
//ex.printStackTrace();
logger.error("Could not get concepts", ex);
throw ex;
}
return conceptList;
}
/**
* Get a string from a json object or an empty string if there is no value for the given key
* @param obj JSON Object
* @param key Key to retrieve
*/
protected String getJsonValue(ObjectNode obj, String key) {
if (obj.has(key)) {
return obj.get(key).asText();
} else {
return "";
}
}
/**
* @param concept_uri Concept URI
* @throws Exception
*/
protected String getAvailableLangs(String concept_uri) throws Exception {
String result = "";
String serviceUrl = GemetWS_address + "getAvailableLanguages" +
"?concept_uri=" + concept_uri;
try {
result = getGemetResults(serviceUrl);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return result;
}
/**
* @param concept_uri concept URI
* @throws Exception
*/
protected String getConcept(String concept_uri) throws Exception {
String result = "";
String serviceUrl = GemetWS_address + "getConcept" +
"?concept_uri=" + concept_uri +
"&language=en";
try {
result = getGemetResults(serviceUrl);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return result;
}
/**
* @param concept_uri Concept URI
* @param property Property
* @throws Exception
*/
protected String getAllTranslationsForConcept(String concept_uri, String property) throws Exception {
String result = "";
String property_uri = "";
switch (property) {
case "definition":
property_uri = definitionUri;
break;
case "preferredLabel":
property_uri = prefLabelUri;
break;
case "scopeNote":
property_uri = scopeNoteUri;
break;
case "nonPreferredLabels":
property_uri = altLabelUri;
break;
case "example":
property_uri = exampleUri;
break;
case "acronymLabel":
property_uri = acronymLabelUri;
break;
}
String serviceUrl = GemetWS_address + "getAllTranslationsForConcept" +
"?concept_uri=" + concept_uri +
"&property_uri=" + property_uri +
"&language=en";
try {
result = getGemetResults(serviceUrl);
List<String> props = getPropertyFromJson(result);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return result;
}
/**
* @param concept_uri Concept URI
* @param relation Relations
* @throws Exception
*/
protected String getRelatedConcepts(String concept_uri, String relation) throws Exception {
String result = "";
String relation_uri = "";
switch (relation) {
case "broader":
relation_uri = broaderUri;
break;
case "narrower":
relation_uri = narrowerUri;
break;
case "related":
relation_uri = relatedUri;
break;
}
String serviceUrl = GemetWS_address + "getRelatedConcepts" +
"?concept_uri=" + concept_uri +
"&relation_uri=" + relation_uri +
"&language=en";
try {
result = getGemetResults(serviceUrl);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return result;
}
/**
* @param keyword Keyword
* @throws Exception
*/
protected String getConceptsMatchingKeyword(String keyword) throws Exception {
String result = "";
String encodedKeyword = URLEncoder.encode(keyword, "UTF-8");
String serviceUrl = GemetWS_address + "getConceptsMatchingKeyword" +
"?keyword=" + encodedKeyword +
"&search_mode=0" +
"&thesaurus_uri=http://www.eionet.europa.eu/gemet/concept/" +
"&language=en";
try {
result = getGemetResults(serviceUrl);
} catch (Exception ex) {
throw ex;
}
return result;
}
/**
* @param url URI
*/
protected String getGemetResults(String url) throws Exception {
String results = "";
//System.out.println("url: "+url);
try {
StringWriter sw = new StringWriter();
URL serviceUrl = new URL(url);
BufferedReader in = new BufferedReader(new InputStreamReader(serviceUrl.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
sw.write(inputLine);
}
in.close();
results = sw.toString();
} catch (Exception ex) {
logger.error("error occurred in servlet", ex);
ex.printStackTrace();
throw ex;
}
return results;
}
protected List<String> getRelatedUris(String json) {
List<String> uriList = new ArrayList<String>();
String uri = "";
ArrayNode jsonArray = (ArrayNode) JacksonUtils.parseJson(json);
if (jsonArray.size() == 0) {
return new ArrayList<String>();
}
for (int i = 0; i < jsonArray.size(); i++) {
ObjectNode jsonObj = (ObjectNode) jsonArray.get(i);
uri = getJsonValue(jsonObj, "uri");
uriList.add(uri);
}
return uriList;
}
protected List<String> getPropertyFromJson(String json) {
List<String> props = new ArrayList<String>();
ArrayNode jsonArray = (ArrayNode) JacksonUtils.parseJson(json);
if (jsonArray.size() == 0) {
return new ArrayList<String>();
}
for (int i = 0; i < jsonArray.size(); i++) {
System.out.println((jsonArray.get(i)).toString());
}
return props;
}
protected String stripConceptId(String uri) {
String conceptId = "";
int lastslash = uri.lastIndexOf('/');
conceptId = uri.substring(lastslash + 1, uri.length());
return conceptId;
}
}

View file

@ -39,8 +39,8 @@ public class LCSHService implements ExternalConceptService {
private final String schemeUri = hostUri + "/authorities/subjects";
private final String baseUri = hostUri + "/search/";
@Override
public List<Concept> getConcepts(String term) throws Exception {
List<Concept> conceptList = new ArrayList<Concept>();
@ -111,19 +111,19 @@ public class LCSHService implements ExternalConceptService {
conceptList.add(c);
}
i++;
}
return conceptList;
}
//Load individual concept using a request
//private
//private
public Concept createConcept(String bestMatch, String conceptURLString, String skosConceptURI) {
Concept concept = new Concept();
log.debug("SKOSConceptURI is " + skosConceptURI);
// get skos version of uri
@ -133,31 +133,31 @@ public class LCSHService implements ExternalConceptService {
concept.setDefinedBy(schemeUri);
concept.setSchemeURI(schemeUri);
concept.setType("");
//Utilize the XML directly instead of the SKOS API
try {
//LCSH doesn't need a language tag right now as results in english
//Also want to add skos notes as definition
concept = SKOSUtils.createConceptUsingXMLFromURL(concept, conceptURLString, null, true);
} catch(Exception ex) {
log.debug("Error occurred for annotation retrieval for skos concept " + skosConceptURI, ex);
return null;
}
return concept;
}
private String getSKOSURL(String uri) {
String skosURI = uri + skosSuffix;
return skosURI;
}
public List<String> getConceptURISFromJSON(String results) {
List<String> uris = new ArrayList<String>();
@ -197,7 +197,7 @@ public class LCSHService implements ExternalConceptService {
}
}
log.debug("concept uri is " + conceptUri);
uris.add(conceptUri);
}
@ -241,6 +241,6 @@ public class LCSHService implements ExternalConceptService {
// TODO Auto-generated method stub
return null;
}
}

View file

@ -1,229 +1,229 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.semservices.service.impl;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import edu.cornell.mannlib.semservices.bo.Concept;
import edu.cornell.mannlib.semservices.exceptions.ConceptsNotFoundException;
import edu.cornell.mannlib.semservices.service.ExternalConceptService;
import edu.cornell.mannlib.vitro.webapp.utils.json.JacksonUtils;
import org.apache.http.HttpVersion;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.utils.URIBuilder;
import org.springframework.util.StringUtils;
/**
* @author jaf30
*
*/
public class UMLSService implements ExternalConceptService {
protected final Log logger = LogFactory.getLog(getClass());
private static String UTS_REST_API_URL = "https://uts-ws.nlm.nih.gov/rest";
private static String SEARCH_PATH = "/search/current";
private static String SEARCH_PARAMETER = "string";
private static String SEARCH_TYPE_PARAMETER = "searchType";
private static String SEARCH_TYPE = "rightTruncation";
private static String PAGE_SIZE_PARAMETER = "pageSize";
private static String RETURN_TYPE_PARAMETER = "returnIdType";
private static String RETURN_TYPE = "concept";
private static String TICKET_PARAMETER = "ticket";
private static String ticketGrantingTicketURL = null;
private static long lastUpdate = -1;
private static String username = null;
private static String password = null;
private static String apikey = null;
private static String pageSize = "50";
private static String UMLS_AUTH_USER_URL = "https://utslogin.nlm.nih.gov/cas/v1/tickets";
private static String UMLS_AUTH_KEY_URL = "https://utslogin.nlm.nih.gov/cas/v1/api-key";
private static String UTS_SERVICE_URL = "http://umlsks.nlm.nih.gov";
{
if (username == null || apikey == null) {
final Properties properties = new Properties();
try (InputStream stream = getClass().getResourceAsStream("/umls.properties")) {
properties.load(stream);
username = properties.getProperty("username");
password = properties.getProperty("password");
apikey = properties.getProperty("apikey");
String exPageSize = properties.getProperty("pagesize");
try {
if (!StringUtils.isEmpty(exPageSize)) {
int iPageSize = Integer.parseInt(exPageSize, 10);
if (iPageSize > 5 && iPageSize < 200) {
pageSize = Integer.toString(iPageSize, 10);
}
}
} catch (Exception e) {
}
} catch (IOException e) {
}
}
}
public boolean isConfigured() {
return !(StringUtils.isEmpty(username) && StringUtils.isEmpty(apikey));
}
@Override
public List<Concept> getConcepts(String term) throws Exception {
String ticket = getSingleUseTicket();
List<Concept> conceptList = new ArrayList<Concept>();
String results = null;
try {
URIBuilder b = new URIBuilder(UTS_REST_API_URL + SEARCH_PATH);
b.addParameter(SEARCH_PARAMETER, term);
b.addParameter(RETURN_TYPE_PARAMETER, RETURN_TYPE);
b.addParameter(SEARCH_TYPE_PARAMETER, SEARCH_TYPE);
b.addParameter(PAGE_SIZE_PARAMETER, pageSize);
b.addParameter(TICKET_PARAMETER, ticket);
results = Request.Get(b.build())
.connectTimeout(3000)
.socketTimeout(3000)
.execute().returnContent().asString();
conceptList = processOutput(results);
return conceptList;
} catch (Exception ex) {
logger.error("error occurred in servlet", ex);
return null;
}
}
public List<Concept> processResults(String term) throws Exception {
return getConcepts(term);
}
/**
* @param uri URI
*/
public List<Concept> getConceptsByURIWithSparql(String uri) throws Exception {
// deprecating this method...just return an empty list
List<Concept> conceptList = new ArrayList<Concept>();
return conceptList;
}
/**
* @param results Results to process
*/
private List<Concept> processOutput(String results) throws Exception {
List<Concept> conceptList = new ArrayList<Concept>();
List<String> bestMatchIdList = new ArrayList<String>();
String bestMatchId = "";
try {
ObjectNode json = (ObjectNode) JacksonUtils.parseJson(results);
ArrayNode allArray = (ArrayNode) json.get("result").get("results");
int len = allArray.size();
int i;
for (i = 0; i < len; i++) {
ObjectNode o = (ObjectNode) allArray.get(i);
Concept concept = new Concept();
concept.setDefinedBy(UTS_SERVICE_URL);
concept.setSchemeURI(UTS_SERVICE_URL);
concept.setType(RETURN_TYPE);
concept.setConceptId(getJsonValue(o, "ui"));
concept.setLabel(getJsonValue(o, "name"));
concept.setUri(getJsonValue(o, "uri"));
concept.setBestMatch("false");
conceptList.add(concept);
}
} catch (Exception ex) {
ex.printStackTrace();
logger.error("Could not get concepts", ex);
throw ex;
}
if (conceptList.size() == 0) {
throw new ConceptsNotFoundException();
}
//
return conceptList;
}
/**
* Get a string from a json object or an empty string if there is no value for the given key
*
* @param obj JSON Object
* @param key Key to retrieve
*/
protected String getJsonValue(ObjectNode obj, String key) {
if (obj.has(key)) {
return obj.get(key).asText();
} else {
return "";
}
}
protected String stripConceptId(String uri) {
String conceptId = "";
int lastslash = uri.lastIndexOf('/');
conceptId = uri.substring(lastslash + 1, uri.length());
return conceptId;
}
private synchronized void getTicketGrantingTicket() {
if (StringUtils.isEmpty(username) && StringUtils.isEmpty(apikey)) {
throw new IllegalStateException("Unable to read umls.properties");
}
if (ticketGrantingTicketURL == null || lastUpdate + 28700000L < System.currentTimeMillis()) {
try {
if (!StringUtils.isEmpty(apikey)) {
ticketGrantingTicketURL = Request.Post(UMLS_AUTH_KEY_URL).useExpectContinue().version(HttpVersion.HTTP_1_1)
.bodyForm(Form.form().add("apikey", apikey).build())
.execute().returnResponse().getFirstHeader("location").getValue();
} else {
ticketGrantingTicketURL = Request.Post(UMLS_AUTH_USER_URL).useExpectContinue().version(HttpVersion.HTTP_1_1)
.bodyForm(Form.form().add("username", username).add("password", password).build())
.execute().returnResponse().getFirstHeader("location").getValue();
}
} catch (IOException e) {
throw new IllegalStateException("Unable to get ticket granting ticket.");
}
lastUpdate = System.currentTimeMillis();
}
}
private String getSingleUseTicket() {
getTicketGrantingTicket();
String ticket = "";
try {
ticket = Request.Post(ticketGrantingTicketURL).useExpectContinue().version(HttpVersion.HTTP_1_1)
.bodyForm(Form.form().add("service", UTS_SERVICE_URL).build())
.execute().returnContent().asString();
} catch (IOException e) {
throw new IllegalStateException("Unable to get ticket.");
}
return ticket;
}
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.semservices.service.impl;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import edu.cornell.mannlib.semservices.bo.Concept;
import edu.cornell.mannlib.semservices.exceptions.ConceptsNotFoundException;
import edu.cornell.mannlib.semservices.service.ExternalConceptService;
import edu.cornell.mannlib.vitro.webapp.utils.json.JacksonUtils;
import org.apache.http.HttpVersion;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.utils.URIBuilder;
import org.springframework.util.StringUtils;
/**
* @author jaf30
*
*/
public class UMLSService implements ExternalConceptService {
protected final Log logger = LogFactory.getLog(getClass());
private static String UTS_REST_API_URL = "https://uts-ws.nlm.nih.gov/rest";
private static String SEARCH_PATH = "/search/current";
private static String SEARCH_PARAMETER = "string";
private static String SEARCH_TYPE_PARAMETER = "searchType";
private static String SEARCH_TYPE = "rightTruncation";
private static String PAGE_SIZE_PARAMETER = "pageSize";
private static String RETURN_TYPE_PARAMETER = "returnIdType";
private static String RETURN_TYPE = "concept";
private static String TICKET_PARAMETER = "ticket";
private static String ticketGrantingTicketURL = null;
private static long lastUpdate = -1;
private static String username = null;
private static String password = null;
private static String apikey = null;
private static String pageSize = "50";
private static String UMLS_AUTH_USER_URL = "https://utslogin.nlm.nih.gov/cas/v1/tickets";
private static String UMLS_AUTH_KEY_URL = "https://utslogin.nlm.nih.gov/cas/v1/api-key";
private static String UTS_SERVICE_URL = "http://umlsks.nlm.nih.gov";
{
if (username == null || apikey == null) {
final Properties properties = new Properties();
try (InputStream stream = getClass().getResourceAsStream("/umls.properties")) {
properties.load(stream);
username = properties.getProperty("username");
password = properties.getProperty("password");
apikey = properties.getProperty("apikey");
String exPageSize = properties.getProperty("pagesize");
try {
if (!StringUtils.isEmpty(exPageSize)) {
int iPageSize = Integer.parseInt(exPageSize, 10);
if (iPageSize > 5 && iPageSize < 200) {
pageSize = Integer.toString(iPageSize, 10);
}
}
} catch (Exception e) {
}
} catch (IOException e) {
}
}
}
public boolean isConfigured() {
return !(StringUtils.isEmpty(username) && StringUtils.isEmpty(apikey));
}
@Override
public List<Concept> getConcepts(String term) throws Exception {
String ticket = getSingleUseTicket();
List<Concept> conceptList = new ArrayList<Concept>();
String results = null;
try {
URIBuilder b = new URIBuilder(UTS_REST_API_URL + SEARCH_PATH);
b.addParameter(SEARCH_PARAMETER, term);
b.addParameter(RETURN_TYPE_PARAMETER, RETURN_TYPE);
b.addParameter(SEARCH_TYPE_PARAMETER, SEARCH_TYPE);
b.addParameter(PAGE_SIZE_PARAMETER, pageSize);
b.addParameter(TICKET_PARAMETER, ticket);
results = Request.Get(b.build())
.connectTimeout(3000)
.socketTimeout(3000)
.execute().returnContent().asString();
conceptList = processOutput(results);
return conceptList;
} catch (Exception ex) {
logger.error("error occurred in servlet", ex);
return null;
}
}
public List<Concept> processResults(String term) throws Exception {
return getConcepts(term);
}
/**
* @param uri URI
*/
public List<Concept> getConceptsByURIWithSparql(String uri) throws Exception {
// deprecating this method...just return an empty list
List<Concept> conceptList = new ArrayList<Concept>();
return conceptList;
}
/**
* @param results Results to process
*/
private List<Concept> processOutput(String results) throws Exception {
List<Concept> conceptList = new ArrayList<Concept>();
List<String> bestMatchIdList = new ArrayList<String>();
String bestMatchId = "";
try {
ObjectNode json = (ObjectNode) JacksonUtils.parseJson(results);
ArrayNode allArray = (ArrayNode) json.get("result").get("results");
int len = allArray.size();
int i;
for (i = 0; i < len; i++) {
ObjectNode o = (ObjectNode) allArray.get(i);
Concept concept = new Concept();
concept.setDefinedBy(UTS_SERVICE_URL);
concept.setSchemeURI(UTS_SERVICE_URL);
concept.setType(RETURN_TYPE);
concept.setConceptId(getJsonValue(o, "ui"));
concept.setLabel(getJsonValue(o, "name"));
concept.setUri(getJsonValue(o, "uri"));
concept.setBestMatch("false");
conceptList.add(concept);
}
} catch (Exception ex) {
ex.printStackTrace();
logger.error("Could not get concepts", ex);
throw ex;
}
if (conceptList.size() == 0) {
throw new ConceptsNotFoundException();
}
//
return conceptList;
}
/**
* Get a string from a json object or an empty string if there is no value for the given key
*
* @param obj JSON Object
* @param key Key to retrieve
*/
protected String getJsonValue(ObjectNode obj, String key) {
if (obj.has(key)) {
return obj.get(key).asText();
} else {
return "";
}
}
protected String stripConceptId(String uri) {
String conceptId = "";
int lastslash = uri.lastIndexOf('/');
conceptId = uri.substring(lastslash + 1, uri.length());
return conceptId;
}
private synchronized void getTicketGrantingTicket() {
if (StringUtils.isEmpty(username) && StringUtils.isEmpty(apikey)) {
throw new IllegalStateException("Unable to read umls.properties");
}
if (ticketGrantingTicketURL == null || lastUpdate + 28700000L < System.currentTimeMillis()) {
try {
if (!StringUtils.isEmpty(apikey)) {
ticketGrantingTicketURL = Request.Post(UMLS_AUTH_KEY_URL).useExpectContinue().version(HttpVersion.HTTP_1_1)
.bodyForm(Form.form().add("apikey", apikey).build())
.execute().returnResponse().getFirstHeader("location").getValue();
} else {
ticketGrantingTicketURL = Request.Post(UMLS_AUTH_USER_URL).useExpectContinue().version(HttpVersion.HTTP_1_1)
.bodyForm(Form.form().add("username", username).add("password", password).build())
.execute().returnResponse().getFirstHeader("location").getValue();
}
} catch (IOException e) {
throw new IllegalStateException("Unable to get ticket granting ticket.");
}
lastUpdate = System.currentTimeMillis();
}
}
private String getSingleUseTicket() {
getTicketGrantingTicket();
String ticket = "";
try {
ticket = Request.Post(ticketGrantingTicketURL).useExpectContinue().version(HttpVersion.HTTP_1_1)
.bodyForm(Form.form().add("service", UTS_SERVICE_URL).build())
.execute().returnContent().asString();
} catch (IOException e) {
throw new IllegalStateException("Unable to get ticket.");
}
return ticket;
}
}

View file

@ -1,6 +1,6 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.controller;
package edu.cornell.mannlib.vitro.webapp.controller;
import java.util.HashMap;
import java.util.Map;
@ -18,7 +18,7 @@ import javax.servlet.annotation.WebServlet;
@WebServlet(name = "AboutQrCodesController", urlPatterns = {"/qrcode/about"})
public class AboutQrCodesController extends FreemarkerHttpServlet {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(ExportQrCodeController.class);
private static final String TEMPLATE_DEFAULT = "aboutQrCodes.ftl";
@ -27,7 +27,7 @@ public class AboutQrCodesController extends FreemarkerHttpServlet {
protected ResponseValues processRequest(VitroRequest vreq) {
try {
Map<String, Object> body = new HashMap<String, Object>();
return new TemplateResponseValues(TEMPLATE_DEFAULT, body);
} catch (Throwable e) {
log.error(e, e);

View file

@ -1,6 +1,6 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.controller;
package edu.cornell.mannlib.vitro.webapp.controller;
import java.util.ArrayList;
import java.util.HashMap;
@ -31,7 +31,7 @@ import javax.servlet.annotation.WebServlet;
@WebServlet(name = "ExportQrCodeController", urlPatterns = {"/qrcode"})
public class ExportQrCodeController extends FreemarkerHttpServlet {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(ExportQrCodeController.class);
private static final String TEMPLATE_DEFAULT = "foaf-person--exportQrCode.ftl";
@ -61,12 +61,12 @@ public class ExportQrCodeController extends FreemarkerHttpServlet {
protected ResponseValues processRequest(VitroRequest vreq) {
try {
Individual individual = getIndividualFromRequest(vreq);
qrData = generateQrData(individual, vreq);
DefaultObjectWrapper wrapper = new DefaultObjectWrapper();
wrapper.setExposureLevel(BeansWrapper.EXPOSE_SAFE);
Map<String, Object> body = new HashMap<String, Object>();
body.put("individual", wrapper.wrap(IndividualTemplateModelBuilder.build(individual, vreq)));
body.put("qrData", qrData);
@ -94,7 +94,7 @@ public class ExportQrCodeController extends FreemarkerHttpServlet {
}
private Map<String, String> generateQrData(Individual individual, VitroRequest vreq) {
try {
String firstName = "";
String lastName = "";
@ -106,7 +106,7 @@ public class ExportQrCodeController extends FreemarkerHttpServlet {
Map<String,String> qrData = new HashMap<String,String>();
for (Map<String, String> map: vcardData) {
for (Map<String, String> map: vcardData) {
firstName = map.get("firstName");
lastName = map.get("lastName");
preferredTitle = map.get("title");
@ -128,13 +128,13 @@ public class ExportQrCodeController extends FreemarkerHttpServlet {
String tempUrl = vreq.getRequestURL().toString();
String prefix = "http://";
tempUrl = tempUrl.substring(0, tempUrl.replace(prefix, "").indexOf("/") + prefix.length());
String externalUrl = tempUrl ;
String externalUrl = tempUrl ;
qrData.put("externalUrl", externalUrl);
String individualUri = individual.getURI();
String contextPath = vreq.getContextPath();
qrData.put("exportQrCodeUrl", contextPath + "/qrcode?uri=" + UrlBuilder.urlEncode(individualUri));
qrData.put("aboutQrCodesUrl", contextPath + "/qrcode/about");
return qrData;
} catch (Exception e) {
@ -155,8 +155,8 @@ public class ExportQrCodeController extends FreemarkerHttpServlet {
}
} catch (Exception e) {
log.error(e, e);
}
}
return vcardData;
}

View file

@ -27,7 +27,7 @@ public class GeoFocusMapLocations extends AbstractAjaxResponder {
private static String GEO_FOCUS_QUERY = ""
+ "PREFIX geo: <http://aims.fao.org/aos/geopolitical.owl#> \n"
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n"
+ "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n"
+ "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n"
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
+ "PREFIX foaf: <http://xmlns.com/foaf/0.1/> \n"
+ "PREFIX vivoc: <http://vivo.library.cornell.edu/ns/0.1#> \n"
@ -52,7 +52,7 @@ public class GeoFocusMapLocations extends AbstractAjaxResponder {
+ " ?person rdf:type foaf:Person \n"
+ "} } \n"
+ "GROUP BY ?label ?location \n";
public GeoFocusMapLocations(HttpServlet parent, VitroRequest vreq,
HttpServletResponse resp) {
super(parent, vreq, resp);
@ -62,12 +62,12 @@ public class GeoFocusMapLocations extends AbstractAjaxResponder {
public String prepareResponse() throws IOException {
try {
geoLocations = getGeoLocations(vreq);
StringBuilder response = new StringBuilder("[");
String geometry = "{\"geometry\": {\"type\": \"Point\",\"coordinates\": \"\"},";
String typeProps = "\"type\": \"Feature\",\"properties\": {\"mapType\": \"\",";
String previousLabel = "";
for (Map<String, String> map: geoLocations) {
String label = map.get("label");
String html = map.get("count");
@ -79,7 +79,7 @@ public class GeoFocusMapLocations extends AbstractAjaxResponder {
Integer count = Integer.parseInt(map.get("count"));
String radius = String.valueOf(calculateRadius(count));
String name = "";
if ( label != null && !label.equals(previousLabel) ) {
if ( label.contains("Ivoire") ) {
name = "Ivory Coast";
@ -94,18 +94,18 @@ public class GeoFocusMapLocations extends AbstractAjaxResponder {
name = label;
}
String tempStr = geometry; //+label
tempStr += typeProps //+ label
tempStr += typeProps //+ label
+ "\"popupContent\": \""
+ name
+ name
+ "\",\"html\":"
+ html
+ html
+ ",\"radius\":"
+ radius
+ ",\"uri\": \""
+ uri
+ "\",\"local\": \""
+ local
+ "\"}},";
+ "\"}},";
response.append(tempStr);
previousLabel = label;
}
@ -123,9 +123,9 @@ public class GeoFocusMapLocations extends AbstractAjaxResponder {
return EMPTY_RESPONSE;
}
}
private List<Map<String,String>> getGeoLocations(VitroRequest vreq) {
String queryStr = GEO_FOCUS_QUERY;
log.debug("queryStr = " + queryStr);
List<Map<String,String>> locations = new ArrayList<Map<String,String>>();
@ -137,12 +137,12 @@ public class GeoFocusMapLocations extends AbstractAjaxResponder {
}
} catch (Exception e) {
log.error(e, e);
}
}
return locations;
}
private Integer calculateRadius(Integer count) {
int radius = 8;
if ( count != null ) {
if ( count < 4 ) {

View file

@ -30,7 +30,7 @@ public class GeoFocusResearcherCount extends AbstractAjaxResponder {
+ " ?person a foaf:Person . \n"
+ " ?person core:geographicFocus ?focus \n"
+ "}" ;
public GeoFocusResearcherCount(HttpServlet parent, VitroRequest vreq,
HttpServletResponse resp) {
super(parent, vreq, resp);
@ -40,9 +40,9 @@ public class GeoFocusResearcherCount extends AbstractAjaxResponder {
public String prepareResponse() throws IOException {
try {
geoFocusCount = getGeoFocusCount(vreq);
StringBuilder response = new StringBuilder("{ ");
for (Map<String, String> map: geoFocusCount) {
String theCount = map.get("count");
response.append("\"count\": \"").append(theCount).append("\"");
@ -55,9 +55,9 @@ public class GeoFocusResearcherCount extends AbstractAjaxResponder {
return EMPTY_RESPONSE;
}
}
private List<Map<String,String>> getGeoFocusCount(VitroRequest vreq) {
String queryStr = GEO_FOCUS_COUNT_QUERY;
log.debug("queryStr = " + queryStr);
List<Map<String,String>> count = new ArrayList<Map<String,String>>();
@ -69,8 +69,8 @@ public class GeoFocusResearcherCount extends AbstractAjaxResponder {
}
} catch (Exception e) {
log.error(e, e);
}
}
return count;
}
}

View file

@ -35,7 +35,7 @@ public class HomePageAjaxController extends VitroAjaxController {
}
else if ("getGeoFocusResearcherCount".equals(function)) {
new GeoFocusResearcherCount(this, vreq, resp).processRequest();
}
}
else {
resp.getWriter().write("[]");
}

View file

@ -46,7 +46,7 @@ public class QrCodeDetails extends AbstractAjaxResponder {
+ " ?vTitle vcard:title ?title . \n"
+ " } \n"
+ "} " ;
public QrCodeDetails(HttpServlet parent, VitroRequest vreq,
HttpServletResponse resp) {
super(parent, vreq, resp);
@ -62,17 +62,17 @@ public class QrCodeDetails extends AbstractAjaxResponder {
String phoneNumber = "";
String email = "";
String response = "[";
vcardData = getVcardData(individual, vreq);
for (Map<String, String> map: vcardData) {
for (Map<String, String> map: vcardData) {
firstName = map.get("firstName");
lastName = map.get("lastName");
preferredTitle = map.get("title");
phoneNumber = map.get("phone");
email = map.get("email");
}
/*
String tempUrl = vreq.getRequestURL().toString();
String prefix = "http://";
@ -121,7 +121,7 @@ public class QrCodeDetails extends AbstractAjaxResponder {
return EMPTY_RESPONSE;
}
}
private List<Map<String,String>> getVcardData(Individual individual, VitroRequest vreq) {
String queryStr = QueryUtils.subUriForQueryVar(VCARD_DATA_QUERY, "subject", individual.getURI());
log.debug("queryStr = " + queryStr);
@ -134,8 +134,8 @@ public class QrCodeDetails extends AbstractAjaxResponder {
}
} catch (Exception e) {
log.error(e, e);
}
}
return vcardData;
}

View file

@ -1,258 +1,258 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.TBOX_ASSERTIONS;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.rdf.model.StmtIterator;
import org.apache.jena.shared.Lock;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.AuthorizationRequest;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.edit.utils.LocalNamespaceClassUtils;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.RedirectResponseValues;
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.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.jena.event.EditEvent;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
/*
* Custom controller for menu management. This will be replaced later once N3 Editing
* has been successfully refactored and integrated with menu management.
*/
@WebServlet(name = "InstitutionalInternalClassController", urlPatterns = {"/processInstitutionalInternalClass"} )
public class InstitutionalInternalClassController extends FreemarkerHttpServlet {
private static final Log log = LogFactory.getLog(InstitutionalInternalClassController.class);
private static final String EDIT_FORM = "/processInstitutionalInternalClass";
public final static AuthorizationRequest REQUIRED_ACTIONS = SimplePermission.MANAGE_MENUS.ACTION;
private static final String DISPLAY_FORM = "/institutionalInternalClassForm.ftl";
private static HashMap<String, String> localNamespaces = new HashMap<String, String>();
private static HashMap<String, String> localNamespaceClasses = new HashMap<String, String>();
private static final String CREATE_CLASS_PARAM = "createClass";
private static final String REDIRECT_PAGE = "/siteAdmin";
@Override
protected AuthorizationRequest requiredActions(VitroRequest vreq) {
return REQUIRED_ACTIONS;
}
@Override
protected ResponseValues processRequest(VitroRequest vreq) {
//Based on existing of local namespaces and number of local classes present
//as well as command parameter, execute command
Map<String, Object> data = new HashMap<String,Object>();
//Get all local classes and namespace information
retrieveLocalClasses(vreq, data);
if(isSubmission(vreq)){
processSubmission(vreq, data);
} else if(isCreateNewClass(vreq)) {
//Local namespace(s) exist and user wishes to create a new class
//Either cmd = create new or no local classes exist at all and one must be created
processCreateNewClass(vreq, data);
} else if(isSelectExistingClass(vreq)) {
//Local namespace(s) exist and user can select an existing class
processSelectExistingClass(vreq, data);
} else if(isCreateOntologies(vreq)) {
//Not being handled expliclity but message will display indicating
//no local namespaces exist and one must be created
processCreateOntologies(vreq, data);
} else {
log.error("Don't recognize the type of request.");
}
//Retrieve local namespaces
//Check if existing local namespaces
data.put("formUrl", vreq.getContextPath() + EDIT_FORM);
data.put("cancelUrl", vreq.getContextPath() + REDIRECT_PAGE);
//if no local namespaces, then provide message to display
//if existing namespace(s), then check
//if single namespace, retrieve all classes belonging to that local namespace
//if multiple namespaces, generate select list with namespaces
//for instertion: VClassDaoJena.insertVClass
//
if(isSubmission(vreq)){
return redirectToSiteAdmin();
}
return new TemplateResponseValues(DISPLAY_FORM, data);
}
private boolean isSubmission(VitroRequest vreq) {
String submit = vreq.getParameter("submitForm");
return(submit!= null && !submit.isEmpty());
}
private void processCreateOntologies(VitroRequest vreq, Map<String, Object> data) {
data.put("submitAction", "");
}
private boolean isCreateOntologies(VitroRequest vreq) {
//no local namespaces
return (localNamespaces.size() == 0);
}
private void processCreateNewClass(VitroRequest vreq, Map<String, Object> data) {
//this may need to be changed on the basis of how new classes interact with new ontologies
data.put("submitAction", "Create Class");
data.put("createNewClass", true);
}
private boolean isCreateNewClass(VitroRequest vreq) {
String command = vreq.getParameter("cmd");
if(command != null && command.equals(CREATE_CLASS_PARAM)) {
return true;
}
//If local namespace exists but no classes in local namespaces, then need to enable creation of new classes
return(localNamespaces.size() > 0 && localNamespaceClasses.size() == 0);
}
private void processSelectExistingClass(VitroRequest vreq, Map<String, Object> data) {
//Check if local classes exist and use for selection
data.put("useExistingLocalClass", true);
data.put("submitAction", "Save");
}
private boolean isSelectExistingClass(VitroRequest vreq) {
//Local namespaces exist and there are existing classes within those namespaces
return (localNamespaces.size() > 0 && localNamespaceClasses.size() > 0);
}
private void retrieveLocalClasses(VitroRequest vreq, Map<String, Object> data) {
localNamespaces = LocalNamespaceClassUtils.getLocalOntologyNamespaces(vreq);
//Get classes for local namespaces
localNamespaceClasses = LocalNamespaceClassUtils.getLocalNamespacesClasses(vreq, localNamespaces);
data.put("existingLocalClasses", localNamespaceClasses);
data.put("existingLocalNamespaces", localNamespaces);
String noLocalOntologiesMessage = "There are currently no local ontologies. You must create a new ontology";
data.put("noLocalOntologiesMessage", noLocalOntologiesMessage);
if(localNamespaces.size() == 0) {
data.put("ontologiesExist", false);
}
else {
data.put("ontologiesExist", true);
if(localNamespaces.size() > 1) {
data.put("multipleLocalNamespaces", true);
} else {
data.put("multipleLocalNamespaces", false);
data.put("existingLocalNamespace", localNamespaces.keySet().iterator().next());
}
//Get current internal class if it exists
data.put("existingInternalClass", retrieveCurrentInternalClass());
}
//Place default namespace within data to pass back to template
String defaultNamespace = vreq.getWebappDaoFactory().getDefaultNamespace();
data.put("defaultNamespace", defaultNamespace);
}
//Process submission on submitting form
private void processSubmission(VitroRequest vreq, Map<String, Object> data) {
//If new class, need to generate new class
String classUri = null;
if(isNewClassSubmission(vreq)){
VClass v= generateNewVClass(vreq.getParameter("localClassName"), vreq.getParameter("existingLocalNamespaces"));
classUri = v.getURI();
try {
vreq.getWebappDaoFactory().getVClassDao().insertNewVClass(v);
} catch(Exception ex) {
log.error("Insertion of new class " + vreq.getParameter("name") + " resulted in error ", ex);
}
} else {
//Existing class so get URI from that
classUri = getExistingClassUri(vreq);
}
//If existing class, need to simply add a statement specifying existing class is an internal class
if(classUri != null && !classUri.isEmpty()) {
Model writeModel = ModelAccess.on(getServletContext()).getOntModel(TBOX_ASSERTIONS);
writeModel.enterCriticalSection(Lock.WRITE);
writeModel.notifyEvent(new EditEvent(null,true));
try {
log.debug("Should be removing these statements " + writeModel.listStatements(null,
ResourceFactory.createProperty(VitroVocabulary.IS_INTERNAL_CLASSANNOT),
(RDFNode) null).toList().toString());
//remove existing internal classes if there are any as assuming only one
writeModel.removeAll(null,
ResourceFactory.createProperty(VitroVocabulary.IS_INTERNAL_CLASSANNOT),
(RDFNode) null);
log.debug("Are there any statements left for internal class annotation: " + writeModel.listStatements(null,
ResourceFactory.createProperty(VitroVocabulary.IS_INTERNAL_CLASSANNOT),
(RDFNode) null).toList().toString());
writeModel.add(
writeModel.createStatement(
ResourceFactory.createResource(classUri),
ResourceFactory.createProperty(VitroVocabulary.IS_INTERNAL_CLASSANNOT),
writeModel.createLiteral("true")));
} catch(Exception ex) {
log.error("Error occurred in adding statement for " + classUri + " becoming internal class", ex);
} finally {
writeModel.notifyEvent(new EditEvent(null,true));
writeModel.leaveCriticalSection();
}
}
}
private VClass generateNewVClass(String newClassName, String namespace) {
VClass newClass = new VClass();
newClass.setName(newClassName);
newClass.setNamespace(namespace);
String uri = namespace + newClassName.replaceAll(" ", "");
newClass.setURI(uri);
//How to g
return newClass;
}
private boolean isNewClassSubmission(VitroRequest vreq) {
String localName = vreq.getParameter("localClassName");
return (localName != null && !localName.isEmpty());
}
private String getExistingClassUri(VitroRequest vreq) {
return vreq.getParameter("existingLocalClasses");
}
private RedirectResponseValues redirectToSiteAdmin() {
return new RedirectResponseValues(REDIRECT_PAGE, HttpServletResponse.SC_SEE_OTHER);
}
//Get current internal class
private String retrieveCurrentInternalClass() {
String internalClassUri = "";
Model mainModel = ModelAccess.on(getServletContext()).getOntModel(TBOX_ASSERTIONS);
StmtIterator internalIt = mainModel.listStatements(null,
ResourceFactory.createProperty(VitroVocabulary.IS_INTERNAL_CLASSANNOT),
(RDFNode) null);
while(internalIt.hasNext()){
Statement s = internalIt.nextStatement();
//The class IS an internal class so the subject is what we're looking for
internalClassUri = s.getSubject().getURI();
log.debug("Found internal class uri " + internalClassUri);
}
return internalClassUri;
}
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.TBOX_ASSERTIONS;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.rdf.model.StmtIterator;
import org.apache.jena.shared.Lock;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.AuthorizationRequest;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.edit.utils.LocalNamespaceClassUtils;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.RedirectResponseValues;
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.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.jena.event.EditEvent;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
/*
* Custom controller for menu management. This will be replaced later once N3 Editing
* has been successfully refactored and integrated with menu management.
*/
@WebServlet(name = "InstitutionalInternalClassController", urlPatterns = {"/processInstitutionalInternalClass"} )
public class InstitutionalInternalClassController extends FreemarkerHttpServlet {
private static final Log log = LogFactory.getLog(InstitutionalInternalClassController.class);
private static final String EDIT_FORM = "/processInstitutionalInternalClass";
public final static AuthorizationRequest REQUIRED_ACTIONS = SimplePermission.MANAGE_MENUS.ACTION;
private static final String DISPLAY_FORM = "/institutionalInternalClassForm.ftl";
private static HashMap<String, String> localNamespaces = new HashMap<String, String>();
private static HashMap<String, String> localNamespaceClasses = new HashMap<String, String>();
private static final String CREATE_CLASS_PARAM = "createClass";
private static final String REDIRECT_PAGE = "/siteAdmin";
@Override
protected AuthorizationRequest requiredActions(VitroRequest vreq) {
return REQUIRED_ACTIONS;
}
@Override
protected ResponseValues processRequest(VitroRequest vreq) {
//Based on existing of local namespaces and number of local classes present
//as well as command parameter, execute command
Map<String, Object> data = new HashMap<String,Object>();
//Get all local classes and namespace information
retrieveLocalClasses(vreq, data);
if(isSubmission(vreq)){
processSubmission(vreq, data);
} else if(isCreateNewClass(vreq)) {
//Local namespace(s) exist and user wishes to create a new class
//Either cmd = create new or no local classes exist at all and one must be created
processCreateNewClass(vreq, data);
} else if(isSelectExistingClass(vreq)) {
//Local namespace(s) exist and user can select an existing class
processSelectExistingClass(vreq, data);
} else if(isCreateOntologies(vreq)) {
//Not being handled expliclity but message will display indicating
//no local namespaces exist and one must be created
processCreateOntologies(vreq, data);
} else {
log.error("Don't recognize the type of request.");
}
//Retrieve local namespaces
//Check if existing local namespaces
data.put("formUrl", vreq.getContextPath() + EDIT_FORM);
data.put("cancelUrl", vreq.getContextPath() + REDIRECT_PAGE);
//if no local namespaces, then provide message to display
//if existing namespace(s), then check
//if single namespace, retrieve all classes belonging to that local namespace
//if multiple namespaces, generate select list with namespaces
//for instertion: VClassDaoJena.insertVClass
//
if(isSubmission(vreq)){
return redirectToSiteAdmin();
}
return new TemplateResponseValues(DISPLAY_FORM, data);
}
private boolean isSubmission(VitroRequest vreq) {
String submit = vreq.getParameter("submitForm");
return(submit!= null && !submit.isEmpty());
}
private void processCreateOntologies(VitroRequest vreq, Map<String, Object> data) {
data.put("submitAction", "");
}
private boolean isCreateOntologies(VitroRequest vreq) {
//no local namespaces
return (localNamespaces.size() == 0);
}
private void processCreateNewClass(VitroRequest vreq, Map<String, Object> data) {
//this may need to be changed on the basis of how new classes interact with new ontologies
data.put("submitAction", "Create Class");
data.put("createNewClass", true);
}
private boolean isCreateNewClass(VitroRequest vreq) {
String command = vreq.getParameter("cmd");
if(command != null && command.equals(CREATE_CLASS_PARAM)) {
return true;
}
//If local namespace exists but no classes in local namespaces, then need to enable creation of new classes
return(localNamespaces.size() > 0 && localNamespaceClasses.size() == 0);
}
private void processSelectExistingClass(VitroRequest vreq, Map<String, Object> data) {
//Check if local classes exist and use for selection
data.put("useExistingLocalClass", true);
data.put("submitAction", "Save");
}
private boolean isSelectExistingClass(VitroRequest vreq) {
//Local namespaces exist and there are existing classes within those namespaces
return (localNamespaces.size() > 0 && localNamespaceClasses.size() > 0);
}
private void retrieveLocalClasses(VitroRequest vreq, Map<String, Object> data) {
localNamespaces = LocalNamespaceClassUtils.getLocalOntologyNamespaces(vreq);
//Get classes for local namespaces
localNamespaceClasses = LocalNamespaceClassUtils.getLocalNamespacesClasses(vreq, localNamespaces);
data.put("existingLocalClasses", localNamespaceClasses);
data.put("existingLocalNamespaces", localNamespaces);
String noLocalOntologiesMessage = "There are currently no local ontologies. You must create a new ontology";
data.put("noLocalOntologiesMessage", noLocalOntologiesMessage);
if(localNamespaces.size() == 0) {
data.put("ontologiesExist", false);
}
else {
data.put("ontologiesExist", true);
if(localNamespaces.size() > 1) {
data.put("multipleLocalNamespaces", true);
} else {
data.put("multipleLocalNamespaces", false);
data.put("existingLocalNamespace", localNamespaces.keySet().iterator().next());
}
//Get current internal class if it exists
data.put("existingInternalClass", retrieveCurrentInternalClass());
}
//Place default namespace within data to pass back to template
String defaultNamespace = vreq.getWebappDaoFactory().getDefaultNamespace();
data.put("defaultNamespace", defaultNamespace);
}
//Process submission on submitting form
private void processSubmission(VitroRequest vreq, Map<String, Object> data) {
//If new class, need to generate new class
String classUri = null;
if(isNewClassSubmission(vreq)){
VClass v= generateNewVClass(vreq.getParameter("localClassName"), vreq.getParameter("existingLocalNamespaces"));
classUri = v.getURI();
try {
vreq.getWebappDaoFactory().getVClassDao().insertNewVClass(v);
} catch(Exception ex) {
log.error("Insertion of new class " + vreq.getParameter("name") + " resulted in error ", ex);
}
} else {
//Existing class so get URI from that
classUri = getExistingClassUri(vreq);
}
//If existing class, need to simply add a statement specifying existing class is an internal class
if(classUri != null && !classUri.isEmpty()) {
Model writeModel = ModelAccess.on(getServletContext()).getOntModel(TBOX_ASSERTIONS);
writeModel.enterCriticalSection(Lock.WRITE);
writeModel.notifyEvent(new EditEvent(null,true));
try {
log.debug("Should be removing these statements " + writeModel.listStatements(null,
ResourceFactory.createProperty(VitroVocabulary.IS_INTERNAL_CLASSANNOT),
(RDFNode) null).toList().toString());
//remove existing internal classes if there are any as assuming only one
writeModel.removeAll(null,
ResourceFactory.createProperty(VitroVocabulary.IS_INTERNAL_CLASSANNOT),
(RDFNode) null);
log.debug("Are there any statements left for internal class annotation: " + writeModel.listStatements(null,
ResourceFactory.createProperty(VitroVocabulary.IS_INTERNAL_CLASSANNOT),
(RDFNode) null).toList().toString());
writeModel.add(
writeModel.createStatement(
ResourceFactory.createResource(classUri),
ResourceFactory.createProperty(VitroVocabulary.IS_INTERNAL_CLASSANNOT),
writeModel.createLiteral("true")));
} catch(Exception ex) {
log.error("Error occurred in adding statement for " + classUri + " becoming internal class", ex);
} finally {
writeModel.notifyEvent(new EditEvent(null,true));
writeModel.leaveCriticalSection();
}
}
}
private VClass generateNewVClass(String newClassName, String namespace) {
VClass newClass = new VClass();
newClass.setName(newClassName);
newClass.setNamespace(namespace);
String uri = namespace + newClassName.replaceAll(" ", "");
newClass.setURI(uri);
//How to g
return newClass;
}
private boolean isNewClassSubmission(VitroRequest vreq) {
String localName = vreq.getParameter("localClassName");
return (localName != null && !localName.isEmpty());
}
private String getExistingClassUri(VitroRequest vreq) {
return vreq.getParameter("existingLocalClasses");
}
private RedirectResponseValues redirectToSiteAdmin() {
return new RedirectResponseValues(REDIRECT_PAGE, HttpServletResponse.SC_SEE_OTHER);
}
//Get current internal class
private String retrieveCurrentInternalClass() {
String internalClassUri = "";
Model mainModel = ModelAccess.on(getServletContext()).getOntModel(TBOX_ASSERTIONS);
StmtIterator internalIt = mainModel.listStatements(null,
ResourceFactory.createProperty(VitroVocabulary.IS_INTERNAL_CLASSANNOT),
(RDFNode) null);
while(internalIt.hasNext()){
Statement s = internalIt.nextStatement();
//The class IS an internal class so the subject is what we're looking for
internalClassUri = s.getSubject().getURI();
log.debug("Found internal class uri " + internalClassUri);
}
return internalClassUri;
}
}

View file

@ -32,7 +32,7 @@ public class ManageGrantsForIndividualController extends FreemarkerHttpServlet {
private static final Log log = LogFactory.getLog(ManageGrantsForIndividualController.class.getName());
private static final String TEMPLATE_NAME = "manageGrantsForIndividual.ftl";
@Override
protected AuthorizationRequest requiredActions(VitroRequest vreq) {
return SimplePermission.DO_FRONT_END_EDITING.ACTION;
@ -54,17 +54,17 @@ public class ManageGrantsForIndividualController extends FreemarkerHttpServlet {
List<String> allSubclasses = getAllSubclasses(grants);
body.put("allSubclasses", allSubclasses);
Individual subject = vreq.getWebappDaoFactory().getIndividualDao().getIndividualByURI(subjectUri);
if( subject != null && subject.getName() != null ){
body.put("subjectName", subject.getName());
}else{
body.put("subjectName", null);
}
return new TemplateResponseValues(TEMPLATE_NAME, body);
}
private static String GRANT_QUERY = ""
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n"
@ -87,12 +87,12 @@ public class ManageGrantsForIndividualController extends FreemarkerHttpServlet {
+ " ?activity a core:Project . \n"
+ " ?activity rdfs:label ?label2 . \n"
+ " } \n"
+ " OPTIONAL { ?role core:hideFromDisplay ?hideThis } \n"
+ " OPTIONAL { ?role core:hideFromDisplay ?hideThis } \n"
+ "} ORDER BY ?subclass ?label2";
HashMap<String, List<Map<String,String>>> getGrants(String subjectUri, VitroRequest vreq) {
VClassDao vcDao = vreq.getUnfilteredAssertionsWebappDaoFactory().getVClassDao();
VClassDao vcDao = vreq.getUnfilteredAssertionsWebappDaoFactory().getVClassDao();
String queryStr = QueryUtils.subUriForQueryVar(GRANT_QUERY, "subject", subjectUri);
log.debug("queryStr = " + queryStr);
HashMap<String, List<Map<String,String>>> subclassToGrants = new HashMap<String, List<Map<String,String>>>();
@ -109,13 +109,13 @@ public class ManageGrantsForIndividualController extends FreemarkerHttpServlet {
subclassToGrants.put(subclass, new ArrayList<Map<String,String>>()); //list of grant information
}
List<Map<String,String>> grantsList = subclassToGrants.get(subclass);
grantsList.add(QueryUtils.querySolutionToStringValueMap(soln));
}
grantsList.add(QueryUtils.querySolutionToStringValueMap(soln));
}
}
} catch (Exception e) {
log.error(e, e);
}
}
return subclassToGrants;
}

View file

@ -32,7 +32,7 @@ public class ManagePeopleForOrganizationController extends FreemarkerHttpServlet
private static final Log log = LogFactory.getLog(ManagePeopleForOrganizationController.class.getName());
private static final String TEMPLATE_NAME = "managePeopleForOrganization.ftl";
@Override
protected AuthorizationRequest requiredActions(VitroRequest vreq) {
return SimplePermission.DO_FRONT_END_EDITING.ACTION;
@ -54,17 +54,17 @@ public class ManagePeopleForOrganizationController extends FreemarkerHttpServlet
List<String> allSubclasses = getAllSubclasses(people);
body.put("allSubclasses", allSubclasses);
Individual subject = vreq.getWebappDaoFactory().getIndividualDao().getIndividualByURI(subjectUri);
if( subject != null && subject.getName() != null ){
body.put("subjectName", subject.getName());
}else{
body.put("subjectName", null);
}
return new TemplateResponseValues(TEMPLATE_NAME, body);
}
private static String PEOPLE_QUERY = ""
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n"
@ -88,8 +88,8 @@ public class ManagePeopleForOrganizationController extends FreemarkerHttpServlet
+ " } \n "
+ " OPTIONAL { ?position core:hideFromDisplay ?hideThis } \n "
+ " FILTER ( !BOUND(?displayRank) || ?displayRank < 500 )"
+ "} ORDER BY ?subclass ?name";
+ "} ORDER BY ?subclass ?name";
HashMap<String, List<Map<String,String>>> getPeople(String subjectUri, VitroRequest vreq) {
VClassDao vcDao = vreq.getUnfilteredAssertionsWebappDaoFactory().getVClassDao();
@ -106,7 +106,7 @@ public class ManagePeopleForOrganizationController extends FreemarkerHttpServlet
VClass vClass = vcDao.getVClassByURI(subclassUriStr);
String subclass = ((vClass.getName() == null) ? subclassUriStr : vClass.getName());
if(!subclassToPeople.containsKey(subclass)) {
subclassToPeople.put(subclass, new ArrayList<Map<String,String>>());
subclassToPeople.put(subclass, new ArrayList<Map<String,String>>());
}
List<Map<String,String>> peopleList = subclassToPeople.get(subclass);
peopleList.add(QueryUtils.querySolutionToStringValueMap(soln));
@ -114,7 +114,7 @@ public class ManagePeopleForOrganizationController extends FreemarkerHttpServlet
}
} catch (Exception e) {
log.error(e, e);
}
}
return subclassToPeople;
}

View file

@ -32,7 +32,7 @@ public class ManagePublicationsForIndividualController extends FreemarkerHttpSer
private static final Log log = LogFactory.getLog(ManagePublicationsForIndividualController.class.getName());
private static final String TEMPLATE_NAME = "managePublicationsForIndividual.ftl";
@Override
protected AuthorizationRequest requiredActions(VitroRequest vreq) {
return SimplePermission.DO_FRONT_END_EDITING.ACTION;
@ -54,17 +54,17 @@ public class ManagePublicationsForIndividualController extends FreemarkerHttpSer
List<String> allSubclasses = getAllSubclasses(publications);
body.put("allSubclasses", allSubclasses);
Individual subject = vreq.getWebappDaoFactory().getIndividualDao().getIndividualByURI(subjectUri);
if( subject != null && subject.getName() != null ){
body.put("subjectName", subject.getName());
}else{
body.put("subjectName", null);
}
return new TemplateResponseValues(TEMPLATE_NAME, body);
}
private static String PUBLICATION_QUERY = ""
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n"
@ -85,10 +85,10 @@ public class ManagePublicationsForIndividualController extends FreemarkerHttpSer
+ " ?pub a <http://purl.org/ontology/bibo/Document> . \n"
+ " ?pub vitro:mostSpecificType ?subclass . \n"
+ " } \n"
+ " } \n"
+ " } \n"
+ " OPTIONAL { ?authorship core:hideFromDisplay ?hideThis } \n"
+ "} ORDER BY ?subclass ?title";
HashMap<String, List<Map<String,String>>> getPublications(String subjectUri, VitroRequest vreq) {
VClassDao vcDao = vreq.getUnfilteredAssertionsWebappDaoFactory().getVClassDao();
@ -118,8 +118,8 @@ public class ManagePublicationsForIndividualController extends FreemarkerHttpSer
}
} catch (Exception e) {
log.error(e, e);
}
}
return subclassToPublications;
}

View file

@ -1,6 +1,6 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.controller.harvester;
package edu.cornell.mannlib.vitro.webapp.controller.harvester;
import java.io.BufferedReader;
import java.io.File;
@ -69,7 +69,7 @@ class CsvFileHarvestJob implements FileHarvestJob {
}
return returnValue;
}
private JobType(String httpParameterName, String templateFileName, String scriptFileName, String xsltFileName, String friendlyName, String linkHeader, String noNewDataMessage, String[] rdfTypesForLinks) {
this.httpParameterName = httpParameterName;
this.templateFileName = templateFileName;
@ -80,13 +80,13 @@ class CsvFileHarvestJob implements FileHarvestJob {
this.noNewDataMessage = noNewDataMessage;
this.rdfTypesForLinks = Arrays.copyOf(rdfTypesForLinks, rdfTypesForLinks.length);
}
private CsvFileHarvestJob constructCsvFileHarvestJob(VitroRequest vreq, String namespace) {
return new CsvFileHarvestJob(vreq, this.templateFileName, this.scriptFileName, this.xsltFileName, namespace, this.friendlyName, this.linkHeader, this.noNewDataMessage, this.rdfTypesForLinks);
}
}
/**
* Logger.
*/
@ -139,17 +139,17 @@ class CsvFileHarvestJob implements FileHarvestJob {
* An array of rdf:type values which will be used for links.
*/
private final String[] rdfTypesForLinks;
/**
* The session ID of this user session.
*/
private final String sessionId;
public static CsvFileHarvestJob createJob(JobType jobType, VitroRequest vreq, String namespace) {
return jobType.constructCsvFileHarvestJob(vreq, namespace);
}
/**
* Constructor.
* @param templateFileName just the name of the template file. The directory is assumed to be standard.
@ -164,7 +164,7 @@ class CsvFileHarvestJob implements FileHarvestJob {
this.linkHeader = linkHeader;
this.noNewDataMessage = noNewDataMessage;
this.rdfTypesForLinks = Arrays.copyOf(rdfTypesForLinks, rdfTypesForLinks.length);
this.sessionId = this.vreq.getSession().getId();
}
@ -189,27 +189,27 @@ class CsvFileHarvestJob implements FileHarvestJob {
}
private boolean[] getLinesEndingInComma(File file) throws IOException {
ArrayList<Boolean> linesEndingInCommaList = new ArrayList<Boolean>();
BufferedReader reader = new BufferedReader(new FileReader(file));
for(String line = reader.readLine(); line != null; line = reader.readLine()) {
boolean lineEndsInComma = line.endsWith(",");
linesEndingInCommaList.add(lineEndsInComma);
}
reader.close();
boolean[] linesEndingInComma = new boolean[linesEndingInCommaList.size()];
for(int i = 0; i < linesEndingInComma.length; i++) {
linesEndingInComma[i] = linesEndingInCommaList.get(i);
}
return linesEndingInComma;
}
@Override
@SuppressWarnings("rawtypes")
public String validateUpload(File file) {
@ -256,31 +256,31 @@ class CsvFileHarvestJob implements FileHarvestJob {
}
}
/*
/*
private void prepareWorkspaceDirectory() {
String path = FileHarvestController.getFileHarvestRootPath() + "workspaces/" + this.sessionId;
File directory = new File(path);
if(!directory.exists())
directory.mkdirs();
File scriptTemplate = this.scriptFile;
String scriptTemplateContents = readFromFile(scriptTemplate);
String scriptTemplateReplacements = performScriptTemplateReplacements(scriptTemplateContents);
File outputScriptFile = new File(path + "/" + scriptTemplate.getName());
writeToFile(outputScriptFile, scriptTemplateReplacements);
File xsltTemplate = this.xsltFile;
String xsltTemplateContents = readFromFile(xsltTemplate);
String xsltTemplateReplacements = performXsltTemplateReplacements(xsltTemplateContents);
File outputXsltFile = new File(path + "/" + xsltTemplate.getName());
writeToFile(outputXsltFile, xsltTemplateReplacements);
}
*/
*/
@Override
public String getScript()
{
@ -302,7 +302,7 @@ class CsvFileHarvestJob implements FileHarvestJob {
if(harvestedDataPath.endsWith("/"))
harvestedDataPath = harvestedDataPath.substring(0, harvestedDataPath.length() - 1);
replacements = replacements.replace("${WORKING_DIRECTORY}", workingDirectory);
replacements = replacements.replace("${UPLOADS_FOLDER}", fileDirectory);
replacements = replacements.replace("${HARVESTED_DATA_PATH}", harvestedDataPath);
@ -314,13 +314,13 @@ class CsvFileHarvestJob implements FileHarvestJob {
/*
private String performXsltTemplateReplacements(String xsltTemplateContents) {
String replacements = xsltTemplateContents;
replacements = replacements.replace("", "");
return replacements;
}
private void writeToFile(File file, String contents) {
PrintWriter writer = null;
try {
@ -333,7 +333,7 @@ class CsvFileHarvestJob implements FileHarvestJob {
writer.close();
}
}
*/
*/
private String readFromFile(File file) {
String contents = null;
@ -407,7 +407,7 @@ class CsvFileHarvestJob implements FileHarvestJob {
public String getNoNewDataMessage() {
return this.noNewDataMessage;
}
}

View file

@ -54,7 +54,7 @@ public class FileHarvestController extends FreemarkerHttpServlet {
private static final String TEMPLATE_DEFAULT = "fileharvest.ftl";
private static final String NORMAL_TERMINATION_LAST_OUTPUT = "File Harvest completed successfully";
private static final String PARAMETER_FIRST_UPLOAD = "firstUpload";
private static final String PARAMETER_UPLOADED_FILE = "uploadedFile";
private static final String PARAMETER_MODE = "mode";
@ -191,7 +191,7 @@ public class FileHarvestController extends FreemarkerHttpServlet {
*/
public static String getHarvesterPath(HttpServletRequest req)
{
String pathToHarvester = ConfigurationProperties.getBean(req).getProperty("harvester.location");
String pathToHarvester = ConfigurationProperties.getBean(req).getProperty("harvester.location");
if (pathToHarvester == null) {
log.error("The runtime.properties file does not contain a value for 'harvester.location'");
return "";
@ -217,7 +217,7 @@ public class FileHarvestController extends FreemarkerHttpServlet {
*/
private static String getUploadPathBase(ServletContext context) throws Exception
{
String vitroHomeDirectoryName = ApplicationUtils.instance().getHomeDirectory().getPath().toString();
String vitroHomeDirectoryName = ApplicationUtils.instance().getHomeDirectory().getPath().toString();
return vitroHomeDirectoryName + "/" + FileStorageImplWrapper.FILE_STORAGE_SUBDIRECTORY + "/" + PATH_TO_UPLOADS;
}
@ -419,7 +419,7 @@ public class FileHarvestController extends FreemarkerHttpServlet {
json = generateJson(true);
log.error(e, e);
}
try {
response.getWriter().write(json.toString());
} catch(IOException e) {
@ -477,8 +477,8 @@ public class FileHarvestController extends FreemarkerHttpServlet {
//remove all entries in "sessionIdTo..." mappings for this session ID
clearSessionInfo(sessionId);
if(sessionInfo.getAbnormalTermination())
if(sessionInfo.getAbnormalTermination())
abnormalTermination = true;
}
@ -500,7 +500,7 @@ public class FileHarvestController extends FreemarkerHttpServlet {
json = generateJson(true);
log.error(e, e);
}
try {
response.getWriter().write(json.toString());
} catch(IOException e) {
@ -543,9 +543,9 @@ public class FileHarvestController extends FreemarkerHttpServlet {
private static String getScriptFileLocation(HttpServletRequest req) {
return getHarvesterPath(req) + PATH_TO_HARVESTER_SCRIPTS + "temp/";
}
private File createScriptFile(String scriptFileLocation, String script) throws IOException {
File scriptDirectory = new File(scriptFileLocation);
if(!scriptDirectory.exists()) {
@ -631,7 +631,7 @@ public class FileHarvestController extends FreemarkerHttpServlet {
Node node = descriptionNodes.item(i);
ArrayList<String> types = getRdfTypes(node);
boolean match = false;
String[] validRdfTypesForJob = job.getRdfTypesForLinks();
for(String rdfType : validRdfTypesForJob) {
@ -640,7 +640,7 @@ public class FileHarvestController extends FreemarkerHttpServlet {
break;
}
}
if(match) {
NamedNodeMap attributes = node.getAttributes();
@ -795,7 +795,7 @@ public class FileHarvestController extends FreemarkerHttpServlet {
public boolean getAbnormalTermination() {
return abnormalTermination;
}
public void finish() {
finished = true;
}
@ -833,7 +833,7 @@ public class FileHarvestController extends FreemarkerHttpServlet {
this.sessionId = sessionId;
this.script = script;
this.additionsFilePath = additionsFilePath;
this.scriptFileLocation = scriptFileLocation;
this.scriptFileLocation = scriptFileLocation;
this.job = job;
}
@ -863,7 +863,7 @@ public class FileHarvestController extends FreemarkerHttpServlet {
for(String line = processOutputReader.readLine(); line != null; line = processOutputReader.readLine()) {
normalTerminationLineFound = line.endsWith(NORMAL_TERMINATION_LAST_OUTPUT); //set every read to ensure it's the last line
//don't add stuff to this list if the main thread is running a "transaction" of copying out the data to send to client and then clearing the list
synchronized(unsentLogLines) {
unsentLogLines.add(line);

View file

@ -1,12 +1,12 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.controller.harvester;
package edu.cornell.mannlib.vitro.webapp.controller.harvester;
import java.io.File;
/**
* Handles specifics of a file harvest.
* Handles specifics of a file harvest.
* @author mbarbieri
*
*/
@ -26,7 +26,7 @@ interface FileHarvestJob {
String getTemplateFilePath();
/**
* Gets the console script which can be used to run the harvest job.
* Gets the console script which can be used to run the harvest job.
* @return the console script which can be used to run the harvest job
*/
String getScript();
@ -44,30 +44,30 @@ interface FileHarvestJob {
String getPageHeader();
/**
* A heading to be shown above the area where links to profiles of newly-harvested entities are listed.
* A heading to be shown above the area where links to profiles of newly-harvested entities are listed.
* @return a heading to be shown above the area where links to profiles of newly-harvested entities are listed
*/
String getLinkHeader();
/**
* Get an array of fully-qualified rdf:type values. When the harvest run is complete, any new entities which have an rdf:type represented
* in this array will have a link displayed on the page allowing the user to visit the new profile.
* in this array will have a link displayed on the page allowing the user to visit the new profile.
* @return an array of types to be used in links
*/
String[] getRdfTypesForLinks();
/**
* Get the HTML to be shown on the page immediately next to the "Download" button for the template.
* @return the HTML to be shown on the page immediately next to the "Download" button for the template.
*/
String getTemplateDownloadHelp();
/**
* Get the HTML to be shown in the collapsible "Help" area in the "Fill in data" section of the page.
* @return the HTML to be shown in the collapsible "Help" area in the "Fill in data" section of the page.
*/
String getTemplateFillInHelp();
/**
* Get the message to show to the user if there are no newly-harvested entities to show them.
* @return the message to show to the user if there are no newly-harvested entities to show them

View file

@ -1,6 +1,6 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.controller.harvester;
package edu.cornell.mannlib.vitro.webapp.controller.harvester;
import java.util.ArrayList;
import java.util.Collections;
@ -47,7 +47,7 @@ import org.vivoweb.harvester.util.XPathTool;
* but that was troublesome for a few reasons, the most important being related to the simple fact that the
* Harvester was designed to be used as a collection of command-line tools, and thus we have, for example, the
* versatility of Score which would be very difficult to replicate without essentially allowing the user to
* pass in a string to be parsed, which would defeat the purpose.
* pass in a string to be parsed, which would defeat the purpose.
*
* @author mbarbieri
*
@ -81,7 +81,7 @@ class Harvester {
public static void runPubmedHTTPFetch(Object ... args) {
PubmedHTTPFetch.main(stringsToArray(args));
}
// qualify
public static void runChangeNamespace(Object ... args) {
ChangeNamespace.main(stringsToArray(args));
@ -101,7 +101,7 @@ class Harvester {
public static void runSplitProperty(Object ... args) {
SplitProperty.main(stringsToArray(args));
}
// score
public static void runMatch(Object ... args) {
Match.main(stringsToArray(args));
@ -112,12 +112,12 @@ class Harvester {
public static void runScore(Object ... args) {
Score.main(stringsToArray(args));
}
// transfer
public static void runTransfer(Object ... args) {
Transfer.main(stringsToArray(args));
}
// translate
public static void runGlozeTranslator(Object ... args) {
GlozeTranslator.main(stringsToArray(args));
@ -153,21 +153,21 @@ class Harvester {
/**
* Convenience method to expand the ability to use Java's "..." arg list. Harvester scripts frequently declare sub-macros,
* so for example you might have:
*
*
* SCOREINPUT="-i $H2MODEL -ImodelName=$MODELNAME -IdbUrl=$MODELDBURL -IcheckEmpty=$CHECKEMPTY"
* SCOREDATA="-s $H2MODEL -SmodelName=$SCOREDATANAME -SdbUrl=$SCOREDATADBURL -ScheckEmpty=$CHECKEMPTY"
* SCOREMODELS="$SCOREINPUT -v $VIVOCONFIG -VcheckEmpty=$CHECKEMPTY $SCOREDATA -t $TEMPCOPYDIR -b $SCOREBATCHSIZE"
* $Score $SCOREMODELS -AGrantNumber=$EQTEST -WGrantNumber=1.0 -FGrantNumber=$GRANTIDNUM -PGrantNumber=$GRANTIDNUM -n ${BASEURI}grant/
*
*
* In order to mimic this functionality for easy use in Java, this method has been created. It takes a "..." arg list of Object
* objects, and returns an array of Strings. For each object, if it's an array of Strings, each String is added to the output
* array. Otherwise, its toString() method is called and that value is added to the output array.
*
* It is intended to be used with a combination of String and String[] values, in any arbitrary order.
*
*
* It is intended to be used with a combination of String and String[] values, in any arbitrary order.
*
* All static Harvester methods in this class take an Object arg list rather than a String arg list, and automatically call
* this method.
*
*
* @param args an array of objects, which ought to be a combination of String and String[] values, in any arbitrary order
* @return all the strings put together as one array
*/

View file

@ -40,73 +40,73 @@ public class AjaxVisualizationController extends FreemarkerHttpServlet {
public static final String URL_ENCODING_SCHEME = "UTF-8";
private static final Log log = LogFactory.getLog(AjaxVisualizationController.class.getName());
protected static final Syntax SYNTAX = Syntax.syntaxARQ;
public static ServletContext servletContext;
@Override
protected AuthorizationRequest requiredActions(VitroRequest vreq) {
/*
* Based on the query parameters passed via URI get the appropriate visualization
* Based on the query parameters passed via URI get the appropriate visualization
* request handler.
* */
VisualizationRequestHandler visRequestHandler =
VisualizationRequestHandler visRequestHandler =
getVisualizationRequestHandler(vreq);
if (visRequestHandler != null) {
AuthorizationRequest requiredPrivileges = visRequestHandler.getRequiredPrivileges();
if (requiredPrivileges != null) {
return requiredPrivileges;
}
}
return super.requiredActions(vreq);
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
VitroRequest vreq = new VitroRequest(request);
Object ajaxResponse = processAjaxRequest(vreq);
if (ajaxResponse instanceof TemplateResponseValues) {
TemplateResponseValues trv = (TemplateResponseValues) ajaxResponse;
try {
writeTemplate(trv.getTemplateName(), trv.getMap(), vreq, response);
} catch (TemplateProcessingException e) {
log.error(e.getMessage(), e);
}
} else {
response.getWriter().write(ajaxResponse.toString());
}
}
private Object processAjaxRequest(VitroRequest vreq) {
/*
* Based on the query parameters passed via URI get the appropriate visualization
* Based on the query parameters passed via URI get the appropriate visualization
* request handler.
* */
VisualizationRequestHandler visRequestHandler =
VisualizationRequestHandler visRequestHandler =
getVisualizationRequestHandler(vreq);
if (visRequestHandler != null) {
/*
* Pass the query to the selected visualization request handler & render the
* visualization. Since the visualization content is directly added to the response
* Pass the query to the selected visualization request handler & render the
* visualization. Since the visualization content is directly added to the response
* object we are side-effecting this method.
* */
return renderVisualization(vreq, visRequestHandler);
} else {
return UtilityFunctions.handleMalformedParameters(
"Visualization Query Error",
"Inappropriate query parameters were submitted.",
@ -117,70 +117,70 @@ public class AjaxVisualizationController extends FreemarkerHttpServlet {
private Object renderVisualization(VitroRequest vitroRequest,
VisualizationRequestHandler visRequestHandler) {
Model model = vitroRequest.getJenaOntModel(); // getModel()
if (model == null) {
String errorMessage = "This service is not supporeted by the current "
+ "webapp configuration. A jena model is required in the "
String errorMessage = "This service is not supporeted by the current "
+ "webapp configuration. A jena model is required in the "
+ "servlet context.";
log.error(errorMessage);
return UtilityFunctions.handleMalformedParameters("Visualization Query Error",
errorMessage,
return UtilityFunctions.handleMalformedParameters("Visualization Query Error",
errorMessage,
vitroRequest);
}
Dataset dataset = setupJENADataSource(vitroRequest);
if (dataset != null && visRequestHandler != null) {
try {
return visRequestHandler.generateAjaxVisualization(vitroRequest,
log,
return visRequestHandler.generateAjaxVisualization(vitroRequest,
log,
dataset);
} catch (JsonProcessingException|MalformedQueryParametersException e) {
return UtilityFunctions.handleMalformedParameters(
"Ajax Visualization Query Error - Individual Publication Count",
e.getMessage(),
"Ajax Visualization Query Error - Individual Publication Count",
e.getMessage(),
vitroRequest);
}
} else {
String errorMessage = "Data Model Empty &/or Inappropriate "
String errorMessage = "Data Model Empty &/or Inappropriate "
+ "query parameters were submitted. ";
log.error(errorMessage);
return UtilityFunctions.handleMalformedParameters("Visualization Query Error",
errorMessage,
return UtilityFunctions.handleMalformedParameters("Visualization Query Error",
errorMessage,
vitroRequest);
}
}
private VisualizationRequestHandler getVisualizationRequestHandler(
VitroRequest vitroRequest) {
String visType = vitroRequest.getParameter(VisualizationFrameworkConstants
.VIS_TYPE_KEY);
VisualizationRequestHandler visRequestHandler = null;
try {
visRequestHandler = VisualizationsDependencyInjector
.getVisualizationIDsToClassMap(
getServletContext()).get(visType);
} catch (NullPointerException nullKeyException) {
return null;
}
return visRequestHandler;
}

View file

@ -38,55 +38,55 @@ public class DataVisualizationController extends VitroHttpServlet {
public static final String URL_ENCODING_SCHEME = "UTF-8";
private static final Log log = LogFactory.getLog(DataVisualizationController.class.getName());
protected static final Syntax SYNTAX = Syntax.syntaxARQ;
public static final String FILE_CONTENT_TYPE_KEY = "fileContentType";
public static final String FILE_CONTENT_KEY = "fileContent";
public static final String FILE_NAME_KEY = "fileName";
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
VitroRequest vreq = new VitroRequest(request);
/*
* Based on the query parameters passed via URI get the appropriate visualization
* Based on the query parameters passed via URI get the appropriate visualization
* request handler.
* */
VisualizationRequestHandler visRequestHandler =
VisualizationRequestHandler visRequestHandler =
getVisualizationRequestHandler(vreq);
if (visRequestHandler != null) {
if (visRequestHandler.getRequiredPrivileges() != null) {
if (!isAuthorizedToDisplayPage(request, response, visRequestHandler.getRequiredPrivileges())) {
return;
}
}
/*
* Pass the query to the selected visualization request handler & render the vis.
* Since the visualization content is directly added to the response object we are side-
* effecting this method.
* */
try {
Map<String, String> dataResponse = renderVisualization(vreq, visRequestHandler);
response.setContentType(dataResponse.get(FILE_CONTENT_TYPE_KEY));
if (dataResponse.containsKey(FILE_NAME_KEY)) {
response.setHeader("Content-Disposition",
response.setHeader("Content-Disposition",
"attachment;filename=" + dataResponse.get(FILE_NAME_KEY));
}
response.getWriter().write(dataResponse.get(FILE_CONTENT_KEY));
return;
} catch (MalformedQueryParametersException e) {
UtilityFunctions.handleMalformedParameters(e.getMessage(),
@ -95,37 +95,37 @@ public class DataVisualizationController extends VitroHttpServlet {
}
} else {
UtilityFunctions.handleMalformedParameters(
"Inappropriate query parameters were submitted.",
response,
log);
}
}
private Map<String, String> renderVisualization(
VitroRequest vitroRequest,
VisualizationRequestHandler visRequestHandler)
VisualizationRequestHandler visRequestHandler)
throws MalformedQueryParametersException {
Model model = vitroRequest.getJenaOntModel(); // getModel()
if (model == null) {
String errorMessage = "This service is not supporeted by the current "
+ "webapp configuration. A jena model is required in the "
String errorMessage = "This service is not supporeted by the current "
+ "webapp configuration. A jena model is required in the "
+ "servlet context.";
log.error(errorMessage);
throw new MalformedQueryParametersException(errorMessage);
}
Dataset dataset = setupJENADataSource(vitroRequest);
if (dataset != null && visRequestHandler != null) {
try {
return visRequestHandler.generateDataVisualization(vitroRequest,
@ -134,7 +134,7 @@ public class DataVisualizationController extends VitroHttpServlet {
} catch (JsonProcessingException e) {
}
}
String errorMessage = "Data Model Empty &/or Inappropriate "
+ "query parameters were submitted. ";
@ -143,21 +143,21 @@ public class DataVisualizationController extends VitroHttpServlet {
private VisualizationRequestHandler getVisualizationRequestHandler(
VitroRequest vitroRequest) {
String visType = vitroRequest.getParameter(VisualizationFrameworkConstants
.VIS_TYPE_KEY);
VisualizationRequestHandler visRequestHandler = null;
try {
visRequestHandler = VisualizationsDependencyInjector
.getVisualizationIDsToClassMap(getServletContext())
.get(visType);
} catch (NullPointerException nullKeyException) {
return null;
}
return visRequestHandler;
}

View file

@ -29,7 +29,7 @@ import edu.cornell.mannlib.vitro.webapp.visualization.visutils.UtilityFunctions;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.VisualizationRequestHandler;
/**
* Services a standard visualization request, which involves templates. This will return a simple
* Services a standard visualization request, which involves templates. This will return a simple
* error message and a 501 if there is no jena Model.
*
* @author cdtank
@ -41,22 +41,22 @@ public class ShortURLVisualizationController extends FreemarkerHttpServlet {
public static final String URL_ENCODING_SCHEME = "UTF-8";
private static final Log log = LogFactory.getLog(ShortURLVisualizationController.class.getName());
protected static final Syntax SYNTAX = Syntax.syntaxARQ;
public static ServletContext servletContext;
@Override
protected AuthorizationRequest requiredActions(VitroRequest vreq) {
/*
* Based on the query parameters passed via URI get the appropriate visualization
* Based on the query parameters passed via URI get the appropriate visualization
* request handler.
* */
VisualizationRequestHandler visRequestHandler =
VisualizationRequestHandler visRequestHandler =
getVisualizationRequestHandler(vreq);
if (visRequestHandler != null) {
AuthorizationRequest requiredPrivileges = visRequestHandler.getRequiredPrivileges();
if (requiredPrivileges != null) {
return requiredPrivileges;
@ -64,161 +64,161 @@ public class ShortURLVisualizationController extends FreemarkerHttpServlet {
}
return super.requiredActions(vreq);
}
@Override
protected ResponseValues processRequest(VitroRequest vreq) {
/*
* Based on the query parameters passed via URI get the appropriate visualization
* Based on the query parameters passed via URI get the appropriate visualization
* request handler.
* */
VisualizationRequestHandler visRequestHandler =
VisualizationRequestHandler visRequestHandler =
getVisualizationRequestHandler(vreq);
servletContext = getServletContext();
if (visRequestHandler != null) {
/*
* Pass the query to the selected visualization request handler & render the vis.
* Since the visualization content is directly added to the response object we are side-
* effecting this method.
* */
return renderVisualization(vreq, visRequestHandler);
} else {
return UtilityFunctions.handleMalformedParameters(
"Visualization Query Error",
"Inappropriate query parameters were submitted.",
"Visualization Query Error",
"Inappropriate query parameters were submitted.",
vreq);
}
}
private ResponseValues renderVisualization(VitroRequest vitroRequest,
VisualizationRequestHandler visRequestHandler) {
Model model = vitroRequest.getJenaOntModel(); // getModel()
if (model == null) {
String errorMessage = "This service is not supporeted by the current "
+ "webapp configuration. A jena model is required in the "
String errorMessage = "This service is not supporeted by the current "
+ "webapp configuration. A jena model is required in the "
+ "servlet context.";
log.error(errorMessage);
return UtilityFunctions.handleMalformedParameters("Visualization Query Error",
errorMessage,
return UtilityFunctions.handleMalformedParameters("Visualization Query Error",
errorMessage,
vitroRequest);
}
Dataset dataset = setupJENADataSource(vitroRequest);
if (dataset != null && visRequestHandler != null) {
try {
List<String> matchedPatternGroups = extractShortURLParameters(vitroRequest);
Map<String, String> parametersForVis = getParamatersForVis(matchedPatternGroups, vitroRequest);
return visRequestHandler.generateVisualizationForShortURLRequests(
parametersForVis,
vitroRequest,
log,
dataset);
} catch (MalformedQueryParametersException e) {
return UtilityFunctions.handleMalformedParameters(
"Standard Visualization Query Error - Individual Publication Count",
e.getMessage(),
"Standard Visualization Query Error - Individual Publication Count",
e.getMessage(),
vitroRequest);
}
} else {
String errorMessage = "Data Model Empty &/or Inappropriate "
String errorMessage = "Data Model Empty &/or Inappropriate "
+ "query parameters were submitted. ";
log.error(errorMessage);
return UtilityFunctions.handleMalformedParameters("Visualization Query Error",
errorMessage,
return UtilityFunctions.handleMalformedParameters("Visualization Query Error",
errorMessage,
vitroRequest);
}
}
private Map<String, String> getParamatersForVis(List<String> matchedPatternGroups,
private Map<String, String> getParamatersForVis(List<String> matchedPatternGroups,
VitroRequest vitroRequest) {
Map<String, String> parameters = new HashMap<String, String>();
/*
* We need to convert the short-form URI into a long form. So we use the
* default namespace to construct one.
* Since VIVO allows non-default namespaces, there are chances that short URLs
* We need to convert the short-form URI into a long form. So we use the
* default namespace to construct one.
* Since VIVO allows non-default namespaces, there are chances that short URLs
* will have a "uri" parameter instead of individual uri being part of the formal
* url.
* */
String subjectURI = null;
if (matchedPatternGroups.size() <= 1) {
subjectURI = vitroRequest.getParameter(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY);
} else {
subjectURI = vitroRequest.getWebappDaoFactory().getDefaultNamespace()
subjectURI = vitroRequest.getWebappDaoFactory().getDefaultNamespace()
+ matchedPatternGroups.get(1);
}
subjectURI = StringEscapeUtils.ESCAPE_HTML4.translate(subjectURI);
parameters.put(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, subjectURI);
if (VisualizationFrameworkConstants.COAUTHORSHIP_VIS_SHORT_URL
.equalsIgnoreCase(matchedPatternGroups.get(0))) {
parameters.put(VisualizationFrameworkConstants.VIS_MODE_KEY,
parameters.put(VisualizationFrameworkConstants.VIS_MODE_KEY,
VisualizationFrameworkConstants.COAUTHOR_VIS_MODE);
} else if (VisualizationFrameworkConstants.COINVESTIGATOR_VIS_SHORT_URL
.equalsIgnoreCase(matchedPatternGroups.get(0))) {
parameters.put(VisualizationFrameworkConstants.VIS_MODE_KEY,
parameters.put(VisualizationFrameworkConstants.VIS_MODE_KEY,
VisualizationFrameworkConstants.COPI_VIS_MODE);
} else {
/*
* Currently temporal vis for both grants & publications do not require use of
* vis_modes in their request handlers, so no need to provide anything other than
* Currently temporal vis for both grants & publications do not require use of
* vis_modes in their request handlers, so no need to provide anything other than
* the URI.
* */
}
return parameters;
}
private VisualizationRequestHandler getVisualizationRequestHandler(
VitroRequest vitroRequest) {
String visType = null;
VisualizationRequestHandler visRequestHandler = null;
List<String> matchedPatternGroups = extractShortURLParameters(vitroRequest);
if (matchedPatternGroups.size() > 0) {
// System.out.println(matchedPatternGroups.get(0) + " --> " + matchedPatternGroups.get(1));
//
// System.out.println(vitroRequest.getRequestURI()
//
// System.out.println(vitroRequest.getRequestURI()
// + " -- " + vitroRequest.getContextPath()
// + " -- " + vitroRequest.getContextPath().length()
// + " -- " + vitroRequest.getRequestURI().substring(vitroRequest.getContextPath().length()));
visType = matchedPatternGroups.get(0);
try {
visRequestHandler = VisualizationsDependencyInjector
.getVisualizationIDsToClassMap(getServletContext())
@ -228,9 +228,9 @@ public class ShortURLVisualizationController extends FreemarkerHttpServlet {
* Let the default flow take care of returning a null.
* */
}
}
return visRequestHandler;
}
@ -244,15 +244,15 @@ public class ShortURLVisualizationController extends FreemarkerHttpServlet {
*/
private List<String> extractShortURLParameters(VitroRequest vitroRequest) {
List<String> matchedGroups = new ArrayList<String>();
List<String> matchedGroups = new ArrayList<String>();
String subURIString = vitroRequest.getRequestURI().substring(vitroRequest.getContextPath().length()+1);
String[] urlParams = StringEscapeUtils.ESCAPE_HTML4.translate(subURIString).split("/");
if (urlParams.length > 1
if (urlParams.length > 1
&& urlParams[0].equalsIgnoreCase("vis")) {
matchedGroups.addAll(Arrays.asList(urlParams).subList(1, urlParams.length));
}
return matchedGroups;
}

View file

@ -22,7 +22,7 @@ import edu.cornell.mannlib.vitro.webapp.visualization.visutils.UtilityFunctions;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.VisualizationRequestHandler;
/**
* Services a standard visualization request, which involves templates. This will return a simple
* Services a standard visualization request, which involves templates. This will return a simple
* error message and a 501 if there is no jena Model.
*
* @author cdtank
@ -34,22 +34,22 @@ public class StandardVisualizationController extends FreemarkerHttpServlet {
public static final String URL_ENCODING_SCHEME = "UTF-8";
private static final Log log = LogFactory.getLog(StandardVisualizationController.class.getName());
protected static final Syntax SYNTAX = Syntax.syntaxARQ;
public static ServletContext servletContext;
@Override
protected AuthorizationRequest requiredActions(VitroRequest vreq) {
/*
* Based on the query parameters passed via URI get the appropriate visualization
* Based on the query parameters passed via URI get the appropriate visualization
* request handler.
* */
VisualizationRequestHandler visRequestHandler =
VisualizationRequestHandler visRequestHandler =
getVisualizationRequestHandler(vreq);
if (visRequestHandler != null) {
AuthorizationRequest requiredPrivileges = visRequestHandler.getRequiredPrivileges();
if (requiredPrivileges != null) {
return requiredPrivileges;
@ -57,93 +57,93 @@ public class StandardVisualizationController extends FreemarkerHttpServlet {
}
return super.requiredActions(vreq);
}
@Override
protected ResponseValues processRequest(VitroRequest vreq) {
/*
* Based on the query parameters passed via URI get the appropriate visualization
* Based on the query parameters passed via URI get the appropriate visualization
* request handler.
* */
VisualizationRequestHandler visRequestHandler =
VisualizationRequestHandler visRequestHandler =
getVisualizationRequestHandler(vreq);
servletContext = getServletContext();
if (visRequestHandler != null) {
/*
* Pass the query to the selected visualization request handler & render the vis.
* Since the visualization content is directly added to the response object we are side-
* effecting this method.
* */
return renderVisualization(vreq, visRequestHandler);
} else {
return UtilityFunctions.handleMalformedParameters(
"Visualization Query Error",
"Inappropriate query parameters were submitted.",
"Visualization Query Error",
"Inappropriate query parameters were submitted.",
vreq);
}
}
private ResponseValues renderVisualization(VitroRequest vitroRequest,
VisualizationRequestHandler visRequestHandler) {
Model model = vitroRequest.getJenaOntModel(); // getModel()
if (model == null) {
String errorMessage = "This service is not supporeted by the current "
+ "webapp configuration. A jena model is required in the "
String errorMessage = "This service is not supporeted by the current "
+ "webapp configuration. A jena model is required in the "
+ "servlet context.";
log.error(errorMessage);
return UtilityFunctions.handleMalformedParameters("Visualization Query Error",
errorMessage,
return UtilityFunctions.handleMalformedParameters("Visualization Query Error",
errorMessage,
vitroRequest);
}
Dataset dataset = setupJENADataSource(vitroRequest);
if (dataset != null && visRequestHandler != null) {
try {
return visRequestHandler.generateStandardVisualization(vitroRequest,
log,
return visRequestHandler.generateStandardVisualization(vitroRequest,
log,
dataset);
} catch (MalformedQueryParametersException e) {
return UtilityFunctions.handleMalformedParameters(
"Standard Visualization Query Error - Individual Publication Count",
e.getMessage(),
"Standard Visualization Query Error - Individual Publication Count",
e.getMessage(),
vitroRequest);
}
} else {
String errorMessage = "Data Model Empty &/or Inappropriate "
String errorMessage = "Data Model Empty &/or Inappropriate "
+ "query parameters were submitted. ";
log.error(errorMessage);
return UtilityFunctions.handleMalformedParameters("Visualization Query Error",
errorMessage,
return UtilityFunctions.handleMalformedParameters("Visualization Query Error",
errorMessage,
vitroRequest);
}
}
private VisualizationRequestHandler getVisualizationRequestHandler(
VitroRequest vitroRequest) {
String visType = vitroRequest.getParameter(VisualizationFrameworkConstants
.VIS_TYPE_KEY);
VisualizationRequestHandler visRequestHandler = null;
try {
visRequestHandler = VisualizationsDependencyInjector
.getVisualizationIDsToClassMap(getServletContext())
@ -152,7 +152,7 @@ public class StandardVisualizationController extends FreemarkerHttpServlet {
return null;
}
return visRequestHandler;
}

View file

@ -1,141 +1,141 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.controller.visualization;
import java.util.regex.Pattern;
public class VisualizationFrameworkConstants {
/*
* Contains the location of bean containing info on all the visualizations
* available in that instance. Currently it is stored under
* "productMods/WEB-INF..."
*/
public static final String RELATIVE_LOCATION_OF_VISUALIZATIONS_BEAN =
"/WEB-INF/visualization/visualizations-beans-injection.xml";
/*
* Freemarker Version
* */
public static final String RELATIVE_LOCATION_OF_FM_VISUALIZATIONS_BEAN =
"/WEB-INF/visualization/visualizations-beans-injection-fm.xml";
public static final String ERROR_TEMPLATE = "/visualization/visualizationError.ftl";
/*
* Vis URL prefix that is seen by all the users
*/
public static final String VISUALIZATION_URL_PREFIX = "/visualization";
public static final String SHORT_URL_VISUALIZATION_REQUEST_PREFIX = "/vis";
public static final String FREEMARKERIZED_VISUALIZATION_URL_PREFIX = "/visualization";
public static final String AJAX_VISUALIZATION_SERVICE_URL_PREFIX = "/visualizationAjax";
public static final String DATA_VISUALIZATION_SERVICE_URL_PREFIX = "/visualizationData";
public static final String INDIVIDUAL_URL_PREFIX = "/individual";
public static final Pattern SHORT_URL_REQUEST_PATTERN = Pattern
.compile("^"
+ SHORT_URL_VISUALIZATION_REQUEST_PREFIX
+ "/([\\w-]+)/([^/]*)$");
/*
* These represent possible query keys in a URI for visualization purposes.
* Examples,
* 1. http://vivo.indiana.edu/visualization?uri=http://vivoweb.org/ontology/core/Person10979&vis=person_level&render_mode=standalone
* 2. http://vivo.indiana.edu/visualization?uri=http://vivoweb.org/ontology/core/Person72&vis=person_pub_count&render_mode=dynamic&container=vis_container
* */
public static final String VIS_TYPE_KEY = "vis";
public static final String VIS_CONTAINER_KEY = "container";
public static final String INDIVIDUAL_URI_KEY = "uri";
public static final String VIS_MODE_KEY = "vis_mode";
public static final String RENDER_MODE_KEY = "render_mode";
public static final String OUTPUT_FORMAT_KEY = "output";
public static final String REQUESTING_TEMPLATE_KEY = "template"; /* tlw72 - added in 1.6 for multi-view support */
/*
* These values represent possible render modes.
* */
public static final String STANDALONE_RENDER_MODE = "standalone";
public static final String DYNAMIC_RENDER_MODE = "dynamic";
public static final String DATA_RENDER_MODE = "data";
public static final String PDF_RENDER_MODE = "pdf";
/*
* These values represent possible sub-vis modes.
* */
public static final String IMAGE_VIS_MODE = "image";
public static final String SHORT_SPARKLINE_VIS_MODE = "short";
public static final String FULL_SPARKLINE_VIS_MODE = "full";
public static final String COPI_VIS_MODE = "copi";
public static final String COAUTHOR_VIS_MODE = "coauthor";
/*
* Vis modes for CoauthorshipRequest Handler
* */
public static final String COAUTHORS_COUNT_PER_YEAR_VIS_MODE = "coauthors_count_per_year";
public static final String COAUTHORS_LIST_VIS_MODE = "coauthors";
public static final String COAUTHOR_NETWORK_STREAM_VIS_MODE = "coauthor_network_stream";
public static final String COAUTHOR_NETWORK_DOWNLOAD_VIS_MODE = "coauthor_network_download";
/*
* Vis modes for CoPIRequest Handler
* */
public static final String COPIS_COUNT_PER_YEAR_VIS_MODE = "copis_count_per_year";
public static final String COPIS_LIST_VIS_MODE = "copis";
public static final String COPI_NETWORK_STREAM_VIS_MODE = "copi_network_stream";
public static final String COPI_NETWORK_DOWNLOAD_VIS_MODE = "copi_network_download";
/*
* Vis modes for Map of Science Handler
* */
public static final String DISCIPLINE_TO_ACTIVTY_VIS_MODE = "discipline";
public static final String SUBDISCIPLINE_TO_ACTIVTY_VIS_MODE = "subdiscipline";
public static final String SCIENCE_UNLOCATED_JOURNALS_VIS_MODE = "unlocated_journals";
/*
* These values represent possible utilities vis modes.
* */
public static final String PROFILE_INFO_UTILS_VIS_MODE = "PROFILE_INFO";
public static final String PROFILE_UTILS_VIS_MODE = "PROFILE_URL";
public static final String COAUTHOR_UTILS_VIS_MODE = "COAUTHORSHIP_URL";
public static final String PERSON_LEVEL_UTILS_VIS_MODE = "PERSON_LEVEL_URL";
public static final String COPI_UTILS_VIS_MODE = "COPI_URL";
public static final String IMAGE_UTILS_VIS_MODE = "IMAGE_URL";
public static final String ARE_PUBLICATIONS_AVAILABLE_UTILS_VIS_MODE = "SHOW_AUTHORSHIP_LINK";
public static final String ARE_GRANTS_AVAILABLE_UTILS_VIS_MODE = "SHOW_GRANTS_LINK";
public static final String UNIVERSITY_COMPARISON_VIS_MODE = "UNIVERSITY";
public static final String SCHOOL_COMPARISON_VIS_MODE = "SCHOOL";
public static final String DEPARTMENT_COMPARISON_VIS_MODE = "DEPARTMENT";
public static final String HIGHEST_LEVEL_ORGANIZATION_VIS_MODE = "HIGHEST_LEVEL_ORGANIZATION";
/*
* These values represent possible visualizations provided as values to the "vis" url key.
* */
public static final String PERSON_PUBLICATION_COUNT_VIS = "person_pub_count";
public static final String PERSON_GRANT_COUNT_VIS = "person_grant_count";
public static final String PDF_REPORT_VIS = "pdf_report";
public static final String COLLEGE_PUBLICATION_COUNT_VIS = "college_pub_count";
public static final String COAUTHORSHIP_VIS = "coauthorship";
public static final String PERSON_LEVEL_VIS = "person_level";
public static final String COAUTHORSHIP_VIS_SHORT_URL = "author-network";
public static final String COINVESTIGATOR_VIS_SHORT_URL = "investigator-network";
public static final String UTILITIES_VIS = "utilities";
public static final String ENTITY_COMPARISON_VIS = "entity_comparison";
public static final String PUBLICATION_TEMPORAL_VIS_SHORT_URL = "publication-graph";
public static final String MAP_OF_SCIENCE_VIS_SHORT_URL = "map-of-science";
public static final String GRANT_TEMPORAL_VIS_SHORT_URL = "grant-graph";
public static final String CO_PI_VIS = "coprincipalinvestigator";
/*
* These values represent possible data serialization formats corresponding to
* output format key.
* */
public static final String JSON_OUTPUT_FORMAT = "json";
public static final String CSV_OUTPUT_FORMAT = "csv";
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.controller.visualization;
import java.util.regex.Pattern;
public class VisualizationFrameworkConstants {
/*
* Contains the location of bean containing info on all the visualizations
* available in that instance. Currently it is stored under
* "productMods/WEB-INF..."
*/
public static final String RELATIVE_LOCATION_OF_VISUALIZATIONS_BEAN =
"/WEB-INF/visualization/visualizations-beans-injection.xml";
/*
* Freemarker Version
* */
public static final String RELATIVE_LOCATION_OF_FM_VISUALIZATIONS_BEAN =
"/WEB-INF/visualization/visualizations-beans-injection-fm.xml";
public static final String ERROR_TEMPLATE = "/visualization/visualizationError.ftl";
/*
* Vis URL prefix that is seen by all the users
*/
public static final String VISUALIZATION_URL_PREFIX = "/visualization";
public static final String SHORT_URL_VISUALIZATION_REQUEST_PREFIX = "/vis";
public static final String FREEMARKERIZED_VISUALIZATION_URL_PREFIX = "/visualization";
public static final String AJAX_VISUALIZATION_SERVICE_URL_PREFIX = "/visualizationAjax";
public static final String DATA_VISUALIZATION_SERVICE_URL_PREFIX = "/visualizationData";
public static final String INDIVIDUAL_URL_PREFIX = "/individual";
public static final Pattern SHORT_URL_REQUEST_PATTERN = Pattern
.compile("^"
+ SHORT_URL_VISUALIZATION_REQUEST_PREFIX
+ "/([\\w-]+)/([^/]*)$");
/*
* These represent possible query keys in a URI for visualization purposes.
* Examples,
* 1. http://vivo.indiana.edu/visualization?uri=http://vivoweb.org/ontology/core/Person10979&vis=person_level&render_mode=standalone
* 2. http://vivo.indiana.edu/visualization?uri=http://vivoweb.org/ontology/core/Person72&vis=person_pub_count&render_mode=dynamic&container=vis_container
* */
public static final String VIS_TYPE_KEY = "vis";
public static final String VIS_CONTAINER_KEY = "container";
public static final String INDIVIDUAL_URI_KEY = "uri";
public static final String VIS_MODE_KEY = "vis_mode";
public static final String RENDER_MODE_KEY = "render_mode";
public static final String OUTPUT_FORMAT_KEY = "output";
public static final String REQUESTING_TEMPLATE_KEY = "template"; /* tlw72 - added in 1.6 for multi-view support */
/*
* These values represent possible render modes.
* */
public static final String STANDALONE_RENDER_MODE = "standalone";
public static final String DYNAMIC_RENDER_MODE = "dynamic";
public static final String DATA_RENDER_MODE = "data";
public static final String PDF_RENDER_MODE = "pdf";
/*
* These values represent possible sub-vis modes.
* */
public static final String IMAGE_VIS_MODE = "image";
public static final String SHORT_SPARKLINE_VIS_MODE = "short";
public static final String FULL_SPARKLINE_VIS_MODE = "full";
public static final String COPI_VIS_MODE = "copi";
public static final String COAUTHOR_VIS_MODE = "coauthor";
/*
* Vis modes for CoauthorshipRequest Handler
* */
public static final String COAUTHORS_COUNT_PER_YEAR_VIS_MODE = "coauthors_count_per_year";
public static final String COAUTHORS_LIST_VIS_MODE = "coauthors";
public static final String COAUTHOR_NETWORK_STREAM_VIS_MODE = "coauthor_network_stream";
public static final String COAUTHOR_NETWORK_DOWNLOAD_VIS_MODE = "coauthor_network_download";
/*
* Vis modes for CoPIRequest Handler
* */
public static final String COPIS_COUNT_PER_YEAR_VIS_MODE = "copis_count_per_year";
public static final String COPIS_LIST_VIS_MODE = "copis";
public static final String COPI_NETWORK_STREAM_VIS_MODE = "copi_network_stream";
public static final String COPI_NETWORK_DOWNLOAD_VIS_MODE = "copi_network_download";
/*
* Vis modes for Map of Science Handler
* */
public static final String DISCIPLINE_TO_ACTIVTY_VIS_MODE = "discipline";
public static final String SUBDISCIPLINE_TO_ACTIVTY_VIS_MODE = "subdiscipline";
public static final String SCIENCE_UNLOCATED_JOURNALS_VIS_MODE = "unlocated_journals";
/*
* These values represent possible utilities vis modes.
* */
public static final String PROFILE_INFO_UTILS_VIS_MODE = "PROFILE_INFO";
public static final String PROFILE_UTILS_VIS_MODE = "PROFILE_URL";
public static final String COAUTHOR_UTILS_VIS_MODE = "COAUTHORSHIP_URL";
public static final String PERSON_LEVEL_UTILS_VIS_MODE = "PERSON_LEVEL_URL";
public static final String COPI_UTILS_VIS_MODE = "COPI_URL";
public static final String IMAGE_UTILS_VIS_MODE = "IMAGE_URL";
public static final String ARE_PUBLICATIONS_AVAILABLE_UTILS_VIS_MODE = "SHOW_AUTHORSHIP_LINK";
public static final String ARE_GRANTS_AVAILABLE_UTILS_VIS_MODE = "SHOW_GRANTS_LINK";
public static final String UNIVERSITY_COMPARISON_VIS_MODE = "UNIVERSITY";
public static final String SCHOOL_COMPARISON_VIS_MODE = "SCHOOL";
public static final String DEPARTMENT_COMPARISON_VIS_MODE = "DEPARTMENT";
public static final String HIGHEST_LEVEL_ORGANIZATION_VIS_MODE = "HIGHEST_LEVEL_ORGANIZATION";
/*
* These values represent possible visualizations provided as values to the "vis" url key.
* */
public static final String PERSON_PUBLICATION_COUNT_VIS = "person_pub_count";
public static final String PERSON_GRANT_COUNT_VIS = "person_grant_count";
public static final String PDF_REPORT_VIS = "pdf_report";
public static final String COLLEGE_PUBLICATION_COUNT_VIS = "college_pub_count";
public static final String COAUTHORSHIP_VIS = "coauthorship";
public static final String PERSON_LEVEL_VIS = "person_level";
public static final String COAUTHORSHIP_VIS_SHORT_URL = "author-network";
public static final String COINVESTIGATOR_VIS_SHORT_URL = "investigator-network";
public static final String UTILITIES_VIS = "utilities";
public static final String ENTITY_COMPARISON_VIS = "entity_comparison";
public static final String PUBLICATION_TEMPORAL_VIS_SHORT_URL = "publication-graph";
public static final String MAP_OF_SCIENCE_VIS_SHORT_URL = "map-of-science";
public static final String GRANT_TEMPORAL_VIS_SHORT_URL = "grant-graph";
public static final String CO_PI_VIS = "coprincipalinvestigator";
/*
* These values represent possible data serialization formats corresponding to
* output format key.
* */
public static final String JSON_OUTPUT_FORMAT = "json";
public static final String CSV_OUTPUT_FORMAT = "csv";
}

View file

@ -1,19 +1,19 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.controller.visualization;
import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.VisualizationRequestHandler;
public class VisualizationInjector {
private Map<String, VisualizationRequestHandler> visualizationIDToClass;
public Map<String, VisualizationRequestHandler> getVisualizationIDToClass() {
return visualizationIDToClass;
}
public void setVisualizations(Map<String, VisualizationRequestHandler> visualizationIDToClass) {
this.visualizationIDToClass = visualizationIDToClass;
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.controller.visualization;
import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.VisualizationRequestHandler;
public class VisualizationInjector {
private Map<String, VisualizationRequestHandler> visualizationIDToClass;
public Map<String, VisualizationRequestHandler> getVisualizationIDToClass() {
return visualizationIDToClass;
}
public void setVisualizations(Map<String, VisualizationRequestHandler> visualizationIDToClass) {
this.visualizationIDToClass = visualizationIDToClass;
}
}

View file

@ -12,18 +12,18 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.VisualizationRequestHandler;
public class VisualizationsDependencyInjector {
private static Map<String, VisualizationRequestHandler> visualizationIDsToClass;
/**
* This method is used to inject vis dependencies i.e. the vis algorithms that are
* being implemented into the vis controller. Modified Dependency Injection pattern is
* used here. XML file containing the location of all the vis is saved in accessible folder.
* This method is used to inject vis dependencies i.e. the vis algorithms that are
* being implemented into the vis controller. Modified Dependency Injection pattern is
* used here. XML file containing the location of all the vis is saved in accessible folder.
* @param servletContext Servlet context
*/
private synchronized static Map<String, VisualizationRequestHandler> initVisualizations(
ServletContext servletContext) {
/*
* A visualization request has already been made causing the visualizationIDsToClass to be
* initiated & populated with visualization ids to its request handlers.
@ -31,26 +31,26 @@ public class VisualizationsDependencyInjector {
if (visualizationIDsToClass != null) {
return visualizationIDsToClass;
}
String resourcePath =
String resourcePath =
servletContext
.getRealPath(VisualizationFrameworkConstants
.RELATIVE_LOCATION_OF_FM_VISUALIZATIONS_BEAN);
ApplicationContext context = new ClassPathXmlApplicationContext(
"file:" + resourcePath);
BeanFactory factory = context;
VisualizationInjector visualizationInjector =
VisualizationInjector visualizationInjector =
(VisualizationInjector) factory.getBean("visualizationInjector");
visualizationIDsToClass = visualizationInjector.getVisualizationIDToClass();
return visualizationIDsToClass;
}
public static Map<String, VisualizationRequestHandler> getVisualizationIDsToClassMap(
ServletContext servletContext) {
if (visualizationIDsToClass != null) {

View file

@ -15,25 +15,25 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmis
public class AutocompleteRequiredInputValidator implements N3ValidatorVTwo {
private static String MISSING_LABEL_ERROR = "Please select an existing value or enter a new value in the Name field.";
private String uriReceiver;
private String labelInput;
public AutocompleteRequiredInputValidator(String uriReceiver, String labelInput) {
this.uriReceiver = uriReceiver;
this.labelInput = labelInput;
}
@Override
public Map<String, String> validate(EditConfigurationVTwo editConfig,
MultiValueEditSubmission editSub) {
Map<String,List<String>> urisFromForm = editSub.getUrisFromForm();
Map<String,List<Literal>> literalsFromForm = editSub.getLiteralsFromForm();
Map<String,String> errors = new HashMap<String,String>();
Map<String,String> errors = new HashMap<String,String>();
List<String> selectedUri = urisFromForm.get(uriReceiver);
// If there's a presentationUri, then we're done. If not, check to see if the label exists.
// If that's null, too, it's an error.
if (allListElementsEmpty(selectedUri) || selectedUri.contains(">SUBMITTED VALUE WAS BLANK<")) {
@ -50,11 +50,11 @@ public class AutocompleteRequiredInputValidator implements N3ValidatorVTwo {
else {
errors.put(labelInput, MISSING_LABEL_ERROR);
}
}
}
return errors.size() != 0 ? errors : null;
}
private boolean allListElementsEmpty(List<String> checkList) {
if(checkList == null)
return true;

View file

@ -18,19 +18,19 @@ public class FirstAndLastNameValidator implements N3ValidatorVTwo {
private static String MISSING_LAST_NAME_ERROR = "You must enter a value in the Last Name field.";
private static String MALFORMED_LAST_NAME_ERROR = "The last name field may not contain a comma. Please enter first name in First Name field.";
private String uriReceiver;
public FirstAndLastNameValidator(String uriReceiver) {
this.uriReceiver = uriReceiver;
}
@Override
public Map<String, String> validate(EditConfigurationVTwo editConfig,
MultiValueEditSubmission editSub) {
Map<String,List<String>> urisFromForm = editSub.getUrisFromForm();
Map<String,List<Literal>> literalsFromForm = editSub.getLiteralsFromForm();
Map<String,String> errors = new HashMap<String,String>();
Map<String,String> errors = new HashMap<String,String>();
List<String> personUri = urisFromForm.get(uriReceiver);
if (allListElementsEmpty(personUri) || personUri.contains(">SUBMITTED VALUE WAS BLANK<")) {
personUri = null;
@ -40,7 +40,7 @@ public class FirstAndLastNameValidator implements N3ValidatorVTwo {
if (personUri != null) {
return null;
}
//Expecting only one first name in this case
//To Do: update logic if multiple first names considered
Literal firstName = null;
@ -48,8 +48,8 @@ public class FirstAndLastNameValidator implements N3ValidatorVTwo {
if(firstNameList != null && firstNameList.size() > 0) {
firstName = firstNameList.get(0);
}
if( firstName != null &&
firstName.getLexicalForm() != null &&
if( firstName != null &&
firstName.getLexicalForm() != null &&
"".equals(firstName.getLexicalForm()) )
firstName = null;
@ -70,17 +70,17 @@ public class FirstAndLastNameValidator implements N3ValidatorVTwo {
if (lastName == null) {
errors.put("lastName", MISSING_LAST_NAME_ERROR);
// Don't reject space in the last name: de Vries, etc.
} else if (lastNameValue.contains(",")) {
} else if (lastNameValue.contains(",")) {
errors.put("lastName", MALFORMED_LAST_NAME_ERROR);
}
if (firstName == null) {
errors.put("firstName", MISSING_FIRST_NAME_ERROR);
}
}
return errors.size() != 0 ? errors : null;
}
private boolean allListElementsEmpty(List<String> checkList) {
if(checkList == null)
return true;

View file

@ -4,7 +4,7 @@ package edu.cornell.mannlib.vitro.webapp.edit.n3editing;
import java.util.HashMap;
import java.util.Map;
public class N3TransitionToV2Mapping extends HashMap<String, String>{
public class N3TransitionToV2Mapping extends HashMap<String, String>{
public N3TransitionToV2Mapping(){
Map<String,String> map = this;
@ -13,7 +13,7 @@ public class N3TransitionToV2Mapping extends HashMap<String, String>{
// vivo forms:
map.put("addAuthorsToInformationResource.jsp",
map.put("addAuthorsToInformationResource.jsp",
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddAuthorsToInformationResourceGenerator.class.getName());
map.put("manageWebpagesForIndividual.jsp",
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.ManageWebpagesForIndividualGenerator.class.getName());
@ -24,7 +24,7 @@ public class N3TransitionToV2Mapping extends HashMap<String, String>{
map.put("personHasEducationalTraining.jsp",
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.PersonHasEducationalTraining.class.getName());
map.put("personHasPositionHistory.jsp",
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.PersonHasPositionHistoryGenerator.class.getName());
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.PersonHasPositionHistoryGenerator.class.getName());
map.put("addGrantRoleToPerson.jsp",
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddGrantRoleToPersonGenerator.class.getName());
map.put("addEditWebpageForm.jsp",
@ -34,12 +34,12 @@ public class N3TransitionToV2Mapping extends HashMap<String, String>{
// map.put("terminologyAnnotation.jsp",
// edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.TerminologyAnnotationGenerator.class.getName());
//
//
// map.put("redirectToPublication.jsp",
// edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.RedirectToPublicationGenerator.class.getName());
// map.put("unsupportedBrowserMessage.jsp",
// edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.UnsupportedBrowserMessage.class.getName());
//
//
// vivo 2 stage role forms:
map.put("addAttendeeRoleToPerson.jsp",
@ -57,7 +57,7 @@ public class N3TransitionToV2Mapping extends HashMap<String, String>{
map.put("addOutreachRoleToPerson.jsp",
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddOutreachProviderRoleToPersonGenerator.class.getName());
map.put("addPresenterRoleToPerson.jsp",
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddPresenterRoleToPersonGenerator.class.getName());
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddPresenterRoleToPersonGenerator.class.getName());
map.put("addResearcherRoleToPerson.jsp",
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddResearcherRoleToPersonGenerator.class.getName());
map.put("addReviewerRoleToPerson.jsp",
@ -68,6 +68,6 @@ public class N3TransitionToV2Mapping extends HashMap<String, String>{
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddServiceProviderRoleToPersonGenerator.class.getName());
map.put("addTeacherRoleToPerson.jsp",
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddTeacherRoleToPersonGenerator.class.getName());
}
}

View file

@ -22,7 +22,7 @@ public class PersonHasPublicationValidator implements N3ValidatorVTwo {
private static String MISSING_FIRST_NAME_ERROR = "You must enter a value in the First Name field.";
private static String MISSING_LAST_NAME_ERROR = "You must enter a value in the Last Name field.";
private static String MALFORMED_LAST_NAME_ERROR = "The last name field may not contain a comma. Please enter first name in First Name field.";
@Override
public Map<String, String> validate(EditConfigurationVTwo editConfig,
MultiValueEditSubmission editSub) {
@ -30,11 +30,11 @@ public class PersonHasPublicationValidator implements N3ValidatorVTwo {
Map<String,List<String>> urisFromForm = editSub.getUrisFromForm();
Map<String,List<Literal>> literalsFromForm = editSub.getLiteralsFromForm();
Map<String,String> errors = new HashMap<String,String>();
// The Editor field is optional for all publication subclasses. Validation is only necessary if the user only enters a
Map<String,String> errors = new HashMap<String,String>();
// The Editor field is optional for all publication subclasses. Validation is only necessary if the user only enters a
// last name or only enters a first name
//Expecting only one first name in this case
//To Do: update logic if multiple first names considered
List<Literal> firstNameList = literalsFromForm.get("firstName");
@ -42,8 +42,8 @@ public class PersonHasPublicationValidator implements N3ValidatorVTwo {
if(firstNameList != null && firstNameList.size() > 0) {
firstName = firstNameList.get(0);
}
if ( firstName != null &&
firstName.getLexicalForm() != null &&
if ( firstName != null &&
firstName.getLexicalForm() != null &&
"".equals(firstName.getLexicalForm()) )
firstName = null;
@ -67,22 +67,22 @@ public class PersonHasPublicationValidator implements N3ValidatorVTwo {
else if ( firstName == null && lastName != null) {
errors.put("firstName", MISSING_FIRST_NAME_ERROR);
}
else if (lastNameValue.contains(",")) {
else if (lastNameValue.contains(",")) {
errors.put("lastName", MALFORMED_LAST_NAME_ERROR);
}
else {
return null;
}
}
return errors.size() != 0 ? errors : null;
}
private Object getFirstElement(List checkList) {
if(checkList == null || checkList.size() == 0) {
return null;
}
return checkList.get(0);
}
}

View file

@ -19,19 +19,19 @@ public class PublicationHasAuthorValidator implements N3ValidatorVTwo {
private static String MISSING_FIRST_NAME_ERROR = "Must specify the author's first name.";
private static String MISSING_LAST_NAME_ERROR = "Must specify the author's last name.";
private static String MALFORMED_LAST_NAME_ERROR = "Last name may not contain a comma. Please enter first name in first name field.";
;
;
@Override
public Map<String, String> validate(EditConfigurationVTwo editConfig,
MultiValueEditSubmission editSub) {
Map<String,List<String>> urisFromForm = editSub.getUrisFromForm();
Map<String,List<Literal>> literalsFromForm = editSub.getLiteralsFromForm();
Map<String,String> errors = new HashMap<String,String>();
Map<String,String> errors = new HashMap<String,String>();
List<String> personUri = urisFromForm.get("personUri");
List<String> orgUri = urisFromForm.get("orgUri");
List<Literal> orgNameList = literalsFromForm.get("orgName");
if (allListElementsEmpty(personUri)) {
personUri = null;
}
@ -47,7 +47,7 @@ public class PublicationHasAuthorValidator implements N3ValidatorVTwo {
if (personUri != null || orgUri != null || orgName != null ) {
return null;
}
//Expecting only one first name in this case
//To Do: update logic if multiple first names considered
Literal firstName = null;
@ -55,8 +55,8 @@ public class PublicationHasAuthorValidator implements N3ValidatorVTwo {
if(firstNameList != null && firstNameList.size() > 0) {
firstName = firstNameList.get(0);
}
if( firstName != null &&
firstName.getLexicalForm() != null &&
if( firstName != null &&
firstName.getLexicalForm() != null &&
"".equals(firstName.getLexicalForm()) )
firstName = null;
@ -77,17 +77,17 @@ public class PublicationHasAuthorValidator implements N3ValidatorVTwo {
if (lastName == null) {
errors.put("lastName", MISSING_LAST_NAME_ERROR);
// Don't reject space in the last name: de Vries, etc.
} else if (lastNameValue.contains(",")) {
} else if (lastNameValue.contains(",")) {
errors.put("lastName", MALFORMED_LAST_NAME_ERROR);
}
if (firstName == null) {
errors.put("firstName", MISSING_FIRST_NAME_ERROR);
}
}
return errors.size() != 0 ? errors : null;
}
private boolean allListElementsEmpty(List<String> checkList) {
if(checkList == null)
return true;

View file

@ -1,67 +1,67 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ConstantFieldOptions;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldOptions;
public class AddAttendeeRoleToPersonGenerator extends AddRoleToPersonTwoStageGenerator {
private static String TEMPLATE = "addAttendeeRoleToPerson.ftl";
@Override
String getTemplate(){ return TEMPLATE; }
@Override
String getRoleType() {
return "http://vivoweb.org/ontology/core#AttendeeRole";
}
/** Editor role involves hard-coded options for the "right side" of the role or activity. */
@Override
FieldOptions getRoleActivityFieldOptions(VitroRequest vreq) throws Exception {
return new ConstantFieldOptions(
"", "Select type",
"http://purl.org/NET/c4dm/event.owl#Event", "Event",
"http://vivoweb.org/ontology/core#Competition", "Competition",
"http://purl.org/ontology/bibo/Conference", "Conference",
"http://vivoweb.org/ontology/core#Course", "Course",
"http://vivoweb.org/ontology/core#Exhibit", "Exhibit",
"http://purl.org/ontology/bibo/Hearing", "Hearing",
"http://purl.org/ontology/bibo/Interview", "Interview",
"http://vivoweb.org/ontology/core#Meeting", "Meeting",
"http://purl.org/ontology/bibo/Performance", "Performance",
"http://vivoweb.org/ontology/core#Presentation", "Presentation",
"http://vivoweb.org/ontology/core#InvitedTalk", "Invited Talk",
"http://purl.org/ontology/bibo/Workshop", "Workshop",
"http://vivoweb.org/ontology/core#EventSeries", "Event Series",
"http://vivoweb.org/ontology/core#ConferenceSeries", "Conference Series",
"http://vivoweb.org/ontology/core#SeminarSeries", "Seminar Series",
"http://vivoweb.org/ontology/core#WorkshopSeries", "Workshop Series"
);
}
@Override
boolean isShowRoleLabelField() {
return false;
}
/*
* Use the methods below to change the date/time precision in the
* custom form associated with this generator. When not used, the
* precision will be YEAR. The other precisons are MONTH, DAY, HOUR,
* MINUTE, TIME and NONE.
*/
/*
public String getStartDatePrecision() {
String precision = VitroVocabulary.Precision.MONTH.uri();
return precision;
}
public String getEndDatePrecision() {
String precision = VitroVocabulary.Precision.DAY.uri();
return precision;
}
*/
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ConstantFieldOptions;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldOptions;
public class AddAttendeeRoleToPersonGenerator extends AddRoleToPersonTwoStageGenerator {
private static String TEMPLATE = "addAttendeeRoleToPerson.ftl";
@Override
String getTemplate(){ return TEMPLATE; }
@Override
String getRoleType() {
return "http://vivoweb.org/ontology/core#AttendeeRole";
}
/** Editor role involves hard-coded options for the "right side" of the role or activity. */
@Override
FieldOptions getRoleActivityFieldOptions(VitroRequest vreq) throws Exception {
return new ConstantFieldOptions(
"", "Select type",
"http://purl.org/NET/c4dm/event.owl#Event", "Event",
"http://vivoweb.org/ontology/core#Competition", "Competition",
"http://purl.org/ontology/bibo/Conference", "Conference",
"http://vivoweb.org/ontology/core#Course", "Course",
"http://vivoweb.org/ontology/core#Exhibit", "Exhibit",
"http://purl.org/ontology/bibo/Hearing", "Hearing",
"http://purl.org/ontology/bibo/Interview", "Interview",
"http://vivoweb.org/ontology/core#Meeting", "Meeting",
"http://purl.org/ontology/bibo/Performance", "Performance",
"http://vivoweb.org/ontology/core#Presentation", "Presentation",
"http://vivoweb.org/ontology/core#InvitedTalk", "Invited Talk",
"http://purl.org/ontology/bibo/Workshop", "Workshop",
"http://vivoweb.org/ontology/core#EventSeries", "Event Series",
"http://vivoweb.org/ontology/core#ConferenceSeries", "Conference Series",
"http://vivoweb.org/ontology/core#SeminarSeries", "Seminar Series",
"http://vivoweb.org/ontology/core#WorkshopSeries", "Workshop Series"
);
}
@Override
boolean isShowRoleLabelField() {
return false;
}
/*
* Use the methods below to change the date/time precision in the
* custom form associated with this generator. When not used, the
* precision will be YEAR. The other precisons are MONTH, DAY, HOUR,
* MINUTE, TIME and NONE.
*/
/*
public String getStartDatePrecision() {
String precision = VitroVocabulary.Precision.MONTH.uri();
return precision;
}
public String getEndDatePrecision() {
String precision = VitroVocabulary.Precision.DAY.uri();
return precision;
}
*/
}

View file

@ -35,9 +35,9 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.
/**
* This is a slightly unusual generator that is used by Manage Authors on
* information resources.
* information resources.
*
* It is intended to always be an add, and never an update.
* It is intended to always be an add, and never an update.
*/
public class AddAuthorsToInformationResourceGenerator extends VivoBaseGenerator implements EditConfigurationGenerator {
public static Log log = LogFactory.getLog(AddAuthorsToInformationResourceGenerator.class);
@ -45,7 +45,7 @@ public class AddAuthorsToInformationResourceGenerator extends VivoBaseGenerator
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
HttpSession session) {
EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo();
EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo();
initBasics(editConfiguration, vreq);
initPropertyParameters(vreq, session, editConfiguration);
@ -53,22 +53,22 @@ public class AddAuthorsToInformationResourceGenerator extends VivoBaseGenerator
setUrlToReturnTo(editConfiguration, vreq);
//set variable names
editConfiguration.setVarNameForSubject("infoResource");
editConfiguration.setVarNameForPredicate("predicate");
editConfiguration.setVarNameForObject("authorshipUri");
editConfiguration.setVarNameForSubject("infoResource");
editConfiguration.setVarNameForPredicate("predicate");
editConfiguration.setVarNameForObject("authorshipUri");
// Required N3
editConfiguration.setN3Required( list( getN3NewAuthorship() ) );
editConfiguration.setN3Required( list( getN3NewAuthorship() ) );
// Optional N3
editConfiguration.setN3Optional( generateN3Optional());
// Optional N3
editConfiguration.setN3Optional( generateN3Optional());
editConfiguration.addNewResource("authorshipUri", DEFAULT_NS_TOKEN);
editConfiguration.addNewResource("newPerson", DEFAULT_NS_TOKEN);
editConfiguration.addNewResource("newOrg", DEFAULT_NS_TOKEN);
editConfiguration.addNewResource("vcardPerson", DEFAULT_NS_TOKEN);
editConfiguration.addNewResource("vcardName", DEFAULT_NS_TOKEN);
//In scope
setUrisAndLiteralsInScope(editConfiguration, vreq);
@ -88,121 +88,121 @@ public class AddAuthorsToInformationResourceGenerator extends VivoBaseGenerator
//Adding additional data, specifically edit mode
addFormSpecificData(editConfiguration, vreq);
editConfiguration.addValidator(new AntiXssValidation());
//NOITCE this generator does not run prepare() since it
//NOITCE this generator does not run prepare() since it
//is never an update and has no SPARQL for existing
return editConfiguration;
}
private void setUrlToReturnTo(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
editConfiguration.setUrlPatternToReturnTo(EditConfigurationUtils.getFormUrlWithoutContext(vreq));
editConfiguration.setUrlPatternToReturnTo(EditConfigurationUtils.getFormUrlWithoutContext(vreq));
}
/***N3 strings both required and optional***/
public String getN3PrefixString() {
return "@prefix core: <" + vivoCore + "> .\n" +
return "@prefix core: <" + vivoCore + "> .\n" +
"@prefix foaf: <" + foaf + "> . \n" ;
}
private String getN3NewAuthorship() {
return getN3PrefixString() +
"?authorshipUri a core:Authorship ;\n" +
" core:relates ?infoResource .\n" +
return getN3PrefixString() +
"?authorshipUri a core:Authorship ;\n" +
" core:relates ?infoResource .\n" +
"?infoResource core:relatedBy ?authorshipUri .";
}
private String getN3AuthorshipRank() {
return getN3PrefixString() +
return getN3PrefixString() +
"?authorshipUri core:rank ?rank .";
}
//first name, middle name, last name, and new perseon for new author being created, and n3 for existing person
//if existing person selected as author
public List<String> generateN3Optional() {
return list(
getN3NewPersonFirstName() ,
getN3NewPersonMiddleName(),
getN3NewPersonLastName(),
getN3NewPersonLastName(),
getN3NewPerson(),
getN3AuthorshipRank(),
getN3ForExistingPerson(),
getN3NewOrg(),
getN3ForExistingOrg());
}
private String getN3NewPersonFirstName() {
return getN3PrefixString() +
return getN3PrefixString() +
"@prefix vcard: <http://www.w3.org/2006/vcard/ns#> . \n" +
"?newPerson <http://purl.obolibrary.org/obo/ARG_2000028> ?vcardPerson . \n" +
"?vcardPerson <http://purl.obolibrary.org/obo/ARG_2000029> ?newPerson . \n" +
"?vcardPerson a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardPerson a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardPerson vcard:hasName ?vcardName . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName vcard:givenName ?firstName .";
}
private String getN3NewPersonMiddleName() {
return getN3PrefixString() +
return getN3PrefixString() +
"@prefix vcard: <http://www.w3.org/2006/vcard/ns#> . \n" +
"?newPerson <http://purl.obolibrary.org/obo/ARG_2000028> ?vcardPerson . \n" +
"?vcardPerson <http://purl.obolibrary.org/obo/ARG_2000029> ?newPerson . \n" +
"?vcardPerson a vcard:Individual . \n" +
"?vcardPerson a vcard:Individual . \n" +
"?vcardPerson vcard:hasName ?vcardName . \n" +
"?vcardName a vcard:Name . \n" +
"?vcardName a vcard:Name . \n" +
"?vcardName <http://vivoweb.org/ontology/core#middleName> ?middleName .";
}
private String getN3NewPersonLastName() {
return getN3PrefixString() +
return getN3PrefixString() +
"@prefix vcard: <http://www.w3.org/2006/vcard/ns#> . \n" +
"?newPerson <http://purl.obolibrary.org/obo/ARG_2000028> ?vcardPerson . \n" +
"?vcardPerson <http://purl.obolibrary.org/obo/ARG_2000029> ?newPerson . \n" +
"?vcardPerson a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardPerson a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardPerson vcard:hasName ?vcardName . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName vcard:familyName ?lastName .";
}
private String getN3NewPerson() {
return getN3PrefixString() +
"?newPerson a foaf:Person ;\n" +
"<" + RDFS.label.getURI() + "> ?label .\n" +
"?authorshipUri core:relates ?newPerson .\n" +
return getN3PrefixString() +
"?newPerson a foaf:Person ;\n" +
"<" + RDFS.label.getURI() + "> ?label .\n" +
"?authorshipUri core:relates ?newPerson .\n" +
"?newPerson core:relatedBy ?authorshipUri . ";
}
private String getN3ForExistingPerson() {
return getN3PrefixString() +
"?authorshipUri core:relates ?personUri .\n" +
return getN3PrefixString() +
"?authorshipUri core:relates ?personUri .\n" +
"?personUri core:relatedBy ?authorshipUri .";
}
private String getN3NewOrg() {
return getN3PrefixString() +
"?newOrg a foaf:Organization ;\n" +
"<" + RDFS.label.getURI() + "> ?orgName .\n" +
"?authorshipUri core:relates ?newOrg .\n" +
return getN3PrefixString() +
"?newOrg a foaf:Organization ;\n" +
"<" + RDFS.label.getURI() + "> ?orgName .\n" +
"?authorshipUri core:relates ?newOrg .\n" +
"?newOrg core:relatedBy ?authorshipUri . ";
}
private String getN3ForExistingOrg() {
return getN3PrefixString() +
"?authorshipUri core:relates ?orgUri .\n" +
return getN3PrefixString() +
"?authorshipUri core:relates ?orgUri .\n" +
"?orgUri core:relatedBy ?authorshipUri .";
}
/** Get new resources */
//A new authorship uri will always be created when an author is added
//A new person may be added if a person not in the system will be added as author
private Map<String, String> generateNewResources(VitroRequest vreq) {
HashMap<String, String> newResources = new HashMap<String, String>();
private Map<String, String> generateNewResources(VitroRequest vreq) {
HashMap<String, String> newResources = new HashMap<String, String>();
newResources.put("authorshipUri", DEFAULT_NS_TOKEN);
newResources.put("newPerson", DEFAULT_NS_TOKEN);
newResources.put("vcardPerson", DEFAULT_NS_TOKEN);
@ -210,26 +210,26 @@ public class AddAuthorsToInformationResourceGenerator extends VivoBaseGenerator
newResources.put("newOrg", DEFAULT_NS_TOKEN);
return newResources;
}
/** Set URIS and Literals In Scope and on form and supporting methods */
/** Set URIS and Literals In Scope and on form and supporting methods */
private void setUrisAndLiteralsInScope(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
//Uris in scope always contain subject and predicate
HashMap<String, List<String>> urisInScope = new HashMap<String, List<String>>();
urisInScope.put(editConfiguration.getVarNameForSubject(),
urisInScope.put(editConfiguration.getVarNameForSubject(),
Arrays.asList(new String[]{editConfiguration.getSubjectUri()}));
urisInScope.put(editConfiguration.getVarNameForPredicate(),
urisInScope.put(editConfiguration.getVarNameForPredicate(),
Arrays.asList(new String[]{editConfiguration.getPredicateUri()}));
editConfiguration.setUrisInScope(urisInScope);
//no literals in scope
//no literals in scope
}
public void setUrisAndLiteralsOnForm(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
List<String> urisOnForm = new ArrayList<String>();
List<String> urisOnForm = new ArrayList<String>();
//If an existing person is being used as an author, need to get the person uri
urisOnForm.add("personUri");
urisOnForm.add("orgUri");
editConfiguration.setUrisOnform(urisOnForm);
//for person who is not in system, need to add first name, last name and middle name
//Also need to store authorship rank and label of author
List<String> literalsOnForm = list("firstName",
@ -239,10 +239,10 @@ public class AddAuthorsToInformationResourceGenerator extends VivoBaseGenerator
"orgName",
"label");
editConfiguration.setLiteralsOnForm(literalsOnForm);
}
/** Set SPARQL Queries and supporting methods. */
private void setSparqlQueries(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
}
/** Set SPARQL Queries and supporting methods. */
private void setSparqlQueries(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
//Sparql queries are all empty for existing values
//This form is different from the others that it gets multiple authors on the same page
//and that information will be queried and stored in the additional form specific data
@ -252,12 +252,12 @@ public class AddAuthorsToInformationResourceGenerator extends VivoBaseGenerator
editConfiguration.setSparqlForAdditionalUrisInScope(new HashMap<String, String>());
editConfiguration.setSparqlForAdditionalLiteralsInScope(new HashMap<String, String>());
}
/**
*
*
* Set Fields and supporting methods
*/
public void setFields(EditConfigurationVTwo editConfiguration, VitroRequest vreq, String predicateUri) {
setLabelField(editConfiguration);
setFirstNameField(editConfiguration);
@ -268,7 +268,7 @@ public class AddAuthorsToInformationResourceGenerator extends VivoBaseGenerator
setOrgUriField(editConfiguration);
setOrgNameField(editConfiguration);
}
private void setLabelField(EditConfigurationVTwo editConfiguration) {
editConfiguration.addField(new FieldVTwo().
setName("label").
@ -333,7 +333,7 @@ public class AddAuthorsToInformationResourceGenerator extends VivoBaseGenerator
setRangeDatatypeUri(XSD.xstring.toString())
);
}
//Form specific data
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
@ -418,27 +418,27 @@ public class AddAuthorsToInformationResourceGenerator extends VivoBaseGenerator
+ "WHERE { { \n"
+ " ?subject core:relatedBy ?authorshipURI . \n"
+ " ?authorshipURI a core:Authorship . \n"
+ " ?authorshipURI core:relates ?authorURI . \n"
+ " ?authorshipURI core:relates ?authorURI . \n"
+ " ?authorURI a foaf:Agent . \n"
+ " OPTIONAL { ?authorURI rdfs:label ?authorName } \n"
+ " OPTIONAL { ?authorshipURI core:rank ?rank } \n"
+ "} UNION { \n"
+ " ?subject core:relatedBy ?authorshipURI . \n"
+ " ?authorshipURI a core:Authorship . \n"
+ " ?authorshipURI core:relates ?authorURI . \n"
+ " ?authorURI a vcard:Individual . \n"
+ " ?authorURI vcard:hasName ?vName . \n"
+ " ?vName vcard:givenName ?firstName . \n"
+ " ?vName vcard:familyName ?lastName . \n"
+ " OPTIONAL { ?vName core:middleName ?middleName . } \n"
+ " OPTIONAL { ?authorshipURI core:rank ?rank } \n"
+ " bind ( COALESCE(?firstName, \"\") As ?firstName1) . \n"
+ " bind ( COALESCE(?middleName, \"\") As ?middleName1) . \n"
+ " bind ( COALESCE(?lastName, \"\") As ?lastName1) . \n"
+ " bind (concat(str(?lastName1 + \", \"),str(?middleName1 + \" \"),str(?firstName1)) as ?authorName) . \n"
+ " OPTIONAL { ?authorshipURI core:rank ?rank } \n"
+ "} UNION { \n"
+ " ?subject core:relatedBy ?authorshipURI . \n"
+ " ?authorshipURI a core:Authorship . \n"
+ " ?authorshipURI core:relates ?authorURI . \n"
+ " ?authorURI a vcard:Individual . \n"
+ " ?authorURI vcard:hasName ?vName . \n"
+ " ?vName vcard:givenName ?firstName . \n"
+ " ?vName vcard:familyName ?lastName . \n"
+ " OPTIONAL { ?vName core:middleName ?middleName . } \n"
+ " OPTIONAL { ?authorshipURI core:rank ?rank } \n"
+ " bind ( COALESCE(?firstName, \"\") As ?firstName1) . \n"
+ " bind ( COALESCE(?middleName, \"\") As ?middleName1) . \n"
+ " bind ( COALESCE(?lastName, \"\") As ?lastName1) . \n"
+ " bind (concat(str(?lastName1 + \", \"),str(?middleName1 + \" \"),str(?firstName1)) as ?authorName) . \n"
+ "} } ORDER BY ?rank";
private List<AuthorshipInfo> getExistingAuthorships(String subjectUri, VitroRequest vreq) {
RDFService rdfService = vreq.getRDFService();
@ -448,7 +448,7 @@ public class AddAuthorsToInformationResourceGenerator extends VivoBaseGenerator
Model constructedModel = ModelFactory.createDefaultModel();
rdfService.sparqlConstructQuery(constructStr, constructedModel);
String queryStr = QueryUtils.subUriForQueryVar(this.getAuthorshipsQuery(), "subject", subjectUri);
log.debug("Query string is: " + queryStr);
@ -467,7 +467,7 @@ public class AddAuthorsToInformationResourceGenerator extends VivoBaseGenerator
}
} catch (Exception e) {
log.error(e, e);
}
}
authorships = QueryUtils.removeDuplicatesMapsFromList(authorships, "authorShipURI", "authorURI");
log.debug("authorships = " + authorships);
return getAuthorshipInfo(authorships);
@ -480,22 +480,22 @@ public class AddAuthorsToInformationResourceGenerator extends VivoBaseGenerator
+ " ?authorship a core:Authorship . \n"
+ " ?authorship core:rank ?rank .\n"
+ "} ORDER BY DESC(?rank) LIMIT 1";
private int getMaxRank(String subjectUri, VitroRequest vreq) {
int maxRank = 0; // default value
int maxRank = 0; // default value
String queryStr = QueryUtils.subUriForQueryVar(this.getMaxRankQueryStr(), "subject", subjectUri);
log.debug("maxRank query string is: " + queryStr);
try {
ResultSet results = QueryUtils.getQueryResults(queryStr, vreq);
if (results != null && results.hasNext()) { // there is at most one result
QuerySolution soln = results.next();
QuerySolution soln = results.next();
RDFNode node = soln.get("rank");
if (node != null && node.isLiteral()) {
// node.asLiteral().getInt() won't return an xsd:string that
// node.asLiteral().getInt() won't return an xsd:string that
// can be parsed as an int.
int rank = Integer.parseInt(node.asLiteral().getLexicalForm());
if (rank > maxRank) {
if (rank > maxRank) {
log.debug("setting maxRank to " + rank);
maxRank = rank;
}
@ -549,8 +549,8 @@ public class AddAuthorsToInformationResourceGenerator extends VivoBaseGenerator
//Author information for authorship node
private String authorUri;
private String authorName;
public AuthorshipInfo(String inputAuthorshipUri,
public AuthorshipInfo(String inputAuthorshipUri,
String inputAuthorshipName,
String inputAuthorUri,
String inputAuthorName) {
@ -560,25 +560,25 @@ public class AddAuthorsToInformationResourceGenerator extends VivoBaseGenerator
authorName = inputAuthorName;
}
//Getters - specifically required for Freemarker template's access to POJO
public String getAuthorshipUri() {
return authorshipUri;
}
public String getAuthorshipName() {
return authorshipName;
}
public String getAuthorUri() {
return authorUri;
}
public String getAuthorName() {
return authorName;
}
}
static final String DEFAULT_NS_TOKEN=null; //null forces the default NS
protected String getMaxRankQueryStr() {

View file

@ -7,28 +7,28 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ConstantField
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldOptions;
public class AddClinicalRoleToPersonGenerator extends AddRoleToPersonTwoStageGenerator {
private static String template = "addClinicalRoleToPerson.ftl";
//Should this be overridden
@Override
String getTemplate() {
return template;
String getTemplate() {
return template;
}
@Override
String getRoleType() {
return "http://vivoweb.org/ontology/core#ClinicalRole";
}
/** Clinical role involves hard-coded options for the "right side" of the role or activity. */
@Override
FieldOptions getRoleActivityFieldOptions(VitroRequest vreq) throws Exception {
FieldOptions getRoleActivityFieldOptions(VitroRequest vreq) throws Exception {
return new ConstantFieldOptions(
"", "Select one",
"http://vivoweb.org/ontology/core#Project", "Project",
"", "Select one",
"http://vivoweb.org/ontology/core#Project", "Project",
"http://purl.obolibrary.org/obo/ERO_0000005", "Service"
);
);
}
//isShowRoleLabelField remains true for this so doesn't need to be overwritten
@ -38,7 +38,7 @@ public class AddClinicalRoleToPersonGenerator extends AddRoleToPersonTwoStageGen
}
/*
/*
* Use the methods below to change the date/time precision in the
* custom form associated with this generator. When not used, the
* precision will be YEAR. The other precisons are MONTH, DAY, HOUR,
@ -54,6 +54,6 @@ public class AddClinicalRoleToPersonGenerator extends AddRoleToPersonTwoStageGen
String precision = VitroVocabulary.Precision.DAY.uri();
return precision;
}
*/
*/
}

View file

@ -22,14 +22,14 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaSearchQueryOptions;
/**
* This generator is for the case where a new concept is being added for an object property other than research/subject areas where the
* This generator is for the case where a new concept is being added for an object property other than research/subject areas where the
* default object property form generator would work instead of the generator for managing concepts.
* In this case, we don't want the dropdown list for types for "add a new item of this type" to show concept subclasses, so we are overriding
* the fields to just include the Concept class.
*/
public class AddConceptThroughObjectPropertyGenerator extends DefaultObjectPropertyFormGenerator implements EditConfigurationGenerator {
private Log log = LogFactory.getLog(AddConceptThroughObjectPropertyGenerator.class);
private Log log = LogFactory.getLog(AddConceptThroughObjectPropertyGenerator.class);
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
@ -44,7 +44,7 @@ public class AddConceptThroughObjectPropertyGenerator extends DefaultObjectPrope
}
return editConfig;
}
private HashMap<String, String> getCreateNewTypesOptions(VitroRequest vreq) {
HashMap<String, String> options = new HashMap<String, String>();
List<VClass> rangeTypes = getRangeTypes(vreq);
@ -53,7 +53,7 @@ public class AddConceptThroughObjectPropertyGenerator extends DefaultObjectPrope
}
return options;
}
//We will override range types as well so that autocomplete and other fields dependent on range
//will only consider the main concept type to be the range type
@Override
@ -73,44 +73,44 @@ public class AddConceptThroughObjectPropertyGenerator extends DefaultObjectPrope
if (rangeUri != null) {
VClass rangeVClass = ctxDaoFact.getVClassDao().getVClassByURI(rangeUri);
if (!rangeVClass.isUnion()) {
types.add(rangeVClass);
types.add(rangeVClass);
} else {
types.addAll(rangeVClass.getUnionComponents());
}
return types;
} else {
//This should never happen
//This should never happen
log.warn("Range not found for this property so employing SKOS concept class");
String vclassURI = "http://www.w3.org/2004/02/skos/core#Concept";
VClass rangeVClass = ctxDaoFact.getVClassDao().getVClassByURI(vclassURI);
types.add(rangeVClass);
}
return types;
}
}
//Should override the method in default object property
private String getTemplate(
VitroRequest vreq) {
String acObjectPropertyTemplate = "addConceptThroughObjectPropertyAutoComplete.ftl";
String objectPropertyTemplate = "addConceptThroughObjectPropertyForm.ftl";
String template = objectPropertyTemplate;
if( doAutoComplete )
template = acObjectPropertyTemplate;
return template;
}
@Override
protected void setFields(EditConfigurationVTwo editConfiguration, VitroRequest vreq, String predicateUri, List<VClass> rangeTypes) throws Exception {
FieldVTwo field = new FieldVTwo();
field.setName("objectVar");
field.setName("objectVar");
List<String> validators = new ArrayList<String>();
validators.add("nonempty");
field.setValidators(validators);
if( ! doAutoComplete ){
List<String> types = new ArrayList<String>();
for(VClass v: rangeTypes) {
@ -125,11 +125,11 @@ public class AddConceptThroughObjectPropertyGenerator extends DefaultObjectPrope
}else{
field.setOptions(null);
}
Map<String, FieldVTwo> fields = new HashMap<String, FieldVTwo>();
fields.put(field.getName(), field);
fields.put(field.getName(), field);
editConfiguration.setFields(fields);
}
}
}

View file

@ -24,8 +24,8 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.
/**
Custom form for adding or editing a webpage associated with an individual. The primary page,
ManageWebpagesForIndividual, should forward to this page if: (a) we are adding a new page, or
(b) an edit link in the Manage Webpages view has been clicked. But right now (a) is not implemented.
ManageWebpagesForIndividual, should forward to this page if: (a) we are adding a new page, or
(b) an edit link in the Manage Webpages view has been clicked. But right now (a) is not implemented.
*/
@ -40,41 +40,41 @@ public class AddEditWebpageFormGenerator extends BaseEditConfigurationGenerator
prepare(vreq, config);
return config;
}
//Have broken this method down into two portions to allow for overriding of edit configuration
//without having to copy the entire method and before prepare is called
protected EditConfigurationVTwo setupConfig(VitroRequest vreq, HttpSession session) throws Exception{
protected EditConfigurationVTwo setupConfig(VitroRequest vreq, HttpSession session) throws Exception{
EditConfigurationVTwo config = new EditConfigurationVTwo();
config.setTemplate(this.getTemplate());
initBasics(config, vreq);
initPropertyParameters(vreq, session, config);
initObjectPropForm(config, vreq);
initObjectPropForm(config, vreq);
String linkUri = getLinkUri(vreq);
String domainUri = vreq.getParameter("domainUri");
String vcardIndividualType = "http://www.w3.org/2006/vcard/ns#Kind";
config.setVarNameForSubject("subject");
config.setVarNameForObject("vcard");
config.addNewResource("vcard", DEFAULT_NS_FOR_NEW_RESOURCE);
config.addNewResource("link", DEFAULT_NS_FOR_NEW_RESOURCE);
config.setN3Required(list( this.getN3ForWebpage(), N3_FOR_URLTYPE ));
config.setN3Optional(list( N3_FOR_ANCHOR, N3_FOR_RANK));
config.addUrisInScope("webpageProperty", list( "http://purl.obolibrary.org/obo/ARG_2000028" ));
config.addUrisInScope("inverseProperty", list( "http://purl.obolibrary.org/obo/ARG_2000029" ));
config.addUrisInScope("linkUrlPredicate", list( "http://www.w3.org/2006/vcard/ns#url" ));
config.addUrisInScope("linkLabelPredicate", list( "http://www.w3.org/2000/01/rdf-schema#label" ));
config.addUrisInScope("rankPredicate", list( core + "rank"));
config.addUrisInScope("vcardType", list( vcardIndividualType ));
if ( config.isUpdate() ) {
config.addUrisInScope("link", list( linkUri ));
}
@ -87,45 +87,45 @@ public class AddEditWebpageFormGenerator extends BaseEditConfigurationGenerator
}
}
config.addSparqlForAdditionalUrisInScope("vcard", individualVcardQuery);
config.setUrisOnForm("urlType");
config.setLiteralsOnForm(list("url","label","rank"));
config.addSparqlForExistingLiteral("url", URL_QUERY);
config.addSparqlForExistingLiteral("label", ANCHOR_QUERY);
config.addSparqlForExistingLiteral("rank", MAX_RANK_QUERY);
config.addSparqlForExistingUris("urlType", URLTYPE_QUERY);
config.addField(new FieldVTwo().
setName("url").
setValidators(list("nonempty", "datatype:"+XSD.anyURI.toString(), "httpUrl")).
setRangeDatatypeUri(XSD.anyURI.toString()));
config.addField( new FieldVTwo().
setName("urlType").
setValidators( list("nonempty") ).
setOptions(
setOptions(
new ChildVClassesWithParent("http://www.w3.org/2006/vcard/ns#URL")));
config.addField(new FieldVTwo().
setName("label"));
config.addField(new FieldVTwo().
setName("rank").
setRangeDatatypeUri(XSD.xint.toString()));
config.addFormSpecificData("newRank",
getMaxRank( EditConfigurationUtils.getObjectUri(vreq),
config.addFormSpecificData("newRank",
getMaxRank( EditConfigurationUtils.getObjectUri(vreq),
EditConfigurationUtils.getSubjectUri(vreq), vreq )
+ 1 );
config.addValidator(new AntiXssValidation());
//might be null
config.addFormSpecificData("subjectName", getName( config, vreq));
return config;
}
/** may be null */
private Object getName(EditConfigurationVTwo config, VitroRequest vreq) {
Individual ind = vreq.getWebappDaoFactory().getIndividualDao().getIndividualByURI(config.getSubjectUri());
@ -136,40 +136,40 @@ public class AddEditWebpageFormGenerator extends BaseEditConfigurationGenerator
}
/* ********* N3 Assertions *********** */
static String N3_FOR_WEBPAGE =
static String N3_FOR_WEBPAGE =
"?subject ?webpageProperty ?vcard . \n"+
"?vcard ?inverseProperty ?subject . \n"+
"?vcard a ?vcardType . \n" +
"?vcard <http://www.w3.org/2006/vcard/ns#hasURL> ?link ."+
"?link a <http://www.w3.org/2006/vcard/ns#URL> . \n" +
"?link ?linkUrlPredicate ?url .";
"?link ?linkUrlPredicate ?url .";
static String N3_FOR_URLTYPE =
"?link a ?urlType .";
static String N3_FOR_ANCHOR =
"?link ?linkLabelPredicate ?label .";
static String N3_FOR_RANK =
static String N3_FOR_RANK =
"?link ?rankPredicate ?rank .";
/* *********** SPARQL queries for existing values ************** */
static String URL_QUERY =
static String URL_QUERY =
"SELECT ?urlExisting WHERE { ?link ?linkUrlPredicate ?urlExisting }";
static String URLTYPE_QUERY =
static String URLTYPE_QUERY =
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
"SELECT ?linkClassExisting WHERE { ?link vitro:mostSpecificType ?linkClassExisting }";
static String ANCHOR_QUERY =
static String ANCHOR_QUERY =
"SELECT ?labelExisting WHERE { ?link ?linkLabelPredicate ?labelExisting }";
static String RANK_QUERY =
"SELECT ?rankExisting WHERE { ?link ?rankPredicate ?rankExisting }";
static String core = "http://vivoweb.org/ontology/core#";
static String individualVcardQuery =
"SELECT ?existingVcard WHERE { \n" +
"?subject <http://purl.obolibrary.org/obo/ARG_2000028> ?existingVcard . \n" +
@ -177,7 +177,7 @@ public class AddEditWebpageFormGenerator extends BaseEditConfigurationGenerator
/* Note on ordering by rank in sparql: if there is a non-integer value on a link, that will be returned,
* since it's ranked highest. Preventing that would require getting all the ranks and sorting in Java,
* throwing out non-int values.
* throwing out non-int values.
*/
private static String MAX_RANK_QUERY = ""
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
@ -187,23 +187,23 @@ public class AddEditWebpageFormGenerator extends BaseEditConfigurationGenerator
+ " ?vcard vcard:hasURL ?link . \n"
+ " ?link core:rank ?rank .\n"
+ "} ORDER BY DESC(?rank) LIMIT 1";
private int getMaxRank(String objectUri, String subjectUri, VitroRequest vreq) {
int maxRank = 0; // default value
if (objectUri == null) { // adding new webpage
int maxRank = 0; // default value
if (objectUri == null) { // adding new webpage
String queryStr = QueryUtils.subUriForQueryVar(this.getMaxRankQueryStr(), "subject", subjectUri);
log.debug("Query string is: " + queryStr);
try {
ResultSet results = QueryUtils.getQueryResults(queryStr, vreq);
if (results != null && results.hasNext()) { // there is at most one result
QuerySolution soln = results.next();
QuerySolution soln = results.next();
RDFNode node = soln.get("rank");
if (node != null && node.isLiteral()) {
// node.asLiteral().getInt() won't return an xsd:string that
// node.asLiteral().getInt() won't return an xsd:string that
// can be parsed as an int.
int rank = Integer.parseInt(node.asLiteral().getLexicalForm());
if (rank > maxRank) {
if (rank > maxRank) {
log.debug("setting maxRank to " + rank);
maxRank = rank;
}
@ -217,11 +217,11 @@ public class AddEditWebpageFormGenerator extends BaseEditConfigurationGenerator
}
return maxRank;
}
protected String getTemplate() {
return formTemplate;
}
protected String getMaxRankQueryStr() {
return MAX_RANK_QUERY;
}
@ -238,8 +238,8 @@ public class AddEditWebpageFormGenerator extends BaseEditConfigurationGenerator
String rangeUri = (String) vreq.getParameter("rangeUri");
String generatorName = "edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.ManageWebpagesForIndividualGenerator";
String editUrl = EditConfigurationUtils.getEditUrlWithoutContext(vreq);
String returnPath = editUrl + "?subjectUri=" + UrlBuilder.urlEncode(subjectUri) +
"&predicateUri=" + UrlBuilder.urlEncode(predicateUri) +
String returnPath = editUrl + "?subjectUri=" + UrlBuilder.urlEncode(subjectUri) +
"&predicateUri=" + UrlBuilder.urlEncode(predicateUri) +
"&editForm=" + UrlBuilder.urlEncode(generatorName);
if(domainUri != null && !domainUri.isEmpty()) {
returnPath += "&domainUri=" + UrlBuilder.urlEncode(domainUri);
@ -248,12 +248,12 @@ public class AddEditWebpageFormGenerator extends BaseEditConfigurationGenerator
returnPath += "&rangeUri=" + UrlBuilder.urlEncode(rangeUri);
}
return returnPath;
}
private String getLinkUri(VitroRequest vreq) {
String linkUri = vreq.getParameter("linkUri");
String linkUri = vreq.getParameter("linkUri");
return linkUri;
}
}

View file

@ -6,36 +6,36 @@ import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ChildVClassesOptions;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldOptions;
/**
* Generates the edit configuration for adding a Role to a Person.
Stage one is selecting the type of the non-person thing
associated with the Role with the intention of reducing the
* Generates the edit configuration for adding a Role to a Person.
Stage one is selecting the type of the non-person thing
associated with the Role with the intention of reducing the
number of Individuals that the user has to select from.
Stage two is selecting the non-person Individual to associate
with the Role.
with the Role.
This is intended to create a set of statements like:
?person core:hasResearchActivityRole ?newRole.
?newRole rdf:type core:ResearchActivityRole ;
?newRole rdf:type core:ResearchActivityRole ;
roleToActivityPredicate ?someActivity .
?someActivity rdf:type core:ResearchActivity .
?someActivity rdfs:label "activity title" .
Each subclass of the abstract two stage Generator class will have the option of overriding certain
methods, and must always implement the following methods:
getRoleType
getRoleActivityTypeOptionsType
getRoleActivityTypeObjectClassUri
getRoleActivityTypeLiteralOptions
*
*/
public class AddEditorRoleToPersonGenerator extends AddRoleToPersonTwoStageGenerator {
private static String TEMPLATE = "addEditorRoleToPerson.ftl";
private static String OPTION_CLASS_URI = "http://purl.org/ontology/bibo/Collection";
@Override
String getTemplate(){ return TEMPLATE; }
@ -49,12 +49,12 @@ public class AddEditorRoleToPersonGenerator extends AddRoleToPersonTwoStageGener
return new ChildVClassesOptions(OPTION_CLASS_URI)
.setDefaultOptionLabel("Select type");
}
/** Do not show the role label field for the AddEditorRoleToPerson form */
@Override
@Override
boolean isShowRoleLabelField() { return true; }
/*
/*
* Use the methods below to change the date/time precision in the
* custom form associated with this generator. When not used, the
* precision will be YEAR. The other precisons are MONTH, DAY, HOUR,
@ -70,5 +70,5 @@ public class AddEditorRoleToPersonGenerator extends AddRoleToPersonTwoStageGener
String precision = VitroVocabulary.Precision.DAY.uri();
return precision;
}
*/
*/
}

View file

@ -35,9 +35,9 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.
/**
* This is a slightly unusual generator that is used by Manage Editors on
* information resources.
* information resources.
*
* It is intended to always be an add, and never an update.
* It is intended to always be an add, and never an update.
*/
public class AddEditorsToInformationResourceGenerator extends VivoBaseGenerator implements EditConfigurationGenerator {
public static Log log = LogFactory.getLog(AddEditorsToInformationResourceGenerator.class);
@ -45,7 +45,7 @@ public class AddEditorsToInformationResourceGenerator extends VivoBaseGenerator
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
HttpSession session) {
EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo();
EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo();
initBasics(editConfiguration, vreq);
initPropertyParameters(vreq, session, editConfiguration);
@ -53,21 +53,21 @@ public class AddEditorsToInformationResourceGenerator extends VivoBaseGenerator
setUrlToReturnTo(editConfiguration, vreq);
//set variable names
editConfiguration.setVarNameForSubject("infoResource");
editConfiguration.setVarNameForPredicate("predicate");
editConfiguration.setVarNameForObject("editorshipUri");
editConfiguration.setVarNameForSubject("infoResource");
editConfiguration.setVarNameForPredicate("predicate");
editConfiguration.setVarNameForObject("editorshipUri");
// Required N3
editConfiguration.setN3Required( list( getN3NewEditorship() ) );
editConfiguration.setN3Required( list( getN3NewEditorship() ) );
// Optional N3
editConfiguration.setN3Optional( generateN3Optional());
// Optional N3
editConfiguration.setN3Optional( generateN3Optional());
editConfiguration.addNewResource("editorshipUri", DEFAULT_NS_TOKEN);
editConfiguration.addNewResource("newPerson", DEFAULT_NS_TOKEN);
editConfiguration.addNewResource("vcardPerson", DEFAULT_NS_TOKEN);
editConfiguration.addNewResource("vcardName", DEFAULT_NS_TOKEN);
//In scope
setUrisAndLiteralsInScope(editConfiguration, vreq);
@ -87,130 +87,130 @@ public class AddEditorsToInformationResourceGenerator extends VivoBaseGenerator
//Adding additional data, specifically edit mode
addFormSpecificData(editConfiguration, vreq);
editConfiguration.addValidator(new AntiXssValidation());
//NOITCE this generator does not run prepare() since it
//NOITCE this generator does not run prepare() since it
//is never an update and has no SPARQL for existing
return editConfiguration;
}
private void setUrlToReturnTo(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
editConfiguration.setUrlPatternToReturnTo(EditConfigurationUtils.getFormUrlWithoutContext(vreq));
editConfiguration.setUrlPatternToReturnTo(EditConfigurationUtils.getFormUrlWithoutContext(vreq));
}
/***N3 strings both required and optional***/
public String getN3PrefixString() {
return "@prefix core: <" + vivoCore + "> .\n" +
return "@prefix core: <" + vivoCore + "> .\n" +
"@prefix foaf: <" + foaf + "> . \n" ;
}
private String getN3NewEditorship() {
return getN3PrefixString() +
"?editorshipUri a core:Editorship ;\n" +
" core:relates ?infoResource .\n" +
return getN3PrefixString() +
"?editorshipUri a core:Editorship ;\n" +
" core:relates ?infoResource .\n" +
"?infoResource core:relatedBy ?editorshipUri .";
}
private String getN3EditorshipRank() {
return getN3PrefixString() +
return getN3PrefixString() +
"?editorshipUri core:editorRank ?rank .";
}
//first name, middle name, last name, and new perseon for new editor being created, and n3 for existing person
//if existing person selected as editor
public List<String> generateN3Optional() {
return list(
getN3NewPersonFirstName() ,
getN3NewPersonMiddleName(),
getN3NewPersonLastName(),
getN3NewPersonLastName(),
getN3NewPerson(),
getN3EditorshipRank(),
getN3ForExistingPerson());
}
private String getN3NewPersonFirstName() {
return getN3PrefixString() +
return getN3PrefixString() +
"@prefix vcard: <http://www.w3.org/2006/vcard/ns#> . \n" +
"?newPerson <http://purl.obolibrary.org/obo/ARG_2000028> ?vcardPerson . \n" +
"?vcardPerson <http://purl.obolibrary.org/obo/ARG_2000029> ?newPerson . \n" +
"?vcardPerson a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardPerson a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardPerson vcard:hasName ?vcardName . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName vcard:givenName ?firstName .";
}
private String getN3NewPersonMiddleName() {
return getN3PrefixString() +
return getN3PrefixString() +
"@prefix vcard: <http://www.w3.org/2006/vcard/ns#> . \n" +
"?newPerson <http://purl.obolibrary.org/obo/ARG_2000028> ?vcardPerson . \n" +
"?vcardPerson <http://purl.obolibrary.org/obo/ARG_2000029> ?newPerson . \n" +
"?vcardPerson a vcard:Individual . \n" +
"?vcardPerson a vcard:Individual . \n" +
"?vcardPerson vcard:hasName ?vcardName . \n" +
"?vcardName a vcard:Name . \n" +
"?vcardName a vcard:Name . \n" +
"?vcardName <http://vivoweb.org/ontology/core#middleName> ?middleName .";
}
private String getN3NewPersonLastName() {
return getN3PrefixString() +
return getN3PrefixString() +
"@prefix vcard: <http://www.w3.org/2006/vcard/ns#> . \n" +
"?newPerson <http://purl.obolibrary.org/obo/ARG_2000028> ?vcardPerson . \n" +
"?vcardPerson <http://purl.obolibrary.org/obo/ARG_2000029> ?newPerson . \n" +
"?vcardPerson a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardPerson a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardPerson vcard:hasName ?vcardName . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName vcard:familyName ?lastName .";
}
private String getN3NewPerson() {
return getN3PrefixString() +
"?newPerson a foaf:Person ;\n" +
"<" + RDFS.label.getURI() + "> ?label .\n" +
"?editorshipUri core:relates ?newPerson .\n" +
return getN3PrefixString() +
"?newPerson a foaf:Person ;\n" +
"<" + RDFS.label.getURI() + "> ?label .\n" +
"?editorshipUri core:relates ?newPerson .\n" +
"?newPerson core:relatedBy ?editorshipUri . ";
}
private String getN3ForExistingPerson() {
return getN3PrefixString() +
"?editorshipUri core:relates ?personUri .\n" +
return getN3PrefixString() +
"?editorshipUri core:relates ?personUri .\n" +
"?personUri core:relatedBy ?editorshipUri .";
}
/** Get new resources */
//A new editorship uri will always be created when an editor is added
//A new person may be added if a person not in the system will be added as editor
private Map<String, String> generateNewResources(VitroRequest vreq) {
HashMap<String, String> newResources = new HashMap<String, String>();
private Map<String, String> generateNewResources(VitroRequest vreq) {
HashMap<String, String> newResources = new HashMap<String, String>();
newResources.put("editorshipUri", DEFAULT_NS_TOKEN);
newResources.put("newPerson", DEFAULT_NS_TOKEN);
newResources.put("vcardPerson", DEFAULT_NS_TOKEN);
newResources.put("vcardName", DEFAULT_NS_TOKEN);
return newResources;
}
/** Set URIS and Literals In Scope and on form and supporting methods */
/** Set URIS and Literals In Scope and on form and supporting methods */
private void setUrisAndLiteralsInScope(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
//Uris in scope always contain subject and predicate
HashMap<String, List<String>> urisInScope = new HashMap<String, List<String>>();
urisInScope.put(editConfiguration.getVarNameForSubject(),
urisInScope.put(editConfiguration.getVarNameForSubject(),
Arrays.asList(new String[]{editConfiguration.getSubjectUri()}));
urisInScope.put(editConfiguration.getVarNameForPredicate(),
urisInScope.put(editConfiguration.getVarNameForPredicate(),
Arrays.asList(new String[]{editConfiguration.getPredicateUri()}));
editConfiguration.setUrisInScope(urisInScope);
//no literals in scope
//no literals in scope
}
public void setUrisAndLiteralsOnForm(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
List<String> urisOnForm = new ArrayList<String>();
List<String> urisOnForm = new ArrayList<String>();
//If an existing person is being used as an editor, need to get the person uri
urisOnForm.add("personUri");
editConfiguration.setUrisOnform(urisOnForm);
//for person who is not in system, need to add first name, last name and middle name
//Also need to store editorship rank and label of editor
List<String> literalsOnForm = list("firstName",
@ -219,10 +219,10 @@ public class AddEditorsToInformationResourceGenerator extends VivoBaseGenerator
"rank",
"label");
editConfiguration.setLiteralsOnForm(literalsOnForm);
}
/** Set SPARQL Queries and supporting methods. */
private void setSparqlQueries(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
}
/** Set SPARQL Queries and supporting methods. */
private void setSparqlQueries(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
//Sparql queries are all empty for existing values
//This form is different from the others that it gets multiple editors on the same page
//and that information will be queried and stored in the additional form specific data
@ -232,12 +232,12 @@ public class AddEditorsToInformationResourceGenerator extends VivoBaseGenerator
editConfiguration.setSparqlForAdditionalUrisInScope(new HashMap<String, String>());
editConfiguration.setSparqlForAdditionalLiteralsInScope(new HashMap<String, String>());
}
/**
*
*
* Set Fields and supporting methods
*/
public void setFields(EditConfigurationVTwo editConfiguration, VitroRequest vreq, String predicateUri) {
setLabelField(editConfiguration);
setFirstNameField(editConfiguration);
@ -246,7 +246,7 @@ public class AddEditorsToInformationResourceGenerator extends VivoBaseGenerator
setRankField(editConfiguration);
setPersonUriField(editConfiguration);
}
private void setLabelField(EditConfigurationVTwo editConfiguration) {
editConfiguration.addField(new FieldVTwo().
setName("label").
@ -352,13 +352,13 @@ public class AddEditorsToInformationResourceGenerator extends VivoBaseGenerator
+ "WHERE { \n"
+ "?subject core:relatedBy ?editorshipURI . \n"
+ "?editorshipURI a core:Editorship . \n"
+ "?editorshipURI core:relates ?editorURI . \n"
+ "?editorshipURI core:relates ?editorURI . \n"
+ "?editorURI a foaf:Person . \n"
+ "OPTIONAL { ?editorURI rdfs:label ?editorName } \n"
+ "OPTIONAL { ?editorshipURI core:rank ?rank } \n"
+ "OPTIONAL { ?editorshipURI core:rank ?rank } \n"
+ "} ORDER BY ?rank";
private List<EditorshipInfo> getExistingEditorships(String subjectUri, VitroRequest vreq) {
RDFService rdfService = vreq.getRDFService();
@ -387,7 +387,7 @@ public class AddEditorsToInformationResourceGenerator extends VivoBaseGenerator
}
} catch (Exception e) {
log.error(e, e);
}
}
log.debug("editorships = " + editorships);
return getEditorshipInfo(editorships);
}
@ -399,22 +399,22 @@ public class AddEditorsToInformationResourceGenerator extends VivoBaseGenerator
+ " ?editorship a core:Editorship . \n"
+ " ?editorship core:rank ?rank .\n"
+ "} ORDER BY DESC(?rank) LIMIT 1";
private int getMaxRank(String subjectUri, VitroRequest vreq) {
int maxRank = 0; // default value
int maxRank = 0; // default value
String queryStr = QueryUtils.subUriForQueryVar(this.getMaxRankQueryStr(), "subject", subjectUri);
log.debug("maxRank query string is: " + queryStr);
try {
ResultSet results = QueryUtils.getQueryResults(queryStr, vreq);
if (results != null && results.hasNext()) { // there is at most one result
QuerySolution soln = results.next();
QuerySolution soln = results.next();
RDFNode node = soln.get("rank");
if (node != null && node.isLiteral()) {
// node.asLiteral().getInt() won't return an xsd:string that
// node.asLiteral().getInt() won't return an xsd:string that
// can be parsed as an int.
int rank = Integer.parseInt(node.asLiteral().getLexicalForm());
if (rank > maxRank) {
if (rank > maxRank) {
log.debug("setting maxRank to " + rank);
maxRank = rank;
}
@ -468,8 +468,8 @@ public class AddEditorsToInformationResourceGenerator extends VivoBaseGenerator
//Editor information for editorship node
private String editorUri;
private String editorName;
public EditorshipInfo(String inputEditorshipUri,
public EditorshipInfo(String inputEditorshipUri,
String inputEditorshipName,
String inputEditorUri,
String inputEditorName) {
@ -479,25 +479,25 @@ public class AddEditorsToInformationResourceGenerator extends VivoBaseGenerator
editorName = inputEditorName;
}
//Getters - specifically required for Freemarker template's access to POJO
public String getEditorshipUri() {
return editorshipUri;
}
public String getEditorshipName() {
return editorshipName;
}
public String getEditorUri() {
return editorUri;
}
public String getEditorName() {
return editorName;
}
}
static final String DEFAULT_NS_TOKEN=null; //null forces the default NS
protected String getMaxRankQueryStr() {

View file

@ -32,12 +32,12 @@ import edu.cornell.mannlib.vitro.webapp.utils.generators.EditModeUtils;
public class AddEditorshipToPersonGenerator extends VivoBaseGenerator implements
EditConfigurationGenerator {
public AddEditorshipToPersonGenerator() {}
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) throws Exception {
if( EditConfigurationUtils.getObjectUri(vreq) == null ){
return doAddNew(vreq,session);
}else{
@ -47,7 +47,7 @@ public class AddEditorshipToPersonGenerator extends VivoBaseGenerator implements
private EditConfigurationVTwo doSkipToDocument(VitroRequest vreq) {
Individual editorshipNode = EditConfigurationUtils.getObjectIndividual(vreq);
//try to get the document
String documentQueryStr = "SELECT ?obj \n" +
"WHERE { <" + editorshipNode.getURI() + "> <http://vivoweb.org/ontology/core#relates> ?obj . \n" +
@ -60,8 +60,8 @@ public class AddEditorshipToPersonGenerator extends VivoBaseGenerator implements
return doBadEditorshipNoPub( vreq );
}else if( rs.size() > 1 ){
return doBadEditorshipMultiplePubs(vreq);
}else{
//skip to document
}else{
//skip to document
RDFNode objNode = rs.next().get("obj");
if (!objNode.isResource() || objNode.isAnon()) {
return doBadEditorshipNoPub( vreq );
@ -77,38 +77,38 @@ public class AddEditorshipToPersonGenerator extends VivoBaseGenerator implements
protected EditConfigurationVTwo doAddNew(VitroRequest vreq,
HttpSession session) throws Exception {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
initObjectPropForm(conf, vreq);
conf.setTemplate("addEditorshipToPerson.ftl");
conf.setVarNameForSubject("person");
conf.setVarNameForPredicate("predicate");
conf.setVarNameForObject("editorship");
conf.setN3Required( Arrays.asList( n3ForNewEditorship ) );
conf.setN3Optional( Arrays.asList( n3ForNewDocumentAssertion,
n3ForExistingDocumentAssertion ) );
conf.addNewResource("editorship", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("newDocument", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.setUrisOnform(Arrays.asList("existingDocument", "documentType"));
conf.setLiteralsOnForm(Arrays.asList("documentLabel", "documentLabelDisplay" ));
conf.addSparqlForExistingLiteral("documentLabel", documentLabelQuery);
conf.addSparqlForExistingUris("documentType", documentTypeQuery);
conf.addSparqlForExistingUris("existingDocument", existingDocumentQuery);
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("documentType").
setValidators( list("nonempty") ).
setOptions( new ConstantFieldOptions("documentType", getDocumentTypeLiteralOptions() ))
setOptions( new ConstantFieldOptions("documentType", getDocumentTypeLiteralOptions() ))
);
conf.addField( new FieldVTwo().
@ -123,61 +123,61 @@ public class AddEditorshipToPersonGenerator extends VivoBaseGenerator implements
conf.addValidator(new AntiXssValidation());
addFormSpecificData(conf, vreq);
prepare(vreq, conf);
return conf;
}
/* N3 assertions */
final static String n3ForNewEditorship =
"@prefix vivo: <" + vivoCore + "> . \n" +
final static String n3ForNewEditorship =
"@prefix vivo: <" + vivoCore + "> . \n" +
"?person ?predicate ?editorship . \n" +
"?editorship a vivo:Editorship . \n" +
"?editorship a vivo:Editorship . \n" +
"?editorship vivo:relates ?person . " ;
final static String n3ForNewDocumentAssertion =
"@prefix vivo: <" + vivoCore + "> . \n" +
"?editorship vivo:relates ?newDocument . \n" +
"?newDocument vivo:editedBy ?editorship . \n" +
"?newDocument a ?documentType . \n" +
final static String n3ForNewDocumentAssertion =
"@prefix vivo: <" + vivoCore + "> . \n" +
"?editorship vivo:relates ?newDocument . \n" +
"?newDocument vivo:editedBy ?editorship . \n" +
"?newDocument a ?documentType . \n" +
"?newDocument <" + label + "> ?documentLabel. " ;
final static String n3ForExistingDocumentAssertion =
"@prefix vivo: <" + vivoCore + "> . \n" +
"?editorship vivo:relates ?existingDocument . \n" +
"?existingDocument vivo:editedBy ?editorship . \n" +
final static String n3ForExistingDocumentAssertion =
"@prefix vivo: <" + vivoCore + "> . \n" +
"?editorship vivo:relates ?existingDocument . \n" +
"?existingDocument vivo:editedBy ?editorship . \n" +
"?existingDocument a ?documentType . " ;
/* Queries for editing an existing entry */
final static String documentTypeQuery =
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
"PREFIX vivo: <" + vivoCore + "> . \n" +
"PREFIX bibo: <http://purl.org/ontology/bibo/> . \n" +
"SELECT ?documentType WHERE { \n" +
" ?editorship vivo:relates ?existingDocument . \n" +
" ?existingDocument a <http://purl.obolibrary.org/obo/IAO_0000030> . \n" +
" ?existingDocument vitro:mostSpecificType ?documentType . \n" +
"PREFIX vivo: <" + vivoCore + "> . \n" +
"PREFIX bibo: <http://purl.org/ontology/bibo/> . \n" +
"SELECT ?documentType WHERE { \n" +
" ?editorship vivo:relates ?existingDocument . \n" +
" ?existingDocument a <http://purl.obolibrary.org/obo/IAO_0000030> . \n" +
" ?existingDocument vitro:mostSpecificType ?documentType . \n" +
"}";
final static String documentLabelQuery =
final static String documentLabelQuery =
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
"PREFIX vivo: <" + vivoCore + "> . \n" +
"PREFIX bibo: <http://purl.org/ontology/bibo/> . \n" +
"SELECT ?documentLabel WHERE { \n" +
" ?editorship vivo:relates ?existingDocument . \n" +
" ?existingDocument a <http://purl.obolibrary.org/obo/IAO_0000030> . \n" +
" ?existingDocument <" + label + "> ?documentLabel . \n" +
"PREFIX vivo: <" + vivoCore + "> . \n" +
"PREFIX bibo: <http://purl.org/ontology/bibo/> . \n" +
"SELECT ?documentLabel WHERE { \n" +
" ?editorship vivo:relates ?existingDocument . \n" +
" ?existingDocument a <http://purl.obolibrary.org/obo/IAO_0000030> . \n" +
" ?existingDocument <" + label + "> ?documentLabel . \n" +
"}";
final static String existingDocumentQuery =
final static String existingDocumentQuery =
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
"PREFIX vivo: <" + vivoCore + "> . \n" +
"PREFIX bibo: <http://purl.org/ontology/bibo/> . \n" +
"SELECT existingDocument WHERE { \n" +
" ?editorship vivo:relates ?existingDocument . \n" +
" ?existingDocument a <http://purl.obolibrary.org/obo/IAO_0000030> . \n" +
"PREFIX vivo: <" + vivoCore + "> . \n" +
"PREFIX bibo: <http://purl.org/ontology/bibo/> . \n" +
"SELECT existingDocument WHERE { \n" +
" ?editorship vivo:relates ?existingDocument . \n" +
" ?existingDocument a <http://purl.obolibrary.org/obo/IAO_0000030> . \n" +
"}";
//Adding form specific data such as edit mode
@ -202,7 +202,7 @@ public class AddEditorshipToPersonGenerator extends VivoBaseGenerator implements
// TODO Auto-generated method stub
return null;
}
private List<List<String>> getDocumentTypeLiteralOptions() {
List<List<String>> literalOptions = new ArrayList<List<String>>();
literalOptions.add(list("http://purl.org/ontology/bibo/Book", "Book"));

View file

@ -21,95 +21,95 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.
public class AddFullNameToPersonGenerator extends VivoBaseGenerator implements
EditConfigurationGenerator {
private Log log = LogFactory.getLog(AddFullNameToPersonGenerator.class);
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
HttpSession session) throws Exception {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
String fullNameUri = getFullNameUri(vreq);
initObjectPropForm(conf, vreq);
String fullNameUri = getFullNameUri(vreq);
conf.setTemplate("addFullNameToPerson.ftl");
conf.setVarNameForSubject("person");
conf.setVarNameForPredicate("predicate");
conf.setVarNameForObject("individualVcard");
conf.setN3Required( Arrays.asList( n3ForNewName ) );
conf.setN3Optional( Arrays.asList( firstNameAssertion, middleNameAssertion, lastNameAssertion, suffixAssertion, prefixAssertion ) );
conf.addNewResource("fullName", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("individualVcard", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.setLiteralsOnForm(Arrays.asList("firstName", "middleName", "lastName", "suffix", "prefix" ));
conf.addSparqlForExistingLiteral("firstName", firstNameQuery);
conf.addSparqlForExistingLiteral("middleName", middleNameQuery);
conf.addSparqlForExistingLiteral("lastName", lastNameQuery);
conf.addSparqlForExistingLiteral("suffix", suffixQuery);
conf.addSparqlForExistingLiteral("prefix", prefixQuery);
conf.addSparqlForAdditionalUrisInScope("individualVcard", individualVcardQuery);
if ( conf.isUpdate() ) {
HashMap<String, List<String>> urisInScope = new HashMap<String, List<String>>();
urisInScope.put("fullName", Arrays.asList(new String[]{fullNameUri}));
conf.addUrisInScope(urisInScope);
}
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("firstName")
.setRangeDatatypeUri( XSD.xstring.toString() ).
setValidators( list("nonempty") ));
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("middleName")
.setRangeDatatypeUri( XSD.xstring.toString()) );
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("lastName")
.setRangeDatatypeUri( XSD.xstring.toString() ).
setValidators( list("nonempty") ));
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("suffix")
.setRangeDatatypeUri( XSD.xstring.toString()) );
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("prefix")
.setRangeDatatypeUri( XSD.xstring.toString()) );
conf.addValidator(new AntiXssValidation());
prepare(vreq, conf);
return conf;
}
/* N3 assertions */
final static String n3ForNewName =
final static String n3ForNewName =
"?person <http://purl.obolibrary.org/obo/ARG_2000028> ?individualVcard . \n" +
"?individualVcard a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?individualVcard a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?individualVcard <http://purl.obolibrary.org/obo/ARG_2000029> ?person . \n" +
"?individualVcard <http://www.w3.org/2006/vcard/ns#hasName> ?fullName . \n" +
"?fullName a <http://www.w3.org/2006/vcard/ns#Name> . " ;
final static String firstNameAssertion =
"?fullName a <http://www.w3.org/2006/vcard/ns#Name> . " ;
final static String firstNameAssertion =
"?fullName <http://www.w3.org/2006/vcard/ns#givenName> ?firstName .";
final static String middleNameAssertion =
final static String middleNameAssertion =
"?fullName <http://vivoweb.org/ontology/core#middleName> ?middleName .";
final static String lastNameAssertion =
final static String lastNameAssertion =
"?fullName <http://www.w3.org/2006/vcard/ns#familyName> ?lastName .";
final static String suffixAssertion =
final static String suffixAssertion =
"?fullName <http://www.w3.org/2006/vcard/ns#honorificSuffix> ?suffix .";
final static String prefixAssertion =
final static String prefixAssertion =
"?fullName <http://www.w3.org/2006/vcard/ns#honorificPrefix> ?prefix .";
/* Queries for editing an existing entry */
@ -119,29 +119,29 @@ public class AddFullNameToPersonGenerator extends VivoBaseGenerator implements
"?person <http://purl.obolibrary.org/obo/ARG_2000028> ?existingIndividualVcard . \n" +
"}";
final static String firstNameQuery =
final static String firstNameQuery =
"SELECT ?existingFirstName WHERE {\n"+
"?fullName <http://www.w3.org/2006/vcard/ns#givenName> ?existingFirstName . }";
final static String middleNameQuery =
final static String middleNameQuery =
"SELECT ?existingMiddleName WHERE {\n"+
"?fullName <http://vivoweb.org/ontology/core#middleName> ?existingMiddleName . }";
final static String lastNameQuery =
final static String lastNameQuery =
"SELECT ?existingLastName WHERE {\n"+
"?fullName <http://www.w3.org/2006/vcard/ns#familyName> ?existingLastName . }";
final static String suffixQuery =
final static String suffixQuery =
"SELECT ?existingSuffix WHERE {\n"+
"?fullName <http://www.w3.org/2006/vcard/ns#honorificSuffix> ?existingSuffix . }";
final static String prefixQuery =
final static String prefixQuery =
"SELECT ?existingPrefix WHERE {\n"+
"?fullName <http://www.w3.org/2006/vcard/ns#honorificPrefix> ?existingPrefix . }";
private String getFullNameUri(VitroRequest vreq) {
String fullNameUri = vreq.getParameter("fullNameUri");
String fullNameUri = vreq.getParameter("fullNameUri");
return fullNameUri;
}
}

View file

@ -37,60 +37,60 @@ import edu.cornell.mannlib.vitro.webapp.utils.generators.EditModeUtils;
/**
* Custom form for adding a grant to an person for the predicates hasCo-PrincipalInvestigatorRole
and hasPrincipalInvestigatorRole.
*
*/
public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator {
private Log log = LogFactory.getLog(AddGrantRoleToPersonGenerator.class);
private String subjectUri = null;
private String predicateUri = null;
private String objectUri = null;
private String template = "addGrantRoleToPerson.ftl";
//Types of options to populate drop-down for types for the "right side" of the role
public static enum RoleActivityOptionTypes {
VCLASSGROUP,
CHILD_VCLASSES,
HARDCODED_LITERALS
}
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) {
EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo();
//process subject, predicate, object parameters
this.initProcessParameters(vreq, session, editConfiguration);
//Assumes this is a simple case of subject predicate var
editConfiguration.setN3Required(this.generateN3Required(vreq));
//n3 optional
editConfiguration.setN3Optional(this.generateN3Optional(vreq));
//Todo: what do new resources depend on here?
//In original form, these variables start off empty
editConfiguration.setNewResources(generateNewResources(vreq));
//In scope
this.setUrisAndLiteralsInScope(editConfiguration, vreq);
//on Form
this.setUrisAndLiteralsOnForm(editConfiguration, vreq);
editConfiguration.setFilesOnForm(new ArrayList<String>());
//Sparql queries
this.setSparqlQueries(editConfiguration, vreq);
//set fields
setFields(editConfiguration, vreq, EditConfigurationUtils.getPredicateUri(vreq));
// No need to put in session here b/c put in session within edit request dispatch controller instead
//placing in session depends on having edit key which is handled in edit request dispatch controller
// editConfiguration.putConfigInSession(editConfiguration, session);
prepareForUpdate(vreq, session, editConfiguration);
//Form title and submit label now moved to edit configuration template
//TODO: check if edit configuration template correct place to set those or whether
//additional methods here should be used and reference instead, e.g. edit configuration template could call
@ -99,7 +99,7 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
setTemplate(editConfiguration, vreq);
//Set edit key
setEditKey(editConfiguration, vreq);
//Add validators
editConfiguration.addValidator(new DateTimeIntervalValidationVTwo("startField","endField") );
editConfiguration.addValidator(new AntiXssValidation());
@ -109,18 +109,18 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
addFormSpecificData(editConfiguration, vreq);
return editConfiguration;
}
private void setEditKey(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
String editKey = EditConfigurationUtils.getEditKey(vreq);
String editKey = EditConfigurationUtils.getEditKey(vreq);
editConfiguration.setEditKey(editKey);
}
protected void setTemplate(EditConfigurationVTwo editConfiguration,
VitroRequest vreq) {
editConfiguration.setTemplate(template);
}
//Initialize setup: process parameters
@ -131,11 +131,11 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
subjectUri = EditConfigurationUtils.getSubjectUri(vreq);
predicateUri = EditConfigurationUtils.getPredicateUri(vreq);
editConfiguration.setFormUrl(formUrl);
editConfiguration.setUrlPatternToReturnTo("/individual");
editConfiguration.setVarNameForSubject("person");
editConfiguration.setSubjectUri(subjectUri);
editConfiguration.setEntityToReturnTo(subjectUri);
@ -143,28 +143,28 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
editConfiguration.setPredicateUri(predicateUri);
//by definition, this is an object property
objectUri = EditConfigurationUtils.getObjectUri(vreq);
this.processObjectPropForm(vreq, editConfiguration);
}
this.processObjectPropForm(vreq, editConfiguration);
}
private void processObjectPropForm(VitroRequest vreq, EditConfigurationVTwo editConfiguration) {
editConfiguration.setVarNameForObject("role");
editConfiguration.setVarNameForObject("role");
editConfiguration.setObject(objectUri);
//this needs to be set for the editing to be triggered properly, otherwise the 'prepare' method
//pretends this is a data property editing statement and throws an error
//TODO: Check if null in case no object uri exists but this is still an object property
//TODO: Check if null in case no object uri exists but this is still an object property
}
/*
* N3 Required and Optional Generators as well as supporting methods
* N3 Required and Optional Generators as well as supporting methods
*/
private String getPrefixesString() {
//TODO: Include dynamic way of including this
return "@prefix core: <http://vivoweb.org/ontology/core#> .";
}
//TODO: Check if single string or multiple strings - check rdfslabel form etc. for prefix
//processing
private List<String> generateN3Required(VitroRequest vreq) {
@ -173,8 +173,8 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
n3ForEdit.add(editString);
return n3ForEdit;
}
private List<String> generateN3Optional(VitroRequest vreq) {
List<String> n3Optional = new ArrayList<String>();
//n3 for new grant
@ -187,61 +187,61 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
n3Optional.addAll(getN3ForStart());
//N3 For End
n3Optional.addAll(getN3ForEnd());
return n3Optional;
return n3Optional;
}
public String getN3ForGrantRole(VitroRequest vreq) {
String editString = getPrefixesString();
editString += "?person ?rolePredicate ?role .";
editString += "?role a <" + getRoleType(vreq) + "> .";
return editString;
}
public String getN3ForNewGrant(VitroRequest vreq) {
String editString = getPrefixesString();
editString += "?role <" + getRoleToGrantPredicate(vreq) + "> ?grant .";
editString += "?grant a core:Grant . ";
editString += "?person core:relatedBy ?grant . ";
editString += "?grant core:relates ?person . ";
editString += "?person core:relatedBy ?grant . ";
editString += "?grant core:relates ?person . ";
editString += "?grant <" + getGrantToRolePredicate(vreq) + "> ?role .";
editString += "?grant <" + RDFS.label.getURI() + "> ?grantLabel .";
return editString;
}
public String getN3ForExistingGrant(VitroRequest vreq) {
String editString = getPrefixesString();
editString += "?person core:relatedBy ?existingGrant . ";
editString += "?existingGrant core:relates ?person . ";
editString += "?role <" + getRoleToGrantPredicate(vreq) + "> ?existingGrant . ";
editString += "?person core:relatedBy ?existingGrant . ";
editString += "?existingGrant core:relates ?person . ";
editString += "?role <" + getRoleToGrantPredicate(vreq) + "> ?existingGrant . ";
editString += "?existingGrant <" + getGrantToRolePredicate(vreq) + "> ?role .";
return editString;
}
//Method b/c used in two locations, n3 optional and n3 assertions
private List<String> getN3ForStart() {
List<String> n3ForStart = new ArrayList<String>();
n3ForStart.add("?role <" + getRoleToIntervalURI() + "> ?intervalNode ." +
"?intervalNode <" + RDF.type.getURI() + "> <" + getIntervalTypeURI() + "> ." +
"?intervalNode <" + getIntervalToStartURI() + "> ?startNode ." +
"?startNode <" + RDF.type.getURI() + "> <" + getDateTimeValueTypeURI() + "> ." +
"?startNode <" + getDateTimeValueURI() + "> ?startField-value ." +
n3ForStart.add("?role <" + getRoleToIntervalURI() + "> ?intervalNode ." +
"?intervalNode <" + RDF.type.getURI() + "> <" + getIntervalTypeURI() + "> ." +
"?intervalNode <" + getIntervalToStartURI() + "> ?startNode ." +
"?startNode <" + RDF.type.getURI() + "> <" + getDateTimeValueTypeURI() + "> ." +
"?startNode <" + getDateTimeValueURI() + "> ?startField-value ." +
"?startNode <" + getDateTimePrecisionURI() + "> ?startField-precision .");
return n3ForStart;
}
private List<String> getN3ForEnd() {
List<String> n3ForEnd = new ArrayList<String>();
n3ForEnd.add("?role <" + getRoleToIntervalURI() + "> ?intervalNode . " +
"?intervalNode <" + RDF.type.getURI() + "> <" + getIntervalTypeURI() + "> ." +
"?intervalNode <" + getIntervalToEndURI() + "> ?endNode ." +
"?endNode <" + RDF.type.getURI() + "> <" + getDateTimeValueTypeURI() + "> ." +
"?endNode <" + getDateTimeValueURI() + "> ?endField-value ." +
n3ForEnd.add("?role <" + getRoleToIntervalURI() + "> ?intervalNode . " +
"?intervalNode <" + RDF.type.getURI() + "> <" + getIntervalTypeURI() + "> ." +
"?intervalNode <" + getIntervalToEndURI() + "> ?endNode ." +
"?endNode <" + RDF.type.getURI() + "> <" + getDateTimeValueTypeURI() + "> ." +
"?endNode <" + getDateTimeValueURI() + "> ?endField-value ." +
"?endNode <" + getDateTimePrecisionURI() + "> ?endField-precision .");
return n3ForEnd;
}
/*
* Get new resources
*/
@ -256,22 +256,22 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
newResources.put("endNode", defaultNamespace + "individual");
return newResources;
}
/*
* Set URIS and Literals In Scope and on form and supporting methods
*/
private void setUrisAndLiteralsInScope(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
HashMap<String, List<String>> urisInScope = new HashMap<String, List<String>>();
//note that at this point the subject, predicate, and object var parameters have already been processed
//these two were always set when instantiating an edit configuration object from json,
//although the json itself did not specify subject/predicate as part of uris in scope
urisInScope.put(editConfiguration.getVarNameForSubject(),
urisInScope.put(editConfiguration.getVarNameForSubject(),
Arrays.asList(new String[]{editConfiguration.getSubjectUri()}));
urisInScope.put(editConfiguration.getVarNameForPredicate(),
urisInScope.put(editConfiguration.getVarNameForPredicate(),
Arrays.asList(new String[]{editConfiguration.getPredicateUri()}));
//Setting role type
urisInScope.put("roleType",
urisInScope.put("roleType",
Arrays.asList(new String[]{getRoleType(vreq)}));
//Setting inverse role predicate
urisInScope.put("inverseRolePredicate", getInversePredicate(vreq));
@ -281,7 +281,7 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
//with existing values for variables
editConfiguration.setLiteralsInScope(new HashMap<String, List<Literal>>());
}
private List<String> getInversePredicate(VitroRequest vreq) {
List<String> inversePredicateArray = new ArrayList<String>();
ObjectProperty op = EditConfigurationUtils.getObjectProperty(vreq);
@ -292,8 +292,8 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
}
//n3 should look as follows
//?subject ?predicate ?objectVar
//?subject ?predicate ?objectVar
private void setUrisAndLiteralsOnForm(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
List<String> urisOnForm = new ArrayList<String>();
List<String> literalsOnForm = new ArrayList<String>();
@ -306,25 +306,25 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
literalsOnForm.add("grantLabelDisplay");
editConfiguration.setLiteralsOnForm(literalsOnForm);
}
/**
* Set SPARQL Queries and supporting methods
*/
private void setSparqlQueries(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
//Sparql queries defining retrieval of literals etc.
editConfiguration.setSparqlForAdditionalLiteralsInScope(new HashMap<String, String>());
Map<String, String> urisInScope = new HashMap<String, String>();
editConfiguration.setSparqlForAdditionalUrisInScope(urisInScope);
editConfiguration.setSparqlForExistingLiterals(generateSparqlForExistingLiterals(vreq));
editConfiguration.setSparqlForExistingUris(generateSparqlForExistingUris(vreq));
}
//Get page uri for object
private HashMap<String, String> generateSparqlForExistingUris(VitroRequest vreq) {
HashMap<String, String> map = new HashMap<String, String>();
@ -337,7 +337,7 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
map.put("endField-precision", getEndPrecisionQuery(vreq));
return map;
}
private String getEndPrecisionQuery(VitroRequest vreq) {
@ -345,7 +345,7 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
"?role <" + getRoleToIntervalURI() + "> ?intervalNode ." +
"?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + getIntervalTypeURI() + "> ." +
"?intervalNode <" + getIntervalToEndURI() + "> ?endNode ." +
"?endNode <" + VitroVocabulary.RDF_TYPE + "> <" + getDateTimeValueTypeURI() + "> . " +
"?endNode <" + VitroVocabulary.RDF_TYPE + "> <" + getDateTimeValueTypeURI() + "> . " +
"?endNode <" + getDateTimePrecisionURI() + "> ?existingEndPrecision . }";
return query;
}
@ -355,7 +355,7 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
"?role <" + getRoleToIntervalURI() + "> ?intervalNode ." +
"?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + getIntervalTypeURI() + "> ." +
"?intervalNode <" + getIntervalToStartURI() + "> ?startNode ." +
"?startNode <" + VitroVocabulary.RDF_TYPE + "> <" + getDateTimeValueTypeURI() + "> . " +
"?startNode <" + VitroVocabulary.RDF_TYPE + "> <" + getDateTimeValueTypeURI() + "> . " +
"?startNode <" + getDateTimePrecisionURI() + "> ?existingStartPrecision . }";
return query;
}
@ -365,27 +365,27 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
"?role <" + getRoleToIntervalURI() + "> ?intervalNode ."+
"?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + getIntervalTypeURI() + "> ."+
" ?intervalNode <" + getIntervalToEndURI() + "> ?existingEndNode . "+
"?existingEndNode <" + VitroVocabulary.RDF_TYPE + "> <" + getDateTimeValueTypeURI() + "> .}";
"?existingEndNode <" + VitroVocabulary.RDF_TYPE + "> <" + getDateTimeValueTypeURI() + "> .}";
return query;
}
private String getStartNodeQuery(VitroRequest vreq) {
String query = "SELECT ?existingStartNode WHERE {"+
"?role <" + getRoleToIntervalURI() + "> ?intervalNode ."+
"?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + getIntervalTypeURI() + "> ."+
"?intervalNode <" + getIntervalToStartURI() + "> ?existingStartNode . "+
"?existingStartNode <" + VitroVocabulary.RDF_TYPE + "> <" + getDateTimeValueTypeURI() + "> .}";
String query = "SELECT ?existingStartNode WHERE {"+
"?role <" + getRoleToIntervalURI() + "> ?intervalNode ."+
"?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + getIntervalTypeURI() + "> ."+
"?intervalNode <" + getIntervalToStartURI() + "> ?existingStartNode . "+
"?existingStartNode <" + VitroVocabulary.RDF_TYPE + "> <" + getDateTimeValueTypeURI() + "> .}";
return query;
}
private String getIntervalNodeQuery(VitroRequest vreq) {
String query = "SELECT ?existingIntervalNode WHERE { " +
"?role <" + getRoleToIntervalURI() + "> ?existingIntervalNode . " +
String query = "SELECT ?existingIntervalNode WHERE { " +
"?role <" + getRoleToIntervalURI() + "> ?existingIntervalNode . " +
" ?existingIntervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + getIntervalTypeURI() + "> . }";
return query;
}
private HashMap<String, String> generateSparqlForExistingLiterals(VitroRequest vreq) {
HashMap<String, String> map = new HashMap<String, String>();
@ -395,55 +395,55 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
map.put("endField-value", getExistingEndDateQuery(vreq));
return map;
}
private String getGrantLabelQuery(VitroRequest vreq) {
String query = "PREFIX core: <" + getVivoCoreNamespace() + ">" +
String query = "PREFIX core: <" + getVivoCoreNamespace() + ">" +
"PREFIX rdfs: <" + RDFS.getURI() + "> \n";
String roleToGrantPredicate = getRoleToGrantPredicate(vreq);
query += "SELECT ?existingGrantLabel WHERE { \n" +
"?role <" + roleToGrantPredicate + "> ?existingGrant . \n" +
query += "SELECT ?existingGrantLabel WHERE { \n" +
"?role <" + roleToGrantPredicate + "> ?existingGrant . \n" +
"?existingGrant rdfs:label ?existingGrantLabel . }";
return query;
}
private String getExistingGrantQuery(VitroRequest vreq) {
String query = "PREFIX core: <" + getVivoCoreNamespace() + ">" +
String query = "PREFIX core: <" + getVivoCoreNamespace() + ">" +
"PREFIX rdfs: <" + RDFS.getURI() + "> \n";
String roleToGrantPredicate = getRoleToGrantPredicate(vreq);
query += "SELECT ?existingGrant WHERE { \n" +
query += "SELECT ?existingGrant WHERE { \n" +
"?role <" + roleToGrantPredicate + "> ?existingGrant . }";
return query;
}
private String getExistingEndDateQuery(VitroRequest vreq) {
String query = " SELECT ?existingEndDate WHERE {\n" +
"?role <" + getRoleToIntervalURI() + "> ?intervalNode .\n" +
"?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + getIntervalTypeURI() + "> .\n" +
"?intervalNode <" + getIntervalToEndURI() + "> ?endNode .\n" +
"?endNode <" + VitroVocabulary.RDF_TYPE + "> <" + getDateTimeValueTypeURI() + "> .\n" +
String query = " SELECT ?existingEndDate WHERE {\n" +
"?role <" + getRoleToIntervalURI() + "> ?intervalNode .\n" +
"?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + getIntervalTypeURI() + "> .\n" +
"?intervalNode <" + getIntervalToEndURI() + "> ?endNode .\n" +
"?endNode <" + VitroVocabulary.RDF_TYPE + "> <" + getDateTimeValueTypeURI() + "> .\n" +
"?endNode <" + getDateTimeValueURI() + "> ?existingEndDate . }";
return query;
}
private String getExistingStartDateQuery(VitroRequest vreq) {
String query = "SELECT ?existingDateStart WHERE {\n" +
"?role <" + getRoleToIntervalURI() + "> ?intervalNode .\n" +
"?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + getIntervalTypeURI() + "> .\n" +
"?intervalNode <" + getIntervalToStartURI() + "> ?startNode .\n" +
"?startNode <" + VitroVocabulary.RDF_TYPE + "> <" + getDateTimeValueTypeURI() + "> .\n" +
String query = "SELECT ?existingDateStart WHERE {\n" +
"?role <" + getRoleToIntervalURI() + "> ?intervalNode .\n" +
"?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + getIntervalTypeURI() + "> .\n" +
"?intervalNode <" + getIntervalToStartURI() + "> ?startNode .\n" +
"?startNode <" + VitroVocabulary.RDF_TYPE + "> <" + getDateTimeValueTypeURI() + "> .\n" +
"?startNode <" + getDateTimeValueURI() + "> ?existingDateStart . }";
return query;
}
/**
*
*
* Set Fields and supporting methods
*/
private void setFields(EditConfigurationVTwo editConfiguration, VitroRequest vreq, String predicateUri) {
Map<String, FieldVTwo> fields = new HashMap<String, FieldVTwo>();
//Multiple fields
@ -455,20 +455,20 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
getEndField(editConfiguration, vreq, fields);
editConfiguration.setFields(fields);
}
private void getGrantField(EditConfigurationVTwo editConfiguration,
VitroRequest vreq, Map<String, FieldVTwo> fields) {
String fieldName = "grant";
FieldVTwo field = new FieldVTwo();
field.setName(fieldName);
//queryForExisting is not being used anywhere in Field
List<String> validators = new ArrayList<String>();
field.setValidators(validators);
fields.put(field.getName(), field);
field.setValidators(validators);
fields.put(field.getName(), field);
}
private void getGrantLabelField(EditConfigurationVTwo editConfiguration,
@ -476,45 +476,45 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
String fieldName = "grantLabel";
//get range data type uri and range language
String stringDatatypeUri = XSD.xstring.toString();
FieldVTwo field = new FieldVTwo();
field.setName(fieldName);
//queryForExisting is not being used anywhere in Field
//Not really interested in validators here
List<String> validators = new ArrayList<String>();
validators.add("datatype:" + stringDatatypeUri);
field.setValidators(validators);
field.setValidators(validators);
fields.put(field.getName(), field);
fields.put(field.getName(), field);
}
private void getGrantLabelDisplayField(EditConfigurationVTwo editConfiguration,
VitroRequest vreq, Map<String, FieldVTwo> fields) {
FieldVTwo field = new FieldVTwo();
String fieldName = "grantLabelDisplay";
field.setName(fieldName);
String stringDatatypeUri = XSD.xstring.toString();
field.setRangeDatatypeUri(null);
fields.put(field.getName(), field);
FieldVTwo field = new FieldVTwo();
String fieldName = "grantLabelDisplay";
field.setName(fieldName);
String stringDatatypeUri = XSD.xstring.toString();
field.setRangeDatatypeUri(null);
fields.put(field.getName(), field);
}
//Need if returning from an invalid submission
private void getExistingGrantField(
EditConfigurationVTwo editConfiguration, VitroRequest vreq,
Map<String, FieldVTwo> fields) {
String fieldName = "existingGrant";
FieldVTwo field = new FieldVTwo();
field.setName(fieldName);
field.setName(fieldName);
//queryForExisting is not being used anywhere in Field
fields.put(field.getName(), field);
fields.put(field.getName(), field);
}
private void getStartField(EditConfigurationVTwo editConfiguration,
@ -522,16 +522,16 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
String fieldName = "startField";
FieldVTwo field = new FieldVTwo();
field.setName(fieldName);
field.setName(fieldName);
//This logic was originally after edit configuration object created from json in original jsp
field.setEditElement(
new DateTimeWithPrecisionVTwo(field,
new DateTimeWithPrecisionVTwo(field,
VitroVocabulary.Precision.YEAR.uri(),
VitroVocabulary.Precision.NONE.uri()));
VitroVocabulary.Precision.NONE.uri()));
fields.put(field.getName(), field);
}
private void getEndField(EditConfigurationVTwo editConfiguration,
@ -539,19 +539,19 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
String fieldName = "endField";
FieldVTwo field = new FieldVTwo();
field.setName(fieldName);
field.setName(fieldName);
List<String> validators = new ArrayList<String>();
field.setValidators(validators);
//Set edit element
field.setEditElement(
new DateTimeWithPrecisionVTwo(field,
new DateTimeWithPrecisionVTwo(field,
VitroVocabulary.Precision.YEAR.uri(),
VitroVocabulary.Precision.NONE.uri()));
fields.put(field.getName(), field);
}
/**
@ -560,9 +560,9 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
* @param session - the HTTP session
* @param editConfiguration - Edit configuration
*/
private void prepareForUpdate(VitroRequest vreq, HttpSession session, EditConfigurationVTwo editConfiguration) {
//Here, retrieve model from
//Here, retrieve model from
OntModel model = ModelAccess.on(session.getServletContext()).getOntModel();
//Object property by definition
String objectUri = EditConfigurationUtils.getObjectUri(vreq);
@ -574,9 +574,9 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
editConfiguration.prepareForNonUpdate( model );
}
}
/**Methods for checking edit mode **
*
*
*/
public EditMode getEditMode(VitroRequest vreq) {
List<String> roleToGrantPredicates = getPossibleRoleToGrantPredicates();
@ -586,15 +586,15 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
private boolean isAddMode(VitroRequest vreq) {
return EditModeUtils.isAddMode(getEditMode(vreq));
}
private boolean isEditMode(VitroRequest vreq) {
return EditModeUtils.isEditMode(getEditMode(vreq));
}
private boolean isRepairMode(VitroRequest vreq) {
return EditModeUtils.isRepairMode(getEditMode(vreq));
}
/**
* Methods that are REQUIRED to be implemented in subclasses
**/
@ -606,12 +606,12 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
}
else if(rangeUri.equals(getCoPrincipalInvestigatorURI())) {
return getVivoOntologyCoreNamespace() + "CoPrincipalInvestigatorRole";
}
}
else {
return getVivoOntologyCoreNamespace() + "InvestigatorRole";
}
}
private Object getCoPrincipalInvestigatorURI() {
return getVivoOntologyCoreNamespace() + "CoPrincipalInvestigatorRole";
}
@ -631,27 +631,27 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
* Methods with default values that may be overwritten when required by a subclass
* Both Default value and method that can be overwritten are included below
**/
public boolean isShowRoleLabelField(VitroRequest vreq) {
return true;
}
//This has a default value, but note that even that will not be used
//in the update with realized in or contributes to
//Overridden when need be in subclassed generator
//Also note that for now we're going to actually going to return a
//Also note that for now we're going to actually going to return a
//placeholder value by default
public String getRoleToGrantPredicate(VitroRequest vreq) {
ObjectProperty predicate = ModelUtils.getPropertyForRoleInClass(getGrantType(), vreq.getWebappDaoFactory());
return predicate.getURI();
}
public String getGrantToRolePredicate(VitroRequest vreq) {
ObjectProperty predicate = ModelUtils.getPropertyForRoleInClass(getGrantType(), vreq.getWebappDaoFactory());
return predicate.getURIInverse();
}
public String getGrantType() {
return "http://vivoweb.org/ontology/core#Grant";
}
@ -662,65 +662,65 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
public String getDefaultgrantToRolePredicate() {
return "http://vivoweb.org/ontology/core#relates";
}
//roleToGrantPredicate
public String getDefaultroleToGrantPredicate() {
return "http://purl.obolibrary.org/obo/BFO_0000054";
}
public List<String> getPossibleRoleToGrantPredicates() {
return ModelUtils.getPossiblePropertiesForRole();
}
public List<String> getPossibleGrantToRolePredicates() {
return ModelUtils.getPossibleInversePropertiesForRole();
}
/**
* Methods to return URIS for various predicates
**/
public String getVivoCoreNamespace() {
return "http://vivoweb.org/ontology/core#";
}
public String getRoleToIntervalURI() {
return getVivoCoreNamespace() + "dateTimeInterval";
}
public String getIntervalTypeURI() {
return getVivoCoreNamespace() + "DateTimeInterval";
}
public String getIntervalToStartURI() {
return getVivoCoreNamespace() + "start";
}
public String getIntervalToEndURI() {
return getVivoCoreNamespace() + "end";
}
public String getStartYearPredURI() {
return getVivoCoreNamespace() + "startYear";
}
public String getEndYearPredURI() {
return getVivoCoreNamespace() + "endYear";
}
public String getDateTimeValueTypeURI() {
return getVivoCoreNamespace() + "DateTimeValue";
}
public String getDateTimePrecisionURI() {
return getVivoCoreNamespace() + "dateTimePrecision";
}
public String getDateTimeValueURI() {
return getVivoCoreNamespace() + "dateTime";
}
//Form specific data
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
@ -731,23 +731,23 @@ public class AddGrantRoleToPersonGenerator implements EditConfigurationGenerator
//Put in the fact that we require field
editConfiguration.setFormSpecificData(formSpecificData);
}
public String getSparqlForAcFilter(VitroRequest vreq) {
String subject = EditConfigurationUtils.getSubjectUri(vreq);
String predicate = EditConfigurationUtils.getPredicateUri(vreq);
String query = "PREFIX core:<" + getVivoCoreNamespace() + "> " +
"SELECT ?grantUri WHERE { " +
String query = "PREFIX core:<" + getVivoCoreNamespace() + "> " +
"SELECT ?grantUri WHERE { " +
"<" + subject + "> <" + predicate + "> ?grantRole ." +
"?grantRole <" + getRoleToGrantPredicate(vreq) + "> ?grantUri . }";
return query;
}
private String getRangeUri(VitroRequest vreq) {
String rangeUri = vreq.getParameter("rangeUri");
String rangeUri = vreq.getParameter("rangeUri");
return rangeUri;
}
}

View file

@ -1,54 +1,54 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ChildVClassesOptions;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldOptions;
public class AddHeadOfRoleToPersonGenerator extends AddRoleToPersonTwoStageGenerator {
private static String template = "addHeadOfRoleToPerson.ftl";
private static String OPTION_CLASS_URI = "http://xmlns.com/foaf/0.1/Organization";
//Should this be overridden
@Override
String getTemplate() {
return template;
}
@Override
String getRoleType() {
return "http://vivoweb.org/ontology/core#LeaderRole";
}
/** Head Of role involves hard-coded options for the "right side" of the role or activity */
@Override
FieldOptions getRoleActivityFieldOptions(VitroRequest vreq) throws Exception {
return new
ChildVClassesOptions(OPTION_CLASS_URI)
.setDefaultOptionLabel("Select type");
}
@Override
boolean isShowRoleLabelField(){return true;}
/*
* Use the methods below to change the date/time precision in the
* custom form associated with this generator. When not used, the
* precision will be YEAR. The other precisons are MONTH, DAY, HOUR,
* MINUTE, TIME and NONE.
*/
/*
public String getStartDatePrecision() {
String precision = VitroVocabulary.Precision.MONTH.uri();
return precision;
}
public String getEndDatePrecision() {
String precision = VitroVocabulary.Precision.DAY.uri();
return precision;
}
*/
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ChildVClassesOptions;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldOptions;
public class AddHeadOfRoleToPersonGenerator extends AddRoleToPersonTwoStageGenerator {
private static String template = "addHeadOfRoleToPerson.ftl";
private static String OPTION_CLASS_URI = "http://xmlns.com/foaf/0.1/Organization";
//Should this be overridden
@Override
String getTemplate() {
return template;
}
@Override
String getRoleType() {
return "http://vivoweb.org/ontology/core#LeaderRole";
}
/** Head Of role involves hard-coded options for the "right side" of the role or activity */
@Override
FieldOptions getRoleActivityFieldOptions(VitroRequest vreq) throws Exception {
return new
ChildVClassesOptions(OPTION_CLASS_URI)
.setDefaultOptionLabel("Select type");
}
@Override
boolean isShowRoleLabelField(){return true;}
/*
* Use the methods below to change the date/time precision in the
* custom form associated with this generator. When not used, the
* precision will be YEAR. The other precisons are MONTH, DAY, HOUR,
* MINUTE, TIME and NONE.
*/
/*
public String getStartDatePrecision() {
String precision = VitroVocabulary.Precision.MONTH.uri();
return precision;
}
public String getEndDatePrecision() {
String precision = VitroVocabulary.Precision.DAY.uri();
return precision;
}
*/
}

View file

@ -7,19 +7,19 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ConstantField
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldOptions;
public class AddMemberRoleToPersonGenerator extends AddRoleToPersonTwoStageGenerator {
private static String template = "addMemberRoleToPerson.ftl";
private static String VCLASS_URI = "http://xmlns.com/foaf/0.1/Organization";
@Override
String getTemplate() {
return template;
}
}
@Override
String getRoleType() {
String getRoleType() {
return "http://vivoweb.org/ontology/core#MemberRole";
}
@Override
FieldOptions getRoleActivityFieldOptions(VitroRequest vreq) throws Exception {
return new ConstantFieldOptions(
@ -58,11 +58,11 @@ public class AddMemberRoleToPersonGenerator extends AddRoleToPersonTwoStageGener
"http://purl.obolibrary.org/obo/ERO_0000565","Technology Transfer Office",
"http://vivoweb.org/ontology/core#University","University");
}
@Override
boolean isShowRoleLabelField(){return true;}
/*
@Override
boolean isShowRoleLabelField(){return true;}
/*
* Use the methods below to change the date/time precision in the
* custom form associated with this generator. When not used, the
* precision will be YEAR. The other precisons are MONTH, DAY, HOUR,
@ -78,5 +78,5 @@ public class AddMemberRoleToPersonGenerator extends AddRoleToPersonTwoStageGener
String precision = VitroVocabulary.Precision.DAY.uri();
return precision;
}
*/
*/
}

View file

@ -17,46 +17,46 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.
public class AddOrcidIdToPersonGenerator extends VivoBaseGenerator implements
EditConfigurationGenerator {
private Log log = LogFactory.getLog(AddOrcidIdToPersonGenerator.class);
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
HttpSession session) throws Exception {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
initObjectPropForm(conf, vreq);
conf.setTemplate("addOrcidIdToPerson.ftl");
conf.setVarNameForSubject("person");
conf.setVarNameForPredicate("predicate");
conf.setVarNameForObject("orcidId");
conf.setN3Required( Arrays.asList( n3ForOrcidId ) );
conf.setUrisOnform(Arrays.asList("orcidId"));
conf.addSparqlForExistingUris("orcidId", orcidIdQuery);
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("orcidId").
setValidators( list("nonempty") ));
conf.addValidator(new AntiXssValidation());
prepare(vreq, conf);
return conf;
}
/* N3 assertions */
final static String n3ForOrcidId =
final static String n3ForOrcidId =
"@prefix owl: <http://www.w3.org/2002/07/owl#> .\n"+
"?person <http://vivoweb.org/ontology/core#orcidId> ?orcidId . \n" +
"?orcidId a owl:Thing . " ;
"?orcidId a owl:Thing . " ;
/* Queries for editing an existing entry */
final static String orcidIdQuery =

View file

@ -7,10 +7,10 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ConstantField
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldOptions;
public class AddOrganizerRoleToPersonGenerator extends AddRoleToPersonTwoStageGenerator {
private static String template = "addOrganizerRoleToPerson.ftl";
@Override
String getTemplate() {
return template;
@ -20,7 +20,7 @@ public class AddOrganizerRoleToPersonGenerator extends AddRoleToPersonTwoStageGe
String getRoleType() {
return "http://vivoweb.org/ontology/core#OrganizerRole";
}
//Organizer role involves hard-coded options for the "right side" of the role or activity
@Override
FieldOptions getRoleActivityFieldOptions(VitroRequest vreq) throws Exception {
@ -48,7 +48,7 @@ public class AddOrganizerRoleToPersonGenerator extends AddRoleToPersonTwoStageGe
boolean isShowRoleLabelField() {
return false;
}
/*
/*
* Use the methods below to change the date/time precision in the
* custom form associated with this generator. When not used, the
* precision will be YEAR. The other precisons are MONTH, DAY, HOUR,
@ -64,5 +64,5 @@ public class AddOrganizerRoleToPersonGenerator extends AddRoleToPersonTwoStageGe
String precision = VitroVocabulary.Precision.DAY.uri();
return precision;
}
*/
*/
}

View file

@ -7,17 +7,17 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ConstantField
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldOptions;
public class AddOutreachProviderRoleToPersonGenerator extends AddRoleToPersonTwoStageGenerator {
private static String template = "addOutreachProviderRoleToPerson.ftl";
private static String OPTION_CLASS_URI = "http://xmlns.com/foaf/0.1/Organization";
@Override
String getTemplate() {
return template;
}
@Override
String getRoleType() {
String getRoleType() {
return "http://vivoweb.org/ontology/core#OutreachProviderRole";
}
@ -79,8 +79,8 @@ public class AddOutreachProviderRoleToPersonGenerator extends AddRoleToPersonTwo
@Override
boolean isShowRoleLabelField(){return true;}
/*
/*
* Use the methods below to change the date/time precision in the
* custom form associated with this generator. When not used, the
* precision will be YEAR. The other precisons are MONTH, DAY, HOUR,
@ -96,5 +96,5 @@ public class AddOutreachProviderRoleToPersonGenerator extends AddRoleToPersonTwo
String precision = VitroVocabulary.Precision.DAY.uri();
return precision;
}
*/
*/
}

View file

@ -37,49 +37,49 @@ public class AddPresenterRoleToPersonGenerator extends VivoBaseGenerator impleme
final static String dateTimeValueType = vivoCore + "DateTimeValue";
final static String dateTimeValue = vivoCore + "dateTime";
final static String dateTimePrecision = vivoCore + "dateTimePrecision";
public AddPresenterRoleToPersonGenerator() {}
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
HttpSession session) throws Exception {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
initObjectPropForm(conf, vreq);
conf.setTemplate("addPresenterRoleToPerson.ftl");
conf.setVarNameForSubject("person");
conf.setVarNameForPredicate("predicate");
conf.setVarNameForObject("role");
conf.setN3Required( Arrays.asList( n3ForNewRole ) );
conf.setN3Optional( Arrays.asList( n3ForRoleLabelAssertion,
n3ForNewPresentation,
n3ForExistingPresentation,
n3ForNewConferenceNewPres,
n3ForNewConferenceExistingPres,
n3ForExistingConferenceNewPres,
n3ForExistingConferenceExistingPres,
n3ForStart,
n3ForNewPresentation,
n3ForExistingPresentation,
n3ForNewConferenceNewPres,
n3ForNewConferenceExistingPres,
n3ForExistingConferenceNewPres,
n3ForExistingConferenceExistingPres,
n3ForStart,
n3ForEnd ) );
conf.addNewResource("presentation", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("newConference", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("role", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("intervalNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("startNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("endNode", DEFAULT_NS_FOR_NEW_RESOURCE);
//uris in scope: none
//uris in scope: none
//literals in scope: none
conf.setUrisOnform(Arrays.asList("existingPresentation", "existingConference", "presentationType"));
conf.setLiteralsOnForm(Arrays.asList("presentationLabel", "presentationLabelDisplay", "conferenceLabel", "conferenceLabelDisplay", "roleLabel"));
conf.addSparqlForExistingLiteral("presentationLabel", presentationLabelQuery);
conf.addSparqlForExistingLiteral("conferenceLabel", conferenceLabelQuery);
conf.addSparqlForExistingLiteral("roleLabel", roleLabelQuery);
@ -94,69 +94,69 @@ public class AddPresenterRoleToPersonGenerator extends VivoBaseGenerator impleme
"intervalNode", existingIntervalNodeQuery);
conf.addSparqlForExistingUris("startNode", existingStartNodeQuery);
conf.addSparqlForExistingUris("endNode", existingEndNodeQuery);
conf.addSparqlForExistingUris("startField-precision",
conf.addSparqlForExistingUris("startField-precision",
existingStartPrecisionQuery);
conf.addSparqlForExistingUris("endField-precision",
conf.addSparqlForExistingUris("endField-precision",
existingEndPrecisionQuery);
conf.addField( new FieldVTwo(). // an autocomplete field
setName("existingPresentation")
setName("existingPresentation")
);
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("presentationLabelDisplay")
.setRangeDatatypeUri( XSD.xstring.toString() ).
setValidators( list("datatype:" + XSD.xstring.toString()) )
);
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("presentationLabel")
.setRangeDatatypeUri( XSD.xstring.toString() ).
setValidators( list("datatype:" + XSD.xstring.toString()) )
);
conf.addField( new FieldVTwo().
setName("presentationType").
setValidators( list("nonempty") ).
setOptions( new ChildVClassesWithParent(
presentationClass))
presentationClass))
);
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("roleLabel").
setRangeDatatypeUri( XSD.xstring.toString() ).
setValidators(list("datatype:" + XSD.xstring.toString())));
conf.addField( new FieldVTwo(). // an autocomplete field
setName("existingConference")
setName("existingConference")
);
conf.addField( new FieldVTwo().
setName("conferenceLabel").
setRangeDatatypeUri(XSD.xstring.toString() )
);
conf.addField( new FieldVTwo().
setName("conferenceLabelDisplay").
setRangeDatatypeUri(XSD.xstring.toString() )
);
conf.addField( new FieldVTwo().setName("startField").
setEditElement(
new DateTimeWithPrecisionVTwo(null,
setEditElement(
new DateTimeWithPrecisionVTwo(null,
VitroVocabulary.Precision.YEAR.uri(),
VitroVocabulary.Precision.NONE.uri())
)
);
conf.addField( new FieldVTwo().setName("endField").
setEditElement(
new DateTimeWithPrecisionVTwo(null,
setEditElement(
new DateTimeWithPrecisionVTwo(null,
VitroVocabulary.Precision.YEAR.uri(),
VitroVocabulary.Precision.NONE.uri())
)
);
conf.addValidator(new DateTimeIntervalValidationVTwo("startField","endField"));
conf.addValidator(new AntiXssValidation());
conf.addValidator(new AutocompleteRequiredInputValidator("existingPresentation", "presentationLabel"));
@ -165,26 +165,26 @@ public class AddPresenterRoleToPersonGenerator extends VivoBaseGenerator impleme
}
/* N3 assertions */
final static String n3ForNewRole =
"@prefix core: <" + vivoCore + "> . \n" +
final static String n3ForNewRole =
"@prefix core: <" + vivoCore + "> . \n" +
"?person <" + hasRolePred + "> ?role . \n" +
"?role a <" + roleClass + "> . \n" +
"?role a <" + roleClass + "> . \n" +
"?role <" + roleOfPred + "> ?person . ";
final static String n3ForRoleLabelAssertion =
"?role <" + label + "> ?roleLabel . ";
final static String n3ForNewPresentation =
"?role <" + roleRealizedInPred + "> ?presentation . \n" +
"?presentation <" + realizedRolePred + "> ?role . \n" +
final static String n3ForRoleLabelAssertion =
"?role <" + label + "> ?roleLabel . ";
final static String n3ForNewPresentation =
"?role <" + roleRealizedInPred + "> ?presentation . \n" +
"?presentation <" + realizedRolePred + "> ?role . \n" +
"?presentation <" + label + "> ?presentationLabel . \n" +
"?presentation a ?presentationType .";
final static String n3ForExistingPresentation =
"?role <" + roleRealizedInPred + "> ?existingPresentation . \n" +
final static String n3ForExistingPresentation =
"?role <" + roleRealizedInPred + "> ?existingPresentation . \n" +
"?existingPresentation <" + realizedRolePred + "> ?role . \n" +
"?existingPresentation a ?presentationType .";
final static String n3ForNewConferenceNewPres =
"?presentation <" + eventWithinPred + "> ?newConference . \n" +
"?newConference <" + includesEventPred + "> ?presentation . \n" +
@ -196,63 +196,63 @@ public class AddPresenterRoleToPersonGenerator extends VivoBaseGenerator impleme
"?newConference <" + includesEventPred + "> ?existingPresentation . \n" +
"?newConference a <" + conferenceClass + "> . \n" +
"?newConference <" + label + "> ?conferenceLabel .";
final static String n3ForExistingConferenceNewPres =
"?existingConference <" + includesEventPred + "> ?presentation . \n" +
"?presentation <" + eventWithinPred + "> ?existingConference . \n" +
"?presentation <" + label + "> ?presentationLabel . ";
final static String n3ForExistingConferenceExistingPres =
"?existingConference <" + includesEventPred + "> ?existingPresentation . \n" +
"?existingPresentation <" + eventWithinPred + "> ?existingConference . ";
final static String n3ForStart =
"?role <" + roleToInterval + "> ?intervalNode . \n" +
"?role <" + roleToInterval + "> ?intervalNode . \n" +
"?intervalNode a <" + intervalType + "> . \n" +
"?intervalNode <" + intervalToStart + "> ?startNode . \n" +
"?intervalNode <" + intervalToStart + "> ?startNode . \n" +
"?startNode a <" + dateTimeValueType + "> . \n" +
"?startNode <" + dateTimeValue + "> ?startField-value . \n" +
"?startNode <" + dateTimePrecision + "> ?startField-precision . \n";
final static String n3ForEnd =
"?role <" + roleToInterval + "> ?intervalNode . \n" +
"?role <" + roleToInterval + "> ?intervalNode . \n" +
"?intervalNode a <" + intervalType + "> . \n" +
"?intervalNode <" + intervalToEnd + "> ?endNode . \n" +
"?endNode a <" + dateTimeValueType + "> . \n" +
"?endNode <" + dateTimeValue + "> ?endField-value . \n" +
"?endNode <" + dateTimePrecision + "> ?endField-precision . \n";
/* Queries for editing an existing entry */
final static String roleLabelQuery =
"SELECT ?existingRoleLabel WHERE { \n" +
"?role <" + label + "> ?existingRoleLabel . }";
final static String presentationQuery =
final static String presentationQuery =
"SELECT ?existingPresentation WHERE { \n" +
"?role <" + roleRealizedInPred + "> ?existingPresentation . }";
final static String presentationLabelQuery =
"SELECT ?existingPresentationLabel WHERE { \n" +
"?role <" + roleRealizedInPred + "> ?existingPresentation . " +
"?existingPresentation <" + label + "> ?existingPresentationLabel . }";
final static String presentationTypeQuery =
final static String presentationTypeQuery =
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
"SELECT ?existingPresentationType WHERE { \n" +
"SELECT ?existingPresentationType WHERE { \n" +
"?role <" + roleRealizedInPred + "> ?existingPresentation . " +
"?existingPresentation vitro:mostSpecificType ?existingPresentationType . }";
final static String existingConferenceQuery =
final static String existingConferenceQuery =
"SELECT ?existingConference WHERE { \n" +
"?role <" + roleRealizedInPred + "> ?existingPresentation . " +
"?existingPresentation <" + eventWithinPred + "> ?existingConference . }";
final static String conferenceLabelQuery =
"SELECT ?existingConferenceLabel WHERE { \n" +
"?role <" + roleRealizedInPred + "> ?existingPresentation . " +
"?existingPresentation <" + eventWithinPred + "> ?existingConference . \n" +
"?existingConference <" + label + "> ?existingConferenceLabel . }";
final static String existingStartDateQuery =
"SELECT ?existingDateStart WHERE { \n" +
" ?role <" + roleToInterval + "> ?intervalNode . \n" +
@ -260,7 +260,7 @@ public class AddPresenterRoleToPersonGenerator extends VivoBaseGenerator impleme
" ?intervalNode <" + intervalToStart + "> ?startNode . \n" +
" ?startNode a <" + dateTimeValueType +"> . \n" +
" ?startNode <" + dateTimeValue + "> ?existingDateStart . }";
final static String existingEndDateQuery =
"SELECT ?existingEndDate WHERE { \n" +
" ?role <" + roleToInterval + "> ?intervalNode . \n" +
@ -270,39 +270,39 @@ public class AddPresenterRoleToPersonGenerator extends VivoBaseGenerator impleme
" ?endNode <" + dateTimeValue + "> ?existingEndDate . }";
final static String existingIntervalNodeQuery =
"SELECT ?existingIntervalNode WHERE { \n" +
"SELECT ?existingIntervalNode WHERE { \n" +
" ?role <" + roleToInterval + "> ?existingIntervalNode . \n" +
" ?existingIntervalNode a <" + intervalType + "> . }";
final static String existingStartNodeQuery =
final static String existingStartNodeQuery =
"SELECT ?existingStartNode WHERE { \n" +
" ?role <" + roleToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToStart + "> ?existingStartNode . \n" +
" ?intervalNode <" + intervalToStart + "> ?existingStartNode . \n" +
" ?existingStartNode a <" + dateTimeValueType + "> . } ";
final static String existingEndNodeQuery =
final static String existingEndNodeQuery =
"SELECT ?existingEndNode WHERE { \n" +
" ?role <" + roleToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToEnd + "> ?existingEndNode . \n" +
" ?existingEndNode a <" + dateTimeValueType + "> .} ";
final static String existingStartPrecisionQuery =
" ?intervalNode <" + intervalToEnd + "> ?existingEndNode . \n" +
" ?existingEndNode a <" + dateTimeValueType + "> .} ";
final static String existingStartPrecisionQuery =
"SELECT ?existingStartPrecision WHERE { \n" +
" ?role <" + roleToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToStart + "> ?startNode . \n" +
" ?startNode a <" + dateTimeValueType + "> . \n" +
" ?startNode a <" + dateTimeValueType + "> . \n" +
" ?startNode <" + dateTimePrecision + "> ?existingStartPrecision . }";
final static String existingEndPrecisionQuery =
final static String existingEndPrecisionQuery =
"SELECT ?existingEndPrecision WHERE { \n" +
" ?role <" + roleToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToEnd + "> ?endNode . \n" +
" ?endNode a <" + dateTimeValueType + "> . \n" +
" ?endNode a <" + dateTimeValueType + "> . \n" +
" ?endNode <" + dateTimePrecision + "> ?existingEndPrecision . }";
}

View file

@ -38,7 +38,7 @@ import edu.cornell.mannlib.vitro.webapp.utils.generators.EditModeUtils;
/**
* On an add/new, this will show a form, on an edit/update this will skip to the
* profile page of the publication.
* profile page of the publication.
*/
public class AddPublicationToPersonGenerator extends VivoBaseGenerator implements EditConfigurationGenerator {
@ -61,12 +61,12 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
final static String dateTimeValue = vivoCore + "dateTime";
final static String dateTimePrecision = vivoCore + "dateTimePrecision";
final static String relatesPred = vivoCore + "relates";
public AddPublicationToPersonGenerator() {}
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) throws Exception {
if( EditConfigurationUtils.getObjectUri(vreq) == null ){
return doAddNew(vreq,session);
}else{
@ -76,7 +76,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
private EditConfigurationVTwo doSkipToPublication(VitroRequest vreq) {
Individual authorshipNode = EditConfigurationUtils.getObjectIndividual(vreq);
//try to get the publication
String pubQueryStr = "SELECT ?obj \n" +
"WHERE { <" + authorshipNode.getURI() + "> <" + relatesPred + "> ?obj . \n" +
@ -89,8 +89,8 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
return doBadAuthorshipNoPub( vreq );
}else if( rs.size() > 1 ){
return doBadAuthorshipMultiplePubs(vreq);
}else{
//skip to publication
}else{
//skip to publication
RDFNode objNode = rs.next().get("obj");
if (!objNode.isResource() || objNode.isAnon()) {
return doBadAuthorshipNoPub( vreq );
@ -154,10 +154,10 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
// TODO Auto-generated method stub
return null;
}
private void setVarNames(EditConfigurationVTwo editConfiguration) {
editConfiguration.setVarNameForSubject("person");
editConfiguration.setVarNameForPredicate("predicate");
editConfiguration.setVarNameForSubject("person");
editConfiguration.setVarNameForPredicate("predicate");
editConfiguration.setVarNameForObject("authorshipUri");
}
@ -216,18 +216,18 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
}
private String getAuthorshipN3() {
return "@prefix core: <" + vivoCore + "> . " +
"?authorshipUri a core:Authorship ;" +
"core:relates ?person ." +
return "@prefix core: <" + vivoCore + "> . " +
"?authorshipUri a core:Authorship ;" +
"core:relates ?person ." +
"?person core:relatedBy ?authorshipUri .";
}
private String getN3ForNewPub() {
return "@prefix core: <" + vivoCore + "> ." +
"?newPublication a ?pubType ." +
"?newPublication <" + label + "> ?title ." +
"?newPublication <" + label + "> ?title ." +
"?authorshipUri core:relates ?newPublication ." +
"?newPublication core:relatedBy ?authorshipUri .";
"?newPublication core:relatedBy ?authorshipUri .";
}
private String getN3ForExistingPub() {
@ -240,7 +240,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
return "@prefix vivo: <" + vivoCore + "> . \n" +
"?newPublication vivo:hasPublicationVenue ?newCollection . \n" +
"?newCollection a <" + collectionClass + "> . \n" +
"?newCollection vivo:publicationVenueFor ?newPublication . \n" +
"?newCollection vivo:publicationVenueFor ?newPublication . \n" +
"?newCollection <" + label + "> ?collection .";
}
@ -248,7 +248,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
return "@prefix vivo: <" + vivoCore + "> . \n" +
"?pubUri vivo:hasPublicationVenue ?newCollection . \n" +
"?newCollection a <" + collectionClass + "> . \n" +
"?newCollection vivo:publicationVenueFor ?pubUri . \n" +
"?newCollection vivo:publicationVenueFor ?pubUri . \n" +
"?newCollection <" + label + "> ?collection .";
}
@ -268,7 +268,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
return "@prefix vivo: <" + vivoCore + "> . \n" +
"?pubUri vivo:hasPublicationVenue ?newBook . \n" +
"?newBook a <" + bookClass + "> . \n" +
"?newBook vivo:publicationVenueFor ?pubUri . \n " +
"?newBook vivo:publicationVenueFor ?pubUri . \n " +
"?newBook <" + label + "> ?book .";
}
@ -282,8 +282,8 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
return "@prefix vivo: <" + vivoCore + "> . \n" +
"?newPublication vivo:hasPublicationVenue ?newBook . \n" +
"?newBook a <" + bookClass + "> . \n" +
"?newBook vivo:publicationVenueFor ?newPublication . \n " +
"?newBook <" + label + "> ?book . ";
"?newBook vivo:publicationVenueFor ?newPublication . \n " +
"?newBook <" + label + "> ?book . ";
}
private String getN3ForNewBookVolume() {
@ -312,7 +312,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
"?editorship a vivo:Editorship . \n" +
"?editorship vivo:relates ?newEditor . \n" +
"?newEditor a <" + editorClass + "> . \n" +
"?newEditor vivo:relatedBy ?editorship . \n" +
"?newEditor vivo:relatedBy ?editorship . \n" +
"?newEditor <" + label + "> ?editor .";
}
@ -323,13 +323,13 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
"?newBook <" + label + "> ?book . \n " +
"?editorship a vivo:Editorship . \n" +
"?editorship vivo:relates ?editorUri . \n" +
"?editorUri vivo:relatedBy ?editorship . ";
"?editorUri vivo:relatedBy ?editorship . ";
}
private String getN3ForNewBookNewPublisher() {
return "@prefix vivo: <" + vivoCore + "> . \n" +
"?newBook vivo:publisher ?newPublisher . \n " +
"?newPublisher vivo:publisherOf ?newBook . \n" +
"?newPublisher vivo:publisherOf ?newBook . \n" +
"?newPublisher <" + label + "> ?publisher .";
}
@ -349,7 +349,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
return "@prefix vivo: <" + vivoCore + "> . \n" +
"?pubUri <" + presentedAtPred + "> ?newConference . \n" +
"?newConference a <" + conferenceClass + "> . \n" +
"?newConference <http://purl.obolibrary.org/obo/BFO_0000051> ?pubUri . \n" +
"?newConference <http://purl.obolibrary.org/obo/BFO_0000051> ?pubUri . \n" +
"?newConference <" + label + "> ?conference .";
}
@ -363,7 +363,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
return "@prefix vivo: <" + vivoCore + "> . \n" +
"?newPublication <" + presentedAtPred + "> ?newConference . \n" +
"?newConference a <" + conferenceClass + "> . \n" +
"?newConference <http://purl.obolibrary.org/obo/BFO_0000051> ?newPublication . \n" +
"?newConference <http://purl.obolibrary.org/obo/BFO_0000051> ?newPublication . \n" +
"?newConference <" + label + "> ?conference .";
}
@ -377,7 +377,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
return "@prefix vivo: <" + vivoCore + "> . \n" +
"?pubUri vivo:proceedingsOf ?newEvent . \n" +
"?newEvent a <" + conferenceClass + "> . \n" +
"?newEvent vivo:hasProceedings ?pubUri . \n" +
"?newEvent vivo:hasProceedings ?pubUri . \n" +
"?newEvent <" + label + "> ?event .";
}
@ -391,7 +391,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
return "@prefix vivo: <" + vivoCore + "> . \n" +
"?newPublication vivo:proceedingsOf ?newEvent . \n" +
"?newEvent a <" + conferenceClass + "> . \n" +
"?newEvent vivo:hasProceedings ?newPublication . \n" +
"?newEvent vivo:hasProceedings ?newPublication . \n" +
"?newEvent <" + label + "> ?event .";
}
@ -408,7 +408,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
"?editorship a vivo:Editorship . \n" +
"?editorship vivo:relates ?newEditor . \n" +
"?newEditor a <" + editorClass + "> . \n" +
"?newEditor vivo:relatedBy ?editorship . \n" +
"?newEditor vivo:relatedBy ?editorship . \n" +
"?newEditor <" + label + "> ?editor .";
}
@ -418,7 +418,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
"?editorship vivo:relates ?pubUri . \n" +
"?editorship a vivo:Editorship . \n" +
"?editorship vivo:relates ?editorUri . \n" +
"?editorUri vivo:relatedBy ?editorship . ";
"?editorUri vivo:relatedBy ?editorship . ";
}
private String getN3ForNewEditorNewPub() {
@ -429,7 +429,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
"?editorship a vivo:Editorship . \n" +
"?editorship vivo:relates ?newEditor . \n" +
"?newEditor a <" + editorClass + "> . \n" +
"?newEditor vivo:relatedBy ?editorship . \n" +
"?newEditor vivo:relatedBy ?editorship . \n" +
"?newEditor <" + label + "> ?editor .";
}
@ -440,14 +440,14 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
"?newPublication <" + label + "> ?title ." +
"?editorship vivo:relates ?editorUri . \n" +
"?editorship a vivo:Editorship . \n" +
"?editorUri vivo:relatedBy ?editorship . ";
"?editorUri vivo:relatedBy ?editorship . ";
}
private String getN3ForNewPublisher() {
return "@prefix vivo: <" + vivoCore + "> . \n" +
"?pubUri vivo:publisher ?newPublisher . \n" +
"?newPublisher a <" + publisherClass + "> . \n" +
"?newPublisher vivo:publisherOf ?pubUri . \n" +
"?newPublisher vivo:publisherOf ?pubUri . \n" +
"?newPublisher <" + label + "> ?publisher .";
}
@ -461,7 +461,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
return "@prefix vivo: <" + vivoCore + "> . \n" +
"?newPublication vivo:publisher ?newPublisher . \n" +
"?newPublisher a <" + publisherClass + "> . \n" +
"?newPublisher vivo:publisherOf ?newPublication . \n" +
"?newPublisher vivo:publisherOf ?newPublication . \n" +
"?newPublisher <" + label + "> ?publisher .";
}
@ -475,9 +475,9 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
return "@prefix vcard: <http://www.w3.org/2006/vcard/ns#> . \n" +
"?newEditor <http://purl.obolibrary.org/obo/ARG_2000028> ?vcardEditor . \n" +
"?vcardEditor <http://purl.obolibrary.org/obo/ARG_2000029> ?newEditor . \n" +
"?vcardEditor a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardEditor a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardEditor vcard:hasName ?vcardName . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName vcard:givenName ?firstName .";
}
@ -485,9 +485,9 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
return "@prefix vcard: <http://www.w3.org/2006/vcard/ns#> . \n" +
"?newEditor <http://purl.obolibrary.org/obo/ARG_2000028> ?vcardEditor . \n" +
"?vcardEditor <http://purl.obolibrary.org/obo/ARG_2000029> ?newEditor . \n" +
"?vcardEditor a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardEditor a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardEditor vcard:hasName ?vcardName . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName vcard:familyName ?lastName .";
}
@ -535,10 +535,10 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
}
/** Get new resources */
private Map<String, String> generateNewResources(VitroRequest vreq) {
private Map<String, String> generateNewResources(VitroRequest vreq) {
String DEFAULT_NS_TOKEN=null; //null forces the default NS
HashMap<String, String> newResources = new HashMap<String, String>();
HashMap<String, String> newResources = new HashMap<String, String>();
newResources.put("authorshipUri", DEFAULT_NS_TOKEN);
newResources.put("newPublication", DEFAULT_NS_TOKEN);
newResources.put("newCollection", DEFAULT_NS_TOKEN);
@ -554,21 +554,21 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
return newResources;
}
/** Set URIS and Literals In Scope and on form and supporting methods */
/** Set URIS and Literals In Scope and on form and supporting methods */
private void setUrisAndLiteralsInScope(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
HashMap<String, List<String>> urisInScope = new HashMap<String, List<String>>();
urisInScope.put(editConfiguration.getVarNameForSubject(),
urisInScope.put(editConfiguration.getVarNameForSubject(),
Arrays.asList(new String[]{editConfiguration.getSubjectUri()}));
urisInScope.put(editConfiguration.getVarNameForPredicate(),
urisInScope.put(editConfiguration.getVarNameForPredicate(),
Arrays.asList(new String[]{editConfiguration.getPredicateUri()}));
editConfiguration.setUrisInScope(urisInScope);
editConfiguration.setUrisInScope(urisInScope);
HashMap<String, List<Literal>> literalsInScope = new HashMap<String, List<Literal>>();
editConfiguration.setLiteralsInScope(literalsInScope);
editConfiguration.setLiteralsInScope(literalsInScope);
}
private void setUrisAndLiteralsOnForm(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
List<String> urisOnForm = new ArrayList<String>();
List<String> urisOnForm = new ArrayList<String>();
//add role activity and roleActivityType to uris on form
urisOnForm.add("pubType");
urisOnForm.add("pubUri");
@ -605,11 +605,11 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
literalsOnForm.add("firstName");
literalsOnForm.add("lastName");
editConfiguration.setLiteralsOnForm(literalsOnForm);
}
}
/** Set SPARQL Queries and supporting methods. */
/** Set SPARQL Queries and supporting methods. */
//In this case no queries for existing
private void setSparqlQueries(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
private void setSparqlQueries(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
editConfiguration.setSparqlForExistingUris(new HashMap<String, String>());
editConfiguration.setSparqlForAdditionalLiteralsInScope(new HashMap<String, String>());
editConfiguration.setSparqlForAdditionalUrisInScope(new HashMap<String, String>());
@ -617,9 +617,9 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
}
/**
*
*
* Set Fields and supporting methods
* @throws Exception
* @throws Exception
*/
private void setFields(EditConfigurationVTwo editConfiguration, VitroRequest vreq) throws Exception {
@ -668,7 +668,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
editConfiguration.addField(new FieldVTwo().
setName("pubType").
setValidators( list("nonempty") ).
setOptions( new ConstantFieldOptions("pubType", getPublicationTypeLiteralOptions() ))
setOptions( new ConstantFieldOptions("pubType", getPublicationTypeLiteralOptions() ))
);
}
@ -697,7 +697,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
editConfiguration.addField(new FieldVTwo().
setName("collectionUri"));
}
private void setBookLabelField(EditConfigurationVTwo editConfiguration) {
String stringDatatypeUri = XSD.xstring.toString();
editConfiguration.addField(new FieldVTwo().
@ -705,7 +705,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
setValidators(list("datatype:" + stringDatatypeUri)).
setRangeDatatypeUri(stringDatatypeUri));
}
private void setBookDisplayField(EditConfigurationVTwo editConfiguration) {
String stringDatatypeUri = XSD.xstring.toString();
editConfiguration.addField(new FieldVTwo().
@ -718,7 +718,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
editConfiguration.addField(new FieldVTwo().
setName("bookUri"));
}
private void setConferenceLabelField(EditConfigurationVTwo editConfiguration) {
String stringDatatypeUri = XSD.xstring.toString();
editConfiguration.addField(new FieldVTwo().
@ -726,7 +726,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
setValidators(list("datatype:" + stringDatatypeUri)).
setRangeDatatypeUri(stringDatatypeUri));
}
private void setConferenceDisplayField(EditConfigurationVTwo editConfiguration) {
String stringDatatypeUri = XSD.xstring.toString();
editConfiguration.addField(new FieldVTwo().
@ -739,7 +739,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
editConfiguration.addField(new FieldVTwo().
setName("conferenceUri"));
}
private void setEventLabelField(EditConfigurationVTwo editConfiguration) {
String stringDatatypeUri = XSD.xstring.toString();
editConfiguration.addField(new FieldVTwo().
@ -747,7 +747,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
setValidators(list("datatype:" + stringDatatypeUri)).
setRangeDatatypeUri(stringDatatypeUri));
}
private void setEventDisplayField(EditConfigurationVTwo editConfiguration) {
String stringDatatypeUri = XSD.xstring.toString();
editConfiguration.addField(new FieldVTwo().
@ -756,7 +756,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
setRangeDatatypeUri(stringDatatypeUri));
}
private void setFirstNameField(EditConfigurationVTwo editConfiguration) {
String stringDatatypeUri = XSD.xstring.toString();
editConfiguration.addField(new FieldVTwo().
@ -764,7 +764,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
setValidators(list("datatype:" + stringDatatypeUri)).
setRangeDatatypeUri(stringDatatypeUri));
}
private void setLastNameField(EditConfigurationVTwo editConfiguration) {
String stringDatatypeUri = XSD.xstring.toString();
editConfiguration.addField(new FieldVTwo().
@ -776,7 +776,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
editConfiguration.addField(new FieldVTwo().
setName("eventUri"));
}
private void setEditorLabelField(EditConfigurationVTwo editConfiguration) {
String stringDatatypeUri = XSD.xstring.toString();
editConfiguration.addField(new FieldVTwo().
@ -784,7 +784,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
setValidators(list("datatype:" + stringDatatypeUri)).
setRangeDatatypeUri(stringDatatypeUri));
}
private void setEditorDisplayField(EditConfigurationVTwo editConfiguration) {
String stringDatatypeUri = XSD.xstring.toString();
editConfiguration.addField(new FieldVTwo().
@ -797,7 +797,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
editConfiguration.addField(new FieldVTwo().
setName("editorUri"));
}
private void setPublisherLabelField(EditConfigurationVTwo editConfiguration) {
String stringDatatypeUri = XSD.xstring.toString();
editConfiguration.addField(new FieldVTwo().
@ -805,7 +805,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
setValidators(list("datatype:" + stringDatatypeUri)).
setRangeDatatypeUri(stringDatatypeUri));
}
private void setPublisherDisplayField(EditConfigurationVTwo editConfiguration) {
String stringDatatypeUri = XSD.xstring.toString();
editConfiguration.addField(new FieldVTwo().
@ -818,7 +818,7 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
editConfiguration.addField(new FieldVTwo().
setName("publisherUri"));
}
private void setLocaleField(EditConfigurationVTwo editConfiguration) {
String stringDatatypeUri = XSD.xstring.toString();
editConfiguration.addField(new FieldVTwo().
@ -879,11 +879,11 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
editConfiguration.addField(new FieldVTwo().
setName("dateTime").
setEditElement(
new DateTimeWithPrecisionVTwo(null,
new DateTimeWithPrecisionVTwo(null,
VitroVocabulary.Precision.YEAR.uri(),
VitroVocabulary.Precision.NONE.uri())
)
);
);
}
private List<List<String>> getPublicationTypeLiteralOptions() {
@ -930,12 +930,12 @@ public class AddPublicationToPersonGenerator extends VivoBaseGenerator implement
}
public String getSparqlForAcFilter(VitroRequest vreq) {
String subject = EditConfigurationUtils.getSubjectUri(vreq);
String subject = EditConfigurationUtils.getSubjectUri(vreq);
String query = "PREFIX core:<" + vivoCore + "> " +
"SELECT ?pubUri WHERE { " +
"<" + subject + "> core:relatedBy ?authorshipUri . " +
"?authorshipUri a core:Authorship . " +
String query = "PREFIX core:<" + vivoCore + "> " +
"SELECT ?pubUri WHERE { " +
"<" + subject + "> core:relatedBy ?authorshipUri . " +
"?authorshipUri a core:Authorship . " +
"?authorshipUri core:relates ?pubUri . }";
return query;
}

View file

@ -7,9 +7,9 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ConstantField
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldOptions;
public class AddResearcherRoleToPersonGenerator extends AddRoleToPersonTwoStageGenerator {
private static String template = "addResearcherRoleToPerson.ftl";
@Override
String getTemplate() {
return template;
@ -19,21 +19,21 @@ public class AddResearcherRoleToPersonGenerator extends AddRoleToPersonTwoStageG
public String getRoleType() {
return "http://vivoweb.org/ontology/core#ResearcherRole";
}
/** Researcher role involves hard-coded options for the "right side" of the role or activity. */
@Override
FieldOptions getRoleActivityFieldOptions(VitroRequest vreq) throws Exception {
return new ConstantFieldOptions(
"", "Select one",
"http://vivoweb.org/ontology/core#Grant", "Grant",
"http://purl.obolibrary.org/obo/ERO_0000015", "Human Study",
"", "Select one",
"http://vivoweb.org/ontology/core#Grant", "Grant",
"http://purl.obolibrary.org/obo/ERO_0000015", "Human Study",
"http://vivoweb.org/ontology/core#Project", "Project",
"http://purl.obolibrary.org/obo/ERO_0000014", "Research Project");
"http://purl.obolibrary.org/obo/ERO_0000014", "Research Project");
}
@Override
@Override
boolean isShowRoleLabelField() { return true; }
/*
/*
* Use the methods below to change the date/time precision in the
* custom form associated with this generator. When not used, the
* precision will be YEAR. The other precisons are MONTH, DAY, HOUR,
@ -49,5 +49,5 @@ public class AddResearcherRoleToPersonGenerator extends AddRoleToPersonTwoStageG
String precision = VitroVocabulary.Precision.DAY.uri();
return precision;
}
*/
*/
}

View file

@ -6,36 +6,36 @@ import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ConstantFieldOptions;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldOptions;
public class AddReviewerRoleToPersonGenerator extends AddRoleToPersonTwoStageGenerator {
public class AddReviewerRoleToPersonGenerator extends AddRoleToPersonTwoStageGenerator {
private static String OBJECT_VCLASS_URI = "http://purl.org/ontology/bibo/Document";
@Override
String getTemplate() { return "addReviewerRoleToPerson.ftl"; }
//The default activityToRolePredicate and roleToActivityPredicates are
//The default activityToRolePredicate and roleToActivityPredicates are
//correct for this subclass so they don't need to be overwritten
/* @Override
public String getRoleToActivityPredicate(VitroRequest vreq) {
return "<http://purl.obolibrary.org/obo/BFO_0000054>";
}
*/
*/
//role type will always be set based on particular form
@Override
public String getRoleType() {
//TODO: Get dynamic way of including vivoweb ontology
return "http://vivoweb.org/ontology/core#ReviewerRole";
}
}
/**
* Each subclass generator will return its own type of option here:
* whether literal hardcoded, based on class group, or subclasses of a specific class
* whether literal hardcoded, based on class group, or subclasses of a specific class
*/
@Override
FieldOptions getRoleActivityFieldOptions(VitroRequest vreq) throws Exception {
return new ConstantFieldOptions(
"", "Select type",
"", "Select type",
"http://purl.org/ontology/bibo/AcademicArticle", "Academic Article",
"http://purl.org/ontology/bibo/Article", "Article",
"http://purl.org/ontology/bibo/AudioDocument", "Audio Document",
@ -106,13 +106,13 @@ public class AddReviewerRoleToPersonGenerator extends AddRoleToPersonTwoStageGen
"http://vivoweb.org/ontology/core#WorkingPaper", "Working Paper"
);
}
//isShowRoleLabelField remains true for this so doesn't need to be overwritten
public boolean isShowRoleLabelField() {
return false;
}
/*
/*
* Use the methods below to change the date/time precision in the
* custom form associated with this generator. When not used, the
* precision will be YEAR. The other precisons are MONTH, DAY, HOUR,
@ -128,6 +128,6 @@ public class AddReviewerRoleToPersonGenerator extends AddRoleToPersonTwoStageGen
String precision = VitroVocabulary.Precision.DAY.uri();
return precision;
}
*/
*/
}

View file

@ -6,19 +6,19 @@ import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ConstantFieldOptions;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldOptions;
public class AddServiceProviderRoleToPersonGenerator extends AddRoleToPersonTwoStageGenerator {
public class AddServiceProviderRoleToPersonGenerator extends AddRoleToPersonTwoStageGenerator {
private static String OPTION_CLASS_URI = "http://xmlns.com/foaf/0.1/Organization";
@Override
String getTemplate() { return "addServiceProviderRoleToPerson.ftl"; }
@Override
String getRoleType() {
String getRoleType() {
return "http://purl.obolibrary.org/obo/ERO_0000012";
}
}
/** Service Provider role involves hard-coded options for the
/** Service Provider role involves hard-coded options for the
* "right side" of the role or activity. */
@Override
FieldOptions getRoleActivityFieldOptions(VitroRequest vreq) throws Exception {
@ -74,11 +74,11 @@ FieldOptions getRoleActivityFieldOptions(VitroRequest vreq) throws Exception {
"http://purl.org/ontology/bibo/Workshop", "Workshop",
"http://vivoweb.org/ontology/core#WorkshopSeries", "Workshop Series");
}
@Override
boolean isShowRoleLabelField(){return true;}
/*
/*
* Use the methods below to change the date/time precision in the
* custom form associated with this generator. When not used, the
* precision will be YEAR. The other precisons are MONTH, DAY, HOUR,
@ -94,5 +94,5 @@ FieldOptions getRoleActivityFieldOptions(VitroRequest vreq) throws Exception {
String precision = VitroVocabulary.Precision.DAY.uri();
return precision;
}
*/
*/
}

View file

@ -1,55 +1,55 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ConstantFieldOptions;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldOptions;
public class AddTeacherRoleToPersonGenerator extends AddRoleToPersonTwoStageGenerator {
private static String template = "addTeacherRoleToPerson.ftl";
@Override
String getTemplate() {
return template;
}
@Override
String getRoleType() {
return "http://vivoweb.org/ontology/core#TeacherRole";
}
/** Teacher role involves hard-coded options for the "right side"
* of the role or activity. */
@Override
FieldOptions getRoleActivityFieldOptions(VitroRequest vreq) throws Exception {
return new ConstantFieldOptions(
"", "Select one",
"http://purl.org/ontology/bibo/Conference", "Conference",
"http://vivoweb.org/ontology/core#Course", "Course",
"http://purl.org/ontology/bibo/Workshop", "Workshop");
}
@Override
boolean isShowRoleLabelField(){return true;}
/*
* Use the methods below to change the date/time precision in the
* custom form associated with this generator. When not used, the
* precision will be YEAR. The other precisons are MONTH, DAY, HOUR,
* MINUTE, TIME and NONE.
*/
/*
public String getStartDatePrecision() {
String precision = VitroVocabulary.Precision.MONTH.uri();
return precision;
}
public String getEndDatePrecision() {
String precision = VitroVocabulary.Precision.DAY.uri();
return precision;
}
*/
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ConstantFieldOptions;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldOptions;
public class AddTeacherRoleToPersonGenerator extends AddRoleToPersonTwoStageGenerator {
private static String template = "addTeacherRoleToPerson.ftl";
@Override
String getTemplate() {
return template;
}
@Override
String getRoleType() {
return "http://vivoweb.org/ontology/core#TeacherRole";
}
/** Teacher role involves hard-coded options for the "right side"
* of the role or activity. */
@Override
FieldOptions getRoleActivityFieldOptions(VitroRequest vreq) throws Exception {
return new ConstantFieldOptions(
"", "Select one",
"http://purl.org/ontology/bibo/Conference", "Conference",
"http://vivoweb.org/ontology/core#Course", "Course",
"http://purl.org/ontology/bibo/Workshop", "Workshop");
}
@Override
boolean isShowRoleLabelField(){return true;}
/*
* Use the methods below to change the date/time precision in the
* custom form associated with this generator. When not used, the
* precision will be YEAR. The other precisons are MONTH, DAY, HOUR,
* MINUTE, TIME and NONE.
*/
/*
public String getStartDatePrecision() {
String precision = VitroVocabulary.Precision.MONTH.uri();
return precision;
}
public String getEndDatePrecision() {
String precision = VitroVocabulary.Precision.DAY.uri();
return precision;
}
*/
}

View file

@ -1,311 +1,311 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.vocabulary.XSD;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
/**
* Generates the edit configuration for importing concepts from external
* search services, e.g. UMLS etc.
*/
public class AddUserDefinedConceptGenerator extends VivoBaseGenerator implements EditConfigurationGenerator {
private Log log = LogFactory.getLog(AddUserDefinedConceptGenerator.class);
private boolean isObjectPropForm = false;
private String subjectUri = null;
private String predicateUri = null;
private String objectUri = null;
private String datapropKeyStr= null;
private int dataHash = 0;
private DataPropertyStatement dps = null;
private String dataLiteral = null;
private String template = "addUserDefinedConcept.ftl";
private static HashMap<String,String> defaultsForXSDtypes ;
private static String SKOSConceptType = "http://www.w3.org/2004/02/skos/core#Concept";
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) {
EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo();
initBasics(editConfiguration, vreq);
initPropertyParameters(vreq, session, editConfiguration);
initObjectPropForm(editConfiguration, vreq);
editConfiguration.setTemplate(template);
setVarNames(editConfiguration);
//Assumes this is a simple case of subject predicate var
editConfiguration.setN3Required(this.generateN3Required(vreq));
//n3 optional
editConfiguration.setN3Optional(this.generateN3Optional());
//Todo: what do new resources depend on here?
//In original form, these variables start off empty
editConfiguration.setNewResources(generateNewResources(vreq));
//In scope
this.setUrisAndLiteralsInScope(editConfiguration, vreq);
//on Form
this.setUrisAndLiteralsOnForm(editConfiguration, vreq);
editConfiguration.setFilesOnForm(new ArrayList<String>());
//Sparql queries
this.setSparqlQueries(editConfiguration, vreq);
//set fields
setFields(editConfiguration, vreq, EditConfigurationUtils.getPredicateUri(vreq));
setTemplate(editConfiguration, vreq);
editConfiguration.addValidator(new AntiXssValidation());
//Add preprocessors
addPreprocessors(editConfiguration, vreq.getWebappDaoFactory());
//Adding additional data, specifically edit mode
addFormSpecificData(editConfiguration, vreq);
//One override for basic functionality, changing url pattern
//and entity
//Adding term should return to this same page, not the subject
//Return takes the page back to the individual form
editConfiguration.setUrlPatternToReturnTo(getUrlPatternToReturnTo(vreq));
prepare(vreq, editConfiguration);
return editConfiguration;
}
private String getUrlPatternToReturnTo(VitroRequest vreq) {
String subjectUri = EditConfigurationUtils.getSubjectUri(vreq);
String predicateUri = EditConfigurationUtils.getPredicateUri(vreq);
String generatorName = "edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddAssociatedConceptGenerator";
String editUrl = EditConfigurationUtils.getEditUrlWithoutContext(vreq);
return editUrl + "?subjectUri=" + UrlBuilder.urlEncode(subjectUri) +
"&predicateUri=" + UrlBuilder.urlEncode(predicateUri) +
"&editForm=" + UrlBuilder.urlEncode(generatorName);
}
private void setVarNames(EditConfigurationVTwo editConfiguration) {
editConfiguration.setVarNameForSubject("subject");
editConfiguration.setVarNameForPredicate("predicate");
editConfiguration.setVarNameForObject("conceptNode");
}
protected void setTemplate(EditConfigurationVTwo editConfiguration,
VitroRequest vreq) {
editConfiguration.setTemplate(template);
}
/*
* N3 Required and Optional Generators as well as supporting methods
*/
private String getPrefixesString() {
//TODO: Include dynamic way of including this
return "@prefix core: <http://vivoweb.org/ontology/core#> .";
}
//Here, the node is typed as a skos concept
private List<String> generateN3Required(VitroRequest vreq) {
List<String> n3Required = list(
getPrefixesString() + "\n" +
"?subject ?predicate ?conceptNode .\n"
);
List<String> inversePredicate = getInversePredicate(vreq);
//Adding inverse predicate if it exists
if(inversePredicate.size() > 0) {
n3Required.add("?conceptNode <" + inversePredicate.get(0) + "> ?subject .");
}
return n3Required;
}
//Optional b/c user may select an existing SKOS concept
private List<String> generateN3Optional() {
return list(
"?conceptNode <" + VitroVocabulary.RDF_TYPE + "> <" + SKOSConceptType + "> .\n" +
"?conceptNode <" + label + "> ?conceptLabel ."
);
}
/*
* Get new resources
*/
private Map<String, String> generateNewResources(VitroRequest vreq) {
HashMap<String, String> newResources = new HashMap<String, String>();
newResources.put("conceptNode", null);
//There are no new resources here, the concept node uri doesn't
//get created but already exists, and vocab uri should already exist as well
return newResources;
}
/*
* Set URIS and Literals In Scope and on form and supporting methods
*/
private void setUrisAndLiteralsInScope(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
HashMap<String, List<String>> urisInScope = new HashMap<String, List<String>>();
//note that at this point the subject, predicate, and object var parameters have already been processed
//these two were always set when instantiating an edit configuration object from json,
//although the json itself did not specify subject/predicate as part of uris in scope
urisInScope.put(editConfiguration.getVarNameForSubject(),
Arrays.asList(new String[]{editConfiguration.getSubjectUri()}));
urisInScope.put(editConfiguration.getVarNameForPredicate(),
Arrays.asList(new String[]{editConfiguration.getPredicateUri()}));
//Setting inverse role predicate
urisInScope.put("inverseRolePredicate", getInversePredicate(vreq));
editConfiguration.setUrisInScope(urisInScope);
//Uris in scope include subject, predicate, and object var
//literals in scope empty initially, usually populated by code in prepare for update
//with existing values for variables
editConfiguration.setLiteralsInScope(new HashMap<String, List<Literal>>());
}
private List<String> getInversePredicate(VitroRequest vreq) {
List<String> inversePredicateArray = new ArrayList<String>();
ObjectProperty op = EditConfigurationUtils.getObjectProperty(vreq);
if(op != null && op.getURIInverse() != null) {
inversePredicateArray.add(op.getURIInverse());
}
return inversePredicateArray;
}
//n3 should look as follows
//?subject ?predicate ?objectVar
private void setUrisAndLiteralsOnForm(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
List<String> urisOnForm = new ArrayList<String>();
List<String> literalsOnForm = new ArrayList<String>();
//The URI of the node that defines the concept
urisOnForm.add("conceptNode");
editConfiguration.setUrisOnform(urisOnForm);
//In case the user defines a new concept, will add a concept label
literalsOnForm.add("conceptLabel");
editConfiguration.setLiteralsOnForm(literalsOnForm);
}
/**
* Set SPARQL Queries and supporting methods
*/
private void setSparqlQueries(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
//Sparql queries defining retrieval of literals etc.
editConfiguration.setSparqlForAdditionalLiteralsInScope(new HashMap<String, String>());
Map<String, String> urisInScope = new HashMap<String, String>();
editConfiguration.setSparqlForAdditionalUrisInScope(new HashMap<String, String>());
editConfiguration.setSparqlForExistingLiterals(new HashMap<String, String>());
editConfiguration.setSparqlForExistingUris(new HashMap<String, String>());
}
/**
*
* Set Fields and supporting methods
*/
private void setFields(EditConfigurationVTwo editConfiguration, VitroRequest vreq, String predicateUri) {
setConceptNodeField(editConfiguration, vreq);
setConceptLabelField(editConfiguration, vreq);
}
//this field will be hidden and include the concept node URI
private void setConceptNodeField(EditConfigurationVTwo editConfiguration,
VitroRequest vreq) {
editConfiguration.addField(new FieldVTwo().
setName("conceptNode"));
}
private void setConceptLabelField(EditConfigurationVTwo editConfiguration,
VitroRequest vreq) {
editConfiguration.addField(new FieldVTwo().
setName("conceptLabel").
setValidators(list("datatype:" + XSD.xstring.toString())).
setRangeDatatypeUri(XSD.xstring.toString())
);
}
//Add preprocessor
private void addPreprocessors(EditConfigurationVTwo editConfiguration, WebappDaoFactory wadf) {
//Will be a completely different type of preprocessor
/*
editConfiguration.addEditSubmissionPreprocessor(
new RoleToActivityPredicatePreprocessor(editConfiguration, wadf));
*/
}
//Form specific data
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
formSpecificData.put("sparqlForAcFilter", getSparqlForAcFilter(vreq));
formSpecificData.put("conceptType", SKOSConceptType);
editConfiguration.setFormSpecificData(formSpecificData);
}
public String getSparqlForAcFilter(VitroRequest vreq) {
String subject = EditConfigurationUtils.getSubjectUri(vreq);
String predicate = EditConfigurationUtils.getPredicateUri(vreq);
String query = "PREFIX core:<" + vivoCore + "> " +
"SELECT ?conceptNode WHERE { " +
"<" + subject + "> <" + predicate + "> ?conceptNode ." +
"?conceptNode <" + VitroVocabulary.RDF_TYPE + "> <" + SKOSConceptType + "> . }";
return query;
}
//skos concepts can be added for either research areas or subject areas
//IF coming in from a different form then can get the predicate here as it will be stored
public String getCurrentPredicate(VitroRequest vreq) {
return vreq.getParameter("conceptPredicate");
}
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.vocabulary.XSD;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
/**
* Generates the edit configuration for importing concepts from external
* search services, e.g. UMLS etc.
*/
public class AddUserDefinedConceptGenerator extends VivoBaseGenerator implements EditConfigurationGenerator {
private Log log = LogFactory.getLog(AddUserDefinedConceptGenerator.class);
private boolean isObjectPropForm = false;
private String subjectUri = null;
private String predicateUri = null;
private String objectUri = null;
private String datapropKeyStr= null;
private int dataHash = 0;
private DataPropertyStatement dps = null;
private String dataLiteral = null;
private String template = "addUserDefinedConcept.ftl";
private static HashMap<String,String> defaultsForXSDtypes ;
private static String SKOSConceptType = "http://www.w3.org/2004/02/skos/core#Concept";
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) {
EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo();
initBasics(editConfiguration, vreq);
initPropertyParameters(vreq, session, editConfiguration);
initObjectPropForm(editConfiguration, vreq);
editConfiguration.setTemplate(template);
setVarNames(editConfiguration);
//Assumes this is a simple case of subject predicate var
editConfiguration.setN3Required(this.generateN3Required(vreq));
//n3 optional
editConfiguration.setN3Optional(this.generateN3Optional());
//Todo: what do new resources depend on here?
//In original form, these variables start off empty
editConfiguration.setNewResources(generateNewResources(vreq));
//In scope
this.setUrisAndLiteralsInScope(editConfiguration, vreq);
//on Form
this.setUrisAndLiteralsOnForm(editConfiguration, vreq);
editConfiguration.setFilesOnForm(new ArrayList<String>());
//Sparql queries
this.setSparqlQueries(editConfiguration, vreq);
//set fields
setFields(editConfiguration, vreq, EditConfigurationUtils.getPredicateUri(vreq));
setTemplate(editConfiguration, vreq);
editConfiguration.addValidator(new AntiXssValidation());
//Add preprocessors
addPreprocessors(editConfiguration, vreq.getWebappDaoFactory());
//Adding additional data, specifically edit mode
addFormSpecificData(editConfiguration, vreq);
//One override for basic functionality, changing url pattern
//and entity
//Adding term should return to this same page, not the subject
//Return takes the page back to the individual form
editConfiguration.setUrlPatternToReturnTo(getUrlPatternToReturnTo(vreq));
prepare(vreq, editConfiguration);
return editConfiguration;
}
private String getUrlPatternToReturnTo(VitroRequest vreq) {
String subjectUri = EditConfigurationUtils.getSubjectUri(vreq);
String predicateUri = EditConfigurationUtils.getPredicateUri(vreq);
String generatorName = "edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddAssociatedConceptGenerator";
String editUrl = EditConfigurationUtils.getEditUrlWithoutContext(vreq);
return editUrl + "?subjectUri=" + UrlBuilder.urlEncode(subjectUri) +
"&predicateUri=" + UrlBuilder.urlEncode(predicateUri) +
"&editForm=" + UrlBuilder.urlEncode(generatorName);
}
private void setVarNames(EditConfigurationVTwo editConfiguration) {
editConfiguration.setVarNameForSubject("subject");
editConfiguration.setVarNameForPredicate("predicate");
editConfiguration.setVarNameForObject("conceptNode");
}
protected void setTemplate(EditConfigurationVTwo editConfiguration,
VitroRequest vreq) {
editConfiguration.setTemplate(template);
}
/*
* N3 Required and Optional Generators as well as supporting methods
*/
private String getPrefixesString() {
//TODO: Include dynamic way of including this
return "@prefix core: <http://vivoweb.org/ontology/core#> .";
}
//Here, the node is typed as a skos concept
private List<String> generateN3Required(VitroRequest vreq) {
List<String> n3Required = list(
getPrefixesString() + "\n" +
"?subject ?predicate ?conceptNode .\n"
);
List<String> inversePredicate = getInversePredicate(vreq);
//Adding inverse predicate if it exists
if(inversePredicate.size() > 0) {
n3Required.add("?conceptNode <" + inversePredicate.get(0) + "> ?subject .");
}
return n3Required;
}
//Optional b/c user may select an existing SKOS concept
private List<String> generateN3Optional() {
return list(
"?conceptNode <" + VitroVocabulary.RDF_TYPE + "> <" + SKOSConceptType + "> .\n" +
"?conceptNode <" + label + "> ?conceptLabel ."
);
}
/*
* Get new resources
*/
private Map<String, String> generateNewResources(VitroRequest vreq) {
HashMap<String, String> newResources = new HashMap<String, String>();
newResources.put("conceptNode", null);
//There are no new resources here, the concept node uri doesn't
//get created but already exists, and vocab uri should already exist as well
return newResources;
}
/*
* Set URIS and Literals In Scope and on form and supporting methods
*/
private void setUrisAndLiteralsInScope(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
HashMap<String, List<String>> urisInScope = new HashMap<String, List<String>>();
//note that at this point the subject, predicate, and object var parameters have already been processed
//these two were always set when instantiating an edit configuration object from json,
//although the json itself did not specify subject/predicate as part of uris in scope
urisInScope.put(editConfiguration.getVarNameForSubject(),
Arrays.asList(new String[]{editConfiguration.getSubjectUri()}));
urisInScope.put(editConfiguration.getVarNameForPredicate(),
Arrays.asList(new String[]{editConfiguration.getPredicateUri()}));
//Setting inverse role predicate
urisInScope.put("inverseRolePredicate", getInversePredicate(vreq));
editConfiguration.setUrisInScope(urisInScope);
//Uris in scope include subject, predicate, and object var
//literals in scope empty initially, usually populated by code in prepare for update
//with existing values for variables
editConfiguration.setLiteralsInScope(new HashMap<String, List<Literal>>());
}
private List<String> getInversePredicate(VitroRequest vreq) {
List<String> inversePredicateArray = new ArrayList<String>();
ObjectProperty op = EditConfigurationUtils.getObjectProperty(vreq);
if(op != null && op.getURIInverse() != null) {
inversePredicateArray.add(op.getURIInverse());
}
return inversePredicateArray;
}
//n3 should look as follows
//?subject ?predicate ?objectVar
private void setUrisAndLiteralsOnForm(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
List<String> urisOnForm = new ArrayList<String>();
List<String> literalsOnForm = new ArrayList<String>();
//The URI of the node that defines the concept
urisOnForm.add("conceptNode");
editConfiguration.setUrisOnform(urisOnForm);
//In case the user defines a new concept, will add a concept label
literalsOnForm.add("conceptLabel");
editConfiguration.setLiteralsOnForm(literalsOnForm);
}
/**
* Set SPARQL Queries and supporting methods
*/
private void setSparqlQueries(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
//Sparql queries defining retrieval of literals etc.
editConfiguration.setSparqlForAdditionalLiteralsInScope(new HashMap<String, String>());
Map<String, String> urisInScope = new HashMap<String, String>();
editConfiguration.setSparqlForAdditionalUrisInScope(new HashMap<String, String>());
editConfiguration.setSparqlForExistingLiterals(new HashMap<String, String>());
editConfiguration.setSparqlForExistingUris(new HashMap<String, String>());
}
/**
*
* Set Fields and supporting methods
*/
private void setFields(EditConfigurationVTwo editConfiguration, VitroRequest vreq, String predicateUri) {
setConceptNodeField(editConfiguration, vreq);
setConceptLabelField(editConfiguration, vreq);
}
//this field will be hidden and include the concept node URI
private void setConceptNodeField(EditConfigurationVTwo editConfiguration,
VitroRequest vreq) {
editConfiguration.addField(new FieldVTwo().
setName("conceptNode"));
}
private void setConceptLabelField(EditConfigurationVTwo editConfiguration,
VitroRequest vreq) {
editConfiguration.addField(new FieldVTwo().
setName("conceptLabel").
setValidators(list("datatype:" + XSD.xstring.toString())).
setRangeDatatypeUri(XSD.xstring.toString())
);
}
//Add preprocessor
private void addPreprocessors(EditConfigurationVTwo editConfiguration, WebappDaoFactory wadf) {
//Will be a completely different type of preprocessor
/*
editConfiguration.addEditSubmissionPreprocessor(
new RoleToActivityPredicatePreprocessor(editConfiguration, wadf));
*/
}
//Form specific data
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
formSpecificData.put("sparqlForAcFilter", getSparqlForAcFilter(vreq));
formSpecificData.put("conceptType", SKOSConceptType);
editConfiguration.setFormSpecificData(formSpecificData);
}
public String getSparqlForAcFilter(VitroRequest vreq) {
String subject = EditConfigurationUtils.getSubjectUri(vreq);
String predicate = EditConfigurationUtils.getPredicateUri(vreq);
String query = "PREFIX core:<" + vivoCore + "> " +
"SELECT ?conceptNode WHERE { " +
"<" + subject + "> <" + predicate + "> ?conceptNode ." +
"?conceptNode <" + VitroVocabulary.RDF_TYPE + "> <" + SKOSConceptType + "> . }";
return query;
}
//skos concepts can be added for either research areas or subject areas
//IF coming in from a different form then can get the predicate here as it will be stored
public String getCurrentPredicate(VitroRequest vreq) {
return vreq.getParameter("conceptPredicate");
}
}

View file

@ -1,67 +1,67 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
import java.util.HashMap;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
/**
* Generates the edit configuration for a default property form.
*
*/
public class AutocompleteDataPropertyFormGenerator extends DefaultDataPropertyFormGenerator {
//The only thing that changes here are the templates
private Log log = LogFactory.getLog(AutocompleteObjectPropertyFormGenerator.class);
private String dataPropertyTemplate = "autoCompleteDataPropForm.ftl";
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) {
EditConfigurationVTwo ec = super.getEditConfiguration(vreq, session);
this.addFormSpecificData(ec, vreq);
return ec;
}
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
//Filter setting - i.e. sparql query for filtering out results from autocomplete
formSpecificData.put("sparqlForAcFilter", getSparqlForAcFilter(vreq));
editConfiguration.setTemplate(dataPropertyTemplate);
//Add edit model
formSpecificData.put("editMode", getEditMode(vreq));
editConfiguration.setFormSpecificData(formSpecificData);
}
public String getSparqlForAcFilter(VitroRequest vreq) {
String subject = EditConfigurationUtils.getSubjectUri(vreq);
String predicate = EditConfigurationUtils.getPredicateUri(vreq);
//Get all objects for existing predicate, filters out results from addition and edit
String query = "SELECT ?dataLiteral WHERE { " +
"<" + subject + "> <" + predicate + "> ?dataLiteral .} ";
return query;
}
//Get edit mode
public String getEditMode(VitroRequest vreq) {
if(isUpdate(vreq))
return "edit";
else
return "add";
}
private boolean isUpdate(VitroRequest vreq) {
Integer dataHash = EditConfigurationUtils.getDataHash(vreq);
return ( dataHash != null );
}
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
import java.util.HashMap;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
/**
* Generates the edit configuration for a default property form.
*
*/
public class AutocompleteDataPropertyFormGenerator extends DefaultDataPropertyFormGenerator {
//The only thing that changes here are the templates
private Log log = LogFactory.getLog(AutocompleteObjectPropertyFormGenerator.class);
private String dataPropertyTemplate = "autoCompleteDataPropForm.ftl";
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) {
EditConfigurationVTwo ec = super.getEditConfiguration(vreq, session);
this.addFormSpecificData(ec, vreq);
return ec;
}
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
//Filter setting - i.e. sparql query for filtering out results from autocomplete
formSpecificData.put("sparqlForAcFilter", getSparqlForAcFilter(vreq));
editConfiguration.setTemplate(dataPropertyTemplate);
//Add edit model
formSpecificData.put("editMode", getEditMode(vreq));
editConfiguration.setFormSpecificData(formSpecificData);
}
public String getSparqlForAcFilter(VitroRequest vreq) {
String subject = EditConfigurationUtils.getSubjectUri(vreq);
String predicate = EditConfigurationUtils.getPredicateUri(vreq);
//Get all objects for existing predicate, filters out results from addition and edit
String query = "SELECT ?dataLiteral WHERE { " +
"<" + subject + "> <" + predicate + "> ?dataLiteral .} ";
return query;
}
//Get edit mode
public String getEditMode(VitroRequest vreq) {
if(isUpdate(vreq))
return "edit";
else
return "add";
}
private boolean isUpdate(VitroRequest vreq) {
Integer dataHash = EditConfigurationUtils.getDataHash(vreq);
return ( dataHash != null );
}
}

View file

@ -16,42 +16,42 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.
public class GrantAdministeredByGenerator extends VivoBaseGenerator implements
EditConfigurationGenerator {
public GrantAdministeredByGenerator() {}
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
HttpSession session) throws Exception {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
initObjectPropForm(conf, vreq);
conf.setTemplate("grantAdministeredBy.ftl");
conf.setVarNameForSubject("grant");
conf.setVarNameForPredicate("predicate");
conf.setVarNameForObject("adminRole");
conf.setN3Required( Arrays.asList( n3ForNewAdminRole) );
conf.setN3Optional( Arrays.asList( n3ForNewAdminOrganization,
conf.setN3Optional( Arrays.asList( n3ForNewAdminOrganization,
n3ForExistingAdminOrganization ) );
conf.addNewResource("newOrganization", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("adminRole", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.setUrisOnform(Arrays.asList("existingOrganization"));
conf.setLiteralsOnForm(Arrays.asList("orgLabel", "orgLabelDisplay" ));
conf.addSparqlForExistingLiteral("orgLabel", orgLabelQuery);
conf.addSparqlForExistingLiteral("orgLabel", orgLabelQuery);
conf.addSparqlForExistingUris("existingOrganization", existingOrganizationQuery);
conf.addField( new FieldVTwo(). // options will be added in browser by auto complete JS
setName("existingOrganization")
);
);
conf.addField( new FieldVTwo().
setName("orgLabel").
@ -67,7 +67,7 @@ public class GrantAdministeredByGenerator extends VivoBaseGenerator implements
conf.addValidator(new AntiXssValidation());
conf.addValidator(new AutocompleteRequiredInputValidator("existingOrganization", "orgLabel"));
// addFormSpecificData(conf, vreq);
prepare(vreq, conf);
return conf;
@ -75,29 +75,29 @@ public class GrantAdministeredByGenerator extends VivoBaseGenerator implements
/* N3 assertions */
final static String n3ForNewAdminRole =
"@prefix vivo: <" + vivoCore + "> . \n" +
final static String n3ForNewAdminRole =
"@prefix vivo: <" + vivoCore + "> . \n" +
"?grant vivo:relates ?adminRole . \n" +
"?adminRole a vivo:AdministratorRole . \n" +
"?adminRole vivo:relatedBy ?grant . " ;
final static String n3ForNewAdminOrganization =
"@prefix vivo: <" + vivoCore + "> . \n\n" +
"?adminRole a vivo:AdministratorRole . \n" +
"?adminRole vivo:relatedBy ?grant . " ;
final static String n3ForNewAdminOrganization =
"@prefix vivo: <" + vivoCore + "> . \n\n" +
"?adminRole <http://purl.obolibrary.org/obo/RO_0000052> ?newOrganization . \n" +
"?newOrganization a <http://xmlns.com/foaf/0.1/Organization> . \n" +
"?newOrganization <http://purl.obolibrary.org/obo/RO_0000053> ?adminRole . \n" +
"?newOrganization vivo:relatedBy ?grant . \n" +
"?grant vivo:relates ?newOrganization . \n" +
"?newOrganization <"+ label + "> ?orgLabel .";
final static String n3ForExistingAdminOrganization =
"@prefix vivo: <" + vivoCore + "> . \n\n" +
final static String n3ForExistingAdminOrganization =
"@prefix vivo: <" + vivoCore + "> . \n\n" +
"?adminRole <http://purl.obolibrary.org/obo/RO_0000052> ?existingOrganization . \n" +
"?existingOrganization a <http://xmlns.com/foaf/0.1/Organization> . \n" +
"?existingOrganization <http://purl.obolibrary.org/obo/RO_0000053> ?adminRole . " +
"?existingOrganization vivo:relatedBy ?grant . \n" +
"?grant vivo:relates ?existingOrganization . \n" ;
/* Queries for editing an existing entry */
final static String existingOrganizationQuery =

View file

@ -20,35 +20,35 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.
import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils.EditMode;
import edu.cornell.mannlib.vitro.webapp.utils.generators.EditModeUtils;
public class GrantHasContributorGenerator extends VivoBaseGenerator implements EditConfigurationGenerator{
public class GrantHasContributorGenerator extends VivoBaseGenerator implements EditConfigurationGenerator{
// NOTE: This generator is for contract as well as grants.
//TODO: can we get rid of the session and get it form the vreq?
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) throws Exception {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
initObjectPropForm(conf, vreq);
conf.setTemplate("grantHasContributor.ftl");
conf.setVarNameForSubject("subject");
conf.setVarNameForPredicate("predicate");
conf.setVarNameForObject("theRole");
conf.setN3Required( Arrays.asList( n3ForNewProjectRole, roleTypeAssertion ) );
conf.setN3Optional(Arrays.asList( n3ForNewPerson, n3ForExistingPerson, firstNameAssertion, lastNameAssertion ) );
conf.addNewResource("theRole", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("newPerson",DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("vcardPerson", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("vcardName", DEFAULT_NS_FOR_NEW_RESOURCE);
//uris in scope: none
//uris in scope: none
//literals in scope: none
conf.setUrisOnform( Arrays.asList( "existingPerson", "roleType"));
conf.setLiteralsOnForm( Arrays.asList("personLabel", "personLabelDisplay", "firstName", "lastName"));
@ -56,12 +56,12 @@ public class GrantHasContributorGenerator extends VivoBaseGenerator implements
conf.addSparqlForExistingUris("existingPerson", existingPersonQuery);
conf.addSparqlForExistingUris("roleType", roleTypeQuery);
conf.addField( new FieldVTwo().
setName("existingPerson")
//options will be added in browser by auto complete JS
);
//options will be added in browser by auto complete JS
);
conf.addField( new FieldVTwo().
setName("personLabel").
setRangeDatatypeUri(XSD.xstring.toString() ).
@ -82,27 +82,27 @@ public class GrantHasContributorGenerator extends VivoBaseGenerator implements
setRangeDatatypeUri(XSD.xstring.toString() ).
setValidators( list("datatype:" + XSD.xstring.toString()) )
);
conf.addField( new FieldVTwo().
setName("roleType").
setValidators( list("nonempty") ).
setOptions(
setOptions(
new ChildVClassesWithParent("http://vivoweb.org/ontology/core#ResearcherRole")));
//Add validator
conf.addValidator(new AntiXssValidation());
conf.addValidator(new FirstAndLastNameValidator("existingPerson"));
//Adding additional data, specifically edit mode
addFormSpecificData(conf, vreq);
prepare(vreq, conf);
return conf;
}
/* N3 assertions for working with educational training */
final static String n3ForNewProjectRole =
final static String n3ForNewProjectRole =
"@prefix core: <"+ vivoCore +"> .\n" +
"@prefix rdfs: <"+ rdfs +"> . \n"+
"?subject core:relates ?theRole .\n" +
@ -111,7 +111,7 @@ public class GrantHasContributorGenerator extends VivoBaseGenerator implements
final static String roleTypeAssertion =
"?theRole a ?roleType .";
final static String n3ForNewPerson =
final static String n3ForNewPerson =
"@prefix core: <"+ vivoCore +"> .\n" +
"?theRole <http://purl.obolibrary.org/obo/RO_0000052> ?newPerson . \n" +
"?newPerson <http://purl.obolibrary.org/obo/RO_0000053> ?theRole . \n" +
@ -120,40 +120,40 @@ public class GrantHasContributorGenerator extends VivoBaseGenerator implements
"?newPerson a <http://xmlns.com/foaf/0.1/Person> . \n" +
"?newPerson <"+ label +"> ?personLabel . ";
final static String n3ForExistingPerson =
final static String n3ForExistingPerson =
"@prefix core: <"+ vivoCore +"> .\n" +
"?theRole <http://purl.obolibrary.org/obo/RO_0000052> ?existingPerson . \n" +
"?existingPerson <http://purl.obolibrary.org/obo/RO_0000053> ?theRole . \n" +
"?subject core:relates ?newPerson . \n" +
"?newPerson core:relatedBy ?subject . \n" +
" ";
final static String firstNameAssertion =
final static String firstNameAssertion =
"@prefix vcard: <http://www.w3.org/2006/vcard/ns#> . \n" +
"?newPerson <http://purl.obolibrary.org/obo/ARG_2000028> ?vcardPerson . \n" +
"?vcardPerson <http://purl.obolibrary.org/obo/ARG_2000029> ?newPerson . \n" +
"?vcardPerson a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardPerson a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardPerson vcard:hasName ?vcardName . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName vcard:givenName ?firstName .";
final static String lastNameAssertion =
final static String lastNameAssertion =
"@prefix vcard: <http://www.w3.org/2006/vcard/ns#> . \n" +
"?newPerson <http://purl.obolibrary.org/obo/ARG_2000028> ?vcardPerson . \n" +
"?vcardPerson <http://purl.obolibrary.org/obo/ARG_2000029> ?newPerson . \n" +
"?vcardPerson a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardPerson a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardPerson vcard:hasName ?vcardName . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName vcard:familyName ?lastName .";
/* Queries for editing an existing educational training entry */
final static String roleTypeQuery =
final static String roleTypeQuery =
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
"SELECT ?roleType WHERE { \n" +
"SELECT ?roleType WHERE { \n" +
" ?theRole vitro:mostSpecificType ?roleType . }";
final static String existingPersonQuery =
final static String existingPersonQuery =
"PREFIX rdfs: <"+ rdfs +"> \n"+
"SELECT ?existingPerson WHERE {\n"+
"?theRole <http://purl.obolibrary.org/obo/RO_0000052> ?existingPerson . \n" +
@ -161,7 +161,7 @@ public class GrantHasContributorGenerator extends VivoBaseGenerator implements
"?existingPerson a <http://xmlns.com/foaf/0.1/Person> . \n " +
" }";
final static String personLabelQuery =
final static String personLabelQuery =
"PREFIX rdfs: <"+ rdfs +"> \n"+
"SELECT ?existingPersonLabel WHERE {\n"+
"?theRole <http://purl.obolibrary.org/obo/RO_0000052> ?existingPerson . \n" +
@ -170,14 +170,14 @@ public class GrantHasContributorGenerator extends VivoBaseGenerator implements
"?existingPerson a <http://xmlns.com/foaf/0.1/Person> . \n " +
" }";
//Adding form specific data such as edit mode
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
formSpecificData.put("editMode", getEditMode(vreq).name().toLowerCase());
editConfiguration.setFormSpecificData(formSpecificData);
}
public EditMode getEditMode(VitroRequest vreq) {
List<String> predicates = new ArrayList<String>();
predicates.add("http://purl.obolibrary.org/obo/RO_0000053");

View file

@ -46,7 +46,7 @@ import edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.DataProper
/**
* This generator is specifically for handling labels for a FOAF Person individual and is an object property form.
*This allows the page to show all the labels for a particular individual and sets up code
*enabling the addition of a new label. Links on the page will allow for removal or editing of a given label.
*enabling the addition of a new label. Links on the page will allow for removal or editing of a given label.
*/
public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerator implements EditConfigurationGenerator {
public static Log log = LogFactory.getLog(ManageLabelsForIndividualGenerator.class);
@ -68,13 +68,13 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
//be employed when the 'add' button is used, we will set this is an object property form
//although label will mean we need to add a data property statement as well
//URL to return to is the same page once addition is complete
initObjectPropForm(config, vreq);
initObjectPropForm(config, vreq);
this.setUrlToReturnTo(config, vreq);
config.setSubjectUri(EditConfigurationUtils.getSubjectUri(vreq));
setVarNames(config);
//config.setDatapropKey( EditConfigurationUtils.getDataHash(vreq) );
//Add n3, fields, etc. in the case where the user wants to add a label
@ -86,10 +86,10 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
this.setUrisAndLiteralsInScope(config);
this.setFields(config, vreq, EditConfigurationUtils
.getPredicateUri(vreq));
//Get existing labels
//this.initExistingLabels(config, vreq);
//Add form specific data used to populate template
addFormSpecificData(config, vreq);
//This preprocessor handles getting the correct label language and putting the attribute on the label
@ -97,24 +97,24 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
new ManageLabelsForPersonPreprocessor(config));
//This will handle generating the label from the first name, middle, and last names and also make sure to associate
//a language with that label
config.addModelChangePreprocessor(new FoafNameToRdfsLabelPreprocessor());
config.addModelChangePreprocessor(new FoafNameToRdfsLabelPreprocessor());
prepare(vreq, config);
return config;
}
/**With ISF Changes**/
//For addition of a label, with ISF changes, the name is now linked to a vcard which in turn is linked to a "fullname" that then has first/middle/last names
private void addNewResources(EditConfigurationVTwo config) {
config.addNewResource("fullName", DEFAULT_NS_FOR_NEW_RESOURCE);
config.addNewResource("individualVcard", DEFAULT_NS_FOR_NEW_RESOURCE);
}
private void setUrlToReturnTo(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
editConfiguration.setUrlPatternToReturnTo(EditConfigurationUtils.getFormUrlWithoutContext(vreq));
editConfiguration.setUrlPatternToReturnTo(EditConfigurationUtils.getFormUrlWithoutContext(vreq));
}
private void setVarNames(EditConfigurationVTwo editConfiguration) {
editConfiguration.setVarNameForSubject("subject");
editConfiguration.setVarNameForPredicate("predicate");
@ -129,29 +129,29 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
private List<String> generateN3Optional(VitroRequest vreq) {
List<String> n3Optional = new ArrayList<String>();
String personFullNameN3 = this.N3_PREFIX +
String personFullNameN3 = this.N3_PREFIX +
"?subject <http://purl.obolibrary.org/obo/ARG_2000028> ?individualVcard . \n" +
"?individualVcard a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?individualVcard a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?individualVcard <http://purl.obolibrary.org/obo/ARG_2000029> ?subject . \n" +
"?individualVcard <http://www.w3.org/2006/vcard/ns#hasName> ?fullName . \n" +
"?fullName a <http://www.w3.org/2006/vcard/ns#Name> .";
String personFirstNameN3 =
String personFirstNameN3 =
"?fullName <http://www.w3.org/2006/vcard/ns#givenName> ?firstName . ";
String personLastNameN3 =
String personLastNameN3 =
"?fullName <http://www.w3.org/2006/vcard/ns#familyName> ?lastName .";
String personMiddleNameN3 = "?subject <http://vivoweb.org/ontology/core#middleName> ?middleName .";
n3Optional.add(personFullNameN3 + "\n " + personFirstNameN3 + "\n " + personLastNameN3);
n3Optional.add(personMiddleNameN3);
return n3Optional;
}
private void setFields(EditConfigurationVTwo editConfiguration, VitroRequest vreq, String predicateUri) {
Map<String, FieldVTwo> fields = new HashMap<String, FieldVTwo>();
editConfiguration.setFields(fields);
editConfiguration.addField(new FieldVTwo(
).setName("newLabelLanguage"));
//no validators since all of this is optional
@ -161,41 +161,41 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
setValidators(getFirstNameValidators(vreq, editConfiguration)));
editConfiguration.addField(new FieldVTwo().
setName("middleName").
setValidators(getMiddleNameValidators(vreq, editConfiguration)));
setValidators(getMiddleNameValidators(vreq, editConfiguration)));
editConfiguration.addField(new FieldVTwo().
setName("lastName").
setValidators(getLastNameValidators(vreq, editConfiguration)));
setValidators(getLastNameValidators(vreq, editConfiguration)));
//With ISF Changes, also include middle name
}
//first and last name have validators if is person is true
private List<String> getFirstNameValidators(VitroRequest vreq, EditConfigurationVTwo config) {
List<String> validators = new ArrayList<String>();
validators.add("nonempty");
return validators;
}
private List<String> getMiddleNameValidators(VitroRequest vreq, EditConfigurationVTwo config) {
List<String> validators = new ArrayList<String>();
return validators;
}
private List<String> getLastNameValidators(VitroRequest vreq, EditConfigurationVTwo config) {
List<String> validators = new ArrayList<String>();
validators.add("nonempty");
return validators;
}
private void setUrisAndLiteralsOnForm(EditConfigurationVTwo config,
VitroRequest vreq) {
List<String> literalsOnForm = new ArrayList<String>();
@ -205,29 +205,29 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
literalsOnForm.add("lastName");
literalsOnForm.add("middleName");
config.setLiteralsOnForm(literalsOnForm);
}
private void setUrisAndLiteralsInScope(EditConfigurationVTwo editConfiguration) {
HashMap<String, List<String>> urisInScope = new HashMap<String, List<String>>();
//note that at this point the subject, predicate, and object var parameters have already been processed
urisInScope.put(editConfiguration.getVarNameForSubject(),
urisInScope.put(editConfiguration.getVarNameForSubject(),
Arrays.asList(new String[]{editConfiguration.getSubjectUri()}));
urisInScope.put(editConfiguration.getVarNameForPredicate(),
urisInScope.put(editConfiguration.getVarNameForPredicate(),
Arrays.asList(new String[]{editConfiguration.getPredicateUri()}));
editConfiguration.setUrisInScope(urisInScope);
//Uris in scope include subject, predicate, and object var
editConfiguration.setLiteralsInScope(new HashMap<String, List<Literal>>());
}
private void initExistingLabels(EditConfigurationVTwo config,
VitroRequest vreq) {
this.existingLabelLiterals = this.getExistingLabels(config.getSubjectUri(), vreq);
}
private List<String> getExistingSortedLanguageNamesList() {
HashSet<String> existingLanguages = new HashSet<String>();
@ -258,7 +258,7 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
//Get available locales for the drop down for adding a new label, also sorted by language name
HashSet<String> existingLanguageNames = new HashSet<String>(existingLabelsByLanguageName.keySet());
List<HashMap<String, String>> availableLocalesForAdd = getAvailableLocales(locales, existingLanguageNames);
//Save all locales
config.addFormSpecificData("selectLocaleFullList", locales);
@ -266,27 +266,27 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
config.addFormSpecificData("labelsSortedByLanguageName", existingLabelsByLanguageName);
config.addFormSpecificData("selectLocale",availableLocalesForAdd);
config.addFormSpecificData("displayRemoveLink", (numberExistingLabels > 1));
//How do we edit? Will need to see
config.addFormSpecificData("deleteWebpageUrl", "/edit/primitiveDelete");
//How do we edit? Will need to see
config.addFormSpecificData("deleteWebpageUrl", "/edit/primitiveDelete");
Individual subject = vreq.getWebappDaoFactory().getIndividualDao().getIndividualByURI(config.getSubjectUri());
if( subject != null && subject.getName() != null ){
config.addFormSpecificData("subjectName", subject.getName());
}else{
config.addFormSpecificData("subjectName", null);
}
config.addFormSpecificData("isPersonType", "true");
//Include whether or not editable to enable edit/remove links and add to show up
config.addFormSpecificData("editable", isEditable(vreq, config));
}
//Based on what locales have already been selected for labels, return a list of
//Based on what locales have already been selected for labels, return a list of
//locales for which new labels can be added and have these sorted by the name of the language
private List<HashMap<String, String>> getAvailableLocales(List<HashMap<String, String>> allLocales,
HashSet<String> existingLabelsLanguageNames) {
@ -309,7 +309,7 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
return languageName1.compareTo(languageName2);
}
});
return availableLocales;
}
@ -319,7 +319,7 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
AddDataPropertyStatement adps = new AddDataPropertyStatement(
vreq.getJenaOntModel(), individual.getURI(),
SOME_URI, SOME_LITERAL);
AddObjectPropertyStatement aops = new AddObjectPropertyStatement(
vreq.getJenaOntModel(), individual.getURI(),
SOME_PREDICATE, SOME_URI);
@ -331,7 +331,7 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
public String getFOAFPersonClassURI() {
return "http://xmlns.com/foaf/0.1/Person";
}
public boolean isPersonType(VitroRequest vreq, EditConfigurationVTwo config) {
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
Boolean isPersonType = Boolean.FALSE;
@ -344,11 +344,11 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
isPersonType = Boolean.TRUE;
break;
}
}
}
}
return isPersonType;
}
//how to get the type of the individual in question
public List<VClass> getVClasses(EditConfigurationVTwo config, VitroRequest vreq) {
Individual subject = EditConfigurationUtils.getIndividual(vreq, config.getSubjectUri());
@ -365,7 +365,7 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
prop.setURI(propertyUri);
//Iterate through the labels and create a hashmap
HashMap<String, List<LabelInformation>> labelsHash= new HashMap<String, List<LabelInformation>>();
for(Literal l: labels) {
String languageTag = l.getLanguage();
String languageName = "";
@ -377,7 +377,7 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
} else {
log.warn("This language tag " + languageTag + " does not have corresponding name in the system and was not processed");
}
if(!StringUtils.isEmpty(languageName)) {
if(!labelsHash.containsKey(languageName)) {
labelsHash.put(languageName, new ArrayList<LabelInformation>());
@ -386,14 +386,14 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
//This should put the label in the list
//Create label information instance with the required information
//To generate link
DataPropertyStatementTemplateModel dpstm = new DataPropertyStatementTemplateModel(subjectUri, prop, l,
template, vreq);
labelsList.add(new LabelInformation(
l, dpstm.getEditUrl(), dpstm.getDeleteUrl(), languageTag, languageName));
}
}
//Sort each label list
LabelInformationComparator lic = new LabelInformationComparator();
for(String languageName: labelsHash.keySet()) {
@ -401,12 +401,12 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
labelInfo.sort(lic);
}
return labelsHash;
}
public static class LabelInformationComparator implements Comparator<LabelInformation> {
public int compare(LabelInformation l1, LabelInformation l2) {
return l1.getLabelStringValue().compareTo(l2.getLabelStringValue());
}
@ -418,8 +418,8 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
+ "SELECT DISTINCT ?label WHERE { \n"
+ " ?subject rdfs:label ?label \n"
+ "} ORDER BY ?label";
private ArrayList<Literal> getExistingLabels(String subjectUri, VitroRequest vreq) {
String queryStr = QueryUtils.subUriForQueryVar(LABEL_QUERY, "subject", subjectUri);
log.debug("queryStr = " + queryStr);
@ -431,31 +431,31 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
while (results.hasNext()) {
QuerySolution soln = results.nextSolution();
Literal nodeLiteral = soln.get("label").asLiteral();
labels.add(nodeLiteral);
labels.add(nodeLiteral);
}
} catch (Exception e) {
log.error(e, e);
}
}
return labels;
}
//Putting this into a method allows overriding it in subclasses
protected String getEditForm() {
return null;
//return AddEditWebpageFormGenerator.class.getName();
}
protected String getTemplate() {
return template;
}
//get locales
public List<HashMap<String, String>> getLocales(VitroRequest vreq) {
List<Locale> selectables = SelectedLocale.getSelectableLocales(vreq);
@ -472,27 +472,27 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
+ "': " + e);
}
}
return list;
}
public HashMap<String, String> getFullCodeToLanguageNameMap(List<HashMap<String, String>> localesList) {
HashMap<String, String> codeToLanguageMap = new HashMap<String, String>();
for(Map<String, String> locale: localesList) {
String code = (String) locale.get("code");
String label = (String) locale.get("label");
if(!codeToLanguageMap.containsKey(code)) {
codeToLanguageMap.put(code, label);
}
codeToLanguageMap.put(code, label);
}
else {
log.warn("Language code " + code + " for " + label + " was not associated in map becayse label already exists");
log.warn("Language code " + code + " for " + label + " was not associated in map becayse label already exists");
}
}
return codeToLanguageMap;
}
public List<String> getFullLanguagesNamesSortedList(List<Map<String, Object>> localesList) {
HashSet<String> languageNamesSet = new HashSet<String>();
for(Map<String, Object> locale: localesList) {
@ -500,13 +500,13 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
if(!languageNamesSet.contains(label)) {
languageNamesSet.add(label);
}
}
List<String> languageNames = new ArrayList<String>(languageNamesSet);
Collections.sort(languageNames);
return languageNames;
}
//copied from locale selection data getter but don't need all this information
private HashMap<String, String> buildLocaleMap(Locale locale,
Locale currentLocale) throws FileNotFoundException {
@ -516,14 +516,14 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
map.put("label", locale.getDisplayName(currentLocale));
return map;
}
//Class used to store the information needed for the template, such as the labels, their languages, their edit links
public class LabelInformation {
private Literal labelLiteral = null;
private String editLinkURL;
private String deleteLinkURL;
private String languageCode; //languageCode
private String languageName;
private String languageName;
public LabelInformation(Literal inputLiteral, String inputEditLinkURL, String inputDeleteLinkURL, String inputLanguageCode, String inputLanguageName) {
this.labelLiteral = inputLiteral;
this.editLinkURL = inputEditLinkURL;
@ -531,32 +531,32 @@ public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerat
this.languageCode = inputLanguageCode;
this.languageName = inputLanguageName;
}
public Literal getLabelLiteral() {
return this.labelLiteral;
}
public String getLabelStringValue() {
return this.labelLiteral.getString();
}
public String getEditLinkURL() {
return this.editLinkURL;
}
public String getDeleteLinkURL() {
return this.deleteLinkURL;
}
public String getLanguageCode() {
return this.languageCode;
}
public String getLanguageName() {
return this.languageName;
}
}
private String N3_PREFIX = "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n";
}

View file

@ -31,13 +31,13 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTw
* This is an odd controller that is just drawing a page with links on it.
* It is not an example of the normal use of the RDF editing system and
* was just migrated over from an odd use of the JSP RDF editing system
* during the 1.4 release.
*
* during the 1.4 release.
*
* This mainly sets up pageData for the template to use.
*/
public class ManageWebpagesForIndividualGenerator extends BaseEditConfigurationGenerator implements EditConfigurationGenerator {
public static Log log = LogFactory.getLog(ManageWebpagesForIndividualGenerator.class);
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) {
@ -55,8 +55,8 @@ public class ManageWebpagesForIndividualGenerator extends BaseEditConfigurationG
config.addFormSpecificData("webpages",webpages);
config.addFormSpecificData("rankPredicate", "http://vivoweb.org/ontology/core#rank" );
config.addFormSpecificData("reorderUrl", "/edit/reorder" );
config.addFormSpecificData("deleteWebpageUrl", "/edit/primitiveDelete");
config.addFormSpecificData("reorderUrl", "/edit/reorder" );
config.addFormSpecificData("deleteWebpageUrl", "/edit/primitiveDelete");
ParamMap paramMap = new ParamMap();
paramMap.put("subjectUri", config.getSubjectUri());
@ -64,7 +64,7 @@ public class ManageWebpagesForIndividualGenerator extends BaseEditConfigurationG
paramMap.put("view", "form");
String path = UrlBuilder.getUrl( UrlBuilder.Route.EDIT_REQUEST_DISPATCH ,paramMap);
config.addFormSpecificData("baseEditWebpageUrl", path);
config.addFormSpecificData("baseEditWebpageUrl", path);
//Also add domainUri and rangeUri if they exist, adding here instead of template
String domainUri = (String) vreq.getParameter("domainUri");
@ -82,7 +82,7 @@ public class ManageWebpagesForIndividualGenerator extends BaseEditConfigurationG
}
path = UrlBuilder.getUrl( UrlBuilder.Route.EDIT_REQUEST_DISPATCH ,paramMap);
config.addFormSpecificData("showAddFormUrl", path);
config.addFormSpecificData("showAddFormUrl", path);
Individual subject = vreq.getWebappDaoFactory().getIndividualDao().getIndividualByURI(config.getSubjectUri());
if( subject != null && subject.getName() != null ){
@ -162,10 +162,10 @@ public class ManageWebpagesForIndividualGenerator extends BaseEditConfigurationG
+ " OPTIONAL { ?link core:rank ?rank } \n"
+ " OPTIONAL { ?link vitro:mostSpecificType ?type } \n"
+ " OPTIONAL { ?type rdfs:label ?typeLabel } \n"
+ "} GROUP BY ?rank ?vcard ?link ?url ?typeLabel \n"
+ "} GROUP BY ?rank ?vcard ?link ?url ?typeLabel \n"
+ " ORDER BY ?rank";
private List<Map<String, String>> getWebpages(String subjectUri, VitroRequest vreq) {
RDFService rdfService = vreq.getRDFService();
@ -195,20 +195,20 @@ public class ManageWebpagesForIndividualGenerator extends BaseEditConfigurationG
}
} catch (Exception e) {
log.error(e, e);
}
}
log.debug("webpages = " + webpages);
return webpages;
}
//Putting this into a method allows overriding it in subclasses
protected String getEditForm() {
return AddEditWebpageFormGenerator.class.getName();
}
protected String getQuery() {
return WEBPAGE_QUERY;
}
protected String getTemplate() {
return "manageWebpagesForIndividual.ftl";
}

View file

@ -16,42 +16,42 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.
public class OrganizationAdministersGrantGenerator extends VivoBaseGenerator implements
EditConfigurationGenerator {
public OrganizationAdministersGrantGenerator() {}
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
HttpSession session) throws Exception {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
initObjectPropForm(conf, vreq);
conf.setTemplate("organizationAdministersGrant.ftl");
conf.setVarNameForSubject("organization");
conf.setVarNameForPredicate("predicate");
conf.setVarNameForObject("adminRole");
conf.setN3Required( Arrays.asList( n3ForNewAdminRole) );
conf.setN3Optional( Arrays.asList( n3ForNewAdminGrant,
conf.setN3Optional( Arrays.asList( n3ForNewAdminGrant,
n3ForExistingAdminGrant ) );
conf.addNewResource("newGrant", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("adminRole", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.setUrisOnform(Arrays.asList("existingGrant"));
conf.setLiteralsOnForm(Arrays.asList("grantLabel", "grantLabelDisplay" ));
conf.addSparqlForExistingLiteral("grantLabel", grantLabelQuery);
conf.addSparqlForExistingLiteral("grantLabel", grantLabelQuery);
conf.addSparqlForExistingUris("existingGrant", existingGrantQuery);
conf.addField( new FieldVTwo(). // options will be added in browser by auto complete JS
setName("existingGrant")
);
);
conf.addField( new FieldVTwo().
setName("grantLabel").
@ -67,7 +67,7 @@ public class OrganizationAdministersGrantGenerator extends VivoBaseGenerator imp
conf.addValidator(new AntiXssValidation());
conf.addValidator(new AutocompleteRequiredInputValidator("existingGrant", "grantLabel"));
// addFormSpecificData(conf, vreq);
prepare(vreq, conf);
return conf;
@ -75,29 +75,29 @@ public class OrganizationAdministersGrantGenerator extends VivoBaseGenerator imp
/* N3 assertions */
final static String n3ForNewAdminRole =
"@prefix vivo: <" + vivoCore + "> . \n\n" +
final static String n3ForNewAdminRole =
"@prefix vivo: <" + vivoCore + "> . \n\n" +
"?organization <http://purl.obolibrary.org/obo/RO_0000053> ?adminRole . \n" +
"?adminRole a vivo:AdministratorRole . \n" +
"?adminRole <http://purl.obolibrary.org/obo/RO_0000052> ?organization . " ;
final static String n3ForNewAdminGrant =
"@prefix vivo: <" + vivoCore + "> . \n" +
"?adminRole a vivo:AdministratorRole . \n" +
"?adminRole <http://purl.obolibrary.org/obo/RO_0000052> ?organization . " ;
final static String n3ForNewAdminGrant =
"@prefix vivo: <" + vivoCore + "> . \n" +
"?adminRole vivo:relatedBy ?newGrant . \n" +
"?newGrant a vivo:Grant . \n" +
"?newGrant vivo:relates ?adminRole . \n" +
"?organization vivo:relatedBy ?newGrant . \n" +
"?newGrant vivo:relates ?organization . \n" +
"?newGrant <"+ label + "> ?grantLabel .";
final static String n3ForExistingAdminGrant =
"@prefix vivo: <" + vivoCore + "> . \n\n" +
final static String n3ForExistingAdminGrant =
"@prefix vivo: <" + vivoCore + "> . \n\n" +
"?adminRole vivo:relatedBy ?existingGrant . \n" +
"?existingGrant a <http://xmlns.com/foaf/0.1/Grant> . \n" +
"?existingGrant vivo:relates ?adminRole . \n" +
"?organization vivo:relatedBy ?newGrant . \n" +
"?newGrant vivo:relates ?organization . " ;
/* Queries for editing an existing entry */
final static String existingGrantQuery =

View file

@ -23,28 +23,28 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.
import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils.EditMode;
import edu.cornell.mannlib.vitro.webapp.utils.generators.EditModeUtils;
public class OrganizationForTrainingGenerator extends VivoBaseGenerator implements EditConfigurationGenerator{
public class OrganizationForTrainingGenerator extends VivoBaseGenerator implements EditConfigurationGenerator{
//TODO: can we get rid of the session and get it form the vreq?
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) throws Exception {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
initObjectPropForm(conf, vreq);
conf.setTemplate("organizationForTraining.ftl");
conf.setVarNameForSubject("organization");
conf.setVarNameForPredicate("predicate");
conf.setVarNameForObject("edTraining");
conf.setN3Required( Arrays.asList( n3ForNewEdTraining, trainingTypeAssertion ) );
conf.setN3Optional(Arrays.asList( majorFieldAssertion, n3ForAwardedDegree, n3ForNewPerson, n3ForExistingPerson,
n3ForNewPersonAwardedDegree, n3ForExistingPersonAwardedDegree, deptAssertion, infoAssertion, n3ForStart,
n3ForNewPersonAwardedDegree, n3ForExistingPersonAwardedDegree, deptAssertion, infoAssertion, n3ForStart,
n3ForEnd, firstNameAssertion, lastNameAssertion ));
conf.addNewResource("edTraining", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("awardedDegree",DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("newPerson",DEFAULT_NS_FOR_NEW_RESOURCE);
@ -53,10 +53,10 @@ public class OrganizationForTrainingGenerator extends VivoBaseGenerator impleme
conf.addNewResource("endNode",DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("vcardPerson", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("vcardName", DEFAULT_NS_FOR_NEW_RESOURCE);
//uris in scope: none
//uris in scope: none
//literals in scope: none
conf.setUrisOnform( Arrays.asList( "existingPerson", "degreeType", "trainingType"));
conf.setLiteralsOnForm( Arrays.asList("personLabel", "personLabelDisplay", "awardedDegreeLabel",
"majorField", "dept", "info", "firstName", "lastName"));
@ -68,7 +68,7 @@ public class OrganizationForTrainingGenerator extends VivoBaseGenerator impleme
conf.addSparqlForExistingLiteral("startField-value", existingStartDateQuery);
conf.addSparqlForExistingLiteral("endField-value", existingEndDateQuery);
conf.addSparqlForExistingUris("awardedDegree", existingAwardedDegreeQuery);
conf.addSparqlForExistingUris("existingPerson", existingPersonQuery);
conf.addSparqlForExistingUris("trainingType", trainingTypeQuery);
@ -80,8 +80,8 @@ public class OrganizationForTrainingGenerator extends VivoBaseGenerator impleme
conf.addSparqlForExistingUris("endField-precision", existingEndPrecisionQuery);
//Add sparql to include inverse property as well
conf.addSparqlForAdditionalUrisInScope("inverseTrainingAtPerson", inverseTrainingAtPersonQuery);
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("degreeType").
setOptions( new IndividualsViaVClassOptions(
degreeTypeClass)));
@ -90,16 +90,16 @@ public class OrganizationForTrainingGenerator extends VivoBaseGenerator impleme
setName("majorField").
setRangeDatatypeUri( XSD.xstring.toString() ).
setValidators(list("datatype:" + XSD.xstring.toString())));
conf.addField( new FieldVTwo().
setName("existingPerson")
//options will be added in browser by auto complete JS
);
//options will be added in browser by auto complete JS
);
conf.addField( new FieldVTwo().
setName("awardedDegree")
//options will be added in browser by auto complete JS
);
//options will be added in browser by auto complete JS
);
conf.addField( new FieldVTwo().
setName("personLabel").
@ -115,11 +115,11 @@ public class OrganizationForTrainingGenerator extends VivoBaseGenerator impleme
setName("existingAwardedDegreeLabel").
setRangeDatatypeUri(XSD.xstring.toString() ).
setValidators( list("datatype:" + XSD.xstring.toString())));
conf.addField( new FieldVTwo().
setName("personLabelDisplay").
setRangeDatatypeUri(XSD.xstring.toString() ));
conf.addField( new FieldVTwo().
setName("firstName").
setRangeDatatypeUri(XSD.xstring.toString() ).
@ -135,14 +135,14 @@ public class OrganizationForTrainingGenerator extends VivoBaseGenerator impleme
conf.addField( new FieldVTwo().
setName("trainingType").
setValidators( list("nonempty") ).
setOptions(
setOptions(
new ChildVClassesWithParent(edProcessClass)));
conf.addField( new FieldVTwo().
setName("dept").
setRangeDatatypeUri( XSD.xstring.toString() ).
setValidators(list("datatype:" + XSD.xstring.toString())));
conf.addField( new FieldVTwo().
setName("info").
setRangeDatatypeUri( XSD.xstring.toString() ).
@ -150,33 +150,33 @@ public class OrganizationForTrainingGenerator extends VivoBaseGenerator impleme
FieldVTwo startField = new FieldVTwo().
setName("startField");
conf.addField(startField.
conf.addField(startField.
setEditElement(
new DateTimeWithPrecisionVTwo(startField,
new DateTimeWithPrecisionVTwo(startField,
VitroVocabulary.Precision.YEAR.uri(),
VitroVocabulary.Precision.NONE.uri())));
FieldVTwo endField = new FieldVTwo().
setName("endField");
conf.addField( endField.
conf.addField( endField.
setEditElement(
new DateTimeWithPrecisionVTwo(endField,
new DateTimeWithPrecisionVTwo(endField,
VitroVocabulary.Precision.YEAR.uri(),
VitroVocabulary.Precision.NONE.uri())));
//Add validator
conf.addValidator(new DateTimeIntervalValidationVTwo("startField","endField"));
conf.addValidator(new AntiXssValidation());
conf.addValidator(new FirstAndLastNameValidator("existingPerson"));
//Adding additional data, specifically edit mode
addFormSpecificData(conf, vreq);
prepare(vreq, conf);
return conf;
}
/* N3 assertions for working with educational training */
final static String n3ForNewEdTraining =
final static String n3ForNewEdTraining =
"@prefix core: <"+ vivoCore +"> .\n"+
"?organization <http://purl.obolibrary.org/obo/RO_0000056> ?edTraining .\n" +
"?edTraining a core:EducationalProcess .\n" +
@ -185,7 +185,7 @@ public class OrganizationForTrainingGenerator extends VivoBaseGenerator impleme
final static String trainingTypeAssertion =
"?edTraining a ?trainingType .";
final static String n3ForAwardedDegree =
final static String n3ForAwardedDegree =
"@prefix core: <"+ vivoCore +"> .\n"+
"?edTraining <http://purl.obolibrary.org/obo/RO_0002234> ?awardedDegree . \n" +
"?awardedDegree <http://purl.obolibrary.org/obo/RO_0002353> ?edTraining . \n" +
@ -196,49 +196,49 @@ public class OrganizationForTrainingGenerator extends VivoBaseGenerator impleme
"?degreeType <http://vivoweb.org/ontology/core#relatedBy> ?awardedDegree . \n"+
"?awardedDegree a core:AwardedDegree .";
final static String n3ForNewPerson =
final static String n3ForNewPerson =
"?edTraining <http://purl.obolibrary.org/obo/RO_0000057> ?newPerson . \n" +
"?newPerson <http://purl.obolibrary.org/obo/RO_0000056> ?edTraining . \n" +
"?newPerson a <http://xmlns.com/foaf/0.1/Person> . \n" +
"?newPerson <"+ label +"> ?personLabel . ";
final static String n3ForExistingPerson =
final static String n3ForExistingPerson =
"?edTraining <http://purl.obolibrary.org/obo/RO_0000057> ?existingPerson . \n" +
"?existingPerson <http://purl.obolibrary.org/obo/RO_0000056> ?edTraining . \n" +
" ";
final static String n3ForNewPersonAwardedDegree =
final static String n3ForNewPersonAwardedDegree =
"?awardedDegree <http://vivoweb.org/ontology/core#relates> ?newPerson . \n" +
"?newPerson <http://vivoweb.org/ontology/core#releatedBy> ?awardedDegree . \n" +
"?newPerson a <http://xmlns.com/foaf/0.1/Person> . \n" +
"?awardedDegree <"+ label +"> ?awardedDegreeLabel . \n" +
"?newPerson <"+ label +"> ?personLabel . ";
final static String firstNameAssertion =
final static String firstNameAssertion =
"@prefix vcard: <http://www.w3.org/2006/vcard/ns#> . \n" +
"?newPerson <http://purl.obolibrary.org/obo/ARG_2000028> ?vcardPerson . \n" +
"?vcardPerson <http://purl.obolibrary.org/obo/ARG_2000029> ?newPerson . \n" +
"?vcardPerson a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardPerson a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardPerson vcard:hasName ?vcardName . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName vcard:givenName ?firstName .";
final static String lastNameAssertion =
final static String lastNameAssertion =
"@prefix vcard: <http://www.w3.org/2006/vcard/ns#> . \n" +
"?newPerson <http://purl.obolibrary.org/obo/ARG_2000028> ?vcardPerson . \n" +
"?vcardPerson <http://purl.obolibrary.org/obo/ARG_2000029> ?newPerson . \n" +
"?vcardPerson a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardPerson a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardPerson vcard:hasName ?vcardName . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName vcard:familyName ?lastName .";
final static String n3ForExistingPersonAwardedDegree =
final static String n3ForExistingPersonAwardedDegree =
"?awardedDegree <http://vivoweb.org/ontology/core#relates> ?existingPerson . \n" +
"?existingPerson <http://vivoweb.org/ontology/core#relatedBy> ?awardedDegree . \n" +
"?awardedDegree <"+ label +"> ?awardedDegreeLabel . \n" +
"?existingPerson a <http://xmlns.com/foaf/0.1/Person> . ";
final static String majorFieldAssertion =
final static String majorFieldAssertion =
"?edTraining <"+ majorFieldPred +"> ?majorField .";
final static String n3ForStart =
@ -257,24 +257,24 @@ public class OrganizationForTrainingGenerator extends VivoBaseGenerator impleme
"?endNode <"+ dateTimeValue +"> ?endField-value .\n"+
"?endNode <"+ dateTimePrecision +"> ?endField-precision .";
final static String deptAssertion =
final static String deptAssertion =
"?edTraining <"+ deptPred +"> ?dept .";
final static String infoAssertion =
final static String infoAssertion =
"?edTraining <"+ infoPred +"> ?info .";
/* Queries for editing an existing educational training entry */
final static String existingAwardedDegreeQuery =
final static String existingAwardedDegreeQuery =
"SELECT ?existingAwardedDegree WHERE {\n"+
"?edTraining <http://purl.obolibrary.org/obo/RO_0002234> ?existingAwardedDegree . }\n";
final static String existingAwardedDegreeLabelQuery =
final static String existingAwardedDegreeLabelQuery =
"SELECT ?existingAwardedDegreeLabel WHERE {\n"+
"?edTraining <http://purl.obolibrary.org/obo/RO_0002234> ?existingAwardedDegree . \n" +
"?existingAwardedDegree <"+ label +"> ?existingAwardedDegreeLabel }\n";
final static String existingPersonQuery =
final static String existingPersonQuery =
"PREFIX rdfs: <"+ rdfs +"> \n"+
"SELECT ?existingPerson WHERE {\n"+
"?edTraining <http://purl.obolibrary.org/obo/RO_0000057> ?existingPerson . \n" +
@ -282,7 +282,7 @@ public class OrganizationForTrainingGenerator extends VivoBaseGenerator impleme
"?existingPerson a <http://xmlns.com/foaf/0.1/Person> . \n " +
" }";
final static String personLabelQuery =
final static String personLabelQuery =
"PREFIX rdfs: <"+ rdfs +"> \n"+
"SELECT ?existingPersonLabel WHERE {\n"+
"?edTraining <http://purl.obolibrary.org/obo/RO_0000057> ?existingPerson . \n" +
@ -291,12 +291,12 @@ public class OrganizationForTrainingGenerator extends VivoBaseGenerator impleme
"?existingPerson a <http://xmlns.com/foaf/0.1/Person> . \n " +
" }";
final static String trainingTypeQuery =
final static String trainingTypeQuery =
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
"SELECT ?existingTrainingType WHERE { \n" +
"SELECT ?existingTrainingType WHERE { \n" +
" ?edTraining vitro:mostSpecificType ?existingTrainingType . }";
final static String degreeTypeQuery =
final static String degreeTypeQuery =
"PREFIX core: <"+ vivoCore +"> \n"+
"SELECT ?existingDegreeType WHERE {\n"+
"?edTraining <http://purl.obolibrary.org/obo/RO_0002234> ?existingAwardedDegree . \n"+
@ -304,31 +304,31 @@ public class OrganizationForTrainingGenerator extends VivoBaseGenerator impleme
"?existingAwardedDegree core:relates ?existingDegreeType . \n" +
"?existingDegreeType a core:AcademicDegree }";
final static String majorFieldQuery =
final static String majorFieldQuery =
"SELECT ?existingMajorField WHERE {\n"+
"?edTraining <"+ majorFieldPred +"> ?existingMajorField . }";
final static String deptQuery =
final static String deptQuery =
"SELECT ?existingDept WHERE {\n"+
"?edTraining <"+ deptPred +"> ?existingDept . }";
final static String infoQuery =
final static String infoQuery =
"SELECT ?existingInfo WHERE {\n"+
"?edTraining <"+ infoPred +"> ?existingInfo . }";
final static String existingIntervalNodeQuery =
final static String existingIntervalNodeQuery =
"SELECT ?existingIntervalNode WHERE {\n"+
"?edTraining <"+ toInterval +"> ?existingIntervalNode .\n"+
"?existingIntervalNode <"+ type +"> <"+ intervalType +"> . }";
final static String existingStartNodeQuery =
final static String existingStartNodeQuery =
"SELECT ?existingStartNode WHERE {\n"+
"?edTraining <"+ toInterval +"> ?intervalNode .\n"+
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
"?intervalNode <"+ intervalToStart +"> ?existingStartNode . \n"+
"?existingStartNode <"+ type +"> <"+ dateTimeValueType +"> .}";
final static String existingStartDateQuery =
final static String existingStartDateQuery =
"SELECT ?existingDateStart WHERE {\n"+
"?edTraining <"+ toInterval +"> ?intervalNode .\n"+
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
@ -336,7 +336,7 @@ public class OrganizationForTrainingGenerator extends VivoBaseGenerator impleme
"?startNode <"+ type +"> <"+ dateTimeValueType +"> .\n"+
"?startNode <"+ dateTimeValue +"> ?existingDateStart . }";
final static String existingStartPrecisionQuery =
final static String existingStartPrecisionQuery =
"SELECT ?existingStartPrecision WHERE {\n"+
"?edTraining <"+ toInterval +"> ?intervalNode .\n"+
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
@ -344,14 +344,14 @@ public class OrganizationForTrainingGenerator extends VivoBaseGenerator impleme
"?startNode <"+ type +"> <"+ dateTimeValueType +"> . \n"+
"?startNode <"+ dateTimePrecision +"> ?existingStartPrecision . }";
final static String existingEndNodeQuery =
final static String existingEndNodeQuery =
"SELECT ?existingEndNode WHERE { \n"+
"?edTraining <"+ toInterval +"> ?intervalNode .\n"+
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
"?intervalNode <"+ intervalToEnd +"> ?existingEndNode . \n"+
"?existingEndNode <"+ type +"> <"+ dateTimeValueType +"> .}";
final static String existingEndDateQuery =
final static String existingEndDateQuery =
"SELECT ?existingEndDate WHERE {\n"+
"?edTraining <"+ toInterval +"> ?intervalNode .\n"+
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
@ -359,28 +359,28 @@ public class OrganizationForTrainingGenerator extends VivoBaseGenerator impleme
"?endNode <"+ type +"> <"+ dateTimeValueType +"> .\n"+
"?endNode <"+ dateTimeValue +"> ?existingEndDate . }";
final static String existingEndPrecisionQuery =
final static String existingEndPrecisionQuery =
"SELECT ?existingEndPrecision WHERE {\n"+
"?edTraining <"+ toInterval +"> ?intervalNode .\n"+
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
"?intervalNode <"+ intervalToEnd +"> ?endNode .\n"+
"?endNode <"+ type +"> <"+ dateTimeValueType +"> .\n"+
"?endNode <"+ dateTimePrecision +"> ?existingEndPrecision . }";
//Query for inverse property
final static String inverseTrainingAtPersonQuery =
"PREFIX owl: <http://www.w3.person/2002/07/owl#>"
+ " SELECT ?inverseTrainingAtPerson "
+ " WHERE { ?inverseTrainingAtPerson owl:inverseOf <http://vivoweb.org/ontology/core#relates> . } ";
//Adding form specific data such as edit mode
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
formSpecificData.put("editMode", getEditMode(vreq).name().toLowerCase());
editConfiguration.setFormSpecificData(formSpecificData);
}
public EditMode getEditMode(VitroRequest vreq) {
List<String> predicates = new ArrayList<String>();
predicates.add("http://vivoweb.org/ontology/core#relates");

View file

@ -113,7 +113,7 @@ public class OrganizationHasPositionHistoryGenerator extends VivoBaseGenerator
+ "@prefix core: <http://vivoweb.org/ontology/core#> . \n"
+ "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . \n"
+ "?organization core:relatedBy ?position . \n"
+ "?position a core:Position . \n"
+ "?position a core:Position . \n"
+ "?position a ?positionType . \n"
+ "?position rdfs:label ?positionTitle . \n"
+ "?position core:relates ?organization . ";
@ -122,7 +122,7 @@ public class OrganizationHasPositionHistoryGenerator extends VivoBaseGenerator
+ "@prefix core: <http://vivoweb.org/ontology/core#> . \n"
+ "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . \n"
+ "@prefix foaf: <http://xmlns.com/foaf/0.1/> . \n"
+ "?position core:relates ?person . \n"
+ "?position core:relates ?person . \n"
+ "?person core:relatedBy ?position . \n"
+ "?person a foaf:Person . \n"
+ "?person rdfs:label ?personLabel . ";
@ -147,7 +147,7 @@ public class OrganizationHasPositionHistoryGenerator extends VivoBaseGenerator
private static final String N3_EXISTING_PERSON = ""
+ "@prefix core: <http://vivoweb.org/ontology/core#> . \n"
+ "?position core:relates ?existingPerson . \n"
+ "?position core:relates ?existingPerson . \n"
+ "?existingPerson core:relatedBy ?position . \n";
private static final String N3_NEW_START_NODE = ""
@ -221,7 +221,7 @@ public class OrganizationHasPositionHistoryGenerator extends VivoBaseGenerator
conf.addField(new FieldVTwo()
.setName("positionType")
.setValidators(list("nonempty"))
.setOptions(
.setOptions(
new ChildVClassesWithParent(URI_POSITION_CLASS))
);
@ -260,7 +260,7 @@ public class OrganizationHasPositionHistoryGenerator extends VivoBaseGenerator
conf.addValidator(new AntiXssValidation());
conf.addValidator(new DateTimeIntervalValidationVTwo("startField",
"endField"));
prepare(vreq, conf);
return conf;
}

View file

@ -37,25 +37,25 @@ public class PersonHasAdviseeRelationshipGenerator extends VivoBaseGenerator imp
final static String dateTimeValueType = vivoCore + "DateTimeValue";
final static String dateTimeValue = vivoCore + "dateTime";
final static String dateTimePrecision = vivoCore + "dateTimePrecision";
public PersonHasAdviseeRelationshipGenerator() {}
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
HttpSession session) throws Exception {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
initObjectPropForm(conf, vreq);
conf.setTemplate("personHasAdviseeRelationship.ftl");
conf.setVarNameForSubject("person");
conf.setVarNameForPredicate("predicate");
conf.setVarNameForObject("adviseeRole");
conf.setN3Required( Arrays.asList( n3ForNewAdvisingRelationship,
advisingRelLabelAssertion,
advisingRelTypeAssertion ) );
@ -66,9 +66,9 @@ public class PersonHasAdviseeRelationshipGenerator extends VivoBaseGenerator imp
lastNameAssertion,
n3ForExistingSubjAreaAssertion, //relationship to existing subject area
n3ForNewSubjAreaAssertion, //this will include all the new information that needs to be captured
n3ForStart,
n3ForStart,
n3ForEnd ) );
conf.addNewResource("advisingRelationship", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("newAdvisor", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("vcardAdvisor", DEFAULT_NS_FOR_NEW_RESOURCE);
@ -79,19 +79,19 @@ public class PersonHasAdviseeRelationshipGenerator extends VivoBaseGenerator imp
conf.addNewResource("intervalNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("startNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("endNode", DEFAULT_NS_FOR_NEW_RESOURCE);
//uris in scope: none
//uris in scope: none
//literals in scope: none
conf.setUrisOnform(Arrays.asList("advisingRelType", "existingSubjArea", "degree", "existingAdvisor"));
conf.setLiteralsOnForm(Arrays.asList("advisingRelLabel", "subjAreaLabel", "advisorLabel", "firstName", "lastName", "subjAreaLabelDisplay", "advisorLabelDisplay" ));
conf.addSparqlForExistingLiteral("advisingRelLabel", advisingRelLabelQuery);
conf.addSparqlForExistingLiteral("advisorLabel", advisorLabelQuery);
conf.addSparqlForExistingLiteral("subjAreaLabel", subjAreaLabelQuery);
conf.addSparqlForExistingLiteral("startField-value", existingStartDateQuery);
conf.addSparqlForExistingLiteral("endField-value", existingEndDateQuery);
conf.addSparqlForExistingUris("advisingRelType", advisingRelTypeQuery);
conf.addSparqlForExistingUris("advisingRelationship", existingAdvisingRelQuery);
conf.addSparqlForExistingUris("advisorRole", existingAdvisorRoleQuery);
@ -103,8 +103,8 @@ public class PersonHasAdviseeRelationshipGenerator extends VivoBaseGenerator imp
conf.addSparqlForExistingUris("endNode", existingEndNodeQuery);
conf.addSparqlForExistingUris("startField-precision", existingStartPrecisionQuery);
conf.addSparqlForExistingUris("endField-precision", existingEndPrecisionQuery);
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("advisingRelType").
setValidators( list("nonempty") ).
setOptions( new ChildVClassesWithParent(advisingRelClass))
@ -129,8 +129,8 @@ public class PersonHasAdviseeRelationshipGenerator extends VivoBaseGenerator imp
);
conf.addField( new FieldVTwo(). // options set by auto complete JS
setName("existingSubjArea")
);
setName("existingSubjArea")
);
conf.addField( new FieldVTwo().
setName("subjAreaLabel").
@ -140,13 +140,13 @@ public class PersonHasAdviseeRelationshipGenerator extends VivoBaseGenerator imp
conf.addField( new FieldVTwo().
setName("degree").
setOptions(
setOptions(
new IndividualsViaVClassOptions(degreeClass))
);
conf.addField( new FieldVTwo(). // options set by auto complete JS
setName("existingAdvisor")
);
setName("existingAdvisor")
);
conf.addField( new FieldVTwo().
setName("advisorLabel").
@ -167,16 +167,16 @@ public class PersonHasAdviseeRelationshipGenerator extends VivoBaseGenerator imp
);
conf.addField( new FieldVTwo().setName("startField").
setEditElement(
new DateTimeWithPrecisionVTwo(null,
setEditElement(
new DateTimeWithPrecisionVTwo(null,
VitroVocabulary.Precision.YEAR.uri(),
VitroVocabulary.Precision.NONE.uri())
)
);
conf.addField( new FieldVTwo().setName("endField").
setEditElement(
new DateTimeWithPrecisionVTwo(null,
setEditElement(
new DateTimeWithPrecisionVTwo(null,
VitroVocabulary.Precision.YEAR.uri(),
VitroVocabulary.Precision.NONE.uri())
)
@ -186,98 +186,98 @@ public class PersonHasAdviseeRelationshipGenerator extends VivoBaseGenerator imp
conf.addValidator(new AntiXssValidation());
conf.addValidator(new FirstAndLastNameValidator("existingAdvisor"));
addFormSpecificData(conf, vreq);
prepare(vreq, conf);
return conf;
}
/* N3 assertions */
final static String n3ForNewAdvisingRelationship =
"@prefix vivo: <" + vivoCore + "> . \n\n" +
final static String n3ForNewAdvisingRelationship =
"@prefix vivo: <" + vivoCore + "> . \n\n" +
"?person <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
"?advisingRelationship a <" + advisingRelClass + "> . \n" +
"?advisingRelationship a <" + advisingRelClass + "> . \n" +
"?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?person . \n" +
"?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?adviseeRole . \n" +
"?adviseeRole a <" + adviseeRoleClass + "> . \n" +
"?adviseeRole a <" + adviseeRoleClass + "> . \n" +
"?adviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
"?person <http://purl.obolibrary.org/obo/RO_0000053> ?adviseeRole . \n" +
"?adviseeRole <http://purl.obolibrary.org/obo/RO_0000052> ?person . ";
final static String advisingRelLabelAssertion =
final static String advisingRelLabelAssertion =
"?advisingRelationship <"+ label + "> ?advisingRelLabel .";
final static String advisingRelTypeAssertion =
final static String advisingRelTypeAssertion =
"?advisingRelationship a ?advisingRelType .";
final static String n3ForNewAdvisorAssertion =
final static String n3ForNewAdvisorAssertion =
"?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?newAdvisor . \n" +
"?newAdvisor <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
"?newAdvisor <" + label + "> ?advisorLabel . \n" +
"?newAdvisor a <" + advisorClass + "> . \n" +
"?newAdvisor <http://purl.obolibrary.org/obo/RO_0000053> ?advisorRole . \n" +
"?advisorRole <http://purl.obolibrary.org/obo/RO_0000052> ?newAdvisor . \n" +
"?advisorRole a <" + advisorRoleClass + "> . \n" +
"?advisorRole a <" + advisorRoleClass + "> . \n" +
"?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?advisorRole . \n" +
"?advisorRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . ";
final static String n3ForExistingAdvisorAssertion =
final static String n3ForExistingAdvisorAssertion =
"?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?existingAdvisor . \n" +
"?existingAdvisor <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
"?existingAdvisor <http://purl.obolibrary.org/obo/RO_0000053> ?advisorRole . \n" +
"?advisorRole <http://purl.obolibrary.org/obo/RO_0000052> ?existingAdvisor . \n" +
"?advisorRole a <" + advisorRoleClass + "> . \n" +
"?advisorRole a <" + advisorRoleClass + "> . \n" +
"?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?advisorRole . \n" +
"?advisorRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . ";
final static String firstNameAssertion =
final static String firstNameAssertion =
"@prefix vcard: <http://www.w3.org/2006/vcard/ns#> . \n" +
"?newAdvisor <http://purl.obolibrary.org/obo/ARG_2000028> ?vcardAdvisor . \n" +
"?vcardAdvisor <http://purl.obolibrary.org/obo/ARG_2000029> ?newAdvisor . \n" +
"?vcardAdvisor a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardAdvisor a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardAdvisor vcard:hasName ?vcardName . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName vcard:givenName ?firstName .";
final static String lastNameAssertion =
final static String lastNameAssertion =
"@prefix vcard: <http://www.w3.org/2006/vcard/ns#> . \n" +
"?newAdvisor <http://purl.obolibrary.org/obo/ARG_2000028> ?vcardAdvisor . \n" +
"?vcardAdvisor <http://purl.obolibrary.org/obo/ARG_2000029> ?newAdvisor . \n" +
"?vcardAdvisor a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardAdvisor a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardAdvisor vcard:hasName ?vcardName . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName vcard:familyName ?lastName .";
final static String degreeAssertion =
final static String degreeAssertion =
"?advisingRelationship <http://vivoweb.org/ontology/core#degreeCandidacy> ?degree . \n" +
" ";
//This is for an existing subject area
//Where we only need the existing subject area label
final static String n3ForExistingSubjAreaAssertion =
final static String n3ForExistingSubjAreaAssertion =
"?advisingRelationship <http://vivoweb.org/ontology/core#hasSubjectArea> ?existingSubjArea . \n" +
"?existingSubjArea <http://vivoweb.org/ontology/core#subjectAreaOf> ?advisingRelationship . ";
"?existingSubjArea <http://vivoweb.org/ontology/core#subjectAreaOf> ?advisingRelationship . ";
//For new subject area, we include all new information
//new subject area should always be a new resource
//and the following should only get evaluated
//and the following should only get evaluated
//when there is something in the label
final static String n3ForNewSubjAreaAssertion =
"?advisingRelationship <http://vivoweb.org/ontology/core#hasSubjectArea> ?newSubjArea . \n" +
"?newSubjArea <http://vivoweb.org/ontology/core#subjectAreaOf> ?advisingRelationship . \n" +
"?newSubjArea <"+ label + "> ?subjAreaLabel . \n" +
"?newSubjArea a <" + subjAreaClass + "> . ";
final static String n3ForNewSubjAreaAssertion =
"?advisingRelationship <http://vivoweb.org/ontology/core#hasSubjectArea> ?newSubjArea . \n" +
"?newSubjArea <http://vivoweb.org/ontology/core#subjectAreaOf> ?advisingRelationship . \n" +
"?newSubjArea <"+ label + "> ?subjAreaLabel . \n" +
"?newSubjArea a <" + subjAreaClass + "> . ";
final static String n3ForStart =
"?advisingRelationship <" + advisingRelToInterval + "> ?intervalNode . \n" +
"?advisingRelationship <" + advisingRelToInterval + "> ?intervalNode . \n" +
"?intervalNode a <" + intervalType + "> . \n" +
"?intervalNode <" + intervalToStart + "> ?startNode . \n" +
"?intervalNode <" + intervalToStart + "> ?startNode . \n" +
"?startNode a <" + dateTimeValueType + "> . \n" +
"?startNode <" + dateTimeValue + "> ?startField-value . \n" +
"?startNode <" + dateTimePrecision + "> ?startField-precision . \n";
final static String n3ForEnd =
"?advisingRelationship <" + advisingRelToInterval + "> ?intervalNode . \n" +
"?advisingRelationship <" + advisingRelToInterval + "> ?intervalNode . \n" +
"?intervalNode a <" + intervalType + "> . \n" +
"?intervalNode <" + intervalToEnd + "> ?endNode . \n" +
"?endNode a <" + dateTimeValueType + "> . \n" +
@ -286,7 +286,7 @@ public class PersonHasAdviseeRelationshipGenerator extends VivoBaseGenerator imp
/* Queries for editing an existing entry */
final static String existingAdvisingRelQuery =
final static String existingAdvisingRelQuery =
"SELECT ?advisingRelationship WHERE { \n" +
" ?adviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?adviseeRole . \n" +
@ -297,7 +297,7 @@ public class PersonHasAdviseeRelationshipGenerator extends VivoBaseGenerator imp
"SELECT ?advisingRelType WHERE { \n" +
" ?adviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?adviseeRole . \n" +
" ?advisingRelationship vitro:mostSpecificType ?advisingRelType . \n" +
" ?advisingRelationship vitro:mostSpecificType ?advisingRelType . \n" +
"}";
final static String advisingRelLabelQuery =
@ -307,7 +307,7 @@ public class PersonHasAdviseeRelationshipGenerator extends VivoBaseGenerator imp
" ?advisingRelationship <" + label + "> ?existingAdvisingRelLabel . \n" +
"}";
final static String advisorQuery =
final static String advisorQuery =
"SELECT ?existingAdvisor WHERE { \n" +
" ?adviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?adviseeRole . \n" +
@ -330,13 +330,13 @@ public class PersonHasAdviseeRelationshipGenerator extends VivoBaseGenerator imp
" ?existingAdvisorRole a <" + advisorRoleClass + "> . \n" +
"}";
final static String existingAdvisorRoleQuery =
final static String existingAdvisorRoleQuery =
"SELECT ?existingAdvisorRole WHERE { \n" +
" ?adviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?adviseeRole . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?existingAdvisorRole . \n" +
" ?existingAdvisorRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?existingAdvisorRole a <" + advisorRoleClass + "> . \n" +
" ?existingAdvisorRole a <" + advisorRoleClass + "> . \n" +
"}";
final static String subjAreaQuery =
@ -348,7 +348,7 @@ public class PersonHasAdviseeRelationshipGenerator extends VivoBaseGenerator imp
" ?existingSubjArea <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#mostSpecificType> ?type \n" +
"}";
final static String subjAreaLabelQuery =
final static String subjAreaLabelQuery =
"SELECT ?existingSubjAreaLabel WHERE { \n" +
" ?adviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?adviseeRole . \n" +
@ -358,14 +358,14 @@ public class PersonHasAdviseeRelationshipGenerator extends VivoBaseGenerator imp
" ?existingSubjArea <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#mostSpecificType> ?type \n" +
"}";
final static String degreeQuery =
final static String degreeQuery =
"SELECT ?existingDegree WHERE {\n"+
" ?adviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?adviseeRole . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#degreeCandidacy> ?existingDegree . \n" +
" ?existingDegree a <" + degreeClass + "> . \n" +
"}";
final static String existingStartDateQuery =
"SELECT ?existingDateStart WHERE { \n" +
" ?adviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
@ -375,7 +375,7 @@ public class PersonHasAdviseeRelationshipGenerator extends VivoBaseGenerator imp
" ?intervalNode <" + intervalToStart + "> ?startNode . \n" +
" ?startNode a <" + dateTimeValueType +"> . \n" +
" ?startNode <" + dateTimeValue + "> ?existingDateStart . }";
final static String existingEndDateQuery =
"SELECT ?existingEndDate WHERE { \n" +
" ?adviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
@ -387,48 +387,48 @@ public class PersonHasAdviseeRelationshipGenerator extends VivoBaseGenerator imp
" ?endNode <" + dateTimeValue + "> ?existingEndDate . }";
final static String existingIntervalNodeQuery =
"SELECT ?existingIntervalNode WHERE { \n" +
"SELECT ?existingIntervalNode WHERE { \n" +
" ?adviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?adviseeRole . \n" +
" ?advisingRelationship <" + advisingRelToInterval + "> ?existingIntervalNode . \n" +
" ?existingIntervalNode a <" + intervalType + "> . }";
final static String existingStartNodeQuery =
final static String existingStartNodeQuery =
"SELECT ?existingStartNode WHERE { \n" +
" ?adviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?adviseeRole . \n" +
" ?advisingRelationship <" + advisingRelToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToStart + "> ?existingStartNode . \n" +
" ?intervalNode <" + intervalToStart + "> ?existingStartNode . \n" +
" ?existingStartNode a <" + dateTimeValueType + "> .} ";
final static String existingEndNodeQuery =
final static String existingEndNodeQuery =
"SELECT ?existingEndNode WHERE { \n" +
" ?adviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?adviseeRole . \n" +
" ?advisingRelationship <" + advisingRelToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToEnd + "> ?existingEndNode . \n" +
" ?existingEndNode a <" + dateTimeValueType + "> } ";
" ?intervalNode <" + intervalToEnd + "> ?existingEndNode . \n" +
" ?existingEndNode a <" + dateTimeValueType + "> } ";
final static String existingStartPrecisionQuery =
final static String existingStartPrecisionQuery =
"SELECT ?existingStartPrecision WHERE { \n" +
" ?adviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?adviseeRole . \n" +
" ?advisingRelationship <" + advisingRelToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToStart + "> ?startNode . \n" +
" ?startNode a <" + dateTimeValueType + "> . \n" +
" ?startNode a <" + dateTimeValueType + "> . \n" +
" ?startNode <" + dateTimePrecision + "> ?existingStartPrecision . }";
final static String existingEndPrecisionQuery =
final static String existingEndPrecisionQuery =
"SELECT ?existingEndPrecision WHERE { \n" +
" ?adviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?adviseeRole . \n" +
" ?advisingRelationship <" + advisingRelToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToEnd + "> ?endNode . \n" +
" ?endNode a <" + dateTimeValueType + "> . \n" +
" ?endNode a <" + dateTimeValueType + "> . \n" +
" ?endNode <" + dateTimePrecision + "> ?existingEndPrecision . }";
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
@ -438,10 +438,10 @@ public class PersonHasAdviseeRelationshipGenerator extends VivoBaseGenerator imp
}
public String getSparqlForAcFilter(VitroRequest vreq) {
String subject = EditConfigurationUtils.getSubjectUri(vreq);
String subject = EditConfigurationUtils.getSubjectUri(vreq);
String predicate = EditConfigurationUtils.getPredicateUri(vreq);
//Get all objects for existing predicate, filters out results from addition and edit
String query = "SELECT ?objectVar WHERE { " +
String query = "SELECT ?objectVar WHERE { " +
"<" + subject + "> <" + predicate + "> ?objectVar .} ";
return query;
}

View file

@ -37,25 +37,25 @@ public class PersonHasAdvisorRelationshipGenerator extends VivoBaseGenerator imp
final static String dateTimeValueType = vivoCore + "DateTimeValue";
final static String dateTimeValue = vivoCore + "dateTime";
final static String dateTimePrecision = vivoCore + "dateTimePrecision";
public PersonHasAdvisorRelationshipGenerator() {}
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
HttpSession session) throws Exception {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
initObjectPropForm(conf, vreq);
conf.setTemplate("personHasAdvisorRelationship.ftl");
conf.setVarNameForSubject("person");
conf.setVarNameForPredicate("predicate");
conf.setVarNameForObject("advisorRole");
conf.setN3Required( Arrays.asList( n3ForNewAdvisingRelationship,
advisingRelLabelAssertion,
advisingRelTypeAssertion ) );
@ -66,9 +66,9 @@ public class PersonHasAdvisorRelationshipGenerator extends VivoBaseGenerator imp
lastNameAssertion,
n3ForExistingSubjAreaAssertion, //relationship to existing subject area
n3ForNewSubjAreaAssertion, //this will include all the new information that needs to be captured
n3ForStart,
n3ForStart,
n3ForEnd ) );
conf.addNewResource("advisingRelationship", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("newAdvisee", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("vcardAdvisee", DEFAULT_NS_FOR_NEW_RESOURCE);
@ -79,19 +79,19 @@ public class PersonHasAdvisorRelationshipGenerator extends VivoBaseGenerator imp
conf.addNewResource("intervalNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("startNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("endNode", DEFAULT_NS_FOR_NEW_RESOURCE);
//uris in scope: none
//uris in scope: none
//literals in scope: none
conf.setUrisOnform(Arrays.asList("advisingRelType", "existingSubjArea", "degree", "existingAdvisee"));
conf.setLiteralsOnForm(Arrays.asList("advisingRelLabel", "subjAreaLabel", "adviseeLabel", "firstName", "lastName", "subjAreaLabelDisplay", "adviseeLabelDisplay" ));
conf.addSparqlForExistingLiteral("advisingRelLabel", advisingRelLabelQuery);
conf.addSparqlForExistingLiteral("adviseeLabel", adviseeLabelQuery);
conf.addSparqlForExistingLiteral("subjAreaLabel", subjAreaLabelQuery);
conf.addSparqlForExistingLiteral("startField-value", existingStartDateQuery);
conf.addSparqlForExistingLiteral("endField-value", existingEndDateQuery);
conf.addSparqlForExistingUris("advisingRelType", advisingRelTypeQuery);
conf.addSparqlForExistingUris("advisingRelationship", existingAdvisingRelQuery);
conf.addSparqlForExistingUris("adviseeRole", existingAdviseeRoleQuery);
@ -103,8 +103,8 @@ public class PersonHasAdvisorRelationshipGenerator extends VivoBaseGenerator imp
conf.addSparqlForExistingUris("endNode", existingEndNodeQuery);
conf.addSparqlForExistingUris("startField-precision", existingStartPrecisionQuery);
conf.addSparqlForExistingUris("endField-precision", existingEndPrecisionQuery);
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("advisingRelType").
setValidators( list("nonempty") ).
setOptions( new ChildVClassesWithParent(advisingRelClass))
@ -129,8 +129,8 @@ public class PersonHasAdvisorRelationshipGenerator extends VivoBaseGenerator imp
);
conf.addField( new FieldVTwo(). // options set by auto complete JS
setName("existingSubjArea")
);
setName("existingSubjArea")
);
conf.addField( new FieldVTwo().
setName("subjAreaLabel").
@ -140,13 +140,13 @@ public class PersonHasAdvisorRelationshipGenerator extends VivoBaseGenerator imp
conf.addField( new FieldVTwo().
setName("degree").
setOptions(
setOptions(
new IndividualsViaVClassOptions(degreeClass))
);
conf.addField( new FieldVTwo(). // options set by auto complete JS
setName("existingAdvisee")
);
setName("existingAdvisee")
);
conf.addField( new FieldVTwo().
setName("adviseeLabel").
@ -167,16 +167,16 @@ public class PersonHasAdvisorRelationshipGenerator extends VivoBaseGenerator imp
);
conf.addField( new FieldVTwo().setName("startField").
setEditElement(
new DateTimeWithPrecisionVTwo(null,
setEditElement(
new DateTimeWithPrecisionVTwo(null,
VitroVocabulary.Precision.YEAR.uri(),
VitroVocabulary.Precision.NONE.uri())
)
);
conf.addField( new FieldVTwo().setName("endField").
setEditElement(
new DateTimeWithPrecisionVTwo(null,
setEditElement(
new DateTimeWithPrecisionVTwo(null,
VitroVocabulary.Precision.YEAR.uri(),
VitroVocabulary.Precision.NONE.uri())
)
@ -186,98 +186,98 @@ public class PersonHasAdvisorRelationshipGenerator extends VivoBaseGenerator imp
conf.addValidator(new AntiXssValidation());
conf.addValidator(new FirstAndLastNameValidator("existingAdvisee"));
addFormSpecificData(conf, vreq);
prepare(vreq, conf);
return conf;
}
/* N3 assertions */
final static String n3ForNewAdvisingRelationship =
"@prefix vivo: <" + vivoCore + "> . \n\n" +
final static String n3ForNewAdvisingRelationship =
"@prefix vivo: <" + vivoCore + "> . \n\n" +
"?person <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
"?advisingRelationship a <" + advisingRelClass + "> . \n" +
"?advisingRelationship a <" + advisingRelClass + "> . \n" +
"?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?person . \n" +
"?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?advisorRole . \n" +
"?advisorRole a <" + advisorRoleClass + "> . \n" +
"?advisorRole a <" + advisorRoleClass + "> . \n" +
"?advisorRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
"?person <http://purl.obolibrary.org/obo/RO_0000053> ?advisorRole . \n" +
"?advisorRole <http://purl.obolibrary.org/obo/RO_0000052> ?person . ";
final static String advisingRelLabelAssertion =
final static String advisingRelLabelAssertion =
"?advisingRelationship <"+ label + "> ?advisingRelLabel .";
final static String advisingRelTypeAssertion =
final static String advisingRelTypeAssertion =
"?advisingRelationship a ?advisingRelType .";
final static String n3ForNewAdviseeAssertion =
final static String n3ForNewAdviseeAssertion =
"?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?newAdvisee . \n" +
"?newAdvisee <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
"?newAdvisee <" + label + "> ?adviseeLabel . \n" +
"?newAdvisee a <" + adviseeClass + "> . \n" +
"?newAdvisee <http://purl.obolibrary.org/obo/RO_0000053> ?adviseeRole . \n" +
"?adviseeRole <http://purl.obolibrary.org/obo/RO_0000052> ?newAdvisee . \n" +
"?adviseeRole a <" + adviseeRoleClass + "> . \n" +
"?adviseeRole a <" + adviseeRoleClass + "> . \n" +
"?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?adviseeRole . \n" +
"?adviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . ";
final static String n3ForExistingAdviseeAssertion =
final static String n3ForExistingAdviseeAssertion =
"?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?existingAdvisee . \n" +
"?existingAdvisee <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
"?existingAdvisee <http://purl.obolibrary.org/obo/RO_0000053> ?adviseeRole . \n" +
"?adviseeRole <http://purl.obolibrary.org/obo/RO_0000052> ?existingAdvisee . \n" +
"?adviseeRole a <" + adviseeRoleClass + "> . \n" +
"?adviseeRole a <" + adviseeRoleClass + "> . \n" +
"?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?adviseeRole . \n" +
"?adviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . ";
final static String firstNameAssertion =
final static String firstNameAssertion =
"@prefix vcard: <http://www.w3.org/2006/vcard/ns#> . \n" +
"?newAdvisee <http://purl.obolibrary.org/obo/ARG_2000028> ?vcardAdvisee . \n" +
"?vcardAdvisee <http://purl.obolibrary.org/obo/ARG_2000029> ?newAdvisee . \n" +
"?vcardAdvisee a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardAdvisee a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardAdvisee vcard:hasName ?vcardName . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName vcard:givenName ?firstName .";
final static String lastNameAssertion =
final static String lastNameAssertion =
"@prefix vcard: <http://www.w3.org/2006/vcard/ns#> . \n" +
"?newAdvisee <http://purl.obolibrary.org/obo/ARG_2000028> ?vcardAdvisee . \n" +
"?vcardAdvisee <http://purl.obolibrary.org/obo/ARG_2000029> ?newAdvisee . \n" +
"?vcardAdvisee a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardAdvisee a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardAdvisee vcard:hasName ?vcardName . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName vcard:familyName ?lastName .";
final static String degreeAssertion =
final static String degreeAssertion =
"?advisingRelationship <http://vivoweb.org/ontology/core#degreeCandidacy> ?degree . \n" +
" ";
//This is for an existing subject area
//Where we only need the existing subject area label
final static String n3ForExistingSubjAreaAssertion =
final static String n3ForExistingSubjAreaAssertion =
"?advisingRelationship <http://vivoweb.org/ontology/core#hasSubjectArea> ?existingSubjArea . \n" +
"?existingSubjArea <http://vivoweb.org/ontology/core#subjectAreaOf> ?advisingRelationship";
"?existingSubjArea <http://vivoweb.org/ontology/core#subjectAreaOf> ?advisingRelationship";
//For new subject area, we include all new information
//new subject area should always be a new resource
//and the following should only get evaluated
//and the following should only get evaluated
//when there is something in the label
final static String n3ForNewSubjAreaAssertion =
"?advisingRelationship <http://vivoweb.org/ontology/core#hasSubjectArea> ?newSubjArea . \n" +
"?newSubjArea <http://vivoweb.org/ontology/core#subjectAreaOf> ?advisingRelationship . \n" +
"?newSubjArea <"+ label + "> ?subjAreaLabel . \n" +
"?newSubjArea a <" + subjAreaClass + "> . ";
final static String n3ForNewSubjAreaAssertion =
"?advisingRelationship <http://vivoweb.org/ontology/core#hasSubjectArea> ?newSubjArea . \n" +
"?newSubjArea <http://vivoweb.org/ontology/core#subjectAreaOf> ?advisingRelationship . \n" +
"?newSubjArea <"+ label + "> ?subjAreaLabel . \n" +
"?newSubjArea a <" + subjAreaClass + "> . ";
final static String n3ForStart =
"?advisingRelationship <" + advisingRelToInterval + "> ?intervalNode . \n" +
"?advisingRelationship <" + advisingRelToInterval + "> ?intervalNode . \n" +
"?intervalNode a <" + intervalType + "> . \n" +
"?intervalNode <" + intervalToStart + "> ?startNode . \n" +
"?intervalNode <" + intervalToStart + "> ?startNode . \n" +
"?startNode a <" + dateTimeValueType + "> . \n" +
"?startNode <" + dateTimeValue + "> ?startField-value . \n" +
"?startNode <" + dateTimePrecision + "> ?startField-precision . \n";
final static String n3ForEnd =
"?advisingRelationship <" + advisingRelToInterval + "> ?intervalNode . \n" +
"?advisingRelationship <" + advisingRelToInterval + "> ?intervalNode . \n" +
"?intervalNode a <" + intervalType + "> . \n" +
"?intervalNode <" + intervalToEnd + "> ?endNode . \n" +
"?endNode a <" + dateTimeValueType + "> . \n" +
@ -286,7 +286,7 @@ public class PersonHasAdvisorRelationshipGenerator extends VivoBaseGenerator imp
/* Queries for editing an existing entry */
final static String existingAdvisingRelQuery =
final static String existingAdvisingRelQuery =
"SELECT ?advisingRelationship WHERE { \n" +
" ?advisorRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?advisorRole . \n" +
@ -294,10 +294,10 @@ public class PersonHasAdvisorRelationshipGenerator extends VivoBaseGenerator imp
final static String advisingRelTypeQuery =
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
"SELECT ?advisingRelType WHERE { \n" +
"SELECT ?advisingRelType WHERE { \n" +
" ?advisorRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?advisorRole . \n" +
" ?advisingRelationship vitro:mostSpecificType ?advisingRelType . \n" +
" ?advisingRelationship vitro:mostSpecificType ?advisingRelType . \n" +
"}";
final static String advisingRelLabelQuery =
@ -307,7 +307,7 @@ public class PersonHasAdvisorRelationshipGenerator extends VivoBaseGenerator imp
" ?advisingRelationship <" + label + "> ?existingAdvisingRelLabel . \n" +
"}";
final static String adviseeQuery =
final static String adviseeQuery =
"SELECT ?existingAdvisee WHERE { \n" +
" ?advisorRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?advisorRole . \n" +
@ -332,13 +332,13 @@ public class PersonHasAdvisorRelationshipGenerator extends VivoBaseGenerator imp
" ?existingAdviseeRole a <" + adviseeRoleClass + "> . \n" +
"}";
final static String existingAdviseeRoleQuery =
final static String existingAdviseeRoleQuery =
"SELECT ?existingAdviseeRole WHERE { \n" +
" ?advisorRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?advisorRole . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?existingAdviseeRole . \n" +
" ?existingAdviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?existingAdviseeRole a <" + adviseeRoleClass + "> . \n" +
" ?existingAdviseeRole a <" + adviseeRoleClass + "> . \n" +
"}";
final static String subjAreaQuery =
@ -350,7 +350,7 @@ public class PersonHasAdvisorRelationshipGenerator extends VivoBaseGenerator imp
" ?existingSubjArea <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#mostSpecificType> ?type \n" +
"}";
final static String subjAreaLabelQuery =
final static String subjAreaLabelQuery =
"SELECT ?existingSubjAreaLabel WHERE { \n" +
" ?advisorRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?advisorRole . \n" +
@ -360,14 +360,14 @@ public class PersonHasAdvisorRelationshipGenerator extends VivoBaseGenerator imp
" ?existingSubjArea <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#mostSpecificType> ?type \n" +
"}";
final static String degreeQuery =
final static String degreeQuery =
"SELECT ?existingDegree WHERE {\n"+
" ?advisorRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?advisorRole . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#degreeCandidacy> ?existingDegree . \n" +
" ?existingDegree a <" + degreeClass + "> . \n" +
"}";
final static String existingStartDateQuery =
"SELECT ?existingDateStart WHERE { \n" +
" ?advisorRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
@ -377,7 +377,7 @@ public class PersonHasAdvisorRelationshipGenerator extends VivoBaseGenerator imp
" ?intervalNode <" + intervalToStart + "> ?startNode . \n" +
" ?startNode a <" + dateTimeValueType +"> . \n" +
" ?startNode <" + dateTimeValue + "> ?existingDateStart . }";
final static String existingEndDateQuery =
"SELECT ?existingEndDate WHERE { \n" +
" ?advisorRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
@ -389,48 +389,48 @@ public class PersonHasAdvisorRelationshipGenerator extends VivoBaseGenerator imp
" ?endNode <" + dateTimeValue + "> ?existingEndDate . }";
final static String existingIntervalNodeQuery =
"SELECT ?existingIntervalNode WHERE { \n" +
"SELECT ?existingIntervalNode WHERE { \n" +
" ?advisorRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?advisorRole . \n" +
" ?advisingRelationship <" + advisingRelToInterval + "> ?existingIntervalNode . \n" +
" ?existingIntervalNode a <" + intervalType + "> . }";
final static String existingStartNodeQuery =
final static String existingStartNodeQuery =
"SELECT ?existingStartNode WHERE { \n" +
" ?advisorRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?advisorRole . \n" +
" ?advisingRelationship <" + advisingRelToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToStart + "> ?existingStartNode . \n" +
" ?intervalNode <" + intervalToStart + "> ?existingStartNode . \n" +
" ?existingStartNode a <" + dateTimeValueType + "> .} ";
final static String existingEndNodeQuery =
final static String existingEndNodeQuery =
"SELECT ?existingEndNode WHERE { \n" +
" ?advisorRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?advisorRole . \n" +
" ?advisingRelationship <" + advisingRelToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToEnd + "> ?existingEndNode . \n" +
" ?existingEndNode a <" + dateTimeValueType + "> } ";
" ?intervalNode <" + intervalToEnd + "> ?existingEndNode . \n" +
" ?existingEndNode a <" + dateTimeValueType + "> } ";
final static String existingStartPrecisionQuery =
final static String existingStartPrecisionQuery =
"SELECT ?existingStartPrecision WHERE { \n" +
" ?advisorRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?advisorRole . \n" +
" ?advisingRelationship <" + advisingRelToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToStart + "> ?startNode . \n" +
" ?startNode a <" + dateTimeValueType + "> . \n" +
" ?startNode a <" + dateTimeValueType + "> . \n" +
" ?startNode <" + dateTimePrecision + "> ?existingStartPrecision . }";
final static String existingEndPrecisionQuery =
final static String existingEndPrecisionQuery =
"SELECT ?existingEndPrecision WHERE { \n" +
" ?advisorRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?advisorRole . \n" +
" ?advisingRelationship <" + advisingRelToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToEnd + "> ?endNode . \n" +
" ?endNode a <" + dateTimeValueType + "> . \n" +
" ?endNode a <" + dateTimeValueType + "> . \n" +
" ?endNode <" + dateTimePrecision + "> ?existingEndPrecision . }";
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
@ -440,10 +440,10 @@ public class PersonHasAdvisorRelationshipGenerator extends VivoBaseGenerator imp
}
public String getSparqlForAcFilter(VitroRequest vreq) {
String subject = EditConfigurationUtils.getSubjectUri(vreq);
String subject = EditConfigurationUtils.getSubjectUri(vreq);
String predicate = EditConfigurationUtils.getPredicateUri(vreq);
//Get all objects for existing predicate, filters out results from addition and edit
String query = "SELECT ?objectVar WHERE { " +
String query = "SELECT ?objectVar WHERE { " +
"<" + subject + "> <" + predicate + "> ?objectVar .} ";
return query;
}

View file

@ -38,38 +38,38 @@ public class PersonHasAwardOrHonorGenerator extends VivoBaseGenerator implements
final static String dateTimeValueType = vivoCore + "DateTimeValue";
final static String dateTimeValue = vivoCore + "dateTime";
final static String dateTimePrecision = vivoCore + "dateTimePrecision";
public PersonHasAwardOrHonorGenerator() {}
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
HttpSession session) throws Exception {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
initObjectPropForm(conf, vreq);
conf.setTemplate("personHasAwardOrHonor.ftl");
conf.setVarNameForSubject("person");
conf.setVarNameForPredicate("predicate");
conf.setVarNameForObject("awardReceipt");
conf.setN3Required( Arrays.asList( n3ForNewAwardReceipt,
awardReceiptLabelAssertion ) );
conf.setN3Optional( Arrays.asList( n3ForNewAwardAssertion,
n3ForExistingAwardAssertion,
descriptionAssertion,
conf.setN3Optional( Arrays.asList( n3ForNewAwardAssertion,
n3ForExistingAwardAssertion,
descriptionAssertion,
n3ForNewOrgNewAwardAssertion,
n3ForExistingOrgNewAwardAssertion,
n3ForNewOrgExistingAwardAssertion,
n3ForExistingOrgExistingAwardAssertion,
n3ForYearAwarded,
n3ForStart,
n3ForYearAwarded,
n3ForStart,
n3ForEnd ) );
conf.addNewResource("award", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("awardReceipt", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("newOrg", DEFAULT_NS_FOR_NEW_RESOURCE);
@ -77,13 +77,13 @@ public class PersonHasAwardOrHonorGenerator extends VivoBaseGenerator implements
conf.addNewResource("intervalNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("startNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("endNode", DEFAULT_NS_FOR_NEW_RESOURCE);
//uris in scope: none
//literals in scope: none
//uris in scope: none
//literals in scope: none
conf.setUrisOnform(Arrays.asList("existingAward", "existingOrg"));
conf.setLiteralsOnForm(Arrays.asList("description", "awardReceiptLabel", "awardLabel", "orgLabel", "yearAwardedDisplay", "orgLabelDisplay", "awardLabelDisplay" ));
conf.addSparqlForExistingLiteral("awardReceiptLabel", awardReceiptLabelQuery);
conf.addSparqlForExistingLiteral("awardLabel", awardLabelQuery);
conf.addSparqlForExistingLiteral("orgLabel", orgLabelQuery);
@ -91,9 +91,9 @@ public class PersonHasAwardOrHonorGenerator extends VivoBaseGenerator implements
conf.addSparqlForExistingLiteral("yearAwarded-value", existingYearAwardedQuery);
conf.addSparqlForExistingLiteral("startField-value", existingStartDateQuery);
conf.addSparqlForExistingLiteral("endField-value", existingEndDateQuery);
conf.addSparqlForExistingUris("existingAward", existingAwardQuery);
conf.addSparqlForExistingUris("existingOrg", existingOrgQuery);
conf.addSparqlForExistingUris("existingOrg", existingOrgQuery);
conf.addSparqlForExistingUris("yearAwardedNode",existingYearAwardedNodeQuery);
conf.addSparqlForExistingUris("intervalNode",existingIntervalNodeQuery);
conf.addSparqlForExistingUris("startNode", existingStartNodeQuery);
@ -101,20 +101,20 @@ public class PersonHasAwardOrHonorGenerator extends VivoBaseGenerator implements
conf.addSparqlForExistingUris("yearAwarded-precision", existingYearAwardedPrecisionQuery);
conf.addSparqlForExistingUris("startField-precision", existingStartPrecisionQuery);
conf.addSparqlForExistingUris("endField-precision", existingEndPrecisionQuery);
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("description")
.setRangeDatatypeUri( XSD.xstring.toString() ).
setValidators( list("datatype:" + XSD.xstring.toString()) )
);
conf.addField( new FieldVTwo(). // options will be added in browser by auto complete JS
setName("existingOrg")
setName("existingOrg")
);
conf.addField( new FieldVTwo(). // options will be added in browser by auto complete JS
setName("existingAward")
);
);
conf.addField( new FieldVTwo().
setName("awardReceiptLabel").
@ -153,24 +153,24 @@ public class PersonHasAwardOrHonorGenerator extends VivoBaseGenerator implements
);
conf.addField( new FieldVTwo().setName("yearAwarded").
setEditElement(
new DateTimeWithPrecisionVTwo(null,
setEditElement(
new DateTimeWithPrecisionVTwo(null,
VitroVocabulary.Precision.YEAR.uri(),
VitroVocabulary.Precision.NONE.uri())
)
);
conf.addField( new FieldVTwo().setName("startField").
setEditElement(
new DateTimeWithPrecisionVTwo(null,
setEditElement(
new DateTimeWithPrecisionVTwo(null,
VitroVocabulary.Precision.YEAR.uri(),
VitroVocabulary.Precision.NONE.uri())
)
);
conf.addField( new FieldVTwo().setName("endField").
setEditElement(
new DateTimeWithPrecisionVTwo(null,
setEditElement(
new DateTimeWithPrecisionVTwo(null,
VitroVocabulary.Precision.YEAR.uri(),
VitroVocabulary.Precision.NONE.uri())
)
@ -185,66 +185,66 @@ public class PersonHasAwardOrHonorGenerator extends VivoBaseGenerator implements
/* N3 assertions */
final static String n3ForNewAwardReceipt =
"@prefix vivo: <" + vivoCore + "> . \n\n" +
final static String n3ForNewAwardReceipt =
"@prefix vivo: <" + vivoCore + "> . \n\n" +
"?person <" + awardReceiptPred + "> ?awardReceipt . \n" +
"?awardReceipt a <" + awardReceiptClass + "> . \n" +
"?awardReceipt <" + awardForPred + "> ?person . " ;
final static String awardReceiptLabelAssertion =
"?awardReceipt a <" + awardReceiptClass + "> . \n" +
"?awardReceipt <" + awardForPred + "> ?person . " ;
final static String awardReceiptLabelAssertion =
"?awardReceipt <"+ label + "> ?awardReceiptLabel .";
final static String n3ForNewAwardAssertion =
final static String n3ForNewAwardAssertion =
"?awardReceipt <" + receiptOfPred + "> ?award . \n" +
"?award a <" + awardClass + "> . \n" +
"?award <" + receiptPred + "> ?awardReceipt . \n" +
"?award <"+ label + "> ?awardLabel .";
final static String n3ForExistingAwardAssertion =
final static String n3ForExistingAwardAssertion =
"?awardReceipt <" + receiptOfPred + "> ?existingAward . \n" +
"?existingAward <" + receiptPred + "> ?awardReceipt . " ;
final static String descriptionAssertion =
final static String descriptionAssertion =
"?awardReceipt <"+ descriptionPred +"> ?description .";
final static String n3ForExistingOrgNewAwardAssertion =
final static String n3ForExistingOrgNewAwardAssertion =
"?awardReceipt <" + awardConferredByPred +"> ?existingOrg . \n" +
"?existingOrg <" + awardConferredPred + "> ?awardReceipt . \n" +
"?award <"+ label + "> ?awardLabel .";
"?award <"+ label + "> ?awardLabel .";
final static String n3ForExistingOrgExistingAwardAssertion =
final static String n3ForExistingOrgExistingAwardAssertion =
"?awardReceipt <" + awardConferredByPred +"> ?existingOrg . \n" +
"?existingOrg <" + awardConferredPred + "> ?awardReceipt . ";
"?existingOrg <" + awardConferredPred + "> ?awardReceipt . ";
final static String n3ForNewOrgNewAwardAssertion =
final static String n3ForNewOrgNewAwardAssertion =
"?newOrg a <" + orgClass + "> . \n" +
"?awardReceipt <" + awardConferredByPred +"> ?newOrg . \n" +
"?newOrg <" + awardConferredPred + "> ?awardReceipt . \n" +
"?award <"+ label + "> ?awardLabel . \n" +
"?newOrg <"+ label + "> ?orgLabel .";
"?award <"+ label + "> ?awardLabel . \n" +
"?newOrg <"+ label + "> ?orgLabel .";
final static String n3ForNewOrgExistingAwardAssertion =
final static String n3ForNewOrgExistingAwardAssertion =
"?newOrg a <" + orgClass + "> . \n" +
"?awardReceipt <" + awardConferredByPred +"> ?newOrg . \n" +
"?newOrg <" + awardConferredPred + "> ?awardReceipt . \n" +
"?newOrg <"+ label + "> ?orgLabel .";
"?newOrg <" + awardConferredPred + "> ?awardReceipt . \n" +
"?newOrg <"+ label + "> ?orgLabel .";
final static String n3ForYearAwarded =
final static String n3ForYearAwarded =
"?awardReceipt <" + yearAwardedPred + "> ?yearAwardedNode . \n" +
"?yearAwardedNode a <" + dateTimeValueType + "> . \n" +
"?yearAwardedNode <" + dateTimeValue + "> ?yearAwarded-value . \n" +
"?yearAwardedNode <" + dateTimePrecision + "> ?yearAwarded-precision .";
final static String n3ForStart =
"?awardReceipt <" + awardReceiptToInterval + "> ?intervalNode . \n" +
"?awardReceipt <" + awardReceiptToInterval + "> ?intervalNode . \n" +
"?intervalNode a <" + intervalType + "> . \n" +
"?intervalNode <" + intervalToStart + "> ?startNode . \n" +
"?intervalNode <" + intervalToStart + "> ?startNode . \n" +
"?startNode a <" + dateTimeValueType + "> . \n" +
"?startNode <" + dateTimeValue + "> ?startField-value . \n" +
"?startNode <" + dateTimePrecision + "> ?startField-precision . \n";
final static String n3ForEnd =
"?awardReceipt <" + awardReceiptToInterval + "> ?intervalNode . \n" +
"?awardReceipt <" + awardReceiptToInterval + "> ?intervalNode . \n" +
"?intervalNode a <" + intervalType + "> . \n" +
"?intervalNode <" + intervalToEnd + "> ?endNode . \n" +
"?endNode a <" + dateTimeValueType + "> . \n" +
@ -259,7 +259,7 @@ public class PersonHasAwardOrHonorGenerator extends VivoBaseGenerator implements
" ?existingAward a <" + awardClass + "> . \n" +
"}";
final static String existingOrgQuery =
final static String existingOrgQuery =
"SELECT ?existingOrg WHERE { \n" +
" ?awardReceipt <" + awardConferredByPred + "> ?existingOrg . \n" +
" ?existingOrg a <" + orgClass + "> . \n" +
@ -277,24 +277,24 @@ public class PersonHasAwardOrHonorGenerator extends VivoBaseGenerator implements
" ?existingAward <" + label + "> ?existingAwardLabel . \n" +
"}";
final static String orgLabelQuery =
final static String orgLabelQuery =
"SELECT ?existingOrgLabel WHERE { \n" +
" ?awardReceipt <" + awardConferredByPred + "> ?existingOrg . \n" +
" ?existingOrg a <" + orgClass + "> . \n" +
" ?existingOrg <" + label + "> ?existingOrgLabel . \n" +
"}";
final static String descriptionQuery =
final static String descriptionQuery =
"SELECT ?existingDescription WHERE {\n"+
" ?awardReceipt <"+ descriptionPred +"> ?existingDescription . }";
final static String existingYearAwardedQuery =
final static String existingYearAwardedQuery =
"SELECT ?existingYearAwardedValue WHERE { \n" +
" ?awardReceipt <" + yearAwardedPred + "> ?yearAwardedNode . \n" +
" ?yearAwardedNode a <" + dateTimeValueType + "> . \n" +
" ?yearAwardedNode <" + dateTimeValue + "> ?existingYearAwardedValue }";
final static String existingYearAwardedNodeQuery =
final static String existingYearAwardedNodeQuery =
"SELECT ?existingYearAwardedNode WHERE { \n" +
" ?awardReceipt <" + yearAwardedPred + "> ?existingYearAwardedNode . }";
@ -305,7 +305,7 @@ public class PersonHasAwardOrHonorGenerator extends VivoBaseGenerator implements
" ?intervalNode <" + intervalToStart + "> ?startNode . \n" +
" ?startNode a <" + dateTimeValueType +"> . \n" +
" ?startNode <" + dateTimeValue + "> ?existingStartDate . }";
final static String existingEndDateQuery =
"SELECT ?existingEndDate WHERE { \n" +
" ?awardReceipt <" + awardReceiptToInterval + "> ?intervalNode . \n" +
@ -315,44 +315,44 @@ public class PersonHasAwardOrHonorGenerator extends VivoBaseGenerator implements
" ?endNode <" + dateTimeValue + "> ?existingEndDate . }";
final static String existingIntervalNodeQuery =
"SELECT ?existingIntervalNode WHERE { \n" +
"SELECT ?existingIntervalNode WHERE { \n" +
" ?awardReceipt <" + awardReceiptToInterval + "> ?existingIntervalNode . \n" +
" ?existingIntervalNode a <" + intervalType + "> . }";
final static String existingStartNodeQuery =
final static String existingStartNodeQuery =
"SELECT ?existingStartNode WHERE { \n" +
" ?awardReceipt <" + awardReceiptToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToStart + "> ?existingStartNode . \n" +
" ?intervalNode <" + intervalToStart + "> ?existingStartNode . \n" +
" ?existingStartNode a <" + dateTimeValueType + "> . } ";
final static String existingEndNodeQuery =
final static String existingEndNodeQuery =
"SELECT ?existingEndNode WHERE { \n" +
" ?awardReceipt <" + awardReceiptToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToEnd + "> ?existingEndNode . \n" +
" ?existingEndNode a <" + dateTimeValueType + "> } ";
" ?intervalNode <" + intervalToEnd + "> ?existingEndNode . \n" +
" ?existingEndNode a <" + dateTimeValueType + "> } ";
final static String existingYearAwardedPrecisionQuery =
final static String existingYearAwardedPrecisionQuery =
"SELECT ?existingYearAwardedPrecision WHERE { \n" +
" ?awardReceipt <" + yearAwardedPred + "> ?yearAwarded . \n" +
" ?yearAwarded a <" + dateTimeValueType + "> . \n" +
" ?yearAwarded a <" + dateTimeValueType + "> . \n" +
" ?yearAwarded <" + dateTimePrecision + "> ?existingYearAwardedPrecision . }";
final static String existingStartPrecisionQuery =
final static String existingStartPrecisionQuery =
"SELECT ?existingStartPrecision WHERE { \n" +
" ?awardReceipt <" + awardReceiptToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToStart + "> ?startNode . \n" +
" ?startNode a <" + dateTimeValueType + "> . \n" +
" ?startNode a <" + dateTimeValueType + "> . \n" +
" ?startNode <" + dateTimePrecision + "> ?existingStartPrecision . }";
final static String existingEndPrecisionQuery =
final static String existingEndPrecisionQuery =
"SELECT ?existingEndPrecision WHERE { \n" +
" ?awardReceipt <" + awardReceiptToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToEnd + "> ?endNode . \n" +
" ?endNode a <" + dateTimeValueType + "> . \n" +
" ?endNode a <" + dateTimeValueType + "> . \n" +
" ?endNode <" + dateTimePrecision + "> ?existingEndPrecision . }";
}

View file

@ -26,60 +26,60 @@ import edu.cornell.mannlib.vitro.webapp.utils.generators.EditModeUtils;
/**
Form for adding an educational attainment to an individual
Classes:
Classes:
core:EducationalProcess - primary new individual being created
foaf:Person - existing individual
foaf:Organization - new or existing individual
core:AcademicDegree - existing individual
core:AwardedDegree - new or existing individual
There are 4 modes that this form can be in:
1. Add, there is a subject and a predicate but no position and nothing else.
There are 4 modes that this form can be in:
1. Add, there is a subject and a predicate but no position and nothing else.
2. normal edit where everything should already be filled out. There is a subject, a object and an individual on
the other end of the object's relationship.
3. Repair a bad role node. There is a subject, prediate and object but there is no individual on the
the other end of the object's relationship.
3. Repair a bad role node. There is a subject, prediate and object but there is no individual on the
other end of the object's relationship. This should be similar to an add but the form should be expanded.
4. Really bad node. multiple statements on the other end of the object's relationship.
* @author bdc34
*
*/
public class PersonHasEducationalTraining extends VivoBaseGenerator implements EditConfigurationGenerator{
public class PersonHasEducationalTraining extends VivoBaseGenerator implements EditConfigurationGenerator{
//TODO: can we get rid of the session and get it form the vreq?
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) throws Exception {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
initObjectPropForm(conf, vreq);
conf.setTemplate("personHasEducationalTraining.ftl");
conf.setVarNameForSubject("person");
conf.setVarNameForPredicate("predicate");
conf.setVarNameForObject("edTraining");
conf.setN3Required( Arrays.asList( n3ForNewEdTraining, trainingTypeAssertion ) );
conf.setN3Optional(Arrays.asList( majorFieldAssertion, n3ForAwardedDegree, n3ForNewOrganization, n3ForExistingOrganization,
n3ForNewOrgAwardedDegree, n3ForExistingOrgAwardedDegree, deptAssertion, infoAssertion, n3ForStart, n3ForEnd ));
conf.addNewResource("edTraining", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("awardedDegree",DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("newOrg",DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("intervalNode",DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("startNode",DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("endNode",DEFAULT_NS_FOR_NEW_RESOURCE);
//uris in scope: none
//uris in scope: none
//literals in scope: none
conf.setUrisOnform( Arrays.asList( "existingOrg", "orgType", "degreeType", "trainingType"));
conf.setLiteralsOnForm( Arrays.asList("orgLabel", "orgLabelDisplay", "awardedDegreeLabel",
"majorField", "dept", "info"));
@ -92,7 +92,7 @@ public class PersonHasEducationalTraining extends VivoBaseGenerator implements
conf.addSparqlForExistingLiteral("startField-value", existingStartDateQuery);
conf.addSparqlForExistingLiteral("endField-value", existingEndDateQuery);
conf.addSparqlForExistingUris("awardedDegree", existingAwardedDegreeQuery);
conf.addSparqlForExistingUris("existingOrg", existingOrgQuery);
conf.addSparqlForExistingUris("orgType", orgTypeQuery);
@ -105,8 +105,8 @@ public class PersonHasEducationalTraining extends VivoBaseGenerator implements
conf.addSparqlForExistingUris("endField-precision", existingEndPrecisionQuery);
//Add sparql to include inverse property as well
conf.addSparqlForAdditionalUrisInScope("inverseTrainingAtOrg", inverseTrainingAtOrgQuery);
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("degreeType").
setOptions( new IndividualsViaVClassOptions(
degreeTypeClass)));
@ -115,16 +115,16 @@ public class PersonHasEducationalTraining extends VivoBaseGenerator implements
setName("majorField").
setRangeDatatypeUri( XSD.xstring.toString() ).
setValidators(list("datatype:" + XSD.xstring.toString())));
conf.addField( new FieldVTwo().
setName("existingOrg")
//options will be added in browser by auto complete JS
);
//options will be added in browser by auto complete JS
);
conf.addField( new FieldVTwo().
setName("awardedDegree")
//options will be added in browser by auto complete JS
);
//options will be added in browser by auto complete JS
);
conf.addField( new FieldVTwo().
setName("orgLabel").
@ -140,28 +140,28 @@ public class PersonHasEducationalTraining extends VivoBaseGenerator implements
setName("existingAwardedDegreeLabel").
setRangeDatatypeUri(XSD.xstring.toString() ).
setValidators( list("datatype:" + XSD.xstring.toString())));
conf.addField( new FieldVTwo().
setName("orgLabelDisplay").
setRangeDatatypeUri(XSD.xstring.toString() ));
conf.addField( new FieldVTwo().
setName("orgType").
setValidators( list("nonempty")).
setOptions( new ChildVClassesOptions(
orgClass)));
conf.addField( new FieldVTwo().
setName("trainingType").
setValidators( list("nonempty") ).
setOptions(
setOptions(
new ChildVClassesWithParent(edProcessClass)));
conf.addField( new FieldVTwo().
setName("dept").
setRangeDatatypeUri( XSD.xstring.toString() ).
setValidators(list("datatype:" + XSD.xstring.toString())));
conf.addField( new FieldVTwo().
setName("info").
setRangeDatatypeUri( XSD.xstring.toString() ).
@ -169,32 +169,32 @@ public class PersonHasEducationalTraining extends VivoBaseGenerator implements
FieldVTwo startField = new FieldVTwo().
setName("startField");
conf.addField(startField.
conf.addField(startField.
setEditElement(
new DateTimeWithPrecisionVTwo(startField,
new DateTimeWithPrecisionVTwo(startField,
VitroVocabulary.Precision.YEAR.uri(),
VitroVocabulary.Precision.NONE.uri())));
FieldVTwo endField = new FieldVTwo().
setName("endField");
conf.addField( endField.
conf.addField( endField.
setEditElement(
new DateTimeWithPrecisionVTwo(endField,
new DateTimeWithPrecisionVTwo(endField,
VitroVocabulary.Precision.YEAR.uri(),
VitroVocabulary.Precision.NONE.uri())));
//Add validator
conf.addValidator(new DateTimeIntervalValidationVTwo("startField","endField"));
conf.addValidator(new AntiXssValidation());
//Adding additional data, specifically edit mode
addFormSpecificData(conf, vreq);
prepare(vreq, conf);
return conf;
}
/* N3 assertions for working with educational training */
final static String n3ForNewEdTraining =
final static String n3ForNewEdTraining =
"@prefix core: <"+ vivoCore +"> .\n"+
"?person <http://purl.obolibrary.org/obo/RO_0000056> ?edTraining .\n" +
"?edTraining a core:EducationalProcess .\n" +
@ -203,7 +203,7 @@ public class PersonHasEducationalTraining extends VivoBaseGenerator implements
final static String trainingTypeAssertion =
"?edTraining a ?trainingType .";
final static String n3ForAwardedDegree =
final static String n3ForAwardedDegree =
"@prefix core: <"+ vivoCore +"> .\n"+
"?edTraining <http://purl.obolibrary.org/obo/RO_0002234> ?awardedDegree . \n" +
"?awardedDegree <http://purl.obolibrary.org/obo/RO_0002353> ?edTraining . \n" +
@ -214,31 +214,31 @@ public class PersonHasEducationalTraining extends VivoBaseGenerator implements
"?degreeType <http://vivoweb.org/ontology/core#relatedBy> ?awardedDegree . \n"+
"?awardedDegree a core:AwardedDegree .";
final static String n3ForNewOrganization =
final static String n3ForNewOrganization =
"?edTraining <http://purl.obolibrary.org/obo/RO_0000057> ?newOrg . \n" +
"?newOrg <http://purl.obolibrary.org/obo/RO_0000056> ?edTraining . \n" +
"?newOrg a ?orgType . \n" +
"?newOrg <"+ label +"> ?orgLabel . ";
final static String n3ForExistingOrganization =
final static String n3ForExistingOrganization =
"?edTraining <http://purl.obolibrary.org/obo/RO_0000057> ?existingOrg . \n" +
"?existingOrg <http://purl.obolibrary.org/obo/RO_0000056> ?edTraining . \n" +
"?existingOrg a ?orgType . ";
final static String n3ForNewOrgAwardedDegree =
final static String n3ForNewOrgAwardedDegree =
"?awardedDegree <http://vivoweb.org/ontology/core#assignedBy> ?newOrg . \n" +
"?newOrg <http://vivoweb.org/ontology/core#assigns> ?awardedDegree . \n" +
"?newOrg a ?orgType . \n" +
"?awardedDegree <"+ label +"> ?awardedDegreeLabel . \n" +
"?newOrg <"+ label +"> ?orgLabel . ";
final static String n3ForExistingOrgAwardedDegree =
final static String n3ForExistingOrgAwardedDegree =
"?awardedDegree <http://vivoweb.org/ontology/core#assignedBy> ?existingOrg . \n" +
"?existingOrg <http://vivoweb.org/ontology/core#assigns> ?awardedDegree . \n" +
"?awardedDegree <"+ label +"> ?awardedDegreeLabel . \n" +
"?existingOrg a ?orgType . ";
final static String majorFieldAssertion =
final static String majorFieldAssertion =
"?edTraining <"+ majorFieldPred +"> ?majorField .";
final static String n3ForStart =
@ -257,24 +257,24 @@ public class PersonHasEducationalTraining extends VivoBaseGenerator implements
"?endNode <"+ dateTimeValue +"> ?endField-value .\n"+
"?endNode <"+ dateTimePrecision +"> ?endField-precision .";
final static String deptAssertion =
final static String deptAssertion =
"?edTraining <"+ deptPred +"> ?dept .";
final static String infoAssertion =
final static String infoAssertion =
"?edTraining <"+ infoPred +"> ?info .";
/* Queries for editing an existing educational training entry */
final static String existingAwardedDegreeQuery =
final static String existingAwardedDegreeQuery =
"SELECT ?existingAwardedDegree WHERE {\n"+
"?edTraining <http://purl.obolibrary.org/obo/RO_0002234> ?existingAwardedDegree . }\n";
final static String existingAwardedDegreeLabelQuery =
final static String existingAwardedDegreeLabelQuery =
"SELECT ?existingAwardedDegreeLabel WHERE {\n"+
"?edTraining <http://purl.obolibrary.org/obo/RO_0002234> ?existingAwardedDegree . \n" +
"?existingAwardedDegree <"+ label +"> ?existingAwardedDegreeLabel }\n";
final static String existingOrgQuery =
final static String existingOrgQuery =
"PREFIX rdfs: <"+ rdfs +"> \n"+
"SELECT ?existingOrg WHERE {\n"+
"?edTraining <http://purl.obolibrary.org/obo/RO_0000057> ?existingOrg . \n" +
@ -282,7 +282,7 @@ public class PersonHasEducationalTraining extends VivoBaseGenerator implements
"?existingOrg a ?existingOrgType . \n " +
"?existingOrgType rdfs:subClassOf <"+ orgClass +"> . }";
final static String orgLabelQuery =
final static String orgLabelQuery =
"PREFIX rdfs: <"+ rdfs +"> \n"+
"SELECT ?existingOrgLabel WHERE {\n"+
"?edTraining <http://purl.obolibrary.org/obo/RO_0000057> ?existingOrg . \n" +
@ -293,7 +293,7 @@ public class PersonHasEducationalTraining extends VivoBaseGenerator implements
/* Limit type to subclasses of foaf:Organization. Otherwise, sometimes owl:Thing or another
type is returned and we don't get a match to the select element options. */
final static String orgTypeQuery =
final static String orgTypeQuery =
"PREFIX rdfs: <"+ rdfs +"> \n"+
"SELECT ?existingOrgType WHERE {\n"+
"?edTraining <http://purl.obolibrary.org/obo/RO_0000057> ?existingOrg . \n" +
@ -302,12 +302,12 @@ public class PersonHasEducationalTraining extends VivoBaseGenerator implements
"?existingOrgType rdfs:subClassOf <"+ orgClass +"> .\n"+
"}";
final static String trainingTypeQuery =
final static String trainingTypeQuery =
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
"SELECT ?existingTrainingType WHERE { \n" +
"SELECT ?existingTrainingType WHERE { \n" +
" ?edTraining vitro:mostSpecificType ?existingTrainingType . }";
final static String degreeTypeQuery =
final static String degreeTypeQuery =
"PREFIX core: <"+ vivoCore +"> \n"+
"SELECT ?existingDegreeType WHERE {\n"+
"?edTraining <http://purl.obolibrary.org/obo/RO_0002234> ?existingAwardedDegree . \n"+
@ -315,31 +315,31 @@ public class PersonHasEducationalTraining extends VivoBaseGenerator implements
"?existingAwardedDegree core:relates ?existingDegreeType . \n" +
"?existingDegreeType a core:AcademicDegree }";
final static String majorFieldQuery =
final static String majorFieldQuery =
"SELECT ?existingMajorField WHERE {\n"+
"?edTraining <"+ majorFieldPred +"> ?existingMajorField . }";
final static String deptQuery =
final static String deptQuery =
"SELECT ?existingDept WHERE {\n"+
"?edTraining <"+ deptPred +"> ?existingDept . }";
final static String infoQuery =
final static String infoQuery =
"SELECT ?existingInfo WHERE {\n"+
"?edTraining <"+ infoPred +"> ?existingInfo . }";
final static String existingIntervalNodeQuery =
final static String existingIntervalNodeQuery =
"SELECT ?existingIntervalNode WHERE {\n"+
"?edTraining <"+ toInterval +"> ?existingIntervalNode .\n"+
"?existingIntervalNode <"+ type +"> <"+ intervalType +"> . }";
final static String existingStartNodeQuery =
final static String existingStartNodeQuery =
"SELECT ?existingStartNode WHERE {\n"+
"?edTraining <"+ toInterval +"> ?intervalNode .\n"+
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
"?intervalNode <"+ intervalToStart +"> ?existingStartNode . \n"+
"?existingStartNode <"+ type +"> <"+ dateTimeValueType +"> .}";
final static String existingStartDateQuery =
final static String existingStartDateQuery =
"SELECT ?existingDateStart WHERE {\n"+
"?edTraining <"+ toInterval +"> ?intervalNode .\n"+
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
@ -347,7 +347,7 @@ public class PersonHasEducationalTraining extends VivoBaseGenerator implements
"?startNode <"+ type +"> <"+ dateTimeValueType +"> .\n"+
"?startNode <"+ dateTimeValue +"> ?existingDateStart . }";
final static String existingStartPrecisionQuery =
final static String existingStartPrecisionQuery =
"SELECT ?existingStartPrecision WHERE {\n"+
"?edTraining <"+ toInterval +"> ?intervalNode .\n"+
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
@ -355,14 +355,14 @@ public class PersonHasEducationalTraining extends VivoBaseGenerator implements
"?startNode <"+ type +"> <"+ dateTimeValueType +"> . \n"+
"?startNode <"+ dateTimePrecision +"> ?existingStartPrecision . }";
final static String existingEndNodeQuery =
final static String existingEndNodeQuery =
"SELECT ?existingEndNode WHERE { \n"+
"?edTraining <"+ toInterval +"> ?intervalNode .\n"+
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
"?intervalNode <"+ intervalToEnd +"> ?existingEndNode . \n"+
"?existingEndNode <"+ type +"> <"+ dateTimeValueType +"> .}";
final static String existingEndDateQuery =
final static String existingEndDateQuery =
"SELECT ?existingEndDate WHERE {\n"+
"?edTraining <"+ toInterval +"> ?intervalNode .\n"+
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
@ -370,28 +370,28 @@ public class PersonHasEducationalTraining extends VivoBaseGenerator implements
"?endNode <"+ type +"> <"+ dateTimeValueType +"> .\n"+
"?endNode <"+ dateTimeValue +"> ?existingEndDate . }";
final static String existingEndPrecisionQuery =
final static String existingEndPrecisionQuery =
"SELECT ?existingEndPrecision WHERE {\n"+
"?edTraining <"+ toInterval +"> ?intervalNode .\n"+
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
"?intervalNode <"+ intervalToEnd +"> ?endNode .\n"+
"?endNode <"+ type +"> <"+ dateTimeValueType +"> .\n"+
"?endNode <"+ dateTimePrecision +"> ?existingEndPrecision . }";
//Query for inverse property
final static String inverseTrainingAtOrgQuery =
"PREFIX owl: <http://www.w3.org/2002/07/owl#>"
+ " SELECT ?inverseTrainingAtOrg "
+ " WHERE { ?inverseTrainingAtOrg owl:inverseOf <http://vivoweb.org/ontology/core#relates> . } ";
//Adding form specific data such as edit mode
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
formSpecificData.put("editMode", getEditMode(vreq).name().toLowerCase());
editConfiguration.setFormSpecificData(formSpecificData);
}
public EditMode getEditMode(VitroRequest vreq) {
List<String> predicates = new ArrayList<String>();
predicates.add("http://vivoweb.org/ontology/core#relates");

View file

@ -21,25 +21,25 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.
public class PersonHasEmailGenerator extends VivoBaseGenerator implements
EditConfigurationGenerator {
private Log log = LogFactory.getLog(PersonHasEmailGenerator.class);
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
HttpSession session) throws Exception {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
String emailUri = getEmailUri(vreq);
String rangeUri = getRangeUri(vreq);
initObjectPropForm(conf, vreq);
String emailUri = getEmailUri(vreq);
String rangeUri = getRangeUri(vreq);
conf.setTemplate("personHasEmailAddress.ftl");
conf.setVarNameForSubject("person");
conf.setVarNameForPredicate("predicate");
conf.setVarNameForObject("individualVcard");
if ( rangeUri.equals("http://www.w3.org/2006/vcard/ns#Work") ) {
conf.setN3Required( Arrays.asList( n3ForNewPrimaryEmail ) );
}
@ -48,12 +48,12 @@ public class PersonHasEmailGenerator extends VivoBaseGenerator implements
}
conf.setN3Optional( Arrays.asList( emailAddressAssertion ) );
conf.addNewResource("email", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("individualVcard", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.setLiteralsOnForm(Arrays.asList("emailAddress" ));
conf.addSparqlForExistingLiteral("emailAddress", emailAddressQuery);
conf.addSparqlForAdditionalUrisInScope("individualVcard", individualVcardQuery);
@ -63,37 +63,37 @@ public class PersonHasEmailGenerator extends VivoBaseGenerator implements
conf.addUrisInScope(urisInScope);
}
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("emailAddress")
.setRangeDatatypeUri( XSD.xstring.toString() ).
setValidators( list("nonempty") ));
conf.addValidator(new AntiXssValidation());
prepare(vreq, conf);
return conf;
}
/* N3 assertions */
final static String n3ForNewEmail =
final static String n3ForNewEmail =
"?person <http://purl.obolibrary.org/obo/ARG_2000028> ?individualVcard . \n" +
"?individualVcard a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?individualVcard a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?individualVcard <http://purl.obolibrary.org/obo/ARG_2000029> ?person . \n" +
"?individualVcard <http://www.w3.org/2006/vcard/ns#hasEmail> ?email . \n" +
"?email a <http://www.w3.org/2006/vcard/ns#Email> . " ;
final static String n3ForNewPrimaryEmail =
"?email a <http://www.w3.org/2006/vcard/ns#Email> . " ;
final static String n3ForNewPrimaryEmail =
"?person <http://purl.obolibrary.org/obo/ARG_2000028> ?individualVcard . \n" +
"?individualVcard a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?individualVcard a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?individualVcard <http://purl.obolibrary.org/obo/ARG_2000029> ?person . \n" +
"?individualVcard <http://www.w3.org/2006/vcard/ns#hasEmail> ?email . \n" +
"?email a <http://www.w3.org/2006/vcard/ns#Email> . \n" +
"?email a <http://www.w3.org/2006/vcard/ns#Work> ." ;
"?email a <http://www.w3.org/2006/vcard/ns#Work> ." ;
final static String emailAddressAssertion =
final static String emailAddressAssertion =
"?email <http://www.w3.org/2006/vcard/ns#email> ?emailAddress .";
/* Queries for editing an existing entry */
final static String individualVcardQuery =
@ -101,18 +101,18 @@ public class PersonHasEmailGenerator extends VivoBaseGenerator implements
"?person <http://purl.obolibrary.org/obo/ARG_2000028> ?existingIndividualVcard . \n" +
"}";
final static String emailAddressQuery =
final static String emailAddressQuery =
"SELECT ?existingEmailAddress WHERE {\n"+
"?email <http://www.w3.org/2006/vcard/ns#email> ?existingEmailAddress . }";
private String getRangeUri(VitroRequest vreq) {
String rangeUri = vreq.getParameter("rangeUri");
String rangeUri = vreq.getParameter("rangeUri");
return rangeUri;
}
private String getEmailUri(VitroRequest vreq) {
String emailUri = vreq.getParameter("emailUri");
String emailUri = vreq.getParameter("emailUri");
return emailUri;
}
}

View file

@ -33,50 +33,50 @@ public class PersonHasIssuedCredentialGenerator extends VivoBaseGenerator implem
final static String dateTimeValueType = vivoCore + "DateTimeValue";
final static String dateTimeValue = vivoCore + "dateTime";
final static String dateTimePrecision = vivoCore + "dateTimePrecision";
public PersonHasIssuedCredentialGenerator() {}
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
HttpSession session) throws Exception {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
initObjectPropForm(conf, vreq);
conf.setTemplate("personHasIssuedCredential.ftl");
conf.setVarNameForSubject("person");
conf.setVarNameForPredicate("predicate");
conf.setVarNameForObject("issuedCredential");
conf.setN3Required( Arrays.asList( n3ForNewIssuedCredential, n3ForICTypeAssertion) );
conf.setN3Optional( Arrays.asList( n3ForNewCredentialAssertion,
n3ForExistingCredentialAssertion,
n3ForYearCredentialed,
n3ForStart,
conf.setN3Optional( Arrays.asList( n3ForNewCredentialAssertion,
n3ForExistingCredentialAssertion,
n3ForYearCredentialed,
n3ForStart,
n3ForEnd ) );
conf.addNewResource("credential", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("issuedCredential", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("yearCredentialedNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("intervalNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("startNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("endNode", DEFAULT_NS_FOR_NEW_RESOURCE);
//uris in scope: none
//literals in scope: none
//uris in scope: none
//literals in scope: none
conf.setUrisOnform(Arrays.asList("existingCredential", "issuedCredentialType", "credentialType"));
conf.setLiteralsOnForm(Arrays.asList("yearCredentialedDisplay","credentialLabel", "credentialLabelDisplay" ));
conf.addSparqlForExistingLiteral("credentialLabel", credentialLabelQuery);
conf.addSparqlForExistingLiteral("yearCredentialed-value", existingYearCredentialedQuery);
conf.addSparqlForExistingLiteral("startField-value", existingStartDateQuery);
conf.addSparqlForExistingLiteral("endField-value", existingEndDateQuery);
conf.addSparqlForExistingUris("existingCredential", existingCredentialQuery);
conf.addSparqlForExistingUris("credentialType", existingCredentialTypeQuery);
conf.addSparqlForExistingUris("issuedCredentialType", issuedCredentialTypeQuery);
@ -87,20 +87,20 @@ public class PersonHasIssuedCredentialGenerator extends VivoBaseGenerator implem
conf.addSparqlForExistingUris("yearCredentialed-precision", existingYearCredentialedPrecisionQuery);
conf.addSparqlForExistingUris("startField-precision", existingStartPrecisionQuery);
conf.addSparqlForExistingUris("endField-precision", existingEndPrecisionQuery);
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("issuedCredentialType").
setRangeDatatypeUri(XSD.xstring.toString() ).
setValidators( list("datatype:" + XSD.xstring.toString()))
);
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("credentialType").
setOptions(getCredentialTypeFieldOptions(vreq)));
conf.addField( new FieldVTwo(). // options will be added in browser by auto complete JS
setName("existingCredential")
);
);
conf.addField( new FieldVTwo().
setName("credentialLabel").
@ -121,24 +121,24 @@ public class PersonHasIssuedCredentialGenerator extends VivoBaseGenerator implem
);
conf.addField( new FieldVTwo().setName("yearCredentialed").
setEditElement(
new DateTimeWithPrecisionVTwo(null,
setEditElement(
new DateTimeWithPrecisionVTwo(null,
VitroVocabulary.Precision.YEAR.uri(),
VitroVocabulary.Precision.NONE.uri())
)
);
conf.addField( new FieldVTwo().setName("startField").
setEditElement(
new DateTimeWithPrecisionVTwo(null,
setEditElement(
new DateTimeWithPrecisionVTwo(null,
VitroVocabulary.Precision.YEAR.uri(),
VitroVocabulary.Precision.NONE.uri())
)
);
conf.addField( new FieldVTwo().setName("endField").
setEditElement(
new DateTimeWithPrecisionVTwo(null,
setEditElement(
new DateTimeWithPrecisionVTwo(null,
VitroVocabulary.Precision.YEAR.uri(),
VitroVocabulary.Precision.NONE.uri())
)
@ -147,7 +147,7 @@ public class PersonHasIssuedCredentialGenerator extends VivoBaseGenerator implem
conf.addValidator(new DateTimeIntervalValidationVTwo("startField","endField"));
conf.addValidator(new AntiXssValidation());
conf.addValidator(new AutocompleteRequiredInputValidator("existingCredential", "credentialLabel"));
addFormSpecificData(conf, vreq);
prepare(vreq, conf);
return conf;
@ -155,46 +155,46 @@ public class PersonHasIssuedCredentialGenerator extends VivoBaseGenerator implem
/* N3 assertions */
final static String n3ForNewIssuedCredential =
"@prefix vivo: <" + vivoCore + "> . \n\n" +
final static String n3ForNewIssuedCredential =
"@prefix vivo: <" + vivoCore + "> . \n\n" +
"?person vivo:relatedBy ?issuedCredential . \n" +
"?issuedCredential a <" + issuedCredentialTypeClass + "> . \n" +
"?issuedCredential vivo:relates ?person . " ;
final static String n3ForICTypeAssertion =
"?issuedCredential a <" + issuedCredentialTypeClass + "> . \n" +
"?issuedCredential vivo:relates ?person . " ;
final static String n3ForICTypeAssertion =
"?issuedCredential a ?issuedCredentialType .";
final static String n3ForNewCredentialAssertion =
"@prefix vivo: <" + vivoCore + "> . \n\n" +
final static String n3ForNewCredentialAssertion =
"@prefix vivo: <" + vivoCore + "> . \n\n" +
"?issuedCredential vivo:relates ?credential . \n" +
"?credential a <" + credentialTypeClass + "> . \n" +
"?credential vivo:relatedBy ?issuedCredential . \n" +
"?credential a ?credentialType . \n" +
"?credential <"+ label + "> ?credentialLabel .";
final static String n3ForExistingCredentialAssertion =
"@prefix vivo: <" + vivoCore + "> . \n\n" +
final static String n3ForExistingCredentialAssertion =
"@prefix vivo: <" + vivoCore + "> . \n\n" +
"?issuedCredential vivo:relates ?existingCredential . \n" +
/* "?existingCredential a <" + credentialTypeClass + "> . \n" +
"?existingCredential a ?credentialType . \n" + */
"?existingCredential vivo:relatedBy ?issuedCredential . " ;
final static String n3ForYearCredentialed =
final static String n3ForYearCredentialed =
"?issuedCredential <" + yearCredentialedPred + "> ?yearCredentialedNode . \n" +
"?yearCredentialedNode a <" + dateTimeValueType + "> . \n" +
"?yearCredentialedNode <" + dateTimeValue + "> ?yearCredentialed-value . \n" +
"?yearCredentialedNode <" + dateTimePrecision + "> ?yearCredentialed-precision .";
final static String n3ForStart =
"?issuedCredential <" + issuedCredentialToInterval + "> ?intervalNode . \n" +
"?issuedCredential <" + issuedCredentialToInterval + "> ?intervalNode . \n" +
"?intervalNode a <" + intervalType + "> . \n" +
"?intervalNode <" + intervalToStart + "> ?startNode . \n" +
"?intervalNode <" + intervalToStart + "> ?startNode . \n" +
"?startNode a <" + dateTimeValueType + "> . \n" +
"?startNode <" + dateTimeValue + "> ?startField-value . \n" +
"?startNode <" + dateTimePrecision + "> ?startField-precision . \n";
final static String n3ForEnd =
"?issuedCredential <" + issuedCredentialToInterval + "> ?intervalNode . \n" +
"?issuedCredential <" + issuedCredentialToInterval + "> ?intervalNode . \n" +
"?intervalNode a <" + intervalType + "> . \n" +
"?intervalNode <" + intervalToEnd + "> ?endNode . \n" +
"?endNode a <" + dateTimeValueType + "> . \n" +
@ -233,13 +233,13 @@ public class PersonHasIssuedCredentialGenerator extends VivoBaseGenerator implem
" ?existingCredential <" + label + "> ?existingCredentialLabel . \n" +
"}";
final static String existingYearCredentialedQuery =
final static String existingYearCredentialedQuery =
"SELECT ?existingYearCredentialedValue WHERE { \n" +
" ?issuedCredential <" + yearCredentialedPred + "> ?yearCredentialedNode . \n" +
" ?yearCredentialedNode a <" + dateTimeValueType + "> . \n" +
" ?yearCredentialedNode <" + dateTimeValue + "> ?existingYearCredentialedValue }";
final static String existingYearCredentialedNodeQuery =
final static String existingYearCredentialedNodeQuery =
"SELECT ?existingYearCredentialedNode WHERE { \n" +
" ?issuedCredential <" + yearCredentialedPred + "> ?existingYearCredentialedNode . }";
@ -250,7 +250,7 @@ public class PersonHasIssuedCredentialGenerator extends VivoBaseGenerator implem
" ?intervalNode <" + intervalToStart + "> ?startNode . \n" +
" ?startNode a <" + dateTimeValueType +"> . \n" +
" ?startNode <" + dateTimeValue + "> ?existingStartDate . }";
final static String existingEndDateQuery =
"SELECT ?existingEndDate WHERE { \n" +
" ?issuedCredential <" + issuedCredentialToInterval + "> ?intervalNode . \n" +
@ -260,44 +260,44 @@ public class PersonHasIssuedCredentialGenerator extends VivoBaseGenerator implem
" ?endNode <" + dateTimeValue + "> ?existingEndDate . }";
final static String existingIntervalNodeQuery =
"SELECT ?existingIntervalNode WHERE { \n" +
"SELECT ?existingIntervalNode WHERE { \n" +
" ?issuedCredential <" + issuedCredentialToInterval + "> ?existingIntervalNode . \n" +
" ?existingIntervalNode a <" + intervalType + "> . }";
final static String existingStartNodeQuery =
final static String existingStartNodeQuery =
"SELECT ?existingStartNode WHERE { \n" +
" ?issuedCredential <" + issuedCredentialToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToStart + "> ?existingStartNode . \n" +
" ?intervalNode <" + intervalToStart + "> ?existingStartNode . \n" +
" ?existingStartNode a <" + dateTimeValueType + "> . } ";
final static String existingEndNodeQuery =
final static String existingEndNodeQuery =
"SELECT ?existingEndNode WHERE { \n" +
" ?issuedCredential <" + issuedCredentialToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToEnd + "> ?existingEndNode . \n" +
" ?existingEndNode a <" + dateTimeValueType + "> } ";
" ?intervalNode <" + intervalToEnd + "> ?existingEndNode . \n" +
" ?existingEndNode a <" + dateTimeValueType + "> } ";
final static String existingYearCredentialedPrecisionQuery =
final static String existingYearCredentialedPrecisionQuery =
"SELECT ?existingYearCredentialedPrecision WHERE { \n" +
" ?issuedCredential <" + yearCredentialedPred + "> ?yearCredentialed . \n" +
" ?yearCredentialed a <" + dateTimeValueType + "> . \n" +
" ?yearCredentialed a <" + dateTimeValueType + "> . \n" +
" ?yearCredentialed <" + dateTimePrecision + "> ?existingYearCredentialedPrecision . }";
final static String existingStartPrecisionQuery =
final static String existingStartPrecisionQuery =
"SELECT ?existingStartPrecision WHERE { \n" +
" ?issuedCredential <" + issuedCredentialToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToStart + "> ?startNode . \n" +
" ?startNode a <" + dateTimeValueType + "> . \n" +
" ?startNode a <" + dateTimeValueType + "> . \n" +
" ?startNode <" + dateTimePrecision + "> ?existingStartPrecision . }";
final static String existingEndPrecisionQuery =
final static String existingEndPrecisionQuery =
"SELECT ?existingEndPrecision WHERE { \n" +
" ?issuedCredential <" + issuedCredentialToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToEnd + "> ?endNode . \n" +
" ?endNode a <" + dateTimeValueType + "> . \n" +
" ?endNode a <" + dateTimeValueType + "> . \n" +
" ?endNode <" + dateTimePrecision + "> ?existingEndPrecision . }";
//Form specific data
@ -306,7 +306,7 @@ public class PersonHasIssuedCredentialGenerator extends VivoBaseGenerator implem
formSpecificData.put("credentialTypeMap", getCredentialTypeMap());
editConfiguration.setFormSpecificData(formSpecificData);
}
// Issued Credentials relate a Credential to a person. The class type of a Credential and its subclasses
// are different than -- but correspond to -- the class type of an Issued Credential and its subclasses.
// When a user picks a type of credential in the GUI, we need to set the corresponding type for the issued

View file

@ -37,64 +37,64 @@ public class PersonHasPositionHistoryGenerator extends VivoBaseGenerator impleme
final static String dateTimeValueType = vivoCore + "DateTimeValue";
final static String dateTimeValue = vivoCore + "dateTime";
final static String dateTimePrecision = vivoCore + "dateTimePrecision";
public PersonHasPositionHistoryGenerator() {}
// There are 4 modes that this form can be in:
// 1. Add. There is a subject and a predicate but no position and
// nothing else.
//
// 2. Normal edit where everything should already be filled out.
// There are 4 modes that this form can be in:
// 1. Add. There is a subject and a predicate but no position and
// nothing else.
//
// 2. Normal edit where everything should already be filled out.
// There is a subject, a object and an individual on
// the other end of the object's core:personInOrganization stmt.
//
// 3. Repair a bad role node. There is a subject, predicate and object
// but there is no individual on the other end of the object's
// core:personInOrganization stmt. This should be similar to an add
// the other end of the object's core:personInOrganization stmt.
//
// 3. Repair a bad role node. There is a subject, predicate and object
// but there is no individual on the other end of the object's
// core:personInOrganization stmt. This should be similar to an add
// but the form should be expanded.
//
// 4. Really bad node. multiple core:personInOrganization statements.
//
// 4. Really bad node. multiple core:personInOrganization statements.
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
HttpSession session) throws Exception {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
initObjectPropForm(conf, vreq);
conf.setTemplate("personHasPositionHistory.ftl");
conf.setVarNameForSubject("person");
conf.setVarNameForPredicate("predicate");
conf.setVarNameForObject("position");
conf.setN3Required( Arrays.asList( n3ForNewPosition,
positionTitleAssertion,
conf.setN3Required( Arrays.asList( n3ForNewPosition,
positionTitleAssertion,
positionTypeAssertion ) );
conf.setN3Optional( Arrays.asList( n3ForNewOrg, n3ForExistingOrg, n3ForStart, n3ForEnd ) );
conf.addNewResource("position", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("newOrg", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("intervalNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("startNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("endNode", DEFAULT_NS_FOR_NEW_RESOURCE);
//uris in scope: none
//uris in scope: none
//literals in scope: none
conf.setUrisOnform(Arrays.asList("existingOrg", "orgType", "positionType"));
conf.setLiteralsOnForm(Arrays.asList("positionTitle", "orgLabel", "orgLabelDisplay"));
conf.addSparqlForExistingLiteral("orgLabel", orgLabelQuery);
conf.addSparqlForExistingLiteral("positionTitle", positionTitleQuery);
conf.addSparqlForExistingLiteral(
"startField-value", existingStartDateQuery);
conf.addSparqlForExistingLiteral(
"endField-value", existingEndDateQuery);
conf.addSparqlForExistingUris("existingOrg", existingOrgQuery);
conf.addSparqlForExistingUris("orgType", orgTypeQuery);
conf.addSparqlForExistingUris("positionType", positionTypeQuery);
@ -102,26 +102,26 @@ public class PersonHasPositionHistoryGenerator extends VivoBaseGenerator impleme
"intervalNode", existingIntervalNodeQuery);
conf.addSparqlForExistingUris("startNode", existingStartNodeQuery);
conf.addSparqlForExistingUris("endNode", existingEndNodeQuery);
conf.addSparqlForExistingUris("startField-precision",
conf.addSparqlForExistingUris("startField-precision",
existingStartPrecisionQuery);
conf.addSparqlForExistingUris("endField-precision",
conf.addSparqlForExistingUris("endField-precision",
existingEndPrecisionQuery);
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("positionTitle")
.setRangeDatatypeUri( XSD.xstring.toString() ).
setValidators( list("nonempty") ) );
conf.addField( new FieldVTwo().
setName("positionType").
setValidators( list("nonempty") ).
setOptions(
setValidators( list("nonempty") ).
setOptions(
new ChildVClassesWithParent(positionClass)));
conf.addField( new FieldVTwo().
setName("existingOrg")); //options set in browser by auto complete JS
conf.addField( new FieldVTwo().
setName("orgLabel").
setRangeDatatypeUri(XSD.xstring.toString() ).
@ -130,89 +130,89 @@ public class PersonHasPositionHistoryGenerator extends VivoBaseGenerator impleme
conf.addField( new FieldVTwo().
setName("orgLabelDisplay").
setRangeDatatypeUri(XSD.xstring.toString() ) );
conf.addField( new FieldVTwo().
setName("orgType").
setOptions(
setOptions(
new ChildVClassesWithParent(orgClass)));
conf.addField( new FieldVTwo().setName("startField").
setEditElement(
new DateTimeWithPrecisionVTwo(null,
setEditElement(
new DateTimeWithPrecisionVTwo(null,
VitroVocabulary.Precision.YEAR.uri(),
VitroVocabulary.Precision.NONE.uri())
)
);
conf.addField( new FieldVTwo().setName("endField").
setEditElement(
new DateTimeWithPrecisionVTwo(null,
setEditElement(
new DateTimeWithPrecisionVTwo(null,
VitroVocabulary.Precision.YEAR.uri(),
VitroVocabulary.Precision.NONE.uri())
)
);
conf.addValidator(new DateTimeIntervalValidationVTwo("startField","endField"));
conf.addValidator(new AntiXssValidation());
conf.addValidator(new AutocompleteRequiredInputValidator("existingOrg", "orgLabel"));
//Adding additional data, specifically edit mode
addFormSpecificData(conf, vreq);
prepare(vreq, conf);
return conf;
}
final static String n3ForNewPosition =
"@prefix core: <" + vivoCore + "> . \n" +
final static String n3ForNewPosition =
"@prefix core: <" + vivoCore + "> . \n" +
"?person core:relatedBy ?position . \n" +
"?position a ?positionType . \n" +
"?position core:relates ?person ; ";
"?position a ?positionType . \n" +
"?position core:relates ?person ; ";
final static String positionTitleAssertion =
"?position <" + label + "> ?positionTitle .";
final static String positionTypeAssertion =
"?position a ?positionType .";
final static String n3ForNewOrg =
final static String positionTypeAssertion =
"?position a ?positionType .";
final static String n3ForNewOrg =
"?position <" + positionInOrgPred + "> ?newOrg . \n" +
"?newOrg <" + orgForPositionPred + "> ?position . \n" +
"?newOrg <" + label + "> ?orgLabel . \n" +
"?newOrg a ?orgType .";
"?newOrg a ?orgType .";
final static String n3ForExistingOrg =
final static String n3ForExistingOrg =
"?position <" + positionInOrgPred + "> ?existingOrg . \n" +
"?existingOrg <" + orgForPositionPred + "> ?position . \n" +
"?existingOrg a ?orgType .";
final static String n3ForStart =
"?position <" + positionToInterval + "> ?intervalNode . \n" +
"?position <" + positionToInterval + "> ?intervalNode . \n" +
"?intervalNode a <" + intervalType + "> . \n" +
"?intervalNode <" + intervalToStart + "> ?startNode . \n" +
"?intervalNode <" + intervalToStart + "> ?startNode . \n" +
"?startNode a <" + dateTimeValueType + "> . \n" +
"?startNode <" + dateTimeValue + "> ?startField-value . \n" +
"?startNode <" + dateTimePrecision + "> ?startField-precision . \n";
final static String n3ForEnd =
"?position <" + positionToInterval + "> ?intervalNode . \n" +
"?position <" + positionToInterval + "> ?intervalNode . \n" +
"?intervalNode a <" + intervalType + "> . \n" +
"?intervalNode <" + intervalToEnd + "> ?endNode . \n" +
"?endNode a <" + dateTimeValueType + "> . \n" +
"?endNode <" + dateTimeValue + "> ?endField-value . \n" +
"?endNode <" + dateTimePrecision + "> ?endField-precision . \n";
// Queries for existing values
// Queries for existing values
final static String orgLabelQuery =
"SELECT ?existingOrgLabel WHERE { \n" +
" ?position <" + positionInOrgPred + "> ?existingOrg . \n" +
" ?existingOrg a <" + orgClass + "> . \n" +
" ?existingOrg <" + label + "> ?existingOrgLabel . \n" +
"}";
final static String positionTitleQuery =
"SELECT ?existingPositionTitle WHERE { \n" +
"?position <" + label + "> ?existingPositionTitle . }";
final static String existingStartDateQuery =
"SELECT ?existingDateStart WHERE { \n" +
" ?position <" + positionToInterval + "> ?intervalNode . \n" +
@ -220,7 +220,7 @@ public class PersonHasPositionHistoryGenerator extends VivoBaseGenerator impleme
" ?intervalNode <" + intervalToStart + "> ?startNode . \n" +
" ?startNode a <" + dateTimeValueType +"> . \n" +
" ?startNode <" + dateTimeValue + "> ?existingDateStart . }";
final static String existingEndDateQuery =
"SELECT ?existingEndDate WHERE { \n" +
" ?position <" + positionToInterval + "> ?intervalNode . \n" +
@ -229,60 +229,60 @@ public class PersonHasPositionHistoryGenerator extends VivoBaseGenerator impleme
" ?endNode a <" + dateTimeValueType + "> . \n" +
" ?endNode <" + dateTimeValue + "> ?existingEndDate . }";
final static String existingOrgQuery =
final static String existingOrgQuery =
"SELECT ?existingOrg WHERE { \n" +
" ?position <" + positionInOrgPred + "> ?existingOrg . \n" +
" ?existingOrg a <" + orgClass + "> }";
final static String orgTypeQuery =
"PREFIX rdfs: <" + rdfs + "> \n" +
final static String orgTypeQuery =
"PREFIX rdfs: <" + rdfs + "> \n" +
"SELECT ?existingOrgType WHERE { \n" +
" ?position <" + positionInOrgPred + "> ?existingOrg . \n" +
" ?existingOrg a ?existingOrgType . \n" +
" ?existingOrgType rdfs:subClassOf <" + orgClass + "> " +
"} ";
//Huda: changed this from rdf:type to vitro:mostSpecificType since returning thing
final static String positionTypeQuery =
final static String positionTypeQuery =
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
"SELECT ?existingPositionType WHERE { \n" +
"SELECT ?existingPositionType WHERE { \n" +
" ?position vitro:mostSpecificType ?existingPositionType . }";
final static String existingIntervalNodeQuery =
"SELECT ?existingIntervalNode WHERE { \n" +
"SELECT ?existingIntervalNode WHERE { \n" +
" ?position <" + positionToInterval + "> ?existingIntervalNode . \n" +
" ?existingIntervalNode a <" + intervalType + "> . }";
final static String existingStartNodeQuery =
final static String existingStartNodeQuery =
"SELECT ?existingStartNode WHERE { \n" +
" ?position <" + positionToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToStart + "> ?existingStartNode . \n" +
" ?intervalNode <" + intervalToStart + "> ?existingStartNode . \n" +
" ?existingStartNode a <" + dateTimeValueType + "> .} ";
final static String existingEndNodeQuery =
final static String existingEndNodeQuery =
"SELECT ?existingEndNode WHERE { \n" +
" ?position <" + positionToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToEnd + "> ?existingEndNode . \n" +
" ?existingEndNode a <" + dateTimeValueType + "> } ";
final static String existingStartPrecisionQuery =
" ?intervalNode <" + intervalToEnd + "> ?existingEndNode . \n" +
" ?existingEndNode a <" + dateTimeValueType + "> } ";
final static String existingStartPrecisionQuery =
"SELECT ?existingStartPrecision WHERE { \n" +
" ?position <" + positionToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToStart + "> ?startNode . \n" +
" ?startNode a <" + dateTimeValueType + "> . \n" +
" ?startNode a <" + dateTimeValueType + "> . \n" +
" ?startNode <" + dateTimePrecision + "> ?existingStartPrecision . }";
final static String existingEndPrecisionQuery =
final static String existingEndPrecisionQuery =
"SELECT ?existingEndPrecision WHERE { \n" +
" ?position <" + positionToInterval + "> ?intervalNode . \n" +
" ?intervalNode a <" + intervalType + "> . \n" +
" ?intervalNode <" + intervalToEnd + "> ?endNode . \n" +
" ?endNode a <" + dateTimeValueType + "> . \n" +
" ?endNode a <" + dateTimeValueType + "> . \n" +
" ?endNode <" + dateTimePrecision + "> ?existingEndPrecision . }";
//Adding form specific data such as edit mode
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();

View file

@ -21,64 +21,64 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.
public class PersonHasPreferredTitleGenerator extends VivoBaseGenerator implements
EditConfigurationGenerator {
private Log log = LogFactory.getLog(PersonHasPreferredTitleGenerator.class);
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
HttpSession session) throws Exception {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
String titleUri = getTitleUri(vreq);
initObjectPropForm(conf, vreq);
String titleUri = getTitleUri(vreq);
conf.setTemplate("personHasPreferredTitle.ftl");
conf.setVarNameForSubject("person");
conf.setVarNameForPredicate("predicate");
conf.setVarNameForObject("individualVcard");
conf.setN3Required( Arrays.asList( n3ForNewPhone ) );
conf.setN3Optional( Arrays.asList( preferredTitleAssertion ) );
conf.addNewResource("title", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("individualVcard", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.setLiteralsOnForm(Arrays.asList("preferredTitle" ));
conf.addSparqlForExistingLiteral("preferredTitle", preferredTitleQuery);
conf.addSparqlForAdditionalUrisInScope("individualVcard", individualVcardQuery);
if ( conf.isUpdate() ) {
HashMap<String, List<String>> urisInScope = new HashMap<String, List<String>>();
urisInScope.put("title", Arrays.asList(new String[]{titleUri}));
conf.addUrisInScope(urisInScope);
}
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("preferredTitle")
.setRangeDatatypeUri( XSD.xstring.toString() ).
setValidators( list("nonempty") ));
conf.addValidator(new AntiXssValidation());
prepare(vreq, conf);
return conf;
}
/* N3 assertions */
final static String n3ForNewPhone =
final static String n3ForNewPhone =
"?person <http://purl.obolibrary.org/obo/ARG_2000028> ?individualVcard . \n" +
"?individualVcard a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?individualVcard a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?individualVcard <http://purl.obolibrary.org/obo/ARG_2000029> ?person . \n" +
"?individualVcard <http://www.w3.org/2006/vcard/ns#hasTitle> ?title . \n" +
"?title a <http://www.w3.org/2006/vcard/ns#Title> . " ;
final static String preferredTitleAssertion =
"?title a <http://www.w3.org/2006/vcard/ns#Title> . " ;
final static String preferredTitleAssertion =
"?title <http://www.w3.org/2006/vcard/ns#title> ?preferredTitle .";
/* Queries for editing an existing entry */
final static String individualVcardQuery =
@ -86,13 +86,13 @@ public class PersonHasPreferredTitleGenerator extends VivoBaseGenerator implemen
"?person <http://purl.obolibrary.org/obo/ARG_2000028> ?existingIndividualVcard . \n" +
"}";
final static String preferredTitleQuery =
final static String preferredTitleQuery =
"SELECT ?existingPreferredTitle WHERE {\n"+
"?title <http://www.w3.org/2006/vcard/ns#title> ?existingPreferredTitle . }";
private String getTitleUri(VitroRequest vreq) {
String titleUri = vreq.getParameter("titleUri");
String titleUri = vreq.getParameter("titleUri");
return titleUri;
}
}

View file

@ -18,48 +18,48 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.
import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils.EditMode;
import edu.cornell.mannlib.vitro.webapp.utils.generators.EditModeUtils;
public class ProjectHasParticipantGenerator extends VivoBaseGenerator implements EditConfigurationGenerator{
public class ProjectHasParticipantGenerator extends VivoBaseGenerator implements EditConfigurationGenerator{
//TODO: can we get rid of the session and get it form the vreq?
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) throws Exception {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
initObjectPropForm(conf, vreq);
conf.setTemplate("projectHasParticipant.ftl");
conf.setVarNameForSubject("project");
conf.setVarNameForPredicate("predicate");
conf.setVarNameForObject("projectRole");
conf.setN3Required( Arrays.asList( n3ForNewProjectRole ) );
conf.setN3Optional(Arrays.asList( n3ForNewPerson, n3ForExistingPerson, firstNameAssertion, lastNameAssertion ) );
conf.addNewResource("projectRole", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("newPerson",DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("vcardPerson", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("vcardName", DEFAULT_NS_FOR_NEW_RESOURCE);
//uris in scope: none
//uris in scope: none
//literals in scope: none
conf.setUrisOnform( Arrays.asList( "existingPerson"));
conf.setLiteralsOnForm( Arrays.asList("personLabel", "personLabelDisplay", "roleLabel",
conf.setLiteralsOnForm( Arrays.asList("personLabel", "personLabelDisplay", "roleLabel",
"roleLabeldisplay", "firstName", "lastName"));
conf.addSparqlForExistingLiteral("personLabel", personLabelQuery);
conf.addSparqlForExistingLiteral("roleLabel", roleLabelQuery);
conf.addSparqlForExistingUris("existingPerson", existingPersonQuery);
conf.addField( new FieldVTwo().
setName("existingPerson")
//options will be added in browser by auto complete JS
);
//options will be added in browser by auto complete JS
);
conf.addField( new FieldVTwo().
setName("personLabel").
setRangeDatatypeUri(XSD.xstring.toString() ).
@ -69,7 +69,7 @@ public class ProjectHasParticipantGenerator extends VivoBaseGenerator implement
setName("roleLabel").
setRangeDatatypeUri(XSD.xstring.toString() ).
setValidators( list("datatype:" + XSD.xstring.toString(),"nonempty")));
conf.addField( new FieldVTwo().
setName("personLabelDisplay").
setRangeDatatypeUri(XSD.xstring.toString() ));
@ -77,7 +77,7 @@ public class ProjectHasParticipantGenerator extends VivoBaseGenerator implement
conf.addField( new FieldVTwo().
setName("roleLabelDisplay").
setRangeDatatypeUri(XSD.xstring.toString() ));
conf.addField( new FieldVTwo().
setName("firstName").
setRangeDatatypeUri(XSD.xstring.toString() ).
@ -93,16 +93,16 @@ public class ProjectHasParticipantGenerator extends VivoBaseGenerator implement
//Add validator
conf.addValidator(new AntiXssValidation());
conf.addValidator(new FirstAndLastNameValidator("existingPerson"));
//Adding additional data, specifically edit mode
addFormSpecificData(conf, vreq);
prepare(vreq, conf);
return conf;
}
/* N3 assertions for working with educational training */
final static String n3ForNewProjectRole =
final static String n3ForNewProjectRole =
"@prefix core: <"+ vivoCore +"> .\n" +
"@prefix rdfs: <"+ rdfs +"> . \n"+
"?project <http://purl.obolibrary.org/obo/BFO_0000055> ?projectRole .\n" +
@ -110,42 +110,42 @@ public class ProjectHasParticipantGenerator extends VivoBaseGenerator implement
"?projectRole <http://purl.obolibrary.org/obo/BFO_0000054> ?project . \n" +
"?projectRole <"+ label +"> ?roleLabel . \n" ;
final static String n3ForNewPerson =
final static String n3ForNewPerson =
"?projectRole <http://purl.obolibrary.org/obo/RO_0000052> ?newPerson . \n" +
"?newPerson <http://purl.obolibrary.org/obo/RO_0000053> ?projectRole . \n" +
"?newPerson a <http://xmlns.com/foaf/0.1/Person> . \n" +
"?newPerson <"+ label +"> ?personLabel . ";
final static String n3ForExistingPerson =
final static String n3ForExistingPerson =
"?projectRole <http://purl.obolibrary.org/obo/RO_0000052> ?existingPerson . \n" +
"?existingPerson <http://purl.obolibrary.org/obo/RO_0000053> ?projectRole . \n" +
" ";
final static String firstNameAssertion =
final static String firstNameAssertion =
"@prefix vcard: <http://www.w3.org/2006/vcard/ns#> . \n" +
"?newPerson <http://purl.obolibrary.org/obo/ARG_2000028> ?vcardPerson . \n" +
"?vcardPerson <http://purl.obolibrary.org/obo/ARG_2000029> ?newPerson . \n" +
"?vcardPerson a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardPerson a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardPerson vcard:hasName ?vcardName . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName vcard:givenName ?firstName .";
final static String lastNameAssertion =
final static String lastNameAssertion =
"@prefix vcard: <http://www.w3.org/2006/vcard/ns#> . \n" +
"?newPerson <http://purl.obolibrary.org/obo/ARG_2000028> ?vcardPerson . \n" +
"?vcardPerson <http://purl.obolibrary.org/obo/ARG_2000029> ?newPerson . \n" +
"?vcardPerson a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardPerson a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?vcardPerson vcard:hasName ?vcardName . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
"?vcardName vcard:familyName ?lastName .";
/* Queries for editing an existing educational training entry */
final static String roleLabelQuery =
final static String roleLabelQuery =
"SELECT ?roleLabel WHERE {\n"+
"?projectRole <"+ label +"> ?roleLabel }\n";
final static String existingPersonQuery =
final static String existingPersonQuery =
"PREFIX rdfs: <"+ rdfs +"> \n"+
"SELECT ?existingPerson WHERE {\n"+
"?projectRole <http://purl.obolibrary.org/obo/RO_0000052> ?existingPerson . \n" +
@ -153,7 +153,7 @@ public class ProjectHasParticipantGenerator extends VivoBaseGenerator implement
"?existingPerson a <http://xmlns.com/foaf/0.1/Person> . \n " +
" }";
final static String personLabelQuery =
final static String personLabelQuery =
"PREFIX rdfs: <"+ rdfs +"> \n"+
"SELECT ?existingPersonLabel WHERE {\n"+
"?projectRole <http://purl.obolibrary.org/obo/RO_0000052> ?existingPerson . \n" +
@ -162,14 +162,14 @@ public class ProjectHasParticipantGenerator extends VivoBaseGenerator implement
"?existingPerson a <http://xmlns.com/foaf/0.1/Person> . \n " +
" }";
//Adding form specific data such as edit mode
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
formSpecificData.put("editMode", getEditMode(vreq).name().toLowerCase());
editConfiguration.setFormSpecificData(formSpecificData);
}
public EditMode getEditMode(VitroRequest vreq) {
List<String> predicates = new ArrayList<String>();
predicates.add("http://purl.obolibrary.org/obo/RO_0000053");

View file

@ -21,42 +21,42 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.
public class SubjectHasMailingAddressGenerator extends VivoBaseGenerator implements
EditConfigurationGenerator {
private Log log = LogFactory.getLog(SubjectHasMailingAddressGenerator.class);
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
HttpSession session) throws Exception {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
String addressUri = vreq.getParameter("addressUri");
initObjectPropForm(conf, vreq);
String addressUri = vreq.getParameter("addressUri");
conf.setTemplate("subjectHasMailingAddress.ftl");
conf.setVarNameForSubject("subject");
conf.setVarNameForPredicate("predicate");
conf.setVarNameForObject("individualVcard");
conf.setN3Required( Arrays.asList( n3ForNewAddress ) );
conf.setN3Optional( Arrays.asList( streetAddressAssertion,
localityAssertion,
regionAssertion,
countryAssertion,
conf.setN3Optional( Arrays.asList( streetAddressAssertion,
localityAssertion,
regionAssertion,
countryAssertion,
postalCodeAssertion ) );
conf.addNewResource("address", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("individualVcard", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.setLiteralsOnForm(Arrays.asList("streetAddress", "locality", "postalCode", "country", "region" ));
conf.addSparqlForExistingLiteral("streetAddress", streetAddressQuery);
conf.addSparqlForExistingLiteral("locality", localityQuery);
conf.addSparqlForExistingLiteral("postalCode", postalCodeQuery);
conf.addSparqlForExistingLiteral("region", regionQuery);
conf.addSparqlForExistingLiteral("country", countryQuery);
conf.addSparqlForExistingLiteral("country", countryQuery);
if ( conf.isUpdate() ) {
HashMap<String, List<String>> urisInScope = new HashMap<String, List<String>>();
urisInScope.put("address", Arrays.asList(new String[]{addressUri}));
@ -66,58 +66,58 @@ public class SubjectHasMailingAddressGenerator extends VivoBaseGenerator impleme
conf.addSparqlForAdditionalUrisInScope("individualVcard", individualVcardQuery);
}
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("streetAddress")
.setRangeDatatypeUri( XSD.xstring.toString() ).
setValidators( list("nonempty") ));
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("country")
.setRangeDatatypeUri( XSD.xstring.toString() ).
setValidators( list("nonempty") ));
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("postalCode")
.setRangeDatatypeUri( XSD.xstring.toString() ).
setValidators( list("nonempty") ));
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("locality")
.setRangeDatatypeUri( XSD.xstring.toString() ).
setValidators( list("nonempty") ) );
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("region")
.setRangeDatatypeUri( XSD.xstring.toString() ).
setValidators( list("datatype:" + XSD.xstring.toString()) ) );
conf.addValidator(new AntiXssValidation());
prepare(vreq, conf);
return conf;
}
/* N3 assertions */
final static String n3ForNewAddress =
final static String n3ForNewAddress =
"?subject <http://purl.obolibrary.org/obo/ARG_2000028> ?individualVcard . \n" +
"?individualVcard a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?individualVcard a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?individualVcard <http://purl.obolibrary.org/obo/ARG_2000029> ?subject . \n" +
"?individualVcard <http://www.w3.org/2006/vcard/ns#hasAddress> ?address . \n" +
"?address a <http://www.w3.org/2006/vcard/ns#Address> . " ;
final static String streetAddressAssertion =
"?address a <http://www.w3.org/2006/vcard/ns#Address> . " ;
final static String streetAddressAssertion =
"?address <http://www.w3.org/2006/vcard/ns#streetAddress> ?streetAddress .";
final static String localityAssertion =
final static String localityAssertion =
"?address <http://www.w3.org/2006/vcard/ns#locality> ?locality .";
final static String postalCodeAssertion =
"?address <http://www.w3.org/2006/vcard/ns#postalCode> ?postalCode .";
final static String regionAssertion =
"?address <http://www.w3.org/2006/vcard/ns#region> ?region .";
final static String postalCodeAssertion =
"?address <http://www.w3.org/2006/vcard/ns#postalCode> ?postalCode .";
final static String regionAssertion =
"?address <http://www.w3.org/2006/vcard/ns#region> ?region .";
final static String countryAssertion =
"?address <http://www.w3.org/2006/vcard/ns#country> ?country .";
@ -129,23 +129,23 @@ public class SubjectHasMailingAddressGenerator extends VivoBaseGenerator impleme
"?subject <http://purl.obolibrary.org/obo/ARG_2000028> ?individualVcard . \n" +
"}";
final static String streetAddressQuery =
final static String streetAddressQuery =
"SELECT ?existingStreetAddress WHERE {\n"+
"?address <http://www.w3.org/2006/vcard/ns#streetAddress> ?existingStreetAddress . }";
final static String localityQuery =
final static String localityQuery =
"SELECT ?existingLocality WHERE {\n"+
"?address <http://www.w3.org/2006/vcard/ns#locality> ?existingLocality . }";
final static String regionQuery =
final static String regionQuery =
"SELECT ?existingRegion WHERE {\n"+
"?address <http://www.w3.org/2006/vcard/ns#region> ?existingRegion . }";
final static String postalCodeQuery =
final static String postalCodeQuery =
"SELECT ?existingPostalCode WHERE {\n"+
"?address <http://www.w3.org/2006/vcard/ns#postalCode> ?existingPostalCode . }";
final static String countryQuery =
final static String countryQuery =
"SELECT ?existingCountry WHERE {\n"+
"?address <http://www.w3.org/2006/vcard/ns#country> ?existingCountry . }";

View file

@ -25,27 +25,27 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.
public class SubjectHasPhoneFaxNumberGenerator extends VivoBaseGenerator implements
EditConfigurationGenerator {
private Log log = LogFactory.getLog(SubjectHasPhoneFaxNumberGenerator.class);
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
HttpSession session) throws Exception {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
Model model = ModelFactory.createDefaultModel();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
String phoneUri = getPhoneUri(vreq);
initObjectPropForm(conf, vreq);
String phoneUri = getPhoneUri(vreq);
String rangeUri = getRangeUri(vreq);
Literal numberType = null;
Literal numberType = null;
conf.setTemplate("subjectHasPhoneFaxNumber.ftl");
conf.setVarNameForSubject("subject");
conf.setVarNameForPredicate("predicate");
conf.setVarNameForObject("individualVcard");
if ( rangeUri.equals("http://www.w3.org/2006/vcard/ns#Fax") ) {
conf.setN3Required( Arrays.asList( n3ForNewFaxNumber ) );
numberType = model.createLiteral("fax");
@ -56,15 +56,15 @@ public class SubjectHasPhoneFaxNumberGenerator extends VivoBaseGenerator impleme
}
conf.setN3Optional( Arrays.asList( telephoneNumberAssertion ) );
conf.addNewResource("phone", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("individualVcard", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.setLiteralsOnForm(Arrays.asList("telephoneNumber" ));
conf.addSparqlForExistingLiteral("telephoneNumber", telephoneNumberQuery);
conf.addSparqlForAdditionalUrisInScope("individualVcard", individualVcardQuery);
conf.addLiteralInScope("numberType", numberType);
if ( conf.isUpdate() ) {
@ -73,37 +73,37 @@ public class SubjectHasPhoneFaxNumberGenerator extends VivoBaseGenerator impleme
conf.addUrisInScope(urisInScope);
}
conf.addField( new FieldVTwo().
conf.addField( new FieldVTwo().
setName("telephoneNumber")
.setRangeDatatypeUri( XSD.xstring.toString() ).
setValidators( list("nonempty") ));
conf.addValidator(new AntiXssValidation());
prepare(vreq, conf);
return conf;
}
/* N3 assertions */
final static String n3ForNewPhoneNumber =
final static String n3ForNewPhoneNumber =
"?subject <http://purl.obolibrary.org/obo/ARG_2000028> ?individualVcard . \n" +
"?individualVcard a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?individualVcard a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?individualVcard <http://purl.obolibrary.org/obo/ARG_2000029> ?subject . \n" +
"?individualVcard <http://www.w3.org/2006/vcard/ns#hasTelephone> ?phone . \n" +
"?phone a <http://www.w3.org/2006/vcard/ns#Telephone> . " ;
final static String n3ForNewFaxNumber =
"?subject <http://purl.obolibrary.org/obo/ARG_2000028> ?individualVcard . \n" +
"?individualVcard a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?individualVcard <http://purl.obolibrary.org/obo/ARG_2000029> ?subject . \n" +
"?individualVcard <http://www.w3.org/2006/vcard/ns#hasTelephone> ?phone . \n" +
"?phone a <http://www.w3.org/2006/vcard/ns#Telephone> . \n " +
"?phone a <http://www.w3.org/2006/vcard/ns#Fax> . " ;
"?phone a <http://www.w3.org/2006/vcard/ns#Telephone> . " ;
final static String telephoneNumberAssertion =
final static String n3ForNewFaxNumber =
"?subject <http://purl.obolibrary.org/obo/ARG_2000028> ?individualVcard . \n" +
"?individualVcard a <http://www.w3.org/2006/vcard/ns#Individual> . \n" +
"?individualVcard <http://purl.obolibrary.org/obo/ARG_2000029> ?subject . \n" +
"?individualVcard <http://www.w3.org/2006/vcard/ns#hasTelephone> ?phone . \n" +
"?phone a <http://www.w3.org/2006/vcard/ns#Telephone> . \n " +
"?phone a <http://www.w3.org/2006/vcard/ns#Fax> . " ;
final static String telephoneNumberAssertion =
"?phone <http://www.w3.org/2006/vcard/ns#telephone> ?telephoneNumber .";
/* Queries for editing an existing entry */
final static String individualVcardQuery =
@ -111,19 +111,19 @@ public class SubjectHasPhoneFaxNumberGenerator extends VivoBaseGenerator impleme
"?subject <http://purl.obolibrary.org/obo/ARG_2000028> ?existingIndividualVcard . \n" +
"}";
final static String telephoneNumberQuery =
final static String telephoneNumberQuery =
"SELECT ?existingTelephoneNumber WHERE {\n"+
"?phone <http://www.w3.org/2006/vcard/ns#telephone> ?existingTelephoneNumber . }";
private String getPhoneUri(VitroRequest vreq) {
String phoneUri = vreq.getParameter("phoneUri");
String phoneUri = vreq.getParameter("phoneUri");
return phoneUri;
}
private String getRangeUri(VitroRequest vreq) {
String rangeUri = vreq.getParameter("rangeUri");
String rangeUri = vreq.getParameter("rangeUri");
return rangeUri;
}
}

View file

@ -22,7 +22,7 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
*
*/
public class VIVODefaultAddMissingIndividualFormGenerator extends DefaultAddMissingIndividualFormGenerator {
private Log log = LogFactory.getLog(VIVODefaultAddMissingIndividualFormGenerator.class);
protected Map<String, String> generateNewResources(VitroRequest vreq) {
@ -37,11 +37,11 @@ public class VIVODefaultAddMissingIndividualFormGenerator extends DefaultAddMiss
prefixStrings.add("@prefix vcard: <http://www.w3.org/2006/vcard/ns#> .");
return prefixStrings;
}
protected String getN3ForName() {
return "?" + objectVarName + " rdfs:label ?label .";
}
protected List<String> generateN3Optional(VitroRequest vreq) {
List<String> n3Optional = super.generateN3Optional(vreq);
n3Optional.add(getN3PrefixesAsString()
@ -52,7 +52,7 @@ public class VIVODefaultAddMissingIndividualFormGenerator extends DefaultAddMiss
+ " ?newVcardName a vcard:Name . \n"
+ " ?newVcardName vcard:givenName ?firstName . \n"
+ " ?newVcardName vcard:familyName ?lastName . \n");
n3Optional.add(getN3PrefixesAsString()
n3Optional.add(getN3PrefixesAsString()
+ "?" + objectVarName + "<http://purl.obolibrary.org/obo/ARG_2000028> ?newVcardInd . \n"
+ " ?newVcardInd a vcard:Individual . \n"
+ " ?newVcardInd vcard:hasName ?newVcardName . \n"
@ -75,39 +75,39 @@ public class VIVODefaultAddMissingIndividualFormGenerator extends DefaultAddMiss
protected void setFields(EditConfigurationVTwo editConfiguration, VitroRequest vreq, String predicateUri) {
Map<String, FieldVTwo> fields = new HashMap<String, FieldVTwo>();
if(EditConfigurationUtils.isObjectProperty(EditConfigurationUtils.getPredicateUri(vreq), vreq)) {
//make name field
FieldVTwo labelField = new FieldVTwo();
labelField.setName("label");
labelField.setName("label");
FieldVTwo firstNameField = new FieldVTwo();
firstNameField.setName("firstName");
firstNameField.setName("firstName");
FieldVTwo middleNameField = new FieldVTwo();
middleNameField.setName("middleName");
middleNameField.setName("middleName");
FieldVTwo lastNameField = new FieldVTwo();
lastNameField.setName("lastName");
lastNameField.setName("lastName");
List<String> validators = new ArrayList<String>();
validators.add("nonempty");
if(!isPersonType(vreq)) {
labelField.setValidators(validators);
if(!isPersonType(vreq)) {
labelField.setValidators(validators);
}
if(isPersonType(vreq)) {
firstNameField.setValidators(validators);
lastNameField.setValidators(validators);
if(isPersonType(vreq)) {
firstNameField.setValidators(validators);
lastNameField.setValidators(validators);
}
fields.put(labelField.getName(), labelField);
fields.put(firstNameField.getName(), firstNameField);
fields.put(middleNameField.getName(), middleNameField);
fields.put(lastNameField.getName(), lastNameField);
} else {
log.error("Is not object property so fields not set");
}
editConfiguration.setFields(fields);
}
@ -131,11 +131,11 @@ public class VIVODefaultAddMissingIndividualFormGenerator extends DefaultAddMiss
VClass type = vreq.getWebappDaoFactory().getVClassDao().getVClassByURI(typeOfNew);
return type.getName();
}
public String getFOAFPersonClassURI() {
return "http://xmlns.com/foaf/0.1/Person";
}
public boolean isPersonType(VitroRequest vreq) {
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
Boolean isPersonType = Boolean.FALSE;
@ -150,7 +150,7 @@ public class VIVODefaultAddMissingIndividualFormGenerator extends DefaultAddMiss
isPersonType = Boolean.TRUE;
break;
}
}
}
}
return isPersonType;
}

View file

@ -15,7 +15,7 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUti
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
/**
*This generator selects the actual generator to be employed based on whether the individual is a Person
*This generator selects the actual generator to be employed based on whether the individual is a Person
*or another individual. Adding a label for a person relies on first/name last name information i.e. object properties.
*/
public class VIVOManageLabelsGenerator extends BaseEditConfigurationGenerator implements EditConfigurationGenerator {
@ -30,14 +30,14 @@ public class VIVOManageLabelsGenerator extends BaseEditConfigurationGenerator im
} else {
//Non-Person individuals
e = new ManageLabelsForIndividualGenerator().getEditConfiguration(vreq, session);
}
return e;
}
public boolean isPersonType(String subjectUri, VitroRequest vreq) {
Boolean isPersonType = Boolean.FALSE;
String foafPersonType = getFOAFPersonClassURI();
@ -49,17 +49,17 @@ public class VIVOManageLabelsGenerator extends BaseEditConfigurationGenerator im
isPersonType = Boolean.TRUE;
break;
}
}
}
}
return isPersonType;
}
//Copied from NewIndividualFormGenerator
//TODO: Refactor so common code can be used by both generators
public String getFOAFPersonClassURI() {
return "http://xmlns.com/foaf/0.1/Person";
}
//how to get the type of the individual in question
public List<VClass> getVClasses(String subjectUri, VitroRequest vreq) {
Individual subject = EditConfigurationUtils.getIndividual(vreq, subjectUri);

View file

@ -24,22 +24,22 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.
/**
* Generates the edit configuration for a default property form.
* ModelChangePreprocessor creates the rdfs:label statement.
* ModelChangePreprocessor creates the rdfs:label statement.
*/
public class VIVONewIndividualFormGenerator extends BaseEditConfigurationGenerator implements EditConfigurationGenerator {
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) {
EditConfigurationVTwo config = new EditConfigurationVTwo();
config.setTemplate( "newIndividualForm.ftl" );
config.setN3Required( list(
"?newInd <" + VitroVocabulary.RDF_TYPE + "> <" + getTypeOfNew(vreq) + "> ."
));
));
//Optional because user may have selected either person or individual of another kind
//Person uses first name and last name whereas individual of other class would use label
//Person uses first name and last name whereas individual of other class would use label
//middle name is also optional
config.setN3Optional(list(
N3_PREFIX + "@prefix vcard: <http://www.w3.org/2006/vcard/ns#> .\n"
@ -58,55 +58,55 @@ public class VIVONewIndividualFormGenerator extends BaseEditConfigurationGenerat
+ " ?newVcardName a vcard:Name . \n"
+ " ?newVcardName <http://vivoweb.org/ontology/core#middleName> ?middleName ."
));
config.addNewResource("newInd", vreq.getWebappDaoFactory().getDefaultNamespace());
config.addNewResource("newVcardInd", vreq.getWebappDaoFactory().getDefaultNamespace());
config.addNewResource("newVcardName", vreq.getWebappDaoFactory().getDefaultNamespace());
config.setUrisOnform(list ());
config.setLiteralsOnForm( list( "label", "firstName", "lastName", "middleName" ));
config.setLiteralsOnForm( list( "label", "firstName", "lastName", "middleName" ));
setUrisAndLiteralsInScope(config);
//No SPARQL queries for existing since this is only used to create new, never for edit
//No SPARQL queries for existing since this is only used to create new, never for edit
config.addField(new FieldVTwo().
setName("firstName").
setRangeDatatypeUri(XSD.xstring.getURI()).
setValidators(getFirstNameValidators(vreq)));
config.addField(new FieldVTwo().
setName("middleName").
setRangeDatatypeUri(XSD.xstring.getURI()).
setValidators(getMiddleNameValidators(vreq)));
config.addField(new FieldVTwo().
setName("lastName").
setRangeDatatypeUri(XSD.xstring.getURI()).
setValidators(getLastNameValidators(vreq)));
setValidators(getLastNameValidators(vreq)));
config.addField(new FieldVTwo().
setName("label").
setRangeDatatypeUri(XSD.xstring.getURI()).
setValidators(getLabelValidators(vreq)));
addFormSpecificData(config, vreq);
setValidators(getLabelValidators(vreq)));
addFormSpecificData(config, vreq);
config.addValidator(new AntiXssValidation());
//This combines the first and last name into the rdfs:label
// currently being done via javascript in the template. May use this again
// when/if updated to ISF ontology. tlw72
// config.addModelChangePreprocessor(new FoafNameToRdfsLabelPreprocessor());
// config.addModelChangePreprocessor(new FoafNameToRdfsLabelPreprocessor());
String formUrl = EditConfigurationUtils.getFormUrlWithoutContext(vreq);
String formUrl = EditConfigurationUtils.getFormUrlWithoutContext(vreq);
config.setFormUrl(formUrl);
//Note, the spaces are important - they were added by ProcessRdfFormController earlier
//as a means of ensuring the substitution worked correctly - as the regex expects spaces
config.setEntityToReturnTo(" ?newInd ");
prepare(vreq, config);
return config;
}
private List<String> getMiddleNameValidators(VitroRequest vreq) {
List<String> validators = new ArrayList<String>();
return validators;
@ -144,9 +144,9 @@ public class VIVONewIndividualFormGenerator extends BaseEditConfigurationGenerat
if( typeUri == null || typeUri.trim().isEmpty() )
return getFOAFPersonClassURI();
else
return typeUri;
return typeUri;
}
//Form specific data
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
@ -167,11 +167,11 @@ public class VIVONewIndividualFormGenerator extends BaseEditConfigurationGenerat
VClass type = vreq.getWebappDaoFactory().getVClassDao().getVClassByURI(typeOfNew);
return type.getName();
}
public String getFOAFPersonClassURI() {
return "http://xmlns.com/foaf/0.1/Person";
}
public boolean isPersonType(VitroRequest vreq) {
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
Boolean isPersonType = Boolean.FALSE;
@ -186,22 +186,22 @@ public class VIVONewIndividualFormGenerator extends BaseEditConfigurationGenerat
isPersonType = Boolean.TRUE;
break;
}
}
}
}
return isPersonType;
}
private void setUrisAndLiteralsInScope(EditConfigurationVTwo editConfiguration) {
HashMap<String, List<String>> urisInScope = new HashMap<String, List<String>>();
//note that at this point the subject, predicate, and object var parameters have already been processed
urisInScope.put(editConfiguration.getVarNameForSubject(),
urisInScope.put(editConfiguration.getVarNameForSubject(),
Arrays.asList(new String[]{editConfiguration.getSubjectUri()}));
urisInScope.put(editConfiguration.getVarNameForPredicate(),
urisInScope.put(editConfiguration.getVarNameForPredicate(),
Arrays.asList(new String[]{editConfiguration.getPredicateUri()}));
editConfiguration.setUrisInScope(urisInScope);
//Uris in scope include subject, predicate, and object var
editConfiguration.setLiteralsInScope(new HashMap<String, List<Literal>>());
}
private String N3_PREFIX = "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n";
}

View file

@ -5,7 +5,7 @@ import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
/**
* Adds static Strings that may be useful for forms that are part of VIVO.
*
*
* @author bdc34
*
*/
@ -14,18 +14,18 @@ public abstract class VivoBaseGenerator extends BaseEditConfigurationGenerator i
final static String vivoCore ="http://vivoweb.org/ontology/core#" ;
final static String rdfs =VitroVocabulary.RDFS ;
final static String foaf = "http://xmlns.com/foaf/0.1/";
final static String type =VitroVocabulary.RDF_TYPE ;
final static String type =VitroVocabulary.RDF_TYPE ;
final static String label =rdfs+"label" ;
final static String bibo = "http://purl.org/ontology/bibo/";
final static String edProcessClass = vivoCore+"EducationalProcess" ;
final static String degreeTypeClass =vivoCore+"AcademicDegree" ;
final static String edProcessClass = vivoCore+"EducationalProcess" ;
final static String degreeTypeClass =vivoCore+"AcademicDegree" ;
final static String majorFieldPred =vivoCore+"majorField" ;
final static String deptPred =vivoCore+"departmentOrSchool" ;
final static String infoPred =vivoCore+"supplementalInformation" ;
final static String authorRankPredicate = vivoCore + "authorRank";
final static String linkedAuthorPredicate = vivoCore + "relates";
final static String dateTimeValue =vivoCore+"dateTime";
final static String dateTimeValueType =vivoCore+"DateTimeValue";
final static String dateTimePrecision =vivoCore+"dateTimePrecision";
@ -37,5 +37,5 @@ public abstract class VivoBaseGenerator extends BaseEditConfigurationGenerator i
final static String orgClass ="http://xmlns.com/foaf/0.1/Organization" ;
final static String personClass = foaf + "Person";
}

View file

@ -28,39 +28,39 @@ import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
public class ConceptSemanticTypesPreprocessor implements ModelChangePreprocessor {
private static String VIVOCore = "http://vivoweb.org/ontology/core#";
private static String SKOSConceptType = "http://www.w3.org/2004/02/skos/core#Concept";
private static String SKOSConceptType = "http://www.w3.org/2004/02/skos/core#Concept";
private Log log = LogFactory.getLog(ConceptSemanticTypesPreprocessor.class);
//Custom constructor
public ConceptSemanticTypesPreprocessor() {
}
@Override
public void preprocess(Model retractionsModel, Model additionsModel,
HttpServletRequest request) {
VitroRequest vreq = new VitroRequest(request);
//Run a construct query against the additions model
String prefixes = "PREFIX rdfs:<" + RDFS.getURI() + "> " +
"PREFIX owl:<http://www.w3.org/2002/07/owl#> " +
"PREFIX rdf:<" + RDF.getURI() + ">" +
"PREFIX skos:<http://www.w3.org/2004/02/skos/core#>";
String constructQuery = prefixes + " CONSTRUCT { " +
"?semanticType rdf:type owl:Class. " +
"?semanticType rdfs:subClassOf skos:Concept . " +
"?semanticType rdfs:label ?label. " +
"} WHERE { " +
"?concept rdf:type ?semanticType. " +
"?semanticType rdfs:label ?label . " +
"?semanticType rdfs:subClassOf skos:Concept . " +
String prefixes = "PREFIX rdfs:<" + RDFS.getURI() + "> " +
"PREFIX owl:<http://www.w3.org/2002/07/owl#> " +
"PREFIX rdf:<" + RDF.getURI() + ">" +
"PREFIX skos:<http://www.w3.org/2004/02/skos/core#>";
String constructQuery = prefixes + " CONSTRUCT { " +
"?semanticType rdf:type owl:Class. " +
"?semanticType rdfs:subClassOf skos:Concept . " +
"?semanticType rdfs:label ?label. " +
"} WHERE { " +
"?concept rdf:type ?semanticType. " +
"?semanticType rdfs:label ?label . " +
"?semanticType rdfs:subClassOf skos:Concept . " +
"}";
//Execute construct query
//Execute construct query
Model constructedModel = ModelFactory.createDefaultModel();
log.debug("CONSTRUCT query string " + constructQuery);
Query query = null;
try {
query = QueryFactory.create(constructQuery, Syntax.syntaxARQ);
@ -69,13 +69,13 @@ public class ConceptSemanticTypesPreprocessor implements ModelChangePreprocessor
"string. " + th.getMessage());
log.error(constructQuery);
return;
}
}
additionsModel.getLock().enterCriticalSection(Lock.READ);
QueryExecution qe = null;
try {
try {
qe = QueryExecutionFactory.create(
query, additionsModel);
qe.execConstruct(constructedModel);
@ -87,7 +87,7 @@ public class ConceptSemanticTypesPreprocessor implements ModelChangePreprocessor
}
additionsModel.getLock().leaveCriticalSection();
}
//Add constructed model to the designated update model
OntModel toUpdateModel = ModelAccess.on(vreq).getOntModelSelector().getTBoxModel();
toUpdateModel.enterCriticalSection(Lock.WRITE);
@ -98,7 +98,7 @@ public class ConceptSemanticTypesPreprocessor implements ModelChangePreprocessor
} finally {
toUpdateModel.leaveCriticalSection();
}
//Take this constructed model and remove from the additions model
additionsModel.enterCriticalSection(Lock.WRITE);
try {
@ -108,9 +108,9 @@ public class ConceptSemanticTypesPreprocessor implements ModelChangePreprocessor
} finally {
additionsModel.leaveCriticalSection();
}
}
}

View file

@ -18,14 +18,14 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmis
public class ManageLabelsForPersonPreprocessor extends ManageLabelsForIndividualPreprocessor {
public ManageLabelsForPersonPreprocessor(EditConfigurationVTwo editConfig) {
super(editConfig);
}
@Override
public void preprocess(MultiValueEditSubmission inputSubmission, VitroRequest vreq) {
//Use the ManageLabelsForIndividualPreprocessor in addition to this code specific for person
@ -42,27 +42,27 @@ public class ManageLabelsForPersonPreprocessor extends ManageLabelsForIndividual
if(inputSubmission.hasLiteralValue("middleName")) {
middleNames = literalsFromForm.get("middleName");
}
//Expecting only one language
if(firstNames.size() > 0 && lastNames.size() > 0 && newLabelLanguages.size() > 0) {
Literal newLabelLanguage = newLabelLanguages.get(0);
Literal firstNameLiteral = firstNames.get(0);
Literal lastNameLiteral = lastNames.get(0);
//Get the string
String lang = this.getLanguage(newLabelLanguage.getString());
String firstNameValue = firstNameLiteral.getString();
String lastNameValue = lastNameLiteral.getString();
//Now add the language category to the literal
Literal firstNameWithLanguage = inputSubmission.createLiteral(firstNameValue,
null,
Literal firstNameWithLanguage = inputSubmission.createLiteral(firstNameValue,
null,
lang);
Literal lastNameWithLanguage = inputSubmission.createLiteral(lastNameValue,
null,
Literal lastNameWithLanguage = inputSubmission.createLiteral(lastNameValue,
null,
lang);
firstNames = new ArrayList<Literal>();
lastNames = new ArrayList<Literal>();
firstNames.add(firstNameWithLanguage);
@ -70,25 +70,25 @@ public class ManageLabelsForPersonPreprocessor extends ManageLabelsForIndividual
//replace the label with one with language, again assuming only one label being returned
literalsFromForm.put("firstName", firstNames);
literalsFromForm.put("lastName", lastNames);
//Middle name handling
if(middleNames.size() > 0) {
Literal middleNameLiteral = middleNames.get(0);
String middleNameValue = middleNameLiteral.getString();
Literal middleNameWithLanguage = inputSubmission.createLiteral(middleNameValue,
null,
Literal middleNameWithLanguage = inputSubmission.createLiteral(middleNameValue,
null,
lang);
middleNames = new ArrayList<Literal>();
middleNames.add(middleNameWithLanguage);
literalsFromForm.put("middleName", middleNames);
}
//Set literals
inputSubmission.setLiteralsFromForm(literalsFromForm);
}
}
}
}

View file

@ -1,34 +1,34 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors;
import java.util.Map;
import java.util.List;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmission;
public class RoleToActivityPredicatePreprocessor extends RoleToPredicatePreprocessor {
public RoleToActivityPredicatePreprocessor(EditConfigurationVTwo editConfig, WebappDaoFactory wadf) {
super(editConfig, wadf);
}
protected void setupVariableNames() {
this.itemType = "roleActivityType";
this.roleToItemPredicate = "roleToActivityPredicate";
this.itemToRolePredicate = "activityToRolePredicate";
}
protected String getItemType(MultiValueEditSubmission submission) {
String type = null;
Map<String, List<String>> urisFromForm = submission.getUrisFromForm();
//Get the type of the activity selected
List<String> itemTypes = urisFromForm.get(itemType);
//Really should just be one here
if(itemTypes != null && itemTypes.size() > 0) {
type = itemTypes.get(0);
}
return type;
}
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors;
import java.util.Map;
import java.util.List;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmission;
public class RoleToActivityPredicatePreprocessor extends RoleToPredicatePreprocessor {
public RoleToActivityPredicatePreprocessor(EditConfigurationVTwo editConfig, WebappDaoFactory wadf) {
super(editConfig, wadf);
}
protected void setupVariableNames() {
this.itemType = "roleActivityType";
this.roleToItemPredicate = "roleToActivityPredicate";
this.itemToRolePredicate = "activityToRolePredicate";
}
protected String getItemType(MultiValueEditSubmission submission) {
String type = null;
Map<String, List<String>> urisFromForm = submission.getUrisFromForm();
//Get the type of the activity selected
List<String> itemTypes = urisFromForm.get(itemType);
//Really should just be one here
if(itemTypes != null && itemTypes.size() > 0) {
type = itemTypes.get(0);
}
return type;
}
}

View file

@ -1,83 +1,83 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.BaseEditSubmissionPreprocessorVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmission;
import org.vivoweb.webapp.util.ModelUtils;
public abstract class RoleToPredicatePreprocessor extends BaseEditSubmissionPreprocessorVTwo {
protected static final Log log = LogFactory.getLog(RoleToPredicatePreprocessor.class.getName());
protected WebappDaoFactory wadf = null;
protected static String itemType;
protected static String roleToItemPredicate;
protected static String itemToRolePredicate;
//Need the webapp dao factory to try to figure out what the predicate should be
public RoleToPredicatePreprocessor(EditConfigurationVTwo editConfig, WebappDaoFactory wadf) {
super(editConfig);
this.wadf = wadf;
setupVariableNames();
}
//Instantiate itemType etc. based on which version of preprocessor required
abstract protected void setupVariableNames();
public void preprocess(MultiValueEditSubmission submission, VitroRequest vreq) {
//Query for all statements using the original roleIn predicate replace
//with the appropriate roleRealizedIn or roleContributesTo
//In addition, need to ensure the inverse predicate is also set correctly
try {
//Get the uris from form
String type = getItemType(submission);
Map<String, List<String>> urisFromForm = submission.getUrisFromForm();
if(type != null) {
ObjectProperty roleToItemProperty = getCorrectProperty(type, wadf);
String roleToItemPredicateURI = roleToItemProperty.getURI();
String itemToRolePredicateURI = roleToItemProperty.getURIInverse();
List<String> predicates = new ArrayList<String>();
predicates.add(roleToItemPredicateURI);
List<String> inversePredicates = new ArrayList<String>();
inversePredicates.add(itemToRolePredicateURI);
//Populate the two fields in edit submission
if(urisFromForm.containsKey(roleToItemPredicate)) {
urisFromForm.remove(roleToItemPredicate);
}
urisFromForm.put(roleToItemPredicate, predicates);
if(urisFromForm.containsKey(itemToRolePredicate)) {
urisFromForm.remove(itemToRolePredicate);
}
urisFromForm.put(itemToRolePredicate, inversePredicates);
}
} catch (Exception e) {
log.error("Error retrieving name values from edit submission.");
}
}
abstract protected String getItemType(MultiValueEditSubmission submission);
private ObjectProperty getCorrectProperty(String uri, WebappDaoFactory wadf) {
ObjectProperty correctProperty = ModelUtils.getPropertyForRoleInClass(uri, wadf);
return correctProperty;
}
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.BaseEditSubmissionPreprocessorVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmission;
import org.vivoweb.webapp.util.ModelUtils;
public abstract class RoleToPredicatePreprocessor extends BaseEditSubmissionPreprocessorVTwo {
protected static final Log log = LogFactory.getLog(RoleToPredicatePreprocessor.class.getName());
protected WebappDaoFactory wadf = null;
protected static String itemType;
protected static String roleToItemPredicate;
protected static String itemToRolePredicate;
//Need the webapp dao factory to try to figure out what the predicate should be
public RoleToPredicatePreprocessor(EditConfigurationVTwo editConfig, WebappDaoFactory wadf) {
super(editConfig);
this.wadf = wadf;
setupVariableNames();
}
//Instantiate itemType etc. based on which version of preprocessor required
abstract protected void setupVariableNames();
public void preprocess(MultiValueEditSubmission submission, VitroRequest vreq) {
//Query for all statements using the original roleIn predicate replace
//with the appropriate roleRealizedIn or roleContributesTo
//In addition, need to ensure the inverse predicate is also set correctly
try {
//Get the uris from form
String type = getItemType(submission);
Map<String, List<String>> urisFromForm = submission.getUrisFromForm();
if(type != null) {
ObjectProperty roleToItemProperty = getCorrectProperty(type, wadf);
String roleToItemPredicateURI = roleToItemProperty.getURI();
String itemToRolePredicateURI = roleToItemProperty.getURIInverse();
List<String> predicates = new ArrayList<String>();
predicates.add(roleToItemPredicateURI);
List<String> inversePredicates = new ArrayList<String>();
inversePredicates.add(itemToRolePredicateURI);
//Populate the two fields in edit submission
if(urisFromForm.containsKey(roleToItemPredicate)) {
urisFromForm.remove(roleToItemPredicate);
}
urisFromForm.put(roleToItemPredicate, predicates);
if(urisFromForm.containsKey(itemToRolePredicate)) {
urisFromForm.remove(itemToRolePredicate);
}
urisFromForm.put(itemToRolePredicate, inversePredicates);
}
} catch (Exception e) {
log.error("Error retrieving name values from edit submission.");
}
}
abstract protected String getItemType(MultiValueEditSubmission submission);
private ObjectProperty getCorrectProperty(String uri, WebappDaoFactory wadf) {
ObjectProperty correctProperty = ModelUtils.getPropertyForRoleInClass(uri, wadf);
return correctProperty;
}
}

View file

@ -1,225 +1,225 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.ServletContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.ResourceFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
//Returns the appropriate n3 for selection of classes from within class group
public class ProcessInternalClassDataGetterN3 extends ProcessIndividualsForClassesDataGetterN3 {
private static String classType = "java:edu.cornell.mannlib.vitro.webapp.utils.dataGetter.InternalClassesDataGetter";
private static String internalClassVarNameBase = "isInternal";
private Log log = LogFactory.getLog(ProcessInternalClassDataGetterN3.class);
public ProcessInternalClassDataGetterN3(){
super();
}
//Pass in variable that represents the counter
//Saving both type and class group here
//That can be included here if need be, but for now just adding the type alone
public List<String> retrieveN3Required(int counter) {
return super.retrieveN3Required(counter);
}
//returns n3 defining internal class
private List<String> addInternalClassN3(int counter) {
List<String> internalClassN3 = new ArrayList<String>();
String dataGetterVar = getDataGetterVar(counter);
internalClassN3.add(dataGetterVar + " <" + DisplayVocabulary.RESTRICT_RESULTS_BY_INTERNAL + "> " +
this.getN3VarName(internalClassVarNameBase, counter) + " .");
return internalClassN3;
}
public List<String> retrieveN3Optional(int counter) {
List<String> optionalN3 = new ArrayList<String>();
//If internal add that as well
optionalN3.addAll(this.addInternalClassN3(counter));
return optionalN3;
}
//These methods will return the literals and uris expected within the n3
//and the counter is used to ensure they are numbered correctly
public List<String> retrieveLiteralsOnForm(int counter) {
//no literals, just the class group URI
List<String> literalsOnForm = new ArrayList<String>();
literalsOnForm.add(getVarName(internalClassVarNameBase, counter));
return literalsOnForm;
}
//URIs on form are same as individuals for class group so no need to reimplement
//i.e. class groups and individuals selected within class group
public List<FieldVTwo> retrieveFields(int counter) {
List<FieldVTwo> fields = super.retrieveFields(counter);
fields.add(new FieldVTwo().setName(getVarName(internalClassVarNameBase, counter)));
return fields;
}
//These var names match the names of the elements within the json object returned with the info required for the data getter
public List<String> getLiteralVarNamesBase() {
return Arrays.asList(internalClassVarNameBase);
}
//get URI Var Names base is same as ProcessIndividualsForClassGroup: classGroup and individualClassVarNameBase
@Override
public String getClassType() {
return classType;
}
public void populateExistingValues(String dataGetterURI, int counter, OntModel queryModel) {
//First, put dataGetterURI within scope as well
//((ProcessDataGetterAbstract)this).populateExistingDataGetterURI(dataGetterURI, counter);
this.populateExistingDataGetterURI(dataGetterURI, counter);
//Put in type
this.populateExistingClassType(this.getClassType(), counter);
//Sparql queries for values to be executed
//And then placed in the correct place/literal or uri
String querystr = getExistingValuesInternalClass(dataGetterURI);
QueryExecution qe = null;
Literal internalClassLiteral = null;
try{
Query query = QueryFactory.create(querystr);
qe = QueryExecutionFactory.create(query, queryModel);
ResultSet results = qe.execSelect();
String classGroupURI = null;
List<String> individualsForClasses = new ArrayList<String>();
while( results.hasNext()){
QuerySolution qs = results.nextSolution();
//Class group
Resource classGroupResource = qs.getResource("classGroup");
String classGroupVarName = this.getVarName(classGroupVarBase, counter);
if(classGroupURI == null) {
//Put both literals in existing literals
existingUriValues.put(this.getVarName(classGroupVarBase, counter),
new ArrayList<String>(Arrays.asList(classGroupResource.getURI())));
}
//Individuals For classes
Resource individualForClassResource = qs.getResource("individualForClass");
individualsForClasses.add(individualForClassResource.getURI());
//If internal class value is present and we have not already saved it in a previous result iteration
if(qs.get("internalClass") != null && internalClassLiteral == null) {
internalClassLiteral= qs.getLiteral("internalClass");
existingLiteralValues.put(this.getVarName(internalClassVarNameBase, counter),
new ArrayList<Literal>(Arrays.asList(internalClassLiteral)));
}
}
//Put array of individuals for classes within
existingUriValues.put(this.getVarName(individualClassVarNameBase, counter),
new ArrayList<String>(individualsForClasses));
//Final check, in case no internal class flag was returned, set to false
if(internalClassLiteral == null) {
existingLiteralValues.put(this.getVarName(internalClassVarNameBase, counter),
new ArrayList<Literal>(
Arrays.asList(ResourceFactory.createPlainLiteral("false"))
));
}
} catch(Exception ex) {
log.error("Exception occurred in retrieving existing values with query " + querystr, ex);
}
}
//?dataGetter a FixedHTMLDataGetter ; display:saveToVar ?saveToVar; display:htmlValue ?htmlValue .
protected String getExistingValuesInternalClass(String dataGetterURI) {
String query = this.getSparqlPrefix() + " SELECT ?classGroup ?individualForClass ?internalClass WHERE {" +
"<" + dataGetterURI + "> <" + DisplayVocabulary.FOR_CLASSGROUP + "> ?classGroup . \n" +
"OPTIONAL {<" + dataGetterURI + "> <" + DisplayVocabulary.GETINDIVIDUALS_FOR_CLASS + "> ?individualForClass . }\n" +
"OPTIONAL {<" + dataGetterURI + "> <" + DisplayVocabulary.RESTRICT_RESULTS_BY_INTERNAL + "> ?internalClass .} \n" +
"}";
return query;
}
public ObjectNode getExistingValuesJSON(String dataGetterURI, OntModel queryModel, ServletContext context) {
ObjectNode jObject = new ObjectMapper().createObjectNode();
jObject.put("dataGetterClass", classType);
//Update to include class type as variable
jObject.put(classTypeVarBase, classType);
//Get selected class group, if internal class, and classes selected from class group
getExistingClassGroupAndInternalClass(dataGetterURI, jObject, queryModel);
//Get all classes in the class group
((ProcessClassGroupDataGetterN3) this).getExistingClassesInClassGroup(context, dataGetterURI, jObject);
return jObject;
}
private void getExistingClassGroupAndInternalClass(String dataGetterURI, ObjectNode jObject, OntModel queryModel) {
String querystr = getExistingValuesInternalClass(dataGetterURI);
QueryExecution qe = null;
Literal internalClassLiteral = null;
try{
Query query = QueryFactory.create(querystr);
qe = QueryExecutionFactory.create(query, queryModel);
ResultSet results = qe.execSelect();
ArrayNode individualsForClasses = new ObjectMapper().createArrayNode();
String classGroupURI = null;
while( results.hasNext()){
QuerySolution qs = results.nextSolution();
if(classGroupURI == null) {
Resource classGroupResource = qs.getResource("classGroup");
classGroupURI = classGroupResource.getURI();
}
//individuals for classes - this may also be optional in case entire class group selected and internal class
if(qs.get("individualForClass") != null ) {
Resource individualForClassResource = qs.getResource("individualForClass");
individualsForClasses.add(individualForClassResource.getURI());
}
//Put both literals in existing literals
//If internal class value is present and we have not already saved it in a previous result iteration
if(qs.get("internalClass") != null && internalClassLiteral == null) {
internalClassLiteral= qs.getLiteral("internalClass");
}
}
jObject.put("classGroup", classGroupURI);
//this is a json array
jObject.set(individualClassVarNameBase, individualsForClasses);
//Internal class - if null then add false otherwise use the value
if(internalClassLiteral != null) {
jObject.put(internalClassVarNameBase, internalClassLiteral.getString());
} else {
jObject.put(internalClassVarNameBase, "false");
}
} catch(Exception ex) {
log.error("Exception occurred in retrieving existing values with query " + querystr, ex);
}
}
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.ServletContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.ResourceFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
//Returns the appropriate n3 for selection of classes from within class group
public class ProcessInternalClassDataGetterN3 extends ProcessIndividualsForClassesDataGetterN3 {
private static String classType = "java:edu.cornell.mannlib.vitro.webapp.utils.dataGetter.InternalClassesDataGetter";
private static String internalClassVarNameBase = "isInternal";
private Log log = LogFactory.getLog(ProcessInternalClassDataGetterN3.class);
public ProcessInternalClassDataGetterN3(){
super();
}
//Pass in variable that represents the counter
//Saving both type and class group here
//That can be included here if need be, but for now just adding the type alone
public List<String> retrieveN3Required(int counter) {
return super.retrieveN3Required(counter);
}
//returns n3 defining internal class
private List<String> addInternalClassN3(int counter) {
List<String> internalClassN3 = new ArrayList<String>();
String dataGetterVar = getDataGetterVar(counter);
internalClassN3.add(dataGetterVar + " <" + DisplayVocabulary.RESTRICT_RESULTS_BY_INTERNAL + "> " +
this.getN3VarName(internalClassVarNameBase, counter) + " .");
return internalClassN3;
}
public List<String> retrieveN3Optional(int counter) {
List<String> optionalN3 = new ArrayList<String>();
//If internal add that as well
optionalN3.addAll(this.addInternalClassN3(counter));
return optionalN3;
}
//These methods will return the literals and uris expected within the n3
//and the counter is used to ensure they are numbered correctly
public List<String> retrieveLiteralsOnForm(int counter) {
//no literals, just the class group URI
List<String> literalsOnForm = new ArrayList<String>();
literalsOnForm.add(getVarName(internalClassVarNameBase, counter));
return literalsOnForm;
}
//URIs on form are same as individuals for class group so no need to reimplement
//i.e. class groups and individuals selected within class group
public List<FieldVTwo> retrieveFields(int counter) {
List<FieldVTwo> fields = super.retrieveFields(counter);
fields.add(new FieldVTwo().setName(getVarName(internalClassVarNameBase, counter)));
return fields;
}
//These var names match the names of the elements within the json object returned with the info required for the data getter
public List<String> getLiteralVarNamesBase() {
return Arrays.asList(internalClassVarNameBase);
}
//get URI Var Names base is same as ProcessIndividualsForClassGroup: classGroup and individualClassVarNameBase
@Override
public String getClassType() {
return classType;
}
public void populateExistingValues(String dataGetterURI, int counter, OntModel queryModel) {
//First, put dataGetterURI within scope as well
//((ProcessDataGetterAbstract)this).populateExistingDataGetterURI(dataGetterURI, counter);
this.populateExistingDataGetterURI(dataGetterURI, counter);
//Put in type
this.populateExistingClassType(this.getClassType(), counter);
//Sparql queries for values to be executed
//And then placed in the correct place/literal or uri
String querystr = getExistingValuesInternalClass(dataGetterURI);
QueryExecution qe = null;
Literal internalClassLiteral = null;
try{
Query query = QueryFactory.create(querystr);
qe = QueryExecutionFactory.create(query, queryModel);
ResultSet results = qe.execSelect();
String classGroupURI = null;
List<String> individualsForClasses = new ArrayList<String>();
while( results.hasNext()){
QuerySolution qs = results.nextSolution();
//Class group
Resource classGroupResource = qs.getResource("classGroup");
String classGroupVarName = this.getVarName(classGroupVarBase, counter);
if(classGroupURI == null) {
//Put both literals in existing literals
existingUriValues.put(this.getVarName(classGroupVarBase, counter),
new ArrayList<String>(Arrays.asList(classGroupResource.getURI())));
}
//Individuals For classes
Resource individualForClassResource = qs.getResource("individualForClass");
individualsForClasses.add(individualForClassResource.getURI());
//If internal class value is present and we have not already saved it in a previous result iteration
if(qs.get("internalClass") != null && internalClassLiteral == null) {
internalClassLiteral= qs.getLiteral("internalClass");
existingLiteralValues.put(this.getVarName(internalClassVarNameBase, counter),
new ArrayList<Literal>(Arrays.asList(internalClassLiteral)));
}
}
//Put array of individuals for classes within
existingUriValues.put(this.getVarName(individualClassVarNameBase, counter),
new ArrayList<String>(individualsForClasses));
//Final check, in case no internal class flag was returned, set to false
if(internalClassLiteral == null) {
existingLiteralValues.put(this.getVarName(internalClassVarNameBase, counter),
new ArrayList<Literal>(
Arrays.asList(ResourceFactory.createPlainLiteral("false"))
));
}
} catch(Exception ex) {
log.error("Exception occurred in retrieving existing values with query " + querystr, ex);
}
}
//?dataGetter a FixedHTMLDataGetter ; display:saveToVar ?saveToVar; display:htmlValue ?htmlValue .
protected String getExistingValuesInternalClass(String dataGetterURI) {
String query = this.getSparqlPrefix() + " SELECT ?classGroup ?individualForClass ?internalClass WHERE {" +
"<" + dataGetterURI + "> <" + DisplayVocabulary.FOR_CLASSGROUP + "> ?classGroup . \n" +
"OPTIONAL {<" + dataGetterURI + "> <" + DisplayVocabulary.GETINDIVIDUALS_FOR_CLASS + "> ?individualForClass . }\n" +
"OPTIONAL {<" + dataGetterURI + "> <" + DisplayVocabulary.RESTRICT_RESULTS_BY_INTERNAL + "> ?internalClass .} \n" +
"}";
return query;
}
public ObjectNode getExistingValuesJSON(String dataGetterURI, OntModel queryModel, ServletContext context) {
ObjectNode jObject = new ObjectMapper().createObjectNode();
jObject.put("dataGetterClass", classType);
//Update to include class type as variable
jObject.put(classTypeVarBase, classType);
//Get selected class group, if internal class, and classes selected from class group
getExistingClassGroupAndInternalClass(dataGetterURI, jObject, queryModel);
//Get all classes in the class group
((ProcessClassGroupDataGetterN3) this).getExistingClassesInClassGroup(context, dataGetterURI, jObject);
return jObject;
}
private void getExistingClassGroupAndInternalClass(String dataGetterURI, ObjectNode jObject, OntModel queryModel) {
String querystr = getExistingValuesInternalClass(dataGetterURI);
QueryExecution qe = null;
Literal internalClassLiteral = null;
try{
Query query = QueryFactory.create(querystr);
qe = QueryExecutionFactory.create(query, queryModel);
ResultSet results = qe.execSelect();
ArrayNode individualsForClasses = new ObjectMapper().createArrayNode();
String classGroupURI = null;
while( results.hasNext()){
QuerySolution qs = results.nextSolution();
if(classGroupURI == null) {
Resource classGroupResource = qs.getResource("classGroup");
classGroupURI = classGroupResource.getURI();
}
//individuals for classes - this may also be optional in case entire class group selected and internal class
if(qs.get("individualForClass") != null ) {
Resource individualForClassResource = qs.getResource("individualForClass");
individualsForClasses.add(individualForClassResource.getURI());
}
//Put both literals in existing literals
//If internal class value is present and we have not already saved it in a previous result iteration
if(qs.get("internalClass") != null && internalClassLiteral == null) {
internalClassLiteral= qs.getLiteral("internalClass");
}
}
jObject.put("classGroup", classGroupURI);
//this is a json array
jObject.set(individualClassVarNameBase, individualsForClasses);
//Internal class - if null then add false otherwise use the value
if(internalClassLiteral != null) {
jObject.put(internalClassVarNameBase, internalClassLiteral.getString());
} else {
jObject.put(internalClassVarNameBase, "false");
}
} catch(Exception ex) {
log.error("Exception occurred in retrieving existing values with query " + querystr, ex);
}
}
}

View file

@ -38,7 +38,7 @@ public class CalculateParameters implements DocumentModifier, ContextModelsUser
private boolean shutdown = false;
private volatile Dataset dataset;
// public static int totalInd=1;
private static final String prefix = "prefix owl: <http://www.w3.org/2002/07/owl#> "
+ " prefix vitroDisplay: <http://vitro.mannlib.cornell.edu/ontologies/display/1.1#> "
+ " prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> "
@ -48,20 +48,20 @@ public class CalculateParameters implements DocumentModifier, ContextModelsUser
+ " prefix localNav: <http://vitro.mannlib.cornell.edu/ns/localnav#> "
+ " prefix obo: <http://purl.obolibrary.org/obo/> "
+ " prefix bibo: <http://purl.org/ontology/bibo/> ";
private static final String betaQuery = prefix + " SELECT count(distinct ?inLinks) " +
" WHERE { " +
" ?uri rdf:type owl:Thing . " +
" ?inLinks ?prop ?uri . " +
" } ";
private static final String totalCountQuery = prefix + " SELECT count(distinct ?ind) " +
" WHERE { " +
" ?ind rdf:type owl:Thing . " +
" } ";
private static Log log = LogFactory.getLog(CalculateParameters.class);
@Override
public void setContextModels(ContextModelAccess models) {
this.dataset = DatasetFactory.create(models.getOntModel());
@ -69,13 +69,13 @@ public class CalculateParameters implements DocumentModifier, ContextModelsUser
public float calculateBeta(String uri){
float beta=0;
int Conn=0;
int Conn=0;
Query query;
QuerySolutionMap initialBinding = new QuerySolutionMap();
QuerySolution soln = null;
Resource uriResource = ResourceFactory.createResource(uri);
initialBinding.add("uri", uriResource);
dataset.getLock().enterCriticalSection(Lock.READ);
dataset.getLock().enterCriticalSection(Lock.READ);
QueryExecution qexec=null;
try{
query = QueryFactory.create(betaQuery,Syntax.syntaxARQ);
@ -90,29 +90,29 @@ public class CalculateParameters implements DocumentModifier, ContextModelsUser
if( ! shutdown )
log.error(t,t);
}finally{
if( qexec != null )
qexec.close();
if( qexec != null )
qexec.close();
dataset.getLock().leaveCriticalSection();
}
beta = (float)Conn;
//beta *= 100;
beta += 1;
// sigmoid function to keep beta between 0 to 1;
beta = (float) (1 / ( 1 + Math.pow(Math.E,(-beta))));
if(beta > 1)
log.info("Beta higher than 1 : " + beta);
else if(beta <= 0)
log.info("Beta lower < = 0 : " + beta);
return beta;
return beta;
}
public String[] getAdjacentNodes(String uri){
List<String> queryList = new ArrayList<String>();
Set<String> adjacentNodes = new HashSet<String>();
Set<String> coauthorNames = new HashSet<String>();
@ -121,8 +121,8 @@ public class CalculateParameters implements DocumentModifier, ContextModelsUser
StringBuffer coauthorBuff = new StringBuffer();
adjacentNodesConcat.append("");
coauthorBuff.append("");
queryList.add(prefix +
queryList.add(prefix +
" SELECT ?adjobj (str(?adjobjLabel) as ?coauthor) " +
" WHERE { " +
" ?uri rdf:type <http://xmlns.com/foaf/0.1/Person> . " +
@ -167,24 +167,24 @@ public class CalculateParameters implements DocumentModifier, ContextModelsUser
" UNION " +
" { ?adjobj rdf:type <http://vivoweb.org/ontology/core#Location> . } ." +
"}");
Query query;
QuerySolution soln;
QuerySolutionMap initialBinding = new QuerySolutionMap();
Resource uriResource = ResourceFactory.createResource(uri);
initialBinding.add("uri", uriResource);
Iterator<String> queryItr = queryList.iterator();
dataset.getLock().enterCriticalSection(Lock.READ);
Resource adjacentIndividual = null;
RDFNode coauthor = null;
try{
while(queryItr.hasNext()){
/*if(!isPerson){
queryItr.next(); // we don't want first query to execute if the ind is not a person.
queryItr.next(); // we don't want first query to execute if the ind is not a person.
}*/
query = QueryFactory.create(queryItr.next(),Syntax.syntaxARQ);
QueryExecution qexec = QueryExecutionFactory.create(query,dataset,initialBinding);
@ -196,35 +196,35 @@ public class CalculateParameters implements DocumentModifier, ContextModelsUser
adjacentIndividual = (Resource)soln.get("adjobj");
if(adjacentIndividual!=null){
adjacentNodes.add(adjacentIndividual.getURI());
}
}
coauthor = soln.get("coauthor");
if(coauthor!=null){
coauthorNames.add(" co-authors " + coauthor.toString() + " co-authors ");
}
}
}
}catch(Exception e){
if( ! shutdown )
log.error("Error found in getAdjacentNodes method of SearchQueryHandler");
}finally{
qexec.close();
}
}
}
queryList = null;
queryList = null;
Iterator<String> itr = adjacentNodes.iterator();
while(itr.hasNext()){
adjacentNodesConcat.append(itr.next()).append(" ");
}
info[0] = adjacentNodesConcat.toString();
itr = coauthorNames.iterator();
while(itr.hasNext()){
coauthorBuff.append(itr.next());
}
info[1] = coauthorBuff.toString();
}
catch(Throwable t){
if( ! shutdown )
@ -237,24 +237,24 @@ public class CalculateParameters implements DocumentModifier, ContextModelsUser
}
return info;
}
@Override
public void modifyDocument(Individual individual, SearchInputDocument doc) {
// TODO Auto-generated method stub
// calculate beta value.
// calculate beta value.
log.debug("Parameter calculation starts..");
float beta = calculateBeta(individual.getURI());
doc.addField(VitroSearchTermNames.BETA, (Object) beta);
doc.setDocumentBoost(beta + doc.getDocumentBoost() );
doc.setDocumentBoost(beta + doc.getDocumentBoost() );
log.debug("Parameter calculation is done");
}
@Override
public void shutdown(){
shutdown=true;
}
@Override
public String toString() {
@ -267,11 +267,11 @@ class TotalInd implements Runnable{
private Dataset dataset;
private String totalCountQuery;
private static Log log = LogFactory.getLog(TotalInd.class);
public TotalInd(Dataset dataset,String totalCountQuery){
this.dataset = dataset;
this.totalCountQuery = totalCountQuery;
}
@Override
public void run(){
@ -280,13 +280,13 @@ class TotalInd implements Runnable{
QuerySolution soln = null;
dataset.getLock().enterCriticalSection(Lock.READ);
QueryExecution qexec = null;
try{
query = QueryFactory.create(totalCountQuery,Syntax.syntaxARQ);
qexec = QueryExecutionFactory.create(query,dataset);
ResultSet results = qexec.execSelect();
List<String> resultVars = results.getResultVars();
if(resultVars!=null && resultVars.size()!=0){
soln = results.next();
totalInd = Integer.parseInt(soln.getLiteral(resultVars.get(0)).getLexicalForm());
@ -296,10 +296,10 @@ class TotalInd implements Runnable{
}catch(Throwable t){
log.error(t,t);
}finally{
if( qexec != null )
if( qexec != null )
qexec.close();
dataset.getLock().leaveCriticalSection();
}
}
}

View file

@ -35,22 +35,22 @@ import edu.cornell.mannlib.vitro.webapp.utils.configuration.Validation;
* If an individual has context nodes then the search document for that
* individual should include the labels of the partners across those nodes. The
* labels will be added to the ALLTEXT and ALLTEXTUNSTEMMED fields.
*
*
* We must specify what property leads to a context node (incoming), and what
* property leads from a context node (outgoing). We may add restrictions to say
* that this only applies to individuals of certain types. We may also restrict
* the type of the applicable context nodes.
*
*
* An instance of this class acts as both a DocumentModifier and an
* IndexingUriFinder:
*
*
* As a DocumentModifier, it looks across approved context nodes to fetch the
* labels of the partners.
*
*
* As an IndexingUriFinder, it recognizes that this relationship can be changed
* by a change to a "label" statement, or to a "relates" property, and finds all
* partners as candidates for reindexing.
*
*
* <pre>
* Configuration:
* rdfs:label -- Optional. Appears in the timings and debug statements.
@ -85,7 +85,7 @@ public class LabelsAcrossContextNodes implements IndexingUriFinder,
/**
* URIs of the types of individuals to whom this instance applies.
*
*
* If this is not empty and an individual does not have any of these types,
* then skip that individual.
*/
@ -93,7 +93,7 @@ public class LabelsAcrossContextNodes implements IndexingUriFinder,
/**
* URIs of the types of acceptable context nodes.
*
*
* If this is not empty and a context node does not have any of these types,
* then skip that context node's label.
*/
@ -296,7 +296,7 @@ public class LabelsAcrossContextNodes implements IndexingUriFinder,
/**
* If this is a "label" statement, check to see if the subject has any
* acceptable partners across acceptable context nodes.
*
*
* If this is a statement that involves the specified incoming property on
* an acceptable context node, check to see if there are any acceptable
* partners on this node.

View file

@ -1,91 +1,91 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.cornell.mannlib.semservices.bo.Concept;
import edu.cornell.mannlib.semservices.bo.ConceptInfo;
import edu.cornell.mannlib.semservices.bo.SemanticServicesError;
import edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.utils.ConceptSearchService.ConceptSearchServiceUtils;
@WebServlet(name = "ConceptSearchService", urlPatterns = {"/conceptSearchService"} )
public class ConceptSearchServlet extends VitroHttpServlet {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(ConceptSearchServlet.class);
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
VitroRequest vreq = new VitroRequest(req);
try{
ServletContext ctx = vreq.getSession().getServletContext();
//Captures both concept list and any errors if they exist
ConceptInfo conceptInfo = new ConceptInfo();
conceptInfo.setSemanticServicesError(null);
//Json output should be written out
List<Concept> results = null;
try {
results = ConceptSearchServiceUtils.getSearchResults(ctx, vreq);
}
catch (Exception ex) {
SemanticServicesError semanticServicesError = new SemanticServicesError(
"Exception encountered ", ex.getMessage(), "fatal");
log.error("An error occurred retrieving search results", ex);
conceptInfo.setSemanticServicesError(semanticServicesError);
}
conceptInfo.setConceptList(results);
String json = renderJson(conceptInfo);
json = StringUtils.replaceChars(json, "\r\t\n", "");
PrintWriter writer = resp.getWriter();
resp.setContentType("application/json");
writer.write(json);
writer.close();
}catch(Exception ex){
log.warn(ex,ex);
}
}
protected String renderJson(ConceptInfo conceptInfo) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(conceptInfo);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
log.error("An error occurred in rendering conceptInfo as json ", e);
return null;
}
}
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.cornell.mannlib.semservices.bo.Concept;
import edu.cornell.mannlib.semservices.bo.ConceptInfo;
import edu.cornell.mannlib.semservices.bo.SemanticServicesError;
import edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.utils.ConceptSearchService.ConceptSearchServiceUtils;
@WebServlet(name = "ConceptSearchService", urlPatterns = {"/conceptSearchService"} )
public class ConceptSearchServlet extends VitroHttpServlet {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(ConceptSearchServlet.class);
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
VitroRequest vreq = new VitroRequest(req);
try{
ServletContext ctx = vreq.getSession().getServletContext();
//Captures both concept list and any errors if they exist
ConceptInfo conceptInfo = new ConceptInfo();
conceptInfo.setSemanticServicesError(null);
//Json output should be written out
List<Concept> results = null;
try {
results = ConceptSearchServiceUtils.getSearchResults(ctx, vreq);
}
catch (Exception ex) {
SemanticServicesError semanticServicesError = new SemanticServicesError(
"Exception encountered ", ex.getMessage(), "fatal");
log.error("An error occurred retrieving search results", ex);
conceptInfo.setSemanticServicesError(semanticServicesError);
}
conceptInfo.setConceptList(results);
String json = renderJson(conceptInfo);
json = StringUtils.replaceChars(json, "\r\t\n", "");
PrintWriter writer = resp.getWriter();
resp.setContentType("application/json");
writer.write(json);
writer.close();
}catch(Exception ex){
log.warn(ex,ex);
}
}
protected String renderJson(ConceptInfo conceptInfo) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(conceptInfo);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
log.error("An error occurred in rendering conceptInfo as json ", e);
return null;
}
}
}

View file

@ -1,101 +1,101 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.utils.ConceptSearchService;
import java.util.HashMap;
import java.util.List;
import javax.servlet.ServletContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.semservices.bo.Concept;
import edu.cornell.mannlib.semservices.service.ExternalConceptService;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
/**
* Utilities for search
*/
public class ConceptSearchServiceUtils {
private static final Log log = LogFactory.getLog(ConceptSearchServiceUtils.class);
//Get the appropriate search service class
//TODO: Change this so retrieved from the system instead using a query
private static final String UMLSVocabSource = "http://link.informatics.stonybrook.edu/umls";
private static final String AgrovocVocabSource = "http://aims.fao.org/aos/agrovoc/agrovocScheme";
private static final String GemetVocabSource = "http://www.eionet.europa.eu/gemet/gemetThesaurus";
private static final String LCSHVocabSource = "http://id.loc.gov/authorities/subjects";
//Get the class that corresponds to the appropriate search
public static String getConceptSearchServiceClassName(String searchServiceName) {
HashMap<String, String> map = getMapping();
if(map.containsKey(searchServiceName)) {
return map.get(searchServiceName);
}
return null;
}
//Get the URLS for the different services
//URL to label
public static HashMap<String, VocabSourceDescription> getVocabSources() {
HashMap<String, VocabSourceDescription> map = new HashMap<String, VocabSourceDescription>();
map.put(UMLSVocabSource, new VocabSourceDescription("UMLS", UMLSVocabSource, "http://www.nlm.nih.gov/research/umls/", "Unified Medical Language System"));
//Commenting out agrovoc for now until implementation is updated
map.put(AgrovocVocabSource, new VocabSourceDescription("AGROVOC", AgrovocVocabSource, "http://www.fao.org/agrovoc/", "Agricultural Vocabulary"));
map.put(GemetVocabSource, new VocabSourceDescription("GEMET", GemetVocabSource, "http://www.eionet.europa.eu/gemet", "GEneral Multilingual Environmental Thesaurus"));
map.put(LCSHVocabSource, new VocabSourceDescription("LCSH", LCSHVocabSource, "http://id.loc.gov/authorities/subjects/", "Library of Congress Subject Headings"));
return map;
}
//Get additional vocab source info
//Get the hashmap mapping service name to Service class
private static HashMap<String, String> getMapping() {
HashMap<String, String> map = new HashMap<String, String>();
map.put(UMLSVocabSource, "edu.cornell.mannlib.semservices.service.impl.UMLSService");
map.put(AgrovocVocabSource, "edu.cornell.mannlib.semservices.service.impl.AgrovocService");
map.put(GemetVocabSource, "edu.cornell.mannlib.semservices.service.impl.GemetService");
map.put(LCSHVocabSource, "edu.cornell.mannlib.semservices.service.impl.LCSHService");
return map;
}
public static List<Concept> getSearchResults(ServletContext context, VitroRequest vreq) throws Exception {
String searchServiceName = getSearchServiceUri(vreq);
String searchServiceClassName = getConceptSearchServiceClassName(searchServiceName);
ExternalConceptService conceptServiceClass = null;
Object object = null;
try {
Class classDefinition = Class.forName(searchServiceClassName);
object = classDefinition.newInstance();
conceptServiceClass = (ExternalConceptService) object;
} catch (InstantiationException | ClassNotFoundException | IllegalAccessException e) {
System.out.println(e);
}
if(conceptServiceClass == null){
log.error("could not find Concept Search Class for " + searchServiceName);
return null;
}
//Get search
String searchTerm = getSearchTerm(vreq);
List<Concept> conceptResults = conceptServiceClass.getConcepts(searchTerm);
return conceptResults;
}
private static String getSearchServiceUri(VitroRequest vreq) {
return vreq.getParameter("source");
}
private static String getSearchTerm(VitroRequest vreq) {
return vreq.getParameter("searchTerm");
}
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.utils.ConceptSearchService;
import java.util.HashMap;
import java.util.List;
import javax.servlet.ServletContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.semservices.bo.Concept;
import edu.cornell.mannlib.semservices.service.ExternalConceptService;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
/**
* Utilities for search
*/
public class ConceptSearchServiceUtils {
private static final Log log = LogFactory.getLog(ConceptSearchServiceUtils.class);
//Get the appropriate search service class
//TODO: Change this so retrieved from the system instead using a query
private static final String UMLSVocabSource = "http://link.informatics.stonybrook.edu/umls";
private static final String AgrovocVocabSource = "http://aims.fao.org/aos/agrovoc/agrovocScheme";
private static final String GemetVocabSource = "http://www.eionet.europa.eu/gemet/gemetThesaurus";
private static final String LCSHVocabSource = "http://id.loc.gov/authorities/subjects";
//Get the class that corresponds to the appropriate search
public static String getConceptSearchServiceClassName(String searchServiceName) {
HashMap<String, String> map = getMapping();
if(map.containsKey(searchServiceName)) {
return map.get(searchServiceName);
}
return null;
}
//Get the URLS for the different services
//URL to label
public static HashMap<String, VocabSourceDescription> getVocabSources() {
HashMap<String, VocabSourceDescription> map = new HashMap<String, VocabSourceDescription>();
map.put(UMLSVocabSource, new VocabSourceDescription("UMLS", UMLSVocabSource, "http://www.nlm.nih.gov/research/umls/", "Unified Medical Language System"));
//Commenting out agrovoc for now until implementation is updated
map.put(AgrovocVocabSource, new VocabSourceDescription("AGROVOC", AgrovocVocabSource, "http://www.fao.org/agrovoc/", "Agricultural Vocabulary"));
map.put(GemetVocabSource, new VocabSourceDescription("GEMET", GemetVocabSource, "http://www.eionet.europa.eu/gemet", "GEneral Multilingual Environmental Thesaurus"));
map.put(LCSHVocabSource, new VocabSourceDescription("LCSH", LCSHVocabSource, "http://id.loc.gov/authorities/subjects/", "Library of Congress Subject Headings"));
return map;
}
//Get additional vocab source info
//Get the hashmap mapping service name to Service class
private static HashMap<String, String> getMapping() {
HashMap<String, String> map = new HashMap<String, String>();
map.put(UMLSVocabSource, "edu.cornell.mannlib.semservices.service.impl.UMLSService");
map.put(AgrovocVocabSource, "edu.cornell.mannlib.semservices.service.impl.AgrovocService");
map.put(GemetVocabSource, "edu.cornell.mannlib.semservices.service.impl.GemetService");
map.put(LCSHVocabSource, "edu.cornell.mannlib.semservices.service.impl.LCSHService");
return map;
}
public static List<Concept> getSearchResults(ServletContext context, VitroRequest vreq) throws Exception {
String searchServiceName = getSearchServiceUri(vreq);
String searchServiceClassName = getConceptSearchServiceClassName(searchServiceName);
ExternalConceptService conceptServiceClass = null;
Object object = null;
try {
Class classDefinition = Class.forName(searchServiceClassName);
object = classDefinition.newInstance();
conceptServiceClass = (ExternalConceptService) object;
} catch (InstantiationException | ClassNotFoundException | IllegalAccessException e) {
System.out.println(e);
}
if(conceptServiceClass == null){
log.error("could not find Concept Search Class for " + searchServiceName);
return null;
}
//Get search
String searchTerm = getSearchTerm(vreq);
List<Concept> conceptResults = conceptServiceClass.getConcepts(searchTerm);
return conceptResults;
}
private static String getSearchServiceUri(VitroRequest vreq) {
return vreq.getParameter("source");
}
private static String getSearchTerm(VitroRequest vreq) {
return vreq.getParameter("searchTerm");
}
}

View file

@ -1,33 +1,33 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.utils.ConceptSearchService;
public class VocabSourceDescription {
private String url;
private String label;
private String schema;
private String description;
public VocabSourceDescription(String inputLabel, String inputSchema, String inputUrl, String inputDescription) {
url = inputUrl;
label = inputLabel;
schema = inputSchema;
description = inputDescription;
}
public String getUrl() {
return url;
}
public String getLabel() {
return label;
}
public String getSchema() {
return schema;
}
public String getDescription() {
return description;
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.utils.ConceptSearchService;
public class VocabSourceDescription {
private String url;
private String label;
private String schema;
private String description;
public VocabSourceDescription(String inputLabel, String inputSchema, String inputUrl, String inputDescription) {
url = inputUrl;
label = inputLabel;
schema = inputSchema;
description = inputDescription;
}
public String getUrl() {
return url;
}
public String getLabel() {
return label;
}
public String getSchema() {
return schema;
}
public String getDescription() {
return description;
}
}

View file

@ -1,135 +1,135 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.utils.dataGetter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.QuerySolutionMap;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.rdf.model.StmtIterator;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames;
/**
* This will pass these variables to the template:
* classGroupUri: uri of the classgroup associated with this page.
* vClassGroup: a data structure that is the classgroup associated with this page.
*/
public class InternalClassesDataGetter extends IndividualsForClassesDataGetter{
private static final Log log = LogFactory.getLog(InternalClassesDataGetter.class);
/**
* Constructor with display model and data getter URI that will be called by reflection.
*/
public InternalClassesDataGetter(VitroRequest vreq, Model displayModel, String dataGetterURI){
super(vreq, displayModel, dataGetterURI);
}
//Use different template name for internal class template
@Override
protected void setTemplateName() {
super.restrictClassesTemplateName = "internalClass";
}
//Retrieve classes and check whether or not page to be filtered by internal class only
@Override
protected Map<String, Object> getClassIntersectionsMap(Model displayModel) {
Map<String, Object> classesAndRestrictions = new HashMap<String, Object>();
QuerySolutionMap initialBindings = new QuerySolutionMap();
initialBindings.add("dataGetterUri", ResourceFactory.createResource(this.dataGetterURI));
List<String> classes = new ArrayList<String>();
displayModel.enterCriticalSection(false);
try{
Query individualsForClassesInternalQuery = QueryFactory.create(individualsForClassesInternalQueryString);
QueryExecution qexec = QueryExecutionFactory.create( individualsForClassesInternalQuery, displayModel , initialBindings);
try{
ResultSet resultSet = qexec.execSelect();
while(resultSet.hasNext()){
QuerySolution soln = resultSet.next();
String dg = DataGetterUtils.nodeToString(soln.get("dg"));
classes.add(DataGetterUtils.nodeToString(soln.get("class")));
//node to string will convert null to empty string
String isInternal = DataGetterUtils.nodeToString(soln.get("isInternal"));
if(!isInternal.isEmpty()) {
log.debug("Internal value is "+ isInternal);
//Retrieve and add internal class
classesAndRestrictions.put("isInternal", isInternal);
}
}
if( classes.size() == 0 ){
log.debug("No classes defined in display model for "+ this.dataGetterURI);
return null;
}
classesAndRestrictions.put("classes", classes);
return classesAndRestrictions;
}finally{
qexec.close();
}
}finally{
displayModel.leaveCriticalSection();
}
}
//Retrieve current internal class uri to restrict by
@Override
protected List<String> retrieveRestrictClasses(
ServletContext context, Map<String, Object> classIntersectionsMap) {
List<String> restrictClasses = new ArrayList<String>();
String internalClass = (String) classIntersectionsMap.get("isInternal");
//if internal class restriction specified and is true
if(internalClass != null && internalClass.equals("true")) {
//Get internal class
Model mainModel = ModelAccess.on(context).getOntModel(ModelNames.TBOX_ASSERTIONS);
StmtIterator internalIt = mainModel.listStatements(null, ResourceFactory.createProperty(VitroVocabulary.IS_INTERNAL_CLASSANNOT), (RDFNode) null);
//Checks for just one statement
if(internalIt.hasNext()){
Statement s = internalIt.nextStatement();
//The class IS an internal class so the subject is what we're looking for
String internalClassUri = s.getSubject().getURI();
log.debug("Found internal class uri " + internalClassUri);
restrictClasses.add(internalClassUri);
}
}
return restrictClasses;
}
@Override
public String getType(){
return DataGetterUtils.generateDataGetterTypeURI(InternalClassesDataGetter.class.getName());
}
static final protected String individualsForClassesInternalQueryString =
DataGetterUtils.prefixes + "\n" +
"SELECT?class ?isInternal WHERE {\n" +
" ?dataGetterUri <" + DisplayVocabulary.GETINDIVIDUALS_FOR_CLASS + "> ?class . \n" +
" OPTIONAL { ?dataGetterUri <"+ DisplayVocabulary.RESTRICT_RESULTS_BY_INTERNAL + "> ?isInternal } .\n" +
"} \n" ;
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.utils.dataGetter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.QuerySolutionMap;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.rdf.model.StmtIterator;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames;
/**
* This will pass these variables to the template:
* classGroupUri: uri of the classgroup associated with this page.
* vClassGroup: a data structure that is the classgroup associated with this page.
*/
public class InternalClassesDataGetter extends IndividualsForClassesDataGetter{
private static final Log log = LogFactory.getLog(InternalClassesDataGetter.class);
/**
* Constructor with display model and data getter URI that will be called by reflection.
*/
public InternalClassesDataGetter(VitroRequest vreq, Model displayModel, String dataGetterURI){
super(vreq, displayModel, dataGetterURI);
}
//Use different template name for internal class template
@Override
protected void setTemplateName() {
super.restrictClassesTemplateName = "internalClass";
}
//Retrieve classes and check whether or not page to be filtered by internal class only
@Override
protected Map<String, Object> getClassIntersectionsMap(Model displayModel) {
Map<String, Object> classesAndRestrictions = new HashMap<String, Object>();
QuerySolutionMap initialBindings = new QuerySolutionMap();
initialBindings.add("dataGetterUri", ResourceFactory.createResource(this.dataGetterURI));
List<String> classes = new ArrayList<String>();
displayModel.enterCriticalSection(false);
try{
Query individualsForClassesInternalQuery = QueryFactory.create(individualsForClassesInternalQueryString);
QueryExecution qexec = QueryExecutionFactory.create( individualsForClassesInternalQuery, displayModel , initialBindings);
try{
ResultSet resultSet = qexec.execSelect();
while(resultSet.hasNext()){
QuerySolution soln = resultSet.next();
String dg = DataGetterUtils.nodeToString(soln.get("dg"));
classes.add(DataGetterUtils.nodeToString(soln.get("class")));
//node to string will convert null to empty string
String isInternal = DataGetterUtils.nodeToString(soln.get("isInternal"));
if(!isInternal.isEmpty()) {
log.debug("Internal value is "+ isInternal);
//Retrieve and add internal class
classesAndRestrictions.put("isInternal", isInternal);
}
}
if( classes.size() == 0 ){
log.debug("No classes defined in display model for "+ this.dataGetterURI);
return null;
}
classesAndRestrictions.put("classes", classes);
return classesAndRestrictions;
}finally{
qexec.close();
}
}finally{
displayModel.leaveCriticalSection();
}
}
//Retrieve current internal class uri to restrict by
@Override
protected List<String> retrieveRestrictClasses(
ServletContext context, Map<String, Object> classIntersectionsMap) {
List<String> restrictClasses = new ArrayList<String>();
String internalClass = (String) classIntersectionsMap.get("isInternal");
//if internal class restriction specified and is true
if(internalClass != null && internalClass.equals("true")) {
//Get internal class
Model mainModel = ModelAccess.on(context).getOntModel(ModelNames.TBOX_ASSERTIONS);
StmtIterator internalIt = mainModel.listStatements(null, ResourceFactory.createProperty(VitroVocabulary.IS_INTERNAL_CLASSANNOT), (RDFNode) null);
//Checks for just one statement
if(internalIt.hasNext()){
Statement s = internalIt.nextStatement();
//The class IS an internal class so the subject is what we're looking for
String internalClassUri = s.getSubject().getURI();
log.debug("Found internal class uri " + internalClassUri);
restrictClasses.add(internalClassUri);
}
}
return restrictClasses;
}
@Override
public String getType(){
return DataGetterUtils.generateDataGetterTypeURI(InternalClassesDataGetter.class.getName());
}
static final protected String individualsForClassesInternalQueryString =
DataGetterUtils.prefixes + "\n" +
"SELECT?class ?isInternal WHERE {\n" +
" ?dataGetterUri <" + DisplayVocabulary.GETINDIVIDUALS_FOR_CLASS + "> ?class . \n" +
" OPTIONAL { ?dataGetterUri <"+ DisplayVocabulary.RESTRICT_RESULTS_BY_INTERNAL + "> ?isInternal } .\n" +
"} \n" ;
}

View file

@ -1,82 +1,82 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.utils.menuManagement;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
import edu.cornell.mannlib.vitro.webapp.utils.dataGetter.DataGetterUtils;
import edu.cornell.mannlib.vitro.webapp.utils.dataGetter.InternalClassesDataGetter;
/*
* Handle processing of data retrieved from IndividualsForClasses data getter to return to form template
* and handle processing of form submission to create the appropriate individuals for classes data getter
*/
public class ProcessInternalClasses extends ProcessIndividualsForClasses {
private static final Log log = LogFactory.getLog(ProcessInternalClasses.class);
/**Retrieve and populate**/
//Based on institutional internal page and not general individualsForClasses
@Override
protected void populateRestrictedClasses(Map<String, Object> pageData, Map<String, Object> templateData) {
//for internal page, restrict results by internal is true or false, otherwise get
//actual restriction classes?
//Get internal class
String internalClassUris = (String) pageData.get("internalClass");
if(internalClassUris != null && !internalClassUris.isEmpty()) {
templateData.put("isInternal", "true");
}
}
/**Process submission**/
//Check and see if we should use this process
//Use this if either internal class is selected or all classes have been selected
public boolean useProcessor(VitroRequest vreq) {
return(internalClassSelected(vreq) || !allClassesSelected(vreq));
}
public Model processSubmission(VitroRequest vreq, Resource dataGetterResource) {
String dataGetterTypeUri = DataGetterUtils.generateDataGetterTypeURI(InternalClassesDataGetter.class.getName());
String[] selectedClasses = vreq.getParameterValues("classInClassGroup");
Model dgModel = ModelFactory.createDefaultModel();
dgModel.add(dgModel.createStatement(dataGetterResource,
RDF.type,
ResourceFactory.createResource(dataGetterTypeUri)));
for(String classUri: selectedClasses) {
dgModel.add(dgModel.createStatement(
dataGetterResource,
ResourceFactory.createProperty(DisplayVocabulary.GETINDIVIDUALS_FOR_CLASS),
ResourceFactory.createResource(classUri)));
}
//Also check if internal class checked
if(internalClassSelected(vreq)) {
dgModel.add(dgModel.createStatement(
dataGetterResource,
ResourceFactory.createProperty(DisplayVocabulary.RESTRICT_RESULTS_BY_INTERNAL),
dgModel.createLiteral("true")));
}
return dgModel;
}
private boolean allClassesSelected(VitroRequest vreq) {
String allClasses = vreq.getParameter("allSelected");
return (allClasses != null && !allClasses.isEmpty());
}
private boolean internalClassSelected(VitroRequest vreq) {
String internalClass = vreq.getParameter("display-internalClass");
return (internalClass != null && !internalClass.isEmpty());
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.utils.menuManagement;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
import edu.cornell.mannlib.vitro.webapp.utils.dataGetter.DataGetterUtils;
import edu.cornell.mannlib.vitro.webapp.utils.dataGetter.InternalClassesDataGetter;
/*
* Handle processing of data retrieved from IndividualsForClasses data getter to return to form template
* and handle processing of form submission to create the appropriate individuals for classes data getter
*/
public class ProcessInternalClasses extends ProcessIndividualsForClasses {
private static final Log log = LogFactory.getLog(ProcessInternalClasses.class);
/**Retrieve and populate**/
//Based on institutional internal page and not general individualsForClasses
@Override
protected void populateRestrictedClasses(Map<String, Object> pageData, Map<String, Object> templateData) {
//for internal page, restrict results by internal is true or false, otherwise get
//actual restriction classes?
//Get internal class
String internalClassUris = (String) pageData.get("internalClass");
if(internalClassUris != null && !internalClassUris.isEmpty()) {
templateData.put("isInternal", "true");
}
}
/**Process submission**/
//Check and see if we should use this process
//Use this if either internal class is selected or all classes have been selected
public boolean useProcessor(VitroRequest vreq) {
return(internalClassSelected(vreq) || !allClassesSelected(vreq));
}
public Model processSubmission(VitroRequest vreq, Resource dataGetterResource) {
String dataGetterTypeUri = DataGetterUtils.generateDataGetterTypeURI(InternalClassesDataGetter.class.getName());
String[] selectedClasses = vreq.getParameterValues("classInClassGroup");
Model dgModel = ModelFactory.createDefaultModel();
dgModel.add(dgModel.createStatement(dataGetterResource,
RDF.type,
ResourceFactory.createResource(dataGetterTypeUri)));
for(String classUri: selectedClasses) {
dgModel.add(dgModel.createStatement(
dataGetterResource,
ResourceFactory.createProperty(DisplayVocabulary.GETINDIVIDUALS_FOR_CLASS),
ResourceFactory.createResource(classUri)));
}
//Also check if internal class checked
if(internalClassSelected(vreq)) {
dgModel.add(dgModel.createStatement(
dataGetterResource,
ResourceFactory.createProperty(DisplayVocabulary.RESTRICT_RESULTS_BY_INTERNAL),
dgModel.createLiteral("true")));
}
return dgModel;
}
private boolean allClassesSelected(VitroRequest vreq) {
String allClasses = vreq.getParameter("allSelected");
return (allClasses != null && !allClasses.isEmpty());
}
private boolean internalClassSelected(VitroRequest vreq) {
String internalClass = vreq.getParameter("display-internalClass");
return (internalClass != null && !internalClass.isEmpty());
}
}

View file

@ -1,60 +1,60 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.utils.menuManagement;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.TBOX_ASSERTIONS;
import java.util.Map;
import javax.servlet.ServletContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.rdf.model.StmtIterator;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
/*
* This class includes methods that help in selecting a data getter based on
* parameters, and VIVO will have its own version or extend this
*/
public class VIVOMenuManagementDataUtils implements MenuManagementDataUtils.IMenuManagementDataUtils {
private static final Log log = LogFactory.getLog(VIVOMenuManagementDataUtils.class);
//Data that is to be returned to template that does not involve data getters
//e.g. what are the current class groups, etc.
public void includeRequiredSystemData(ServletContext context, Map<String, Object> templateData) {
checkInstitutionalInternalClass(context, templateData);
}
//Check whether any classes exist with internal class restrictions
private void checkInstitutionalInternalClass(ServletContext context, Map<String, Object> templateData) {
//TODO: replace with more generic ModelContext retrieval method
String internalClass = retrieveInternalClass(context);
if(internalClass != null) {
templateData.put("internalClass", internalClass);
templateData.put("internalClassUri", internalClass);
} else {
//need to initialize to empty string anyway
templateData.put("internalClassUri", "");
}
}
private String retrieveInternalClass(ServletContext context) {
OntModel mainModel = ModelAccess.on(context).getOntModel(TBOX_ASSERTIONS);
StmtIterator internalIt = mainModel.listStatements(null, ResourceFactory.createProperty(VitroVocabulary.IS_INTERNAL_CLASSANNOT), (RDFNode) null);
if(internalIt.hasNext()) {
String internalClass = internalIt.nextStatement().getSubject().getURI();
return internalClass;
}
return null;
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.utils.menuManagement;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.TBOX_ASSERTIONS;
import java.util.Map;
import javax.servlet.ServletContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.rdf.model.StmtIterator;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
/*
* This class includes methods that help in selecting a data getter based on
* parameters, and VIVO will have its own version or extend this
*/
public class VIVOMenuManagementDataUtils implements MenuManagementDataUtils.IMenuManagementDataUtils {
private static final Log log = LogFactory.getLog(VIVOMenuManagementDataUtils.class);
//Data that is to be returned to template that does not involve data getters
//e.g. what are the current class groups, etc.
public void includeRequiredSystemData(ServletContext context, Map<String, Object> templateData) {
checkInstitutionalInternalClass(context, templateData);
}
//Check whether any classes exist with internal class restrictions
private void checkInstitutionalInternalClass(ServletContext context, Map<String, Object> templateData) {
//TODO: replace with more generic ModelContext retrieval method
String internalClass = retrieveInternalClass(context);
if(internalClass != null) {
templateData.put("internalClass", internalClass);
templateData.put("internalClassUri", internalClass);
} else {
//need to initialize to empty string anyway
templateData.put("internalClassUri", "");
}
}
private String retrieveInternalClass(ServletContext context) {
OntModel mainModel = ModelAccess.on(context).getOntModel(TBOX_ASSERTIONS);
StmtIterator internalIt = mainModel.listStatements(null, ResourceFactory.createProperty(VitroVocabulary.IS_INTERNAL_CLASSANNOT), (RDFNode) null);
if(internalIt.hasNext()) {
String internalClass = internalIt.nextStatement().getSubject().getURI();
return internalClass;
}
return null;
}
}

View file

@ -1,332 +1,332 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.visualization.coauthorship;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder.ParamMap;
import edu.cornell.mannlib.vitro.webapp.controller.visualization.VisualizationFrameworkConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.collaborationutils.CollaborationComparator;
import edu.cornell.mannlib.vitro.webapp.visualization.collaborationutils.CollaborationData;
import edu.cornell.mannlib.vitro.webapp.visualization.collaborationutils.CollaboratorComparator;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Collaboration;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Collaborator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class CoAuthorshipGraphMLWriter {
private StringBuilder coAuthorshipGraphMLContent;
private final String GRAPHML_NS = "http://graphml.graphdrawing.org/xmlns";
public CoAuthorshipGraphMLWriter(CollaborationData visVOContainer) {
coAuthorshipGraphMLContent = createCoAuthorshipGraphMLContent(visVOContainer);
}
private StringBuilder createCoAuthorshipGraphMLContent(CollaborationData coAuthorshipData) {
StringBuilder graphMLContent = new StringBuilder();
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
doc.setXmlVersion("1.0");
Element rootElement = doc.createElementNS(GRAPHML_NS, "graphml");
doc.appendChild(rootElement);
/*
* We are side-effecting "graphMLContent" object in this method since creating
* another String object to hold key definition data will be redundant & will
* not serve the purpose.
* */
generateKeyDefinitionContent(coAuthorshipData, rootElement);
/*
* Used to generate graph content. It will contain both the nodes & edge information.
* We are side-effecting "graphMLContent".
* */
generateGraphContent(coAuthorshipData, rootElement);
DOMSource source = new DOMSource(doc);
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
graphMLContent.append(writer.toString());
} catch (ParserConfigurationException | TransformerException e) {
throw new IllegalStateException("XML error generating GraphML", e);
}
return graphMLContent;
}
public StringBuilder getCoAuthorshipGraphMLContent() {
return coAuthorshipGraphMLContent;
}
private void generateGraphContent(CollaborationData coAuthorshipData, Element rootElement) {
Document doc = rootElement.getOwnerDocument();
Element graph = doc.createElementNS(GRAPHML_NS, "graph");
graph.setAttribute("edgedefault", "undirected");
rootElement.appendChild(graph);
if (coAuthorshipData.getCollaborators() != null && coAuthorshipData.getCollaborators().size() > 0) {
generateNodeSectionContent(coAuthorshipData, graph);
}
if (coAuthorshipData.getCollaborations() != null && coAuthorshipData.getCollaborations().size() > 0) {
generateEdgeSectionContent(coAuthorshipData, graph);
}
}
private void generateEdgeSectionContent(CollaborationData coAuthorshipData, Element graphElement) {
Document doc = graphElement.getOwnerDocument();
graphElement.appendChild(doc.createComment("edges"));
Set<Collaboration> edges = coAuthorshipData.getCollaborations();
List<Collaboration> orderedEdges = new ArrayList<Collaboration>(edges);
orderedEdges.sort(new CollaborationComparator());
for (Collaboration currentEdge : orderedEdges) {
/*
* This method actually creates the XML code for a single Collaboration.
* "graphMLContent" is being side-effected.
* */
getEdgeContent(graphElement, currentEdge);
}
}
private void getEdgeContent(Element graphElement, Collaboration currentEdge) {
Document doc = graphElement.getOwnerDocument();
Element edge = doc.createElementNS(GRAPHML_NS, "edge");
edge.setAttribute("id", String.valueOf(currentEdge.getCollaborationID()));
edge.setAttribute("source", String.valueOf(currentEdge.getSourceCollaborator().getCollaboratorID()));
edge.setAttribute("target", String.valueOf(currentEdge.getTargetCollaborator().getCollaboratorID()));
graphElement.appendChild(edge);
Element collaborator1 = doc.createElementNS(GRAPHML_NS, "data");
collaborator1.setAttribute("key", "collaborator1");
collaborator1.setTextContent(currentEdge.getSourceCollaborator().getCollaboratorName());
edge.appendChild(collaborator1);
Element collaborator2 = doc.createElementNS(GRAPHML_NS, "data");
collaborator2.setAttribute("key", "collaborator2");
collaborator2.setTextContent(currentEdge.getTargetCollaborator().getCollaboratorName());
edge.appendChild(collaborator2);
Element works = doc.createElementNS(GRAPHML_NS, "data");
works.setAttribute("key", "number_of_coauthored_works");
works.setTextContent(String.valueOf(currentEdge.getNumOfCollaborations()));
edge.appendChild(works);
if (currentEdge.getEarliestCollaborationYearCount() != null) {
/*
* There is no clean way of getting the map contents in java even though
* we are sure to have only one entry on the map. So using the for loop.
* */
for (Map.Entry<String, Integer> publicationInfo : currentEdge.getEarliestCollaborationYearCount().entrySet()) {
Element earliest = doc.createElementNS(GRAPHML_NS, "data");
earliest.setAttribute("key", "earliest_collaboration");
earliest.setTextContent(publicationInfo.getKey());
edge.appendChild(earliest);
Element earliestCount = doc.createElementNS(GRAPHML_NS, "data");
earliestCount.setAttribute("key", "num_earliest_collaboration");
earliestCount.setTextContent(publicationInfo.getValue().toString());
edge.appendChild(earliestCount);
}
}
if (currentEdge.getLatestCollaborationYearCount() != null) {
for (Map.Entry<String, Integer> publicationInfo : currentEdge.getLatestCollaborationYearCount().entrySet()) {
Element latest = doc.createElementNS(GRAPHML_NS, "data");
latest.setAttribute("key", "latest_collaboration");
latest.setTextContent(publicationInfo.getKey());
edge.appendChild(latest);
Element latestCount = doc.createElementNS(GRAPHML_NS, "data");
latestCount.setAttribute("key", "num_latest_collaboration");
latestCount.setTextContent(publicationInfo.getValue().toString());
edge.appendChild(latestCount);
}
}
if (currentEdge.getUnknownCollaborationYearCount() != null) {
Element unknown = doc.createElementNS(GRAPHML_NS, "data");
unknown.setAttribute("key", "num_unknown_collaboration");
unknown.setTextContent(String.valueOf(currentEdge.getUnknownCollaborationYearCount()));
edge.appendChild(unknown);
}
}
private void generateNodeSectionContent(CollaborationData coAuthorshipData, Element graphElement) {
Document doc = graphElement.getOwnerDocument();
graphElement.appendChild(doc.createComment("nodes"));
Collaborator egoNode = coAuthorshipData.getEgoCollaborator();
Set<Collaborator> authorNodes = coAuthorshipData.getCollaborators();
/*
* This method actually creates the XML code for a single Collaborator. "graphMLContent"
* is being side-effected. The egoNode is added first because this is the "requirement"
* of the co-author vis. Ego should always come first.
*
* */
getNodeContent(graphElement, egoNode);
List<Collaborator> orderedAuthorNodes = new ArrayList<Collaborator>(authorNodes);
orderedAuthorNodes.remove(egoNode);
orderedAuthorNodes.sort(new CollaboratorComparator());
for (Collaborator currNode : orderedAuthorNodes) {
/*
* We have already printed the Ego Collaborator info.
* */
if (currNode != egoNode) {
getNodeContent(graphElement, currNode);
}
}
}
private void getNodeContent(Element graphElement, Collaborator collaborator) {
Document doc = graphElement.getOwnerDocument();
ParamMap individualProfileURLParams =
new ParamMap(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, collaborator.getCollaboratorURI());
String profileURL = UrlBuilder.getUrl(VisualizationFrameworkConstants.INDIVIDUAL_URL_PREFIX, individualProfileURLParams);
Element node = doc.createElementNS(GRAPHML_NS, "node");
node.setAttribute("id", String.valueOf(collaborator.getCollaboratorID()));
graphElement.appendChild(node);
Element url = doc.createElementNS(GRAPHML_NS, "data");
url.setAttribute("key", "url");
url.setTextContent(collaborator.getCollaboratorURI());
node.appendChild(url);
Element label = doc.createElementNS(GRAPHML_NS, "data");
label.setAttribute("key", "label");
label.setTextContent(collaborator.getCollaboratorName());
node.appendChild(label);
if (profileURL != null) {
Element profile = doc.createElementNS(GRAPHML_NS, "data");
profile.setAttribute("key", "profile_url");
profile.setTextContent(profileURL);
node.appendChild(profile);
}
Element works = doc.createElementNS(GRAPHML_NS, "data");
works.setAttribute("key", "number_of_authored_works");
works.setTextContent(String.valueOf(collaborator.getNumOfActivities()));
node.appendChild(works);
if (collaborator.getEarliestActivityYearCount() != null) {
/*
* There is no clean way of getting the map contents in java even though
* we are sure to have only one entry on the map. So using the for loop.
* I am feeling dirty just about now.
* */
for (Map.Entry<String, Integer> publicationInfo : collaborator.getEarliestActivityYearCount().entrySet()) {
Element earliest = doc.createElementNS(GRAPHML_NS, "data");
earliest.setAttribute("key", "earliest_publication");
earliest.setTextContent(publicationInfo.getKey());
node.appendChild(earliest);
Element earliestCount = doc.createElementNS(GRAPHML_NS, "data");
earliestCount.setAttribute("key", "num_earliest_publication");
earliestCount.setTextContent(publicationInfo.getValue().toString());
node.appendChild(earliestCount);
}
}
if (collaborator.getLatestActivityYearCount() != null) {
for (Map.Entry<String, Integer> publicationInfo : collaborator.getLatestActivityYearCount().entrySet()) {
Element latest = doc.createElementNS(GRAPHML_NS, "data");
latest.setAttribute("key", "latest_publication");
latest.setTextContent(publicationInfo.getKey());
node.appendChild(latest);
Element latestCount = doc.createElementNS(GRAPHML_NS, "data");
latestCount.setAttribute("key", "num_latest_publication");
latestCount.setTextContent(publicationInfo.getValue().toString());
node.appendChild(latestCount);
}
}
if (collaborator.getUnknownActivityYearCount() != null) {
Element unknown = doc.createElementNS(GRAPHML_NS, "data");
unknown.setAttribute("key", "num_unknown_publication");
unknown.setTextContent(String.valueOf(collaborator.getUnknownActivityYearCount()));
node.appendChild(unknown);
}
}
private void generateKeyDefinitionContent(CollaborationData visVOContainer, Element rootElement) {
/*
* Generate the key definition content for node.
* */
getKeyDefinitionFromSchema(visVOContainer.getNodeSchema(), rootElement);
/*
* Generate the key definition content for edge.
* */
getKeyDefinitionFromSchema(visVOContainer.getEdgeSchema(), rootElement);
}
private void getKeyDefinitionFromSchema(Set<Map<String, String>> schema, Element rootElement) {
Document doc = rootElement.getOwnerDocument();
for (Map<String, String> currentNodeSchemaAttribute : schema) {
Element key = doc.createElementNS(GRAPHML_NS, "key");
for (Map.Entry<String, String> currentAttributeKey : currentNodeSchemaAttribute.entrySet()) {
key.setAttribute(currentAttributeKey.getKey(), currentAttributeKey.getValue());
}
if (currentNodeSchemaAttribute.containsKey("default")) {
Element def = doc.createElementNS(GRAPHML_NS, "default");
def.setTextContent(currentNodeSchemaAttribute.get("default"));
key.appendChild(def);
}
rootElement.appendChild(key);
}
}
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.visualization.coauthorship;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder.ParamMap;
import edu.cornell.mannlib.vitro.webapp.controller.visualization.VisualizationFrameworkConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.collaborationutils.CollaborationComparator;
import edu.cornell.mannlib.vitro.webapp.visualization.collaborationutils.CollaborationData;
import edu.cornell.mannlib.vitro.webapp.visualization.collaborationutils.CollaboratorComparator;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Collaboration;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Collaborator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class CoAuthorshipGraphMLWriter {
private StringBuilder coAuthorshipGraphMLContent;
private final String GRAPHML_NS = "http://graphml.graphdrawing.org/xmlns";
public CoAuthorshipGraphMLWriter(CollaborationData visVOContainer) {
coAuthorshipGraphMLContent = createCoAuthorshipGraphMLContent(visVOContainer);
}
private StringBuilder createCoAuthorshipGraphMLContent(CollaborationData coAuthorshipData) {
StringBuilder graphMLContent = new StringBuilder();
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
doc.setXmlVersion("1.0");
Element rootElement = doc.createElementNS(GRAPHML_NS, "graphml");
doc.appendChild(rootElement);
/*
* We are side-effecting "graphMLContent" object in this method since creating
* another String object to hold key definition data will be redundant & will
* not serve the purpose.
* */
generateKeyDefinitionContent(coAuthorshipData, rootElement);
/*
* Used to generate graph content. It will contain both the nodes & edge information.
* We are side-effecting "graphMLContent".
* */
generateGraphContent(coAuthorshipData, rootElement);
DOMSource source = new DOMSource(doc);
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
graphMLContent.append(writer.toString());
} catch (ParserConfigurationException | TransformerException e) {
throw new IllegalStateException("XML error generating GraphML", e);
}
return graphMLContent;
}
public StringBuilder getCoAuthorshipGraphMLContent() {
return coAuthorshipGraphMLContent;
}
private void generateGraphContent(CollaborationData coAuthorshipData, Element rootElement) {
Document doc = rootElement.getOwnerDocument();
Element graph = doc.createElementNS(GRAPHML_NS, "graph");
graph.setAttribute("edgedefault", "undirected");
rootElement.appendChild(graph);
if (coAuthorshipData.getCollaborators() != null && coAuthorshipData.getCollaborators().size() > 0) {
generateNodeSectionContent(coAuthorshipData, graph);
}
if (coAuthorshipData.getCollaborations() != null && coAuthorshipData.getCollaborations().size() > 0) {
generateEdgeSectionContent(coAuthorshipData, graph);
}
}
private void generateEdgeSectionContent(CollaborationData coAuthorshipData, Element graphElement) {
Document doc = graphElement.getOwnerDocument();
graphElement.appendChild(doc.createComment("edges"));
Set<Collaboration> edges = coAuthorshipData.getCollaborations();
List<Collaboration> orderedEdges = new ArrayList<Collaboration>(edges);
orderedEdges.sort(new CollaborationComparator());
for (Collaboration currentEdge : orderedEdges) {
/*
* This method actually creates the XML code for a single Collaboration.
* "graphMLContent" is being side-effected.
* */
getEdgeContent(graphElement, currentEdge);
}
}
private void getEdgeContent(Element graphElement, Collaboration currentEdge) {
Document doc = graphElement.getOwnerDocument();
Element edge = doc.createElementNS(GRAPHML_NS, "edge");
edge.setAttribute("id", String.valueOf(currentEdge.getCollaborationID()));
edge.setAttribute("source", String.valueOf(currentEdge.getSourceCollaborator().getCollaboratorID()));
edge.setAttribute("target", String.valueOf(currentEdge.getTargetCollaborator().getCollaboratorID()));
graphElement.appendChild(edge);
Element collaborator1 = doc.createElementNS(GRAPHML_NS, "data");
collaborator1.setAttribute("key", "collaborator1");
collaborator1.setTextContent(currentEdge.getSourceCollaborator().getCollaboratorName());
edge.appendChild(collaborator1);
Element collaborator2 = doc.createElementNS(GRAPHML_NS, "data");
collaborator2.setAttribute("key", "collaborator2");
collaborator2.setTextContent(currentEdge.getTargetCollaborator().getCollaboratorName());
edge.appendChild(collaborator2);
Element works = doc.createElementNS(GRAPHML_NS, "data");
works.setAttribute("key", "number_of_coauthored_works");
works.setTextContent(String.valueOf(currentEdge.getNumOfCollaborations()));
edge.appendChild(works);
if (currentEdge.getEarliestCollaborationYearCount() != null) {
/*
* There is no clean way of getting the map contents in java even though
* we are sure to have only one entry on the map. So using the for loop.
* */
for (Map.Entry<String, Integer> publicationInfo : currentEdge.getEarliestCollaborationYearCount().entrySet()) {
Element earliest = doc.createElementNS(GRAPHML_NS, "data");
earliest.setAttribute("key", "earliest_collaboration");
earliest.setTextContent(publicationInfo.getKey());
edge.appendChild(earliest);
Element earliestCount = doc.createElementNS(GRAPHML_NS, "data");
earliestCount.setAttribute("key", "num_earliest_collaboration");
earliestCount.setTextContent(publicationInfo.getValue().toString());
edge.appendChild(earliestCount);
}
}
if (currentEdge.getLatestCollaborationYearCount() != null) {
for (Map.Entry<String, Integer> publicationInfo : currentEdge.getLatestCollaborationYearCount().entrySet()) {
Element latest = doc.createElementNS(GRAPHML_NS, "data");
latest.setAttribute("key", "latest_collaboration");
latest.setTextContent(publicationInfo.getKey());
edge.appendChild(latest);
Element latestCount = doc.createElementNS(GRAPHML_NS, "data");
latestCount.setAttribute("key", "num_latest_collaboration");
latestCount.setTextContent(publicationInfo.getValue().toString());
edge.appendChild(latestCount);
}
}
if (currentEdge.getUnknownCollaborationYearCount() != null) {
Element unknown = doc.createElementNS(GRAPHML_NS, "data");
unknown.setAttribute("key", "num_unknown_collaboration");
unknown.setTextContent(String.valueOf(currentEdge.getUnknownCollaborationYearCount()));
edge.appendChild(unknown);
}
}
private void generateNodeSectionContent(CollaborationData coAuthorshipData, Element graphElement) {
Document doc = graphElement.getOwnerDocument();
graphElement.appendChild(doc.createComment("nodes"));
Collaborator egoNode = coAuthorshipData.getEgoCollaborator();
Set<Collaborator> authorNodes = coAuthorshipData.getCollaborators();
/*
* This method actually creates the XML code for a single Collaborator. "graphMLContent"
* is being side-effected. The egoNode is added first because this is the "requirement"
* of the co-author vis. Ego should always come first.
*
* */
getNodeContent(graphElement, egoNode);
List<Collaborator> orderedAuthorNodes = new ArrayList<Collaborator>(authorNodes);
orderedAuthorNodes.remove(egoNode);
orderedAuthorNodes.sort(new CollaboratorComparator());
for (Collaborator currNode : orderedAuthorNodes) {
/*
* We have already printed the Ego Collaborator info.
* */
if (currNode != egoNode) {
getNodeContent(graphElement, currNode);
}
}
}
private void getNodeContent(Element graphElement, Collaborator collaborator) {
Document doc = graphElement.getOwnerDocument();
ParamMap individualProfileURLParams =
new ParamMap(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, collaborator.getCollaboratorURI());
String profileURL = UrlBuilder.getUrl(VisualizationFrameworkConstants.INDIVIDUAL_URL_PREFIX, individualProfileURLParams);
Element node = doc.createElementNS(GRAPHML_NS, "node");
node.setAttribute("id", String.valueOf(collaborator.getCollaboratorID()));
graphElement.appendChild(node);
Element url = doc.createElementNS(GRAPHML_NS, "data");
url.setAttribute("key", "url");
url.setTextContent(collaborator.getCollaboratorURI());
node.appendChild(url);
Element label = doc.createElementNS(GRAPHML_NS, "data");
label.setAttribute("key", "label");
label.setTextContent(collaborator.getCollaboratorName());
node.appendChild(label);
if (profileURL != null) {
Element profile = doc.createElementNS(GRAPHML_NS, "data");
profile.setAttribute("key", "profile_url");
profile.setTextContent(profileURL);
node.appendChild(profile);
}
Element works = doc.createElementNS(GRAPHML_NS, "data");
works.setAttribute("key", "number_of_authored_works");
works.setTextContent(String.valueOf(collaborator.getNumOfActivities()));
node.appendChild(works);
if (collaborator.getEarliestActivityYearCount() != null) {
/*
* There is no clean way of getting the map contents in java even though
* we are sure to have only one entry on the map. So using the for loop.
* I am feeling dirty just about now.
* */
for (Map.Entry<String, Integer> publicationInfo : collaborator.getEarliestActivityYearCount().entrySet()) {
Element earliest = doc.createElementNS(GRAPHML_NS, "data");
earliest.setAttribute("key", "earliest_publication");
earliest.setTextContent(publicationInfo.getKey());
node.appendChild(earliest);
Element earliestCount = doc.createElementNS(GRAPHML_NS, "data");
earliestCount.setAttribute("key", "num_earliest_publication");
earliestCount.setTextContent(publicationInfo.getValue().toString());
node.appendChild(earliestCount);
}
}
if (collaborator.getLatestActivityYearCount() != null) {
for (Map.Entry<String, Integer> publicationInfo : collaborator.getLatestActivityYearCount().entrySet()) {
Element latest = doc.createElementNS(GRAPHML_NS, "data");
latest.setAttribute("key", "latest_publication");
latest.setTextContent(publicationInfo.getKey());
node.appendChild(latest);
Element latestCount = doc.createElementNS(GRAPHML_NS, "data");
latestCount.setAttribute("key", "num_latest_publication");
latestCount.setTextContent(publicationInfo.getValue().toString());
node.appendChild(latestCount);
}
}
if (collaborator.getUnknownActivityYearCount() != null) {
Element unknown = doc.createElementNS(GRAPHML_NS, "data");
unknown.setAttribute("key", "num_unknown_publication");
unknown.setTextContent(String.valueOf(collaborator.getUnknownActivityYearCount()));
node.appendChild(unknown);
}
}
private void generateKeyDefinitionContent(CollaborationData visVOContainer, Element rootElement) {
/*
* Generate the key definition content for node.
* */
getKeyDefinitionFromSchema(visVOContainer.getNodeSchema(), rootElement);
/*
* Generate the key definition content for edge.
* */
getKeyDefinitionFromSchema(visVOContainer.getEdgeSchema(), rootElement);
}
private void getKeyDefinitionFromSchema(Set<Map<String, String>> schema, Element rootElement) {
Document doc = rootElement.getOwnerDocument();
for (Map<String, String> currentNodeSchemaAttribute : schema) {
Element key = doc.createElementNS(GRAPHML_NS, "key");
for (Map.Entry<String, String> currentAttributeKey : currentNodeSchemaAttribute.entrySet()) {
key.setAttribute(currentAttributeKey.getKey(), currentAttributeKey.getValue());
}
if (currentNodeSchemaAttribute.containsKey("default")) {
Element def = doc.createElementNS(GRAPHML_NS, "default");
def.setTextContent(currentNodeSchemaAttribute.get("default"));
key.appendChild(def);
}
rootElement.appendChild(key);
}
}
}

View file

@ -46,8 +46,8 @@ import edu.cornell.mannlib.vitro.webapp.visualization.visutils.UniqueIDGenerator
/**
* This query runner is used to execute a sparql query to get all the publications
* for a particular individual. It will also fetch all the authors that worked
* on that particular publication.
*
* on that particular publication.
*
* @author cdtank
*/
public class CoAuthorshipQueryRunner implements QueryRunner<CoAuthorshipData> {
@ -63,7 +63,7 @@ public class CoAuthorshipQueryRunner implements QueryRunner<CoAuthorshipData> {
private RDFService rdfService;
private VitroRequest vitroRequest;
private Log log;
public CoAuthorshipQueryRunner(String egoURI, VitroRequest vreq, Log log) {
@ -77,12 +77,12 @@ public class CoAuthorshipQueryRunner implements QueryRunner<CoAuthorshipData> {
private static class QueryResultConsumer extends ResultSetConsumer {
Set<Collaborator> nodes = new HashSet<Collaborator>();
Map<String, Activity> biboDocumentURLToVO = new HashMap<String, Activity>();
Map<String, Set<Collaborator>> biboDocumentURLToCoAuthors = new HashMap<String, Set<Collaborator>>();
Map<String, Collaborator> nodeURLToVO = new HashMap<String, Collaborator>();
Map<String, Collaboration> edgeUniqueIdentifierToVO = new HashMap<String, Collaboration>();
Collaborator egoNode = null;
Set<Collaboration> edges = new HashSet<Collaboration>();

View file

@ -28,10 +28,10 @@ import edu.cornell.mannlib.vitro.webapp.visualization.visutils.VisualizationRequ
/**
* This request handler is used when information related to co-authorship network
* for an individual is requested. It currently provides 2 outputs,
* 1. Graphml content representing the individual's co-authorship network
* 1. CSV file containing the list(& count) of unique co-authors with which
* 1. Graphml content representing the individual's co-authorship network
* 1. CSV file containing the list(& count) of unique co-authors with which
* the individual has worked over the years. This data powers the related sparkline.
*
*
* @author cdtank
*/
public class CoAuthorshipRequestHandler implements VisualizationRequestHandler {
@ -54,7 +54,7 @@ public class CoAuthorshipRequestHandler implements VisualizationRequestHandler {
VitroRequest vitroRequest, Log log, Dataset dataset)
throws MalformedQueryParametersException {
String egoURI = vitroRequest.getParameter(
VisualizationFrameworkConstants
.INDIVIDUAL_URI_KEY);
@ -65,88 +65,88 @@ public class CoAuthorshipRequestHandler implements VisualizationRequestHandler {
CoAuthorshipQueryRunner queryManager =
new CoAuthorshipQueryRunner(egoURI, vitroRequest, log);
CollaborationData authorNodesAndEdges =
CollaborationData authorNodesAndEdges =
queryManager.getQueryResult();
/*
/*
* We will be using the same visualization package for both sparkline & coauthorship
* flash vis. We will use "VIS_MODE_KEY" as a modifier to differentiate
* flash vis. We will use "VIS_MODE_KEY" as a modifier to differentiate
* between these two. The default will be to render the coauthorship network vis.
* */
* */
if (VisualizationFrameworkConstants.COAUTHORS_COUNT_PER_YEAR_VIS_MODE
.equalsIgnoreCase(visMode)) {
.equalsIgnoreCase(visMode)) {
/*
* When the csv file is required - based on which sparkline visualization will
* When the csv file is required - based on which sparkline visualization will
* be rendered.
* */
return prepareCoauthorsCountPerYearDataResponse(authorNodesAndEdges);
} else if (VisualizationFrameworkConstants.COAUTHORS_LIST_VIS_MODE
.equalsIgnoreCase(visMode)) {
.equalsIgnoreCase(visMode)) {
/*
* When the csv file is required - based on which sparkline visualization will
* When the csv file is required - based on which sparkline visualization will
* be rendered.
* */
return prepareCoauthorsListDataResponse(authorNodesAndEdges);
} else if (VisualizationFrameworkConstants.COAUTHOR_NETWORK_DOWNLOAD_VIS_MODE
.equalsIgnoreCase(visMode)) {
.equalsIgnoreCase(visMode)) {
/*
* When the csv file is required - based on which sparkline visualization will
* When the csv file is required - based on which sparkline visualization will
* be rendered.
* */
return prepareNetworkDownloadDataResponse(authorNodesAndEdges);
} else {
/*
* When the graphML file is required - based on which coauthorship network
* When the graphML file is required - based on which coauthorship network
* visualization will be rendered.
* */
return prepareNetworkStreamDataResponse(authorNodesAndEdges);
}
}
public ResponseValues generateStandardVisualization(VitroRequest vitroRequest,
Log log,
Dataset dataset)
Log log,
Dataset dataset)
throws MalformedQueryParametersException {
throw new UnsupportedOperationException("CoAuthorship Visualization "
throw new UnsupportedOperationException("CoAuthorship Visualization "
+ "does not provide Standalone response.");
}
private String getCoauthorsListCSVContent(CollaborationData coAuthorshipData) {
StringBuilder csvFileContent = new StringBuilder();
csvFileContent.append("Co-author, Count\n");
for (Collaborator currNode : coAuthorshipData.getCollaborators()) {
for (Collaborator currNode : coAuthorshipData.getCollaborators()) {
/*
* We have already printed the Ego Node info.
* */
if (currNode != coAuthorshipData.getEgoCollaborator()) {
csvFileContent.append(StringEscapeUtils.escapeCsv(currNode.getCollaboratorName()));
csvFileContent.append(",");
csvFileContent.append(currNode.getNumOfActivities());
csvFileContent.append("\n");
}
}
return csvFileContent.toString();
}
private String getCoauthorsPerYearCSVContent(Map<String, Set<Collaborator>> yearToCoauthors) {
StringBuilder csvFileContent = new StringBuilder();
csvFileContent.append("Year, Count, Co-author(s)\n");
for (Entry<String, Set<Collaborator>> currentEntry : yearToCoauthors.entrySet()) {
csvFileContent.append(StringEscapeUtils.escapeCsv(currentEntry.getKey()));
csvFileContent.append(",");
@ -156,136 +156,136 @@ public class CoAuthorshipRequestHandler implements VisualizationRequestHandler {
getCoauthorNamesAsString(currentEntry.getValue())));
csvFileContent.append("\n");
}
return csvFileContent.toString();
}
private String getCoauthorNamesAsString(Set<Collaborator> coAuthors) {
StringBuilder coAuthorsMerged = new StringBuilder();
String coAuthorSeparator = "; ";
for (Collaborator currCoAuthor : coAuthors) {
coAuthorsMerged.append(currCoAuthor.getCollaboratorName()).append(coAuthorSeparator);
}
return StringUtils.removeEnd(coAuthorsMerged.toString(), coAuthorSeparator);
}
/**
* Provides response when a csv file containing number & names of unique co-authors per
* year is requested.
* Provides response when a csv file containing number & names of unique co-authors per
* year is requested.
* @param authorNodesAndEdges Author nodes and edges
*/
private Map<String, String> prepareCoauthorsCountPerYearDataResponse(
CollaborationData authorNodesAndEdges) {
String outputFileName;
Map<String, Set<Collaborator>> yearToCoauthors = new TreeMap<String, Set<Collaborator>>();
if (authorNodesAndEdges.getCollaborators() != null
if (authorNodesAndEdges.getCollaborators() != null
&& authorNodesAndEdges.getCollaborators().size() > 0) {
outputFileName = UtilityFunctions.slugify(authorNodesAndEdges
.getEgoCollaborator().getCollaboratorName())
+ "_co-authors-per-year" + ".csv";
yearToCoauthors = UtilityFunctions.getActivityYearToCollaborators(authorNodesAndEdges);
} else {
outputFileName = "no_co-authors-per-year" + ".csv";
outputFileName = "no_co-authors-per-year" + ".csv";
}
Map<String, String> fileData = new HashMap<String, String>();
fileData.put(DataVisualizationController.FILE_NAME_KEY,
fileData.put(DataVisualizationController.FILE_NAME_KEY,
outputFileName);
fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY,
fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY,
"application/octet-stream");
fileData.put(DataVisualizationController.FILE_CONTENT_KEY,
fileData.put(DataVisualizationController.FILE_CONTENT_KEY,
getCoauthorsPerYearCSVContent(yearToCoauthors));
return fileData;
}
/**
* Provides response when a csv file containing number & names of unique co-authors per
* year is requested.
* Provides response when a csv file containing number & names of unique co-authors per
* year is requested.
* @param coAuthorshipData Co authorship data
*/
private Map<String, String> prepareCoauthorsListDataResponse(
CollaborationData coAuthorshipData) {
String outputFileName = "";
if (coAuthorshipData.getCollaborators() != null
if (coAuthorshipData.getCollaborators() != null
&& coAuthorshipData.getCollaborators().size() > 0) {
outputFileName = UtilityFunctions.slugify(coAuthorshipData.getEgoCollaborator()
.getCollaboratorName())
.getCollaboratorName())
+ "_co-authors" + ".csv";
} else {
outputFileName = "no_co-authors" + ".csv";
}
Map<String, String> fileData = new HashMap<String, String>();
fileData.put(DataVisualizationController.FILE_NAME_KEY,
fileData.put(DataVisualizationController.FILE_NAME_KEY,
outputFileName);
fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY,
fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY,
"application/octet-stream");
fileData.put(DataVisualizationController.FILE_CONTENT_KEY,
fileData.put(DataVisualizationController.FILE_CONTENT_KEY,
getCoauthorsListCSVContent(coAuthorshipData));
return fileData;
}
/**
* Provides a response when graphml formatted co-authorship network is requested, typically by
* Provides a response when graphml formatted co-authorship network is requested, typically by
* the flash vis.
* @param authorNodesAndEdges Author nodes and edges
*/
private Map<String, String> prepareNetworkStreamDataResponse(
CollaborationData authorNodesAndEdges) {
CoAuthorshipGraphMLWriter coAuthorshipGraphMLWriter =
CoAuthorshipGraphMLWriter coAuthorshipGraphMLWriter =
new CoAuthorshipGraphMLWriter(authorNodesAndEdges);
Map<String, String> fileData = new HashMap<String, String>();
fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY,
fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY,
"text/xml");
fileData.put(DataVisualizationController.FILE_CONTENT_KEY,
fileData.put(DataVisualizationController.FILE_CONTENT_KEY,
coAuthorshipGraphMLWriter.getCoAuthorshipGraphMLContent().toString());
return fileData;
}
private Map<String, String> prepareNetworkDownloadDataResponse(
CollaborationData authorNodesAndEdges) {
String outputFileName = "";
if (authorNodesAndEdges.getCollaborators() != null
if (authorNodesAndEdges.getCollaborators() != null
&& authorNodesAndEdges.getCollaborators().size() > 0) {
outputFileName = UtilityFunctions.slugify(authorNodesAndEdges
.getEgoCollaborator().getCollaboratorName())
.getEgoCollaborator().getCollaboratorName())
+ "_co-author-network.graphml" + ".xml";
} else {
outputFileName = "no_co-author-network.graphml" + ".xml";
outputFileName = "no_co-author-network.graphml" + ".xml";
}
CoAuthorshipGraphMLWriter coAuthorshipGraphMLWriter =
CoAuthorshipGraphMLWriter coAuthorshipGraphMLWriter =
new CoAuthorshipGraphMLWriter(authorNodesAndEdges);
Map<String, String> fileData = new HashMap<String, String>();
fileData.put(DataVisualizationController.FILE_NAME_KEY,
fileData.put(DataVisualizationController.FILE_NAME_KEY,
outputFileName);
fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY,
fileData.put(DataVisualizationController.FILE_CONTENT_TYPE_KEY,
"text/xml");
fileData.put(DataVisualizationController.FILE_CONTENT_KEY,
fileData.put(DataVisualizationController.FILE_CONTENT_KEY,
coAuthorshipGraphMLWriter.getCoAuthorshipGraphMLContent().toString());
return fileData;

View file

@ -1,254 +1,254 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.visualization.coauthorship;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.apache.commons.logging.Log;
import edu.cornell.mannlib.vitro.webapp.controller.visualization.VisualizationFrameworkConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.constants.VOConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.constants.VisConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Collaborator;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.SparklineData;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.YearToEntityCountDataElement;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.UtilityFunctions;
public class CoAuthorshipVisCodeGenerator {
/*
* There are 2 modes of sparkline that are available via this visualization.
* 1. Short Sparkline - This sparkline will render all the data points (or sparks),
* which in this case are the coauthors over the years, from the last 10 years.
*
* 2. Full Sparkline - This sparkline will render all the data points (or sparks)
* spanning the career of the person & last 10 years at the minimum, in case if
* the person started his career in the last 10 yeras.
* */
private static final String DEFAULT_VISCONTAINER_DIV_ID = "unique_coauthors_vis_container";
private Map<String, Set<Collaborator>> yearToUniqueCoauthors;
private Log log;
private SparklineData sparklineParameterVO;
private String individualURI;
public CoAuthorshipVisCodeGenerator(String individualURI,
String visMode,
String visContainer,
Map<String, Set<Collaborator>> yearToUniqueCoauthors,
Log log) {
this.individualURI = individualURI;
this.yearToUniqueCoauthors = yearToUniqueCoauthors;
this.log = log;
this.sparklineParameterVO = setupSparklineParameters(visMode, visContainer);
}
/**
* This method is used to setup parameters for the sparkline value object. These parameters
* will be used in the template to construct the actual html/javascript code.
* @param visMode Visualization mode
* @param providedVisContainerID Container ID
*/
private SparklineData setupSparklineParameters(String visMode,
String providedVisContainerID) {
SparklineData sparklineData = new SparklineData();
int numOfYearsToBeRendered = 0;
/*
* It was decided that to prevent downward curve that happens if there are no publications
* in the current year seems a bit harsh, so we consider only publications from the last 10
* complete years.
* */
int currentYear = Calendar.getInstance().get(Calendar.YEAR) - 1;
int shortSparkMinYear = currentYear
- VisConstants.MINIMUM_YEARS_CONSIDERED_FOR_SPARKLINE
+ 1;
/*
* This is required because when deciding the range of years over which the vis
* was rendered we dont want to be influenced by the "DEFAULT_PUBLICATION_YEAR".
* */
Set<String> publishedYears = new HashSet<String>(yearToUniqueCoauthors.keySet());
publishedYears.remove(VOConstants.DEFAULT_PUBLICATION_YEAR);
/*
* We are setting the default value of minPublishedYear to be 10 years before
* the current year (which is suitably represented by the shortSparkMinYear),
* this in case we run into invalid set of published years.
* */
int minPublishedYear = shortSparkMinYear;
String visContainerID = null;
if (yearToUniqueCoauthors.size() > 0) {
try {
minPublishedYear = Integer.parseInt(Collections.min(publishedYears));
} catch (NoSuchElementException | NumberFormatException e1) {
log.debug("vis: " + e1.getMessage() + " error occurred for "
+ yearToUniqueCoauthors.toString());
}
}
int minPubYearConsidered = 0;
/*
* There might be a case that the author has made his first publication within the
* last 10 years but we want to make sure that the sparkline is representative of
* at least the last 10 years, so we will set the minPubYearConsidered to
* "currentYear - 10" which is also given by "shortSparkMinYear".
* */
if (minPublishedYear > shortSparkMinYear) {
minPubYearConsidered = shortSparkMinYear;
} else {
minPubYearConsidered = minPublishedYear;
}
numOfYearsToBeRendered = currentYear - minPubYearConsidered + 1;
sparklineData.setNumOfYearsToBeRendered(numOfYearsToBeRendered);
int uniqueCoAuthorCounter = 0;
Set<Collaborator> allCoAuthorsWithKnownAuthorshipYears = new HashSet<Collaborator>();
List<YearToEntityCountDataElement> yearToUniqueCoauthorsCountDataTable =
new ArrayList<YearToEntityCountDataElement>();
for (int publicationYear = minPubYearConsidered;
publicationYear <= currentYear;
publicationYear++) {
String publicationYearAsString = String.valueOf(publicationYear);
Set<Collaborator> currentCoAuthors = yearToUniqueCoauthors
.get(publicationYearAsString);
Integer currentUniqueCoAuthors = null;
if (currentCoAuthors != null) {
currentUniqueCoAuthors = currentCoAuthors.size();
allCoAuthorsWithKnownAuthorshipYears.addAll(currentCoAuthors);
} else {
currentUniqueCoAuthors = 0;
}
yearToUniqueCoauthorsCountDataTable.add(
new YearToEntityCountDataElement(uniqueCoAuthorCounter,
publicationYearAsString,
currentUniqueCoAuthors));
uniqueCoAuthorCounter++;
}
/*
* For the purpose of this visualization I have come up with a term "Sparks" which
* essentially means data points.
* Sparks that will be rendered in full mode will always be the one's which have any year
* associated with it. Hence.
* */
sparklineData.setRenderedSparks(allCoAuthorsWithKnownAuthorshipYears.size());
sparklineData.setYearToEntityCountDataTable(yearToUniqueCoauthorsCountDataTable);
/*
* This is required only for the sparklines which convey collaborationships like
* coinvestigatorships and coauthorship. There are edge cases where a collaborator can be
* present for in a collaboration with known & unknown year. We do not want to repeat the
* count for this collaborator when we present it in the front-end.
* */
Set<Collaborator> totalUniqueCoInvestigators =
new HashSet<Collaborator>(allCoAuthorsWithKnownAuthorshipYears);
/*
* Total publications will also consider publications that have no year associated with
* them. Hence.
* */
Integer unknownYearCoauthors = 0;
if (yearToUniqueCoauthors.get(VOConstants.DEFAULT_PUBLICATION_YEAR) != null) {
unknownYearCoauthors = yearToUniqueCoauthors
.get(VOConstants.DEFAULT_PUBLICATION_YEAR).size();
totalUniqueCoInvestigators.addAll(
yearToUniqueCoauthors.get(VOConstants.DEFAULT_GRANT_YEAR));
}
sparklineData.setUnknownYearPublications(unknownYearCoauthors);
sparklineData.setTotalCollaborationshipCount(totalUniqueCoInvestigators.size());
if (providedVisContainerID != null) {
visContainerID = providedVisContainerID;
} else {
visContainerID = DEFAULT_VISCONTAINER_DIV_ID;
}
sparklineData.setVisContainerDivID(visContainerID);
/*
* By default these represents the range of the rendered sparks. Only in case of
* "short" sparkline mode we will set the Earliest RenderedPublication year to
* "currentYear - 10".
* */
sparklineData.setEarliestYearConsidered(minPubYearConsidered);
sparklineData.setEarliestRenderedPublicationYear(minPublishedYear);
sparklineData.setLatestRenderedPublicationYear(currentYear);
/*
* The Full Sparkline will be rendered by default. Only if the url has specific mention of
* SHORT_SPARKLINE_MODE_KEY then we render the short sparkline and not otherwise.
* */
if (VisualizationFrameworkConstants.SHORT_SPARKLINE_VIS_MODE.equalsIgnoreCase(visMode)) {
sparklineData.setEarliestRenderedPublicationYear(shortSparkMinYear);
sparklineData.setShortVisMode(true);
} else {
sparklineData.setShortVisMode(false);
}
if (yearToUniqueCoauthors.size() > 0) {
sparklineData.setFullTimelineNetworkLink(
UtilityFunctions.getCollaboratorshipNetworkLink(
individualURI,
VisualizationFrameworkConstants.PERSON_LEVEL_VIS,
VisualizationFrameworkConstants.COAUTHOR_VIS_MODE));
sparklineData.setDownloadDataLink(
UtilityFunctions.getCSVDownloadURL(
individualURI,
VisualizationFrameworkConstants.COAUTHORSHIP_VIS,
VisualizationFrameworkConstants.COAUTHORS_COUNT_PER_YEAR_VIS_MODE));
Map<String, Integer> yearToUniqueCoauthorsCount = new HashMap<String, Integer>();
for (Map.Entry<String, Set<Collaborator>> currentYearToCoAuthors
: yearToUniqueCoauthors.entrySet()) {
yearToUniqueCoauthorsCount.put(currentYearToCoAuthors.getKey(),
currentYearToCoAuthors.getValue().size());
}
sparklineData.setYearToActivityCount(yearToUniqueCoauthorsCount);
}
return sparklineData;
}
public SparklineData getValueObjectContainer() {
return this.sparklineParameterVO;
}
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.visualization.coauthorship;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.apache.commons.logging.Log;
import edu.cornell.mannlib.vitro.webapp.controller.visualization.VisualizationFrameworkConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.constants.VOConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.constants.VisConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Collaborator;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.SparklineData;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.YearToEntityCountDataElement;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.UtilityFunctions;
public class CoAuthorshipVisCodeGenerator {
/*
* There are 2 modes of sparkline that are available via this visualization.
* 1. Short Sparkline - This sparkline will render all the data points (or sparks),
* which in this case are the coauthors over the years, from the last 10 years.
*
* 2. Full Sparkline - This sparkline will render all the data points (or sparks)
* spanning the career of the person & last 10 years at the minimum, in case if
* the person started his career in the last 10 yeras.
* */
private static final String DEFAULT_VISCONTAINER_DIV_ID = "unique_coauthors_vis_container";
private Map<String, Set<Collaborator>> yearToUniqueCoauthors;
private Log log;
private SparklineData sparklineParameterVO;
private String individualURI;
public CoAuthorshipVisCodeGenerator(String individualURI,
String visMode,
String visContainer,
Map<String, Set<Collaborator>> yearToUniqueCoauthors,
Log log) {
this.individualURI = individualURI;
this.yearToUniqueCoauthors = yearToUniqueCoauthors;
this.log = log;
this.sparklineParameterVO = setupSparklineParameters(visMode, visContainer);
}
/**
* This method is used to setup parameters for the sparkline value object. These parameters
* will be used in the template to construct the actual html/javascript code.
* @param visMode Visualization mode
* @param providedVisContainerID Container ID
*/
private SparklineData setupSparklineParameters(String visMode,
String providedVisContainerID) {
SparklineData sparklineData = new SparklineData();
int numOfYearsToBeRendered = 0;
/*
* It was decided that to prevent downward curve that happens if there are no publications
* in the current year seems a bit harsh, so we consider only publications from the last 10
* complete years.
* */
int currentYear = Calendar.getInstance().get(Calendar.YEAR) - 1;
int shortSparkMinYear = currentYear
- VisConstants.MINIMUM_YEARS_CONSIDERED_FOR_SPARKLINE
+ 1;
/*
* This is required because when deciding the range of years over which the vis
* was rendered we dont want to be influenced by the "DEFAULT_PUBLICATION_YEAR".
* */
Set<String> publishedYears = new HashSet<String>(yearToUniqueCoauthors.keySet());
publishedYears.remove(VOConstants.DEFAULT_PUBLICATION_YEAR);
/*
* We are setting the default value of minPublishedYear to be 10 years before
* the current year (which is suitably represented by the shortSparkMinYear),
* this in case we run into invalid set of published years.
* */
int minPublishedYear = shortSparkMinYear;
String visContainerID = null;
if (yearToUniqueCoauthors.size() > 0) {
try {
minPublishedYear = Integer.parseInt(Collections.min(publishedYears));
} catch (NoSuchElementException | NumberFormatException e1) {
log.debug("vis: " + e1.getMessage() + " error occurred for "
+ yearToUniqueCoauthors.toString());
}
}
int minPubYearConsidered = 0;
/*
* There might be a case that the author has made his first publication within the
* last 10 years but we want to make sure that the sparkline is representative of
* at least the last 10 years, so we will set the minPubYearConsidered to
* "currentYear - 10" which is also given by "shortSparkMinYear".
* */
if (minPublishedYear > shortSparkMinYear) {
minPubYearConsidered = shortSparkMinYear;
} else {
minPubYearConsidered = minPublishedYear;
}
numOfYearsToBeRendered = currentYear - minPubYearConsidered + 1;
sparklineData.setNumOfYearsToBeRendered(numOfYearsToBeRendered);
int uniqueCoAuthorCounter = 0;
Set<Collaborator> allCoAuthorsWithKnownAuthorshipYears = new HashSet<Collaborator>();
List<YearToEntityCountDataElement> yearToUniqueCoauthorsCountDataTable =
new ArrayList<YearToEntityCountDataElement>();
for (int publicationYear = minPubYearConsidered;
publicationYear <= currentYear;
publicationYear++) {
String publicationYearAsString = String.valueOf(publicationYear);
Set<Collaborator> currentCoAuthors = yearToUniqueCoauthors
.get(publicationYearAsString);
Integer currentUniqueCoAuthors = null;
if (currentCoAuthors != null) {
currentUniqueCoAuthors = currentCoAuthors.size();
allCoAuthorsWithKnownAuthorshipYears.addAll(currentCoAuthors);
} else {
currentUniqueCoAuthors = 0;
}
yearToUniqueCoauthorsCountDataTable.add(
new YearToEntityCountDataElement(uniqueCoAuthorCounter,
publicationYearAsString,
currentUniqueCoAuthors));
uniqueCoAuthorCounter++;
}
/*
* For the purpose of this visualization I have come up with a term "Sparks" which
* essentially means data points.
* Sparks that will be rendered in full mode will always be the one's which have any year
* associated with it. Hence.
* */
sparklineData.setRenderedSparks(allCoAuthorsWithKnownAuthorshipYears.size());
sparklineData.setYearToEntityCountDataTable(yearToUniqueCoauthorsCountDataTable);
/*
* This is required only for the sparklines which convey collaborationships like
* coinvestigatorships and coauthorship. There are edge cases where a collaborator can be
* present for in a collaboration with known & unknown year. We do not want to repeat the
* count for this collaborator when we present it in the front-end.
* */
Set<Collaborator> totalUniqueCoInvestigators =
new HashSet<Collaborator>(allCoAuthorsWithKnownAuthorshipYears);
/*
* Total publications will also consider publications that have no year associated with
* them. Hence.
* */
Integer unknownYearCoauthors = 0;
if (yearToUniqueCoauthors.get(VOConstants.DEFAULT_PUBLICATION_YEAR) != null) {
unknownYearCoauthors = yearToUniqueCoauthors
.get(VOConstants.DEFAULT_PUBLICATION_YEAR).size();
totalUniqueCoInvestigators.addAll(
yearToUniqueCoauthors.get(VOConstants.DEFAULT_GRANT_YEAR));
}
sparklineData.setUnknownYearPublications(unknownYearCoauthors);
sparklineData.setTotalCollaborationshipCount(totalUniqueCoInvestigators.size());
if (providedVisContainerID != null) {
visContainerID = providedVisContainerID;
} else {
visContainerID = DEFAULT_VISCONTAINER_DIV_ID;
}
sparklineData.setVisContainerDivID(visContainerID);
/*
* By default these represents the range of the rendered sparks. Only in case of
* "short" sparkline mode we will set the Earliest RenderedPublication year to
* "currentYear - 10".
* */
sparklineData.setEarliestYearConsidered(minPubYearConsidered);
sparklineData.setEarliestRenderedPublicationYear(minPublishedYear);
sparklineData.setLatestRenderedPublicationYear(currentYear);
/*
* The Full Sparkline will be rendered by default. Only if the url has specific mention of
* SHORT_SPARKLINE_MODE_KEY then we render the short sparkline and not otherwise.
* */
if (VisualizationFrameworkConstants.SHORT_SPARKLINE_VIS_MODE.equalsIgnoreCase(visMode)) {
sparklineData.setEarliestRenderedPublicationYear(shortSparkMinYear);
sparklineData.setShortVisMode(true);
} else {
sparklineData.setShortVisMode(false);
}
if (yearToUniqueCoauthors.size() > 0) {
sparklineData.setFullTimelineNetworkLink(
UtilityFunctions.getCollaboratorshipNetworkLink(
individualURI,
VisualizationFrameworkConstants.PERSON_LEVEL_VIS,
VisualizationFrameworkConstants.COAUTHOR_VIS_MODE));
sparklineData.setDownloadDataLink(
UtilityFunctions.getCSVDownloadURL(
individualURI,
VisualizationFrameworkConstants.COAUTHORSHIP_VIS,
VisualizationFrameworkConstants.COAUTHORS_COUNT_PER_YEAR_VIS_MODE));
Map<String, Integer> yearToUniqueCoauthorsCount = new HashMap<String, Integer>();
for (Map.Entry<String, Set<Collaborator>> currentYearToCoAuthors
: yearToUniqueCoauthors.entrySet()) {
yearToUniqueCoauthorsCount.put(currentYearToCoAuthors.getKey(),
currentYearToCoAuthors.getValue().size());
}
sparklineData.setYearToActivityCount(yearToUniqueCoauthorsCount);
}
return sparklineData;
}
public SparklineData getValueObjectContainer() {
return this.sparklineParameterVO;
}
}

View file

@ -27,169 +27,169 @@ public class CoAuthorshipData extends CollaborationData {
public Set<Map<String, String>> initializeEdgeSchema() {
Set<Map<String, String>> edgeSchema = new HashSet<Map<String, String>>();
Map<String, String> schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "collaborator1");
schemaAttributes.put("for", "edge");
schemaAttributes.put("attr.name", "collaborator1");
schemaAttributes.put("attr.type", "string");
edgeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "collaborator2");
schemaAttributes.put("for", "edge");
schemaAttributes.put("attr.name", "collaborator2");
schemaAttributes.put("attr.type", "string");
edgeSchema.add(schemaAttributes);
edgeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "number_of_coauthored_works");
schemaAttributes.put("for", "edge");
schemaAttributes.put("attr.name", "number_of_coauthored_works");
schemaAttributes.put("attr.type", "int");
edgeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "earliest_collaboration");
schemaAttributes.put("for", "edge");
schemaAttributes.put("attr.name", "earliest_collaboration");
schemaAttributes.put("attr.type", "int");
edgeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "num_earliest_collaboration");
schemaAttributes.put("for", "edge");
schemaAttributes.put("attr.name", "num_earliest_collaboration");
schemaAttributes.put("attr.type", "int");
edgeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "latest_collaboration");
schemaAttributes.put("for", "edge");
schemaAttributes.put("attr.name", "latest_collaboration");
schemaAttributes.put("attr.type", "int");
edgeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "num_latest_collaboration");
schemaAttributes.put("for", "edge");
schemaAttributes.put("attr.name", "num_latest_collaboration");
schemaAttributes.put("attr.type", "int");
edgeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "num_unknown_collaboration");
schemaAttributes.put("for", "edge");
schemaAttributes.put("attr.name", "num_unknown_collaboration");
schemaAttributes.put("attr.type", "int");
edgeSchema.add(schemaAttributes);
return edgeSchema;
}
public Set<Map<String, String>> initializeNodeSchema() {
Set<Map<String, String>> nodeSchema = new HashSet<Map<String, String>>();
Map<String, String> schemaAttributes = new LinkedHashMap<String, String>();
Map<String, String> schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "url");
schemaAttributes.put("for", "node");
schemaAttributes.put("attr.name", "url");
schemaAttributes.put("attr.type", "string");
nodeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "label");
schemaAttributes.put("for", "node");
schemaAttributes.put("attr.name", "label");
schemaAttributes.put("attr.type", "string");
nodeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "profile_url");
schemaAttributes.put("for", "node");
schemaAttributes.put("attr.name", "profile_url");
schemaAttributes.put("attr.type", "string");
nodeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "number_of_authored_works");
schemaAttributes.put("for", "node");
schemaAttributes.put("attr.name", "number_of_authored_works");
schemaAttributes.put("attr.type", "int");
nodeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "earliest_publication");
schemaAttributes.put("for", "node");
schemaAttributes.put("attr.name", "earliest_publication");
schemaAttributes.put("attr.type", "int");
nodeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "num_earliest_publication");
schemaAttributes.put("for", "node");
schemaAttributes.put("attr.name", "num_earliest_publication");
schemaAttributes.put("attr.type", "int");
nodeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "latest_publication");
schemaAttributes.put("for", "node");
schemaAttributes.put("attr.name", "latest_publication");
schemaAttributes.put("attr.type", "int");
nodeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "num_latest_publication");
schemaAttributes.put("for", "node");
schemaAttributes.put("attr.name", "num_latest_publication");
schemaAttributes.put("attr.type", "int");
nodeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "num_unknown_publication");
schemaAttributes.put("for", "node");
schemaAttributes.put("attr.name", "num_unknown_publication");
schemaAttributes.put("attr.type", "int");
nodeSchema.add(schemaAttributes);
return nodeSchema;
}

View file

@ -27,169 +27,169 @@ public class CoInvestigationData extends CollaborationData {
public Set<Map<String, String>> initializeEdgeSchema() {
Set<Map<String, String>> edgeSchema = new HashSet<Map<String, String>>();
Map<String, String> schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "collaborator1");
schemaAttributes.put("for", "edge");
schemaAttributes.put("attr.name", "collaborator1");
schemaAttributes.put("attr.type", "string");
edgeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "collaborator2");
schemaAttributes.put("for", "edge");
schemaAttributes.put("attr.name", "collaborator2");
schemaAttributes.put("attr.type", "string");
edgeSchema.add(schemaAttributes);
edgeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "number_of_coinvestigated_grants");
schemaAttributes.put("for", "edge");
schemaAttributes.put("attr.name", "number_of_coinvestigated_grants");
schemaAttributes.put("attr.type", "int");
edgeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "earliest_collaboration");
schemaAttributes.put("for", "edge");
schemaAttributes.put("attr.name", "earliest_collaboration");
schemaAttributes.put("attr.type", "int");
edgeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "num_earliest_collaboration");
schemaAttributes.put("for", "edge");
schemaAttributes.put("attr.name", "num_earliest_collaboration");
schemaAttributes.put("attr.type", "int");
edgeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "latest_collaboration");
schemaAttributes.put("for", "edge");
schemaAttributes.put("attr.name", "latest_collaboration");
schemaAttributes.put("attr.type", "int");
edgeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "num_latest_collaboration");
schemaAttributes.put("for", "edge");
schemaAttributes.put("attr.name", "num_latest_collaboration");
schemaAttributes.put("attr.type", "int");
edgeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "num_unknown_collaboration");
schemaAttributes.put("for", "edge");
schemaAttributes.put("attr.name", "num_unknown_collaboration");
schemaAttributes.put("attr.type", "int");
edgeSchema.add(schemaAttributes);
return edgeSchema;
}
public Set<Map<String, String>> initializeNodeSchema() {
Set<Map<String, String>> nodeSchema = new HashSet<Map<String, String>>();
Map<String, String> schemaAttributes = new LinkedHashMap<String, String>();
Map<String, String> schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "url");
schemaAttributes.put("for", "node");
schemaAttributes.put("attr.name", "url");
schemaAttributes.put("attr.type", "string");
nodeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "label");
schemaAttributes.put("for", "node");
schemaAttributes.put("attr.name", "label");
schemaAttributes.put("attr.type", "string");
nodeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "profile_url");
schemaAttributes.put("for", "node");
schemaAttributes.put("attr.name", "profile_url");
schemaAttributes.put("attr.type", "string");
nodeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "number_of_investigated_grants");
schemaAttributes.put("for", "node");
schemaAttributes.put("attr.name", "number_of_investigated_grants");
schemaAttributes.put("attr.type", "int");
nodeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "earliest_grant");
schemaAttributes.put("for", "node");
schemaAttributes.put("attr.name", "earliest_grant");
schemaAttributes.put("attr.type", "int");
nodeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "num_earliest_grant");
schemaAttributes.put("for", "node");
schemaAttributes.put("attr.name", "num_earliest_grant");
schemaAttributes.put("attr.type", "int");
nodeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "latest_grant");
schemaAttributes.put("for", "node");
schemaAttributes.put("attr.name", "latest_grant");
schemaAttributes.put("attr.type", "int");
nodeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "num_latest_grant");
schemaAttributes.put("for", "node");
schemaAttributes.put("attr.name", "num_latest_grant");
schemaAttributes.put("attr.type", "int");
nodeSchema.add(schemaAttributes);
schemaAttributes = new LinkedHashMap<String, String>();
schemaAttributes.put("id", "num_unknown_grant");
schemaAttributes.put("for", "node");
schemaAttributes.put("attr.name", "num_unknown_grant");
schemaAttributes.put("attr.type", "int");
nodeSchema.add(schemaAttributes);
return nodeSchema;
}

View file

@ -1,22 +1,22 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.visualization.collaborationutils;
import java.util.Comparator;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Collaboration;
/**
* This Comparator is used to sort the edges based on their IDs in ascending order.
* @author cdtank
*
*/
public class CollaborationComparator implements Comparator<Collaboration> {
@Override
public int compare(Collaboration arg0, Collaboration arg1) {
return arg0.getCollaborationID() - arg1.getCollaborationID();
}
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.visualization.collaborationutils;
import java.util.Comparator;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Collaboration;
/**
* This Comparator is used to sort the edges based on their IDs in ascending order.
* @author cdtank
*
*/
public class CollaborationComparator implements Comparator<Collaboration> {
@Override
public int compare(Collaboration arg0, Collaboration arg1) {
return arg0.getCollaborationID() - arg1.getCollaborationID();
}
}

View file

@ -1,73 +1,73 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.visualization.collaborationutils;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Collaboration;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Collaborator;
public abstract class CollaborationData {
private Set<Collaborator> collaborators;
private Set<Collaboration> collaborations;
private Collaborator egoCollaborator;
private Set<Map<String, String>> NODE_SCHEMA;
private Set<Map<String, String>> EDGE_SCHEMA;
private Date builtFromCacheTime = null;
public CollaborationData(Collaborator egoCollaborator,
Set<Collaborator> collaborators,
Set<Collaboration> collaborations) {
this.egoCollaborator = egoCollaborator;
this.collaborators = collaborators;
this.collaborations = collaborations;
}
public Date getBuiltFromCacheTime() { return builtFromCacheTime; }
public Set<Collaborator> getCollaborators() {
return collaborators;
}
public Set<Collaboration> getCollaborations() {
return collaborations;
}
public Collaborator getEgoCollaborator() {
return egoCollaborator;
}
/*
* Node Schema for graphML
* */
public Set<Map<String, String>> getNodeSchema() {
if (NODE_SCHEMA == null) {
NODE_SCHEMA = initializeNodeSchema();
}
return NODE_SCHEMA;
}
/*
* Edge Schema for graphML
* */
public Set<Map<String, String>> getEdgeSchema() {
if (EDGE_SCHEMA == null) {
EDGE_SCHEMA = initializeEdgeSchema();
}
return EDGE_SCHEMA;
}
public void setBuiltFromCacheTime(Date time) { this.builtFromCacheTime = time; }
abstract Set<Map<String, String>> initializeEdgeSchema();
abstract Set<Map<String, String>> initializeNodeSchema();
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.visualization.collaborationutils;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Collaboration;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Collaborator;
public abstract class CollaborationData {
private Set<Collaborator> collaborators;
private Set<Collaboration> collaborations;
private Collaborator egoCollaborator;
private Set<Map<String, String>> NODE_SCHEMA;
private Set<Map<String, String>> EDGE_SCHEMA;
private Date builtFromCacheTime = null;
public CollaborationData(Collaborator egoCollaborator,
Set<Collaborator> collaborators,
Set<Collaboration> collaborations) {
this.egoCollaborator = egoCollaborator;
this.collaborators = collaborators;
this.collaborations = collaborations;
}
public Date getBuiltFromCacheTime() { return builtFromCacheTime; }
public Set<Collaborator> getCollaborators() {
return collaborators;
}
public Set<Collaboration> getCollaborations() {
return collaborations;
}
public Collaborator getEgoCollaborator() {
return egoCollaborator;
}
/*
* Node Schema for graphML
* */
public Set<Map<String, String>> getNodeSchema() {
if (NODE_SCHEMA == null) {
NODE_SCHEMA = initializeNodeSchema();
}
return NODE_SCHEMA;
}
/*
* Edge Schema for graphML
* */
public Set<Map<String, String>> getEdgeSchema() {
if (EDGE_SCHEMA == null) {
EDGE_SCHEMA = initializeEdgeSchema();
}
return EDGE_SCHEMA;
}
public void setBuiltFromCacheTime(Date time) { this.builtFromCacheTime = time; }
abstract Set<Map<String, String>> initializeEdgeSchema();
abstract Set<Map<String, String>> initializeNodeSchema();
}

View file

@ -1,21 +1,21 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.visualization.collaborationutils;
import java.util.Comparator;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Collaborator;
/**
* This Comparator is used to sort the nodes based on their IDs in ascending order.
* @author cdtank
*/
public class CollaboratorComparator implements Comparator<Collaborator> {
@Override
public int compare(Collaborator arg0, Collaborator arg1) {
return arg0.getCollaboratorID() - arg1.getCollaboratorID();
}
}
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.visualization.collaborationutils;
import java.util.Comparator;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Collaborator;
/**
* This Comparator is used to sort the nodes based on their IDs in ascending order.
* @author cdtank
*/
public class CollaboratorComparator implements Comparator<Collaborator> {
@Override
public int compare(Collaborator arg0, Collaborator arg1) {
return arg0.getCollaboratorID() - arg1.getCollaboratorID();
}
}

Some files were not shown because too many files have changed in this diff Show more