diff --git a/productMods/templates/freemarker/edit/forms/addGrantRoleToPerson.ftl b/productMods/templates/freemarker/edit/forms/addGrantRoleToPerson.ftl index 4300ae78..41e55e18 100644 --- a/productMods/templates/freemarker/edit/forms/addGrantRoleToPerson.ftl +++ b/productMods/templates/freemarker/edit/forms/addGrantRoleToPerson.ftl @@ -2,32 +2,53 @@ <#-- Template for adding a grant role, such as principal investigator, to a foaf:Persons --> <#import "lib-vivo-form.ftl" as lvf> - -<#if editConfig.object?has_content> - <#assign editMode = "edit"> -<#else> - <#assign editMode = "add"> +<#--Retrieve certain edit configuration information--> +<#assign editMode = editConfiguration.pageData.editMode /> +<#assign literalValues = editConfiguration.existingLiteralValues /> +<#assign uriValues = editConfiguration.existingUriValues /> +<#assign htmlForElements = editConfiguration.pageData.htmlForElements /> +<#assign sparqlForAcFilter = editConfiguration.pageData.sparqlForAcFilter /> +<#assign disabledVal = ""/> +<#if editMode = "edit"> + <#assign disabledVal = "" /> -<#if editMode == "edit"> - <#assign titleVerb="Edit"> - <#assign submitButtonText="Edit Grant"> - <#assign disabledVal="disabled"> -<#else> - <#assign titleVerb="Create"> - <#assign submitButtonText="Create Grant"> - <#assign disabledVal=""/> +<#--the heading and submit button label depend on the predicate uri--> +<#assign formHeading = "investigator entry for "/> +<#assign submitButtonLabel = "Edit Investigator" /> +<#if editConfiguration.predicateUri?ends_with("hasPrincipalInvestigatorRole") > + <#assign formHeading = "principal investigator entry for "/> + <#assign submitButtonLabel = "Edit Principal Investigator" /> +<#elseif editConfiguration.predicateUri?ends_with("hasCo-PrincipalInvestigatorRole") > + <#assign formHeading = "co-principal investigator entry for "/> + <#assign submitButtonLabel = "Edit Co-Principal Investigator" /> +<#--Get existing value for specific data literals and uris--> + + +<#--Get selected activity type value if it exists, this is alternative to below--> +<#assign grantLabel = ""/> +<#if literalValues?keys?seq_contains("grantLabel") && (literalValues.grantLabel?size > 0)> + <#assign grantLabel = literalValues.grantLabel[0] /> + + + <#--Get existing grant label value--> +<#assign existingGrantLabel = "" /> +<#if literalValues?keys?seq_contains("existingGrantLabel") && (literalValues.existingGrantLabel?size > 0)> + <#assign existingGrantLabel = literalValues.existingGrantLabel[0] /> + + + <#assign requiredHint = " *" /> <#assign yearHint = "(YYYY)" /> -<#if editMode = “ERROR”> +<#if editMode = "error">
This form is unable to handle the editing of this position because it is associated with multiple Position individuals.
<#else> -

${titleVerb} ${roleDescriptor} entry for ${subjectName}

+

${formHeading} ${editConfiguration.subjectName}

<#if errorNameFieldIsEmpty??> <#assign errorMessage = "Enter a name for the grant." /> @@ -42,72 +63,79 @@
-<@lvf.unsupportedBrowser> +<@lvf.unsupportedBrowser/>

- +

- <#-- DO WE NEED THIS?? - Store this value in a hidden field, because the displayed field is disabled and doesn't submit. This ensures that when - returning from a validation error, we retain the value. - <#if editMode == "edit"> - - - --> + <#if editMode = "edit"> + +

(Verify this match)

- + - + <#--Field value populated by javascript above--> +
-

Years of Participation in Grant

- - -
- -
- - -
- -
- +

Years of Participation in Grant

+ <#if htmlForElements?keys?seq_contains("startField")> + + ${htmlForElements["startField"]} + + <#if htmlForElements?keys?seq_contains("endField")> + + ${htmlForElements["endField"]} + +

- - or Cancel + + or Cancel

* required fields

