Removing old N3 editing code. NIHVIVO-3807

This commit is contained in:
briancaruso 2012-06-21 21:57:45 +00:00
parent f6b2387a3e
commit 56d23c8e2c
42 changed files with 85 additions and 6172 deletions

View file

@ -2,36 +2,33 @@
package edu.cornell.mannlib.vitro.webapp.controller;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
import edu.cornell.mannlib.vitro.webapp.beans.PropertyInstance;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.PropertyGroup;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.PropertyInstanceDao;
import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.PropertyGroupDao;
import edu.cornell.mannlib.vitro.webapp.web.jsptags.InputElementFormattingTag;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.HashSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
import edu.cornell.mannlib.vitro.webapp.beans.PropertyGroup;
import edu.cornell.mannlib.vitro.webapp.beans.PropertyInstance;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.PropertyGroupDao;
import edu.cornell.mannlib.vitro.webapp.dao.PropertyInstanceDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
/**
* Handles requests for entity information.

View file

@ -1,562 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.edit;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.shared.Lock;
import edu.cornell.mannlib.vedit.beans.LoginStatusBean;
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties;
import edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet;
import edu.cornell.mannlib.vitro.webapp.dao.jena.event.EditEvent;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditN3Generator;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditN3Utils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
import edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.FileUploadServletRequest;
import edu.cornell.mannlib.vitro.webapp.utils.MailUtil;
/**
* Process a N3 form submission with a multipart data encoding. This follows a
* similar sort of processing as a N3 form update where each submitted file is
* processed using the configuration information from a Field.
*
* For each file uploaded the assertions of the Field associated with the file
* will be processed. These additional values will be defined:
*
* ?fileURI = the URI of the newly uploaded file. ?fileName = original name of
* the uploaded file. ?fileSaveLocation = location on file system the file was
* saved to. ?fileSavedName = name that was used to save the file, this may be
* different than the fileName if there is an existing file with a conflicting
* name. ?fileContentType = MIME type reported by client browser. ?fileSize =
* file size reported by ServletFileUpload parser.
*
* How to do optional n3: For a Field, each N3 assertion string is optional. N3
* Strings that are incomplete after the substitution process will ignored as
* optional.
*/
public class N3MultiPartUpload extends VitroHttpServlet {
private static final int DEFAULT_MAX_SIZE = 1024 * 1024 * 1024;
private static final String DEFAULT_FILE_URI_PREFIX = "http://vivo.library.cornell.edu/ns/0.1#file";
private static final String DEFAULT_BASE_DIR = "/usr/local/vitrofiles";
private static String fileUriPrefix = DEFAULT_FILE_URI_PREFIX;
private static String baseDirectoryForFiles = DEFAULT_BASE_DIR;
private static int maxFileSize = DEFAULT_MAX_SIZE;
private static PostUpload postUpload = null;
/**
* Check to see if there is a postFileUpload object configured in the file
* /WEB-INF/postFileUpload.jsp"
*/
@Override
public void init() throws ServletException {
ConfigurationProperties configProperties = ConfigurationProperties
.getBean(getServletContext());
fileUriPrefix = configProperties.getProperty("n3.defaultUriPrefix",
DEFAULT_FILE_URI_PREFIX);
baseDirectoryForFiles = configProperties.getProperty(
"n3.baseDirectoryForFiles", DEFAULT_BASE_DIR);
String postUploadProcess = configProperties.getProperty("n3.postUploadProcess");
System.out.println("Attempting to load postUploadProcess "
+ postUploadProcess);
postUpload = getPostUpload(postUploadProcess);
String maxSize = configProperties.getProperty("n3.maxSize", Long.toString(DEFAULT_MAX_SIZE));
log.debug("Max size is " + maxSize);
try {
maxFileSize = Integer.parseInt(maxSize);
} catch (NumberFormatException nfe) {
log.error(nfe);
maxFileSize = DEFAULT_MAX_SIZE;
}
}
@Override
protected void doPost(HttpServletRequest rawRequest, HttpServletResponse resp)
throws ServletException, IOException {
log.debug("N3MultiPartProcess 0.01");
FileUploadServletRequest request = FileUploadServletRequest.parseRequest(rawRequest, maxFileSize);
if (request.hasFileUploadException()) {
// TODO: forward to error message
throw new ServletException("Size limit exceeded: " + request.getFileUploadException().getLocalizedMessage());
}
if (!request.isMultipart()) {
// TODO: forward to error message
throw new ServletException("Must POST a multipart encoded request");
}
log.debug("multipart content detected: " + request.isMultipart());
ServletContext application = getServletContext();
HttpSession session = request.getSession();
List<String> errorMessages = new ArrayList<String>();
OntModel jenaOntModel = getJenaOntModel(request, application);
EditConfiguration editConfig = EditConfiguration.getConfigFromSession(
session, request);
if (editConfig == null) {
RequestDispatcher rd = request
.getRequestDispatcher("/edit/messages/noEditConfigFound.jsp");
rd.forward(request, resp);
return;
}
EditSubmission submission =
new EditSubmission(request.getParameterMap(), editConfig, request.getFiles());
EditN3Generator n3Subber = editConfig.getN3Generator();
// check for form validation errors
Map<String, String> errors = submission.getValidationErrors();
EditSubmission.putEditSubmissionInSession(session, submission);
if (errors != null && !errors.isEmpty()) {
String form = editConfig.getFormUrl();
request.setAttribute("formUrl", form);
RequestDispatcher rd = request.getRequestDispatcher(form);
rd.forward(request, resp);
return;
}
boolean requestIsAnUpdate = editConfig.getObject() != null
&& editConfig.getObject().trim().length() > 0;
log.debug(requestIsAnUpdate ? "request is an update for a file object"
: "request is for a new file object");
/** *************************************************** */
String uploadFileName = "";
if (requestIsAnUpdate) {
log.error("Editing an existing file resource is not supported by N3MultiPartUpload.java ");
request.setAttribute("errors", "Editing an existing file resource is not supported.");
RequestDispatcher rd = request
.getRequestDispatcher("/edit/fileUploadError.jsp");
rd.forward(request, resp);
return;
} else { // do new file upload
Map<String, List<Model>> requiredFieldAssertions = new HashMap<String, List<Model>>();
boolean saveFileToDiskSuccess = false;
for (String fileItemKey : request.getFiles().keySet()) {
Field field = editConfig.getField(fileItemKey);
if (field.getOptionsType() != Field.OptionsType.FILE) {
log.debug("Field "
+ fileItemKey
+ " is not of Field.OptionsType.FILE, "
+ "assertion graphs for non-file Fields don't get processed by N3MultiPartProcess");
continue;
}
/* build the models from the field assertions for each file */
for (FileItem fileItem : request.getFiles().get(fileItemKey)) {
try {
requiredFieldAssertions.putAll(buildModelsForFileItem(
fileItem, editConfig, submission, field
.getAssertions(), jenaOntModel,
n3Subber, baseDirectoryForFiles));
saveFileToDiskSuccess = true;
if (log.isDebugEnabled()) {
log.debug("build assertions for field "
+ fileItemKey + " and file "
+ fileItem.getName() + "\n"
+ requiredFieldAssertions.get(fileItemKey));
}
//DEBUG
System.out.println("build assertions for field "
+ fileItemKey + " and file "
+ fileItem.getName() + "\n"
+ requiredFieldAssertions.get(fileItemKey));
//Save upload file name for use in email confirmation
uploadFileName = fileItem.getName();
} catch (Exception e) {
long t = System.currentTimeMillis();
log.error("uplaod ticket " + t + " " + e.getMessage(), e);
errors.put(fileItem.getFieldName(),e.getMessage());
saveFileToDiskSuccess = false;
break;
}
}
}
if ( ! saveFileToDiskSuccess) {
if (errors != null && !errors.isEmpty()) {
String form = editConfig.getFormUrl();
request.setAttribute("formUrl", form);
RequestDispatcher rd = request.getRequestDispatcher(form);
rd.forward(request, resp);
return;
}
}else{
OntModel assertionModel = ModelFactory
.createOntologyModel(OntModelSpec.OWL_MEM);
for (List<Model> modelList : requiredFieldAssertions.values()) {
for (Model model : modelList) {
assertionModel.add(model);
}
}
if( log.isDebugEnabled()){
StmtIterator it = assertionModel.listStatements();
while(it.hasNext()){
log.debug( it.nextStatement().toString() );
}
}
//DEBUG to see what statements are being added
StmtIterator it = assertionModel.listStatements();
while(it.hasNext()){
System.out.println("NEXT Statement:" + it.nextStatement().toString() );
}
/* ****** do PostUpload if there is one ******* */
boolean postUploadSuccess = false;
if (postUpload != null) {
log.debug("found post upload processing task ");
for (String fileURI : requiredFieldAssertions.keySet()) {
try {
Model pModel = postUpload.postUpload(
assertionModel, jenaOntModel, application,
fileURI);
if (pModel != null) {
postUploadSuccess = true;
assertionModel.add(pModel);
}
} catch (Exception re) {
long t = System.currentTimeMillis();
log.error("upload ticket " + t + " "
+ re.getMessage());
errorMessages
.add("There was an error uploading your file, "
+ "upload ticket "
+ t
+ " "
+ re.getMessage());
postUploadSuccess = false;
break;
}
}
}
if (postUploadSuccess) {
/* **** Save the models for all the files **** */
String editorUri = EditN3Utils.getEditorUri(request);
Lock lock = null;
try {
lock = jenaOntModel.getLock();
lock.enterCriticalSection(Lock.WRITE);
jenaOntModel.getBaseModel().notifyEvent(
new EditEvent(editorUri, true));
jenaOntModel.add(assertionModel);
} catch (Throwable t) {
errorMessages
.add("error adding edit change n3required model to in memory model \n"
+ t.getMessage());
} finally {
jenaOntModel.getBaseModel().notifyEvent(
new EditEvent(editorUri, false));
lock.leaveCriticalSection();
}
}
}
}// end of do new file upload
if (errorMessages.size() > 0) {
request.setAttribute("errors", errorMessages);
RequestDispatcher rd = request
.getRequestDispatcher("/edit/fileUploadError.jsp");
rd.forward(request, resp);
} else {
//This is before the redirect occurs from postEditCleanUp
//Send out email confirmation here
try {
sendUserEmail(request, session, uploadFileName);
} catch(Exception ex) {
System.out.println("Problem with retrieving and/or sending email");
}
RequestDispatcher rd = request
.getRequestDispatcher("/edit/postEditCleanUp.jsp");
rd.forward(request, resp);
}
}
private Map<String, List<Model>> buildModelsForFileItem(FileItem fileItem,
EditConfiguration editConfig, EditSubmission submission,
List<String> assertions, OntModel jenaOntModel,
EditN3Generator n3Subber, String dataDir) throws Exception {
Map<String, List<Model>> requiredFieldAssertions = new HashMap<String, List<Model>>();
List<Model> modelList = new ArrayList<Model>(assertions.size());
/* **** Save file and add file properties ***** */
assertions = saveFileAndSubInFileInfo(fileItem, dataDir, n3Subber,
assertions);
if (log.isDebugEnabled())
log.debug("subsititued in literals from file save: " + assertions);
/* **** Make a URI for the file that was just saved **** */
String newFileUri = makeNewUri(editConfig.getNewResources().get(
"fileURI"), jenaOntModel);
assertions = EditN3Generator.subInUris("fileURI", newFileUri, assertions);
/* **** URIs and Literals on Form/Parameters ** */
assertions = EditN3Generator.subInUris(submission.getUrisFromForm(),
assertions);
assertions = n3Subber.subInLiterals(submission.getLiteralsFromForm(),
assertions);
if (log.isDebugEnabled())
log.debug("subsititued in literals from form: " + assertions);
/* **** URIs and Literals in Scope ************ */
assertions = EditN3Generator
.subInUris(editConfig.getUrisInScope(), assertions);
assertions = n3Subber.subInLiterals(editConfig.getLiteralsInScope(),
assertions);
if (log.isDebugEnabled())
log.debug("subsititued in URIs and Literals from scope:"
+ assertions);
/* **** build models from N3 assertion strings */
for (String n3 : assertions) {
try {
Model model = ModelFactory.createDefaultModel();
StringReader reader = new StringReader(n3);
model.read(reader, "", "N3");
modelList.add(model);
} catch (Throwable t) {
log.debug("error processing N3 assertion string "
+ "for field " + fileItem.getFieldName() + " for file "
+ fileItem.getName() + "\n" + t.getMessage() + '\n'
+ "n3: \n" + n3);
}
}
requiredFieldAssertions.put(newFileUri, modelList);
return requiredFieldAssertions;
}
private List<String> saveFileAndSubInFileInfo(FileItem fileItem,
String dataDir, EditN3Generator n3generator, List<String> assertions)
throws Exception {
String originalName = fileItem.getName();
String name = originalName.replaceAll("[,+\\\\/$%^&*#@!<>'\"~;]", "_");
name = name.replace("..", "_");
name = name.trim().toLowerCase();
String saveLocation = dataDir + File.separator + name;
String savedName = name;
int next = 0;
boolean foundUnusedName = false;
while (!foundUnusedName) {
File test = new File(saveLocation);
if (test.exists()) {
next++;
savedName = name + '(' + next + ')';
saveLocation = dataDir + File.separator + savedName;
} else {
foundUnusedName = true;
}
}
File uploadedFile = new File(saveLocation);
try {
fileItem.write(uploadedFile);
} catch (Exception ex) {
log.error("Unable to save POSTed file. " + ex.getMessage());
throw new Exception("Unable to save file to the disk. "
+ ex.getMessage());
}
if( fileItem.getSize() < 1){
throw new Exception("No file was uploaded or file was empty.");
}else{
Map<String, Literal> fileValues = new HashMap<String, Literal>();
fileValues.put("fileName", ResourceFactory
.createTypedLiteral(originalName));
fileValues.put("fileSaveLocation", ResourceFactory
.createTypedLiteral(saveLocation));
fileValues.put("fileSavedName", ResourceFactory
.createTypedLiteral(savedName));
fileValues.put("fileContentType", ResourceFactory
.createTypedLiteral(fileItem.getContentType()));
fileValues.put("fileSize", ResourceFactory.createTypedLiteral(fileItem
.getSize()));
assertions = n3generator.subInLiterals(fileValues, assertions);
}
return assertions;
}
public static String makeNewUri(String prefix, Model model) {
if (prefix == null || prefix.length() == 0)
prefix = fileUriPrefix;
String uri = prefix + Math.abs(random.nextInt());
Resource r = ResourceFactory.createResource(uri);
while (model.containsResource(r)) {
uri = prefix + Math.abs(random.nextInt());
r = ResourceFactory.createResource(uri);
}
return uri;
}
private OntModel getJenaOntModel(HttpServletRequest request,
ServletContext application) {
Object sessionOntModel = request.getSession().getAttribute(
"jenaOntModel");
OntModel jenaOntModel = (sessionOntModel != null && sessionOntModel instanceof OntModel) ? (OntModel) sessionOntModel
: (OntModel) application.getAttribute("jenaOntModel");
return jenaOntModel;
}
private PostUpload getPostUpload(String postUploadProcess) {
PostUpload newPu = null;
// this is hard coded for now but needs to be configured some how.
String name = "edu.cornell.mannlib.datastar.DataStarPostUpload";
try {
Class<?> newClass = Class.forName(name);
Object obj = newClass.newInstance();
if (obj instanceof PostUpload) {
newPu = (PostUpload) obj;
}
} catch (Throwable ex) {
log
.error("could not build PostUpload object for Class "
+ name, ex);
}
if (newPu != null) {
log.info("using postUploadProcess " + name);
}
return newPu;
}
public static interface PostUpload {
public String checkStatus(OntModel model, ServletContext context)
throws Exception;
public Model postUpload(OntModel model, OntModel fullModel,
ServletContext context, String fileURI) throws Exception;
}
public Map<String, List<String>> fieldsToAssertionMap(
Map<String, Field> fields) {
Map<String, List<String>> out = new HashMap<String, List<String>>();
for (String fieldName : fields.keySet()) {
Field field = fields.get(fieldName);
List<String> copyOfN3 = new ArrayList<String>();
for (String str : field.getAssertions()) {
copyOfN3.add(str);
}
out.put(fieldName, copyOfN3);
}
return out;
}
public Map<String, List<String>> fieldsToRetractionMap(
Map<String, Field> fields) {
Map<String, List<String>> out = new HashMap<String, List<String>>();
for (String fieldName : fields.keySet()) {
Field field = fields.get(fieldName);
List<String> copyOfN3 = new ArrayList<String>();
if( field.getRetractions() != null ){
for (String str : field.getRetractions()) {
copyOfN3.add(str);
}
}
out.put(fieldName, copyOfN3);
}
return out;
}
public void sendUserEmail(HttpServletRequest request, HttpSession session, String uploadFileName) {
UserAccount userAccount = LoginStatusBean.getCurrentUser(request);
if (userAccount == null) {
return;
}
try{
System.out.println("User URI is " + userAccount.getUri());
String email = userAccount.getEmailAddress();
String deliveryFrom = "hjk54@cornell.edu";//TO DO: replace with email address to be used
//Now send message
MailUtil mu = new MailUtil(request);
List<String> deliverToArray = new ArrayList<String>();
deliverToArray.add(email);
//Compose body of message
StringBuffer msgBuf = new StringBuffer();
String lineSeparator = System.getProperty("line.separator");
msgBuf.setLength(0);
msgBuf.append("<html>" + lineSeparator );
msgBuf.append("<head>" + lineSeparator );
msgBuf.append("<style>a {text-decoration: none}</style>" + lineSeparator );
msgBuf.append("<title>" + deliveryFrom + "</title>" + lineSeparator );
msgBuf.append("</head>" + lineSeparator );
msgBuf.append("<body>" + lineSeparator );
String messageBody = "<h4>File has been uploaded to datastar";
//Include file name if it exists and is not empty
if(uploadFileName != null && uploadFileName != "") {
messageBody += ": " + uploadFileName;
}
messageBody += "</h4>";
msgBuf.append(messageBody + lineSeparator + "</body></html>");
String messageText = msgBuf.toString();
//Send message
mu.sendMessage(messageText, "Datastar File Upload: Success", deliveryFrom, email, deliverToArray);
} catch(Exception ex) {
System.out.println("Error " + ex.getMessage());
}
}
// private boolean logAddRetract(String msg, Map<String, List<String>> add,
// Map<String, List<String>> retract) {
// log.debug(msg);
// if (add != null)
// log.debug("assertions: " + add.toString());
// if (retract != null)
// log.debug("retractions: " + retract.toString());
// return true;
// }
static Random random = new Random();
Log log = LogFactory.getLog(N3MultiPartUpload.class);
}

