From dc08fbea1afb4abd9414f8318405a7ec801f6c88 Mon Sep 17 00:00:00 2001 From: hjkhjk54 Date: Wed, 2 Nov 2011 14:56:54 +0000 Subject: [PATCH] --- productMods/WEB-INF/web.xml | 1 + .../edit/forms/addClinicalRoleToPerson.ftl | 11 +- .../edit/forms/addRoleToPersonTwoStage.ftl | 195 ++++ .../AddClinicalRoleToPersonGenerator.java | 123 ++ .../AddRoleToPersonTwoStageGenerator.java | 1025 +++++++++++++++++ .../RoleToActivityPredicatePreprocessor.java | 168 +++ src/org/vivoweb/webapp/util/ModelUtils.java | 8 +- 7 files changed, 1524 insertions(+), 7 deletions(-) create mode 100644 productMods/templates/freemarker/edit/forms/addRoleToPersonTwoStage.ftl create mode 100644 src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddClinicalRoleToPersonGenerator.java create mode 100644 src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddRoleToPersonTwoStageGenerator.java create mode 100644 src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/RoleToActivityPredicatePreprocessor.java diff --git a/productMods/WEB-INF/web.xml b/productMods/WEB-INF/web.xml index 7b75f152..37510262 100644 --- a/productMods/WEB-INF/web.xml +++ b/productMods/WEB-INF/web.xml @@ -924,6 +924,7 @@ /contact + JSON Service edu.cornell.mannlib.vitro.webapp.controller.JsonServlet diff --git a/productMods/templates/freemarker/edit/forms/addClinicalRoleToPerson.ftl b/productMods/templates/freemarker/edit/forms/addClinicalRoleToPerson.ftl index 7a815b63..f505ab53 100644 --- a/productMods/templates/freemarker/edit/forms/addClinicalRoleToPerson.ftl +++ b/productMods/templates/freemarker/edit/forms/addClinicalRoleToPerson.ftl @@ -7,14 +7,19 @@ roleDescriptor. The other required values (roleType, optionsType, objectClassUri, and literalOptions are set in the JAVA class corresponding to the form, e.g. AddClinicalRoleToPersonGenerator.java. -Optional values can be set, but each of these has default values +Optional values can be set in Freemarker, but each of these has default values set in addRoleToPersonTwoStage.ftl: buttonText typeSelectorLabel numDateFields -showRoleLAbelField -roleExamples--> +roleExamples + +Optional values set in JAVA include +ShowRoleLabelField +ActivityToRolePredicate +RoleToActivityPredicate +--> <#--Variable assignments for Add Clinical Role To Person--> diff --git a/productMods/templates/freemarker/edit/forms/addRoleToPersonTwoStage.ftl b/productMods/templates/freemarker/edit/forms/addRoleToPersonTwoStage.ftl new file mode 100644 index 00000000..ab4c8634 --- /dev/null +++ b/productMods/templates/freemarker/edit/forms/addRoleToPersonTwoStage.ftl @@ -0,0 +1,195 @@ +<#-- $This file is distributed under the terms of the license in /doc/license.txt$ --> + +<#--Retrieve certain edit configuration information--> +<#assign editMode = editConfiguration.pageData.editMode /> +<#assign literalValues = editConfiguration.existingLiteralValues /> +<#assign uriValues = editConfiguration.existingUriValues /> +<#assign htmlForElements = editConfiguration.pageData.htmlForElements /> +<#assign showRoleLabelField = editConfiguration.pageData.showRoleLabelField /> +<#--Freemarker variables with default values that can be overridden by specific forms--> + + +<#--buttonText, typeSelectorLabel, numDateFields, roleExamples--> +<#if !buttonText?has_content> + <#assign buttonText = roleDescriptor /> + +<#if !typeSelectorLabel?has_content> + <#assign typeSelectorLabel = roleDescriptor /> + +<#if !numDateFields?has_content> + <#assign numDateFields = 2 /> + + +<#if !roleExamples?has_content> + <#assign roleExamples = "" /> + + +<#--Setting values for titleVerb, submitButonText, and disabled Value--> +<#if editConfiguration.objectUri?has_content> + <#assign titleVerb = "Edit"/> + <#assign submitButtonText>Edit ${buttonText} + <#if editMode = "repair"> + <#assign disabledVal = ""/> + <#else> + <#assign disabledVal = "disabled"/> + +<#else> + <#assign titleVerb = "Create"/> + <#assign submitButtonText>${buttonText} + <#assign disabledVal = ""/> + <#assign editMode = "add" /> + + +<#--Get existing value for specific data literals and uris--> + + +<#--Get selected activity type value if it exists, this is alternative to below--> +<#assign activityTypeValue = ""/> +<#if uriValues?keys?seq_contains("roleActivityType") && (uriValues.roleActivityType?size > 0)> + <#assign activityTypeValue = uriValues.roleActivityType[0] /> + + + <#--Get activity label value--> +<#assign activityLabelValue = "" /> +<#if literalValues?keys?seq_contains("activityLabel") && (literalValues.activityLabel?size > 0)> + <#assign activityLabelValue = literalValues.activityLabel[0] /> + + +<#--Get role label--> +<#assign roleLabel = "" /> +<#if literalValues?keys?seq_contains("roleLabel") && (literalValues.roleLabel?size > 0) > + <#assign roleLabel = literalValues.roleLabel[0] /> + + + + +

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

+ +<#--Display error messages if any--> +<#if errorNameFieldIsEmpty??> + <#assign errorMessage = "Enter a name for the ." /> + + +<#if errorRoleFieldIsEmpty??> + <#assign errorMessage = "Specify a role for this ." /> + + +<#if errorMessage?has_content> + + + + +
+ +
+ +

+ +

+ + + +
+

+ + + disabled=${disabledVal} + + /> +

+ + + + + <#if editMode = "edit"> + + + + +
+

+ + + (Verify this match) +

+ + +
+ + <#if showRoleLabelField = true> +

+ +

+ + + <#if numDateFields == 1 > + <#--Generated html is a map with key name mapping to html string--> + <#if htmlForElements?keys?seq_contains("startField")> + + ${htmlForElements["startField"]} + + <#else> +

Years of Participation in ${roleDescriptor?capitalize}

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

+ +

* required fields

+ + +<#--Specifying form-specific script and adding stylesheets and scripts--> + + + +${stylesheets.add('')} +${stylesheets.add('')} +${stylesheets.add('')} + +${scripts.add('')} +${scripts.add('')} +${scripts.add('')} + + +
\ No newline at end of file diff --git a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddClinicalRoleToPersonGenerator.java b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddClinicalRoleToPersonGenerator.java new file mode 100644 index 00000000..1e886f35 --- /dev/null +++ b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddClinicalRoleToPersonGenerator.java @@ -0,0 +1,123 @@ +/* $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 java.util.Set; +import org.apache.commons.lang.StringUtils; +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.DateTimeWithPrecisionVTwo; +import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils; +import edu.cornell.mannlib.vitro.webapp.dao.jena.QueryUtils; + +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.RDF; +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; +import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils; +import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils.EditMode; +import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.DateTimeIntervalValidation; +/** + * 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 AddClinicalRoleToPersonGenerator extends AddRoleToPersonTwoStageGenerator { + + private Log log = LogFactory.getLog(AddClinicalRoleToPersonGenerator.class); + private static String template = "addClinicalRoleToPerson.ftl"; + + //Should this be overridden + @Override + protected void setTemplate(EditConfigurationVTwo editConfiguration, + VitroRequest vreq) { + editConfiguration.setTemplate(template); + } + + + //The default activityToRolePredicate and roleToActivityPredicates are + //correct for this subclass so they don't need to be overwritten + + //role type will always be set based on particular form + public String getRoleType(VitroRequest vreq) { + //TODO: Get dynamic way of including vivoweb ontology + return "http://vivoweb.org/ontology/core#ClinicalRole"; + } + + //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 ? + public RoleActivityOptionTypes getRoleActivityTypeOptionsType(VitroRequest vreq) { + return RoleActivityOptionTypes.HARDCODED_LITERALS; + } + + //This too will depend on the specific subclass of generator + public String getRoleActivityTypeObjectClassUri(VitroRequest vreq) { + return null; + } + + + //Clinical role involves hard-coded options for the "right side" of the role or activity + protected HashMap getRoleActivityTypeLiteralOptions(VitroRequest vreq) { + HashMap literalOptions = new HashMap(); + literalOptions.put("", "Select one"); + literalOptions.put("http://vivoweb.org/ontology/core#Project", "Project"); + literalOptions.put("http://vivoweb.org/ontology/core#Service","Service"); + return literalOptions; + } + + //isShowRoleLabelField remains true for this so doesn't need to be overwritten + + +} 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 new file mode 100644 index 00000000..4461c7aa --- /dev/null +++ b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddRoleToPersonTwoStageGenerator.java @@ -0,0 +1,1025 @@ +/* $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 java.util.Set; +import org.apache.commons.lang.StringUtils; +import javax.servlet.http.HttpSession; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.vivoweb.webapp.util.ModelUtils; + +import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo; +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.dao.jena.QueryUtils; + +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.RDF; +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.configuration.preprocessors.RoleToActivityPredicatePreprocessor; +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; +import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils; +import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils.EditMode; +/** + * 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. + + * + */ +public abstract class AddRoleToPersonTwoStageGenerator implements EditConfigurationGenerator { + + private Log log = LogFactory.getLog(AddRoleToPersonTwoStageGenerator.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 = "addRoleToPersonTwoStage.ftl"; + private static HashMap defaultsForXSDtypes ; + + //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()); + + //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") ); + //Add preprocessors + addPreprocessors(editConfiguration); + //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: http://vivoweb.org/ontology/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 = getPrefixesString() + " /n"; + editString += "?person ?rolePredicate ?role ."; + editString += "?role a <" + getRoleType(vreq) + "> ."; + editString += "?role <" + getRoleToActivityPredicate(vreq) + "> ?roleActivity ."; + editString += "?roleActivity <" + getActivityToRolePredicate(vreq) + "> ?role ."; + n3ForEdit.add(editString); + return n3ForEdit; + } + + + private List generateN3Optional() { + List n3Optional = new ArrayList(); + //n3 for activity label + n3Optional.add(getN3ForActivityLabel()); + //n3 for activity type + n3Optional.add(getN3ForActivityType()); + //n3 for inverse + n3Optional.add("?role ?inverseRolePredicate ?person ."); + //N3ForStart + n3Optional.addAll(getN3ForStart()); + //N3 For End + n3Optional.addAll(getN3ForEnd()); + //role label assertion + n3Optional.add(getN3RoleLabelAssertion()); + return n3Optional; + } + + + public String getN3ForActivityLabel() { + return "?roleActivity <" + RDFS.label.getURI() + "> ?activityLabel ."; + } + + public String getN3ForActivityType() { + return "?roleActivity a ?roleActivityType ."; + } + + public String getN3RoleLabelAssertion() { + return "?role <" + RDFS.label.getURI() + "> ?roleLabel ."; + } + + //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("roleActivity", 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 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("roleActivity"); + urisOnForm.add("roleActivityType"); + editConfiguration.setUrisOnform(urisOnForm); + //activity label and role label are literals on form + literalsOnForm.add("activityLabel"); + literalsOnForm.add("roleLabel"); + 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("roleActivity", getRoleActivityQuery(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)); + 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; + } + + + /* + * 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. + */ + //This method had some code already setup in the jsp file + private String getActivityTypeQuery(VitroRequest vreq) { + String activityTypeQuery = null; + + //roleActivityType_optionsType: This gets you whether this is a literal + // + RoleActivityOptionTypes optionsType = getRoleActivityTypeOptionsType(vreq); + + // Note that this value is overloaded to specify either object class uri or classgroup uri + String objectClassUri = getRoleActivityTypeObjectClassUri(vreq); + + if (StringUtils.isNotBlank(objectClassUri)) { + log.debug("objectClassUri = " + objectClassUri); + + if (RoleActivityOptionTypes.VCLASSGROUP.equals(optionsType)) { + activityTypeQuery = getClassgroupActivityTypeQuery(vreq); + activityTypeQuery = QueryUtils.subUriForQueryVar(activityTypeQuery, "classgroup", objectClassUri); + + } else if (RoleActivityOptionTypes.CHILD_VCLASSES.equals(optionsType)) { + activityTypeQuery = getSubclassActivityTypeQuery(vreq); + activityTypeQuery = QueryUtils.subUriForQueryVar(activityTypeQuery, "objectClassUri", objectClassUri); + + } else { + activityTypeQuery = getDefaultActivityTypeQuery(vreq); + } + + // Select options are hardcoded + } else if (RoleActivityOptionTypes.HARDCODED_LITERALS.equals(optionsType)) { + + //literal options + HashMap typeLiteralOptions = getRoleActivityTypeLiteralOptions(vreq); + if (typeLiteralOptions.size() > 0) { + try { + List typeUris = new ArrayList(); + Set optionUris = typeLiteralOptions.keySet(); + for(String uri: optionUris) { + typeUris.add("(?existingActivityType = <" + uri + ">)"); + } + String typeFilters = "FILTER (" + StringUtils.join(typeUris, "||") + ")"; + String defaultActivityTypeQuery = getDefaultActivityTypeQuery(vreq); + activityTypeQuery = defaultActivityTypeQuery.replaceAll("}$", "") + typeFilters + "}"; + } catch (Exception e) { + activityTypeQuery = getDefaultActivityTypeQuery(vreq); + } + + } else { + activityTypeQuery = getDefaultActivityTypeQuery(vreq); + } + + } else { + activityTypeQuery = getDefaultActivityTypeQuery(vreq); + } + + String roleToActivityPredicate = getRoleToActivityPredicate(vreq); + activityTypeQuery = QueryUtils.subUriForQueryVar(activityTypeQuery, "predicate", roleToActivityPredicate); + log.debug("Activity type query: " + activityTypeQuery); + + return activityTypeQuery; + } + + + private String getDefaultActivityTypeQuery(VitroRequest vreq) { + String query = "PREFIX core: <" + getVivoCoreNamespace() + ">\n" + + "PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" + + "SELECT ?existingActivityType WHERE { \n" + + " ?role ?predicate ?existingActivity . \n" + + " ?existingActivity vitro:mostSpecificType ?existingActivityType . \n" + + "}"; + return query; + } + + private String getSubclassActivityTypeQuery(VitroRequest vreq) { + String query = "PREFIX core: <" + getVivoCoreNamespace() + ">\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" + + "}"; + return query; + } + + private String getClassgroupActivityTypeQuery(VitroRequest vreq) { + String query = "PREFIX core: <" + getVivoCoreNamespace() + ">\n" + + "PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" + + "SELECT ?existingActivityType WHERE { \n" + + " ?role ?predicate ?existingActivity . \n" + + " ?existingActivity vitro:mostSpecificType ?existingActivityType . \n" + + " ?existingActivityType vitro:inClassGroup ?classgroup . \n" + + "}"; + return query; + } + + + private String getRoleActivityQuery(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: <" + getVivoCoreNamespace() + ">"; + + String roleToActivityPredicate = getRoleToActivityPredicate(vreq); + //Portion below for multiple possible predicates + /*if(roleToActivityPredicate.equals(getDefaultRoleToActivityPredicate())) { + query += "SELECT ?existingActivity WHERE { " + + "{?role <" + ModelUtils.processPropertyURI + "> ?existingActivity .} UNION " + + "{?role <" + ModelUtils.nonProcessPropertyURI + "> ?existingActivity .}" + + "}"; + } else { + */ + query += "SELECT ?existingActivity WHERE { ?role <" +roleToActivityPredicate + "> ?existingActivity . }"; + /*}*/ + + 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("activityLabel", getActivityLabelQuery(vreq)); + map.put("roleLabel", getRoleLabelQuery(vreq)); + map.put("startField-value", getExistingStartDateQuery(vreq)); + map.put("endField-value", getExistingEndDateQuery(vreq)); + return map; + } + + + 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; + } + + private String getRoleLabelQuery(VitroRequest vreq) { + String query = "SELECT ?existingRoleLabel WHERE { ?role <" + VitroVocabulary.LABEL + "> ?existingRoleLabel . }"; + return query; + } + + private String getActivityLabelQuery(VitroRequest vreq) { + String query = "PREFIX core: <" + getVivoCoreNamespace() + ">" + + "PREFIX rdfs: <" + RDFS.getURI() + "> \n"; + + String roleToActivityPredicate = getRoleToActivityPredicate(vreq); + /*if(roleToActivityPredicate.equals(getDefaultRoleToActivityPredicate())) { + query += "SELECT ?existingTitle WHERE { \n" + + "{?role <" + ModelUtils.processPropertyURI + "> ?existingActivity . \n" + + "?existingActivity rdfs:label ?existingTitle . } UNION " + + "{?role <" + ModelUtils.nonProcessPropertyURI + "> ?existingActivity . \n" + + "?existingActivity rdfs:label ?existingTitle . } " + + "}"; + + } else {*/ + query += "SELECT ?existingTitle WHERE { \n" + + "?role <" + roleToActivityPredicate + "> ?existingActivity . \n" + + "?existingActivity rdfs:label ?existingTitle . }"; + /*}*/ + + return query; + } + + /** + * + * Set Fields and supporting methods + */ + + private void setFields(EditConfigurationVTwo editConfiguration, VitroRequest vreq, String predicateUri) { + Map fields = new HashMap(); + //Multiple fields + getActivityLabelField(editConfiguration, vreq, fields); + getRoleActivityTypeField(editConfiguration, vreq, fields); + getRoleActivityField(editConfiguration, vreq, fields); + getRoleLabelField(editConfiguration, vreq, fields); + getStartField(editConfiguration, vreq, fields); + getEndField(editConfiguration, vreq, fields); + + editConfiguration.setFields(fields); + } + + + //Label of "right side" of role, i.e. label for role roleIn Activity + private void getActivityLabelField(EditConfigurationVTwo editConfiguration, + VitroRequest vreq, Map fields) { + String fieldName = "activityLabel"; + //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 + + + List validators = new ArrayList(); + //If add mode or repair, etc. need to add label required validator + if(isAddMode(vreq) || isRepairMode(vreq)) { + validators.add("nonempty"); + } + validators.add("datatype:" + stringDatatypeUri); + 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(); + assertions.add(getN3ForActivityLabel()); + field.setAssertions(assertions); + 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 fields) { + String fieldName = "roleActivityType"; + //get range data type uri and range language + + FieldVTwo field = new FieldVTwo(); + field.setName(fieldName); + field.setNewResource(true); + //queryForExisting is not being used anywhere in Field + + + List validators = new ArrayList(); + if(isAddMode(vreq) || isRepairMode(vreq)) { + validators.add("nonempty"); + } + field.setValidators(validators); + + //subjectUri and subjectClassUri are not being used in Field + //TODO: Check if this is correct + field.setOptionsType(getRoleActivityTypeOptionsType(vreq).toString()); + //why isn't predicate uri set for data properties? + field.setPredicateUri(null); + field.setObjectClassUri(getRoleActivityTypeObjectClassUri(vreq)); + field.setRangeDatatypeUri(null); + + + HashMap literalOptionsMap = getRoleActivityTypeLiteralOptions(vreq); + List> fieldLiteralOptions = new ArrayList>(); + Set optionUris = literalOptionsMap.keySet(); + for(String optionUri: optionUris) { + List uriLabelArray = new ArrayList(); + uriLabelArray.add(optionUri); + uriLabelArray.add(literalOptionsMap.get(optionUri)); + fieldLiteralOptions.add(uriLabelArray); + } + field.setLiteralOptions(fieldLiteralOptions); + + //set assertions + List assertions = new ArrayList(); + assertions.add(getN3ForActivityType()); + field.setAssertions(assertions); + fields.put(field.getName(), field); + + } + + //Assuming URI for activity for role? + private void getRoleActivityField(EditConfigurationVTwo editConfiguration, + VitroRequest vreq, Map fields) { + String fieldName = "roleActivity"; + //get range data type uri and range language + + FieldVTwo field = new FieldVTwo(); + field.setName(fieldName); + field.setNewResource(true); + + 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(); + //N3ForRoleToActivity + String n3ForRoleToActivity = "@prefix core: <" + getVivoCoreNamespace() + "> ." + + "?role <" + getRoleToActivityPredicate(vreq) + "> ?roleActivity ." + + "?roleActivity <" + getActivityToRolePredicate(vreq) + "> ?role ."; + assertions.add(n3ForRoleToActivity); + field.setAssertions(assertions); + fields.put(field.getName(), field); + + } + + private void getRoleLabelField(EditConfigurationVTwo editConfiguration, + VitroRequest vreq, Map fields) { + String fieldName = "roleLabel"; + String stringDatatypeUri = XSD.xstring.toString(); + + + FieldVTwo field = new FieldVTwo(); + field.setName(fieldName); + field.setNewResource(false); + + List validators = new ArrayList(); + validators.add("datatype:" + stringDatatypeUri); + if(isShowRoleLabelField(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); + //empty + field.setLiteralOptions(new ArrayList>()); + + //set assertions + List assertions = new ArrayList(); + assertions.add(getN3RoleLabelAssertion()); + 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 ); + } + } + + + //Add preprocessor + + private void addPreprocessors(EditConfigurationVTwo editConfiguration) { + //Add preprocessor that will replace the generic role to activity predicate preprocessor + //With roleIn + editConfiguration.addModelChangePreprocessor(new RoleToActivityPredicatePreprocessor()); + } + + /** + * Methods that are REQUIRED to be implemented in subclasses + **/ + //role type will always be set based on particular form + abstract public String getRoleType(VitroRequest vreq); + //In the case of literal options, subclass generator will set the options to be returned + abstract protected HashMap getRoleActivityTypeLiteralOptions(VitroRequest vreq); + //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 ? + abstract public RoleActivityOptionTypes getRoleActivityTypeOptionsType(VitroRequest vreq); + //This too will depend on the specific subclass of generator + abstract public String getRoleActivityTypeObjectClassUri(VitroRequest vreq); + + /** + * 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; + } + + public String getActivityToRolePredicate(VitroRequest vreq) { + return getDefaultActivityToRolePredicate(); + } + + //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 + public String getRoleToActivityPredicate(VitroRequest vreq) { + return getDefaultRoleToActivityPredicate(); + } + + //Some values will have a default value + //activityToRolePredicate + public String getDefaultActivityToRolePredicate() { + return "http://vivoweb.org/ontology/core#relatedRole"; + } + + //roleToActivityPredicate + public String getDefaultRoleToActivityPredicate() { + return "http://vivoweb.org/ontology/core#roleIn"; + + } + + /** + * Methods that check edit mode + */ + + //Get edit mode + private EditMode getEditMode(VitroRequest vreq) { + String roleToActivityPredicate = getRoleToActivityPredicate(vreq); + Individual object = EditConfigurationUtils.getObjectIndividual(vreq); + EditMode mode = FrontEndEditingUtils.getEditMode(vreq, object, roleToActivityPredicate); + return mode; + //(mode == EditMode.ADD || mode == EditMode.REPAIR) ? "\"nonempty\" + } + 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()); + //Fields that will need select lists generated + //Store field names + List objectSelect = new ArrayList(); + 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(vreq)); + //Put in the fact that we require field + editConfiguration.setFormSpecificData(formSpecificData); + } + +} 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 new file mode 100644 index 00000000..debcd4a8 --- /dev/null +++ b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/RoleToActivityPredicatePreprocessor.java @@ -0,0 +1,168 @@ +/* $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.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 class RoleToActivityPredicatePreprocessor implements ModelChangePreprocessor { + + private static final Log log = LogFactory.getLog(CreateLabelFromNameFields.class.getName()); + public RoleToActivityPredicatePreprocessor() { + super(); + } + + public void preprocess(Model retractionsModel, Model additionsModel, HttpServletRequest request) { + //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 { + VitroRequest vreq = new VitroRequest(request); + WebappDaoFactory wadf = vreq.getWebappDaoFactory(); + replacePredicates(retractionsModel, wadf); + replacePredicates(additionsModel, wadf); + + } catch (Exception e) { + log.error("Error retrieving name values from edit submission."); + } + + } + + private void replacePredicates(Model inputModel, WebappDaoFactory wadf) { + executeQueryAndReplace(inputModel, wadf); + } + private void executeQueryAndReplace(Model inputModel, WebappDaoFactory wadf) { + String queryString= getRoleAndActivityQuery(); + Query query = QueryFactory.create(queryString); + QueryExecution qe = QueryExecutionFactory.create(query, inputModel); + ResultSet rs = qe.execSelect(); + + while(rs.hasNext()) { + QuerySolution qs = rs.nextSolution(); + Resource role = null, activity = null, mostSpecificType = null; + role = getResourceFromSolution(qs, "role"); + activity = getResourceFromSolution(qs, "activity"); + mostSpecificType = getResourceFromSolution(qs, "mostSpecificType"); + + //Within the input model, replace predicate linking role and activity and vice versa + //based on the most specific type of the activity + replacePredicatesForRoleAndActivity(inputModel, role, activity, mostSpecificType, wadf); + + } + } + private void replacePredicatesForRoleAndActivity(Model inputModel, + Resource role, Resource activity, Resource mostSpecificType, + WebappDaoFactory wadf) { + Property roleToActivityPredicate = ResourceFactory.createProperty(getGenericRoleToActivityPredicate()); + Property activityToRolePredicate = ResourceFactory.createProperty(getGenericActivityToRolePredicate()); + if(role != null && activity != null && mostSpecificType != null) { + + ObjectProperty newRoleToActivityProperty = getCorrectProperty(mostSpecificType.getURI(), wadf); + String propertyURI = newRoleToActivityProperty.getURI(); + String inversePropertyURI = newRoleToActivityProperty.getURIInverse(); + //Remove all the old statements connecting role and activity + inputModel.enterCriticalSection(Lock.WRITE); + try { + Model removeRoleToActivityModel = ModelFactory.createDefaultModel(); + removeRoleToActivityModel.add(inputModel.listStatements( + role, + roleToActivityPredicate, + activity)); + Model removeActivityToRoleModel = ModelFactory.createDefaultModel(); + removeActivityToRoleModel.add(inputModel.listStatements( + activity, + activityToRolePredicate, + role)); + //Add statements + inputModel.add(inputModel.createStatement( + role, + ResourceFactory.createProperty(propertyURI), + activity)); + + inputModel.add(inputModel.createStatement( + activity, + ResourceFactory.createProperty(inversePropertyURI), + role)); + + //Remove all roleToActivityPredicates and replace with the new predicate + inputModel.remove(removeRoleToActivityModel); + //Remove all activity to role predicates and replace with new predicate + inputModel.remove(removeActivityToRoleModel); + } catch(Exception ex) { + log.error("Exception occurred in replacing predicates in model ", ex); + } finally { + inputModel.leaveCriticalSection(); + } + } + + } + + private ObjectProperty getCorrectProperty(String uri, WebappDaoFactory wadf) { + //ObjectProperty correctProperty = ModelUtils.getPropertyForRoleInClass(uri, wadf); + ObjectProperty op = new ObjectProperty(); + op.setURI( "http://vivoweb.org/ontology/core#roleRealizedIn"); + op.setURIInverse("http://vivoweb.org/ontology/core#realizedRole"); + return op; +} + + private String getRoleAndActivityQuery() { + String roleToActivityPredicate = getGenericRoleToActivityPredicate(); + String query = "PREFIX core: " + + "SELECT ?role ?activity ?mostSpecificType WHERE { ?role <" + roleToActivityPredicate + "> ?activity . \n" + + "?activity <" + VitroVocabulary.RDF_TYPE + "> ?mostSpecificType. \n" + + "}"; + return query; + } + + private Resource getResourceFromSolution(QuerySolution qs, String variableName) { + Resource resource = null; + if(qs.get(variableName) != null && qs.get(variableName).isResource()) { + resource = qs.getResource(variableName); + } + return resource; + } + + + //Values used in the forms + private static String getGenericRoleToActivityPredicate() { + return "http://vivoweb.org/ontology/core#roleIn"; + } + + private static String getGenericActivityToRolePredicate() { + return "http://vivoweb.org/ontology/core#relatedRole"; + + } +} diff --git a/src/org/vivoweb/webapp/util/ModelUtils.java b/src/org/vivoweb/webapp/util/ModelUtils.java index e78f630e..319019d1 100644 --- a/src/org/vivoweb/webapp/util/ModelUtils.java +++ b/src/org/vivoweb/webapp/util/ModelUtils.java @@ -19,10 +19,10 @@ public class ModelUtils { private static final Log log = LogFactory.getLog(ModelUtils.class.getName()); - private static final String processPropertyURI = "http://vivoweb.org/ontology/core#roleRealizedIn"; - private static final String processPropertyInverseURI = "http://vivoweb.org/ontology/core#realizedRole"; - private static final String nonProcessPropertyURI = "http://vivoweb.org/ontology/core#roleContributesTo"; - private static final String nonProcessPropertyInverseURI = "http://vivoweb.org/ontology/core#ContributingRole"; + public static final String processPropertyURI = "http://vivoweb.org/ontology/core#roleRealizedIn"; + public static final String processPropertyInverseURI = "http://vivoweb.org/ontology/core#realizedRole"; + public static final String nonProcessPropertyURI = "http://vivoweb.org/ontology/core#roleContributesTo"; + public static final String nonProcessPropertyInverseURI = "http://vivoweb.org/ontology/core#ContributingRole"; private static Set processClass = new HashSet(); static {