diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/AdditionsAndRetractions.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/AdditionsAndRetractions.java index 1025b2aa2..5fe092a9a 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/AdditionsAndRetractions.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/AdditionsAndRetractions.java @@ -12,7 +12,6 @@ import com.hp.hpl.jena.rdf.model.ModelFactory; * This is a data structure to allow a method to return * a pair of Model objects for additions and retractions. * - * Move this to its own class */ public class AdditionsAndRetractions { Model additions; diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditConfigurationUtils.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditConfigurationUtils.java index a06f337a7..bd2f14c0c 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditConfigurationUtils.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditConfigurationUtils.java @@ -6,7 +6,9 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; +import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; @@ -248,6 +250,45 @@ public class EditConfigurationUtils { } return html; } - + /** Make a copy of list of Strings. */ + public static List copy(List list) { + List copyList = new ArrayList(); + for(String l: list) { + copyList.add( new String (l) ); + } + return copyList; + } + + /** Make a copy of a Map */ + public static Map copyMap(Map source) { + HashMap map = new HashMap(); + Set keys = map.keySet(); + for(String key: keys) { + if( source.get(key) != null ) + map.put(new String(key), new String( source.get(key)) ); + else + map.put(new String(key),null); + } + return map; + } + + /** Make a copy of a Map> */ + public static Map> copyListMap(Map> source) { + HashMap> map = new HashMap>(); + Set keys = map.keySet(); + for(String key: keys) { + List vals = map.get(key); + map.put(new String(key), copy(vals)); + } + return map; + } + + + public static EditConfigurationVTwo getEditConfiguration(HttpServletRequest request) { + HttpSession session = request.getSession(); + EditConfigurationVTwo editConfiguration = EditConfigurationVTwo.getConfigFromSession(session, request); + return editConfiguration; + } + } diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditConfigurationVTwo.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditConfigurationVTwo.java index ab488a628..98a85a9f0 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditConfigurationVTwo.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditConfigurationVTwo.java @@ -3,12 +3,12 @@ package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo; import java.text.SimpleDateFormat; import java.util.ArrayList; +import java.util.Arrays; import java.util.Calendar; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; -import java.util.Set; import javax.servlet.ServletContext; import javax.servlet.ServletRequest; @@ -96,8 +96,7 @@ public class EditConfigurationVTwo { * object is the uri without the quoting < or >. */ String object; - String varNameForObject; - boolean isObjectResource; + String varNameForObject; String datapropKey; String datapropValue; @@ -111,7 +110,7 @@ public class EditConfigurationVTwo { EditN3GeneratorVTwo n3generator; - private List modelChangePreprocessors; + private List modelChangePreprocessors =new LinkedList(); private List editSubmissionPreprocessors; @@ -147,19 +146,21 @@ public class EditConfigurationVTwo { * Usually this is set to null and the main model will be used. */ private WDFSelector wdfSelectorForOptons; + private boolean hasBeenPreparedForUpdate; + public EditConfigurationVTwo(){ writeModelSelector = StandardModelSelector.selector; queryModelSelector = StandardModelSelector.selector; resourceModelSelector = StandardModelSelector.selector; - wdfSelectorForOptons = StandardWDFSelector.selector; - modelChangePreprocessors = new LinkedList(); + wdfSelectorForOptons = StandardWDFSelector.selector; + n3generator = new EditN3GeneratorVTwo(); } //Make copy of edit configuration object public EditConfigurationVTwo copy() { EditConfigurationVTwo editConfig = new EditConfigurationVTwo(); //Copy n3generator - make copy of n3generator or get something else? - editConfig.setN3Generator(new EditN3GeneratorVTwo(this)); + editConfig.setN3Generator( this.getN3Generator() ); //For remaining ensure we make copies of all the objects and we don't use refererences //Set form url editConfig.setFormUrl(this.getFormUrl()); @@ -177,74 +178,50 @@ public class EditConfigurationVTwo { editConfig.setObject(this.getObject()); } editConfig.setVarNameForObject(this.getVarNameForObject()); - editConfig.setObjectResource(this.isObjectResource()); + editConfig.setDatapropKey(this.getDatapropKey()); //original set datapropValue, which in this case would be empty string but no way here editConfig.setDatapropValue(this.datapropValue); editConfig.setUrlPatternToReturnTo(this.getUrlPatternToReturnTo()); //n3 required - editConfig.setN3Required(this.copy(this.getN3Required())); + editConfig.setN3Required(EditConfigurationUtils.copy(this.getN3Required())); //n3 optional - editConfig.setN3Optional(this.copy(this.getN3Optional())); + editConfig.setN3Optional(EditConfigurationUtils.copy(this.getN3Optional())); //uris on form - editConfig.setUrisOnform(this.copy(this.getUrisOnform())); + editConfig.setUrisOnform(EditConfigurationUtils.copy(this.getUrisOnform())); //literals on form - editConfig.setLiteralsOnForm(this.copy(this.getLiteralsOnForm())); + editConfig.setLiteralsOnForm(EditConfigurationUtils.copy(this.getLiteralsOnForm())); //files on form - editConfig.setFilesOnForm(this.copy(this.getFilesOnForm())); - //new resources - Map copyNewResources = new HashMap(); - editConfig.setNewResources(this.copy(this.getNewResources(), copyNewResources)); + editConfig.setFilesOnForm(EditConfigurationUtils.copy(this.getFilesOnForm())); + //new resources + editConfig.setNewResources(EditConfigurationUtils.copyMap(this.getNewResources())); //uris in scope - editConfig.setUrisInScope(this.copy(this.getUrisInScope())); + editConfig.setUrisInScope(EditConfigurationUtils.copyListMap(this.getUrisInScope())); + //TODO: ensure this is not a shallow copy of literals but makes entirely new literal objects - editConfig.setLiteralsInScope(this.getLiteralsInScope()); - //editConfig.setLiteralsInScope(this.copy(this.getLiteralsInScope())); + editConfig.setLiteralsInScope(this.getLiteralsInScope()); + //editConfig.setLiteralsInScope(EditConfigurationUtils.copy(this.getLiteralsInScope())); + //sparql for additional uris in scope editConfig.setSparqlForAdditionalUrisInScope( - this.copy(this.getSparqlForAdditionalUrisInScope(), - (Map) new HashMap())); + EditConfigurationUtils.copyMap(this.getSparqlForAdditionalUrisInScope())); //sparql for additional literals in scope editConfig.setSparqlForAdditionalLiteralsInScope( - this.copy(this.getSparqlForAdditionalLiteralsInScope(), - (Map) new HashMap())); + EditConfigurationUtils.copyMap(this.getSparqlForAdditionalLiteralsInScope())); //sparql for existing literals editConfig.setSparqlForExistingLiterals( - this.copy(this.getSparqlForExistingLiterals(), - (Map) new HashMap())); + EditConfigurationUtils.copyMap(this.getSparqlForExistingLiterals())); //sparql for existing uris editConfig.setSparqlForExistingUris( - this.copy(this.getSparqlForExistingUris(), - (Map) new HashMap())); + EditConfigurationUtils.copyMap(this.getSparqlForExistingUris())); + //TODO: Ensure this is true copy of field and not just shallow copy with same references Map fields = this.getFields(); editConfig.setFields(fields); return editConfig; - } - - //make copy of list of strings - public List copy(List list) { - List copyList = new ArrayList(); - for(String l: list) { - copyList.add(l); - } - return copyList; - } - - public Map> copy(Map> source) { - HashMap> map = new HashMap>(); - Set keys = map.keySet(); - for(String key: keys) { - List vals = map.get(key); - map.put(key, this.copy(vals)); - } - return map; - } - - - + } /** @@ -266,7 +243,7 @@ public class EditConfigurationVTwo { String formattedDate = dateTime.format(Calendar.getInstance().getTime()); List dateLiterals = new ArrayList(); dateLiterals.add(ResourceFactory.createTypedLiteral(formattedDate, XSDDatatype.XSDdateTime)); - getLiteralsInScope().put("currentTime", dateLiterals); + literalsInScope.put("currentTime", dateLiterals); } /* editing user */ @@ -282,41 +259,62 @@ public class EditConfigurationVTwo { log.debug("EditConfiguration.java - checking system value for User URI " + userUri); List userUriList = new ArrayList(); userUriList.add(userUri); - getUrisInScope().put("editingUser", userUriList); + urisInScope.put("editingUser", userUriList); } } + protected void basicPrepare( ){ + if( subjectUri != null && ! subjectUri.trim().isEmpty() && + varNameForSubject != null && ! varNameForSubject.trim().isEmpty() ){ + urisInScope.put( varNameForSubject, Arrays.asList( subjectUri )); + log.debug("Putting uris in scope - var name for subject " + + varNameForSubject + " and subject is " + subjectUri); + } + + if( predicateUri != null && ! predicateUri.trim().isEmpty() && + varNameForPredicate != null && ! varNameForPredicate.trim().isEmpty() ){ + urisInScope.put( varNameForPredicate, Arrays.asList( predicateUri )); + log.debug("Putting uris in scope - var name for predicate " + + varNameForPredicate + " and predicate is " + predicateUri); + } + + if( isObjectResource() && + varNameForObject != null && ! varNameForObject.trim().isEmpty() ){ + urisInScope.put( varNameForObject, Arrays.asList(getObject())); + log.debug("Putting uris in scope - var name for object " + + varNameForObject + " and object is " + object); + } + } + //TODO: Check if require /** * Make a copy of this EditConfiguration, prepare for a DataProperty update * and return it. + * + * TODO: there is a good chance that this could be moved to the generator for + * the default data property form since that is the only place this is useful. */ public void prepareForDataPropUpdate( Model model, DataPropertyStatement dpStmt){ if( model == null ) throw new Error("EditConfiguration.prepareForDataPropUpdate() needs a Model"); - if( isObjectResource ){ - throw new Error("This request seems to be an objectPropertyStmt update, not a DataPropStmt update"); + if( isObjectResource() ){ + throw new Error("This request does not seems to be a DataPropStmt update"); } else if (datapropKey == null) { throw new Error("This request does not appear to be for an update since it lacks a dataprop object or a dataProp hash key "); } + basicPrepare(); + //TODO: Check if multiple statements might affect this implementation? List dataPropLiterals = new ArrayList(); dataPropLiterals.add(new EditLiteral(dpStmt.getData(),dpStmt.getDatatypeURI(), dpStmt.getLanguage())); - getLiteralsInScope().put(varNameForObject, dataPropLiterals); + literalsInScope.put(varNameForObject, dataPropLiterals); // run SPARQL, sub in values SparqlEvaluateVTwo sparqlEval = new SparqlEvaluateVTwo(model); runSparqlForAdditional( sparqlEval ); runSparqlForExisting( sparqlEval ); - //Saving previous N3 state before edit - //build retraction N3 for each Field - for(String var : getFields().keySet() ){ - FieldVTwo field = getField(var); - List retractions = null; - retractions = n3generator.subInMultiLiterals(getLiteralsInScope(),field.getAssertions()); - retractions = n3generator.subInMultiUris(getUrisInScope(), retractions); - field.setRetractions(retractions); - } + + hasBeenPreparedForUpdate = true; } /** @@ -325,27 +323,15 @@ public class EditConfigurationVTwo { */ public void prepareForObjPropUpdate( Model model ){ if( model == null ) { - //Added parens and output log.debug("Model is null and will be throwing an error"); throw new Error("EditConfiguration.prepareForObjPropUpdate() needs a Model");} - if( !isObjectResource ) - { - //Added parens and output - log.debug("This is not an object resource? lacks dataprop "); - throw new Error("This request does not appear to be for an update since it lacks a dataprop object or a dataProp hash key "); - } - //find the variable for object, this anchors the paths to the existing values - if( object == null || object.trim().length() == 0) - { - //Added parens and output - log.debug("Object is null or object length is null"); - throw new Error("This request does not appear to be for an update since it lacks an object"); - } + if( !isObjectResource() ) { + log.debug("This does not seem to be an object property update. Lacks object."); + throw new Error("This request does not appear to be for a object property update."); + } + + basicPrepare(); - List objectUris = new ArrayList(); - objectUris.add(object); - getUrisInScope().put( varNameForObject, objectUris); - log.debug("Putting uris in scope - var name for object " + varNameForObject + " and object is " + object); // run SPARQL, sub in values SparqlEvaluateVTwo sparqlEval = new SparqlEvaluateVTwo( model ); runSparqlForAdditional( sparqlEval ); @@ -355,23 +341,18 @@ public class EditConfigurationVTwo { e.printStackTrace(); } - //build retraction N3 for each Field - for(String var : getFields().keySet() ){ - FieldVTwo field = getField(var); - List retractions = null; - retractions = n3generator.subInMultiLiterals(getLiteralsInScope(),field.getAssertions()); - retractions = n3generator.subInMultiUris(getUrisInScope(), retractions); - field.setRetractions(retractions); - } + hasBeenPreparedForUpdate = true; } public void prepareForNonUpdate( Model model ){ if( model == null ) throw new Error("EditConfiguration.prepareForNonUpdate() needs a Model"); + + basicPrepare(); SparqlEvaluateVTwo sparqlEval = new SparqlEvaluateVTwo( model ); runSparqlForAdditional( sparqlEval ); - //runSparqlForExisting( sparqlEval ); + //runSparqlForExisting( sparqlEval ); } public void setFields(Map fields) { @@ -404,15 +385,11 @@ public class EditConfigurationVTwo { return fields.get(key); } - /** return a copy of the value so that the configuration is not modified by external code. + /** Return a copy of the value so that the configuration is not modified by external code. * @return */ public List getN3Required() { - List copyForPassByValue = new ArrayList (n3Required.size()); - for( String str : n3Required){ - copyForPassByValue.add(str); - } - return copyForPassByValue; + return EditConfigurationUtils.copy(n3Required); } public void setN3Required(List n3Required) { @@ -423,11 +400,7 @@ public class EditConfigurationVTwo { * @return */ public List getN3Optional() { - List copyForPassByValue = new ArrayList (n3Optional.size()); - for( String str : n3Optional){ - copyForPassByValue.add(str); - } - return copyForPassByValue; + return EditConfigurationUtils.copy( n3Optional ); } public void setN3Optional(List n3Optional) { @@ -482,33 +455,32 @@ public class EditConfigurationVTwo { this.literalsInScope = literalsInScope; } - /** return a copy of the value so that the configuration is not modified by external code. + /** Return a copy of the value so that the configuration is not modified by external code. * @return */ - public Map getSparqlForAdditionalUrisInScope() { - Map copyForPassByValue = new HashMap(); - copy(sparqlForAdditionalUrisInScope, copyForPassByValue); - return copyForPassByValue; + public Map getSparqlForAdditionalUrisInScope() { + return copyMap(sparqlForAdditionalUrisInScope); } public void setSparqlForAdditionalUrisInScope(Map sparqlForAdditionalUrisInScope) { this.sparqlForAdditionalUrisInScope = sparqlForAdditionalUrisInScope; } - /** return a copy of the value so that the configuration is not modified by external code. + /** Return a copy of the value so that the configuration is not modified by external code. * @return */ - public Map getSparqlForAdditionalLiteralsInScope() { - Map copyForPassByValue = new HashMap(); - copy(sparqlForAdditionalLiteralsInScope, copyForPassByValue); - return copyForPassByValue; - } - - private Map copy(Map source, Map dest){ + public Map getSparqlForAdditionalLiteralsInScope() { + return copyMap(sparqlForAdditionalLiteralsInScope); + } + + private Map copyMap(Map source){ if( source == null ) return null; - dest.clear(); + Map dest = new HashMap(); for( String key : source.keySet()){ - dest.put(key, source.get(key)); + if( source.get(key) != null ) + dest.put(new String(key), source.get(key)); + else + dest.put(new String(key), null); } return dest; } @@ -537,9 +509,7 @@ public class EditConfigurationVTwo { * @return */ public Map getSparqlForExistingLiterals() { - Map copyForPassByValue = new HashMap(); - copy(sparqlForExistingLiterals, copyForPassByValue); - return copyForPassByValue; + return copyMap(sparqlForExistingLiterals); } public void setSparqlForExistingLiterals(Map sparqlForExistingLiterals) { @@ -549,34 +519,13 @@ public class EditConfigurationVTwo { /** return a copy of the value so that the configuration is not modified by external code. * @return */ - public Map getSparqlForExistingUris() { - Map copyForPassByValue = new HashMap(); - copy(sparqlForExistingUris, copyForPassByValue); - return copyForPassByValue; + public Map getSparqlForExistingUris() { + return copyMap(sparqlForExistingUris); } public void setSparqlForExistingUris(Map sparqlForExistingUris) { this.sparqlForExistingUris = sparqlForExistingUris; - } - - - public Map> getN3ForFields(){ - return fieldsToMap( getFields() ); - } - - private Map> fieldsToMap( Map fields){ - Map> out = new HashMap>(); - for( String fieldName : fields.keySet()){ - FieldVTwo field = fields.get(fieldName); - - List copyOfN3 = new ArrayList(); - for( String str : field.getAssertions()){ - copyOfN3.add(str); - } - out.put( fieldName, copyOfN3 ); - } - return out; - } + } /* ********************** static methods to get EditConfigs from Session ******************************** */ @@ -699,12 +648,16 @@ public class EditConfigurationVTwo { } public boolean isObjectResource() { - return isObjectResource; - } - - public void setObjectResource(boolean isObjectResource) { - this.isObjectResource = isObjectResource; - } + boolean objectFound = false; + boolean dataKeyFound = false; + if( object != null && ! object.trim().isEmpty() ) + objectFound = true; + if( getDatapropKey() != null && ! getDatapropKey().isEmpty() ) + dataKeyFound = true; + if( dataKeyFound && objectFound ) + throw new Error("Bad configuration: both datapropKey and object are defined."); + return objectFound; + } public String getDatapropKey() { return datapropKey; @@ -804,11 +757,7 @@ public class EditConfigurationVTwo { public List getModelChangePreprocessors() { return this.modelChangePreprocessors; } - - public List setModelChangePreprocessors() { - return this.modelChangePreprocessors; - } - + public void addModelChangePreprocessor( ModelChangePreprocessor modelChangePreprocessor) { this.modelChangePreprocessors.add( modelChangePreprocessor ); } @@ -934,38 +883,44 @@ public class EditConfigurationVTwo { // TODO Auto-generated method stub return this.formSpecificData; } + + public boolean hasBeenPreparedForUpdate() { + return hasBeenPreparedForUpdate; + } public void addNewResource(String key, String namespace){ - if( key == null || key.isEmpty() ) throw new IllegalArgumentException("key of new resource must not be null"); - Map map = getNewResources(); - if( map == null ) { - map = new HashMap(); - map.put(key, namespace); - setNewResources(map); + if( key == null || key.isEmpty() ) + throw new IllegalArgumentException("key of new resource must not be null"); + if( newResources == null ) { + newResources = new HashMap(); + newResources.put(key, namespace); }else{ - map.put(key, namespace); + newResources.put(key, namespace); } } public void addSparqlForExistingLiteral(String key, String sparql){ - if( key == null || key.isEmpty() ) throw new IllegalArgumentException("key must not be null"); - if( sparql == null || sparql .isEmpty() ) throw new IllegalArgumentException("sparql must not be null"); + if( key == null || key.isEmpty() ) + throw new IllegalArgumentException("key must not be null"); + if( sparql == null || sparql .isEmpty() ) + throw new IllegalArgumentException("sparql must not be null"); - Map map = getSparqlForExistingLiterals(); + Map map = sparqlForExistingLiterals; if( map == null ) { map = new HashMap(); - map.put(key, sparql); - setSparqlForExistingLiterals(map); + map.put(key, sparql); }else{ map.put(key, sparql); } } public void addSparqlForExistingUris(String key, String sparql){ - if( key == null || key.isEmpty() ) throw new IllegalArgumentException("key must not be null"); - if( sparql == null || sparql .isEmpty() ) throw new IllegalArgumentException("sparql must not be null"); + if( key == null || key.isEmpty() ) + throw new IllegalArgumentException("key must not be null"); + if( sparql == null || sparql .isEmpty() ) + throw new IllegalArgumentException("sparql must not be null"); - Map map = getSparqlForExistingUris(); + Map map = sparqlForExistingUris; if( map == null ) { map = new HashMap(); map.put(key, sparql); @@ -976,17 +931,17 @@ public class EditConfigurationVTwo { } public void addField( FieldVTwo field){ - if( field == null ) throw new IllegalArgumentException("field must not be null"); - if( field.getName() == null || field.getName().isEmpty() ) throw new IllegalArgumentException("field must not have null or empty name"); + if( field == null ) + throw new IllegalArgumentException("field must not be null"); + if( field.getName() == null || field.getName().isEmpty() ) + throw new IllegalArgumentException("field must not have null or empty name"); + if( fields == null ) + fields = new HashMap(); + + if( fields.containsKey(field.getName() )) + throw new IllegalArgumentException("adding filed that is already in the field list"); - Map map = getFields(); - if( map == null ) - setFields( new HashMap()); - - if( map.containsKey(field.getName() )) - throw new IllegalArgumentException("adding filed that is already in the fieild list"); - - map.put( field.getName(), field); + fields.put( field.getName(), field); } @Override diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditN3GeneratorVTwo.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditN3GeneratorVTwo.java index dc320ae1a..f26530bca 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditN3GeneratorVTwo.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditN3GeneratorVTwo.java @@ -26,141 +26,185 @@ import com.hp.hpl.jena.vocabulary.XSD; * */ public class EditN3GeneratorVTwo { - - EditConfigurationVTwo editConfig; - static final Log log = LogFactory.getLog( EditN3GeneratorVTwo.class ); - - public EditN3GeneratorVTwo( EditConfigurationVTwo editConfig ){ - this.editConfig = editConfig; - } - - public List generateN3(MultiValueEditSubmission editSub, Model model){ - return Collections.EMPTY_LIST; - } + + static final Log log = LogFactory.getLog( EditN3GeneratorVTwo.class ); /** * This is the method to use to substitute in URIs into variables of target N3 strings. * This takes into account multiple values that would be returned from a select list. * subInUris should no longer be used. + * * It's important that the map contain String to List mapping. - * Before values are sent in, all of the values for a variable should be placed within an array - */ - - - public static List subInMultiUris(Map> varsToVals, List n3targets){ + * + * Before values are sent in, all of the values for a variable should be placed within an array. + * + * The List n3targets will be modified. + */ + public void subInMultiUris(Map> varsToVals, List n3targets){ - if( varsToVals == null || varsToVals.isEmpty() ) return n3targets; - ArrayList outv = new ArrayList(); - for( String target : n3targets){ - String temp = target; - Set keySet = varsToVals.keySet(); - for( String key : keySet) { - List value = varsToVals.get(key); - String valueString = value.toString(); - log.debug("Value String is " + valueString); - valueString = org.apache.commons.lang.StringUtils.join(value, ">, <"); - valueString = "<" + valueString + ">"; - log.debug("Value string is " + valueString); - temp = subInNonBracketedURIS( key, valueString, temp) ; - } - outv.add(temp); - } - return outv; - } - - //Already includes "<> for URIs so no need to add those here - private static String subInNonBracketedURIS(String var, String value, String target) { - //empty URIs get skipped - if( var == null || var.length() == 0 || value==null ) - return target; - /* var followed by dot some whitespace or var followed by whitespace*/ - String varRegex = "\\?" + var + "(?=\\.\\p{Space}|\\p{Space})"; - String out = null; - if("".equals(value)) - out = target.replaceAll(varRegex,">::" + var + " was BLANK::< "); - else { - String replaceWith = Matcher.quoteReplacement(value); - out = target.replaceAll(varRegex,replaceWith); - } - if( out != null && out.length() > 0 ) - return out; - else - return target; - } - - public static List subInUris(Map varsToVals, List targets){ - if( varsToVals == null || varsToVals.isEmpty() ) return targets; - ArrayList outv = new ArrayList(); - for( String target : targets){ - String temp = target; - for( String key : varsToVals.keySet()) { - temp = subInUris( key, varsToVals.get(key), temp) ; + if( varsToVals == null || varsToVals.isEmpty() ) return; + + //for (String target : n3targets) { + for( int i = 0; i < n3targets.size() ; i++ ){ + String result = n3targets.get(i); + Set keySet = varsToVals.keySet(); + for (String key : keySet) { + List value = varsToVals.get(key); + log.debug("The original value String is " + value.toString()); + + String valueString = org.apache.commons.lang.StringUtils.join(value, + ">, <"); + valueString = "<" + valueString + ">"; + log.debug("The multiUri value String is " + valueString); + + result = subInNonBracketedURIS(key, valueString, result); } - outv.add(temp); - } - return outv; + n3targets.set(i, result); + } } + + /** + * The List targets will be modified. + */ + public void subInUris(Map varsToVals, List targets){ + if( varsToVals == null || varsToVals.isEmpty() || targets == null ) + return; - - - //Already includes "<> for URIs so no need to add those here - public static String subInUris(String var, String value, String target) { + for( int i = 0; i < targets.size() ; i++ ){ + String result = targets.get(i); + for( String key : varsToVals.keySet()) { + result = subInUris( key, varsToVals.get(key), result); + } + targets.set(i,result); + } + } + + public String subInUris(String var, String value, String target) { + // empty URIs get skipped if( var == null || var.isEmpty() || value == null ) - return target; + return target; + return subInNonBracketedURIS(var, "<" + value + ">", target); } - - /* - //For cases where comma delimited URIs sent in already including <> - public static String subInMultipleUris(String var, List values, String target){ - //empty URIs get skipped - if( var == null || var.length() == 0 || values==null || values.size() == 0) - return target; - - String varRegex = "\\?" + var + "(?=\\.\\p{Space}|\\p{Space})"; - String out = null; - //Process each - for(String value: values) { - if("".equals(value)) - out = target.replaceAll(varRegex,">::" + var + " was BLANK::< "); - else - out = target.replaceAll(varRegex,"<"+Matcher.quoteReplacement(value)+"> "); - } - if( out != null && out.length() > 0 ) - return out; - else - return target; - - } - */ - public static ListsubInUris(String var, String value, List targets){ - ArrayList outv =new ArrayList(); + + public void subInUris(String var, String value, List targets){ for( String target : targets){ - outv.add( subInUris( var,value, target) ) ; - } - return outv; + subInUris( var, value, target); + } } /** * This is the method to use to substitute in Literals into variables of target N3 strings. * This takes into account multiple values that would be returned from a select list. * subInUris should no longer be used. + * + * It will modify the list n3targets. */ - public static List subInMultiLiterals(Map> varsToVals, List n3targets){ - if( varsToVals == null || varsToVals.isEmpty()) return n3targets; - - ArrayListoutv=new ArrayList(); - for( String n3 : n3targets ){ - String tmp = n3; - for( String key : varsToVals.keySet()){ - tmp = subInMultiLiterals( key, varsToVals.get(key),tmp); - } - outv.add(tmp); + public void subInMultiLiterals(Map> varsToVals, List n3targets){ + if( varsToVals == null || varsToVals.isEmpty() || n3targets == null) + return; + + for( int i=0; i< n3targets.size() ; i++ ){ + String orginalN3 = n3targets.get(i); + String newN3 = orginalN3; + for( String key : varsToVals.keySet() ){ + newN3 = subInMultiLiterals( key, varsToVals.get(key), newN3 ); + } + n3targets.set(i, newN3); } - return outv; } - protected static String subInMultiLiterals(String var, Listvalues, String n3){ + public void subInLiterals(Map varsToVals, List n3targets){ + if( varsToVals == null || varsToVals.isEmpty() || n3targets==null) + return; + + for( int i=0; i< n3targets.size() ; i++ ){ + String orginalN3 = n3targets.get(i); + String newN3 = orginalN3; + for( String key : varsToVals.keySet() ){ + newN3 = subInLiterals( key, varsToVals.get(key), newN3 ); + } + n3targets.set(i, newN3); + } + } + + + /** + * When we sub in literals we have to take in to account the Lang or Datatype of + * the literal. N3 needs to have its literals escaped in Python style. Java regex + * Matcher is used to do the substitution and it need escaping to avoid group + * references, Matcher.quoteReplacement() serves the purpose. + * + */ + protected String subInLiterals(String var, Literal literal, String target){ + String varRegex = "\\?" + var + "(?=\\.\\p{Space}|\\p{Space})"; + if (target==null ) { + log.error("subInLiterals was passed a null target"); + return "blankBecauseTargetOrValueWasNull"; + }else if( var == null ){ + log.warn("subInLiterals was passed a null var name"); + return target; + }else if( literal == null ){ + log.debug("subInLiterals was passed a null value for var '"+var+"'; returning target: '"+target+"'"); + return target; + } + + try{ + if( literal.getValue() == null ) + log.debug("value of literal for " + var + " was null"); + }catch(com.hp.hpl.jena.datatypes.DatatypeFormatException ex){ + log.debug("value for " + var + " " + ex.getMessage()); + } + + String replacement = null; + if ( literal.getLexicalForm().length()==0 ) { + log.debug("empty string found on form for " + var + "."); + replacement = ">::" + var + " was empty::<"; + }else{ + replacement = formatLiteral(literal); + } + + String out = null; + if( replacement != null ) + out = target.replaceAll(varRegex, Matcher.quoteReplacement( replacement )); + else + out = target; + + if( out != null && out.length() > 0 ) + return out; + else{ + log.debug("After attempting to substitue in literals, the target N3 was empty" ); + return target; + } + } + + + private Map> substituteIntoValues + (Map> varsToUris, + Map> varsToLiterals, + Map> namesToN3 ) + { + Map> outHash = new HashMap>(); + + if (namesToN3==null) { + return outHash; + } else if (namesToN3.isEmpty()) { + return outHash; + } else { + for(String fieldName : namesToN3.keySet()){ + List n3strings = namesToN3.get(fieldName); + List newList = new ArrayList(); +// if( varsToUris != null) +// newList = subInMultiUris(varsToUris, n3strings); +// if( varsToLiterals != null) +// newList = subInMultiLiterals(varsToLiterals, newList); + outHash.put(fieldName, newList); + } + } + return outHash; + } + + protected String subInMultiLiterals(String var, Listvalues, String n3){ if (n3==null ) { log.error("subInMultiLiterals was passed a null n3 String"); return "blankBecauseTargetOrValueWasNull"; @@ -197,108 +241,7 @@ public class EditN3GeneratorVTwo { } - public List subInLiterals(Map varsToVals, List targets){ - if( varsToVals == null || varsToVals.isEmpty()) return targets; - ArrayList outv =new ArrayList(); - for( String target : targets){ - String temp = target; - for( String key : varsToVals.keySet()) { - temp = subInLiterals( key, varsToVals.get(key), temp); - } - outv.add(temp); - } - return outv; - } - -// public ListsubInLiterals(String var, String value, List targets){ -// ArrayList outv =new ArrayList(); -// for( String target : targets){ -// outv.add( subInLiterals( var,value, target) ) ; -// } -// return outv; -// } - - /** - * When we sub in literals we have to take in to account the Lang or Datatype of - * the literal. N3 needs to have its literals escaped in Python style. Java regex - * Matcher is used to do the substitution and it need escaping to avoid group - * references, Matcher.quoteReplacement() serves the purpose. - * - */ - public String subInLiterals(String var, Literal literal, String target){ - String varRegex = "\\?" + var + "(?=\\.\\p{Space}|\\p{Space})"; - if (target==null ) { - log.error("subInLiterals was passed a null target"); - return "blankBecauseTargetOrValueWasNull"; - }else if( var == null ){ - log.warn("subInLiterals was passed a null var name"); - return target; - }else if( literal == null ){ - log.debug("subInLiterals was passed a null value for var '"+var+"'; returning target: '"+target+"'"); - return target; - } - - try{ - if( literal.getValue() == null ) - log.debug("value of literal for " + var + " was null"); - }catch(com.hp.hpl.jena.datatypes.DatatypeFormatException ex){ - log.debug("value for " + var + " " + ex.getMessage()); - } - - //if( editConfig != null && editConfig.getFields() != null && - // editConfig.getFields().get(var) != null ){ - //The var might not be in the editConfig.fields if an EditN3Generator - //is being used to substitute in values that are not on the form, - //eg ?fileSize for file uploads - - String replacement = null; - if ( literal.getLexicalForm().length()==0 ) { - log.debug("empty string found on form for " + var + "."); - replacement = ">::" + var + " was empty::<"; - }else{ - replacement = formatLiteral(literal); - } - - String out = null; - if( replacement != null ) - out = target.replaceAll(varRegex, Matcher.quoteReplacement( replacement )); - else - out = target; - - if( out != null && out.length() > 0 ) - return out; - else{ - log.debug("After attempting to substitue in literals, the target N3 was empty" ); - return target; - } - } - - - public Map> substituteIntoValues - (Map> varsToUris, - Map> varsToLiterals, - Map> namesToN3 ) - { - Map> outHash = new HashMap>(); - - if (namesToN3==null) { - return outHash; - } else if (namesToN3.isEmpty()) { - return outHash; - } else { - for(String fieldName : namesToN3.keySet()){ - List n3strings = namesToN3.get(fieldName); - List newList = new ArrayList(); - if( varsToUris != null) - newList = subInMultiUris(varsToUris, n3strings); - if( varsToLiterals != null) - newList = subInMultiLiterals(varsToLiterals, newList); - outHash.put(fieldName, newList); - } - } - return outHash; - } protected String quoteForN3(String in){ //TODO: THIS NEEDS TO BE ESCAPED FOR N3 which is python string escaping @@ -306,6 +249,19 @@ public class EditN3GeneratorVTwo { } + //Already includes "<> for URIs so no need to add those here + protected String subInNonBracketedURIS(String var, String value, String target) { + /* var followed by dot some whitespace or var followed by whitespace*/ + String varRegex = "\\?" + var + "(?=\\p{Punct}|\\p{Space})"; + String out = null; + if("".equals(value)) + return target.replaceAll(varRegex,">::" + var + " was BLANK::< "); + else { + String replaceWith = Matcher.quoteReplacement(value); + return target.replaceAll(varRegex,replaceWith); + } + } + /* * bdc34 2008-07-33 * diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/FieldVTwo.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/FieldVTwo.java index c97538f64..bd6c072d3 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/FieldVTwo.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/FieldVTwo.java @@ -38,10 +38,7 @@ public class FieldVTwo { }; public static String RDF_XML_LITERAL_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral"; - - private boolean newResource; - - private static Log log = LogFactory.getLog( FieldVTwo.class ); + private String name; @@ -90,31 +87,6 @@ public class FieldVTwo { */ private List> literalOptions; - /** - * Strings of N3 to add to model. - */ - private List assertions; - - /** - * JSON configuration that was used to build this object. - */ - private String originalJson; - - /** - * Do not attempt to set the retractions when configuring a Field; they get built by the - * edit processing object. - * - * The strings in this list should be N3 for statements that need to be retracted to affect an update. - * Per Field retractions are necessary since we only want to retract for fields that have changed. - * The Model should be checked to make sure that all of the retractions exist so we are changing the - * statements that existed when this edit was configured. - * - * These retractions are just the assertions with the values subistituted in from before the change. - */ - private List retractions; - - private Map queryForExisting; - /** * Property for special edit element. */ @@ -140,37 +112,7 @@ public class FieldVTwo { public String getName(){ return name; - } - - public List getRetractions() { - return retractions; - } - - public FieldVTwo setRetractions(List retractions) { - this.retractions = retractions; - return this; - } - - public List getAssertions() { - return assertions; - } - - public FieldVTwo setAssertions(List assertions) { - this.assertions = assertions; - return this; - } - - public FieldVTwo setAssertions( String ... assertions ){ - return setAssertions( Arrays.asList( assertions )); - } - - public boolean isNewResource() { - return newResource; - } - public FieldVTwo setNewResource(boolean b) { - newResource = b; - return this; - } + } public List getValidators() { return validators; diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/N3EditUtils.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/N3EditUtils.java index e150acc15..e17491f79 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/N3EditUtils.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/N3EditUtils.java @@ -17,8 +17,7 @@ public class N3EditUtils { /** - * Execute any modelChangePreprocessors in the editConfiguration; - * TODO: Should be moved to Utils or Controller + * Execute any modelChangePreprocessors in the editConfiguration; */ public static void preprocessModels( AdditionsAndRetractions changes, @@ -49,8 +48,8 @@ public class N3EditUtils { EditN3GeneratorVTwo n3Subber = configuration.getN3Generator(); //Substitute URIs and literals from form - entityToReturnTo = n3Subber.subInMultiUris(submission.getUrisFromForm(), entityToReturnTo); - entityToReturnTo = n3Subber.subInMultiLiterals(submission.getLiteralsFromForm(), entityToReturnTo); + n3Subber.subInMultiUris(submission.getUrisFromForm(), entityToReturnTo); + n3Subber.subInMultiLiterals(submission.getLiteralsFromForm(), entityToReturnTo); //TODO: this won't work, must the same new resources as in ProcessRdfForm.process //setVarToNewResource(configuration, vreq); diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/ProcessRdfForm.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/ProcessRdfForm.java index ba34633d9..ef6b0c8ac 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/ProcessRdfForm.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/ProcessRdfForm.java @@ -15,6 +15,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hp.hpl.jena.ontology.OntModel; +import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.shared.Lock; @@ -36,6 +37,19 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.controller.ProcessRdfForm */ public class ProcessRdfForm { + private NewURIMaker newURIMaker; + private EditN3GeneratorVTwo populator; + + private Map urisForNewResources = null; + + /** + * Construct the ProcessRdfForm object. + */ + public ProcessRdfForm( EditConfigurationVTwo config, NewURIMaker newURIMaker){ + this.newURIMaker = newURIMaker; + this.populator = config.getN3Generator(); + } + /** * This detects if this is an edit of an existing statement or an edit * to create a new statement or set of statements. Then the correct @@ -48,10 +62,9 @@ public class ProcessRdfForm { * @throws Exception May throw an exception if Required N3 does not * parse correctly. */ - public static AdditionsAndRetractions process( + public AdditionsAndRetractions process( EditConfigurationVTwo configuration, - MultiValueEditSubmission submission, - NewURIMaker newURIMaker) + MultiValueEditSubmission submission) throws Exception{ log.debug("configuration:\n" + configuration.toString()); log.debug("submission:\n" + submission.toString()); @@ -60,9 +73,9 @@ public class ProcessRdfForm { AdditionsAndRetractions changes; if( configuration.isUpdate() ){ - changes = editExistingStatements(configuration, submission, newURIMaker); + changes = editExistingStatements(configuration, submission); } else { - changes = createNewStatements(configuration, submission, newURIMaker); + changes = createNewStatements(configuration, submission ); } changes = getMinimalChanges(changes); @@ -85,85 +98,139 @@ public class ProcessRdfForm { * * @throws Exception May throw an exception if the required N3 * does not parse. - */ - @SuppressWarnings("static-access") - private static AdditionsAndRetractions createNewStatements( + */ + private AdditionsAndRetractions createNewStatements( EditConfigurationVTwo configuration, - MultiValueEditSubmission submission, - NewURIMaker newURIMaker) throws Exception { - - log.debug("in createNewStatements()" ); - - EditN3GeneratorVTwo n3Populator = configuration.getN3Generator(); + MultiValueEditSubmission submission) throws Exception { + log.debug("in createNewStatements()" ); + //getN3Required and getN3Optional will return copies of the + //N3 String Lists so that this code will not modify the originals. List requiredN3 = configuration.getN3Required(); List optionalN3 = configuration.getN3Optional(); - logRequiredOpt("Original valus for required and optional", requiredN3, optionalN3); - /* add subject from configuration */ - requiredN3 = n3Populator.subInUris(getSubPedObjVarMap(configuration), requiredN3); - optionalN3 = n3Populator.subInUris(getSubPedObjVarMap(configuration), optionalN3); - logRequiredOpt("attempted to substitute in subject, predicate and object from configuration", requiredN3, optionalN3); - - /* add URIs from the form/EditSubmission */ - requiredN3 = n3Populator.subInMultiUris(submission.getUrisFromForm(), requiredN3); - optionalN3 = n3Populator.subInMultiUris(submission.getUrisFromForm(), optionalN3); - logRequiredOpt("substitued in URIs from submission", requiredN3, optionalN3); - - /* add Literals from the form/EditSubmission */ - requiredN3 = n3Populator.subInMultiLiterals(submission.getLiteralsFromForm(), requiredN3); - optionalN3 = n3Populator.subInMultiLiterals(submission.getLiteralsFromForm(), optionalN3); - logRequiredOpt("substitued in Literals from form", requiredN3, optionalN3); - - /* Add URIs in scope */ - requiredN3 = n3Populator.subInMultiUris(configuration.getUrisInScope(), requiredN3); - optionalN3 = n3Populator.subInMultiUris(configuration.getUrisInScope(), optionalN3); - logRequiredOpt("substitued in URIs from configuration scope", requiredN3, optionalN3); - - /* Add Literals in scope */ - requiredN3 = n3Populator.subInMultiLiterals(configuration.getLiteralsInScope(), requiredN3); - optionalN3 = n3Populator.subInMultiLiterals(configuration.getLiteralsInScope(), optionalN3); - logRequiredOpt("substitued in Literals from scope", requiredN3, optionalN3); - - /* add URIs for new resources */ - Map urisForNewResources = URIsForNewRsources(configuration, newURIMaker); - - requiredN3 = n3Populator.subInUris(urisForNewResources, requiredN3); - optionalN3 = n3Populator.subInUris(urisForNewResources, optionalN3); - logRequiredOpt("substitued in new resource URIs", requiredN3, optionalN3); - - /* parse N3 to RDF Models */ - List assertions = parseN3ToRDF( requiredN3 , REQUIRED ); - assertions.addAll( parseN3ToRDF( optionalN3, OPTIONAL )); - - /* No retractions since all of the statements are new. */ - List retractions = Collections.emptyList(); - return new AdditionsAndRetractions(assertions, retractions); + /* substitute in the form values and existing values */ + subInValuesToN3( configuration, submission, requiredN3, optionalN3, null , null); + + /* parse N3 to RDF Models, No retractions since all of the statements are new. */ + return parseN3ToChange(requiredN3, optionalN3, null, null); } +// @SuppressWarnings("unchecked") +// protected void substituteInValuesForCreateNew( +// EditConfigurationVTwo configuration, +// MultiValueEditSubmission submission, List requiredN3, +// List optionalN3) throws InsertException { +// logRequiredOpt("Original valus for required and optional", requiredN3, optionalN3); +// +// /* add subject from configuration */ +// substituteInSubPredObjURIs( configuration, requiredN3, optionalN3); +// logRequiredOpt("attempted to substitute in subject, predicate and object from configuration", requiredN3, optionalN3); +// +// /* add URIs from the form/EditSubmission */ +// substituteInMultiURIs( submission.getUrisFromForm(), requiredN3, optionalN3); +// logRequiredOpt("substitued in URIs from submission", requiredN3, optionalN3); +// +// /* add Literals from the form/EditSubmission */ +// substituteInMultiLiterals( submission.getLiteralsFromForm(), requiredN3, optionalN3); +// logRequiredOpt("substitued in Literals from form", requiredN3, optionalN3); +// +// /* Add URIs in scope */ +// substituteInMultiURIs( configuration.getUrisInScope(), requiredN3, optionalN3); +// logRequiredOpt("substitued in URIs from configuration scope", requiredN3, optionalN3); +// +// /* Add Literals in scope */ +// substituteInMultiLiterals(configuration.getLiteralsInScope(), requiredN3, optionalN3); +// logRequiredOpt("substitued in Literals from scope", requiredN3, optionalN3); +// +// /* add URIs for new resources */ +// urisForNewResources = URIsForNewRsources(configuration, newURIMaker); +// substituteInURIs( urisForNewResources, requiredN3, optionalN3); +// logRequiredOpt("substitued in new resource URIs", requiredN3, optionalN3); +// } - /** - * Process an EditConfiguration to edit a set of existing statements. - * - * In this method, the N3 associated with fields that changed be - * processed in two sets, one for the state before the edit and - * another for the state after the edit. - * - * This will handle data property editing, object property editing - * and general editing. - */ - private static AdditionsAndRetractions editExistingStatements( - EditConfigurationVTwo editConfiguration, - MultiValueEditSubmission submission, - NewURIMaker newURIMaker) { - log.debug("in editExistingStatements()"); - - List fieldAssertions = populateAssertions(editConfiguration, submission, newURIMaker); - List fieldRetractions = populateRetractions(editConfiguration, submission, newURIMaker); - return new AdditionsAndRetractions(fieldAssertions, fieldRetractions); + /* for a list of N3 strings, substitute in the subject, predicate and object URIs + * from the EditConfiguration. */ + protected void substituteInSubPredObjURIs( + EditConfigurationVTwo configuration, + List... n3StrLists){ + Map valueMap = getSubPedObjVarMap(configuration); + for (List n3s : n3StrLists) { + populator.subInUris(valueMap, n3s); + } } + + /** + * Process an EditConfiguration to edit a set of existing statements. + * + * This will handle data property editing, object property editing and + * general editing. + * + * No longer checking if field has changed, because assertions and + * retractions are mutually diff'ed before statements are added to or + * removed from the model. The explicit change check can cause problems in + * more complex setups, like the automatic form building in DataStaR. + */ + protected AdditionsAndRetractions editExistingStatements( + EditConfigurationVTwo editConfig, + MultiValueEditSubmission submission) throws Exception { + + log.debug("editing an existing resource: " + editConfig.getObject() ); + + //getN3Required and getN3Optional will return copies of the + //N3 String Lists so that this code will not modify the originals. + List N3RequiredAssert = editConfig.getN3Required(); + List N3OptionalAssert = editConfig.getN3Optional(); + List N3RequiredRetract = editConfig.getN3Required(); + List N3OptionalRetract = editConfig.getN3Optional(); + + subInValuesToN3(editConfig, submission, + N3RequiredAssert, N3OptionalAssert, + N3RequiredRetract, N3OptionalRetract); + + return parseN3ToChange( + N3RequiredAssert,N3OptionalAssert, + N3RequiredRetract, N3OptionalRetract); + } + @SuppressWarnings("unchecked") + protected void subInValuesToN3( + EditConfigurationVTwo editConfig, MultiValueEditSubmission submission, + List requiredAsserts, List optionalAsserts, + List requiredRetracts, List optionalRetracts ) throws InsertException{ + + /* ********** Form submission URIs ********* */ + substituteInMultiURIs(submission.getUrisFromForm(), requiredAsserts, optionalAsserts); + logSubstitue( "Added form URIs", requiredAsserts, optionalAsserts, requiredRetracts, optionalRetracts); + //Retractions does NOT get values from form. + + /* ******** Form submission Literals *********** */ + substituteInMultiLiterals( submission.getLiteralsFromForm(), requiredAsserts, optionalAsserts); + logSubstitue( "Added form Literals", requiredAsserts, optionalAsserts, requiredRetracts, optionalRetracts); + //Retractions does NOT get values from form. + + /* *********** Add subject, object and predicate ******** */ + substituteInSubPredObjURIs(editConfig, requiredAsserts, optionalAsserts, requiredRetracts, optionalRetracts); + logSubstitue( "Added sub, pred and obj URIs", requiredAsserts, optionalAsserts, requiredRetracts, optionalRetracts); + + /* ********* Existing URIs and Literals ********** */ + substituteInMultiURIs(editConfig.getUrisInScope(), + requiredAsserts, optionalAsserts, requiredRetracts, optionalRetracts); + logSubstitue( "Added existing URIs", requiredAsserts, optionalAsserts, requiredRetracts, optionalRetracts); + + substituteInMultiLiterals(editConfig.getLiteralsInScope(), + requiredAsserts, optionalAsserts, requiredRetracts, optionalRetracts); + logSubstitue( "Added existing Literals", requiredAsserts, optionalAsserts, requiredRetracts, optionalRetracts); + //Both Assertions and Retractions get existing values. + + /* ************ Edits may need new resources *********** */ + urisForNewResources = URIsForNewRsources(editConfig, newURIMaker); + substituteInURIs( urisForNewResources, requiredAsserts, optionalAsserts); + logSubstitue( "Added URIs for new Resources", requiredAsserts, optionalAsserts, requiredRetracts, optionalRetracts); + // Only Assertions get new resources. + } + //TODO: maybe move this to utils or contorller? public static AdditionsAndRetractions addDependentDeletes( AdditionsAndRetractions changes, Model queryModel){ //Add retractions for dependent resource delete if that is configured and @@ -196,6 +263,22 @@ public class ProcessRdfForm { } } + protected AdditionsAndRetractions parseN3ToChange( + List requiredAdds, List optionalAdds, + List requiredDels, List optionalDels) throws Exception{ + + List adds = parseN3ToRDF(requiredAdds, REQUIRED); + adds.addAll( parseN3ToRDF(optionalAdds, OPTIONAL)); + + List retracts = new ArrayList(); + if( requiredDels != null && optionalDels != null ){ + retracts.addAll( parseN3ToRDF(requiredDels, REQUIRED) ); + retracts.addAll( parseN3ToRDF(optionalDels, OPTIONAL) ); + } + + return new AdditionsAndRetractions(adds,retracts); + } + /** * Parse the n3Strings to a List of RDF Model objects. * @@ -204,7 +287,7 @@ public class ProcessRdfForm { * If REQUIRED, then throw exceptions on errors. * @throws Exception */ - private static List parseN3ToRDF( + protected static List parseN3ToRDF( List n3Strings, N3ParseType parseType ) throws Exception { List errorMessages = new ArrayList(); @@ -241,94 +324,7 @@ public class ProcessRdfForm { } return rdfModels; - } - - - - - //optional field assertions - //if data property, then this would be empty - public static List getOptionalN3Assertions( - EditConfigurationVTwo configuration, MultiValueEditSubmission submission, - NewURIMaker newURIMaker) { - - //Default object property form and default data property form - // avoid having the optional N3 assertions worked with by - // not configuring anything in configuration.setN3Optional() - - List optionalN3Assertions = new ArrayList(); - List n3Optional = configuration.getN3Optional(); - //Substitute uris and literals, including for - n3Optional = subUrisAndLiteralsForN3(configuration, submission, newURIMaker, n3Optional); - optionalN3Assertions = processN3Assertions(configuration, submission, newURIMaker, n3Optional); - return optionalN3Assertions; - } - - - /** - * Certain methods/mechanisms overlap across type of property (object or data) and whether or not - * the updates are for existing or new resource or value - */ - - - //get field assertions - so these appear to be employed when editing an EXISTING literal or resource - //Also note this depends on field assertions - public static List getRequiredFieldAssertions( - EditConfigurationVTwo configuration, - MultiValueEditSubmission submission, - NewURIMaker newURIMaker) { - - List requiredFieldAssertions = new ArrayList(); - //Get the original assertions from the edit configuration field - Map> fieldAssertions = - Utilities.fieldsToN3Map(configuration.getFields(), Utilities.assertionsType); - - fieldAssertions = subUrisAndLiteralsInFieldAssertions(configuration, submission, newURIMaker, fieldAssertions); - //process assertions - requiredFieldAssertions = parseFieldAssertions( fieldAssertions ); - return requiredFieldAssertions; - } - - - public static List getRequiredFieldRetractions( - EditConfigurationVTwo configuration, - MultiValueEditSubmission submission ) { - - List requiredFieldRetractions = new ArrayList(); - - //TODO: Huda: Check if need to check twice or if once is sufficient? - //if adding new object no retractions, although this should be empty if adding new literal too? - if(!configuration.isDataPropertyUpdate() && !configuration.isObjectPropertyUpdate()) { - return new ArrayList(); - } - - //else populate - //If data property, field retractions based on field alone and if object property additional - //retraction processing required - if(configuration.isObjectPropertyUpdate()){ - Map> fieldRetractions = Utilities.fieldsToN3Map(configuration.getFields(), Utilities.retractionsType); - //sub in uris and literals for field - //fieldRetractions = subUrisAndLiteralsInFieldRetractions(configuration, submission, fieldRetractions); - requiredFieldRetractions = processFieldRetractions(configuration, submission, fieldRetractions); - } - if(configuration.isDataPropertyUpdate()) { - //this simply goes through each field and checks if it has retractions - requiredFieldRetractions = processFieldRetractions(configuration, submission); - } - return requiredFieldRetractions; - } - - //required assertions based on N3 - public static List getRequiredN3Assertions( - EditConfigurationVTwo configuration, MultiValueEditSubmission submission, - NewURIMaker newURIMaker) { - - List n3Required = configuration.getN3Required(); - //Substitute uris and literals, including for - n3Required = subUrisAndLiteralsForN3(configuration, submission, newURIMaker, n3Required); - return processN3Assertions(configuration, submission, newURIMaker, n3Required); - } - + } /** * TODO: bdc34: what does this check? Why? @@ -346,290 +342,27 @@ public class ProcessRdfForm { // } return false; } - - private static boolean logRequiredOpt(String msg, Listrequired, Listoptional){ - if( log.isDebugEnabled() ){ - String out = msg + "\n"; - - if( required != null ){ - out += "required:\n" ; - for( String str : required){ - out += " " + str + "\n"; - } - }else{ - out += " No required\n"; - } - - if( optional != null ){ - out += "optional:\n"; - for( String str : optional){ - out += " " + str + "\n"; - } - }else{ - out += " No Optional\n"; - } - - } - return true; + + protected void logSubstitue(String msg, List requiredAsserts, + List optionalAsserts, List requiredRetracts, + List optionalRetracts) { + if( !log.isDebugEnabled() ) return; + logSubstitueN3( msg, requiredAsserts, "required assertions"); + logSubstitueN3( msg, optionalAsserts, "optional assertions"); + logSubstitueN3( msg, requiredRetracts, "required retractions"); + logSubstitueN3( msg, optionalRetracts, "optional retractions"); } - - //generally should always have assertions - private static List populateAssertions( - EditConfigurationVTwo configuration, MultiValueEditSubmission submission, - NewURIMaker newURIMaker) { - List assertions = new ArrayList(); - //if editing existing statement, then assertions based on field - if(configuration.isDataPropertyUpdate() || configuration.isObjectPropertyUpdate()) { - assertions = getRequiredFieldAssertions(configuration, submission, newURIMaker); - } - //otherwise, if new literal or value, assertions generated from n3 required or n3 optional statements - else { - - } - return assertions; - } - - //"final" or general methods- get the assertions and retractions - private static List populateRetractions( - EditConfigurationVTwo configuration, MultiValueEditSubmission submission, - NewURIMaker newURIMaker) { - List retractions = new ArrayList(); - //if adding new object no retractions, although this should be empty if adding new literal too? - if(!configuration.isDataPropertyUpdate() && !configuration.isObjectPropertyUpdate()) { - return new ArrayList(); - } - - //retractions = getRequiredFieldRetractions(configuration, submission, newURIMaker); - - return retractions; - } - - - //this occurs for edits of existing statements whether object resource or literal - //In data form, not only is the condition for edit check but an additional check regarding - //has field changed is included, whereas object form depends only on whether or not this is an edit - //Here we take care of both conditions but including a method that checks whether or not to populate the assertions - //model - - /** Parse field assertion N3 to RDF Model objects */ - private static List parseFieldAssertions( -// EditConfigurationVTwo configuration, -// MultiValueEditSubmission submission, - Map> fieldAssertions) { - - List requiredFieldAssertions = new ArrayList(); - List errorMessages = new ArrayList(); - - //Loop through field assertions - for(String fieldName : fieldAssertions.keySet()){ - //this checks whether or not proceed with populating the model based on the field -// if(isGenerateModelFromField(fieldName, configuration, submission)) { - List assertions = fieldAssertions.get(fieldName); - for(String n3: assertions){ - try{ - Model model = ModelFactory.createDefaultModel(); - StringReader reader = new StringReader(n3); - model.read(reader, "", "N3"); - requiredFieldAssertions.add(model); - }catch(Throwable t){ - String errMsg = "error processing N3 assertion string from field " + fieldName + "\n" + - t.getMessage() + '\n' + "n3: \n" + n3; - errorMessages.add(errMsg); - } - //} - } - } - - log.error("bdc34: is this code every used?"); - if( !errorMessages.isEmpty() ){ - String msg = "Error processing required N3.\n"; - for( String em : errorMessages){ - msg += em + '\n'; - } - throw new Error(msg); - } - - //if data property - since only see that there - then check for empty string condition - //which means only one value and it is an empty string - //TODO: bdc34 why is this happening here? Could this happen in a default data property form - // model processor? -// if(Utilities.checkForEmptyString(submission, configuration, vreq)) { -// requiredFieldAssertions.clear(); -// } - return requiredFieldAssertions; - } - - //data property version , gets retractions from each field - private static List processFieldRetractions( - EditConfigurationVTwo configuration, - MultiValueEditSubmission submission) { - - List requiredFieldRetractions = new ArrayList(); - //Get key set for fields - Map fields = configuration.getFields(); - for(String fieldName: fields.keySet()) { - //get retractions from field retractions for this field - post uri substitution etc. - FieldVTwo field = fields.get(fieldName); - if(Utilities.hasFieldChanged(fieldName, configuration, submission)) { - List retractions = field.getRetractions(); - if(retractions != null) { - for( String n3 : retractions ){ - try{ - Model model = ModelFactory.createDefaultModel(); - StringReader reader = new StringReader(n3); - model.read(reader, "", "N3"); - requiredFieldRetractions.add(model); - }catch(Throwable t){ - String errMsg = "error processing N3 retraction string from field " + fieldName + "\n"+ - t.getMessage() + '\n' + - "n3: \n" + n3; - //errorMessages.add(errMsg); - log.error(errMsg); - } - } - - } - } - } - return requiredFieldRetractions; - } - - //this expects an input map with retractions populated and and with uris/literals subbed - private static List processFieldRetractions( - EditConfigurationVTwo configuration, - MultiValueEditSubmission submission, - Map> fieldRetractions) { - List requiredFieldRetractions = new ArrayList(); - //Get key set for fields - Map fields = configuration.getFields(); - for(String fieldName: fields.keySet()) { - //get retractions from field retractions for this field - post uri substitution etc. - List retractions = fieldRetractions.get(fieldName); - for( String n3 : retractions ){ - try{ - Model model = ModelFactory.createDefaultModel(); - StringReader reader = new StringReader(n3); - model.read(reader, "", "N3"); - requiredFieldRetractions.add(model); - }catch(Throwable t){ - String errMsg = "error processing N3 retraction string from field " + fieldName + "\n"+ - t.getMessage() + '\n' + - "n3: \n" + n3; - //errorMessages.add(errMsg); - log.error(errMsg); - } - } - } - return requiredFieldRetractions; - } - - private static List processN3Assertions( - EditConfigurationVTwo configuration, MultiValueEditSubmission submission, - NewURIMaker newURIMaker, - List n3Statements) { - - //deal with required N3, any that cannot - //be parsed are serious configuration errors - List errorMessages = new ArrayList(); - List n3Models = new ArrayList(); - for(String n3 : n3Statements){ - try{ - Model model = ModelFactory.createDefaultModel(); - StringReader reader = new StringReader(n3); - model.read(reader, "", "N3"); - n3Models.add( model ); - }catch(Throwable t){ - errorMessages.add( t.getMessage() + '\n' + - "Required N3: \n" + n3 ); - } - } - - if( !errorMessages.isEmpty() ){ - String msg = "Error processing required N3.\n"; - for( String em : errorMessages){ - msg += em + '\n'; - } - throw new Error(msg); - } - - return n3Models; - } - - private static void setVarToNewResource(EditConfigurationVTwo configuration, NewURIMaker newURIMaker) { -// if(varToNewResource == null) { -// varToNewResource = Utilities.newToUriMap(configuration.getNewResources(),newURIMaker); -// } - } - -//there are no retractions based on N3 since N3 is only employed when new literal or resource being processed - - //For both new and existing statement, need to incorporate varToNewResource - //Check whether data or not, to be consistent - //Map varToNewResource = newToUriMap - //TODO: Check if this still needs to differentiate between object and data property - private static Map> subNewResourceForField( - EditConfigurationVTwo configuration, NewURIMaker newURIMaker, - Map> fieldAssertions) { - - EditN3GeneratorVTwo n3Subber = configuration.getN3Generator(); - setVarToNewResource(configuration, newURIMaker); - //fieldAssertions = n3Subber.substituteIntoValues(varToNewResource, null, fieldAssertions ); - return fieldAssertions; - } - - //Substitue for uris and literals from both form and scope for field - private static Map> subUrisAndLiteralsForField( - EditConfigurationVTwo configuration, - MultiValueEditSubmission submission, - Map> fieldN3) { - EditN3GeneratorVTwo n3Subber = configuration.getN3Generator(); - //Substitute URIs and literals from form - fieldN3 = n3Subber.substituteIntoValues(submission.getUrisFromForm(), submission.getLiteralsFromForm(), fieldN3); - //Substitute URIS and literals from scope - fieldN3 = n3Subber.substituteIntoValues(configuration.getUrisInScope(), configuration.getLiteralsInScope(), fieldN3 ); - return fieldN3; - } - - //Substitute for uris and literals for n3 required or n3Optional - private static List subUrisAndLiteralsForN3( - EditConfigurationVTwo configuration, - MultiValueEditSubmission submission, - NewURIMaker newURIMaker, List n3Statements) { - EditN3GeneratorVTwo n3Subber = configuration.getN3Generator(); - - //Substitute URIs and literals from form - n3Statements = n3Subber.subInMultiUris(submission.getUrisFromForm(), n3Statements); - n3Statements = n3Subber.subInMultiLiterals(submission.getLiteralsFromForm(), n3Statements); - //Substitute URIS and literals in scope - n3Statements = n3Subber.subInMultiUris(configuration.getUrisInScope(), n3Statements); - n3Statements = n3Subber.subInMultiLiterals(configuration.getLiteralsInScope(), n3Statements); - //for new resource - setVarToNewResource(configuration, newURIMaker); - //n3Statements = n3Subber.subInMultiUris(varToNewResource, n3Statements); - return n3Statements; - } - - //substitute uris and literals and also handle new resource - private static Map> subUrisAndLiteralsInFieldAssertions( - EditConfigurationVTwo configuration, - MultiValueEditSubmission submission, - NewURIMaker newURIMaker, Map> fieldAssertions) { - //Substitute URIs and literals from form and from scope - //fieldAssertions = subUrisAndLiteralsForField(configuration, submission, newURIMaker, fieldAssertions); - fieldAssertions = subNewResourceForField(configuration, newURIMaker, fieldAssertions); - return fieldAssertions; - } - - //TODO: get rid of this as it does nothing new or interesting - private static Map> subUrisAndLiteralsInFieldRetractions( - EditConfigurationVTwo configuration, - MultiValueEditSubmission submission, - NewURIMaker newURIMaker, Map> fieldRetractions) { - return subUrisAndLiteralsForField(configuration, submission, fieldRetractions); - } - - private static Map getSubPedObjVarMap( + private void logSubstitueN3(String msg, List n3, String label){ + if( n3 == null) return; + String out = label + ":\n"; + for( String str : n3 ){ + out += " " + str + "\n"; + } + log.debug(out); + } + + private static Map getSubPedObjVarMap( EditConfigurationVTwo configuration) { Map varToValue = new HashMap(); @@ -670,7 +403,7 @@ public class ProcessRdfForm { return new AdditionsAndRetractions(assertions,retractions); } - private static void applyEditSubmissionPreprocessors( + private void applyEditSubmissionPreprocessors( EditConfigurationVTwo configuration, MultiValueEditSubmission submission) { List preprocessors = configuration.getEditSubmissionPreprocessors(); if(preprocessors != null) { @@ -680,13 +413,9 @@ public class ProcessRdfForm { } } - //this works differently based on whether this is object property editing or data property editing - //TODO: bdc34: Why would this work differently for data prop or obj prop? - //Object prop version below - //Also updating to allow an array to be returned with the uri instead of a single uri - //Note this would require more analysis in context of multiple uris possible for a field - public static Map URIsForNewRsources( + //Note this would require more analysis in context of multiple URIs + public Map URIsForNewRsources( EditConfigurationVTwo configuration, NewURIMaker newURIMaker) throws InsertException { Map newResources = configuration.getNewResources(); @@ -719,7 +448,30 @@ public class ProcessRdfForm { * stop the processing and throw an exception. */ REQUIRED }; - - static Random random = new Random(); + + private void substituteInMultiLiterals( + Map> literalsFromForm, + List ... n3StrLists) { + + for( List n3s : n3StrLists){ + populator.subInMultiLiterals(literalsFromForm, n3s); + } + } + + private void substituteInMultiURIs( + Map> multiUris, List ... n3StrLists) { + + for( List n3s : n3StrLists){ + populator.subInMultiUris(multiUris, n3s); + } + } + + private void substituteInURIs( + Map uris, List ... n3StrLists) { + for( List n3s : n3StrLists){ + populator.subInUris(uris, n3s); + } + } + private static Log log = LogFactory.getLog(ProcessRdfForm.class); -} +} \ No newline at end of file diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/SparqlEvaluateVTwo.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/SparqlEvaluateVTwo.java index 35f64a834..734f10c5c 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/SparqlEvaluateVTwo.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/SparqlEvaluateVTwo.java @@ -16,11 +16,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -/** - * User: bdc34 - * Date: Jan 22, 2008 - * Time: 5:55:57 PM - */ + public class SparqlEvaluateVTwo { private static Log log = LogFactory.getLog( SparqlEvaluateVTwo.class ); @@ -99,8 +95,8 @@ public class SparqlEvaluateVTwo { List queryStrings = new ArrayList (); queryStrings.add( query ); - queryStrings= editConfig.getN3Generator().subInMultiUris(uriScope, queryStrings); - queryStrings = editConfig.getN3Generator().subInMultiLiterals(literalScope,queryStrings); + editConfig.getN3Generator().subInMultiUris(uriScope, queryStrings); + editConfig.getN3Generator().subInMultiLiterals(literalScope,queryStrings); varToLiterals.put(var, queryToLiteral( queryStrings.get(0) )); //might result in (key -> null) } @@ -120,8 +116,8 @@ public class SparqlEvaluateVTwo { continue; List queryStrings = new ArrayList (); queryStrings.add(query); - queryStrings= editConfig.getN3Generator().subInMultiUris(uriScope, queryStrings); - queryStrings = editConfig.getN3Generator().subInMultiLiterals(literalScope,queryStrings); + editConfig.getN3Generator().subInMultiUris(uriScope, queryStrings); + editConfig.getN3Generator().subInMultiLiterals(literalScope,queryStrings); List uriFromQuery = queryToUri( queryStrings.get(0) ); if( uriFromQuery != null ) { diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddClinicalRoleToPersonGenerator.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddClinicalRoleToPersonGenerator.java deleted file mode 100644 index 1e886f355..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddClinicalRoleToPersonGenerator.java +++ /dev/null @@ -1,123 +0,0 @@ -/* $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/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddRoleToPersonTwoStageGenerator.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddRoleToPersonTwoStageGenerator.java deleted file mode 100644 index cfb784b4e..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddRoleToPersonTwoStageGenerator.java +++ /dev/null @@ -1,984 +0,0 @@ -/* $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.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.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") ); - //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) { - String query = "PREFIX core: <" + getVivoCoreNamespace() + ">" + - "SELECT ?existingActivity WHERE { ?role <" + getRoleToActivityPredicate(vreq) + "> ?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() + "> \n" + - "PREFIX rdfs: <" + RDFS.getURI() + "> \n" + - "SELECT ?existingTitle WHERE { \n" + - "?role <" + getRoleToActivityPredicate(vreq) + "> ?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 ); - } - } - - - - - /** - * 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); - //Put in the fact that we require field - editConfiguration.setFormSpecificData(formSpecificData); - } - -} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/BaseEditConfigurationGenerator.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/BaseEditConfigurationGenerator.java index dc19514d1..e13a9c40c 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/BaseEditConfigurationGenerator.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/BaseEditConfigurationGenerator.java @@ -14,99 +14,6 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfigu public abstract class BaseEditConfigurationGenerator implements EditConfigurationGenerator { -// @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.initPropertyParameters(vreq, session, editConfiguration); -// -// //Assumes this is a simple case of subject predicate var -// editConfiguration.setN3Required(generateN3Required(vreq)); -// -// //n3 optional -// editConfiguration.setN3Optional(generateN3Optional()); -// -// //Todo: what do new resources depend on here? -// //In original form, these variables start off empty -// editConfiguration.setNewResources(generateNewResources(vreq)); -// //In scope -// setUrisAndLiteralsInScope(editConfiguration, vreq); -// -// //on Form -// setUrisAndLiteralsOnForm(editConfiguration, vreq); -// -// editConfiguration.setFilesOnForm(new ArrayList()); -// -// //Sparql queries -// setSparqlQueries(editConfiguration, vreq); -// -// //set fields -// setFields(editConfiguration, vreq, EditConfigurationUtils.getPredicateUri(vreq)); -// -// 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 -// setValidators(editConfiguration, vreq); -// -// //Add preprocessors -// addPreprocessors(editConfiguration, vreq.getWebappDaoFactory()); -// -// //Adding additional data, specifically edit mode -// addFormSpecificData(editConfiguration, vreq); -// -// return editConfiguration; -// -//} -// -// abstract void setValidators(EditConfigurationVTwo editConfiguration, VitroRequest vreq) ; -// -// abstract void addFormSpecificData(EditConfigurationVTwo editConfiguration, -// VitroRequest vreq) ; -// -// abstract void addPreprocessors(EditConfigurationVTwo editConfiguration, -// WebappDaoFactory webappDaoFactory) ; -// -// abstract void setEditKey(EditConfigurationVTwo editConfiguration, -// VitroRequest vreq) ; -// -// abstract void setTemplate(EditConfigurationVTwo editConfiguration, -// VitroRequest vreq) ; -// -// abstract void prepareForUpdate(VitroRequest vreq, HttpSession session, -// EditConfigurationVTwo editConfiguration) ; -// -// abstract void setFields(EditConfigurationVTwo editConfiguration, -// VitroRequest vreq, String predicateUri) ; -// -// abstract void setSparqlQueries(EditConfigurationVTwo editConfiguration, -// VitroRequest vreq) ; -// -// abstract void setUrisAndLiteralsOnForm( -// EditConfigurationVTwo editConfiguration, VitroRequest vreq) ; -// -// abstract void setUrisAndLiteralsInScope( -// EditConfigurationVTwo editConfiguration, VitroRequest vreq) ; -// -// abstract Map generateNewResources(VitroRequest vreq) ; -// -// abstract List generateN3Optional() ; -// -// abstract List generateN3Required(VitroRequest vreq) ; - /* constants */ public static final String DEFAULT_NS_FOR_NEW_RESOURCE= ""; @@ -115,13 +22,11 @@ public abstract class BaseEditConfigurationGenerator implements EditConfiguratio /** * Sets up the things that should be done for just about every form. */ - void initBasics(EditConfigurationVTwo editConf, VitroRequest vreq){ - editConf.setN3Generator( new EditN3GeneratorVTwo(editConf) ); - + void initBasics(EditConfigurationVTwo editConf, VitroRequest vreq){ String editKey = EditConfigurationUtils.getEditKey(vreq); editConf.setEditKey(editKey); - String formUrl = EditConfigurationUtils.getFormUrl(vreq); + String formUrl = EditConfigurationUtils.getFormUrl(vreq); editConf.setFormUrl(formUrl); } @@ -142,14 +47,7 @@ public abstract class BaseEditConfigurationGenerator implements EditConfiguratio } void initObjectPropForm(EditConfigurationVTwo editConfiguration,VitroRequest vreq) { - editConfiguration.setObject( EditConfigurationUtils.getObjectUri(vreq) ); - - //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(editConfiguration.getObject() != null ) { - editConfiguration.setObjectResource(true); - } + editConfiguration.setObject( EditConfigurationUtils.getObjectUri(vreq) ); } } diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultAddMissingIndividualFormGenerator.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultAddMissingIndividualFormGenerator.java index cc45ec86b..27578c7b4 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultAddMissingIndividualFormGenerator.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultAddMissingIndividualFormGenerator.java @@ -79,8 +79,6 @@ public class DefaultAddMissingIndividualFormGenerator implements EditConfigurati @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); @@ -199,10 +197,7 @@ public class DefaultAddMissingIndividualFormGenerator implements EditConfigurati } //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); - } + //TODO: Check if null in case no object uri exists but this is still an object property } @@ -358,8 +353,7 @@ public class DefaultAddMissingIndividualFormGenerator implements EditConfigurati EditConfigurationVTwo editConfiguration, VitroRequest vreq) { Map fields = new HashMap(); FieldVTwo field = new FieldVTwo(); - field.setName("name"); - field.setNewResource(false); + field.setName("name"); //queryForExisting is not being used anywhere in Field List validators = new ArrayList(); @@ -379,8 +373,7 @@ public class DefaultAddMissingIndividualFormGenerator implements EditConfigurati field.setLiteralOptions(new ArrayList>()); List assertions = new ArrayList(); - assertions.add(getN3ForName()); - field.setAssertions(assertions); + assertions.add(getN3ForName()); fields.put(field.getName(), field); return fields; diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultDataPropertyFormGenerator.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultDataPropertyFormGenerator.java index bbb2453a8..4256f29cd 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultDataPropertyFormGenerator.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultDataPropertyFormGenerator.java @@ -3,6 +3,7 @@ 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; @@ -16,6 +17,7 @@ import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement; import edu.cornell.mannlib.vitro.webapp.beans.Individual; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo; +import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.DefaultDataPropEmptyField; import edu.cornell.mannlib.vitro.webapp.web.MiscWebUtils; public class DefaultDataPropertyFormGenerator implements EditConfigurationGenerator { @@ -119,12 +121,10 @@ public class DefaultDataPropertyFormGenerator implements EditConfigurationGenera editConfiguration.setVarNameForPredicate("predicate"); editConfiguration.setPredicateUri(predicateUriJson); - - - + //deal with empty field + editConfiguration.addModelChangePreprocessor( new DefaultDataPropEmptyField() ); - - return null; + return editConfiguration; } private EditConfigurationVTwo doHelp(VitroRequest vreq, String string) { diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultDeleteGenerator.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultDeleteGenerator.java index 6f4bbb2a7..0b72b901a 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultDeleteGenerator.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultDeleteGenerator.java @@ -131,13 +131,9 @@ public class DefaultDeleteGenerator implements EditConfigurationGenerator { //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); //original set datapropValue, which in this case would be empty string but no way here diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultObjectPropertyFormGenerator.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultObjectPropertyFormGenerator.java index d89683657..2745252e6 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultObjectPropertyFormGenerator.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultObjectPropertyFormGenerator.java @@ -2,8 +2,8 @@ package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators; -import java.util.Arrays; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -13,29 +13,19 @@ 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.ontology.OntModel; import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.Model; -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.WebappDaoFactory; +import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo; -import edu.cornell.mannlib.vitro.webapp.edit.n3editing.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; /** @@ -43,7 +33,8 @@ import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch; * */ public class DefaultObjectPropertyFormGenerator implements EditConfigurationGenerator { - + + //TODO: bdc34 why does the DefaultObjectPropertyForm have all this data property stuff? private Log log = LogFactory.getLog(DefaultObjectPropertyFormGenerator.class); private boolean isObjectPropForm = false; private String subjectUri = null; @@ -76,9 +67,7 @@ public class DefaultObjectPropertyFormGenerator implements EditConfigurationGene } private EditConfigurationVTwo getDefaultObjectEditConfiguration(VitroRequest vreq, HttpSession session) { - EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo(); - //Set n3 generator - editConfiguration.setN3Generator(new EditN3GeneratorVTwo(editConfiguration)); + EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo(); //process subject, predicate, object parameters this.initProcessParameters(vreq, session, editConfiguration); @@ -204,19 +193,11 @@ public class DefaultObjectPropertyFormGenerator implements EditConfigurationGene //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"); + //bdc34 + throw new Error("DefaultObjectPropertyForm should not be doing data property editng"); } //Get N3 required @@ -338,7 +319,6 @@ public class DefaultObjectPropertyFormGenerator implements EditConfigurationGene Map fields = new HashMap(); FieldVTwo field = new FieldVTwo(); field.setName(dataLiteral); - field.setNewResource(false); //queryForExisting is not being used anywhere in Field String rangeDatatypeUri = getRangeDatatypeUri(editConfiguration, vreq); String rangeLang = getRangeLang(editConfiguration, vreq); @@ -360,12 +340,7 @@ public class DefaultObjectPropertyFormGenerator implements EditConfigurationGene } field.setLiteralOptions(getLiteralOptions(editConfiguration, vreq)); - //set assertions - List assertions = new ArrayList(); - assertions.addAll(editConfiguration.getN3Required()); - field.setAssertions(assertions); - fields.put(field.getName(), field); - + fields.put(field.getName(), field); return fields; } @@ -436,8 +411,7 @@ public class DefaultObjectPropertyFormGenerator implements EditConfigurationGene EditConfigurationVTwo editConfiguration, VitroRequest vreq) { Map fields = new HashMap(); FieldVTwo field = new FieldVTwo(); - field.setName("objectVar"); - field.setNewResource(false); + field.setName("objectVar"); //queryForExisting is not being used anywhere in Field List validators = new ArrayList(); @@ -454,11 +428,7 @@ public class DefaultObjectPropertyFormGenerator implements EditConfigurationGene field.setRangeLang(null); field.setLiteralOptions(new ArrayList>()); - - List assertions = new ArrayList(); - assertions.addAll(editConfiguration.getN3Required()); - assertions.addAll(editConfiguration.getN3Optional()); - field.setAssertions(assertions); + fields.put(field.getName(), field); return fields; @@ -480,6 +450,7 @@ public class DefaultObjectPropertyFormGenerator implements EditConfigurationGene editConfiguration.prepareForNonUpdate( model ); } } else { + //TODO: why is this checking for data prop keys? if(datapropKeyStr != null && datapropKeyStr.trim().length() > 0 ) { DataPropertyStatement dps = EditConfigurationUtils.getDataPropertyStatement(vreq, session, @@ -490,13 +461,7 @@ public class DefaultObjectPropertyFormGenerator implements EditConfigurationGene } } } - - //Command processing - private boolean isTypeOfNew(VitroRequest vreq) { - String typeOfNew = vreq.getParameter("typeOfNew"); - return (typeOfNew != null && !typeOfNew.isEmpty()); - } - + private boolean isSelectFromExisting(VitroRequest vreq) { String predicateUri = EditConfigurationUtils.getPredicateUri(vreq); if(EditConfigurationUtils.isDataProperty(predicateUri, vreq)) { diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/MenuEditingFormGenerator.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/MenuEditingFormGenerator.java index 0512c0f27..8b2189638 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/MenuEditingFormGenerator.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/MenuEditingFormGenerator.java @@ -171,9 +171,7 @@ public class MenuEditingFormGenerator implements EditConfigurationGenerator { private void processObjectPropForm(VitroRequest vreq, EditConfigurationVTwo editConfiguration) { editConfiguration.setVarNameForObject("objectVar"); - editConfiguration.setObject(objectUri); - //For page - editConfiguration.setObjectResource(true); + editConfiguration.setObject(objectUri); } private void processDataPropForm(VitroRequest vreq, EditConfigurationVTwo editConfiguration) { @@ -369,15 +367,13 @@ public class MenuEditingFormGenerator implements EditConfigurationGenerator { //Field should be for page title and other associations (assuming this is what actually goes on the form) FieldVTwo field = new FieldVTwo(); field.setName("title"); - field.setNewResource(false); + List validators = new ArrayList(); validators.add("nonempty"); field.setValidators(validators); field.setOptionsType("LITERALS"); field.setPredicateUri(DisplayVocabulary.DISPLAY_NS + "title"); - List assertions = this.generateN3Required(vreq); - assertions.addAll(this.generateN3Optional()); - field.setAssertions(assertions); + fields.put("title", field); //Object Var Field //Won't need this in our case diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/NewIndividualFormGenerator.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/NewIndividualFormGenerator.java index 9e65c1764..6d0e3c999 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/NewIndividualFormGenerator.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/NewIndividualFormGenerator.java @@ -47,28 +47,23 @@ import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch; */ 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); @@ -154,7 +149,6 @@ public class NewIndividualFormGenerator implements EditConfigurationGenerator { 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); } @@ -171,21 +165,8 @@ public class NewIndividualFormGenerator implements EditConfigurationGenerator { //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) { @@ -202,15 +183,7 @@ public class NewIndividualFormGenerator implements EditConfigurationGenerator { 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 @@ -235,12 +208,7 @@ public class NewIndividualFormGenerator implements EditConfigurationGenerator { 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) { @@ -276,8 +244,7 @@ public class NewIndividualFormGenerator implements EditConfigurationGenerator { private void getLabelField(EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map fields) { FieldVTwo field = new FieldVTwo(); - field.setName("label"); - field.setNewResource(false); + field.setName("label"); //queryForExisting is not being used anywhere in Field String stringDatatypeUri = XSD.xstring.toString(); @@ -296,11 +263,7 @@ public class NewIndividualFormGenerator implements EditConfigurationGenerator { field.setLiteralOptions(new ArrayList>()); - //set assertions - List assertions = new ArrayList(); - field.setAssertions(assertions); - fields.put(field.getName(), field); - + fields.put(field.getName(), field); } diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/RDFSLabelGenerator.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/RDFSLabelGenerator.java index a81aa4ec0..77050bf41 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/RDFSLabelGenerator.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/RDFSLabelGenerator.java @@ -75,8 +75,6 @@ public class RDFSLabelGenerator implements EditConfigurationGenerator { private EditConfigurationVTwo setupEditConfiguration(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); @@ -164,10 +162,10 @@ public class RDFSLabelGenerator implements EditConfigurationGenerator { 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(literalName); + //original set datapropValue, which in this case would be empty string but no way here editConfiguration.setDatapropValue(""); editConfiguration.setUrlPatternToReturnTo("/entity"); @@ -249,7 +247,6 @@ public class RDFSLabelGenerator implements EditConfigurationGenerator { Map fields = new HashMap(); FieldVTwo field = new FieldVTwo(); field.setName(literalName); - field.setNewResource(false); //queryForExisting is not being used anywhere in Field String rangeDatatypeUri = getRangeDatatypeUri(editConfiguration, vreq); String rangeLang = getRangeLang(editConfiguration, vreq); @@ -270,11 +267,7 @@ public class RDFSLabelGenerator implements EditConfigurationGenerator { field.setRangeLang(rangeLang); } field.setLiteralOptions(getLiteralOptions(editConfiguration, vreq)); - - //set assertions - List assertions = new ArrayList(); - assertions.addAll(editConfiguration.getN3Required()); - field.setAssertions(assertions); + fields.put(field.getName(), field); return fields; } diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/DefaultDataPropEmptyField.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/DefaultDataPropEmptyField.java new file mode 100644 index 000000000..d969036d6 --- /dev/null +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/DefaultDataPropEmptyField.java @@ -0,0 +1,69 @@ +/* $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.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import com.hp.hpl.jena.rdf.model.Literal; +import com.hp.hpl.jena.rdf.model.Model; + +import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; +import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils; +import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo; +import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditSubmissionUtils; +import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmission; +import edu.cornell.mannlib.vitro.webapp.edit.n3editing.controller.ProcessRdfFormController.Utilities; + +/** + * Editors have gotten into the habit of clearing the text from the + * textarea and saving it to invoke a delete. see Issue VITRO-432 + * + */ +public class DefaultDataPropEmptyField implements ModelChangePreprocessor{ + + @Override + public void preprocess(Model retractionsModel, Model additionsModel, + HttpServletRequest request) { + + EditConfigurationVTwo configuration = EditConfigurationUtils.getEditConfiguration(request); + + HttpSession session = request.getSession(); + MultiValueEditSubmission submission = EditSubmissionUtils.getEditSubmissionFromSession(session,configuration); + + //if data property, then check for empty string condition + //which means only one value and it is an empty string + if( checkForEmptyString(submission, configuration, new VitroRequest(request)) ) { + additionsModel.removeAll(); + } + } + + + protected boolean checkForEmptyString( + MultiValueEditSubmission submission, + EditConfigurationVTwo configuration, + VitroRequest vreq) { + + if(EditConfigurationUtils.isDataProperty(configuration.getPredicateUri(), vreq)) { + // Our editors have gotten into the habit of clearing the text from the + // textarea and saving it to invoke a delete. see Issue VITRO-432 + if (configuration.getFields().size() == 1) { + String onlyField = configuration.getFields().keySet().iterator() + .next(); + List value = submission.getLiteralsFromForm().get(onlyField); + if( value == null || value.size() == 0){ + return true; + }else { + if(value.size() == 1) { + if( "".equals(value.get(0).getLexicalForm())) { + return true; + } + } + } + } + } + return false; + } + +} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/controller/EditRequestDispatchController.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/controller/EditRequestDispatchController.java index 395406a12..52b3e06b5 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/controller/EditRequestDispatchController.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/controller/EditRequestDispatchController.java @@ -13,6 +13,8 @@ import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import com.hp.hpl.jena.rdf.model.Model; + import edu.cornell.mannlib.vitro.webapp.beans.Individual; import edu.cornell.mannlib.vitro.webapp.beans.Property; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; @@ -77,6 +79,7 @@ public class EditRequestDispatchController extends FreemarkerHttpServlet { /**** make new or get an existing edit configuration ***/ EditConfigurationVTwo editConfig = setupEditConfiguration(editConfGeneratorName, vreq); + //what template? String template = editConfig.getTemplate(); @@ -124,6 +127,19 @@ public class EditRequestDispatchController extends FreemarkerHttpServlet { //put edit configuration in session EditConfigurationVTwo.putConfigInSession(editConfig, session); + + Model model = (Model) getServletContext().getAttribute("jenaOntModel"); + String objectUri = EditConfigurationUtils.getObjectUri(vreq); + String dataKey = EditConfigurationUtils.getDataPropKey(vreq); + if (objectUri != null) { // editing existing object + editConfig.prepareForObjPropUpdate(model); + } else if( dataKey != null ) { // edit of a data prop + //do nothing since the data prop form generator must take care of it + } else{ + //this might be a create new or a form + editConfig.prepareForNonUpdate(model); + } + return editConfig; } diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/controller/ProcessRdfFormController.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/controller/ProcessRdfFormController.java index c79d2063c..6153580b2 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/controller/ProcessRdfFormController.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/controller/ProcessRdfFormController.java @@ -56,7 +56,7 @@ public class ProcessRdfFormController extends FreemarkerHttpServlet{ @Override protected ResponseValues processRequest(VitroRequest vreq) { //get the EditConfiguration - EditConfigurationVTwo configuration = getEditConfiguration(vreq); + EditConfigurationVTwo configuration = EditConfigurationUtils.getEditConfiguration(vreq); if(configuration == null) throw new Error("No edit configuration found."); @@ -84,7 +84,11 @@ public class ProcessRdfFormController extends FreemarkerHttpServlet{ AdditionsAndRetractions changes; try { - changes = getAdditionsAndRetractions(configuration, submission, vreq); + + ProcessRdfForm prf = + new ProcessRdfForm(configuration, new NewURIMakerVitro(vreq.getWebappDaoFactory())); + changes = prf.process(configuration, submission); + } catch (Exception e) { throw new Error(e); } @@ -92,7 +96,7 @@ public class ProcessRdfFormController extends FreemarkerHttpServlet{ if( configuration.isUseDependentResourceDelete() ) changes = ProcessRdfForm.addDependentDeletes(changes, queryModel); - N3EditUtils.preprocessModels(changes, configuration, vreq); + N3EditUtils.preprocessModels(changes, configuration, vreq); ProcessRdfForm.applyChangesToWriteModel(changes, queryModel, writeModel, EditN3Utils.getEditorUri(vreq) ); @@ -101,13 +105,12 @@ public class ProcessRdfFormController extends FreemarkerHttpServlet{ //Also what do we actually DO with the vreq attribute: Answer: Use it for redirection //And no where else so we could technically calculate and send that here String entityToReturnTo = N3EditUtils.processEntityToReturnTo(configuration, submission, vreq); + //For data property processing, need to update edit configuration for back button N3EditUtils.updateEditConfigurationForBackButton(configuration, submission, vreq, writeModel); return PostEditCleanupController.doPostEdit(vreq, entityToReturnTo); } - - //In case of back button confusion //Currently returning an error message: //Later TODO: Per Brian Caruso's instructions, replicate @@ -153,35 +156,6 @@ public class ProcessRdfFormController extends FreemarkerHttpServlet{ } - - private AdditionsAndRetractions getAdditionsAndRetractions( - EditConfigurationVTwo configuration, - MultiValueEditSubmission submission, VitroRequest vreq) throws Exception { - - return ProcessRdfForm.process(configuration, submission, - new NewURIMakerVitro(vreq.getWebappDaoFactory())); - - } - - - private EditConfigurationVTwo getEditConfiguration(HttpServletRequest request) { - HttpSession session = request.getSession(); - EditConfigurationVTwo editConfiguration = EditConfigurationVTwo.getConfigFromSession(session, request); - return editConfiguration; - } - - -// private ResponseValues doEditConfigNotFound(VitroRequest request) { -// HashMapmap = new HashMap(); -// map.put("message", "No editing configuration found, cannot process edit."); -// ResponseValues values = new TemplateResponseValues("message.ftl", map); -// try { -// doResponse(request,values); -// } catch (TemplateProcessingException e) { -// log.error("Could not process template for doEditConfigNotFound()",e); -// } -// } - private ResponseValues doValidationErrors(VitroRequest vreq, EditConfigurationVTwo editConfiguration, MultiValueEditSubmission submission) { @@ -196,7 +170,6 @@ public class ProcessRdfFormController extends FreemarkerHttpServlet{ } return null; //no errors } - //Move to EditN3Utils but keep make new uris here public static class Utilities { @@ -222,33 +195,6 @@ public class ProcessRdfFormController extends FreemarkerHttpServlet{ } return copyOfN3; } - - public static List getFieldStmts(FieldVTwo field, String stmtType) { - if(stmtType.equals(assertionsType)) { - return field.getAssertions(); - } else { - return field.getRetractions(); - } - } - - public static Map> fieldsToN3Map(Map fields, String stmtType) { - Map> out = new HashMap>(); - for( String fieldName : fields.keySet()){ - FieldVTwo field = fields.get(fieldName); - List n3Stmts = getFieldStmts(field, stmtType); - List copyOfN3 = makeListCopy(n3Stmts); - out.put( fieldName, copyOfN3 ); - } - return out; - } - - public static Map> fieldsToAssertionMap( Map fields){ - return fieldsToN3Map(fields, assertionsType); - } - - public static Map> fieldsToRetractionMap( Map fields){ - return fieldsToN3Map(fields, retractionsType); - } //TODO: Check if this would be correct with multiple values and uris being passed back //First, need to order by uris in original and new values probably and @@ -299,35 +245,7 @@ public class ProcessRdfFormController extends FreemarkerHttpServlet{ + (fieldChanged ? "did Change" : "did NOT change")); return fieldChanged; } - - - public static boolean checkForEmptyString( - MultiValueEditSubmission submission, - EditConfigurationVTwo configuration, VitroRequest vreq) { - // TODO Auto-generated method stub - if(isDataProperty(configuration, vreq)) { - // Our editors have gotten into the habbit of clearing the text from the - // textarea and saving it to invoke a delete. see Issue VITRO-432 - if (configuration.getFields().size() == 1) { - String onlyField = configuration.getFields().keySet().iterator() - .next(); - List value = submission.getLiteralsFromForm().get(onlyField); - if( value == null || value.size() == 0){ - log.debug("No parameters found in submission for field \"" + onlyField +"\""); - return true; - }else { - if(value.size() == 1) { - if( "".equals(value.get(0).getLexicalForm())) { - log.debug("Submission was a single field named \"" + onlyField + "\" with an empty string"); - return true; - } - } - } - } - } - return false; - } - + //Get predicate local anchor public static String getPredicateLocalName(EditConfigurationVTwo editConfig) { String predicateLocalName = null; diff --git a/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditN3GeneratorVTwoTest.java b/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditN3GeneratorVTwoTest.java index e4447133c..bbcff2bc1 100644 --- a/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditN3GeneratorVTwoTest.java +++ b/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditN3GeneratorVTwoTest.java @@ -4,6 +4,7 @@ package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo; import java.io.StringReader; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -16,8 +17,27 @@ import com.hp.hpl.jena.rdf.model.ModelFactory; public class EditN3GeneratorVTwoTest { + static EditN3GeneratorVTwo gen = new EditN3GeneratorVTwo(); + + @Test + public void testPunctAfterVarName(){ + List targets = Arrays.asList("?var.","?var;","?var]","?var,"); + + Map> keyToValues = new HashMap>(); + keyToValues.put("var", Arrays.asList("ABC")); + + gen.subInMultiUris(keyToValues, targets); + Assert.assertNotNull(targets); + Assert.assertEquals(4,targets.size()); + + Assert.assertEquals(".", targets.get(0)); + Assert.assertEquals(";", targets.get(1)); + Assert.assertEquals("]", targets.get(2)); + Assert.assertEquals(",", targets.get(3)); + } + @Test - public void testSubInMultiUrisNull(){ + public void testSubInMultiUrisNull(){ String n3 = "?varXYZ" ; List targets = new ArrayList(); targets.add(n3); @@ -27,11 +47,11 @@ public class EditN3GeneratorVTwoTest { targetValue.add(null); keyToValues.put("varXYZ", targetValue); - List result = EditN3GeneratorVTwo.subInMultiUris(keyToValues, targets); - Assert.assertNotNull(result); - Assert.assertEquals(1,result.size()); + gen.subInMultiUris(keyToValues, targets); + Assert.assertNotNull(targets); + Assert.assertEquals(1,targets.size()); - String resultN3 = result.get(0); + String resultN3 = targets.get(0); Assert.assertNotNull(resultN3); Assert.assertTrue("String was empty", !resultN3.isEmpty()); @@ -49,7 +69,8 @@ public class EditN3GeneratorVTwoTest { Map keyToValues = new HashMap(); keyToValues.put("varXYZ", "xyzURI"); - List result = EditN3GeneratorVTwo.subInUris(keyToValues, targets); + gen.subInUris(keyToValues, targets); + List result = targets; Assert.assertNotNull(result); Assert.assertEquals(1,result.size()); @@ -60,13 +81,15 @@ public class EditN3GeneratorVTwoTest { keyToValues = new HashMap(); keyToValues.put("varXYZ", null); + + List targets2 = new ArrayList(); + targets2.add(n3); - result = EditN3GeneratorVTwo.subInUris(keyToValues, targets); - Assert.assertNotNull(result); - Assert.assertEquals(1,result.size()); + gen.subInUris(keyToValues, targets2); + Assert.assertNotNull(targets2); + Assert.assertEquals(1,targets2.size()); - resultN3 = result.get(0); - resultN3 = result.get(0); + resultN3 = targets2.get(0); Assert.assertNotNull(resultN3); Assert.assertTrue("String was empty", !resultN3.isEmpty()); Assert.assertEquals(" ?varXYZ ", resultN3); @@ -109,19 +132,19 @@ core:educationalTrainingOf ?person ; keyToValues.put("subject", subject); keyToValues.put("predicate", predicate); - List n3results = EditN3GeneratorVTwo.subInMultiUris(keyToValues, strs); + gen.subInMultiUris(keyToValues, strs); - Assert.assertNotNull(n3results); - Assert.assertTrue( n3results.size() == 1 ); + Assert.assertNotNull(strs); + Assert.assertTrue( strs.size() == 1 ); String expected =" , , ."; - Assert.assertEquals(expected, n3results.get(0)); + Assert.assertEquals(expected, strs.get(0)); //Replace subject and predicate with other variables //make a model, Model expectedModel = ModelFactory.createDefaultModel(); StringReader expectedReader = new StringReader(expected); - StringReader resultReader = new StringReader(n3results.get(0)); + StringReader resultReader = new StringReader(strs.get(0)); expectedModel.read(expectedReader, null, "N3"); Model resultModel = ModelFactory.createDefaultModel(); resultModel.read(resultReader, null, "N3"); diff --git a/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/ProcessRdfFormTest.java b/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/ProcessRdfFormTest.java new file mode 100644 index 000000000..22fb7f899 --- /dev/null +++ b/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/ProcessRdfFormTest.java @@ -0,0 +1,166 @@ +/* $This file is distributed under the terms of the license in /doc/license.txt$ */ +package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.*; +import org.junit.Test; + +import com.hp.hpl.jena.rdf.model.Model; +import com.hp.hpl.jena.rdf.model.ModelFactory; +import com.hp.hpl.jena.rdf.model.ResourceFactory; + +import edu.cornell.mannlib.vitro.testing.AbstractTestClass; +import edu.cornell.mannlib.vitro.webapp.dao.InsertException; + +public class ProcessRdfFormTest extends AbstractTestClass{ + + + @Test + public void basicNewStatementTest() throws Exception{ + + /* A very basic new statement edit. */ + EditConfigurationVTwo config = new EditConfigurationVTwo(); + config.setEditKey("mockEditKey"); + config.setN3Required(Arrays.asList("?test1 ?test2 ?test3 ." )); + config.setUrisOnform(Arrays.asList("test1", "test2", "test3")); + + Map values = new HashMap(); + values.put("test1", (new String[] {"http://test.com/uri1"})); + values.put("test2", (new String[] {"http://test.com/uri2"})); + values.put("test3", (new String[] {"http://test.com/uri3"})); + values.put("editKey", (new String[] {"mockEditKey"})); + + MultiValueEditSubmission submission = new MultiValueEditSubmission(values, config); + + ProcessRdfForm processor = new ProcessRdfForm(config,getMockNewURIMaker()); + + /* test just the N3 substitution part */ + Listreq = config.getN3Required(); + Listopt = config.getN3Optional(); + processor.subInValuesToN3( config , submission, req, opt, null , null); + assertNotNull(req); + assertTrue( req.size() > 0); + assertNotNull(req.get(0)); + assertEquals(" .", req.get(0)); + /* test the N3 and parse RDF parts */ + AdditionsAndRetractions changes = processor.process( config, submission ); + + assertNotNull( changes ); + assertNotNull( changes.getAdditions() ); + assertNotNull( changes.getRetractions()); + assertTrue( changes.getAdditions().size() == 1 ); + assertTrue( changes.getRetractions().size() == 0 ); + + assertTrue( changes.getAdditions().contains( + ResourceFactory.createResource("http://test.com/uri1"), + ResourceFactory.createProperty("http://test.com/uri2"), + ResourceFactory.createResource("http://test.com/uri3"))); + } + + /* A very basic edit of an existing statement. */ + @Test + public void basicEditStatement() throws Exception{ + String testXURI = "http://test.com/uriX"; + String testYURI = "http://test.com/uriY"; + String testZURIOrginal = "http://test.com/uriZ"; + String testZURIChanged = "http://test.com/uriZChanged"; + + /* set up model */ + Model model = ModelFactory.createDefaultModel(); + model.add(model.createResource(testXURI), + model.createProperty(testYURI), + model.createResource(testZURIOrginal)); + + /* set up EditConfiguration */ + EditConfigurationVTwo config = new EditConfigurationVTwo(); + config.setEditKey("mockEditKey"); + config.setUrisOnform(Arrays.asList("testX", "testY", "testZ")); + config.setN3Required( Arrays.asList("?testX ?testY ?testZ ." )); + + config.setVarNameForSubject("testX"); + config.setSubjectUri(testXURI); + + config.setPredicateUri(testYURI); + config.setVarNameForPredicate("testY"); + + config.setObject(testZURIOrginal); + config.setVarNameForObject("testZ"); + + config.prepareForObjPropUpdate(model); + + /* set up Submission */ + Map values = new HashMap(); + values.put("testZ", (new String[] {testZURIChanged})); + values.put("editKey", (new String[] {"mockEditKey"})); + MultiValueEditSubmission submission = new MultiValueEditSubmission(values, config); + + ProcessRdfForm processor = new ProcessRdfForm(config,getMockNewURIMaker()); + AdditionsAndRetractions changes = processor.process( config, submission ); + + assertNotNull( changes ); + assertNotNull( changes.getAdditions() ); + assertNotNull( changes.getRetractions()); + + assertTrue( changes.getAdditions().size() == 1 ); + assertTrue( changes.getRetractions().size() == 1 ); + + assertTrue( changes.getAdditions().contains( + ResourceFactory.createResource(testXURI), + ResourceFactory.createProperty(testYURI), + ResourceFactory.createResource(testZURIChanged))); + + assertTrue( changes.getRetractions().contains( + ResourceFactory.createResource(testXURI), + ResourceFactory.createProperty(testYURI), + ResourceFactory.createResource(testZURIOrginal))); + } + + @Test + public void substituteInSubPredObjURIsTest(){ + String testXURI = "http://test.com/uriX"; + String testYURI = "http://test.com/uriY"; + String testZURI = "http://test.com/uriZ"; + + /* set up EditConfiguration */ + EditConfigurationVTwo config = new EditConfigurationVTwo(); + + config.setVarNameForSubject("testX"); + config.setSubjectUri(testXURI); + + config.setPredicateUri(testYURI); + config.setVarNameForPredicate("testY"); + + config.setObject(testZURI); + config.setVarNameForObject("testZ"); + + List a = Arrays.asList("a.0 ?testX ?testY ?testZ.", "a.1 ?testX ?testY ?testZ."); + List b = Arrays.asList("b.0 ?testX ?testY ?testZ.", "b.1 ?testX ?testY ?testZ."); + + ProcessRdfForm processor = new ProcessRdfForm(config,getMockNewURIMaker()); + + processor.substituteInSubPredObjURIs(config, a, b); + assertEquals("a.0 <" + testXURI + "> <" + testYURI + "> <" + testZURI + ">.", a.get(0)); + assertEquals("a.1 <" + testXURI + "> <" + testYURI + "> <" + testZURI + ">.", a.get(1)); + assertEquals("b.0 <" + testXURI + "> <" + testYURI + "> <" + testZURI + ">.", b.get(0)); + assertEquals("b.1 <" + testXURI + "> <" + testYURI + "> <" + testZURI + ">.", b.get(1)); + + } + + + public NewURIMaker getMockNewURIMaker(){ + return new NewURIMaker() { + int count = 0; + @Override + public String getUnusedNewURI(String prefixURI) throws InsertException { + if( prefixURI != null ) + return prefixURI + count; + else + return "http://newURI/n" + count; + } + }; + } +}