View file

@ -0,0 +1,12 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.edit;
import edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet;
/**
*TO BE DELETED.
*/
public class N3MultiPartUploadDELETEME extends VitroHttpServlet {
}

View file

@ -2,19 +2,6 @@
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ExceptionResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateModelException;
/**
* This controller is intended to place N3 editing data into the
@ -22,62 +9,5 @@ import freemarker.template.TemplateModelException;
*/
public class N3EditFormController extends FreemarkerHttpServlet{
@Override
protected ResponseValues processRequest(VitroRequest vreq) {
try{
//get edit objects
HttpSession session = vreq.getSession(false);
if( session == null )
throw new Exception("Cannot get session");
EditConfiguration editConfig = EditConfiguration.getConfigFromSession(session, vreq);
if(editConfig == null )
throw new Exception("Cannot get EditConfiguration from session");
EditSubmission editSubmission = EditSubmission.getEditSubmissionFromSession(session, editConfig);
//add edit info to the template data model and call template
Map<String,Object> map = makeEditDataMap(editConfig, editSubmission);
//how do I add css or js?
//The jsp is adding css and js like this:
/*
List<String> customJs = new ArrayList<String>(Arrays.asList(JavaScript.JQUERY_UI.path(),
JavaScript.CUSTOM_FORM_UTILS.path(),
"/edit/forms/js/customFormWithAutocomplete.js"
));
request.setAttribute("customJs", customJs);
List<String> customCss = new ArrayList<String>(Arrays.asList(Css.JQUERY_UI.path(),
Css.CUSTOM_FORM.path(),
"/edit/forms/css/customFormWithAutocomplete.css"
));
request.setAttribute("customCss", customCss);
*/
//What needs to happen??
//map.put(???);
return new TemplateResponseValues(editConfig.getTemplate(), map);
}catch(Exception ex){
return new ExceptionResponseValues(ex);
}
}
/**
* This method get data out of the editConfig and editSubmission for the template.
* @throws TemplateModelException
*/
private Map<String, Object> makeEditDataMap(EditConfiguration editConfig,
EditSubmission editSubmission) throws TemplateModelException {
Map<String,Object> map = new HashMap<String,Object>();
map.put("editConfig", editConfig);
if( editSubmission != null)
map.put("editSubmission", editSubmission);
return map;
}
//TO BE DELETED
}

View file

@ -1,76 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.elements;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public abstract class BaseEditElement implements EditElement {
private static final Log log = LogFactory.getLog(BaseEditElement.class);
protected Field field;
public BaseEditElement(Field field){
this.field = field;
}
/**
* Utility method for use in EditElements to merge a freemarker template.
*/
protected String merge(Configuration fmConfig, String templateName, Map map){
Template template = null;
try {
template = fmConfig.getTemplate(templateName);
} catch (IOException e) {
log.error("Cannot get template " + templateName);
}
StringWriter writer = new StringWriter();
try {
template.process(map, writer);
} catch (TemplateException e) {
log.error(e,e);
} catch (IOException e) {
log.error(e,e);
}
return writer.toString();
}
/**
* Utility method to check if a value from the query parameters is none or a single value.
* This returns true if the key is there and the value is null.
* This does not check if the value is the empty string.
*/
protected boolean hasNoneOrSingle(String key, Map<String, String[]> queryParameters){
if( queryParameters != null ){
if( ! queryParameters.containsKey(key) )
return true; //none
String[] vt = queryParameters.get(key);
return vt == null || vt.length == 0 || vt.length==1;
}else{
log.error("passed null queryParameters");
return false;
}
}
protected boolean hasSingleNonNullNonEmptyValueForKey(String key, Map<String, String[]> queryParameters){
if( queryParameters != null ){
if( ! queryParameters.containsKey(key) )
return true; //none
String[] vt = queryParameters.get(key);
return vt != null && vt.length == 1 && vt[0] != null && ! vt[0].isEmpty() ;
}else{
log.error("passed null queryParameters");
return false;
}
}
}

View file

@ -1,47 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.elements;
import java.util.Map;
import com.hp.hpl.jena.rdf.model.Literal;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
import freemarker.template.Configuration;
/**
* All classes that implement this interface must have a public constructor that
* takes a edu.cornell.mannlib.vitro.webapp.edit.n3editing.Field. It will be
* called with using reflection.
*/
public interface EditElement {
/**
* This is a method to get a map of variable name to Literal value from the submitted form.
*/
public Map<String,Literal>
getLiterals(String fieldName, EditConfiguration editConfig, Map<String,String[]> queryParameters );
/**
* This is a method to get a map of variable name to URI value from the submitted form.
*/
public Map<String,String>
getURIs(String fieldName, EditConfiguration editConfig, Map<String,String[]> queryParameters );
/**
* Gets validation error messages. Returns an empty list if there are no errors.
*/
public Map<String,String>
getValidationMessages(String fieldName, EditConfiguration editConfig, Map<String,String[]> queryParameters);
/**
* This is a method to generate the HTML output for a form element. It should use a freemarker template
* to produce the output.
*/
public String draw(String fieldName, EditConfiguration editConfig, EditSubmission editSub, Configuration fmConfig);
/* in the future, we may need to get existing values */
/*
public Map<String,Literal> getExistingLiterals(???)
public Map<String,String> getExistingURIs(???);
*/
}

View file

