From 56d23c8e2c379b58d2f9c2ed4fe12c3c21c295b4 Mon Sep 17 00:00:00 2001 From: briancaruso Date: Thu, 21 Jun 2012 21:57:45 +0000 Subject: [PATCH] Removing old N3 editing code. NIHVIVO-3807 --- .../DashboardPropertyListController.java | 57 +- .../controller/edit/N3MultiPartUpload.java | 562 -------- .../edit/N3MultiPartUploadDELETEME.java | 12 + .../freemarker/N3EditFormController.java | 72 +- .../webapp/edit/elements/BaseEditElement.java | 76 - .../webapp/edit/elements/EditElement.java | 47 - ...ividualDataPropertyStatementProcessor.java | 38 +- .../n3editing/VTwo/BasicValidationVTwo.java | 4 - .../VTwo/DateTimeWithPrecisionVTwo.java | 9 +- .../VTwo/EditConfigurationUtils.java | 16 +- .../n3editing/VTwo/EditSubmissionUtils.java | 2 - .../VTwo/MultiValueEditSubmission.java | 11 +- .../edit/n3editing/VTwo/N3ValidatorVTwo.java | 3 - .../configuration/EditConfiguration.java | 972 ------------- .../edit/n3editing/configuration/Field.java | 405 ------ .../configuration/SelectListGenerator.java | 459 ------ ...aultAddMissingIndividualFormGenerator.java | 16 +- .../generators/DefaultDeleteGenerator.java | 26 +- .../InstitutionalInternalClassForm.java | 11 +- .../NewIndividualFormGenerator.java | 27 +- .../generators/RDFSLabelGenerator.java | 27 +- .../BaseEditSubmissionPreprocessor.java | 18 - .../CreateLabelFromNameFields.java | 69 - .../EditSubmissionPreprocessor.java | 9 - .../validators/BasicValidation.java | 276 ---- .../configuration/validators/N3Validator.java | 12 - .../validators/StartDateBeforeEndDate.java | 86 -- .../validators/StartYearBeforeEndYear.java | 68 - .../controller/n3DeleteController.java | 77 - .../processEdit/EditN3Generator.java | 356 ----- .../n3editing/processEdit/EditSubmission.java | 490 ------- .../n3editing/processEdit/RdfLiteralHash.java | 2 - .../n3editing/processEdit/SparqlEvaluate.java | 235 ---- .../webapp/web/jsptags/ErrorMessage.java | 61 - .../jsptags/InputElementFormattingTag.java | 1239 ----------------- .../edit/EditSubmissionTemplateModel.java | 37 - .../webapp/web/widgets/SelectListWidget.java | 58 - .../edit/n3editing/BasicValidationTest.java | 31 - .../edit/n3editing/EditN3GeneratorTest.java | 85 -- .../edit/n3editing/EditSubmissionTest.java | 75 - .../edit/n3editing/SparqlEvaluateTest.java | 32 - .../processEdit/EditN3GeneratorTest.java | 89 -- 42 files changed, 85 insertions(+), 6172 deletions(-) delete mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/controller/edit/N3MultiPartUpload.java create mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/controller/edit/N3MultiPartUploadDELETEME.java delete mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/edit/elements/BaseEditElement.java delete mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/edit/elements/EditElement.java delete mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/EditConfiguration.java delete mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/Field.java delete mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/SelectListGenerator.java delete mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/BaseEditSubmissionPreprocessor.java delete mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/CreateLabelFromNameFields.java delete mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/EditSubmissionPreprocessor.java delete mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/validators/BasicValidation.java delete mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/validators/N3Validator.java delete mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/validators/StartDateBeforeEndDate.java delete mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/validators/StartYearBeforeEndYear.java delete mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/controller/n3DeleteController.java delete mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/processEdit/EditN3Generator.java delete mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/processEdit/EditSubmission.java delete mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/processEdit/SparqlEvaluate.java delete mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/web/jsptags/ErrorMessage.java delete mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/web/jsptags/InputElementFormattingTag.java delete mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/web/templatemodels/edit/EditSubmissionTemplateModel.java delete mode 100644 webapp/src/edu/cornell/mannlib/vitro/webapp/web/widgets/SelectListWidget.java delete mode 100644 webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/BasicValidationTest.java delete mode 100644 webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/EditN3GeneratorTest.java delete mode 100644 webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/EditSubmissionTest.java delete mode 100644 webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/SparqlEvaluateTest.java delete mode 100644 webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/processEdit/EditN3GeneratorTest.java diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/DashboardPropertyListController.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/DashboardPropertyListController.java index e506a6827..095739cdd 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/DashboardPropertyListController.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/DashboardPropertyListController.java @@ -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.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 java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +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. diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/edit/N3MultiPartUpload.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/edit/N3MultiPartUpload.java deleted file mode 100644 index 4c397e20e..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/edit/N3MultiPartUpload.java +++ /dev/null @@ -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 errorMessages = new ArrayList(); - 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 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> requiredFieldAssertions = new HashMap>(); - - 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 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> buildModelsForFileItem(FileItem fileItem, - EditConfiguration editConfig, EditSubmission submission, - List assertions, OntModel jenaOntModel, - EditN3Generator n3Subber, String dataDir) throws Exception { - Map> requiredFieldAssertions = new HashMap>(); - List modelList = new ArrayList(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 saveFileAndSubInFileInfo(FileItem fileItem, - String dataDir, EditN3Generator n3generator, List 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 fileValues = new HashMap(); - 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> fieldsToAssertionMap( - Map fields) { - Map> out = new HashMap>(); - for (String fieldName : fields.keySet()) { - Field field = fields.get(fieldName); - - List copyOfN3 = new ArrayList(); - for (String str : field.getAssertions()) { - copyOfN3.add(str); - } - out.put(fieldName, copyOfN3); - } - return out; - } - - public Map> fieldsToRetractionMap( - Map fields) { - Map> out = new HashMap>(); - for (String fieldName : fields.keySet()) { - Field field = fields.get(fieldName); - - List copyOfN3 = new ArrayList(); - 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 deliverToArray = new ArrayList(); - deliverToArray.add(email); - - //Compose body of message - StringBuffer msgBuf = new StringBuffer(); - String lineSeparator = System.getProperty("line.separator"); - msgBuf.setLength(0); - msgBuf.append("" + lineSeparator ); - msgBuf.append("" + lineSeparator ); - msgBuf.append("" + lineSeparator ); - msgBuf.append("" + deliveryFrom + "" + lineSeparator ); - msgBuf.append("" + lineSeparator ); - msgBuf.append("" + lineSeparator ); - String messageBody = "

File has been uploaded to datastar"; - //Include file name if it exists and is not empty - if(uploadFileName != null && uploadFileName != "") { - messageBody += ": " + uploadFileName; - } - messageBody += "

"; - msgBuf.append(messageBody + lineSeparator + ""); - 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> add, -// Map> 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); -} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/edit/N3MultiPartUploadDELETEME.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/edit/N3MultiPartUploadDELETEME.java new file mode 100644 index 000000000..95a633b94 --- /dev/null +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/edit/N3MultiPartUploadDELETEME.java @@ -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 { + +} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/freemarker/N3EditFormController.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/freemarker/N3EditFormController.java index 0e0c4506a..56a107fdf 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/freemarker/N3EditFormController.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/freemarker/N3EditFormController.java @@ -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 map = makeEditDataMap(editConfig, editSubmission); - - //how do I add css or js? - //The jsp is adding css and js like this: - /* - List customJs = new ArrayList(Arrays.asList(JavaScript.JQUERY_UI.path(), - JavaScript.CUSTOM_FORM_UTILS.path(), - "/edit/forms/js/customFormWithAutocomplete.js" - )); - request.setAttribute("customJs", customJs); - - List customCss = new ArrayList(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 makeEditDataMap(EditConfiguration editConfig, - EditSubmission editSubmission) throws TemplateModelException { - - Map map = new HashMap(); - - map.put("editConfig", editConfig); - - if( editSubmission != null) - map.put("editSubmission", editSubmission); - - return map; - } + //TO BE DELETED } diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/elements/BaseEditElement.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/elements/BaseEditElement.java deleted file mode 100644 index 158bbb8c6..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/elements/BaseEditElement.java +++ /dev/null @@ -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 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 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; - } - } -} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/elements/EditElement.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/elements/EditElement.java deleted file mode 100644 index ebc5b562d..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/elements/EditElement.java +++ /dev/null @@ -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 - getLiterals(String fieldName, EditConfiguration editConfig, Map queryParameters ); - - /** - * This is a method to get a map of variable name to URI value from the submitted form. - */ - public Map - getURIs(String fieldName, EditConfiguration editConfig, Map queryParameters ); - - /** - * Gets validation error messages. Returns an empty list if there are no errors. - */ - public Map - getValidationMessages(String fieldName, EditConfiguration editConfig, Map 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 getExistingLiterals(???) - public Map getExistingURIs(???); - */ -} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/listener/impl/IndividualDataPropertyStatementProcessor.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/listener/impl/IndividualDataPropertyStatementProcessor.java index 59efcd7ac..145320d76 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/listener/impl/IndividualDataPropertyStatementProcessor.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/listener/impl/IndividualDataPropertyStatementProcessor.java @@ -2,24 +2,24 @@ package edu.cornell.mannlib.vitro.webapp.edit.listener.impl; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import edu.cornell.mannlib.vedit.beans.EditProcessObject; -import edu.cornell.mannlib.vedit.listener.ChangeListener; -import edu.cornell.mannlib.vedit.util.FormUtils; -import edu.cornell.mannlib.vitro.webapp.beans.DataProperty; -import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement; -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 java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import edu.cornell.mannlib.vedit.beans.EditProcessObject; +import edu.cornell.mannlib.vedit.listener.ChangeListener; +import edu.cornell.mannlib.vedit.util.FormUtils; +import edu.cornell.mannlib.vitro.webapp.beans.DataProperty; +import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement; +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.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) { diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/BasicValidationVTwo.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/BasicValidationVTwo.java index 34d8117a6..b5438610f 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/BasicValidationVTwo.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/BasicValidationVTwo.java @@ -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 { diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/DateTimeWithPrecisionVTwo.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/DateTimeWithPrecisionVTwo.java index 26f123a54..dea8a2f1d 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/DateTimeWithPrecisionVTwo.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/DateTimeWithPrecisionVTwo.java @@ -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; /** diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditConfigurationUtils.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditConfigurationUtils.java index 569450210..a88aa24b4 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditConfigurationUtils.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditConfigurationUtils.java @@ -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 { diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditSubmissionUtils.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditSubmissionUtils.java index bba7037a3..32bce34b1 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditSubmissionUtils.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/EditSubmissionUtils.java @@ -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"; diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/MultiValueEditSubmission.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/MultiValueEditSubmission.java index f9c86afe9..b28a8f21d 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/MultiValueEditSubmission.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/MultiValueEditSubmission.java @@ -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 { diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/N3ValidatorVTwo.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/N3ValidatorVTwo.java index fb0529a0e..5e6cd3e34 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/N3ValidatorVTwo.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/N3ValidatorVTwo.java @@ -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 validate(EditConfigurationVTwo editConfig, MultiValueEditSubmission editSub); } diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/EditConfiguration.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/EditConfiguration.java deleted file mode 100644 index 8ef2c3bf4..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/EditConfiguration.java +++ /dev/null @@ -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 n3Required; - List n3Optional; - List urisOnform; - List literalsOnForm; - List filesOnForm; - - Map urisInScope; - Map literalsInScope; - Map sparqlForAdditionalUrisInScope; - Map sparqlForAdditionalLiteralsInScope; - Map newResources; - - Map fields; - - MapsparqlForExistingLiterals; - MapsparqlForExistingUris; - - 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 < or >. - */ - String object; - String varNameForObject; - boolean isObjectResource; - - String datapropKey; - String datapropValue; - - String urlPatternToReturnTo; - String entityToReturnTo; - String formUrl; - String editKey; - - List validators; - - EditN3Generator n3generator; - private String originalJson; - - private List modelChangePreprocessors; - - private List 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(); - 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 makeLiteralsInScopeFromJson(JSONObject jsonObject) throws JSONException{ - Map out = new HashMap(); - - 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 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 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 fieldMap = new HashMap(); - 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 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 getN3Required() { - List copyForPassByValue = new ArrayList (n3Required.size()); - for( String str : n3Required){ - copyForPassByValue.add(str); - } - return copyForPassByValue; - } - - public void setN3Required(List n3Required) { - this.n3Required = n3Required; - } - - /** return a copy of the value so that the configuration is not modified by external code. - * @return - */ - public List getN3Optional() { - List copyForPassByValue = new ArrayList (n3Optional.size()); - for( String str : n3Optional){ - copyForPassByValue.add(str); - } - return copyForPassByValue; - } - - public void setN3Optional(List n3Optional) { - this.n3Optional = n3Optional; - } - - public Map getNewResources() { - return newResources; - } - - public void setNewResources(Map newResources) { - this.newResources = newResources; - } - - public List getUrisOnform() { - return urisOnform; - } - - public void setUrisOnform(List urisOnform) { - this.urisOnform = urisOnform; - } - - public void setFilesOnForm(List filesOnForm){ - this.filesOnForm = filesOnForm; - } - - public List getFilesOnForm(){ - return filesOnForm; - } - - public List getLiteralsOnForm() { - return literalsOnForm; - } - - public void setLiteralsOnForm(List literalsOnForm) { - this.literalsOnForm = literalsOnForm; - } - - public Map getUrisInScope() { - return urisInScope; - } - - public void setUrisInScope(Map urisInScope) { - this.urisInScope = urisInScope; - } - - public Map getLiteralsInScope() { - return literalsInScope; - } - - public void setLiteralsInScope(Map literalsInScope) { - this.literalsInScope = literalsInScope; - } - - /** return a copy of the value so that the configuration is not modified by external code. - * @return - */ - public Map getSparqlForAdditionalUrisInScope() { - Map copyForPassByValue = new HashMap(); - copy(sparqlForAdditionalUrisInScope, copyForPassByValue); - return copyForPassByValue; - } - - public void setSparqlForAdditionalUrisInScope(Map sparqlForAdditionalUrisInScope) { - this.sparqlForAdditionalUrisInScope = sparqlForAdditionalUrisInScope; - } - - /** return a copy of the value so that the configuration is not modified by external code. - * @return - */ - public Map getSparqlForAdditionalLiteralsInScope() { - Map copyForPassByValue = new HashMap(); - copy(sparqlForAdditionalLiteralsInScope, copyForPassByValue); - return copyForPassByValue; - } - - private Map copy(Map source, Map dest){ - if( source == null ) return null; - dest.clear(); - for( String key : source.keySet()){ - dest.put(key, source.get(key)); - } - return dest; - } - - public void setSparqlForAdditionalLiteralsInScope(Map 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 getSparqlForExistingLiterals() { - Map copyForPassByValue = new HashMap(); - copy(sparqlForExistingLiterals, copyForPassByValue); - return copyForPassByValue; - } - - public void setSparqlForExistingLiterals(Map sparqlForExistingLiterals) { - this.sparqlForExistingLiterals = sparqlForExistingLiterals; - } - - /** return a copy of the value so that the configuration is not modified by external code. - * @return - */ - public Map getSparqlForExistingUris() { - Map copyForPassByValue = new HashMap(); - copy(sparqlForExistingUris, copyForPassByValue); - return copyForPassByValue; - } - - public void setSparqlForExistingUris(Map sparqlForExistingUris) { - this.sparqlForExistingUris = sparqlForExistingUris; - } - - public static List JsonArrayToStringList(JSONArray jarray){ - ArrayList outv = new ArrayList(); - 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 JsonObjToMap(JSONObject jobj){ - HashMap outv = new HashMap(); - 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 JsonObjToMapOfFields(JSONObject jobj){ - HashMap outv = new HashMap(); - 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> getN3ForFields(){ - return fieldsToMap( getFields() ); - } - - private Map> fieldsToMap( Map fields){ - Map> out = new HashMap>(); - for( String fieldName : fields.keySet()){ - Field field = fields.get(fieldName); - - List copyOfN3 = new ArrayList(); - for( String str : field.getAssertions()){ - copyOfN3.add(str); - } - out.put( fieldName, copyOfN3 ); - } - return out; - } - - /* ********************** static methods to get EditConfigs from Session ******************************** */ - - 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 configs = (Map)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 configs = (Map)sess.getAttribute("EditConfigurations"); - if( configs == null ){ - configs = new HashMap(); - sess.setAttribute("EditConfigurations",configs); - } - configs.put(ec.editKey , ec); - } - - public static EditConfiguration getConfigFromSession(HttpSession sess, String editKey){ - Map configs = (Map)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 configs = (Map)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 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 getModelChangePreprocessors() { - return this.modelChangePreprocessors; - } - - public List 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 itemListFromMap(Map map){ -// if( map == null ) return Collections.EMPTY_LIST; -// -// ArrayList outList = new ArrayList(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 getValidators() { - return validators; - } - - public void addValidator( N3Validator validator){ - if( this.validators == null ) - this.validators = new ArrayList(); - this.validators.add(validator); - } - - public void addEditSubmissionPreprocessor( EditSubmissionPreprocessor preprocessor){ - if( editSubmissionPreprocessors == null ) - editSubmissionPreprocessors = new ArrayList(); - editSubmissionPreprocessors.add(preprocessor); - } - - public List 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; - } -} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/Field.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/Field.java deleted file mode 100644 index 674a3ae40..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/Field.java +++ /dev/null @@ -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 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"^^ - * 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> literalOptions; - - /** - * Strings of N3 to add to model. - */ - private List assertions; - - /** - * JSON configuration that was used to build this object. - */ - private String originalJson; - - /** - * Do not attempt to set the retractions when configuring a Field; they get built by the - * edit processing object. - * - * The strings in this list should be N3 for statements that need to be retracted to affect an update. - * Per Field retractions are necessary since we only want to retract for fields that have changed. - * The Model should be checked to make sure that all of the retractions exist so we are changing the - * statements that existed when this edit was configured. - * - * These retractions are just the assertions with the values subistituted in from before the change. - */ - private List retractions; - - private Map queryForExisting; - - /** - * Property for special edit element. - */ - 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 getRetractions() { - return retractions; - } - - public void setRetractions(List retractions) { - this.retractions = retractions; - } - - public List getAssertions() { - return assertions; - } - - public void setAssertions(List assertions) { - this.assertions = assertions; - } - - public boolean isNewResource() { - return newResource; - } - public void setNewResource(boolean b) { - newResource = b; - } - - public List getValidators() { - return validators; - } - public void setValidators(List 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 > getLiteralOptions() { - return literalOptions; - } - public void setLiteralOptions(List> 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> out = new ArrayList>( array.length() ); - - for(int i =0; ioption = new ArrayList(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"); - - Listoption = new ArrayList(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; - } - -} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/SelectListGenerator.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/SelectListGenerator.java deleted file mode 100644 index abc7ddd2c..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/SelectListGenerator.java +++ /dev/null @@ -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 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 optionsMap = new LinkedHashMap(); - // 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> 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 (); - } - for(Object obj: ((Iterable)hardcodedLiteralOptions)){ - List 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> 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 (); - } - for(Object obj: ((Iterable)literalOptions)){ - List 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 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 vclasses = new ArrayList(); - 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 individuals = new ArrayList(); - HashSet uriSet = new HashSet(); - 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 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 individualMap = new HashMap(); - - 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 individuals = new ArrayList(); - 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 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 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 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 > defaultOptions = (List>) field.getLiteralOptions(); - if (defaultOptions!=null) { - for(Object obj: ((Iterable)defaultOptions)) { - List pair = (List)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 removeIndividualsAlreadyInRange(List individuals, - List stmts, String predicateUri, String objectUriBeingEdited){ - log.debug("starting to check for duplicate range individuals in SelectListGenerator.removeIndividualsAlreadyInRange() ..."); - HashSet range = new HashSet(); - - for(ObjectPropertyStatement ops : stmts){ - if( ops.getPropertyURI().equals(predicateUri)) - range.add( ops.getObjectURI() ); - } - - int removeCount=0; - ListIterator 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 = ""; -} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultAddMissingIndividualFormGenerator.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultAddMissingIndividualFormGenerator.java index 07abc3620..ca2f7b74a 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultAddMissingIndividualFormGenerator.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultAddMissingIndividualFormGenerator.java @@ -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; diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultDeleteGenerator.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultDeleteGenerator.java index cadf89338..e93754aa5 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultDeleteGenerator.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DefaultDeleteGenerator.java @@ -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. diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/InstitutionalInternalClassForm.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/InstitutionalInternalClassForm.java index d2c085ace..ea2f9b911 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/InstitutionalInternalClassForm.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/InstitutionalInternalClassForm.java @@ -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,14 +31,8 @@ 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? - 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() ); + //bdc34: maybe this is redundant with the keys of the fields Map? + editConfig.setUrisOnform( new StringList( "internalClassUri" )); //edit config should have URL to submit the form to //editConfig.setUrl diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/NewIndividualFormGenerator.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/NewIndividualFormGenerator.java index 417a2cca7..0c0adcdde 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/NewIndividualFormGenerator.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/NewIndividualFormGenerator.java @@ -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. diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/RDFSLabelGenerator.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/RDFSLabelGenerator.java index 79153c1cd..764f2f7b4 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/RDFSLabelGenerator.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/RDFSLabelGenerator.java @@ -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. * diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/BaseEditSubmissionPreprocessor.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/BaseEditSubmissionPreprocessor.java deleted file mode 100644 index 7ae4d246e..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/BaseEditSubmissionPreprocessor.java +++ /dev/null @@ -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; - } - - -} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/CreateLabelFromNameFields.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/CreateLabelFromNameFields.java deleted file mode 100644 index a6ab3e67e..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/CreateLabelFromNameFields.java +++ /dev/null @@ -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 - // ", ". 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 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."); - } - - } -} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/EditSubmissionPreprocessor.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/EditSubmissionPreprocessor.java deleted file mode 100644 index 8a14c01d8..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/EditSubmissionPreprocessor.java +++ /dev/null @@ -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); -} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/validators/BasicValidation.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/validators/BasicValidation.java deleted file mode 100644 index 623a05f79..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/validators/BasicValidation.java +++ /dev/null @@ -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> varsToValidations; - EditConfiguration editConfig; - - public BasicValidation(EditConfiguration editConfig, EditSubmission editSub){ - this.editConfig = editConfig; - Map> validatorsForFields = new HashMap>(); - for(String fieldName: editConfig.getFields().keySet()){ - Field field = editConfig.getField(fieldName); - validatorsForFields.put(fieldName,field.getValidators()); - } - this.varsToValidations = validatorsForFields; - checkValidations(); - } - - public BasicValidation(Map> varsToValidations){ - this.varsToValidations = varsToValidations; - checkValidations(); - } - - public Map validateUris(Map varNamesToValues){ - HashMap errors = new HashMap(); - - for( String name : varNamesToValues.keySet()){ - - String value = varNamesToValues.get(name); - List 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 validateLiterals(Map varNamesToValues){ - HashMap errors = new HashMap(); - - for( String name : editConfig.getLiteralsOnForm() ){ - Literal literal = varNamesToValues.get(name); - Listvalidations = 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 MapvalidateFiles(Map> fileItemMap) { - - HashMap errors = new HashMap(); - for(String name: editConfig.getFilesOnForm() ){ - List 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 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 unknown = new ArrayList(); - 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 basicValidations; - static{ - basicValidations = Arrays.asList( - "nonempty","isDate","dateNotPast","httpUrl" ,"anti-xss"); - } - - private Log log = LogFactory.getLog(BasicValidation.class); -} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/validators/N3Validator.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/validators/N3Validator.java deleted file mode 100644 index 255ffc828..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/validators/N3Validator.java +++ /dev/null @@ -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 validate(EditConfiguration editConfig, EditSubmission editSub); -} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/validators/StartDateBeforeEndDate.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/validators/StartDateBeforeEndDate.java deleted file mode 100644 index a6c4b0dc0..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/validators/StartDateBeforeEndDate.java +++ /dev/null @@ -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 validate(EditConfiguration editConfig, - EditSubmission editSub) { - Map existingLiterals = editConfig.getLiteralsInScope(); - Literal existingStartDate = existingLiterals.get(startFieldName); - Literal existingEndDate = existingLiterals.get(endFieldName); - - Map literalsFromForm = editSub.getLiteralsFromForm(); - Literal formStartDate = literalsFromForm.get(startFieldName); - Literal formEndDate = literalsFromForm.get(endFieldName); - - Map errors = new HashMap(); - - 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 checkDateLiterals(Literal startLit, - Literal endLit) { - Map errors = new HashMap(); - 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); -} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/validators/StartYearBeforeEndYear.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/validators/StartYearBeforeEndYear.java deleted file mode 100644 index fb7eb2df1..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/validators/StartYearBeforeEndYear.java +++ /dev/null @@ -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 validate(EditConfiguration editConfig, - EditSubmission editSub) { - Map existingLiterals = editConfig.getLiteralsInScope(); - Literal existingStartYear = existingLiterals.get(startFieldName); - Literal existingEndYear = existingLiterals.get(endFieldName); - - Map literalsFromForm = editSub.getLiteralsFromForm(); - Literal formStartYear = literalsFromForm.get(startFieldName); - Literal formEndYear = literalsFromForm.get(endFieldName); - - Map errors = new HashMap(); - - 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 checkDateLiterals(Literal startLit, - Literal endLit) { - Map errors = new HashMap(); - 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; - } - -} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/controller/n3DeleteController.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/controller/n3DeleteController.java deleted file mode 100644 index edf05893a..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/controller/n3DeleteController.java +++ /dev/null @@ -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 queryParameters = null; - queryParameters = vreq.getParameterMap(); - - List errorMessages = new ArrayList(); - - 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 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 requiredAssertionsToDelete = new ArrayList(); - List optionalAssertionsToDelete = new ArrayList(); - - boolean requestIsAValidDelete = editConfiguration.getObject() != null && editConfiguration.getObject().trim().length() > 0; - - - - return null; - } -} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/processEdit/EditN3Generator.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/processEdit/EditN3Generator.java deleted file mode 100644 index 5a2439f57..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/processEdit/EditN3Generator.java +++ /dev/null @@ -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 generateN3(EditSubmission editSub, Model model){ - return Collections.EMPTY_LIST; - } - - - - public static List subInUris(Map varsToVals, List targets){ - if( varsToVals == null || varsToVals.isEmpty() ) return targets; - ArrayList outv = new ArrayList(); - for( String target : targets){ - String temp = target; - for( String key : varsToVals.keySet()) { - temp = subInUris( key, varsToVals.get(key), temp) ; - } - 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 ListsubInUris(String var, String value, List targets){ - ArrayList outv =new ArrayList(); - for( String target : targets){ - outv.add( subInUris( var,value, target) ) ; - } - return outv; - } - - public List subInLiterals(Map varsToVals, List targets){ - if( varsToVals == null || varsToVals.isEmpty()) return targets; - - ArrayList outv =new ArrayList(); - for( String target : targets){ - String temp = target; - for( String key : varsToVals.keySet()) { - temp = subInLiterals( key, varsToVals.get(key), temp); - } - outv.add(temp); - } - return outv; - } - -// public ListsubInLiterals(String var, String value, List targets){ -// ArrayList outv =new ArrayList(); -// for( String target : targets){ -// outv.add( subInLiterals( var,value, target) ) ; -// } -// return outv; -// } - - /** - * When we sub in literals we have to take in to account the Lang or Datatype of - * the literal. N3 needs to have its literals escaped in Python style. Java regex - * Matcher is used to do the substitution and it need escaping to avoid group - * references, Matcher.quoteReplacement() serves the purpose. - * - */ - public String subInLiterals(String var, Literal literal, String target){ - String varRegex = "\\?" + var + "(?=\\.\\p{Space}|\\p{Space})"; - if (target==null ) { - log.error("subInLiterals was passed a null target"); - return "blankBecauseTargetOrValueWasNull"; - }else if( var == null ){ - log.warn("subInLiterals was passed a null var name"); - return target; - }else if( literal == null ){ - log.debug("subInLiterals was passed a null value for var '"+var+"'; returning target: '"+target+"'"); - return target; - } - - try{ - if( literal.getValue() == null ) - log.debug("value of literal for " + var + " was null"); - }catch(com.hp.hpl.jena.datatypes.DatatypeFormatException ex){ - log.debug("value for " + var + " " + ex.getMessage()); - } - - //if( editConfig != null && editConfig.getFields() != null && - // editConfig.getFields().get(var) != null ){ - //The var might not be in the editConfig.fields if an EditN3Generator - //is being used to substitute in values that are not on the form, - //eg ?fileSize for file uploads - - String replacement = null; - if ( literal.getLexicalForm().length()==0 ) { - log.debug("empty string found on form for " + var + "."); - replacement = ">::" + var + " was empty::<"; - }else{ - replacement = formatLiteral(literal); - } - - String out = null; - if( replacement != null ) - out = target.replaceAll(varRegex, Matcher.quoteReplacement( replacement )); - else - out = target; - - if( out != null && out.length() > 0 ) - return out; - else{ - log.debug("After attempting to substitue in literals, the target N3 was empty" ); - return target; - } - } - - public Map> substituteIntoValues - (Map varsToUris, - Map varsToLiterals, - Map> namesToN3 ) - { - Map> outHash = new HashMap>(); - - if (namesToN3==null) { - return outHash; - } else if (namesToN3.isEmpty()) { - return outHash; - } else { - for(String fieldName : namesToN3.keySet()){ - List n3strings = namesToN3.get(fieldName); - List newList = new ArrayList(); - if( varsToUris != null) - newList = 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 - *************************************************************************/ -} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/processEdit/EditSubmission.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/processEdit/EditSubmission.java deleted file mode 100644 index 21ae95ff5..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/processEdit/EditSubmission.java +++ /dev/null @@ -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 literalsFromForm ; - private Map urisFromForm ; - - private Map validationErrors; - private BasicValidation basicValidation; - - private Map> filesFromForm; - - private static Model literalCreationModel; - - static{ - literalCreationModel = ModelFactory.createDefaultModel(); - } - - public EditSubmission(Map 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(); - - this.urisFromForm = new HashMap(); - for( String var: editConfig.getUrisOnform() ){ - String[] valuesArray = queryParameters.get( var ); - String uri = null; - List 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(); - 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 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 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 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 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 urisFromElement = element.getURIs(fieldName, editConfig, queryParameters); - if( urisFromElement != null ) - urisFromForm.putAll(urisFromElement); - Map 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 queryParameters, EditConfiguration editConfig, - Map> 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"^^ - */ - public Literal getDateTime(Map queryParameters,String fieldName){ - DateTime dt = null; - List year = Arrays.asList(queryParameters.get("year"+ fieldName)); - List month = Arrays.asList(queryParameters.get("month" + fieldName)); - List day = Arrays.asList(queryParameters.get("day" + fieldName)); - List hour = Arrays.asList(queryParameters.get("hour"+ fieldName)); - List 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"^^ - */ - public Literal getTime(Map queryParameters,String fieldName) { - List hour = Arrays.asList(queryParameters.get("hour" + fieldName)); - List 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"^^ - */ - public Literal getDate(Map queryParameters,String fieldName){ - DateTime dt = null; - List year = Arrays.asList(queryParameters.get("year"+ fieldName)); - List month = Arrays.asList(queryParameters.get("month" + fieldName)); - List 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 getValidationErrors(){ - return validationErrors; - } - - public Map getLiteralsFromForm() { - return literalsFromForm; - } - - public Map getUrisFromForm() { - return urisFromForm; - } - - public void setLiteralsFromForm(Map literalsFromForm) { - this.literalsFromForm = literalsFromForm; - } - - public void setUrisFromForm(Map 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 submissions = (Map)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 submissions = (Map)sess.getAttribute("EditSubmissions"); - if( submissions == null ){ - submissions = new HashMap(); - 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 submissions = (Map)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 convertParams( - Map> queryParameters) { - HashMap out = new HashMap(); - 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); -} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/processEdit/RdfLiteralHash.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/processEdit/RdfLiteralHash.java index 46a90e24b..3959ed345 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/processEdit/RdfLiteralHash.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/processEdit/RdfLiteralHash.java @@ -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; diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/processEdit/SparqlEvaluate.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/processEdit/SparqlEvaluate.java deleted file mode 100644 index c6afe3a55..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/processEdit/SparqlEvaluate.java +++ /dev/null @@ -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 varsToUris = sparqlEvaluateForUris(editConfig, editConfig.getSparqlForAdditionalUrisInScope()); - editConfig.getUrisInScope().putAll(varsToUris); - } - - public void evalulateForAdditionalLiterals( EditConfiguration editConfig ){ - Map varsToLiterals = sparqlEvaluateForLiterals(editConfig, editConfig.getSparqlForAdditionalLiteralsInScope()); - editConfig.getLiteralsInScope().putAll(varsToLiterals); - } - - public void evaluateForExistingUris( EditConfiguration editConfig){ - Map varsToUris = sparqlEvaluateForUris(editConfig, editConfig.getSparqlForExistingUris()); - editConfig.getUrisInScope().putAll(varsToUris); - } - - public void evaluateForExistingLiterals( EditConfiguration editConfig){ - Map varsToLiterals = sparqlEvaluateForLiterals(editConfig, editConfig.getSparqlForExistingLiterals()); - editConfig.getLiteralsInScope().putAll(varsToLiterals); - } - -// public Map sparqlEvaluateForExistingToUris(Map varToSpqrql){ -// Map varToUris = new HashMap(); -// for(String var : varToSpqrql.keySet()){ -// varToUris.put(var, queryToUri( varToSpqrql.get(var) )); -// } -// return varToUris; -// } -// -// public Map sparqlEvaluateForAdditionalLiterals(Map varToSpqrql){ -// Map varToLiterals = new HashMap(); -// for(String var : varToSpqrql.keySet()){ -// varToLiterals.put(var, queryToLiteral( varToSpqrql.get(var) )); -// } -// return varToLiterals; -// } - -// private Map sparqlEvaluateForExistingToUris( EditConfiguration editConfig ) { -// Map varToSpqrql = editConfig.getSparqlForExistingUris(); -// Map uriScope = editConfig.getUrisInScope(); -// Map literalScope = editConfig.getLiteralsInScope(); -// -// Map varToUris = new HashMap(); -// -// for(String var : varToSpqrql.keySet()){ -// String query = varToSpqrql.get(var); -// List queryStrings = new ArrayList (); -// 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 sparqlEvaluateForLiterals( EditConfiguration editConfig, Map varToSparql) { - Map uriScope = editConfig.getUrisInScope(); - Map literalScope = editConfig.getLiteralsInScope(); - - Map varToLiterals = new HashMap(); - 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 queryStrings = new ArrayList (); - 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 sparqlEvaluateForUris( EditConfiguration editConfig, MapvarToSparql) { - Map uriScope = editConfig.getUrisInScope(); - Map literalScope = editConfig.getLiteralsInScope(); - - Map varToUris = new HashMap(); - - 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 queryStrings = new ArrayList (); - 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 sparqlEvaluateForAdditionalLiterals( EditConfiguration editConfig) { -// Map varToSpqrql = editConfig.getSparqlForAdditionalLiteralsInScope(); -// Map uriScope = editConfig.getUrisInScope(); -// Map literalScope = editConfig.getLiteralsInScope(); -// -// Map varToLiterals = new HashMap(); -// for(String var : varToSpqrql.keySet()){ -// String query = varToSpqrql.get(var); -// List queryStrings = new ArrayList (); -// 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; - } - - -} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/web/jsptags/ErrorMessage.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/web/jsptags/ErrorMessage.java deleted file mode 100644 index 092b9b2d2..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/web/jsptags/ErrorMessage.java +++ /dev/null @@ -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 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; - } -} \ No newline at end of file diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/web/jsptags/InputElementFormattingTag.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/web/jsptags/InputElementFormattingTag.java deleted file mode 100644 index 395c8e08a..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/web/jsptags/InputElementFormattingTag.java +++ /dev/null @@ -1,1239 +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 static edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary.DISPLAY_ONT_MODEL; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.text.Collator; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import javax.servlet.jsp.JspWriter; -import javax.servlet.jsp.tagext.TagSupport; - -import org.apache.commons.lang.StringEscapeUtils; -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.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; - -import com.hp.hpl.jena.datatypes.xsd.XSDDateTime; -import com.hp.hpl.jena.ontology.OntModel; -import com.hp.hpl.jena.rdf.model.Literal; -import com.hp.hpl.jena.vocabulary.XSD; - -import edu.cornell.mannlib.vitro.webapp.beans.Individual; -import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty; -import edu.cornell.mannlib.vitro.webapp.beans.VClass; -import edu.cornell.mannlib.vitro.webapp.controller.Controllers; -import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; -import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerConfigurationLoader; -import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary; -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.Field; -import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.SelectListGenerator; -import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission; -import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch; -import freemarker.template.Configuration; - -/** - * This tag will build an option list for individuals of a VClass. - * - * User: bdc34 - * Date: Jan 4, 2008 - * Time: 12:16:29 PM - */ -public class InputElementFormattingTag extends TagSupport { - private String id; - // NB name is optional. If not specified, the name comes from the id value. - private String name; - private String type; - private String label; - private String cancelLabel; - private String cancelUrl; - private String cssClass; - private String labelClass; - private String disabled; - private String value; - private String error; - private int size = 0; - private int rows = 0; - private int cols = 0; - private String multiple = ""; - private String listMarkup; - private String cancel; - - private static final Log log = LogFactory.getLog(InputElementFormattingTag.class.getName()); - - public String getId() { - return id; - } - public void setId(String idStr) { - this.id = idStr; - } - - public String getName() { - return StringUtils.isEmpty(name) ? id : name; - } - public void setName(String name) { - this.name = name; - } - - public String getType() { - return type; - } - public void setType(String typeStr) { - this.type = typeStr; - } - - public String getLabel() { - return label; - } - public void setLabel(String labelStr) { - this.label = labelStr; - } - - public String getCancelLabel() { - return cancelLabel; - } - public void setCancelLabel(String cancelLabel) { - this.cancelLabel = cancelLabel; - } - public String getCancelUrl() { - return cancelUrl; - } - public void setCancelUrl(String cancelUrl) { - this.cancelUrl = cancelUrl; - } - public String getCssClass() { - return cssClass; - } - public void setCssClass(String classStr) { - this.cssClass = classStr; - } - public String getLabelClass() { - return labelClass; - } - public void setLabelClass(String labelClassStr) { - this.labelClass = labelClassStr; - } - public String getDisabled() { - return disabled; - } - public void setDisabled(String disabled) { - this.disabled = disabled; - } - public String getValue() { - return value; - } - public void setValue(String valueStr) { - this.value = valueStr; - } - -/* public String getDefaultValue() { - return defaultValue; - } - public void setDefaultValue(String valueStr) { - this.defaultValue = valueStr; - } */ - - public String getError() { - return error; - } - public void setError(String errorStr) { - this.error = errorStr; - } - - public int getSize() { - return size; - } - public void setSize(int i) { - size = i; - } - - public int getRows() { - return rows; - } - public void setRows(int i) { - rows = i; - } - - public int getCols() { - return cols; - } - public void setCols(int i) { - cols = i; - } - - public String getMultiple() { - return multiple; - } - public void setMultiple(String s) { - multiple = s; - } - - public String getListMarkup() { - return listMarkup; - } - public void setListMarkup(String s){ - listMarkup = s; - } - - public String getCancel() { - return cancel; - } - public void setCancel(String s){ - cancel = s; - } - - private String doLabelClass() { - String labelClass = getLabelClass(); - if (labelClass != null && !labelClass.equals("")) { - return " class=\""+labelClass+"\""; - } - return ""; - } - - private String doClass() { - /* only insert the class attribute if it has been populated */ - if (getCssClass()!=null && !getCssClass().equals("")) { - return "class=\""+getCssClass()+"\""; - } - return ""; - } - - private String doDisabled() { - /* Only insert the disabled attribute if it has been populated. Support - * both "true" and "disabled" as values. */ - String disabled = getDisabled(); - if ("true".equals(disabled) || "disabled".equals(disabled)) { - return "disabled=\"disabled\""; - } - return ""; - } - - private String doSize() { - if (getSize()>0) { - return "size=\"" + getSize() + "\""; - } - return ""; - } - - private String doRows() { - if (getRows()>0) { - return "rows=\"" + getRows() + "\""; - } - return ""; - } - - private String doCols() { - if (getCols()>0) { - return "cols=\"" + getCols() + "\""; - } - return ""; - } - - /** - * attempt to get value from editSub. If that value is there then this is a re-draw - * of the form after a validation failure. If there is no editSub, or no value in - * the editSub, then try to get it from the editConfig. This is where the value would - * be if the form is being built for an edit of an existing property. - * - */ - private String doValue(EditConfiguration editConfig, EditSubmission editSub) { - Literal literal = null; - String uri = null; - if( editConfig == null && editSub == null ) { - log.error("both editSub and editConfig null in InputElementFormattingTag.doValue()"); - return ""; - } - try{ - Map literals = null; - Map uris = null; - if (editSub != null) { // are reloading a form after a validation error, look in editSub - literals = editSub.getLiteralsFromForm(); - if( literals!= null && literals.containsKey(getName())){ - literal = literals.get(getName()); - if( literal != null ) { - return literalToString(literal); - } - } else { //look for a uri - uris = editSub.getUrisFromForm(); - if( uris != null ) - uri = uris.get(getName()); - if( uri != null ){ - return uri; - } - } - } else { // check in editConfig - literals = editConfig.getLiteralsInScope(); - if( literals != null && literals.containsKey(getName()) ) { - literal = literals.get(getName()); - return literalToString(literal); - } else { - uris = editConfig.getUrisInScope(); - if( uris != null && uris.containsKey( getName() ) && uris.get( getName() ) != null ) { - return editConfig.getUrisInScope().get(getName()); - } - } - } - }catch(Exception ex){ - log.debug("doValue():", ex); - } - - log.debug("doValue(): No existing or default value for key '"+getId()+"' found from in editConfig or" - +" or editSub"); - return ""; - } - - private String literalToString(Literal lit){ - if( lit == null || lit.getValue() == null) return ""; - String value = lit.getValue().toString(); - if( "http://www.w3.org/2001/XMLSchema#anyURI".equals( lit.getDatatypeURI() )){ - //strings from anyURI will be URLEncoded from the literal. - try{ - value = URLDecoder.decode(value, "UTF8"); - }catch(UnsupportedEncodingException ex){ - log.error(ex); - } - } - return value; - } - - private String doCancel(String labelStr, EditConfiguration editConfig){ - if (labelStr==null || labelStr.equals("")) { - labelStr = getCancelLabel(); - if (labelStr==null || labelStr.equals("")) { - labelStr="Cancel"; - } - } - VitroRequest vreq = new VitroRequest((HttpServletRequest)pageContext.getRequest()); - if( "about".equals( getCancel() )){ - return " or "+labelStr+""; - } else if ( "admin".equals( getCancel() )){ - return " or "+labelStr+""; - }else if( "dashboard".equals( getCancel() )){ //this case is Datastar-specific. - return " or "+labelStr+""; - }else if (getCancel()!=null && !getCancel().equals("") && !getCancel().equals("false")) { - if( editConfig != null && editConfig.getEditKey() != null ){ - try{ - String url = vreq.getContextPath() + - "/edit/postEditCleanUp.jsp?editKey="+ - URLEncoder.encode(editConfig.getEditKey(),"UTF-8") + - "&cancel=true"; - String cancelUrl = getCancelUrl(); - if (!StringUtils.isEmpty(cancelUrl)) { - url += "&url=" + cancelUrl; - } - return " or "+labelStr+""; - }catch(UnsupportedEncodingException ex){ - log.error( "doCancel(): " , ex); - } - } else {//no edit config? try to just use the subjectUri. This is the case when on propDelete.jsp - try { - String url = vreq.getContextPath(); - if( vreq.getParameter("subjectUri") != null ) - url += "/entity?uri=" + URLEncoder.encode( vreq.getParameter("subjectUri"),"UTF-8"); - String pred = vreq.getParameter("predicateUri"); - if( pred != null && pred.length() > 0 ){ - String[] kf = pred.split("#"); - if( kf != null && kf.length == 2 ) - url += "&property=" + URLEncoder.encode( kf[1],"UTF-8"); - } - - return "or "+labelStr+""; - } catch (UnsupportedEncodingException ex) { - log.error( "doCancel(): " , ex); - } - } - } - return ""; - } - - private String getValidationErrors(EditSubmission editSub) { - if( editSub == null ) - return ""; - Map errors = editSub.getValidationErrors(); - if( errors == null || errors.isEmpty()) - return ""; - - String val = errors.get(getName()); - if( val != null){ - return val; - } - return ""; - } - - - public int doStartTag() { - try { - - if (getId()==null || getId().equals("")){ - log.error("Error in doStartTag: input element id is blank or not specified."); - } - - HttpSession session = pageContext.getSession(); - EditConfiguration editConfig = EditConfiguration.getConfigFromSession(session,(HttpServletRequest) pageContext.getRequest()); - EditSubmission editSub = EditSubmission.getEditSubmissionFromSession(session,editConfig); - - VitroRequest vreq = new VitroRequest((HttpServletRequest)pageContext.getRequest()); - WebappDaoFactory wdf; - if (editConfig != null) { - wdf = editConfig.getWdfSelectorForOptons().getWdf( - (HttpServletRequest)pageContext.getRequest(), - pageContext.getServletContext()); - } else { - wdf = vreq.getWebappDaoFactory(); - } - - //get freemarker Configuration - Configuration fmConfig = FreemarkerConfigurationLoader.getConfig(vreq); - - /* populate the pieces */ - String classStr = doClass(); - String disabledStr = doDisabled(); - String errorStr = getValidationErrors(editSub); - JspWriter out = pageContext.getOut(); - - boolean definitionTags = false; // current default - /* if (getListMarkup()!=null && getListMarkup().equalsIgnoreCase("definition")) { - definitionTags=true; - } */ - - if( getLabel()!=null && !getLabel().equals("")) { - if (definitionTags) { out.println("
"); } - out.println(""+getLabel()+""); - if (definitionTags) { out.println("
"); } - } - - - // bdc34 2010-11-08 field may be null - Field field = editConfig == null ? null : editConfig.getField(getId()); - - /* bdc34 2010-11-08 : this is odd, I'm having problems with the submit on this next line because - * it is not a field in the editConfig. This wasn't happening before. */ -// if( field == null ){ -// log.error("could not get field for id " + getId()); -// return SKIP_BODY; -// } - - - if ((getType()==null || getType().equals("")) && (field != null && field.getEditElement() == null )){ - log.error("Error in doStartTag: input element type not specified and editElement not specified."); - } - - // set ProhibitedFromSearch object so picklist doesn't show - // individuals from classes that should be hidden from list views - OntModel displayOntModel = - (OntModel) pageContext.getServletContext() - .getAttribute(DISPLAY_ONT_MODEL); - if (displayOntModel != null) { - ProhibitedFromSearch pfs = new ProhibitedFromSearch( - DisplayVocabulary.SEARCH_INDEX_URI, displayOntModel); - if( editConfig != null ) - editConfig.setProhibitedFromSearch(pfs); - } - - if( field != null && field.getEditElement() != null ){ - out.print( field.getEditElement().draw(getId(), editConfig, editSub, fmConfig)); - }else if( getType() == null ){ - log.error("type or editElement must be specified for input element " + getId() ); - }else if( getType().equalsIgnoreCase("date") || - (field != null && field.getRangeDatatypeUri() != null && field.getRangeDatatypeUri().equals(XSD.date.getURI())) ){ - //if its a dataprop that should be a string override type and use date picker - if (definitionTags) { out.print(""); } - out.print( generateHtmlForDate(getId(),editConfig,editSub) ); - if (definitionTags) { out.print(""); } - } else if ( getType().equalsIgnoreCase("time") || - (field != null && field.getRangeDatatypeUri() != null && field.getRangeDatatypeUri().equals(XSD.time.getURI())) ) { - if (definitionTags) { out.print("
"); } - out.print( generateHtmlForTime(getId(),editConfig,editSub) ); - if (definitionTags) { out.print("
\n"); } - } else if ( getType().equalsIgnoreCase("datetime") || - (field != null && field.getRangeDatatypeUri() != null && field.getRangeDatatypeUri().equals(XSD.dateTime.getURI()))) { - if (definitionTags) { out.print("
"); } - out.print( generateHtmlForDateTime(getId(),editConfig,editSub) ); - if (definitionTags) { out.print("
\n"); } - } else if( getType().equalsIgnoreCase("text")) { - String valueStr = doValue(editConfig, editSub); - String sizeStr = doSize(); - if (definitionTags) { out.print("
"); } - out.print(""); - if (definitionTags) { out.print("
"); } - out.println(); - // Handle hidden inputs where Javascript writes a value that needs to be returned with an invalid submission. - } else if( getType().equalsIgnoreCase("hidden")) { - String valueStr = doValue(editConfig, editSub); - if (definitionTags) { out.print("
"); } - out.print(""); - if (definitionTags) { out.print("
"); } - out.println(); - } else if (getType().equalsIgnoreCase("textarea")) { - String valueStr = doValue(editConfig, editSub); - String rowStr = doRows(); - String colStr = doCols(); - if (definitionTags) { out.print("
"); } - out.print(""); - if (definitionTags) { out.print("
"); } - out.println(); - } else if( getType().equalsIgnoreCase("select")) { - String valueStr = doValue(editConfig, editSub); - //String sizeStr = getSize(); //"style=\"width:"+getSize()+"%;\""; - Map optionsMap = (Map) pageContext.getRequest().getAttribute("rangeOptions." + getId()); - if (optionsMap == null) { - optionsMap = SelectListGenerator.getOptions(editConfig,getName(), wdf); - } - if (optionsMap==null){ - log.error("Error in InputElementFormattingTag.doStartTag(): null optionsMap returned from getOptions()"); - } - if (optionsMap.size()>0) { // e.g., an Educational Background where may be no choices left after remove existing - if (definitionTags) { out.print("
"); } - if (multiple!=null && !multiple.equals("")) { - out.print(""); - } - - Field thisField = editConfig.getField(getName()); - if (! thisField.getOptionsType().equals(Field.OptionsType.HARDCODED_LITERALS)) { - optionsMap = getSortedMap(optionsMap); - } - Iterator iter = optionsMap.keySet().iterator(); - while (iter.hasNext()) { - String key = (String) iter.next(); - String mapValue = optionsMap.get(key); - out.print(" "); - } - out.print(""); - if (definitionTags) { out.print("
"); } - } else { - out.println("

no appropriate choice available

"); - } - } else if( getType().equalsIgnoreCase("checkbox")) { - String valueStr = doValue(editConfig, editSub); - if (definitionTags) { out.print("
"); } - Map optionsMap = (Map) pageContext.getRequest().getAttribute("rangeOptions." + getId()); - if (optionsMap == null) { - optionsMap = SelectListGenerator.getOptions(editConfig,getName(),wdf); - } - if (optionsMap==null){ - log.error("Error in InputElementFormattingTag.doStartTag(): null optionsMap returned from getOptions()"); - } - optionsMap = getSortedMap(optionsMap); - Iterator iter = optionsMap.keySet().iterator(); - while (iter.hasNext()) { - String key = (String) iter.next(); - String mapValue = optionsMap.get(key); - out.print(""+ StringEscapeUtils.escapeHtml(trim(mapValue,getSize())) +""); - } - if (definitionTags) { out.print("
"); } - } else if( getType().equalsIgnoreCase("radio")) { - String valueStr = doValue(editConfig, editSub); - if (definitionTags) { out.print("
"); } - Map optionsMap = (Map) pageContext.getRequest().getAttribute("rangeOptions." + getId()); - if (optionsMap == null) { - optionsMap = SelectListGenerator.getOptions(editConfig,getName(),wdf); - } - if (optionsMap==null){ - log.error("Error in InputElementFormattingTag.doStartTag(): null optionsMap returned from getOptions()"); - } - optionsMap = getSortedMap(optionsMap); - Iterator iter = optionsMap.keySet().iterator(); - while (iter.hasNext()) { - String key = (String) iter.next(); - String mapValue = optionsMap.get(key); - out.print(""+ StringEscapeUtils.escapeHtml(trim(mapValue,getSize())) +""); - } - if (definitionTags) { out.print("
"); } - } else if( getType().equalsIgnoreCase("file")) { - - String fieldName = getName(); - if( editConfig.getUrisInScope().containsKey(fieldName) ){ - //if there is a link to a file Individual then this is - //a update and we should just disable the control - out.println(""); - } else { - if(definitionTags) {out.print("
");} - out.print(""); - if(definitionTags) {out.print("
");} - out.print("\n"); - } - } else if( getType().equalsIgnoreCase("cancel")) { - out.println(doCancel(getLabel(),editConfig)); - } else if( getType().equalsIgnoreCase("submit")) { // add cancel URL, too - - if( editConfig != null && editConfig.getEditKey() != null ) - out.println(""); - - out.println(""); - out.println( doCancel("",editConfig) ); - } else if( getType().equals("typesForCreateNew")){ - - //this is only for use on the defaultObjPropForm.jsp to create a select list of types. - Map optionsMap = getTypesForCreateNew(editConfig,wdf); - if (optionsMap==null){ - log.error("Error in InputElementFormattingTag.doStartTag(): null optionsMap returned from getTypesForCreateNew()"); - } - if (optionsMap.size()>0) { - if (definitionTags) { out.print("
"); } - out.print(""); - if (definitionTags) { out.print("
"); } - } - - } else if( getType().equalsIgnoreCase("editKey")) { - log.warn("Input element of type editKey was ignored, editKey fields are created by InputElementFormat submit and cancel."); - } - //added this for general form validation errors - else if(getType().equalsIgnoreCase("formerror")) { - //print nothing since error string still printed below - } - else { // among other things, not supporting input type "reset" - log.error("Error in InputElementFormattingTag.doStartTag(): unknown input element type "+getType()); - } - - if( errorStr!=null && !errorStr.equals("")) { - out.println("

"+errorStr+"

"); - } - } catch (IOException ex) { - log.error("Error in doStartTag: " + ex.getMessage()); - } - return SKIP_BODY; - } - - - - - - private Map getTypesForCreateNew( - EditConfiguration editConfig, WebappDaoFactory wdf) { - ObjectProperty op = - wdf.getObjectPropertyDao().getObjectPropertyByURI(editConfig.getPredicateUri()); - - Individual sub = - wdf.getIndividualDao().getIndividualByURI(editConfig.getSubjectUri()); - - List vclasses = null; - vclasses = wdf.getVClassDao().getVClassesForProperty(sub.getVClassURI(), op.getURI()); - if( vclasses == null ) - vclasses = wdf.getVClassDao().getAllVclasses(); - - HashMap types = new HashMap(); - for( VClass vclass : vclasses ){ - - String name = null; - if( vclass.getPickListName() != null && vclass.getPickListName().length() > 0){ - name = vclass.getPickListName(); - }else if( vclass.getName() != null && vclass.getName().length() > 0){ - name = vclass.getName(); - }else if (vclass.getLocalNameWithPrefix() != null && vclass.getLocalNameWithPrefix().length() > 0){ - name = vclass.getLocalNameWithPrefix(); - } - if( name != null && name.length() > 0) - types.put(vclass.getURI(),name); - } - return types; - } - - - private String trim(String in, int sizeLimit){ - if (sizeLimit>0 && in.trim().length()>(sizeLimit+4)) - return in.trim().substring(0,sizeLimit)+" ..."; - else - return in.trim(); - } - - public int doEndTag(){ - return EVAL_PAGE; - } - - // from http://forum.java.sun.com/thread.jspa?threadID=639077&messageID=4250708 - public Map getSortedMap(Map hmap){ - // first make temporary list of String arrays holding both the key and its corresponding value, so that the list can be sorted with a decent comparator - List objectsToSort = new ArrayList(hmap.size()); - for (String key:hmap.keySet()) { - String[] x = new String[2]; - x[0] = key; - x[1] = hmap.get(key); - objectsToSort.add(x); - } - Collections.sort(objectsToSort, new MapPairsComparator()); - - HashMap map = new LinkedHashMap(objectsToSort.size()); - for (String[] pair:objectsToSort) { - map.put(pair[0],pair[1]); - } - return map; - } - - private class MapPairsComparator implements Comparator { - public int compare (String[] s1, String[] s2) { - Collator collator = Collator.getInstance(); - if (s2 == null) { - return 1; - } else if (s1 == null) { - return -1; - } else { - if ("".equals(s1[0])) { - return -1; - } else if ("".equals(s2[0])) { - return 1; - } - if (s2[1]==null) { - return 1; - } else if (s1[1] == null){ - return -1; - } else { - return collator.compare(s1[1],s2[1]); - } - } - } - } - - private String generateHtmlForDate(String fieldName, - EditConfiguration editConfig, EditSubmission editSub) { - Date dateFromLit = null; - String dateStrFromLit = null; - if( editSub != null && editSub.getLiteralsFromForm() != null && - editSub.getLiteralsFromForm().get(fieldName) != null ){ - //found the field on the EditSubmission - Literal date = editSub.getLiteralsFromForm().get(fieldName); - Object valueFromLiteral = date.getValue(); - if( valueFromLiteral != null && valueFromLiteral instanceof Date){ - dateFromLit = (Date)valueFromLiteral; - log.debug("found literal in submission of type Date for field " + fieldName); - }else if( valueFromLiteral != null && valueFromLiteral instanceof String){ - dateStrFromLit = (String) valueFromLiteral; - log.debug("found literal in submission of type String for field " + fieldName); - } else if ( valueFromLiteral != null && valueFromLiteral instanceof XSDDateTime) { - dateStrFromLit = date.getLexicalForm(); - log.debug("found existing literal of type XSDDateTime for field " + fieldName); - } else { - log.error("found a value from the submsission but it was not a String or Date."); - } - }else if( editConfig != null && editConfig.getLiteralsInScope() != null - && editConfig.getLiteralsInScope().containsKey(fieldName)){ - //No EditSubmission found, try to get an existing value - Literal date = editConfig.getLiteralsInScope().get(fieldName); - Object valueFromLiteral = date.getValue(); - if( valueFromLiteral != null && valueFromLiteral instanceof Date){ - dateFromLit = (Date)valueFromLiteral; - log.debug("found existing literal of type Date for field " + fieldName); - }else if( valueFromLiteral != null && valueFromLiteral instanceof String){ - dateStrFromLit = (String) valueFromLiteral; - log.debug("found exisitng literal of type String for field " + fieldName); - } else if ( valueFromLiteral != null && valueFromLiteral instanceof XSDDateTime) { - dateStrFromLit = date.getLexicalForm(); - log.debug("found existing literal of type XSDDateTime for field " + fieldName); - } else { - log.error("found an existing value from the editConfig but it was not a String or Date:"); - log.error(valueFromLiteral.getClass().getName()); - } - }else{ - //try to get default value - - Field field = editConfig.getField(fieldName); - List> options = field.getLiteralOptions(); - if( options.size() >=1 && options.get(0) != null && - options.get(0).size() >= 1 && options.get(0).get(0) != null){ - dateStrFromLit = options.get(0).get(0); - }else{ - - log.debug("no default found for field " + fieldName); - } - } - - - - DateTime dt = null; - if( dateStrFromLit != null){ - try { - /* See: - * http://joda-time.sourceforge.net/api-release/org/joda/time/format/ISODateTimeFormat.html#dateParser() - * for date format information*/ - DateTimeFormatter dtFmt = ISODateTimeFormat.dateParser(); - dt = new DateTime( dtFmt.parseDateTime( dateStrFromLit )); - } catch (Exception e) { - log.warn("Could not convert '" + dateStrFromLit +"' to DateTime.",e); - dt = null; - } - }else if (dateFromLit != null){ - dt = new DateTime(dateFromLit); - } - - int year = 0; // negative years (BCE) are legal, but 0 isn't (treat as null) - int month = -1; - int day = -1; - - //if( dt == null ) - // dt = new DateTime(); - - if (dt != null) { - year = dt.getYear(); - month = dt.getMonthOfYear(); - day = dt.getDayOfMonth(); - } - - String sb = ""; - - sb += "
\n"; - sb += " \n"; - sb += " \n"; - sb += " \n"; - sb += " \n"; - sb += " \n"; - sb += " \n"; - sb += " \n"; - sb += "
\n"; - if(fieldName.equals("expectedPublicationDateEdited")) { - - sb += ""; - } - return sb; - } - - - public String generateHtmlForTime(String fieldName, - EditConfiguration editConfig, EditSubmission editSub ) { - DateTime dt = null; - - int hour = -1; - int minute = -1; - - if( editSub != null && editSub.getLiteralsFromForm() != null && - editSub.getLiteralsFromForm().get(fieldName) != null ){ - //found the field on the EditSubmission - Literal time = editSub.getLiteralsFromForm().get(fieldName); - Object valueFromLiteral = time.getValue(); - if( valueFromLiteral != null && valueFromLiteral instanceof XSDDateTime){ - XSDDateTime xsdDateTime = (XSDDateTime) valueFromLiteral; - hour = xsdDateTime.getHours(); - minute = xsdDateTime.getMinutes(); - log.debug("found literal of type XSDDateTime for field " + fieldName); - }else{ - try { - /* See: - * http://joda-time.sourceforge.net/api-release/org/joda/time/format/ISODateTimeFormat.html#dateParser() - * for date format information*/ - DateTimeFormatter dtFmt = ISODateTimeFormat.dateParser(); - dt = new DateTime( dtFmt.parseDateTime(time.getLexicalForm())); - //what about timezones? - log.debug("found string literal with lexical form '" - + time.getLexicalForm()+ "' and convered into DateTime."); - } catch (Exception e) { - log.warn("Could not convert lexical form '" - + time.getLexicalForm() +"' to DateTime.",e); - // dt = new DateTime(); - } - } - }else if( editConfig != null && editConfig.getLiteralsInScope() != null - && editConfig.getLiteralsInScope().containsKey(fieldName)){ - //No EditSubmission found, try to get an existing value - Literal time = editConfig.getLiteralsInScope().get(fieldName); - Object valueFromLiteral = time.getValue(); - if (valueFromLiteral instanceof XSDDateTime) { - XSDDateTime xsddt = (XSDDateTime) valueFromLiteral; - hour = xsddt.getHours(); - minute = xsddt.getMinutes(); - } else { - log.warn("Unrecognizeed value of type " + - valueFromLiteral.getClass().getName() + - " for time value in field " + fieldName); - } - }else{ - //No EditSubmission found, try to get default value from EditConfig - Field field = editConfig.getField(fieldName); - List> options = field.getLiteralOptions(); - if( options.size() >=1 && options.get(0) != null && - options.get(0).size() >= 1 && options.get(0).get(0) != null){ - String defaultValue = options.get(0).get(0); - try { - /* See: - * http://joda-time.sourceforge.net/api-release/org/joda/time/format/ISODateTimeFormat.html#dateParser() - * for date format information*/ - //DateTimeFormatter dtFmt = ISODateTimeFormat.dateParser(); - //dt = new DateTime( dtFmt.parseDateTime(defaultValue) ); - dt = new DateTime( defaultValue ); - //what about timezones? currently we use local. - log.debug("found default value of " + defaultValue + " and converted into DateTime."); - } catch (RuntimeException e) { - log.warn("Could not parse '" + defaultValue +"' into DateTime" , e); - //dt = new DateTime(); - } - }else{ - log.debug("no default found for field " + fieldName); - } - } - - - //if( dt == null ) - // dt = new DateTime(); - - if (dt != null) { - hour = dt.getHourOfDay(); - minute = dt.getMinuteOfHour(); - } - - String sb = "
\n"; - - sb += generateMarkupForTime(fieldName, hour, minute); - - sb += "
\n"; - - return sb; - } - - public String generateMarkupForTime(String fieldName, int hour, int minute) { - StringBuffer sb = new StringBuffer(); - sb.append("
"); - sb.append(" \n"); - sb.append(" \n"); - sb.append(" \n"); - sb.append(" \n"); - sb.append(" \n"); - sb.append("
"); - return sb.toString(); - } - - public String generateHtmlForDateTime(String fieldName, - EditConfiguration editConfig, EditSubmission editSub ){ - DateTime dt = null; - if( editSub != null && editSub.getLiteralsFromForm() != null && - editSub.getLiteralsFromForm().get(fieldName) != null ){ - //found the field on the EditSubmission - Literal date = editSub.getLiteralsFromForm().get(fieldName); - Object valueFromLiteral = date.getValue(); - if( valueFromLiteral != null && valueFromLiteral instanceof Date){ - dt = new DateTime( (Date)valueFromLiteral); - log.debug("found literal of type Date for field " + fieldName); - }else{ - try { - /* See: - * http://joda-time.sourceforge.net/api-release/org/joda/time/format/ISODateTimeFormat.html#dateParser() - * for date format information*/ - DateTimeFormatter dtFmt = ISODateTimeFormat.dateParser(); - dt = new DateTime( dtFmt.parseDateTime(date.getLexicalForm())); - //what about timezones? - log.debug("found string literal with lexical form '" - + date.getLexicalForm()+ "' and convered into DateTime."); - } catch (Exception e) { - log.warn("Could not convert lexical form '" - + date.getLexicalForm() +"' to DateTime.",e); - dt = new DateTime(); - } - } - }else if( editConfig != null && editConfig.getLiteralsInScope() != null - && editConfig.getLiteralsInScope().containsKey(fieldName)){ - //No EditSubmission found, try to get an existing value - Literal date = editConfig.getLiteralsInScope().get(fieldName); - Object valueFromLiteral = date.getValue(); - String strFromLit = null; - Date dateFromLit = null; - if( valueFromLiteral != null){ - if( valueFromLiteral instanceof Date){ - dateFromLit = (Date)valueFromLiteral; - log.debug("found existing literal of type Date for field " + fieldName); - }else if( valueFromLiteral instanceof String){ - strFromLit = (String) valueFromLiteral; - log.debug("found existing literal of type String for field " + fieldName); - } else if ( valueFromLiteral instanceof XSDDateTime) { - strFromLit = date.getLexicalForm(); - log.debug("found existing literal of type XSDDateTime for field " + fieldName); - } else { - log.error("found an existing value for field " + fieldName - + "but it was not a String or Date:" - + valueFromLiteral.getClass().getName()); - } - - if( dateFromLit != null ){ - dt = new DateTime(dateFromLit); - }else{ - //DateTimeFormatter dtFmt = ISODateTimeFormat.dateParser(); - //dt = new DateTime( dtFmt.parseDateTime(strFromLit) ); - dt = new DateTime( strFromLit ); - } - } - }else{ - //No EditSubmission found, try to get default value from EditConfig - Field field = editConfig.getField(fieldName); - List> options = field.getLiteralOptions(); - if( options.size() >=1 && options.get(0) != null && - options.get(0).size() >= 1 && options.get(0).get(0) != null){ - String defaultValue = options.get(0).get(0); - try { - /* See: - * http://joda-time.sourceforge.net/api-release/org/joda/time/format/ISODateTimeFormat.html#dateParser() - * for date format information*/ - //DateTimeFormatter dtFmt = ISODateTimeFormat.dateParser(); - //dt = new DateTime( dtFmt.parseDateTime(defaultValue) ); - dt = new DateTime( defaultValue ); - //what about timezones? currently we use local. - log.debug("found default value of " + defaultValue + " and converted into DateTime."); - } catch (RuntimeException e) { - log.warn("Could not parse '" + defaultValue +"' into DateTime" , e); - dt = new DateTime(); - } - }else{ - log.debug("no default found for field " + fieldName); - } - } - - int year = 0; // negative years (BCE) are legal, but 0 isn't (treat as null) - int month = -1; - int day = -1; - int hour = -1; - int minute = -1; - - //if( dt == null ) - // dt = new DateTime(); - - if (dt != null) { - year = dt.getYear(); - month = dt.getMonthOfYear(); - day = dt.getDayOfMonth(); - hour = dt.getHourOfDay(); - minute = dt.getMinuteOfHour(); - } - - String sb = ""; - - sb += "
\n"; - sb += " \n"; - sb += " \n"; - sb += " \n"; - sb += " \n"; - sb += " \n"; - sb += " \n"; - sb += " \n"; - sb += " \n"; - - sb += generateMarkupForTime(fieldName, hour, minute); - - sb += "
\n"; - - return sb; - } - - final String SELECTED = "selected=\"selected\""; -} \ No newline at end of file diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/web/templatemodels/edit/EditSubmissionTemplateModel.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/web/templatemodels/edit/EditSubmissionTemplateModel.java deleted file mode 100644 index d9ea48a2a..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/web/templatemodels/edit/EditSubmissionTemplateModel.java +++ /dev/null @@ -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 getLiteralsFromForm() { - if(editSub == null) - return null; - return editSub.getLiteralsFromForm(); - } - - public Map getValidationErrors() { - if(editSub == null) - return null; - return editSub.getValidationErrors(); - } - - public Map getUrisFromForm() { - if(editSub == null) - return null; - return editSub.getUrisFromForm(); - } - -} diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/web/widgets/SelectListWidget.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/web/widgets/SelectListWidget.java deleted file mode 100644 index a2976656b..000000000 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/web/widgets/SelectListWidget.java +++ /dev/null @@ -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 selectOptions = SelectListGenerator.getOptions(editConfig, fieldName, wdf); - Map rmap = new HashMap(); - rmap.put("selectList", selectOptions); - - return new WidgetTemplateValues("markup", rmap); - } - -} diff --git a/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/BasicValidationTest.java b/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/BasicValidationTest.java deleted file mode 100644 index cd60ae8ec..000000000 --- a/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/BasicValidationTest.java +++ /dev/null @@ -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); - } - -} diff --git a/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/EditN3GeneratorTest.java b/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/EditN3GeneratorTest.java deleted file mode 100644 index adf85fe28..000000000 --- a/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/EditN3GeneratorTest.java +++ /dev/null @@ -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 varToExisting= new HashMap(); - varToExisting.put("bob", "http://uri.edu#BobTheElder"); - varToExisting.put("bobJr", "http://uri.edu#BobTheSon"); - - String target = "SELECT ?cat WHERE{ ?bobJr ?cat }" ; - List targets = new ArrayList(); - targets.add(target); - - List out = en3g.subInUris(varToExisting, targets); - Assert.assertNotNull(out); - Assert.assertNotNull( out.get(0) ); - String expected = "SELECT ?cat WHERE{ ?cat }"; - Assert.assertEquals(expected, out.get(0) ); - - //force a non match on a initial-partial var name - varToExisting= new HashMap(); - varToExisting.put("bob", "http://uri.edu#BobTheElder"); - - target = "SELECT ?cat WHERE{ ?bobJr ?cat }" ; - targets = new ArrayList(); - targets.add(target); - - out = en3g.subInUris(varToExisting, targets); - Assert.assertNotNull(out); - Assert.assertNotNull( out.get(0) ); - expected = target; - Assert.assertEquals(expected, out.get(0) ); - - } - -} diff --git a/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/EditSubmissionTest.java b/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/EditSubmissionTest.java deleted file mode 100644 index 616f0cf4e..000000000 --- a/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/EditSubmissionTest.java +++ /dev/null @@ -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); - } -} diff --git a/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/SparqlEvaluateTest.java b/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/SparqlEvaluateTest.java deleted file mode 100644 index e4ba6909e..000000000 --- a/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/SparqlEvaluateTest.java +++ /dev/null @@ -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 } "); - Assert.assertNull( uri ); - } - -} diff --git a/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/processEdit/EditN3GeneratorTest.java b/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/processEdit/EditN3GeneratorTest.java deleted file mode 100644 index ff6149063..000000000 --- a/webapp/test/edu/cornell/mannlib/vitro/webapp/edit/n3editing/processEdit/EditN3GeneratorTest.java +++ /dev/null @@ -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 varToExisting= new HashMap(); - varToExisting.put("bob", "http://uri.edu#BobTheElder"); - varToExisting.put("bobJr", "http://uri.edu#BobTheSon"); - - String target = "SELECT ?cat WHERE{ ?bobJr ?cat }" ; - List targets = new ArrayList(); - targets.add(target); - - List out = en3g.subInUris(varToExisting, targets); - Assert.assertNotNull(out); - Assert.assertNotNull( out.get(0) ); - String expected = "SELECT ?cat WHERE{ ?cat }"; - Assert.assertEquals(expected, out.get(0) ); - - //force a non match on a initial-partial var name - varToExisting= new HashMap(); - varToExisting.put("bob", "http://uri.edu#BobTheElder"); - - target = "SELECT ?cat WHERE{ ?bobJr ?cat }" ; - targets = new ArrayList(); - targets.add(target); - - out = en3g.subInUris(varToExisting, targets); - Assert.assertNotNull(out); - Assert.assertNotNull( out.get(0) ); - expected = target; - Assert.assertEquals(expected, out.get(0) ); - - } - -}