- -<#assign acUrl value="/autocomplete?tokenize=true" /> +
+<#assign acUrl="/autocomplete?tokenize=true" /> <#assign sparqlQueryUrl ="/ajax/sparqlQuery" /> -<#assign sparqlForAcFilter = "PREFIX core: <${vivoCore}> SELECT ?grantUri WHERE {<${subjectUri}> <${predicateUri}> ?grantRole . ?grantRole core:roleIn ?grantUri .}>" +${stylesheets.add('')} +${stylesheets.add('')} +${stylesheets.add('')} - - +${scripts.add('')} +${scripts.add('')} +${scripts.add('')} + +<#-- +Scripts based on jsp also include browserUtils +${scripts.add('')} +${scripts.add('')} +${scripts.add('')} +${scripts.add('')} +--> + \ No newline at end of file diff --git a/productMods/templates/freemarker/edit/forms/newIndividualForm.ftl b/productMods/templates/freemarker/edit/forms/newIndividualForm.ftl index f101c08b..a840f606 100644 --- a/productMods/templates/freemarker/edit/forms/newIndividualForm.ftl +++ b/productMods/templates/freemarker/edit/forms/newIndividualForm.ftl @@ -2,8 +2,11 @@ <#-- Template for adding a new individual from the Site Admin page: VIVO version --> +<#--Retrieve certain edit configuration information--> +<#assign typeName = editConfiguration.pageData.typeName /> +<#assign isPersonType = editConfiguration.pageData.isPersonType /> -

Create a new ${subclassName}

+

Create a new ${typeName}

<#if errorFirstNameIsEmpty??> <#assign errorMessage = "Enter a first name." /> @@ -30,7 +33,7 @@
- <#if isPersonType > + <#if isPersonType = "true">

@@ -43,14 +46,14 @@ <#else>

- +

- - - or Cancel + + + or Cancel

* required fields

diff --git a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddGrantRoleToPersonGenerator.java b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddGrantRoleToPersonGenerator.java new file mode 100644 index 00000000..12fa6cc9 --- /dev/null +++ b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddGrantRoleToPersonGenerator.java @@ -0,0 +1,875 @@ +/* $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.rdf.model.Literal; +import com.hp.hpl.jena.rdf.model.Model; +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.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.EditConfigurationUtils; +import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo; +import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditN3GeneratorVTwo; +import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.FieldVTwo; +import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils; +import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils.EditMode; +/** + * Custom form for adding a grant to an person for the predicates hasCo-PrincipalInvestigatorRole + and hasPrincipalInvestigatorRole. + +This is intended to create a set of statements like: + +?person core:hasPrincipalInvestigatorRole ?newRole. +?newRole rdf:type core:PrincipalInvestigatorRole ; + core:relatedRole ?someGrant . + + * + */ +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(); + //Set n3 generator + editConfiguration.setN3Generator(new EditN3GeneratorVTwo(editConfiguration)); + + //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()); + + //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 validator + editConfiguration.addValidator(new DateTimeIntervalValidationVTwo("startField","endField") ); + //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.getFormUrl(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 + this.initObjectParameters(vreq); + this.processObjectPropForm(vreq, editConfiguration); + + } + + + + private void initObjectParameters(VitroRequest vreq) { + //in case of object property + objectUri = EditConfigurationUtils.getObjectUri(vreq); + } + + 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 + if(objectUri != null) { + editConfiguration.setObjectResource(true); + } + } + + + /* + * N3 Required and Optional Generators as well as supporting methods + */ + + private String getPrefixesString() { + //TODO: Include dynamic way of including this + return "@prefix core: ."; + } + + //TODO: Check if single string or multiple strings - check rdfslabel form etc. for prefix + //processing + private List generateN3Required(VitroRequest vreq) { + List n3ForEdit = new ArrayList(); + String editString = getN3ForGrantRole(vreq); + n3ForEdit.add(editString); + return n3ForEdit; + } + + + private List generateN3Optional(VitroRequest vreq) { + List n3Optional = new ArrayList(); + //n3 for grant label + n3Optional.add(getN3ForGrantLabel(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) + "> ."; + editString += "?role <" + getRoleToGrantPredicate(vreq) + "> ?grant ."; + editString += "?grant a core:Grant ;" + + "core:relatedRole ?role ."; + return editString; + } + + public String getN3ForGrantLabel(VitroRequest vreq) { + return "?grant <" + RDFS.label.getURI() + "> ?grantLabel ."; + + } + + //Method b/c used in two locations, n3 optional and n3 assertions + private List getN3ForStart() { + List n3ForStart = new ArrayList(); + 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 getN3ForEnd() { + List n3ForEnd = new ArrayList(); + 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 generateNewResources(VitroRequest vreq) { + HashMap newResources = new HashMap(); + //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> urisInScope = new HashMap>(); + //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>()); + } + + private List getInversePredicate(VitroRequest vreq) { + List inversePredicateArray = new ArrayList(); + 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 urisOnForm = new ArrayList(); + List literalsOnForm = new ArrayList(); + //add role activity and roleActivityType to uris on form + urisOnForm.add("grant"); + editConfiguration.setUrisOnform(urisOnForm); + //activity label and role label are literals on form + literalsOnForm.add("grantLabel"); + literalsOnForm.add("existingGrantLabel"); + 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()); + + Map urisInScope = new HashMap(); + editConfiguration.setSparqlForAdditionalUrisInScope(urisInScope); + + editConfiguration.setSparqlForExistingLiterals(generateSparqlForExistingLiterals(vreq)); + editConfiguration.setSparqlForExistingUris(generateSparqlForExistingUris(vreq)); + } + + + //Get page uri for object + private HashMap generateSparqlForExistingUris(VitroRequest vreq) { + HashMap map = new HashMap(); + //Queries for role activity, activity type query, interval node, start node, end node, start field precision, endfield precision + map.put("grant", getGrantQuery(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 generateSparqlForExistingLiterals(VitroRequest vreq) { + HashMap map = new HashMap(); + //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 getGrantQuery(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 fields = new HashMap(); + //Multiple fields + getGrantField(editConfiguration, vreq, fields); + getGrantLabelField(editConfiguration, vreq, fields); + getExistingGrantLabelField(editConfiguration, vreq, fields); + getStartField(editConfiguration, vreq, fields); + getEndField(editConfiguration, vreq, fields); + editConfiguration.setFields(fields); + } + + private void getGrantField(EditConfigurationVTwo editConfiguration, + VitroRequest vreq, Map fields) { + String fieldName = "grant"; + + FieldVTwo field = new FieldVTwo(); + field.setName(fieldName); + field.setNewResource(false); + //queryForExisting is not being used anywhere in Field + + List validators = new ArrayList(); + field.setValidators(validators); + + //subjectUri and subjectClassUri are not being used in Field + + field.setOptionsType("UNDEFINED"); + //why isn't predicate uri set for data properties? + field.setPredicateUri(null); + field.setObjectClassUri(getGrantType()); + field.setRangeDatatypeUri(null); + + field.setLiteralOptions(new ArrayList>()); + + //set assertions + List assertions = new ArrayList(); + assertions.add(getN3ForGrantRole(vreq)); + field.setAssertions(assertions); + fields.put(field.getName(), field); + + } + + private void getGrantLabelField(EditConfigurationVTwo editConfiguration, + VitroRequest vreq, Map fields) { + String fieldName = "grantLabel"; + //get range data type uri and range language + String stringDatatypeUri = XSD.xstring.toString(); + + FieldVTwo field = new FieldVTwo(); + field.setName(fieldName); + field.setNewResource(false); + //queryForExisting is not being used anywhere in Field + + //Not really interested in validators here + List validators = new ArrayList(); + validators.add("datatype:" + stringDatatypeUri); + if(isAddMode(vreq) || isRepairMode(vreq)) { + validators.add("nonempty"); + } + field.setValidators(validators); + + //subjectUri and subjectClassUri are not being used in Field + + field.setOptionsType("UNDEFINED"); + //why isn't predicate uri set for data properties? + field.setPredicateUri(null); + field.setObjectClassUri(null); + field.setRangeDatatypeUri(null); + + field.setLiteralOptions(new ArrayList>()); + + //set assertions + List assertions = new ArrayList(); + assertions.add(getN3ForGrantLabel(vreq)); + assertions.add(getN3ForGrantRole(vreq)); + field.setAssertions(assertions); + fields.put(field.getName(), field); + + } + + //Need if returning from an invalid submission + private void getExistingGrantLabelField( + EditConfigurationVTwo editConfiguration, VitroRequest vreq, + Map fields) { + String fieldName = "existingGrantLabel"; + + FieldVTwo field = new FieldVTwo(); + field.setName(fieldName); + field.setNewResource(false); + //queryForExisting is not being used anywhere in Field + + //Not really interested in validators here + List validators = new ArrayList(); + field.setValidators(validators); + + //subjectUri and subjectClassUri are not being used in Field + + field.setOptionsType("UNDEFINED"); + //why isn't predicate uri set for data properties? + field.setPredicateUri(null); + field.setObjectClassUri(null); + field.setRangeDatatypeUri(null); + field.setLiteralOptions(new ArrayList>()); + + //set assertions + List assertions = new ArrayList(); + field.setAssertions(assertions); + fields.put(field.getName(), field); + } + + private void getStartField(EditConfigurationVTwo editConfiguration, + VitroRequest vreq, Map fields) { + String fieldName = "startField"; + + FieldVTwo field = new FieldVTwo(); + field.setName(fieldName); + field.setNewResource(false); + + List validators = new ArrayList(); + field.setValidators(validators); + + //subjectUri and subjectClassUri are not being used in Field + + field.setOptionsType("UNDEFINED"); + //why isn't predicate uri set for data properties? + field.setPredicateUri(null); + field.setObjectClassUri(null); + field.setRangeDatatypeUri(null); + //empty + field.setLiteralOptions(new ArrayList>()); + + //set assertions + List assertions = new ArrayList(); + assertions.addAll(getN3ForStart()); + field.setAssertions(assertions); + + //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 fields) { + String fieldName = "endField"; + + FieldVTwo field = new FieldVTwo(); + field.setName(fieldName); + field.setNewResource(false); + + List validators = new ArrayList(); + field.setValidators(validators); + + //subjectUri and subjectClassUri are not being used in Field + + field.setOptionsType("UNDEFINED"); + //why isn't predicate uri set for data properties? + field.setPredicateUri(null); + field.setObjectClassUri(null); + field.setRangeDatatypeUri(null); + //empty + field.setLiteralOptions(new ArrayList>()); + + //set assertions + List assertions = new ArrayList(); + assertions.addAll(getN3ForEnd()); + field.setAssertions(assertions); + //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 + Model model = (Model) session.getServletContext().getAttribute("jenaOntModel"); + //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 that are REQUIRED to be implemented in subclasses + **/ + //role type will always be set based on particular form + public String getRoleType(VitroRequest vreq) { + String predicateUri = EditConfigurationUtils.getPredicateUri(vreq); + if(predicateUri.equals(getHasPrincipalInvestigatorURI())) { + return getVivoOntologyCoreNamespace() + "PrincipalInvestigatorRole"; + } + else if(predicateUri.equals(getHasCoPrincipalInvestigatorURI())) { + return getVivoOntologyCoreNamespace() + "CoPrincipalInvestigatorRole"; + } else { + return getVivoOntologyCoreNamespace() + "InvestigatorRole"; + } + } + + private Object getHasCoPrincipalInvestigatorURI() { + return getVivoOntologyCoreNamespace() + "hasPrincipalInvestigatorRole"; + } + + + //TODO: More dynamic way of getting this or standard mechanism + private String getVivoOntologyCoreNamespace() { + return "http://vivoweb.org/ontology/core#"; + } + + private Object getHasPrincipalInvestigatorURI() { + return getVivoOntologyCoreNamespace() + "hasCo-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#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#relatedRole"; + } + + //roleToGrantPredicate + public String getDefaultroleToGrantPredicate() { + return "http://vivoweb.org/ontology/core#roleIn"; + + } + + public List getPossibleroleToGrantPredicates() { + return ModelUtils.getPossiblePropertiesForRole(); + } + + public List getPossiblegrantToRolePredicates() { + return ModelUtils.getPossibleInversePropertiesForRole(); + } + + /** + * Methods that check edit mode + */ + + //Get edit mode + private EditMode getEditMode(VitroRequest vreq) { + List roleToGrantPredicates = getPossibleroleToGrantPredicates(); + //We're making some assumptions here: That there is only one role objec tot one activity object + //pairing, i.e. the same role object can't be related to a different activity object + //That said, there should only be one role to Activity predicate linking a role to an activity + //So if + Individual object = EditConfigurationUtils.getObjectIndividual(vreq); + boolean foundErrorMode = false; + int numberEditModes = 0; + int numberRepairModes = 0; + int numberPredicates = roleToGrantPredicates.size(); + for(String predicate:roleToGrantPredicates) { + EditMode mode = FrontEndEditingUtils.getEditMode(vreq, object, predicate); + //Any error mode should result in error + if(mode == EditMode.ERROR) { + foundErrorMode = true; + break; + } + if(mode == EditMode.EDIT) { + numberEditModes++; + } + else if(mode == EditMode.REPAIR) { + numberEditModes++; + } + + } + + //if found an error or if more than one edit mode returned, incorrect + + if(foundErrorMode || numberEditModes > 1) + { + return EditMode.ERROR; + } + EditMode mode = EditMode.ADD; + //if exactly one edit mode found, then edit mode + if(numberEditModes == 1) { + mode = EditMode.EDIT; + } + //if all modes are repair, this means that all of them have zero statements returning + //which is incorrect + if(numberRepairModes == numberPredicates) { + mode = EditMode.REPAIR; + } + //otherwise all the modes are Add and Add will be returned + return mode; + } + private boolean isAddMode(VitroRequest vreq) { + EditMode mode = getEditMode(vreq); + return (mode == EditMode.ADD); + } + + private boolean isEditMode(VitroRequest vreq) { + EditMode mode = getEditMode(vreq); + return (mode == EditMode.EDIT); + } + + private boolean isRepairMode(VitroRequest vreq) { + EditMode mode = getEditMode(vreq); + return (mode == EditMode.REPAIR); + } + + + /** + * 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 formSpecificData = new HashMap(); + formSpecificData.put("editMode", getEditMode(vreq).name().toLowerCase()); + //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() + "> \n" + + "SELECT ?grantUri WHERE { \n" + + "<" + subject + "> <" + predicate + "> ?grantRole .\n" + + "?grantRole <" + getRoleToGrantPredicate(vreq) + "> ?grantUri . }"; + return query; + } + + + + + +} diff --git a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddRoleToPersonTwoStageGenerator.java b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddRoleToPersonTwoStageGenerator.java index c34d8022..9daf872f 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddRoleToPersonTwoStageGenerator.java +++ b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddRoleToPersonTwoStageGenerator.java @@ -1099,36 +1099,45 @@ public abstract class AddRoleToPersonTwoStageGenerator implements EditConfigurat //pairing, i.e. the same role object can't be related to a different activity object //That said, there should only be one role to Activity predicate linking a role to an activity //So if - List editModes = new ArrayList(); Individual object = EditConfigurationUtils.getObjectIndividual(vreq); - boolean foundEditMode = false; boolean foundErrorMode = false; - boolean onlyRepairModes = true; + int numberEditModes = 0; + int numberRepairModes = 0; + int numberPredicates = roleToActivityPredicates.size(); for(String predicate:roleToActivityPredicates) { EditMode mode = FrontEndEditingUtils.getEditMode(vreq, object, predicate); - //TODO: Check what to do with repair, because unclear - if(mode != EditMode.REPAIR) { - onlyRepairModes = false; - } - if(mode == EditMode.EDIT) { - foundEditMode = true; - break; - } + //Any error mode should result in error if(mode == EditMode.ERROR) { foundErrorMode = true; break; } + if(mode == EditMode.EDIT) { + numberEditModes++; + } + else if(mode == EditMode.REPAIR) { + numberEditModes++; + } + + } + + //if found an error or if more than one edit mode returned, incorrect + + if(foundErrorMode || numberEditModes > 1) + { + return EditMode.ERROR; } EditMode mode = EditMode.ADD; - //if found one edit or error, then sufficient - - if(foundEditMode) mode = EditMode.EDIT; - if(foundErrorMode) mode = EditMode.ERROR; - //if all results are repair, then we need to repair - //doing this this way b/c unclear since zero statements may be returned otherwise - if(onlyRepairModes) mode = EditMode.REPAIR; + //if exactly one edit mode found, then edit mode + if(numberEditModes == 1) { + mode = EditMode.EDIT; + } + //if all modes are repair, this means that all of them have zero statements returning + //which is incorrect + if(numberRepairModes == numberPredicates) { + mode = EditMode.REPAIR; + } + //otherwise all the modes are Add and Add will be returned return mode; - //(mode == EditMode.ADD || mode == EditMode.REPAIR) ? "\"nonempty\" } private boolean isAddMode(VitroRequest vreq) { EditMode mode = getEditMode(vreq); diff --git a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/NewIndividualFormGenerator.java b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/NewIndividualFormGenerator.java new file mode 100644 index 00000000..6dd82528 --- /dev/null +++ b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/NewIndividualFormGenerator.java @@ -0,0 +1,435 @@ +/* $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.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.edit.n3editing.VTwo.EditConfigurationUtils; + + +import com.hp.hpl.jena.rdf.model.Literal; +import com.hp.hpl.jena.rdf.model.Model; +import com.hp.hpl.jena.vocabulary.RDFS; +import com.hp.hpl.jena.vocabulary.XSD; +import com.hp.hpl.jena.ontology.OntModel; +import edu.cornell.mannlib.vitro.webapp.beans.DataProperty; +import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement; +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.controller.freemarker.responsevalues.ResponseValues; +import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues; +import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary; +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.EditConfigurationVTwo; +import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field; +import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.RdfLiteralHash; +import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditN3GeneratorVTwo; +import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.SelectListGeneratorVTwo; +import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.FieldVTwo; +import edu.cornell.mannlib.vitro.webapp.web.MiscWebUtils; +import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch; + +/** + * Generates the edit configuration for a default property form. + * + */ +public class NewIndividualFormGenerator implements EditConfigurationGenerator { + + private Log log = LogFactory.getLog(NewIndividualFormGenerator.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 = "newIndividualForm.ftl"; + private static HashMap defaultsForXSDtypes ; + static { + defaultsForXSDtypes = new HashMap(); + //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"); + } + @Override + public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) { + EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo(); + //Set n3 generator + editConfiguration.setN3Generator(new EditN3GeneratorVTwo(editConfiguration)); + + //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()); + + //Todo: what do new resources depend on here? + //In original form, these variables start off empty + editConfiguration.setNewResources(this.generateNewResources(vreq)); + //In scope + this.setUrisAndLiteralsInScope(editConfiguration); + + //on Form + this.setUrisAndLiteralsOnForm(editConfiguration, vreq); + + editConfiguration.setFilesOnForm(new ArrayList()); + + //Sparql queries + this.setSparqlQueries(editConfiguration); + + //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); + addFormSpecificData(editConfiguration, vreq); + + return editConfiguration; + + + } + + private Map generateNewResources(VitroRequest vreq) { + HashMap newResources = new HashMap(); + //TODO: Get default namespace + String defaultNamespace = vreq.getWebappDaoFactory().getDefaultNamespace(); + newResources.put("newInd", defaultNamespace + "individual"); + return newResources; + } + + private void setEditKey(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { + String editKey = EditConfigurationUtils.getEditKey(vreq); + editConfiguration.setEditKey(editKey); + } + + private void setTemplate(EditConfigurationVTwo editConfiguration, + VitroRequest vreq) { + editConfiguration.setTemplate(template); + + } + + //Initialize setup: process parameters + private void initProcessParameters(VitroRequest vreq, HttpSession session, EditConfigurationVTwo editConfiguration) { + String formUrl = EditConfigurationUtils.getFormUrl(vreq); + + subjectUri = EditConfigurationUtils.getSubjectUri(vreq); + predicateUri = EditConfigurationUtils.getPredicateUri(vreq); + + editConfiguration.setFormUrl(formUrl); + + editConfiguration.setUrlPatternToReturnTo("/individual"); + + editConfiguration.setVarNameForSubject("subjectNotUsed"); + editConfiguration.setSubjectUri(subjectUri); + editConfiguration.setEntityToReturnTo("?newInd"); + editConfiguration.setVarNameForPredicate("predicateNotUsed"); + editConfiguration.setPredicateUri(predicateUri); + + //not concerned about remainder, can move into default obj prop form if required + this.isObjectPropForm = true; + this.initObjectParameters(vreq); + this.processObjectPropForm(vreq, editConfiguration); + } + + + private void initObjectParameters(VitroRequest vreq) { + //in case of object property + objectUri = EditConfigurationUtils.getObjectUri(vreq); + } + + private void processObjectPropForm(VitroRequest vreq, EditConfigurationVTwo editConfiguration) { + editConfiguration.setVarNameForObject("objectNotUsed"); + 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 + if(objectUri != null) { + editConfiguration.setObjectResource(true); + } + } + + private void processDataPropForm(VitroRequest vreq, EditConfigurationVTwo editConfiguration) { + editConfiguration.setObjectResource(false); + //set data prop value, data prop key str, + editConfiguration.setDatapropKey((datapropKeyStr==null)?"":datapropKeyStr); + editConfiguration.setVarNameForObject(dataLiteral); + //original set datapropValue, which in this case would be empty string but no way here + editConfiguration.setDatapropValue(""); + editConfiguration.setUrlPatternToReturnTo("/entity"); + } + + //Get N3 required + //Handles both object and data property + private List generateN3Required(VitroRequest vreq) { + List n3ForEdit = new ArrayList(); + String editString = "?newInd <" + VitroVocabulary.RDF_TYPE + "> <" + getTypeOfNew(vreq) + "> ."; + n3ForEdit.add(editString); + return n3ForEdit; + } + + private List generateN3Optional() { + List n3Optional = new ArrayList(); + String editString = "@prefix foaf: ." + + " ?newInd foaf:firstName ?firstName ; " + + " ?newInd foaf:lastName ?lastName ."; + n3Optional.add(editString); + n3Optional.add("?newInd <" + RDFS.label.getURI() + "> ?label ."); + return n3Optional; + + } + + //Set queries + private String retrieveQueryForInverse () { + String queryForInverse = "PREFIX owl: " + + " SELECT ?inverse_property " + + " WHERE { ?inverse_property owl:inverseOf ?predicate } "; + return queryForInverse; + } + + private void setUrisAndLiteralsInScope(EditConfigurationVTwo editConfiguration) { + HashMap> urisInScope = new HashMap>(); + //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>()); + } + + //n3 should look as follows + //?subject ?predicate ?objectVar + + private void setUrisAndLiteralsOnForm(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { + List urisOnForm = new ArrayList(); + List literalsOnForm = new ArrayList(); + literalsOnForm.add("label"); + literalsOnForm.add("firstName"); + literalsOnForm.add("lastName"); + editConfiguration.setUrisOnform(urisOnForm); + editConfiguration.setLiteralsOnForm(literalsOnForm); + } + + private String getDataLiteral(VitroRequest vreq) { + DataProperty prop = EditConfigurationUtils.getDataProperty(vreq); + return prop.getLocalName() + "Edited"; + } + + //This is for various items + private void setSparqlQueries(EditConfigurationVTwo editConfiguration) { + //Sparql queries defining retrieval of literals etc. + editConfiguration.setSparqlForAdditionalLiteralsInScope(new HashMap()); + + Map urisInScope = new HashMap(); + editConfiguration.setSparqlForAdditionalUrisInScope(urisInScope); + + editConfiguration.setSparqlForExistingLiterals(generateSparqlForExistingLiterals()); + editConfiguration.setSparqlForExistingUris(generateSparqlForExistingUris()); + } + + + //Get page uri for object + private HashMap generateSparqlForExistingUris() { + HashMap map = new HashMap(); + return map; + } + + private HashMap generateSparqlForExistingLiterals() { + HashMap map = new HashMap(); + return map; + } + + + private void setFields(EditConfigurationVTwo editConfiguration, VitroRequest vreq, String predicateUri) { + Map fields = new HashMap(); + getLabelField(editConfiguration, vreq, fields); + getFirstNameField(editConfiguration, vreq, fields); + getLastNameField(editConfiguration, vreq, fields); + } + + private void getLastNameField(EditConfigurationVTwo editConfiguration, + VitroRequest vreq, Map fields) { + FieldVTwo field = new FieldVTwo(); + field.setName("lastName"); + field.setNewResource(false); + //queryForExisting is not being used anywhere in Field + String stringDatatypeUri = XSD.xstring.toString(); + + + List validators = new ArrayList(); + if(isPersonType(vreq)) { + validators.add("nonempty"); + } + field.setValidators(validators); + + //subjectUri and subjectClassUri are not being used in Field + + field.setOptionsType("UNDEFINED"); + //why isn't predicate uri set for data properties? + field.setPredicateUri(null); + field.setObjectClassUri(null); + field.setRangeDatatypeUri(stringDatatypeUri); + + field.setLiteralOptions(new ArrayList>()); + + //set assertions + List assertions = new ArrayList(); + field.setAssertions(assertions); + fields.put(field.getName(), field); + + } + + private void getFirstNameField(EditConfigurationVTwo editConfiguration, + VitroRequest vreq, Map fields) { + FieldVTwo field = new FieldVTwo(); + field.setName("firstName"); + field.setNewResource(false); + //queryForExisting is not being used anywhere in Field + String stringDatatypeUri = XSD.xstring.toString(); + + + List validators = new ArrayList(); + if(isPersonType(vreq)) { + validators.add("nonempty"); + } + field.setValidators(validators); + + //subjectUri and subjectClassUri are not being used in Field + + field.setOptionsType("UNDEFINED"); + //why isn't predicate uri set for data properties? + field.setPredicateUri(null); + field.setObjectClassUri(null); + field.setRangeDatatypeUri(stringDatatypeUri); + + field.setLiteralOptions(new ArrayList>()); + + //set assertions + List assertions = new ArrayList(); + field.setAssertions(assertions); + fields.put(field.getName(), field); + + + } + + private void getLabelField(EditConfigurationVTwo editConfiguration, + VitroRequest vreq, Map fields) { + FieldVTwo field = new FieldVTwo(); + field.setName("label"); + field.setNewResource(false); + //queryForExisting is not being used anywhere in Field + String stringDatatypeUri = XSD.xstring.toString(); + + + List validators = new ArrayList(); + if(!isPersonType(vreq)) { + validators.add("nonempty"); + } + field.setValidators(validators); + + //subjectUri and subjectClassUri are not being used in Field + + field.setOptionsType("UNDEFINED"); + //why isn't predicate uri set for data properties? + field.setPredicateUri(null); + field.setObjectClassUri(null); + field.setRangeDatatypeUri(stringDatatypeUri); + + field.setLiteralOptions(new ArrayList>()); + + //set assertions + List assertions = new ArrayList(); + field.setAssertions(assertions); + fields.put(field.getName(), field); + + } + + + + private void prepareForUpdate(VitroRequest vreq, HttpSession session, EditConfigurationVTwo editConfiguration) { + //Here, retrieve model from + Model model = (Model) session.getServletContext().getAttribute("jenaOntModel"); + //This form is always doing a non-update + editConfiguration.prepareForNonUpdate( model ); + + } + + + //Get parameter + private String getTypeOfNew(VitroRequest vreq) { + return vreq.getParameter("typeOfNew"); + } + + //Form specific data + public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { + HashMap formSpecificData = new HashMap(); + 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(); + List superTypes = wdf.getVClassDao().getAllSuperClassURIs(getTypeOfNew(vreq)); + if( superTypes != null ){ + for( String typeUri : superTypes){ + if( foafPersonType.equals(typeUri)) { + isPersonType = Boolean.TRUE; + break; + } + } + } + return isPersonType; + } + + +} diff --git a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/RoleToActivityPredicatePreprocessor.java b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/RoleToActivityPredicatePreprocessor.java index 129f0839..0436215c 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/RoleToActivityPredicatePreprocessor.java +++ b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/RoleToActivityPredicatePreprocessor.java @@ -38,60 +38,26 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmis import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.FieldVTwo; import org.vivoweb.webapp.util.ModelUtils; -public class RoleToActivityPredicatePreprocessor extends BaseEditSubmissionPreprocessorVTwo { - - private static final Log log = LogFactory.getLog(CreateLabelFromNameFields.class.getName()); - private WebappDaoFactory wadf = null; - //Need the webapp dao factory to try to figure out what the predicate should be - public RoleToActivityPredicatePreprocessor(EditConfigurationVTwo editConfig, WebappDaoFactory wadf) { - super(editConfig); - this.wadf = wadf; +public class RoleToActivityPredicatePreprocessor extends RoleToPredicatePreprocessor { + public RoleToActivityPredicatePreprocessor(EditConfigurationVTwo editConfig, WebappDaoFactory wadf) { + super(editConfig, wadf); } - public void preprocess(MultiValueEditSubmission submission) { - //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 - Map> urisFromForm = submission.getUrisFromForm(); - //Get the type of the activity selected - List activityTypes = urisFromForm.get("roleActivityType"); - //Really should just be one here - if(activityTypes != null && activityTypes.size() > 0) { - String type = activityTypes.get(0); - ObjectProperty roleToActivityProperty = getCorrectProperty(type, wadf); - String roleToActivityPredicate = roleToActivityProperty.getURI(); - String activityToRolePredicate = roleToActivityProperty.getURIInverse(); - List predicates = new ArrayList(); - predicates.add(roleToActivityPredicate); - - List inversePredicates = new ArrayList(); - inversePredicates.add(activityToRolePredicate); - //Populate the two fields in edit submission - if(urisFromForm.containsKey("roleToActivityPredicate")) { - urisFromForm.remove("roleToActivityPredicate"); - } - - urisFromForm.put("roleToActivityPredicate", predicates); - - if(urisFromForm.containsKey("activityToRolePredicate")) { - urisFromForm.remove("activityToRolePredicate"); - } - urisFromForm.put("activityToRolePredicate", inversePredicates); - - } - - } catch (Exception e) { - log.error("Error retrieving name values from edit submission."); - } - + protected void setupVariableNames() { + this.itemType = "roleActivityType"; + this.roleToItemPredicate = "roleToActivityPredicate"; + this.itemToRolePredicate = "activityToRolePredicate"; } - private ObjectProperty getCorrectProperty(String uri, WebappDaoFactory wadf) { - ObjectProperty correctProperty = ModelUtils.getPropertyForRoleInClass(uri, wadf); - return correctProperty; - } - + protected String getItemType(MultiValueEditSubmission submission) { + String type = null; + Map> urisFromForm = submission.getUrisFromForm(); + //Get the type of the activity selected + List itemTypes = urisFromForm.get(itemType); + //Really should just be one here + if(itemTypes != null && itemTypes.size() > 0) { + type = itemTypes.get(0); + } + return type; + } } diff --git a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/RoleToPredicatePreprocessor.java b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/RoleToPredicatePreprocessor.java new file mode 100644 index 00000000..68ca1df8 --- /dev/null +++ b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/RoleToPredicatePreprocessor.java @@ -0,0 +1,103 @@ +/* $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.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) { + //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> urisFromForm = submission.getUrisFromForm(); + if(type != null) { + ObjectProperty roleToItemProperty = getCorrectProperty(type, wadf); + String roleToItemPredicate = roleToItemProperty.getURI(); + String itemToRolePredicate = roleToItemProperty.getURIInverse(); + List predicates = new ArrayList(); + predicates.add(roleToItemPredicate); + + List inversePredicates = new ArrayList(); + inversePredicates.add(itemToRolePredicate); + //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; + } + +}