@ -19,7 +19,7 @@ import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatementImpl;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyStatementDao;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.BasicValidation;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.BasicValidationVTwo;
public class IndividualDataPropertyStatementProcessor implements ChangeListener {
@ -82,7 +82,7 @@ public class IndividualDataPropertyStatementProcessor implements ChangeListener
String rangeDatatypeURI = dataPropertyDao.getRequiredDatatypeURI(individual, dp);
if (rangeDatatypeURI != null) {
dataPropertyStmt.setDatatypeURI(rangeDatatypeURI);
String validationMsg = BasicValidation.validateAgainstDatatype(dataPropertyStmt.getData(), rangeDatatypeURI);
String validationMsg = BasicValidationVTwo.validateAgainstDatatype(dataPropertyStmt.getData(), rangeDatatypeURI);
// Since this backend editing system is de facto deprecated,
// not worrying about implementing per-field validation
if (validationMsg != null) {

View file

@ -8,7 +8,6 @@ import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.fileupload.FileItem;
@ -25,9 +24,6 @@ import edu.cornell.mannlib.vitro.webapp.beans.Datatype;
import edu.cornell.mannlib.vitro.webapp.dao.jena.DatatypeDaoJena;
import edu.cornell.mannlib.vitro.webapp.dao.jena.WebappDaoFactoryJena;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
public class BasicValidationVTwo {

View file

@ -2,13 +2,14 @@
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.List;
import java.util.ArrayList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
@ -18,12 +19,8 @@ import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerConfiguration;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
import freemarker.template.Configuration;
/**

View file

@ -16,21 +16,17 @@ import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.vocabulary.XSD;
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.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
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.web.templatemodels.edit.EditConfigurationTemplateModel;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerConfigurationLoader;
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.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerConfigurationLoader;
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.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.RdfLiteralHash;
import freemarker.template.Configuration;
public class EditConfigurationUtils {

View file

@ -8,8 +8,6 @@ import java.util.Map;
import javax.servlet.http.HttpSession;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
public class EditSubmissionUtils {
protected static final String MULTI_VALUED_EDIT_SUBMISSION = "MultiValueEditSubmission";

View file

@ -4,25 +4,20 @@ package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.joda.time.IllegalFieldValueException;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.json.JSONObject;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
@ -31,11 +26,7 @@ import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.vocabulary.XSD;
import edu.cornell.mannlib.vitro.webapp.edit.EditLiteral;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditElementVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.BasicValidation;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.N3Validator;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditN3Utils;
public class MultiValueEditSubmission {

View file

@ -4,9 +4,6 @@ package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo;
import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
public interface N3ValidatorVTwo {
public Map<String,String> validate(EditConfigurationVTwo editConfig, MultiValueEditSubmission editSub);
}

View file

@ -1,972 +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;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.edit.EditLiteral;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.EditSubmissionPreprocessor;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.ModelChangePreprocessor;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.N3Validator;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditN3Generator;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditN3Utils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.SparqlEvaluate;
import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch;
/**
* Represents a set of fields on a form and how parameters from a from
* submission should be manipulated to create N3.
*
* Uris in urisInScope and urisOnForm should not have any quoting or escaping.
*
* Literals in literalsOnForm and literalsInScope should be escaped and quoted
* in preparation for N3. They may also be appended with a datatype or lang.
*
* @deprecated Use EditConfigurationVTwo instead of this class.
*/
public class EditConfiguration {
List<String> n3Required;
List<String> n3Optional;
List<String> urisOnform;
List<String> literalsOnForm;
List<String> filesOnForm;
Map<String,String> urisInScope;
Map<String, Literal> literalsInScope;
Map<String,String> sparqlForAdditionalUrisInScope;
Map<String,String> sparqlForAdditionalLiteralsInScope;
Map<String,String> newResources;
Map<String,Field> fields;
Map<String,String>sparqlForExistingLiterals;
Map<String,String>sparqlForExistingUris;
String subjectUri;
String varNameForSubject;
String predicateUri;
String varNameForPredicate;
/** When this is a DataPropertyStmt edit the object is not used, the
* DataPropertyStatement is retrieved using the subject, predicate and the
* datapropKey. When this edit is for a ObjectPropertyStmt
* object is the uri without the quoting &lt; or &gt;.
*/
String object;
String varNameForObject;
boolean isObjectResource;
String datapropKey;
String datapropValue;
String urlPatternToReturnTo;
String entityToReturnTo;
String formUrl;
String editKey;
List<N3Validator> validators;
EditN3Generator n3generator;
private String originalJson;
private List<ModelChangePreprocessor> modelChangePreprocessors;
private List<EditSubmissionPreprocessor> editSubmissionPreprocessors = null;
private ProhibitedFromSearch prohibitedFromSearch;
/** Name of freemarker template to generate form. */
String template;
/** URL to submit form to. */
String submitToUrl;
/**
* If true, then any dependent resources that are unlinked should be
* removed using DependentResourceDelete.
*/
private boolean useDependentResourceDelete = true;
/** Model to write changes of a completed edit to. Usually this is null
* and the edit will be written to the main graph of the system. */
private ModelSelector writeModelSelector;
/** Model to query for existing and things like that. Usually this is null
* and the main Model of the system will be used as the default. */
private ModelSelector queryModelSelector;
/** Model to check when making new URIs to check that there is not already
* a resource with a given URI. */
private ModelSelector resourceModelSelector;
/** WebappDaoFactory to build option, check box, and radio button lists.
* Usually this is set to null and the main model will be used. */
private WDFSelector wdfSelectorForOptons;
public EditConfiguration(String config) {
this();
n3generator = new EditN3Generator(this );
modelChangePreprocessors = new LinkedList<ModelChangePreprocessor>();
JSONObject jsonObj = null;
if( config == null) throw new Error("EditConfiguration must be constructed with a non-null JSON config string");
try{
jsonObj = new JSONObject(config);
}catch (JSONException je){
throw new Error(je);
}
originalJson = config;
setValuesFromJson(jsonObj);
}
public EditConfiguration(){
writeModelSelector = StandardModelSelector.selector;
queryModelSelector = StandardModelSelector.selector;
resourceModelSelector = StandardModelSelector.selector;
wdfSelectorForOptons = StandardWDFSelector.selector;
}
private void setValuesFromJson(JSONObject obj){
try{
if(log.isDebugEnabled())
log.debug("JSON to use for configuration: \n" + obj.toString(1)+ "\n");
n3Required = JsonArrayToStringList(obj.getJSONArray("n3required"));
n3Optional = JsonArrayToStringList(obj.getJSONArray("n3optional"));
urisOnform = JsonArrayToStringList(obj.getJSONArray("urisOnForm"));
literalsOnForm = JsonArrayToStringList(obj.getJSONArray("literalsOnForm"));
filesOnForm = JsonArrayToStringList(obj.getJSONArray("filesOnForm"));
newResources = JsonObjToMap(obj.getJSONObject("newResources"));
urisInScope = JsonObjToMap(obj.getJSONObject("urisInScope"));
literalsInScope = makeLiteralsInScopeFromJson(obj.getJSONObject( "literalsInScope"));
sparqlForAdditionalUrisInScope = JsonObjToMap(obj.getJSONObject("sparqlForUris"));
sparqlForAdditionalLiteralsInScope = JsonObjToMap(obj.getJSONObject("sparqlForLiterals"));
sparqlForExistingLiterals = JsonObjToMap(obj.getJSONObject("sparqlForExistingLiterals"));
sparqlForExistingUris = JsonObjToMap(obj.getJSONObject("sparqlForExistingUris"));
JSONArray subject = obj.getJSONArray("subject");
if( subject.length() != 2 )
throw new Error("EditConfiguration subject field must be an array with two items: [varnameForSubject, subjectUri]");
varNameForSubject = subject.getString(0);
subjectUri = subject.getString(1);
urisInScope.put(varNameForSubject, subjectUri);
entityToReturnTo = subjectUri;
urlPatternToReturnTo = obj.getString("urlPatternToReturnTo");
JSONArray predicate = obj.getJSONArray("predicate");
if( predicate.length() != 2 )
throw new Error("EditConfiguration predicate field must be an array with two items: [varnameForPredicate, predicateUri]");
varNameForPredicate = predicate.getString(0);
predicateUri = predicate.getString(1);
urisInScope.put(varNameForPredicate, predicateUri);
JSONArray object = obj.getJSONArray("object");
if( object.length() != 3 )
throw new Error("EditConfiguration object field must be an array with THREE items: [varnameForObject, objectValue, objectType]"+
"\n ObjectValue may be a uri or a literal. ObjectType may be the string value 'URI' or 'DATAPROPHASH");
varNameForObject= object.getString(0);
isObjectResource = ("URI".equalsIgnoreCase( object.getString(2) ));
if( isObjectResource ){
this.object = object.getString(1);
}else{
datapropValue = object.getString(1);
datapropKey = obj.getString("datapropKey");
log.debug("Set datapropValue ["+datapropValue+"] and datapropKey ["+datapropKey+"] in EditConfiguration");
}
fields = JsonObjToMapOfFields(obj.getJSONObject("fields"));
formUrl = obj.getString("formUrl");
editKey = obj.getString("editKey");
}catch(JSONException ex){
throw new Error(ex);
}
}
private Map<String, Literal> makeLiteralsInScopeFromJson(JSONObject jsonObject) throws JSONException{
Map<String, Literal> out = new HashMap<String,Literal>();
Iterator keys = jsonObject.keys();
while(keys.hasNext() ){
String key = (String)keys.next();
JSONObject jLit = jsonObject.getJSONObject(key);
String value = jLit.getString("value");
String datatype = jLit.optString("datatype",null);
String lang = jLit.optString("lang",null);
Literal literal = new EditLiteral( value, datatype, lang);
out.put(key,literal);
}
return out;
}
/**
* Add symbols for things like currentTime and editingUser to
* editConfig.urisInScope and editConfig.literalsInScope.
*/
public void addSystemValues( Model model, HttpServletRequest request, ServletContext context){
if( model == null ) throw new Error("EditConfiguration.addSystemValues() needs a Model");
if( request == null ) throw new Error("EditConfiguration.addSystemValues() needs a request");
/* current time */
if( getSparqlForAdditionalLiteralsInScope() != null &&
getSparqlForAdditionalLiteralsInScope().containsKey("currentTime") &&
USE_SYSTEM_VALUE.equals(getSparqlForAdditionalLiteralsInScope().get("currentTime"))){
//Updating so that this is represented as an XSD Date Time literal - to allow for comparison later
//Currently it appears that this is only used for file upload
//getLiteralsInScope().put("currentTime", ResourceFactory.createTypedLiteral(new Date()));
SimpleDateFormat dateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String formattedDate = dateTime.format(Calendar.getInstance().getTime());
getLiteralsInScope().put("currentTime", ResourceFactory.createTypedLiteral(formattedDate, XSDDatatype.XSDdateTime));
}
/* editing user */
if( getSparqlForAdditionalUrisInScope() != null &&
getSparqlForAdditionalUrisInScope().containsKey("editingUser") &&
USE_SYSTEM_VALUE.equals(getSparqlForAdditionalUrisInScope().get("editingUser"))) {
if( request.getSession() == null )
throw new Error("EditConfiguration.addSystemValues() needs a session");
/* ********** Get URI of a logged in user ************** */
String userUri = EditN3Utils.getEditorUri(request);
log.debug("EditConfiguration.java - checking system value for User URI " + userUri);
getUrisInScope().put("editingUser", userUri);
}
}
/**
* Make a copy of this EditConfiguration, prepare for a DataProperty update
* and return it.
*/
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");
} 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 ");
}
getLiteralsInScope().put(varNameForObject, new EditLiteral(dpStmt.getData(),dpStmt.getDatatypeURI(), dpStmt.getLanguage()));
// run SPARQL, sub in values
SparqlEvaluate sparqlEval = new SparqlEvaluate(model);
runSparqlForAdditional( sparqlEval );
runSparqlForExisting( sparqlEval );
//build retraction N3 for each Field
for(String var : getFields().keySet() ){
Field field = getField(var);
List<String> retractions = null;
retractions = n3generator.subInLiterals(getLiteralsInScope(),field.getAssertions());
retractions = n3generator.subInUris(getUrisInScope(), retractions);
field.setRetractions(retractions);
}
}
/**
* Make a copy of this EditConfiguration, prepare for a ObjectProperty update
* and return it.
*/
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");
}
getUrisInScope().put( varNameForObject, object);
log.debug("Putting uris in scope - var name for object " + varNameForObject + " and object is " + object);
// run SPARQL, sub in values
SparqlEvaluate sparqlEval = new SparqlEvaluate( model );
runSparqlForAdditional( sparqlEval );
try {
runSparqlForExisting( sparqlEval );
} catch (Exception e) {
e.printStackTrace();
}
//build retraction N3 for each Field
for(String var : getFields().keySet() ){
Field field = getField(var);
List<String> retractions = null;
retractions = n3generator.subInLiterals(getLiteralsInScope(),field.getAssertions());
retractions = n3generator.subInUris(getUrisInScope(), retractions);
field.setRetractions(retractions);
}
}
public void prepareForNonUpdate( Model model ){
if( model == null ) throw new Error("EditConfiguration.prepareForNonUpdate() needs a Model");
SparqlEvaluate sparqlEval = new SparqlEvaluate( model );
runSparqlForAdditional( sparqlEval );
//runSparqlForExisting( sparqlEval );
}
public void setFields(JSONObject obj) {
HashMap<String,Field> fieldMap = new HashMap<String,Field>();
Iterator it = obj.keys();
while(it.hasNext()){
String key = (String)it.next();
JSONArray v = obj.optJSONArray(key);
if( v != null ){ //the key is present and optJSONArray returns a JSONArray
for(int i=0; i<v.length(); i++){
if (v.opt(i) instanceof Field) {
fieldMap.put(key,(Field)v.opt(i));
}
}
continue;
} // else the key is not present or optJSONArray() returns something that is not a JSONArray
throw new Error("fields must be a JSONArray of Field objects");
}
fields = fieldMap;
}
public void setFields(Map<String,Field> fields) {
this.fields = fields;
}
public void prepareForResubmit(EditSubmission editSub){
//get any values from editSub and add to scope
}
/**
* Runs the queries for additional uris and literals then add those back into
* the urisInScope and literalsInScope.
*/
public void runSparqlForAdditional(SparqlEvaluate sparqlEval){
sparqlEval.evaluateForAdditionalUris( this );
sparqlEval.evalulateForAdditionalLiterals( this );
}
public void runSparqlForExisting(SparqlEvaluate sparqlEval){
sparqlEval.evaluateForExistingUris( this );
sparqlEval.evaluateForExistingLiterals( this );
}
public Field getField(String key){
if( fields == null) {
throw new Error("hashmap of field objects must be set before you can get a value from the EditConfiguration");
}
return fields.get(key);
}
/** return a copy of the value so that the configuration is not modified by external code.
* @return
*/
public List<String> getN3Required() {
List<String> copyForPassByValue = new ArrayList<String> (n3Required.size());
for( String str : n3Required){
copyForPassByValue.add(str);
}
return copyForPassByValue;
}
public void setN3Required(List<String> n3Required) {
this.n3Required = n3Required;
}
/** return a copy of the value so that the configuration is not modified by external code.
* @return
*/
public List<String> getN3Optional() {
List<String> copyForPassByValue = new ArrayList<String> (n3Optional.size());
for( String str : n3Optional){
copyForPassByValue.add(str);
}
return copyForPassByValue;
}
public void setN3Optional(List<String> n3Optional) {
this.n3Optional = n3Optional;
}
public Map<String,String> getNewResources() {
return newResources;
}
public void setNewResources(Map<String,String> newResources) {
this.newResources = newResources;
}
public List<String> getUrisOnform() {
return urisOnform;
}
public void setUrisOnform(List<String> urisOnform) {
this.urisOnform = urisOnform;
}
public void setFilesOnForm(List<String> filesOnForm){
this.filesOnForm = filesOnForm;
}
public List<String> getFilesOnForm(){
return filesOnForm;
}
public List<String> getLiteralsOnForm() {
return literalsOnForm;
}
public void setLiteralsOnForm(List<String> literalsOnForm) {
this.literalsOnForm = literalsOnForm;
}
public Map<String, String> getUrisInScope() {
return urisInScope;
}
public void setUrisInScope(Map<String, String> urisInScope) {
this.urisInScope = urisInScope;
}
public Map<String, Literal> getLiteralsInScope() {
return literalsInScope;
}
public void setLiteralsInScope(Map<String, Literal> literalsInScope) {
this.literalsInScope = literalsInScope;
}
/** return a copy of the value so that the configuration is not modified by external code.
* @return
*/
public Map<String, String> getSparqlForAdditionalUrisInScope() {
Map<String, String> copyForPassByValue = new HashMap<String, String>();
copy(sparqlForAdditionalUrisInScope, copyForPassByValue);
return copyForPassByValue;
}
public void setSparqlForAdditionalUrisInScope(Map<String, String> sparqlForAdditionalUrisInScope) {
this.sparqlForAdditionalUrisInScope = sparqlForAdditionalUrisInScope;
}
/** return a copy of the value so that the configuration is not modified by external code.
* @return
*/
public Map<String, String> getSparqlForAdditionalLiteralsInScope() {
Map<String, String> copyForPassByValue = new HashMap<String, String>();
copy(sparqlForAdditionalLiteralsInScope, copyForPassByValue);
return copyForPassByValue;
}
private Map<String,String> copy(Map<String,String> source, Map<String,String> dest){
if( source == null ) return null;
dest.clear();
for( String key : source.keySet()){
dest.put(key, source.get(key));
}
return dest;
}
public void setSparqlForAdditionalLiteralsInScope(Map<String, String> sparqlForAdditionalLiteralsInScope) {
this.sparqlForAdditionalLiteralsInScope = sparqlForAdditionalLiteralsInScope;
}
public String getEntityToReturnTo() {
return entityToReturnTo;
}
public void setEntityToReturnTo(String entityToReturnTo) {
this.entityToReturnTo = entityToReturnTo;
}
public String getUrlPatternToReturnTo() {
return urlPatternToReturnTo;
}
public void setUrlPatternToReturnTo(String s) {
urlPatternToReturnTo = s;
}
/** return a copy of the value so that the configuration is not modified by external code.
* @return
*/
public Map<String, String> getSparqlForExistingLiterals() {
Map<String, String> copyForPassByValue = new HashMap<String, String>();
copy(sparqlForExistingLiterals, copyForPassByValue);
return copyForPassByValue;
}
public void setSparqlForExistingLiterals(Map<String, String> sparqlForExistingLiterals) {
this.sparqlForExistingLiterals = sparqlForExistingLiterals;
}
/** return a copy of the value so that the configuration is not modified by external code.
* @return
*/
public Map<String, String> getSparqlForExistingUris() {
Map<String, String> copyForPassByValue = new HashMap<String, String>();
copy(sparqlForExistingUris, copyForPassByValue);
return copyForPassByValue;
}
public void setSparqlForExistingUris(Map<String, String> sparqlForExistingUris) {
this.sparqlForExistingUris = sparqlForExistingUris;
}
public static List<String> JsonArrayToStringList(JSONArray jarray){
ArrayList<String> outv = new ArrayList<String>();
if( jarray != null ){
for( int i = 0; i< jarray.length(); i++){
try{
outv.add(jarray.getString(i));
}catch(JSONException je){}
}
}
return outv;
}
public static Map<String,String> JsonObjToMap(JSONObject jobj){
HashMap<String,String> outv = new HashMap<String,String>();
if( jobj != null ){
Iterator keyIt = jobj.keys();
while( keyIt.hasNext()){
try{
String key = (String)keyIt.next();
outv.put(key,jobj.getString(key));
}catch(JSONException je){ }
}
}
return outv;
}
public static Map<String,Field> JsonObjToMapOfFields(JSONObject jobj){
HashMap<String,Field> outv = new HashMap<String,Field>();
if( jobj != null ){
Iterator keyIt = jobj.keys();
while( keyIt.hasNext()){
try{
String key = (String)keyIt.next();
JSONObject obj = jobj.getJSONObject(key);
Field field = new Field(obj, key);
outv.put(key, field);
}catch(JSONException je){ }
}
}
return outv;
}
public Map<String, List<String>> getN3ForFields(){
return fieldsToMap( getFields() );
}
private Map<String,List<String>> fieldsToMap( Map<String,Field> fields){
Map<String,List<String>> out = new HashMap<String,List<String>>();
for( String fieldName : fields.keySet()){
Field field = fields.get(fieldName);
List<String> copyOfN3 = new ArrayList<String>();
for( String str : field.getAssertions()){
copyOfN3.add(str);
}
out.put( fieldName, copyOfN3 );
}
return out;
}
/* ********************** static methods to get EditConfigs from Session ******************************** */
public static void clearAllConfigsInSession( HttpSession sess ){
if(sess == null ) return;
sess.removeAttribute("editConfiguration");
}
public static void clearEditConfigurationInSession(HttpSession session, EditConfiguration editConfig) {
if( session == null || editConfig == null )
return;
Map<String,EditConfiguration> configs = (Map<String,EditConfiguration>)session.getAttribute("EditConfigurations");
if( configs == null )
return ;
if( configs.containsKey( editConfig.editKey ) )
configs.remove( editConfig.editKey );
}
public static void putConfigInSession(EditConfiguration ec, HttpSession sess){
if( sess == null )
throw new Error("EditConfig: could not put config in session because session was null");
if( ec.editKey == null )
throw new Error("EditConfig: could not put into session because editKey was null.");
Map<String,EditConfiguration> configs = (Map<String,EditConfiguration>)sess.getAttribute("EditConfigurations");
if( configs == null ){
configs = new HashMap<String,EditConfiguration>();
sess.setAttribute("EditConfigurations",configs);
}
configs.put(ec.editKey , ec);
}
public static EditConfiguration getConfigFromSession(HttpSession sess, String editKey){
Map<String,EditConfiguration> configs = (Map<String,EditConfiguration>)sess.getAttribute("EditConfigurations");
if( configs == null )
return null;
EditConfiguration config = configs.get( editKey );
if( config == null )
return null;
else
return config;
}
/**
* This may return null, which indicates that there is no editKey or EditConfiguration in the
* request or session. If the queryParams are supplied, look for the editKey
* there first since multipart parsing might have cleared them from the request.
*/
public static EditConfiguration getConfigFromSession( HttpSession sess, HttpServletRequest request ){
String key = getEditKey(request);
if( key == null )
return null;
return getConfigFromSession(sess, key);
}
/**
* The editKey can be a HTTP query parameter or it can be a request attribute.
*/
public static String getEditKey( ServletRequest request){
String key = null;
if( request instanceof HttpServletRequest ){
HttpServletRequest hsreq = (HttpServletRequest)request;
boolean isMultipart = ServletFileUpload.isMultipartContent(hsreq);
if( isMultipart ) {
//multipart parsing will consume all request parameters so
//the editKey needs to be stashed in the request attributes.
key = (String)request.getAttribute("editKey");
if( key == null ) {
// handle the cancel button where nothing is really uploaded
key = request.getParameter("editKey");
}
}else{
key = (String)request.getAttribute("editKey");
if( key != null ){
return key;
} else {
key = request.getParameter("editKey");
}
}
}
if( key != null && key.trim().length() > 0 ){
return key;
}else{
log.debug("cannnot find editKey in request query parameters or from request");
return null;
}
}
public static String newEditKey(HttpSession sess){
DateTime time = new DateTime();
int mills = time.getMillisOfDay();
Map<String,EditConfiguration> configs = (Map<String,EditConfiguration>)sess.getAttribute("EditConfigurations");
if( configs == null ){
return Integer.toString(mills);
}else{
while( configs.containsKey( Integer.toString(mills) )){
mills ++;
}
return Integer.toString(mills);
}
}
/*
* getters and setters
*/
public String getObject() {
return object;
}
public void setObject(String object) {
this.object = object;
}
public boolean isObjectResource() {
return isObjectResource;
}
public void setObjectResource(boolean isObjectResource) {
this.isObjectResource = isObjectResource;
}
public String getDatapropKey() {
return datapropKey;
}
public void setDatapropKey(String datapropKey) {
this.datapropKey = datapropKey;
}
public String getSubjectUri() {
return subjectUri;
}
public void setSubjectUri(String subjectUri) {
this.subjectUri = subjectUri;
}
public String getPredicateUri() {
return predicateUri;
}
public void setPredicateUri(String predicateUri) {
this.predicateUri = predicateUri;
}
public Map<String,Field> getFields() {
return fields;
}
public String getEditKey() {
return editKey;
}
public void setEditKey(String editKey) {
this.editKey = editKey;
}
public String getFormUrl() {
return formUrl;
}
public void setFormUrl(String formUrl) {
this.formUrl = formUrl;
}
public EditN3Generator getN3Generator(){
return n3generator;
}
public void setN3Generator(EditN3Generator gen) {
this.n3generator = gen;
}
public String getVarNameForSubject() {
return this.varNameForSubject;
}
public void setVarNameForSubject(String varName) {
this.varNameForSubject = varName;
}
public String getVarNameForPredicate() {
return this.varNameForPredicate;
}
public void setVarNameForPredicate(String varName) {
this.varNameForPredicate = varName;
}
public String getVarNameForObject(){
return this.varNameForObject;
}
public void setVarNameForObject(String varName) {
this.varNameForObject = varName;
}
/**If this is set to true, then dependent resources should be deleted on edits that
* remove the parent resource.
*/
public boolean isUseDependentResourceDelete() {
return useDependentResourceDelete;
}
/**If this is set to true, then dependent resources should be deleted on edits that
* remove the parent resource.
*/
public void setUseDependentResourceDelete(boolean useDependentResourceDelete) {
this.useDependentResourceDelete = useDependentResourceDelete;
}
public List<ModelChangePreprocessor> getModelChangePreprocessors() {
return this.modelChangePreprocessors;
}
public List<ModelChangePreprocessor> setModelChangePreprocessors() {
return this.modelChangePreprocessors;
}
public void addModelChangePreprocessor( ModelChangePreprocessor modelChangePreprocessor) {
this.modelChangePreprocessors.add( modelChangePreprocessor );
}
public void setProhibitedFromSearch( ProhibitedFromSearch prohibitedFromSearch) {
this.prohibitedFromSearch = prohibitedFromSearch;
}
public ProhibitedFromSearch getProhibitedFromSearch() {
return this.prohibitedFromSearch;
}
private void debugScope(String msg){
if( log.isDebugEnabled()){
log.debug(msg);
log.debug("literalsInScope:");
for( String key: literalsInScope.keySet() ){
String val = literalsInScope.get(key).toString();
log.debug( key + " " + val );
}
log.debug("uris in scope: " );
for( String key: urisInScope.keySet() ){
String val = urisInScope.get(key).toString();
log.debug( key + " " + val );
}
}
}
public EditConfiguration copy(){
return new EditConfiguration(this.originalJson);
}
// public static class SelectItem{
// public SelectItem(String value, String name){
// this.value = value;
// this.name = name;
// }
// String value;
// String name;
//
// public static List<SelectItem> itemListFromMap(Map<String,String> map){
// if( map == null ) return Collections.EMPTY_LIST;
//
// ArrayList<SelectItem> outList = new ArrayList<SelectItem>(map.size());
// for( String key : map.keySet()){
// outList.add( new SelectItem(key, map.get(key)) );
// }
// return outList;
// }
//
// }
public final static String USE_SYSTEM_VALUE = "USE_SYSTEM_VALUE";
private static final Log log = LogFactory.getLog(EditConfiguration.class.getName());
public ModelSelector getWriteModelSelector() {
return writeModelSelector;
}
public void setWriteModelSelector(ModelSelector writeModel) {
if( writeModel != null )
this.writeModelSelector = writeModel;
}
public ModelSelector getQueryModelSelector() {
return queryModelSelector;
}
public void setQueryModelSelector(ModelSelector queryModel) {
if( queryModel != null )
this.queryModelSelector = queryModel;
}
public WDFSelector getWdfSelectorForOptons() {
return wdfSelectorForOptons;
}
public void setWdfSelectorForOptons(WDFSelector wdfForOptons) {
this.wdfSelectorForOptons = wdfForOptons;
}
public ModelSelector getResourceModelSelector() {
return resourceModelSelector;
}
public void setResourceModelSelector(ModelSelector resourceModelSelector) {
if( resourceModelSelector != null )
this.resourceModelSelector = resourceModelSelector;
}
public List<N3Validator> getValidators() {
return validators;
}
public void addValidator( N3Validator validator){
if( this.validators == null )
this.validators = new ArrayList<N3Validator>();
this.validators.add(validator);
}
public void addEditSubmissionPreprocessor( EditSubmissionPreprocessor preprocessor){
if( editSubmissionPreprocessors == null )
editSubmissionPreprocessors = new ArrayList<EditSubmissionPreprocessor>();
editSubmissionPreprocessors.add(preprocessor);
}
public List<EditSubmissionPreprocessor> getEditSubmissionPreprocessors() {
return editSubmissionPreprocessors;
}
public void setTemplate(String template){
this.template = template;
}
public String getTemplate() {
return this.template;
}
public String getSubmitToUrl() {
return submitToUrl;
}
public void setSubmitToUrl(String submitToUrl) {
this.submitToUrl = submitToUrl;
}
public boolean isUpdate(){
return this.getObject() != null && this.getObject().trim().length() > 0;
}
}

View file

@ -1,405 +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;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import edu.cornell.mannlib.vitro.webapp.edit.elements.EditElement;
public class Field {
public enum OptionsType {
LITERALS,
HARDCODED_LITERALS,
STRINGS_VIA_DATATYPE_PROPERTY,
INDIVIDUALS_VIA_OBJECT_PROPERTY,
INDIVIDUALS_VIA_VCLASS,
CHILD_VCLASSES,
CHILD_VCLASSES_WITH_PARENT,
VCLASSGROUP,
FILE,
UNDEFINED,
DATETIME,
DATE,
TIME
};
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( Field.class );
private String name;
/**
* List of basic validators. See BaiscValidation.
*/
private List <String> validators;
/**
* What type of options is this?
*/
private OptionsType optionsType;
/**
* Special class to use for option type
*/
private Class customOptionType;
/**
* Used for building Options when OptionsType is INDIVIDUALS_VIA_OBJECT_PROPERTY
*/
private String predicateUri;
/**
* Used for building Options when OptionsType is INDIVIDUALS_VIA_VCLASS
*/
private String objectClassUri;
/**
* Used for holding the expected/required datatype of the predicate when the predicate is a datatype propertyl.
* this can be a explicit URI or a qname.
* example:
* "this is the literal"^^<http://someuri.com/v1.2#type23>
* or
* "this is the literal"^^someprefix:type23
*/
private String rangeDatatypeUri;
/**
* Used for holding the language of the literal when the predicate is a datatype property.
* This is the lang of the literal. lang strings must be: [a-z]+(-[a-z0-9]+)*
*/
private String rangeLang;
/**
* If this is a Select and it is of OptionsType LITERALS, these are the literals.
*/
private List<List<String>> literalOptions;
/**
* Strings of N3 to add to model.
*/
private List <String> 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 <String> retractions;
private Map<String, String> queryForExisting;
/**
* Property for special edit element.
*/
private EditElement editElement=null;;
/* *********************** Constructors ************************** */
public Field(String config, String varName) {
name=varName;
JSONObject jsonObj = null;
try{
jsonObj = new JSONObject(config);
}catch (JSONException je){
throw new Error(je);
}
originalJson = config;
setValuesFromJson(jsonObj, varName);
}
public Field(JSONObject obj, String varName) {
setValuesFromJson(obj, varName);
}
public Field() {}
private static String[] parameterNames = {"editElement","newResource","validators","optionsType","predicateUri","objectClassUri","rangeDatatypeUri","rangeLang","literalOptions","assertions"};
static{ Arrays.sort(parameterNames); }
private void setValuesFromJson(JSONObject obj, String fieldName){
try{
this.name = fieldName;
setNewResource(obj.getBoolean("newResource"));
validators = EditConfiguration.JsonArrayToStringList(obj.getJSONArray("validators"));
setOptionsType(obj.getString("optionsType"));
predicateUri = obj.getString("predicateUri");
objectClassUri = obj.getString("objectClassUri");
rangeDatatypeUri = obj.getString("rangeDatatypeUri");
if( rangeDatatypeUri != null && rangeDatatypeUri.trim().length() == 0)
rangeDatatypeUri = null;
rangeLang = obj.getString("rangeLang");
if( rangeLang != null && rangeLang.trim().length() == 0)
rangeLang = null;
setLiteralOptions(obj.getJSONArray("literalOptions"));
setAssertions(EditConfiguration.JsonArrayToStringList(obj.getJSONArray("assertions")));
setEditElement( obj, fieldName);
//check for odd parameters
JSONArray names = obj.names();
int size = names.length();
for(int i=0 ; i < size ; i++ ){
String name = (String)names.optString(i);
if( Arrays.binarySearch(parameterNames, name) < 0 )
log.debug("setValuesFromJson(): the field " + fieldName + " has the unrecognized parameter " + name);
}
}catch(JSONException ex){
throw new Error(ex);
}
}
public void setEditElement(EditElement editElement){
this.editElement = editElement;
}
/**
* A field may specify a class for additional features.
*/
private void setEditElement(JSONObject fieldConfigObj, String fieldName) {
String className = fieldConfigObj.optString("editElement");
if( className == null || className.isEmpty() )
return;
setOptionsType(Field.OptionsType.UNDEFINED);
Class clz = null;
try {
clz = Class.forName(className);
} catch (ClassNotFoundException e) {
log.error("Java Class " + className + " not found for field " + name);
return;
} catch (SecurityException e) {
log.error("Problem with Java Class " + className + " for field " + name, e);
return;
} catch (IllegalArgumentException e) {
log.error("Problem with Java Class " +className + " for field " + name, e);
return;
}
Class[] types = new Class[]{ Field.class };
Constructor cons;
try {
cons = clz.getConstructor(types);
} catch (SecurityException e) {
log.error("Problem with Java Class " + className + " for field " + name, e);
return;
} catch (NoSuchMethodException e) {
log.error("Java Class " + className + " must have a constructor that takes a Field.", e);
return;
}
Object[] args = new Object[] { this };
Object obj;
try {
obj = cons.newInstance(args);
} catch (Exception e) {
log.error("Problem with Java Class " + className + " for field " + name, e);
return;
}
editElement = (EditElement)obj;
}
/* ****************** Getters and Setters ******************************* */
public String getName(){
return name;
}
public List<String> getRetractions() {
return retractions;
}
public void setRetractions(List<String> retractions) {
this.retractions = retractions;
}
public List<String> getAssertions() {
return assertions;
}
public void setAssertions(List<String> assertions) {
this.assertions = assertions;
}
public boolean isNewResource() {
return newResource;
}
public void setNewResource(boolean b) {
newResource = b;
}
public List <String> getValidators() {
return validators;
}
public void setValidators(List <String> v) {
validators = v;
}
public OptionsType getOptionsType() {
return optionsType;
}
public void setOptionsType(OptionsType ot) {
optionsType = ot;
}
public void setOptionsType(String s) {
setOptionsType( getOptionForString(s));
}
public static OptionsType getOptionForString(String s){
if( s== null || s.isEmpty() )
return OptionsType.UNDEFINED;
if ("LITERALS".equals(s)) {
return Field.OptionsType.LITERALS;
} else if ("HARDCODED_LITERALS".equals(s)) {
return Field.OptionsType.HARDCODED_LITERALS;
} else if ("STRINGS_VIA_DATATYPE_PROPERTY".equalsIgnoreCase(s)) {
return Field.OptionsType.STRINGS_VIA_DATATYPE_PROPERTY;
} else if ("INDIVIDUALS_VIA_OBJECT_PROPERTY".equalsIgnoreCase(s)) {
return Field.OptionsType.INDIVIDUALS_VIA_OBJECT_PROPERTY;
} else if ("INDIVIDUALS_VIA_VCLASS".equalsIgnoreCase(s)) {
return Field.OptionsType.INDIVIDUALS_VIA_VCLASS;
} else if ("DATETIME".equalsIgnoreCase(s)) {
return Field.OptionsType.DATETIME;
} else if ("CHILD_VCLASSES".equalsIgnoreCase(s)) {
return Field.OptionsType.CHILD_VCLASSES;
} else if ("CHILD_VCLASSES_WITH_PARENT".equalsIgnoreCase(s)) {
return Field.OptionsType.CHILD_VCLASSES_WITH_PARENT;
} else if ("VCLASSGROUP".equalsIgnoreCase(s)) {
return Field.OptionsType.VCLASSGROUP;
} else if ("FILE".equalsIgnoreCase(s)) {
return Field.OptionsType.FILE;
} else if ("DATE".equalsIgnoreCase(s)) {
return Field.OptionsType.DATE;
} else if ("TIME".equalsIgnoreCase(s)) {
return Field.OptionsType.TIME;
} else {
return Field.OptionsType.UNDEFINED;
}
}
public String getPredicateUri() {
return predicateUri;
}
public void setPredicateUri(String s) {
predicateUri = s;
}
public String getObjectClassUri() {
return objectClassUri;
}
public void setObjectClassUri(String s) {
objectClassUri = s;
}
public String getRangeDatatypeUri() {
return rangeDatatypeUri;
}
public void setRangeDatatypeUri(String r) {
if( rangeLang != null && rangeLang.trim().length() > 0 )
throw new IllegalArgumentException("A Field object may not have both rangeDatatypeUri and rangeLanguage set");
rangeDatatypeUri = r;
}
public List <List<String>> getLiteralOptions() {
return literalOptions;
}
public void setLiteralOptions(List<List<String>> literalOptions) {
this.literalOptions = literalOptions;
}
/**
* Expects a JSONArray of JSONArrays like:
* [ ["http://example.org/bob", "bob"] , ["http://example.org/kate", "kate"] ]
*/
private void setLiteralOptions(JSONArray array) {
if( array == null )
literalOptions = Collections.EMPTY_LIST;
literalOptions = Collections.EMPTY_LIST;
List<List<String>> out = new ArrayList<List<String>>( array.length() );
for(int i =0; i<array.length() ; i++){
JSONArray pair = array.optJSONArray(i);
if( pair == null ){
String value = array.optString(i);
if( value != null ){
List<String>option = new ArrayList<String>(2);
option.add(value);
option.add(value);
out.add( option );
} else { log.warn("could not get option list for " + this.name ); }
}else{
if( pair.length() == 0 ){
log.warn("option list too short for " + this.name + ": " + array.opt(i));
continue;
}
if( pair.length() > 2 )
log.warn("option list too long for " + this.name + ": " + array.opt(i) + " using first two items");
List<String>option = new ArrayList<String>(2);
option.add(pair.optString(0));
if( pair.length() > 1 )
option.add(pair.optString(1));
else
option.add(pair.optString(0));
out.add( option );
}
}
literalOptions = out;
}
public String getRangeLang() {
return rangeLang;
}
public void setRangeLang(String rangeLang) {
if( rangeDatatypeUri != null && rangeDatatypeUri.trim().length() > 0)
throw new IllegalArgumentException("A Field object may not have both rangeDatatypeUri and rangeLanguage set");
this.rangeLang = rangeLang;
}
public Field copy(){
Field copy = new Field(this.originalJson, name);
return copy;
}
public EditElement getEditElement(){
return editElement;
}
/* this is mainly for unit testing */
public void setName(String name){
this.name = name;
}
}

View file

@ -1,459 +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;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.vocabulary.OWL;
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.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyStatementDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassGroupDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.jena.WebappDaoFactoryJena;
import edu.cornell.mannlib.vitro.webapp.dao.jena.pellet.PelletListener;
public class SelectListGenerator {
static Log log = LogFactory.getLog(SelectListGenerator.class);
public static Map<String,String> getOptions(
EditConfiguration editConfig,
String fieldName,
WebappDaoFactory wDaoFact){
if( editConfig == null ){
log.error( "fieldToSelectItemList() must be called with a non-null EditConfiguration ");
return Collections.EMPTY_MAP;
}
if( fieldName == null ){
log.error( "fieldToSelectItemList() must be called with a non-null fieldName");
return Collections.EMPTY_MAP;
}
Field field = editConfig.getField(fieldName);
if (field==null) {
log.error("no field \""+fieldName+"\" found from editConfig in SelectListGenerator.getOptions()");
return Collections.EMPTY_MAP;
}
// now create an empty HashMap to populate and return
HashMap <String,String> optionsMap = new LinkedHashMap<String,String>();
// for debugging, keep a count of the number of options populated
int optionsCount=0;
Field.OptionsType optionsType = field.getOptionsType();
String vclassUri = null;
switch (optionsType){
case HARDCODED_LITERALS: // not auto-sorted, and empty values not removed or replaced
List<List<String>> hardcodedLiteralOptions = field.getLiteralOptions();
if (hardcodedLiteralOptions==null) {
log.error("no literalOptions List found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType HARDCODED_LITERALS specified");
return new HashMap <String,String>();
}
for(Object obj: ((Iterable)hardcodedLiteralOptions)){
List<String> literalPair = (List)obj;
String value=(String)literalPair.get(0);
if( value != null){ // allow empty string as a value
String label=(String)literalPair.get(1);
if (label!=null) {
optionsMap.put(value,label);
} else {
optionsMap.put(value, value);
}
++optionsCount;
}
}
break;
case LITERALS:
List<List<String>> literalOptions = field.getLiteralOptions();
if (literalOptions==null) {
log.error("no literalOptions List found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType LITERALS specified");
return new HashMap <String,String>();
}
for(Object obj: ((Iterable)literalOptions)){
List<String> literalPair = (List)obj;
String value=(String)literalPair.get(0);
if( value != null && value.trim().length() > 0){
String label=(String)literalPair.get(1);
if (label!=null && label.trim().length() > 0) {
optionsMap.put(value,label);
} else {
optionsMap.put(value, value);
}
++optionsCount;
}
}
break;
case STRINGS_VIA_DATATYPE_PROPERTY:
log.debug("processing Field \""+fieldName+"\" optionType as a datatype property predicateUri in SelectListGenerator.getOptions()");
String dataPropUri = field.getPredicateUri();
if (dataPropUri==null || dataPropUri.equals("")){
log.error("no predicate dataPropUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType STRINGS_VIA_DATATYPE_PROPERTY specified");
} else {
/* first test to see whether there's a default "leave blank" value specified with the literal options
String defaultOption=null;
if ((defaultOption=getDefaultOption(field))!=null) {
optionsMap.put(LEFT_BLANK, defaultOption);
} */
// now populate the options
log.debug("finding all choices for data property \""+dataPropUri+"\" in SelectListGenerator.getOptions()");
if( wDaoFact == null ) log.error("incoming WebappDaoFactory from request is null in SelectListGenerator.getOptions().");
DataPropertyStatementDao dpsDao = wDaoFact.getDataPropertyStatementDao();
DataPropertyDao dpDao = wDaoFact.getDataPropertyDao();
DataProperty dp = dpDao.getDataPropertyByURI(dataPropUri);
for (Iterator<DataPropertyStatement> i = dpsDao.getDataPropertyStatements(dp).iterator(); i.hasNext();) {
DataPropertyStatement dps = i.next();
if( dps != null ){
optionsMap.put(dps.getData().trim(),dps.getData().trim());
++optionsCount;
}
}
}
break;
case INDIVIDUALS_VIA_OBJECT_PROPERTY:
log.debug("processing Field \""+fieldName+"\" optionType as an object property predicateUri in SelectListGenerator.getOptions()");
String subjectUri = editConfig.getSubjectUri();
if (subjectUri==null || subjectUri.equals("")){
log.error("no subjectUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType INDIVIDUALS_VIA_OBJECTPROPERTY specified");
} else {
String predicateUri = field.getPredicateUri();
if (predicateUri==null || predicateUri.equals("")){
log.error("no predicateUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType INDIVIDUALS_VIA_OBJECTPROPERTY specified");
} else {
// first test to see whether there's a default "leave blank" value specified with the literal options
String defaultOption=null;
if ((defaultOption=getDefaultOption(field))!=null) {
optionsMap.put(LEFT_BLANK, defaultOption);
}
// now populate the options
log.debug("finding range individuals for subject \""+subjectUri+"\" and object property \""+predicateUri+"\" in SelectListGenerator.getOptions()");
if( wDaoFact == null ) log.error("could not get WebappDaoFactory from request in SelectListGenerator.getOptions().");
Individual subject = wDaoFact.getIndividualDao().getIndividualByURI(subjectUri);
if( subject == null ) log.error("could not get individual for subject uri "+subjectUri+" in SelectListGenerator.getOptions()");
ObjectProperty objProp = wDaoFact.getObjectPropertyDao().getObjectPropertyByURI(predicateUri);
if( objProp == null )
log.error("could not get object property for predicate "+predicateUri+" in SelectListGenerator.getOptions()");
List <VClass> vclasses = new ArrayList<VClass>();
vclasses = wDaoFact.getVClassDao().getVClassesForProperty(subject.getVClassURI(),predicateUri);
if( vclasses == null ){
log.error("no owl:Class found for predicate " + predicateUri );
break;
}
if( vclasses.size() == 0 )
log.error("no owl:Class found for predicate " + predicateUri );
List<Individual> individuals = new ArrayList<Individual>();
HashSet<String> uriSet = new HashSet<String>();
long startTime = System.currentTimeMillis();
for ( VClass vclass : vclasses){
for( Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(vclass.getURI(),-1,-1)) {
if( !uriSet.contains(ind.getURI())) {
uriSet.add(ind.getURI());
individuals.add(ind);
}
}
}
List<ObjectPropertyStatement> stmts = subject.getObjectPropertyStatements();
if( stmts == null ) log.error("object properties for subject were null in SelectListGenerator.getOptions()");
individuals = removeIndividualsAlreadyInRange(individuals,stmts,predicateUri,editConfig.getObject());
//Collections.sort(individuals,new compareIndividualsByName());
for( Individual ind : individuals ){
String uri = ind.getURI();
if( uri != null ){
optionsMap.put(uri,ind.getName().trim());
++optionsCount;
}
}
}
}
break;
case INDIVIDUALS_VIA_VCLASS: //so we have a vclass URI
vclassUri = field.getObjectClassUri();
if (vclassUri==null || vclassUri.equals("")){
log.error("no vclassUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType INDIVIDUALS_VIA_VCLASS specified");
} else {
// first test to see whether there's a default "leave blank" value specified with the literal options
String defaultOption=null;
if ((defaultOption=getDefaultOption(field))!=null) {
optionsMap.put(LEFT_BLANK, defaultOption);
}
// now populate the options
if( wDaoFact == null ) log.error("could not get WebappDaoFactory from request in SelectListGenerator.getOptions().");
// if reasoning isn't available, we will also need to add
// individuals asserted in subclasses
boolean inferenceAvailable = false;
if (wDaoFact instanceof WebappDaoFactoryJena) {
PelletListener pl = ((WebappDaoFactoryJena) wDaoFact)
.getPelletListener();
if (pl != null && pl.isConsistent()
&& !pl.isInErrorState()
&& !pl.isReasoning()) {
inferenceAvailable = true;
}
}
VClass vclass = wDaoFact.getVClassDao().getVClassByURI( vclassUri );
if( vclass == null ) {
log.error("Cannot find owl:Class " + vclassUri + " in the model" );
optionsMap.put("", "Could not find class " + vclassUri);
}else{
Map<String, Individual> individualMap = new HashMap<String, Individual>();
for (Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(vclass.getURI(),-1,-1)) {
if (ind.getURI() != null) {
individualMap.put(ind.getURI(), ind);
}
}
if (!inferenceAvailable) {
for (String subclassURI : wDaoFact.getVClassDao().getAllSubClassURIs(vclass.getURI())) {
for (Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(subclassURI,-1,-1)) {
if (ind.getURI() != null) {
individualMap.put(ind.getURI(), ind);
}
}
}
}
List<Individual> individuals = new ArrayList<Individual>();
individuals.addAll(individualMap.values());
Collections.sort(individuals);
for (Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(vclass.getURI(),-1,-1)) {
if (ind.getURI() != null) {
individualMap.put(ind.getURI(), ind);
}
}
if (!inferenceAvailable) {
for (String subclassURI : wDaoFact.getVClassDao().getAllSubClassURIs(vclass.getURI())) {
for (Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(subclassURI,-1,-1)) {
if (ind.getURI() != null) {
individualMap.put(ind.getURI(), ind);
}
}
}
}
individuals.addAll(individualMap.values());
Collections.sort(individuals);
if (individuals.size()==0){
log.error("No individuals of type "+vclass.getName()+" to add to pick list in SelectListGenerator.getOptions()");
optionsMap.put("", "No " + vclass.getName() + " found");
}else{
for( Individual ind : individuals ) {
String uri = ind.getURI();
if( uri != null ) {
optionsMap.put(uri,ind.getName().trim());
++optionsCount;
}
}
}
}
}
break;
case CHILD_VCLASSES: //so we have a vclass URI
vclassUri = field.getObjectClassUri();
if (vclassUri==null || vclassUri.equals("")){
log.error("no vclassUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType CHILD_VCLASSES specified");
} else {
// first test to see whether there's a default "leave blank" value specified with the literal options
String defaultOption=null;
if ((defaultOption=getDefaultOption(field))!=null) {
optionsMap.put(LEFT_BLANK, defaultOption);
}
// now populate the options
if( wDaoFact == null ) log.error("could not get WebappDaoFactory from request in SelectListGenerator.getOptions().");
VClassDao vclassDao = wDaoFact.getVClassDao();
List<String> subClassList = vclassDao.getAllSubClassURIs(vclassUri);
if( subClassList == null || subClassList.size()==0 ) {
log.debug("No subclasses of " + vclassUri + " found in the model so only default value from field's literalOptions will be used" );
} else {
for( String subClassUri : subClassList ) {
VClass subClass = vclassDao.getVClassByURI(subClassUri);
if( subClass != null && !OWL.Nothing.getURI().equals(subClassUri)) {
optionsMap.put(subClassUri,subClass.getName().trim());
++optionsCount;
}
}
}
}
break;
case CHILD_VCLASSES_WITH_PARENT: //so we have a vclass URI
vclassUri = field.getObjectClassUri();
if (vclassUri==null || vclassUri.equals("")){
log.error("no vclassUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType CHILD_VCLASSES specified");
} else {
// first test to see whether there's a default "leave blank" value specified with the literal options
String defaultOption=null;
if ((defaultOption=getDefaultOption(field))!=null) {
optionsMap.put(LEFT_BLANK, defaultOption);
}
// now populate the options
if( wDaoFact == null ) log.error("could not get WebappDaoFactory from request in SelectListGenerator.getOptions().");
VClassDao vclassDao = wDaoFact.getVClassDao();
List<String> subClassList = vclassDao.getAllSubClassURIs(vclassUri);
if( subClassList == null || subClassList.size()==0 ) {
log.debug("No subclasses of " + vclassUri + " found in the model so only default value from field's literalOptions will be used" );
} else {
for( String subClassUri : subClassList ) {
VClass subClass = vclassDao.getVClassByURI(subClassUri);
if( subClass != null && !OWL.Nothing.getURI().equals(subClassUri)) {
optionsMap.put(subClassUri,subClass.getName().trim());
++optionsCount;
}
}
optionsMap.put(vclassUri, "Other");
++optionsCount;
}
}
break;
case VCLASSGROUP:
String classGroupUri = field.getObjectClassUri(); // we're overloading this property to specify the classgroup
if (classGroupUri==null || classGroupUri.equals("")){
log.error("no classGroupUri found for field \""+fieldName+"\" in SelectListGenerator.getOptions() when OptionsType VCLASSGROUP specified");
} else {
// first test to see whether there's a default "leave blank" value specified with the literal options
String defaultOption=null;
if ((defaultOption=getDefaultOption(field))!=null) {
optionsMap.put(LEFT_BLANK, defaultOption);
}
// now populate the options
if( wDaoFact == null ) log.error("could not get WebappDaoFactory from request in SelectListGenerator.getOptions().");
VClassGroupDao vcgd = wDaoFact.getVClassGroupDao();
// Need to call this method to populate the classgroups - otherwise the classgroup class list is empty
List vClassGroups = vcgd.getPublicGroupsWithVClasses();
if (vClassGroups == null) {
log.error("No class groups found, so only default value from field's literalOptions will be used.");
} else {
VClassGroup vClassGroup = null;
for (Object o : vClassGroups) {
VClassGroup vcg = (VClassGroup) o;
if (vcg.getURI().equals(classGroupUri)) {
vClassGroup = vcg;
break;
}
}
if (vClassGroup == null) {
log.error("No class group with uri " + classGroupUri + "found, so only default value from field's literalOptions will be used.");
} else {
List<VClass> vClassList = vClassGroup.getVitroClassList();
if( vClassList == null || vClassList.size()==0 ) {
log.debug("No classes in class group " + classGroupUri + " found in the model, so only default value from field's literalOptions will be used" );
} else {
for( VClass vClass : vClassList ) {
String vClassUri = vClass.getURI();
if( vClass != null && !OWL.Nothing.getURI().equals(vClassUri)) {
optionsMap.put(vClassUri,vClass.getName().trim());
++optionsCount;
}
}
}
}
}
}
break;
case UNDEFINED :
log.error("optionsType \"UNDEFINED\" for Field \""+fieldName+"\" in SelectListGenerator.getOptions()");
break;
default: log.error("unknown optionsType "+optionsType.toString()+" for Field \""+fieldName+"\" in SelectListGenerator.getOptions()");
}
log.debug("added "+optionsCount+" options for field \""+fieldName+"\" in SelectListGenerator.getOptions()");
return optionsMap;
}
/**
* The default option is used when a option list is being auto
* generated from a VClass or an ObjectProperty. If there is an
* item in the literals item list then the name of it will be used
* as the text to display for an empty string value option.
*
* Having an option with an empty string for a Field that expects
* a URI will cause the form processing to assume that the field
* was left blank.
*
* @param field
* @return
*/
private static String getDefaultOption(Field field) {
List <List<String>> defaultOptions = (List<List<String>>) field.getLiteralOptions();
if (defaultOptions!=null) {
for(Object obj: ((Iterable)defaultOptions)) {
List<String> pair = (List<String>)obj;
String value = pair.get(0);
String label = pair.get(1);
if( label != null && label.trim().length() > 0){
return label; // don't want to return a value
}
}
}
return null;
}
// copied from OptionsForPropertyTag.java in the thought that class may be deprecated
private static List<Individual> removeIndividualsAlreadyInRange(List<Individual> individuals,
List<ObjectPropertyStatement> stmts, String predicateUri, String objectUriBeingEdited){
log.debug("starting to check for duplicate range individuals in SelectListGenerator.removeIndividualsAlreadyInRange() ...");
HashSet<String> range = new HashSet<String>();
for(ObjectPropertyStatement ops : stmts){
if( ops.getPropertyURI().equals(predicateUri))
range.add( ops.getObjectURI() );
}
int removeCount=0;
ListIterator<Individual> it = individuals.listIterator();
while(it.hasNext()){
Individual ind = it.next();
if( range.contains( ind.getURI()) && !(ind.getURI().equals(objectUriBeingEdited)) ) {
it.remove();
++removeCount;
}
}
log.debug("removed "+removeCount+" duplicate range individuals");
return individuals;
}
private static final String LEFT_BLANK = "";
}

View file

@ -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;
@ -14,29 +14,17 @@ import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import 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.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.SelectListGeneratorVTwo;
import edu.cornell.mannlib.vitro.webapp.web.MiscWebUtils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.DefaultAddMissingIndividualFormModelPreprocessor;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;

View file

@ -2,41 +2,17 @@
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.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.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.SelectListGeneratorVTwo;
import edu.cornell.mannlib.vitro.webapp.web.MiscWebUtils;
import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch;
/**
* Generates delete form which submits the deletion request to the deletion controller.

View file

@ -8,7 +8,6 @@ import javax.servlet.http.HttpSession;
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.Field;
/**
* Generate the EditConfiguration for the Institutional Internal Class Form.
@ -32,15 +31,9 @@ public class InstitutionalInternalClassForm extends BaseEditConfigurationGenerat
StringList n3ForInternalClass =new StringList( " ?internalClassUri "+INTERNAL_CLASS_ANNOTATION_URI+" \"true\" . " );
editConfig.setN3Required( n3ForInternalClass );
//bdc34: maybe this is redundent with the keys of the fields Map?
//bdc34: maybe this is redundant with the keys of the fields Map?
editConfig.setUrisOnform( new StringList( "internalClassUri" ));
Field field = new Field();
field.setAssertions( n3ForInternalClass );
//maybe field should have a way to get an option list?
//field.setOptionGenerator( new InternalClassOptionGenerator() );
//edit config should have URL to submit the form to
//editConfig.setUrl
//set the url pattern that the client will return to after a successful edit

View file

@ -2,45 +2,26 @@
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;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.vocabulary.RDFS;
import com.hp.hpl.jena.vocabulary.XSD;
import com.hp.hpl.jena.ontology.OntModel;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.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.configuration.validators.AntiXssValidation;
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.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.SelectListGeneratorVTwo;
import edu.cornell.mannlib.vitro.webapp.web.MiscWebUtils;
import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
/**
* Generates the edit configuration for a default property form.

View file

@ -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,32 +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.vocabulary.XSD;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.vocabulary.XSD;
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.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
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.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.SelectListGeneratorVTwo;
import edu.cornell.mannlib.vitro.webapp.web.MiscWebUtils;
import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
/**
* Generates the edit configuration for RDFS Label form.
*

View file

@ -1,18 +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.preprocessors;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
public abstract class BaseEditSubmissionPreprocessor implements
EditSubmissionPreprocessor {
protected EditConfiguration editConfiguration;
public BaseEditSubmissionPreprocessor(EditConfiguration editConfig) {
editConfiguration = editConfig;
}
}

View file

@ -1,69 +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.preprocessors;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.vocabulary.XSD;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
public class CreateLabelFromNameFields extends BaseEditSubmissionPreprocessor {
private static final Log log = LogFactory.getLog(CreateLabelFromNameFields.class.getName());
public CreateLabelFromNameFields(EditConfiguration editConfig) {
super(editConfig);
}
// Create label by concatenating first name, middle name, and last name fields as
// "<last name>, <first name> <middle name>". First name and last name are required;
// middle name is optional.
// rjy7 Using all hard-coded field names for now. If we want to control these, pass in
// a map of field names when creating the preprocessor object.
public void preprocess(EditSubmission editSubmission) {
Map<String, Literal> literalsFromForm = editSubmission.getLiteralsFromForm();
try {
// Create the label string
// Assuming last name and first name fields will be on the form
String lastName = literalsFromForm.get("lastName").getLexicalForm();
String firstName = literalsFromForm.get("firstName").getLexicalForm();
// The form may or may not have a middle name field
String middleName = "";
Literal middleNameLiteral = literalsFromForm.get("middleName");
if (middleNameLiteral != null) {
middleName = middleNameLiteral.getLexicalForm();
}
String label = lastName + ", " + firstName;
if (!StringUtils.isEmpty(middleName)) {
label += " " + middleName;
}
// Add the label to the form literals
Field labelField = editConfiguration.getField("label");
String rangeDatatypeUri = labelField.getRangeDatatypeUri();
if (StringUtils.isEmpty(rangeDatatypeUri)) {
rangeDatatypeUri = XSD.xstring.toString();
}
String rangeLang = labelField.getRangeLang();
// RY Had to change createLiteral method to protected - check w/Brian
Literal labelLiteral = editSubmission.createLiteral(label, rangeDatatypeUri, rangeLang);
literalsFromForm.put("label", labelLiteral);
editSubmission.setLiteralsFromForm(literalsFromForm);
} catch (Exception e) {
log.error("Error retrieving name values from edit submission.");
}
}
}

View file

@ -1,9 +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.preprocessors;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
public interface EditSubmissionPreprocessor {
public void preprocess(EditSubmission editSubmission);
}

View file

@ -1,276 +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.validators;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.datatypes.RDFDatatype;
import com.hp.hpl.jena.datatypes.TypeMapper;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import edu.cornell.mannlib.vitro.webapp.beans.Datatype;
import edu.cornell.mannlib.vitro.webapp.dao.jena.DatatypeDaoJena;
import edu.cornell.mannlib.vitro.webapp.dao.jena.WebappDaoFactoryJena;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
/**
*
*/
public class BasicValidation {
Map<String, List<String>> varsToValidations;
EditConfiguration editConfig;
public BasicValidation(EditConfiguration editConfig, EditSubmission editSub){
this.editConfig = editConfig;
Map<String,List<String>> validatorsForFields = new HashMap<String,List<String>>();
for(String fieldName: editConfig.getFields().keySet()){
Field field = editConfig.getField(fieldName);
validatorsForFields.put(fieldName,field.getValidators());
}
this.varsToValidations = validatorsForFields;
checkValidations();
}
public BasicValidation(Map<String, List<String>> varsToValidations){
this.varsToValidations = varsToValidations;
checkValidations();
}
public Map<String,String> validateUris(Map<String,String> varNamesToValues){
HashMap<String,String> errors = new HashMap<String,String>();
for( String name : varNamesToValues.keySet()){
String value = varNamesToValues.get(name);
List<String> validations = varsToValidations.get(name);
if( validations!= null){
for( String validationType : validations){
String validateMsg = validate(validationType,value);
if( validateMsg != null) {
errors.put(name,validateMsg);
}
}
}
}
return errors;
}
public Map<String,String> validateLiterals(Map<String, Literal> varNamesToValues){
HashMap<String,String> errors = new HashMap<String,String>();
for( String name : editConfig.getLiteralsOnForm() ){
Literal literal = varNamesToValues.get(name);
List<String>validations = varsToValidations.get(name);
if( validations != null ){
// NB this is case-sensitive
boolean isRequiredField = validations.contains("nonempty");
for( String validationType : validations){
String value = null;
try{
if( literal != null ){
value = literal.getString();
}
}catch(Throwable th){
log.debug("could not convert literal to string" , th);
}
// Empty field: if required, include only the empty field
// error message, not a format validation message. If non-required,
// don't do format validation, since that is both unnecessary and may
// incorrectly generate errors.
if (isEmpty(value)) {
if (isRequiredField) {
errors.put(name, REQUIRED_FIELD_EMPTY_MSG);
}
break;
}
String validateMsg = validate(validationType, value);
if( validateMsg != null) {
errors.put(name,validateMsg);
}
}
}
}
return errors;
}
public Map<String,String>validateFiles(Map<String, List<FileItem>> fileItemMap) {
HashMap<String,String> errors = new HashMap<String,String>();
for(String name: editConfig.getFilesOnForm() ){
List<String> validators = varsToValidations.get(name);
for( String validationType : validators){
String validateMsg = validate(validationType, fileItemMap.get(name));
if( validateMsg != null ) {
errors.put(name, validateMsg);
}
}
}
return errors;
}
private String validate(String validationType, List<FileItem> fileItems) {
if( "nonempty".equalsIgnoreCase(validationType)){
if( fileItems == null || fileItems.size() == 0 ){
return "a file must be entered for this field.";
}else{
FileItem fileItem = fileItems.get(0);
if( fileItem == null || fileItem.getName() == null || fileItem.getName().length() < 1 || fileItem.getSize() < 0){
return "a file must be entered for this field.";
}
}
}
return null;
}
/* null indicates success. A returned string is the validation
error message.
*/
public String validate(String validationType, String value){
// Required field validation.
// For literals, testing empty required values in validateLiterals.
// This case may be needed for validation of other field types.
if( "nonempty".equalsIgnoreCase(validationType)){
if( isEmpty(value) )
return REQUIRED_FIELD_EMPTY_MSG;
}
// Format validation
else if("isDate".equalsIgnoreCase(validationType)){
if( isDate( value))
return SUCCESS;
else
return "must be in valid date format mm/dd/yyyy.";
}
else if( validationType.indexOf("datatype:") == 0 ) {
String datatypeURI = validationType.substring(9);
String errorMsg = validateAgainstDatatype( value, datatypeURI );
if ( errorMsg == null ) {
return SUCCESS;
} else {
return errorMsg;
}
} else if ("httpUrl".equalsIgnoreCase(validationType)){
//check if it has http or https, we could do more but for now this is all.
if(! value.startsWith("http://") && ! value.startsWith("https://") ){
return "This URL must start with http:// or https://";
}else{
return SUCCESS;
}
}
//Date not past validation
else if( "dateNotPast".equalsIgnoreCase(validationType)){
//if( ! past (value) )
// return "date must not be in the past";
//Current date
Calendar c = Calendar.getInstance();
//Input
Calendar inputC = Calendar.getInstance();
String yearParamStr, monthParamStr, dayParamStr;
int yearDash = value.indexOf("-");
int monthDash = value.lastIndexOf("-");
if(yearDash != -1 && yearDash != monthDash) {
yearParamStr = value.substring(0, yearDash);
monthParamStr = value.substring(yearDash + 1, monthDash);
dayParamStr = value.substring(monthDash + 1, value.length());
inputC.set(Integer.parseInt(yearParamStr), Integer.parseInt(monthParamStr) - 1, Integer.parseInt(dayParamStr));
if(inputC.before(c)) {
return this.DATE_NOT_PAST_MSG;
//Returning null makes the error message "field is empty" display instead
//return null;
} else {
return SUCCESS;
}
}
}
return null; //
}
private boolean isDate(String in){
return datePattern.matcher(in).matches();
}
private static DatatypeDaoJena ddao = null;
public static synchronized String validateAgainstDatatype( String value, String datatypeURI ) {
if ( ( datatypeURI != null ) && ( datatypeURI.length()>0 ) ) {
RDFDatatype datatype = TypeMapper.getInstance().getSafeTypeByName(datatypeURI);
if ( datatype == null ) {
throw new RuntimeException( datatypeURI + " is not a recognized datatype");
}
if ( datatype.isValid(value) ) {
return null;
} else {
// TODO: better way of getting more friendly names for common datatypes
if (ddao == null) {
ddao = new DatatypeDaoJena(new WebappDaoFactoryJena(ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM)));
}
Datatype dtype = ddao.getDatatypeByURI(datatypeURI);
String dtypeMsg = (dtype != null) ? dtype.getName() : datatypeURI;
return " Please correct this value: must be a valid " + dtypeMsg + ".";
}
}
return null;
}
private void checkValidations(){
List<String> unknown = new ArrayList<String>();
for( String key : varsToValidations.keySet()){
for( String validator : varsToValidations.get(key)){
if( ! basicValidations.contains( validator)) {
if ( ! ( ( validator != null) &&
( validator.indexOf( "datatype:" ) == 0 ) ) ) {
unknown.add(validator);
}
}
}
}
if( unknown.isEmpty() )
return ;
throw new Error( "Unknown basic validators: " + unknown.toArray());
}
private static boolean isEmpty(String value) {
return (value == null || value.trim().length() == 0);
}
private static Pattern urlRX = Pattern.compile("(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)/{0,2}[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?");
/** we use null to indicate success */
public final static String SUCCESS = null;
public final static String REQUIRED_FIELD_EMPTY_MSG = "This field must not be empty.";
public final static String DATE_NOT_PAST_MSG = "Please enter a future target date for publication (past dates are invalid).";
//public final static String MIN_FIELDS_NOT_POPULATED = "Please enter values for at least ";
//public final static String FORM_ERROR_FIELD_ID = "formannotationerrors";
/** regex for strings like "12/31/2004" */
private final String dateRegex = "((1[012])|([1-9]))/((3[10])|([12][0-9])|([1-9]))/[\\d]{4}";
private final Pattern datePattern = Pattern.compile(dateRegex);
static final List<String> basicValidations;
static{
basicValidations = Arrays.asList(
"nonempty","isDate","dateNotPast","httpUrl" ,"anti-xss");
}
private Log log = LogFactory.getLog(BasicValidation.class);
}

View file

@ -1,12 +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.validators;
import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
public interface N3Validator {
public Map<String,String> validate(EditConfiguration editConfig, EditSubmission editSub);
}

View file

@ -1,86 +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.validators;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.rdf.model.Literal;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
public class StartDateBeforeEndDate implements N3Validator {
private String startFieldName;
private String endFieldName;
public StartDateBeforeEndDate(String startFieldName, String endFieldName){
this.startFieldName = startFieldName;
this.endFieldName = endFieldName;
}
public Map<String, String> validate(EditConfiguration editConfig,
EditSubmission editSub) {
Map<String, Literal> existingLiterals = editConfig.getLiteralsInScope();
Literal existingStartDate = existingLiterals.get(startFieldName);
Literal existingEndDate = existingLiterals.get(endFieldName);
Map<String, Literal> literalsFromForm = editSub.getLiteralsFromForm();
Literal formStartDate = literalsFromForm.get(startFieldName);
Literal formEndDate = literalsFromForm.get(endFieldName);
Map<String, String> errors = new HashMap<String, String>();
if (formStartDate != null && formEndDate != null) {
errors.putAll(checkDateLiterals(formStartDate, formEndDate));
} else if (formStartDate != null && existingEndDate != null) {
errors.putAll(checkDateLiterals(formStartDate, existingEndDate));
} else if (existingStartDate != null && formEndDate != null) {
errors.putAll(checkDateLiterals(existingStartDate, formEndDate));
} else if (existingStartDate != null && existingEndDate != null) {
errors
.putAll(checkDateLiterals(existingStartDate,
existingEndDate));
}
if (errors.size() != 0)
return errors;
else
return null;
}
private Map<String, String> checkDateLiterals(Literal startLit,
Literal endLit) {
Map<String, String> errors = new HashMap<String, String>();
Calendar startDate = getDateFromLiteral(startLit);
Calendar endDate = getDateFromLiteral(endLit);
try {
if (startDate.compareTo(endDate) > 0) {
errors.put(startFieldName, "Start date cannot follow end date");
errors.put(endFieldName, "End date cannot precede start date");
}
} catch (NullPointerException npe){
log.error("Cannot compare date to null.");
} catch (IllegalArgumentException iae) {
log.error("IllegalArgumentException");
}
return errors;
}
private Calendar getDateFromLiteral(Literal dateLit) {
String[] date = dateLit.getLexicalForm().split("-");
int year = Integer.parseInt(date[0]);
int day = date.length < 3 ? 1 : Integer.parseInt(date[2]);
int month = date.length < 2 ? 0 : Integer.parseInt(date[1]);
Calendar c = Calendar.getInstance();
c.set(year, month, day);
return c;
}
private Log log = LogFactory.getLog(StartDateBeforeEndDate.class);
}

View file

@ -1,68 +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.validators;
import java.util.HashMap;
import java.util.Map;
import com.hp.hpl.jena.rdf.model.Literal;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
public class StartYearBeforeEndYear implements N3Validator {
private String startFieldName;
private String endFieldName;
public StartYearBeforeEndYear(String startFieldName, String endFieldName){
this.startFieldName = startFieldName;
this.endFieldName = endFieldName;
}
public Map<String, String> validate(EditConfiguration editConfig,
EditSubmission editSub) {
Map<String, Literal> existingLiterals = editConfig.getLiteralsInScope();
Literal existingStartYear = existingLiterals.get(startFieldName);
Literal existingEndYear = existingLiterals.get(endFieldName);
Map<String, Literal> literalsFromForm = editSub.getLiteralsFromForm();
Literal formStartYear = literalsFromForm.get(startFieldName);
Literal formEndYear = literalsFromForm.get(endFieldName);
Map<String, String> errors = new HashMap<String, String>();
if (formStartYear != null && formEndYear != null) {
errors.putAll(checkDateLiterals(formStartYear, formEndYear));
} else if (formStartYear != null && existingEndYear != null) {
errors.putAll(checkDateLiterals(formStartYear, existingEndYear));
} else if (existingStartYear != null && formEndYear != null) {
errors.putAll(checkDateLiterals(existingStartYear, formEndYear));
} else if (existingStartYear != null && existingEndYear != null) {
errors
.putAll(checkDateLiterals(existingStartYear,
existingEndYear));
}
if (errors.size() != 0)
return errors;
else
return null;
}
private Map<String, String> checkDateLiterals(Literal startLit,
Literal endLit) {
Map<String, String> errors = new HashMap<String, String>();
try {
int start = Integer.parseInt(startLit.getLexicalForm());
int end = Integer.parseInt(endLit.getLexicalForm());
if (end < start) {
errors.put(startFieldName, "Start year must be before end year");
errors.put(endFieldName, "End year must be after start year");
}
} catch (NumberFormatException nfe) {
errors.put(startFieldName, "could not format star or end date");
errors.put(endFieldName, "could not format star or end date");
}
return errors;
}
}

View file

@ -1,77 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.rdf.model.Model;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerHttpServlet;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditN3Generator;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
/**
* N3 based deletion.
*
* Build up the n3 using the fields from an edit configuration and then remove
* all of those statements from the systems model. In general this should
* do the same thing as an update with processRdfForm2.jsp but it should just
* build the assertions graph and remove that from the system model.
*
*/
public class n3DeleteController extends FreemarkerHttpServlet {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(n3DeleteController.class);
@Override
protected ResponseValues processRequest(VitroRequest vreq){
/* the post parameters seem to get consumed by the parsing so
* we have to make a copy. */
Map<String, String[]> queryParameters = null;
queryParameters = vreq.getParameterMap();
List<String> errorMessages = new ArrayList<String>();
HttpSession session = vreq.getSession();
EditConfiguration editConfiguration = EditConfiguration.getConfigFromSession(session, vreq);
if(editConfiguration == null){
//TODO: previously forwarded to noEditConfigFound.jsp
//probably needs to forward to something else now
}
EditN3Generator n3Subber = editConfiguration.getN3Generator();
EditSubmission submission = new EditSubmission(queryParameters, editConfiguration);
Map<String, String> errors = submission.getValidationErrors();
EditSubmission.putEditSubmissionInSession(session, submission);
if(errors != null && !errors.isEmpty()){
String form = editConfiguration.getFormUrl();
vreq.setAttribute("formUrl", form);
//TODO: forwards to form. Needs to change
return null;
}
List<Model> requiredAssertionsToDelete = new ArrayList<Model>();
List<Model> optionalAssertionsToDelete = new ArrayList<Model>();
boolean requestIsAValidDelete = editConfiguration.getObject() != null && editConfiguration.getObject().trim().length() > 0;
return null;
}
}

View file

@ -1,356 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.vocabulary.XSD;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
/**
* Builds the N3 strings for the given EditConfiguration, model
* and EditSubmission. Main responsibility is the proper substitution
* of URI and literal strings in to the template N3.
*
*
*/
public class EditN3Generator {
EditConfiguration editConfig;
static final Log log = LogFactory.getLog( EditN3Generator.class );
public EditN3Generator( EditConfiguration editConfig ){
this.editConfig = editConfig;
}
public List<String> generateN3(EditSubmission editSub, Model model){
return Collections.EMPTY_LIST;
}
public static List<String> subInUris(Map<String,String> varsToVals, List<String> targets){
if( varsToVals == null || varsToVals.isEmpty() ) return targets;
ArrayList<String> outv = new ArrayList<String>();
for( String target : targets){
String temp = target;
for( String key : varsToVals.keySet()) {
temp = subInUris( key, varsToVals.get(key), temp) ;
}
outv.add(temp);
}
return outv;
}
public static String subInUris(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
out = target.replaceAll(varRegex,"<"+Matcher.quoteReplacement(value)+"> ");
if( out != null && out.length() > 0 )
return out;
else
return target;
}
public static List<String>subInUris(String var, String value, List<String> targets){
ArrayList<String> outv =new ArrayList<String>();
for( String target : targets){
outv.add( subInUris( var,value, target) ) ;
}
return outv;
}
public List<String> subInLiterals(Map<String, Literal> varsToVals, List<String> targets){
if( varsToVals == null || varsToVals.isEmpty()) return targets;
ArrayList<String> outv =new ArrayList<String>();
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 List<String>subInLiterals(String var, String value, List<String> targets){
// ArrayList<String> outv =new ArrayList<String>();
// 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<String,List<String>> substituteIntoValues
(Map<String,String> varsToUris,
Map<String,Literal> varsToLiterals,
Map<String,List<String>> namesToN3 )
{
Map<String,List<String>> outHash = new HashMap<String,List<String>>();
if (namesToN3==null) {
return outHash;
} else if (namesToN3.isEmpty()) {
return outHash;
} else {
for(String fieldName : namesToN3.keySet()){
List<String> n3strings = namesToN3.get(fieldName);
List<String> newList = new ArrayList<String>();
if( varsToUris != null)
newList = subInUris(varsToUris, n3strings);
if( varsToLiterals != null)
newList = subInLiterals(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
return in;
}
/*
* bdc34 2008-07-33
*
* The following methods are from
* HP's Jena project ver 2.5.5
* Found in file Jena-2.5.5/src/com/hp/hpl/jena/n3/N3JenaWriterCommon.java
*
* The following copyright statement applies to these methods.
*/
/*
* (c) Copyright 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Hewlett-Packard Development Company, LP
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
protected String formatLiteral(Literal literal)
{
String datatype = literal.getDatatypeURI() ;
String lang = literal.getLanguage() ;
String s = literal.getLexicalForm() ;
if ( datatype != null )
{
// Special form we know how to handle?
// Assume valid text
if ( datatype.equals(XSD.integer.getURI()) )
{
try {
new java.math.BigInteger(s) ;
return s ;
} catch (NumberFormatException nfe) {}
// No luck. Continue.
// Continuing is always safe.
}
if ( datatype.equals(XSD.decimal.getURI()) )
{
// Must have ., can't have e or E
if ( s.indexOf('.') >= 0 &&
s.indexOf('e') == -1 && s.indexOf('E') == -1 )
{
// See if parsable.
try {
BigDecimal d = new BigDecimal(s) ;
return s ;
} catch (NumberFormatException nfe) {}
}
}
if ( datatype.equals(XSD.xdouble.getURI()) )
{
// Must have 'e' or 'E' (N3 and Turtle now read 2.3 as a decimal).
if ( s.indexOf('e') >= 0 ||
s.indexOf('E') >= 0 )
{
try {
// Validate it.
Double.parseDouble(s) ;
return s ;
} catch (NumberFormatException nfe) {}
// No luck. Continue.
}
}
}
// Format the text - with escaping.
StringBuffer sbuff = new StringBuffer() ;
String quoteMarks = "\"" ;
sbuff.append(quoteMarks);
pyString(sbuff, s ) ;
sbuff.append(quoteMarks);
// Format the language tag
if ( lang != null && lang.length()>0)
{
sbuff.append("@") ;
sbuff.append(lang) ;
}
// Format the datatype
if ( datatype != null )
{
sbuff.append("^^") ;
sbuff.append(formatURI(datatype)) ;
}
return sbuff.toString() ;
}
/*
*
* see http://www.python.org/doc/2.5.2/ref/strings.html
* or see jena's n3 grammar jena/src/com/hp/hpl/jena/n3/n3.g
*/
protected static void pyString(StringBuffer sbuff, String s)
{
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// Escape escapes and quotes
if (c == '\\' || c == '"' )
{
sbuff.append('\\') ;
sbuff.append(c) ;
continue ;
}
// Whitespace
if (c == '\n'){ sbuff.append("\\n");continue; }
if (c == '\t'){ sbuff.append("\\t");continue; }
if (c == '\r'){ sbuff.append("\\r");continue; }
if (c == '\f'){ sbuff.append("\\f");continue; }
if (c == '\b'){ sbuff.append("\\b");continue; }
if( c == 7 ) { sbuff.append("\\a");continue; }
// Output as is (subject to UTF-8 encoding on output that is)
sbuff.append(c) ;
// // Unicode escapes
// // c < 32, c >= 127, not whitespace or other specials
// String hexstr = Integer.toHexString(c).toUpperCase();
// int pad = 4 - hexstr.length();
// sbuff.append("\\u");
// for (; pad > 0; pad--)
// sbuff.append("0");
// sbuff.append(hexstr);
}
}
protected String formatURI(String uriStr)
{
// Not as a qname - write as a quoted URIref
// Should we unicode escape here?
// It should be right - the writer should be UTF-8 on output.
return "<"+uriStr+">" ;
}
/*************************************************************************
* End code taken from the Jena project and Hewlett-Packard
*************************************************************************/
}

View file

@ -1,490 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.joda.time.IllegalFieldValueException;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.json.JSONObject;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.vocabulary.XSD;
import edu.cornell.mannlib.vitro.webapp.edit.EditLiteral;
import edu.cornell.mannlib.vitro.webapp.edit.elements.EditElement;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmission;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.BasicValidation;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.N3Validator;
/**
* @deprecated use {@link MultiValueEditSubmission}
*/
public class EditSubmission {
String editKey;
private Map<String,Literal> literalsFromForm ;
private Map<String,String> urisFromForm ;
private Map<String,String> validationErrors;
private BasicValidation basicValidation;
private Map<String, List<FileItem>> filesFromForm;
private static Model literalCreationModel;
static{
literalCreationModel = ModelFactory.createDefaultModel();
}
public EditSubmission(Map<String,String[]> queryParameters, EditConfiguration editConfig){
if( editConfig == null )
throw new Error("EditSubmission needs an EditConfiguration");
this.editKey = editConfig.getEditKey();
if( this.editKey == null || this.editKey.trim().length() == 0)
throw new Error("EditSubmission needs an 'editKey' parameter from the EditConfiguration");
validationErrors = new HashMap<String,String>();
this.urisFromForm = new HashMap<String,String>();
for( String var: editConfig.getUrisOnform() ){
String[] valuesArray = queryParameters.get( var );
String uri = null;
List<String> values = (valuesArray != null) ? Arrays.asList(valuesArray) : null;
if( values != null && values.size() > 0){
if( values.size() == 1 ) {
uri = values.get(0);
} else if( values.size() > 1 ){
uri = values.get(0);
log.error("Cannot yet handle multiple URIs for a single field, using first URI on list");
}
urisFromForm.put(var,uri);
} else {
log.debug("No value found for query parameter " + var);
}
//check to see if a URI field from the form was blank but was intended to create a new URI
if( uri != null && uri.length() == 0 && editConfig.getNewResources().containsKey(var) ){
log.debug("A new resource URI will be made for var " + var + " since it was blank on the form.");
urisFromForm.remove(var);
}
}
this.literalsFromForm =new HashMap<String,Literal>();
for(String var: editConfig.getLiteralsOnForm() ){
Field field = editConfig.getField(var);
if( field == null ) {
log.error("could not find field " + var + " in EditConfiguration" );
continue;
}
if( field.getOptionsType() == Field.OptionsType.DATETIME ||
XSD.dateTime.getURI().equals(field.getRangeDatatypeUri()) ) {
Literal literal = getDateTime(queryParameters, var);
if( literal != null){
literalsFromForm.put(var, literal);
} else {
log.debug("datetime fields for parameter " + var + " were not on form" );
}
} else if( field.getOptionsType() == Field.OptionsType.DATE ||
XSD.date.getURI().equals(field.getRangeDatatypeUri()) ){
Literal literal = getDate(queryParameters, var);
if( literal != null){
literalsFromForm.put(var, literal);
} else {
log.debug("date fields for parameter " + var + " were not on form" );
}
} else if( field.getOptionsType() == Field.OptionsType.TIME ||
XSD.time.getURI().equals(field.getRangeDatatypeUri()) ){
Literal literal = getTime(queryParameters, var);
if( literal != null){
literalsFromForm.put(var, literal);
} else {
log.debug("time fields for parameter " + var + " were not on form" );
}
} else if( field.getEditElement() != null ){
log.debug("skipping field with edit element, it should not be in literals on form list");
}else{
String[] valuesArray = queryParameters.get(var);
List<String> valueList = (valuesArray != null) ? Arrays.asList(valuesArray) : null;
if( valueList != null && valueList.size() > 0 ) {
String value = valueList.get(0);
// remove any characters that are not valid in XML 1.0
// from user input so they don't cause problems
// with model serialization
value = EditN3Utils.stripInvalidXMLChars(value);
if (!StringUtils.isEmpty(value)) {
literalsFromForm.put(var, createLiteral(
value,
field.getRangeDatatypeUri(),
field.getRangeLang()));
}
if(valueList != null && valueList.size() > 1 )
log.debug("For field " + var +", cannot yet handle multiple " +
"Literals for a single field, using first Literal on list");
}else{
log.debug("could not find value for parameter " + var );
}
}
}
if( log.isDebugEnabled() ){
for( String key : literalsFromForm.keySet() ){
log.debug( key + " literal " + literalsFromForm.get(key) );
}
for( String key : urisFromForm.keySet() ){
log.debug( key + " uri " + urisFromForm.get(key) );
}
}
processEditElementFields(editConfig,queryParameters);
this.basicValidation = new BasicValidation(editConfig,this);
Map<String,String> errors = basicValidation.validateUris( urisFromForm );
if( errors != null ) {
validationErrors.putAll( errors );
}
errors = basicValidation.validateLiterals( literalsFromForm );
if( errors != null ) {
validationErrors.putAll( errors);
}
if(editConfig.getValidators() != null ){
for( N3Validator validator : editConfig.getValidators()){
if( validator != null ){
errors = validator.validate(editConfig, this);
if ( errors != null )
validationErrors.putAll(errors);
}
}
}
if( log.isDebugEnabled() )
log.debug( this.toString() );
}
protected void processEditElementFields(EditConfiguration editConfig, Map<String,String[]> queryParameters ){
for( String fieldName : editConfig.getFields().keySet()){
Field field = editConfig.getFields().get(fieldName);
if( field != null && field.getEditElement() != null ){
EditElement element = field.getEditElement();
log.debug("Checking EditElement for field " + fieldName + " type: " + element.getClass().getName());
//check for validation error messages
Map<String,String> errMsgs =
element.getValidationMessages(fieldName, editConfig, queryParameters);
validationErrors.putAll(errMsgs);
if( errMsgs == null || errMsgs.isEmpty()){
//only check for uris and literals when element has no validation errors
Map<String,String> urisFromElement = element.getURIs(fieldName, editConfig, queryParameters);
if( urisFromElement != null )
urisFromForm.putAll(urisFromElement);
Map<String,Literal> literalsFromElement = element.getLiterals(fieldName, editConfig, queryParameters);
if( literalsFromElement != null )
literalsFromForm.putAll(literalsFromElement);
}else{
log.debug("got validation errors for field " + fieldName + " not processing field for literals or URIs");
}
}
}
}
public EditSubmission(Map<String, String[]> queryParameters, EditConfiguration editConfig,
Map<String, List<FileItem>> fileItems) {
this(queryParameters,editConfig);
this.filesFromForm = fileItems;
validationErrors.putAll(this.basicValidation.validateFiles( fileItems ) );
}
public Literal createLiteral(String value, String datatypeUri, String lang) {
if( datatypeUri != null ){
if( "http://www.w3.org/2001/XMLSchema:anyURI".equals(datatypeUri) ){
try {
return literalCreationModel.createTypedLiteral( URLEncoder.encode(value, "UTF8"), datatypeUri);
} catch (UnsupportedEncodingException e) {
log.error(e, e);
}
}
return literalCreationModel.createTypedLiteral(value, datatypeUri);
}else if( lang != null && lang.length() > 0 )
return literalCreationModel.createLiteral(value, lang);
else
return ResourceFactory.createPlainLiteral(value);
}
/**
* need to generate something like
* "2008-03-14T00:00:00"^^<http://www.w3.org/2001/XMLSchema#dateTime>
*/
public Literal getDateTime(Map<String,String[]> queryParameters,String fieldName){
DateTime dt = null;
List<String> year = Arrays.asList(queryParameters.get("year"+ fieldName));
List<String> month = Arrays.asList(queryParameters.get("month" + fieldName));
List<String> day = Arrays.asList(queryParameters.get("day" + fieldName));
List<String> hour = Arrays.asList(queryParameters.get("hour"+ fieldName));
List<String> minute = Arrays.asList(queryParameters.get("minute" + fieldName));
if( year == null || year.size() == 0 ||
month == null || month.size() == 0 ||
day == null || day.size() == 0 ||
hour == null || hour.size() == 0 ||
minute == null || minute.size() == 0 ){
//log.info("Could not find query parameter values for date field " + fieldName );
} /* else if( year.size() > 1 || month.size() > 1 || day.size() > 1 || hour.size() > 1 || minute.size() > 1 ){
log.info("Cannot yet handle multiple values for the same field ");
} */
String yearParamStr = year.get(0);
String monthParamStr = month.get(0);
String dayParamStr = day.get(0);
String hourParamStr = hour.get(0);
String minuteParamStr = minute.get(0);
// if all fields are blank, just return a null value
if (yearParamStr.length() == 0 &&
monthParamStr.length() == 0 &&
dayParamStr.length() == 0 &&
hourParamStr.length() == 0 &&
minuteParamStr.length() == 0) {
return null;
}
DateTimeFormatter dateFmt = DateTimeFormat.forPattern("yyyyMMdd:HH:mm");
try{
dt = dateFmt.parseDateTime(yearParamStr + monthParamStr + dayParamStr + ':' + hourParamStr + ':' + minuteParamStr);
String dateStr = dformater.print(dt);
return new EditLiteral(dateStr,DATE_TIME_URI, null );
}catch(IllegalFieldValueException ifve){
validationErrors.put(fieldName, ifve.getLocalizedMessage());
return null;
}
}
/**
* need to generate something like
* "09:10:11"^^<http://www.w3.org/2001/XMLSchema#time>
*/
public Literal getTime(Map<String,String[]> queryParameters,String fieldName) {
List<String> hour = Arrays.asList(queryParameters.get("hour" + fieldName));
List<String> minute = Arrays.asList(queryParameters.get("minute" + fieldName));
if ( hour == null || hour.size() == 0 ||
minute == null || minute.size() == 0 ) {
log.info("Could not find query parameter values for time field " + fieldName);
validationErrors.put(fieldName, "time must be supplied");
return null;
}
int hourInt = -1;
int minuteInt = -1;
String hourParamStr = hour.get(0);
String minuteParamStr = minute.get(0);
// if all fields are blank, just return a null value
if (hourParamStr.length() == 0 && minuteParamStr.length() == 0) {
return null;
}
String errors = "";
try{
hourInt = Integer.parseInt(hour.get(0));
if (hourInt < 0 || hourInt > 23) {
throw new NumberFormatException();
}
} catch( NumberFormatException nfe ) {
errors += "Please enter a valid hour. ";
}
try{
minuteInt = Integer.parseInt(minute.get(0));
if (minuteInt < 0 || minuteInt > 59) {
throw new NumberFormatException();
}
} catch( NumberFormatException nfe ) {
errors += "Please enter a valid minute. ";
}
if( errors.length() > 0 ){
validationErrors.put( fieldName, errors);
return null;
}
String hourStr = (hourInt < 10) ? "0" + Integer.toString(hourInt) : Integer.toString(hourInt);
String minuteStr = (minuteInt < 10) ? "0" + Integer.toString(minuteInt) : Integer.toString(minuteInt);
String secondStr = "00";
return new EditLiteral(hourStr + ":" + minuteStr + ":" + secondStr, TIME_URI, null);
}
/**
* need to generate something like
* "2008-03-14"^^<http://www.w3.org/2001/XMLSchema#date>
*/
public Literal getDate(Map<String,String[]> queryParameters,String fieldName){
DateTime dt = null;
List<String> year = Arrays.asList(queryParameters.get("year"+ fieldName));
List<String> month = Arrays.asList(queryParameters.get("month" + fieldName));
List<String> day = Arrays.asList(queryParameters.get("day" + fieldName));
if( year == null || year.size() == 0 ||
month == null || month.size() == 0 ||
day == null || day.size() == 0 ){
log.info("Could not find query parameter values for date field " + fieldName );
validationErrors.put( fieldName, "date must be supplied");
return null;
}
String yearParamStr = year.get(0);
String monthParamStr = month.get(0);
String dayParamStr = day.get(0);
// if all fields are blank, just return a null value
if (yearParamStr.length() == 0 &&
monthParamStr.length() == 0 &&
dayParamStr.length() == 0) {
return null;
}
String errors = "";
try{ Integer.parseInt(yearParamStr); }
catch( NumberFormatException nfe )
{ errors += "Please enter a valid year. "; }
try{ Integer.parseInt(monthParamStr); }
catch( NumberFormatException nfe )
{ errors += "Please enter a valid month. "; }
try{ Integer.parseInt(dayParamStr); }
catch( NumberFormatException nfe )
{ errors += "Please enter a valid day. "; }
if( errors.length() > 0 ){
validationErrors.put( fieldName, errors);
return null;
}
//Removing this
/*
boolean compareCurrentDate = false;
String[] dateNotPastArgs = queryParameters.get("validDateParam");
if(dateNotPastArgs != null && dateNotPastArgs.length > 0) {
compareCurrentDate = (dateNotPastArgs[0].equals("dateNotPast"));
}*/
try{
dt = dateFormater.parseDateTime(year.get(0) +'-'+ month.get(0) +'-'+ day.get(0));
String dateStr = dateFormater.print(dt);
return new EditLiteral(dateStr,DATE_URI, null );
}catch(IllegalFieldValueException ifve){
validationErrors.put( fieldName, ifve.getLocalizedMessage() );
return null;
}
}
private static final String DATE_TIME_URI = XSD.dateTime.getURI();
private static final String DATE_URI = XSD.date.getURI();
private static final String TIME_URI = XSD.time.getURI();
private static DateTimeFormatter dformater = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:00");
private static DateTimeFormatter dateFormater = DateTimeFormat.forPattern("yyyy-MM-dd");
public Map<String,String> getValidationErrors(){
return validationErrors;
}
public Map<String, Literal> getLiteralsFromForm() {
return literalsFromForm;
}
public Map<String, String> getUrisFromForm() {
return urisFromForm;
}
public void setLiteralsFromForm(Map<String, Literal> literalsFromForm) {
this.literalsFromForm = literalsFromForm;
}
public void setUrisFromForm(Map<String, String> urisFromForm) {
this.urisFromForm = urisFromForm;
}
public String toString(){
String[] names ={
"literalsFromForm",
"urisFromForm","validationErrors","basicValidation"
};
JSONObject obj = new JSONObject(this,names);
return obj.toString();
}
/* *************** Static utility methods to get EditSub from Session *********** */
public static EditSubmission getEditSubmissionFromSession(HttpSession sess, EditConfiguration editConfig){
Map<String,EditSubmission> submissions = (Map<String,EditSubmission>)sess.getAttribute("EditSubmissions");
if( submissions == null )
return null;
if( editConfig != null )
return submissions.get( editConfig.getEditKey() ); //this might be null
else
return null;
}
public static void putEditSubmissionInSession(HttpSession sess, EditSubmission editSub){
Map<String,EditSubmission> submissions = (Map<String,EditSubmission>)sess.getAttribute("EditSubmissions");
if( submissions == null ){
submissions = new HashMap<String,EditSubmission>();
sess.setAttribute("EditSubmissions",submissions);
}
submissions.put(editSub.editKey, editSub);
}
public static void clearEditSubmissionInSession(HttpSession sess, EditSubmission editSub){
if( sess == null) return;
if( editSub == null ) return;
Map<String,EditSubmission> submissions = (Map<String,EditSubmission>)sess.getAttribute("EditSubmissions");
if( submissions == null ){
throw new Error("EditSubmission: could not get a Map of EditSubmissions from the session.");
}
submissions.remove( editSub.editKey );
}
public static void clearAllEditSubmissionsInSession(HttpSession sess ){
if( sess == null) return;
sess.removeAttribute("editSubmission");
}
public static Map<String, String[]> convertParams(
Map<String, List<String>> queryParameters) {
HashMap<String,String[]> out = new HashMap<String,String[]>();
for( String key : queryParameters.keySet()){
List item = queryParameters.get(key);
out.put(key, (String[])item.toArray(new String[item.size()]));
}
return out;
}
private Log log = LogFactory.getLog(EditSubmission.class);
}

View file

@ -2,8 +2,6 @@
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

View file

@ -1,235 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit;
import com.hp.hpl.jena.query.*;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Resource;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.ArrayList;
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 SparqlEvaluate {
private static Log log = LogFactory.getLog( SparqlEvaluate.class );
Model model;
public SparqlEvaluate(Model model){
if( model == null ) throw new Error("SparqlEvaluate must be passed a Model");
this.model = model;
}
public void evaluateForAdditionalUris( EditConfiguration editConfig ){
Map<String,String> varsToUris = sparqlEvaluateForUris(editConfig, editConfig.getSparqlForAdditionalUrisInScope());
editConfig.getUrisInScope().putAll(varsToUris);
}
public void evalulateForAdditionalLiterals( EditConfiguration editConfig ){
Map<String,Literal> varsToLiterals = sparqlEvaluateForLiterals(editConfig, editConfig.getSparqlForAdditionalLiteralsInScope());
editConfig.getLiteralsInScope().putAll(varsToLiterals);
}
public void evaluateForExistingUris( EditConfiguration editConfig){
Map<String,String> varsToUris = sparqlEvaluateForUris(editConfig, editConfig.getSparqlForExistingUris());
editConfig.getUrisInScope().putAll(varsToUris);
}
public void evaluateForExistingLiterals( EditConfiguration editConfig){
Map<String,Literal> varsToLiterals = sparqlEvaluateForLiterals(editConfig, editConfig.getSparqlForExistingLiterals());
editConfig.getLiteralsInScope().putAll(varsToLiterals);
}
// public Map<String,String> sparqlEvaluateForExistingToUris(Map<String,String> varToSpqrql){
// Map<String,String> varToUris = new HashMap<String,String>();
// for(String var : varToSpqrql.keySet()){
// varToUris.put(var, queryToUri( varToSpqrql.get(var) ));
// }
// return varToUris;
// }
//
// public Map<String,String> sparqlEvaluateForAdditionalLiterals(Map<String,String> varToSpqrql){
// Map<String,String> varToLiterals = new HashMap<String,String>();
// for(String var : varToSpqrql.keySet()){
// varToLiterals.put(var, queryToLiteral( varToSpqrql.get(var) ));
// }
// return varToLiterals;
// }
// private Map<String,String> sparqlEvaluateForExistingToUris( EditConfiguration editConfig ) {
// Map<String,String> varToSpqrql = editConfig.getSparqlForExistingUris();
// Map<String,String> uriScope = editConfig.getUrisInScope();
// Map<String,Literal> literalScope = editConfig.getLiteralsInScope();
//
// Map<String,String> varToUris = new HashMap<String,String>();
//
// for(String var : varToSpqrql.keySet()){
// String query = varToSpqrql.get(var);
// List<String> queryStrings = new ArrayList <String>();
// queryStrings.add(query);
// queryStrings= editConfig.getN3Generator().subInUris(uriScope, queryStrings);
// queryStrings = editConfig.getN3Generator().subInLiterals(literalScope,queryStrings);
// varToUris.put(var, queryToUri( queryStrings.get(0) )); //might result in (key -> null)
// }
//
// return varToUris;
// }
public Map<String,Literal> sparqlEvaluateForLiterals( EditConfiguration editConfig, Map<String,String> varToSparql) {
Map<String,String> uriScope = editConfig.getUrisInScope();
Map<String,Literal> literalScope = editConfig.getLiteralsInScope();
Map<String,Literal> varToLiterals = new HashMap<String,Literal>();
for(String var : varToSparql.keySet()){
String query = varToSparql.get(var);
/* skip if var set to use a system generated value */
if( query == null || EditConfiguration.USE_SYSTEM_VALUE.equals( query ))
continue;
List<String> queryStrings = new ArrayList <String>();
queryStrings.add( query );
queryStrings= editConfig.getN3Generator().subInUris(uriScope, queryStrings);
queryStrings = editConfig.getN3Generator().subInLiterals(literalScope,queryStrings);
varToLiterals.put(var, queryToLiteral( queryStrings.get(0) )); //might result in (key -> null)
}
return varToLiterals;
}
public Map<String,String> sparqlEvaluateForUris( EditConfiguration editConfig, Map<String,String>varToSparql) {
Map<String,String> uriScope = editConfig.getUrisInScope();
Map<String,Literal> literalScope = editConfig.getLiteralsInScope();
Map<String,String> varToUris = new HashMap<String,String>();
for(String var : varToSparql.keySet()){
String query = varToSparql.get(var);
/* skip if var set to use a system generated value */
if( query == null || EditConfiguration.USE_SYSTEM_VALUE.equals( query ))
continue;
List<String> queryStrings = new ArrayList <String>();
queryStrings.add(query);
queryStrings= editConfig.getN3Generator().subInUris(uriScope, queryStrings);
queryStrings = editConfig.getN3Generator().subInLiterals(literalScope,queryStrings);
String uriFromQuery = queryToUri( queryStrings.get(0) );
if( uriFromQuery != null )
{
//Added parens and output
varToUris.put(var, uriFromQuery);
}
else
log.debug("sparqlEvaluateForUris(): for var " + var
+ " the following query evaluated to null:\n"+queryStrings.get(0)+"\n(end of query)\n");
}
return varToUris;
}
// public Map<String,Literal> sparqlEvaluateForAdditionalLiterals( EditConfiguration editConfig) {
// Map<String,String> varToSpqrql = editConfig.getSparqlForAdditionalLiteralsInScope();
// Map<String,String> uriScope = editConfig.getUrisInScope();
// Map<String,Literal> literalScope = editConfig.getLiteralsInScope();
//
// Map<String,Literal> varToLiterals = new HashMap<String,Literal>();
// for(String var : varToSpqrql.keySet()){
// String query = varToSpqrql.get(var);
// List<String> queryStrings = new ArrayList <String>();
// queryStrings.add( query );
// queryStrings= editConfig.getN3Generator().subInUris(uriScope, queryStrings);
// queryStrings = editConfig.getN3Generator().subInLiterals(literalScope,queryStrings);
// Literal literalFromQuery = queryToLiteral( queryStrings.get(0) );
// if( literalFromQuery != null )
// varToLiterals.put(var, literalFromQuery );
// else
// log.debug("sparqlEvaluateForAdditionalLiterals(): for var " + var
// + "query evaluated to null. query: '" + queryStrings.get(0) +"'");
// }
//
// return varToLiterals;
// }
public String queryToUri(String querystr){
log.debug("Query string in queryToUri():" + querystr);
String value = null;
QueryExecution qe = null;
try{
Query query = QueryFactory.create(querystr);
qe = QueryExecutionFactory.create(query, model);
if( query.isSelectType() ){
ResultSet results = null;
results = qe.execSelect();
if( results.hasNext()){
List vars = results.getResultVars();
if( vars == null )
throw new Error("sparql had no result variables");
if( vars.size() > 1 )
throw new Error("sparql queries for use on forms may only return one result");
String var =(String) vars.get(0);
QuerySolution qs = results.nextSolution();
Resource resource = qs.getResource(var);
value = resource.getURI();
}else{
return null;
}
} else {
throw new Error("only SELECT type SPARQL queries are supported");
}
}catch(Exception ex){
throw new Error("could not parse SPARQL in queryToUri: \n" + querystr + '\n' + ex.getMessage());
}finally{
if( qe != null)
qe.close();
}
if( log.isDebugEnabled() ) log.debug("queryToUri() query: '"+ querystr +"'\nvalue: '" + value +"'");
return value;
}
public Literal queryToLiteral(String querystr){
Literal value = null;
QueryExecution qe = null;
try{
Query query = QueryFactory.create(querystr);
qe = QueryExecutionFactory.create(query, model);
if( query.isSelectType() ){
ResultSet results = null;
results = qe.execSelect();
if( results.hasNext()){
List vars = results.getResultVars();
if( vars == null )
throw new Error("sparql had no result variables");
if( vars.size() > 1 )
throw new Error("sparql queries for use on forms may only return one result");
String var =(String) vars.get(0);
QuerySolution qs = results.nextSolution();
value = qs.getLiteral(var);
}else{
return null;
}
} else {
throw new Error("only SELECT type SPARQL queries are supported");
}
}catch(Exception ex){
throw new Error("could not parse SPARQL in queryToLiteral: \n" + querystr + '\n' + ex.getMessage());
}finally{
if( qe != null)
qe.close();
}
if( log.isDebugEnabled() ) log.debug("queryToLiteral() query: '"+ querystr +"'\nvalue: '" + value +"'");
return value;
}
}

View file

@ -1,61 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.web.jsptags;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.util.Map;
/**
*
* Build the options list using info in EditConfiguration. If there are
* parameters in the request that match the name attribute then mark that
* option as selected.
*
* User: bdc34
* Date: Jan 26, 2008
* Time: 3:00:22 PM
*/
public class ErrorMessage extends TagSupport {
private String name;
public String getName() {
return name;
}
public void setName(String n) {
this.name = n;
}
public int doStartTag() {
try {
HttpSession session = pageContext.getSession();
EditConfiguration editConfig = EditConfiguration.getConfigFromSession(session,(HttpServletRequest) pageContext.getRequest());
EditSubmission editSub = EditSubmission.getEditSubmissionFromSession(session,editConfig);
if( editSub == null )
return SKIP_BODY;
Map<String,String> errors = editSub.getValidationErrors();
if( errors == null || errors.isEmpty())
return SKIP_BODY;
String val = errors.get(getName());
if( val != null){
JspWriter out = pageContext.getOut();
out.print( val );
}
} catch (Exception ex) {
throw new Error("Error in of ErrorMessage.doStartTag: " + ex.getMessage());
}
return SKIP_BODY;
}
public int doEndTag(){
return EVAL_PAGE;
}
}

View file

@ -1,37 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.web.templatemodels.edit;
import java.util.Map;
import com.hp.hpl.jena.rdf.model.Literal;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
public class EditSubmissionTemplateModel {
private final EditSubmission editSub;
public EditSubmissionTemplateModel(EditSubmission editSub){
this.editSub = editSub;
}
public Map<String, Literal> getLiteralsFromForm() {
if(editSub == null)
return null;
return editSub.getLiteralsFromForm();
}
public Map<String, String> getValidationErrors() {
if(editSub == null)
return null;
return editSub.getValidationErrors();
}
public Map<String, String> getUrisFromForm() {
if(editSub == null)
return null;
return editSub.getUrisFromForm();
}
}

View file

@ -1,58 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.web.widgets;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.SelectListGenerator;
import freemarker.core.Environment;
import freemarker.template.SimpleScalar;
public class SelectListWidget extends Widget {
private static final Log log = LogFactory.getLog(SelectListWidget.class);
@Override
protected WidgetTemplateValues process(Environment env, Map params,
HttpServletRequest request, ServletContext context) {
Object obj = params.get("fieldName");
if( obj == null || !(obj instanceof SimpleScalar)){
log.error("SelectListWidget must have a parameter 'fieldName'");
throw new Error("SelectListWidget must have a parameter'fieldName'");
}
String fieldName = ((SimpleScalar)obj).getAsString();
if( fieldName.isEmpty() ){
log.error("SelectListWidget must have a parameter 'fieldName'");
throw new Error("SelectListWidget must have a parameter 'fieldName' of type String");
}
VitroRequest vreq = new VitroRequest(request);
HttpSession session = request.getSession(false);
EditConfiguration editConfig = EditConfiguration.getConfigFromSession(session,request);
WebappDaoFactory wdf;
if (editConfig != null) {
wdf = editConfig.getWdfSelectorForOptons().getWdf(vreq,context);
} else {
wdf = vreq.getWebappDaoFactory();
}
Map<String,String> selectOptions = SelectListGenerator.getOptions(editConfig, fieldName, wdf);
Map<String,Object> rmap = new HashMap<String,Object>();
rmap.put("selectList", selectOptions);
return new WidgetTemplateValues("markup", rmap);
}
}

View file

@ -1,31 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing;
import static org.junit.Assert.*;
import java.util.Collections;
import junit.framework.Assert;
import org.junit.Test;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.BasicValidation;
public class BasicValidationTest {
@Test
public void testValidate() {
BasicValidation bv = new BasicValidation(Collections.EMPTY_MAP);
String res;
res = bv.validate("httpUrl", "http://example.com/index");
Assert.assertEquals(res, bv.SUCCESS);
res = bv.validate("httpUrl", "http://example.com/index?bogus=skjd%20skljd&something=sdkf");
Assert.assertEquals(res, bv.SUCCESS);
res = bv.validate("httpUrl", "http://example.com/index#2.23?bogus=skjd%20skljd&something=sdkf");
Assert.assertEquals(res, bv.SUCCESS);
}
}

View file

@ -1,85 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.hp.hpl.jena.rdf.model.Literal;
import edu.cornell.mannlib.vitro.webapp.edit.EditLiteral;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditN3Generator;
public class EditN3GeneratorTest {
EditN3Generator en3g ;
@Before
public void setUp() throws Exception {
en3g = new EditN3Generator((EditConfiguration) null);
}
@Test
public void testSubInLiterals() {
String var = "TestVar";
String target = "Fake n3 ?TestVar .";
Literal literal = null;
EditN3Generator en3g = new EditN3Generator((EditConfiguration) null);
String result = en3g.subInLiterals(var, literal, target);
Assert.assertNotNull( result );
}
@Test
public void testSubInLiteralsWithGroupReference() {
String var = "TestVar";
String target = "Fake n3 ?TestVar .";
Literal literal = new EditLiteral("should not a regex group --> ?2 <-- blblkj (lskdfj) " ,null,null);
EditN3Generator en3g = new EditN3Generator((EditConfiguration) null);
String result = en3g.subInLiterals(var, literal, target);
Assert.assertNotNull( result );
Assert.assertEquals("Fake n3 \"should not a regex group --> ?2 <-- blblkj (lskdfj) \" ." , result);
}
@Test
public void testConflictingVarNames(){
Map<String,String> varToExisting= new HashMap<String,String>();
varToExisting.put("bob", "http://uri.edu#BobTheElder");
varToExisting.put("bobJr", "http://uri.edu#BobTheSon");
String target = "SELECT ?cat WHERE{ ?bobJr <http://uri.edu#hasCat> ?cat }" ;
List<String> targets = new ArrayList<String>();
targets.add(target);
List<String> out = en3g.subInUris(varToExisting, targets);
Assert.assertNotNull(out);
Assert.assertNotNull( out.get(0) );
String expected = "SELECT ?cat WHERE{ <http://uri.edu#BobTheSon> <http://uri.edu#hasCat> ?cat }";
Assert.assertEquals(expected, out.get(0) );
//force a non match on a initial-partial var name
varToExisting= new HashMap<String,String>();
varToExisting.put("bob", "http://uri.edu#BobTheElder");
target = "SELECT ?cat WHERE{ ?bobJr <http://uri.edu#hasCat> ?cat }" ;
targets = new ArrayList<String>();
targets.add(target);
out = en3g.subInUris(varToExisting, targets);
Assert.assertNotNull(out);
Assert.assertNotNull( out.get(0) );
expected = target;
Assert.assertEquals(expected, out.get(0) );
}
}

View file

@ -1,75 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import stubs.javax.servlet.http.HttpServletRequestStub;
import com.hp.hpl.jena.rdf.model.Literal;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
public class EditSubmissionTest extends AbstractTestClass {
HttpServletRequestStub request;
EditConfiguration editConfig;
@Before
public void createEditConfig() throws IOException {
InputStream is = this.getClass().getResourceAsStream(
"testEditConfig.json");
editConfig = new EditConfiguration(readAll(is));
}
@Before
public void createRequest() {
request = new HttpServletRequestStub();
request.addParameter("yearfield222", "2001");
request.addParameter("monthfield222", "10");
request.addParameter("dayfield222", "13");
request.addParameter("hourfield222", "11");
request.addParameter("minutefield222", "00");
request.addParameter("talkName", "this is the name of a talk");
request.addParameter("room", "http://someBogusUri/#individual2323");
request.addParameter("editKey", "fakeEditKey");
}
public void testSetup() {
Assert.assertNotNull("EditConfiguration is null", editConfig);
Assert.assertNotNull("request must not be null", request);
}
@Test
public void testDateTimeParameter() {
EditSubmission editSub = new EditSubmission(request.getParameterMap(),
editConfig);
Literal field222 = editSub.getLiteralsFromForm().get("field222");
Assert.assertNotNull(field222);
}
@Test
public void testCanHandleMissingParameter() {
/*
* test if the EditSubmission can be passed a request which is missing a
* parameter. This will be the case when a checkbox type input is not
* selected.
*/
request.removeParameter("talkName");
request.removeParameter("room");
// just trying to make this without an exception
EditSubmission editSub = new EditSubmission(request.getParameterMap(),
editConfig);
Assert.assertNotNull(editSub);
}
}

View file

@ -1,32 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.SparqlEvaluate;
public class SparqlEvaluateTest {
SparqlEvaluate sEval;
@Before
public void setUp() throws Exception {
EditConfiguration edConfig = new EditConfiguration();
Model model = ModelFactory.createDefaultModel(); //just used to parse sparql
sEval = new SparqlEvaluate(model);
}
@Test
public void testForNoSolution() {
String uri = sEval.queryToUri("SELECT ?cat WHERE { ?cat <http://cornell.edu#hasOwner> <http://cornell.edu#bdc34>} ");
Assert.assertNull( uri );
}
}

View file

@ -1,89 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
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 edu.cornell.mannlib.vitro.webapp.edit.EditLiteral;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import java.io.StringReader;
public class EditN3GeneratorTest {
EditN3Generator en3g ;
@Before
public void setUp() throws Exception {
en3g = new EditN3Generator((EditConfiguration) null);
}
@Test
public void testSubInLiterals() {
String var = "TestVar";
String target = "Fake n3 ?TestVar .";
Literal literal = null;
EditN3Generator en3g = new EditN3Generator((EditConfiguration) null);
String result = en3g.subInLiterals(var, literal, target);
Assert.assertNotNull( result );
}
@Test
public void testSubInLiteralsWithGroupReference() {
String var = "TestVar";
String target = "Fake n3 ?TestVar .";
Literal literal = new EditLiteral("should not a regex group --> ?2 <-- blblkj (lskdfj) " ,null,null);
EditN3Generator en3g = new EditN3Generator((EditConfiguration) null);
String result = en3g.subInLiterals(var, literal, target);
Assert.assertNotNull( result );
Assert.assertEquals("Fake n3 \"should not a regex group --> ?2 <-- blblkj (lskdfj) \" ." , result);
}
@Test
public void testConflictingVarNames(){
Map<String,String> varToExisting= new HashMap<String,String>();
varToExisting.put("bob", "http://uri.edu#BobTheElder");
varToExisting.put("bobJr", "http://uri.edu#BobTheSon");
String target = "SELECT ?cat WHERE{ ?bobJr <http://uri.edu#hasCat> ?cat }" ;
List<String> targets = new ArrayList<String>();
targets.add(target);
List<String> out = en3g.subInUris(varToExisting, targets);
Assert.assertNotNull(out);
Assert.assertNotNull( out.get(0) );
String expected = "SELECT ?cat WHERE{ <http://uri.edu#BobTheSon> <http://uri.edu#hasCat> ?cat }";
Assert.assertEquals(expected, out.get(0) );
//force a non match on a initial-partial var name
varToExisting= new HashMap<String,String>();
varToExisting.put("bob", "http://uri.edu#BobTheElder");
target = "SELECT ?cat WHERE{ ?bobJr <http://uri.edu#hasCat> ?cat }" ;
targets = new ArrayList<String>();
targets.add(target);
out = en3g.subInUris(varToExisting, targets);
Assert.assertNotNull(out);
Assert.assertNotNull( out.get(0) );
expected = target;
Assert.assertEquals(expected, out.get(0) );
}
}