Maven migration (first draft)
This commit is contained in:
parent
da79ac3e1d
commit
fee48b0b50
1711 changed files with 662 additions and 0 deletions
96
api/pom.xml
Normal file
96
api/pom.xml
Normal file
|
@ -0,0 +1,96 @@
|
|||
<project
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>org.vivoweb</groupId>
|
||||
<artifactId>vivo-api</artifactId>
|
||||
<version>1.9.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>org.vivoweb</groupId>
|
||||
<artifactId>vivo-project</artifactId>
|
||||
<version>1.9.0-SNAPSHOT</version>
|
||||
<relativePath>..</relativePath>
|
||||
</parent>
|
||||
|
||||
<name>VIVO API</name>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.vivoweb</groupId>
|
||||
<artifactId>vitro-api</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>axis</groupId>
|
||||
<artifactId>axis</artifactId>
|
||||
<version>1.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>1.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.itextpdf</groupId>
|
||||
<artifactId>itextpdf</artifactId>
|
||||
<version>5.0.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-beans</artifactId>
|
||||
<version>2.5.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>2.5.6</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.vivoweb.dependencies</groupId>
|
||||
<artifactId>agrovocws</artifactId>
|
||||
<version>3.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.vivoweb.dependencies</groupId>
|
||||
<artifactId>oim.vivo.scimapcore</artifactId>
|
||||
<version>1.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.vivoweb.dependencies</groupId>
|
||||
<artifactId>orcid-api-client</artifactId>
|
||||
<version>0.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>servlet-api</artifactId>
|
||||
<version>2.5</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>jsp-api</artifactId>
|
||||
<version>2.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.11</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.vivoweb</groupId>
|
||||
<artifactId>vitro-api</artifactId>
|
||||
<type>test-jar</type>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
|
@ -0,0 +1,28 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
package edu.cornell.mannlib.semservices.bo;
|
||||
|
||||
public class BaseObject {
|
||||
/**
|
||||
* Simple JavaBean domain object with an id property.
|
||||
* Used as a base class for objects needing this property.
|
||||
*
|
||||
* @author Ken Krebs
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
private Integer id;
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public boolean isNew() {
|
||||
return (this.id == null);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,163 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.semservices.bo;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Concept {
|
||||
|
||||
private String definedBy;
|
||||
private String conceptId;
|
||||
private String bestMatch;
|
||||
private String label;
|
||||
private String type;
|
||||
private String definition;
|
||||
private String uri;
|
||||
private String schemeURI;
|
||||
private List<String> broaderURIList;
|
||||
private List<String> narrowerURIList;
|
||||
private List<String> exactMatchURIList;
|
||||
private List<String> closeMatchURIList;
|
||||
private List<String> altLabelList;
|
||||
|
||||
/**
|
||||
* default constructor
|
||||
*/
|
||||
public Concept() {
|
||||
this.broaderURIList = new ArrayList<String>();
|
||||
this.narrowerURIList = new ArrayList<String>();
|
||||
this.exactMatchURIList = new ArrayList<String>();
|
||||
this.closeMatchURIList = new ArrayList<String>();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the conceptId
|
||||
*/
|
||||
public String getConceptId() {
|
||||
return conceptId;
|
||||
}
|
||||
/**
|
||||
* @param conceptId the conceptId to set
|
||||
*/
|
||||
public void setConceptId(String conceptId) {
|
||||
this.conceptId = conceptId;
|
||||
}
|
||||
/**
|
||||
* @return the label
|
||||
*/
|
||||
public String getLabel() {
|
||||
return label;
|
||||
}
|
||||
/**
|
||||
* @param label the label to set
|
||||
*/
|
||||
public void setLabel(String label) {
|
||||
this.label = label;
|
||||
}
|
||||
/**
|
||||
* @return the type
|
||||
*/
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
/**
|
||||
* @param type the type to set
|
||||
*/
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
/**
|
||||
* @return the definition
|
||||
*/
|
||||
public String getDefinition() {
|
||||
return definition;
|
||||
}
|
||||
/**
|
||||
* @param definition the definition to set
|
||||
*/
|
||||
public void setDefinition(String definition) {
|
||||
this.definition = definition;
|
||||
}
|
||||
/**
|
||||
* @return the uri
|
||||
*/
|
||||
public String getUri() {
|
||||
return uri;
|
||||
}
|
||||
/**
|
||||
* @param uri the uri to set
|
||||
*/
|
||||
public void setUri(String uri) {
|
||||
this.uri = uri;
|
||||
}
|
||||
/**
|
||||
* @return the definedBy
|
||||
*/
|
||||
public String getDefinedBy() {
|
||||
return definedBy;
|
||||
}
|
||||
/**
|
||||
* @param definedBy the definedBy to set
|
||||
*/
|
||||
public void setDefinedBy(String definedBy) {
|
||||
this.definedBy = definedBy;
|
||||
}
|
||||
/**
|
||||
* @return the schemeURI
|
||||
*/
|
||||
public String getSchemeURI() {
|
||||
return schemeURI;
|
||||
}
|
||||
/**
|
||||
* @param schemeURI the schemeURI to set
|
||||
*/
|
||||
public void setSchemeURI(String schemeURI) {
|
||||
this.schemeURI = schemeURI;
|
||||
}
|
||||
/**
|
||||
* @return the bestMatch
|
||||
*/
|
||||
public String getBestMatch() {
|
||||
return bestMatch;
|
||||
}
|
||||
/**
|
||||
* @param bestMatch the bestMatch to set
|
||||
*/
|
||||
public void setBestMatch(String bestMatch) {
|
||||
this.bestMatch = bestMatch;
|
||||
}
|
||||
public List<String> getBroaderURIList() {
|
||||
return broaderURIList;
|
||||
}
|
||||
public void setBroaderURIList(List<String> broaderURIList) {
|
||||
this.broaderURIList = broaderURIList;
|
||||
}
|
||||
public List<String> getNarrowerURIList() {
|
||||
return narrowerURIList;
|
||||
}
|
||||
public void setNarrowerURIList(List<String> narrowerURIList) {
|
||||
this.narrowerURIList = narrowerURIList;
|
||||
}
|
||||
public List<String> getExactMatchURIList() {
|
||||
return exactMatchURIList;
|
||||
}
|
||||
public void setExactMatchURIList(List<String> exactMatchURIList) {
|
||||
this.exactMatchURIList = exactMatchURIList;
|
||||
}
|
||||
public List<String> getCloseMatchURIList() {
|
||||
return closeMatchURIList;
|
||||
}
|
||||
public void setCloseMatchURIList(List<String> closeMatchURIList) {
|
||||
this.closeMatchURIList = closeMatchURIList;
|
||||
}
|
||||
|
||||
public List<String> getAltLabelList() {
|
||||
return altLabelList;
|
||||
}
|
||||
|
||||
public void setAltLabelList(List<String> altLabelList) {
|
||||
this.altLabelList = altLabelList;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.semservices.bo;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class ConceptInfo extends SemanticServicesInfoBase {
|
||||
|
||||
private List<?> conceptList;
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public ConceptInfo() {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the conceptList
|
||||
*/
|
||||
public List<?> getConceptList() {
|
||||
return conceptList;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param conceptList the conceptList to set
|
||||
*/
|
||||
public void setConceptList(List<?> conceptList) {
|
||||
this.conceptList = conceptList;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,75 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.semservices.bo;
|
||||
|
||||
public class SemanticServicesError {
|
||||
private String message;
|
||||
private String exception;
|
||||
private String severity;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public SemanticServicesError() {
|
||||
super();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param exception
|
||||
* @param message
|
||||
* @param severity
|
||||
*/
|
||||
public SemanticServicesError(String exception, String message, String severity) {
|
||||
super();
|
||||
this.exception = exception;
|
||||
this.message = message;
|
||||
this.severity = severity;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return the message
|
||||
*/
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param message the message to set
|
||||
*/
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the exception
|
||||
*/
|
||||
public String getException() {
|
||||
return exception;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param exception the exception to set
|
||||
*/
|
||||
public void setException(String exception) {
|
||||
this.exception = exception;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the severity
|
||||
*/
|
||||
public String getSeverity() {
|
||||
return severity;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param severity the severity to set
|
||||
*/
|
||||
public void setSeverity(String severity) {
|
||||
this.severity = severity;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.semservices.bo;
|
||||
|
||||
public class SemanticServicesInfoBase {
|
||||
|
||||
private SemanticServicesError semanticServicesError;
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public SemanticServicesInfoBase() {
|
||||
super();
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the semanticServicesError
|
||||
*/
|
||||
public SemanticServicesError getSemanticServicesError() {
|
||||
return semanticServicesError;
|
||||
}
|
||||
/**
|
||||
* @param semanticServicesError the semanticServicesError to set
|
||||
*/
|
||||
public void setSemanticServicesError(SemanticServicesError semanticServicesError) {
|
||||
this.semanticServicesError = semanticServicesError;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.semservices.exceptions;
|
||||
|
||||
public class ConceptsNotFoundException extends Exception {
|
||||
/**
|
||||
* An exception that indicates a service could not find a Concept
|
||||
*/
|
||||
private static final long serialVersionUID = -4729465393290022840L;
|
||||
public ConceptsNotFoundException() { }
|
||||
public ConceptsNotFoundException(String message) { super(message); }
|
||||
public ConceptsNotFoundException(Throwable cause) { super(cause); }
|
||||
public ConceptsNotFoundException(String message, Throwable cause) { super(message, cause); }
|
||||
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.semservices.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import edu.cornell.mannlib.semservices.bo.Concept;
|
||||
|
||||
public interface ExternalConceptService {
|
||||
|
||||
/**
|
||||
* @param term
|
||||
* @return
|
||||
*/
|
||||
List<Concept> processResults(String term) throws Exception;
|
||||
|
||||
/**
|
||||
* @param term
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
List<Concept> getConcepts(String term) throws Exception;
|
||||
|
||||
/**
|
||||
* @param uri
|
||||
* @return
|
||||
*/
|
||||
List<Concept> getConceptsByURIWithSparql(String uri) throws Exception;
|
||||
|
||||
}
|
|
@ -0,0 +1,594 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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.MalformedURLException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.rmi.RemoteException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import javax.xml.rpc.ServiceException;
|
||||
|
||||
import net.sf.json.JSONArray;
|
||||
import net.sf.json.JSONObject;
|
||||
import net.sf.json.JSONSerializer;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.fao.www.webservices.AgrovocWS.ACSWWebService;
|
||||
import org.fao.www.webservices.AgrovocWS.ACSWWebServiceServiceLocator;
|
||||
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.hp.hpl.jena.query.Query;
|
||||
import com.hp.hpl.jena.query.QueryExecution;
|
||||
import com.hp.hpl.jena.query.QueryExecutionFactory;
|
||||
import com.hp.hpl.jena.query.QueryFactory;
|
||||
import com.hp.hpl.jena.query.QuerySolution;
|
||||
import com.hp.hpl.jena.query.ResultSet;
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
import com.hp.hpl.jena.rdf.model.RDFNode;
|
||||
import com.hp.hpl.jena.rdf.model.Resource;
|
||||
|
||||
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.web.URLEncoder;
|
||||
|
||||
public class AgrovocService implements ExternalConceptService {
|
||||
|
||||
protected final Log logger = LogFactory.getLog(getClass());
|
||||
private java.lang.String AgrovocWS_address = "http://agrovoc.fao.org/axis/services/SKOSWS";
|
||||
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://aims.fao.org/skosmos/rest/v1/";
|
||||
protected final String conceptsSkosMosSearch = conceptSkosMosBase + "search?";
|
||||
protected final String conceptSkosMosURL = conceptSkosMosBase + "/agrovoc/data?";
|
||||
@Override
|
||||
public List<Concept> getConcepts(String term) throws Exception {
|
||||
List<Concept> conceptList = new ArrayList<Concept>();
|
||||
|
||||
//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<String>();
|
||||
|
||||
// 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);
|
||||
// System.out.println("description: "+ description);
|
||||
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;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
protected String getTermcodeByTerm(String term) throws Exception {
|
||||
String result = new String();
|
||||
ACSWWebServiceServiceLocator locator = new ACSWWebServiceServiceLocator();
|
||||
try {
|
||||
URL url = new URL(AgrovocWS_address);
|
||||
ACSWWebService agrovoc_service = locator.getACSWWebService(url);
|
||||
result = agrovoc_service.getTermcodeByTerm(term);
|
||||
} catch (ServiceException e) {
|
||||
logger.error("service exception", e);
|
||||
throw e;
|
||||
} catch (RemoteException e) {
|
||||
logger.error("remote exception", e);
|
||||
throw e;
|
||||
} catch (MalformedURLException e) {
|
||||
logger.error("malformed URL exception", e);
|
||||
throw e;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
protected String getTermCodeByTermAndLangXML(String ontologyName,
|
||||
String searchString, String lang, String codeName, String format) {
|
||||
String result = new String();
|
||||
ACSWWebServiceServiceLocator locator = new ACSWWebServiceServiceLocator();
|
||||
try {
|
||||
URL url = new URL(AgrovocWS_address);
|
||||
ACSWWebService agrovoc_service = locator.getACSWWebService(url);
|
||||
result = agrovoc_service.getTermCodeByTermAndLangXML(ontologyName,
|
||||
searchString, lang, codeName, format);
|
||||
} catch (ServiceException e) {
|
||||
logger.error("service exception", e);
|
||||
e.printStackTrace();
|
||||
} catch (RemoteException e) {
|
||||
e.printStackTrace();
|
||||
} catch (MalformedURLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
protected String getURIByTermAndLangXML(String ontologyName, String term,
|
||||
String searchMode, String format, String lang) {
|
||||
String result = new String();
|
||||
ACSWWebServiceServiceLocator locator = new ACSWWebServiceServiceLocator();
|
||||
try {
|
||||
URL url = new URL(AgrovocWS_address);
|
||||
ACSWWebService agrovoc_service = locator.getACSWWebService(url);
|
||||
result = agrovoc_service.getURIByTermAndLangXML(ontologyName, term,
|
||||
searchMode, format, lang);
|
||||
} catch (ServiceException e) {
|
||||
e.printStackTrace();
|
||||
} catch (RemoteException e) {
|
||||
e.printStackTrace();
|
||||
} catch (MalformedURLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Creating method for term expansion
|
||||
protected String getTermExpansion(String ontologyName, String term,
|
||||
String searchMode, String format, String lang) {
|
||||
String result = new String();
|
||||
ACSWWebServiceServiceLocator locator = new ACSWWebServiceServiceLocator();
|
||||
try {
|
||||
URL url = new URL(AgrovocWS_address);
|
||||
ACSWWebService agrovoc_service = locator.getACSWWebService(url);
|
||||
result = agrovoc_service.getTermExpansion(ontologyName, term,
|
||||
format, searchMode, lang); // the actual call has this order
|
||||
// for parameters
|
||||
} catch (ServiceException e) {
|
||||
e.printStackTrace();
|
||||
} catch (RemoteException e) {
|
||||
e.printStackTrace();
|
||||
} catch (MalformedURLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
protected String getConceptInfoByTermcodeXML(String termcode, String format) {
|
||||
String result = new String();
|
||||
ACSWWebServiceServiceLocator locator = new ACSWWebServiceServiceLocator();
|
||||
try {
|
||||
URL url = new URL(AgrovocWS_address);
|
||||
ACSWWebService agrovoc_service = locator.getACSWWebService(url);
|
||||
result = agrovoc_service.getConceptInfoByTermcodeXML(termcode,
|
||||
format);
|
||||
} catch (ServiceException e) {
|
||||
logger.error("service exception", e);
|
||||
e.printStackTrace();
|
||||
} catch (RemoteException e) {
|
||||
e.printStackTrace();
|
||||
} catch (MalformedURLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
protected String getConceptByKeyword(String ontologyName,
|
||||
String searchString, String format, String searchMode, String lang) {
|
||||
String result = new String();
|
||||
ACSWWebServiceServiceLocator locator = new ACSWWebServiceServiceLocator();
|
||||
try {
|
||||
URL url = new URL(AgrovocWS_address);
|
||||
ACSWWebService agrovoc_service = locator.getACSWWebService(url);
|
||||
result = agrovoc_service.getConceptByKeyword(ontologyName,
|
||||
searchString, format, searchMode, lang);
|
||||
} catch (ServiceException e) {
|
||||
logger.error("service exception", e);
|
||||
e.printStackTrace();
|
||||
} catch (RemoteException e) {
|
||||
e.printStackTrace();
|
||||
} catch (MalformedURLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
protected String getWsdl() {
|
||||
String result = new String();
|
||||
try {
|
||||
|
||||
StringWriter sw = new StringWriter();
|
||||
URL rss = new URL(this.AgrovocWS_address + "?wsdl");
|
||||
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(
|
||||
rss.openStream()));
|
||||
String inputLine;
|
||||
while ((inputLine = in.readLine()) != null) {
|
||||
sw.write(inputLine);
|
||||
}
|
||||
in.close();
|
||||
|
||||
result = sw.toString();
|
||||
|
||||
} catch (Exception ex) {
|
||||
logger.error("error occurred in servlet", ex);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public List<Concept> getConceptsByURIWithSparql(String uri)
|
||||
throws Exception {
|
||||
// deprecating this method...just return an empty list
|
||||
List<Concept> conceptList = new ArrayList<Concept>();
|
||||
return conceptList;
|
||||
}
|
||||
|
||||
protected String getAgrovocTermCode(String rdf) throws Exception {
|
||||
String termcode = new String();
|
||||
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 e) {
|
||||
// e.printStackTrace();
|
||||
throw e;
|
||||
} catch (ParserConfigurationException e) {
|
||||
// e.printStackTrace();
|
||||
throw e;
|
||||
} catch (IOException e) {
|
||||
// e.printStackTrace();
|
||||
throw e;
|
||||
}
|
||||
return termcode;
|
||||
}
|
||||
|
||||
protected String getConceptURIFromRDF(String rdf) {
|
||||
String conceptUri = new String();
|
||||
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 e) {
|
||||
e.printStackTrace();
|
||||
System.err.println("rdf: " + rdf);
|
||||
} catch (SAXException e) {
|
||||
e.printStackTrace();
|
||||
System.err.println("rdf: " + rdf);
|
||||
} catch (ParserConfigurationException 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<String>();
|
||||
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 e) {
|
||||
e.printStackTrace();
|
||||
System.err.println("rdf: " + rdf);
|
||||
} catch (SAXException e) {
|
||||
e.printStackTrace();
|
||||
System.err.println("rdf: " + rdf);
|
||||
} catch (ParserConfigurationException e) {
|
||||
e.printStackTrace();
|
||||
System.err.println("rdf: " + rdf);
|
||||
}
|
||||
return conceptUris;
|
||||
|
||||
}
|
||||
|
||||
protected String getDbpediaDescription(String uri) throws Exception {
|
||||
String descriptionSource = " (Source: DBpedia)";
|
||||
String description = new String();
|
||||
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<HashMap>();
|
||||
QueryExecution qexec = null;
|
||||
try {
|
||||
|
||||
Query query = QueryFactory.create(qs);
|
||||
qexec = QueryExecutionFactory.sparqlService(this.dbpedia_endpoint,
|
||||
query);
|
||||
resultList = new ArrayList<HashMap>();
|
||||
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<String, String>();
|
||||
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
|
||||
* @return
|
||||
*/
|
||||
protected String stripConceptId(String uri) {
|
||||
String conceptId = new String();
|
||||
int lastslash = uri.lastIndexOf('/');
|
||||
conceptId = uri.substring(lastslash + 1, uri.length());
|
||||
return conceptId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param str
|
||||
* @return
|
||||
*/
|
||||
protected String extractConceptId(String str) {
|
||||
try {
|
||||
return str.substring(1, str.length() - 1);
|
||||
} catch (Exception ex) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// Get concept using agrovoc service
|
||||
protected String getConceptInfoByURI(String ontologyName,
|
||||
String conceptURI, String format) {
|
||||
String result = new String();
|
||||
ACSWWebServiceServiceLocator locator = new ACSWWebServiceServiceLocator();
|
||||
try {
|
||||
URL url = new URL(AgrovocWS_address);
|
||||
ACSWWebService agrovoc_service = locator.getACSWWebService(url);
|
||||
result = agrovoc_service.getConceptByURI(ontologyName, conceptURI,
|
||||
format);
|
||||
} catch (ServiceException e) {
|
||||
logger.error("service exception", e);
|
||||
e.printStackTrace();
|
||||
} catch (RemoteException e) {
|
||||
e.printStackTrace();
|
||||
} catch (MalformedURLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<String>();
|
||||
JSONObject json = (JSONObject) JSONSerializer.toJSON(results);
|
||||
//Format should be: { ..."results":["uri":uri...]
|
||||
if (json.containsKey("results")) {
|
||||
JSONArray jsonArray = json.getJSONArray("results");
|
||||
int numberResults = jsonArray.size();
|
||||
int i;
|
||||
for(i = 0; i < numberResults; i++) {
|
||||
JSONObject jsonObject = jsonArray.getJSONObject(i);
|
||||
if(jsonObject.containsKey("uri")) {
|
||||
conceptURIs.add(jsonObject.getString("uri"));
|
||||
}
|
||||
}
|
||||
}
|
||||
return conceptURIs;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,359 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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 net.sf.json.JSONArray;
|
||||
import net.sf.json.JSONObject;
|
||||
import net.sf.json.JSONSerializer;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import edu.cornell.mannlib.semservices.bo.Concept;
|
||||
import edu.cornell.mannlib.semservices.exceptions.ConceptsNotFoundException;
|
||||
import edu.cornell.mannlib.semservices.service.ExternalConceptService;
|
||||
|
||||
public class GemetService implements ExternalConceptService {
|
||||
protected final Log logger = LogFactory.getLog(getClass());
|
||||
private final String GemetWS_address = "http://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
|
||||
* @return
|
||||
*/
|
||||
private List<Concept> processOutput(String results) throws Exception {
|
||||
|
||||
List<Concept> conceptList = new ArrayList<Concept>();
|
||||
|
||||
try {
|
||||
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( 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");
|
||||
JSONObject json = jsonArray.getJSONObject(i);
|
||||
String uri = getJsonValue(json, "uri");
|
||||
|
||||
concept.setUri(uri);
|
||||
concept.setConceptId(stripConceptId(uri));
|
||||
concept.setSchemeURI(schemeURI);
|
||||
concept.setType("");
|
||||
if (json.has("preferredLabel")) {
|
||||
JSONObject preferredLabelObj = json
|
||||
.getJSONObject("preferredLabel");
|
||||
if (preferredLabelObj.has("string")) {
|
||||
concept.setLabel(getJsonValue(preferredLabelObj,
|
||||
"string"));
|
||||
}
|
||||
}
|
||||
if (json.has("definition")) {
|
||||
JSONObject definitionObj = json.getJSONObject("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
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
protected String getJsonValue(JSONObject obj, String key) {
|
||||
if (obj.has(key)) {
|
||||
return obj.getString(key);
|
||||
} else {
|
||||
return new String("");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param concept_uri
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
protected String getAvailableLangs(String concept_uri) throws Exception {
|
||||
String result = new String();
|
||||
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
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
protected String getConcept(String concept_uri) throws Exception {
|
||||
String result = new String();
|
||||
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
|
||||
* @param property
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
protected String getAllTranslationsForConcept(String concept_uri, String property) throws Exception {
|
||||
String result = new String();
|
||||
String property_uri = new String();
|
||||
if (property.equals("definition")) {
|
||||
property_uri = definitionUri;
|
||||
} else if (property.equals("preferredLabel")) {
|
||||
property_uri = prefLabelUri;
|
||||
} else if (property.equals("scopeNote")) {
|
||||
property_uri = scopeNoteUri;
|
||||
} else if (property.equals("nonPreferredLabels")) {
|
||||
property_uri = altLabelUri;
|
||||
} else if (property.equals("example")) {
|
||||
property_uri = exampleUri;
|
||||
} else if (property.equals("acronymLabel")) {
|
||||
property_uri = acronymLabelUri;
|
||||
}
|
||||
|
||||
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
|
||||
* @param relation
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
protected String getRelatedConcepts(String concept_uri, String relation) throws Exception {
|
||||
String result = new String();
|
||||
String relation_uri = new String();
|
||||
if (relation.equals("broader")) {
|
||||
relation_uri = broaderUri;
|
||||
} else if (relation.equals("narrower")) {
|
||||
relation_uri = narrowerUri;
|
||||
} else if (relation.equals("related")) {
|
||||
relation_uri = relatedUri;
|
||||
}
|
||||
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
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
protected String getConceptsMatchingKeyword(String keyword) throws Exception {
|
||||
String result = new String();
|
||||
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
|
||||
* @return
|
||||
*/
|
||||
protected String getGemetResults(String url) throws Exception {
|
||||
String results = new String();
|
||||
//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 = new String();
|
||||
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( json );
|
||||
if (jsonArray.size() == 0) {
|
||||
return new ArrayList<String>();
|
||||
}
|
||||
for (int i = 0; i < jsonArray.size(); i++) {
|
||||
JSONObject jsonObj = jsonArray.getJSONObject(i);
|
||||
uri = getJsonValue(jsonObj, "uri");
|
||||
uriList.add(uri);
|
||||
}
|
||||
|
||||
return uriList;
|
||||
|
||||
}
|
||||
|
||||
protected List<String> getPropertyFromJson(String json) {
|
||||
List<String> props = new ArrayList<String>();
|
||||
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(json);
|
||||
if (jsonArray.size() == 0) {
|
||||
return new ArrayList<String>();
|
||||
}
|
||||
for (int i = 0; i < jsonArray.size(); i++) {
|
||||
JSONObject jsonObj = jsonArray.getJSONObject(i);
|
||||
System.out.println(jsonObj.toString());
|
||||
}
|
||||
return props;
|
||||
}
|
||||
|
||||
protected String stripConceptId(String uri) {
|
||||
String conceptId = new String();
|
||||
int lastslash = uri.lastIndexOf('/');
|
||||
conceptId = uri.substring(lastslash + 1, uri.length());
|
||||
return conceptId;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,261 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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.net.URLEncoder;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
|
||||
import net.sf.json.JSONObject;
|
||||
import net.sf.json.JSONSerializer;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
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 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;
|
||||
|
||||
public class LCSHService implements ExternalConceptService {
|
||||
|
||||
protected final Log log = LogFactory.getLog(getClass());
|
||||
private final String skosSuffix = ".skos.rdf";
|
||||
private final String hostUri = "http://id.loc.gov";
|
||||
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>();
|
||||
String results = null;
|
||||
String dataUrl = baseUri + "?q=" + URLEncoder.encode(term, "UTF-8")
|
||||
+ "&q=cs%3Ahttp%3A%2F%2Fid.loc.gov%2Fauthorities%2Fsubjects"
|
||||
+ "&format=XML";
|
||||
log.debug("dataURL " + dataUrl);
|
||||
|
||||
try {
|
||||
|
||||
StringWriter sw = new StringWriter();
|
||||
URL rss = new URL(dataUrl);
|
||||
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(
|
||||
rss.openStream()));
|
||||
String inputLine;
|
||||
while ((inputLine = in.readLine()) != null) {
|
||||
sw.write(inputLine);
|
||||
}
|
||||
in.close();
|
||||
|
||||
results = sw.toString();
|
||||
log.debug(results);
|
||||
} catch (Exception ex) {
|
||||
log.error("error occurred in servlet", ex);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (StringUtils.isEmpty(results)) {
|
||||
return conceptList;
|
||||
}
|
||||
|
||||
conceptList = processOutput(results);
|
||||
|
||||
return conceptList;
|
||||
}
|
||||
|
||||
// Results are in json format (atom) - atom entries need to be extracted
|
||||
// retrieve the URIs and get the SKOS version of the entry, getting broader
|
||||
// and narrower terms as applicable as well as any description (skos:note)
|
||||
// that might exist
|
||||
private List<Concept> processOutput(String results) throws Exception {
|
||||
List<Concept> conceptList = new ArrayList<Concept>();
|
||||
// Get uris from the results
|
||||
List<String> uris = getConceptURIFromXML(results);
|
||||
String bestMatch = "true";
|
||||
int i = 0;
|
||||
for (String uri : uris) {
|
||||
if(i > 0) {
|
||||
bestMatch = "false";
|
||||
}
|
||||
log.debug("-" + uri + "-");
|
||||
//This is the URL for retrieving the concept - the pattern is http://id.loc.gov/authorities/subjects/sh85014203.skos.rdf
|
||||
//This is not the URI itself which would be http://id.loc.gov/authorities/subjects/sh85014203
|
||||
String conceptURLString = getSKOSURL(uri);
|
||||
String baseConceptURI = getConceptURI(uri);
|
||||
URL conceptURL = null;
|
||||
try {
|
||||
conceptURL = new URL(conceptURLString);
|
||||
} catch (Exception e) {
|
||||
log.error("Error in trying to retrieve concept " + conceptURLString, e);
|
||||
return conceptList;
|
||||
}
|
||||
log.debug("loading concept uri " + conceptURLString);
|
||||
Concept c = this.createConcept(bestMatch, conceptURLString, baseConceptURI);
|
||||
if(c != null) {
|
||||
conceptList.add(c);
|
||||
}
|
||||
i++;
|
||||
|
||||
}
|
||||
return conceptList;
|
||||
}
|
||||
|
||||
|
||||
//Load individual concept using a request
|
||||
//private
|
||||
|
||||
public Concept createConcept(String bestMatch, String conceptURLString, String skosConceptURI) {
|
||||
|
||||
Concept concept = new Concept();
|
||||
|
||||
log.debug("SKOSConceptURI is " + skosConceptURI);
|
||||
// get skos version of uri
|
||||
|
||||
concept.setUri(skosConceptURI);
|
||||
concept.setConceptId(stripConceptId(skosConceptURI));
|
||||
concept.setBestMatch(bestMatch);
|
||||
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) {
|
||||
// Strip .xml at the end and replace with .skos.rdf
|
||||
String skosURI = uri;
|
||||
if (uri.endsWith(".xml")) {
|
||||
skosURI = uri.substring(0, uri.length() - 4);
|
||||
skosURI += skosSuffix;
|
||||
}
|
||||
return hostUri + skosURI;
|
||||
}
|
||||
|
||||
//Given the URI from the xml, get just the base URI
|
||||
private String getConceptURI(String uri) {
|
||||
String skosURI = uri;
|
||||
if (uri.endsWith(".xml")) {
|
||||
skosURI = uri.substring(0, uri.length() - 4);
|
||||
}
|
||||
return hostUri + skosURI;
|
||||
}
|
||||
|
||||
public List<String> getConceptURISFromJSON(String results) {
|
||||
List<String> uris = new ArrayList<String>();
|
||||
try {
|
||||
JSONObject json = (JSONObject) JSONSerializer.toJSON(results);
|
||||
log.debug(json.toString());
|
||||
// Get atom entry elements
|
||||
|
||||
} catch (Exception ex) {
|
||||
log.error("Could not get concepts", ex);
|
||||
throw ex;
|
||||
}
|
||||
return uris;
|
||||
|
||||
}
|
||||
|
||||
protected List<String> getConceptURIFromXML(String rdf) {
|
||||
List<String> uris = new ArrayList<String>();
|
||||
String conceptUri = new String();
|
||||
try {
|
||||
Document doc = XMLUtils.parse(rdf);
|
||||
NodeList nodes = doc.getElementsByTagName("search:result");
|
||||
int len = nodes.getLength();
|
||||
int i;
|
||||
for (i = 0; i < len; i++) {
|
||||
Node node = nodes.item(i);
|
||||
NamedNodeMap attrs = node.getAttributes();
|
||||
Attr idAttr = (Attr) attrs.getNamedItem("uri");
|
||||
conceptUri = idAttr.getTextContent();
|
||||
log.debug("concept uri is " + conceptUri);
|
||||
uris.add(conceptUri);
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
log.error("error occurred in parsing " +rdf, e);
|
||||
} catch (SAXException e) {
|
||||
log.error("error occurred in parsing " +rdf, e);
|
||||
} catch (ParserConfigurationException e) {
|
||||
log.error("error occurred in parsing " +rdf, e);
|
||||
|
||||
}
|
||||
return uris;
|
||||
|
||||
}
|
||||
|
||||
public List<Concept> processResults(String term) throws Exception {
|
||||
return getConcepts(term);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param uri
|
||||
* @return
|
||||
*/
|
||||
protected String stripConceptId(String uri) {
|
||||
String conceptId = new String();
|
||||
int lastslash = uri.lastIndexOf('/');
|
||||
conceptId = uri.substring(lastslash + 1, uri.length());
|
||||
return conceptId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param str
|
||||
* @return
|
||||
*/
|
||||
protected String extractConceptId(String str) {
|
||||
try {
|
||||
return str.substring(1, str.length() - 1);
|
||||
} catch (Exception ex) {
|
||||
log.error("Exception occurred in extracting concept id for " + str, ex);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Concept> getConceptsByURIWithSparql(String uri)
|
||||
throws Exception {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,217 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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 net.sf.json.JSONArray;
|
||||
import net.sf.json.JSONObject;
|
||||
import net.sf.json.JSONSerializer;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import edu.cornell.mannlib.semservices.bo.Concept;
|
||||
import edu.cornell.mannlib.semservices.exceptions.ConceptsNotFoundException;
|
||||
import edu.cornell.mannlib.semservices.service.ExternalConceptService;
|
||||
|
||||
/**
|
||||
* @author jaf30
|
||||
*
|
||||
*/
|
||||
public class UMLSService implements ExternalConceptService {
|
||||
protected final Log logger = LogFactory.getLog(getClass());
|
||||
private static final String submissionUrl = "http://link.informatics.stonybrook.edu/MeaningLookup/MlServiceServlet?";
|
||||
private static final String baseUri = "http://link.informatics.stonybrook.edu/umls/CUI/";
|
||||
private static final String endpoint = "http://link.informatics.stonybrook.edu/sparql/";
|
||||
private static final String schemeURI = "http://link.informatics.stonybrook.edu/umls";
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public List<Concept> getConcepts(String term) throws Exception {
|
||||
List<Concept> conceptList = new ArrayList<Concept>();
|
||||
|
||||
String results = null;
|
||||
String dataUrl = submissionUrl + "textToProcess="
|
||||
+ URLEncoder.encode(term, "UTF-8")
|
||||
+ "&format=json";
|
||||
|
||||
try {
|
||||
|
||||
StringWriter sw = new StringWriter();
|
||||
URL rss = new URL(dataUrl);
|
||||
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(
|
||||
rss.openStream()));
|
||||
String inputLine;
|
||||
while ((inputLine = in.readLine()) != null) {
|
||||
sw.write(inputLine);
|
||||
}
|
||||
in.close();
|
||||
|
||||
results = sw.toString();
|
||||
//System.out.println("results before processing: "+results);
|
||||
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 {
|
||||
String results = null;
|
||||
String dataUrl = submissionUrl + "textToProcess="
|
||||
+ URLEncoder.encode(term, "UTF-8") + "&format=json";
|
||||
|
||||
try {
|
||||
|
||||
StringWriter sw = new StringWriter();
|
||||
URL rss = new URL(dataUrl);
|
||||
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(rss.openStream()));
|
||||
String inputLine;
|
||||
while ((inputLine = in.readLine()) != null) {
|
||||
sw.write(inputLine);
|
||||
}
|
||||
in.close();
|
||||
|
||||
results = sw.toString();
|
||||
//System.out.println("results before processing: "+results);
|
||||
List<Concept> conceptList = processOutput(results);
|
||||
return conceptList;
|
||||
|
||||
} catch (Exception ex) {
|
||||
logger.error("error occurred in servlet", ex);
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param uri
|
||||
* @return
|
||||
*/
|
||||
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
|
||||
* @return
|
||||
*/
|
||||
private List<Concept> processOutput(String results) throws Exception {
|
||||
|
||||
List<Concept> conceptList = new ArrayList<Concept>();
|
||||
List<String> bestMatchIdList = new ArrayList<String>();
|
||||
String bestMatchId = new String();
|
||||
boolean bestMatchFound = false;
|
||||
boolean allFound = false;
|
||||
|
||||
try {
|
||||
JSONObject json = (JSONObject) JSONSerializer.toJSON( results );
|
||||
//System.out.println(json.toString());
|
||||
if (json.has("Best Match")) {
|
||||
bestMatchFound = true;
|
||||
//System.out.println("Best Match");
|
||||
|
||||
JSONArray bestMatchArray = json.getJSONArray("Best Match");
|
||||
int len = bestMatchArray.size();
|
||||
if (len > 1) {
|
||||
logger.debug("Found this many best matches: "+ len);
|
||||
}
|
||||
int i;
|
||||
for (i = 0; i < len; i++) {
|
||||
JSONObject o = bestMatchArray.getJSONObject(i);
|
||||
//System.out.println(o.toString());
|
||||
Concept concept = new Concept();
|
||||
concept.setDefinedBy(schemeURI);
|
||||
concept.setBestMatch("true");
|
||||
String cui = getJsonValue(o, "CUI");
|
||||
bestMatchIdList.add(cui);
|
||||
|
||||
concept.setConceptId(cui);
|
||||
concept.setLabel(getJsonValue(o, "label"));
|
||||
concept.setType(getJsonValue(o, "type"));
|
||||
concept.setDefinition(getJsonValue(o, "definition"));
|
||||
concept.setUri(baseUri + cui);
|
||||
concept.setSchemeURI(schemeURI);
|
||||
conceptList.add(concept);
|
||||
}
|
||||
}
|
||||
if (json.has("All")) {
|
||||
allFound = true;
|
||||
JSONArray allArray = json.getJSONArray("All");
|
||||
int len = allArray.size();
|
||||
//System.out.println("size of best match array: "+ len);
|
||||
int i;
|
||||
for (i = 0; i < len; i++) {
|
||||
JSONObject o = allArray.getJSONObject(i);
|
||||
//System.out.println(o.toString());
|
||||
Concept concept = new Concept();
|
||||
concept.setDefinedBy(schemeURI);
|
||||
String cui = getJsonValue(o, "CUI");
|
||||
concept.setConceptId(cui);
|
||||
|
||||
concept.setLabel(getJsonValue(o, "label"));
|
||||
concept.setType(getJsonValue(o, "type"));
|
||||
concept.setDefinition(getJsonValue(o, "definition"));
|
||||
concept.setUri(baseUri + cui);
|
||||
concept.setSchemeURI(schemeURI);
|
||||
// prevent duplicate concepts in list
|
||||
if (! bestMatchIdList.contains(cui)) {
|
||||
concept.setBestMatch("false");
|
||||
conceptList.add(concept);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception ex ) {
|
||||
ex.printStackTrace();
|
||||
logger.error("Could not get concepts", ex);
|
||||
throw ex;
|
||||
}
|
||||
if (! bestMatchFound && !allFound) {
|
||||
// we did not get a bestMatch or All element
|
||||
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
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
protected String getJsonValue(JSONObject obj, String key) {
|
||||
if (obj.has(key)) {
|
||||
return obj.getString(key);
|
||||
} else {
|
||||
return new String("");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
protected String stripConceptId(String uri) {
|
||||
String conceptId = new String();
|
||||
int lastslash = uri.lastIndexOf('/');
|
||||
conceptId = uri.substring(lastslash + 1, uri.length());
|
||||
return conceptId;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.semservices.util;
|
||||
import java.util.Iterator;
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.namespace.NamespaceContext;
|
||||
|
||||
public class MetadataNamespaceContext implements NamespaceContext {
|
||||
public String getNamespaceURI(String prefix) {
|
||||
if (prefix == null) throw new NullPointerException("Null prefix");
|
||||
else if ("mix".equals(prefix)) return "http://www.loc.gov/mix/";
|
||||
else if ("xml".equals(prefix)) return XMLConstants.XML_NS_URI;
|
||||
return XMLConstants.NULL_NS_URI;
|
||||
}
|
||||
|
||||
// This method isn't necessary for XPath processing.
|
||||
public String getPrefix(String uri) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
// This method isn't necessary for XPath processing either.
|
||||
public Iterator getPrefixes(String uri) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,266 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
/* We are no longer using the SKOS API since Vitro has moved to V 4.0 of OWL API which does not appear to be compatible.
|
||||
This file will contain methods used for reading SKOS as XML and parsing it for the properties
|
||||
we want to extract*/
|
||||
|
||||
package edu.cornell.mannlib.semservices.util;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.StringReader;
|
||||
import java.io.StringWriter;
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.rdf.model.Model;
|
||||
import com.hp.hpl.jena.rdf.model.ModelFactory;
|
||||
import com.hp.hpl.jena.rdf.model.NodeIterator;
|
||||
import com.hp.hpl.jena.rdf.model.RDFNode;
|
||||
import com.hp.hpl.jena.rdf.model.ResourceFactory;
|
||||
import com.hp.hpl.jena.rdf.model.Statement;
|
||||
import com.hp.hpl.jena.rdf.model.StmtIterator;
|
||||
|
||||
import edu.cornell.mannlib.semservices.bo.Concept;
|
||||
|
||||
public class SKOSUtils {
|
||||
protected final static Log log = LogFactory.getLog(SKOSUtils.class);
|
||||
|
||||
public static String getConceptXML(String conceptUriString) {
|
||||
URL conceptURL = null;
|
||||
try {
|
||||
conceptURL = new URL(conceptUriString);
|
||||
} catch (Exception e) {
|
||||
log.error("Exception occurred in instantiating URL for "
|
||||
+ conceptUriString, e);
|
||||
// If the url is having trouble, just return null for the concept
|
||||
return null;
|
||||
}
|
||||
log.debug("loading concept uri " + conceptUriString);
|
||||
|
||||
String results = null;
|
||||
try {
|
||||
|
||||
StringWriter sw = new StringWriter();
|
||||
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(
|
||||
conceptURL.openStream()));
|
||||
String inputLine;
|
||||
while ((inputLine = in.readLine()) != null) {
|
||||
sw.write(inputLine);
|
||||
}
|
||||
in.close();
|
||||
|
||||
results = sw.toString();
|
||||
log.debug(results);
|
||||
} catch (Exception ex) {
|
||||
log.error("Error occurred in getting concept from the URL "
|
||||
+ conceptUriString, ex);
|
||||
return null;
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
// Downloading the XML from the URI itself
|
||||
// No language tag support here but can be specified if need be at this
|
||||
// level as well
|
||||
public static Concept createConceptUsingXMLFromURL(Concept concept,
|
||||
String conceptURLString, String langTagValue, boolean addNotes) {
|
||||
String results = getConceptXML(conceptURLString);
|
||||
if (StringUtils.isEmpty(results)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// return createConceptUsingXML(concept, results, langTagValue);
|
||||
return createConceptUsingXMLModel(concept, results, langTagValue,
|
||||
addNotes);
|
||||
|
||||
}
|
||||
|
||||
// Because of the fact the xml returns matches by tag name, and the XML may
|
||||
// look like <skos:narrower><skos:Concept ..><skos:broader
|
||||
// rdf:resource:"conceptURI">
|
||||
// where conceptURI is the concept that is the subject of skos:narrower, we
|
||||
// need to ensure we are not returning the same uri as that of the main
|
||||
// concept
|
||||
public static List<String> removeConceptURIFromList(List<String> uris,
|
||||
String conceptURI) {
|
||||
// remove will return a boolean if the value exists in the list and is
|
||||
// removed
|
||||
// if/when it returns false, the URI is not in the list
|
||||
while (uris.remove(conceptURI)) {
|
||||
}
|
||||
;
|
||||
return uris;
|
||||
}
|
||||
|
||||
/**
|
||||
* The above code, although functional, does not take advantage of the fact
|
||||
* that we can actually read and query the RDF in precisely the manner we
|
||||
* wish.
|
||||
*/
|
||||
|
||||
public static Concept createConceptUsingXMLModel(Concept concept,
|
||||
String results, String langTagValue, boolean addNotes) {
|
||||
|
||||
try {
|
||||
String conceptURI = concept.getUri();
|
||||
|
||||
// Load Model from RDF
|
||||
StringReader reader = new StringReader(results);
|
||||
Model model = ModelFactory.createDefaultModel();
|
||||
model.read(reader, null, "RDF/XML");
|
||||
|
||||
// Execute the following query to get the information we want for
|
||||
// this resource
|
||||
|
||||
// Preferred label
|
||||
List<String> labelLiterals = getPrefLabelsFromModel(conceptURI,
|
||||
model, langTagValue);
|
||||
if (labelLiterals.size() > 0) {
|
||||
concept.setLabel(labelLiterals.get(0));
|
||||
} else {
|
||||
// This is an error because there should be at least one label
|
||||
// returned
|
||||
log.debug("The number of preferred labels is not greater than zero");
|
||||
}
|
||||
|
||||
// Alternate label
|
||||
|
||||
List<String> altLabelList = getAltLabelsFromModel(conceptURI,
|
||||
model, langTagValue);
|
||||
concept.setAltLabelList(altLabelList);
|
||||
|
||||
// Broder, narrower, exact match, and close match properties
|
||||
|
||||
List<String> broaderURIList = getBroaderURIsFromModel(conceptURI,
|
||||
model);
|
||||
// broaderURIList = removeConceptURIFromList(broaderURIList,
|
||||
// conceptURI);
|
||||
concept.setBroaderURIList(broaderURIList);
|
||||
List<String> narrowerURIList = getNarrowerURIsFromModel(conceptURI,
|
||||
model);
|
||||
// narrowerURIList = removeConceptURIFromList(narrowerURIList,
|
||||
// conceptURI);
|
||||
concept.setNarrowerURIList(narrowerURIList);
|
||||
|
||||
List<String> exactMatchURIList = getExactMatchURIsFromModel(
|
||||
conceptURI, model);
|
||||
// exactMatchURIList = removeConceptURIFromList(exactMatchURIList,
|
||||
// conceptURI);
|
||||
concept.setExactMatchURIList(exactMatchURIList);
|
||||
List<String> closeMatchURIList = getCloseMatchURIsFromModel(
|
||||
conceptURI, model);
|
||||
// closeMatchURIList = removeConceptURIFromList(closeMatchURIList,
|
||||
// conceptURI);
|
||||
concept.setCloseMatchURIList(closeMatchURIList);
|
||||
|
||||
// Notes may exist, in which case they should be employed
|
||||
if (addNotes) {
|
||||
List<String> notes = getNotesFromModel(conceptURI, model,
|
||||
langTagValue);
|
||||
if (notes.size() > 0) {
|
||||
concept.setDefinition(notes.get(0));
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("error occurred in parsing " + results, e);
|
||||
}
|
||||
|
||||
return concept;
|
||||
|
||||
}
|
||||
|
||||
private static List<String> getPrefLabelsFromModel(String conceptURI,
|
||||
Model model, String langTagValue) {
|
||||
String propertyURI = "http://www.w3.org/2004/02/skos/core#prefLabel";
|
||||
return getLabelsFromModel(conceptURI, propertyURI, model, langTagValue);
|
||||
}
|
||||
|
||||
private static List<String> getAltLabelsFromModel(String conceptURI,
|
||||
Model model, String langTagValue) {
|
||||
String propertyURI = "http://www.w3.org/2004/02/skos/core#altLabel";
|
||||
return getLabelsFromModel(conceptURI, propertyURI, model, langTagValue);
|
||||
}
|
||||
|
||||
private static List<String> getLabelsFromModel(String conceptURI,
|
||||
String propertyURI, Model model, String langTagValue) {
|
||||
List<String> labels = new ArrayList<String>();
|
||||
StmtIterator statements = model.listStatements(
|
||||
ResourceFactory.createResource(conceptURI),
|
||||
ResourceFactory.createProperty(propertyURI), (RDFNode) null);
|
||||
while (statements.hasNext()) {
|
||||
Statement statement = statements.nextStatement();
|
||||
RDFNode node = statement.getObject();
|
||||
if (node != null && node.isLiteral()) {
|
||||
String label = node.asLiteral().getString();
|
||||
if (StringUtils.isNotEmpty(langTagValue)) {
|
||||
String language = node.asLiteral().getLanguage();
|
||||
if (language != null && language.equals(langTagValue)) {
|
||||
labels.add(label);
|
||||
}
|
||||
} else {
|
||||
labels.add(label);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return labels;
|
||||
}
|
||||
|
||||
private static List<String> getNotesFromModel(String conceptURI,
|
||||
Model model, String langTagValue) {
|
||||
String propertyURI = "http://www.w3.org/2004/02/skos/core#note";
|
||||
return getLabelsFromModel(conceptURI, propertyURI, model, langTagValue);
|
||||
}
|
||||
|
||||
private static List<String> getCloseMatchURIsFromModel(String conceptURI,
|
||||
Model model) {
|
||||
String propertyURI = "http://www.w3.org/2004/02/skos/core#closeMatch";
|
||||
return getRelatedURIsFromModel(conceptURI, propertyURI, model);
|
||||
|
||||
}
|
||||
|
||||
private static List<String> getExactMatchURIsFromModel(String conceptURI,
|
||||
Model model) {
|
||||
String propertyURI = "http://www.w3.org/2004/02/skos/core#exactMatch";
|
||||
return getRelatedURIsFromModel(conceptURI, propertyURI, model);
|
||||
}
|
||||
|
||||
private static List<String> getNarrowerURIsFromModel(String conceptURI,
|
||||
Model model) {
|
||||
String propertyURI = "http://www.w3.org/2004/02/skos/core#narrower";
|
||||
return getRelatedURIsFromModel(conceptURI, propertyURI, model);
|
||||
}
|
||||
|
||||
private static List<String> getBroaderURIsFromModel(String conceptURI,
|
||||
Model model) {
|
||||
String propertyURI = "http://www.w3.org/2004/02/skos/core#broader";
|
||||
return getRelatedURIsFromModel(conceptURI, propertyURI, model);
|
||||
}
|
||||
|
||||
private static List<String> getRelatedURIsFromModel(String conceptURI,
|
||||
String propertyURI, Model model) {
|
||||
List<String> URIs = new ArrayList<String>();
|
||||
NodeIterator nodeIterator = model.listObjectsOfProperty(
|
||||
ResourceFactory.createResource(conceptURI),
|
||||
ResourceFactory.createProperty(propertyURI));
|
||||
|
||||
while (nodeIterator.hasNext()) {
|
||||
RDFNode node = nodeIterator.nextNode();
|
||||
if (node.isResource() && node.asResource().getURI() != null) {
|
||||
String URI = node.asResource().getURI();
|
||||
URIs.add(URI);
|
||||
}
|
||||
}
|
||||
|
||||
return URIs;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,365 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.semservices.util;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.StringReader;
|
||||
import java.io.StringWriter;
|
||||
import java.io.Writer;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import javax.xml.transform.OutputKeys;
|
||||
import javax.xml.transform.Source;
|
||||
import javax.xml.transform.Transformer;
|
||||
import javax.xml.transform.TransformerConfigurationException;
|
||||
import javax.xml.transform.TransformerException;
|
||||
import javax.xml.transform.TransformerFactory;
|
||||
import javax.xml.transform.TransformerFactoryConfigurationError;
|
||||
import javax.xml.transform.stream.StreamResult;
|
||||
import javax.xml.transform.stream.StreamSource;
|
||||
import javax.xml.xpath.XPath;
|
||||
import javax.xml.xpath.XPathConstants;
|
||||
import javax.xml.xpath.XPathExpressionException;
|
||||
import javax.xml.xpath.XPathFactory;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.DocumentType;
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
import org.xml.sax.InputSource;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
/**
|
||||
* Convenience Class to parse XML strings to DOM Document for XML contents
|
||||
* retrieval.
|
||||
*/
|
||||
public class XMLUtils {
|
||||
private static DocumentBuilder parser;
|
||||
public static Writer writer;
|
||||
static private String indent = "";
|
||||
protected static final Log logger = LogFactory.getLog(XMLUtils.class);
|
||||
|
||||
|
||||
/**
|
||||
* @return
|
||||
* @throws ParserConfigurationException
|
||||
*/
|
||||
public static DocumentBuilder getDocumentBuilder()
|
||||
throws ParserConfigurationException {
|
||||
if (parser == null) {
|
||||
// JPT: Remove xerces use
|
||||
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
|
||||
.newInstance();
|
||||
documentBuilderFactory.setNamespaceAware(true);
|
||||
documentBuilderFactory.setValidating(false);
|
||||
parser = documentBuilderFactory.newDocumentBuilder();
|
||||
}
|
||||
|
||||
return parser;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param xmlString
|
||||
* @return
|
||||
* @throws IOException
|
||||
* @throws SAXException
|
||||
* @throws ParserConfigurationException
|
||||
*/
|
||||
public synchronized static Document parse(String xmlString)
|
||||
throws IOException, SAXException, ParserConfigurationException {
|
||||
StringReader reader = new StringReader(xmlString);
|
||||
InputSource inputSource = new InputSource(reader);
|
||||
return getDocumentBuilder().parse(inputSource);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param stream
|
||||
* @return
|
||||
* @throws IOException
|
||||
* @throws SAXException
|
||||
* @throws ParserConfigurationException
|
||||
*/
|
||||
public synchronized static Document parse(InputStream stream)
|
||||
throws IOException, SAXException, ParserConfigurationException {
|
||||
return getDocumentBuilder().parse(stream);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param document
|
||||
* @param name
|
||||
* @return
|
||||
*/
|
||||
public static String getElementByName(Document document, String name) {
|
||||
NodeList nodes = document.getElementsByTagName(name);
|
||||
String s = null;
|
||||
for (int i=0; i < nodes.getLength() ; i++) {
|
||||
Node node = nodes.item(i);
|
||||
s = node.getTextContent().trim();
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param doc
|
||||
* @throws IOException
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
public static void serializeDoc(Document doc) throws IOException {
|
||||
org.apache.xml.serialize.XMLSerializer serializer = new org.apache.xml.serialize.XMLSerializer();
|
||||
serializer.setOutputByteStream(System.out);
|
||||
serializer.serialize(doc);
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static String serializeDoctoString(Document doc) throws IOException {
|
||||
org.apache.xml.serialize.XMLSerializer serializer = new org.apache.xml.serialize.XMLSerializer();
|
||||
ByteArrayOutputStream bout = new ByteArrayOutputStream();
|
||||
|
||||
serializer.setOutputByteStream(bout);
|
||||
serializer.serialize(doc);
|
||||
return bout.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param xml
|
||||
*/
|
||||
public static void prettyPrint(String xml) {
|
||||
Source xmlInput = new StreamSource(new StringReader(xml));
|
||||
StreamResult xmlOutput = new StreamResult(new StringWriter());
|
||||
Transformer transformer = null;
|
||||
try {
|
||||
transformer = TransformerFactory.newInstance().newTransformer();
|
||||
} catch (TransformerConfigurationException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
} catch (TransformerFactoryConfigurationError e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
//transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "testing.dtd");
|
||||
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
||||
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
|
||||
try {
|
||||
transformer.transform(xmlInput, xmlOutput);
|
||||
} catch (TransformerException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
String formattedxml=xmlOutput.getWriter().toString();
|
||||
System.out.println(formattedxml);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param xml
|
||||
*/
|
||||
public static String prettyPrintToString(String xml) {
|
||||
Source xmlInput = new StreamSource(new StringReader(xml));
|
||||
StreamResult xmlOutput = new StreamResult(new StringWriter());
|
||||
Transformer transformer = null;
|
||||
try {
|
||||
transformer = TransformerFactory.newInstance().newTransformer();
|
||||
} catch (TransformerConfigurationException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
} catch (TransformerFactoryConfigurationError e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
//transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "testing.dtd");
|
||||
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
||||
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
|
||||
try {
|
||||
transformer.transform(xmlInput, xmlOutput);
|
||||
} catch (TransformerException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
String formattedxml=xmlOutput.getWriter().toString();
|
||||
return formattedxml;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param node
|
||||
*/
|
||||
public static void displayNodeInfo(Node node) {
|
||||
switch (node.getNodeType()) {
|
||||
case Node.DOCUMENT_NODE:
|
||||
System.out.println("Document Node ");
|
||||
break;
|
||||
case Node.ELEMENT_NODE:
|
||||
System.out.println("Element Node: "+ node.getNodeName());
|
||||
break;
|
||||
case Node.TEXT_NODE:
|
||||
System.out.println("Text Node: "+ node.getNodeName());
|
||||
break;
|
||||
case Node.CDATA_SECTION_NODE:
|
||||
System.out.println("CDATA Section Node: ");
|
||||
break;
|
||||
case Node.COMMENT_NODE:
|
||||
System.out.println("Comment Node ");
|
||||
break;
|
||||
case Node.PROCESSING_INSTRUCTION_NODE:
|
||||
System.out.println("Processing Instruction Node ");
|
||||
break;
|
||||
case Node.ENTITY_REFERENCE_NODE:
|
||||
System.out.println("Entity Reference Node ");
|
||||
break;
|
||||
case Node.DOCUMENT_TYPE_NODE:
|
||||
System.out.println("Document Type Node ");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param node
|
||||
* @throws IOException
|
||||
*/
|
||||
public static void serializeNode(Node node) throws IOException {
|
||||
if (writer == null) writer = new BufferedWriter(new OutputStreamWriter(System.out));
|
||||
|
||||
switch (node.getNodeType()) {
|
||||
case Node.DOCUMENT_NODE:
|
||||
Document doc = (Document) node;
|
||||
writer.write("<?xml version=\"");
|
||||
writer.write(doc.getXmlVersion());
|
||||
writer.write("\" encoding=\"UTF-8\" standalone=\"");
|
||||
if (doc.getXmlStandalone())
|
||||
writer.write("yes");
|
||||
else
|
||||
writer.write("no");
|
||||
writer.write("\"?>\n");
|
||||
|
||||
NodeList nodes = node.getChildNodes();
|
||||
if (nodes != null)
|
||||
for (int i = 0; i < nodes.getLength(); i++)
|
||||
serializeNode(nodes.item(i));
|
||||
break;
|
||||
case Node.ELEMENT_NODE:
|
||||
String name = node.getNodeName();
|
||||
writer.write("<" + name);
|
||||
NamedNodeMap attributes = node.getAttributes();
|
||||
for (int i = 0; i < attributes.getLength(); i++) {
|
||||
Node current = attributes.item(i);
|
||||
writer.write(" " + current.getNodeName() + "=\"");
|
||||
print(current.getNodeValue());
|
||||
writer.write("\"");
|
||||
}
|
||||
writer.write(">");
|
||||
|
||||
NodeList children = node.getChildNodes();
|
||||
if (children != null) {
|
||||
//if ((children.item(0) != null) && (children.item(0).getNodeType() == Node.ELEMENT_NODE))
|
||||
// writer.write("\n");
|
||||
|
||||
for (int i = 0; i < children.getLength(); i++)
|
||||
serializeNode(children.item(i));
|
||||
if ((children.item(0) != null)
|
||||
&& (children.item(children.getLength() - 1).getNodeType() == Node.ELEMENT_NODE))
|
||||
writer.write("");
|
||||
}
|
||||
|
||||
writer.write("</" + name + ">");
|
||||
break;
|
||||
case Node.TEXT_NODE:
|
||||
print(node.getNodeValue());
|
||||
break;
|
||||
case Node.CDATA_SECTION_NODE:
|
||||
writer.write("CDATA");
|
||||
print(node.getNodeValue());
|
||||
writer.write("");
|
||||
break;
|
||||
case Node.COMMENT_NODE:
|
||||
writer.write("<!-- " + node.getNodeValue() + " -->\n");
|
||||
break;
|
||||
case Node.PROCESSING_INSTRUCTION_NODE:
|
||||
writer.write("<?" + node.getNodeName() + " " + node.getNodeValue() + "?>\n");
|
||||
break;
|
||||
case Node.ENTITY_REFERENCE_NODE:
|
||||
writer.write("&" + node.getNodeName() + ";");
|
||||
break;
|
||||
case Node.DOCUMENT_TYPE_NODE:
|
||||
DocumentType docType = (DocumentType) node;
|
||||
String publicId = docType.getPublicId();
|
||||
String systemId = docType.getSystemId();
|
||||
String internalSubset = docType.getInternalSubset();
|
||||
writer.write("<!DOCTYPE " + docType.getName());
|
||||
if (publicId != null)
|
||||
writer.write(" PUBLIC \"" + publicId + "\" ");
|
||||
else
|
||||
writer.write(" SYSTEM ");
|
||||
writer.write("\"" + systemId + "\"");
|
||||
if (internalSubset != null)
|
||||
writer.write(" [" + internalSubset + "]");
|
||||
writer.write(">\n");
|
||||
break;
|
||||
}
|
||||
writer.flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param s
|
||||
* @throws IOException
|
||||
*/
|
||||
private static void print(String s) throws IOException {
|
||||
if (s == null)
|
||||
return;
|
||||
for (int i = 0, len = s.length(); i < len; i++) {
|
||||
char c = s.charAt(i);
|
||||
switch (c) {
|
||||
case '<':
|
||||
writer.write("<");
|
||||
break;
|
||||
case '>':
|
||||
writer.write(">");
|
||||
break;
|
||||
case '&':
|
||||
writer.write("&");
|
||||
break;
|
||||
case '\r':
|
||||
writer.write("
");
|
||||
break;
|
||||
default:
|
||||
writer.write(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param doc (either a Document or a Node)
|
||||
* @param expression
|
||||
* @return string contents
|
||||
*/
|
||||
public static Node getNodeWithXpath(Object obj, String expression) {
|
||||
Object root = null;
|
||||
if (obj instanceof Document) {
|
||||
Document doc = (Document) obj;
|
||||
root = doc.getDocumentElement();
|
||||
} else {
|
||||
root = (Node) obj;
|
||||
}
|
||||
|
||||
XPath xpath = XPathFactory.newInstance().newXPath();
|
||||
xpath.setNamespaceContext(new MetadataNamespaceContext());
|
||||
Node result = null;
|
||||
|
||||
try {
|
||||
result = ((Node) xpath.evaluate(expression, root, XPathConstants.NODE));
|
||||
return result;
|
||||
} catch (XPathExpressionException e) {
|
||||
logger.error("XPathExpressionException ", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
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.controller.freemarker.FreemarkerHttpServlet;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ExceptionResponseValues;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
|
||||
|
||||
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";
|
||||
|
||||
@Override
|
||||
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);
|
||||
return new ExceptionResponseValues(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getTitle(String siteName, VitroRequest vreq) {
|
||||
return "About QR Codes";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,162 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.query.QuerySolution;
|
||||
import com.hp.hpl.jena.query.ResultSet;
|
||||
import com.hp.hpl.jena.rdf.model.RDFNode;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerHttpServlet;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ExceptionResponseValues;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.individual.IndividualRequestAnalysisContextImpl;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.individual.IndividualRequestAnalyzer;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.individual.IndividualRequestInfo;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.jena.QueryUtils;
|
||||
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.IndividualTemplateModel;
|
||||
import freemarker.ext.beans.BeansWrapper;
|
||||
import freemarker.template.DefaultObjectWrapper;
|
||||
|
||||
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";
|
||||
private static String VCARD_DATA_QUERY = ""
|
||||
+ "PREFIX obo: <http://purl.obolibrary.org/obo/> \n"
|
||||
+ "PREFIX vcard: <http://www.w3.org/2006/vcard/ns#> \n"
|
||||
+ "SELECT DISTINCT ?firstName ?lastName ?email ?phone ?title \n"
|
||||
+ "WHERE { \n"
|
||||
+ " ?subject obo:ARG_2000028 ?vIndividual . \n"
|
||||
+ " ?vIndividual vcard:hasName ?vName . \n"
|
||||
+ " ?vName vcard:givenName ?firstName . \n"
|
||||
+ " ?vName vcard:familyName ?lastName . \n"
|
||||
+ " OPTIONAL { ?vIndividual vcard:hasEmail ?vEmail . \n"
|
||||
+ " ?vEmail vcard:email ?email . \n"
|
||||
+ " } \n"
|
||||
+ " OPTIONAL { ?vIndividual vcard:hasTelephone ?vPhone . \n"
|
||||
+ " ?vPhone vcard:telephone ?phone . \n"
|
||||
+ " } \n"
|
||||
+ " OPTIONAL { ?vIndividual vcard:hasTitle ?vTitle . \n"
|
||||
+ " ?vTitle vcard:title ?title . \n"
|
||||
+ " } \n"
|
||||
+ "} " ;
|
||||
private List<Map<String,String>> vcardData;
|
||||
private Map<String, String> qrData = null;
|
||||
|
||||
@Override
|
||||
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(new IndividualTemplateModel(individual, vreq)));
|
||||
body.put("qrData", qrData);
|
||||
return new TemplateResponseValues(TEMPLATE_DEFAULT, body);
|
||||
} catch (Throwable e) {
|
||||
log.error(e, e);
|
||||
return new ExceptionResponseValues(e);
|
||||
}
|
||||
}
|
||||
|
||||
private Individual getIndividualFromRequest(VitroRequest vreq) {
|
||||
IndividualRequestInfo requestInfo = new IndividualRequestAnalyzer(vreq,
|
||||
new IndividualRequestAnalysisContextImpl(vreq)).analyze();
|
||||
return requestInfo.getIndividual();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getTitle(String siteName, VitroRequest vreq) {
|
||||
try {
|
||||
return "Export QR Code for " + getIndividualFromRequest(vreq).getRdfsLabel();
|
||||
} catch (Throwable e) {
|
||||
log.error(e, e);
|
||||
return "There was an error in the system. The individual could not be found";
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, String> generateQrData(Individual individual, VitroRequest vreq) {
|
||||
|
||||
try {
|
||||
String firstName = "";
|
||||
String lastName = "";
|
||||
String preferredTitle = "";
|
||||
String phoneNumber = "";
|
||||
String email = "";
|
||||
|
||||
vcardData = getVcardData(individual, vreq);
|
||||
|
||||
Map<String,String> qrData = new HashMap<String,String>();
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
if(firstName != null && firstName.length() > 0)
|
||||
qrData.put("firstName", firstName);
|
||||
if(lastName != null && lastName.length() > 0)
|
||||
qrData.put("lastName", lastName);
|
||||
if(preferredTitle != null && preferredTitle.length() > 0)
|
||||
qrData.put("preferredTitle", preferredTitle);
|
||||
if(phoneNumber != null && phoneNumber.length() > 0)
|
||||
qrData.put("phoneNumber", phoneNumber);
|
||||
if(email != null && email.length() > 0)
|
||||
qrData.put("email", email);
|
||||
|
||||
String tempUrl = vreq.getRequestURL().toString();
|
||||
String prefix = "http://";
|
||||
tempUrl = tempUrl.substring(0, tempUrl.replace(prefix, "").indexOf("/") + prefix.length());
|
||||
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) {
|
||||
log.error("Failed getting QR code data", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private List<Map<String,String>> getVcardData(Individual individual, VitroRequest vreq) {
|
||||
String queryStr = QueryUtils.subUriForQueryVar(VCARD_DATA_QUERY, "subject", individual.getURI());
|
||||
log.debug("queryStr = " + queryStr);
|
||||
List<Map<String,String>> vcardData = new ArrayList<Map<String,String>>();
|
||||
try {
|
||||
ResultSet results = QueryUtils.getQueryResults(queryStr, vreq);
|
||||
while (results.hasNext()) {
|
||||
QuerySolution soln = results.nextSolution();
|
||||
vcardData.add(QueryUtils.querySolutionToStringValueMap(soln));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e, e);
|
||||
}
|
||||
|
||||
return vcardData;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,179 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.ajax;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.Integer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.json.JSONException;
|
||||
|
||||
import com.hp.hpl.jena.query.QuerySolution;
|
||||
import com.hp.hpl.jena.query.ResultSet;
|
||||
import com.hp.hpl.jena.rdf.model.RDFNode;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.ajax.VitroAjaxController;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.jena.QueryUtils;
|
||||
|
||||
public class GeoFocusMapLocations extends AbstractAjaxResponder {
|
||||
|
||||
private static final Log log = LogFactory.getLog(GeoFocusMapLocations.class.getName());
|
||||
private List<Map<String,String>> geoLocations;
|
||||
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 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"
|
||||
+ "PREFIX afn: <http://jena.hpl.hp.com/ARQ/function#> "
|
||||
+ "SELECT DISTINCT ?label ?location (afn:localname(?location) AS ?localName) (COUNT(DISTINCT ?person) AS ?count) \n"
|
||||
+ "WHERE { { \n"
|
||||
+ " ?location rdf:type core:GeographicRegion . \n"
|
||||
+ " ?location rdfs:label ?label . \n"
|
||||
+ " ?location core:geographicFocusOf ?person . \n"
|
||||
+ " ?person rdf:type foaf:Person . \n"
|
||||
+ " FILTER (NOT EXISTS {?location a core:StateOrProvince}) \n"
|
||||
+ "} UNION { \n"
|
||||
+ " ?location rdf:type core:GeographicRegion . \n"
|
||||
+ " ?location <http://purl.obolibrary.org/obo/BFO_0000051> ?sublocation . \n"
|
||||
+ " ?location rdfs:label ?label . \n"
|
||||
+ " ?sublocation core:geographicFocusOf ?person . \n"
|
||||
+ " ?person rdf:type foaf:Person \n"
|
||||
+ "} UNION { \n"
|
||||
+ " ?location rdf:type core:GeographicRegion . \n"
|
||||
+ " ?location geo:hasMember ?sublocation . \n"
|
||||
+ " ?location rdfs:label ?label . \n"
|
||||
+ " ?sublocation core:geographicFocusOf ?person . \n"
|
||||
+ " ?person rdf:type foaf:Person \n"
|
||||
+ "} } \n"
|
||||
+ "GROUP BY ?label ?location \n";
|
||||
|
||||
public GeoFocusMapLocations(HttpServlet parent, VitroRequest vreq,
|
||||
HttpServletResponse resp) {
|
||||
super(parent, vreq, resp);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String prepareResponse() throws IOException, JSONException {
|
||||
try {
|
||||
geoLocations = getGeoLocations(vreq);
|
||||
|
||||
String response = "[";
|
||||
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");
|
||||
String uri = map.get("location");
|
||||
String local = map.get("localName");
|
||||
if ( uri != null ) {
|
||||
uri = UrlBuilder.urlEncode(uri);
|
||||
}
|
||||
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";
|
||||
}
|
||||
else if ( label.contains("United States of America") ) {
|
||||
name = "United States of America";
|
||||
}
|
||||
else if ( label.contains("United Kingdom") ) {
|
||||
name = "United Kingdom";
|
||||
}
|
||||
else {
|
||||
name = label;
|
||||
}
|
||||
String tempStr = geometry; //+label
|
||||
tempStr += typeProps //+ label
|
||||
+ "\"popupContent\": \""
|
||||
+ name
|
||||
+ "\",\"html\":"
|
||||
+ html
|
||||
+ ",\"radius\":"
|
||||
+ radius
|
||||
+ ",\"uri\": \""
|
||||
+ uri
|
||||
+ "\",\"local\": \""
|
||||
+ local
|
||||
+ "\"}},";
|
||||
response += tempStr;
|
||||
previousLabel = label;
|
||||
}
|
||||
}
|
||||
if ( response.lastIndexOf(",") > 0 ) {
|
||||
response = response.substring(0, response.lastIndexOf(","));
|
||||
}
|
||||
response += " ]";
|
||||
if ( log.isDebugEnabled() ) {
|
||||
log.debug(response);
|
||||
}
|
||||
return response;
|
||||
} catch (Exception e) {
|
||||
log.error("Failed geographic focus locations", e);
|
||||
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>>();
|
||||
try {
|
||||
ResultSet results = QueryUtils.getQueryResults(queryStr, vreq);
|
||||
while (results.hasNext()) {
|
||||
QuerySolution soln = results.nextSolution();
|
||||
locations.add(QueryUtils.querySolutionToStringValueMap(soln));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e, e);
|
||||
}
|
||||
|
||||
return locations;
|
||||
}
|
||||
private Integer calculateRadius(Integer count) {
|
||||
|
||||
int radius = 8;
|
||||
if ( count != null ) {
|
||||
if ( count < 4 ) {
|
||||
radius = 8;
|
||||
}
|
||||
else if ( count < 7 ) {
|
||||
radius = 10;
|
||||
}
|
||||
else if ( count < 10 ) {
|
||||
radius = 12;
|
||||
}
|
||||
else if ( count < 16 ) {
|
||||
radius = 14;
|
||||
}
|
||||
else if ( count < 21 ) {
|
||||
radius = 16;
|
||||
}
|
||||
else if ( count < 26 ) {
|
||||
radius = 18;
|
||||
}
|
||||
else {
|
||||
radius = 20;
|
||||
}
|
||||
}
|
||||
|
||||
return radius;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.ajax;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.Integer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.json.JSONException;
|
||||
|
||||
import com.hp.hpl.jena.query.QuerySolution;
|
||||
import com.hp.hpl.jena.query.ResultSet;
|
||||
import com.hp.hpl.jena.rdf.model.RDFNode;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.ajax.VitroAjaxController;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.jena.QueryUtils;
|
||||
|
||||
public class GeoFocusResearcherCount extends AbstractAjaxResponder {
|
||||
|
||||
private static final Log log = LogFactory.getLog(GeoFocusResearcherCount.class.getName());
|
||||
private List<Map<String,String>> geoFocusCount;
|
||||
private static String GEO_FOCUS_COUNT_QUERY = ""
|
||||
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
|
||||
+ "PREFIX foaf: <http://xmlns.com/foaf/0.1/> \n"
|
||||
+ "SELECT DISTINCT (COUNT(DISTINCT ?person) AS ?count) \n"
|
||||
+ "WHERE { \n"
|
||||
+ " ?person a foaf:Person . \n"
|
||||
+ " ?person core:geographicFocus ?focus \n"
|
||||
+ "}" ;
|
||||
|
||||
public GeoFocusResearcherCount(HttpServlet parent, VitroRequest vreq,
|
||||
HttpServletResponse resp) {
|
||||
super(parent, vreq, resp);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String prepareResponse() throws IOException, JSONException {
|
||||
try {
|
||||
geoFocusCount = getGeoFocusCount(vreq);
|
||||
|
||||
String response = "{ ";
|
||||
|
||||
for (Map<String, String> map: geoFocusCount) {
|
||||
String theCount = map.get("count");
|
||||
response += "\"count\": \"" + theCount + "\"";
|
||||
}
|
||||
response += " }";
|
||||
log.debug(response);
|
||||
return response;
|
||||
} catch (Exception e) {
|
||||
log.error("Failed geographic focus count", e);
|
||||
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>>();
|
||||
try {
|
||||
ResultSet results = QueryUtils.getQueryResults(queryStr, vreq);
|
||||
while (results.hasNext()) {
|
||||
QuerySolution soln = results.nextSolution();
|
||||
count.add(QueryUtils.querySolutionToStringValueMap(soln));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e, e);
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.ajax;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
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.controller.ajax.VitroAjaxController;
|
||||
|
||||
/**
|
||||
* Handle the AJAX functions that are specific to the "new" home page sections, at
|
||||
* this point just the mapping of geographic locations.
|
||||
*/
|
||||
public class HomePageAjaxController extends VitroAjaxController {
|
||||
private static final Log log = LogFactory
|
||||
.getLog(HomePageAjaxController.class);
|
||||
|
||||
private static final String PARAMETER_ACTION = "action";
|
||||
|
||||
@Override
|
||||
protected void doRequest(VitroRequest vreq, HttpServletResponse resp)
|
||||
throws ServletException, IOException {
|
||||
try {
|
||||
String function = vreq.getParameter(PARAMETER_ACTION);
|
||||
if ("getGeoFocusLocations".equals(function)) {
|
||||
new GeoFocusMapLocations(this, vreq, resp).processRequest();
|
||||
}
|
||||
else if ("getGeoFocusResearcherCount".equals(function)) {
|
||||
new GeoFocusResearcherCount(this, vreq, resp).processRequest();
|
||||
}
|
||||
else {
|
||||
resp.getWriter().write("[]");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e, e);
|
||||
resp.getWriter().write("[]");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.ajax;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
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.controller.ajax.VitroAjaxController;
|
||||
|
||||
/**
|
||||
* Handle the AJAX functions that are specific to the "new" home page sections, at
|
||||
* this point just the mapping of geographic locations.
|
||||
*/
|
||||
public class QrCodeAjaxController extends VitroAjaxController {
|
||||
private static final Log log = LogFactory
|
||||
.getLog(QrCodeAjaxController.class);
|
||||
|
||||
private static final String PARAMETER_ACTION = "action";
|
||||
|
||||
@Override
|
||||
protected void doRequest(VitroRequest vreq, HttpServletResponse resp)
|
||||
throws ServletException, IOException {
|
||||
try {
|
||||
String function = vreq.getParameter(PARAMETER_ACTION);
|
||||
if ("getQrCodeDetails".equals(function)) {
|
||||
new QrCodeDetails(this, vreq, resp).processRequest();
|
||||
}
|
||||
else {
|
||||
resp.getWriter().write("[]");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e, e);
|
||||
resp.getWriter().write("[]");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,161 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.ajax;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.Integer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.json.JSONException;
|
||||
|
||||
import com.hp.hpl.jena.query.QuerySolution;
|
||||
import com.hp.hpl.jena.query.ResultSet;
|
||||
import com.hp.hpl.jena.rdf.model.RDFNode;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.ajax.VitroAjaxController;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerHttpServlet;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ExceptionResponseValues;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.individual.IndividualRequestAnalysisContextImpl;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.individual.IndividualRequestAnalyzer;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.individual.IndividualRequestInfo;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.jena.QueryUtils;
|
||||
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.IndividualTemplateModel;
|
||||
|
||||
|
||||
public class QrCodeDetails extends AbstractAjaxResponder {
|
||||
|
||||
private static final Log log = LogFactory.getLog(QrCodeDetails.class.getName());
|
||||
private List<Map<String,String>> vcardData;
|
||||
private static String VCARD_DATA_QUERY = ""
|
||||
+ "PREFIX obo: <http://purl.obolibrary.org/obo/> \n"
|
||||
+ "PREFIX vcard: <http://www.w3.org/2006/vcard/ns#> \n"
|
||||
+ "SELECT DISTINCT ?firstName ?lastName ?email ?phone ?title \n"
|
||||
+ "WHERE { \n"
|
||||
+ " ?subject obo:ARG_2000028 ?vIndividual . \n"
|
||||
+ " ?vIndividual vcard:hasName ?vName . \n"
|
||||
+ " ?vName vcard:givenName ?firstName . \n"
|
||||
+ " ?vName vcard:familyName ?lastName . \n"
|
||||
+ " OPTIONAL { ?vIndividual vcard:hasEmail ?vEmail . \n"
|
||||
+ " ?vEmail vcard:email ?email . \n"
|
||||
+ " } \n"
|
||||
+ " OPTIONAL { ?vIndividual vcard:hasTelephone ?vPhone . \n"
|
||||
+ " ?vPhone vcard:telephone ?phone . \n"
|
||||
+ " } \n"
|
||||
+ " OPTIONAL { ?vIndividual vcard:hasTitle ?vTitle . \n"
|
||||
+ " ?vTitle vcard:title ?title . \n"
|
||||
+ " } \n"
|
||||
+ "} " ;
|
||||
|
||||
public QrCodeDetails(HttpServlet parent, VitroRequest vreq,
|
||||
HttpServletResponse resp) {
|
||||
super(parent, vreq, resp);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String prepareResponse() throws IOException, JSONException {
|
||||
try {
|
||||
Individual individual = getIndividualFromRequest(vreq);
|
||||
String firstName = "";
|
||||
String lastName = "";
|
||||
String preferredTitle = "";
|
||||
String phoneNumber = "";
|
||||
String email = "";
|
||||
String response = "[";
|
||||
|
||||
vcardData = getVcardData(individual, vreq);
|
||||
|
||||
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://";
|
||||
tempUrl = tempUrl.substring(0, tempUrl.replace(prefix, "").indexOf("/") + prefix.length());
|
||||
String profileUrl = UrlBuilder.getIndividualProfileUrl(individual, vreq);
|
||||
String externalUrl = tempUrl + profileUrl;
|
||||
*/
|
||||
if (firstName != null && firstName.length() > 0) {
|
||||
response += "{\"firstName\": \"" + firstName + "\"},";
|
||||
}
|
||||
else {
|
||||
response += "{\"firstName\": \"\"},";
|
||||
}
|
||||
if (lastName != null && lastName.length() > 0) {
|
||||
response += "{\"lastName\": \"" + lastName + "\"},";
|
||||
}
|
||||
else {
|
||||
response += "{\"lastName\": \"\"},";
|
||||
}
|
||||
if (preferredTitle != null && preferredTitle.length() > 0) {
|
||||
response += "{\"preferredTitle\": \"" + preferredTitle + "\"},";
|
||||
}
|
||||
else {
|
||||
response += "{\"preferredTitle\": \"\"},";
|
||||
}
|
||||
if (phoneNumber != null && phoneNumber.length() > 0) {
|
||||
response += "{\"phoneNumber\": \"\"},";
|
||||
}
|
||||
else {
|
||||
response += "{\"phoneNumber\": \"\"},";
|
||||
}
|
||||
if (email != null && email.length() > 0) {
|
||||
response += "{\"email\": \"" + email + "\"},";
|
||||
}
|
||||
else {
|
||||
response += "{\"email\": \"\"},";
|
||||
}
|
||||
|
||||
response += " ]";
|
||||
response = response.replace(", ]"," ]");
|
||||
|
||||
log.debug(response);
|
||||
return response;
|
||||
} catch (Exception e) {
|
||||
log.error("Could not retrieve vCard information", e);
|
||||
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);
|
||||
List<Map<String,String>> vcardData = new ArrayList<Map<String,String>>();
|
||||
try {
|
||||
ResultSet results = QueryUtils.getQueryResults(queryStr, vreq);
|
||||
while (results.hasNext()) {
|
||||
QuerySolution soln = results.nextSolution();
|
||||
vcardData.add(QueryUtils.querySolutionToStringValueMap(soln));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e, e);
|
||||
}
|
||||
|
||||
return vcardData;
|
||||
}
|
||||
|
||||
private Individual getIndividualFromRequest(VitroRequest vreq) {
|
||||
IndividualRequestInfo requestInfo = new IndividualRequestAnalyzer(vreq,
|
||||
new IndividualRequestAnalysisContextImpl(vreq)).analyze();
|
||||
return requestInfo.getIndividual();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,256 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.rdf.model.Model;
|
||||
import com.hp.hpl.jena.rdf.model.RDFNode;
|
||||
import com.hp.hpl.jena.rdf.model.ResourceFactory;
|
||||
import com.hp.hpl.jena.rdf.model.Statement;
|
||||
import com.hp.hpl.jena.rdf.model.StmtIterator;
|
||||
import com.hp.hpl.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.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,127 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.query.QuerySolution;
|
||||
import com.hp.hpl.jena.query.ResultSet;
|
||||
import com.hp.hpl.jena.rdf.model.RDFNode;
|
||||
|
||||
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.Individual;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.jena.QueryUtils;
|
||||
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ResponseValues processRequest(VitroRequest vreq) {
|
||||
|
||||
Map<String, Object> body = new HashMap<String, Object>();
|
||||
|
||||
String subjectUri = vreq.getParameter("subjectUri");
|
||||
body.put("subjectUri", subjectUri);
|
||||
|
||||
HashMap<String, List<Map<String,String>>> grants = getGrants(subjectUri, vreq);
|
||||
if ( log.isDebugEnabled() ) {
|
||||
log.debug("grants = " + grants);
|
||||
}
|
||||
body.put("grants", grants);
|
||||
|
||||
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"
|
||||
+ "PREFIX vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> \n"
|
||||
+ "PREFIX afn: <http://jena.hpl.hp.com/ARQ/function#> \n"
|
||||
+ "SELECT DISTINCT ?subclass ?role (str(?label2) as ?label) ?activity ?hideThis WHERE { \n"
|
||||
+ " ?subject <http://purl.obolibrary.org/obo/RO_0000053> ?role . \n"
|
||||
+ " ?role a core:ResearcherRole . \n"
|
||||
+ " ?role vitro:mostSpecificType ?subclass \n"
|
||||
+ " OPTIONAL { \n"
|
||||
+ " ?subject <http://purl.obolibrary.org/obo/RO_0000053> ?role . \n"
|
||||
+ " ?role a core:ResearcherRole . \n"
|
||||
+ " ?role core:relatedBy ?activity . \n"
|
||||
+ " ?activity a core:Grant . \n"
|
||||
+ " ?activity rdfs:label ?label2 . \n"
|
||||
+ " } \n"
|
||||
+ " OPTIONAL { \n"
|
||||
+ " ?subject <http://purl.obolibrary.org/obo/RO_0000053> ?role . \n"
|
||||
+ " ?role a core:ResearcherRole . \n"
|
||||
+ " ?role <http://purl.obolibrary.org/obo/BFO_0000054> ?activity . \n"
|
||||
+ " ?activity a core:Project . \n"
|
||||
+ " ?activity rdfs:label ?label2 . \n"
|
||||
+ " } \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();
|
||||
|
||||
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>>>();
|
||||
try {
|
||||
ResultSet results = QueryUtils.getQueryResults(queryStr, vreq);
|
||||
while (results.hasNext()) {
|
||||
QuerySolution soln = results.nextSolution();
|
||||
RDFNode subclassUri= soln.get("subclass");
|
||||
if ( subclassUri != null ) {
|
||||
String subclassUriStr = soln.get("subclass").toString();
|
||||
VClass vClass = vcDao.getVClassByURI(subclassUriStr);
|
||||
String subclass = ((vClass.getName() == null) ? subclassUriStr : vClass.getName());
|
||||
if(!subclassToGrants.containsKey(subclass)) {
|
||||
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));
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e, e);
|
||||
}
|
||||
|
||||
return subclassToGrants;
|
||||
}
|
||||
|
||||
private List<String> getAllSubclasses(HashMap<String, List<Map<String, String>>> grants) {
|
||||
List<String> allSubclasses = new ArrayList<String>(grants.keySet());
|
||||
Collections.sort(allSubclasses);
|
||||
return allSubclasses;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,129 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.query.QuerySolution;
|
||||
import com.hp.hpl.jena.query.ResultSet;
|
||||
import com.hp.hpl.jena.rdf.model.RDFNode;
|
||||
|
||||
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.Individual;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.jena.QueryUtils;
|
||||
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ResponseValues processRequest(VitroRequest vreq) {
|
||||
|
||||
Map<String, Object> body = new HashMap<String, Object>();
|
||||
|
||||
String subjectUri = vreq.getParameter("subjectUri");
|
||||
body.put("subjectUri", subjectUri);
|
||||
|
||||
HashMap<String, List<Map<String,String>>> people = getPeople(subjectUri, vreq);
|
||||
if ( log.isDebugEnabled() ) {
|
||||
log.debug("people = " + people);
|
||||
}
|
||||
body.put("people", people);
|
||||
|
||||
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"
|
||||
+ "PREFIX vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> \n"
|
||||
+ "PREFIX afn: <http://jena.hpl.hp.com/ARQ/function#> \n"
|
||||
+ "PREFIX foaf: <http://xmlns.com/foaf/0.1/> \n"
|
||||
+ "SELECT DISTINCT ?subclass ?position ?positionLabel (str(?label) as ?name) ?person ?hideThis WHERE { \n"
|
||||
+ " ?subject core:relatedBy ?position . \n"
|
||||
+ " ?position a core:Position . \n"
|
||||
+ " ?position rdfs:label ?positionLabel . \n"
|
||||
+ " OPTIONAL { \n"
|
||||
+ " ?subject core:relatedBy ?position . \n"
|
||||
+ " ?position a core:Position . \n"
|
||||
+ " ?position core:relates ?person . "
|
||||
+ " ?person a foaf:Person . \n"
|
||||
+ " ?person rdfs:label ?label } \n"
|
||||
+ " OPTIONAL { \n"
|
||||
+ " ?subject core:relatedBy ?position . \n"
|
||||
+ " ?position a core:Position . \n"
|
||||
+ " ?position vitro:mostSpecificType ?subclass . \n"
|
||||
+ " OPTIONAL { ?subclass vitro:displayRankAnnot ?displayRank } \n"
|
||||
+ " } \n "
|
||||
+ " OPTIONAL { ?position core:hideFromDisplay ?hideThis } \n "
|
||||
+ " FILTER ( !BOUND(?displayRank) || ?displayRank < 500 )"
|
||||
+ "} ORDER BY ?subclass ?name";
|
||||
|
||||
HashMap<String, List<Map<String,String>>> getPeople(String subjectUri, VitroRequest vreq) {
|
||||
VClassDao vcDao = vreq.getUnfilteredAssertionsWebappDaoFactory().getVClassDao();
|
||||
|
||||
String queryStr = QueryUtils.subUriForQueryVar(PEOPLE_QUERY, "subject", subjectUri);
|
||||
log.debug("queryStr = " + queryStr);
|
||||
HashMap<String, List<Map<String,String>>> subclassToPeople = new HashMap<String, List<Map<String,String>>>();
|
||||
try {
|
||||
ResultSet results = QueryUtils.getQueryResults(queryStr, vreq);
|
||||
while (results.hasNext()) {
|
||||
QuerySolution soln = results.nextSolution();
|
||||
RDFNode subclassUri= soln.get("subclass");
|
||||
if ( subclassUri != null ) {
|
||||
String subclassUriStr = soln.get("subclass").toString();
|
||||
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>>());
|
||||
}
|
||||
List<Map<String,String>> peopleList = subclassToPeople.get(subclass);
|
||||
peopleList.add(QueryUtils.querySolutionToStringValueMap(soln));
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e, e);
|
||||
}
|
||||
|
||||
return subclassToPeople;
|
||||
}
|
||||
|
||||
private List<String> getAllSubclasses(
|
||||
HashMap<String, List<Map<String, String>>> people) {
|
||||
List<String> allSubclasses = new ArrayList<String>(people.keySet());
|
||||
Collections.sort(allSubclasses);
|
||||
return allSubclasses;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,129 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.query.QuerySolution;
|
||||
import com.hp.hpl.jena.query.ResultSet;
|
||||
import com.hp.hpl.jena.rdf.model.RDFNode;
|
||||
|
||||
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.Individual;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.jena.QueryUtils;
|
||||
|
||||
|
||||
public class ManagePublicationsForIndividualController extends FreemarkerHttpServlet {
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ResponseValues processRequest(VitroRequest vreq) {
|
||||
|
||||
Map<String, Object> body = new HashMap<String, Object>();
|
||||
|
||||
String subjectUri = vreq.getParameter("subjectUri");
|
||||
body.put("subjectUri", subjectUri);
|
||||
|
||||
HashMap<String, List<Map<String,String>>> publications = getPublications(subjectUri, vreq);
|
||||
if ( log.isDebugEnabled() ) {
|
||||
log.debug("publications = " + publications);
|
||||
}
|
||||
body.put("publications", publications);
|
||||
|
||||
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"
|
||||
+ "PREFIX vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> \n"
|
||||
+ "PREFIX afn: <http://jena.hpl.hp.com/ARQ/function#> \n"
|
||||
+ "SELECT DISTINCT ?subclass ?authorship (str(?label) as ?title) ?pub ?hideThis WHERE { \n"
|
||||
+ " ?subject core:relatedBy ?authorship . \n"
|
||||
+ " ?authorship a core:Authorship . \n"
|
||||
+ " OPTIONAL { \n "
|
||||
+ " ?subject core:relatedBy ?authorship . \n"
|
||||
+ " ?authorship a core:Authorship . \n"
|
||||
+ " ?authorship core:relates ?pub . "
|
||||
+ " ?pub a <http://purl.org/ontology/bibo/Document> . \n"
|
||||
+ " ?pub rdfs:label ?label . \n"
|
||||
+ " OPTIONAL { \n"
|
||||
+ " ?subject core:relatedBy ?authorship . \n"
|
||||
+ " ?authorship a core:Authorship . \n"
|
||||
+ " ?authorship core:relates ?pub . "
|
||||
+ " ?pub a <http://purl.org/ontology/bibo/Document> . \n"
|
||||
+ " ?pub vitro:mostSpecificType ?subclass . \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();
|
||||
|
||||
String queryStr = QueryUtils.subUriForQueryVar(PUBLICATION_QUERY, "subject", subjectUri);
|
||||
String subclass = "";
|
||||
log.debug("queryStr = " + queryStr);
|
||||
HashMap<String, List<Map<String,String>>> subclassToPublications = new HashMap<String, List<Map<String,String>>>();
|
||||
try {
|
||||
ResultSet results = QueryUtils.getQueryResults(queryStr, vreq);
|
||||
while (results.hasNext()) {
|
||||
QuerySolution soln = results.nextSolution();
|
||||
RDFNode subclassUri= soln.get("subclass");
|
||||
if ( subclassUri != null ) {
|
||||
String subclassUriStr = soln.get("subclass").toString();
|
||||
VClass vClass = vcDao.getVClassByURI(subclassUriStr);
|
||||
subclass = ((vClass.getName() == null) ? subclassUriStr : vClass.getName());
|
||||
}
|
||||
else {
|
||||
subclass = "Unclassified Publication";
|
||||
}
|
||||
if(!subclassToPublications.containsKey(subclass)) {
|
||||
subclassToPublications.put(subclass, new ArrayList<Map<String,String>>()); //list of publication information
|
||||
}
|
||||
List<Map<String,String>> publicationsList = subclassToPublications.get(subclass);
|
||||
publicationsList.add(QueryUtils.querySolutionToStringValueMap(soln));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e, e);
|
||||
}
|
||||
|
||||
return subclassToPublications;
|
||||
}
|
||||
|
||||
private List<String> getAllSubclasses(HashMap<String, List<Map<String, String>>> publications) {
|
||||
List<String> allSubclasses = new ArrayList<String>(publications.keySet());
|
||||
Collections.sort(allSubclasses);
|
||||
return allSubclasses;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.policy.PolicyHelper;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.visualization.tools.ToolsRequestHandler;
|
||||
|
||||
public class SiteAdminController extends BaseSiteAdminController {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final Log log = LogFactory.getLog(SiteAdminController.class);
|
||||
|
||||
@Override
|
||||
protected Map<String, Object> getSiteMaintenanceUrls(VitroRequest vreq) {
|
||||
|
||||
Map<String, Object> urls = super.getSiteMaintenanceUrls(vreq);
|
||||
|
||||
if (PolicyHelper.isAuthorizedForActions(vreq, ToolsRequestHandler.REQUIRED_ACTIONS)) {
|
||||
urls.put("rebuildVisCache", UrlBuilder.getUrl("/vis/tools"));
|
||||
}
|
||||
|
||||
return urls;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Map<String, Object> getSiteConfigData(VitroRequest vreq) {
|
||||
|
||||
Map<String, Object> data = super.getSiteConfigData(vreq);
|
||||
|
||||
if (PolicyHelper.isAuthorizedForActions(vreq, InstitutionalInternalClassController.REQUIRED_ACTIONS)) {
|
||||
data.put("internalClass", UrlBuilder.getUrl("/processInstitutionalInternalClass"));
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,440 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.harvester;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.skife.csv.SimpleReader;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* An implementation of FileHarvestJob that can be used for any CSV file harvest.
|
||||
*/
|
||||
class CsvFileHarvestJob implements FileHarvestJob {
|
||||
|
||||
/**
|
||||
* Contains constant constructor inputs for CsvFileHarvestJob
|
||||
* @author mbarbieri
|
||||
*/
|
||||
public enum JobType {
|
||||
GRANT("csvGrant", "granttemplate.csv", "CSVtoRDFgrant.sh", "csv-grant-to-vivo.xsl", "Grant", "Imported Grants", "No new grants were imported.", new String[] {"http://vivoweb.org/ontology/core#Grant"}),
|
||||
PERSON("csvPerson", "persontemplate.csv", "CSVtoRDFperson.sh", "csv-people-to-vivo.xsl", "Person", "Imported Persons", "No new persons were imported.", new String[] {"http://xmlns.com/foaf/0.1/Person"});
|
||||
|
||||
public final String httpParameterName;
|
||||
private final String templateFileName;
|
||||
private final String scriptFileName;
|
||||
private final String xsltFileName;
|
||||
private final String friendlyName;
|
||||
private final String linkHeader;
|
||||
private final String noNewDataMessage;
|
||||
private final String[] rdfTypesForLinks;
|
||||
|
||||
/**
|
||||
* Determines if there is a JobType with the specified HTTP parameter name.
|
||||
* @param httpParameterName the HTTP parameter name to look for a Job Type for
|
||||
* @return true if there is such a JobType, false otherwise
|
||||
*/
|
||||
public static boolean containsTypeWithHttpParameterName(String httpParameterName) {
|
||||
return (getByHttpParameterName(httpParameterName) != null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the JobType with the specified HTTP parameter name. This is essentially a string identifier for the job type. This
|
||||
* method accepts nulls, returning null in that case.
|
||||
* @param httpParameterName the HTTP parameter name to find the job for
|
||||
* @return the JobType with the specified HTTP parameter name, or null if there is none or httpParameterName was null
|
||||
*/
|
||||
public static JobType getByHttpParameterName(String httpParameterName) {
|
||||
JobType returnValue = null;
|
||||
|
||||
if(httpParameterName != null) {
|
||||
JobType[] values = JobType.values();
|
||||
for(JobType jobType : values) {
|
||||
if(jobType.httpParameterName.equalsIgnoreCase(httpParameterName)) {
|
||||
returnValue = jobType;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
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;
|
||||
this.scriptFileName = scriptFileName;
|
||||
this.xsltFileName = xsltFileName;
|
||||
this.friendlyName = friendlyName;
|
||||
this.linkHeader = linkHeader;
|
||||
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.
|
||||
*/
|
||||
private static final Log log = LogFactory.getLog(CsvFileHarvestJob.class);
|
||||
|
||||
/**
|
||||
* The HTTP request.
|
||||
*/
|
||||
private VitroRequest vreq;
|
||||
|
||||
/**
|
||||
* The template file against which uploaded CSV files will be validated.
|
||||
*/
|
||||
private File templateFile;
|
||||
|
||||
/**
|
||||
* The script which will be run after needed replacements are made.
|
||||
*/
|
||||
private File scriptFile;
|
||||
|
||||
/* *
|
||||
* The datamap to convert the JDBCFetch output to RDF/XML.
|
||||
*/
|
||||
/*
|
||||
private File xsltFile;
|
||||
*/
|
||||
|
||||
/**
|
||||
* The namespace to be used for the harvest.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
private final String namespace;
|
||||
|
||||
/**
|
||||
* A name for the type of data being imported. For example "Grant" or "Person".
|
||||
*/
|
||||
private final String friendlyName;
|
||||
|
||||
/**
|
||||
* A heading to be shown above the area where links to profiles of newly-harvested entities are listed.
|
||||
*/
|
||||
private final String linkHeader;
|
||||
|
||||
/**
|
||||
* The message to show to the user if there are no newly-harvested entities to show them.
|
||||
*/
|
||||
private final String noNewDataMessage;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
private CsvFileHarvestJob(VitroRequest vreq, String templateFileName, String scriptFileName, String xsltFileName, String namespace, String friendlyName, String linkHeader, String noNewDataMessage, String[] rdfTypesForLinks) {
|
||||
this.vreq = vreq;
|
||||
this.templateFile = new File(getTemplateFileDirectory() + templateFileName);
|
||||
this.scriptFile = new File(getScriptFileDirectory() + scriptFileName);
|
||||
// this.xsltFile = new File(FileHarvestController.getHarvesterPath() + "config/datamaps/" + xsltFileName);
|
||||
this.namespace = namespace;
|
||||
this.friendlyName = friendlyName;
|
||||
this.linkHeader = linkHeader;
|
||||
this.noNewDataMessage = noNewDataMessage;
|
||||
this.rdfTypesForLinks = Arrays.copyOf(rdfTypesForLinks, rdfTypesForLinks.length);
|
||||
|
||||
this.sessionId = this.vreq.getSession().getId();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the path to the directory containing the template files.
|
||||
* @return the path to the directory containing the template files
|
||||
*/
|
||||
private String getTemplateFileDirectory() {
|
||||
String harvesterPath = FileHarvestController.getHarvesterPath(vreq);
|
||||
String pathToTemplateFiles = harvesterPath + FileHarvestController.PATH_TO_TEMPLATE_FILES;
|
||||
return pathToTemplateFiles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the path to the directory containing the script files.
|
||||
* @return the path to the directory containing the script files
|
||||
*/
|
||||
private String getScriptFileDirectory() {
|
||||
String harvesterPath = FileHarvestController.getHarvesterPath(vreq);
|
||||
String pathToScriptFiles = harvesterPath + FileHarvestController.PATH_TO_HARVESTER_SCRIPTS;
|
||||
return pathToScriptFiles;
|
||||
}
|
||||
|
||||
|
||||
|
||||
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) {
|
||||
try {
|
||||
SimpleReader reader = new SimpleReader();
|
||||
|
||||
List templateCsv = reader.parse(this.templateFile);
|
||||
String[] templateFirstLine = (String[])templateCsv.get(0);
|
||||
|
||||
//if a line ends in a comma (absolutely a comma, no whitespace), SimpleReader will not consider the part after the comma to be a blank section.
|
||||
List csv = reader.parse(file);
|
||||
boolean[] linesEndingInComma = getLinesEndingInComma(file);
|
||||
|
||||
int length = csv.size();
|
||||
|
||||
if(length == 0)
|
||||
return "No data in file";
|
||||
|
||||
for(int i = 0; i < length; i++) {
|
||||
String[] line = (String[])csv.get(i);
|
||||
boolean endsInComma = linesEndingInComma[i];
|
||||
if(i == 0) {
|
||||
String errorMessage = validateCsvFirstLine(templateFirstLine, line);
|
||||
if(errorMessage != null)
|
||||
return errorMessage;
|
||||
}
|
||||
else if(line.length != 0) {
|
||||
int actualLineLength = line.length + (endsInComma ? 1 : 0);
|
||||
if(actualLineLength != templateFirstLine.length) {
|
||||
return "Mismatch in number of entries in row " + i + ": expected " + templateFirstLine.length + ", found " + actualLineLength;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
log.error(e, e);
|
||||
return e.getMessage();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes sure that the first line of the CSV file is identical to the first line of the template file. This is
|
||||
* assuming we are expecting all user CSV files to contain an initial header line. If this is not the case, then
|
||||
* this method is unnecessary.
|
||||
* @param templateFirstLine the parsed-out contents of the first line of the template file
|
||||
* @param line the parsed-out contents of the first line of the input file
|
||||
* @return an error message if the two lines don't match, or null if they do
|
||||
*/
|
||||
private String validateCsvFirstLine(String[] templateFirstLine, String[] line) {
|
||||
String errorMessage = "File header does not match template";
|
||||
if(line.length != templateFirstLine.length) {
|
||||
//return errorMessage + ": " + "file header columns = " + line.length + ", template columns = " + templateFirstLine.length;
|
||||
String errorMsg = "";
|
||||
errorMsg += "file header items: ";
|
||||
for(int i = 0; i < line.length; i++) {
|
||||
errorMsg += line[i] + ", ";
|
||||
}
|
||||
errorMsg += "template items: ";
|
||||
for(int i = 0; i < templateFirstLine.length; i++) {
|
||||
errorMsg += templateFirstLine[i] + ", ";
|
||||
}
|
||||
return errorMsg;
|
||||
}
|
||||
for(int i = 0; i < line.length; i++)
|
||||
{
|
||||
if(!line[i].equals(templateFirstLine[i]))
|
||||
return errorMessage + ": file header column " + (i + 1) + " = " + line[i] + ", template column " + (i + 1) + " = " + templateFirstLine[i];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
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()
|
||||
{
|
||||
File scriptTemplate = this.scriptFile;
|
||||
|
||||
String scriptTemplateContents = readFromFile(scriptTemplate);
|
||||
String replacements = performScriptTemplateReplacements(scriptTemplateContents);
|
||||
return replacements;
|
||||
}
|
||||
|
||||
|
||||
private String performScriptTemplateReplacements(String scriptTemplateContents) {
|
||||
String replacements = scriptTemplateContents;
|
||||
|
||||
String workingDirectory = FileHarvestController.getHarvesterPath(vreq);
|
||||
String fileDirectory = FileHarvestController.getUploadPath(vreq);
|
||||
String harvestedDataPath = getHarvestedDataPath();
|
||||
String globalHarvestedDataRelativePath = FileHarvestController.PATH_TO_HARVESTED_DATA;
|
||||
|
||||
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);
|
||||
replacements = replacements.replace("${GLOBAL_HARVESTED_DATA_RELATIVE_PATH}", globalHarvestedDataRelativePath);
|
||||
|
||||
return replacements;
|
||||
}
|
||||
|
||||
/*
|
||||
private String performXsltTemplateReplacements(String xsltTemplateContents) {
|
||||
String replacements = xsltTemplateContents;
|
||||
|
||||
replacements = replacements.replace("", "");
|
||||
|
||||
return replacements;
|
||||
}
|
||||
|
||||
|
||||
private void writeToFile(File file, String contents) {
|
||||
PrintWriter writer = null;
|
||||
try {
|
||||
writer = new PrintWriter(file);
|
||||
writer.print(contents);
|
||||
} catch(IOException e) {
|
||||
log.error(e, e);
|
||||
} finally {
|
||||
if(writer != null)
|
||||
writer.close();
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
private String readFromFile(File file) {
|
||||
String contents = null;
|
||||
BufferedReader reader = null;
|
||||
try {
|
||||
int fileSize = (int)(file.length());
|
||||
char[] buffer = new char[fileSize];
|
||||
reader = new BufferedReader(new FileReader(file), fileSize);
|
||||
reader.read(buffer);
|
||||
contents = new String(buffer);
|
||||
} catch (IOException e) {
|
||||
log.error(e, e);
|
||||
} finally {
|
||||
try {
|
||||
if(reader != null)
|
||||
reader.close();
|
||||
} catch(IOException e) {
|
||||
log.error(e, e);
|
||||
}
|
||||
}
|
||||
|
||||
return contents;
|
||||
}
|
||||
|
||||
private String getHarvestedDataPath() {
|
||||
return FileHarvestController.getHarvesterPath(vreq) + FileHarvestController.PATH_TO_HARVESTED_DATA + "csv/" + this.sessionId + "/";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAdditionsFilePath() {
|
||||
return getHarvestedDataPath() + "additions.rdf.xml";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPageHeader() {
|
||||
return "Harvest " + this.friendlyName + " data from CSV file(s)";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLinkHeader() {
|
||||
return this.linkHeader;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTemplateFilePath() {
|
||||
return this.templateFile.getPath();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getRdfTypesForLinks() {
|
||||
return Arrays.copyOf(this.rdfTypesForLinks, this.rdfTypesForLinks.length);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTemplateDownloadHelp() {
|
||||
return "Click here to download a template file to assist you with harvesting the data.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTemplateFillInHelp() {
|
||||
String newline = "\n";
|
||||
String help = "";
|
||||
help += "<p>A CSV, or <strong>C</strong>omma-<strong>S</strong>eparated <strong>V</strong>alues file, is a method of storing tabular data in plain text. The first line of a CSV file contains header information, while each subsequent line contains a data record.</p>" + newline;
|
||||
help += "<p>The template we provide contains only the header, which you will then fill in accordingly. For example, if the template contains the text \"firstName,lastName\", then you might add two more lines, \"John,Doe\" and \"Jane,Public\".</p>" + newline;
|
||||
help += "<p>People in the harvest are grouped by the \"PersonID\" field and matched with existing data using the \"Email\" and/or \"FullName\" fields.</p>" + newline;
|
||||
help += "<p>In the grant harvest grants, people, and departments are grouped by \"GrantID\",\"PIID\" and \"CoPIID\", \"AdminDepartmentID\" fields respectively and matched with existing data using the name fields.</p>" + newline;
|
||||
return help;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getNoNewDataMessage() {
|
||||
return this.noNewDataMessage;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,946 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.harvester;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Hashtable;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
|
||||
import org.apache.commons.fileupload.FileItem;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.application.ApplicationUtils;
|
||||
import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerHttpServlet;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ExceptionResponseValues;
|
||||
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.filestorage.impl.FileStorageImplWrapper;
|
||||
|
||||
public class FileHarvestController extends FreemarkerHttpServlet {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final Log log = LogFactory.getLog(FileHarvestController.class);
|
||||
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";
|
||||
private static final String PARAMETER_JOB = "job";
|
||||
|
||||
private static final String POST_TO = UrlBuilder.getUrl("/harvester/harvest");
|
||||
|
||||
private static final String MODE_HARVEST = "harvest";
|
||||
private static final String MODE_CHECK_STATUS = "checkStatus";
|
||||
private static final String MODE_DOWNLOAD_TEMPLATE = "template";
|
||||
|
||||
|
||||
/**
|
||||
* Stores information about the Harvester thread for a particular user session.
|
||||
*/
|
||||
private Map<String, SessionInfo> sessionIdToSessionInfo = new Hashtable<String, SessionInfo>(); //Hashtable is threadsafe, HashMap is not
|
||||
|
||||
/**
|
||||
* A list of known job parameters (that is, "job=" values from the query string which we will accept from the browser).
|
||||
* This should be filled in the static initializer and then never written to again.
|
||||
*/
|
||||
private static final List<String> knownJobs = new ArrayList<String>();
|
||||
|
||||
|
||||
/**
|
||||
* Relative path from the VIVO Uploads directory to the root location where user-uploaded files will be stored. Include
|
||||
* final slash.
|
||||
*/
|
||||
private static final String PATH_TO_UPLOADS = "harvester/";
|
||||
|
||||
/**
|
||||
* Relative path from the Harvester root directory to the main area reserved for the VIVO File Harvest feature. Include
|
||||
* final slash.
|
||||
*/
|
||||
private static final String PATH_TO_FILE_HARVEST_ROOT = "vivo/";
|
||||
|
||||
/**
|
||||
* Relative path from the Harvester root directory to the directory where user-downloadable template files are stored.
|
||||
* Include final slash.
|
||||
*/
|
||||
public static final String PATH_TO_TEMPLATE_FILES = PATH_TO_FILE_HARVEST_ROOT + "templates/";
|
||||
|
||||
/**
|
||||
* Relative path from the Harvester root directory to the directory containing the script templates. Include final slash.
|
||||
*/
|
||||
public static final String PATH_TO_HARVESTER_SCRIPTS = PATH_TO_FILE_HARVEST_ROOT + "scripts/";
|
||||
|
||||
/**
|
||||
* Relative path from the Harvester root directory to the directory containing the script templates. Include final slash.
|
||||
*/
|
||||
public static final String PATH_TO_HARVESTED_DATA = PATH_TO_FILE_HARVEST_ROOT + "harvested-data/";
|
||||
|
||||
|
||||
static {
|
||||
fillKnownJobTypesList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fill the known job types list. Any time a new job type is added, we need to make sure this method is adding it to the list.
|
||||
* By "new job type" is meant a new "job=" parameter that we understand when we see it in the query string. This typically means
|
||||
* we have also handled seeing this parameter in the getJob() method of this class.
|
||||
*
|
||||
* The exception to all this is a new CSV job, which is entirely handled by adding a new CsvFileHarvestJob.JobType enum value. This
|
||||
* method as well as this class's getJob() method already handle the rest.
|
||||
*/
|
||||
private static void fillKnownJobTypesList() {
|
||||
|
||||
//fill known CSV job types
|
||||
CsvFileHarvestJob.JobType[] csvFileHarvestJobTypes = CsvFileHarvestJob.JobType.values();
|
||||
for(CsvFileHarvestJob.JobType csvFileHarvestJobType : csvFileHarvestJobTypes) {
|
||||
knownJobs.add(csvFileHarvestJobType.httpParameterName.toLowerCase());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public long maximumMultipartFileSize() {
|
||||
return 1024 * 1024;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean stashFileSizeException() {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected ResponseValues processRequest(VitroRequest vreq) {
|
||||
try {
|
||||
cleanUpOldSessions();
|
||||
|
||||
String job = vreq.getParameter(PARAMETER_JOB);
|
||||
String jobKnown = "false";
|
||||
if((job != null) && FileHarvestController.knownJobs.contains(job.toLowerCase()))
|
||||
jobKnown = "true";
|
||||
|
||||
FileHarvestJob jobObject = getJob(vreq, job);
|
||||
|
||||
Map<String, Object> body = new HashMap<String, Object>();
|
||||
String harvesterPath = getHarvesterPath(vreq);
|
||||
//body.put("uploadPostback", "false");
|
||||
body.put("paramFirstUpload", PARAMETER_FIRST_UPLOAD);
|
||||
body.put("paramUploadedFile", PARAMETER_UPLOADED_FILE);
|
||||
body.put("paramMode", PARAMETER_MODE);
|
||||
body.put("paramJob", PARAMETER_JOB);
|
||||
body.put("modeHarvest", MODE_HARVEST);
|
||||
body.put("modeCheckStatus", MODE_CHECK_STATUS);
|
||||
body.put("modeDownloadTemplate", MODE_DOWNLOAD_TEMPLATE);
|
||||
body.put("job", job);
|
||||
body.put("jobKnown", jobKnown);
|
||||
body.put("harvesterLocation", harvesterPath);
|
||||
body.put("postTo", POST_TO + "?" + PARAMETER_JOB + "=" + job);
|
||||
body.put("jobSpecificHeader", (jobObject != null) ? jobObject.getPageHeader() : "");
|
||||
body.put("jobSpecificLinkHeader", (jobObject != null) ? jobObject.getLinkHeader() : "");
|
||||
body.put("jobSpecificDownloadHelp", (jobObject != null) ? jobObject.getTemplateDownloadHelp() : "");
|
||||
body.put("jobSpecificFillInHelp", (jobObject != null) ? jobObject.getTemplateFillInHelp() : "");
|
||||
body.put("jobSpecificNoNewDataMessage", (jobObject != null) ? jobObject.getNoNewDataMessage() : "");
|
||||
return new TemplateResponseValues(TEMPLATE_DEFAULT, body);
|
||||
} catch (Throwable e) {
|
||||
log.error(e, e);
|
||||
return new ExceptionResponseValues(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getTitle(String siteName, VitroRequest vreq) {
|
||||
return "VIVO Harvester Test";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the root location of the VIVO Harvester on this machine.
|
||||
* @return the root location of the VIVO Harvester on this machine
|
||||
*/
|
||||
public static String getHarvesterPath(HttpServletRequest req)
|
||||
{
|
||||
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 "";
|
||||
}
|
||||
return pathToHarvester;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the path on this machine of the area within Harvester reserved for File Harvest.
|
||||
* @return the path on this machine of the area within Harvester reserved for File Harvest
|
||||
*/
|
||||
public static String getFileHarvestRootPath(HttpServletRequest req)
|
||||
{
|
||||
String fileHarvestRootPath = getHarvesterPath(req) + PATH_TO_FILE_HARVEST_ROOT;
|
||||
return fileHarvestRootPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the base directory used for all File Harvest uploads.
|
||||
* @param context the current servlet context
|
||||
* @return the base directory for file harvest uploads
|
||||
* @throws Exception if the Vitro home directory could not be found
|
||||
*/
|
||||
private static String getUploadPathBase(ServletContext context) throws Exception
|
||||
{
|
||||
String vitroHomeDirectoryName = ApplicationUtils.instance().getHomeDirectory().getPath().toString();
|
||||
return vitroHomeDirectoryName + "/" + FileStorageImplWrapper.FILE_STORAGE_SUBDIRECTORY + "/" + PATH_TO_UPLOADS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the FileHarvestJob implementation that is needed to handle the specified request. This
|
||||
* will depend on the type of harvest being performed (CSV, RefWorks, etc.)
|
||||
* @param vreq the request from the browser
|
||||
* @param jobParameter the POST or GET parameter "job". Might not be available in vreq at this point,
|
||||
* thus we are requiring that it be sent in.
|
||||
* @return the FileHarvestJob that will provide harvest-type-specific services for this request
|
||||
*/
|
||||
private FileHarvestJob getJob(VitroRequest vreq, String jobParameter)
|
||||
{
|
||||
String namespace = vreq.getWebappDaoFactory().getDefaultNamespace();
|
||||
|
||||
FileHarvestJob job = null;
|
||||
|
||||
if(jobParameter == null)
|
||||
log.error("No job specified.");
|
||||
else if(CsvFileHarvestJob.JobType.containsTypeWithHttpParameterName(jobParameter)) //check if this is a CSV job
|
||||
job = CsvFileHarvestJob.createJob(CsvFileHarvestJob.JobType.getByHttpParameterName(jobParameter), vreq, namespace);
|
||||
else
|
||||
log.error("Invalid job: " + jobParameter);
|
||||
|
||||
return job;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the location where we want to save uploaded files. This location is in the VIVO uploads directory under
|
||||
* "harvester", and then in a directory named by the user's session ID as retrieved from the request. The path
|
||||
* returned by this method will end in a slash (/).
|
||||
* @param vreq the request from which to get the session ID
|
||||
* @return the path to the location where uploaded files will be saved. This path will end in a slash (/)
|
||||
*/
|
||||
public static String getUploadPath(VitroRequest vreq) {
|
||||
try {
|
||||
String path = getUploadPathBase(vreq.getSession().getServletContext()) + getSessionId(vreq) + "/";
|
||||
return path;
|
||||
} catch(Exception e) {
|
||||
log.error(e, e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doPost(HttpServletRequest request, HttpServletResponse response)
|
||||
throws IOException, ServletException {
|
||||
|
||||
try {
|
||||
boolean isMultipart = new VitroRequest(request).isMultipart();
|
||||
String mode = request.getParameter(PARAMETER_MODE);
|
||||
if(isMultipart)
|
||||
doFileUploadPost(request, response);
|
||||
else if(mode.equals(MODE_HARVEST))
|
||||
doHarvestPost(request, response);
|
||||
else if(mode.equals(MODE_CHECK_STATUS))
|
||||
doCheckHarvestStatusPost(request, response);
|
||||
else if(mode.equals(MODE_DOWNLOAD_TEMPLATE))
|
||||
doDownloadTemplatePost(request, response);
|
||||
else
|
||||
throw new Exception("Unrecognized post mode: " + mode);
|
||||
} catch(Exception e) {
|
||||
log.error(e, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This is for when the user clicks the "Upload" button on the form, sending a file to the server. An HTTP post is
|
||||
* redirected here when it is determined that the request was multipart (as this will identify the post as a file
|
||||
* upload click).
|
||||
* @param request the HTTP request
|
||||
* @param response the HTTP response
|
||||
* @throws IOException if an IO error occurs
|
||||
* @throws ServletException if a servlet error occurs
|
||||
*/
|
||||
private void doFileUploadPost(HttpServletRequest request, HttpServletResponse response)
|
||||
throws IOException, ServletException {
|
||||
|
||||
JSONObject json = generateJson(false);
|
||||
try {
|
||||
VitroRequest vreq = new VitroRequest(request);
|
||||
|
||||
//check that the parsing was successful
|
||||
if(vreq.hasFileSizeException()) {
|
||||
Exception e = vreq.getFileSizeException();
|
||||
throw new ExceptionVisibleToUser(e);
|
||||
}
|
||||
|
||||
//get the job parameter
|
||||
String jobParameter = vreq.getParameter(PARAMETER_JOB);
|
||||
|
||||
//get the location where we want to save the files (it will end in a slash), then create a File object out of it
|
||||
String path = getUploadPath(vreq);
|
||||
File directory = new File(path);
|
||||
|
||||
//if this is a page refresh, we do not want to save stale files that the user doesn't want anymore, but we
|
||||
// still have the same session ID and therefore the upload directory is unchanged. Thus we must clear the
|
||||
// upload directory if it exists (a "first upload" parameter, initialized to "true" but which gets set to
|
||||
// "false" once the user starts uploading stuff is used for this).
|
||||
String firstUpload = vreq.getParameter(PARAMETER_FIRST_UPLOAD); //clear directory on first upload
|
||||
if(firstUpload.toLowerCase().equals("true")) {
|
||||
if(directory.exists()) {
|
||||
File[] children = directory.listFiles();
|
||||
for(File child : children) {
|
||||
child.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//if the upload directory does not exist then create it
|
||||
if(!directory.exists())
|
||||
directory.mkdirs();
|
||||
|
||||
//get the file harvest job for this request (this will determine what type of harvest is run)
|
||||
FileHarvestJob job = getJob(vreq, jobParameter);
|
||||
|
||||
//get the files out of the parsed request (there should only be one)
|
||||
Map<String, List<FileItem>> fileStreams = vreq.getFiles();
|
||||
if(fileStreams.get(PARAMETER_UPLOADED_FILE) != null && fileStreams.get(PARAMETER_UPLOADED_FILE).size() > 0) {
|
||||
|
||||
//get the individual file data from the request
|
||||
FileItem csvStream = fileStreams.get(PARAMETER_UPLOADED_FILE).get(0);
|
||||
String name = csvStream.getName();
|
||||
|
||||
//if another uploaded file exists with the same name, alter the name so that it is unique
|
||||
name = handleNameCollision(name, directory);
|
||||
|
||||
//write the file from the request to the upload directory
|
||||
File file = new File(path + name);
|
||||
try {
|
||||
csvStream.write(file);
|
||||
} finally {
|
||||
csvStream.delete();
|
||||
}
|
||||
|
||||
//ask the file harvest job to validate that it's okay with what was uploaded; if not delete the file
|
||||
String errorMessage = job.validateUpload(file);
|
||||
boolean success;
|
||||
if(errorMessage != null) {
|
||||
success = false;
|
||||
file.delete();
|
||||
} else {
|
||||
success = true;
|
||||
errorMessage = "success";
|
||||
}
|
||||
|
||||
//prepare the results which will be sent back to the browser for display
|
||||
try {
|
||||
json.put("success", success);
|
||||
json.put("fileName", name);
|
||||
json.put("errorMessage", errorMessage);
|
||||
}
|
||||
catch(JSONException e) {
|
||||
log.error(e, e);
|
||||
return;
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
//if for some reason no file was included with the request, send an error back
|
||||
try {
|
||||
json.put("success", false);
|
||||
json.put("fileName", "(none)");
|
||||
json.put("errorMessage", "No file uploaded");
|
||||
} catch(JSONException e) {
|
||||
log.error(e, e);
|
||||
return;
|
||||
}
|
||||
|
||||
}
|
||||
} catch(ExceptionVisibleToUser e) {
|
||||
log.error(e, e);
|
||||
|
||||
//handle exceptions whose message is for the user
|
||||
try {
|
||||
json.put("success", false);
|
||||
json.put("filename", "(none)");
|
||||
json.put("errorMessage", e.getMessage());
|
||||
} catch(JSONException f) {
|
||||
log.error(f, f);
|
||||
return;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
log.error(e, e);
|
||||
json = generateJson(true);
|
||||
}
|
||||
|
||||
//write the prepared response
|
||||
response.getWriter().write(json.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* This is for when the user clicks the "Harvest" button on the form, sending a file to the server. An HTTP post is
|
||||
* redirected here when an isHarvestClick parameter is contained in the post data and set to "true".
|
||||
* @param request the HTTP request
|
||||
* @param response the HTTP response
|
||||
*/
|
||||
private void doHarvestPost(HttpServletRequest request, HttpServletResponse response) {
|
||||
|
||||
JSONObject json;
|
||||
try {
|
||||
VitroRequest vreq = new VitroRequest(request);
|
||||
FileHarvestJob job = getJob(vreq, vreq.getParameter(PARAMETER_JOB));
|
||||
|
||||
//String path = getUploadPath(vreq);
|
||||
|
||||
String script = job.getScript();
|
||||
String additionsFilePath = job.getAdditionsFilePath();
|
||||
String scriptFileLocation = getScriptFileLocation(vreq);
|
||||
runScript(getSessionId(request), script, additionsFilePath, scriptFileLocation, job);
|
||||
|
||||
json = generateJson(false);
|
||||
json.put("progressSinceLastCheck", "");
|
||||
json.put("scriptText", script);
|
||||
json.put("finished", false);
|
||||
|
||||
} catch(Exception e) {
|
||||
json = generateJson(true);
|
||||
log.error(e, e);
|
||||
}
|
||||
|
||||
try {
|
||||
response.getWriter().write(json.toString());
|
||||
} catch(IOException e) {
|
||||
log.error(e, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This is for posts automatically sent by the client during the harvest, to check on the status of the harvest and
|
||||
* return updated log data and whether the harvest is complete or still running. An HTTP post is redirected here
|
||||
* when an isHarvestClick parameter is contained in the post data and set to "false".
|
||||
* @param request the HTTP request
|
||||
* @param response the HTTP response
|
||||
*/
|
||||
private void doCheckHarvestStatusPost(HttpServletRequest request, HttpServletResponse response) {
|
||||
|
||||
JSONObject json;
|
||||
try {
|
||||
String newline = "\n";
|
||||
|
||||
String sessionId = getSessionId(request);
|
||||
SessionInfo sessionInfo = sessionIdToSessionInfo.get(sessionId);
|
||||
|
||||
//if we have started a thread, check the status and return it to the user
|
||||
if(sessionInfo != null) {
|
||||
|
||||
String[] unsentLogLines;
|
||||
ArrayList<String> unsentLogLinesList = sessionInfo.unsentLogLines;
|
||||
|
||||
//don't let the harvester thread add data to the unsent log lines list until we have both copied it and cleared it
|
||||
synchronized (unsentLogLinesList) {
|
||||
unsentLogLines = unsentLogLinesList.toArray(new String[unsentLogLinesList.size()]);
|
||||
unsentLogLinesList.clear();
|
||||
}
|
||||
|
||||
String progressSinceLastCheck = "";
|
||||
for(int i = 0; i < unsentLogLines.length; i++) {
|
||||
progressSinceLastCheck += unsentLogLines[i] + newline;
|
||||
}
|
||||
|
||||
boolean finished = sessionInfo.isFinished();
|
||||
boolean abnormalTermination = false;
|
||||
|
||||
VitroRequest vreq = new VitroRequest(request);
|
||||
ArrayList<String> newlyAddedUrls = new ArrayList<String>();
|
||||
ArrayList<String> newlyAddedUris = new ArrayList<String>();
|
||||
if(finished) {
|
||||
newlyAddedUris = sessionInfo.newlyAddedUris;
|
||||
if(newlyAddedUris != null) {
|
||||
for(String uri : newlyAddedUris) {
|
||||
|
||||
newlyAddedUrls.add(UrlBuilder.getIndividualProfileUrl(uri, vreq));
|
||||
}
|
||||
}
|
||||
|
||||
//remove all entries in "sessionIdTo..." mappings for this session ID
|
||||
clearSessionInfo(sessionId);
|
||||
|
||||
if(sessionInfo.getAbnormalTermination())
|
||||
abnormalTermination = true;
|
||||
}
|
||||
|
||||
if(!abnormalTermination) {
|
||||
json = generateJson(false);
|
||||
json.put("progressSinceLastCheck", progressSinceLastCheck);
|
||||
json.put("finished", finished);
|
||||
json.put("newlyAddedUris", newlyAddedUris);
|
||||
json.put("newlyAddedUrls", newlyAddedUrls);
|
||||
} else {
|
||||
json = generateJson(true);
|
||||
log.error("File harvest terminated abnormally.");
|
||||
}
|
||||
} else { //if we have not started a harvest thread, the browser should not have made this request to begin with. Bad browser, very bad browser.
|
||||
json = generateJson(true);
|
||||
log.error("Attempt to check status of a harvest that was never started! (Session ID " + sessionId + ")");
|
||||
}
|
||||
} catch(Exception e) {
|
||||
json = generateJson(true);
|
||||
log.error(e, e);
|
||||
}
|
||||
|
||||
try {
|
||||
response.getWriter().write(json.toString());
|
||||
} catch(IOException e) {
|
||||
log.error(e, e);
|
||||
}
|
||||
}
|
||||
|
||||
private void doDownloadTemplatePost(HttpServletRequest request, HttpServletResponse response) {
|
||||
|
||||
VitroRequest vreq = new VitroRequest(request);
|
||||
FileHarvestJob job = getJob(vreq, vreq.getParameter(PARAMETER_JOB));
|
||||
File fileToSend = new File(job.getTemplateFilePath());
|
||||
|
||||
response.setContentType("application/octet-stream");
|
||||
response.setContentLength((int)(fileToSend.length()));
|
||||
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileToSend.getName() + "\"");
|
||||
|
||||
try {
|
||||
byte[] byteBuffer = new byte[(int)(fileToSend.length())];
|
||||
DataInputStream inStream = new DataInputStream(new FileInputStream(fileToSend));
|
||||
|
||||
ServletOutputStream outputStream = response.getOutputStream();
|
||||
for(int length = inStream.read(byteBuffer); length != -1; length = inStream.read(byteBuffer)) {
|
||||
outputStream.write(byteBuffer, 0, length);
|
||||
}
|
||||
|
||||
inStream.close();
|
||||
outputStream.flush();
|
||||
outputStream.close();
|
||||
} catch(IOException e) {
|
||||
log.error(e, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the location in which the ready-to-run scripts, after having template replacements made on them, will be
|
||||
* placed. Final slash included.
|
||||
* @return the location in which the ready-to-run scripts will be placed
|
||||
*/
|
||||
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()) {
|
||||
scriptDirectory.mkdirs();
|
||||
}
|
||||
|
||||
File tempFile = File.createTempFile("harv", ".sh", scriptDirectory);
|
||||
|
||||
FileWriter writer = new FileWriter(tempFile);
|
||||
writer.write(script);
|
||||
writer.close();
|
||||
|
||||
return tempFile;
|
||||
}
|
||||
|
||||
|
||||
private void runScript(String sessionId, String script, String additionsFilePath, String scriptFileLocation, FileHarvestJob job) {
|
||||
clearSessionInfo(sessionId);
|
||||
|
||||
ScriptRunner runner = new ScriptRunner(sessionId, script, additionsFilePath, scriptFileLocation, job);
|
||||
SessionInfo info = new SessionInfo(sessionId, runner);
|
||||
sessionIdToSessionInfo.put(sessionId, info);
|
||||
runner.start();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Handles a name conflict in a directory by providing a new name that does not conflict with the
|
||||
* name of a file already uploaded.
|
||||
* @param filename the name of the file to be added to the directory
|
||||
* @param directory the directory where the file should be added, in which to check for files of the
|
||||
* same name
|
||||
* @return a filename that does not conflict with any files in the directory. If the filename parameter
|
||||
* works, then that is returned. Otherwise a number is appended in parentheses to the part of
|
||||
* the file name prior to the final "." symbol (if one exists).
|
||||
*/
|
||||
private String handleNameCollision(String filename, File directory) {
|
||||
String base = filename;
|
||||
String extension = "";
|
||||
if(filename.contains(".")) {
|
||||
base = filename.substring(0, filename.lastIndexOf("."));
|
||||
extension = filename.substring(filename.indexOf("."));
|
||||
}
|
||||
|
||||
String renamed = filename;
|
||||
|
||||
for(int i = 1; new File(directory, renamed).exists(); i++) {
|
||||
renamed = base + " (" + String.valueOf(i) + ")" + extension;
|
||||
}
|
||||
|
||||
return renamed;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the ID of the current session between server and browser.
|
||||
* @param request the request coming in from the browser
|
||||
* @return the session ID
|
||||
*/
|
||||
private static String getSessionId(HttpServletRequest request) {
|
||||
return request.getSession().getId();
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse an additions file (RDF/XML) to get the URIs of newly-harvested data, which will be sent to the browser and
|
||||
* displayed to the user as links.
|
||||
* @param additionsFile the file containing the newly-added RDF/XML
|
||||
* @param newlyAddedUris a list in which to place the newly added URIs
|
||||
*/
|
||||
private void extractNewlyAddedUris(File additionsFile, List<String> newlyAddedUris, FileHarvestJob job) {
|
||||
|
||||
try {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setNamespaceAware(true);
|
||||
Document document = factory.newDocumentBuilder().parse(additionsFile);
|
||||
//Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(additionsFile);
|
||||
NodeList descriptionNodes = document.getElementsByTagNameNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "Description");
|
||||
|
||||
int numNodes = descriptionNodes.getLength();
|
||||
for(int i = 0; i < numNodes; i++) {
|
||||
Node node = descriptionNodes.item(i);
|
||||
|
||||
ArrayList<String> types = getRdfTypes(node);
|
||||
|
||||
boolean match = false;
|
||||
String[] validRdfTypesForJob = job.getRdfTypesForLinks();
|
||||
for(String rdfType : validRdfTypesForJob) {
|
||||
if(types.contains(rdfType))
|
||||
match = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if(match) {
|
||||
|
||||
NamedNodeMap attributes = node.getAttributes();
|
||||
Node aboutAttribute = attributes.getNamedItemNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "about");
|
||||
if(aboutAttribute != null) {
|
||||
String value = aboutAttribute.getNodeValue();
|
||||
newlyAddedUris.add(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} catch(Exception e) {
|
||||
log.error(e, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse an XML node for all subnodes with qualified name "rdf:type", and return each's "rdf:resource" value in a list.
|
||||
* @param descriptionNode the RDF description node
|
||||
* @return a list of rdf:types of the given description node
|
||||
*/
|
||||
private ArrayList<String> getRdfTypes(Node descriptionNode) {
|
||||
ArrayList<String> rdfTypesList = new ArrayList<String>();
|
||||
|
||||
NodeList children = descriptionNode.getChildNodes();
|
||||
int numChildren = children.getLength();
|
||||
for(int i = 0; i < numChildren; i++) {
|
||||
Node child = children.item(i);
|
||||
|
||||
String namespace = child.getNamespaceURI();
|
||||
String name = child.getLocalName();
|
||||
String fullName = namespace + name;
|
||||
if(fullName.equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")) {
|
||||
NamedNodeMap attributes = child.getAttributes();
|
||||
Node resourceAttribute = attributes.getNamedItemNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "resource");
|
||||
if(resourceAttribute != null) {
|
||||
//String attributeNamespace = resourceAttribute.getNamespaceURI();
|
||||
String value = resourceAttribute.getNodeValue();
|
||||
//rdfTypesList.add(attributeNamespace + value);
|
||||
rdfTypesList.add(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return rdfTypesList;
|
||||
}
|
||||
|
||||
/**
|
||||
* If a session info object exists for this session ID, abort the thread if it is still running and remove the object.
|
||||
* @param sessionId the session ID for which to clear info
|
||||
*/
|
||||
private void clearSessionInfo(String sessionId) {
|
||||
SessionInfo sessionInfo = this.sessionIdToSessionInfo.get(sessionId);
|
||||
if(sessionInfo != null) {
|
||||
if(!sessionInfo.isFinished()) {
|
||||
if(sessionInfo.harvestThread.isAlive()) {
|
||||
sessionInfo.harvestThread.abortRun();
|
||||
}
|
||||
}
|
||||
this.sessionIdToSessionInfo.remove(sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If all goes according to plan, clearSessionInfo() should be called once the client gets the last bit of information from the
|
||||
* harvest. However, if the client doesn't request it (because the browser was closed, etc.) then the method will never get called.
|
||||
* This method gets called every time the page is initially loaded, to look for session data that is 6 hours old or more, and remove
|
||||
* it.
|
||||
*/
|
||||
private void cleanUpOldSessions() {
|
||||
int minutesToAllowSession = 360;
|
||||
long millisecondsToAllowSession = minutesToAllowSession * 60 * 1000;
|
||||
|
||||
Date now = new Date();
|
||||
Set<String> keySet = this.sessionIdToSessionInfo.keySet();
|
||||
for(String sessionId : keySet) {
|
||||
SessionInfo info = this.sessionIdToSessionInfo.get(sessionId);
|
||||
Date startTime = info.createTime;
|
||||
long differenceInMilliseconds = now.getTime() - startTime.getTime();
|
||||
if(differenceInMilliseconds > millisecondsToAllowSession) {
|
||||
log.debug("Removing old session: " + sessionId);
|
||||
clearSessionInfo(sessionId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create a new JSON object
|
||||
* @param fatalError whether the fatal error flag should be set on this object
|
||||
* @return the new JSON object
|
||||
*/
|
||||
private JSONObject generateJson(boolean fatalError) {
|
||||
JSONObject json = null;
|
||||
try {
|
||||
json = new JSONObject();
|
||||
json.put("fatalError", fatalError);
|
||||
} catch(JSONException e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Information relating to a particular user session, created just before the harvester thread is starting.
|
||||
* @author mbarbieri
|
||||
*/
|
||||
private class SessionInfo {
|
||||
|
||||
/**
|
||||
* The session ID for this user session.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public final String sessionId;
|
||||
|
||||
/**
|
||||
* The time this object was created.
|
||||
*/
|
||||
public final Date createTime;
|
||||
|
||||
/**
|
||||
* The Harvester thread for his user session.
|
||||
*/
|
||||
public final ScriptRunner harvestThread;
|
||||
|
||||
/**
|
||||
* Harvester output that has not yet been sent back to the browser, for this user session.
|
||||
*/
|
||||
public final ArrayList<String> unsentLogLines = new ArrayList<String>();
|
||||
|
||||
/**
|
||||
* Flag indicating that the thread has finished.
|
||||
*/
|
||||
private boolean finished = false;
|
||||
|
||||
/**
|
||||
* Flag indicating that the thread finished abnormally.
|
||||
*/
|
||||
private boolean abnormalTermination = false;
|
||||
|
||||
|
||||
/**
|
||||
* Newly added entries to VIVO, for this user session.
|
||||
*/
|
||||
public final ArrayList<String> newlyAddedUris = new ArrayList<String>();
|
||||
|
||||
public SessionInfo(String sessionId, ScriptRunner harvestThread) {
|
||||
|
||||
this.createTime = new Date();
|
||||
|
||||
this.sessionId = sessionId;
|
||||
this.harvestThread = harvestThread;
|
||||
}
|
||||
|
||||
public void setAbnormalTermination() {
|
||||
abnormalTermination = true;
|
||||
}
|
||||
public boolean getAbnormalTermination() {
|
||||
return abnormalTermination;
|
||||
}
|
||||
|
||||
public void finish() {
|
||||
finished = true;
|
||||
}
|
||||
public boolean isFinished() {
|
||||
return finished;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Provides a way of throwing an exception whose message it is OK to display unedited to the user.
|
||||
*/
|
||||
private class ExceptionVisibleToUser extends Exception {
|
||||
private static final long serialVersionUID = 1L;
|
||||
public ExceptionVisibleToUser(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private class ScriptRunner extends Thread {
|
||||
|
||||
private final String sessionId;
|
||||
private final String script;
|
||||
private final String additionsFilePath;
|
||||
private final String scriptFileLocation;
|
||||
private final FileHarvestJob job;
|
||||
|
||||
private volatile boolean abort = false;
|
||||
|
||||
public ScriptRunner(String sessionId, String script, String additionsFilePath, String scriptFileLocation, FileHarvestJob job) {
|
||||
this.sessionId = sessionId;
|
||||
this.script = script;
|
||||
this.additionsFilePath = additionsFilePath;
|
||||
this.scriptFileLocation = scriptFileLocation;
|
||||
this.job = job;
|
||||
}
|
||||
|
||||
public void abortRun() {
|
||||
abort = true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
SessionInfo sessionInfo = sessionIdToSessionInfo.get(sessionId);
|
||||
boolean normalTerminationLineFound = false;
|
||||
if(sessionInfo != null) {
|
||||
try {
|
||||
ArrayList<String> unsentLogLines = sessionInfo.unsentLogLines;
|
||||
|
||||
File scriptFile = createScriptFile(this.scriptFileLocation, this.script);
|
||||
|
||||
String command = "/bin/bash " + this.scriptFileLocation + scriptFile.getName();
|
||||
|
||||
log.info("Running command: " + command);
|
||||
Process pr = Runtime.getRuntime().exec(command);
|
||||
|
||||
//try { Thread.sleep(15000); } catch(InterruptedException e) {log.error(e, e);}
|
||||
|
||||
BufferedReader processOutputReader = new BufferedReader(new InputStreamReader(pr.getInputStream()));
|
||||
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);
|
||||
}
|
||||
log.info("Harvester output: " + line);
|
||||
|
||||
if(this.abort)
|
||||
break;
|
||||
}
|
||||
|
||||
if(!this.abort){
|
||||
BufferedReader processErrorReader = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
|
||||
for(String line = processErrorReader.readLine(); line != null; line = processErrorReader.readLine()) {
|
||||
log.info("Harvester error: " + line);
|
||||
|
||||
if(this.abort)
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if(this.abort) {
|
||||
log.debug("Aborting harvester script for session " + this.sessionId + ".");
|
||||
pr.destroy();
|
||||
} else {
|
||||
int exitVal;
|
||||
|
||||
try {
|
||||
exitVal = pr.waitFor();
|
||||
}
|
||||
catch(InterruptedException e) {
|
||||
throw new IOException(e.getMessage(), e);
|
||||
}
|
||||
|
||||
log.debug("Harvester script for session " + this.sessionId + " exited with error code " + exitVal);
|
||||
|
||||
File additionsFile = new File(this.additionsFilePath);
|
||||
if(additionsFile.exists())
|
||||
extractNewlyAddedUris(additionsFile, sessionInfo.newlyAddedUris, this.job);
|
||||
else
|
||||
log.error("Additions file not found: " + this.additionsFilePath);
|
||||
}
|
||||
|
||||
log.info("Harvester script execution complete");
|
||||
} catch (IOException e) {
|
||||
log.error(e, e);
|
||||
} finally {
|
||||
sessionInfo.finish();
|
||||
if(!normalTerminationLineFound)
|
||||
sessionInfo.setAbnormalTermination();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,77 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.harvester;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
|
||||
/**
|
||||
* Handles specifics of a file harvest.
|
||||
* @author mbarbieri
|
||||
*
|
||||
*/
|
||||
interface FileHarvestJob {
|
||||
|
||||
/**
|
||||
* Checks to make sure the uploaded file can be handled by this job (for instance, are we looking for a CSV file with specific columns?)
|
||||
* @param file the uploaded file to check
|
||||
* @return null if success, message to be returned to the user if failure
|
||||
*/
|
||||
String validateUpload(File file);
|
||||
|
||||
/**
|
||||
* Gets the path on the server of the file which the user can download to serve as a guide for what to upload.
|
||||
* @return the path on the server of the file which the user can download to serve as a guide for what to upload.
|
||||
*/
|
||||
String getTemplateFilePath();
|
||||
|
||||
/**
|
||||
* 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();
|
||||
|
||||
/**
|
||||
* The path to the file containing the RDF/XML triples that get added to VIVO.
|
||||
* @return the path to the file containing the RDF/XML triples that get added to VIVO
|
||||
*/
|
||||
String getAdditionsFilePath();
|
||||
|
||||
/**
|
||||
* A heading to be shown at the top of the page.
|
||||
* @return a heading to be shown at the top of the page
|
||||
*/
|
||||
String getPageHeader();
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @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
|
||||
*/
|
||||
String getNoNewDataMessage();
|
||||
}
|
||||
|
|
@ -0,0 +1,188 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.harvester;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
/* //PLEASE SEE JAVADOC COMMENT FOR CLASS BELOW
|
||||
import org.vivoweb.harvester.diff.Diff;
|
||||
import org.vivoweb.harvester.fetch.CSVtoRDF;
|
||||
import org.vivoweb.harvester.fetch.D2RMapFetch;
|
||||
import org.vivoweb.harvester.fetch.JDBCFetch;
|
||||
import org.vivoweb.harvester.fetch.NLMJournalFetch;
|
||||
import org.vivoweb.harvester.fetch.OAIFetch;
|
||||
import org.vivoweb.harvester.fetch.PubmedFetch;
|
||||
import org.vivoweb.harvester.fetch.PubmedHTTPFetch;
|
||||
import org.vivoweb.harvester.qualify.ChangeNamespace;
|
||||
import org.vivoweb.harvester.qualify.Qualify;
|
||||
import org.vivoweb.harvester.qualify.RenameBlankNodes;
|
||||
import org.vivoweb.harvester.qualify.RenameResources;
|
||||
import org.vivoweb.harvester.qualify.Smush;
|
||||
import org.vivoweb.harvester.qualify.SplitProperty;
|
||||
import org.vivoweb.harvester.score.Match;
|
||||
import org.vivoweb.harvester.score.PubmedScore;
|
||||
import org.vivoweb.harvester.score.Score;
|
||||
import org.vivoweb.harvester.transfer.Transfer;
|
||||
import org.vivoweb.harvester.translate.GlozeTranslator;
|
||||
import org.vivoweb.harvester.translate.RunBibutils;
|
||||
import org.vivoweb.harvester.translate.SPARQLTranslator;
|
||||
import org.vivoweb.harvester.translate.SanitizeMODSXML;
|
||||
import org.vivoweb.harvester.translate.XSLTranslator;
|
||||
import org.vivoweb.harvester.util.CSVtoJDBC;
|
||||
import org.vivoweb.harvester.util.DatabaseClone;
|
||||
import org.vivoweb.harvester.util.Merge;
|
||||
import org.vivoweb.harvester.util.XPathTool;
|
||||
*/
|
||||
|
||||
/**
|
||||
* *** NOTE: This is currently completely commented-out until we (all VIVO developers) decide on a policy for
|
||||
* integrating the Harvester with the rest of VIVO. If Harvester is added to the classpath of VIVO,
|
||||
* this can be uncommented and will work fine. ***
|
||||
|
||||
* Interface to the Harvester.
|
||||
*
|
||||
* The best approach for doing this is probably a bunch of static methods that call the Harvester main classes.
|
||||
* At first I tried to call the execute() methods, using the object parameters rather than the raw string args,
|
||||
* 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.
|
||||
*
|
||||
* @author mbarbieri
|
||||
*
|
||||
*/
|
||||
class Harvester {
|
||||
/*
|
||||
// diff
|
||||
public static void runDiff(Object ... args) {
|
||||
Diff.main(stringsToArray(args));
|
||||
}
|
||||
|
||||
// fetch
|
||||
public static void runCSVtoRDF(Object ... args) {
|
||||
CSVtoRDF.main(stringsToArray(args));
|
||||
}
|
||||
public static void runD2RMapFetch(Object ... args) {
|
||||
D2RMapFetch.main(stringsToArray(args));
|
||||
}
|
||||
public static void runJDBCFetch(Object ... args) {
|
||||
JDBCFetch.main(stringsToArray(args));
|
||||
}
|
||||
public static void runNLMJournalFetch(Object ... args) {
|
||||
NLMJournalFetch.main(stringsToArray(args));
|
||||
}
|
||||
public static void runOAIFetch(Object ... args) {
|
||||
OAIFetch.main(stringsToArray(args));
|
||||
}
|
||||
public static void runPubmedFetch(Object ... args) {
|
||||
PubmedFetch.main(stringsToArray(args));
|
||||
}
|
||||
public static void runPubmedHTTPFetch(Object ... args) {
|
||||
PubmedHTTPFetch.main(stringsToArray(args));
|
||||
}
|
||||
|
||||
// qualify
|
||||
public static void runChangeNamespace(Object ... args) {
|
||||
ChangeNamespace.main(stringsToArray(args));
|
||||
}
|
||||
public static void runQualify(Object ... args) {
|
||||
Qualify.main(stringsToArray(args));
|
||||
}
|
||||
public static void runRenameBlankNodes(Object ... args) {
|
||||
RenameBlankNodes.main(stringsToArray(args));
|
||||
}
|
||||
public static void runRenameResources(Object ... args) {
|
||||
RenameResources.main(stringsToArray(args));
|
||||
}
|
||||
public static void runSmush(Object ... args) {
|
||||
Smush.main(stringsToArray(args));
|
||||
}
|
||||
public static void runSplitProperty(Object ... args) {
|
||||
SplitProperty.main(stringsToArray(args));
|
||||
}
|
||||
|
||||
// score
|
||||
public static void runMatch(Object ... args) {
|
||||
Match.main(stringsToArray(args));
|
||||
}
|
||||
public static void runPubmedScore(Object ... args) {
|
||||
PubmedScore.main(stringsToArray(args));
|
||||
}
|
||||
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));
|
||||
}
|
||||
public static void runRunBibutils(Object ... args) {
|
||||
RunBibutils.main(stringsToArray(args));
|
||||
}
|
||||
public static void runSanitizeMODSXML(Object ... args) {
|
||||
SanitizeMODSXML.main(stringsToArray(args));
|
||||
}
|
||||
public static void runSPARQLTranslator(Object ... args) {
|
||||
SPARQLTranslator.main(stringsToArray(args));
|
||||
}
|
||||
public static void runXSLTranslator(Object ... args) {
|
||||
XSLTranslator.main(stringsToArray(args));
|
||||
}
|
||||
|
||||
// util
|
||||
public static void runCSVtoJDBC(Object ... args) {
|
||||
CSVtoJDBC.main(stringsToArray(args));
|
||||
}
|
||||
public static void runDatabaseClone(Object ... args) {
|
||||
DatabaseClone.main(stringsToArray(args));
|
||||
}
|
||||
public static void runMerge(Object ... args) {
|
||||
Merge.main(stringsToArray(args));
|
||||
}
|
||||
public static void runXPathTool(Object ... args) {
|
||||
XPathTool.main(stringsToArray(args));
|
||||
}
|
||||
*/
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* 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
|
||||
*/
|
||||
public static String[] stringsToArray(Object ... args) {
|
||||
ArrayList<String> allData = new ArrayList<String>();
|
||||
for(int i = 0; i < args.length; i++) {
|
||||
if(args[i] instanceof String[]) {
|
||||
String[] array = (String[])(args[i]);
|
||||
for(int j = 0; j < array.length; j++) {
|
||||
allData.add(array[j]);
|
||||
}
|
||||
} else {
|
||||
allData.add(args[i].toString());
|
||||
}
|
||||
}
|
||||
return allData.toArray(new String[allData.size()]);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.individuallist;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import com.hp.hpl.jena.query.QuerySolution;
|
||||
import com.hp.hpl.jena.query.ResultSet;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyStatementDao;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.jena.QueryUtils;
|
||||
|
||||
/**
|
||||
* Wrap an Individual in a JSON object for display by the script.
|
||||
*
|
||||
* This overrides the Vitro version so we can have more info in the display.
|
||||
*/
|
||||
public class IndividualJsonWrapper {
|
||||
private static final Log log = LogFactory
|
||||
.getLog(IndividualJsonWrapper.class);
|
||||
|
||||
private static String VCARD_DATA_QUERY = ""
|
||||
+ "PREFIX obo: <http://purl.obolibrary.org/obo/> \n"
|
||||
+ "PREFIX vcard: <http://www.w3.org/2006/vcard/ns#> \n"
|
||||
+ "SELECT DISTINCT ?title \n" + "WHERE { \n"
|
||||
+ " ?subject obo:ARG_2000028 ?vIndividual . \n"
|
||||
+ " ?vIndividual vcard:hasTitle ?vTitle . \n"
|
||||
+ " ?vTitle vcard:title ?title . \n" + "} ";
|
||||
|
||||
static JSONObject packageIndividualAsJson(VitroRequest vreq, Individual ind)
|
||||
throws JSONException {
|
||||
// need an unfiltered dao to get firstnames and lastnames
|
||||
WebappDaoFactory fullWdf = vreq.getUnfilteredWebappDaoFactory();
|
||||
|
||||
JSONObject jo = new JSONObject();
|
||||
jo.put("URI", ind.getURI());
|
||||
jo.put("label", ind.getRdfsLabel());
|
||||
jo.put("name", ind.getName());
|
||||
jo.put("thumbUrl", ind.getThumbUrl());
|
||||
jo.put("imageUrl", ind.getImageUrl());
|
||||
jo.put("profileUrl", UrlBuilder.getIndividualProfileUrl(ind, vreq));
|
||||
jo.put("mostSpecificTypes", getMostSpecificTypes(ind, fullWdf));
|
||||
jo.put("preferredTitle", findPreferredTitle(vreq, ind));
|
||||
return jo;
|
||||
}
|
||||
|
||||
private static String findPreferredTitle(VitroRequest vreq, Individual ind) {
|
||||
String queryStr = QueryUtils.subUriForQueryVar(VCARD_DATA_QUERY,
|
||||
"subject", ind.getURI());
|
||||
log.debug("queryStr = " + queryStr);
|
||||
String value = "";
|
||||
try {
|
||||
ResultSet results = QueryUtils.getQueryResults(queryStr, vreq);
|
||||
while (results.hasNext()) {
|
||||
QuerySolution soln = results.nextSolution();
|
||||
String t = QueryUtils.nodeToString(soln.get("title"));
|
||||
if (StringUtils.isNotBlank(t)) {
|
||||
value = t;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e, e);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public static Collection<String> getMostSpecificTypes(
|
||||
Individual individual, WebappDaoFactory wdf) {
|
||||
ObjectPropertyStatementDao opsDao = wdf.getObjectPropertyStatementDao();
|
||||
Map<String, String> mostSpecificTypes = opsDao
|
||||
.getMostSpecificTypesInClassgroupsForIndividual(individual
|
||||
.getURI());
|
||||
return mostSpecificTypes.values();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,189 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.visualization;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.query.Dataset;
|
||||
import com.hp.hpl.jena.query.Syntax;
|
||||
import com.hp.hpl.jena.rdf.model.Model;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.AuthorizationRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerHttpServlet;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.TemplateProcessingHelper.TemplateProcessingException;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
|
||||
import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException;
|
||||
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.UtilityFunctions;
|
||||
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.VisualizationRequestHandler;
|
||||
|
||||
/**
|
||||
* Services a visualization request. This will return a simple error message and a 501 if
|
||||
* there is no jena Model.
|
||||
*
|
||||
* @author cdtank
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
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
|
||||
* request handler.
|
||||
* */
|
||||
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
|
||||
* request handler.
|
||||
* */
|
||||
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
|
||||
* object we are side-effecting this method.
|
||||
* */
|
||||
return renderVisualization(vreq, visRequestHandler);
|
||||
|
||||
} else {
|
||||
|
||||
return UtilityFunctions.handleMalformedParameters(
|
||||
"Visualization Query Error",
|
||||
"Inappropriate query parameters were submitted.",
|
||||
vreq);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
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 "
|
||||
+ "servlet context.";
|
||||
|
||||
log.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,
|
||||
dataset);
|
||||
} catch (MalformedQueryParametersException e) {
|
||||
return UtilityFunctions.handleMalformedParameters(
|
||||
"Ajax Visualization Query Error - Individual Publication Count",
|
||||
e.getMessage(),
|
||||
vitroRequest);
|
||||
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
String errorMessage = "Data Model Empty &/or Inappropriate "
|
||||
+ "query parameters were submitted. ";
|
||||
|
||||
log.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;
|
||||
}
|
||||
|
||||
private Dataset setupJENADataSource(VitroRequest vreq) {
|
||||
return vreq.getDataset();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,171 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.visualization;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.query.Dataset;
|
||||
import com.hp.hpl.jena.query.Syntax;
|
||||
import com.hp.hpl.jena.rdf.model.Model;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.visualization.constants.VisConstants;
|
||||
import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException;
|
||||
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.UtilityFunctions;
|
||||
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.VisualizationRequestHandler;
|
||||
|
||||
/**
|
||||
* Services a visualization request. This will return a simple error message and a 501 if
|
||||
* there is no jena Model.
|
||||
*
|
||||
* @author cdtank
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
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
|
||||
* request handler.
|
||||
* */
|
||||
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",
|
||||
"attachment;filename=" + dataResponse.get(FILE_NAME_KEY));
|
||||
}
|
||||
|
||||
response.getWriter().write(dataResponse.get(FILE_CONTENT_KEY));
|
||||
|
||||
return;
|
||||
|
||||
} catch (MalformedQueryParametersException e) {
|
||||
|
||||
UtilityFunctions.handleMalformedParameters(e.getMessage(),
|
||||
response,
|
||||
log);
|
||||
}
|
||||
|
||||
return;
|
||||
|
||||
} else {
|
||||
|
||||
UtilityFunctions.handleMalformedParameters(
|
||||
"Inappropriate query parameters were submitted.",
|
||||
response,
|
||||
log);
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
private Map<String, String> renderVisualization(
|
||||
VitroRequest vitroRequest,
|
||||
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 "
|
||||
+ "servlet context.";
|
||||
|
||||
log.error(errorMessage);
|
||||
|
||||
throw new MalformedQueryParametersException(errorMessage);
|
||||
}
|
||||
|
||||
Dataset dataset = setupJENADataSource(vitroRequest);
|
||||
|
||||
if (dataset != null && visRequestHandler != null) {
|
||||
return visRequestHandler.generateDataVisualization(vitroRequest,
|
||||
log,
|
||||
dataset);
|
||||
|
||||
} else {
|
||||
|
||||
String errorMessage = "Data Model Empty &/or Inappropriate "
|
||||
+ "query parameters were submitted. ";
|
||||
|
||||
throw new MalformedQueryParametersException(errorMessage);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
private Dataset setupJENADataSource(VitroRequest vreq) {
|
||||
|
||||
log.debug("rdfResultFormat was: " + VisConstants.RDF_RESULT_FORMAT_PARAM);
|
||||
|
||||
return vreq.getDataset();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,266 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.visualization;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
|
||||
import org.apache.commons.lang.StringEscapeUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.query.Dataset;
|
||||
import com.hp.hpl.jena.query.Syntax;
|
||||
import com.hp.hpl.jena.rdf.model.Model;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.AuthorizationRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerHttpServlet;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
|
||||
import edu.cornell.mannlib.vitro.webapp.visualization.constants.VisConstants;
|
||||
import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException;
|
||||
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
|
||||
* error message and a 501 if there is no jena Model.
|
||||
*
|
||||
* @author cdtank
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
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
|
||||
* request handler.
|
||||
* */
|
||||
VisualizationRequestHandler visRequestHandler =
|
||||
getVisualizationRequestHandler(vreq);
|
||||
|
||||
if (visRequestHandler != null) {
|
||||
|
||||
AuthorizationRequest requiredPrivileges = visRequestHandler.getRequiredPrivileges();
|
||||
if (requiredPrivileges != null) {
|
||||
return requiredPrivileges;
|
||||
}
|
||||
}
|
||||
return super.requiredActions(vreq);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ResponseValues processRequest(VitroRequest vreq) {
|
||||
|
||||
/*
|
||||
* Based on the query parameters passed via URI get the appropriate visualization
|
||||
* request handler.
|
||||
* */
|
||||
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.",
|
||||
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 "
|
||||
+ "servlet context.";
|
||||
|
||||
log.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(),
|
||||
vitroRequest);
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
String errorMessage = "Data Model Empty &/or Inappropriate "
|
||||
+ "query parameters were submitted. ";
|
||||
|
||||
log.error(errorMessage);
|
||||
|
||||
return UtilityFunctions.handleMalformedParameters("Visualization Query Error",
|
||||
errorMessage,
|
||||
vitroRequest);
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
* 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()
|
||||
+ matchedPatternGroups.get(1);
|
||||
}
|
||||
|
||||
subjectURI = StringEscapeUtils.escapeHtml(subjectURI);
|
||||
parameters.put(VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, subjectURI);
|
||||
|
||||
if (VisualizationFrameworkConstants.COAUTHORSHIP_VIS_SHORT_URL
|
||||
.equalsIgnoreCase(matchedPatternGroups.get(0))) {
|
||||
|
||||
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,
|
||||
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
|
||||
* 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()
|
||||
// + " -- " + vitroRequest.getContextPath()
|
||||
// + " -- " + vitroRequest.getContextPath().length()
|
||||
// + " -- " + vitroRequest.getRequestURI().substring(vitroRequest.getContextPath().length()));
|
||||
|
||||
visType = matchedPatternGroups.get(0);
|
||||
|
||||
try {
|
||||
visRequestHandler = VisualizationsDependencyInjector
|
||||
.getVisualizationIDsToClassMap(getServletContext())
|
||||
.get(visType);
|
||||
} catch (NullPointerException nullKeyException) {
|
||||
/*
|
||||
* Let the default flow take care of returning a null.
|
||||
* */
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return visRequestHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* An ideal short url request would mimic,
|
||||
* vivo.com/vis/author-network/shortURI
|
||||
* vivo.com/vis/grant-graph/shortURI
|
||||
* etc. So first we obtain the request url which can be used to extract the requested visualization
|
||||
* and the subject of the visualization. So the below pattern matcher will take "/vis/<vis-name>/<shortURI>"
|
||||
* as an input.
|
||||
*/
|
||||
private List<String> extractShortURLParameters(VitroRequest vitroRequest) {
|
||||
|
||||
List<String> matchedGroups = new ArrayList<String>();
|
||||
String subURIString = vitroRequest.getRequestURI().substring(vitroRequest.getContextPath().length()+1);
|
||||
String[] urlParams = StringEscapeUtils.escapeHtml(subURIString).split("/");
|
||||
|
||||
if (urlParams.length > 1
|
||||
&& urlParams[0].equalsIgnoreCase("vis")) {
|
||||
for (int ii=1; ii < urlParams.length; ii++) {
|
||||
matchedGroups.add(urlParams[ii]);
|
||||
}
|
||||
}
|
||||
|
||||
return matchedGroups;
|
||||
}
|
||||
|
||||
private Dataset setupJENADataSource(VitroRequest vreq) {
|
||||
|
||||
log.debug("rdfResultFormat was: " + VisConstants.RDF_RESULT_FORMAT_PARAM);
|
||||
|
||||
return vreq.getDataset();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,165 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.visualization;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.query.Dataset;
|
||||
import com.hp.hpl.jena.query.Syntax;
|
||||
import com.hp.hpl.jena.rdf.model.Model;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.AuthorizationRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerHttpServlet;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
|
||||
import edu.cornell.mannlib.vitro.webapp.visualization.constants.VisConstants;
|
||||
import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException;
|
||||
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
|
||||
* error message and a 501 if there is no jena Model.
|
||||
*
|
||||
* @author cdtank
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
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
|
||||
* request handler.
|
||||
* */
|
||||
VisualizationRequestHandler visRequestHandler =
|
||||
getVisualizationRequestHandler(vreq);
|
||||
|
||||
if (visRequestHandler != null) {
|
||||
|
||||
AuthorizationRequest requiredPrivileges = visRequestHandler.getRequiredPrivileges();
|
||||
if (requiredPrivileges != null) {
|
||||
return requiredPrivileges;
|
||||
}
|
||||
}
|
||||
return super.requiredActions(vreq);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ResponseValues processRequest(VitroRequest vreq) {
|
||||
/*
|
||||
* Based on the query parameters passed via URI get the appropriate visualization
|
||||
* request handler.
|
||||
* */
|
||||
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.",
|
||||
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 "
|
||||
+ "servlet context.";
|
||||
|
||||
log.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,
|
||||
dataset);
|
||||
} catch (MalformedQueryParametersException e) {
|
||||
return UtilityFunctions.handleMalformedParameters(
|
||||
"Standard Visualization Query Error - Individual Publication Count",
|
||||
e.getMessage(),
|
||||
vitroRequest);
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
String errorMessage = "Data Model Empty &/or Inappropriate "
|
||||
+ "query parameters were submitted. ";
|
||||
|
||||
log.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;
|
||||
}
|
||||
|
||||
private Dataset setupJENADataSource(VitroRequest vreq) {
|
||||
|
||||
log.debug("rdfResultFormat was: " + VisConstants.RDF_RESULT_FORMAT_PARAM);
|
||||
|
||||
return vreq.getDataset();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,141 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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";
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,64 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.visualization;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
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.
|
||||
* @param servletContext
|
||||
* @return
|
||||
*/
|
||||
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.
|
||||
* */
|
||||
if (visualizationIDsToClass != null) {
|
||||
return visualizationIDsToClass;
|
||||
}
|
||||
|
||||
String resourcePath =
|
||||
servletContext
|
||||
.getRealPath(VisualizationFrameworkConstants
|
||||
.RELATIVE_LOCATION_OF_FM_VISUALIZATIONS_BEAN);
|
||||
|
||||
ApplicationContext context = new ClassPathXmlApplicationContext(
|
||||
"file:" + resourcePath);
|
||||
|
||||
BeanFactory factory = context;
|
||||
|
||||
VisualizationInjector visualizationInjector =
|
||||
(VisualizationInjector) factory.getBean("visualizationInjector");
|
||||
|
||||
visualizationIDsToClass = visualizationInjector.getVisualizationIDToClass();
|
||||
|
||||
|
||||
return visualizationIDsToClass;
|
||||
}
|
||||
|
||||
public static Map<String, VisualizationRequestHandler> getVisualizationIDsToClassMap(
|
||||
ServletContext servletContext) {
|
||||
if (visualizationIDsToClass != null) {
|
||||
return visualizationIDsToClass;
|
||||
} else {
|
||||
return initVisualizations(servletContext);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,74 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.N3ValidatorVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmission;
|
||||
|
||||
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>();
|
||||
|
||||
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<")) {
|
||||
selectedUri = null;
|
||||
}
|
||||
if (selectedUri != null) {
|
||||
return null;
|
||||
}
|
||||
else {
|
||||
List<Literal> specifiedLabel = literalsFromForm.get(labelInput);
|
||||
if (specifiedLabel != null && specifiedLabel.size() > 0) {
|
||||
return null;
|
||||
}
|
||||
else {
|
||||
errors.put(labelInput, MISSING_LABEL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
return errors.size() != 0 ? errors : null;
|
||||
}
|
||||
|
||||
private boolean allListElementsEmpty(List<String> checkList) {
|
||||
if(checkList == null)
|
||||
return true;
|
||||
if(checkList.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
boolean allEmpty = true;
|
||||
for(String s: checkList) {
|
||||
if(s.length() != 0){
|
||||
allEmpty = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return allEmpty;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,100 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.N3ValidatorVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmission;
|
||||
|
||||
public class FirstAndLastNameValidator 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.";
|
||||
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>();
|
||||
|
||||
List<String> personUri = urisFromForm.get(uriReceiver);
|
||||
if (allListElementsEmpty(personUri) || personUri.contains(">SUBMITTED VALUE WAS BLANK<")) {
|
||||
personUri = null;
|
||||
}
|
||||
// If there's an personUri, then we're done. The firstName and lastName fields are
|
||||
// disabled and so don't get submitted.
|
||||
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;
|
||||
List<Literal> firstNameList = literalsFromForm.get("firstName");
|
||||
if(firstNameList != null && firstNameList.size() > 0) {
|
||||
firstName = firstNameList.get(0);
|
||||
}
|
||||
if( firstName != null &&
|
||||
firstName.getLexicalForm() != null &&
|
||||
"".equals(firstName.getLexicalForm()) )
|
||||
firstName = null;
|
||||
|
||||
|
||||
List<Literal> lastNameList = literalsFromForm.get("lastName");
|
||||
Literal lastName = null;
|
||||
if(lastNameList != null && lastNameList.size() > 0) {
|
||||
lastName = lastNameList.get(0);
|
||||
}
|
||||
String lastNameValue = "";
|
||||
if (lastName != null) {
|
||||
lastNameValue = lastName.getLexicalForm();
|
||||
if( "".equals(lastNameValue) ) {
|
||||
lastName = null;
|
||||
}
|
||||
}
|
||||
|
||||
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(",")) {
|
||||
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;
|
||||
if(checkList.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
boolean allEmpty = true;
|
||||
for(String s: checkList) {
|
||||
if(s.length() != 0){
|
||||
allEmpty = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return allEmpty;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,70 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class N3TransitionToV2Mapping extends HashMap<String, String>{
|
||||
public N3TransitionToV2Mapping(){
|
||||
Map<String,String> map = this;
|
||||
|
||||
// vivo forms:
|
||||
|
||||
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());
|
||||
map.put("newIndividualForm.jsp",
|
||||
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.NewIndividualFormGenerator.class.getName());
|
||||
map.put("organizationHasPositionHistory.jsp",
|
||||
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.OrganizationHasPositionHistoryGenerator.class.getName());
|
||||
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());
|
||||
map.put("addGrantRoleToPerson.jsp",
|
||||
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddGrantRoleToPersonGenerator.class.getName());
|
||||
map.put("addEditWebpageForm.jsp",
|
||||
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddEditWebpageFormGenerator.class.getName());
|
||||
map.put("addPublicationToPerson.jsp",
|
||||
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddPublicationToPersonGenerator.class.getName());
|
||||
|
||||
// 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",
|
||||
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddAttendeeRoleToPersonGenerator.class.getName());
|
||||
map.put("addClinicalRoleToPerson.jsp",
|
||||
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddClinicalRoleToPersonGenerator.class.getName());
|
||||
map.put("addEditorRoleToPerson.jsp",
|
||||
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddEditorRoleToPersonGenerator.class.getName());
|
||||
map.put("addHeadOfRoleToPerson.jsp",
|
||||
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddHeadOfRoleToPersonGenerator.class.getName());
|
||||
map.put("addMemberRoleToPerson.jsp",
|
||||
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddMemberRoleToPersonGenerator.class.getName());
|
||||
map.put("addOrganizerRoleToPerson.jsp",
|
||||
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddOrganizerRoleToPersonGenerator.class.getName());
|
||||
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());
|
||||
map.put("addResearcherRoleToPerson.jsp",
|
||||
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddResearcherRoleToPersonGenerator.class.getName());
|
||||
map.put("addReviewerRoleToPerson.jsp",
|
||||
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddReviewerRoleToPersonGenerator.class.getName());
|
||||
map.put("addRoleToPersonTwoStage.jsp",
|
||||
edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddRoleToPersonTwoStageGenerator.class.getName());
|
||||
map.put("addServiceProviderRoleToPerson.jsp",
|
||||
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());
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,89 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.N3ValidatorVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmission;
|
||||
|
||||
public class PersonHasPublicationValidator implements N3ValidatorVTwo {
|
||||
|
||||
private Log log = LogFactory.getLog(PersonHasPublicationValidator.class);
|
||||
|
||||
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) {
|
||||
|
||||
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
|
||||
// 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");
|
||||
Literal firstName = null;
|
||||
if(firstNameList != null && firstNameList.size() > 0) {
|
||||
firstName = firstNameList.get(0);
|
||||
}
|
||||
if ( firstName != null &&
|
||||
firstName.getLexicalForm() != null &&
|
||||
"".equals(firstName.getLexicalForm()) )
|
||||
firstName = null;
|
||||
|
||||
List<Literal> lastNameList = literalsFromForm.get("lastName");
|
||||
Literal lastName = null;
|
||||
if(lastNameList != null && lastNameList.size() > 0) {
|
||||
lastName = lastNameList.get(0);
|
||||
}
|
||||
String lastNameValue = "";
|
||||
if (lastName != null) {
|
||||
lastNameValue = lastName.getLexicalForm();
|
||||
if( "".equals(lastNameValue) ) {
|
||||
lastName = null;
|
||||
}
|
||||
}
|
||||
|
||||
if ( lastName == null && firstName != null ) {
|
||||
errors.put("lastName", MISSING_LAST_NAME_ERROR);
|
||||
// Don't reject space in the last name: de Vries, etc.
|
||||
}
|
||||
else if ( firstName == null && lastName != null) {
|
||||
errors.put("firstName", MISSING_FIRST_NAME_ERROR);
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,109 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing;
|
||||
|
||||
import java.lang.String;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.N3ValidatorVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmission;
|
||||
|
||||
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>();
|
||||
|
||||
List<String> personUri = urisFromForm.get("personUri");
|
||||
List<String> orgUri = urisFromForm.get("orgUri");
|
||||
List<Literal> orgNameList = literalsFromForm.get("orgName");
|
||||
|
||||
if (allListElementsEmpty(personUri)) {
|
||||
personUri = null;
|
||||
}
|
||||
if (allListElementsEmpty(orgUri)) {
|
||||
orgUri = null;
|
||||
}
|
||||
Literal orgName = null;
|
||||
if(orgNameList != null && orgNameList.size() > 0) {
|
||||
orgName = orgNameList.get(0);
|
||||
}
|
||||
// If there's a personUri, orgUri or orgName, then we're done. The firstName and lastName fields are
|
||||
// disabled and so don't get submitted.
|
||||
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;
|
||||
List<Literal> firstNameList = literalsFromForm.get("firstName");
|
||||
if(firstNameList != null && firstNameList.size() > 0) {
|
||||
firstName = firstNameList.get(0);
|
||||
}
|
||||
if( firstName != null &&
|
||||
firstName.getLexicalForm() != null &&
|
||||
"".equals(firstName.getLexicalForm()) )
|
||||
firstName = null;
|
||||
|
||||
|
||||
List<Literal> lastNameList = literalsFromForm.get("lastName");
|
||||
Literal lastName = null;
|
||||
if(lastNameList != null && lastNameList.size() > 0) {
|
||||
lastName = lastNameList.get(0);
|
||||
}
|
||||
String lastNameValue = "";
|
||||
if (lastName != null) {
|
||||
lastNameValue = lastName.getLexicalForm();
|
||||
if( "".equals(lastNameValue) ) {
|
||||
lastName = null;
|
||||
}
|
||||
}
|
||||
|
||||
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(",")) {
|
||||
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;
|
||||
if(checkList.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
boolean allEmpty = true;
|
||||
for(String s: checkList) {
|
||||
if(s.length() != 0){
|
||||
allEmpty = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return allEmpty;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,569 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
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 com.hp.hpl.jena.ontology.OntModel;
|
||||
import com.hp.hpl.jena.query.Query;
|
||||
import com.hp.hpl.jena.query.QueryExecution;
|
||||
import com.hp.hpl.jena.query.QueryExecutionFactory;
|
||||
import com.hp.hpl.jena.query.QueryFactory;
|
||||
import com.hp.hpl.jena.query.QuerySolution;
|
||||
import com.hp.hpl.jena.query.ResultSet;
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
import com.hp.hpl.jena.rdf.model.Model;
|
||||
import com.hp.hpl.jena.rdf.model.Resource;
|
||||
import com.hp.hpl.jena.vocabulary.RDF;
|
||||
import com.hp.hpl.jena.vocabulary.RDFS;
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder;
|
||||
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.preprocessors.AddAssociatedConceptsPreprocessor;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.ConceptSemanticTypesPreprocessor;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
|
||||
import edu.cornell.mannlib.vitro.webapp.utils.ConceptSearchService.ConceptSearchServiceUtils;
|
||||
/**
|
||||
* Generates the edit configuration for importing concepts from external
|
||||
* search services, e.g. UMLS etc.
|
||||
*
|
||||
* Since editing/deletion is handled by separate custom code, this generator always assumes
|
||||
* property addition mode.
|
||||
*/
|
||||
public class AddAssociatedConceptGenerator extends VivoBaseGenerator implements EditConfigurationGenerator {
|
||||
|
||||
private Log log = LogFactory.getLog(AddAssociatedConceptGenerator.class);
|
||||
private String template = "addAssociatedConcept.ftl";
|
||||
//TODO: Set this to a dynamic mechanism
|
||||
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 SKOSBroaderURI = "http://www.w3.org/2004/02/skos/core#broader";
|
||||
private static String SKOSNarrowerURI = "http://www.w3.org/2004/02/skos/core#narrower";
|
||||
@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());
|
||||
|
||||
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);
|
||||
// No validators required here
|
||||
// Add preprocessors
|
||||
//Passing from servlet context for now but will have to see if there's a way to pass vreq
|
||||
addPreprocessors(editConfiguration);
|
||||
// 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(EditConfigurationUtils
|
||||
.getFormUrlWithoutContext(vreq));
|
||||
|
||||
editConfiguration.addValidator(new AntiXssValidation());
|
||||
|
||||
// prepare
|
||||
prepare(vreq, editConfiguration);
|
||||
return editConfiguration;
|
||||
}
|
||||
|
||||
//In this case, the generator is not equipped to handle any deletion
|
||||
//Editing in the usual sense does not exist for this form
|
||||
//So we will disable editing
|
||||
@Override
|
||||
void initObjectPropForm(EditConfigurationVTwo editConfiguration,VitroRequest vreq) {
|
||||
editConfiguration.setObject( null );
|
||||
}
|
||||
|
||||
//Ensuring that editing property logic does not get executed on processing
|
||||
//since form's deletions are handled separately
|
||||
@Override
|
||||
void prepare(VitroRequest vreq, EditConfigurationVTwo editConfig) {
|
||||
Model model = vreq.getJenaOntModel();
|
||||
//Set subject and predicate uri
|
||||
if( editConfig.getSubjectUri() == null)
|
||||
editConfig.setSubjectUri( EditConfigurationUtils.getSubjectUri(vreq));
|
||||
if( editConfig.getPredicateUri() == null )
|
||||
editConfig.setPredicateUri( EditConfigurationUtils.getPredicateUri(vreq));
|
||||
//Always set creation
|
||||
editConfig.prepareForNonUpdate(model);
|
||||
|
||||
}
|
||||
|
||||
|
||||
private void setVarNames(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.setVarNameForSubject("subject");
|
||||
editConfiguration.setVarNameForPredicate("predicate");
|
||||
//We are not including concept node here since
|
||||
//we never actually "edit" using this form
|
||||
//the n3 required and optional will still be evaluated based on the form
|
||||
editConfiguration.setVarNameForObject("object");
|
||||
}
|
||||
|
||||
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#> .";
|
||||
}
|
||||
|
||||
//The only string always required is that linking the subject to the concept node
|
||||
//Since the concept node from an external vocabulary may already be in the system
|
||||
//The label and is defined by may already be defined and don't require re-saving
|
||||
private List<String> generateN3Required(VitroRequest vreq) {
|
||||
List<String> n3Required = list(
|
||||
getPrefixesString() + "\n" +
|
||||
"?subject ?predicate ?conceptNode .\n" +
|
||||
"?conceptNode <" + RDF.type.getURI() + "> <" + this.SKOSConceptType + "> ."
|
||||
);
|
||||
//"?conceptNode <" + RDF.type.getURI() + "> <http://www.w3.org/2002/07/owl#Thing> ."
|
||||
|
||||
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 N3, includes possibility of semantic type which may or may not be included
|
||||
//label and source are independent of semantic type
|
||||
//concept semantic type uri is a placeholder which is actually processed in the sparql update preprocessor
|
||||
private List<String> generateN3Optional() {
|
||||
return list("?conceptNode <" + RDFS.label.getURI() + "> ?conceptLabel .\n" +
|
||||
"?conceptNode <" + RDFS.isDefinedBy.getURI() + "> ?conceptSource .",
|
||||
"?conceptNode <" + RDF.type + "> ?conceptSemanticTypeURI ." +
|
||||
"?conceptSemanticTypeURI <" + RDFS.label.getURI() + "> ?conceptSemanticTypeLabel ." +
|
||||
"?conceptSemanticTypeURI <" + RDFS.subClassOf + "> <" + SKOSConceptType + "> .",
|
||||
"?conceptNode <" + this.SKOSNarrowerURI + "> ?conceptNarrowerURI ." +
|
||||
"?conceptNarrowerURI <" + this.SKOSBroaderURI + "> ?conceptNode .",
|
||||
"?conceptNode <" + this.SKOSBroaderURI + "> ?conceptBroaderURI ." +
|
||||
"?conceptBroaderURI <" + this.SKOSNarrowerURI + "> ?conceptNode ."
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* Get new resources
|
||||
*/
|
||||
private Map<String, String> generateNewResources(VitroRequest vreq) {
|
||||
HashMap<String, String> newResources = new HashMap<String, String>();
|
||||
//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
|
||||
//Adding concept semantic type uri just to test - note this isn't really on the form at all
|
||||
newResources.put("conceptSemanticTypeURI", null);
|
||||
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");
|
||||
urisOnForm.add("conceptSource");
|
||||
urisOnForm.add("conceptSemanticTypeURI");
|
||||
urisOnForm.add("conceptBroaderURI");
|
||||
urisOnForm.add("conceptNarrowerURI");
|
||||
editConfiguration.setUrisOnform(urisOnForm);
|
||||
//Also need to add the label of the concept
|
||||
literalsOnForm.add("conceptLabel");
|
||||
literalsOnForm.add("conceptSemanticTypeLabel");
|
||||
|
||||
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>());
|
||||
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);
|
||||
setVocabURIField(editConfiguration, vreq);
|
||||
setConceptSemanticTypeURIField(editConfiguration,vreq);
|
||||
setConceptSemanticTypeLabelField(editConfiguration,vreq);
|
||||
setConceptBroaderURIField(editConfiguration, vreq);
|
||||
setConceptNarrowerURIField(editConfiguration, vreq);
|
||||
}
|
||||
|
||||
private void setConceptNarrowerURIField(
|
||||
EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("conceptNarrowerURI"));
|
||||
}
|
||||
|
||||
private void setConceptBroaderURIField(
|
||||
EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("conceptBroaderURI"));
|
||||
|
||||
}
|
||||
|
||||
//this field will be hidden and include the concept node URI
|
||||
private void setConceptNodeField(EditConfigurationVTwo editConfiguration,
|
||||
VitroRequest vreq) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("conceptNode").
|
||||
setValidators(list("nonempty")));
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void setVocabURIField(EditConfigurationVTwo editConfiguration,
|
||||
VitroRequest vreq) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("conceptSource"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void setConceptLabelField(EditConfigurationVTwo editConfiguration,
|
||||
VitroRequest vreq) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("conceptLabel").
|
||||
setRangeDatatypeUri(XSD.xstring.toString())
|
||||
);
|
||||
}
|
||||
|
||||
//This will also be a URI
|
||||
private void setConceptSemanticTypeURIField(EditConfigurationVTwo editConfiguration,
|
||||
VitroRequest vreq) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("conceptSemanticTypeURI")
|
||||
);
|
||||
}
|
||||
|
||||
private void setConceptSemanticTypeLabelField(EditConfigurationVTwo editConfiguration,
|
||||
VitroRequest vreq) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("conceptSemanticTypeLabel").
|
||||
setRangeDatatypeUri(XSD.xstring.toString())
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
//Add preprocessor
|
||||
|
||||
private void addPreprocessors(EditConfigurationVTwo editConfiguration) {
|
||||
//An Edit submission preprocessor for enabling addition of multiple terms for a single search
|
||||
//TODO: Check if this is the appropriate way of getting model
|
||||
|
||||
//Passing model to check for any URIs that are present
|
||||
|
||||
editConfiguration.addEditSubmissionPreprocessor(
|
||||
new AddAssociatedConceptsPreprocessor(editConfiguration));
|
||||
editConfiguration.addModelChangePreprocessor(new ConceptSemanticTypesPreprocessor());
|
||||
|
||||
}
|
||||
|
||||
|
||||
//Form specific data
|
||||
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
|
||||
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
|
||||
//These are the concepts that already exist currently
|
||||
formSpecificData.put("existingConcepts", getExistingConcepts(vreq));
|
||||
//Return url for adding user defined concept
|
||||
formSpecificData.put("userDefinedConceptUrl", getUserDefinedConceptUrl(vreq));
|
||||
//Add URIs and labels for different services
|
||||
formSpecificData.put("searchServices", ConceptSearchServiceUtils.getVocabSources());
|
||||
List<String> inversePredicate = getInversePredicate(vreq);
|
||||
if(inversePredicate.size() > 0) {
|
||||
formSpecificData.put("inversePredicate", inversePredicate.get(0));
|
||||
} else {
|
||||
formSpecificData.put("inversePredicate", "");
|
||||
}
|
||||
editConfiguration.setFormSpecificData(formSpecificData);
|
||||
}
|
||||
|
||||
|
||||
//
|
||||
private Object getUserDefinedConceptUrl(VitroRequest vreq) {
|
||||
String subjectUri = EditConfigurationUtils.getSubjectUri(vreq);
|
||||
String predicateUri = EditConfigurationUtils.getPredicateUri(vreq);
|
||||
String generatorName = "edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddUserDefinedConceptGenerator";
|
||||
String editUrl = EditConfigurationUtils.getEditUrl(vreq);
|
||||
|
||||
return editUrl + "?subjectUri=" + UrlBuilder.urlEncode(subjectUri) +
|
||||
"&predicateUri=" + UrlBuilder.urlEncode(predicateUri) +
|
||||
"&editForm=" + UrlBuilder.urlEncode(generatorName);
|
||||
}
|
||||
|
||||
private List<AssociatedConceptInfo> getExistingConcepts(VitroRequest vreq) {
|
||||
Individual individual = EditConfigurationUtils.getSubjectIndividual(vreq);
|
||||
List<Individual> concepts = individual.getRelatedIndividuals(
|
||||
EditConfigurationUtils.getPredicateUri(vreq));
|
||||
List<AssociatedConceptInfo> associatedConcepts = getAssociatedConceptInfo(concepts, vreq);
|
||||
sortConcepts(associatedConcepts);
|
||||
return associatedConcepts;
|
||||
}
|
||||
|
||||
|
||||
private void sortConcepts(List<AssociatedConceptInfo> concepts) {
|
||||
Collections.sort(concepts, new AssociatedConceptInfoComparator());
|
||||
log.debug("Concepts should be sorted now" + concepts.toString());
|
||||
}
|
||||
|
||||
|
||||
//To determine whether or not a concept is a user generated or one from an external vocab source.
|
||||
//we cannot rely on whether or not it is a skos concept because incorporating UMLS semantic network classes as
|
||||
//SKOS concept subclasses means that even concepts from an external vocab source might be considered SKOS concepts
|
||||
//Instead, we will simply determine whether a concept is defined by an external vocabulary source and use that
|
||||
//as the primary indicator of whether a concept is from an external vocabulary source or a user generated concept
|
||||
private List<AssociatedConceptInfo> getAssociatedConceptInfo(
|
||||
List<Individual> concepts, VitroRequest vreq) {
|
||||
List<AssociatedConceptInfo> info = new ArrayList<AssociatedConceptInfo>();
|
||||
for ( Individual conceptIndividual : concepts ) {
|
||||
boolean userGenerated = true;
|
||||
//Note that this isn't technically
|
||||
String conceptUri = conceptIndividual.getURI();
|
||||
String conceptLabel = conceptIndividual.getName();
|
||||
|
||||
//Check if defined by an external vocabulary source
|
||||
List<ObjectPropertyStatement> vocabList = conceptIndividual.getObjectPropertyStatements(RDFS.isDefinedBy.getURI());
|
||||
String vocabSource = null;
|
||||
String vocabLabel = null;
|
||||
if(vocabList != null && vocabList.size() > 0) {
|
||||
userGenerated = false;
|
||||
vocabSource = vocabList.get(0).getObjectURI();
|
||||
Individual sourceIndividual = EditConfigurationUtils.getIndividual(vreq, vocabSource);
|
||||
//Assuming name will get label
|
||||
vocabLabel = sourceIndividual.getName();
|
||||
}
|
||||
|
||||
|
||||
|
||||
if(userGenerated) {
|
||||
//if the concept in question is skos - which would imply a user generated concept
|
||||
info.add(new AssociatedConceptInfo(conceptLabel, conceptUri, null, null, SKOSConceptType, null, null));
|
||||
} else {
|
||||
String conceptSemanticTypeURI = null;
|
||||
String conceptSemanticTypeLabel = null;
|
||||
//Can a concept have multiple semantic types? Currently we are only returning the first one
|
||||
//TODO: Change this into a sparql query that returns all types for the concept that are subclasses of SKOS concepts
|
||||
HashMap<String, String> typeAndLabel = this.getConceptSemanticTypeQueryResults(conceptIndividual.getURI(), ModelAccess.on(vreq).getOntModel());
|
||||
if(typeAndLabel.containsKey("semanticTypeURI")) {
|
||||
conceptSemanticTypeURI = typeAndLabel.get("semanticTypeURI");
|
||||
}
|
||||
if(typeAndLabel.containsKey("semanticTypeLabel")) {
|
||||
conceptSemanticTypeLabel = typeAndLabel.get("semanticTypeLabel");
|
||||
}
|
||||
|
||||
//Assuming this is from an external vocabulary source
|
||||
info.add(new AssociatedConceptInfo(conceptLabel, conceptUri, vocabSource, vocabLabel, null, conceptSemanticTypeURI, conceptSemanticTypeLabel));
|
||||
|
||||
}
|
||||
}
|
||||
return info;
|
||||
}
|
||||
|
||||
private HashMap<String, String> getConceptSemanticTypeQueryResults(String conceptURI, OntModel ontModel) {
|
||||
HashMap<String, String> typeAndLabel = new HashMap<String, String>();
|
||||
String queryStr = "SELECT ?semanticTypeURI ?semanticTypeLabel WHERE { " +
|
||||
"<" + conceptURI + "> <" + RDF.type.getURI() + "> ?semanticTypeURI . " +
|
||||
"?semanticTypeURI <" + RDFS.subClassOf.getURI() + "> <" + this.SKOSConceptType + ">. " +
|
||||
"?semanticTypeURI <" + RDFS.label.getURI() + "> ?semanticTypeLabel ." +
|
||||
"}";
|
||||
QueryExecution qe = null;
|
||||
try{
|
||||
Query query = QueryFactory.create(queryStr);
|
||||
qe = QueryExecutionFactory.create(query, ontModel);
|
||||
ResultSet results = null;
|
||||
results = qe.execSelect();
|
||||
|
||||
while( results.hasNext()){
|
||||
QuerySolution qs = results.nextSolution();
|
||||
if(qs.get("semanticTypeURI") != null) {
|
||||
Resource semanticTypeURI = qs.getResource("semanticTypeURI");
|
||||
log.debug("Semantic Type URI returned " + semanticTypeURI.getURI());
|
||||
typeAndLabel.put("semanticTypeURI", semanticTypeURI.getURI());
|
||||
}
|
||||
if(qs.get("semanticTypeLabel") != null) {
|
||||
Literal semanticTypeLabel = qs.getLiteral("semanticTypeLabel");
|
||||
log.debug("Semantic Type label returned " + semanticTypeLabel.getString());
|
||||
typeAndLabel.put("semanticTypeLabel", semanticTypeLabel.getString());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}catch(Exception ex){
|
||||
throw new Error("Error in executing query string: \n" + queryStr + '\n' + ex.getMessage());
|
||||
}finally{
|
||||
if( qe != null)
|
||||
qe.close();
|
||||
}
|
||||
return typeAndLabel;
|
||||
}
|
||||
|
||||
public class AssociatedConceptInfo {
|
||||
private String conceptLabel;
|
||||
private String conceptURI;
|
||||
private String vocabURI;
|
||||
private String vocabLabel;
|
||||
private String type; //In case of SKOS concept, will have skos concept type
|
||||
private String conceptSemanticTypeURI; //For some services, such as UMLS, we have a semantic type associated
|
||||
private String conceptSemanticTypeLabel;
|
||||
public AssociatedConceptInfo(String inputLabel, String inputURI, String inputVocabURI, String inputVocabLabel, String inputType, String inputConceptSemanticTypeURI, String inputConceptSemanticTypeLabel) {
|
||||
this.conceptLabel = inputLabel;
|
||||
this.conceptURI = inputURI;
|
||||
this.vocabURI = inputVocabURI;
|
||||
this.vocabLabel = inputVocabLabel;
|
||||
this.type = inputType;
|
||||
this.conceptSemanticTypeURI = inputConceptSemanticTypeURI;
|
||||
this.conceptSemanticTypeLabel = inputConceptSemanticTypeLabel;
|
||||
}
|
||||
|
||||
//Getters
|
||||
public String getConceptLabel() {
|
||||
return conceptLabel;
|
||||
}
|
||||
|
||||
public String getConceptURI() {
|
||||
return conceptURI;
|
||||
}
|
||||
|
||||
public String getVocabURI() {
|
||||
return vocabURI;
|
||||
}
|
||||
|
||||
public String getVocabLabel(){
|
||||
return vocabLabel;
|
||||
}
|
||||
|
||||
public String getType(){
|
||||
return type;
|
||||
}
|
||||
|
||||
public String getConceptSemanticTypeURI(){
|
||||
return conceptSemanticTypeURI;
|
||||
}
|
||||
|
||||
public String getConceptSemanticTypeLabel(){
|
||||
return conceptSemanticTypeLabel;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public class AssociatedConceptInfoComparator implements Comparator<AssociatedConceptInfo>{
|
||||
public int compare(AssociatedConceptInfo concept1, AssociatedConceptInfo concept2) {
|
||||
String concept1Label = concept1.getConceptLabel().toLowerCase();
|
||||
String concept2Label = concept2.getConceptLabel().toLowerCase();
|
||||
return concept1Label.compareTo(concept2Label);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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;
|
||||
}
|
||||
*/
|
||||
}
|
|
@ -0,0 +1,599 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import com.hp.hpl.jena.query.QueryExecution;
|
||||
import com.hp.hpl.jena.query.QueryExecutionFactory;
|
||||
import com.hp.hpl.jena.rdf.model.Model;
|
||||
import com.hp.hpl.jena.rdf.model.ModelFactory;
|
||||
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.query.QuerySolution;
|
||||
import com.hp.hpl.jena.query.ResultSet;
|
||||
import com.hp.hpl.jena.rdf.model.RDFNode;
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
import com.hp.hpl.jena.vocabulary.RDFS;
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyComparator;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.jena.QueryUtils;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.PublicationHasAuthorValidator;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeIntervalValidationVTwo;
|
||||
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;
|
||||
|
||||
/**
|
||||
* This is a slightly unusual generator that is used by Manage Authors on
|
||||
* information resources.
|
||||
*
|
||||
* 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);
|
||||
|
||||
@Override
|
||||
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
|
||||
HttpSession session) {
|
||||
EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo();
|
||||
initBasics(editConfiguration, vreq);
|
||||
initPropertyParameters(vreq, session, editConfiguration);
|
||||
|
||||
//Overriding URL to return to
|
||||
setUrlToReturnTo(editConfiguration, vreq);
|
||||
|
||||
//set variable names
|
||||
editConfiguration.setVarNameForSubject("infoResource");
|
||||
editConfiguration.setVarNameForPredicate("predicate");
|
||||
editConfiguration.setVarNameForObject("authorshipUri");
|
||||
|
||||
// Required N3
|
||||
editConfiguration.setN3Required( list( getN3NewAuthorship() ) );
|
||||
|
||||
// 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);
|
||||
|
||||
//on Form
|
||||
setUrisAndLiteralsOnForm(editConfiguration, vreq);
|
||||
|
||||
//Sparql queries
|
||||
setSparqlQueries(editConfiguration, vreq);
|
||||
|
||||
//set fields
|
||||
setFields(editConfiguration, vreq, EditConfigurationUtils.getPredicateUri(vreq));
|
||||
|
||||
//template file
|
||||
editConfiguration.setTemplate("addAuthorsToInformationResource.ftl");
|
||||
//add validators
|
||||
editConfiguration.addValidator(new PublicationHasAuthorValidator());
|
||||
|
||||
//Adding additional data, specifically edit mode
|
||||
addFormSpecificData(editConfiguration, vreq);
|
||||
|
||||
editConfiguration.addValidator(new AntiXssValidation());
|
||||
|
||||
//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));
|
||||
}
|
||||
|
||||
/***N3 strings both required and optional***/
|
||||
|
||||
public String getN3PrefixString() {
|
||||
return "@prefix core: <" + vivoCore + "> .\n" +
|
||||
"@prefix foaf: <" + foaf + "> . \n" ;
|
||||
}
|
||||
|
||||
private String getN3NewAuthorship() {
|
||||
return getN3PrefixString() +
|
||||
"?authorshipUri a core:Authorship ;\n" +
|
||||
" core:relates ?infoResource .\n" +
|
||||
"?infoResource core:relatedBy ?authorshipUri .";
|
||||
}
|
||||
|
||||
private String getN3AuthorshipRank() {
|
||||
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(),
|
||||
getN3NewPerson(),
|
||||
getN3AuthorshipRank(),
|
||||
getN3ForExistingPerson(),
|
||||
getN3NewOrg(),
|
||||
getN3ForExistingOrg());
|
||||
|
||||
}
|
||||
|
||||
|
||||
private String getN3NewPersonFirstName() {
|
||||
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 vcard:hasName ?vcardName . \n" +
|
||||
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
|
||||
"?vcardName vcard:givenName ?firstName .";
|
||||
}
|
||||
|
||||
private String getN3NewPersonMiddleName() {
|
||||
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 vcard:hasName ?vcardName . \n" +
|
||||
"?vcardName a vcard:Name . \n" +
|
||||
"?vcardName <http://vivoweb.org/ontology/core#middleName> ?middleName .";
|
||||
}
|
||||
|
||||
private String getN3NewPersonLastName() {
|
||||
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 vcard:hasName ?vcardName . \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" +
|
||||
"?newPerson core:relatedBy ?authorshipUri . ";
|
||||
}
|
||||
|
||||
private String getN3ForExistingPerson() {
|
||||
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" +
|
||||
"?newOrg core:relatedBy ?authorshipUri . ";
|
||||
}
|
||||
|
||||
private String getN3ForExistingOrg() {
|
||||
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>();
|
||||
newResources.put("authorshipUri", DEFAULT_NS_TOKEN);
|
||||
newResources.put("newPerson", DEFAULT_NS_TOKEN);
|
||||
newResources.put("vcardPerson", DEFAULT_NS_TOKEN);
|
||||
newResources.put("vcardName", DEFAULT_NS_TOKEN);
|
||||
newResources.put("newOrg", DEFAULT_NS_TOKEN);
|
||||
return newResources;
|
||||
}
|
||||
|
||||
/** 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(),
|
||||
Arrays.asList(new String[]{editConfiguration.getSubjectUri()}));
|
||||
urisInScope.put(editConfiguration.getVarNameForPredicate(),
|
||||
Arrays.asList(new String[]{editConfiguration.getPredicateUri()}));
|
||||
editConfiguration.setUrisInScope(urisInScope);
|
||||
//no literals in scope
|
||||
}
|
||||
|
||||
public void setUrisAndLiteralsOnForm(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
|
||||
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",
|
||||
"middleName",
|
||||
"lastName",
|
||||
"rank",
|
||||
"orgName",
|
||||
"label");
|
||||
editConfiguration.setLiteralsOnForm(literalsOnForm);
|
||||
}
|
||||
|
||||
/** 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
|
||||
HashMap<String, String> map = new HashMap<String, String>();
|
||||
editConfiguration.setSparqlForExistingUris(new HashMap<String, String>());
|
||||
editConfiguration.setSparqlForExistingLiterals(new HashMap<String, String>());
|
||||
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);
|
||||
setMiddleNameField(editConfiguration);
|
||||
setLastNameField(editConfiguration);
|
||||
setRankField(editConfiguration);
|
||||
setPersonUriField(editConfiguration);
|
||||
setOrgUriField(editConfiguration);
|
||||
setOrgNameField(editConfiguration);
|
||||
}
|
||||
|
||||
private void setLabelField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("label").
|
||||
setValidators(list("datatype:" + XSD.xstring.toString())).
|
||||
setRangeDatatypeUri(XSD.xstring.toString())
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
private void setFirstNameField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("firstName").
|
||||
setValidators(list("datatype:" + XSD.xstring.toString())).
|
||||
setRangeDatatypeUri(XSD.xstring.toString())
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
private void setMiddleNameField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("middleName").
|
||||
setValidators(list("datatype:" + XSD.xstring.toString())).
|
||||
setRangeDatatypeUri(XSD.xstring.toString())
|
||||
);
|
||||
}
|
||||
|
||||
private void setLastNameField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("lastName").
|
||||
setValidators(list("datatype:" + XSD.xstring.toString())).
|
||||
setRangeDatatypeUri(XSD.xstring.toString())
|
||||
);
|
||||
}
|
||||
|
||||
private void setRankField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("rank").
|
||||
setValidators(list("nonempty")).
|
||||
setRangeDatatypeUri(XSD.xint.toString())
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
private void setPersonUriField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("personUri")
|
||||
//.setObjectClassUri(personClass)
|
||||
);
|
||||
}
|
||||
|
||||
private void setOrgUriField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("orgUri")
|
||||
//.setObjectClassUri(personClass)
|
||||
);
|
||||
}
|
||||
|
||||
private void setOrgNameField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("orgName").
|
||||
setValidators(list("datatype:" + XSD.xstring.toString())).
|
||||
setRangeDatatypeUri(XSD.xstring.toString())
|
||||
);
|
||||
}
|
||||
|
||||
//Form specific data
|
||||
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
|
||||
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
|
||||
//Get the existing authorships
|
||||
formSpecificData.put("existingAuthorInfo", getExistingAuthorships(editConfiguration.getSubjectUri(), vreq));
|
||||
formSpecificData.put("newRank", getMaxRank(editConfiguration.getSubjectUri(), vreq) + 1);
|
||||
formSpecificData.put("rankPredicate", "http://vivoweb.org/ontology/core#rank");
|
||||
editConfiguration.setFormSpecificData(formSpecificData);
|
||||
}
|
||||
|
||||
private static String AUTHORSHIPS_MODEL = " \n"
|
||||
+ "PREFIX core: <http://vivoweb.org/ontology/core#>\n"
|
||||
+ "PREFIX afn: <http://jena.hpl.hp.com/ARQ/function#>\n"
|
||||
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
|
||||
+ "PREFIX foaf: <http://xmlns.com/foaf/0.1/>\n"
|
||||
+ "PREFIX vcard: <http://www.w3.org/2006/vcard/ns#>\n"
|
||||
+ "CONSTRUCT\n"
|
||||
+ "{\n"
|
||||
+ " ?subject core:relatedBy ?authorshipURI .\n"
|
||||
+ " ?authorshipURI a core:Authorship .\n"
|
||||
+ " ?authorshipURI core:relates ?authorURI .\n"
|
||||
+ " ?authorURI a ?type .\n"
|
||||
+ " ?authorURI rdfs:label ?authorName .\n"
|
||||
+ " ?authorURI vcard:hasName ?vName .\n"
|
||||
+ " ?vName vcard:givenName ?firstName .\n"
|
||||
+ " ?vName vcard:familyName ?lastName .\n"
|
||||
+ " ?vName core:middleName ?middleName .\n"
|
||||
+ "}\n"
|
||||
+ "WHERE\n"
|
||||
+ "{\n"
|
||||
+ " {\n"
|
||||
+ " ?subject core:relatedBy ?authorshipURI .\n"
|
||||
+ " ?authorshipURI a core:Authorship .\n"
|
||||
+ " ?authorshipURI core:relates ?authorURI .\n"
|
||||
+ " ?authorURI a foaf:Agent .\n"
|
||||
+ " ?authorURI a ?type .\n"
|
||||
+ " }\n"
|
||||
+ " UNION\n"
|
||||
+ " {\n"
|
||||
+ " ?subject core:relatedBy ?authorshipURI .\n"
|
||||
+ " ?authorshipURI a core:Authorship .\n"
|
||||
+ " ?authorshipURI core:relates ?authorURI .\n"
|
||||
+ " ?authorURI a foaf:Agent .\n"
|
||||
+ " ?authorURI rdfs:label ?authorName\n"
|
||||
+ " }\n"
|
||||
+ " UNION\n"
|
||||
+ " {\n"
|
||||
+ " ?subject core:relatedBy ?authorshipURI .\n"
|
||||
+ " ?authorshipURI a core:Authorship .\n"
|
||||
+ " ?authorshipURI core:rank ?rank\n"
|
||||
+ " }\n"
|
||||
+ " UNION\n"
|
||||
+ " {\n"
|
||||
+ " ?subject core:relatedBy ?authorshipURI .\n"
|
||||
+ " ?authorshipURI a core:Authorship .\n"
|
||||
+ " ?authorshipURI core:relates ?authorURI .\n"
|
||||
+ " ?authorURI a vcard:Individual .\n"
|
||||
+ " ?authorURI a ?type .\n"
|
||||
+ " ?authorURI vcard:hasName ?vName .\n"
|
||||
+ " ?vName vcard:givenName ?firstName .\n"
|
||||
+ " ?vName vcard:familyName ?lastName .\n"
|
||||
+ " }\n"
|
||||
+ " UNION\n"
|
||||
+ " {\n"
|
||||
+ " ?subject core:relatedBy ?authorshipURI .\n"
|
||||
+ " ?authorshipURI a core:Authorship .\n"
|
||||
+ " ?authorshipURI core:relates ?authorURI .\n"
|
||||
+ " ?authorURI a vcard:Individual .\n"
|
||||
+ " ?authorURI a ?type .\n"
|
||||
+ " ?authorURI vcard:hasName ?vName .\n"
|
||||
+ " ?vName core:middleName ?middleName .\n"
|
||||
+ " }\n"
|
||||
+ "}\n"
|
||||
;
|
||||
|
||||
private static String AUTHORSHIPS_QUERY = " \n"
|
||||
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
|
||||
+ "PREFIX afn: <http://jena.hpl.hp.com/ARQ/function#> \n"
|
||||
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n"
|
||||
+ "PREFIX foaf: <http://xmlns.com/foaf/0.1/> \n"
|
||||
+ "PREFIX vcard: <http://www.w3.org/2006/vcard/ns#> \n"
|
||||
+ "SELECT ?authorshipURI (afn:localname(?authorshipURI) AS ?authorshipName) ?authorURI ?authorName ?rank \n"
|
||||
+ "WHERE { { \n"
|
||||
+ " ?subject core:relatedBy ?authorshipURI . \n"
|
||||
+ " ?authorshipURI a core:Authorship . \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"
|
||||
+ "} } ORDER BY ?rank";
|
||||
|
||||
|
||||
private List<AuthorshipInfo> getExistingAuthorships(String subjectUri, VitroRequest vreq) {
|
||||
RDFService rdfService = vreq.getRDFService();
|
||||
|
||||
List<Map<String, String>> authorships = new ArrayList<Map<String, String>>();
|
||||
try {
|
||||
String constructStr = QueryUtils.subUriForQueryVar(AUTHORSHIPS_MODEL, "subject", subjectUri);
|
||||
|
||||
Model constructedModel = ModelFactory.createDefaultModel();
|
||||
rdfService.sparqlConstructQuery(constructStr, constructedModel);
|
||||
|
||||
String queryStr = QueryUtils.subUriForQueryVar(this.getAuthorshipsQuery(), "subject", subjectUri);
|
||||
log.debug("Query string is: " + queryStr);
|
||||
|
||||
QueryExecution qe = QueryExecutionFactory.create(queryStr, constructedModel);
|
||||
try {
|
||||
ResultSet results = qe.execSelect();
|
||||
while (results.hasNext()) {
|
||||
QuerySolution soln = results.nextSolution();
|
||||
RDFNode node = soln.get("authorshipURI");
|
||||
if (node.isURIResource()) {
|
||||
authorships.add(QueryUtils.querySolutionToStringValueMap(soln));
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
qe.close();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e, e);
|
||||
}
|
||||
authorships = QueryUtils.removeDuplicatesMapsFromList(authorships, "authorShipURI", "authorURI");
|
||||
log.debug("authorships = " + authorships);
|
||||
return getAuthorshipInfo(authorships);
|
||||
}
|
||||
|
||||
private static String MAX_RANK_QUERY = ""
|
||||
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
|
||||
+ "SELECT DISTINCT ?rank WHERE { \n"
|
||||
+ " ?subject core:relatedBy ?authorship . \n"
|
||||
+ " ?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
|
||||
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();
|
||||
RDFNode node = soln.get("rank");
|
||||
if (node != null && node.isLiteral()) {
|
||||
// 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) {
|
||||
log.debug("setting maxRank to " + rank);
|
||||
maxRank = rank;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
log.error("Invalid rank returned from query: not an integer value.");
|
||||
} catch (Exception e) {
|
||||
log.error(e, e);
|
||||
}
|
||||
log.debug("maxRank is: " + maxRank);
|
||||
return maxRank;
|
||||
}
|
||||
|
||||
private List<AuthorshipInfo> getAuthorshipInfo(
|
||||
List<Map<String, String>> authorships) {
|
||||
List<AuthorshipInfo> info = new ArrayList<AuthorshipInfo>();
|
||||
String authorshipUri = "";
|
||||
String authorshipName = "";
|
||||
String authorUri = "";
|
||||
String authorName = "";
|
||||
|
||||
for ( Map<String, String> authorship : authorships ) {
|
||||
for (Entry<String, String> entry : authorship.entrySet() ) {
|
||||
if ( entry.getKey().equals("authorshipURI") ) {
|
||||
authorshipUri = entry.getValue();
|
||||
}
|
||||
else if ( entry.getKey().equals("authorshipName") ) {
|
||||
authorshipName = entry.getValue();
|
||||
}
|
||||
else if ( entry.getKey().equals("authorURI") ) {
|
||||
authorUri = entry.getValue();
|
||||
}
|
||||
else if ( entry.getKey().equals("authorName") ) {
|
||||
authorName = entry.getValue();
|
||||
}
|
||||
}
|
||||
|
||||
AuthorshipInfo aaInfo = new AuthorshipInfo(authorshipUri, authorshipName, authorUri, authorName);
|
||||
info.add(aaInfo);
|
||||
}
|
||||
log.debug("info = " + info);
|
||||
return info;
|
||||
}
|
||||
|
||||
//This is the information about authors the form will require
|
||||
public class AuthorshipInfo {
|
||||
//This is the authorship node information
|
||||
private String authorshipUri;
|
||||
private String authorshipName;
|
||||
//Author information for authorship node
|
||||
private String authorUri;
|
||||
private String authorName;
|
||||
|
||||
public AuthorshipInfo(String inputAuthorshipUri,
|
||||
String inputAuthorshipName,
|
||||
String inputAuthorUri,
|
||||
String inputAuthorName) {
|
||||
authorshipUri = inputAuthorshipUri;
|
||||
authorshipName = inputAuthorshipName;
|
||||
authorUri = inputAuthorUri;
|
||||
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() {
|
||||
return MAX_RANK_QUERY;
|
||||
}
|
||||
|
||||
protected String getAuthorshipsQuery() {
|
||||
return AUTHORSHIPS_QUERY;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
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 AddClinicalRoleToPersonGenerator extends AddRoleToPersonTwoStageGenerator {
|
||||
|
||||
private static String template = "addClinicalRoleToPerson.ftl";
|
||||
|
||||
//Should this be overridden
|
||||
@Override
|
||||
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 {
|
||||
return new ConstantFieldOptions(
|
||||
"", "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
|
||||
@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;
|
||||
}
|
||||
*/
|
||||
|
||||
}
|
|
@ -0,0 +1,137 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.ArrayList;
|
||||
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 edu.cornell.mannlib.vitro.webapp.beans.Individual;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
|
||||
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.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.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
|
||||
* 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);
|
||||
|
||||
@Override
|
||||
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
|
||||
HttpSession session) throws Exception {
|
||||
EditConfigurationVTwo editConfig = super.getEditConfiguration(vreq, session);
|
||||
//If this isn't adding a new individual, then override template/types
|
||||
if(!DefaultAddMissingIndividualFormGenerator.isCreateNewIndividual(vreq, session)) {
|
||||
//return rangetypes in form specific data
|
||||
editConfig.addFormSpecificData("createNewTypes", getCreateNewTypesOptions(vreq));
|
||||
//override templates with ones that will override create new types portion
|
||||
editConfig.setTemplate(getTemplate(vreq));
|
||||
}
|
||||
return editConfig;
|
||||
}
|
||||
|
||||
private HashMap<String, String> getCreateNewTypesOptions(VitroRequest vreq) {
|
||||
HashMap<String, String> options = new HashMap<String, String>();
|
||||
List<VClass> rangeTypes = getRangeTypes(vreq);
|
||||
for(VClass v: rangeTypes) {
|
||||
options.put(v.getURI(), v.getName());
|
||||
}
|
||||
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
|
||||
protected List<VClass> getRangeTypes(VitroRequest vreq) {
|
||||
// This first part needs a WebappDaoFactory with no filtering/RDFService
|
||||
// funny business because it needs to be able to retrieve anonymous union
|
||||
// classes by their "pseudo-bnode URIs".
|
||||
// Someday we'll need to figure out a different way of doing this.
|
||||
//WebappDaoFactory ctxDaoFact = ModelAccess.on(
|
||||
// vreq.getSession().getServletContext()).getWebappDaoFactory();
|
||||
WebappDaoFactory ctxDaoFact = vreq.getLanguageNeutralWebappDaoFactory();
|
||||
|
||||
List<VClass> types = new ArrayList<VClass>();
|
||||
Individual subject = EditConfigurationUtils.getSubjectIndividual(vreq);
|
||||
String predicateUri = EditConfigurationUtils.getPredicateUri(vreq);
|
||||
String rangeUri = EditConfigurationUtils.getRangeUri(vreq);
|
||||
if (rangeUri != null) {
|
||||
VClass rangeVClass = ctxDaoFact.getVClassDao().getVClassByURI(rangeUri);
|
||||
if (!rangeVClass.isUnion()) {
|
||||
types.add(rangeVClass);
|
||||
} else {
|
||||
for (VClass unionComponent : rangeVClass.getUnionComponents()) {
|
||||
types.add(unionComponent);
|
||||
}
|
||||
}
|
||||
return types;
|
||||
} else {
|
||||
//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");
|
||||
|
||||
List<String> validators = new ArrayList<String>();
|
||||
validators.add("nonempty");
|
||||
field.setValidators(validators);
|
||||
|
||||
if( ! doAutoComplete ){
|
||||
List<String> types = new ArrayList<String>();
|
||||
for(VClass v: rangeTypes) {
|
||||
types.add(v.getURI());
|
||||
}
|
||||
String[] typesArray = types.toArray(new String[types.size()]);
|
||||
field.setOptions( new IndividualsViaSearchQueryOptions(
|
||||
getSubjectUri(),
|
||||
predicateUri,
|
||||
getObjectUri(),
|
||||
typesArray));
|
||||
}else{
|
||||
field.setOptions(null);
|
||||
}
|
||||
|
||||
Map<String, FieldVTwo> fields = new HashMap<String, FieldVTwo>();
|
||||
fields.put(field.getName(), field);
|
||||
|
||||
editConfiguration.setFields(fields);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,266 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.query.QuerySolution;
|
||||
import com.hp.hpl.jena.query.ResultSet;
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
import com.hp.hpl.jena.rdf.model.Model;
|
||||
import com.hp.hpl.jena.rdf.model.ModelFactory;
|
||||
import com.hp.hpl.jena.rdf.model.RDFNode;
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
|
||||
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.jena.QueryUtils;
|
||||
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.ChildVClassesWithParent;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
/**
|
||||
|
||||
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.
|
||||
|
||||
|
||||
*/
|
||||
public class AddEditWebpageFormGenerator extends BaseEditConfigurationGenerator implements EditConfigurationGenerator {
|
||||
public static Log log = LogFactory.getLog( AddEditWebpageFormGenerator.class );
|
||||
private static String formTemplate = "addEditWebpageForm.ftl";
|
||||
@Override
|
||||
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) throws Exception {
|
||||
EditConfigurationVTwo config = setupConfig(vreq, session);
|
||||
|
||||
config.setUrlPatternToReturnTo(getUrlPatternToReturnTo(vreq));
|
||||
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{
|
||||
|
||||
EditConfigurationVTwo config = new EditConfigurationVTwo();
|
||||
|
||||
config.setTemplate(this.getTemplate());
|
||||
|
||||
initBasics(config, vreq);
|
||||
initPropertyParameters(vreq, session, config);
|
||||
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 ));
|
||||
}
|
||||
else {
|
||||
if ( domainUri.equals("http://xmlns.com/foaf/0.1/Person") ) {
|
||||
vcardIndividualType = "http://www.w3.org/2006/vcard/ns#Individual";
|
||||
}
|
||||
else if ( domainUri.equals("http://xmlns.com/foaf/0.1/Organization") ) {
|
||||
vcardIndividualType = "http://www.w3.org/2006/vcard/ns#Organization";
|
||||
}
|
||||
}
|
||||
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(
|
||||
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),
|
||||
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());
|
||||
if( ind == null )
|
||||
return null;
|
||||
else
|
||||
return ind.getName();
|
||||
}
|
||||
|
||||
/* ********* N3 Assertions *********** */
|
||||
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 .";
|
||||
|
||||
static String N3_FOR_URLTYPE =
|
||||
"?link a ?urlType .";
|
||||
|
||||
static String N3_FOR_ANCHOR =
|
||||
"?link ?linkLabelPredicate ?label .";
|
||||
|
||||
static String N3_FOR_RANK =
|
||||
"?link ?rankPredicate ?rank .";
|
||||
|
||||
/* *********** SPARQL queries for existing values ************** */
|
||||
|
||||
static String URL_QUERY =
|
||||
"SELECT ?urlExisting WHERE { ?link ?linkUrlPredicate ?urlExisting }";
|
||||
|
||||
static String URLTYPE_QUERY =
|
||||
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
|
||||
"SELECT ?linkClassExisting WHERE { ?link vitro:mostSpecificType ?linkClassExisting }";
|
||||
|
||||
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" +
|
||||
"}";
|
||||
|
||||
/* 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.
|
||||
*/
|
||||
private static String MAX_RANK_QUERY = ""
|
||||
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
|
||||
+ "PREFIX vcard: <http://www.w3.org/2006/vcard/ns#> \n"
|
||||
+ "SELECT DISTINCT ?rank WHERE { \n"
|
||||
+ " ?subject <http://purl.obolibrary.org/obo/ARG_2000028> ?vcard . \n"
|
||||
+ " ?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
|
||||
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();
|
||||
RDFNode node = soln.get("rank");
|
||||
if (node != null && node.isLiteral()) {
|
||||
// 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) {
|
||||
log.debug("setting maxRank to " + rank);
|
||||
maxRank = rank;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
log.error("Invalid rank returned from query: not an integer value.");
|
||||
} catch (Exception e) {
|
||||
log.error(e, e);
|
||||
}
|
||||
}
|
||||
return maxRank;
|
||||
}
|
||||
|
||||
protected String getTemplate() {
|
||||
return formTemplate;
|
||||
}
|
||||
|
||||
protected String getMaxRankQueryStr() {
|
||||
return MAX_RANK_QUERY;
|
||||
}
|
||||
|
||||
protected String getN3ForWebpage() {
|
||||
return N3_FOR_WEBPAGE;
|
||||
}
|
||||
|
||||
private String getUrlPatternToReturnTo(VitroRequest vreq) {
|
||||
String subjectUri = EditConfigurationUtils.getSubjectUri(vreq);
|
||||
String predicateUri = EditConfigurationUtils.getPredicateUri(vreq);
|
||||
//Also add domain and range uris if they exist to enable cancel to work properly
|
||||
String domainUri = (String) vreq.getParameter("domainUri");
|
||||
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) +
|
||||
"&editForm=" + UrlBuilder.urlEncode(generatorName);
|
||||
if(domainUri != null && !domainUri.isEmpty()) {
|
||||
returnPath += "&domainUri=" + UrlBuilder.urlEncode(domainUri);
|
||||
}
|
||||
if(rangeUri != null && !rangeUri.isEmpty()) {
|
||||
returnPath += "&rangeUri=" + UrlBuilder.urlEncode(rangeUri);
|
||||
}
|
||||
return returnPath;
|
||||
|
||||
}
|
||||
|
||||
private String getLinkUri(VitroRequest vreq) {
|
||||
String linkUri = vreq.getParameter("linkUri");
|
||||
|
||||
return linkUri;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,75 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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.ChildVClassesWithParent;
|
||||
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
|
||||
number of Individuals that the user has to select from.
|
||||
Stage two is selecting the non-person Individual to associate
|
||||
with the Role.
|
||||
|
||||
This is intended to create a set of statements like:
|
||||
|
||||
?person core:hasResearchActivityRole ?newRole.
|
||||
?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; }
|
||||
|
||||
@Override
|
||||
String getRoleType() {
|
||||
return "http://vivoweb.org/ontology/core#EditorRole";
|
||||
}
|
||||
|
||||
@Override
|
||||
FieldOptions getRoleActivityFieldOptions(VitroRequest vreq) throws Exception {
|
||||
return new ChildVClassesOptions(OPTION_CLASS_URI)
|
||||
.setDefaultOptionLabel("Select type");
|
||||
}
|
||||
|
||||
/** Do not show the role label field for the AddEditorRoleToPerson form */
|
||||
@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;
|
||||
}
|
||||
*/
|
||||
}
|
|
@ -0,0 +1,519 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import com.hp.hpl.jena.query.QueryExecution;
|
||||
import com.hp.hpl.jena.query.QueryExecutionFactory;
|
||||
import com.hp.hpl.jena.rdf.model.Model;
|
||||
import com.hp.hpl.jena.rdf.model.ModelFactory;
|
||||
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.query.QuerySolution;
|
||||
import com.hp.hpl.jena.query.ResultSet;
|
||||
import com.hp.hpl.jena.rdf.model.RDFNode;
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
import com.hp.hpl.jena.vocabulary.RDFS;
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyComparator;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.jena.QueryUtils;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.FirstAndLastNameValidator;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeIntervalValidationVTwo;
|
||||
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;
|
||||
|
||||
/**
|
||||
* This is a slightly unusual generator that is used by Manage Editors on
|
||||
* information resources.
|
||||
*
|
||||
* 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);
|
||||
|
||||
@Override
|
||||
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
|
||||
HttpSession session) {
|
||||
EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo();
|
||||
initBasics(editConfiguration, vreq);
|
||||
initPropertyParameters(vreq, session, editConfiguration);
|
||||
|
||||
//Overriding URL to return to
|
||||
setUrlToReturnTo(editConfiguration, vreq);
|
||||
|
||||
//set variable names
|
||||
editConfiguration.setVarNameForSubject("infoResource");
|
||||
editConfiguration.setVarNameForPredicate("predicate");
|
||||
editConfiguration.setVarNameForObject("editorshipUri");
|
||||
|
||||
// Required N3
|
||||
editConfiguration.setN3Required( list( getN3NewEditorship() ) );
|
||||
|
||||
// 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);
|
||||
|
||||
//on Form
|
||||
setUrisAndLiteralsOnForm(editConfiguration, vreq);
|
||||
|
||||
//Sparql queries
|
||||
setSparqlQueries(editConfiguration, vreq);
|
||||
|
||||
//set fields
|
||||
setFields(editConfiguration, vreq, EditConfigurationUtils.getPredicateUri(vreq));
|
||||
|
||||
//template file
|
||||
editConfiguration.setTemplate("addEditorsToInformationResource.ftl");
|
||||
//add validators
|
||||
editConfiguration.addValidator(new FirstAndLastNameValidator("personUri"));
|
||||
|
||||
//Adding additional data, specifically edit mode
|
||||
addFormSpecificData(editConfiguration, vreq);
|
||||
|
||||
editConfiguration.addValidator(new AntiXssValidation());
|
||||
|
||||
//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));
|
||||
}
|
||||
|
||||
/***N3 strings both required and optional***/
|
||||
|
||||
public String getN3PrefixString() {
|
||||
return "@prefix core: <" + vivoCore + "> .\n" +
|
||||
"@prefix foaf: <" + foaf + "> . \n" ;
|
||||
}
|
||||
|
||||
private String getN3NewEditorship() {
|
||||
return getN3PrefixString() +
|
||||
"?editorshipUri a core:Editorship ;\n" +
|
||||
" core:relates ?infoResource .\n" +
|
||||
"?infoResource core:relatedBy ?editorshipUri .";
|
||||
}
|
||||
|
||||
private String getN3EditorshipRank() {
|
||||
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(),
|
||||
getN3NewPerson(),
|
||||
getN3EditorshipRank(),
|
||||
getN3ForExistingPerson());
|
||||
}
|
||||
|
||||
|
||||
private String getN3NewPersonFirstName() {
|
||||
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 vcard:hasName ?vcardName . \n" +
|
||||
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
|
||||
"?vcardName vcard:givenName ?firstName .";
|
||||
}
|
||||
|
||||
private String getN3NewPersonMiddleName() {
|
||||
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 vcard:hasName ?vcardName . \n" +
|
||||
"?vcardName a vcard:Name . \n" +
|
||||
"?vcardName <http://vivoweb.org/ontology/core#middleName> ?middleName .";
|
||||
}
|
||||
|
||||
private String getN3NewPersonLastName() {
|
||||
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 vcard:hasName ?vcardName . \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" +
|
||||
"?newPerson core:relatedBy ?editorshipUri . ";
|
||||
}
|
||||
|
||||
private String getN3ForExistingPerson() {
|
||||
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>();
|
||||
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 */
|
||||
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(),
|
||||
Arrays.asList(new String[]{editConfiguration.getSubjectUri()}));
|
||||
urisInScope.put(editConfiguration.getVarNameForPredicate(),
|
||||
Arrays.asList(new String[]{editConfiguration.getPredicateUri()}));
|
||||
editConfiguration.setUrisInScope(urisInScope);
|
||||
//no literals in scope
|
||||
}
|
||||
|
||||
public void setUrisAndLiteralsOnForm(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
|
||||
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",
|
||||
"middleName",
|
||||
"lastName",
|
||||
"rank",
|
||||
"label");
|
||||
editConfiguration.setLiteralsOnForm(literalsOnForm);
|
||||
}
|
||||
|
||||
/** 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
|
||||
HashMap<String, String> map = new HashMap<String, String>();
|
||||
editConfiguration.setSparqlForExistingUris(new HashMap<String, String>());
|
||||
editConfiguration.setSparqlForExistingLiterals(new HashMap<String, String>());
|
||||
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);
|
||||
setMiddleNameField(editConfiguration);
|
||||
setLastNameField(editConfiguration);
|
||||
setRankField(editConfiguration);
|
||||
setPersonUriField(editConfiguration);
|
||||
}
|
||||
|
||||
private void setLabelField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("label").
|
||||
setValidators(list("datatype:" + XSD.xstring.toString())).
|
||||
setRangeDatatypeUri(XSD.xstring.toString())
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
private void setFirstNameField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("firstName").
|
||||
setValidators(list("datatype:" + XSD.xstring.toString())).
|
||||
setRangeDatatypeUri(XSD.xstring.toString())
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
private void setMiddleNameField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("middleName").
|
||||
setValidators(list("datatype:" + XSD.xstring.toString())).
|
||||
setRangeDatatypeUri(XSD.xstring.toString())
|
||||
);
|
||||
}
|
||||
|
||||
private void setLastNameField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("lastName").
|
||||
setValidators(list("datatype:" + XSD.xstring.toString())).
|
||||
setRangeDatatypeUri(XSD.xstring.toString())
|
||||
);
|
||||
}
|
||||
|
||||
private void setRankField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("rank").
|
||||
setValidators(list("nonempty")).
|
||||
setRangeDatatypeUri(XSD.xint.toString())
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
private void setPersonUriField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("personUri")
|
||||
//.setObjectClassUri(personClass)
|
||||
);
|
||||
}
|
||||
|
||||
//Form specific data
|
||||
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
|
||||
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
|
||||
//Get the existing editorships
|
||||
formSpecificData.put("existingEditorInfo", getExistingEditorships(editConfiguration.getSubjectUri(), vreq));
|
||||
formSpecificData.put("newRank", getMaxRank(editConfiguration.getSubjectUri(), vreq) + 1);
|
||||
formSpecificData.put("rankPredicate", "http://vivoweb.org/ontology/core#rank");
|
||||
editConfiguration.setFormSpecificData(formSpecificData);
|
||||
}
|
||||
|
||||
private static String EDITORSHIPS_MODEL = ""
|
||||
+ "PREFIX core: <http://vivoweb.org/ontology/core#>\n"
|
||||
+ "PREFIX afn: <http://jena.hpl.hp.com/ARQ/function#>\n"
|
||||
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
|
||||
+ "PREFIX foaf: <http://xmlns.com/foaf/0.1/>\n"
|
||||
+ "CONSTRUCT\n"
|
||||
+ "{\n"
|
||||
+ " ?subject core:relatedBy ?editorshipURI .\n"
|
||||
+ " ?editorshipURI a core:Editorship .\n"
|
||||
+ " ?editorshipURI core:relates ?editorURI .\n"
|
||||
+ " ?editorshipURI core:rank ?rank.\n"
|
||||
+ " ?editorURI a foaf:Person .\n"
|
||||
+ " ?editorURI rdfs:label ?editorName .\n"
|
||||
+ "}\n"
|
||||
+ "WHERE\n"
|
||||
+ "{\n"
|
||||
+ " {\n"
|
||||
+ " ?subject core:relatedBy ?editorshipURI .\n"
|
||||
+ " ?editorshipURI a core:Editorship .\n"
|
||||
+ " ?editorshipURI core:relates ?editorURI .\n"
|
||||
+ " ?editorURI a foaf:Person .\n"
|
||||
+ " }\n"
|
||||
+ " UNION\n"
|
||||
+ " {\n"
|
||||
+ " ?subject core:relatedBy ?editorshipURI .\n"
|
||||
+ " ?editorshipURI a core:Editorship .\n"
|
||||
+ " ?editorshipURI core:relates ?editorURI .\n"
|
||||
+ " ?editorURI a foaf:Person .\n"
|
||||
+ " ?editorURI rdfs:label ?editorName .\n"
|
||||
+ " }\n"
|
||||
+ " UNION\n"
|
||||
+ " {\n"
|
||||
+ " ?subject core:relatedBy ?editorshipURI .\n"
|
||||
+ " ?editorshipURI a core:Editorship .\n"
|
||||
+ " ?editorshipURI core:rank ?rank.\n"
|
||||
+ " }\n"
|
||||
+ "}\n";
|
||||
|
||||
private static String EDITORSHIPS_QUERY = ""
|
||||
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
|
||||
+ "PREFIX afn: <http://jena.hpl.hp.com/ARQ/function#> \n"
|
||||
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n"
|
||||
+ "PREFIX foaf: <http://xmlns.com/foaf/0.1/> \n"
|
||||
+ "SELECT ?editorshipURI (afn:localname(?editorshipURI) AS ?editorshipName) ?editorURI ?editorName ?rank \n"
|
||||
+ "WHERE { \n"
|
||||
+ "?subject core:relatedBy ?editorshipURI . \n"
|
||||
+ "?editorshipURI a core:Editorship . \n"
|
||||
+ "?editorshipURI core:relates ?editorURI . \n"
|
||||
+ "?editorURI a foaf:Person . \n"
|
||||
+ "OPTIONAL { ?editorURI rdfs:label ?editorName } \n"
|
||||
+ "OPTIONAL { ?editorshipURI core:rank ?rank } \n"
|
||||
+ "} ORDER BY ?rank";
|
||||
|
||||
|
||||
private List<EditorshipInfo> getExistingEditorships(String subjectUri, VitroRequest vreq) {
|
||||
RDFService rdfService = vreq.getRDFService();
|
||||
|
||||
List<Map<String, String>> editorships = new ArrayList<Map<String, String>>();
|
||||
try {
|
||||
String constructStr = QueryUtils.subUriForQueryVar(EDITORSHIPS_MODEL, "subject", subjectUri);
|
||||
|
||||
Model constructedModel = ModelFactory.createDefaultModel();
|
||||
rdfService.sparqlConstructQuery(constructStr, constructedModel);
|
||||
|
||||
String queryStr = QueryUtils.subUriForQueryVar(this.getEditorshipsQuery(), "subject", subjectUri);
|
||||
log.debug("Query string is: " + queryStr);
|
||||
|
||||
QueryExecution qe = QueryExecutionFactory.create(queryStr, constructedModel);
|
||||
try {
|
||||
ResultSet results = qe.execSelect();
|
||||
while (results.hasNext()) {
|
||||
QuerySolution soln = results.nextSolution();
|
||||
RDFNode node = soln.get("editorshipURI");
|
||||
if (node.isURIResource()) {
|
||||
editorships.add(QueryUtils.querySolutionToStringValueMap(soln));
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
qe.close();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e, e);
|
||||
}
|
||||
log.debug("editorships = " + editorships);
|
||||
return getEditorshipInfo(editorships);
|
||||
}
|
||||
|
||||
private static String MAX_RANK_QUERY = ""
|
||||
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
|
||||
+ "SELECT DISTINCT ?rank WHERE { \n"
|
||||
+ " ?subject core:relatedBy ?editorship . \n"
|
||||
+ " ?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
|
||||
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();
|
||||
RDFNode node = soln.get("rank");
|
||||
if (node != null && node.isLiteral()) {
|
||||
// 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) {
|
||||
log.debug("setting maxRank to " + rank);
|
||||
maxRank = rank;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
log.error("Invalid rank returned from query: not an integer value.");
|
||||
} catch (Exception e) {
|
||||
log.error(e, e);
|
||||
}
|
||||
log.debug("maxRank is: " + maxRank);
|
||||
return maxRank;
|
||||
}
|
||||
|
||||
private List<EditorshipInfo> getEditorshipInfo(
|
||||
List<Map<String, String>> editorships) {
|
||||
List<EditorshipInfo> info = new ArrayList<EditorshipInfo>();
|
||||
String editorshipUri = "";
|
||||
String editorshipName = "";
|
||||
String editorUri = "";
|
||||
String editorName = "";
|
||||
|
||||
for ( Map<String, String> editorship : editorships ) {
|
||||
for (Entry<String, String> entry : editorship.entrySet() ) {
|
||||
if ( entry.getKey().equals("editorshipURI") ) {
|
||||
editorshipUri = entry.getValue();
|
||||
}
|
||||
else if ( entry.getKey().equals("editorshipName") ) {
|
||||
editorshipName = entry.getValue();
|
||||
}
|
||||
else if ( entry.getKey().equals("editorURI") ) {
|
||||
editorUri = entry.getValue();
|
||||
}
|
||||
else if ( entry.getKey().equals("editorName") ) {
|
||||
editorName = entry.getValue();
|
||||
}
|
||||
}
|
||||
|
||||
EditorshipInfo aaInfo = new EditorshipInfo(editorshipUri, editorshipName, editorUri, editorName);
|
||||
info.add(aaInfo);
|
||||
}
|
||||
log.debug("info = " + info);
|
||||
return info;
|
||||
}
|
||||
|
||||
//This is the information about editors the form will require
|
||||
public class EditorshipInfo {
|
||||
//This is the editorship node information
|
||||
private String editorshipUri;
|
||||
private String editorshipName;
|
||||
//Editor information for editorship node
|
||||
private String editorUri;
|
||||
private String editorName;
|
||||
|
||||
public EditorshipInfo(String inputEditorshipUri,
|
||||
String inputEditorshipName,
|
||||
String inputEditorUri,
|
||||
String inputEditorName) {
|
||||
editorshipUri = inputEditorshipUri;
|
||||
editorshipName = inputEditorshipName;
|
||||
editorUri = inputEditorUri;
|
||||
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() {
|
||||
return MAX_RANK_QUERY;
|
||||
}
|
||||
|
||||
protected String getEditorshipsQuery() {
|
||||
return EDITORSHIPS_QUERY;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,223 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
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 javax.servlet.http.HttpSession;
|
||||
|
||||
import com.hp.hpl.jena.query.Query;
|
||||
import com.hp.hpl.jena.query.QueryExecution;
|
||||
import com.hp.hpl.jena.query.QueryExecutionFactory;
|
||||
import com.hp.hpl.jena.query.QueryFactory;
|
||||
import com.hp.hpl.jena.rdf.model.RDFNode;
|
||||
import com.hp.hpl.jena.rdf.model.Resource;
|
||||
import com.hp.hpl.jena.sparql.resultset.ResultSetMem;
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
|
||||
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.edit.n3editing.VTwo.EditConfigurationUtils;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ConstantFieldOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
|
||||
import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils.EditMode;
|
||||
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{
|
||||
return doSkipToDocument(vreq);
|
||||
}
|
||||
}
|
||||
|
||||
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" +
|
||||
" ?obj a <http://purl.obolibrary.org/obo/IAO_0000030> . } \n";
|
||||
Query documentQuery = QueryFactory.create(documentQueryStr);
|
||||
QueryExecution qe = QueryExecutionFactory.create(documentQuery, ModelAccess.on(vreq).getOntModel());
|
||||
try {
|
||||
ResultSetMem rs = new ResultSetMem(qe.execSelect());
|
||||
if(!rs.hasNext()){
|
||||
return doBadEditorshipNoPub( vreq );
|
||||
}else if( rs.size() > 1 ){
|
||||
return doBadEditorshipMultiplePubs(vreq);
|
||||
}else{
|
||||
//skip to document
|
||||
RDFNode objNode = rs.next().get("obj");
|
||||
if (!objNode.isResource() || objNode.isAnon()) {
|
||||
return doBadEditorshipNoPub( vreq );
|
||||
}
|
||||
EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo();
|
||||
editConfiguration.setSkipToUrl(UrlBuilder.getIndividualProfileUrl(((Resource) objNode).getURI(), vreq));
|
||||
return editConfiguration;
|
||||
}
|
||||
} finally {
|
||||
qe.close();
|
||||
}
|
||||
}
|
||||
|
||||
protected EditConfigurationVTwo doAddNew(VitroRequest vreq,
|
||||
HttpSession session) throws Exception {
|
||||
|
||||
EditConfigurationVTwo conf = new EditConfigurationVTwo();
|
||||
|
||||
initBasics(conf, vreq);
|
||||
initPropertyParameters(vreq, session, conf);
|
||||
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().
|
||||
setName("documentType").
|
||||
setValidators( list("nonempty") ).
|
||||
setOptions( new ConstantFieldOptions("documentType", getDocumentTypeLiteralOptions() ))
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("documentLabel").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("documentLabelDisplay").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ));
|
||||
|
||||
conf.addValidator(new AntiXssValidation());
|
||||
addFormSpecificData(conf, vreq);
|
||||
|
||||
prepare(vreq, conf);
|
||||
return conf;
|
||||
}
|
||||
|
||||
/* N3 assertions */
|
||||
|
||||
final static String n3ForNewEditorship =
|
||||
"@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?person ?predicate ?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" +
|
||||
"?newDocument <" + label + "> ?documentLabel. " ;
|
||||
|
||||
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" +
|
||||
"}";
|
||||
|
||||
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" +
|
||||
"}";
|
||||
|
||||
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" +
|
||||
"}";
|
||||
|
||||
//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");
|
||||
return EditModeUtils.getEditMode(vreq, predicates);
|
||||
}
|
||||
|
||||
private EditConfigurationVTwo doBadEditorshipMultiplePubs(VitroRequest vreq) {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
private EditConfigurationVTwo doBadEditorshipNoPub(VitroRequest vreq) {
|
||||
// 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"));
|
||||
literalOptions.add(list("http://purl.org/ontology/bibo/Chapter", "Chapter"));
|
||||
literalOptions.add(list("http://purl.org/ontology/bibo/EditedBook", "Edited Book"));
|
||||
literalOptions.add(list("http://purl.org/ontology/bibo/Film", "Film"));
|
||||
literalOptions.add(list("http://purl.org/ontology/bibo/Magazine", "Magazine"));
|
||||
literalOptions.add(list("http://vivoweb.org/ontology/core#Newsletter", "Newsletter"));
|
||||
literalOptions.add(list("http://purl.org/ontology/bibo/Newspaper", "Newspaper"));
|
||||
literalOptions.add(list("http://vivoweb.org/ontology/core#NewsRelease", "News Release"));
|
||||
literalOptions.add(list("http://purl.org/ontology/bibo/Report", "Report"));
|
||||
literalOptions.add(list("http://vivoweb.org/ontology/core#Video", "Video"));
|
||||
literalOptions.add(list("http://purl.org/ontology/bibo/Webpage", "Webpage"));
|
||||
literalOptions.add(list("http://purl.org/ontology/bibo/Website", "Website"));
|
||||
return literalOptions;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,154 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
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 com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
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.ChildVClassesOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaVClassOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
|
||||
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);
|
||||
|
||||
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().
|
||||
setName("firstName")
|
||||
.setRangeDatatypeUri( XSD.xstring.toString() ).
|
||||
setValidators( list("nonempty") ));
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("middleName")
|
||||
.setRangeDatatypeUri( XSD.xstring.toString()) );
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("lastName")
|
||||
.setRangeDatatypeUri( XSD.xstring.toString() ).
|
||||
setValidators( list("nonempty") ));
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("suffix")
|
||||
.setRangeDatatypeUri( XSD.xstring.toString()) );
|
||||
|
||||
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 =
|
||||
"?person <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> ?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 <http://www.w3.org/2006/vcard/ns#givenName> ?firstName .";
|
||||
|
||||
final static String middleNameAssertion =
|
||||
"?fullName <http://vivoweb.org/ontology/core#middleName> ?middleName .";
|
||||
|
||||
final static String lastNameAssertion =
|
||||
"?fullName <http://www.w3.org/2006/vcard/ns#familyName> ?lastName .";
|
||||
|
||||
final static String suffixAssertion =
|
||||
"?fullName <http://www.w3.org/2006/vcard/ns#honorificSuffix> ?suffix .";
|
||||
|
||||
final static String prefixAssertion =
|
||||
"?fullName <http://www.w3.org/2006/vcard/ns#honorificPrefix> ?prefix .";
|
||||
|
||||
/* Queries for editing an existing entry */
|
||||
|
||||
final static String individualVcardQuery =
|
||||
"SELECT ?existingIndividualVcard WHERE { \n" +
|
||||
"?person <http://purl.obolibrary.org/obo/ARG_2000028> ?existingIndividualVcard . \n" +
|
||||
"}";
|
||||
|
||||
final static String firstNameQuery =
|
||||
"SELECT ?existingFirstName WHERE {\n"+
|
||||
"?fullName <http://www.w3.org/2006/vcard/ns#givenName> ?existingFirstName . }";
|
||||
|
||||
final static String middleNameQuery =
|
||||
"SELECT ?existingMiddleName WHERE {\n"+
|
||||
"?fullName <http://vivoweb.org/ontology/core#middleName> ?existingMiddleName . }";
|
||||
|
||||
final static String lastNameQuery =
|
||||
"SELECT ?existingLastName WHERE {\n"+
|
||||
"?fullName <http://www.w3.org/2006/vcard/ns#familyName> ?existingLastName . }";
|
||||
|
||||
final static String suffixQuery =
|
||||
"SELECT ?existingSuffix WHERE {\n"+
|
||||
"?fullName <http://www.w3.org/2006/vcard/ns#honorificSuffix> ?existingSuffix . }";
|
||||
|
||||
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");
|
||||
|
||||
return fullNameUri;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,753 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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.vivoweb.webapp.util.ModelUtils;
|
||||
|
||||
import com.hp.hpl.jena.ontology.OntModel;
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
import com.hp.hpl.jena.vocabulary.RDF;
|
||||
import com.hp.hpl.jena.vocabulary.RDFS;
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.AutocompleteRequiredInputValidator;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeIntervalValidationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo;
|
||||
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;
|
||||
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
|
||||
import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils.EditMode;
|
||||
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
|
||||
//default obj property form.populateTemplate or some such method
|
||||
//Select from existing also set within template itself
|
||||
setTemplate(editConfiguration, vreq);
|
||||
//Set edit key
|
||||
setEditKey(editConfiguration, vreq);
|
||||
|
||||
//Add validators
|
||||
editConfiguration.addValidator(new DateTimeIntervalValidationVTwo("startField","endField") );
|
||||
editConfiguration.addValidator(new AntiXssValidation());
|
||||
editConfiguration.addValidator(new AutocompleteRequiredInputValidator("existingGrant","grantLabel"));
|
||||
//no preprocessors required here
|
||||
//Adding additional data, specifically edit mode
|
||||
addFormSpecificData(editConfiguration, vreq);
|
||||
return editConfiguration;
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void setEditKey(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
|
||||
String editKey = EditConfigurationUtils.getEditKey(vreq);
|
||||
editConfiguration.setEditKey(editKey);
|
||||
}
|
||||
|
||||
protected void setTemplate(EditConfigurationVTwo editConfiguration,
|
||||
VitroRequest vreq) {
|
||||
editConfiguration.setTemplate(template);
|
||||
|
||||
}
|
||||
|
||||
//Initialize setup: process parameters
|
||||
//There will be specialized parameters as well, we may include them here or in a
|
||||
//separate method
|
||||
private void initProcessParameters(VitroRequest vreq, HttpSession session, EditConfigurationVTwo editConfiguration) {
|
||||
String formUrl = EditConfigurationUtils.getFormUrlWithoutContext(vreq);
|
||||
|
||||
subjectUri = EditConfigurationUtils.getSubjectUri(vreq);
|
||||
predicateUri = EditConfigurationUtils.getPredicateUri(vreq);
|
||||
|
||||
editConfiguration.setFormUrl(formUrl);
|
||||
|
||||
editConfiguration.setUrlPatternToReturnTo("/individual");
|
||||
|
||||
editConfiguration.setVarNameForSubject("person");
|
||||
editConfiguration.setSubjectUri(subjectUri);
|
||||
editConfiguration.setEntityToReturnTo(subjectUri);
|
||||
editConfiguration.setVarNameForPredicate("rolePredicate");
|
||||
editConfiguration.setPredicateUri(predicateUri);
|
||||
//by definition, this is an object property
|
||||
objectUri = EditConfigurationUtils.getObjectUri(vreq);
|
||||
|
||||
this.processObjectPropForm(vreq, editConfiguration);
|
||||
}
|
||||
|
||||
private void processObjectPropForm(VitroRequest vreq, EditConfigurationVTwo editConfiguration) {
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* 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) {
|
||||
List<String> n3ForEdit = new ArrayList<String>();
|
||||
String editString = getN3ForGrantRole(vreq);
|
||||
n3ForEdit.add(editString);
|
||||
return n3ForEdit;
|
||||
}
|
||||
|
||||
|
||||
private List<String> generateN3Optional(VitroRequest vreq) {
|
||||
List<String> n3Optional = new ArrayList<String>();
|
||||
//n3 for new grant
|
||||
n3Optional.add(getN3ForNewGrant(vreq));
|
||||
//n3 for existing grant
|
||||
n3Optional.add(getN3ForExistingGrant(vreq));
|
||||
//n3 for inverse
|
||||
n3Optional.add("?role ?inverseRolePredicate ?person .");
|
||||
//N3ForStart
|
||||
n3Optional.addAll(getN3ForStart());
|
||||
//N3 For End
|
||||
n3Optional.addAll(getN3ForEnd());
|
||||
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 += "?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 += "?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 ." +
|
||||
"?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 ." +
|
||||
"?endNode <" + getDateTimePrecisionURI() + "> ?endField-precision .");
|
||||
return n3ForEnd;
|
||||
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Get new resources
|
||||
*/
|
||||
private Map<String, String> generateNewResources(VitroRequest vreq) {
|
||||
HashMap<String, String> newResources = new HashMap<String, String>();
|
||||
//TODO: Get default namespace
|
||||
String defaultNamespace = vreq.getWebappDaoFactory().getDefaultNamespace();
|
||||
newResources.put("role", defaultNamespace + "individual");
|
||||
newResources.put("grant", defaultNamespace + "individual");
|
||||
newResources.put("intervalNode", defaultNamespace + "individual");
|
||||
newResources.put("startNode", defaultNamespace + "individual");
|
||||
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(),
|
||||
Arrays.asList(new String[]{editConfiguration.getSubjectUri()}));
|
||||
urisInScope.put(editConfiguration.getVarNameForPredicate(),
|
||||
Arrays.asList(new String[]{editConfiguration.getPredicateUri()}));
|
||||
//Setting role type
|
||||
urisInScope.put("roleType",
|
||||
Arrays.asList(new String[]{getRoleType(vreq)}));
|
||||
//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>();
|
||||
//add role activity and roleActivityType to uris on form
|
||||
urisOnForm.add("grant");
|
||||
urisOnForm.add("existingGrant");
|
||||
editConfiguration.setUrisOnform(urisOnForm);
|
||||
//activity label and role label are literals on form
|
||||
literalsOnForm.add("grantLabel");
|
||||
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>();
|
||||
//Queries for role activity, activity type query, interval node, start node, end node, start field precision, endfield precision
|
||||
map.put("existingGrant", getExistingGrantQuery(vreq));
|
||||
map.put("intervalNode", getIntervalNodeQuery(vreq));
|
||||
map.put("startNode", getStartNodeQuery(vreq));
|
||||
map.put("endNode", getEndNodeQuery(vreq));
|
||||
map.put("startField-precision", getStartPrecisionQuery(vreq));
|
||||
map.put("endField-precision", getEndPrecisionQuery(vreq));
|
||||
return map;
|
||||
}
|
||||
|
||||
|
||||
|
||||
private String getEndPrecisionQuery(VitroRequest vreq) {
|
||||
String query = "SELECT ?existingEndPrecision WHERE {" +
|
||||
"?role <" + getRoleToIntervalURI() + "> ?intervalNode ." +
|
||||
"?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + getIntervalTypeURI() + "> ." +
|
||||
"?intervalNode <" + getIntervalToEndURI() + "> ?endNode ." +
|
||||
"?endNode <" + VitroVocabulary.RDF_TYPE + "> <" + getDateTimeValueTypeURI() + "> . " +
|
||||
"?endNode <" + getDateTimePrecisionURI() + "> ?existingEndPrecision . }";
|
||||
return query;
|
||||
}
|
||||
|
||||
private String getStartPrecisionQuery(VitroRequest vreq) {
|
||||
String query = "SELECT ?existingStartPrecision WHERE {" +
|
||||
"?role <" + getRoleToIntervalURI() + "> ?intervalNode ." +
|
||||
"?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + getIntervalTypeURI() + "> ." +
|
||||
"?intervalNode <" + getIntervalToStartURI() + "> ?startNode ." +
|
||||
"?startNode <" + VitroVocabulary.RDF_TYPE + "> <" + getDateTimeValueTypeURI() + "> . " +
|
||||
"?startNode <" + getDateTimePrecisionURI() + "> ?existingStartPrecision . }";
|
||||
return query;
|
||||
}
|
||||
|
||||
private String getEndNodeQuery(VitroRequest vreq) {
|
||||
String query = "SELECT ?existingEndNode WHERE {"+
|
||||
"?role <" + getRoleToIntervalURI() + "> ?intervalNode ."+
|
||||
"?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + getIntervalTypeURI() + "> ."+
|
||||
" ?intervalNode <" + getIntervalToEndURI() + "> ?existingEndNode . "+
|
||||
"?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() + "> .}";
|
||||
return query;
|
||||
}
|
||||
|
||||
private String getIntervalNodeQuery(VitroRequest vreq) {
|
||||
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>();
|
||||
//Queries for activity label, role label, start Field value, end Field value
|
||||
map.put("grantLabel", getGrantLabelQuery(vreq));
|
||||
map.put("startField-value", getExistingStartDateQuery(vreq));
|
||||
map.put("endField-value", getExistingEndDateQuery(vreq));
|
||||
return map;
|
||||
}
|
||||
|
||||
private String getGrantLabelQuery(VitroRequest vreq) {
|
||||
String query = "PREFIX core: <" + getVivoCoreNamespace() + ">" +
|
||||
"PREFIX rdfs: <" + RDFS.getURI() + "> \n";
|
||||
|
||||
String roleToGrantPredicate = getRoleToGrantPredicate(vreq);
|
||||
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() + ">" +
|
||||
"PREFIX rdfs: <" + RDFS.getURI() + "> \n";
|
||||
|
||||
String roleToGrantPredicate = getRoleToGrantPredicate(vreq);
|
||||
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" +
|
||||
"?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" +
|
||||
"?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
|
||||
getGrantField(editConfiguration, vreq, fields);
|
||||
getGrantLabelField(editConfiguration, vreq, fields);
|
||||
getGrantLabelDisplayField(editConfiguration, vreq, fields);
|
||||
getExistingGrantField(editConfiguration, vreq, fields);
|
||||
getStartField(editConfiguration, vreq, fields);
|
||||
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);
|
||||
|
||||
}
|
||||
|
||||
private void getGrantLabelField(EditConfigurationVTwo editConfiguration,
|
||||
VitroRequest vreq, Map<String, FieldVTwo> fields) {
|
||||
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);
|
||||
|
||||
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);
|
||||
|
||||
}
|
||||
//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);
|
||||
//queryForExisting is not being used anywhere in Field
|
||||
|
||||
fields.put(field.getName(), field);
|
||||
}
|
||||
|
||||
private void getStartField(EditConfigurationVTwo editConfiguration,
|
||||
VitroRequest vreq, Map<String, FieldVTwo> fields) {
|
||||
String fieldName = "startField";
|
||||
|
||||
FieldVTwo field = new FieldVTwo();
|
||||
field.setName(fieldName);
|
||||
|
||||
//This logic was originally after edit configuration object created from json in original jsp
|
||||
field.setEditElement(
|
||||
new DateTimeWithPrecisionVTwo(field,
|
||||
VitroVocabulary.Precision.YEAR.uri(),
|
||||
VitroVocabulary.Precision.NONE.uri()));
|
||||
|
||||
fields.put(field.getName(), field);
|
||||
|
||||
}
|
||||
|
||||
private void getEndField(EditConfigurationVTwo editConfiguration,
|
||||
VitroRequest vreq, Map<String, FieldVTwo> fields) {
|
||||
String fieldName = "endField";
|
||||
|
||||
FieldVTwo field = new FieldVTwo();
|
||||
field.setName(fieldName);
|
||||
|
||||
List<String> validators = new ArrayList<String>();
|
||||
field.setValidators(validators);
|
||||
|
||||
//Set edit element
|
||||
field.setEditElement(
|
||||
new DateTimeWithPrecisionVTwo(field,
|
||||
VitroVocabulary.Precision.YEAR.uri(),
|
||||
VitroVocabulary.Precision.NONE.uri()));
|
||||
|
||||
fields.put(field.getName(), field);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare edit configuration for update
|
||||
* @param vreq
|
||||
* @param session
|
||||
* @param editConfiguration
|
||||
*/
|
||||
|
||||
private void prepareForUpdate(VitroRequest vreq, HttpSession session, EditConfigurationVTwo editConfiguration) {
|
||||
//Here, retrieve model from
|
||||
OntModel model = ModelAccess.on(session.getServletContext()).getOntModel();
|
||||
//Object property by definition
|
||||
String objectUri = EditConfigurationUtils.getObjectUri(vreq);
|
||||
if(objectUri != null) {
|
||||
//update existing object
|
||||
editConfiguration.prepareForObjPropUpdate(model);
|
||||
} else {
|
||||
//new object to be created
|
||||
editConfiguration.prepareForNonUpdate( model );
|
||||
}
|
||||
}
|
||||
|
||||
/**Methods for checking edit mode **
|
||||
*
|
||||
*/
|
||||
public EditMode getEditMode(VitroRequest vreq) {
|
||||
List<String> roleToGrantPredicates = getPossibleRoleToGrantPredicates();
|
||||
return EditModeUtils.getEditMode(vreq, roleToGrantPredicates);
|
||||
}
|
||||
|
||||
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
|
||||
**/
|
||||
//role type will always be set based on particular form
|
||||
public String getRoleType(VitroRequest vreq) {
|
||||
String rangeUri = EditConfigurationUtils.getRangeUri(vreq);
|
||||
if(rangeUri.equals(getPrincipalInvestigatorURI())) {
|
||||
return getVivoOntologyCoreNamespace() + "PrincipalInvestigatorRole";
|
||||
}
|
||||
else if(rangeUri.equals(getCoPrincipalInvestigatorURI())) {
|
||||
return getVivoOntologyCoreNamespace() + "CoPrincipalInvestigatorRole";
|
||||
}
|
||||
else {
|
||||
return getVivoOntologyCoreNamespace() + "InvestigatorRole";
|
||||
}
|
||||
}
|
||||
|
||||
private Object getCoPrincipalInvestigatorURI() {
|
||||
return getVivoOntologyCoreNamespace() + "CoPrincipalInvestigatorRole";
|
||||
}
|
||||
|
||||
|
||||
//TODO: More dynamic way of getting this or standard mechanism
|
||||
private String getVivoOntologyCoreNamespace() {
|
||||
return "http://vivoweb.org/ontology/core#";
|
||||
}
|
||||
|
||||
private Object getPrincipalInvestigatorURI() {
|
||||
return getVivoOntologyCoreNamespace() + "PrincipalInvestigatorRole";
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
//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";
|
||||
}
|
||||
//Ensure when overwritten that this includes the <> b/c otherwise the query won't work
|
||||
|
||||
//Some values will have a default value
|
||||
//grantToRolePredicate
|
||||
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>();
|
||||
formSpecificData.put("editMode", getEditMode(vreq).name().toLowerCase());
|
||||
formSpecificData.put("rangeUri", getRangeUri(vreq));
|
||||
//In this case, passing back a sparql query
|
||||
formSpecificData.put("sparqlForAcFilter", getSparqlForAcFilter(vreq));
|
||||
//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 { " +
|
||||
"<" + subject + "> <" + predicate + "> ?grantRole ." +
|
||||
"?grantRole <" + getRoleToGrantPredicate(vreq) + "> ?grantUri . }";
|
||||
return query;
|
||||
}
|
||||
|
||||
private String getRangeUri(VitroRequest vreq) {
|
||||
String rangeUri = vreq.getParameter("rangeUri");
|
||||
|
||||
return rangeUri;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
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;
|
||||
}
|
||||
*/
|
||||
}
|
|
@ -0,0 +1,82 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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 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() {
|
||||
return "http://vivoweb.org/ontology/core#MemberRole";
|
||||
}
|
||||
|
||||
@Override
|
||||
FieldOptions getRoleActivityFieldOptions(VitroRequest vreq) throws Exception {
|
||||
return new ConstantFieldOptions(
|
||||
"","Select type",
|
||||
"http://vivoweb.org/ontology/core#AcademicDepartment","Academic Department",
|
||||
"http://vivoweb.org/ontology/core#Association","Association",
|
||||
"http://vivoweb.org/ontology/core#Center","Center",
|
||||
"http://vivoweb.org/ontology/core#ClinicalOrganization","Clinical Organization",
|
||||
"http://vivoweb.org/ontology/core#College","College",
|
||||
"http://vivoweb.org/ontology/core#Committee","Committee",
|
||||
"http://vivoweb.org/ontology/core#Company","Company",
|
||||
"http://vivoweb.org/ontology/core#Consortium","Consortium",
|
||||
"http://vivoweb.org/ontology/core#CoreLaboratory","Core Laboratory",
|
||||
"http://vivoweb.org/ontology/core#Department","Department",
|
||||
"http://vivoweb.org/ontology/core#Division","Division",
|
||||
"http://vivoweb.org/ontology/core#ExtensionUnit","Extension Unit",
|
||||
"http://vivoweb.org/ontology/core#Foundation","Foundation",
|
||||
"http://vivoweb.org/ontology/core#FundingOrganization","Funding Organization",
|
||||
"http://vivoweb.org/ontology/core#GovernmentAgency","Government Agency",
|
||||
"http://xmlns.com/foaf/0.1/Group","Group",
|
||||
"http://vivoweb.org/ontology/core#Hospital","Hospital",
|
||||
"http://vivoweb.org/ontology/core#Institute","Institute",
|
||||
"http://vivoweb.org/ontology/core#Laboratory","Laboratory",
|
||||
"http://vivoweb.org/ontology/core#Library","Library",
|
||||
"http://purl.obolibrary.org/obo/OBI_0000835","Manufacturer",
|
||||
"http://vivoweb.org/ontology/core#Museum","Museum",
|
||||
"http://xmlns.com/foaf/0.1/Organization","Organization",
|
||||
"http://vivoweb.org/ontology/core#PrivateCompany","Private Company",
|
||||
"http://vivoweb.org/ontology/core#Program","Program",
|
||||
"http://vivoweb.org/ontology/core#Publisher","Publisher",
|
||||
"http://vivoweb.org/ontology/core#ResearchOrganization","Research Organization",
|
||||
"http://vivoweb.org/ontology/core#School","School",
|
||||
"http://vivoweb.org/ontology/core#Team","Team",
|
||||
"http://vivoweb.org/ontology/core#ServiceProvidingLaboratory","Service Providing Lab",
|
||||
"http://vivoweb.org/ontology/core#StudentOrganization","Student Organization",
|
||||
"http://purl.obolibrary.org/obo/ERO_0000565","Technology Transfer Office",
|
||||
"http://vivoweb.org/ontology/core#University","University");
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
*/
|
||||
}
|
|
@ -0,0 +1,78 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
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 com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
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.ChildVClassesOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaVClassOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
|
||||
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);
|
||||
|
||||
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().
|
||||
setName("orcidId").
|
||||
setValidators( list("nonempty") ));
|
||||
|
||||
conf.addValidator(new AntiXssValidation());
|
||||
|
||||
prepare(vreq, conf);
|
||||
return conf;
|
||||
}
|
||||
|
||||
/* N3 assertions */
|
||||
|
||||
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 . " ;
|
||||
|
||||
/* Queries for editing an existing entry */
|
||||
|
||||
final static String orcidIdQuery =
|
||||
"SELECT ?existingOrcidId WHERE { \n" +
|
||||
"?person <http://vivoweb.org/ontology/core#orcidId> ?existingOrcidId . \n" +
|
||||
"}";
|
||||
|
||||
}
|
|
@ -0,0 +1,68 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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 AddOrganizerRoleToPersonGenerator extends AddRoleToPersonTwoStageGenerator {
|
||||
|
||||
private static String template = "addOrganizerRoleToPerson.ftl";
|
||||
|
||||
|
||||
@Override
|
||||
String getTemplate() {
|
||||
return template;
|
||||
}
|
||||
|
||||
@Override
|
||||
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 {
|
||||
return new ConstantFieldOptions(
|
||||
"","Select type",
|
||||
"http://vivoweb.org/ontology/core#Competition", "Competition",
|
||||
"http://purl.org/ontology/bibo/Conference", "Conference",
|
||||
"http://vivoweb.org/ontology/core#Course", "Course",
|
||||
"http://purl.org/NET/c4dm/event.owl#Event", "Event",
|
||||
"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#InvitedTalk", "Invited Talk",
|
||||
"http://vivoweb.org/ontology/core#Meeting", "Meeting",
|
||||
"http://purl.org/ontology/bibo/Performance", "Performance",
|
||||
"http://vivoweb.org/ontology/core#Presentation", "Presentation",
|
||||
"http://purl.org/ontology/bibo/Workshop", "Workshop",
|
||||
"http://vivoweb.org/ontology/core#ConferenceSeries", "Conference Series",
|
||||
"http://vivoweb.org/ontology/core#EventSeries", "Event 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;
|
||||
}
|
||||
*/
|
||||
}
|
|
@ -0,0 +1,100 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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 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() {
|
||||
return "http://vivoweb.org/ontology/core#OutreachProviderRole";
|
||||
}
|
||||
|
||||
//Outreach Provider 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://vivoweb.org/ontology/core#AcademicDepartment","Academic Department",
|
||||
"http://vivoweb.org/ontology/core#Association","Association",
|
||||
"http://vivoweb.org/ontology/core#Center","Center",
|
||||
"http://vivoweb.org/ontology/core#ClinicalOrganization","Clinical Organization",
|
||||
"http://vivoweb.org/ontology/core#College","College",
|
||||
"http://vivoweb.org/ontology/core#Committee","Committee",
|
||||
"http://vivoweb.org/ontology/core#Company","Company",
|
||||
"http://vivoweb.org/ontology/core#Competition", "Competition",
|
||||
"http://purl.org/ontology/bibo/Conference", "Conference",
|
||||
"http://vivoweb.org/ontology/core#ConferenceSeries", "Conference Series",
|
||||
"http://vivoweb.org/ontology/core#Consortium","Consortium",
|
||||
"http://vivoweb.org/ontology/core#CoreLaboratory","Core Laboratory",
|
||||
"http://vivoweb.org/ontology/core#Course", "Course",
|
||||
"http://vivoweb.org/ontology/core#Department","Department",
|
||||
"http://vivoweb.org/ontology/core#Division","Division",
|
||||
"http://purl.org/NET/c4dm/event.owl#Event","Event",
|
||||
"http://vivoweb.org/ontology/core#EventSeries", "Event Series",
|
||||
"http://vivoweb.org/ontology/core#Exhibit", "Exhibit",
|
||||
"http://vivoweb.org/ontology/core#ExtensionUnit","Extension Unit",
|
||||
"http://vivoweb.org/ontology/core#Foundation","Foundation",
|
||||
"http://vivoweb.org/ontology/core#FundingOrganization","Funding Organization",
|
||||
"http://vivoweb.org/ontology/core#GovernmentAgency","Government Agency",
|
||||
"http://xmlns.com/foaf/0.1/Group","Group",
|
||||
"http://purl.org/ontology/bibo/Hearing", "Hearing",
|
||||
"http://vivoweb.org/ontology/core#Hospital","Hospital",
|
||||
"http://vivoweb.org/ontology/core#Institute","Institute",
|
||||
"http://purl.org/ontology/bibo/Interview", "Interview",
|
||||
"http://vivoweb.org/ontology/core#InvitedTalk", "Invited Talk",
|
||||
"http://vivoweb.org/ontology/core#Laboratory","Laboratory",
|
||||
"http://vivoweb.org/ontology/core#Library","Library",
|
||||
"http://purl.obolibrary.org/obo/OBI_0000835","Manufacturer",
|
||||
"http://vivoweb.org/ontology/core#Meeting", "Meeting",
|
||||
"http://vivoweb.org/ontology/core#Museum","Museum",
|
||||
"http://xmlns.com/foaf/0.1/Organization","Organization",
|
||||
"http://purl.org/ontology/bibo/Performance", "Performance",
|
||||
"http://vivoweb.org/ontology/core#Presentation", "Presentation",
|
||||
"http://vivoweb.org/ontology/core#PrivateCompany","Private Company",
|
||||
"http://vivoweb.org/ontology/core#Program","Program",
|
||||
"http://vivoweb.org/ontology/core#Publisher","Publisher",
|
||||
"http://vivoweb.org/ontology/core#ResearchOrganization","Research Organization",
|
||||
"http://vivoweb.org/ontology/core#School","School",
|
||||
"http://vivoweb.org/ontology/core#SeminarSeries", "Seminar Series",
|
||||
"http://vivoweb.org/ontology/core#Team","Team",
|
||||
"http://vivoweb.org/ontology/core#ServiceProvidingLaboratory","Service Providing Lab",
|
||||
"http://vivoweb.org/ontology/core#StudentOrganization","Student Organization",
|
||||
"http://purl.obolibrary.org/obo/ERO_0000565","Technology Transfer Office",
|
||||
"http://vivoweb.org/ontology/core#University","University",
|
||||
"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,
|
||||
* 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;
|
||||
}
|
||||
*/
|
||||
}
|
|
@ -0,0 +1,310 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.AutocompleteRequiredInputValidator;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeIntervalValidationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ChildVClassesOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ChildVClassesWithParent;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaVClassOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
|
||||
public class AddPresenterRoleToPersonGenerator extends VivoBaseGenerator implements
|
||||
EditConfigurationGenerator {
|
||||
|
||||
final static String presentationClass = vivoCore + "Presentation";
|
||||
final static String roleClass = vivoCore + "PresenterRole";
|
||||
final static String conferenceClass = bibo + "Conference";
|
||||
final static String hasRolePred = "http://purl.obolibrary.org/obo/RO_0000053";
|
||||
final static String roleOfPred = "http://purl.obolibrary.org/obo/RO_0000052";
|
||||
final static String roleRealizedInPred = "http://purl.obolibrary.org/obo/BFO_0000054";
|
||||
final static String realizedRolePred = "http://purl.obolibrary.org/obo/BFO_0000055";
|
||||
final static String includesEventPred = "http://purl.obolibrary.org/obo/BFO_0000051";
|
||||
final static String eventWithinPred = "http://purl.obolibrary.org/obo/BFO_0000050";
|
||||
final static String roleToInterval = vivoCore + "dateTimeInterval";
|
||||
final static String intervalType = vivoCore + "DateTimeInterval";
|
||||
final static String intervalToStart = vivoCore + "start";
|
||||
final static String intervalToEnd = vivoCore + "end";
|
||||
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);
|
||||
|
||||
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,
|
||||
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
|
||||
//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);
|
||||
conf.addSparqlForExistingUris("existingPresentation", presentationQuery);
|
||||
conf.addSparqlForExistingUris("existingConference", existingConferenceQuery);
|
||||
conf.addSparqlForExistingUris("presentationType", presentationTypeQuery);
|
||||
conf.addSparqlForExistingLiteral(
|
||||
"startField-value", existingStartDateQuery);
|
||||
conf.addSparqlForExistingLiteral(
|
||||
"endField-value", existingEndDateQuery);
|
||||
conf.addSparqlForExistingUris(
|
||||
"intervalNode", existingIntervalNodeQuery);
|
||||
conf.addSparqlForExistingUris("startNode", existingStartNodeQuery);
|
||||
conf.addSparqlForExistingUris("endNode", existingEndNodeQuery);
|
||||
conf.addSparqlForExistingUris("startField-precision",
|
||||
existingStartPrecisionQuery);
|
||||
conf.addSparqlForExistingUris("endField-precision",
|
||||
existingEndPrecisionQuery);
|
||||
|
||||
conf.addField( new FieldVTwo(). // an autocomplete field
|
||||
setName("existingPresentation")
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("presentationLabelDisplay")
|
||||
.setRangeDatatypeUri( XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
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))
|
||||
);
|
||||
|
||||
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")
|
||||
);
|
||||
|
||||
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,
|
||||
VitroVocabulary.Precision.YEAR.uri(),
|
||||
VitroVocabulary.Precision.NONE.uri())
|
||||
)
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().setName("endField").
|
||||
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"));
|
||||
prepare(vreq, conf);
|
||||
return conf;
|
||||
}
|
||||
|
||||
/* N3 assertions */
|
||||
final static String n3ForNewRole =
|
||||
"@prefix core: <" + vivoCore + "> . \n" +
|
||||
"?person <" + hasRolePred + "> ?role . \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" +
|
||||
"?presentation <" + label + "> ?presentationLabel . \n" +
|
||||
"?presentation a ?presentationType .";
|
||||
|
||||
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" +
|
||||
"?newConference a <" + conferenceClass + "> . \n" +
|
||||
"?newConference <" + label + "> ?conferenceLabel .";
|
||||
|
||||
final static String n3ForNewConferenceExistingPres =
|
||||
"?existingPresentation <" + eventWithinPred + "> ?newConference . \n" +
|
||||
"?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" +
|
||||
"?intervalNode a <" + intervalType + "> . \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" +
|
||||
"?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 =
|
||||
"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 =
|
||||
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
|
||||
"SELECT ?existingPresentationType WHERE { \n" +
|
||||
"?role <" + roleRealizedInPred + "> ?existingPresentation . " +
|
||||
"?existingPresentation vitro:mostSpecificType ?existingPresentationType . }";
|
||||
|
||||
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" +
|
||||
" ?intervalNode a <" + intervalType + "> . \n" +
|
||||
" ?intervalNode <" + intervalToStart + "> ?startNode . \n" +
|
||||
" ?startNode a <" + dateTimeValueType +"> . \n" +
|
||||
" ?startNode <" + dateTimeValue + "> ?existingDateStart . }";
|
||||
|
||||
final static String existingEndDateQuery =
|
||||
"SELECT ?existingEndDate WHERE { \n" +
|
||||
" ?role <" + roleToInterval + "> ?intervalNode . \n" +
|
||||
" ?intervalNode a <" + intervalType + "> . \n " +
|
||||
" ?intervalNode <" + intervalToEnd + "> ?endNode . \n" +
|
||||
" ?endNode a <" + dateTimeValueType + "> . \n" +
|
||||
" ?endNode <" + dateTimeValue + "> ?existingEndDate . }";
|
||||
|
||||
final static String existingIntervalNodeQuery =
|
||||
"SELECT ?existingIntervalNode WHERE { \n" +
|
||||
" ?role <" + roleToInterval + "> ?existingIntervalNode . \n" +
|
||||
" ?existingIntervalNode a <" + intervalType + "> . }";
|
||||
|
||||
final static String existingStartNodeQuery =
|
||||
"SELECT ?existingStartNode WHERE { \n" +
|
||||
" ?role <" + roleToInterval + "> ?intervalNode . \n" +
|
||||
" ?intervalNode a <" + intervalType + "> . \n" +
|
||||
" ?intervalNode <" + intervalToStart + "> ?existingStartNode . \n" +
|
||||
" ?existingStartNode a <" + dateTimeValueType + "> . } ";
|
||||
|
||||
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 =
|
||||
"SELECT ?existingStartPrecision WHERE { \n" +
|
||||
" ?role <" + roleToInterval + "> ?intervalNode . \n" +
|
||||
" ?intervalNode a <" + intervalType + "> . \n" +
|
||||
" ?intervalNode <" + intervalToStart + "> ?startNode . \n" +
|
||||
" ?startNode a <" + dateTimeValueType + "> . \n" +
|
||||
" ?startNode <" + dateTimePrecision + "> ?existingStartPrecision . }";
|
||||
|
||||
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 <" + dateTimePrecision + "> ?existingEndPrecision . }";
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,947 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
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 com.hp.hpl.jena.query.Query;
|
||||
import com.hp.hpl.jena.query.QueryExecution;
|
||||
import com.hp.hpl.jena.query.QueryExecutionFactory;
|
||||
import com.hp.hpl.jena.query.QueryFactory;
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
import com.hp.hpl.jena.rdf.model.RDFNode;
|
||||
import com.hp.hpl.jena.rdf.model.Resource;
|
||||
import com.hp.hpl.jena.sparql.resultset.ResultSetMem;
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
|
||||
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.edit.n3editing.AutocompleteRequiredInputValidator;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.PersonHasPublicationValidator;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo;
|
||||
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.ConstantFieldOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
|
||||
import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils.EditMode;
|
||||
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.
|
||||
*/
|
||||
public class AddPublicationToPersonGenerator extends VivoBaseGenerator implements EditConfigurationGenerator {
|
||||
|
||||
final static String collectionClass = bibo + "Journal";
|
||||
final static String bookClass = bibo + "Book";
|
||||
final static String documentClass = "http://purl.obolibrary.org/obo/IAO_0000030";
|
||||
final static String conferenceClass = bibo + "Conference";
|
||||
final static String editorClass = foaf + "Person";
|
||||
final static String publisherClass = vivoCore + "Publisher";
|
||||
final static String presentedAtPred = bibo + "presentedAt";
|
||||
final static String localePred = vivoCore + "placeOfPublication";
|
||||
final static String volumePred = bibo + "volume";
|
||||
final static String numberPred = bibo + "number";
|
||||
final static String issuePred = bibo + "issue";
|
||||
final static String chapterNbrPred = bibo + "chapter";
|
||||
final static String startPagePred = bibo + "pageStart";
|
||||
final static String endPagePred = bibo + "pageEnd";
|
||||
final static String dateTimePred = vivoCore + "dateTimeValue";
|
||||
final static String dateTimeValueType = vivoCore + "DateTimeValue";
|
||||
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{
|
||||
return doSkipToPublication(vreq);
|
||||
}
|
||||
}
|
||||
|
||||
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" +
|
||||
" ?obj a <" + documentClass + "> . } \n";
|
||||
Query pubQuery = QueryFactory.create(pubQueryStr);
|
||||
QueryExecution qe = QueryExecutionFactory.create(pubQuery, ModelAccess.on(vreq).getOntModel());
|
||||
try {
|
||||
ResultSetMem rs = new ResultSetMem(qe.execSelect());
|
||||
if(!rs.hasNext()){
|
||||
return doBadAuthorshipNoPub( vreq );
|
||||
}else if( rs.size() > 1 ){
|
||||
return doBadAuthorshipMultiplePubs(vreq);
|
||||
}else{
|
||||
//skip to publication
|
||||
RDFNode objNode = rs.next().get("obj");
|
||||
if (!objNode.isResource() || objNode.isAnon()) {
|
||||
return doBadAuthorshipNoPub( vreq );
|
||||
}
|
||||
EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo();
|
||||
editConfiguration.setSkipToUrl(UrlBuilder.getIndividualProfileUrl(((Resource) objNode).getURI(), vreq));
|
||||
return editConfiguration;
|
||||
}
|
||||
} finally {
|
||||
qe.close();
|
||||
}
|
||||
}
|
||||
|
||||
protected EditConfigurationVTwo doAddNew(VitroRequest vreq,
|
||||
HttpSession session) throws Exception {
|
||||
EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo();
|
||||
initBasics(editConfiguration, vreq);
|
||||
initPropertyParameters(vreq, session, editConfiguration);
|
||||
initObjectPropForm(editConfiguration, vreq);
|
||||
setVarNames(editConfiguration);
|
||||
|
||||
// Required N3
|
||||
editConfiguration.setN3Required(generateN3Required());
|
||||
|
||||
// Optional N3
|
||||
editConfiguration.setN3Optional(generateN3Optional());
|
||||
|
||||
editConfiguration.setNewResources(generateNewResources(vreq));
|
||||
|
||||
// In scope
|
||||
setUrisAndLiteralsInScope(editConfiguration, vreq);
|
||||
|
||||
// on Form
|
||||
setUrisAndLiteralsOnForm(editConfiguration, vreq);
|
||||
|
||||
// Sparql queries
|
||||
setSparqlQueries(editConfiguration, vreq);
|
||||
|
||||
// set fields
|
||||
setFields(editConfiguration, vreq);
|
||||
|
||||
// template file
|
||||
editConfiguration.setTemplate("addPublicationToPerson.ftl");
|
||||
// adding person has publication validator
|
||||
editConfiguration.addValidator(new AntiXssValidation());
|
||||
editConfiguration.addValidator(new AutocompleteRequiredInputValidator("pubUri", "title"));
|
||||
editConfiguration.addValidator(new PersonHasPublicationValidator());
|
||||
|
||||
// Adding additional data, specifically edit mode
|
||||
addFormSpecificData(editConfiguration, vreq);
|
||||
prepare(vreq, editConfiguration);
|
||||
return editConfiguration;
|
||||
}
|
||||
|
||||
private EditConfigurationVTwo doBadAuthorshipMultiplePubs(VitroRequest vreq) {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
private EditConfigurationVTwo doBadAuthorshipNoPub(VitroRequest vreq) {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
private void setVarNames(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.setVarNameForSubject("person");
|
||||
editConfiguration.setVarNameForPredicate("predicate");
|
||||
editConfiguration.setVarNameForObject("authorshipUri");
|
||||
|
||||
}
|
||||
|
||||
/***N3 strings both required and optional***/
|
||||
private List<String> generateN3Optional() {
|
||||
return list(getN3ForNewPub(),
|
||||
getN3ForExistingPub(),
|
||||
getN3ForNewCollection(),
|
||||
getN3ForNewBook(),
|
||||
getN3ForNewConference(),
|
||||
getN3ForNewEvent(),
|
||||
getN3ForNewEditor(),
|
||||
getN3ForNewPublisher(),
|
||||
getN3ForNewCollectionNewPub(),
|
||||
getN3ForNewBookNewPub(),
|
||||
getN3ForNewConferenceNewPub(),
|
||||
getN3ForNewEventNewPub(),
|
||||
getN3ForNewEditorNewPub(),
|
||||
getN3ForNewPublisherNewPub(),
|
||||
getN3ForCollection(),
|
||||
getN3ForBook(),
|
||||
getN3ForConference(),
|
||||
getN3ForEvent(),
|
||||
getN3ForEditor(),
|
||||
getN3ForPublisher(),
|
||||
getN3ForCollectionNewPub(),
|
||||
getN3ForBookNewPub(),
|
||||
getN3ForConferenceNewPub(),
|
||||
getN3ForEventNewPub(),
|
||||
getN3ForEditorNewPub(),
|
||||
getN3ForPublisherNewPub(),
|
||||
getN3FirstNameAssertion(),
|
||||
getN3LastNameAssertion(),
|
||||
getN3ForLocaleAssertion(),
|
||||
getN3ForVolumeAssertion(),
|
||||
getN3ForNumberAssertion(),
|
||||
getN3ForIssueAssertion(),
|
||||
getN3ForChapterNbrAssertion(),
|
||||
getN3ForStartPageAssertion(),
|
||||
getN3ForEndPageAssertion(),
|
||||
getN3ForDateTimeAssertion(),
|
||||
getN3ForNewBookNewEditor(),
|
||||
getN3ForNewBookEditor(),
|
||||
getN3ForNewBookNewPublisher(),
|
||||
getN3ForNewBookPublisher(),
|
||||
getN3ForNewBookVolume(),
|
||||
getN3ForNewBookLocale(),
|
||||
getN3ForNewBookPubDate()
|
||||
);
|
||||
}
|
||||
|
||||
private List<String> generateN3Required() {
|
||||
return list(getAuthorshipN3()
|
||||
);
|
||||
}
|
||||
|
||||
private String getAuthorshipN3() {
|
||||
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 ." +
|
||||
"?authorshipUri core:relates ?newPublication ." +
|
||||
"?newPublication core:relatedBy ?authorshipUri .";
|
||||
}
|
||||
|
||||
private String getN3ForExistingPub() {
|
||||
return "@prefix core: <" + vivoCore + "> ." +
|
||||
"?authorshipUri core:relates ?pubUri ." +
|
||||
"?pubUri core:relatedBy ?authorshipUri .";
|
||||
}
|
||||
|
||||
private String getN3ForNewCollectionNewPub() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newPublication vivo:hasPublicationVenue ?newCollection . \n" +
|
||||
"?newCollection a <" + collectionClass + "> . \n" +
|
||||
"?newCollection vivo:publicationVenueFor ?newPublication . \n" +
|
||||
"?newCollection <" + label + "> ?collection .";
|
||||
}
|
||||
|
||||
private String getN3ForNewCollection() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?pubUri vivo:hasPublicationVenue ?newCollection . \n" +
|
||||
"?newCollection a <" + collectionClass + "> . \n" +
|
||||
"?newCollection vivo:publicationVenueFor ?pubUri . \n" +
|
||||
"?newCollection <" + label + "> ?collection .";
|
||||
}
|
||||
|
||||
private String getN3ForCollectionNewPub() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newPublication vivo:hasPublicationVenue ?collectionUri . \n" +
|
||||
"?collectionUri vivo:publicationVenueFor ?newPublication . ";
|
||||
}
|
||||
|
||||
private String getN3ForCollection() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?pubUri vivo:hasPublicationVenue ?collectionUri . \n" +
|
||||
"?collectionUri vivo:publicationVenueFor ?pubUri . ";
|
||||
}
|
||||
|
||||
private String getN3ForNewBook() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?pubUri vivo:hasPublicationVenue ?newBook . \n" +
|
||||
"?newBook a <" + bookClass + "> . \n" +
|
||||
"?newBook vivo:publicationVenueFor ?pubUri . \n " +
|
||||
"?newBook <" + label + "> ?book .";
|
||||
}
|
||||
|
||||
private String getN3ForBook() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?pubUri vivo:hasPublicationVenue ?bookUri . \n" +
|
||||
"?bookUri vivo:publicationVenueFor ?pubUri . ";
|
||||
}
|
||||
|
||||
private String getN3ForNewBookNewPub() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newPublication vivo:hasPublicationVenue ?newBook . \n" +
|
||||
"?newBook a <" + bookClass + "> . \n" +
|
||||
"?newBook vivo:publicationVenueFor ?newPublication . \n " +
|
||||
"?newBook <" + label + "> ?book . ";
|
||||
}
|
||||
|
||||
private String getN3ForNewBookVolume() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newBook <" + volumePred + "> ?volume . ";
|
||||
}
|
||||
|
||||
private String getN3ForNewBookLocale() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newBook <" + localePred + "> ?locale . ";
|
||||
}
|
||||
|
||||
private String getN3ForNewBookPubDate() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newBook <" + dateTimePred + "> ?dateTimeNode . \n" +
|
||||
"?dateTimeNode a <" + dateTimeValueType + "> . \n" +
|
||||
"?dateTimeNode <" + dateTimeValue + "> ?dateTime-value . \n" +
|
||||
"?dateTimeNode <" + dateTimePrecision + "> ?dateTime-precision .";
|
||||
}
|
||||
|
||||
private String getN3ForNewBookNewEditor() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newBook vivo:relatedBy ?editorship . \n" +
|
||||
"?editorship vivo:relates ?newBook . \n" +
|
||||
"?newBook <" + label + "> ?book . \n " +
|
||||
"?editorship a vivo:Editorship . \n" +
|
||||
"?editorship vivo:relates ?newEditor . \n" +
|
||||
"?newEditor a <" + editorClass + "> . \n" +
|
||||
"?newEditor vivo:relatedBy ?editorship . \n" +
|
||||
"?newEditor <" + label + "> ?editor .";
|
||||
}
|
||||
|
||||
private String getN3ForNewBookEditor() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newBook vivo:relatedBy ?editorship . \n" +
|
||||
"?editorship vivo:relates ?newBook . \n" +
|
||||
"?newBook <" + label + "> ?book . \n " +
|
||||
"?editorship a vivo:Editorship . \n" +
|
||||
"?editorship vivo:relates ?editorUri . \n" +
|
||||
"?editorUri vivo:relatedBy ?editorship . ";
|
||||
}
|
||||
|
||||
private String getN3ForNewBookNewPublisher() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newBook vivo:publisher ?newPublisher . \n " +
|
||||
"?newPublisher vivo:publisherOf ?newBook . \n" +
|
||||
"?newPublisher <" + label + "> ?publisher .";
|
||||
}
|
||||
|
||||
private String getN3ForNewBookPublisher() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newBook vivo:publisher ?publisherUri . \n" +
|
||||
"?publisherUri vivo:publisherOf ?newBook . ";
|
||||
}
|
||||
|
||||
private String getN3ForBookNewPub() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newPublication vivo:hasPublicationVenue ?bookUri . \n" +
|
||||
"?bookUri vivo:publicationVenueFor ?newPublication . ";
|
||||
}
|
||||
|
||||
private String getN3ForNewConference() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?pubUri <" + presentedAtPred + "> ?newConference . \n" +
|
||||
"?newConference a <" + conferenceClass + "> . \n" +
|
||||
"?newConference <http://purl.obolibrary.org/obo/BFO_0000051> ?pubUri . \n" +
|
||||
"?newConference <" + label + "> ?conference .";
|
||||
}
|
||||
|
||||
private String getN3ForConference() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?pubUri <" + presentedAtPred + "> ?conferenceUri . \n" +
|
||||
"?conferenceUri <http://purl.obolibrary.org/obo/BFO_0000051> ?pubUri . ";
|
||||
}
|
||||
|
||||
private String getN3ForNewConferenceNewPub() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newPublication <" + presentedAtPred + "> ?newConference . \n" +
|
||||
"?newConference a <" + conferenceClass + "> . \n" +
|
||||
"?newConference <http://purl.obolibrary.org/obo/BFO_0000051> ?newPublication . \n" +
|
||||
"?newConference <" + label + "> ?conference .";
|
||||
}
|
||||
|
||||
private String getN3ForConferenceNewPub() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newPublication <" + presentedAtPred + "> ?conferenceUri . \n" +
|
||||
"?conferenceUri <http://purl.obolibrary.org/obo/BFO_0000051> ?newPublication . ";
|
||||
}
|
||||
|
||||
private String getN3ForNewEvent() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?pubUri vivo:proceedingsOf ?newEvent . \n" +
|
||||
"?newEvent a <" + conferenceClass + "> . \n" +
|
||||
"?newEvent vivo:hasProceedings ?pubUri . \n" +
|
||||
"?newEvent <" + label + "> ?event .";
|
||||
}
|
||||
|
||||
private String getN3ForEvent() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?pubUri vivo:proceedingsOf ?eventUri . \n" +
|
||||
"?eventUri vivo:hasProceedings ?pubUri . ";
|
||||
}
|
||||
|
||||
private String getN3ForNewEventNewPub() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newPublication vivo:proceedingsOf ?newEvent . \n" +
|
||||
"?newEvent a <" + conferenceClass + "> . \n" +
|
||||
"?newEvent vivo:hasProceedings ?newPublication . \n" +
|
||||
"?newEvent <" + label + "> ?event .";
|
||||
}
|
||||
|
||||
private String getN3ForEventNewPub() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newPublication vivo:proceedingsOf ?eventUri . \n" +
|
||||
"?eventUri vivo:hasProceedings ?newPublication . ";
|
||||
}
|
||||
|
||||
private String getN3ForNewEditor() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?pubUri vivo:relatedBy ?editorship . \n" +
|
||||
"?editorship vivo:relates ?pubUri . \n" +
|
||||
"?editorship a vivo:Editorship . \n" +
|
||||
"?editorship vivo:relates ?newEditor . \n" +
|
||||
"?newEditor a <" + editorClass + "> . \n" +
|
||||
"?newEditor vivo:relatedBy ?editorship . \n" +
|
||||
"?newEditor <" + label + "> ?editor .";
|
||||
}
|
||||
|
||||
private String getN3ForEditor() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?pubUri vivo:relatedBy ?editorship . \n" +
|
||||
"?editorship vivo:relates ?pubUri . \n" +
|
||||
"?editorship a vivo:Editorship . \n" +
|
||||
"?editorship vivo:relates ?editorUri . \n" +
|
||||
"?editorUri vivo:relatedBy ?editorship . ";
|
||||
}
|
||||
|
||||
private String getN3ForNewEditorNewPub() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newPublication vivo:relatedBy ?editorship . \n" +
|
||||
"?editorship vivo:relates ?newPublication . \n" +
|
||||
"?newPublication <" + label + "> ?title ." +
|
||||
"?editorship a vivo:Editorship . \n" +
|
||||
"?editorship vivo:relates ?newEditor . \n" +
|
||||
"?newEditor a <" + editorClass + "> . \n" +
|
||||
"?newEditor vivo:relatedBy ?editorship . \n" +
|
||||
"?newEditor <" + label + "> ?editor .";
|
||||
}
|
||||
|
||||
private String getN3ForEditorNewPub() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newPublication vivo:relatedBy ?editorship . \n" +
|
||||
"?editorship vivo:relates ?newPublication . \n" +
|
||||
"?newPublication <" + label + "> ?title ." +
|
||||
"?editorship vivo:relates ?editorUri . \n" +
|
||||
"?editorship a vivo:Editorship . \n" +
|
||||
"?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 <" + label + "> ?publisher .";
|
||||
}
|
||||
|
||||
private String getN3ForPublisher() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?pubUri vivo:publisher ?publisherUri . \n" +
|
||||
"?publisherUri vivo:publisherOf ?pubUri . ";
|
||||
}
|
||||
|
||||
private String getN3ForNewPublisherNewPub() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newPublication vivo:publisher ?newPublisher . \n" +
|
||||
"?newPublisher a <" + publisherClass + "> . \n" +
|
||||
"?newPublisher vivo:publisherOf ?newPublication . \n" +
|
||||
"?newPublisher <" + label + "> ?publisher .";
|
||||
}
|
||||
|
||||
private String getN3ForPublisherNewPub() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newPublication vivo:publisher ?publisherUri . \n" +
|
||||
"?publisherUri vivo:publisherOf ?newPublication . ";
|
||||
}
|
||||
|
||||
private String getN3FirstNameAssertion() {
|
||||
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 vcard:hasName ?vcardName . \n" +
|
||||
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
|
||||
"?vcardName vcard:givenName ?firstName .";
|
||||
}
|
||||
|
||||
private String getN3LastNameAssertion() {
|
||||
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 vcard:hasName ?vcardName . \n" +
|
||||
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
|
||||
"?vcardName vcard:familyName ?lastName .";
|
||||
}
|
||||
|
||||
private String getN3ForLocaleAssertion() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newPublication <" + localePred + "> ?locale . ";
|
||||
}
|
||||
|
||||
private String getN3ForVolumeAssertion() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newPublication <" + volumePred + "> ?volume . ";
|
||||
}
|
||||
|
||||
private String getN3ForNumberAssertion() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newPublication <" + numberPred + "> ?number . ";
|
||||
}
|
||||
|
||||
private String getN3ForIssueAssertion() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newPublication <" + issuePred + "> ?issue . ";
|
||||
}
|
||||
|
||||
private String getN3ForChapterNbrAssertion() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newPublication <" + chapterNbrPred + "> ?chapterNbr . ";
|
||||
}
|
||||
|
||||
private String getN3ForStartPageAssertion() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newPublication <" + startPagePred + "> ?startPage . ";
|
||||
}
|
||||
|
||||
private String getN3ForEndPageAssertion() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newPublication <" + endPagePred + ">?endPage . ";
|
||||
}
|
||||
|
||||
private String getN3ForDateTimeAssertion() {
|
||||
return "@prefix vivo: <" + vivoCore + "> . \n" +
|
||||
"?newPublication <" + dateTimePred + "> ?dateTimeNode . \n" +
|
||||
"?dateTimeNode a <" + dateTimeValueType + "> . \n" +
|
||||
"?dateTimeNode <" + dateTimeValue + "> ?dateTime-value . \n" +
|
||||
"?dateTimeNode <" + dateTimePrecision + "> ?dateTime-precision . ";
|
||||
}
|
||||
|
||||
/** Get new resources */
|
||||
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>();
|
||||
newResources.put("authorshipUri", DEFAULT_NS_TOKEN);
|
||||
newResources.put("newPublication", DEFAULT_NS_TOKEN);
|
||||
newResources.put("newCollection", DEFAULT_NS_TOKEN);
|
||||
newResources.put("newBook", DEFAULT_NS_TOKEN);
|
||||
newResources.put("newConference", DEFAULT_NS_TOKEN);
|
||||
newResources.put("newEvent", DEFAULT_NS_TOKEN);
|
||||
newResources.put("newEditor", DEFAULT_NS_TOKEN);
|
||||
newResources.put("editorship", DEFAULT_NS_TOKEN);
|
||||
newResources.put("vcardEditor", DEFAULT_NS_TOKEN);
|
||||
newResources.put("vcardName", DEFAULT_NS_TOKEN);
|
||||
newResources.put("newPublisher", DEFAULT_NS_TOKEN);
|
||||
newResources.put("dateTimeNode", DEFAULT_NS_TOKEN);
|
||||
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>>();
|
||||
urisInScope.put(editConfiguration.getVarNameForSubject(),
|
||||
Arrays.asList(new String[]{editConfiguration.getSubjectUri()}));
|
||||
urisInScope.put(editConfiguration.getVarNameForPredicate(),
|
||||
Arrays.asList(new String[]{editConfiguration.getPredicateUri()}));
|
||||
editConfiguration.setUrisInScope(urisInScope);
|
||||
HashMap<String, List<Literal>> literalsInScope = new HashMap<String, List<Literal>>();
|
||||
editConfiguration.setLiteralsInScope(literalsInScope);
|
||||
|
||||
}
|
||||
|
||||
private void setUrisAndLiteralsOnForm(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
|
||||
List<String> urisOnForm = new ArrayList<String>();
|
||||
//add role activity and roleActivityType to uris on form
|
||||
urisOnForm.add("pubType");
|
||||
urisOnForm.add("pubUri");
|
||||
urisOnForm.add("collectionUri");
|
||||
urisOnForm.add("bookUri");
|
||||
urisOnForm.add("conferenceUri");
|
||||
urisOnForm.add("eventUri");
|
||||
urisOnForm.add("editorUri");
|
||||
urisOnForm.add("publisherUri");
|
||||
editConfiguration.setUrisOnform(urisOnForm);
|
||||
|
||||
//activity label and role label are literals on form
|
||||
List<String> literalsOnForm = new ArrayList<String>();
|
||||
literalsOnForm.add("title");
|
||||
literalsOnForm.add("collection");
|
||||
literalsOnForm.add("book");
|
||||
literalsOnForm.add("conference");
|
||||
literalsOnForm.add("event");
|
||||
literalsOnForm.add("editor");
|
||||
literalsOnForm.add("publisher");
|
||||
literalsOnForm.add("collectionDisplay");
|
||||
literalsOnForm.add("bookDisplay");
|
||||
literalsOnForm.add("conferenceDisplay");
|
||||
literalsOnForm.add("eventDisplay");
|
||||
literalsOnForm.add("editorDisplay");
|
||||
literalsOnForm.add("publisherDisplay");
|
||||
literalsOnForm.add("locale");
|
||||
literalsOnForm.add("volume");
|
||||
literalsOnForm.add("number");
|
||||
literalsOnForm.add("issue");
|
||||
literalsOnForm.add("chapterNbr");
|
||||
literalsOnForm.add("startPage");
|
||||
literalsOnForm.add("endPage");
|
||||
literalsOnForm.add("firstName");
|
||||
literalsOnForm.add("lastName");
|
||||
editConfiguration.setLiteralsOnForm(literalsOnForm);
|
||||
}
|
||||
|
||||
/** Set SPARQL Queries and supporting methods. */
|
||||
//In this case no queries for existing
|
||||
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>());
|
||||
editConfiguration.setSparqlForExistingLiterals(new HashMap<String, String>());
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Set Fields and supporting methods
|
||||
* @throws Exception
|
||||
*/
|
||||
|
||||
private void setFields(EditConfigurationVTwo editConfiguration, VitroRequest vreq) throws Exception {
|
||||
setTitleField(editConfiguration);
|
||||
setPubTypeField(editConfiguration);
|
||||
setPubUriField(editConfiguration);
|
||||
setCollectionLabelField(editConfiguration);
|
||||
setCollectionDisplayField(editConfiguration);
|
||||
setCollectionUriField(editConfiguration);
|
||||
setBookLabelField(editConfiguration);
|
||||
setBookDisplayField(editConfiguration);
|
||||
setBookUriField(editConfiguration);
|
||||
setConferenceLabelField(editConfiguration);
|
||||
setConferenceDisplayField(editConfiguration);
|
||||
setConferenceUriField(editConfiguration);
|
||||
setEventLabelField(editConfiguration);
|
||||
setEventDisplayField(editConfiguration);
|
||||
setEventUriField(editConfiguration);
|
||||
setEditorLabelField(editConfiguration);
|
||||
setEditorDisplayField(editConfiguration);
|
||||
setFirstNameField(editConfiguration);
|
||||
setLastNameField(editConfiguration);
|
||||
setEditorUriField(editConfiguration);
|
||||
setPublisherLabelField(editConfiguration);
|
||||
setPublisherDisplayField(editConfiguration);
|
||||
setPublisherUriField(editConfiguration);
|
||||
setLocaleField(editConfiguration);
|
||||
setVolumeField(editConfiguration);
|
||||
setNumberField(editConfiguration);
|
||||
setIssueField(editConfiguration);
|
||||
setChapterNbrField(editConfiguration);
|
||||
setStartPageField(editConfiguration);
|
||||
setEndPageField(editConfiguration);
|
||||
setDateTimeField(editConfiguration);
|
||||
}
|
||||
|
||||
private void setTitleField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("title").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
|
||||
private void setPubTypeField(EditConfigurationVTwo editConfiguration) throws Exception {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("pubType").
|
||||
setValidators( list("nonempty") ).
|
||||
setOptions( new ConstantFieldOptions("pubType", getPublicationTypeLiteralOptions() ))
|
||||
);
|
||||
}
|
||||
|
||||
private void setPubUriField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("pubUri"));
|
||||
}
|
||||
|
||||
private void setCollectionLabelField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("collection").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
|
||||
private void setCollectionDisplayField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("collectionDisplay").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
|
||||
private void setCollectionUriField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("collectionUri"));
|
||||
}
|
||||
|
||||
private void setBookLabelField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("book").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
|
||||
private void setBookDisplayField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("bookDisplay").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
|
||||
private void setBookUriField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("bookUri"));
|
||||
}
|
||||
|
||||
private void setConferenceLabelField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("conference").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
|
||||
private void setConferenceDisplayField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("conferenceDisplay").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
|
||||
private void setConferenceUriField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("conferenceUri"));
|
||||
}
|
||||
|
||||
private void setEventLabelField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("event").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
|
||||
private void setEventDisplayField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("eventDisplay").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
|
||||
|
||||
private void setFirstNameField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("firstName").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
|
||||
private void setLastNameField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("lastName").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
private void setEventUriField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("eventUri"));
|
||||
}
|
||||
|
||||
private void setEditorLabelField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("editor").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
|
||||
private void setEditorDisplayField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("editorDisplay").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
|
||||
private void setEditorUriField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("editorUri"));
|
||||
}
|
||||
|
||||
private void setPublisherLabelField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("publisher").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
|
||||
private void setPublisherDisplayField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("publisherDisplay").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
|
||||
private void setPublisherUriField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("publisherUri"));
|
||||
}
|
||||
|
||||
private void setLocaleField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("locale").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
|
||||
private void setVolumeField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("volume").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
|
||||
private void setNumberField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("number").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
|
||||
private void setIssueField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("issue").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
|
||||
private void setChapterNbrField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("chapterNbr").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
|
||||
private void setStartPageField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("startPage").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
|
||||
private void setEndPageField(EditConfigurationVTwo editConfiguration) {
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("endPage").
|
||||
setValidators(list("datatype:" + stringDatatypeUri)).
|
||||
setRangeDatatypeUri(stringDatatypeUri));
|
||||
}
|
||||
|
||||
private void setDateTimeField(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("dateTime").
|
||||
setEditElement(
|
||||
new DateTimeWithPrecisionVTwo(null,
|
||||
VitroVocabulary.Precision.YEAR.uri(),
|
||||
VitroVocabulary.Precision.NONE.uri())
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
private List<List<String>> getPublicationTypeLiteralOptions() {
|
||||
List<List<String>> literalOptions = new ArrayList<List<String>>();
|
||||
literalOptions.add(list("http://vivoweb.org/ontology/core#Abstract", "Abstract"));
|
||||
literalOptions.add(list("http://purl.org/ontology/bibo/AcademicArticle", "Academic Article"));
|
||||
literalOptions.add(list("http://purl.org/ontology/bibo/Article", "Article"));
|
||||
literalOptions.add(list("http://purl.org/ontology/bibo/AudioDocument", "Audio Document"));
|
||||
literalOptions.add(list("http://vivoweb.org/ontology/core#BlogPosting", "Blog Posting"));
|
||||
literalOptions.add(list("http://purl.org/ontology/bibo/Book", "Book"));
|
||||
literalOptions.add(list("http://vivoweb.org/ontology/core#CaseStudy", "Case Study"));
|
||||
literalOptions.add(list("http://vivoweb.org/ontology/core#Catalog", "Catalog"));
|
||||
literalOptions.add(list("http://purl.org/ontology/bibo/Chapter", "Chapter"));
|
||||
literalOptions.add(list("http://vivoweb.org/ontology/core#ConferencePaper", "Conference Paper"));
|
||||
literalOptions.add(list("http://vivoweb.org/ontology/core#ConferencePoster", "Conference Poster"));
|
||||
literalOptions.add(list("http://vivoweb.org/ontology/core#Database", "Database"));
|
||||
literalOptions.add(list("http://vivoweb.org/ontology/core#Dataset", "Dataset"));
|
||||
literalOptions.add(list("http://purl.org/ontology/bibo/EditedBook", "Edited Book"));
|
||||
literalOptions.add(list("http://vivoweb.org/ontology/core#EditorialArticle", "Editorial Article"));
|
||||
literalOptions.add(list("http://purl.org/ontology/bibo/Film", "Film"));
|
||||
literalOptions.add(list("http://vivoweb.org/ontology/core#Newsletter", "Newsletter"));
|
||||
literalOptions.add(list("http://vivoweb.org/ontology/core#NewsRelease", "News Release"));
|
||||
literalOptions.add(list("http://purl.org/ontology/bibo/Patent", "Patent"));
|
||||
literalOptions.add(list("http://purl.obolibrary.org/obo/OBI_0000272", "Protocol"));
|
||||
literalOptions.add(list("http://purl.org/ontology/bibo/Report", "Report"));
|
||||
literalOptions.add(list("http://vivoweb.org/ontology/core#ResearchProposal", "Research Proposal"));
|
||||
literalOptions.add(list("http://vivoweb.org/ontology/core#Review", "Review"));
|
||||
literalOptions.add(list("http://purl.obolibrary.org/obo/ERO_0000071 ", "Software"));
|
||||
literalOptions.add(list("http://vivoweb.org/ontology/core#Speech", "Speech"));
|
||||
literalOptions.add(list("http://purl.org/ontology/bibo/Thesis", "Thesis"));
|
||||
literalOptions.add(list("http://vivoweb.org/ontology/core#Video", "Video"));
|
||||
literalOptions.add(list("http://purl.org/ontology/bibo/Webpage", "Webpage"));
|
||||
literalOptions.add(list("http://purl.org/ontology/bibo/Website", "Website"));
|
||||
literalOptions.add(list("http://vivoweb.org/ontology/core#WorkingPaper", "Working Paper"));
|
||||
return literalOptions;
|
||||
}
|
||||
|
||||
//Form specific data
|
||||
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
|
||||
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
|
||||
formSpecificData.put("editMode", getEditMode(vreq).name().toLowerCase());
|
||||
formSpecificData.put("sparqlForAcFilter", getSparqlForAcFilter(vreq));
|
||||
editConfiguration.setFormSpecificData(formSpecificData);
|
||||
}
|
||||
|
||||
public String getSparqlForAcFilter(VitroRequest vreq) {
|
||||
String subject = EditConfigurationUtils.getSubjectUri(vreq);
|
||||
|
||||
String query = "PREFIX core:<" + vivoCore + "> " +
|
||||
"SELECT ?pubUri WHERE { " +
|
||||
"<" + subject + "> core:relatedBy ?authorshipUri . " +
|
||||
"?authorshipUri a core:Authorship . " +
|
||||
"?authorshipUri core:relates ?pubUri . }";
|
||||
return query;
|
||||
}
|
||||
|
||||
public EditMode getEditMode(VitroRequest vreq) {
|
||||
return EditModeUtils.getEditMode(vreq, list("http://vivoweb.org/ontology/core#relates"));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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 AddResearcherRoleToPersonGenerator extends AddRoleToPersonTwoStageGenerator {
|
||||
|
||||
private static String template = "addResearcherRoleToPerson.ftl";
|
||||
|
||||
@Override
|
||||
String getTemplate() {
|
||||
return template;
|
||||
}
|
||||
|
||||
@Override
|
||||
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",
|
||||
"http://vivoweb.org/ontology/core#Project", "Project",
|
||||
"http://purl.obolibrary.org/obo/ERO_0000014", "Research Project");
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
*/
|
||||
}
|
|
@ -0,0 +1,134 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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.ConstantFieldOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldOptions;
|
||||
|
||||
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
|
||||
//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
|
||||
*/
|
||||
@Override
|
||||
FieldOptions getRoleActivityFieldOptions(VitroRequest vreq) throws Exception {
|
||||
return new ConstantFieldOptions(
|
||||
"", "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",
|
||||
"http://purl.org/ontology/bibo/AudioVisualDocument", "Audio-Visual Document",
|
||||
"http://purl.org/ontology/bibo/Bill", "Bill",
|
||||
"http://vivoweb.org/ontology/core#Blog", "Blog",
|
||||
"http://vivoweb.org/ontology/core#BlogPosting", "Blog Posting",
|
||||
"http://purl.org/ontology/bibo/Book", "Book",
|
||||
"http://purl.org/ontology/bibo/BookSection", "Book Section",
|
||||
"http://purl.org/ontology/bibo/Brief", "Brief",
|
||||
"http://vivoweb.org/ontology/core#CaseStudy", "Case Study",
|
||||
"http://vivoweb.org/ontology/core#Catalog", "Catalog",
|
||||
"http://purl.org/ontology/bibo/Chapter", "Chapter",
|
||||
"http://purl.org/spar/fabio/ClinicalGuideline", "Clinical Guideline",
|
||||
"http://purl.org/ontology/bibo/Code", "Code",
|
||||
"http://purl.org/ontology/bibo/CollectedDocument", "Collected Document",
|
||||
"http://purl.org/spar/fabio/Comment", "Comment",
|
||||
"http://vivoweb.org/ontology/core#ConferencePaper", "Conference Paper",
|
||||
"http://vivoweb.org/ontology/core#ConferencePoster", "Conference Poster",
|
||||
"http://purl.org/ontology/bibo/CourtReporter", "Court Reporter",
|
||||
"http://vivoweb.org/ontology/core#Database", "Database",
|
||||
"http://purl.org/ontology/bibo/LegalDecision", "Decision",
|
||||
"http://purl.org/ontology/bibo/DocumentPart", "Document Part",
|
||||
"http://purl.org/ontology/bibo/EditedBook", "Edited Book",
|
||||
"http://vivoweb.org/ontology/core#EditorialArticle", "Editorial Article",
|
||||
"http://purl.org/spar/fabio/Erratum", "Erratum",
|
||||
"http://purl.org/ontology/bibo/Excerpt", "Excerpt",
|
||||
"http://purl.org/ontology/bibo/Film", "Film",
|
||||
"http://purl.org/ontology/bibo/Image", "Image",
|
||||
"http://purl.org/ontology/bibo/Issue", "Issue",
|
||||
"http://purl.org/ontology/bibo/Journal", "Journal",
|
||||
"http://purl.obolibrary.org/obo/IAO_0000013", "Journal Article",
|
||||
"http://purl.org/ontology/bibo/LegalCaseDocument", "Legal Case Document",
|
||||
"http://purl.org/ontology/bibo/LegalDocument", "Legal Document",
|
||||
"http://purl.org/ontology/bibo/Legislation", "Legislation",
|
||||
"http://purl.org/ontology/bibo/Letter", "Letter",
|
||||
"http://purl.org/ontology/bibo/Magazine", "Magazine",
|
||||
"http://purl.org/ontology/bibo/Manual", "Manual",
|
||||
"http://purl.org/ontology/bibo/Manuscript", "Manuscript",
|
||||
"http://purl.org/ontology/bibo/Map", "Map",
|
||||
"http://vivoweb.org/ontology/core#Newsletter", "Newsletter",
|
||||
"http://purl.org/ontology/bibo/Newspaper", "Newspaper",
|
||||
"http://vivoweb.org/ontology/core#NewsRelease", "News Release",
|
||||
"http://purl.org/ontology/bibo/Note", "Note",
|
||||
"http://purl.org/ontology/bibo/Patent", "Patent",
|
||||
"http://purl.org/ontology/bibo/Periodical", "Periodical",
|
||||
"http://purl.org/ontology/bibo/PersonalCommunicationDocument", "Personal Communication Document",
|
||||
"http://purl.org/ontology/bibo/Proceedings", "Proceedings",
|
||||
"http://purl.obolibrary.org/obo/OBI_0000272", "protocol",
|
||||
"http://purl.org/ontology/bibo/Quote", "Quote",
|
||||
"http://purl.org/ontology/bibo/ReferenceSource", "Reference Source",
|
||||
"http://purl.org/ontology/bibo/Report", "Report",
|
||||
"http://vivoweb.org/ontology/core#ResearchProposal", "Research Proposal",
|
||||
"http://vivoweb.org/ontology/core#Review", "Review",
|
||||
"http://vivoweb.org/ontology/core#Score", "Score",
|
||||
"http://vivoweb.org/ontology/core#Screenplay", "Screenplay",
|
||||
"http://purl.org/ontology/bibo/Series", "Series",
|
||||
"http://purl.org/ontology/bibo/Slide", "Slide",
|
||||
"http://purl.org/ontology/bibo/Slideshow", "Slideshow",
|
||||
"http://vivoweb.org/ontology/core#Speech", "Speech",
|
||||
"http://purl.org/ontology/bibo/Standard", "Standard",
|
||||
"http://purl.org/ontology/bibo/Statute", "Statute",
|
||||
"http://purl.org/ontology/bibo/Thesis", "Thesis",
|
||||
"http://vivoweb.org/ontology/core#Translation", "Translation",
|
||||
"http://vivoweb.org/ontology/core#Video", "Video",
|
||||
"http://purl.org/ontology/bibo/Webpage", "Webpage",
|
||||
"http://purl.org/ontology/bibo/Website", "Website",
|
||||
"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,
|
||||
* 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;
|
||||
}
|
||||
*/
|
||||
|
||||
}
|
|
@ -0,0 +1,896 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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.lang.StringUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.vivoweb.webapp.util.ModelUtils;
|
||||
|
||||
import com.hp.hpl.jena.vocabulary.RDF;
|
||||
import com.hp.hpl.jena.vocabulary.RDFS;
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.jena.QueryUtils;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.AutocompleteRequiredInputValidator;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeIntervalValidationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo;
|
||||
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.ChildVClassesOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ConstantFieldOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaClassGroupOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.RoleToActivityPredicatePreprocessor;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils.EditMode;
|
||||
import edu.cornell.mannlib.vitro.webapp.utils.generators.EditModeUtils;
|
||||
/**
|
||||
* 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.
|
||||
|
||||
This is intended to create a set of statements like:
|
||||
|
||||
?person core:hasResearchActivityRole ?newRole.
|
||||
?newRole rdf:type core:ResearchActivityRole ;
|
||||
roleToActivityPredicate ?someActivity .
|
||||
?someActivity rdf:type core:ResearchActivity .
|
||||
?someActivity rdfs:label "activity title" .
|
||||
|
||||
|
||||
|
||||
Important: This form cannot be directly used as a custom form. It has parameters that must be set.
|
||||
See addClinicalRoleToPerson.jsp for an example.
|
||||
|
||||
roleToActivityPredicate and activityToRolePredicate are both dependent on the type of
|
||||
the activity itself. For a new statement, the predicate type is not known.
|
||||
For an existing statement, the predicate is known but may change based on the type of the activity newly selected.
|
||||
|
||||
|
||||
bdc34:
|
||||
TODO: figure out what needs to be customized per role form, document it here in comments
|
||||
TODO: rewrite class as an abstract class with simple, documented, required methods to override
|
||||
|
||||
AddRoleToPersonTwoStageGenerator is abstract, each subclass will need to configure:
|
||||
From the old JSP version:
|
||||
|
||||
showRoleLabelField boolean
|
||||
roleType URI
|
||||
roleToActivityPredicate URI
|
||||
activityToRolePredicate URI
|
||||
roleActivityType_optionsType
|
||||
roleActivityType_objectClassURI
|
||||
roleActivityType_literalOptions
|
||||
|
||||
For the new generator version:
|
||||
template
|
||||
*
|
||||
*/
|
||||
public abstract class AddRoleToPersonTwoStageGenerator extends BaseEditConfigurationGenerator implements EditConfigurationGenerator {
|
||||
|
||||
private Log log = LogFactory.getLog(AddRoleToPersonTwoStageGenerator.class);
|
||||
|
||||
/* ***** Methods that are REQUIRED to be implemented in subclasses ***** */
|
||||
|
||||
// abstract String getStartDatePrecision();
|
||||
|
||||
// abstract String getEndDatePrecision();
|
||||
|
||||
/** Freemarker template to use */
|
||||
abstract String getTemplate();
|
||||
|
||||
/** URI of type for the role context node */
|
||||
abstract String getRoleType();
|
||||
|
||||
/** return the java object that generates the role activity field options for
|
||||
* the subclass.
|
||||
* @throws Exception */
|
||||
abstract FieldOptions getRoleActivityFieldOptions(VitroRequest vreq) throws Exception;
|
||||
|
||||
/** In the case of literal options, subclass generator will set the options to be returned */
|
||||
//not needed any more since the FieldOption can be returned
|
||||
//abstract HashMap<String, String> getRoleActivityTypeLiteralOptions();
|
||||
|
||||
/**
|
||||
* Each subclass generator will return its own type of option here:
|
||||
* whether literal hardcoded, based on class group, or subclasses of a specific class
|
||||
* The latter two will apparently lend some kind of uri to objectClassUri ? */
|
||||
//not needed any more since the FieldOption can be returned
|
||||
//abstract RoleActivityOptionTypes getRoleActivityTypeOptionsType();
|
||||
|
||||
/** The URI of a Class to use with options if required. An option type like
|
||||
* CHILD_VCLASSES would reqire a role activity object class URI. */
|
||||
//not needed any more since the FieldOption can be returned
|
||||
//abstract String getRoleActivityTypeObjectClassUri(VitroRequest vreq);
|
||||
|
||||
/** If true an input should be shown on the form for a
|
||||
* label for the role context node
|
||||
* TODO: move this to the FTL and have label optional. */
|
||||
abstract boolean isShowRoleLabelField();
|
||||
|
||||
/** URI of predicate between role context node and activity
|
||||
* @throws Exception */
|
||||
//Bdc34: not used anywhere? that's odd
|
||||
//abstract String getActivityToRolePredicate();
|
||||
|
||||
@Override
|
||||
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) throws Exception {
|
||||
EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo();
|
||||
initProcessParameters(vreq, session, editConfiguration);
|
||||
|
||||
editConfiguration.setVarNameForSubject("person");
|
||||
editConfiguration.setVarNameForPredicate("rolePredicate");
|
||||
editConfiguration.setVarNameForObject("role");
|
||||
|
||||
// Required N3
|
||||
editConfiguration.setN3Required(list(
|
||||
N3_PREFIX + "\n" +
|
||||
"?person ?rolePredicate ?role .\n" +
|
||||
"?role a ?roleType .\n" +
|
||||
"?role ?inverseRolePredicate ?person ."
|
||||
));
|
||||
|
||||
// Optional N3
|
||||
//Note here we are placing the role to activity relationships as optional, since
|
||||
//it's possible to delete this relationship from the activity
|
||||
//On submission, if we kept these statements in n3required, the retractions would
|
||||
//not have all variables substituted, leading to an error
|
||||
//Note also we are including the relationship as a separate string in the array, to allow it to be
|
||||
//independently evaluated and passed back with substitutions even if the other strings are not
|
||||
//substituted correctly.
|
||||
editConfiguration.setN3Optional( list(
|
||||
getN3ForNewRoleActivity(),
|
||||
getN3ForExistingRoleActivity(),
|
||||
// getN3ForActivityType(),
|
||||
getN3RoleLabelAssertion(),
|
||||
getN3ForStart(),
|
||||
getN3ForEnd() ));
|
||||
|
||||
editConfiguration.setNewResources( newResources(vreq) );
|
||||
|
||||
//In scope
|
||||
setUrisAndLiteralsInScope(editConfiguration, vreq);
|
||||
|
||||
//on Form
|
||||
setUrisAndLiteralsOnForm(editConfiguration, vreq);
|
||||
|
||||
//Sparql queries
|
||||
setSparqlQueries(editConfiguration, vreq);
|
||||
|
||||
//set fields
|
||||
setFields(editConfiguration, vreq, EditConfigurationUtils.getPredicateUri(vreq));
|
||||
|
||||
//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
|
||||
//default obj property form.populateTemplate or some such method
|
||||
//Select from existing also set within template itself
|
||||
editConfiguration.setTemplate(getTemplate());
|
||||
|
||||
//Add validator
|
||||
editConfiguration.addValidator(new DateTimeIntervalValidationVTwo("startField","endField") );
|
||||
editConfiguration.addValidator(new AntiXssValidation());
|
||||
editConfiguration.addValidator(new AutocompleteRequiredInputValidator("existingRoleActivity", "activityLabel"));
|
||||
|
||||
//Add preprocessors
|
||||
addPreprocessors(editConfiguration, vreq.getWebappDaoFactory());
|
||||
//Adding additional data, specifically edit mode
|
||||
addFormSpecificData(editConfiguration, vreq);
|
||||
|
||||
//prepare
|
||||
prepare(vreq, editConfiguration);
|
||||
return editConfiguration;
|
||||
}
|
||||
|
||||
private void initProcessParameters(VitroRequest vreq, HttpSession session, EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.setFormUrl(EditConfigurationUtils.getFormUrlWithoutContext(vreq));
|
||||
editConfiguration.setEntityToReturnTo(EditConfigurationUtils.getSubjectUri(vreq));
|
||||
}
|
||||
|
||||
/* N3 Required and Optional Generators as well as supporting methods */
|
||||
|
||||
private List<String> getN3ForNewRoleActivity() {
|
||||
List<String> n3ForNewRoleActivity = new ArrayList<String>();
|
||||
n3ForNewRoleActivity.add("?role " + getRoleToActivityPlaceholder() + " ?roleActivity .\n"+
|
||||
"?roleActivity " + getActivityToRolePlaceholder() + " ?role . \n" +
|
||||
"?roleActivity <" + RDFS.label.getURI() + "> ?activityLabel . \n" +
|
||||
"?roleActivity a ?roleActivityType .");
|
||||
return n3ForNewRoleActivity;
|
||||
}
|
||||
|
||||
private List<String> getN3ForExistingRoleActivity() {
|
||||
List<String> n3ForExistingRoleActivity = new ArrayList<String>();
|
||||
n3ForExistingRoleActivity.add("?role " + getRoleToActivityPlaceholder() + " ?existingRoleActivity .\n"+
|
||||
"?existingRoleActivity " + getActivityToRolePlaceholder() + " ?role . \n" +
|
||||
"?existingRoleActivity a ?roleActivityType .");
|
||||
return n3ForExistingRoleActivity;
|
||||
}
|
||||
|
||||
|
||||
private String getN3RoleLabelAssertion() {
|
||||
return "?role <" + RDFS.label.getURI() + "> ?roleLabel .";
|
||||
}
|
||||
|
||||
private List<String> getN3ForStart() {
|
||||
List<String> n3ForStart = new ArrayList<String>();
|
||||
n3ForStart.add("?role <" + RoleToIntervalURI + "> ?intervalNode ." +
|
||||
"?intervalNode <" + RDF.type.getURI() + "> <" + IntervalTypeURI + "> ." +
|
||||
"?intervalNode <" + IntervalToStartURI + "> ?startNode ." +
|
||||
"?startNode <" + RDF.type.getURI() + "> <" + DateTimeValueTypeURI + "> ." +
|
||||
"?startNode <" + DateTimeValueURI + "> ?startField-value ." +
|
||||
"?startNode <" + DateTimePrecisionURI + "> ?startField-precision .");
|
||||
return n3ForStart;
|
||||
}
|
||||
|
||||
private List<String> getN3ForEnd() {
|
||||
List<String> n3ForEnd = new ArrayList<String>();
|
||||
n3ForEnd.add("?role <" + RoleToIntervalURI + "> ?intervalNode . " +
|
||||
"?intervalNode <" + RDF.type.getURI() + "> <" + IntervalTypeURI + "> ." +
|
||||
"?intervalNode <" + IntervalToEndURI + "> ?endNode ." +
|
||||
"?endNode <" + RDF.type.getURI() + "> <" + DateTimeValueTypeURI + "> ." +
|
||||
"?endNode <" + DateTimeValueURI + "> ?endField-value ." +
|
||||
"?endNode <" + DateTimePrecisionURI+ "> ?endField-precision .");
|
||||
return n3ForEnd;
|
||||
}
|
||||
|
||||
/** Get new resources */
|
||||
private Map<String, String> newResources(VitroRequest vreq) {
|
||||
String DEFAULT_NS_TOKEN=null; //null forces the default NS
|
||||
|
||||
HashMap<String, String> newResources = new HashMap<String, String>();
|
||||
newResources.put("role", DEFAULT_NS_TOKEN);
|
||||
newResources.put("roleActivity", DEFAULT_NS_TOKEN);
|
||||
newResources.put("intervalNode", DEFAULT_NS_TOKEN);
|
||||
newResources.put("startNode", DEFAULT_NS_TOKEN);
|
||||
newResources.put("endNode", DEFAULT_NS_TOKEN);
|
||||
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>>();
|
||||
|
||||
//Setting inverse role predicate
|
||||
urisInScope.put("inverseRolePredicate", getInversePredicate(vreq));
|
||||
urisInScope.put("roleType", list( getRoleType() ) );
|
||||
|
||||
//Uris in scope include subject, predicate, and object var
|
||||
editConfiguration.setUrisInScope(urisInScope);
|
||||
|
||||
//literals in scope empty initially, usually populated by code in prepare for update
|
||||
//with existing values for variables
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
private void setUrisAndLiteralsOnForm(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
|
||||
List<String> urisOnForm = new ArrayList<String>();
|
||||
//add role activity and roleActivityType to uris on form
|
||||
urisOnForm.add("existingRoleActivity");
|
||||
urisOnForm.add("roleActivityType");
|
||||
//Also adding the predicates
|
||||
//TODO: Check how to override this in case of default parameter? Just write hidden input to form?
|
||||
urisOnForm.add("roleToActivityPredicate");
|
||||
urisOnForm.add("activityToRolePredicate");
|
||||
editConfiguration.setUrisOnform(urisOnForm);
|
||||
|
||||
//activity label and role label are literals on form
|
||||
List<String> literalsOnForm = new ArrayList<String>();
|
||||
literalsOnForm.add("activityLabel");
|
||||
literalsOnForm.add("activityLabelDisplay");
|
||||
literalsOnForm.add("roleLabel");
|
||||
editConfiguration.setLiteralsOnForm(literalsOnForm);
|
||||
}
|
||||
|
||||
/** Set SPARQL Queries and supporting methods.
|
||||
* @throws Exception */
|
||||
private void setSparqlQueries(EditConfigurationVTwo editConfiguration, VitroRequest vreq) throws Exception {
|
||||
//Queries for activity label, role label, start Field value, end Field value
|
||||
HashMap<String, String> map = new HashMap<String, String>();
|
||||
map.put("activityLabel", getActivityLabelQuery(vreq));
|
||||
map.put("roleLabel", getRoleLabelQuery(vreq));
|
||||
map.put("startField-value", getExistingStartDateQuery(vreq));
|
||||
map.put("endField-value", getExistingEndDateQuery(vreq));
|
||||
|
||||
editConfiguration.setSparqlForExistingLiterals(map);
|
||||
|
||||
//Queries for role activity, activity type query, interval node,
|
||||
// start node, end node, start field precision, endfield precision
|
||||
map = new HashMap<String, String>();
|
||||
map.put("existingRoleActivity", getExistingRoleActivityQuery(vreq));
|
||||
map.put("roleActivityType", getActivityTypeQuery(vreq));
|
||||
map.put("intervalNode", getIntervalNodeQuery(vreq));
|
||||
map.put("startNode", getStartNodeQuery(vreq));
|
||||
map.put("endNode", getEndNodeQuery(vreq));
|
||||
map.put("startField-precision", getStartPrecisionQuery(vreq));
|
||||
map.put("endField-precision", getEndPrecisionQuery(vreq));
|
||||
//Also need sparql queries for roleToActivityPredicate and activityToRolePredicate
|
||||
map.put("roleToActivityPredicate", getRoleToActivityPredicateQuery(vreq));
|
||||
map.put("activityToRolePredicate", getActivityToRolePredicateQuery(vreq));
|
||||
|
||||
editConfiguration.setSparqlForExistingUris(map);
|
||||
}
|
||||
|
||||
private String getActivityToRolePredicateQuery(VitroRequest vreq) {
|
||||
String query = "SELECT ?existingActivityToRolePredicate \n " +
|
||||
"WHERE { \n" +
|
||||
"?roleActivity ?existingActivityToRolePredicate ?role .\n";
|
||||
//Get possible predicates
|
||||
List<String> addToQuery = new ArrayList<String>();
|
||||
List<String> predicates = getPossibleActivityToRolePredicates();
|
||||
for(String p:predicates) {
|
||||
addToQuery.add("(?existingActivityToRolePredicate=<" + p + ">)");
|
||||
}
|
||||
query += "FILTER (" + StringUtils.join(addToQuery, " || ") + ")\n";
|
||||
query += "}";
|
||||
return query;
|
||||
}
|
||||
|
||||
private String getRoleToActivityPredicateQuery(VitroRequest vreq) {
|
||||
String query = "SELECT ?existingRoleToActivityPredicate \n " +
|
||||
"WHERE { \n" +
|
||||
"?role ?existingRoleToActivityPredicate ?roleActivity .\n";
|
||||
//Get possible predicates
|
||||
query += getFilterRoleToActivityPredicate("existingRoleToActivityPredicate");
|
||||
query += "\n}";
|
||||
return query;
|
||||
}
|
||||
|
||||
private String getEndPrecisionQuery(VitroRequest vreq) {
|
||||
String query = "SELECT ?existingEndPrecision WHERE {\n" +
|
||||
"?role <" + RoleToIntervalURI + "> ?intervalNode .\n" +
|
||||
"?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n" +
|
||||
"?intervalNode <" + IntervalToEndURI + "> ?endNode .\n" +
|
||||
"?endNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> . \n" +
|
||||
"?endNode <" + DateTimePrecisionURI + "> ?existingEndPrecision . }";
|
||||
return query;
|
||||
}
|
||||
|
||||
private String getStartPrecisionQuery(VitroRequest vreq) {
|
||||
String query = "SELECT ?existingStartPrecision WHERE {\n" +
|
||||
"?role <" + RoleToIntervalURI + "> ?intervalNode .\n" +
|
||||
"?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n" +
|
||||
"?intervalNode <" + IntervalToStartURI + "> ?startNode .\n" +
|
||||
"?startNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> . \n" +
|
||||
"?startNode <" + DateTimePrecisionURI + "> ?existingStartPrecision . }";
|
||||
return query;
|
||||
}
|
||||
|
||||
private String getEndNodeQuery(VitroRequest vreq) {
|
||||
String query = "SELECT ?existingEndNode WHERE {\n"+
|
||||
"?role <" + RoleToIntervalURI + "> ?intervalNode .\n"+
|
||||
"?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n"+
|
||||
"?intervalNode <" + IntervalToEndURI + "> ?existingEndNode . \n"+
|
||||
"?existingEndNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> .}\n";
|
||||
return query;
|
||||
}
|
||||
|
||||
private String getStartNodeQuery(VitroRequest vreq) {
|
||||
String query = "SELECT ?existingStartNode WHERE {\n"+
|
||||
"?role <" + RoleToIntervalURI + "> ?intervalNode .\n"+
|
||||
"?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n"+
|
||||
"?intervalNode <" + IntervalToStartURI + "> ?existingStartNode . \n"+
|
||||
"?existingStartNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> .}";
|
||||
return query;
|
||||
}
|
||||
|
||||
private String getIntervalNodeQuery(VitroRequest vreq) {
|
||||
String query = "SELECT ?existingIntervalNode WHERE { \n" +
|
||||
"?role <" + RoleToIntervalURI + "> ?existingIntervalNode . \n" +
|
||||
" ?existingIntervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> . }\n";
|
||||
return query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method for subclasses to make a query for type from a ConstantFieldOptions object.
|
||||
* @throws Exception
|
||||
*/
|
||||
protected String getActivityTypeQueryForConstantOptions(VitroRequest vreq, ConstantFieldOptions fieldOptions )
|
||||
throws Exception{
|
||||
|
||||
//make list of type URIs from options, this can be called with null since
|
||||
//ConstantFieldOptions doesn't use any of the arguments.
|
||||
Map<String,String> options = fieldOptions.getOptions(null, null, null) ;
|
||||
|
||||
if (options != null && options.size() > 0) {
|
||||
List<String> typeUris = new ArrayList<String>();
|
||||
for(String typeUri: options.keySet()) {
|
||||
if(typeUri != null && !typeUri.isEmpty()) {
|
||||
typeUris.add("(?existingActivityType = <" + typeUri + ">)");
|
||||
}
|
||||
}
|
||||
|
||||
String defaultActivityTypeQuery = getDefaultActivityTypeQuery(vreq);
|
||||
String typeFilters = "FILTER (" + StringUtils.join(typeUris, "||") + ")";
|
||||
return defaultActivityTypeQuery.replaceAll("}$", "") + typeFilters + "}";
|
||||
} else {
|
||||
return getDefaultActivityTypeQuery(vreq);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method for subclasses to make a query for type from a ChildVClassesOptions object.
|
||||
* @throws Exception
|
||||
*/
|
||||
protected String getActivityTypeQueryForChildVClassOptions(VitroRequest vreq, ChildVClassesOptions opts){
|
||||
log.debug("objectClassUri = " + opts.getClassUri());
|
||||
return QueryUtils.subUriForQueryVar(
|
||||
getSubclassActivityTypeQuery(vreq),
|
||||
"objectClassUri", opts.getClassUri());
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method for subclasses to make a query for type from a IndividualsViaClassGroupOptions object.
|
||||
* @throws Exception
|
||||
*/
|
||||
protected String getActivityTypeQueryForIndividualsViaClassGroupOptions(VitroRequest vreq, IndividualsViaClassGroupOptions opts){
|
||||
log.debug("ClassGroupUri = " + opts.getClassGroupUri());
|
||||
return QueryUtils.subUriForQueryVar(
|
||||
getClassgroupActivityTypeQuery(vreq),
|
||||
"classgroup", opts.getClassGroupUri());
|
||||
}
|
||||
|
||||
/*
|
||||
* The activity type query results must be limited to the values in the activity type select element.
|
||||
* Sometimes the query returns a superclass such as owl:Thing instead.
|
||||
* Make use of vitro:mostSpecificType so that, for example, an individual is both a
|
||||
* core:InvitedTalk and a core:Presentation, core:InvitedTalk is selected.
|
||||
* vitro:mostSpecificType alone may not suffice, since it does not guarantee that the value returned
|
||||
* is in the select list.
|
||||
* We could still have problems if the value from the select list is not a vitro:mostSpecificType,
|
||||
* but that is unlikely.
|
||||
*
|
||||
*/
|
||||
private String getActivityTypeQuery(VitroRequest vreq) throws Exception {
|
||||
|
||||
String activityTypeQuery = null;
|
||||
|
||||
FieldOptions fieldOpts = getRoleActivityFieldOptions(vreq);
|
||||
try{
|
||||
if( fieldOpts == null ){
|
||||
activityTypeQuery = getDefaultActivityTypeQuery(vreq);
|
||||
}if( fieldOpts instanceof ConstantFieldOptions ){
|
||||
activityTypeQuery = getActivityTypeQueryForConstantOptions(vreq, (ConstantFieldOptions)fieldOpts); //
|
||||
}else if (fieldOpts instanceof ChildVClassesOptions ){
|
||||
activityTypeQuery = getActivityTypeQueryForChildVClassOptions(vreq, (ChildVClassesOptions)fieldOpts);
|
||||
}else if( fieldOpts instanceof IndividualsViaClassGroupOptions){
|
||||
activityTypeQuery = getActivityTypeQueryForIndividualsViaClassGroupOptions(vreq, (IndividualsViaClassGroupOptions)fieldOpts);
|
||||
}
|
||||
}catch(Exception ex){
|
||||
log.debug("error while building activity type query",ex);
|
||||
}
|
||||
activityTypeQuery = getDefaultActivityTypeQuery(vreq);
|
||||
|
||||
//The replacement of activity type query's predicate was only relevant when we actually
|
||||
//know which predicate is definitely being used here
|
||||
//Here we have multiple values possible for predicate so the original
|
||||
//Replacement should only happen when we have an actual predicate
|
||||
//String replaceRoleToActivityPredicate = getRoleToActivityPredicate(vreq);
|
||||
activityTypeQuery = QueryUtils.replaceQueryVar(activityTypeQuery, "predicate", getRoleToActivityPlaceholderName());
|
||||
|
||||
log.debug("Activity type query: " + activityTypeQuery);
|
||||
return activityTypeQuery;
|
||||
}
|
||||
|
||||
|
||||
private String getDefaultActivityTypeQuery(VitroRequest vreq) {
|
||||
String query = "PREFIX core: <" + VIVO_NS + ">\n" +
|
||||
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
|
||||
"SELECT ?existingActivityType WHERE { \n" +
|
||||
" ?role ?predicate ?existingActivity . \n" +
|
||||
" ?existingActivity vitro:mostSpecificType ?existingActivityType . \n";
|
||||
query += getFilterRoleToActivityPredicate("predicate");
|
||||
query+= "}";
|
||||
return query;
|
||||
}
|
||||
|
||||
private String getSubclassActivityTypeQuery(VitroRequest vreq) {
|
||||
String query = "PREFIX core: <" + VIVO_NS + ">\n" +
|
||||
"PREFIX rdfs: <" + VitroVocabulary.RDFS + ">\n" +
|
||||
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
|
||||
"SELECT ?existingActivityType WHERE {\n" +
|
||||
" ?role ?predicate ?existingActivity . \n" +
|
||||
" ?existingActivity vitro:mostSpecificType ?existingActivityType . \n" +
|
||||
" ?existingActivityType rdfs:subClassOf ?objectClassUri . \n";
|
||||
query += getFilterRoleToActivityPredicate("predicate");
|
||||
query+= "}";
|
||||
return query;
|
||||
}
|
||||
|
||||
private String getClassgroupActivityTypeQuery(VitroRequest vreq) {
|
||||
String query = "PREFIX core: <" + VIVO_NS + ">\n" +
|
||||
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
|
||||
"SELECT ?existingActivityType WHERE { \n" +
|
||||
" ?role ?predicate ?existingActivity . \n" +
|
||||
" ?existingActivity vitro:mostSpecificType ?existingActivityType . \n" +
|
||||
" ?existingActivityType vitro:inClassGroup ?classgroup . \n";
|
||||
query += getFilterRoleToActivityPredicate("predicate");
|
||||
query+= "}";
|
||||
return query;
|
||||
}
|
||||
|
||||
|
||||
private String getExistingRoleActivityQuery(VitroRequest vreq) {
|
||||
//If role to activity predicate is the default query, then we need to replace with a union
|
||||
//of both realizedIn and the other
|
||||
String query = "PREFIX core: <" + VIVO_NS + ">";
|
||||
|
||||
query += "SELECT ?existingRoleActivity WHERE { \n" +
|
||||
" ?role ?predicate ?existingRoleActivity . \n ";
|
||||
query += getFilterRoleToActivityPredicate("predicate");
|
||||
query += "}";
|
||||
return query;
|
||||
}
|
||||
|
||||
private String getExistingEndDateQuery(VitroRequest vreq) {
|
||||
String query = " SELECT ?existingEndDate WHERE {\n" +
|
||||
"?role <" + RoleToIntervalURI + "> ?intervalNode .\n" +
|
||||
"?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n" +
|
||||
"?intervalNode <" + IntervalToEndURI + "> ?endNode .\n" +
|
||||
"?endNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> .\n" +
|
||||
"?endNode <" + DateTimeValueURI + "> ?existingEndDate . }";
|
||||
return query;
|
||||
}
|
||||
|
||||
private String getExistingStartDateQuery(VitroRequest vreq) {
|
||||
String query = "SELECT ?existingDateStart WHERE {\n" +
|
||||
"?role <" + RoleToIntervalURI + "> ?intervalNode .\n" +
|
||||
"?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n" +
|
||||
"?intervalNode <" + IntervalToStartURI+ "> ?startNode .\n" +
|
||||
"?startNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> .\n" +
|
||||
"?startNode <" + DateTimeValueURI + "> ?existingDateStart . }";
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
private String getRoleLabelQuery(VitroRequest vreq) {
|
||||
String query = "SELECT ?existingRoleLabel WHERE { \n" +
|
||||
"?role <" + VitroVocabulary.LABEL + "> ?existingRoleLabel . }";
|
||||
return query;
|
||||
}
|
||||
|
||||
private String getActivityLabelQuery(VitroRequest vreq) {
|
||||
String query = "PREFIX core: <" + VIVO_NS + ">" +
|
||||
"PREFIX rdfs: <" + RDFS.getURI() + "> \n";
|
||||
|
||||
query += "SELECT ?existingTitle WHERE { \n" +
|
||||
"?role ?predicate ?existingActivity . \n" +
|
||||
"?existingActivity rdfs:label ?existingTitle . \n";
|
||||
query += getFilterRoleToActivityPredicate("predicate");
|
||||
query += "}";
|
||||
return query;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Set Fields and supporting methods
|
||||
* @throws Exception
|
||||
*/
|
||||
|
||||
private void setFields(EditConfigurationVTwo editConfiguration, VitroRequest vreq, String predicateUri) throws Exception {
|
||||
Map<String, FieldVTwo> fields = new HashMap<String, FieldVTwo>();
|
||||
//Multiple fields
|
||||
getActivityLabelField(editConfiguration, vreq, fields);
|
||||
getActivityLabelDisplayField(editConfiguration, vreq, fields);
|
||||
getRoleActivityTypeField(editConfiguration, vreq, fields);
|
||||
getExistingRoleActivityField(editConfiguration, vreq, fields);
|
||||
getRoleLabelField(editConfiguration, vreq, fields);
|
||||
getStartField(editConfiguration, vreq, fields);
|
||||
getEndField(editConfiguration, vreq, fields);
|
||||
//These fields are for the predicates that will be set later
|
||||
//TODO: Do these only if not using a parameter for the predicate?
|
||||
getRoleToActivityPredicateField(editConfiguration, vreq, fields);
|
||||
getActivityToRolePredicateField(editConfiguration, vreq, fields);
|
||||
editConfiguration.setFields(fields);
|
||||
}
|
||||
|
||||
//This is a literal technically?
|
||||
private void getActivityToRolePredicateField(
|
||||
EditConfigurationVTwo editConfiguration, VitroRequest vreq,
|
||||
Map<String, FieldVTwo> fields) {
|
||||
|
||||
FieldVTwo field = new FieldVTwo();
|
||||
|
||||
String fieldName = "activityToRolePredicate";
|
||||
field.setName(fieldName);
|
||||
|
||||
//get range data type uri and range language
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
field.setRangeDatatypeUri( stringDatatypeUri );
|
||||
|
||||
fields.put(field.getName(), field);
|
||||
}
|
||||
|
||||
private void getRoleToActivityPredicateField(
|
||||
EditConfigurationVTwo editConfiguration, VitroRequest vreq,
|
||||
Map<String, FieldVTwo> fields) {
|
||||
|
||||
FieldVTwo field = new FieldVTwo();
|
||||
|
||||
String fieldName = "roleToActivityPredicate";
|
||||
field.setName(fieldName);
|
||||
|
||||
//get range data type uri and range language
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
field.setRangeDatatypeUri(stringDatatypeUri);
|
||||
|
||||
fields.put(field.getName(), field);
|
||||
}
|
||||
|
||||
//Label of "right side" of role, i.e. label for role roleIn Activity
|
||||
private void getActivityLabelField(EditConfigurationVTwo editConfiguration,
|
||||
VitroRequest vreq, Map<String, FieldVTwo> fields) {
|
||||
|
||||
FieldVTwo field = new FieldVTwo();
|
||||
String fieldName = "activityLabel";
|
||||
field.setName(fieldName);
|
||||
|
||||
//get range data type uri and range language
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
field.setRangeDatatypeUri(stringDatatypeUri);
|
||||
|
||||
List<String> validators = new ArrayList<String>();
|
||||
validators.add("datatype:" + stringDatatypeUri);
|
||||
field.setValidators(validators);
|
||||
|
||||
fields.put(field.getName(), field);
|
||||
}
|
||||
|
||||
private void getActivityLabelDisplayField(EditConfigurationVTwo editConfiguration,
|
||||
VitroRequest vreq, Map<String, FieldVTwo> fields) {
|
||||
FieldVTwo field = new FieldVTwo();
|
||||
|
||||
String fieldName = "activityLabelDisplay";
|
||||
field.setName(fieldName);
|
||||
|
||||
//get range data type uri and range language
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
field.setRangeDatatypeUri(stringDatatypeUri);
|
||||
|
||||
fields.put(field.getName(), field);
|
||||
}
|
||||
|
||||
//type of "right side" of role, i.e. type of activity from role roleIn activity
|
||||
private void getRoleActivityTypeField(
|
||||
EditConfigurationVTwo editConfiguration, VitroRequest vreq,
|
||||
Map<String, FieldVTwo> fields) throws Exception {
|
||||
String fieldName = "roleActivityType";
|
||||
//get range data type uri and range language
|
||||
|
||||
FieldVTwo field = new FieldVTwo();
|
||||
field.setName(fieldName);
|
||||
|
||||
List<String> validators = new ArrayList<String>();
|
||||
if(isAddMode(vreq) || isRepairMode(vreq)) {
|
||||
validators.add("nonempty");
|
||||
}
|
||||
field.setValidators(validators);
|
||||
|
||||
field.setOptions( getRoleActivityFieldOptions(vreq) );
|
||||
|
||||
// field.setOptionsType(getRoleActivityTypeOptionsType().toString());
|
||||
// field.setObjectClassUri(getRoleActivityTypeObjectClassUri(vreq));
|
||||
//
|
||||
// HashMap<String, String> literalOptionsMap = getRoleActivityTypeLiteralOptions();
|
||||
// List<List<String>> fieldLiteralOptions = new ArrayList<List<String>>();
|
||||
// Set<String> optionUris = literalOptionsMap.keySet();
|
||||
// for(String optionUri: optionUris) {
|
||||
// List<String> uriLabelArray = new ArrayList<String>();
|
||||
// uriLabelArray.add(optionUri);
|
||||
// uriLabelArray.add(literalOptionsMap.get(optionUri));
|
||||
// fieldLiteralOptions.add(uriLabelArray);
|
||||
// }
|
||||
// field.setLiteralOptions(fieldLiteralOptions);
|
||||
|
||||
fields.put(field.getName(), field);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
//Assuming URI for activity for role?
|
||||
private void getExistingRoleActivityField(EditConfigurationVTwo editConfiguration,
|
||||
VitroRequest vreq, Map<String, FieldVTwo> fields) {
|
||||
String fieldName = "existingRoleActivity";
|
||||
|
||||
FieldVTwo field = new FieldVTwo();
|
||||
field.setName(fieldName);
|
||||
|
||||
fields.put(field.getName(), field);
|
||||
}
|
||||
|
||||
private void getRoleLabelField(EditConfigurationVTwo editConfiguration,
|
||||
VitroRequest vreq, Map<String, FieldVTwo> fields) {
|
||||
String fieldName = "roleLabel";
|
||||
|
||||
FieldVTwo field = new FieldVTwo();
|
||||
field.setName(fieldName);
|
||||
|
||||
String stringDatatypeUri = XSD.xstring.toString();
|
||||
field.setRangeDatatypeUri(stringDatatypeUri);
|
||||
|
||||
List<String> validators = new ArrayList<String>();
|
||||
validators.add("datatype:" + stringDatatypeUri);
|
||||
field.setValidators(validators);
|
||||
|
||||
fields.put(field.getName(), field);
|
||||
}
|
||||
|
||||
private void getStartField(EditConfigurationVTwo editConfiguration,
|
||||
VitroRequest vreq, Map<String, FieldVTwo> fields) {
|
||||
FieldVTwo field = new FieldVTwo();
|
||||
|
||||
String fieldName = "startField";
|
||||
field.setName(fieldName);
|
||||
|
||||
field.setEditElement(
|
||||
new DateTimeWithPrecisionVTwo(field,
|
||||
getStartDatePrecision(),
|
||||
VitroVocabulary.Precision.NONE.uri()));
|
||||
|
||||
fields.put(field.getName(), field);
|
||||
}
|
||||
|
||||
private void getEndField(EditConfigurationVTwo editConfiguration,
|
||||
VitroRequest vreq, Map<String, FieldVTwo> fields) {
|
||||
FieldVTwo field = new FieldVTwo();
|
||||
|
||||
String fieldName = "endField";
|
||||
field.setName(fieldName);
|
||||
|
||||
field.setEditElement(
|
||||
new DateTimeWithPrecisionVTwo(field,
|
||||
getEndDatePrecision(),
|
||||
VitroVocabulary.Precision.NONE.uri()));
|
||||
|
||||
fields.put(field.getName(), field);
|
||||
}
|
||||
|
||||
private void addPreprocessors(EditConfigurationVTwo editConfiguration, WebappDaoFactory wadf) {
|
||||
//Add preprocessor that will replace the role to activity predicate and inverse
|
||||
//with correct properties based on the activity type
|
||||
editConfiguration.addEditSubmissionPreprocessor(
|
||||
new RoleToActivityPredicatePreprocessor(editConfiguration, wadf));
|
||||
|
||||
}
|
||||
|
||||
//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
|
||||
//placeholder value by default
|
||||
public String getRoleToActivityPredicate(VitroRequest vreq) {
|
||||
//TODO: <uri> and ?placeholder are incompatible
|
||||
return getRoleToActivityPlaceholder();
|
||||
}
|
||||
//Ensure when overwritten that this includes the <> b/c otherwise the query won't work
|
||||
|
||||
//Some values will have a default value
|
||||
|
||||
public List<String> getPossibleRoleToActivityPredicates() {
|
||||
return ModelUtils.getPossiblePropertiesForRole();
|
||||
}
|
||||
|
||||
public List<String> getPossibleActivityToRolePredicates() {
|
||||
return ModelUtils.getPossibleInversePropertiesForRole();
|
||||
}
|
||||
|
||||
/* Methods that check edit mode */
|
||||
public EditMode getEditMode(VitroRequest vreq) {
|
||||
List<String> roleToGrantPredicates = getPossibleRoleToActivityPredicates();
|
||||
return EditModeUtils.getEditMode(vreq, roleToGrantPredicates);
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
/* URIS for various predicates */
|
||||
private final String VIVO_NS="http://vivoweb.org/ontology/core#";
|
||||
|
||||
private final String RoleToIntervalURI = VIVO_NS + "dateTimeInterval";
|
||||
private final String IntervalTypeURI = VIVO_NS + "DateTimeInterval";
|
||||
private final String IntervalToStartURI = VIVO_NS + "start";
|
||||
private final String IntervalToEndURI = VIVO_NS + "end";
|
||||
private final String StartYearPredURI = VIVO_NS + "startYear";
|
||||
private final String EndYearPredURI = VIVO_NS + "endYear";
|
||||
private final String DateTimeValueTypeURI=VIVO_NS + "DateTimeValue";
|
||||
private final String DateTimePrecisionURI=VIVO_NS + "dateTimePrecision";
|
||||
private final String DateTimeValueURI = VIVO_NS + "dateTime";
|
||||
|
||||
//Form specific data
|
||||
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
|
||||
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
|
||||
formSpecificData.put("editMode", getEditMode(vreq).name().toLowerCase());
|
||||
//Fields that will need select lists generated
|
||||
//Store field names
|
||||
List<String> objectSelect = new ArrayList<String>();
|
||||
objectSelect.add("roleActivityType");
|
||||
//TODO: Check if this is the proper way to do this?
|
||||
formSpecificData.put("objectSelect", objectSelect);
|
||||
//Also put in show role label field
|
||||
formSpecificData.put("showRoleLabelField", isShowRoleLabelField());
|
||||
//Put in the fact that we require field
|
||||
editConfiguration.setFormSpecificData(formSpecificData);
|
||||
}
|
||||
|
||||
public String getFilterRoleToActivityPredicate(String predicateVar) {
|
||||
String addFilter = "FILTER (";
|
||||
List<String> predicates = getPossibleRoleToActivityPredicates();
|
||||
List<String> filterPortions = new ArrayList<String>();
|
||||
for(String p: predicates) {
|
||||
filterPortions.add("(?" + predicateVar + "=<" + p + ">)");
|
||||
}
|
||||
addFilter += StringUtils.join(filterPortions, " || ");
|
||||
addFilter += ")";
|
||||
return addFilter;
|
||||
}
|
||||
|
||||
private String getRoleToActivityPlaceholder() {
|
||||
return "?" + getRoleToActivityPlaceholderName();
|
||||
}
|
||||
|
||||
private String getRoleToActivityPlaceholderName() {
|
||||
return "roleToActivityPredicate";
|
||||
}
|
||||
|
||||
|
||||
private String getActivityToRolePlaceholder() {
|
||||
return "?activityToRolePredicate";
|
||||
}
|
||||
|
||||
//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
|
||||
};
|
||||
|
||||
private final String N3_PREFIX = "@prefix core: <http://vivoweb.org/ontology/core#> .";
|
||||
|
||||
protected String getStartDatePrecision() {
|
||||
String precision = VitroVocabulary.Precision.YEAR.uri();
|
||||
return precision;
|
||||
}
|
||||
|
||||
protected String getEndDatePrecision() {
|
||||
String precision = VitroVocabulary.Precision.YEAR.uri();
|
||||
return precision;
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,98 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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 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() {
|
||||
return "http://purl.obolibrary.org/obo/ERO_0000012";
|
||||
}
|
||||
|
||||
/** Service Provider 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://vivoweb.org/ontology/core#AcademicDepartment","Academic Department",
|
||||
"http://vivoweb.org/ontology/core#Association","Association",
|
||||
"http://vivoweb.org/ontology/core#Center","Center",
|
||||
"http://vivoweb.org/ontology/core#ClinicalOrganization","Clinical Organization",
|
||||
"http://vivoweb.org/ontology/core#College","College",
|
||||
"http://vivoweb.org/ontology/core#Committee","Committee",
|
||||
"http://vivoweb.org/ontology/core#Company","Company",
|
||||
"http://vivoweb.org/ontology/core#Competition", "Competition",
|
||||
"http://purl.org/ontology/bibo/Conference", "Conference",
|
||||
"http://vivoweb.org/ontology/core#ConferenceSeries", "Conference Series",
|
||||
"http://vivoweb.org/ontology/core#Consortium","Consortium",
|
||||
"http://vivoweb.org/ontology/core#CoreLaboratory","Core Laboratory",
|
||||
"http://vivoweb.org/ontology/core#Course", "Course",
|
||||
"http://vivoweb.org/ontology/core#Department","Department",
|
||||
"http://vivoweb.org/ontology/core#Division","Division",
|
||||
"http://purl.org/NET/c4dm/event.owl#Event","Event",
|
||||
"http://vivoweb.org/ontology/core#EventSeries", "Event Series",
|
||||
"http://vivoweb.org/ontology/core#Exhibit", "Exhibit",
|
||||
"http://vivoweb.org/ontology/core#ExtensionUnit","Extension Unit",
|
||||
"http://vivoweb.org/ontology/core#Foundation","Foundation",
|
||||
"http://vivoweb.org/ontology/core#FundingOrganization","Funding Organization",
|
||||
"http://vivoweb.org/ontology/core#GovernmentAgency","Government Agency",
|
||||
"http://xmlns.com/foaf/0.1/Group","Group",
|
||||
"http://purl.org/ontology/bibo/Hearing", "Hearing",
|
||||
"http://vivoweb.org/ontology/core#Hospital","Hospital",
|
||||
"http://vivoweb.org/ontology/core#Institute","Institute",
|
||||
"http://purl.org/ontology/bibo/Interview", "Interview",
|
||||
"http://vivoweb.org/ontology/core#InvitedTalk", "Invited Talk",
|
||||
"http://vivoweb.org/ontology/core#Laboratory","Laboratory",
|
||||
"http://vivoweb.org/ontology/core#Library","Library",
|
||||
"http://purl.obolibrary.org/obo/OBI_0000835","Manufacturer",
|
||||
"http://vivoweb.org/ontology/core#Meeting", "Meeting",
|
||||
"http://vivoweb.org/ontology/core#Museum","Museum",
|
||||
"http://xmlns.com/foaf/0.1/Organization","Organization",
|
||||
"http://purl.org/ontology/bibo/Performance", "Performance",
|
||||
"http://vivoweb.org/ontology/core#Presentation", "Presentation",
|
||||
"http://vivoweb.org/ontology/core#PrivateCompany","Private Company",
|
||||
"http://vivoweb.org/ontology/core#Program","Program",
|
||||
"http://vivoweb.org/ontology/core#Publisher","Publisher",
|
||||
"http://vivoweb.org/ontology/core#ResearchOrganization","Research Organization",
|
||||
"http://vivoweb.org/ontology/core#School","School",
|
||||
"http://vivoweb.org/ontology/core#SeminarSeries", "Seminar Series",
|
||||
"http://vivoweb.org/ontology/core#Team","Team",
|
||||
"http://vivoweb.org/ontology/core#ServiceProvidingLaboratory","Service Providing Lab",
|
||||
"http://vivoweb.org/ontology/core#StudentOrganization","Student Organization",
|
||||
"http://purl.obolibrary.org/obo/ERO_0000565","Technology Transfer Office",
|
||||
"http://vivoweb.org/ontology/core#University","University",
|
||||
"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,
|
||||
* 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;
|
||||
}
|
||||
*/
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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;
|
||||
}
|
||||
*/
|
||||
}
|
|
@ -0,0 +1,311 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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 com.hp.hpl.jena.rdf.model.Literal;
|
||||
import com.hp.hpl.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");
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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 );
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,547 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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.lang.StringUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.ontology.OntModel;
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
|
||||
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.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.preprocessors.DefaultAddMissingIndividualFormModelPreprocessor;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
|
||||
|
||||
/**
|
||||
* Generates the edit configuration for a default property form.
|
||||
*
|
||||
*/
|
||||
public class DefaultAddMissingIndividualFormGenerator implements EditConfigurationGenerator {
|
||||
|
||||
private Log log = LogFactory.getLog(DefaultAddMissingIndividualFormGenerator.class);
|
||||
private boolean isObjectPropForm = false;
|
||||
private String subjectUri = null;
|
||||
private String predicateUri = null;
|
||||
private String objectUri = null;
|
||||
|
||||
private String template = "defaultAddMissingIndividualForm.ftl";
|
||||
private static String createCommand = "create";
|
||||
private static String objectVarName = "newIndividual";
|
||||
private static HashMap<String,String> defaultsForXSDtypes ;
|
||||
static {
|
||||
defaultsForXSDtypes = new HashMap<String,String>();
|
||||
//defaultsForXSDtypes.put("http://www.w3.org/2001/XMLSchema#dateTime","2001-01-01T12:00:00");
|
||||
defaultsForXSDtypes.put("http://www.w3.org/2001/XMLSchema#dateTime","#Unparseable datetime defaults to now");
|
||||
}
|
||||
|
||||
//Method which checks whether this particular generator should be employed
|
||||
public static boolean isCreateNewIndividual(VitroRequest vreq, HttpSession session) {
|
||||
String command = vreq.getParameter("cmd");
|
||||
String predicateUri = EditConfigurationUtils.getPredicateUri(vreq);
|
||||
//This method also looks at domain and range uris and so is different than just getting the
|
||||
//object property based on predicate uri alone
|
||||
ObjectProperty objProp = EditConfigurationUtils.getObjectPropertyForPredicate(vreq,
|
||||
predicateUri);
|
||||
if(objProp != null) {
|
||||
return(objProp.getOfferCreateNewOption() &&
|
||||
(
|
||||
(command != null && command.equals(createCommand)) ||
|
||||
objProp.getSelectFromExisting() == false
|
||||
)
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@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));
|
||||
|
||||
|
||||
editConfiguration.setNewResources(this.generateNewResources(vreq));
|
||||
//In scope
|
||||
this.setUrisAndLiteralsInScope(editConfiguration);
|
||||
|
||||
//on Form
|
||||
this.setUrisAndLiteralsOnForm(editConfiguration, vreq);
|
||||
|
||||
editConfiguration.setFilesOnForm(new ArrayList<String>());
|
||||
|
||||
//Sparql queries
|
||||
this.setSparqlQueries(editConfiguration);
|
||||
|
||||
//set fields
|
||||
setFields(editConfiguration, vreq, EditConfigurationUtils.getPredicateUri(vreq));
|
||||
|
||||
//form specific data
|
||||
addFormSpecificData(editConfiguration, vreq);
|
||||
|
||||
//add preprocesoors
|
||||
addPreprocessors(vreq, editConfiguration);
|
||||
|
||||
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
|
||||
//default obj property form.populateTemplate or some such method
|
||||
//Select from existing also set within template itself
|
||||
setTemplate(editConfiguration, vreq);
|
||||
|
||||
editConfiguration.addValidator(new AntiXssValidation());
|
||||
|
||||
//edit key now set in the edit request dispatch controller
|
||||
return editConfiguration;
|
||||
}
|
||||
|
||||
private Map<String, String> generateNewResources(VitroRequest vreq) {
|
||||
HashMap<String, String> newResources = new HashMap<String, String>();
|
||||
//Null triggers default namespace
|
||||
newResources.put(objectVarName, null);
|
||||
newResources.put("newVcardInd", null);
|
||||
newResources.put("newVcardName", null);
|
||||
return newResources;
|
||||
}
|
||||
//Need to replace edit key
|
||||
//TODO:Check if we need to recheck forward to create new or assume that is the case since
|
||||
//we're using this generator
|
||||
//In this case we always set a new edit key as the original jsp checked 'isForwardToCreateNew'
|
||||
//which condition would require that an entirely new edit key be created
|
||||
private void setEditKey(HttpSession session, EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
|
||||
String editKey = EditConfigurationVTwo.newEditKey(session);
|
||||
editConfiguration.setEditKey(editKey);
|
||||
}
|
||||
|
||||
private void setTemplate(EditConfigurationVTwo editConfiguration,
|
||||
VitroRequest vreq) {
|
||||
editConfiguration.setTemplate(template);
|
||||
|
||||
}
|
||||
|
||||
//Initialize setup: process parameters
|
||||
//Doesn't look like we need to set up separate processing for data property form
|
||||
private void initProcessParameters(VitroRequest vreq, HttpSession session, EditConfigurationVTwo editConfiguration) {
|
||||
String formUrl = EditConfigurationUtils.getFormUrlWithoutContext(vreq);
|
||||
|
||||
subjectUri = EditConfigurationUtils.getSubjectUri(vreq);
|
||||
predicateUri = EditConfigurationUtils.getPredicateUri(vreq);
|
||||
|
||||
editConfiguration.setFormUrl(formUrl);
|
||||
|
||||
|
||||
editConfiguration.setUrlPatternToReturnTo("/individual");
|
||||
|
||||
editConfiguration.setVarNameForSubject("subject");
|
||||
editConfiguration.setSubjectUri(subjectUri);
|
||||
editConfiguration.setEntityToReturnTo(subjectUri);
|
||||
editConfiguration.setVarNameForPredicate("predicate");
|
||||
editConfiguration.setPredicateUri(predicateUri);
|
||||
|
||||
|
||||
//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
|
||||
//"object" : [ "newIndividual" , "${objectUriJson}" , "URI"],
|
||||
if(EditConfigurationUtils.isObjectProperty(predicateUri, vreq)) {
|
||||
//not concerned about remainder, can move into default obj prop form if required
|
||||
this.isObjectPropForm = true;
|
||||
this.initObjectParameters(vreq);
|
||||
this.processObjectPropForm(vreq, editConfiguration);
|
||||
} else {
|
||||
log.error("Add missing individual called for a data property instead of object property");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
private void initObjectParameters(VitroRequest vreq) {
|
||||
//in case of object property
|
||||
String thisObjectUri = EditConfigurationUtils.getObjectUri(vreq);
|
||||
if(thisObjectUri != null && !thisObjectUri.isEmpty()) {
|
||||
objectUri = EditConfigurationUtils.getObjectUri(vreq);
|
||||
}
|
||||
//otherwise object uri will stay null - since don't want to set it to empty string
|
||||
}
|
||||
|
||||
//this particular form uses a different var name for object "newIndividual"
|
||||
private void processObjectPropForm(VitroRequest vreq, EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.setVarNameForObject(objectVarName);
|
||||
//If is replace with new, set Object resource to null
|
||||
if(isReplaceWithNew(vreq)) {
|
||||
editConfiguration.setObject(null);
|
||||
} else {
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
|
||||
//Get N3 required
|
||||
//Handles both object and data property
|
||||
private List<String> generateN3Required(VitroRequest vreq) {
|
||||
List<String> n3ForEdit = new ArrayList<String>();
|
||||
n3ForEdit.add(getN3PrefixesAsString() + "\n" + getN3ForName());
|
||||
n3ForEdit.add("?subject ?predicate ?" + objectVarName + " .");
|
||||
n3ForEdit.add(getN3PrefixesAsString() + "\n" + "?" + objectVarName + " rdf:type <" + getRangeClassUri(vreq) + "> . ");
|
||||
return n3ForEdit;
|
||||
}
|
||||
|
||||
private List<String> getN3Prefixes() {
|
||||
List<String> prefixStrings = new ArrayList<String>();
|
||||
prefixStrings.add("@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .");
|
||||
prefixStrings.add("@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .");
|
||||
prefixStrings.add("@prefix vcard:<http://www.w3.org/2006/vcard/ns#> .");
|
||||
return prefixStrings;
|
||||
}
|
||||
|
||||
private String getN3PrefixesAsString() {
|
||||
String prefixes = StringUtils.join(getN3Prefixes(), "\n");
|
||||
return prefixes;
|
||||
}
|
||||
|
||||
private String getN3ForName() {
|
||||
return "?" + objectVarName + " rdfs:label ?label .";
|
||||
}
|
||||
|
||||
private List<String> generateN3Optional(VitroRequest vreq) {
|
||||
//flag uri and asserted types need to be added here
|
||||
List<String> n3Optional = new ArrayList<String>();
|
||||
n3Optional.add("?" + objectVarName + " ?inverseProp ?subject .");
|
||||
//asserted types string buffer is empty in the original jsp
|
||||
//TODO: Review original comments in jsp to see what could go here
|
||||
//n3Optional.add(getN3AssertedTypes(vreq));
|
||||
n3Optional.add(getN3PrefixesAsString() + "\n" + "?" + objectVarName + " rdf:type <" + getFlagURI(vreq) + "> . ");
|
||||
n3Optional.add(getN3PrefixesAsString()
|
||||
+ "?" + objectVarName + "<http://purl.obolibrary.org/obo/ARG_2000028> ?newVcardInd . \n"
|
||||
+ " ?newVcardInd <http://purl.obolibrary.org/obo/ARG_2000029> ?" + objectVarName + " . \n"
|
||||
+ " ?newVcardInd a vcard:Individual . \n"
|
||||
+ " ?newVcardInd vcard:hasName ?newVcardName . \n"
|
||||
+ " ?newVcardName a vcard:Name . \n"
|
||||
+ " ?newVcardName vcard:givenName ?firstName . \n"
|
||||
+ " ?newVcardName vcard:familyName ?lastName . \n");
|
||||
n3Optional.add(getN3PrefixesAsString()
|
||||
+ "?" + objectVarName + "<http://purl.obolibrary.org/obo/ARG_2000028> ?newVcardInd . \n"
|
||||
+ " ?newVcardInd a vcard:Individual . \n"
|
||||
+ " ?newVcardInd vcard:hasName ?newVcardName . \n"
|
||||
+ " ?newVcardName a vcard:Name . \n"
|
||||
+ " ?newVcardName <http://vivoweb.org/ontology/core#middleName> ?middleName .");
|
||||
return n3Optional;
|
||||
|
||||
}
|
||||
|
||||
private String getFlagURI(VitroRequest vreq) {
|
||||
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
|
||||
String flagURI = wdf.getVClassDao().getTopConcept().getURI();
|
||||
return flagURI;
|
||||
}
|
||||
private String getN3AssertedTypes(VitroRequest vreq) {
|
||||
return null;
|
||||
}
|
||||
//Set queries
|
||||
private String retrieveQueryForInverse () {
|
||||
String queryForInverse = "PREFIX owl: <http://www.w3.org/2002/07/owl#>"
|
||||
+ " SELECT ?inverse_property "
|
||||
+ " WHERE { ?inverse_property owl:inverseOf ?predicate } ";
|
||||
return queryForInverse;
|
||||
}
|
||||
|
||||
private void setUrisAndLiteralsInScope(EditConfigurationVTwo editConfiguration) {
|
||||
HashMap<String, List<String>> urisInScope = new HashMap<String, List<String>>();
|
||||
//Add subject uri and predicate turo to uris in scope
|
||||
urisInScope.put(editConfiguration.getVarNameForSubject(),
|
||||
Arrays.asList(new String[]{editConfiguration.getSubjectUri()}));
|
||||
urisInScope.put(editConfiguration.getVarNameForPredicate(),
|
||||
Arrays.asList(new String[]{editConfiguration.getPredicateUri()}));
|
||||
editConfiguration.setUrisInScope(urisInScope);
|
||||
editConfiguration.setLiteralsInScope(new HashMap<String, List<Literal>>());
|
||||
}
|
||||
|
||||
//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>();
|
||||
literalsOnForm.add("label");
|
||||
literalsOnForm.add("firstName");
|
||||
literalsOnForm.add("middleName");
|
||||
literalsOnForm.add("lastName");
|
||||
editConfiguration.setUrisOnform(urisOnForm);
|
||||
editConfiguration.setLiteralsOnForm(literalsOnForm);
|
||||
}
|
||||
|
||||
|
||||
//This is for various items
|
||||
private void setSparqlQueries(EditConfigurationVTwo editConfiguration) {
|
||||
//Sparql queries defining retrieval of literals etc.
|
||||
editConfiguration.setSparqlForAdditionalLiteralsInScope(new HashMap<String, String>());
|
||||
|
||||
Map<String, String> urisInScope = new HashMap<String, String>();
|
||||
urisInScope.put("inverseProp", this.retrieveQueryForInverse());
|
||||
editConfiguration.setSparqlForAdditionalUrisInScope(urisInScope);
|
||||
|
||||
editConfiguration.setSparqlForExistingLiterals(generateSparqlForExistingLiterals());
|
||||
editConfiguration.setSparqlForExistingUris(generateSparqlForExistingUris());
|
||||
}
|
||||
|
||||
|
||||
//Sparql queries
|
||||
|
||||
|
||||
private HashMap<String, String> generateSparqlForExistingUris() {
|
||||
HashMap<String, String> map = new HashMap<String, String>();
|
||||
return map;
|
||||
}
|
||||
|
||||
private HashMap<String, String> generateSparqlForExistingLiterals() {
|
||||
HashMap<String, String> map = new HashMap<String, String>();
|
||||
String query = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> ";
|
||||
query += "SELECT ?existingName WHERE { ?" + objectVarName + " rdfs:label ?existingName . }";
|
||||
map.put("name", query);
|
||||
return map;
|
||||
}
|
||||
|
||||
|
||||
private 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");
|
||||
|
||||
FieldVTwo firstNameField = new FieldVTwo();
|
||||
firstNameField.setName("firstName");
|
||||
|
||||
FieldVTwo middleNameField = new FieldVTwo();
|
||||
middleNameField.setName("middleName");
|
||||
|
||||
FieldVTwo lastNameField = new FieldVTwo();
|
||||
lastNameField.setName("lastName");
|
||||
|
||||
List<String> validators = new ArrayList<String>();
|
||||
validators.add("nonempty");
|
||||
if(!isPersonType(vreq)) {
|
||||
labelField.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);
|
||||
}
|
||||
|
||||
private String getRangeClassUri(VitroRequest vreq) {
|
||||
Individual subject = EditConfigurationUtils.getSubjectIndividual(vreq);
|
||||
ObjectProperty prop = EditConfigurationUtils.getObjectProperty(vreq);
|
||||
|
||||
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
|
||||
if( prop.getRangeVClassURI() == null ) {
|
||||
// If property has no explicit range, we will use e.g. owl:Thing.
|
||||
// Typically an allValuesFrom restriction will come into play later.
|
||||
VClass top = wdf.getVClassDao().getTopConcept();
|
||||
prop.setRangeVClassURI(top.getURI());
|
||||
}
|
||||
|
||||
VClass rangeClass = null;
|
||||
String typeOfNew = getTypeOfNew(vreq);
|
||||
if(typeOfNew != null )
|
||||
rangeClass = wdf.getVClassDao().getVClassByURI( typeOfNew );
|
||||
if( rangeClass == null ){
|
||||
rangeClass = wdf.getVClassDao().getVClassByURI(prop.getRangeVClassURI());
|
||||
if( rangeClass == null ) throw new Error ("Cannot find class for range for property. Looking for " + prop.getRangeVClassURI() );
|
||||
}
|
||||
return rangeClass.getURI();
|
||||
}
|
||||
|
||||
private void prepareForUpdate(VitroRequest vreq, HttpSession session, EditConfigurationVTwo editConfiguration) {
|
||||
//Here, retrieve model from
|
||||
OntModel model = ModelAccess.on(session.getServletContext()).getOntModel();
|
||||
//if object property
|
||||
if(EditConfigurationUtils.isObjectProperty(EditConfigurationUtils.getPredicateUri(vreq), vreq)){
|
||||
Individual objectIndividual = EditConfigurationUtils.getObjectIndividual(vreq);
|
||||
if(!isReplaceWithNew(vreq) &&
|
||||
(isForwardToCreateButEdit(vreq) ||
|
||||
objectIndividual != null)
|
||||
) {
|
||||
editConfiguration.prepareForObjPropUpdate(model);
|
||||
} else {
|
||||
//new object to be created
|
||||
editConfiguration.prepareForNonUpdate( model );
|
||||
}
|
||||
} else {
|
||||
log.error("Data property not object property so update can't be done correctly");
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private void addPreprocessors(VitroRequest vreq, EditConfigurationVTwo editConfiguration) {
|
||||
if(isReplaceWithNew(vreq)) {
|
||||
//String subjectUri = EditConfigurationUtils.getSubjectUri(vreq);
|
||||
//String predicateUri = EditConfigurationUtils.getPredicateUri(vreq);
|
||||
//String objectUri = EditConfigurationUtils.getObjectUri(vreq);
|
||||
editConfiguration.addModelChangePreprocessor(
|
||||
new DefaultAddMissingIndividualFormModelPreprocessor(
|
||||
subjectUri, predicateUri, objectUri));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
//Command processing
|
||||
private boolean isTypeOfNew(VitroRequest vreq) {
|
||||
String typeOfNew = getTypeOfNew(vreq);
|
||||
return (typeOfNew != null && !typeOfNew.isEmpty());
|
||||
}
|
||||
|
||||
private String getTypeOfNew(VitroRequest vreq) {
|
||||
return vreq.getParameter("typeOfNew");
|
||||
}
|
||||
// The default object proepty form offers the option to create a new item
|
||||
// instead of selecting from existing individuals in the system.
|
||||
// This is where the request to create a new indivdiual is handled.
|
||||
//We don't really need this again b/c we wouldn't be using this generator unless we want
|
||||
//to create a new individual so commenting out for now
|
||||
/*
|
||||
private boolean isForwardToCreateNew(VitroRequest vreq) {
|
||||
String command = vreq.getParameter("cmd");
|
||||
ObjectProperty objectProp = EditConfigurationUtils.getObjectProperty(vreq);
|
||||
if(hasCustomForm(objectProp)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean isForwardToCreateNew =
|
||||
( objectProp != null && objectProp.getOfferCreateNewOption() )
|
||||
&& ( objectProp.getSelectFromExisting() == false
|
||||
|| "create".equals(command));
|
||||
|
||||
return isForwardToCreateNew;
|
||||
|
||||
}
|
||||
|
||||
private boolean hasCustomForm(ObjectProperty objectProp) {
|
||||
return( objectProp != null &&
|
||||
objectProp.getCustomEntryForm() != null &&
|
||||
!objectProp.getCustomEntryForm().isEmpty());
|
||||
|
||||
}*/
|
||||
|
||||
private boolean isReplaceWithNew(VitroRequest vreq) {
|
||||
ObjectProperty objectProp = EditConfigurationUtils.getObjectProperty(vreq);
|
||||
boolean isEditOfExistingStmt = isEditOfExistingStatement(vreq);
|
||||
String command = vreq.getParameter("cmd");
|
||||
return (isEditOfExistingStmt
|
||||
&& "create".equals(command))
|
||||
&& (objectProp != null)
|
||||
&& (objectProp.getOfferCreateNewOption() == true);
|
||||
}
|
||||
|
||||
private boolean isForwardToCreateButEdit(VitroRequest vreq) {
|
||||
boolean isEditOfExistingStmt = isEditOfExistingStatement(vreq);
|
||||
ObjectProperty objectProp = EditConfigurationUtils.getObjectProperty(vreq);
|
||||
String command = vreq.getParameter("cmd");
|
||||
return (isEditOfExistingStmt
|
||||
&& (! "create".equals(command))
|
||||
&& (objectProp != null)
|
||||
&& (objectProp.getOfferCreateNewOption() == true)
|
||||
&& (objectProp.getSelectFromExisting() == false)
|
||||
);
|
||||
}
|
||||
|
||||
//Form specific data
|
||||
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
|
||||
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
|
||||
formSpecificData.put("typeName", getTypeName(vreq));
|
||||
//Put in whether or not person type
|
||||
if(isPersonType(vreq)) {
|
||||
//Doing this b/c unsure how freemarker will handle boolean value from JAVA
|
||||
formSpecificData.put("isPersonType", "true");
|
||||
} else {
|
||||
formSpecificData.put("isPersonType", "false");
|
||||
|
||||
}
|
||||
editConfiguration.setFormSpecificData(formSpecificData);
|
||||
}
|
||||
|
||||
private String getTypeName(VitroRequest vreq) {
|
||||
String typeOfNew = getTypeOfNew(vreq);
|
||||
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;
|
||||
String foafPersonType = getFOAFPersonClassURI();
|
||||
String typeOfNew = getTypeOfNew(vreq);
|
||||
List<String> superTypes = wdf.getVClassDao().getAllSuperClassURIs(typeOfNew);
|
||||
//add the actual type as well so we can add that for the list to be checked
|
||||
superTypes.add(typeOfNew);
|
||||
if( superTypes != null ){
|
||||
for( String typeUri : superTypes){
|
||||
if( foafPersonType.equals(typeUri)) {
|
||||
isPersonType = Boolean.TRUE;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return isPersonType;
|
||||
}
|
||||
|
||||
//Is edit of existing statement only applicable to object properties
|
||||
private boolean isEditOfExistingStatement(VitroRequest vreq) {
|
||||
//TODO: Check if also applicable to data property, currently returning false
|
||||
if(EditConfigurationUtils.isDataProperty(EditConfigurationUtils.getPredicateUri(vreq), vreq)) {
|
||||
return false;
|
||||
}
|
||||
Individual object = EditConfigurationUtils.getObjectIndividual(vreq);
|
||||
return (object != null);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,127 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.AutocompleteRequiredInputValidator;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeIntervalValidationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ChildVClassesWithParent;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ConstantFieldOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaVClassOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
|
||||
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);
|
||||
|
||||
conf.setTemplate("grantAdministeredBy.ftl");
|
||||
|
||||
conf.setVarNameForSubject("grant");
|
||||
conf.setVarNameForPredicate("predicate");
|
||||
conf.setVarNameForObject("adminRole");
|
||||
|
||||
conf.setN3Required( Arrays.asList( n3ForNewAdminRole) );
|
||||
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.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").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("orgLabelDisplay").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()))
|
||||
);
|
||||
|
||||
conf.addValidator(new AntiXssValidation());
|
||||
conf.addValidator(new AutocompleteRequiredInputValidator("existingOrganization", "orgLabel"));
|
||||
|
||||
// addFormSpecificData(conf, vreq);
|
||||
prepare(vreq, conf);
|
||||
return conf;
|
||||
}
|
||||
|
||||
/* N3 assertions */
|
||||
|
||||
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 <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" +
|
||||
"?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 =
|
||||
"PREFIX vivo: <http://vivoweb.org/ontology/core#> \n" +
|
||||
"SELECT ?existingOrganization WHERE { \n" +
|
||||
" ?adminRole <http://purl.obolibrary.org/obo/RO_0000052> ?existingOrganization . \n" +
|
||||
" ?existingOrganization a <http://xmlns.com/foaf/0.1/Organization> . \n" +
|
||||
"}";
|
||||
|
||||
final static String orgLabelQuery =
|
||||
"PREFIX vivo: <http://vivoweb.org/ontology/core#> \n" +
|
||||
"SELECT ?existingOrganizationLabel WHERE { \n" +
|
||||
" ?adminRole <http://purl.obolibrary.org/obo/RO_0000052> ?existingOrganization . \n" +
|
||||
" ?existingOrganization a <http://xmlns.com/foaf/0.1/Organization> . \n" +
|
||||
" ?existingOrganization <" + label + "> ?existingOrganizationLabel . \n" +
|
||||
"}";
|
||||
|
||||
}
|
|
@ -0,0 +1,190 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
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 javax.servlet.http.HttpSession;
|
||||
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.FirstAndLastNameValidator;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeIntervalValidationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ChildVClassesOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ChildVClassesWithParent;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaVClassOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
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{
|
||||
|
||||
// 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);
|
||||
|
||||
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
|
||||
//literals in scope: none
|
||||
|
||||
conf.setUrisOnform( Arrays.asList( "existingPerson", "roleType"));
|
||||
conf.setLiteralsOnForm( Arrays.asList("personLabel", "personLabelDisplay", "firstName", "lastName"));
|
||||
|
||||
conf.addSparqlForExistingLiteral("personLabel", personLabelQuery);
|
||||
|
||||
conf.addSparqlForExistingUris("existingPerson", existingPersonQuery);
|
||||
conf.addSparqlForExistingUris("roleType", roleTypeQuery);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("existingPerson")
|
||||
//options will be added in browser by auto complete JS
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("personLabel").
|
||||
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() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("lastName").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("roleType").
|
||||
setValidators( list("nonempty") ).
|
||||
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 =
|
||||
"@prefix core: <"+ vivoCore +"> .\n" +
|
||||
"@prefix rdfs: <"+ rdfs +"> . \n"+
|
||||
"?subject core:relates ?theRole .\n" +
|
||||
"?theRole core:relatedBy ?subject . \n" ;
|
||||
|
||||
final static String roleTypeAssertion =
|
||||
"?theRole a ?roleType .";
|
||||
|
||||
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" +
|
||||
"?subject core:relates ?newPerson . \n" +
|
||||
"?newPerson core:relatedBy ?subject . \n" +
|
||||
"?newPerson a <http://xmlns.com/foaf/0.1/Person> . \n" +
|
||||
"?newPerson <"+ label +"> ?personLabel . ";
|
||||
|
||||
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 =
|
||||
"@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 vcard:hasName ?vcardName . \n" +
|
||||
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
|
||||
"?vcardName vcard:givenName ?firstName .";
|
||||
|
||||
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 vcard:hasName ?vcardName . \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 =
|
||||
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
|
||||
"SELECT ?roleType WHERE { \n" +
|
||||
" ?theRole vitro:mostSpecificType ?roleType . }";
|
||||
|
||||
final static String existingPersonQuery =
|
||||
"PREFIX rdfs: <"+ rdfs +"> \n"+
|
||||
"SELECT ?existingPerson WHERE {\n"+
|
||||
"?theRole <http://purl.obolibrary.org/obo/RO_0000052> ?existingPerson . \n" +
|
||||
"?existingPerson <http://purl.obolibrary.org/obo/RO_0000053> ?theRole . \n" +
|
||||
"?existingPerson a <http://xmlns.com/foaf/0.1/Person> . \n " +
|
||||
" }";
|
||||
|
||||
final static String personLabelQuery =
|
||||
"PREFIX rdfs: <"+ rdfs +"> \n"+
|
||||
"SELECT ?existingPersonLabel WHERE {\n"+
|
||||
"?theRole <http://purl.obolibrary.org/obo/RO_0000052> ?existingPerson . \n" +
|
||||
"?existingPerson <http://purl.obolibrary.org/obo/RO_0000053> ?theRole .\n"+
|
||||
"?existingPerson <"+ label +"> ?existingPersonLabel .\n"+
|
||||
"?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");
|
||||
return EditModeUtils.getEditMode(vreq, predicates);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,561 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import static edu.cornell.mannlib.vitro.webapp.auth.requestedAction.RequestedAction.SOME_LITERAL;
|
||||
import static edu.cornell.mannlib.vitro.webapp.auth.requestedAction.RequestedAction.SOME_PREDICATE;
|
||||
import static edu.cornell.mannlib.vitro.webapp.auth.requestedAction.RequestedAction.SOME_URI;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.query.QuerySolution;
|
||||
import com.hp.hpl.jena.query.ResultSet;
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.policy.PolicyHelper;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.AddDataPropertyStatement;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.AddObjectPropertyStatement;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.Property;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.jena.QueryUtils;
|
||||
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.preprocessors.FoafNameToRdfsLabelPreprocessor;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.ManageLabelsForPersonPreprocessor;
|
||||
import edu.cornell.mannlib.vitro.webapp.i18n.selection.SelectedLocale;
|
||||
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.DataPropertyStatementTemplateModel;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
public class ManageLabelsForPersonGenerator extends BaseEditConfigurationGenerator implements EditConfigurationGenerator {
|
||||
public static Log log = LogFactory.getLog(ManageLabelsForIndividualGenerator.class);
|
||||
private static String template = "manageLabelsForIndividual.ftl";
|
||||
private HashMap<String, List<LabelInformation>> labelsSortedByLanguage = null;
|
||||
private List<Literal> existingLabelLiterals = null;
|
||||
|
||||
@Override
|
||||
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) {
|
||||
|
||||
EditConfigurationVTwo config = new EditConfigurationVTwo();
|
||||
config.setTemplate(this.getTemplate());
|
||||
|
||||
initBasics(config, vreq);
|
||||
initPropertyParameters(vreq, session, config);
|
||||
//This form is technically not an object property form in the true sense
|
||||
//or a data property form because it is used to list the various labels
|
||||
//and allow for adding new labels, but since the generator will
|
||||
//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);
|
||||
|
||||
|
||||
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
|
||||
//N3 required should be empty since the addition of a label is optional in this case
|
||||
config.setN3Required(this.generateN3Required(vreq));
|
||||
config.setN3Optional(this.generateN3Optional(vreq));
|
||||
this.addNewResources(config);
|
||||
this.setUrisAndLiteralsOnForm(config, vreq);
|
||||
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
|
||||
config.addEditSubmissionPreprocessor(
|
||||
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());
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
private void setVarNames(EditConfigurationVTwo editConfiguration) {
|
||||
editConfiguration.setVarNameForSubject("subject");
|
||||
editConfiguration.setVarNameForPredicate("predicate");
|
||||
|
||||
}
|
||||
|
||||
|
||||
private List<String> generateN3Required(VitroRequest vreq) {
|
||||
List<String> n3Required = new ArrayList<String>();
|
||||
return n3Required;
|
||||
}
|
||||
|
||||
private List<String> generateN3Optional(VitroRequest vreq) {
|
||||
List<String> n3Optional = new ArrayList<String>();
|
||||
|
||||
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 <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 =
|
||||
"?fullName <http://www.w3.org/2006/vcard/ns#givenName> ?firstName . ";
|
||||
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
|
||||
//there should be error-checking client side though
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("firstName").
|
||||
setValidators(getFirstNameValidators(vreq, editConfiguration)));
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("middleName").
|
||||
setValidators(getMiddleNameValidators(vreq, editConfiguration)));
|
||||
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName("lastName").
|
||||
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>();
|
||||
literalsOnForm.add("newLabelLanguage");
|
||||
//optional for person
|
||||
literalsOnForm.add("firstName");
|
||||
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(),
|
||||
Arrays.asList(new String[]{editConfiguration.getSubjectUri()}));
|
||||
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>();
|
||||
for(Literal l: this.existingLabelLiterals) {
|
||||
String language = l.getLanguage();
|
||||
if(!existingLanguages.contains(language)) {
|
||||
existingLanguages.add(language);
|
||||
}
|
||||
}
|
||||
List<String> sortedNames = new ArrayList<String>(existingLanguages);
|
||||
//sort alphabetically
|
||||
Collections.sort(sortedNames);
|
||||
return sortedNames;
|
||||
}
|
||||
|
||||
|
||||
private void addFormSpecificData(EditConfigurationVTwo config,
|
||||
VitroRequest vreq) {
|
||||
//Get all language codes/labels in the system, and this list is sorted by language name
|
||||
List<HashMap<String, String>> locales = this.getLocales(vreq);
|
||||
//Get code to label hashmap - we use this to get the language name for the language code returned in the rdf literal
|
||||
HashMap<String, String> localeCodeToNameMap = this.getFullCodeToLanguageNameMap(locales);
|
||||
//the labels already added by the user
|
||||
ArrayList<Literal> existingLabels = this.getExistingLabels(config.getSubjectUri(), vreq);
|
||||
int numberExistingLabels = existingLabels.size();
|
||||
//existing labels keyed by language name and each of the list of labels is sorted by language name
|
||||
HashMap<String, List<LabelInformation>> existingLabelsByLanguageName = this.getLabelsSortedByLanguageName(existingLabels, localeCodeToNameMap, config, vreq);
|
||||
//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);
|
||||
//Save labels sorted by language name, untyped have "untyped" as the language name value
|
||||
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");
|
||||
|
||||
|
||||
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
|
||||
//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) {
|
||||
List<HashMap<String, String>> availableLocales = new ArrayList<HashMap<String, String>>();
|
||||
for(HashMap<String, String> localeInfo: allLocales) {
|
||||
String languageName = (String) localeInfo.get("label");
|
||||
//If this language label is NOT in the labels sorted by language, then available
|
||||
//for selection when creating a new label
|
||||
//The assumption here is we don't want to allow the user to add a new label when a label
|
||||
//already exists in that language
|
||||
if(languageName != "untyped" && !existingLabelsLanguageNames.contains(languageName)) {
|
||||
availableLocales.add(localeInfo);
|
||||
}
|
||||
}
|
||||
//Sort list by language label and return
|
||||
Collections.sort(availableLocales, new Comparator<HashMap<String, String>>() {
|
||||
public int compare(HashMap<String, String> h1, HashMap<String, String> h2) {
|
||||
String languageName1 = (String) h1.get("label");
|
||||
String languageName2 = (String) h2.get("label");
|
||||
return languageName1.compareTo(languageName2);
|
||||
}
|
||||
});
|
||||
|
||||
return availableLocales;
|
||||
}
|
||||
|
||||
|
||||
private Object isEditable(VitroRequest vreq, EditConfigurationVTwo config) {
|
||||
Individual individual = EditConfigurationUtils.getIndividual(vreq, config.getSubjectUri());
|
||||
AddDataPropertyStatement adps = new AddDataPropertyStatement(
|
||||
vreq.getJenaOntModel(), individual.getURI(),
|
||||
SOME_URI, SOME_LITERAL);
|
||||
|
||||
AddObjectPropertyStatement aops = new AddObjectPropertyStatement(
|
||||
vreq.getJenaOntModel(), individual.getURI(),
|
||||
SOME_PREDICATE, SOME_URI);
|
||||
return PolicyHelper.isAuthorizedForActions(vreq, adps.or(aops));
|
||||
}
|
||||
|
||||
|
||||
//Copied from NewIndividualFormGenerator
|
||||
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;
|
||||
String foafPersonType = getFOAFPersonClassURI();
|
||||
List<VClass> vclasses = this.getVClasses(config, vreq);
|
||||
if( vclasses != null ){
|
||||
for( VClass v: vclasses){
|
||||
String typeUri = v.getURI();
|
||||
if( foafPersonType.equals(typeUri)) {
|
||||
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());
|
||||
//Get the vclasses appropriate for this subject
|
||||
return subject.getVClasses();
|
||||
}
|
||||
|
||||
//Languages sorted by language name
|
||||
private HashMap<String, List<LabelInformation>> getLabelsSortedByLanguageName(List<Literal> labels, Map<String, String> localeCodeToNameMap, EditConfigurationVTwo config,
|
||||
VitroRequest vreq) {
|
||||
String subjectUri = config.getSubjectUri();
|
||||
String propertyUri = config.getPredicateUri();
|
||||
Property prop = new Property();
|
||||
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 = "";
|
||||
if(languageTag == "") {
|
||||
languageName = "untyped";
|
||||
}
|
||||
else if(localeCodeToNameMap.containsKey(languageTag)) {
|
||||
languageName = localeCodeToNameMap.get(languageTag);
|
||||
} else {
|
||||
log.warn("This language tag " + languageTag + " does not have corresponding name in the system and was not processed");
|
||||
}
|
||||
|
||||
if(languageName != "") {
|
||||
if(!labelsHash.containsKey(languageName)) {
|
||||
labelsHash.put(languageName, new ArrayList<LabelInformation>());
|
||||
}
|
||||
ArrayList<LabelInformation> labelsList = (ArrayList<LabelInformation>)labelsHash.get(languageName);
|
||||
//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()) {
|
||||
List<LabelInformation> labelInfo = labelsHash.get(languageName);
|
||||
Collections.sort(labelInfo, lic);
|
||||
}
|
||||
return labelsHash;
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static class LabelInformationComparator implements Comparator<LabelInformation> {
|
||||
|
||||
public int compare(LabelInformation l1, LabelInformation l2) {
|
||||
return l1.getLabelStringValue().compareTo(l2.getLabelStringValue());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static String LABEL_QUERY = ""
|
||||
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n"
|
||||
+ "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);
|
||||
|
||||
ArrayList<Literal> labels = new ArrayList<Literal>();
|
||||
try {
|
||||
//We want to get the labels for all the languages, not just the display language
|
||||
ResultSet results = QueryUtils.getLanguageNeutralQueryResults(queryStr, vreq);
|
||||
while (results.hasNext()) {
|
||||
QuerySolution soln = results.nextSolution();
|
||||
Literal nodeLiteral = soln.get("label").asLiteral();
|
||||
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);
|
||||
if (selectables.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
|
||||
Locale currentLocale = SelectedLocale.getCurrentLocale(vreq);
|
||||
for (Locale locale : selectables) {
|
||||
try {
|
||||
list.add(buildLocaleMap(locale, currentLocale));
|
||||
} catch (FileNotFoundException e) {
|
||||
log.warn("Can't show the Locale selector for '" + locale
|
||||
+ "': " + 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);
|
||||
}
|
||||
else {
|
||||
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) {
|
||||
String label = (String) locale.get("label");
|
||||
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 {
|
||||
HashMap<String, String> map = new HashMap<String, String>();
|
||||
//Replacing the underscore with a hyphen because that is what is represented in the actual literals
|
||||
map.put("code", locale.toString().replace("_", "-"));
|
||||
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;
|
||||
public LabelInformation(Literal inputLiteral, String inputEditLinkURL, String inputDeleteLinkURL, String inputLanguageCode, String inputLanguageName) {
|
||||
this.labelLiteral = inputLiteral;
|
||||
this.editLinkURL = inputEditLinkURL;
|
||||
this.deleteLinkURL = inputDeleteLinkURL;
|
||||
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";
|
||||
|
||||
}
|
|
@ -0,0 +1,70 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
|
||||
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;
|
||||
|
||||
/**
|
||||
*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 ManageLabelsGenerator extends BaseEditConfigurationGenerator implements EditConfigurationGenerator {
|
||||
public static Log log = LogFactory.getLog(ManageLabelsForIndividualGenerator.class);
|
||||
@Override
|
||||
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) {
|
||||
EditConfigurationVTwo e = null;
|
||||
String subjectUri = EditConfigurationUtils.getSubjectUri(vreq);
|
||||
if(this.isPersonType(subjectUri, vreq)) {
|
||||
//Generator for persons
|
||||
e = new ManageLabelsForPersonGenerator().getEditConfiguration(vreq, session);
|
||||
} 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();
|
||||
List<VClass> vclasses = this.getVClasses(subjectUri, vreq);
|
||||
if( vclasses != null ){
|
||||
for( VClass v: vclasses){
|
||||
String typeUri = v.getURI();
|
||||
if( foafPersonType.equals(typeUri)) {
|
||||
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);
|
||||
//Get the vclasses appropriate for this subject
|
||||
return subject.getVClasses();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,215 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import com.hp.hpl.jena.query.QueryExecution;
|
||||
import com.hp.hpl.jena.query.QueryExecutionFactory;
|
||||
import com.hp.hpl.jena.rdf.model.Model;
|
||||
import com.hp.hpl.jena.rdf.model.ModelFactory;
|
||||
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.query.QuerySolution;
|
||||
import com.hp.hpl.jena.query.ResultSet;
|
||||
import com.hp.hpl.jena.rdf.model.RDFNode;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
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.dao.jena.QueryUtils;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* 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) {
|
||||
|
||||
EditConfigurationVTwo config = new EditConfigurationVTwo();
|
||||
config.setTemplate(this.getTemplate());
|
||||
|
||||
initBasics(config, vreq);
|
||||
initPropertyParameters(vreq, session, config);
|
||||
initObjectPropForm(config, vreq);
|
||||
|
||||
config.setSubjectUri(EditConfigurationUtils.getSubjectUri(vreq));
|
||||
config.setEntityToReturnTo( EditConfigurationUtils.getSubjectUri(vreq));
|
||||
|
||||
List<Map<String,String>> webpages = getWebpages(config.getSubjectUri(), vreq);
|
||||
config.addFormSpecificData("webpages",webpages);
|
||||
|
||||
config.addFormSpecificData("rankPredicate", "http://vivoweb.org/ontology/core#rank" );
|
||||
config.addFormSpecificData("reorderUrl", "/edit/reorder" );
|
||||
config.addFormSpecificData("deleteWebpageUrl", "/edit/primitiveDelete");
|
||||
|
||||
ParamMap paramMap = new ParamMap();
|
||||
paramMap.put("subjectUri", config.getSubjectUri());
|
||||
paramMap.put("editForm", this.getEditForm());
|
||||
paramMap.put("view", "form");
|
||||
String path = UrlBuilder.getUrl( UrlBuilder.Route.EDIT_REQUEST_DISPATCH ,paramMap);
|
||||
|
||||
config.addFormSpecificData("baseEditWebpageUrl", path);
|
||||
|
||||
//Also add domainUri and rangeUri if they exist, adding here instead of template
|
||||
String domainUri = (String) vreq.getParameter("domainUri");
|
||||
String rangeUri = (String) vreq.getParameter("rangeUri");
|
||||
paramMap = new ParamMap();
|
||||
paramMap.put("subjectUri", config.getSubjectUri());
|
||||
paramMap.put("predicateUri", config.getPredicateUri());
|
||||
paramMap.put("editForm" , this.getEditForm() );
|
||||
paramMap.put("cancelTo", "manage");
|
||||
if(domainUri != null && !domainUri.isEmpty()) {
|
||||
paramMap.put("domainUri", domainUri);
|
||||
}
|
||||
if(rangeUri != null && !rangeUri.isEmpty()) {
|
||||
paramMap.put("rangeUri", rangeUri);
|
||||
}
|
||||
path = UrlBuilder.getUrl( UrlBuilder.Route.EDIT_REQUEST_DISPATCH ,paramMap);
|
||||
|
||||
config.addFormSpecificData("showAddFormUrl", path);
|
||||
|
||||
Individual subject = vreq.getWebappDaoFactory().getIndividualDao().getIndividualByURI(config.getSubjectUri());
|
||||
if( subject != null && subject.getName() != null ){
|
||||
config.addFormSpecificData("subjectName", subject.getName());
|
||||
}else{
|
||||
config.addFormSpecificData("subjectName", null);
|
||||
}
|
||||
prepare(vreq, config);
|
||||
return config;
|
||||
}
|
||||
|
||||
private static String WEBPAGE_MODEL = ""
|
||||
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
|
||||
+ "PREFIX vcard: <http://www.w3.org/2006/vcard/ns#> \n"
|
||||
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n"
|
||||
+ "PREFIX vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#>\n"
|
||||
+ "CONSTRUCT\n"
|
||||
+ "{\n"
|
||||
+ " ?subject <http://purl.obolibrary.org/obo/ARG_2000028> ?vcard .\n"
|
||||
+ " ?vcard vcard:hasURL ?link .\n"
|
||||
+ " ?link a vcard:URL .\n"
|
||||
+ " ?link vcard:url ?url .\n"
|
||||
+ " ?link rdfs:label ?linkLabel .\n"
|
||||
+ " ?link core:rank ?rank .\n"
|
||||
+ " ?link vitro:mostSpecificType ?type .\n"
|
||||
+ " ?type rdfs:label ?typeLabel .\n"
|
||||
+ "}\n"
|
||||
+ "WHERE\n"
|
||||
+ "{\n"
|
||||
+ " {\n"
|
||||
+ " ?subject <http://purl.obolibrary.org/obo/ARG_2000028> ?vcard .\n"
|
||||
+ " ?vcard vcard:hasURL ?link .\n"
|
||||
+ " ?link a vcard:URL .\n"
|
||||
+ " }\n"
|
||||
+ " UNION\n"
|
||||
+ " {\n"
|
||||
+ " ?subject <http://purl.obolibrary.org/obo/ARG_2000028> ?vcard .\n"
|
||||
+ " ?vcard vcard:hasURL ?link .\n"
|
||||
+ " ?link a vcard:URL .\n"
|
||||
+ " ?link vcard:url ?url .\n"
|
||||
+ " }\n"
|
||||
+ " UNION\n"
|
||||
+ " {\n"
|
||||
+ " ?subject <http://purl.obolibrary.org/obo/ARG_2000028> ?vcard .\n"
|
||||
+ " ?vcard vcard:hasURL ?link .\n"
|
||||
+ " ?link a vcard:URL .\n"
|
||||
+ " ?link rdfs:label ?linkLabel .\n"
|
||||
+ " }\n"
|
||||
+ " UNION\n"
|
||||
+ " {\n"
|
||||
+ " ?subject <http://purl.obolibrary.org/obo/ARG_2000028> ?vcard . \n"
|
||||
+ " ?vcard vcard:hasURL ?link .\n"
|
||||
+ " ?link a vcard:URL .\n"
|
||||
+ " ?link core:rank ?rank .\n"
|
||||
+ " }\n"
|
||||
+ " UNION\n"
|
||||
+ " {\n"
|
||||
+ " ?subject <http://purl.obolibrary.org/obo/ARG_2000028> ?vcard .\n"
|
||||
+ " ?vcard vcard:hasURL ?link .\n"
|
||||
+ " ?link a vcard:URL .\n"
|
||||
+ " ?link vitro:mostSpecificType ?type .\n"
|
||||
+ " ?type rdfs:label ?typeLabel .\n"
|
||||
+ " }\n"
|
||||
+ "}\n";
|
||||
|
||||
private static String WEBPAGE_QUERY = ""
|
||||
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
|
||||
+ "PREFIX vcard: <http://www.w3.org/2006/vcard/ns#> \n"
|
||||
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n"
|
||||
+ "PREFIX vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> \n"
|
||||
+ "SELECT DISTINCT ?vcard ?link ?url ?rank ?typeLabel (group_concat(distinct ?linkLabel;separator=\"/\") as ?label) WHERE { \n"
|
||||
+ " ?subject <http://purl.obolibrary.org/obo/ARG_2000028> ?vcard . \n"
|
||||
+ " ?vcard vcard:hasURL ?link . \n"
|
||||
+ " ?link a vcard:URL \n"
|
||||
+ " OPTIONAL { ?link vcard:url ?url } \n"
|
||||
+ " OPTIONAL { ?link rdfs:label ?linkLabel } \n"
|
||||
+ " 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"
|
||||
+ " ORDER BY ?rank";
|
||||
|
||||
|
||||
private List<Map<String, String>> getWebpages(String subjectUri, VitroRequest vreq) {
|
||||
RDFService rdfService = vreq.getRDFService();
|
||||
|
||||
List<Map<String, String>> webpages = new ArrayList<Map<String, String>>();
|
||||
try {
|
||||
String constructStr = QueryUtils.subUriForQueryVar(WEBPAGE_MODEL, "subject", subjectUri);
|
||||
|
||||
Model constructedModel = ModelFactory.createDefaultModel();
|
||||
rdfService.sparqlConstructQuery(constructStr, constructedModel);
|
||||
|
||||
String queryStr = QueryUtils.subUriForQueryVar(this.getQuery(), "subject", subjectUri);
|
||||
log.debug("Query string is: " + queryStr);
|
||||
|
||||
QueryExecution qe = QueryExecutionFactory.create(queryStr, constructedModel);
|
||||
try {
|
||||
ResultSet results = qe.execSelect();
|
||||
|
||||
while (results.hasNext()) {
|
||||
QuerySolution soln = results.nextSolution();
|
||||
RDFNode node = soln.get("link");
|
||||
if (node != null && node.isURIResource()) {
|
||||
webpages.add(QueryUtils.querySolutionToStringValueMap(soln));
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
qe.close();
|
||||
}
|
||||
} 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";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,208 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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 javax.servlet.http.HttpSession;
|
||||
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
import com.hp.hpl.jena.vocabulary.RDFS;
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
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.preprocessors.FoafNameToRdfsLabelPreprocessor;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
|
||||
/**
|
||||
* Generates the edit configuration for a default property form.
|
||||
* ModelChangePreprocessor creates the rdfs:label statement.
|
||||
*/
|
||||
public class NewIndividualFormGenerator 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
|
||||
//middle name is also optional
|
||||
config.setN3Optional(list(
|
||||
N3_PREFIX + "@prefix vcard:<http://www.w3.org/2006/vcard/ns#> .\n"
|
||||
+ " ?newInd <http://purl.obolibrary.org/obo/ARG_2000028> ?newVcardInd . \n"
|
||||
+ " ?newVcardInd <http://purl.obolibrary.org/obo/ARG_2000029> ?newInd . \n"
|
||||
+ " ?newVcardInd a vcard:Individual . \n"
|
||||
+ " ?newVcardInd vcard:hasName ?newVcardName . \n"
|
||||
+ " ?newVcardName a vcard:Name . \n"
|
||||
+ " ?newVcardName vcard:givenName ?firstName . \n"
|
||||
+ " ?newVcardName vcard:familyName ?lastName . \n",
|
||||
N3_PREFIX + " ?newInd <" + RDFS.label.getURI() + "> ?label .",
|
||||
N3_PREFIX + "@prefix vcard:<http://www.w3.org/2006/vcard/ns#> .\n"
|
||||
+ " ?newInd <http://purl.obolibrary.org/obo/ARG_2000028> ?newVcardInd . \n"
|
||||
+ " ?newVcardInd a vcard:Individual . \n"
|
||||
+ " ?newVcardInd vcard:hasName ?newVcardName . \n"
|
||||
+ " ?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" ));
|
||||
setUrisAndLiteralsInScope(config);
|
||||
//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)));
|
||||
|
||||
config.addField(new FieldVTwo().
|
||||
setName("label").
|
||||
setRangeDatatypeUri(XSD.xstring.getURI()).
|
||||
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());
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
//first and last name have validators if is person is true
|
||||
private List<String> getFirstNameValidators(VitroRequest vreq) {
|
||||
List<String> validators = new ArrayList<String>();
|
||||
if(isPersonType(vreq)) {
|
||||
validators.add("nonempty");
|
||||
}
|
||||
return validators;
|
||||
}
|
||||
|
||||
private List<String> getLastNameValidators(VitroRequest vreq) {
|
||||
List<String> validators = new ArrayList<String>();
|
||||
if(isPersonType(vreq)) {
|
||||
validators.add("nonempty");
|
||||
}
|
||||
return validators;
|
||||
}
|
||||
|
||||
//validate label if person is not true
|
||||
private List<String> getLabelValidators(VitroRequest vreq) {
|
||||
List<String> validators = new ArrayList<String>();
|
||||
if(!isPersonType(vreq)) {
|
||||
validators.add("nonempty");
|
||||
}
|
||||
return validators;
|
||||
}
|
||||
|
||||
//Get parameter from HTTP request for type of new individual
|
||||
private String getTypeOfNew(VitroRequest vreq) {
|
||||
String typeUri = vreq.getParameter("typeOfNew");
|
||||
if( typeUri == null || typeUri.trim().isEmpty() )
|
||||
return getFOAFPersonClassURI();
|
||||
else
|
||||
return typeUri;
|
||||
}
|
||||
|
||||
//Form specific data
|
||||
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
|
||||
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
|
||||
formSpecificData.put("typeName", getTypeName(vreq));
|
||||
//Put in whether or not person type
|
||||
if(isPersonType(vreq)) {
|
||||
//Doing this b/c unsure how freemarker will handle boolean value from JAVA
|
||||
formSpecificData.put("isPersonType", "true");
|
||||
} else {
|
||||
formSpecificData.put("isPersonType", "false");
|
||||
|
||||
}
|
||||
editConfiguration.setFormSpecificData(formSpecificData);
|
||||
}
|
||||
|
||||
private String getTypeName(VitroRequest vreq) {
|
||||
String typeOfNew = getTypeOfNew(vreq);
|
||||
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;
|
||||
String foafPersonType = getFOAFPersonClassURI();
|
||||
String typeOfNew = getTypeOfNew(vreq);
|
||||
List<String> superTypes = wdf.getVClassDao().getAllSuperClassURIs(typeOfNew);
|
||||
//add the actual type as well so we can add that for the list to be checked
|
||||
superTypes.add(typeOfNew);
|
||||
if( superTypes != null ){
|
||||
for( String typeUri : superTypes){
|
||||
if( foafPersonType.equals(typeUri)) {
|
||||
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(),
|
||||
Arrays.asList(new String[]{editConfiguration.getSubjectUri()}));
|
||||
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";
|
||||
}
|
|
@ -0,0 +1,127 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.AutocompleteRequiredInputValidator;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeIntervalValidationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ChildVClassesWithParent;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ConstantFieldOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaVClassOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
|
||||
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);
|
||||
|
||||
conf.setTemplate("organizationAdministersGrant.ftl");
|
||||
|
||||
conf.setVarNameForSubject("organization");
|
||||
conf.setVarNameForPredicate("predicate");
|
||||
conf.setVarNameForObject("adminRole");
|
||||
|
||||
conf.setN3Required( Arrays.asList( n3ForNewAdminRole) );
|
||||
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.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").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("grantLabelDisplay").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()))
|
||||
);
|
||||
|
||||
conf.addValidator(new AntiXssValidation());
|
||||
conf.addValidator(new AutocompleteRequiredInputValidator("existingGrant", "grantLabel"));
|
||||
|
||||
// addFormSpecificData(conf, vreq);
|
||||
prepare(vreq, conf);
|
||||
return conf;
|
||||
}
|
||||
|
||||
/* N3 assertions */
|
||||
|
||||
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 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" +
|
||||
"?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 =
|
||||
"PREFIX vivo: <http://vivoweb.org/ontology/core#> \n" +
|
||||
"SELECT ?existingGrant WHERE { \n" +
|
||||
" ?adminRole vivo:relatedBy ?existingGrant . \n" +
|
||||
" ?existingGrant a vivo:Grant . \n" +
|
||||
"}";
|
||||
|
||||
final static String grantLabelQuery =
|
||||
"PREFIX vivo: <http://vivoweb.org/ontology/core#> \n" +
|
||||
"SELECT ?existingGrantLabel WHERE { \n" +
|
||||
" ?adminRole vivo:relatedBy ?existingGrant . \n" +
|
||||
" ?existingGrant a vivo:Grant . \n" +
|
||||
" ?existingGrant <" + label + "> ?existingGrantLabel . \n" +
|
||||
"}";
|
||||
|
||||
}
|
|
@ -0,0 +1,390 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
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 javax.servlet.http.HttpSession;
|
||||
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.FirstAndLastNameValidator;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeIntervalValidationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ChildVClassesOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ChildVClassesWithParent;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaVClassOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
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{
|
||||
|
||||
//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);
|
||||
|
||||
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,
|
||||
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);
|
||||
conf.addNewResource("intervalNode",DEFAULT_NS_FOR_NEW_RESOURCE);
|
||||
conf.addNewResource("startNode",DEFAULT_NS_FOR_NEW_RESOURCE);
|
||||
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
|
||||
//literals in scope: none
|
||||
|
||||
conf.setUrisOnform( Arrays.asList( "existingPerson", "degreeType", "trainingType"));
|
||||
conf.setLiteralsOnForm( Arrays.asList("personLabel", "personLabelDisplay", "awardedDegreeLabel",
|
||||
"majorField", "dept", "info", "firstName", "lastName"));
|
||||
|
||||
conf.addSparqlForExistingLiteral("personLabel", personLabelQuery);
|
||||
conf.addSparqlForExistingLiteral("majorField", majorFieldQuery);
|
||||
conf.addSparqlForExistingLiteral("dept", deptQuery);
|
||||
conf.addSparqlForExistingLiteral("info", infoQuery);
|
||||
conf.addSparqlForExistingLiteral("startField-value", existingStartDateQuery);
|
||||
conf.addSparqlForExistingLiteral("endField-value", existingEndDateQuery);
|
||||
|
||||
|
||||
conf.addSparqlForExistingUris("awardedDegree", existingAwardedDegreeQuery);
|
||||
conf.addSparqlForExistingUris("existingPerson", existingPersonQuery);
|
||||
conf.addSparqlForExistingUris("trainingType", trainingTypeQuery);
|
||||
conf.addSparqlForExistingUris("degreeType", degreeTypeQuery);
|
||||
conf.addSparqlForExistingUris("intervalNode",existingIntervalNodeQuery);
|
||||
conf.addSparqlForExistingUris("startNode", existingStartNodeQuery);
|
||||
conf.addSparqlForExistingUris("endNode", existingEndNodeQuery);
|
||||
conf.addSparqlForExistingUris("startField-precision", existingStartPrecisionQuery);
|
||||
conf.addSparqlForExistingUris("endField-precision", existingEndPrecisionQuery);
|
||||
//Add sparql to include inverse property as well
|
||||
conf.addSparqlForAdditionalUrisInScope("inverseTrainingAtPerson", inverseTrainingAtPersonQuery);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("degreeType").
|
||||
setOptions( new IndividualsViaVClassOptions(
|
||||
degreeTypeClass)));
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
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
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("awardedDegree")
|
||||
//options will be added in browser by auto complete JS
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("personLabel").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString())));
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("awardedDegreeLabel").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString())));
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
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() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("lastName").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("trainingType").
|
||||
setValidators( list("nonempty") ).
|
||||
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() ).
|
||||
setValidators(list("datatype:" + XSD.xstring.toString())));
|
||||
|
||||
FieldVTwo startField = new FieldVTwo().
|
||||
setName("startField");
|
||||
conf.addField(startField.
|
||||
setEditElement(
|
||||
new DateTimeWithPrecisionVTwo(startField,
|
||||
VitroVocabulary.Precision.YEAR.uri(),
|
||||
VitroVocabulary.Precision.NONE.uri())));
|
||||
|
||||
FieldVTwo endField = new FieldVTwo().
|
||||
setName("endField");
|
||||
conf.addField( endField.
|
||||
setEditElement(
|
||||
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 =
|
||||
"@prefix core: <"+ vivoCore +"> .\n"+
|
||||
"?organization <http://purl.obolibrary.org/obo/RO_0000056> ?edTraining .\n" +
|
||||
"?edTraining a core:EducationalProcess .\n" +
|
||||
"?edTraining <http://purl.obolibrary.org/obo/RO_0000057> ?organization .";
|
||||
|
||||
final static String trainingTypeAssertion =
|
||||
"?edTraining a ?trainingType .";
|
||||
|
||||
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" +
|
||||
"?awardedDegree <http://vivoweb.org/ontology/core#assignedBy> ?organization . \n" +
|
||||
"?organization <http://vivoweb.org/ontology/core#assigns> ?awardedDegree . \n" +
|
||||
"?awardedDegree <"+ label +"> ?awardedDegreeLabel . \n" +
|
||||
"?awardedDegree <http://vivoweb.org/ontology/core#relates> ?degreeType .\n"+
|
||||
"?degreeType <http://vivoweb.org/ontology/core#relatedBy> ?awardedDegree . \n"+
|
||||
"?awardedDegree a core:AwardedDegree .";
|
||||
|
||||
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 =
|
||||
"?edTraining <http://purl.obolibrary.org/obo/RO_0000057> ?existingPerson . \n" +
|
||||
"?existingPerson <http://purl.obolibrary.org/obo/RO_0000056> ?edTraining . \n" +
|
||||
" ";
|
||||
|
||||
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 =
|
||||
"@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 vcard:hasName ?vcardName . \n" +
|
||||
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
|
||||
"?vcardName vcard:givenName ?firstName .";
|
||||
|
||||
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 vcard:hasName ?vcardName . \n" +
|
||||
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
|
||||
"?vcardName vcard:familyName ?lastName .";
|
||||
|
||||
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 =
|
||||
"?edTraining <"+ majorFieldPred +"> ?majorField .";
|
||||
|
||||
final static String n3ForStart =
|
||||
"?edTraining <"+ toInterval +"> ?intervalNode .\n"+
|
||||
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
|
||||
"?intervalNode <"+ intervalToStart +"> ?startNode .\n"+
|
||||
"?startNode <"+ type +"> <"+ dateTimeValueType +"> .\n"+
|
||||
"?startNode <"+ dateTimeValue +"> ?startField-value .\n"+
|
||||
"?startNode <"+ dateTimePrecision +"> ?startField-precision .";
|
||||
|
||||
final static String n3ForEnd =
|
||||
"?edTraining <"+ toInterval +"> ?intervalNode . \n"+
|
||||
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
|
||||
"?intervalNode <"+ intervalToEnd +"> ?endNode .\n"+
|
||||
"?endNode <"+ type +"> <"+ dateTimeValueType +"> .\n"+
|
||||
"?endNode <"+ dateTimeValue +"> ?endField-value .\n"+
|
||||
"?endNode <"+ dateTimePrecision +"> ?endField-precision .";
|
||||
|
||||
final static String deptAssertion =
|
||||
"?edTraining <"+ deptPred +"> ?dept .";
|
||||
|
||||
final static String infoAssertion =
|
||||
"?edTraining <"+ infoPred +"> ?info .";
|
||||
|
||||
/* Queries for editing an existing educational training entry */
|
||||
|
||||
final static String existingAwardedDegreeQuery =
|
||||
"SELECT ?existingAwardedDegree WHERE {\n"+
|
||||
"?edTraining <http://purl.obolibrary.org/obo/RO_0002234> ?existingAwardedDegree . }\n";
|
||||
|
||||
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 =
|
||||
"PREFIX rdfs: <"+ rdfs +"> \n"+
|
||||
"SELECT ?existingPerson WHERE {\n"+
|
||||
"?edTraining <http://purl.obolibrary.org/obo/RO_0000057> ?existingPerson . \n" +
|
||||
"?existingPerson <http://purl.obolibrary.org/obo/RO_0000056> ?edTraining . \n" +
|
||||
"?existingPerson a <http://xmlns.com/foaf/0.1/Person> . \n " +
|
||||
" }";
|
||||
|
||||
final static String personLabelQuery =
|
||||
"PREFIX rdfs: <"+ rdfs +"> \n"+
|
||||
"SELECT ?existingPersonLabel WHERE {\n"+
|
||||
"?edTraining <http://purl.obolibrary.org/obo/RO_0000057> ?existingPerson . \n" +
|
||||
"?existingPerson <http://purl.obolibrary.org/obo/RO_0000056> ?edTraining .\n"+
|
||||
"?existingPerson <"+ label +"> ?existingPersonLabel .\n"+
|
||||
"?existingPerson a <http://xmlns.com/foaf/0.1/Person> . \n " +
|
||||
" }";
|
||||
|
||||
final static String trainingTypeQuery =
|
||||
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
|
||||
"SELECT ?existingTrainingType WHERE { \n" +
|
||||
" ?edTraining vitro:mostSpecificType ?existingTrainingType . }";
|
||||
|
||||
final static String degreeTypeQuery =
|
||||
"PREFIX core: <"+ vivoCore +"> \n"+
|
||||
"SELECT ?existingDegreeType WHERE {\n"+
|
||||
"?edTraining <http://purl.obolibrary.org/obo/RO_0002234> ?existingAwardedDegree . \n"+
|
||||
"?existingAwardedDegree a core:AwardedDegree . \n"+
|
||||
"?existingAwardedDegree core:relates ?existingDegreeType . \n" +
|
||||
"?existingDegreeType a core:AcademicDegree }";
|
||||
|
||||
final static String majorFieldQuery =
|
||||
"SELECT ?existingMajorField WHERE {\n"+
|
||||
"?edTraining <"+ majorFieldPred +"> ?existingMajorField . }";
|
||||
|
||||
final static String deptQuery =
|
||||
"SELECT ?existingDept WHERE {\n"+
|
||||
"?edTraining <"+ deptPred +"> ?existingDept . }";
|
||||
|
||||
final static String infoQuery =
|
||||
"SELECT ?existingInfo WHERE {\n"+
|
||||
"?edTraining <"+ infoPred +"> ?existingInfo . }";
|
||||
|
||||
final static String existingIntervalNodeQuery =
|
||||
"SELECT ?existingIntervalNode WHERE {\n"+
|
||||
"?edTraining <"+ toInterval +"> ?existingIntervalNode .\n"+
|
||||
"?existingIntervalNode <"+ type +"> <"+ intervalType +"> . }";
|
||||
|
||||
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 =
|
||||
"SELECT ?existingDateStart WHERE {\n"+
|
||||
"?edTraining <"+ toInterval +"> ?intervalNode .\n"+
|
||||
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
|
||||
"?intervalNode <"+ intervalToStart +"> ?startNode .\n"+
|
||||
"?startNode <"+ type +"> <"+ dateTimeValueType +"> .\n"+
|
||||
"?startNode <"+ dateTimeValue +"> ?existingDateStart . }";
|
||||
|
||||
final static String existingStartPrecisionQuery =
|
||||
"SELECT ?existingStartPrecision WHERE {\n"+
|
||||
"?edTraining <"+ toInterval +"> ?intervalNode .\n"+
|
||||
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
|
||||
"?intervalNode <"+ intervalToStart +"> ?startNode .\n"+
|
||||
"?startNode <"+ type +"> <"+ dateTimeValueType +"> . \n"+
|
||||
"?startNode <"+ dateTimePrecision +"> ?existingStartPrecision . }";
|
||||
|
||||
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 =
|
||||
"SELECT ?existingEndDate WHERE {\n"+
|
||||
"?edTraining <"+ toInterval +"> ?intervalNode .\n"+
|
||||
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
|
||||
"?intervalNode <"+ intervalToEnd +"> ?endNode .\n"+
|
||||
"?endNode <"+ type +"> <"+ dateTimeValueType +"> .\n"+
|
||||
"?endNode <"+ dateTimeValue +"> ?existingEndDate . }";
|
||||
|
||||
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");
|
||||
return EditModeUtils.getEditMode(vreq, predicates);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,268 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary.Precision;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.FirstAndLastNameValidator;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeIntervalValidationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ChildVClassesWithParent;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaVClassOptions;
|
||||
|
||||
public class OrganizationHasPositionHistoryGenerator extends VivoBaseGenerator
|
||||
implements EditConfigurationGenerator {
|
||||
|
||||
private final static String NS_VIVO_CORE = "http://vivoweb.org/ontology/core#";
|
||||
|
||||
private static final String URI_PRECISION_NONE = Precision.NONE.uri();
|
||||
private static final String URI_PRECISION_YEAR = Precision.YEAR.uri();
|
||||
|
||||
private final static String URI_POSITION_CLASS = NS_VIVO_CORE + "Position";
|
||||
|
||||
private static final String QUERY_EXISTING_POSITION_TITLE = ""
|
||||
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n"
|
||||
+ "SELECT ?existingPositionTitle WHERE { \n"
|
||||
+ " ?position rdfs:label ?existingPositionTitle . }";
|
||||
|
||||
private static final String QUERY_EXISTING_POSITION_TYPE = ""
|
||||
+ "PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n"
|
||||
+ "SELECT ?existingPositionType WHERE { \n"
|
||||
+ " ?position vitro:mostSpecificType ?existingPositionType . }";
|
||||
|
||||
private static final String QUERY_EXISTING_PERSON = ""
|
||||
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
|
||||
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n"
|
||||
+ "SELECT ?existingPerson WHERE { \n"
|
||||
+ " ?position core:relates ?existingPerson .}";
|
||||
|
||||
private static final String QUERY_EXISTING_PERSON_LABEL = ""
|
||||
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
|
||||
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n"
|
||||
+ "SELECT ?existingPersonLabel WHERE { \n"
|
||||
+ " ?position core:relates ?existingPerson . \n"
|
||||
+ " ?existingPerson rdfs:label ?existingPersonLabel . }";
|
||||
|
||||
private static final String QUERY_EXISTING_INTERVAL_NODE = ""
|
||||
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
|
||||
+ "SELECT ?existingIntervalNode WHERE { \n"
|
||||
+ " ?position core:dateTimeInterval ?existingIntervalNode . \n"
|
||||
+ " ?existingIntervalNode a core:DateTimeInterval . }";
|
||||
|
||||
private static final String QUERY_EXISTING_START_NODE = ""
|
||||
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
|
||||
+ "SELECT ?existingStartNode WHERE { \n"
|
||||
+ " ?position core:dateTimeInterval ?intervalNode .\n"
|
||||
+ " ?intervalNode a core:DateTimeInterval ;\n"
|
||||
+ " core:start ?existingStartNode . \n"
|
||||
+ " ?existingStartNode a core:DateTimeValue . }";
|
||||
|
||||
private static final String QUERY_EXISTING_START_VALUE = ""
|
||||
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
|
||||
+ "SELECT ?existingDateStart WHERE { \n"
|
||||
+ " ?position core:dateTimeInterval ?intervalNode .\n"
|
||||
+ " ?intervalNode a core:DateTimeInterval ; \n"
|
||||
+ " core:start ?startNode . \n"
|
||||
+ " ?startNode a core:DateTimeValue ; \n"
|
||||
+ " core:dateTime ?existingDateStart . }";
|
||||
|
||||
private static final String QUERY_EXISTING_START_PRECISION = ""
|
||||
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
|
||||
+ "SELECT ?existingStartPrecision WHERE { \n"
|
||||
+ " ?position core:dateTimeInterval ?intervalNode .\n"
|
||||
+ " ?intervalNode a core:DateTimeInterval ;\n"
|
||||
+ " core:start ?startNode . \n"
|
||||
+ " ?startNode a core:DateTimeValue ; \n"
|
||||
+ " core:dateTimePrecision ?existingStartPrecision . }";
|
||||
|
||||
private static final String QUERY_EXISTING_END_NODE = ""
|
||||
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
|
||||
+ "SELECT ?existingEndNode WHERE { \n"
|
||||
+ " ?position core:dateTimeInterval ?intervalNode .\n"
|
||||
+ " ?intervalNode a core:DateTimeInterval ;\n"
|
||||
+ " core:end ?existingEndNode . \n"
|
||||
+ " ?existingEndNode a core:DateTimeValue . }";
|
||||
|
||||
private static final String QUERY_EXISTING_END_VALUE = ""
|
||||
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
|
||||
+ "SELECT ?existingDateEnd WHERE { \n"
|
||||
+ " ?position core:dateTimeInterval ?intervalNode .\n"
|
||||
+ " ?intervalNode a core:DateTimeInterval ; \n"
|
||||
+ " core:end ?endNode . \n"
|
||||
+ " ?endNode a core:DateTimeValue ; \n"
|
||||
+ " core:dateTime ?existingDateEnd . }";
|
||||
|
||||
private static final String QUERY_EXISTING_END_PRECISION = ""
|
||||
+ "PREFIX core: <http://vivoweb.org/ontology/core#> \n"
|
||||
+ "SELECT ?existingEndPrecision WHERE { \n"
|
||||
+ " ?position core:dateTimeInterval ?intervalNode .\n"
|
||||
+ " ?intervalNode a core:DateTimeInterval ;\n"
|
||||
+ " core:end ?endNode . \n"
|
||||
+ " ?endNode a core:DateTimeValue ; \n"
|
||||
+ " core:dateTimePrecision ?existingEndPrecision . }";
|
||||
|
||||
private static final String N3_NEW_POSITION = ""
|
||||
+ "@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 ?positionType . \n"
|
||||
+ "?position rdfs:label ?positionTitle . \n"
|
||||
+ "?position core:relates ?organization . ";
|
||||
|
||||
private static final String N3_NEW_PERSON = ""
|
||||
+ "@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"
|
||||
+ "?person core:relatedBy ?position . \n"
|
||||
+ "?person a foaf:Person . \n"
|
||||
+ "?person rdfs:label ?personLabel . ";
|
||||
|
||||
private static final String N3_NEW_FIRST_NAME = ""
|
||||
+ "@prefix vcard: <http://www.w3.org/2006/vcard/ns#> . \n"
|
||||
+ "?person <http://purl.obolibrary.org/obo/ARG_2000028> ?vcardPerson . \n"
|
||||
+ "?vcardPerson <http://purl.obolibrary.org/obo/ARG_2000029> ?person . \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 vcard:givenName ?firstName .";
|
||||
|
||||
private static final String N3_NEW_LAST_NAME = ""
|
||||
+ "@prefix vcard: <http://www.w3.org/2006/vcard/ns#> . \n"
|
||||
+ "?person <http://purl.obolibrary.org/obo/ARG_2000028> ?vcardPerson . \n"
|
||||
+ "?vcardPerson <http://purl.obolibrary.org/obo/ARG_2000029> ?person . \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 vcard:familyName ?lastName .";
|
||||
|
||||
private static final String N3_EXISTING_PERSON = ""
|
||||
+ "@prefix core: <http://vivoweb.org/ontology/core#> . \n"
|
||||
+ "?position core:relates ?existingPerson . \n"
|
||||
+ "?existingPerson core:relatedBy ?position . \n";
|
||||
|
||||
private static final String N3_NEW_START_NODE = ""
|
||||
+ "@prefix core: <http://vivoweb.org/ontology/core#> . \n"
|
||||
+ "?position core:dateTimeInterval ?intervalNode . \n"
|
||||
+ "?intervalNode a core:DateTimeInterval . \n"
|
||||
+ "?intervalNode core:start ?startNode . \n "
|
||||
+ "?startNode a core:DateTimeValue . \n"
|
||||
+ "?startNode core:dateTime ?startField-value. \n"
|
||||
+ "?startNode core:dateTimePrecision ?startField-precision . ";
|
||||
|
||||
private static final String N3_NEW_END_NODE = ""
|
||||
+ "@prefix core: <http://vivoweb.org/ontology/core#> . \n"
|
||||
+ "?position core:dateTimeInterval ?intervalNode . \n"
|
||||
+ "?intervalNode a core:DateTimeInterval . \n"
|
||||
+ "?intervalNode core:end ?endNode . \n "
|
||||
+ "?endNode a core:DateTimeValue . \n"
|
||||
+ "?endNode core:dateTime ?endField-value . \n"
|
||||
+ "?endNode core:dateTimePrecision ?endField-precision . ";
|
||||
|
||||
@Override
|
||||
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
|
||||
HttpSession session) throws Exception {
|
||||
EditConfigurationVTwo conf = new EditConfigurationVTwo();
|
||||
|
||||
initBasics(conf, vreq);
|
||||
initPropertyParameters(vreq, session, conf);
|
||||
initObjectPropForm(conf, vreq);
|
||||
|
||||
conf.setVarNameForSubject("organization");
|
||||
conf.setVarNameForPredicate("predicate");
|
||||
conf.setVarNameForObject("position");
|
||||
|
||||
conf.setTemplate("organizationHasPositionHistory.ftl");
|
||||
|
||||
conf.setN3Required(Arrays.asList(N3_NEW_POSITION));
|
||||
conf.setN3Optional(Arrays.asList(N3_NEW_PERSON, N3_EXISTING_PERSON, N3_NEW_START_NODE, N3_NEW_END_NODE, N3_NEW_FIRST_NAME, N3_NEW_LAST_NAME));
|
||||
|
||||
conf.addNewResource("position", DEFAULT_NS_FOR_NEW_RESOURCE);
|
||||
conf.addNewResource("person", DEFAULT_NS_FOR_NEW_RESOURCE);
|
||||
conf.addNewResource("vcardName", DEFAULT_NS_FOR_NEW_RESOURCE);
|
||||
conf.addNewResource("vcardPerson", 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);
|
||||
|
||||
conf.setUrisOnform(Arrays.asList("existingPerson", "position", "positionType"));
|
||||
conf.addSparqlForExistingUris("positionType",
|
||||
QUERY_EXISTING_POSITION_TYPE);
|
||||
conf.addSparqlForExistingUris("intervalNode",
|
||||
QUERY_EXISTING_INTERVAL_NODE);
|
||||
conf.addSparqlForExistingUris("startNode", QUERY_EXISTING_START_NODE);
|
||||
conf.addSparqlForExistingUris("endNode", QUERY_EXISTING_END_NODE);
|
||||
|
||||
conf.setLiteralsOnForm(Arrays.asList("positionTitle", "personLabelDisplay", "personLabel", "firstName", "lastName"));
|
||||
conf.addSparqlForExistingLiteral("positionTitle",
|
||||
QUERY_EXISTING_POSITION_TITLE);
|
||||
conf.addSparqlForExistingLiteral("personLabel",
|
||||
QUERY_EXISTING_PERSON_LABEL);
|
||||
conf.addSparqlForExistingUris("existingPerson",
|
||||
QUERY_EXISTING_PERSON);
|
||||
conf.addSparqlForExistingLiteral("startField-value",
|
||||
QUERY_EXISTING_START_VALUE);
|
||||
conf.addSparqlForExistingUris("startField-precision",
|
||||
QUERY_EXISTING_START_PRECISION);
|
||||
conf.addSparqlForExistingLiteral("endField-value",
|
||||
QUERY_EXISTING_END_VALUE);
|
||||
conf.addSparqlForExistingUris("endField-precision",
|
||||
QUERY_EXISTING_END_PRECISION);
|
||||
|
||||
conf.addField(new FieldVTwo()
|
||||
.setName("positionType")
|
||||
.setValidators(list("nonempty"))
|
||||
.setOptions(
|
||||
new ChildVClassesWithParent(URI_POSITION_CLASS))
|
||||
);
|
||||
|
||||
conf.addField(new FieldVTwo().setName("positionTitle")
|
||||
.setRangeDatatypeUri(XSD.xstring.toString())
|
||||
.setValidators(list("nonempty")));
|
||||
|
||||
//options for existingPerson will be added in browser by auto complete JS
|
||||
conf.addField(new FieldVTwo().setName("existingPerson"));
|
||||
|
||||
conf.addField(new FieldVTwo().setName("personLabel")
|
||||
.setRangeDatatypeUri(XSD.xstring.toString())
|
||||
.setValidators( list("datatype:" + XSD.xstring.toString()) ));
|
||||
|
||||
conf.addField(new FieldVTwo().setName("firstName")
|
||||
.setRangeDatatypeUri(XSD.xstring.toString())
|
||||
.setValidators( list("datatype:" + XSD.xstring.toString()) ));
|
||||
|
||||
conf.addField(new FieldVTwo().setName("lastName")
|
||||
.setRangeDatatypeUri(XSD.xstring.toString())
|
||||
.setValidators( list("datatype:" + XSD.xstring.toString()) ));
|
||||
|
||||
conf.addField(new FieldVTwo().setName("personLabelDisplay")
|
||||
.setRangeDatatypeUri(XSD.xstring.toString())
|
||||
.setValidators( list("datatype:" + XSD.xstring.toString()) ));
|
||||
|
||||
FieldVTwo startField = new FieldVTwo().setName("startField");
|
||||
conf.addField(startField.setEditElement(new DateTimeWithPrecisionVTwo(
|
||||
startField, URI_PRECISION_YEAR, URI_PRECISION_NONE)));
|
||||
|
||||
FieldVTwo endField = new FieldVTwo().setName("endField");
|
||||
conf.addField(endField.setEditElement(new DateTimeWithPrecisionVTwo(
|
||||
endField, URI_PRECISION_YEAR, URI_PRECISION_NONE)));
|
||||
|
||||
conf.addValidator(new FirstAndLastNameValidator("existingPerson"));
|
||||
conf.addValidator(new AntiXssValidation());
|
||||
conf.addValidator(new DateTimeIntervalValidationVTwo("startField",
|
||||
"endField"));
|
||||
|
||||
prepare(vreq, conf);
|
||||
return conf;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,449 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.FirstAndLastNameValidator;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeIntervalValidationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo;
|
||||
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.ChildVClassesWithParent;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaVClassOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
|
||||
public class PersonHasAdviseeRelationshipGenerator extends VivoBaseGenerator implements
|
||||
EditConfigurationGenerator {
|
||||
|
||||
final static String advisingRelClass = vivoCore + "AdvisingRelationship";
|
||||
final static String subjAreaClass = "http://www.w3.org/2004/02/skos/core#Concept";
|
||||
final static String degreeClass = vivoCore+"AcademicDegree";
|
||||
final static String advisorClass = foaf + "Person";
|
||||
final static String advisorRoleClass = "http://vivoweb.org/ontology/core#AdvisorRole";
|
||||
final static String adviseeRoleClass = "http://vivoweb.org/ontology/core#AdviseeRole";
|
||||
final static String advisingRelToInterval = vivoCore + "dateTimeInterval";
|
||||
final static String intervalType = vivoCore + "DateTimeInterval";
|
||||
final static String intervalToStart = vivoCore + "start";
|
||||
final static String intervalToEnd = vivoCore + "end";
|
||||
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);
|
||||
|
||||
conf.setTemplate("personHasAdviseeRelationship.ftl");
|
||||
|
||||
conf.setVarNameForSubject("person");
|
||||
conf.setVarNameForPredicate("predicate");
|
||||
conf.setVarNameForObject("adviseeRole");
|
||||
|
||||
conf.setN3Required( Arrays.asList( n3ForNewAdvisingRelationship,
|
||||
advisingRelLabelAssertion,
|
||||
advisingRelTypeAssertion ) );
|
||||
conf.setN3Optional( Arrays.asList( n3ForNewAdvisorAssertion,
|
||||
n3ForExistingAdvisorAssertion,
|
||||
degreeAssertion,
|
||||
firstNameAssertion,
|
||||
lastNameAssertion,
|
||||
n3ForExistingSubjAreaAssertion, //relationship to existing subject area
|
||||
n3ForNewSubjAreaAssertion, //this will include all the new information that needs to be captured
|
||||
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);
|
||||
conf.addNewResource("vcardName", DEFAULT_NS_FOR_NEW_RESOURCE);
|
||||
conf.addNewResource("adviseeRole", DEFAULT_NS_FOR_NEW_RESOURCE);
|
||||
conf.addNewResource("advisorRole", DEFAULT_NS_FOR_NEW_RESOURCE);
|
||||
conf.addNewResource("newSubjArea", 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
|
||||
|
||||
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);
|
||||
conf.addSparqlForExistingUris("existingSubjArea", subjAreaQuery);
|
||||
conf.addSparqlForExistingUris("existingAdvisor", advisorQuery);
|
||||
conf.addSparqlForExistingUris("degree", degreeQuery);
|
||||
conf.addSparqlForExistingUris("intervalNode",existingIntervalNodeQuery);
|
||||
conf.addSparqlForExistingUris("startNode", existingStartNodeQuery);
|
||||
conf.addSparqlForExistingUris("endNode", existingEndNodeQuery);
|
||||
conf.addSparqlForExistingUris("startField-precision", existingStartPrecisionQuery);
|
||||
conf.addSparqlForExistingUris("endField-precision", existingEndPrecisionQuery);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("advisingRelType").
|
||||
setValidators( list("nonempty") ).
|
||||
setOptions( new ChildVClassesWithParent(advisingRelClass))
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("advisingRelLabel").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("firstName").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("lastName").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo(). // options set by auto complete JS
|
||||
setName("existingSubjArea")
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("subjAreaLabel").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("degree").
|
||||
setOptions(
|
||||
new IndividualsViaVClassOptions(degreeClass))
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo(). // options set by auto complete JS
|
||||
setName("existingAdvisor")
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("advisorLabel").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("subjAreaLabelDisplay").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("advisorLabelDisplay").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().setName("startField").
|
||||
setEditElement(
|
||||
new DateTimeWithPrecisionVTwo(null,
|
||||
VitroVocabulary.Precision.YEAR.uri(),
|
||||
VitroVocabulary.Precision.NONE.uri())
|
||||
)
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().setName("endField").
|
||||
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 FirstAndLastNameValidator("existingAdvisor"));
|
||||
addFormSpecificData(conf, vreq);
|
||||
|
||||
prepare(vreq, conf);
|
||||
return conf;
|
||||
}
|
||||
|
||||
/* N3 assertions */
|
||||
|
||||
final static String n3ForNewAdvisingRelationship =
|
||||
"@prefix vivo: <" + vivoCore + "> . \n\n" +
|
||||
"?person <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \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 <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 =
|
||||
"?advisingRelationship <"+ label + "> ?advisingRelLabel .";
|
||||
|
||||
final static String advisingRelTypeAssertion =
|
||||
"?advisingRelationship a ?advisingRelType .";
|
||||
|
||||
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" +
|
||||
"?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?advisorRole . \n" +
|
||||
"?advisorRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . ";
|
||||
|
||||
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" +
|
||||
"?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?advisorRole . \n" +
|
||||
"?advisorRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . ";
|
||||
|
||||
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 vcard:hasName ?vcardName . \n" +
|
||||
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
|
||||
"?vcardName vcard:givenName ?firstName .";
|
||||
|
||||
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 vcard:hasName ?vcardName . \n" +
|
||||
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
|
||||
"?vcardName vcard:familyName ?lastName .";
|
||||
|
||||
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 =
|
||||
"?advisingRelationship <http://vivoweb.org/ontology/core#hasSubjectArea> ?existingSubjArea . \n" +
|
||||
"?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
|
||||
//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 n3ForStart =
|
||||
"?advisingRelationship <" + advisingRelToInterval + "> ?intervalNode . \n" +
|
||||
"?intervalNode a <" + intervalType + "> . \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" +
|
||||
"?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 existingAdvisingRelQuery =
|
||||
"SELECT ?advisingRelationship WHERE { \n" +
|
||||
" ?adviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
|
||||
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?adviseeRole . \n" +
|
||||
"}";
|
||||
|
||||
final static String advisingRelTypeQuery =
|
||||
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
|
||||
"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" +
|
||||
"}";
|
||||
|
||||
final static String advisingRelLabelQuery =
|
||||
"SELECT ?existingAdvisingRelLabel WHERE { \n" +
|
||||
" ?adviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
|
||||
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?adviseeRole . \n" +
|
||||
" ?advisingRelationship <" + label + "> ?existingAdvisingRelLabel . \n" +
|
||||
"}";
|
||||
|
||||
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" +
|
||||
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?existingAdvisor . \n" +
|
||||
" ?existingAdvisor <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
|
||||
" ?existingAdvisor a <" + advisorClass + "> . \n" +
|
||||
" ?existingAdvisor <http://purl.obolibrary.org/obo/RO_0000053> ?existingAdvisorRole . \n" +
|
||||
" ?existingAdvisorRole a <" + advisorRoleClass + "> . \n" +
|
||||
"}";
|
||||
|
||||
final static String advisorLabelQuery =
|
||||
"SELECT ?existingAdvisorLabel 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> ?existingAdvisor . \n" +
|
||||
" ?existingAdvisor <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
|
||||
" ?existingAdvisor a <" + advisorClass + "> . \n" +
|
||||
" ?existingAdvisor <" + label + "> ?existingAdvisorLabel . \n" +
|
||||
" ?existingAdvisor <http://purl.obolibrary.org/obo/RO_0000053> ?existingAdvisorRole . \n" +
|
||||
" ?existingAdvisorRole a <" + advisorRoleClass + "> . \n" +
|
||||
"}";
|
||||
|
||||
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" +
|
||||
"}";
|
||||
|
||||
final static String subjAreaQuery =
|
||||
"SELECT ?existingSubjArea 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#hasSubjectArea> ?existingSubjArea . \n" +
|
||||
" ?existingSubjArea a <http://www.w3.org/2004/02/skos/core#Concept> . \n" +
|
||||
" ?existingSubjArea <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#mostSpecificType> ?type \n" +
|
||||
"}";
|
||||
|
||||
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" +
|
||||
" ?advisingRelationship <http://vivoweb.org/ontology/core#hasSubjectArea> ?existingSubjArea . \n" +
|
||||
" ?existingSubjArea a <http://www.w3.org/2004/02/skos/core#Concept> . \n" +
|
||||
" ?existingSubjArea <" + label + "> ?existingSubjAreaLabel . \n" +
|
||||
" ?existingSubjArea <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#mostSpecificType> ?type \n" +
|
||||
"}";
|
||||
|
||||
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" +
|
||||
" ?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 <" + dateTimeValue + "> ?existingDateStart . }";
|
||||
|
||||
final static String existingEndDateQuery =
|
||||
"SELECT ?existingEndDate 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 <" + dateTimeValue + "> ?existingEndDate . }";
|
||||
|
||||
final static String existingIntervalNodeQuery =
|
||||
"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 =
|
||||
"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" +
|
||||
" ?existingStartNode a <" + dateTimeValueType + "> .} ";
|
||||
|
||||
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 + "> } ";
|
||||
|
||||
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 <" + dateTimePrecision + "> ?existingStartPrecision . }";
|
||||
|
||||
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 <" + dateTimePrecision + "> ?existingEndPrecision . }";
|
||||
|
||||
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
|
||||
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
|
||||
formSpecificData.put("sparqlForAcFilter", getSparqlForAcFilter(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 ?objectVar WHERE { " +
|
||||
"<" + subject + "> <" + predicate + "> ?objectVar .} ";
|
||||
return query;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,451 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.FirstAndLastNameValidator;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeIntervalValidationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo;
|
||||
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.ChildVClassesWithParent;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaVClassOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
|
||||
public class PersonHasAdvisorRelationshipGenerator extends VivoBaseGenerator implements
|
||||
EditConfigurationGenerator {
|
||||
|
||||
final static String advisingRelClass = vivoCore + "AdvisingRelationship";
|
||||
final static String subjAreaClass = "http://www.w3.org/2004/02/skos/core#Concept";
|
||||
final static String degreeClass = vivoCore+"AcademicDegree";
|
||||
final static String adviseeClass = foaf + "Person";
|
||||
final static String adviseeRoleClass = "http://vivoweb.org/ontology/core#AdviseeRole";
|
||||
final static String advisorRoleClass = "http://vivoweb.org/ontology/core#AdvisorRole";
|
||||
final static String advisingRelToInterval = vivoCore + "dateTimeInterval";
|
||||
final static String intervalType = vivoCore + "DateTimeInterval";
|
||||
final static String intervalToStart = vivoCore + "start";
|
||||
final static String intervalToEnd = vivoCore + "end";
|
||||
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);
|
||||
|
||||
conf.setTemplate("personHasAdvisorRelationship.ftl");
|
||||
|
||||
conf.setVarNameForSubject("person");
|
||||
conf.setVarNameForPredicate("predicate");
|
||||
conf.setVarNameForObject("advisorRole");
|
||||
|
||||
conf.setN3Required( Arrays.asList( n3ForNewAdvisingRelationship,
|
||||
advisingRelLabelAssertion,
|
||||
advisingRelTypeAssertion ) );
|
||||
conf.setN3Optional( Arrays.asList( n3ForNewAdviseeAssertion,
|
||||
n3ForExistingAdviseeAssertion,
|
||||
degreeAssertion,
|
||||
firstNameAssertion,
|
||||
lastNameAssertion,
|
||||
n3ForExistingSubjAreaAssertion, //relationship to existing subject area
|
||||
n3ForNewSubjAreaAssertion, //this will include all the new information that needs to be captured
|
||||
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);
|
||||
conf.addNewResource("vcardName", DEFAULT_NS_FOR_NEW_RESOURCE);
|
||||
conf.addNewResource("advisorRole", DEFAULT_NS_FOR_NEW_RESOURCE);
|
||||
conf.addNewResource("adviseeRole", DEFAULT_NS_FOR_NEW_RESOURCE);
|
||||
conf.addNewResource("newSubjArea", 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
|
||||
|
||||
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);
|
||||
conf.addSparqlForExistingUris("existingSubjArea", subjAreaQuery);
|
||||
conf.addSparqlForExistingUris("existingAdvisee", adviseeQuery);
|
||||
conf.addSparqlForExistingUris("degree", degreeQuery);
|
||||
conf.addSparqlForExistingUris("intervalNode",existingIntervalNodeQuery);
|
||||
conf.addSparqlForExistingUris("startNode", existingStartNodeQuery);
|
||||
conf.addSparqlForExistingUris("endNode", existingEndNodeQuery);
|
||||
conf.addSparqlForExistingUris("startField-precision", existingStartPrecisionQuery);
|
||||
conf.addSparqlForExistingUris("endField-precision", existingEndPrecisionQuery);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("advisingRelType").
|
||||
setValidators( list("nonempty") ).
|
||||
setOptions( new ChildVClassesWithParent(advisingRelClass))
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("advisingRelLabel").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("firstName").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("lastName").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo(). // options set by auto complete JS
|
||||
setName("existingSubjArea")
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("subjAreaLabel").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("degree").
|
||||
setOptions(
|
||||
new IndividualsViaVClassOptions(degreeClass))
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo(). // options set by auto complete JS
|
||||
setName("existingAdvisee")
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("adviseeLabel").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("subjAreaLabelDisplay").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("adviseeLabelDisplay").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().setName("startField").
|
||||
setEditElement(
|
||||
new DateTimeWithPrecisionVTwo(null,
|
||||
VitroVocabulary.Precision.YEAR.uri(),
|
||||
VitroVocabulary.Precision.NONE.uri())
|
||||
)
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().setName("endField").
|
||||
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 FirstAndLastNameValidator("existingAdvisee"));
|
||||
addFormSpecificData(conf, vreq);
|
||||
|
||||
prepare(vreq, conf);
|
||||
return conf;
|
||||
}
|
||||
|
||||
/* N3 assertions */
|
||||
|
||||
final static String n3ForNewAdvisingRelationship =
|
||||
"@prefix vivo: <" + vivoCore + "> . \n\n" +
|
||||
"?person <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \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 <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 =
|
||||
"?advisingRelationship <"+ label + "> ?advisingRelLabel .";
|
||||
|
||||
final static String advisingRelTypeAssertion =
|
||||
"?advisingRelationship a ?advisingRelType .";
|
||||
|
||||
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" +
|
||||
"?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?adviseeRole . \n" +
|
||||
"?adviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . ";
|
||||
|
||||
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" +
|
||||
"?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?adviseeRole . \n" +
|
||||
"?adviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . ";
|
||||
|
||||
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 vcard:hasName ?vcardName . \n" +
|
||||
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
|
||||
"?vcardName vcard:givenName ?firstName .";
|
||||
|
||||
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 vcard:hasName ?vcardName . \n" +
|
||||
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
|
||||
"?vcardName vcard:familyName ?lastName .";
|
||||
|
||||
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 =
|
||||
"?advisingRelationship <http://vivoweb.org/ontology/core#hasSubjectArea> ?existingSubjArea . \n" +
|
||||
"?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
|
||||
//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 n3ForStart =
|
||||
"?advisingRelationship <" + advisingRelToInterval + "> ?intervalNode . \n" +
|
||||
"?intervalNode a <" + intervalType + "> . \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" +
|
||||
"?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 existingAdvisingRelQuery =
|
||||
"SELECT ?advisingRelationship WHERE { \n" +
|
||||
" ?advisorRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
|
||||
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?advisorRole . \n" +
|
||||
"}";
|
||||
|
||||
final static String advisingRelTypeQuery =
|
||||
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \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" +
|
||||
"}";
|
||||
|
||||
final static String advisingRelLabelQuery =
|
||||
"SELECT ?existingAdvisingRelLabel WHERE { \n" +
|
||||
" ?advisorRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
|
||||
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?advisorRole . \n" +
|
||||
" ?advisingRelationship <" + label + "> ?existingAdvisingRelLabel . \n" +
|
||||
"}";
|
||||
|
||||
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" +
|
||||
" ?advisingRelationship <http://vivoweb.org/ontology/core#relates> ?existingAdvisee . \n" +
|
||||
" ?existingAdvisee <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
|
||||
" ?existingAdvisee a <" + adviseeClass + "> . \n" +
|
||||
" ?existingAdvisee <http://purl.obolibrary.org/obo/RO_0000053> ?existingAdviseeRole . \n" +
|
||||
" ?existingAdviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
|
||||
" ?existingAdviseeRole a <" + adviseeRoleClass + "> . \n" +
|
||||
"}";
|
||||
|
||||
final static String adviseeLabelQuery =
|
||||
"SELECT ?existingAdviseeLabel 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> ?existingAdvisee . \n" +
|
||||
" ?existingAdvisee <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
|
||||
" ?existingAdvisee a <" + adviseeClass + "> . \n" +
|
||||
" ?existingAdvisee <" + label + "> ?existingAdviseeLabel . \n" +
|
||||
" ?existingAdvisee <http://purl.obolibrary.org/obo/RO_0000053> ?existingAdviseeRole . \n" +
|
||||
" ?existingAdviseeRole <http://vivoweb.org/ontology/core#relatedBy> ?advisingRelationship . \n" +
|
||||
" ?existingAdviseeRole a <" + adviseeRoleClass + "> . \n" +
|
||||
"}";
|
||||
|
||||
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" +
|
||||
"}";
|
||||
|
||||
final static String subjAreaQuery =
|
||||
"SELECT ?existingSubjArea 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#hasSubjectArea> ?existingSubjArea . \n" +
|
||||
" ?existingSubjArea a <http://www.w3.org/2004/02/skos/core#Concept> . \n" +
|
||||
" ?existingSubjArea <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#mostSpecificType> ?type \n" +
|
||||
"}";
|
||||
|
||||
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" +
|
||||
" ?advisingRelationship <http://vivoweb.org/ontology/core#hasSubjectArea> ?existingSubjArea . \n" +
|
||||
" ?existingSubjArea a <http://www.w3.org/2004/02/skos/core#Concept> . \n" +
|
||||
" ?existingSubjArea <" + label + "> ?existingSubjAreaLabel . \n" +
|
||||
" ?existingSubjArea <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#mostSpecificType> ?type \n" +
|
||||
"}";
|
||||
|
||||
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" +
|
||||
" ?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 <" + dateTimeValue + "> ?existingDateStart . }";
|
||||
|
||||
final static String existingEndDateQuery =
|
||||
"SELECT ?existingEndDate 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 <" + dateTimeValue + "> ?existingEndDate . }";
|
||||
|
||||
final static String existingIntervalNodeQuery =
|
||||
"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 =
|
||||
"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" +
|
||||
" ?existingStartNode a <" + dateTimeValueType + "> .} ";
|
||||
|
||||
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 + "> } ";
|
||||
|
||||
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 <" + dateTimePrecision + "> ?existingStartPrecision . }";
|
||||
|
||||
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 <" + dateTimePrecision + "> ?existingEndPrecision . }";
|
||||
|
||||
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
|
||||
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
|
||||
formSpecificData.put("sparqlForAcFilter", getSparqlForAcFilter(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 ?objectVar WHERE { " +
|
||||
"<" + subject + "> <" + predicate + "> ?objectVar .} ";
|
||||
return query;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,359 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.AutocompleteRequiredInputValidator;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeIntervalValidationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo;
|
||||
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.VTwo.fields.IndividualsViaVClassOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
|
||||
public class PersonHasAwardOrHonorGenerator extends VivoBaseGenerator implements
|
||||
EditConfigurationGenerator {
|
||||
|
||||
final static String awardReceiptClass = vivoCore + "AwardReceipt";
|
||||
final static String awardClass = vivoCore + "Award";
|
||||
final static String orgClass = "http://xmlns.com/foaf/0.1/Organization";
|
||||
final static String awardReceiptPred = vivoCore + "relatedBy";
|
||||
final static String awardForPred = vivoCore + "relates";
|
||||
final static String receiptPred =vivoCore+"relatedBy" ;
|
||||
final static String receiptOfPred =vivoCore+"relates" ;
|
||||
final static String awardConferredByPred =vivoCore+"assignedBy" ;
|
||||
final static String awardConferredPred =vivoCore+"assigns" ;
|
||||
final static String descriptionPred = vivoCore + "description";
|
||||
final static String yearAwardedPred = vivoCore + "dateTimeValue";
|
||||
final static String awardReceiptToInterval = vivoCore + "dateTimeInterval";
|
||||
final static String intervalType = vivoCore + "DateTimeInterval";
|
||||
final static String intervalToStart = vivoCore + "start";
|
||||
final static String intervalToEnd = vivoCore + "end";
|
||||
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);
|
||||
|
||||
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,
|
||||
n3ForNewOrgNewAwardAssertion,
|
||||
n3ForExistingOrgNewAwardAssertion,
|
||||
n3ForNewOrgExistingAwardAssertion,
|
||||
n3ForExistingOrgExistingAwardAssertion,
|
||||
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);
|
||||
conf.addNewResource("yearAwardedNode", 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
|
||||
|
||||
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);
|
||||
conf.addSparqlForExistingLiteral("description", descriptionQuery);
|
||||
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("yearAwardedNode",existingYearAwardedNodeQuery);
|
||||
conf.addSparqlForExistingUris("intervalNode",existingIntervalNodeQuery);
|
||||
conf.addSparqlForExistingUris("startNode", existingStartNodeQuery);
|
||||
conf.addSparqlForExistingUris("endNode", existingEndNodeQuery);
|
||||
conf.addSparqlForExistingUris("yearAwarded-precision", existingYearAwardedPrecisionQuery);
|
||||
conf.addSparqlForExistingUris("startField-precision", existingStartPrecisionQuery);
|
||||
conf.addSparqlForExistingUris("endField-precision", existingEndPrecisionQuery);
|
||||
|
||||
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")
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo(). // options will be added in browser by auto complete JS
|
||||
setName("existingAward")
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("awardReceiptLabel").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("orgLabel").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("awardLabel").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()))
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("yearAwardedDisplay").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()))
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("orgLabelDisplay").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()))
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("awardLabelDisplay").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()))
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().setName("yearAwarded").
|
||||
setEditElement(
|
||||
new DateTimeWithPrecisionVTwo(null,
|
||||
VitroVocabulary.Precision.YEAR.uri(),
|
||||
VitroVocabulary.Precision.NONE.uri())
|
||||
)
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().setName("startField").
|
||||
setEditElement(
|
||||
new DateTimeWithPrecisionVTwo(null,
|
||||
VitroVocabulary.Precision.YEAR.uri(),
|
||||
VitroVocabulary.Precision.NONE.uri())
|
||||
)
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().setName("endField").
|
||||
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("existingAward", "awardLabel"));
|
||||
prepare(vreq, conf);
|
||||
return conf;
|
||||
}
|
||||
|
||||
/* N3 assertions */
|
||||
|
||||
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 <"+ label + "> ?awardReceiptLabel .";
|
||||
|
||||
final static String n3ForNewAwardAssertion =
|
||||
"?awardReceipt <" + receiptOfPred + "> ?award . \n" +
|
||||
"?award a <" + awardClass + "> . \n" +
|
||||
"?award <" + receiptPred + "> ?awardReceipt . \n" +
|
||||
"?award <"+ label + "> ?awardLabel .";
|
||||
|
||||
final static String n3ForExistingAwardAssertion =
|
||||
"?awardReceipt <" + receiptOfPred + "> ?existingAward . \n" +
|
||||
"?existingAward <" + receiptPred + "> ?awardReceipt . " ;
|
||||
|
||||
final static String descriptionAssertion =
|
||||
"?awardReceipt <"+ descriptionPred +"> ?description .";
|
||||
|
||||
final static String n3ForExistingOrgNewAwardAssertion =
|
||||
"?awardReceipt <" + awardConferredByPred +"> ?existingOrg . \n" +
|
||||
"?existingOrg <" + awardConferredPred + "> ?awardReceipt . \n" +
|
||||
"?award <"+ label + "> ?awardLabel .";
|
||||
|
||||
final static String n3ForExistingOrgExistingAwardAssertion =
|
||||
"?awardReceipt <" + awardConferredByPred +"> ?existingOrg . \n" +
|
||||
"?existingOrg <" + awardConferredPred + "> ?awardReceipt . ";
|
||||
|
||||
final static String n3ForNewOrgNewAwardAssertion =
|
||||
"?newOrg a <" + orgClass + "> . \n" +
|
||||
"?awardReceipt <" + awardConferredByPred +"> ?newOrg . \n" +
|
||||
"?newOrg <" + awardConferredPred + "> ?awardReceipt . \n" +
|
||||
"?award <"+ label + "> ?awardLabel . \n" +
|
||||
"?newOrg <"+ label + "> ?orgLabel .";
|
||||
|
||||
final static String n3ForNewOrgExistingAwardAssertion =
|
||||
"?newOrg a <" + orgClass + "> . \n" +
|
||||
"?awardReceipt <" + awardConferredByPred +"> ?newOrg . \n" +
|
||||
"?newOrg <" + awardConferredPred + "> ?awardReceipt . \n" +
|
||||
"?newOrg <"+ label + "> ?orgLabel .";
|
||||
|
||||
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" +
|
||||
"?intervalNode a <" + intervalType + "> . \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" +
|
||||
"?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 existingAwardQuery =
|
||||
"SELECT ?existingAward WHERE { \n" +
|
||||
" ?awardReceipt <" + receiptOfPred + "> ?existingAward . \n" +
|
||||
" ?existingAward a <" + awardClass + "> . \n" +
|
||||
"}";
|
||||
|
||||
final static String existingOrgQuery =
|
||||
"SELECT ?existingOrg WHERE { \n" +
|
||||
" ?awardReceipt <" + awardConferredByPred + "> ?existingOrg . \n" +
|
||||
" ?existingOrg a <" + orgClass + "> . \n" +
|
||||
" ?existingOrg <" + awardConferredPred + "> ?existingAward . }";
|
||||
|
||||
final static String awardReceiptLabelQuery =
|
||||
"SELECT ?existingAwardReceiptLabel WHERE { \n" +
|
||||
" ?awardReceipt <" + label + "> ?existingAwardReceiptLabel . \n" +
|
||||
"}";
|
||||
|
||||
final static String awardLabelQuery =
|
||||
"SELECT ?existingAwardLabel WHERE { \n" +
|
||||
" ?awardReceipt <" + receiptOfPred + "> ?existingAward . \n" +
|
||||
" ?existingAward a <" + awardClass + "> . \n" +
|
||||
" ?existingAward <" + label + "> ?existingAwardLabel . \n" +
|
||||
"}";
|
||||
|
||||
final static String orgLabelQuery =
|
||||
"SELECT ?existingOrgLabel WHERE { \n" +
|
||||
" ?awardReceipt <" + awardConferredByPred + "> ?existingOrg . \n" +
|
||||
" ?existingOrg a <" + orgClass + "> . \n" +
|
||||
" ?existingOrg <" + label + "> ?existingOrgLabel . \n" +
|
||||
"}";
|
||||
|
||||
final static String descriptionQuery =
|
||||
"SELECT ?existingDescription WHERE {\n"+
|
||||
" ?awardReceipt <"+ descriptionPred +"> ?existingDescription . }";
|
||||
|
||||
final static String existingYearAwardedQuery =
|
||||
"SELECT ?existingYearAwardedValue WHERE { \n" +
|
||||
" ?awardReceipt <" + yearAwardedPred + "> ?yearAwardedNode . \n" +
|
||||
" ?yearAwardedNode a <" + dateTimeValueType + "> . \n" +
|
||||
" ?yearAwardedNode <" + dateTimeValue + "> ?existingYearAwardedValue }";
|
||||
|
||||
final static String existingYearAwardedNodeQuery =
|
||||
"SELECT ?existingYearAwardedNode WHERE { \n" +
|
||||
" ?awardReceipt <" + yearAwardedPred + "> ?existingYearAwardedNode . }";
|
||||
|
||||
final static String existingStartDateQuery =
|
||||
"SELECT ?existingStartDate WHERE { \n" +
|
||||
" ?awardReceipt <" + awardReceiptToInterval + "> ?intervalNode . \n" +
|
||||
" ?intervalNode a <" + intervalType + "> . \n" +
|
||||
" ?intervalNode <" + intervalToStart + "> ?startNode . \n" +
|
||||
" ?startNode a <" + dateTimeValueType +"> . \n" +
|
||||
" ?startNode <" + dateTimeValue + "> ?existingStartDate . }";
|
||||
|
||||
final static String existingEndDateQuery =
|
||||
"SELECT ?existingEndDate WHERE { \n" +
|
||||
" ?awardReceipt <" + awardReceiptToInterval + "> ?intervalNode . \n" +
|
||||
" ?intervalNode a <" + intervalType + "> . \n " +
|
||||
" ?intervalNode <" + intervalToEnd + "> ?endNode . \n" +
|
||||
" ?endNode a <" + dateTimeValueType + "> . \n" +
|
||||
" ?endNode <" + dateTimeValue + "> ?existingEndDate . }";
|
||||
|
||||
final static String existingIntervalNodeQuery =
|
||||
"SELECT ?existingIntervalNode WHERE { \n" +
|
||||
" ?awardReceipt <" + awardReceiptToInterval + "> ?existingIntervalNode . \n" +
|
||||
" ?existingIntervalNode a <" + intervalType + "> . }";
|
||||
|
||||
final static String existingStartNodeQuery =
|
||||
"SELECT ?existingStartNode WHERE { \n" +
|
||||
" ?awardReceipt <" + awardReceiptToInterval + "> ?intervalNode . \n" +
|
||||
" ?intervalNode a <" + intervalType + "> . \n" +
|
||||
" ?intervalNode <" + intervalToStart + "> ?existingStartNode . \n" +
|
||||
" ?existingStartNode a <" + dateTimeValueType + "> . } ";
|
||||
|
||||
final static String existingEndNodeQuery =
|
||||
"SELECT ?existingEndNode WHERE { \n" +
|
||||
" ?awardReceipt <" + awardReceiptToInterval + "> ?intervalNode . \n" +
|
||||
" ?intervalNode a <" + intervalType + "> . \n" +
|
||||
" ?intervalNode <" + intervalToEnd + "> ?existingEndNode . \n" +
|
||||
" ?existingEndNode a <" + dateTimeValueType + "> } ";
|
||||
|
||||
final static String existingYearAwardedPrecisionQuery =
|
||||
"SELECT ?existingYearAwardedPrecision WHERE { \n" +
|
||||
" ?awardReceipt <" + yearAwardedPred + "> ?yearAwarded . \n" +
|
||||
" ?yearAwarded a <" + dateTimeValueType + "> . \n" +
|
||||
" ?yearAwarded <" + dateTimePrecision + "> ?existingYearAwardedPrecision . }";
|
||||
|
||||
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 <" + dateTimePrecision + "> ?existingStartPrecision . }";
|
||||
|
||||
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 <" + dateTimePrecision + "> ?existingEndPrecision . }";
|
||||
|
||||
}
|
|
@ -0,0 +1,400 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
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 javax.servlet.http.HttpSession;
|
||||
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeIntervalValidationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ChildVClassesOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ChildVClassesWithParent;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaVClassOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils.EditMode;
|
||||
import edu.cornell.mannlib.vitro.webapp.utils.generators.EditModeUtils;
|
||||
|
||||
/**
|
||||
Form for adding an educational attainment to an individual
|
||||
|
||||
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.
|
||||
|
||||
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
|
||||
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{
|
||||
|
||||
//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);
|
||||
|
||||
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
|
||||
//literals in scope: none
|
||||
|
||||
conf.setUrisOnform( Arrays.asList( "existingOrg", "orgType", "degreeType", "trainingType"));
|
||||
conf.setLiteralsOnForm( Arrays.asList("orgLabel", "orgLabelDisplay", "awardedDegreeLabel",
|
||||
"majorField", "dept", "info"));
|
||||
|
||||
conf.addSparqlForExistingLiteral("orgLabel", orgLabelQuery);
|
||||
// conf.addSparqlForExistingLiteral("existingAwardedDegreeLabel", existingAwardedDegreeLabelQuery);
|
||||
conf.addSparqlForExistingLiteral("majorField", majorFieldQuery);
|
||||
conf.addSparqlForExistingLiteral("dept", deptQuery);
|
||||
conf.addSparqlForExistingLiteral("info", infoQuery);
|
||||
conf.addSparqlForExistingLiteral("startField-value", existingStartDateQuery);
|
||||
conf.addSparqlForExistingLiteral("endField-value", existingEndDateQuery);
|
||||
|
||||
|
||||
conf.addSparqlForExistingUris("awardedDegree", existingAwardedDegreeQuery);
|
||||
conf.addSparqlForExistingUris("existingOrg", existingOrgQuery);
|
||||
conf.addSparqlForExistingUris("orgType", orgTypeQuery);
|
||||
conf.addSparqlForExistingUris("trainingType", trainingTypeQuery);
|
||||
conf.addSparqlForExistingUris("degreeType", degreeTypeQuery);
|
||||
conf.addSparqlForExistingUris("intervalNode",existingIntervalNodeQuery);
|
||||
conf.addSparqlForExistingUris("startNode", existingStartNodeQuery);
|
||||
conf.addSparqlForExistingUris("endNode", existingEndNodeQuery);
|
||||
conf.addSparqlForExistingUris("startField-precision", existingStartPrecisionQuery);
|
||||
conf.addSparqlForExistingUris("endField-precision", existingEndPrecisionQuery);
|
||||
//Add sparql to include inverse property as well
|
||||
conf.addSparqlForAdditionalUrisInScope("inverseTrainingAtOrg", inverseTrainingAtOrgQuery);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("degreeType").
|
||||
setOptions( new IndividualsViaVClassOptions(
|
||||
degreeTypeClass)));
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
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
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("awardedDegree")
|
||||
//options will be added in browser by auto complete JS
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("orgLabel").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString())));
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("awardedDegreeLabel").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString())));
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
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(
|
||||
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() ).
|
||||
setValidators(list("datatype:" + XSD.xstring.toString())));
|
||||
|
||||
FieldVTwo startField = new FieldVTwo().
|
||||
setName("startField");
|
||||
conf.addField(startField.
|
||||
setEditElement(
|
||||
new DateTimeWithPrecisionVTwo(startField,
|
||||
VitroVocabulary.Precision.YEAR.uri(),
|
||||
VitroVocabulary.Precision.NONE.uri())));
|
||||
|
||||
FieldVTwo endField = new FieldVTwo().
|
||||
setName("endField");
|
||||
conf.addField( endField.
|
||||
setEditElement(
|
||||
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 =
|
||||
"@prefix core: <"+ vivoCore +"> .\n"+
|
||||
"?person <http://purl.obolibrary.org/obo/RO_0000056> ?edTraining .\n" +
|
||||
"?edTraining a core:EducationalProcess .\n" +
|
||||
"?edTraining <http://purl.obolibrary.org/obo/RO_0000057> ?person .";
|
||||
|
||||
final static String trainingTypeAssertion =
|
||||
"?edTraining a ?trainingType .";
|
||||
|
||||
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" +
|
||||
"?awardedDegree <http://vivoweb.org/ontology/core#relates> ?person . \n" +
|
||||
"?person <http://vivoweb.org/ontology/core#relatedBy> ?awardedDegree . \n" +
|
||||
"?awardedDegree <"+ label +"> ?awardedDegreeLabel . \n" +
|
||||
"?awardedDegree <http://vivoweb.org/ontology/core#relates> ?degreeType .\n"+
|
||||
"?degreeType <http://vivoweb.org/ontology/core#relatedBy> ?awardedDegree . \n"+
|
||||
"?awardedDegree a core:AwardedDegree .";
|
||||
|
||||
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 =
|
||||
"?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 =
|
||||
"?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 =
|
||||
"?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 =
|
||||
"?edTraining <"+ majorFieldPred +"> ?majorField .";
|
||||
|
||||
final static String n3ForStart =
|
||||
"?edTraining <"+ toInterval +"> ?intervalNode .\n"+
|
||||
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
|
||||
"?intervalNode <"+ intervalToStart +"> ?startNode .\n"+
|
||||
"?startNode <"+ type +"> <"+ dateTimeValueType +"> .\n"+
|
||||
"?startNode <"+ dateTimeValue +"> ?startField-value .\n"+
|
||||
"?startNode <"+ dateTimePrecision +"> ?startField-precision .";
|
||||
|
||||
final static String n3ForEnd =
|
||||
"?edTraining <"+ toInterval +"> ?intervalNode . \n"+
|
||||
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
|
||||
"?intervalNode <"+ intervalToEnd +"> ?endNode .\n"+
|
||||
"?endNode <"+ type +"> <"+ dateTimeValueType +"> .\n"+
|
||||
"?endNode <"+ dateTimeValue +"> ?endField-value .\n"+
|
||||
"?endNode <"+ dateTimePrecision +"> ?endField-precision .";
|
||||
|
||||
final static String deptAssertion =
|
||||
"?edTraining <"+ deptPred +"> ?dept .";
|
||||
|
||||
final static String infoAssertion =
|
||||
"?edTraining <"+ infoPred +"> ?info .";
|
||||
|
||||
/* Queries for editing an existing educational training entry */
|
||||
|
||||
final static String existingAwardedDegreeQuery =
|
||||
"SELECT ?existingAwardedDegree WHERE {\n"+
|
||||
"?edTraining <http://purl.obolibrary.org/obo/RO_0002234> ?existingAwardedDegree . }\n";
|
||||
|
||||
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 =
|
||||
"PREFIX rdfs: <"+ rdfs +"> \n"+
|
||||
"SELECT ?existingOrg WHERE {\n"+
|
||||
"?edTraining <http://purl.obolibrary.org/obo/RO_0000057> ?existingOrg . \n" +
|
||||
"?existingOrg <http://purl.obolibrary.org/obo/RO_0000056> ?edTraining . \n" +
|
||||
"?existingOrg a ?existingOrgType . \n " +
|
||||
"?existingOrgType rdfs:subClassOf <"+ orgClass +"> . }";
|
||||
|
||||
final static String orgLabelQuery =
|
||||
"PREFIX rdfs: <"+ rdfs +"> \n"+
|
||||
"SELECT ?existingOrgLabel WHERE {\n"+
|
||||
"?edTraining <http://purl.obolibrary.org/obo/RO_0000057> ?existingOrg . \n" +
|
||||
"?existingOrg <http://purl.obolibrary.org/obo/RO_0000056> ?edTraining .\n"+
|
||||
"?existingOrg <"+ label +"> ?existingOrgLabel .\n"+
|
||||
"?existingOrg a ?existingOrgType . \n " +
|
||||
"?existingOrgType rdfs:subClassOf <"+ orgClass +"> . }";
|
||||
|
||||
/* 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 =
|
||||
"PREFIX rdfs: <"+ rdfs +"> \n"+
|
||||
"SELECT ?existingOrgType WHERE {\n"+
|
||||
"?edTraining <http://purl.obolibrary.org/obo/RO_0000057> ?existingOrg . \n" +
|
||||
"?existingOrg <http://purl.obolibrary.org/obo/RO_0000056> ?edTraining .\n"+
|
||||
"?existingOrg a ?existingOrgType .\n"+
|
||||
"?existingOrgType rdfs:subClassOf <"+ orgClass +"> .\n"+
|
||||
"}";
|
||||
|
||||
final static String trainingTypeQuery =
|
||||
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
|
||||
"SELECT ?existingTrainingType WHERE { \n" +
|
||||
" ?edTraining vitro:mostSpecificType ?existingTrainingType . }";
|
||||
|
||||
final static String degreeTypeQuery =
|
||||
"PREFIX core: <"+ vivoCore +"> \n"+
|
||||
"SELECT ?existingDegreeType WHERE {\n"+
|
||||
"?edTraining <http://purl.obolibrary.org/obo/RO_0002234> ?existingAwardedDegree . \n"+
|
||||
"?existingAwardedDegree a core:AwardedDegree . \n"+
|
||||
"?existingAwardedDegree core:relates ?existingDegreeType . \n" +
|
||||
"?existingDegreeType a core:AcademicDegree }";
|
||||
|
||||
final static String majorFieldQuery =
|
||||
"SELECT ?existingMajorField WHERE {\n"+
|
||||
"?edTraining <"+ majorFieldPred +"> ?existingMajorField . }";
|
||||
|
||||
final static String deptQuery =
|
||||
"SELECT ?existingDept WHERE {\n"+
|
||||
"?edTraining <"+ deptPred +"> ?existingDept . }";
|
||||
|
||||
final static String infoQuery =
|
||||
"SELECT ?existingInfo WHERE {\n"+
|
||||
"?edTraining <"+ infoPred +"> ?existingInfo . }";
|
||||
|
||||
final static String existingIntervalNodeQuery =
|
||||
"SELECT ?existingIntervalNode WHERE {\n"+
|
||||
"?edTraining <"+ toInterval +"> ?existingIntervalNode .\n"+
|
||||
"?existingIntervalNode <"+ type +"> <"+ intervalType +"> . }";
|
||||
|
||||
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 =
|
||||
"SELECT ?existingDateStart WHERE {\n"+
|
||||
"?edTraining <"+ toInterval +"> ?intervalNode .\n"+
|
||||
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
|
||||
"?intervalNode <"+ intervalToStart +"> ?startNode .\n"+
|
||||
"?startNode <"+ type +"> <"+ dateTimeValueType +"> .\n"+
|
||||
"?startNode <"+ dateTimeValue +"> ?existingDateStart . }";
|
||||
|
||||
final static String existingStartPrecisionQuery =
|
||||
"SELECT ?existingStartPrecision WHERE {\n"+
|
||||
"?edTraining <"+ toInterval +"> ?intervalNode .\n"+
|
||||
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
|
||||
"?intervalNode <"+ intervalToStart +"> ?startNode .\n"+
|
||||
"?startNode <"+ type +"> <"+ dateTimeValueType +"> . \n"+
|
||||
"?startNode <"+ dateTimePrecision +"> ?existingStartPrecision . }";
|
||||
|
||||
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 =
|
||||
"SELECT ?existingEndDate WHERE {\n"+
|
||||
"?edTraining <"+ toInterval +"> ?intervalNode .\n"+
|
||||
"?intervalNode <"+ type +"> <"+ intervalType +"> .\n"+
|
||||
"?intervalNode <"+ intervalToEnd +"> ?endNode .\n"+
|
||||
"?endNode <"+ type +"> <"+ dateTimeValueType +"> .\n"+
|
||||
"?endNode <"+ dateTimeValue +"> ?existingEndDate . }";
|
||||
|
||||
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");
|
||||
return EditModeUtils.getEditMode(vreq, predicates);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,125 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
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 com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
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.ChildVClassesOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaVClassOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
|
||||
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);
|
||||
|
||||
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 ) );
|
||||
}
|
||||
else {
|
||||
conf.setN3Required( Arrays.asList( n3ForNewEmail ) );
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
if ( conf.isUpdate() ) {
|
||||
HashMap<String, List<String>> urisInScope = new HashMap<String, List<String>>();
|
||||
urisInScope.put("email", Arrays.asList(new String[]{emailUri}));
|
||||
conf.addUrisInScope(urisInScope);
|
||||
}
|
||||
|
||||
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 =
|
||||
"?person <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> ?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 =
|
||||
"?person <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> ?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> ." ;
|
||||
|
||||
final static String emailAddressAssertion =
|
||||
"?email <http://www.w3.org/2006/vcard/ns#email> ?emailAddress .";
|
||||
|
||||
/* Queries for editing an existing entry */
|
||||
|
||||
final static String individualVcardQuery =
|
||||
"SELECT ?existingIndividualVcard WHERE { \n" +
|
||||
"?person <http://purl.obolibrary.org/obo/ARG_2000028> ?existingIndividualVcard . \n" +
|
||||
"}";
|
||||
|
||||
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");
|
||||
|
||||
return rangeUri;
|
||||
}
|
||||
private String getEmailUri(VitroRequest vreq) {
|
||||
String emailUri = vreq.getParameter("emailUri");
|
||||
|
||||
return emailUri;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,332 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.AutocompleteRequiredInputValidator;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeIntervalValidationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ChildVClassesWithParent;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ConstantFieldOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaVClassOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
|
||||
public class PersonHasIssuedCredentialGenerator extends VivoBaseGenerator implements
|
||||
EditConfigurationGenerator {
|
||||
|
||||
final static String issuedCredentialTypeClass = vivoCore + "IssuedCredential";
|
||||
final static String credentialTypeClass = vivoCore + "Credential";
|
||||
final static String yearCredentialedPred = vivoCore + "dateIssued";
|
||||
final static String issuedCredentialToInterval = vivoCore + "dateTimeInterval";
|
||||
final static String intervalType = vivoCore + "DateTimeInterval";
|
||||
final static String intervalToStart = vivoCore + "start";
|
||||
final static String intervalToEnd = vivoCore + "end";
|
||||
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);
|
||||
|
||||
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,
|
||||
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
|
||||
|
||||
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);
|
||||
conf.addSparqlForExistingUris("yearCredentialedNode",existingYearCredentialedNodeQuery);
|
||||
conf.addSparqlForExistingUris("intervalNode",existingIntervalNodeQuery);
|
||||
conf.addSparqlForExistingUris("startNode", existingStartNodeQuery);
|
||||
conf.addSparqlForExistingUris("endNode", existingEndNodeQuery);
|
||||
conf.addSparqlForExistingUris("yearCredentialed-precision", existingYearCredentialedPrecisionQuery);
|
||||
conf.addSparqlForExistingUris("startField-precision", existingStartPrecisionQuery);
|
||||
conf.addSparqlForExistingUris("endField-precision", existingEndPrecisionQuery);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("issuedCredentialType").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()))
|
||||
);
|
||||
|
||||
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").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("yearCredentialedDisplay").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()))
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("credentialLabelDisplay").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()))
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().setName("yearCredentialed").
|
||||
setEditElement(
|
||||
new DateTimeWithPrecisionVTwo(null,
|
||||
VitroVocabulary.Precision.YEAR.uri(),
|
||||
VitroVocabulary.Precision.NONE.uri())
|
||||
)
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().setName("startField").
|
||||
setEditElement(
|
||||
new DateTimeWithPrecisionVTwo(null,
|
||||
VitroVocabulary.Precision.YEAR.uri(),
|
||||
VitroVocabulary.Precision.NONE.uri())
|
||||
)
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().setName("endField").
|
||||
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("existingCredential", "credentialLabel"));
|
||||
|
||||
addFormSpecificData(conf, vreq);
|
||||
prepare(vreq, conf);
|
||||
return conf;
|
||||
}
|
||||
|
||||
/* N3 assertions */
|
||||
|
||||
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 ?issuedCredentialType .";
|
||||
|
||||
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" +
|
||||
"?issuedCredential vivo:relates ?existingCredential . \n" +
|
||||
/* "?existingCredential a <" + credentialTypeClass + "> . \n" +
|
||||
"?existingCredential a ?credentialType . \n" + */
|
||||
"?existingCredential vivo:relatedBy ?issuedCredential . " ;
|
||||
|
||||
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" +
|
||||
"?intervalNode a <" + intervalType + "> . \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" +
|
||||
"?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 existingCredentialQuery =
|
||||
"PREFIX vivo: <http://vivoweb.org/ontology/core#> \n" +
|
||||
"SELECT ?existingCredential WHERE { \n" +
|
||||
" ?issuedCredential vivo:relates ?existingCredential . \n" +
|
||||
" ?existingCredential a vivo:Credential . \n" +
|
||||
"}";
|
||||
|
||||
final static String existingCredentialTypeQuery =
|
||||
"PREFIX vivo: <http://vivoweb.org/ontology/core#> \n" +
|
||||
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
|
||||
"SELECT ?existingCredentialType WHERE { \n" +
|
||||
" ?issuedCredential vivo:relates ?existingCredential . \n" +
|
||||
" ?existingCredential a vivo:Credential . \n" +
|
||||
" ?existingCredential vitro:mostSpecificType ?existingCredentialType . \n" +
|
||||
"}";
|
||||
|
||||
final static String issuedCredentialTypeQuery =
|
||||
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
|
||||
"SELECT ?existingICType WHERE { \n" +
|
||||
" ?issuedCredential vitro:mostSpecificType ?existingICType . \n" +
|
||||
"}";
|
||||
|
||||
final static String credentialLabelQuery =
|
||||
"PREFIX vivo: <http://vivoweb.org/ontology/core#> \n" +
|
||||
"SELECT ?existingCredentialLabel WHERE { \n" +
|
||||
" ?issuedCredential vivo:relates ?existingCredential . \n" +
|
||||
" ?existingCredential a <http://vivoweb.org/ontology/core#Credential> . \n" +
|
||||
" ?existingCredential <" + label + "> ?existingCredentialLabel . \n" +
|
||||
"}";
|
||||
|
||||
final static String existingYearCredentialedQuery =
|
||||
"SELECT ?existingYearCredentialedValue WHERE { \n" +
|
||||
" ?issuedCredential <" + yearCredentialedPred + "> ?yearCredentialedNode . \n" +
|
||||
" ?yearCredentialedNode a <" + dateTimeValueType + "> . \n" +
|
||||
" ?yearCredentialedNode <" + dateTimeValue + "> ?existingYearCredentialedValue }";
|
||||
|
||||
final static String existingYearCredentialedNodeQuery =
|
||||
"SELECT ?existingYearCredentialedNode WHERE { \n" +
|
||||
" ?issuedCredential <" + yearCredentialedPred + "> ?existingYearCredentialedNode . }";
|
||||
|
||||
final static String existingStartDateQuery =
|
||||
"SELECT ?existingStartDate WHERE { \n" +
|
||||
" ?issuedCredential <" + issuedCredentialToInterval + "> ?intervalNode . \n" +
|
||||
" ?intervalNode a <" + intervalType + "> . \n" +
|
||||
" ?intervalNode <" + intervalToStart + "> ?startNode . \n" +
|
||||
" ?startNode a <" + dateTimeValueType +"> . \n" +
|
||||
" ?startNode <" + dateTimeValue + "> ?existingStartDate . }";
|
||||
|
||||
final static String existingEndDateQuery =
|
||||
"SELECT ?existingEndDate WHERE { \n" +
|
||||
" ?issuedCredential <" + issuedCredentialToInterval + "> ?intervalNode . \n" +
|
||||
" ?intervalNode a <" + intervalType + "> . \n " +
|
||||
" ?intervalNode <" + intervalToEnd + "> ?endNode . \n" +
|
||||
" ?endNode a <" + dateTimeValueType + "> . \n" +
|
||||
" ?endNode <" + dateTimeValue + "> ?existingEndDate . }";
|
||||
|
||||
final static String existingIntervalNodeQuery =
|
||||
"SELECT ?existingIntervalNode WHERE { \n" +
|
||||
" ?issuedCredential <" + issuedCredentialToInterval + "> ?existingIntervalNode . \n" +
|
||||
" ?existingIntervalNode a <" + intervalType + "> . }";
|
||||
|
||||
final static String existingStartNodeQuery =
|
||||
"SELECT ?existingStartNode WHERE { \n" +
|
||||
" ?issuedCredential <" + issuedCredentialToInterval + "> ?intervalNode . \n" +
|
||||
" ?intervalNode a <" + intervalType + "> . \n" +
|
||||
" ?intervalNode <" + intervalToStart + "> ?existingStartNode . \n" +
|
||||
" ?existingStartNode a <" + dateTimeValueType + "> . } ";
|
||||
|
||||
final static String existingEndNodeQuery =
|
||||
"SELECT ?existingEndNode WHERE { \n" +
|
||||
" ?issuedCredential <" + issuedCredentialToInterval + "> ?intervalNode . \n" +
|
||||
" ?intervalNode a <" + intervalType + "> . \n" +
|
||||
" ?intervalNode <" + intervalToEnd + "> ?existingEndNode . \n" +
|
||||
" ?existingEndNode a <" + dateTimeValueType + "> } ";
|
||||
|
||||
final static String existingYearCredentialedPrecisionQuery =
|
||||
"SELECT ?existingYearCredentialedPrecision WHERE { \n" +
|
||||
" ?issuedCredential <" + yearCredentialedPred + "> ?yearCredentialed . \n" +
|
||||
" ?yearCredentialed a <" + dateTimeValueType + "> . \n" +
|
||||
" ?yearCredentialed <" + dateTimePrecision + "> ?existingYearCredentialedPrecision . }";
|
||||
|
||||
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 <" + dateTimePrecision + "> ?existingStartPrecision . }";
|
||||
|
||||
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 <" + dateTimePrecision + "> ?existingEndPrecision . }";
|
||||
|
||||
//Form specific data
|
||||
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
|
||||
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
|
||||
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
|
||||
// credential. This map makes that possible. The class name of the credential is on the right, and the URI
|
||||
// of th eissued credential is on the left.
|
||||
private HashMap<String, String> getCredentialTypeMap() {
|
||||
HashMap<String, String> credentials = new HashMap<String, String>();
|
||||
credentials.put("Credential","http://vivoweb.org/ontology/core#IssuedCredential");
|
||||
credentials.put("Certificate","http://vivoweb.org/ontology/core#Certification");
|
||||
credentials.put("License","http://vivoweb.org/ontology/core#Licensure");
|
||||
return credentials;
|
||||
}
|
||||
private FieldOptions getCredentialTypeFieldOptions(VitroRequest vreq) throws Exception {
|
||||
return new ConstantFieldOptions(
|
||||
"http://vivoweb.org/ontology/core#Certificate", "Certificate",
|
||||
"http://vivoweb.org/ontology/core#Credential", "Credential",
|
||||
"http://vivoweb.org/ontology/core#License", "License");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,301 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
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 javax.servlet.http.HttpSession;
|
||||
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.AutocompleteRequiredInputValidator;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeIntervalValidationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ChildVClassesOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ChildVClassesWithParent;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaVClassOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils.EditMode;
|
||||
import edu.cornell.mannlib.vitro.webapp.utils.generators.EditModeUtils;
|
||||
|
||||
public class PersonHasPositionHistoryGenerator extends VivoBaseGenerator implements
|
||||
EditConfigurationGenerator {
|
||||
|
||||
final static String positionClass = vivoCore + "Position";
|
||||
final static String orgClass = "http://xmlns.com/foaf/0.1/Organization";
|
||||
final static String positionInOrgPred = vivoCore + "relates";
|
||||
final static String orgForPositionPred = vivoCore + "relatedBy";
|
||||
final static String positionToInterval = vivoCore + "dateTimeInterval";
|
||||
final static String intervalType = vivoCore + "DateTimeInterval";
|
||||
final static String intervalToStart = vivoCore + "start";
|
||||
final static String intervalToEnd = vivoCore + "end";
|
||||
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 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
|
||||
// but the form should be expanded.
|
||||
//
|
||||
// 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);
|
||||
|
||||
conf.setTemplate("personHasPositionHistory.ftl");
|
||||
|
||||
conf.setVarNameForSubject("person");
|
||||
conf.setVarNameForPredicate("predicate");
|
||||
conf.setVarNameForObject("position");
|
||||
|
||||
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
|
||||
//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);
|
||||
conf.addSparqlForExistingUris(
|
||||
"intervalNode", existingIntervalNodeQuery);
|
||||
conf.addSparqlForExistingUris("startNode", existingStartNodeQuery);
|
||||
conf.addSparqlForExistingUris("endNode", existingEndNodeQuery);
|
||||
conf.addSparqlForExistingUris("startField-precision",
|
||||
existingStartPrecisionQuery);
|
||||
conf.addSparqlForExistingUris("endField-precision",
|
||||
existingEndPrecisionQuery);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("positionTitle")
|
||||
.setRangeDatatypeUri( XSD.xstring.toString() ).
|
||||
setValidators( list("nonempty") ) );
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("positionType").
|
||||
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() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) ) );
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("orgLabelDisplay").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ) );
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("orgType").
|
||||
setOptions(
|
||||
new ChildVClassesWithParent(orgClass)));
|
||||
|
||||
conf.addField( new FieldVTwo().setName("startField").
|
||||
setEditElement(
|
||||
new DateTimeWithPrecisionVTwo(null,
|
||||
VitroVocabulary.Precision.YEAR.uri(),
|
||||
VitroVocabulary.Precision.NONE.uri())
|
||||
)
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().setName("endField").
|
||||
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" +
|
||||
"?person core:relatedBy ?position . \n" +
|
||||
"?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 =
|
||||
"?position <" + positionInOrgPred + "> ?newOrg . \n" +
|
||||
"?newOrg <" + orgForPositionPred + "> ?position . \n" +
|
||||
"?newOrg <" + label + "> ?orgLabel . \n" +
|
||||
"?newOrg a ?orgType .";
|
||||
|
||||
final static String n3ForExistingOrg =
|
||||
"?position <" + positionInOrgPred + "> ?existingOrg . \n" +
|
||||
"?existingOrg <" + orgForPositionPred + "> ?position . \n" +
|
||||
"?existingOrg a ?orgType .";
|
||||
|
||||
final static String n3ForStart =
|
||||
"?position <" + positionToInterval + "> ?intervalNode . \n" +
|
||||
"?intervalNode a <" + intervalType + "> . \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" +
|
||||
"?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
|
||||
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" +
|
||||
" ?intervalNode a <" + intervalType + "> . \n" +
|
||||
" ?intervalNode <" + intervalToStart + "> ?startNode . \n" +
|
||||
" ?startNode a <" + dateTimeValueType +"> . \n" +
|
||||
" ?startNode <" + dateTimeValue + "> ?existingDateStart . }";
|
||||
|
||||
final static String existingEndDateQuery =
|
||||
"SELECT ?existingEndDate WHERE { \n" +
|
||||
" ?position <" + positionToInterval + "> ?intervalNode . \n" +
|
||||
" ?intervalNode a <" + intervalType + "> . \n " +
|
||||
" ?intervalNode <" + intervalToEnd + "> ?endNode . \n" +
|
||||
" ?endNode a <" + dateTimeValueType + "> . \n" +
|
||||
" ?endNode <" + dateTimeValue + "> ?existingEndDate . }";
|
||||
|
||||
final static String existingOrgQuery =
|
||||
"SELECT ?existingOrg WHERE { \n" +
|
||||
" ?position <" + positionInOrgPred + "> ?existingOrg . \n" +
|
||||
" ?existingOrg a <" + orgClass + "> }";
|
||||
|
||||
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 =
|
||||
"PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" +
|
||||
"SELECT ?existingPositionType WHERE { \n" +
|
||||
" ?position vitro:mostSpecificType ?existingPositionType . }";
|
||||
|
||||
final static String existingIntervalNodeQuery =
|
||||
"SELECT ?existingIntervalNode WHERE { \n" +
|
||||
" ?position <" + positionToInterval + "> ?existingIntervalNode . \n" +
|
||||
" ?existingIntervalNode a <" + intervalType + "> . }";
|
||||
|
||||
final static String existingStartNodeQuery =
|
||||
"SELECT ?existingStartNode WHERE { \n" +
|
||||
" ?position <" + positionToInterval + "> ?intervalNode . \n" +
|
||||
" ?intervalNode a <" + intervalType + "> . \n" +
|
||||
" ?intervalNode <" + intervalToStart + "> ?existingStartNode . \n" +
|
||||
" ?existingStartNode a <" + dateTimeValueType + "> .} ";
|
||||
|
||||
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 =
|
||||
"SELECT ?existingStartPrecision WHERE { \n" +
|
||||
" ?position <" + positionToInterval + "> ?intervalNode . \n" +
|
||||
" ?intervalNode a <" + intervalType + "> . \n" +
|
||||
" ?intervalNode <" + intervalToStart + "> ?startNode . \n" +
|
||||
" ?startNode a <" + dateTimeValueType + "> . \n" +
|
||||
" ?startNode <" + dateTimePrecision + "> ?existingStartPrecision . }";
|
||||
|
||||
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 <" + 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>();
|
||||
formSpecificData.put("editMode", getEditMode(vreq).name().toLowerCase());
|
||||
editConfiguration.setFormSpecificData(formSpecificData);
|
||||
}
|
||||
|
||||
public EditMode getEditMode(VitroRequest vreq) {
|
||||
List<String> predicates = new ArrayList<String>();
|
||||
predicates.add(positionInOrgPred);
|
||||
return EditModeUtils.getEditMode(vreq, predicates);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,105 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
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 com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
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.ChildVClassesOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaVClassOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
|
||||
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);
|
||||
|
||||
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().
|
||||
setName("preferredTitle")
|
||||
.setRangeDatatypeUri( XSD.xstring.toString() ).
|
||||
setValidators( list("nonempty") ));
|
||||
|
||||
conf.addValidator(new AntiXssValidation());
|
||||
|
||||
prepare(vreq, conf);
|
||||
return conf;
|
||||
}
|
||||
|
||||
/* N3 assertions */
|
||||
|
||||
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 <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 <http://www.w3.org/2006/vcard/ns#title> ?preferredTitle .";
|
||||
|
||||
/* Queries for editing an existing entry */
|
||||
|
||||
final static String individualVcardQuery =
|
||||
"SELECT ?existingIndividualVcard WHERE { \n" +
|
||||
"?person <http://purl.obolibrary.org/obo/ARG_2000028> ?existingIndividualVcard . \n" +
|
||||
"}";
|
||||
|
||||
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");
|
||||
|
||||
return titleUri;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,184 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
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 javax.servlet.http.HttpSession;
|
||||
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.FirstAndLastNameValidator;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeIntervalValidationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ChildVClassesOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ChildVClassesWithParent;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaVClassOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
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{
|
||||
|
||||
//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);
|
||||
|
||||
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
|
||||
//literals in scope: none
|
||||
|
||||
conf.setUrisOnform( Arrays.asList( "existingPerson"));
|
||||
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
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("personLabel").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString())));
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("roleLabel").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString(),"nonempty")));
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("personLabelDisplay").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ));
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("roleLabelDisplay").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ));
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("firstName").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("lastName").
|
||||
setRangeDatatypeUri(XSD.xstring.toString() ).
|
||||
setValidators( list("datatype:" + XSD.xstring.toString()) )
|
||||
);
|
||||
|
||||
//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 =
|
||||
"@prefix core: <"+ vivoCore +"> .\n" +
|
||||
"@prefix rdfs: <"+ rdfs +"> . \n"+
|
||||
"?project <http://purl.obolibrary.org/obo/BFO_0000055> ?projectRole .\n" +
|
||||
"?projectRole a <http://vivoweb.org/ontology/core#ResearcherRole> .\n" +
|
||||
"?projectRole <http://purl.obolibrary.org/obo/BFO_0000054> ?project . \n" +
|
||||
"?projectRole <"+ label +"> ?roleLabel . \n" ;
|
||||
|
||||
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 =
|
||||
"?projectRole <http://purl.obolibrary.org/obo/RO_0000052> ?existingPerson . \n" +
|
||||
"?existingPerson <http://purl.obolibrary.org/obo/RO_0000053> ?projectRole . \n" +
|
||||
" ";
|
||||
|
||||
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 vcard:hasName ?vcardName . \n" +
|
||||
"?vcardName a <http://www.w3.org/2006/vcard/ns#Name> . \n" +
|
||||
"?vcardName vcard:givenName ?firstName .";
|
||||
|
||||
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 vcard:hasName ?vcardName . \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 =
|
||||
"SELECT ?roleLabel WHERE {\n"+
|
||||
"?projectRole <"+ label +"> ?roleLabel }\n";
|
||||
|
||||
final static String existingPersonQuery =
|
||||
"PREFIX rdfs: <"+ rdfs +"> \n"+
|
||||
"SELECT ?existingPerson WHERE {\n"+
|
||||
"?projectRole <http://purl.obolibrary.org/obo/RO_0000052> ?existingPerson . \n" +
|
||||
"?existingPerson <http://purl.obolibrary.org/obo/RO_0000053> ?projectRole . \n" +
|
||||
"?existingPerson a <http://xmlns.com/foaf/0.1/Person> . \n " +
|
||||
" }";
|
||||
|
||||
final static String personLabelQuery =
|
||||
"PREFIX rdfs: <"+ rdfs +"> \n"+
|
||||
"SELECT ?existingPersonLabel WHERE {\n"+
|
||||
"?projectRole <http://purl.obolibrary.org/obo/RO_0000052> ?existingPerson . \n" +
|
||||
"?existingPerson <http://purl.obolibrary.org/obo/RO_0000053> ?projectRole .\n"+
|
||||
"?existingPerson <"+ label +"> ?existingPersonLabel .\n"+
|
||||
"?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");
|
||||
return EditModeUtils.getEditMode(vreq, predicates);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,159 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
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 com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
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.ChildVClassesOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaVClassOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
|
||||
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");
|
||||
|
||||
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,
|
||||
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);
|
||||
|
||||
if ( conf.isUpdate() ) {
|
||||
HashMap<String, List<String>> urisInScope = new HashMap<String, List<String>>();
|
||||
urisInScope.put("address", Arrays.asList(new String[]{addressUri}));
|
||||
conf.addUrisInScope(urisInScope);
|
||||
}
|
||||
else {
|
||||
conf.addSparqlForAdditionalUrisInScope("individualVcard", individualVcardQuery);
|
||||
}
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("streetAddress")
|
||||
.setRangeDatatypeUri( XSD.xstring.toString() ).
|
||||
setValidators( list("nonempty") ));
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("country")
|
||||
.setRangeDatatypeUri( XSD.xstring.toString() ).
|
||||
setValidators( list("nonempty") ));
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("postalCode")
|
||||
.setRangeDatatypeUri( XSD.xstring.toString() ).
|
||||
setValidators( list("nonempty") ));
|
||||
|
||||
conf.addField( new FieldVTwo().
|
||||
setName("locality")
|
||||
.setRangeDatatypeUri( XSD.xstring.toString() ).
|
||||
setValidators( list("nonempty") ) );
|
||||
|
||||
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 =
|
||||
"?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#hasAddress> ?address . \n" +
|
||||
"?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 =
|
||||
"?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 countryAssertion =
|
||||
"?address <http://www.w3.org/2006/vcard/ns#country> ?country .";
|
||||
|
||||
|
||||
/* Queries for editing an existing entry */
|
||||
|
||||
final static String individualVcardQuery =
|
||||
"SELECT ?individualVcard WHERE { \n" +
|
||||
"?subject <http://purl.obolibrary.org/obo/ARG_2000028> ?individualVcard . \n" +
|
||||
"}";
|
||||
|
||||
final static String streetAddressQuery =
|
||||
"SELECT ?existingStreetAddress WHERE {\n"+
|
||||
"?address <http://www.w3.org/2006/vcard/ns#streetAddress> ?existingStreetAddress . }";
|
||||
|
||||
final static String localityQuery =
|
||||
"SELECT ?existingLocality WHERE {\n"+
|
||||
"?address <http://www.w3.org/2006/vcard/ns#locality> ?existingLocality . }";
|
||||
|
||||
final static String regionQuery =
|
||||
"SELECT ?existingRegion WHERE {\n"+
|
||||
"?address <http://www.w3.org/2006/vcard/ns#region> ?existingRegion . }";
|
||||
|
||||
final static String postalCodeQuery =
|
||||
"SELECT ?existingPostalCode WHERE {\n"+
|
||||
"?address <http://www.w3.org/2006/vcard/ns#postalCode> ?existingPostalCode . }";
|
||||
|
||||
final static String countryQuery =
|
||||
"SELECT ?existingCountry WHERE {\n"+
|
||||
"?address <http://www.w3.org/2006/vcard/ns#country> ?existingCountry . }";
|
||||
|
||||
}
|
|
@ -0,0 +1,137 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
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.commons.lang.StringUtils;
|
||||
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
import com.hp.hpl.jena.rdf.model.Model;
|
||||
import com.hp.hpl.jena.rdf.model.ModelFactory;
|
||||
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
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.ChildVClassesOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaVClassOptions;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
|
||||
|
||||
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);
|
||||
String rangeUri = getRangeUri(vreq);
|
||||
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");
|
||||
}
|
||||
else {
|
||||
conf.setN3Required( Arrays.asList( n3ForNewPhoneNumber ) );
|
||||
numberType = model.createLiteral("phone");
|
||||
}
|
||||
|
||||
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() ) {
|
||||
HashMap<String, List<String>> urisInScope = new HashMap<String, List<String>>();
|
||||
urisInScope.put("phone", Arrays.asList(new String[]{phoneUri}));
|
||||
conf.addUrisInScope(urisInScope);
|
||||
}
|
||||
|
||||
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 =
|
||||
"?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> . " ;
|
||||
|
||||
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 =
|
||||
"SELECT ?existingIndividualVcard WHERE { \n" +
|
||||
"?subject <http://purl.obolibrary.org/obo/ARG_2000028> ?existingIndividualVcard . \n" +
|
||||
"}";
|
||||
|
||||
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");
|
||||
|
||||
return phoneUri;
|
||||
}
|
||||
private String getRangeUri(VitroRequest vreq) {
|
||||
String rangeUri = vreq.getParameter("rangeUri");
|
||||
|
||||
return rangeUri;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
|
||||
/**
|
||||
* Adds static Strings that may be useful for forms that are part of VIVO.
|
||||
*
|
||||
* @author bdc34
|
||||
*
|
||||
*/
|
||||
public abstract class VivoBaseGenerator extends BaseEditConfigurationGenerator implements EditConfigurationGenerator {
|
||||
|
||||
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 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 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";
|
||||
|
||||
final static String toInterval =vivoCore+"dateTimeInterval";
|
||||
final static String intervalType =vivoCore+"DateTimeInterval";
|
||||
final static String intervalToStart =vivoCore+"start";
|
||||
final static String intervalToEnd =vivoCore+"end";
|
||||
|
||||
final static String orgClass ="http://xmlns.com/foaf/0.1/Organization" ;
|
||||
final static String personClass = foaf + "Person";
|
||||
|
||||
}
|
|
@ -0,0 +1,876 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import net.sf.json.JSON;
|
||||
import net.sf.json.JSONArray;
|
||||
import net.sf.json.JSONSerializer;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.ontology.OntModel;
|
||||
import com.hp.hpl.jena.query.Query;
|
||||
import com.hp.hpl.jena.query.QueryExecution;
|
||||
import com.hp.hpl.jena.query.QueryExecutionFactory;
|
||||
import com.hp.hpl.jena.query.QueryFactory;
|
||||
import com.hp.hpl.jena.query.QuerySolution;
|
||||
import com.hp.hpl.jena.query.ResultSet;
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
import com.hp.hpl.jena.rdf.model.Resource;
|
||||
import com.hp.hpl.jena.vocabulary.OWL;
|
||||
import com.hp.hpl.jena.vocabulary.RDF;
|
||||
import com.hp.hpl.jena.vocabulary.RDFS;
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
|
||||
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.EditConfigurationUtils;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmission;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
|
||||
|
||||
public class AddAssociatedConceptsPreprocessor extends
|
||||
BaseEditSubmissionPreprocessorVTwo {
|
||||
|
||||
protected static final Log log = LogFactory
|
||||
.getLog(AddAssociatedConceptsPreprocessor.class.getName());
|
||||
protected OntModel ontModel = null;
|
||||
protected WebappDaoFactory wdf = null;
|
||||
// Field names/variables names for n3 - these will have numbers added as
|
||||
// suffix if more than one term
|
||||
private static String conceptNodeBase = "conceptNode";
|
||||
private static String sourceBase = "conceptSource";
|
||||
private static String labelBase = "conceptLabel";
|
||||
private static String conceptSemanticTypeLabelBase = "conceptSemanticTypeLabel";
|
||||
private static String conceptSemanticTypeURIBase = "conceptSemanticTypeURI";
|
||||
private static String conceptBroaderURIBase = "conceptBroaderURI";
|
||||
private static String conceptNarrowerURIBase = "conceptNarrowerURI";
|
||||
|
||||
//keyed off label variable, specifies which uri variable should be used, useful if same label repeated twice
|
||||
private HashMap<String, String> labelVarToUriVarHash = null;
|
||||
private HashMap<String, List<String>> conceptSemanticTypeURIVarToValueMap = null;
|
||||
//Also storing submission values
|
||||
private static String conceptNodeValues = null;
|
||||
private static String conceptLabelValues = null;
|
||||
private static String conceptSourceValues = null;
|
||||
private static String conceptSemanticTypeLabelValues = null;
|
||||
private static String conceptSemanticTypeURIValues = null;
|
||||
private static List<String> conceptBroaderURIValues = null;
|
||||
private static List<String> conceptNarrowerURIValues = null;
|
||||
private static MultiValueEditSubmission submission = null;
|
||||
|
||||
private static String SKOSBroaderURI = "http://www.w3.org/2004/02/skos/core#broader";
|
||||
private static String SKOSNarrowerURI = "http://www.w3.org/2004/02/skos/core#narrower";
|
||||
private static String SKOSConceptType = "http://www.w3.org/2004/02/skos/core#Concept";
|
||||
|
||||
// String datatype
|
||||
|
||||
// Will be editing the edit configuration as well as edit submission here
|
||||
|
||||
public AddAssociatedConceptsPreprocessor(EditConfigurationVTwo editConfig) {
|
||||
super(editConfig);
|
||||
this.labelVarToUriVarHash = new HashMap<String, String>();
|
||||
//Saves values of concept type uris
|
||||
this.conceptSemanticTypeURIVarToValueMap = new HashMap<String, List<String>>();
|
||||
}
|
||||
|
||||
public void preprocess(MultiValueEditSubmission inputSubmission, VitroRequest vreq) {
|
||||
submission = inputSubmission;
|
||||
this.wdf = vreq.getWebappDaoFactory();
|
||||
this.ontModel = ModelAccess.on(vreq).getOntModel();
|
||||
//Set the models that we need here
|
||||
// Get the input elements for concept node and concept label as well
|
||||
// as vocab uri (which is based on thge
|
||||
// For query parameters, check whether CUI
|
||||
copySubmissionValues();
|
||||
|
||||
|
||||
if (conceptNodeValues != null) {
|
||||
String[] conceptNodes = convertDelimitedStringToArray(conceptNodeValues);
|
||||
int numberConcepts = conceptNodes.length;
|
||||
//This will put the URI value in scope for the first semantic type label
|
||||
//and generate the rest if need be
|
||||
processConceptSemanticValues();
|
||||
//Also need to see if any broader or narrower uris for the concepts that already exist in the system
|
||||
//and set up the appropriate relationships between this concept and the broader/narrower uri
|
||||
getExistingConceptRelationships();
|
||||
if (numberConcepts > 1) {
|
||||
processConceptNodes(numberConcepts);
|
||||
}
|
||||
|
||||
} else {
|
||||
log.error("No concept nodes were added from the service");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
//Since we will change the uris and literals from form, we should make copies
|
||||
//of the original values and store them, this will also make iterations
|
||||
//and updates to the submission independent from accessing the values
|
||||
private void copySubmissionValues() {
|
||||
conceptLabelValues = getConceptLabelValues();
|
||||
conceptNodeValues = getConceptNodeValues();
|
||||
conceptSourceValues = getConceptSourceValues();
|
||||
conceptBroaderURIValues = getConceptBroaderURIValues();
|
||||
conceptNarrowerURIValues = getConceptNarrowerURIValues();
|
||||
log.debug("concept label values are " + conceptLabelValues);
|
||||
|
||||
}
|
||||
|
||||
|
||||
//For broader and narrower relationships, we will be
|
||||
//linking the concept to broader and narrower terms where those terms already
|
||||
//exist in the system
|
||||
//This method or approach may change later in which case this method should change
|
||||
private void getExistingConceptRelationships() {
|
||||
List<String> existingNarrowerURIs = getExistingNarrowerURIs(conceptNarrowerURIValues);
|
||||
List<String> existingBroaderURIs = getExistingBroaderURIs(conceptBroaderURIValues);
|
||||
//Now set the submission values to these, overwriting the original
|
||||
Map<String, List<String>> urisFromForm = submission.getUrisFromForm();
|
||||
if(existingNarrowerURIs.size() > 0) {
|
||||
urisFromForm.put("conceptNarrowerURI", existingNarrowerURIs);
|
||||
} else {
|
||||
//The original code for submission wouldn't put in a key if the values were null or size 0
|
||||
urisFromForm.remove("conceptNarrowerURI");
|
||||
}
|
||||
//Set the copied values to this value as well so when if there are multiple
|
||||
//concepts, the inputs get copied correctly for each of them
|
||||
this.conceptNarrowerURIValues = existingNarrowerURIs;
|
||||
if(existingBroaderURIs.size() > 0) {
|
||||
urisFromForm.put("conceptBroaderURI", existingBroaderURIs);
|
||||
} else {
|
||||
urisFromForm.remove("conceptBroaderURI");
|
||||
}
|
||||
this.conceptBroaderURIValues = existingBroaderURIs;
|
||||
}
|
||||
|
||||
//get the broader and narrower uri values that already exist in the system from the ones returned in the search
|
||||
//and use those to populate relationships between the concept and other concepts already in the system
|
||||
//We should also make sure to use bidirectional n3 so the graph has both sets of relationships represented
|
||||
private List<String> getConceptNarrowerURIValues() {
|
||||
return this.getJSONFormURIValues("conceptNarrowerURI");
|
||||
}
|
||||
|
||||
private List<String> getConceptBroaderURIValues() {
|
||||
return this.getJSONFormURIValues("conceptBroaderURI");
|
||||
}
|
||||
|
||||
private List<String> getJSONFormURIValues(String varName) {
|
||||
Map<String, List<String>> urisFromForm = submission.getUrisFromForm();
|
||||
List<String> uris = urisFromForm.get(varName);
|
||||
//This should be a JSON object stringified
|
||||
if(uris.size() > 0) {
|
||||
String jsonString = uris.get(0);
|
||||
if(jsonString != null && !jsonString.isEmpty()) {
|
||||
JSON json = JSONSerializer.toJSON(jsonString);
|
||||
//This should be an array
|
||||
if(json.isArray()) {
|
||||
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(jsonString);
|
||||
//Convert to list of strings
|
||||
return convertJsonArrayToList(jsonArray);
|
||||
}
|
||||
}
|
||||
}
|
||||
return uris;
|
||||
}
|
||||
|
||||
private List<String> convertJsonArrayToList(JSONArray jsonArray) {
|
||||
List<String> stringList = new ArrayList<String>();
|
||||
int len = jsonArray.size();
|
||||
int i = 0;
|
||||
for(i = 0; i < len; i++) {
|
||||
stringList.add(jsonArray.getString(i));
|
||||
}
|
||||
return stringList;
|
||||
}
|
||||
|
||||
private List<String> getExistingBroaderURIs(List<String> broaderURIs) {
|
||||
if(broaderURIs == null) {
|
||||
return new ArrayList<String>();
|
||||
}
|
||||
List<String> existingBroaderURIs = this.getExistingURIs(broaderURIs);
|
||||
return existingBroaderURIs;
|
||||
}
|
||||
|
||||
private List<String> getExistingNarrowerURIs(List<String> narrowerURIs) {
|
||||
if(narrowerURIs == null)
|
||||
return new ArrayList<String>();
|
||||
List<String> existingNarrowerURIs = this.getExistingURIs(narrowerURIs);
|
||||
return existingNarrowerURIs;
|
||||
}
|
||||
|
||||
//We need to keep the number of elements the same if there are any entries at all in the original
|
||||
//So we will use an empty string or null
|
||||
private List<String> getExistingURIs(List<String> uris) {
|
||||
//Important to keep the same formatting as original, because a comma delimited string as an element in the array
|
||||
//refers to a list of uris appropriate for a given concept, where each element in the array corresponds to a different
|
||||
//concept
|
||||
List<String> existingURIs = new ArrayList<String>();
|
||||
for(String uri:uris) {
|
||||
if(uri.indexOf(",") != -1) {
|
||||
List<String> existingURISet = new ArrayList<String>();
|
||||
String[] uriSet = uri.split(",");
|
||||
for(String u: uriSet) {
|
||||
if(u != null && !u.isEmpty() && this.wdf.hasExistingURI(u)) {
|
||||
existingURISet.add(u);
|
||||
}
|
||||
}
|
||||
//Now add the comma delimited version back to the array
|
||||
if(existingURISet.size() > 0) {
|
||||
existingURIs.add(StringUtils.join(existingURISet, ","));
|
||||
} else {
|
||||
//add empty string to indicate no value here
|
||||
existingURIs.add("");
|
||||
}
|
||||
} else {
|
||||
if(uri != null && !uri.isEmpty() && this.wdf.hasExistingURI(uri)) {
|
||||
existingURIs.add(uri);
|
||||
}
|
||||
else
|
||||
{
|
||||
existingURIs.add("");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return existingURIs;
|
||||
}
|
||||
|
||||
|
||||
//Process the semantic type label and URI values for the concepts
|
||||
private void processConceptSemanticValues() {
|
||||
conceptSemanticTypeLabelValues = getConceptSemanticTypeLabelValues();
|
||||
conceptSemanticTypeURIValues = getConceptSemanticTypeURIValues();
|
||||
|
||||
//We are first going to handle the single value case and then handle additional values
|
||||
//where the rest of the additional values are handled
|
||||
|
||||
}
|
||||
|
||||
|
||||
//This is for additional concept nodes (i.e. if user selects more than one concept)
|
||||
private void processConceptNodes(int numberConcepts) {
|
||||
//There are no "new" resources b/c the concept nodes are URIs from external vocabularies
|
||||
//New resources for concept semantic type uris
|
||||
addNewResources(numberConcepts);
|
||||
// Add N3Required
|
||||
addN3Required(numberConcepts);
|
||||
//Add N3 Optional as well
|
||||
addN3Optional(numberConcepts);
|
||||
// Add URIs on Form and Add Literals On Form
|
||||
addLiteralsAndUrisOnForm(numberConcepts);
|
||||
// Add fields
|
||||
addFields(numberConcepts);
|
||||
//Add input values to submission
|
||||
addInputsToSubmission(numberConcepts);
|
||||
|
||||
}
|
||||
|
||||
//This is specifically for concept semantic type URIs which may need to be generated
|
||||
private void addNewResources(int numberConcepts) {
|
||||
// TODO Auto-generated method stub
|
||||
addConceptSemanticTypeURIResources(numberConcepts);
|
||||
}
|
||||
|
||||
private void addConceptSemanticTypeURIResources(int numberConcepts) {
|
||||
//Iterate through the labels and get the corresponding uris
|
||||
HashSet<String> urisToAdd = new HashSet<String>();
|
||||
String[] conceptSemanticTypeLabels= convertDelimitedStringToArray(conceptSemanticTypeLabelValues);
|
||||
//the number of existing values may not match up, or at least existing populated ones
|
||||
//Now we can't determine whether all concepts will have semantic types - at some point what if
|
||||
//we ran a search across all external vocabularies? So we can't compare labels to number of concepts
|
||||
//but we can ensure that it isn't greater than then number of concepts
|
||||
if(conceptSemanticTypeLabels != null && conceptSemanticTypeLabels.length <= numberConcepts) {
|
||||
int i;
|
||||
for(i = 0; i < numberConcepts; i++) {
|
||||
int suffix = i + 1;
|
||||
String conceptSemanticTypeLabelVar = conceptSemanticTypeLabelBase + suffix;
|
||||
if(this.labelVarToUriVarHash.containsKey(conceptSemanticTypeLabelVar)) {
|
||||
String newResourceName = this.labelVarToUriVarHash.get(conceptSemanticTypeLabelVar);
|
||||
if(!urisToAdd.contains(newResourceName)) {
|
||||
urisToAdd.add(newResourceName);
|
||||
editConfiguration.addNewResource(newResourceName, null);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
} else if(conceptSemanticTypeLabels != null && conceptSemanticTypeLabels.length > numberConcepts){
|
||||
log.error("Number of concept semantic type labels is greater than number of concepts");
|
||||
} else{
|
||||
log.error("Concept semantic type labels returned are null");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//This is where the actual values will be submitted as if they were separate input fields
|
||||
//Each field name will correspond to the names of the fileds/uris on form/literals on form
|
||||
//generated here
|
||||
|
||||
private void addInputsToSubmission(int numberConcepts) {
|
||||
//This will essentially manufacture a set of query parameters
|
||||
//And will add the appropriate fields to the multivalue submission
|
||||
addConceptNodeInputs(numberConcepts);
|
||||
addConceptSourceInputs(numberConcepts);
|
||||
addConceptLabelInputs(numberConcepts);
|
||||
//for concept semantic type labels and uris where they exist
|
||||
addConceptSemanticTypeLabelAndURIInputs(numberConcepts);
|
||||
//For broader and narrower uris where they exist (this of course is in the case of multiple broader and narrower uris
|
||||
addConceptBroaderURIInputs(numberConcepts);
|
||||
addConceptNarrowerURIInputs(numberConcepts);
|
||||
}
|
||||
|
||||
private void addConceptNodeInputs(int numberConcepts) {
|
||||
|
||||
String[] conceptNodes = convertDelimitedStringToArray(conceptNodeValues);
|
||||
if(conceptNodes != null && conceptNodes.length == numberConcepts) {
|
||||
int i;
|
||||
//iterate through the concept nodes converted string array
|
||||
for(i = 0; i < numberConcepts; i++) {
|
||||
int suffix = i + 1;
|
||||
String conceptInputName = conceptNodeBase + suffix;
|
||||
String[] nodeValues = new String[1];
|
||||
nodeValues[0] = conceptNodes[i];
|
||||
//Add value for uri to form
|
||||
submission.addUriToForm(editConfiguration, conceptInputName, nodeValues);
|
||||
}
|
||||
} else if(conceptNodes != null && conceptNodes.length != numberConcepts){
|
||||
log.error("Number of concept nodes did not match the number of concepts to be added");
|
||||
} else{
|
||||
log.error("Concept nodes returned were null");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void addConceptSourceInputs(int numberConcepts) {
|
||||
String[] conceptSources = convertDelimitedStringToArray(conceptSourceValues);
|
||||
if(conceptSources != null && conceptSources.length == numberConcepts) {
|
||||
int i;
|
||||
for(i = 0; i < numberConcepts; i++) {
|
||||
int suffix = i + 1;
|
||||
String conceptInputName = sourceBase + suffix;
|
||||
String[] sourceValues = new String[1];
|
||||
sourceValues[0] = conceptSources[i];
|
||||
//Add value for uri to form
|
||||
submission.addUriToForm(editConfiguration, conceptInputName, sourceValues);
|
||||
}
|
||||
} else if(conceptSources != null && conceptSources.length != numberConcepts){
|
||||
log.error("Number of concept nodes did not match the number of concepts to be added");
|
||||
} else{
|
||||
log.error("Concept nodes returned were null");
|
||||
}
|
||||
}
|
||||
|
||||
private void addConceptLabelInputs(int numberConcepts) {
|
||||
String[] labels = convertDelimitedStringToArray(conceptLabelValues);
|
||||
if(labels != null && labels.length == numberConcepts) {
|
||||
int i;
|
||||
for(i = 0; i < numberConcepts; i++) {
|
||||
int suffix = i + 1;
|
||||
String labelInputName = labelBase + suffix;
|
||||
String[] labelValues = new String[1];
|
||||
labelValues[0] = labels[i];
|
||||
//TODO: Check if there are no funky typed information also stored
|
||||
//At this point the field should already have been added to edit configuration
|
||||
FieldVTwo labelField = editConfiguration.getField(labelInputName);
|
||||
if(labelField != null) {
|
||||
submission.addLiteralToForm(editConfiguration, labelField, labelInputName, labelValues);
|
||||
} else {
|
||||
log.error("Corresponding field for " + labelInputName + " was not added to edit configuration");
|
||||
}
|
||||
|
||||
}
|
||||
} else if(labels != null && labels.length != numberConcepts){
|
||||
log.error("Number of concept labels did not match the number of concepts to be added");
|
||||
} else{
|
||||
log.error("Concept labels returned were null");
|
||||
}
|
||||
}
|
||||
|
||||
private void addConceptSemanticTypeLabelAndURIInputs(int numberConcepts) {
|
||||
String[] labels = convertDelimitedStringToArray(conceptSemanticTypeLabelValues);
|
||||
HashSet<String> uniqueLabelValues = new HashSet<String>();
|
||||
if(labels != null && labels.length == numberConcepts) {
|
||||
int i;
|
||||
for(i = 0; i < numberConcepts; i++) {
|
||||
String thisLabel = labels[i];
|
||||
int suffix = i + 1;
|
||||
String labelInputName = conceptSemanticTypeLabelBase + suffix;
|
||||
String[] labelValues = new String[1];
|
||||
labelValues[0] = thisLabel;
|
||||
//TODO: Check if there are no funky typed information also stored
|
||||
//At this point the field should already have been added to edit configuration
|
||||
FieldVTwo labelField = editConfiguration.getField(labelInputName);
|
||||
//TODO: Also check to see whether the label is actually populate or will n3 editing take care of that?
|
||||
if(labelField != null) {
|
||||
submission.addLiteralToForm(editConfiguration, labelField, labelInputName, labelValues);
|
||||
//Associate URI
|
||||
if(!uniqueLabelValues.contains(thisLabel)) {
|
||||
uniqueLabelValues.add(thisLabel);
|
||||
this.addConceptSemanticTypeURIInputForLabel(labelInputName, suffix);
|
||||
}
|
||||
} else {
|
||||
log.error("Corresponding field for " + labelInputName + " was not added to edit configuration");
|
||||
}
|
||||
|
||||
}
|
||||
} else if(labels != null && labels.length != numberConcepts){
|
||||
log.error("Number of concept semantic type labels did not match the number of concepts to be added");
|
||||
} else{
|
||||
log.error("Concept labels returned were null");
|
||||
}
|
||||
}
|
||||
|
||||
private void addConceptSemanticTypeURIInputForLabel(String conceptSemanticTypeLabel, int suffix) {
|
||||
//String[] conceptSemanticTypeURIs= convertDelimitedStringToArray(conceptSemanticTypeURIValues);
|
||||
|
||||
//Get the semantic type URI variable name associated with this label
|
||||
String uriInputName = this.getConceptSemanticTypeURIFieldName(conceptSemanticTypeLabel, suffix);
|
||||
//List<>
|
||||
if(this.conceptSemanticTypeURIVarToValueMap.containsKey(uriInputName)) {
|
||||
List<String> uriVals = this.conceptSemanticTypeURIVarToValueMap.get(uriInputName);
|
||||
String[] uriValuesArray = uriVals.toArray(new String[uriVals.size()]);
|
||||
submission.addUriToForm(editConfiguration, uriInputName, uriValuesArray);
|
||||
}
|
||||
}
|
||||
|
||||
private void addConceptBroaderURIInputs(int numberConcepts) {
|
||||
int i;
|
||||
//Add inputs based on if there are any broader uris to add
|
||||
//Can't really compare number of existing broader uris to concepts
|
||||
//as each concept may or may not have a broader uri
|
||||
if(this.conceptBroaderURIValues.size() > 0 && this.conceptBroaderURIValues.size() <= numberConcepts) {
|
||||
for(i = 0; i < numberConcepts; i++) {
|
||||
int suffix = i + 1;
|
||||
String conceptBroaderURIInputName = conceptBroaderURIBase + suffix;
|
||||
String broaderURIs = this.conceptBroaderURIValues.get(i);
|
||||
if(broaderURIs != null && !broaderURIs.isEmpty()) {
|
||||
String[] broaderURISet = new String[1];
|
||||
if(broaderURIs.indexOf(",") != -1) {
|
||||
broaderURISet = broaderURIs.split(",");
|
||||
} else {
|
||||
broaderURISet[0] = broaderURIs;
|
||||
}
|
||||
//Add value for uri to form
|
||||
submission.addUriToForm(editConfiguration, conceptBroaderURIInputName, broaderURISet);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
private void addConceptNarrowerURIInputs(int numberConcepts) {
|
||||
int i;
|
||||
if(this.conceptNarrowerURIValues.size() > 0 && this.conceptNarrowerURIValues.size() <= numberConcepts) {
|
||||
for(i = 0; i < numberConcepts; i++) {
|
||||
int suffix = i + 1;
|
||||
String conceptNarrowerURIInputName = conceptNarrowerURIBase + suffix;
|
||||
String narrowerURIs = this.conceptNarrowerURIValues.get(i);
|
||||
if(narrowerURIs != null && !narrowerURIs.isEmpty()) {
|
||||
String[] narrowerURISet = new String[1];
|
||||
if(narrowerURIs.indexOf(",") != -1) {
|
||||
narrowerURISet = narrowerURIs.split(",");
|
||||
} else {
|
||||
narrowerURISet[0] = narrowerURIs;
|
||||
}
|
||||
//Add value for uri to form
|
||||
submission.addUriToForm(editConfiguration, conceptNarrowerURIInputName, narrowerURISet);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Fields
|
||||
|
||||
private void addFields(int numberConcepts) {
|
||||
//Clear out all fields in edit configuration first
|
||||
editConfiguration.setFields(new HashMap<String, FieldVTwo>());
|
||||
int index;
|
||||
HashSet<String> conceptSemanticTypeUris = new HashSet<String>();
|
||||
// First one already included in generator so add additional ones here
|
||||
for (index = 1; index <= numberConcepts; index++) {
|
||||
int suffix = index;
|
||||
String conceptNode = conceptNodeBase + suffix;
|
||||
String label = labelBase + suffix;
|
||||
String source = sourceBase + suffix;
|
||||
String conceptSemanticTypeLabel = conceptSemanticTypeLabelBase + suffix;
|
||||
String conceptSemanticTypeURI = this.getConceptSemanticTypeURIFieldName(conceptSemanticTypeLabel, suffix);
|
||||
String conceptBroaderURI = conceptBroaderURIBase + suffix;
|
||||
String conceptNarrowerURI = conceptNarrowerURIBase + suffix;
|
||||
addConceptNodeField(conceptNode);
|
||||
addLabelField(label);
|
||||
addSourceField(source);
|
||||
//Also add fields for concept semantic type label
|
||||
addConceptSemanticTypeLabelField(conceptSemanticTypeLabel);
|
||||
//and concept semantic type URI
|
||||
if(!conceptSemanticTypeUris.contains(conceptSemanticTypeURI)) {
|
||||
conceptSemanticTypeUris.add(conceptSemanticTypeURI);
|
||||
addConceptSemanticTypeURIField(conceptSemanticTypeURI);
|
||||
}
|
||||
|
||||
//add fields for concept broader and narrower uris
|
||||
addConceptBroaderURIField(conceptBroaderURI);
|
||||
addConceptNarrowerURIField(conceptNarrowerURI);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void addConceptNodeField(String conceptNode) {
|
||||
List<String> validators = new ArrayList<String>();
|
||||
validators.add("nonempty");
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName(conceptNode).
|
||||
setValidators(validators));
|
||||
}
|
||||
|
||||
private void addLabelField(String label) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName(label).
|
||||
setRangeDatatypeUri(XSD.xstring.toString())
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
private void addSourceField(String source) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName(source));
|
||||
|
||||
}
|
||||
|
||||
//TODO: Do we need to check if label is empty string?
|
||||
private void addConceptSemanticTypeLabelField(String label) {
|
||||
if(label != null) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName(label).
|
||||
setRangeDatatypeUri(XSD.xstring.toString())
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void addConceptSemanticTypeURIField(String conceptSemanticTypeURI) {
|
||||
if(conceptSemanticTypeURI != null) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName(conceptSemanticTypeURI));
|
||||
}
|
||||
}
|
||||
|
||||
private void addConceptNarrowerURIField(String conceptNarrowerURI) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName(conceptNarrowerURI));
|
||||
|
||||
}
|
||||
|
||||
private void addConceptBroaderURIField(String conceptBroaderURI) {
|
||||
editConfiguration.addField(new FieldVTwo().
|
||||
setName(conceptBroaderURI));
|
||||
|
||||
}
|
||||
|
||||
//original literals on form: label, uris on form: conceptNode and conceptSource
|
||||
//This will overwrite the original values in the edit configuration
|
||||
private void addLiteralsAndUrisOnForm(int numberTerms) {
|
||||
List<String> urisOnForm = new ArrayList<String>();
|
||||
List<String> literalsOnForm = new ArrayList<String>();
|
||||
|
||||
int index;
|
||||
HashSet<String> conceptSemanticTypeURIs = new HashSet<String>();
|
||||
// First one already included so add new ones here
|
||||
for (index = 1; index <= numberTerms; index++) {
|
||||
int suffix = index;
|
||||
String conceptNode = conceptNodeBase + suffix;
|
||||
String label = labelBase + suffix;
|
||||
String source = sourceBase + suffix;
|
||||
String conceptSemanticTypeLabel = conceptSemanticTypeLabelBase + suffix;
|
||||
//String conceptSemanticTypeURI = conceptSemanticTypeURIBase + suffix;
|
||||
String conceptSemanticTypeURI = this.getConceptSemanticTypeURIFieldName(conceptSemanticTypeLabel, suffix);
|
||||
String conceptBroaderURI = conceptBroaderURIBase + suffix;
|
||||
String conceptNarrowerURI = conceptNarrowerURIBase + suffix;
|
||||
urisOnForm.add(conceptNode);
|
||||
urisOnForm.add(source);
|
||||
if(!conceptSemanticTypeURIs.contains(conceptSemanticTypeURI)) {
|
||||
conceptSemanticTypeURIs.add(conceptSemanticTypeURI);
|
||||
urisOnForm.add(conceptSemanticTypeURI);
|
||||
}
|
||||
urisOnForm.add(conceptBroaderURI);
|
||||
urisOnForm.add(conceptNarrowerURI);
|
||||
literalsOnForm.add(label);
|
||||
literalsOnForm.add(conceptSemanticTypeLabel);
|
||||
}
|
||||
editConfiguration.setUrisOnform(urisOnForm);
|
||||
editConfiguration.setLiteralsOnForm(literalsOnForm);
|
||||
}
|
||||
|
||||
// N3 being reproduced
|
||||
/*
|
||||
* ?subject ?predicate ?conceptNode .
|
||||
*/
|
||||
//This will overwrite the original with the set of new n3 required
|
||||
private void addN3Required(int numberConcepts) {
|
||||
// List<String> n3Required = editConfig.getN3Required();
|
||||
List<String> n3Required = new ArrayList<String>();
|
||||
int index;
|
||||
String nodeBase = "?" + conceptNodeBase;
|
||||
|
||||
String prefixStr = "@prefix core: <http://vivoweb.org/ontology/core#> .";
|
||||
// First one already included so add new ones here
|
||||
for (index = 1; index <= numberConcepts; index++) {
|
||||
int suffix = index;
|
||||
String node = nodeBase + suffix;
|
||||
String n3String = prefixStr;
|
||||
n3String += "?subject ?predicate " + node + " . \n" +
|
||||
node + " <" + RDF.type.getURI() + "> <" + this.SKOSConceptType + "> .";
|
||||
n3Required.add(n3String);
|
||||
}
|
||||
editConfiguration.setN3Required(n3Required);
|
||||
}
|
||||
//Add n3 optional
|
||||
//TODO: Rewrite optional N3
|
||||
private void addN3Optional(int numberConcepts) {
|
||||
List<String> n3Optional = new ArrayList<String>();
|
||||
int index;
|
||||
String nodeBase = "?" + conceptNodeBase;
|
||||
String labelVar = "?" + labelBase;
|
||||
String sourceVar = "?" + sourceBase;
|
||||
String conceptSemanticTypeLabelVar = "?" + conceptSemanticTypeLabelBase;
|
||||
String conceptBroaderURIVar = "?" + conceptBroaderURIBase;
|
||||
String conceptNarrowerURIVar = "?" + conceptNarrowerURIBase;
|
||||
String prefixStr = "@prefix core: <http://vivoweb.org/ontology/core#> .";
|
||||
// First one already included so add new ones here
|
||||
//We already have a label var to uri var setup
|
||||
for (index = 1; index <= numberConcepts; index++) {
|
||||
//Set up the variables based on which concept node
|
||||
int suffix = index;
|
||||
String node = nodeBase + suffix;
|
||||
String label = labelVar + suffix;
|
||||
String source = sourceVar + suffix;
|
||||
String conceptSemanticTypeLabel = conceptSemanticTypeLabelVar + suffix;
|
||||
//get the URI appropriate for the concept semantic type label var
|
||||
String conceptSemanticTypeURI = getConceptSemanticTypeURIVar(conceptSemanticTypeLabelBase + suffix, suffix);
|
||||
String conceptBroaderURI = conceptBroaderURIVar + suffix;
|
||||
String conceptNarrowerURI = conceptNarrowerURIVar + suffix;
|
||||
//Set up the n3 strings
|
||||
String n3String = prefixStr;
|
||||
n3String += node + " <" + RDFS.label.getURI() + "> " + label + " .\n" +
|
||||
node + " <" + RDFS.isDefinedBy.getURI() + "> " + source + " .";
|
||||
String n3ConceptTypeString = prefixStr;
|
||||
n3ConceptTypeString += node + " <" + RDF.type.getURI() + "> " + conceptSemanticTypeURI + " ." +
|
||||
conceptSemanticTypeURI + " <" + RDFS.label.getURI() + "> " + conceptSemanticTypeLabel + " .\n" +
|
||||
conceptSemanticTypeURI + " <" + RDFS.subClassOf.getURI() + "> <http://www.w3.org/2004/02/skos/core#Concept> .\n" ;
|
||||
//String representing the broader and narrower uri(s) for each of the concepts - these may or may not exist
|
||||
String n3ConceptBroaderURI = prefixStr + node + " <" + this.SKOSNarrowerURI + "> " + conceptNarrowerURI + " ." +
|
||||
conceptNarrowerURI + " <" + this.SKOSBroaderURI + "> " + node + " .";
|
||||
String n3ConceptNarrowerURI = prefixStr + node + " <" + this.SKOSBroaderURI + "> " + conceptBroaderURI + " ." +
|
||||
conceptBroaderURI + " <" + this.SKOSNarrowerURI + "> " + node + " .";
|
||||
|
||||
n3Optional.add(n3String);
|
||||
//adding separately so their resolution does not depend on each other
|
||||
n3Optional.add(n3ConceptTypeString);
|
||||
n3Optional.add(n3ConceptBroaderURI);
|
||||
n3Optional.add(n3ConceptNarrowerURI);
|
||||
|
||||
}
|
||||
//Already have n3 required so need to add to that
|
||||
|
||||
editConfiguration.setN3Optional(n3Optional);
|
||||
}
|
||||
|
||||
//get the URI variable that is associated with this concept type URI, which might not be
|
||||
//the same suffix because the same label value might be repeated and we need to use the same URI
|
||||
//representing that concept semantic type
|
||||
private String getConceptSemanticTypeURIVar(String labelVar, int suffix) {
|
||||
// TODO Auto-generated method stub
|
||||
return "?" + this.getConceptSemanticTypeURIFieldName(labelVar, suffix);
|
||||
}
|
||||
|
||||
private String getConceptSemanticTypeURIFieldName(String labelVar, int suffix) {
|
||||
// TODO Auto-generated method stub
|
||||
if(this.labelVarToUriVarHash.containsKey(labelVar)) {
|
||||
return this.labelVarToUriVarHash.get(labelVar);
|
||||
}
|
||||
return this.conceptSemanticTypeURIBase + suffix;
|
||||
}
|
||||
|
||||
private String[] convertDelimitedStringToArray(String inputString) {
|
||||
String[] inputArray = new String[1];
|
||||
if (inputString.indexOf(",") != -1) {
|
||||
inputArray = inputString.split(",");
|
||||
} else {
|
||||
inputArray[0] = inputString;
|
||||
}
|
||||
return inputArray;
|
||||
|
||||
}
|
||||
|
||||
|
||||
//Get values from submission
|
||||
private String getConceptNodeValues() {
|
||||
Map<String, List<String>> urisFromForm = submission.getUrisFromForm();
|
||||
List<String> conceptNodes = urisFromForm.get("conceptNode");
|
||||
return (String) getFirstElement(conceptNodes);
|
||||
}
|
||||
|
||||
private String getConceptSourceValues() {
|
||||
Map<String, List<String>> urisFromForm = submission.getUrisFromForm();
|
||||
return (String) getFirstElement(urisFromForm.get("conceptSource"));
|
||||
}
|
||||
|
||||
private String getConceptLabelValues() {
|
||||
Map<String, List<Literal>> literalsFromForm = submission.getLiteralsFromForm();
|
||||
Map<String, List<String>> transformed = EditConfigurationUtils.transformLiteralMap(literalsFromForm);
|
||||
return (String) getFirstElement(transformed.get("conceptLabel"));
|
||||
|
||||
}
|
||||
|
||||
private String getConceptSemanticTypeLabelValues() {
|
||||
Map<String, List<Literal>> literalsFromForm = submission.getLiteralsFromForm();
|
||||
Map<String, List<String>> transformed = EditConfigurationUtils.transformLiteralMap(literalsFromForm);
|
||||
String label = (String) getFirstElement(transformed.get("conceptSemanticTypeLabel"));
|
||||
if(label == null) {
|
||||
label = "";
|
||||
}
|
||||
|
||||
return label;
|
||||
}
|
||||
|
||||
//This will either generate or retrieve URIs for the concept semantic type labels if they exist
|
||||
//We will then update the submission to include this
|
||||
private String getConceptSemanticTypeURIValues() {
|
||||
String pseudoInputString = "";
|
||||
if(conceptSemanticTypeLabelValues != null && !conceptSemanticTypeLabelValues.isEmpty()) {
|
||||
String[] conceptSemanticTypeLabels = convertDelimitedStringToArray(conceptSemanticTypeLabelValues);
|
||||
//keep track of what label values already exist and to which label variables they map
|
||||
HashMap<String, List<Integer>> labelValueToVarSuffix = new HashMap<String, List<Integer>>();
|
||||
int numberLabels = conceptSemanticTypeLabels.length;
|
||||
|
||||
//The rest of this code is really only relevant for multiple values, so we could break out the old code above
|
||||
//as we don't need to set up hashes etc. if there is only one concept node being added
|
||||
if(numberLabels == 1) {
|
||||
String label = conceptSemanticTypeLabels[0];
|
||||
String uri = getURIForSemanticTypeLabel(label);
|
||||
if(uri != "") {
|
||||
String[] urisToAdd = new String[1];
|
||||
urisToAdd[0] = uri;
|
||||
pseudoInputString = uri;
|
||||
log.debug("uris to add" + uri);
|
||||
submission.addUriToForm(this.editConfiguration, "conceptSemanticTypeURI", urisToAdd);
|
||||
}
|
||||
|
||||
}
|
||||
//if there is more than one concept node, we may have duplicate semantic types
|
||||
//which will need to be referred to by the same semantic type uri
|
||||
else if (numberLabels > 1){
|
||||
|
||||
for(int i = 0; i < numberLabels; i++) {
|
||||
int suffix = i + 1;
|
||||
String label = conceptSemanticTypeLabels[i];
|
||||
String labelVar = this.conceptSemanticTypeLabelBase + suffix;
|
||||
//if label has not already been encountered, create entry for label value
|
||||
//and list with the label variables that would refer to it
|
||||
//for unique values, the uri variable will be the same as label
|
||||
Integer thisSuffix = new Integer(suffix);
|
||||
if(!labelValueToVarSuffix.containsKey(label)) {
|
||||
labelValueToVarSuffix.put(label, new ArrayList<Integer>());
|
||||
//Add suffix to list if not already there
|
||||
labelValueToVarSuffix.get(label).add(thisSuffix);
|
||||
} else {
|
||||
//in this case, the label already exists, get the very first element in the list
|
||||
//and use that as the uri variable
|
||||
List<Integer> suffixList = labelValueToVarSuffix.get(label);
|
||||
if(suffixList != null && suffixList.size() > 0) {
|
||||
thisSuffix = suffixList.get(0);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//Now add the uri var to the hash mapping label variable to uri variable
|
||||
String uriVar = this.conceptSemanticTypeURIBase + thisSuffix.intValue();
|
||||
this.labelVarToUriVarHash.put(labelVar, uriVar);
|
||||
|
||||
|
||||
//Make or retrieve URI for this label
|
||||
//TODO: Do we create this string with empty inputs ?
|
||||
String uri = getURIForSemanticTypeLabel(label);
|
||||
if(uri != "") {
|
||||
//uri var shouldn't be repeated?
|
||||
if(!this.conceptSemanticTypeURIVarToValueMap.containsKey(uriVar)) {
|
||||
this.conceptSemanticTypeURIVarToValueMap.put(uriVar, new ArrayList<String>());
|
||||
this.conceptSemanticTypeURIVarToValueMap.get(uriVar).add(uri);
|
||||
}
|
||||
}
|
||||
if(i != 0) {
|
||||
pseudoInputString += ",";
|
||||
}
|
||||
pseudoInputString += uri;
|
||||
|
||||
}
|
||||
|
||||
//Add this string to the uris for the form
|
||||
String[] urisToAdd = new String[1];
|
||||
urisToAdd[0] = pseudoInputString;
|
||||
log.debug("uris to add" + pseudoInputString);
|
||||
submission.addUriToForm(this.editConfiguration, "conceptSemanticTypeURI", urisToAdd);
|
||||
|
||||
}
|
||||
}
|
||||
return pseudoInputString;
|
||||
}
|
||||
|
||||
private String getURIForSemanticTypeLabel(String label) {
|
||||
String existingURI = this.getExistingSemanticTypeURI(label);
|
||||
if(existingURI != null) {
|
||||
return existingURI;
|
||||
}
|
||||
//if we leave this as null, we should be able to generate a new resource
|
||||
//empty string because there may be more than one value returned for labels
|
||||
else return "";
|
||||
|
||||
}
|
||||
|
||||
private String getExistingSemanticTypeURI(String label) {
|
||||
String queryStr = "SELECT ?semanticType WHERE { ?semanticType <" + RDF.type.getURI() + "> <" + OWL.Class.getURI() + "> . " +
|
||||
"?semanticType <" + RDFS.label.getURI() + "> \"" + label + "\"^^<http://www.w3.org/2001/XMLSchema#string> . }";
|
||||
QueryExecution qe = null;
|
||||
try{
|
||||
Query query = QueryFactory.create(queryStr);
|
||||
qe = QueryExecutionFactory.create(query, this.ontModel);
|
||||
ResultSet results = null;
|
||||
results = qe.execSelect();
|
||||
|
||||
while( results.hasNext()){
|
||||
QuerySolution qs = results.nextSolution();
|
||||
if(qs.get("semanticType") != null) {
|
||||
Resource semanticTypeURI = qs.getResource("semanticType");
|
||||
log.debug("Semantic Type URI returned " + semanticTypeURI.getURI());
|
||||
return semanticTypeURI.getURI();
|
||||
}
|
||||
}
|
||||
}catch(Exception ex){
|
||||
throw new Error("Error in executing query string: \n" + queryStr + '\n' + ex.getMessage());
|
||||
}finally{
|
||||
if( qe != null)
|
||||
qe.close();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private Object getFirstElement(List inputList) {
|
||||
if(inputList == null || inputList.size() == 0)
|
||||
return null;
|
||||
return inputList.get(0);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,116 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.ontology.OntModel;
|
||||
import com.hp.hpl.jena.query.Query;
|
||||
import com.hp.hpl.jena.query.QueryExecution;
|
||||
import com.hp.hpl.jena.query.QueryExecutionFactory;
|
||||
import com.hp.hpl.jena.query.QueryFactory;
|
||||
import com.hp.hpl.jena.query.Syntax;
|
||||
import com.hp.hpl.jena.rdf.model.Model;
|
||||
import com.hp.hpl.jena.rdf.model.ModelFactory;
|
||||
import com.hp.hpl.jena.shared.Lock;
|
||||
import com.hp.hpl.jena.vocabulary.RDF;
|
||||
import com.hp.hpl.jena.vocabulary.RDFS;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
|
||||
|
||||
//We are representing semantic types from the UMLS Semantic Network as OWL Classes
|
||||
//and this preprocessor will add the appropriate class information to the TBox
|
||||
|
||||
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 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 . " +
|
||||
"}";
|
||||
|
||||
//Execute construct query
|
||||
Model constructedModel = ModelFactory.createDefaultModel();
|
||||
|
||||
|
||||
log.debug("CONSTRUCT query string " + constructQuery);
|
||||
|
||||
Query query = null;
|
||||
try {
|
||||
query = QueryFactory.create(constructQuery, Syntax.syntaxARQ);
|
||||
} catch(Throwable th){
|
||||
log.error("Could not create CONSTRUCT SPARQL query for query " +
|
||||
"string. " + th.getMessage());
|
||||
log.error(constructQuery);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
|
||||
additionsModel.getLock().enterCriticalSection(Lock.READ);
|
||||
QueryExecution qe = null;
|
||||
try {
|
||||
qe = QueryExecutionFactory.create(
|
||||
query, additionsModel);
|
||||
qe.execConstruct(constructedModel);
|
||||
} catch (Exception e) {
|
||||
log.error("Error getting constructed model for query string " + constructQuery);
|
||||
} finally {
|
||||
if (qe != null) {
|
||||
qe.close();
|
||||
}
|
||||
additionsModel.getLock().leaveCriticalSection();
|
||||
}
|
||||
|
||||
//Add constructed model to the designated update model
|
||||
OntModel toUpdateModel = ModelAccess.on(vreq).getOntModelSelector().getTBoxModel();
|
||||
toUpdateModel.enterCriticalSection(Lock.WRITE);
|
||||
try {
|
||||
toUpdateModel.add(constructedModel);
|
||||
} catch (Exception e) {
|
||||
log.error("Error adding statements to update model for " + constructQuery);
|
||||
} finally {
|
||||
toUpdateModel.leaveCriticalSection();
|
||||
}
|
||||
|
||||
//Take this constructed model and remove from the additions model
|
||||
additionsModel.enterCriticalSection(Lock.WRITE);
|
||||
try {
|
||||
additionsModel.remove(constructedModel.listStatements().toList());
|
||||
} catch (Exception e) {
|
||||
log.error("Error removing statements from additions model for " + constructQuery);
|
||||
} finally {
|
||||
additionsModel.leaveCriticalSection();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,105 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import com.hp.hpl.jena.ontology.OntModel;
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
import com.hp.hpl.jena.rdf.model.Model;
|
||||
import com.hp.hpl.jena.rdf.model.Property;
|
||||
import com.hp.hpl.jena.rdf.model.ResIterator;
|
||||
import com.hp.hpl.jena.rdf.model.Resource;
|
||||
import com.hp.hpl.jena.rdf.model.Statement;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
/*
|
||||
* This preprocessor is used to set the language attribute on the label based on the user selection
|
||||
* on the manage labels page when adding a new label.
|
||||
*/
|
||||
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;
|
||||
|
||||
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
|
||||
super.preprocess(inputSubmission, vreq);
|
||||
//First name and last name would also have a language selected so make sure those literals are also
|
||||
//correctly typed
|
||||
//Middle name is optional
|
||||
if(inputSubmission.hasLiteralValue("firstName") && inputSubmission.hasLiteralValue("lastName") && inputSubmission.hasLiteralValue("newLabelLanguage")) {
|
||||
Map<String, List<Literal>> literalsFromForm = inputSubmission.getLiteralsFromForm();
|
||||
List<Literal> newLabelLanguages = literalsFromForm.get("newLabelLanguage");
|
||||
List<Literal> firstNames = literalsFromForm.get("firstName");
|
||||
List<Literal> lastNames = literalsFromForm.get("lastName");
|
||||
List<Literal> middleNames = new ArrayList<Literal>();
|
||||
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,
|
||||
lang);
|
||||
Literal lastNameWithLanguage = inputSubmission.createLiteral(lastNameValue,
|
||||
null,
|
||||
lang);
|
||||
|
||||
firstNames = new ArrayList<Literal>();
|
||||
lastNames = new ArrayList<Literal>();
|
||||
firstNames.add(firstNameWithLanguage);
|
||||
lastNames.add(lastNameWithLanguage);
|
||||
//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,
|
||||
lang);
|
||||
middleNames = new ArrayList<Literal>();
|
||||
middleNames.add(middleNameWithLanguage);
|
||||
literalsFromForm.put("middleName", middleNames);
|
||||
}
|
||||
|
||||
//Set literals
|
||||
inputSubmission.setLiteralsFromForm(literalsFromForm);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,64 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.query.Query;
|
||||
import com.hp.hpl.jena.query.QueryExecution;
|
||||
import com.hp.hpl.jena.query.QueryExecutionFactory;
|
||||
import com.hp.hpl.jena.query.QueryFactory;
|
||||
import com.hp.hpl.jena.query.QuerySolution;
|
||||
import com.hp.hpl.jena.query.ResultSet;
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
import com.hp.hpl.jena.rdf.model.Model;
|
||||
import com.hp.hpl.jena.rdf.model.ModelFactory;
|
||||
import com.hp.hpl.jena.rdf.model.Resource;
|
||||
import com.hp.hpl.jena.rdf.model.ResourceFactory;
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
import com.hp.hpl.jena.rdf.model.Property;
|
||||
import com.hp.hpl.jena.shared.Lock;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
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.BaseEditSubmissionPreprocessorVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmission;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
|
||||
import org.vivoweb.webapp.util.ModelUtils;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,104 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.query.Query;
|
||||
import com.hp.hpl.jena.query.QueryExecution;
|
||||
import com.hp.hpl.jena.query.QueryExecutionFactory;
|
||||
import com.hp.hpl.jena.query.QueryFactory;
|
||||
import com.hp.hpl.jena.query.QuerySolution;
|
||||
import com.hp.hpl.jena.query.ResultSet;
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
import com.hp.hpl.jena.rdf.model.Model;
|
||||
import com.hp.hpl.jena.rdf.model.ModelFactory;
|
||||
import com.hp.hpl.jena.rdf.model.Resource;
|
||||
import com.hp.hpl.jena.rdf.model.ResourceFactory;
|
||||
import com.hp.hpl.jena.vocabulary.XSD;
|
||||
import com.hp.hpl.jena.rdf.model.Property;
|
||||
import com.hp.hpl.jena.shared.Lock;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
|
||||
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.BaseEditSubmissionPreprocessorVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmission;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.utils;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
/*
|
||||
* This class determines what n3 should be returned for a particular data getter and can be overwritten or extended in VIVO.
|
||||
*/
|
||||
public class ProcessDataGetterN3Map {
|
||||
private static final Log log = LogFactory.getLog(ProcessDataGetterN3Map.class);
|
||||
public static HashMap<String, String> getDataGetterTypeToProcessorMap() {
|
||||
HashMap<String, String> map = new HashMap<String, String>();
|
||||
map.put("edu.cornell.mannlib.vitro.webapp.utils.dataGetter.SparqlQueryDataGetter", "edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.utils.ProcessSparqlDataGetterN3");
|
||||
map.put("edu.cornell.mannlib.vitro.webapp.utils.dataGetter.ClassGroupPageData", "edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.utils.ProcessClassGroupDataGetterN3");
|
||||
map.put("edu.cornell.mannlib.vitro.webapp.utils.dataGetter.InternalClassesDataGetter", "edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.utils.ProcessInternalClassDataGetterN3");
|
||||
map.put("edu.cornell.mannlib.vitro.webapp.utils.dataGetter.FixedHTMLDataGetter", "edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.utils.ProcessFixedHTMLN3");
|
||||
map.put("edu.cornell.mannlib.vitro.webapp.utils.dataGetter.SearchIndividualsDataGetter", "edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.utils.ProcessSearchIndividualsDataGetterN3");
|
||||
|
||||
return map;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,227 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.utils;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.ontology.OntModel;
|
||||
import com.hp.hpl.jena.query.Query;
|
||||
import com.hp.hpl.jena.query.QueryExecution;
|
||||
import com.hp.hpl.jena.query.QueryExecutionFactory;
|
||||
import com.hp.hpl.jena.query.QueryFactory;
|
||||
import com.hp.hpl.jena.query.QuerySolution;
|
||||
import com.hp.hpl.jena.query.ResultSet;
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
import com.hp.hpl.jena.rdf.model.Resource;
|
||||
import com.hp.hpl.jena.rdf.model.ResourceFactory;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
|
||||
import javax.servlet.ServletContext;
|
||||
|
||||
import net.sf.json.JSONArray;
|
||||
import net.sf.json.JSONObject;
|
||||
import net.sf.json.JSONSerializer;
|
||||
//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 JSONObject getExistingValuesJSON(String dataGetterURI, OntModel queryModel, ServletContext context) {
|
||||
JSONObject jObject = new JSONObject();
|
||||
jObject.element("dataGetterClass", classType);
|
||||
//Update to include class type as variable
|
||||
jObject.element(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, JSONObject 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();
|
||||
JSONArray individualsForClasses = new JSONArray();
|
||||
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.element("classGroup", classGroupURI);
|
||||
//this is a json array
|
||||
jObject.element(individualClassVarNameBase, individualsForClasses);
|
||||
//Internal class - if null then add false otherwise use the value
|
||||
if(internalClassLiteral != null) {
|
||||
jObject.element(internalClassVarNameBase, internalClassLiteral.getString());
|
||||
} else {
|
||||
jObject.element(internalClassVarNameBase, "false");
|
||||
}
|
||||
} catch(Exception ex) {
|
||||
log.error("Exception occurred in retrieving existing values with query " + querystr, ex);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,305 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.searchindex.documentBuilding;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.query.Dataset;
|
||||
import com.hp.hpl.jena.query.DatasetFactory;
|
||||
import com.hp.hpl.jena.query.Query;
|
||||
import com.hp.hpl.jena.query.QueryExecution;
|
||||
import com.hp.hpl.jena.query.QueryExecutionFactory;
|
||||
import com.hp.hpl.jena.query.QueryFactory;
|
||||
import com.hp.hpl.jena.query.QuerySolution;
|
||||
import com.hp.hpl.jena.query.QuerySolutionMap;
|
||||
import com.hp.hpl.jena.query.ResultSet;
|
||||
import com.hp.hpl.jena.query.Syntax;
|
||||
import com.hp.hpl.jena.rdf.model.RDFNode;
|
||||
import com.hp.hpl.jena.rdf.model.Resource;
|
||||
import com.hp.hpl.jena.rdf.model.ResourceFactory;
|
||||
import com.hp.hpl.jena.shared.Lock;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
|
||||
import edu.cornell.mannlib.vitro.webapp.modelaccess.ContextModelAccess;
|
||||
import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchInputDocument;
|
||||
import edu.cornell.mannlib.vitro.webapp.search.VitroSearchTermNames;
|
||||
import edu.cornell.mannlib.vitro.webapp.utils.configuration.ContextModelsUser;
|
||||
|
||||
|
||||
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#> "
|
||||
+ " prefix core: <http://vivoweb.org/ontology/core#> "
|
||||
+ " prefix foaf: <http://xmlns.com/foaf/0.1/> "
|
||||
+ " prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> "
|
||||
+ " 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());
|
||||
}
|
||||
|
||||
public float calculateBeta(String uri){
|
||||
float beta=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);
|
||||
QueryExecution qexec=null;
|
||||
try{
|
||||
query = QueryFactory.create(betaQuery,Syntax.syntaxARQ);
|
||||
qexec = QueryExecutionFactory.create(query,dataset,initialBinding);
|
||||
ResultSet results = qexec.execSelect();
|
||||
List<String> resultVars = results.getResultVars();
|
||||
if(resultVars!=null && resultVars.size()!=0){
|
||||
soln = results.next();
|
||||
Conn = Integer.parseInt(soln.getLiteral(resultVars.get(0)).getLexicalForm());
|
||||
}
|
||||
}catch(Throwable t){
|
||||
if( ! shutdown )
|
||||
log.error(t,t);
|
||||
}finally{
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
public String[] getAdjacentNodes(String uri){
|
||||
|
||||
List<String> queryList = new ArrayList<String>();
|
||||
Set<String> adjacentNodes = new HashSet<String>();
|
||||
Set<String> coauthorNames = new HashSet<String>();
|
||||
String[] info = new String[]{"",""};
|
||||
StringBuffer adjacentNodesConcat = new StringBuffer();
|
||||
StringBuffer coauthorBuff = new StringBuffer();
|
||||
adjacentNodesConcat.append("");
|
||||
coauthorBuff.append("");
|
||||
|
||||
queryList.add(prefix +
|
||||
" SELECT ?adjobj (str(?adjobjLabel) as ?coauthor) " +
|
||||
" WHERE { " +
|
||||
" ?uri rdf:type <http://xmlns.com/foaf/0.1/Person> . " +
|
||||
" ?uri ?prop ?obj . " +
|
||||
" ?obj rdf:type <http://vivoweb.org/ontology/core#Relationship> . " +
|
||||
" ?obj ?prop2 ?obj2 . " +
|
||||
" ?obj2 rdf:type obo:IAO_0000030 . " +
|
||||
" ?obj2 ?prop3 ?obj3 . " +
|
||||
" ?obj3 rdf:type <http://vivoweb.org/ontology/core#Relationship> . " +
|
||||
" ?obj3 ?prop4 ?adjobj . " +
|
||||
" ?adjobj rdfs:label ?adjobjLabel . " +
|
||||
" ?adjobj rdf:type <http://xmlns.com/foaf/0.1/Person> . " +
|
||||
|
||||
" FILTER (?prop !=rdf:type) . " +
|
||||
" FILTER (?prop2!=rdf:type) . " +
|
||||
" FILTER (?prop3!=rdf:type) . " +
|
||||
" FILTER (?prop4!=rdf:type) . " +
|
||||
" FILTER (?adjobj != ?uri) . " +
|
||||
"}");
|
||||
|
||||
queryList.add(prefix +
|
||||
" SELECT ?adjobj " +
|
||||
" WHERE{ " +
|
||||
|
||||
" ?uri rdf:type foaf:Agent . " +
|
||||
" ?uri ?prop ?obj . " +
|
||||
" ?obj ?prop2 ?adjobj . " +
|
||||
|
||||
|
||||
" FILTER (?prop !=rdf:type) . " +
|
||||
" FILTER isURI(?obj) . " +
|
||||
|
||||
" FILTER (?prop2!=rdf:type) . " +
|
||||
" FILTER (?adjobj != ?uri) . " +
|
||||
" FILTER isURI(?adjobj) . " +
|
||||
|
||||
" { ?adjobj rdf:type <http://xmlns.com/foaf/0.1/Organization> . } " +
|
||||
" UNION " +
|
||||
" { ?adjobj rdf:type <http://xmlns.com/foaf/0.1/Person> . } " +
|
||||
" UNION " +
|
||||
" { ?adjobj rdf:type obo:IAO_0000030 . } " +
|
||||
" 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.
|
||||
}*/
|
||||
query = QueryFactory.create(queryItr.next(),Syntax.syntaxARQ);
|
||||
QueryExecution qexec = QueryExecutionFactory.create(query,dataset,initialBinding);
|
||||
try{
|
||||
ResultSet results = qexec.execSelect();
|
||||
while(results.hasNext()){
|
||||
soln = results.nextSolution();
|
||||
|
||||
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;
|
||||
Iterator<String> itr = adjacentNodes.iterator();
|
||||
while(itr.hasNext()){
|
||||
adjacentNodesConcat.append(itr.next() + " ");
|
||||
}
|
||||
|
||||
info[0] = adjacentNodesConcat.toString();
|
||||
|
||||
itr = coauthorNames.iterator();
|
||||
while(itr.hasNext()){
|
||||
coauthorBuff.append(itr.next());
|
||||
}
|
||||
|
||||
info[1] = coauthorBuff.toString();
|
||||
|
||||
}
|
||||
catch(Throwable t){
|
||||
if( ! shutdown )
|
||||
log.error(t,t);
|
||||
}finally{
|
||||
dataset.getLock().leaveCriticalSection();
|
||||
adjacentNodes = null;
|
||||
adjacentNodesConcat = null;
|
||||
coauthorBuff = null;
|
||||
}
|
||||
return info;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void modifyDocument(Individual individual, SearchInputDocument doc) {
|
||||
// TODO Auto-generated method stub
|
||||
// calculate beta value.
|
||||
log.debug("Parameter calculation starts..");
|
||||
float beta = calculateBeta(individual.getURI());
|
||||
doc.addField(VitroSearchTermNames.BETA, (Object) beta);
|
||||
doc.setDocumentBoost(beta + doc.getDocumentBoost() );
|
||||
log.debug("Parameter calculation is done");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void shutdown(){
|
||||
shutdown=true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.getClass().getSimpleName() + "[]";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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(){
|
||||
int totalInd=0;
|
||||
Query query;
|
||||
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());
|
||||
}
|
||||
//CalculateParameters.totalInd = totalInd;
|
||||
//log.info("Total number of individuals in the system are : " + CalculateParameters.totalInd);
|
||||
}catch(Throwable t){
|
||||
log.error(t,t);
|
||||
}finally{
|
||||
if( qexec != null )
|
||||
qexec.close();
|
||||
dataset.getLock().leaveCriticalSection();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,432 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.searchindex.extensions;
|
||||
|
||||
import static edu.cornell.mannlib.vitro.webapp.search.VitroSearchTermNames.ALLTEXT;
|
||||
import static edu.cornell.mannlib.vitro.webapp.search.VitroSearchTermNames.ALLTEXTUNSTEMMED;
|
||||
import static edu.cornell.mannlib.vitro.webapp.utils.sparql.SelectQueryRunner.createQueryContext;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import com.hp.hpl.jena.rdf.model.ResourceFactory;
|
||||
import com.hp.hpl.jena.rdf.model.Statement;
|
||||
import com.hp.hpl.jena.vocabulary.RDFS;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.modelaccess.ContextModelAccess;
|
||||
import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchInputDocument;
|
||||
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
|
||||
import edu.cornell.mannlib.vitro.webapp.searchindex.documentBuilding.DocumentModifier;
|
||||
import edu.cornell.mannlib.vitro.webapp.searchindex.indexing.IndexingUriFinder;
|
||||
import edu.cornell.mannlib.vitro.webapp.utils.configuration.ContextModelsUser;
|
||||
import edu.cornell.mannlib.vitro.webapp.utils.configuration.Property;
|
||||
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.
|
||||
* :hasIncomingProperty -- Required. Property leading to the context node.
|
||||
* :hasOutgoingProperty -- Required. Property leading from the context node.
|
||||
* :hasTypeRestriction -- Optional. Match any. If none, then no restriction.
|
||||
* :appliesToContextNodeType -- Optional. Match any. If none, then no restriction.
|
||||
* </pre>
|
||||
*/
|
||||
public class LabelsAcrossContextNodes implements IndexingUriFinder,
|
||||
DocumentModifier, ContextModelsUser {
|
||||
private static final Log log = LogFactory
|
||||
.getLog(LabelsAcrossContextNodes.class);
|
||||
|
||||
private RDFService rdfService;
|
||||
|
||||
/**
|
||||
* A name to be used in logging, to identify this instance. If not provided,
|
||||
* then a descriptive label will be created.
|
||||
*/
|
||||
private String label;
|
||||
|
||||
/**
|
||||
* The URI of the property that leads into the context node. Required.
|
||||
*/
|
||||
private String incomingPropertyUri;
|
||||
|
||||
/**
|
||||
* The URI of the property that leads from the context node. Required.
|
||||
*/
|
||||
private String outgoingPropertyUri;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
private Set<String> typeRestrictions = new HashSet<>();
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
private Set<String> contextNodeClasses = new HashSet<>();
|
||||
|
||||
@Override
|
||||
public void setContextModels(ContextModelAccess models) {
|
||||
this.rdfService = models.getRDFService();
|
||||
}
|
||||
|
||||
@Property(uri = "http://www.w3.org/2000/01/rdf-schema#label")
|
||||
public void setLabel(String l) {
|
||||
label = l;
|
||||
}
|
||||
|
||||
@Property(uri = "http://vitro.mannlib.cornell.edu/ns/vitro/ApplicationSetup#hasIncomingProperty")
|
||||
public void setIncomingProperty(String incomingUri) {
|
||||
if (incomingPropertyUri == null) {
|
||||
incomingPropertyUri = incomingUri;
|
||||
} else {
|
||||
throw new IllegalStateException(
|
||||
"Configuration includes multiple declarations for hasIncomingProperty: "
|
||||
+ incomingPropertyUri + ", and " + incomingUri);
|
||||
}
|
||||
}
|
||||
|
||||
@Property(uri = "http://vitro.mannlib.cornell.edu/ns/vitro/ApplicationSetup#hasOutgoingProperty")
|
||||
public void setOutgoingProperty(String outgoingUri) {
|
||||
if (outgoingPropertyUri == null) {
|
||||
outgoingPropertyUri = outgoingUri;
|
||||
} else {
|
||||
throw new IllegalStateException(
|
||||
"Configuration includes multiple declarations for hasOutgoingProperty: "
|
||||
+ outgoingPropertyUri + ", and " + outgoingUri);
|
||||
}
|
||||
}
|
||||
|
||||
@Property(uri = "http://vitro.mannlib.cornell.edu/ns/vitro/ApplicationSetup#hasTypeRestriction")
|
||||
public void addTypeRestriction(String typeUri) {
|
||||
typeRestrictions.add(typeUri);
|
||||
}
|
||||
|
||||
@Property(uri = "http://vitro.mannlib.cornell.edu/ns/vitro/ApplicationSetup#appliesToContextNodeType")
|
||||
public void addContextNodeClass(String cnc) {
|
||||
contextNodeClasses.add(cnc);
|
||||
}
|
||||
|
||||
@Validation
|
||||
public void validate() {
|
||||
if (label == null) {
|
||||
label = String.format("%s[types=%s, contextNodeTypes=%s]", this
|
||||
.getClass().getSimpleName(),
|
||||
formatRestrictions(typeRestrictions),
|
||||
formatRestrictions(contextNodeClasses));
|
||||
}
|
||||
if (incomingPropertyUri == null) {
|
||||
throw new IllegalStateException(
|
||||
"Configuration did not declare hasIncomingProperty.");
|
||||
}
|
||||
if (outgoingPropertyUri == null) {
|
||||
throw new IllegalStateException(
|
||||
"Configuration did not declare hasOutgoingProperty.");
|
||||
}
|
||||
}
|
||||
|
||||
private String formatRestrictions(Set<String> uris) {
|
||||
if (uris.isEmpty()) {
|
||||
return "ALL";
|
||||
} else {
|
||||
return localNames(uris).toString();
|
||||
}
|
||||
}
|
||||
|
||||
private Set<String> localNames(Set<String> uris) {
|
||||
Set<String> names = new HashSet<>();
|
||||
for (String uri : uris) {
|
||||
try {
|
||||
names.add(ResourceFactory.createResource(uri).getLocalName());
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to parse URI: " + uri, e);
|
||||
names.add(uri);
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return (label == null) ? super.toString() : label;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// DocumentModifier
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private static final String LABELS_WITHOUT_RESTRICTION = ""
|
||||
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n"
|
||||
+ "SELECT ?label \n" //
|
||||
+ "WHERE { \n" //
|
||||
+ " ?uri ?incoming ?contextNode . \n" //
|
||||
+ " ?contextNode ?outgoing ?partner . \n" //
|
||||
+ " ?partner rdfs:label ?label . \n" //
|
||||
+ " FILTER( ?uri != ?partner ) \n" //
|
||||
+ "} \n";
|
||||
private static final String LABELS_FOR_SPECIFIC_CONTEXT_NODE_TYPE = ""
|
||||
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n"
|
||||
+ "SELECT ?label \n" //
|
||||
+ "WHERE { \n" //
|
||||
+ " ?uri ?incoming ?contextNode . \n" //
|
||||
+ " ?contextNode a ?nodeType . \n" //
|
||||
+ " ?contextNode ?outgoing ?partner . \n" //
|
||||
+ " ?partner rdfs:label ?label . \n" //
|
||||
+ " FILTER( ?uri != ?partner ) \n" //
|
||||
+ "} \n";
|
||||
|
||||
/**
|
||||
* If this individual is acceptable, locate the labels of any context
|
||||
* partners across acceptable context nodes. Add those labels to the text
|
||||
* fields of the search document.
|
||||
*/
|
||||
@Override
|
||||
public void modifyDocument(Individual ind, SearchInputDocument doc) {
|
||||
if (passesTypeRestriction(ind)) {
|
||||
if (contextNodeClasses.isEmpty()) {
|
||||
addLabelsFromAllContextNodeClasses(ind, doc);
|
||||
} else {
|
||||
for (String contextNodeClass : contextNodeClasses) {
|
||||
addLabelsFromContextNodeClass(ind, doc, contextNodeClass);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean passesTypeRestriction(Individual ind) {
|
||||
if (typeRestrictions.isEmpty()) {
|
||||
return true;
|
||||
} else {
|
||||
for (VClass type : ind.getVClasses()) {
|
||||
if (typeRestrictions.contains(type.getURI())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void addLabelsFromAllContextNodeClasses(Individual ind,
|
||||
SearchInputDocument doc) {
|
||||
addValuesToTextFields(doc,
|
||||
createQueryContext(rdfService, LABELS_WITHOUT_RESTRICTION)
|
||||
.bindVariableToUri("uri", ind.getURI())
|
||||
.bindVariableToUri("incoming", incomingPropertyUri)
|
||||
.bindVariableToUri("outgoing", outgoingPropertyUri)
|
||||
.execute().getStringFields("label").flatten());
|
||||
}
|
||||
|
||||
private void addLabelsFromContextNodeClass(Individual ind,
|
||||
SearchInputDocument doc, String contextNodeClass) {
|
||||
addValuesToTextFields(
|
||||
doc,
|
||||
createQueryContext(rdfService,
|
||||
LABELS_FOR_SPECIFIC_CONTEXT_NODE_TYPE)
|
||||
.bindVariableToUri("uri", ind.getURI())
|
||||
.bindVariableToUri("nodeType", contextNodeClass)
|
||||
.bindVariableToUri("incoming", incomingPropertyUri)
|
||||
.bindVariableToUri("outgoing", outgoingPropertyUri)
|
||||
.execute().getStringFields("label").flatten());
|
||||
}
|
||||
|
||||
private void addValuesToTextFields(SearchInputDocument doc,
|
||||
List<String> values) {
|
||||
for (String value : values) {
|
||||
doc.addField(ALLTEXT, value);
|
||||
doc.addField(ALLTEXTUNSTEMMED, value);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
// Nothing to shut down.
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// IndexingUriFinder
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private static final String LOCATE_PARTNERS_WITHOUT_RESTRICTION = ""
|
||||
+ "SELECT ?partner \n" //
|
||||
+ "WHERE { \n" //
|
||||
+ " ?partner ?incoming ?contextNode . \n" //
|
||||
+ " ?contextNode ?outgoing ?uri . \n" //
|
||||
+ " FILTER( ?uri != ?partner ) \n" //
|
||||
+ "} \n";
|
||||
private static final String LOCATE_PARTNERS_ON_CONTEXT_NODE_TYPE = ""
|
||||
+ "SELECT ?partner \n" //
|
||||
+ "WHERE { \n" //
|
||||
+ " ?partner ?incoming ?contextNode . \n" //
|
||||
+ " ?contextNode ?outgoing ?uri . \n" //
|
||||
+ " ?contextNode a ?nodeType . \n" //
|
||||
+ " FILTER( ?uri != ?partner ) \n" //
|
||||
+ "} \n";
|
||||
private static final String LOCATE_OTHER_PARTNERS_ON_THIS_NODE = ""
|
||||
+ "SELECT ?partner \n" //
|
||||
+ "WHERE { \n" //
|
||||
+ " ?contextNode ?outgoing ?partner . \n" //
|
||||
+ " FILTER( ?uri != ?partner ) \n" //
|
||||
+ "} \n";
|
||||
private static final String GET_TYPES = "" //
|
||||
+ "SELECT ?type \n" //
|
||||
+ "WHERE { \n" //
|
||||
+ " ?uri a ?type . \n" //
|
||||
+ "} \n";
|
||||
|
||||
@Override
|
||||
public void startIndexing() {
|
||||
// Nothing to do.
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
@Override
|
||||
public List<String> findAdditionalURIsToIndex(Statement stmt) {
|
||||
if (isLabelStatement(stmt)) {
|
||||
return filterByType(locatePartners(stmt));
|
||||
} else if (isIncomingStatementOnAcceptableContextNode(stmt)) {
|
||||
return filterByType(locateOtherPartners(stmt));
|
||||
}
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
private boolean isLabelStatement(Statement stmt) {
|
||||
return RDFS.label.getURI().equals(stmt.getPredicate().getURI());
|
||||
}
|
||||
|
||||
private Set<String> locatePartners(Statement stmt) {
|
||||
String uri = stmt.getSubject().getURI();
|
||||
if (contextNodeClasses.isEmpty()) {
|
||||
return locatePartnersWithoutRestriction(uri);
|
||||
} else {
|
||||
Set<String> uris = new HashSet<>();
|
||||
for (String contextNodeClass : contextNodeClasses) {
|
||||
uris.addAll(locatePartnersAcrossContextNodeClass(uri,
|
||||
contextNodeClass));
|
||||
}
|
||||
return uris;
|
||||
}
|
||||
}
|
||||
|
||||
private Set<String> locatePartnersWithoutRestriction(String uri) {
|
||||
return createQueryContext(rdfService,
|
||||
LOCATE_PARTNERS_WITHOUT_RESTRICTION)
|
||||
.bindVariableToUri("uri", uri)
|
||||
.bindVariableToUri("incoming", incomingPropertyUri)
|
||||
.bindVariableToUri("outgoing", outgoingPropertyUri).execute()
|
||||
.getStringFields("partner").flattenToSet();
|
||||
}
|
||||
|
||||
private Collection<? extends String> locatePartnersAcrossContextNodeClass(
|
||||
String uri, String contextNodeClass) {
|
||||
return createQueryContext(rdfService,
|
||||
LOCATE_PARTNERS_ON_CONTEXT_NODE_TYPE)
|
||||
.bindVariableToUri("uri", uri)
|
||||
.bindVariableToUri("nodeType", contextNodeClass)
|
||||
.bindVariableToUri("incoming", incomingPropertyUri)
|
||||
.bindVariableToUri("outgoing", outgoingPropertyUri).execute()
|
||||
.getStringFields("partner").flattenToSet();
|
||||
}
|
||||
|
||||
private boolean isIncomingStatementOnAcceptableContextNode(Statement stmt) {
|
||||
String subjectUri = stmt.getSubject().getURI();
|
||||
String predicateUri = stmt.getPredicate().getURI();
|
||||
|
||||
if (incomingPropertyUri.equals(predicateUri)
|
||||
&& (contextNodeClasses.isEmpty() || isAnyMatch(
|
||||
contextNodeClasses, getTypes(subjectUri)))) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isAnyMatch(Set<String> set1, Set<String> set2) {
|
||||
Set<String> matches = new HashSet<>(set1);
|
||||
matches.retainAll(set2);
|
||||
return !matches.isEmpty();
|
||||
}
|
||||
|
||||
private Set<String> getTypes(String uri) {
|
||||
return createQueryContext(rdfService, GET_TYPES)
|
||||
.bindVariableToUri("uri", uri).execute()
|
||||
.getStringFields("type").flattenToSet();
|
||||
}
|
||||
|
||||
private Set<String> locateOtherPartners(Statement stmt) {
|
||||
if (!stmt.getSubject().isURIResource()) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
String nodeUri = stmt.getSubject().getURI();
|
||||
String objectUri = (stmt.getObject().isURIResource()) ? stmt
|
||||
.getObject().asResource().getURI() : "NO_MATCH";
|
||||
|
||||
return createQueryContext(rdfService,
|
||||
LOCATE_OTHER_PARTNERS_ON_THIS_NODE)
|
||||
.bindVariableToUri("contextNode", nodeUri)
|
||||
.bindVariableToUri("uri", objectUri)
|
||||
.bindVariableToUri("outgoing", outgoingPropertyUri).execute()
|
||||
.getStringFields("partner").flattenToSet();
|
||||
}
|
||||
|
||||
private List<String> filterByType(Collection<String> uris) {
|
||||
if (typeRestrictions.isEmpty()) {
|
||||
return new ArrayList<>(uris);
|
||||
} else {
|
||||
List<String> filtered = new ArrayList<>();
|
||||
for (String uri : uris) {
|
||||
if (isAnyMatch(typeRestrictions, getTypes(uri))) {
|
||||
filtered.add(uri);
|
||||
}
|
||||
}
|
||||
return filtered;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void endIndexing() {
|
||||
// Nothing to do.
|
||||
}
|
||||
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue