Improve output: distinguish between failed assertions (failures) and unexpected exceptions (errors), and print a filtered stack trace for any exception.

This commit is contained in:
jeb228 2010-01-29 22:13:57 +00:00
commit 4f2e303079
1839 changed files with 235630 additions and 0 deletions

11
webapp/web/about.jsp Normal file
View file

@ -0,0 +1,11 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<div id="content">
<h2>${title}</h2>
<div class="pageGroupBody" id="aboutText">${aboutText}</div>
<div class="pageGroupBody" id="acknowledgementText">${acknowledgeText}</div>
</div> <!-- content -->

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,114 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<html>
<%@ page contentType="text/html; charset=utf-8" %>
<%
/*
* Copyright 2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
%>
<%@ include file="i18nLib.jsp" %>
<%
// initialize a private HttpServletRequest
setRequest(request);
// set a resouce base
setResouceBase("i18n");
%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Apache-Axis</title>
</head>
<body bgcolor="#FFFFFF">
<h1 align="center">Apache-AXIS</h1>
<%= getLocaleChoice() %>
<%
out.print(getMessage("welcomeMessage")+"<p/>");
out.print(getMessage("operationType"));
%>
<ul>
<li>
<%
out.print("<a href=\""+ getMessage("validationURL") +"\">");
out.print(getMessage("validation") +"</a> - ");
out.print(getMessage("validationFootnote00") +"<br>");
out.print("<i>"+ getMessage("validationFootnote01") +"</i>");
%>
</li>
<li>
<%
out.print("<a href=\""+ getMessage("serviceListURL") +"\">");
out.print(getMessage("serviceList") +"</a> - ");
out.print(getMessage("serviceListFootnote"));
%>
</li>
<li>
<%
out.print("<a href=\""+ getMessage("callAnEndpointURL") +"\">");
out.print(getMessage("callAnEndpoint") +"</a> - ");
out.print(getMessage("callAnEndpointFootnote00") +" ");
out.print(getMessage("callAnEndpointFootnote01"));
%>
</li>
<li>
<%
out.print("<a href=\""+ getMessage("visitURL") +"\">");
out.print(getMessage("visit") +"</a> - ");
out.print(getMessage("visitFootnote"));
%>
</li>
<li>
<%
out.print("<a href=\""+ getMessage("adminURL") +"\">");
out.print(getMessage("admin") +"</a> - ");
out.print(getMessage("adminFootnote"));
%>
</li>
<li>
<%
out.print("<a href=\""+ getMessage("soapMonitorURL") +"\">");
out.print(getMessage("soapMonitor") +"</a> - ");
out.print(getMessage("soapMonitorFootnote"));
%>
</li>
</ul>
<%
out.print(getMessage("sideNote") +"<p/>");
%>
<%
out.print("<h3>"+ getMessage("validatingAxis") +"</h3>");
out.print(getMessage("validationNote00") +"<p/>");
out.print(getMessage("validationNote01"));
%>
</body>
</html>

View file

@ -0,0 +1,274 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="java.io.File,
java.io.IOException,
java.util.Date"
session="false" %>
<html>
<head>
<title>System Fingerprint</title>
</head>
<body bgcolor=#ffffff>
<%!
/*
* Fingerprint the users system. This is mainly for use in
* diagnosing classpath problems. It is intended to dump out
* a copy of the environment this webapp is running in,
* and additionally attempt to identify versions of each jar
* in the classpath.
*
* @author Brian Ewins
*/
private java.util.Properties versionProps=new java.util.Properties();
/**
* Identify the version of a jar file. This uses a properties file
* containing known names and sizes in the format
* 'name(size)=version'. Version strings should be like 'xerces-1.4'
* ie they should include the name of the library.
*/
public String getFileVersion(File file) throws IOException {
String key="<td>"+file.getName()+"</td>";
key+= "<td>"+file.length()+"</td>";
Date timestamp=new Date(file.lastModified());
key+= "<td>"+timestamp.toString()+"</td>";
return key;
/* TODO: implement
String value=versionProps.getProperty(key);
if (value==null) {
// make it possible to have jars without version nos
value=versionProps.getProperty(file.getName());
}
if (value==null) {
// fall back on something obvious
value=key;
Date timestamp=new Date(file.lastModified());
value+=" / "+timestamp.toString();
}
return value;
*/
}
/**
* Split up a classpath-like variable. Returns a list of files.
* TODO: this can't cope with relative paths. I think theres code in BCEL that
* can be used for this?
*/
File[] splitClasspath(String path) throws IOException {
java.util.StringTokenizer st=
new java.util.StringTokenizer(path,
System.getProperty("path.separator"));
int toks=st.countTokens();
File[] files=new File[toks];
for(int i=0;i<toks;i++) {
files[i]=new File(st.nextToken());
}
return files;
}
/** given a list of files, return a list of jars which actually exist */
File[] scanFiles(File[] files) throws IOException {
File[] jars=new File[files.length];
int found=0;
for (int i=0; i<files.length; i++) {
if (files[i].getName().toLowerCase().endsWith(".jar")
&& files[i].exists()) {
jars[found]=files[i];
found++;
}
}
if (found<files.length) {
File[] temp=new File[found];
System.arraycopy(jars,0,temp,0,found);
jars=temp;
}
return jars;
}
private static final File[] NO_FILES=new File[0];
/** scan a directory for jars */
public File[] scanDir(String dir) throws IOException
{
if(dir==null) {
return NO_FILES;
}
return scanDir(new File(dir));
}
public File[] scanDir(File dir) throws IOException {
if (!dir.exists() || !dir.isDirectory()) {
return NO_FILES;
}
return scanFiles(dir.listFiles());
}
/** scan a classpath for jars */
public File[] scanClasspath(String path) throws IOException {
if (path==null) {
return NO_FILES;
}
return scanFiles(splitClasspath(path));
}
/**
* scan a 'dirpath' (like the java.ext.dirs system property) for jars
*/
public File[] scanDirpath(String path) throws IOException {
if (path==null) {
return NO_FILES;
}
File[] current=new File[0];
File[] dirs=splitClasspath(path);
for(int i=0; i<dirs.length; i++) {
File[] jars=scanDir(dirs[i]);
File[] temp=new File[current.length+jars.length];
System.arraycopy(current,0,temp,0,current.length);
System.arraycopy(jars,0,temp,current.length,jars.length);
current=temp;
}
return scanFiles(current);
}
/** print out the jar versions for a directory */
public void listDirectory(String title, JspWriter out,String dir, String comment) throws IOException {
listVersions(title, out,scanDir(dir), comment);
}
/** print out the jar versions for a directory-like system property */
public void listDirProperty(String title, JspWriter out,String key, String comment) throws IOException {
listVersions(title, out,scanDir(System.getProperty(key)), comment);
}
/** print out the jar versions for a classpath-like system property */
public void listClasspathProperty(String title, JspWriter out,String key, String comment) throws IOException {
listVersions(title, out,scanClasspath(System.getProperty(key)), comment);
}
/** print out the jar versions for a 'java.ext.dirs'-like system property */
public void listDirpathProperty(String title, JspWriter out,String key, String comment) throws IOException {
listVersions(title, out,scanDirpath(System.getProperty(key)), comment);
}
/** print out the jar versions for a context-relative directory */
public void listContextPath(String title, JspWriter out, String path, String comment) throws IOException {
listVersions(title, out,scanDir(getServletConfig().getServletContext().getRealPath(path)), comment);
}
/** print out the jar versions for a given list of files */
public void listVersions(String title, JspWriter out,File[] jars, String comment) throws IOException {
out.print("<h2>");
out.print(title);
out.println("</h2>");
out.println("<table>");
for (int i=0; i<jars.length; i++) {
out.println("<tr>"+getFileVersion(jars[i])+"</tr>");
}
out.println("</table>");
if(comment!=null && comment.length()>0) {
out.println("<p>");
out.println(comment);
out.println("<p>");
}
}
%>
<h1>System Fingerprint</h1>
<h2>JVM and Server Version</h2>
<table>
<tr>
<td>Servlet Engine</td>
<td><%= getServletConfig().getServletContext().getServerInfo() %></td>
<td><%= getServletConfig().getServletContext().getMajorVersion() %></td>
<td><%= getServletConfig().getServletContext().getMinorVersion() %></td>
</tr>
<tr>
<td>Java VM</td>
<td><%= System.getProperty("java.vm.vendor") %></td>
<td><%= System.getProperty("java.vm.name") %></td>
<td><%= System.getProperty("java.vm.version") %></td>
</tr>
<tr>
<td>Java RE</td>
<td><%= System.getProperty("java.vendor") %></td>
<td><%= System.getProperty("java.version") %></td>
<td> </td>
</tr>
<tr>
<td>Platform</td>
<td><%= System.getProperty("os.name") %></td>
<td><%= System.getProperty("os.arch") %></td>
<td><%= System.getProperty("os.version") %></td>
</tr>
</table>
<%
listClasspathProperty("Boot jars", out,"sun.boot.class.path", "Only valid on a sun jvm");
listClasspathProperty("System jars", out,"java.class.path", null);
listDirpathProperty("Extra system jars", out,"java.ext.dirs", null);
listContextPath("Webapp jars", out, "/WEB-INF/lib", null);
// identify the container...
String container=getServletConfig().getServletContext().getServerInfo();
if (container.startsWith("Tomcat Web Server/3.2")) {
String home=System.getProperty("tomcat.home");
if(home!=null) {
listDirectory("Tomcat 3.2 Common Jars", out,
home+File.separator
+"lib",
null);
}
} else if (container.startsWith("Tomcat Web Server/3.3")) {
String home=System.getProperty("tomcat.home");
if(home!=null) {
listDirectory("Tomcat 3.3 Container Jars", out,
home+File.separator
+"lib"+File.separator
+"container",
null);
listDirectory("Tomcat 3.3 Common Jars", out,
home+File.separator
+"lib"+File.separator
+"common",
null);
}
} else if (container.startsWith("Apache Tomcat/4.0")) {
//handle catalina common dir
String home=System.getProperty("catalina.home");
if(home!=null) {
listDirectory("Tomcat 4.0 Common Jars", out,
home+File.separator
+"common"+File.separator
+"lib",
null);
}
} else if (container.startsWith("Apache Tomcat/4.1")) {
//handle catalina common dir
String home=System.getProperty("catalina.home");
if(home!=null) {
listDirectory("Tomcat 4.1 Common Jars", out,
home+File.separator
+"shared"+File.separator
+"lib",
null);
}
} else if (System.getProperty("resin.home")!=null) {
String home=System.getProperty("resin.home");
if(home!=null) {
listDirectory("Resin Common Jars", out,
home+File.separator
+"lib",
null);
}
} else if (System.getProperty("weblogic.httpd.servlet.classpath")!=null) {
listClasspathProperty("Weblogic Servlet Jars", out,
"weblogic.httpd.servlet.classpath",
null);
} else {
//TODO: identify more servlet engine classpaths.
}
%>
</body>
</html>

View file

@ -0,0 +1,493 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<html>
<%@ page contentType="text/html; charset=utf-8"
import="java.io.InputStream,
java.io.IOException,
javax.xml.parsers.SAXParser,
java.lang.reflect.*,
javax.xml.parsers.SAXParserFactory"
session="false" %>
<%
/*
* Copyright 2002,2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
%>
<%!
/*
* Happiness tests for axis. These look at the classpath and warn if things
* are missing. Normally addng this much code in a JSP page is mad
* but here we want to validate JSP compilation too, and have a drop-in
* page for easy re-use
* @author Steve 'configuration problems' Loughran
* @author dims
* @author Brian Ewins
*/
/**
* test for a class existing
* @param classname
* @return class iff present
*/
Class classExists(String classname) {
try {
return Class.forName(classname);
} catch (ClassNotFoundException e) {
return null;
}
}
/**
* test for resource on the classpath
* @param resource
* @return true iff present
*/
boolean resourceExists(String resource) {
boolean found;
InputStream instream=this.getClass().getResourceAsStream(resource);
found=instream!=null;
if(instream!=null) {
try {
instream.close();
} catch (IOException e) {
}
}
return found;
}
/**
* probe for a class, print an error message is missing
* @param out stream to print stuff
* @param category text like "warning" or "error"
* @param classname class to look for
* @param jarFile where this class comes from
* @param errorText extra error text
* @param homePage where to d/l the library
* @return the number of missing classes
* @throws IOException
*/
int probeClass(JspWriter out,
String category,
String classname,
String jarFile,
String description,
String errorText,
String homePage) throws IOException {
try {
Class clazz = classExists(classname);
if(clazz == null) {
String url="";
if(homePage!=null) {
url=getMessage("seeHomepage",homePage,homePage);
}
out.write(getMessage("couldNotFound",category,classname,jarFile,errorText,url));
return 1;
} else {
String location = getLocation(out, clazz);
if(location == null) {
out.write("<li>"+getMessage("foundClass00",description,classname)+"</li><br>");
}
else {
out.write("<li>"+getMessage("foundClass01",description,classname,location)+"</li><br>");
}
return 0;
}
} catch(NoClassDefFoundError ncdfe) {
String url="";
if(homePage!=null) {
url=getMessage("seeHomepage",homePage,homePage);
}
out.write(getMessage("couldNotFoundDep",category, classname, errorText, url));
out.write(getMessage("theRootCause",ncdfe.getMessage(), classname));
return 1;
}
}
/**
* get the location of a class
* @param out
* @param clazz
* @return the jar file or path where a class was found
*/
String getLocation(JspWriter out,
Class clazz) {
try {
java.net.URL url = clazz.getProtectionDomain().getCodeSource().getLocation();
String location = url.toString();
if(location.startsWith("jar")) {
url = ((java.net.JarURLConnection)url.openConnection()).getJarFileURL();
location = url.toString();
}
if(location.startsWith("file")) {
java.io.File file = new java.io.File(url.getFile());
return file.getAbsolutePath();
} else {
return url.toString();
}
} catch (Throwable t){
}
return getMessage("classFoundError");
}
/**
* a class we need if a class is missing
* @param out stream to print stuff
* @param classname class to look for
* @param jarFile where this class comes from
* @param errorText extra error text
* @param homePage where to d/l the library
* @throws IOException when needed
* @return the number of missing libraries (0 or 1)
*/
int needClass(JspWriter out,
String classname,
String jarFile,
String description,
String errorText,
String homePage) throws IOException {
return probeClass(out,
"<b>"+getMessage("error")+"</b>",
classname,
jarFile,
description,
errorText,
homePage);
}
/**
* print warning message if a class is missing
* @param out stream to print stuff
* @param classname class to look for
* @param jarFile where this class comes from
* @param errorText extra error text
* @param homePage where to d/l the library
* @throws IOException when needed
* @return the number of missing libraries (0 or 1)
*/
int wantClass(JspWriter out,
String classname,
String jarFile,
String description,
String errorText,
String homePage) throws IOException {
return probeClass(out,
"<b>"+getMessage("warning")+"</b>",
classname,
jarFile,
description,
errorText,
homePage);
}
/**
* get servlet version string
*
*/
public String getServletVersion() {
ServletContext context=getServletConfig().getServletContext();
int major = context.getMajorVersion();
int minor = context.getMinorVersion();
return Integer.toString(major) + '.' + Integer.toString(minor);
}
/**
* what parser are we using.
* @return the classname of the parser
*/
private String getParserName() {
SAXParser saxParser = getSAXParser();
if (saxParser == null) {
return getMessage("couldNotCreateParser");
}
// check to what is in the classname
String saxParserName = saxParser.getClass().getName();
return saxParserName;
}
/**
* Create a JAXP SAXParser
* @return parser or null for trouble
*/
private SAXParser getSAXParser() {
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
if (saxParserFactory == null) {
return null;
}
SAXParser saxParser = null;
try {
saxParser = saxParserFactory.newSAXParser();
} catch (Exception e) {
}
return saxParser;
}
/**
* get the location of the parser
* @return path or null for trouble in tracking it down
*/
private String getParserLocation(JspWriter out) {
SAXParser saxParser = getSAXParser();
if (saxParser == null) {
return null;
}
String location = getLocation(out,saxParser.getClass());
return location;
}
/**
* Check if class implements specified interface.
* @param Class clazz
* @param String interface name
* @return boolean
*/
private boolean implementsInterface(Class clazz, String interfaceName) {
if (clazz == null) {
return false;
}
Class[] interfaces = clazz.getInterfaces();
if (interfaces.length != 0) {
for (int i = 0; i < interfaces.length; i++) {
if (interfaces[i].getName().equals(interfaceName)) {
return true;
}
}
}
return false;
}
%>
<%@ include file="i18nLib.jsp" %>
<%
// initialize a private HttpServletRequest
setRequest(request);
// set a resouce base
setResouceBase("i18n");
%>
<head>
<title><%= getMessage("pageTitle") %></title>
</head>
<body bgcolor='#ffffff'>
<%
out.print("<h1>"+ getMessage("pageTitle") +"</h1>");
out.print("<h2>"+ getMessage("pageRole") +"</h2><p/>");
%>
<%= getLocaleChoice() %>
<%
out.print("<h3>"+ getMessage("neededComponents") +"</h3>");
%>
<UL>
<%
int needed=0,wanted=0;
/**
* the essentials, without these Axis is not going to work
*/
// need to check if the available version of SAAJ API meets requirements
String className = "javax.xml.soap.SOAPPart";
String interfaceName = "org.w3c.dom.Document";
Class clazz = classExists(className);
if (clazz == null || implementsInterface(clazz, interfaceName)) {
needed = needClass(out, "javax.xml.soap.SOAPMessage",
"saaj.jar",
"SAAJ API",
getMessage("criticalErrorMessage"),
"http://ws.apache.org/axis/");
} else {
String location = getLocation(out, clazz);
out.print(getMessage("invalidSAAJ",location));
out.print(getMessage("criticalErrorMessage"));
out.print(getMessage("seeHomepage","http://ws.apache.org/axis/java/install.html",getMessage("axisInstallation")));
out.print("<br>");
}
needed+=needClass(out, "javax.xml.rpc.Service",
"jaxrpc.jar",
"JAX-RPC API",
getMessage("criticalErrorMessage"),
"http://ws.apache.org/axis/");
needed+=needClass(out, "org.apache.axis.transport.http.AxisServlet",
"axis.jar",
"Apache-Axis",
getMessage("criticalErrorMessage"),
"http://ws.apache.org/axis/");
needed+=needClass(out, "org.apache.commons.discovery.Resource",
"commons-discovery.jar",
"Jakarta-Commons Discovery",
getMessage("criticalErrorMessage"),
"http://jakarta.apache.org/commons/discovery/");
needed+=needClass(out, "org.apache.commons.logging.Log",
"commons-logging.jar",
"Jakarta-Commons Logging",
getMessage("criticalErrorMessage"),
"http://jakarta.apache.org/commons/logging/");
needed+=needClass(out, "org.apache.log4j.Layout",
"log4j-1.2.8.jar",
"Log4j",
getMessage("uncertainErrorMessage"),
"http://jakarta.apache.org/log4j");
//should we search for a javax.wsdl file here, to hint that it needs
//to go into an approved directory? because we dont seem to need to do that.
needed+=needClass(out, "com.ibm.wsdl.factory.WSDLFactoryImpl",
"wsdl4j.jar",
"IBM's WSDL4Java",
getMessage("criticalErrorMessage"),
null);
needed+=needClass(out, "javax.xml.parsers.SAXParserFactory",
"xerces.jar",
"JAXP implementation",
getMessage("criticalErrorMessage"),
"http://xml.apache.org/xerces-j/");
needed+=needClass(out,"javax.activation.DataHandler",
"activation.jar",
"Activation API",
getMessage("criticalErrorMessage"),
"http://java.sun.com/products/javabeans/glasgow/jaf.html");
%>
</UL>
<%
out.print("<h3>"+ getMessage("optionalComponents") +"</h3>");
%>
<UL>
<%
/*
* now the stuff we can live without
*/
wanted+=wantClass(out,"javax.mail.internet.MimeMessage",
"mail.jar",
"Mail API",
getMessage("attachmentsError"),
"http://java.sun.com/products/javamail/");
wanted+=wantClass(out,"org.apache.xml.security.Init",
"xmlsec.jar",
"XML Security API",
getMessage("xmlSecurityError"),
"http://xml.apache.org/security/");
wanted += wantClass(out, "javax.net.ssl.SSLSocketFactory",
"jsse.jar or java1.4+ runtime",
"Java Secure Socket Extension",
getMessage("httpsError"),
"http://java.sun.com/products/jsse/");
/*
* resources on the classpath path
*/
/* add more libraries here */
%>
</UL>
<%
out.write("<h3>");
//is everythng we need here
if(needed==0) {
//yes, be happy
out.write(getMessage("happyResult00"));
} else {
//no, be very unhappy
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
out.write(getMessage("unhappyResult00",Integer.toString(needed)));
}
//now look at wanted stuff
if(wanted>0) {
out.write(getMessage("unhappyResult01",Integer.toString(wanted)));
} else {
out.write(getMessage("happyResult01"));
}
out.write("</h3>");
%>
<UL>
<%
//hint if anything is missing
if(needed>0 || wanted>0 ) {
out.write(getMessage("hintString"));
}
out.write(getMessage("noteString"));
%>
</UL>
<h2><%= getMessage("apsExamining") %></h2>
<UL>
<%
String servletVersion=getServletVersion();
String xmlParser=getParserName();
String xmlParserLocation = getParserLocation(out);
%>
<table border="1" cellpadding="10">
<tr><td>Servlet version</td><td><%= servletVersion %></td></tr>
<tr><td>XML Parser</td><td><%= xmlParser %></td></tr>
<tr><td>XML ParserLocation</td><td><%= xmlParserLocation %></td></tr>
</table>
</UL>
<% if(xmlParser.indexOf("crimson")>=0) { %>
<p>
<%= getMessage("recommendedParser") %>
</p>
<% } %>
<h2><%= getMessage("sysExamining") %></h2>
<UL>
<%
/**
* Dump the system properties
*/
java.util.Enumeration e=null;
try {
e= System.getProperties().propertyNames();
} catch (SecurityException se) {
}
if(e!=null) {
out.write("<pre>");
for (;e.hasMoreElements();) {
String key = (String) e.nextElement();
out.write(key + "=" + System.getProperty(key)+"\n");
}
out.write("</pre><p>");
} else {
out.write(getMessage("sysPropError"));
}
%>
</UL>
<hr>
<%= getMessage("apsPlatform") %>:
<%= getServletConfig().getServletContext().getServerInfo() %>
</body>
</html>

View file

@ -0,0 +1,223 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="java.util.*" %>
<%
/*
* Copyright 2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
%>
<%!
/*
* A library file to produce i18n web applications. This can be easily
* reused from your jsp(s) - just include and call any methods.
* @author toshi
*/
// private variable
HttpServletRequest _req = null;
// private variable
String _strResourceName = null;
/**
* Set a HttpServletRequest to a private variable.
* @param request HttpServletRequest
*/
void setRequest(HttpServletRequest request) {
_req = request;
}
/**
* Get the private variable of the HttpServletRequest.
* @return HttpServletRequest
*/
HttpServletRequest getRequest() {
return _req;
}
/**
* Set a resouce base name to a private variable.
* @param resouce The resouce base name
*/
void setResouceBase(String resource) {
_strResourceName = resource;
}
/**
* Get the private variable of the resouce base name.
* @return resouce The resouce base name
*/
String getResouceBase() {
return _strResourceName;
}
/**
* Get a ResourceBundle object.
* @return a ResourceBundle object
*/
ResourceBundle getRB() {
String strLocale = getRequest().getParameter("locale");
ResourceBundle objRb = null;
Locale objLcl = null;
if (strLocale!=null) {
objLcl=new Locale(strLocale,"");
} else {
objLcl=getRequest().getLocale();
}
Locale.setDefault(objLcl);
objRb = ResourceBundle.getBundle(getResouceBase(),objLcl);
return objRb;
}
/**
* Get a list of locale choice
* @return a list of supported locales
*/
String getLocaleChoice() {
String choice = getMessage("locales");
StringBuffer buf = new StringBuffer();
buf.append("<div align=\"right\">\n");
buf.append(getMessage("language"));
buf.append(": ");
StringTokenizer st = new StringTokenizer(choice);
String locale = null;
while (st.hasMoreTokens()) {
locale = st.nextToken();
buf.append("[<a href=\"?locale="+ locale +"\">"+ locale +"</a>] ");
}
buf.append("\n</div>\n");
return buf.toString();
}
/**
* Get a message from i18n.properties with several arguments.
* @param key The resource key
* @return The formatted message
*/
String getMessage(String key) {
return getMessage(key, null, null, null, null, null);
}
/**
* Get a message from i18n.properties with several arguments.
* @param key The resource key
* @param arg0 The argument to place in variable {0}
* @return The formatted message
*/
String getMessage(String key, String arg0) {
return getMessage(key, arg0, null, null, null, null);
}
/**
* Get a message from i18n.properties with several arguments.
* @param key The resource key
* @param arg0 The argument to place in variable {0}
* @param arg1 The argument to place in variable {1}
* @return The formatted message
*/
String getMessage(String key, String arg0, String arg1) {
return getMessage(key, arg0, arg1, null, null, null);
}
/**
* Get a message from i18n.properties with several arguments.
* @param key The resource key
* @param arg0 The argument to place in variable {0}
* @param arg1 The argument to place in variable {1}
* @param arg2 The argument to place in variable {2}
* @return The formatted message
*/
String getMessage(String key, String arg0, String arg1, String arg2) {
return getMessage(key, arg0, arg1, arg2, null, null);
}
/**
* Get a message from i18n.properties with several arguments.
* @param key The resource key
* @param arg0 The argument to place in variable {0}
* @param arg1 The argument to place in variable {1}
* @param arg2 The argument to place in variable {2}
* @param arg3 The argument to place in variable {3}
* @return The formatted message
*/
String getMessage(String key, String arg0, String arg1,
String arg2, String arg3) {
return getMessage(key, arg0, arg1, arg2, arg3, null);
}
/**
* Get a message from i18n.properties with several arguments.
* @param key The resource key
* @param arg0 The argument to place in variable {0}
* @param arg1 The argument to place in variable {1}
* @param arg2 The argument to place in variable {2}
* @param arg3 The argument to place in variable {3}
* @param arg4 The argument to place in variable {4}
* @return The formatted message
*/
String getMessage(String key, String arg0, String arg1,
String arg2, String arg3, String arg4) {
String strPattern = getRB().getString(key);
String [] params = { arg0, arg1, arg2, arg3, arg4 };
for (int i=0; i<5; i++) {
if (params[i]!=null) params[i]=replaceAll(params[i],"%20"," ");
}
if (arg0!=null) strPattern = replaceAll(strPattern,"{0}",params[0]);
if (arg1!=null) strPattern = replaceAll(strPattern,"{1}",params[1]);
if (arg2!=null) strPattern = replaceAll(strPattern,"{2}",params[2]);
if (arg3!=null) strPattern = replaceAll(strPattern,"{3}",params[3]);
if (arg4!=null) strPattern = replaceAll(strPattern,"{4}",params[4]);
return strPattern;
}
/**
* Get a replaced string by the specified message.
* @param source The original message
* @param pattern The key message for replacing
* @param replace The message to place in the key variable - 'pattern'
* @return The replaced message
*/
String replaceAll(String source, String pattern, String replace)
{
int i=0;
boolean ret = false;
StringBuffer buf = new StringBuffer();
int lenSource = source.length();
int lenPattern = pattern.length();
for (i=0; i<lenSource; i++) {
ret = source.regionMatches(i, pattern, 0, lenPattern);
if (ret) {
buf.append(source.substring(0,i));
buf.append(replace);
buf.append(source.substring(i+lenPattern));
source = replaceAll(buf.toString(), pattern, replace);
break;
}
}
return source;
}
%>

View file

@ -0,0 +1,86 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ page import="edu.cornell.mannlib.vedit.beans.LoginFormBean" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.Controllers" %>
<%
if(session == null || !LoginFormBean.loggedIn(request, LoginFormBean.CURATOR)) {
%><c:redirect url="<%= Controllers.LOGIN %>" /><%
}
String conceptIdStr = request.getParameter("conceptId");
if (conceptIdStr != null) {
String describeQueryStr =
"PREFIX afn: <http://jena.hpl.hp.com/ARQ/function#> \n\n" +
"DESCRIBE ?bnode \n" +
"WHERE { \n" +
" FILTER(afn:bnode(?bnode) = \"" + conceptIdStr + "\")\n" +
"}";
OntModel ontModel = (OntModel) getServletContext().getAttribute("baseOntModel");
Model conceptDescription = ModelFactory.createDefaultModel();
try {
ontModel.enterCriticalSection(Lock.READ);
Query describeQuery = QueryFactory.create(describeQueryStr, Syntax.syntaxARQ);
QueryExecution qe = QueryExecutionFactory.create(describeQuery, ontModel);
qe.execDescribe(conceptDescription);
conceptDescription.add(ontModel.listStatements((Resource) null, (Property) null, ontModel.createResource(new AnonId(conceptIdStr))));
} finally {
ontModel.leaveCriticalSection();
}
List<String> actionStrList = (request.getParameterValues("action") != null)
? Arrays.asList(request.getParameterValues("action"))
: new ArrayList<String>();
if (actionStrList.contains("remove")) {
try {
ontModel.enterCriticalSection(Lock.WRITE);
ontModel.remove(conceptDescription);
} finally {
ontModel.leaveCriticalSection();
}
}
if (actionStrList.contains("describe")) {
conceptDescription.write(response.getOutputStream(), "TTL");
return;
}
}
%>
<%@page import="com.hp.hpl.jena.ontology.OntModel"%>
<%@page import="com.hp.hpl.jena.shared.Lock"%>
<%@page import="com.hp.hpl.jena.query.Syntax"%>
<%@page import="com.hp.hpl.jena.query.Query"%>
<%@page import="com.hp.hpl.jena.query.QueryFactory"%>
<%@page import="com.hp.hpl.jena.query.QueryExecutionFactory"%>
<%@page import="com.hp.hpl.jena.rdf.model.ModelFactory"%>
<%@page import="com.hp.hpl.jena.rdf.model.Model"%>
<%@page import="com.hp.hpl.jena.query.QueryExecution"%>
<%@page import="java.util.Arrays"%>
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@page import="com.hp.hpl.jena.rdf.model.Resource"%>
<%@page import="com.hp.hpl.jena.rdf.model.Property"%>
<%@page import="com.hp.hpl.jena.rdf.model.AnonId"%><html>
<head>
<title>Anonymous Concept Repair Tools</title>
</head>
<body>
<h1>Concept Repair</h1>
<form action="" method="post">
<p>Concept bnode id: <input name="conceptId"/></p>
<p><input type="checkbox" name="action" value="describe"/> describe concept</p>
<p><input type="checkbox" name="action" value="remove"/> remove concept</p>
<p><input type="submit" value="Perform action"/></p>
</form>
</body></html>

View file

@ -0,0 +1,62 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="edu.cornell.mannlib.vedit.beans.LoginFormBean" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.Controllers" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.filters.VitroRequestPrep" %>
<%@ page import="java.util.Enumeration" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.FakeSelfEditingIdentifierFactory" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%
if(session == null || !LoginFormBean.loggedIn(request, LoginFormBean.CURATOR)) {
%><c:redirect url="<%= Controllers.LOGIN %>" /><%
}
if( request.getParameter("force") != null ){
VitroRequestPrep.forceToSelfEditing(request);
String netid = request.getParameter("netid");
FakeSelfEditingIdentifierFactory.clearFakeIdInSession( session );
FakeSelfEditingIdentifierFactory.putFakeIdInSession( netid , session );%>
<c:redirect url="/entity">
<c:param name="netid" value="<%=netid%>" />
</c:redirect>
<% }
if( request.getParameter("stopfaking") != null){
VitroRequestPrep.forceOutOfSelfEditing(request);
FakeSelfEditingIdentifierFactory.clearFakeIdInSession( session );
}
String netid = (String)session.getAttribute(FakeSelfEditingIdentifierFactory.FAKE_SELF_EDIT_NETID);
String msg = "You have not configured a netid for testing self-editing. ";
if( netid != null ) {
msg = "You have are testing self-editing as '" + netid + "'.";%>
<c:redirect url="/entity">
<c:param name="netid" value="<%=netid%>"/>
</c:redirect>
<% } else {
netid = "";
}
%>
<html>
<title>Test Self-Edit</title>
<body>
<h2>Configure Self-Edit Testing</h2>
<p><%=msg %></p>
<form action="<c:url value="fakeselfedit.jsp"/>" >
<input type="text" name="netid" value="<%= netid %>"/>
<input type="hidden" name="force" value="1"/>
<input type="submit" value="use a netid for testing"/>
</form>
<p/>
<form action="<c:url value="fakeselfedit.jsp"/>" >
<input type="hidden" name="stopfaking" value="1"/>
<input type="submit" value="stop usng netid for testing"/>
</form>
</body>
</html>

View file

@ -0,0 +1,46 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@page import="edu.cornell.mannlib.vitro.webapp.filters.VitroRequestPrep"%>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.Controllers" %>
<%@page import="edu.cornell.mannlib.vedit.beans.LoginFormBean"%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%
if (session == null || !LoginFormBean.loggedIn(request, LoginFormBean.DBA)) {
%><c:redirect url="<%= Controllers.LOGIN %>" /><%
}
if( request.getParameter("uri") != null ){
%> <c:redirect url="/entity"><c:param name="uri" value="${param.uri}"/></c:redirect> <%
return;
}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head> <!-- gotoIndividual.jsp -->
<link rel="stylesheet" type="text/css" href="<c:url value="/${themeDir}css/screen.css"/>" media="screen"/>
<link rel="stylesheet" type="text/css" href="<c:url value="/${themeDir}css/formedit.css" />" media="screen"/>
<title>Enter a URI</title>
</head>
<body class="formsEdit">
<div id="wrap">
<% /* BJL23 put this is in a catch block because it seems to fail ungracefully for
some clones */ %>
<c:catch>
<jsp:include page="/${themeDir}jsp/identity.jsp" flush="true"/>
<div id="contentwrap">
<jsp:include page="/${themeDir}jsp/menu.jsp" flush="true"/>
<!-- end of formPrefix.jsp -->
</c:catch>
<form>
<input name="uri" type="text" size="200" />
<input type="submit" value="Lookup Individual for URI"/>
</form>

View file

@ -0,0 +1,27 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<html>
<head>
<title>Jena Admin Actions</title>
</head>
<body>
<h1>Jena Admin Actions</h1>
<p>(Right click and Save Target As with the following links)</p>
<ul>
<li>
<a href="../jenaAdmin?action=output">output entire in-memory model</a>
</li>
<li>
<a href="../jenaAdmin?action=output&amp;assertionsOnly=true">output in-memory assertions</a>
</li>
<li>
<a href="../jenaAdmin?action=output&amp;inferences=true">output in-memory inferences</a>
</li>
<li>
<a href="../jenaAdmin?action=output&amp;pellet=pellet">output Pellet model</a>
<li>
<a href="../jenaAdmin?action=outputTaxonomy">output taxonomy</a>
</li>
<ul>
</body>
</html>

161
webapp/web/admin/log4j.jsp Normal file
View file

@ -0,0 +1,161 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="edu.cornell.mannlib.vedit.beans.LoginFormBean" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.Controllers" %>
<%@ page import="org.apache.log4j.*" %>
<%@ page import="java.util.*" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%--
This JSP will display all the log4j Logger objects, their
levels and their appenders. The levels of the Logger objects
can be changed and test messages can be sent.
Brian Cauros bdc34@cornell.edu
based on work by Volker Mentzner. --%>
<%
if (session == null || !LoginFormBean.loggedIn(request, LoginFormBean.DBA)) {
%><c:redirect url="<%= Controllers.LOGIN %>" /><%
}
try {
String name;
Level[] levels = new Level[]
{Level.OFF, Level.FATAL, Level.ERROR, Level.WARN, Level.INFO, Level.DEBUG};
out.write("<HTML><HEAD><TITLE>log4j configuration</TITLE></HEAD>\r\n");
out.write("<BODY><H1>log4j</H1>\r\n");
// handle a request with query
if( request.getParameterMap().size() > 0){
if( request.getParameter("doTestMsg") != null){
//handle test message
Logger logger = LogManager.getLogger( request.getParameter("logger") );
Level level = (Level)Level.toLevel( request.getParameter("level"));
logger.log(level, request.getParameter("msg"));
out.write("<h3>message sent</h3>");
} else {
//handle logging level changes
Enumeration names = request.getParameterNames();
while(names.hasMoreElements()){
String catname = (String)names.nextElement();
String catval = request.getParameter(catname);
if( "root".equalsIgnoreCase(catname))
LogManager.getRootLogger().setLevel((Level)Level.toLevel(catval));
else
LogManager.getLogger(catname).setLevel((Level)Level.toLevel(catval));
}
}
}
out.write("<p>" + notes + "</p>");
// output category information in a form with a simple table
out.write("<form name=\"Formular\" ACTION=\""+request.getContextPath()+request.getServletPath()+"\" METHOD=\"POST\">");
out.write("<table cellpadding=4>\r\n");
out.write(" <tr>\r\n");
out.write(" <td><b>Logger</b></td>\r\n");
out.write(" <td><b>Level</b></td>\r\n");
out.write(" <td><b>Appender</b></td>\r\n");
out.write(" </tr>\r\n");
// output for all Loggers
List<String> logNames = new LinkedList<String>();
for(Enumeration en = LogManager.getCurrentLoggers(); en.hasMoreElements() ;){
logNames.add(((Logger)en.nextElement()).getName());
}
Collections.sort(logNames);
logNames.add(0,"root");
Logger cat;
for (String logName : logNames) {
if( "root".equalsIgnoreCase(logName))
cat = LogManager.getRootLogger();
else
cat = LogManager.getLogger(logName);
out.write(" <tr>\r\n");
out.write(" <td>" + cat.getName() + "</td>\r\n");
out.write(" <td>\r\n");
out.write(" <select size=1 name=\""+ cat.getName() +"\">");
for (int i = 0; i < levels.length; i++) {
if (cat.getEffectiveLevel().toString().equals(levels[i].toString()))
out.write("<option selected>"+levels[i].toString());
else
out.write("<option>"+levels[i].toString());
}
out.write("</select>\r\n");
out.write(" </td>\r\n");
out.write(" <td>\r\n");
for( Appender apd : getAllAppenders( cat )){
name = apd.getName();
if (name == null)
name = "<i>(no name)</i>";
out.write(name);
if (apd instanceof AppenderSkeleton) {
try {
AppenderSkeleton apskel = (AppenderSkeleton)apd;
out.write(" [" + apskel.getThreshold().toString() + "]");
} catch (Exception ex) {
}
}
out.write(" ");
}
out.write(" </td>\r\n");
out.write(" </tr>\r\n");
}
out.write("</table>\r\n");
out.write("<input type=submit value=\"Submit changes to logging levels\">");
out.write("</form>\n");
/* write out form to do a test message */
out.write("<h2>Test the logging configuration by sending a test message</h2>\n");
out.write("<form name=\"TestForm\" ACTION=\""+request.getContextPath()+request.getServletPath()+"\" METHOD=\"PUT\">\n");
out.write("<input type=\"hidden\" name=\"doTestMsg\" value=\"true\">\n");
out.write("<table>\n\r");
out.write(" <tr><td>logger:</td>\n\r");
out.write(" <td><select name=\"logger\"/>\n\r");
for(String logName : logNames){
out.write(" <option>" + logName + "</option>\n\r");
}
out.write(" </select></td></tr>\n\r");
out.write(" <tr><td>level:</td>\n\r");
out.write(" <td><select name=\"level\">\n\r");
for (int i = 0; i < levels.length; i++) {
out.write(" <option>"+levels[i].toString() + "</option>\n\r");
}
out.write(" </select></td></tr>\n\r");
out.write(" <tr><td>message:</td> \n\r");
out.write(" <td><textarea name=\"msg\"></textarea></td></tr>\n\r");
out.write(" <tr><td><input type=\"submit\" value=\"submit test message\"/></td></tr>\n\r");
out.write("</table></form>\n");
out.write("</BODY></HTML>\r\n");
out.flush();
} catch (Exception ex) {
throw new Error( ex);
}
%>
<%!
String notes ="<p>Changing the level of a Logger on this form does not change the levels of that Logger's children."+
"<p>Example: if you change the level of the Logger edu.cornell.mannlib.utils from ERROR to DEBUG, the " +
"logging level of edu.cornell.mannlib.utils.StringUtils will not be modified." +
"<p>Loggers will write message to all of their Appenders; you cannot have a DEBUG level For Logger A, Appender A "+
" and a WARN level for a Logger A, Appender B.";
%>
<%!
private Collection<Appender> getAllAppenders(Category logger){
HashSet<Appender> appenders = new HashSet<Appender>();
Enumeration en = logger.getAllAppenders();
while( en.hasMoreElements()){
appenders.add((Appender) en.nextElement());
}
if( logger.getParent() != null )
appenders.addAll( getAllAppenders(logger.getParent()));
return appenders;
}
%>

View file

@ -0,0 +1,120 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ page import="edu.cornell.mannlib.vedit.beans.LoginFormBean" %>
<%
if(session == null || !LoginFormBean.loggedIn(request, LoginFormBean.CURATOR)) {
%><c:redirect url="/siteAdmin"></c:redirect><%
}
if (request.getParameter("execute") != null) {
OntModel ontModel = (OntModel) getServletContext().getAttribute(JenaBaseDao.ASSERTIONS_ONT_MODEL_ATTRIBUTE_NAME);
int results = doRemoval(ontModel);
request.setAttribute("removalCount", results);
}
%>
<%!
private int doRemoval(OntModel ontModel) {
int removedStmts = 0;
List<String> bnodeIds = new ArrayList<String>();
ontModel.enterCriticalSection(Lock.READ);
try {
Iterator<Restriction> restIt = ontModel.listRestrictions();
while(restIt.hasNext()) {
Restriction rest = restIt.next();
if (rest.isAnon()) {
boolean bad = false;
bad |= (rest.getPropertyValue(OWL.onProperty) == null);
bad |= ( !(
(rest.getPropertyValue(OWL.someValuesFrom) != null) ||
(rest.getPropertyValue(OWL.allValuesFrom) != null) ||
(rest.getPropertyValue(OWL.hasValue) != null) ||
(rest.getPropertyValue(OWL.cardinality) != null) ||
(rest.getPropertyValue(OWL.minCardinality) != null) ||
(rest.getPropertyValue(OWL.maxCardinality) != null)
)
);
if (bad) {
bnodeIds.add(rest.getId().toString());
}
}
}
} finally {
ontModel.leaveCriticalSection();
}
for (String id : bnodeIds) {
Model toRemove = describeBnode(id);
ontModel.enterCriticalSection(Lock.WRITE);
try {
ontModel.remove(toRemove);
} finally {
ontModel.leaveCriticalSection();
}
removedStmts += toRemove.size();
}
return removedStmts;
}
private Model describeBnode(String bnodeId) {
String describeQueryStr =
"PREFIX afn: <http://jena.hpl.hp.com/ARQ/function#> \n\n" +
"DESCRIBE ?bnode \n" +
"WHERE { \n" +
" FILTER(afn:bnode(?bnode) = \"" + bnodeId + "\")\n" +
"}";
OntModel ontModel = (OntModel) getServletContext().getAttribute("baseOntModel");
Model conceptDescription = ModelFactory.createDefaultModel();
try {
ontModel.enterCriticalSection(Lock.READ);
Query describeQuery = QueryFactory.create(describeQueryStr, Syntax.syntaxARQ);
QueryExecution qe = QueryExecutionFactory.create(describeQuery, ontModel);
qe.execDescribe(conceptDescription);
conceptDescription.add(ontModel.listStatements((Resource) null, (Property) null, ontModel.createResource(new AnonId(bnodeId))));
return conceptDescription;
} finally {
ontModel.leaveCriticalSection();
}
}
%>
<%@page import="com.hp.hpl.jena.ontology.OntModel"%>
<%@page import="com.hp.hpl.jena.shared.Lock"%>
<%@page import="com.hp.hpl.jena.query.Syntax"%>
<%@page import="com.hp.hpl.jena.query.Query"%>
<%@page import="com.hp.hpl.jena.query.QueryFactory"%>
<%@page import="com.hp.hpl.jena.query.QueryExecutionFactory"%>
<%@page import="com.hp.hpl.jena.rdf.model.ModelFactory"%>
<%@page import="com.hp.hpl.jena.rdf.model.Model"%>
<%@page import="com.hp.hpl.jena.query.QueryExecution"%>
<%@page import="java.util.Arrays"%>
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@page import="com.hp.hpl.jena.rdf.model.Resource"%>
<%@page import="com.hp.hpl.jena.rdf.model.Property"%>
<%@page import="com.hp.hpl.jena.rdf.model.AnonId"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.dao.jena.JenaBaseDao"%>
<%@page import="java.util.Iterator"%>
<%@page import="com.hp.hpl.jena.ontology.Restriction"%>
<%@page import="com.hp.hpl.jena.vocabulary.OWL"%><html>
<head>
<title>Remove Bad Restrictions</title>
</head>
<body>
<c:if test="${!empty requestScope.removalCount}">
<p>${removalCount} statements removed</p>
</c:if>
<h1>Remove Bad Restrictions</h1>
<form action="" method="post">
<p><input name="execute" type="submit" value="Remove now"/></p>
</form>
</body></html>

View file

@ -0,0 +1,83 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ page import="edu.cornell.mannlib.vedit.beans.LoginFormBean" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.Controllers" %>
<%
if(session == null || !LoginFormBean.loggedIn(request, LoginFormBean.CURATOR)) {
%><c:redirect url="<%= Controllers.LOGIN %>" /><%
}
String resourceURIStr = request.getParameter("resourceURI");
if (resourceURIStr != null) {
String describeQueryStr =
"DESCRIBE <" + resourceURIStr + ">";
OntModel ontModel = (OntModel) getServletContext().getAttribute("baseOntModel");
Model resourceDescription = ModelFactory.createDefaultModel();
try {
ontModel.enterCriticalSection(Lock.READ);
Query describeQuery = QueryFactory.create(describeQueryStr, Syntax.syntaxARQ);
QueryExecution qe = QueryExecutionFactory.create(describeQuery, ontModel);
qe.execDescribe(resourceDescription);
resourceDescription.add(ontModel.listStatements((Resource) null, (Property) null, ontModel.getResource(resourceURIStr)));
} finally {
ontModel.leaveCriticalSection();
}
List<String> actionStrList = (request.getParameterValues("action") != null)
? Arrays.asList(request.getParameterValues("action"))
: new ArrayList<String>();
if (actionStrList.contains("remove")) {
try {
ontModel.enterCriticalSection(Lock.WRITE);
ontModel.remove(resourceDescription);
} finally {
ontModel.leaveCriticalSection();
}
}
if (actionStrList.contains("describe")) {
resourceDescription.write(response.getOutputStream(), "TTL");
return;
}
}
%>
<%@page import="com.hp.hpl.jena.ontology.OntModel"%>
<%@page import="com.hp.hpl.jena.shared.Lock"%>
<%@page import="com.hp.hpl.jena.query.Syntax"%>
<%@page import="com.hp.hpl.jena.query.Query"%>
<%@page import="com.hp.hpl.jena.query.QueryFactory"%>
<%@page import="com.hp.hpl.jena.query.QueryExecutionFactory"%>
<%@page import="com.hp.hpl.jena.rdf.model.ModelFactory"%>
<%@page import="com.hp.hpl.jena.rdf.model.Model"%>
<%@page import="com.hp.hpl.jena.query.QueryExecution"%>
<%@page import="java.util.Arrays"%>
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@page import="com.hp.hpl.jena.rdf.model.Resource"%>
<%@page import="com.hp.hpl.jena.rdf.model.Property"%>
<%@page import="com.hp.hpl.jena.rdf.model.AnonId"%><html>
<head>
<title>Anonymous Concept Repair Tools</title>
</head>
<body>
<h1>Remove resource using DESCRIBE</h1>
<form action="" method="post">
<p>Resource URI: <input name="resourceURI"/></p>
<p><input type="checkbox" name="action" value="describe"/> describe resource</p>
<p><input type="checkbox" name="action" value="remove"/> remove resource</p>
<p><input type="submit" value="Perform action"/></p>
</form>
</body></html>

View file

@ -0,0 +1,25 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@page
import="edu.cornell.mannlib.vitro.webapp.auth.identifier.ServletIdentifierBundleFactory"%>
<%@page
import="java.util.List"%>
<%
List idb = ServletIdentifierBundleFactory.getIdBundleForRequest(request, session, application);
out.write("<html><body>");
out.write("<h2>Identifiers in effect: </h2>");
out.write("<p>This is a utility that shows which identifiers are in effect.</p>\n");
out.write("<table><tr><th>class</th><th>value</th></tr>\n");
for( Object id : idb ){
out.write( "<tr>" );
out.write( "<td>" + id.getClass().getName() + "</td>");
out.write( "<td>" + id.toString() + "</td>" );
out.write( "</tr>\n" );
}
out.write("</table>\n");
out.write("</body></html>");
%>

View file

@ -0,0 +1,95 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@page import="com.hp.hpl.jena.rdf.model.ModelMaker"%>
<%@page import="java.util.Iterator"%>
<body>
<div id="content" class="sparqlform">
<h1>SPARQL Query</h1>
<form action='sparqlquery'>
query:
<div>
<textarea name='query' rows ='23' cols='100' class="span-23">
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX swrl: <http://www.w3.org/2003/11/swrl#>
PREFIX swrlb: <http://www.w3.org/2003/11/swrlb#>
PREFIX vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#>
PREFIX vivo: <http://vivo.library.cornell.edu/ns/0.1#>
#
# This example query gets the label, research focus, and netID
# for 20 Cornell employees.
#
SELECT ?person ?personLabel ?focus ?netid
WHERE
{
?person vivo:CornellemailnetId ?netid .
?person rdf:type vivo:CornellEmployee .
?person vivo:researchFocus ?focus.
OPTIONAL { ?person rdfs:label ?personLabel }
}
limit 20
</textarea>
</div>
<p>
<h4>Format for SELECT query results:</h4>
<input id='RS_XML_BUTTON' type='radio' name='resultFormat' value='RS_XML'> <label for='RS_XML_BUTTON'>RS_XML</label>
<input id='RS_TEXT_BUTTON' type='radio' name='resultFormat' value='RS_TEXT' checked='checked'> <label for='RS_TEXT_BUTTON'>RS_TEXT</label>
<input id='RS_CSV_BUTTON' type='radio' name='resultFormat' value='vitro:csv'> <label for='RS_CSV_BUTTON'>CSV</label>
<input id='RS_RDF_N3_BUTTON' type='radio' name='resultFormat' value='RS_RDF/N3'> <label for='RS_RDF_N3_BUTTON'>RS_RDF/N3</label>
<input id='RS_JSON_BUTTON' type='radio' name='resultFormat' value='RS_JSON'> <label for='RS_JSON_BUTTON'>RS_JSON</label>
<input id='RS_RDF_BUTTON' type='radio' name='resultFormat' value='RS_RDF'> <label for='RS_RDF_BUTTON'>RS_RDF</label>
</p>
<p>
<h4>Format for CONSTRUCT and DESCRIBE query results:</h4>
<input id='RR_RDFXML_BUTTON' type='radio' name='rdfResultFormat' value='RDF/XML'> <label for='RR_RDFXML_BUTTON'>RDF/XML</label>
<input id='RR_RDFXMLABBREV_BUTTON' type='radio' name='rdfResultFormat' value='RDF/XML-ABBREV' checked='checked'> <label for='RR_RDFXMLABBREV_BUTTON'>RDF/XML-ABBREV</label>
<input id='RR_N3_BUTTON' type='radio' name='rdfResultFormat' value='N3'> <label for='RR_N3_BUTTON'>N3</label>
<input id='RR_NTRIPLE_BUTTON' type='radio' name='rdfResultFormat' value='N-TRIPLE'> <label for='RR_NTRIPLE_BUTTON'>N-Triples</label>
<input id='RR_TURTLE_BUTTON' type='radio' name='rdfResultFormat' value='TTL'> <label for='RR_TURTLE_BUTTON'>Turtle</label>
</p>
<div>
<ul class="clean">
<%
try{
if( request.getSession() != null && application.getAttribute("vitroJenaModelMaker") != null ){
ModelMaker maker = (ModelMaker) application.getAttribute("vitroJenaModelMaker");
for (Iterator it = maker.listModels(); it.hasNext(); ) {
String modelName = (String) it.next();
%> <li> <input type="checkbox" name="sourceModelName" value="<%=modelName%>"/><%=modelName%></li>
<%
}
}else{
%><li>could not find named models in session</li><%
}
}catch(Exception ex){
%><li>could not find named models in ModelMaker</li><%
}
%>
</ul>
</div>
<input type="submit" value="Run Query">
</form>
<%--
<h4>Notes</h4>
<p>CONSTRUCT and DESCRIBE queries always return RDF XML</p>
<p>The parameter 'resultFormat' must not be null or zero length</p>
<p>The parameter 'resultFormat' must be one of the following: <ul>
<li>RS_XML</li>
<li>RS_TEXT</li>
<li>RS_RDF/N3</li>
<li>RS_JSON</li>
<li>RS_RDF</li>
</ul>
</p>
--%>
</div><!-- content -->
</body></html>

View file

@ -0,0 +1,104 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@page import="edu.cornell.mannlib.vitro.webapp.utils.jena.SesameSyncUtils"%>
<%@page import="com.hp.hpl.jena.rdf.model.ModelFactory"%>
<%@page import="com.hp.hpl.jena.shared.Lock"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.dao.jena.JenaModelUtils"%>
<%@page import="com.hp.hpl.jena.rdf.model.Model"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.dao.jena.JenaBaseDao"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.util.Properties"%>
<%@page import="edu.cornell.mannlib.vedit.beans.LoginFormBean"%>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.Controllers" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%!
final String SESAME_PROPS_PATH = "/WEB-INF/classes/sesame.sync.properties" ;
final String SESAME_SERVER = "vitro.sesame.server" ;
final String SESAME_REPOSITORY = "vitro.sesame.repository" ;
final String SESAME_CONTEXT = "vitro.sesame.context" ;
final String USER_SPARQL_QUERY =
"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n" +
"PREFIX vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> \n\n" +
"DESCRIBE ?user WHERE { \n " +
" ?user rdf:type vitro:User \n" +
"}";
%>
<%
if(session == null || !LoginFormBean.loggedIn(request, LoginFormBean.DBA)) {
%>
<c:redirect url="<%= Controllers.LOGIN %>" />
<%
}
long startTime = System.currentTimeMillis();
Properties sesameProperties = new Properties();
InputStream propStream = getServletContext().getResourceAsStream(SESAME_PROPS_PATH);
if (propStream == null) {
response.setStatus(500, "Sesame properties not found at " + SESAME_PROPS_PATH);
return;
}
sesameProperties.load(propStream);
String sesameLocation = sesameProperties.getProperty(SESAME_SERVER);
if (sesameLocation == null) {
response.setStatus(500, "Missing property " + SESAME_SERVER);
}
String sesameRepository = sesameProperties.getProperty(SESAME_REPOSITORY);
if (sesameRepository == null) {
response.setStatus(500, "Missing property " + SESAME_REPOSITORY);
}
String contextId = sesameProperties.getProperty(SESAME_CONTEXT);
Model fullModel = (Model) getServletContext().getAttribute(JenaBaseDao.JENA_ONT_MODEL_ATTRIBUTE_NAME);
// Copy the model to avoid locking the main model during sync. Assumes enough memory.
Model copyModel = ModelFactory.createDefaultModel();
fullModel.enterCriticalSection(Lock.READ);
try {
copyModel.add(fullModel);
} finally {
fullModel.leaveCriticalSection();
}
Model userDataToRetract = ModelFactory.createDefaultModel();
Query userDataQuery = QueryFactory.create(USER_SPARQL_QUERY);
QueryExecution qe = QueryExecutionFactory.create(userDataQuery, copyModel);
qe.execDescribe(userDataToRetract);
copyModel.remove(userDataToRetract);
System.out.println("Not sharing " + userDataToRetract.size() + " statements of user data");
System.out.println("Using Sesame server at " + sesameLocation);
System.out.println("Using Sesame repository at " + sesameRepository);
System.out.println("Using context " + contextId);
try {
(new SesameSyncUtils()).writeModelToSesameContext(copyModel, sesameLocation, sesameRepository, contextId);
} catch (Throwable t) {
t.printStackTrace();
throw new Error(t);
}
System.out.println((System.currentTimeMillis() - startTime) + " ms to sync");
%>
<%@page import="com.hp.hpl.jena.rdf.model.StmtIterator"%>
<%@page import="com.hp.hpl.jena.rdf.model.Statement"%>
<%@page import="com.hp.hpl.jena.query.Query"%>
<%@page import="com.hp.hpl.jena.query.QueryFactory"%>
<%@page import="com.hp.hpl.jena.query.QueryExecution"%>
<%@page import="com.hp.hpl.jena.query.QueryExecutionFactory"%><html>
<head>
<title>Sync successful</title>
</head>
</html>

View file

@ -0,0 +1,210 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="edu.cornell.mannlib.vedit.beans.LoginFormBean" %>
<%@ page import="com.hp.hpl.jena.rdf.model.*" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.filters.VitroRequestPrep" %>
<%@ page import="java.util.Enumeration" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.FakeSelfEditingIdentifierFactory" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.auth.policy.setup.CuratorEditingPolicySetup" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.Controllers" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<% if(session == null || !LoginFormBean.loggedIn(request, LoginFormBean.CURATOR)) {
%><c:redirect url="<%= Controllers.LOGIN %>" /><%
}
if( request.getParameter("force") != null ){
VitroRequestPrep.forceToSelfEditing(request);
String netid = request.getParameter("netid");
// note that this affects the current user's session, not the whole servlet context
FakeSelfEditingIdentifierFactory.clearFakeIdInSession( session );
FakeSelfEditingIdentifierFactory.putFakeIdInSession( netid , session );
// don't want to do this because would affect the whole session
// if(LoginFormBean.loggedIn(request, LoginFormBean.CURATOR)) {
// CuratorEditingPolicySetup.removeAllCuratorEditingPolicies(getServletConfig().getServletContext());
//} %>
<jsp:forward page="/edit/login.jsp"/>
<% }
String loggedOutNetId = (String)session.getAttribute(FakeSelfEditingIdentifierFactory.FAKE_SELF_EDIT_NETID);
if( request.getParameter("stopfaking") != null){
VitroRequestPrep.forceOutOfSelfEditing(request);
FakeSelfEditingIdentifierFactory.clearFakeIdInSession( session );
// don't want to do this because would affect the whole session
// if(LoginFormBean.loggedIn(request, LoginFormBean.CURATOR)) {
// CuratorEditingPolicySetup.replaceCuratorEditing(getServletConfig().getServletContext(),(Model)application.getAttribute("jenaOntModel"));
//}
%><c:redirect url="/"></c:redirect><%
}
String netid = (String)session.getAttribute(FakeSelfEditingIdentifierFactory.FAKE_SELF_EDIT_NETID);
String msg = "You have not configured a netid for testing self-editing. ";
if( netid != null )
msg = "You are testing self-editing as '" + netid + "'.";
else
netid = "";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head><title>CUWebLogin</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="temporaryLoginFiles/main.css">
<link rel="stylesheet" type="text/css" href="temporaryLoginFiles/filter.css">
<link rel="stylesheet" type="text/css" href="temporaryLoginFiles/dialogs.css">
<script language="JavaScript">
<!--
function OpenCertDetails()
{
thewindow=window.open('https://www.thawte.com/cgi/server/certdetails.exe?code=uscorn123-1',
'anew',config='height=400,width=450,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,directories=no,status=yes');
}
// -->
</script>
</head><body onload="cuwl_focus_netid();">
<!-- header 1 -->
<div class="wrapper" id="header1wrap">
<div class="inner" id="header1">
<div id="logo">
<a href="http://www.cornell.edu/" title="Cornell University"><img src="temporaryLoginFiles/cu.gif" alt="Cornell University" border="0" height="23" width="211"></a>
</div>
</div>
</div>
<!-- end header 1 -->
<hr class="hidden">
<!-- header 2 -->
<div id="header2wrap">
<!-- these two divs are just for background color -->
<div id="header2left">&nbsp;</div>
<div id="header2right">&nbsp;</div>
<!-- end background divs -->
<div id="header2">
<div id="title"><a href="http://www.cit.cornell.edu/authent/new/cuwl/cuwl.html"><img src="temporaryLoginFiles/cuwl-title.png" alt="CUWebLogin" border="0" height="74" width="213"></a></div>
<div id="manage">
Cornell University Login
</div>
</div>
</div>
<!-- end header 2 -->
<!-- header 3 -->
<div class="wrapper" id="header3wrap">
<div class="inner" id="header3">
<span>
<a href="http://www.cit.cornell.edu/identity/cuweblogin.html">About
CUWebLogin</a>
</span>
</div>
</div>
<!-- end header 3 -->
<!-- ---------------------------- BEGIN main body -->
<div class="wrapper" id="main">
<div class="inner" id="content">
<hr class="hidden">
<form name="dialog" method="post" action="temporaryLogin.jsp">
<table>
<tbody><tr>
<td id="loginboxcell">
<table class="loginbox" id="webloginbox">
<tbody><tr id="toprow">
<td>
<img src="temporaryLoginFiles/logindogs.gif" alt="">
</td>
<td>
<img src="temporaryLoginFiles/KfWeb.gif" alt="Kerberos for Web"><br>
<em>
Please enter your Cornell NetID
</em>
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
<td>
<table id="entrybox">
<tbody><tr>
<td>NetID:</td>
<td>
<input class="textinput" name="netid" type="text" value="" />
<input type="hidden" name="force" value="1"/>
</td>
</tr>
<tr>
<td><!-- Password: --></td>
<td>
<strong>For testing purposes only</strong>.
</td>
</tr>
</tbody></table>
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
<td id="buttoncell">
<input class="inputsubmitHead" name="cancel" value="Cancel" onclick="cancel_submit();" type="button">
<input class="inputsubmitHead" name="ok" value="OK" type="submit">
</td>
</tr>
</tbody></table>
</td>
<td id="infocell">
<br>
<table id="reasonbox">
<tbody><tr><td>
<c:if test="${!empty param.stopfaking}">
You have successfully logged out from <%=loggedOutNetId%>.
<c:url var="profileHref" value="/entity">
<c:param name="netid" value="<%=loggedOutNetId%>" />
</c:url>
Return to that <a href="${profileHref}" title="view your public profile">public profile</a>.
</c:if>
</td></tr>
</tbody></table>
<br>
<!-- The Web site you are visiting requires you to authenticate with your NetID and Password -->
<br>
<!-- <a href="javascript:OpenCertDetails()">
<IMG SRC="/images/thawte-seal.gif" BORDER=0 ALT='Click here for SSL Cert Details'>
</a> -->
<!-- GeoTrust True Site [tm] Smart Icon tag. Do not edit. -->
<!-- <SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript" SRC="//smarticon.geotrust.com/si.js"></SCRIPT> -->
<!-- <img src="temporaryLoginFiles/quickssl_anim.gif" border="0"> -->
<!-- end GeoTrust Smart Icon tag -->
<br>
</td>
</tr>
</tbody></table>
</form>
<hr class="hidden">
</div>
</div>
<!-- ---------------------------- END main body -->
<!-- footer include in -->
<div class="wrapper" id="footer">
<div class="inner">
<em>Mann Library Notice:</em> <strong>This IS NOT an official CUWebLogin
screen. It is meant for testing purposes only</strong>.
</div>
</div>
<!-- footer include out -->
</body></html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 654 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3 KiB

View file

@ -0,0 +1,84 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
img {
padding: 0;
margin: 0;
}
#chpassbox {
width:450px;
}
#guestloginbox {
width: 300px;
}
#webloginbox {
width: 325px;
}
td#infocell {
padding-left: 30px;
height: 100%;
vertical-align: middle;
}
td#loginboxcell {
vertical-align: middle;
}
td #loginboxtitle {
font-size: x-large;
line-height: 1.1em;
}
.loginbox {
border-collapse: collapse;
border: 1px solid #bbb;
}
.loginbox td {
background: #dfdfdf;
}
#toprow img {
margin-bottom: 5px;
}
#toprow td {
padding-top: 6px;
vertical-align: top;
text-align: center;
line-height: 1.3em;
}
#entrybox {
margin: 6px;
padding: 2px;
}
#entrybox td {
width: 100%;
text-align: right;
}
#entrybox input {
width: 240px;
}
#entrybox2 {
margin: 6px;
padding: 2px;
}
#entrybox2 td {
width: 100%;
text-align: right;
}
#entrybox2 input {
width: 45px;
height: 1.7em;
}
#buttoncell {
padding: 0 6px 6px 0;
width: 100%;
text-align: right;
}
#buttoncell input {
width: 5.5em;
}
#reasonbox{
background: #dfdfdf;
border-collapse: collapse;
border: 1px solid #bbb;
color: #AB1A2A;
}

View file

@ -0,0 +1,44 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
body {background: #fff;}
h2
{
margin: 0;
font-size: 14pt;
line-height: 20px;
padding: 12px 0 22px 0px;
font-weight: normal;
}
.confirm
{
margin: 0;
font-size: 14pt;
line-height: 20px;
padding: 12px 0 12px 0px;
font-weight: normal;
color: #AB1A2A;
}
td
{
font-family: verdana, arial, helvetica, geneva, sans-serif;
font-size: 11px;
line-height: 20px;
}
.rowBkgrd { background: #F4F4F4; } /* was #eee; */
.tableHeading
{
font-weight: bold;
white-space: nowrap;
}
.label
{
font-weight: bold;
text-align: right;
white-space: nowrap;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

View file

@ -0,0 +1,437 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
/***********************
* General formatting
***********************/
.hidden { display: none;}
body {
margin: 0;
padding: 0;
font-family: verdana, arial, helvetica, geneva, sans-serif;
font-size: 11px;
color: #484848; /*666;*/
background: #fff;
}
.wrapper {
width: 100%;
text-align: center;
}
.inner {
width: 720px;
margin: 0 auto;
text-align: left;
}
/****************************************************************/
//#hm a, #hm a:link, #hm a:visited {
// color: #85A3C2;
// text-decoration: none;
// font-weight: bold;
//}
//#hm a:hover {
// color: #596C80;
// text-decoration: underline;
// font-weight: bold;
//}
//#hm a:active {
// color: #85A3C2;
//}
h2 {
margin: 0;
font-size: 14pt;
line-height: 20px;
padding: 20px 0px 20px 0px;
font-weight: normal;
}
#confirm {
margin: 0;
font-size: 14pt;
line-height: 20px;
padding: 12px 0px 12px 0px;
font-weight: normal;
color: black;
}
#confirmdata {
color: black;
font-size: 111%;
margin-left: 4em;
line-height: 1em;
padding: 0em;
}
#confirmdata td {
padding-left: 1em;
// font-size: 90%;
line-height: 120%;
}
#error {
margin: 0;
font-size: 111%;
line-height: 1.2em;
padding-bottom: 0.5em;
font-weight: normal;
color: #AB1A2A;
}
#errordata {
margin: 0em;
// font-size: 90%;
line-height: 1em;
padding-bottom: 2em;
font-weight: normal;
color: #AB1A2A;
}
td
{
font-family: verdana, arial, helvetica, geneva, sans-serif;
font-size: 11px;
line-height: 20px;
}
.rowBkgrd { background: #F4F4F4; } /* was #eee; */
.tableHeading {
font-weight: bold;
white-space: nowrap;
}
.label {
font-weight: bold;
text-align: right;
white-space: nowrap;
}
/****************************************************************/
/***********************
* Header layout
***********************/
/* HEADER 1 */
#header1wrap {
border-bottom: 4px solid #bbb; /*#DCE2E5;*/
height: 23px;
background: #AB1A2A;
}
#logo {
float: left;
width: 211px;
border-left: 1px solid #ddd;
border-right: 1px solid #ddd;
/* ie5 box model hack */
width: 213px;
voice-family: "\"}\"";
voice-family:inherit;
/* unhack */
width: 211px;
}
/* be nice to Opera */
html>#logo {
width: 211px;
}
#status {
float: left;
padding-left: 10px;
width: 497px;
height: 23px;
color: #ddd;
font-size: .9em;
line-height: 23px;
}
/* HEADER 2 */
#header2wrap {
position: relative;
}
#header2left {
position: absolute;
top: 0;
left: 0;
width: 50%;
background: #fff;
}
#header2right {
position: absolute;
top: 0;
left: 50%;
width: 50%;
margin-top: 36px;
padding: 10px 0;
height: 17px;
line-height: 17px;
background: #dfdfdf; /*#f4f4f4;*/
border-top: 1px solid #bbb; /*#ddd;*/
}
#header2 {
position: absolute;
top: 0;
left: 50%;
margin-left: -360px;
margin-right: 0;
width: 720px;
/* SSK IE 6 Hack */
* html{
width:700px;
}
background: #fff;
}
/*SSK be nice to Opera */
html>#manage { width: 487px; }
#title {
float: left;
width: 211px;
height: 74px;
border-left: 1px solid #ddd;
border-right: 1px solid #ddd;
}
#manage {
float: left;
margin-top: 36px;
border-top: 1px solid #bbb; /*#ddd;*/
padding: 10px;
width: 485px;
height: 17px;
background: #dfdfdf; /*#f4f4f4;*/
line-height: 17px;
/* ie5 box model hack */
width: 507px;
voice-family: "\"}\"";
voice-family:inherit;
/* unhack */
width: 485px;
}
/* be nice to Opera */
html>#manage { width: 487px; }
#manage a, #manage a:link, #manage a:visited {
color: #85A3C2;
text-decoration: none;
font-weight: bold;
}
#manage a:hover {
color: #596C80;
text-decoration: underline;
font-weight: bold;
}
#manage a:active {color: #85A3C2;}
/* HEADER 3 */
#header3wrap {
margin-top: 74px;
background: #dfdfdf; /*#f4f4f4;*/
border-top: 1px solid #bbb; /*#ddd;*/
border-bottom: 1px solid #bbb /*#ddd;*/
}
#header3 {
padding: 8px 0 8px 10px;
width: 750px;
/* ie5 box model hack */
width: 760px;
voice-family: "\"}\"";
voice-family:inherit;
/* unhack */
width: 750px;
}
/* be nice to Opera */
html>#header3 {
width: 750px;
}
/***********************
* Contents
***********************/
#content {
margin-top: 20px;
padding-left: 10px;
width: 750px;
/* ie5 box model hack */
width: 760px;
voice-family: "\"}\"";
voice-family:inherit;
/* unhack */
width: 760px;
}
/* be nice to Opera */
html>#content {
width: 750px;
}
#footer {
margin: 20px 0;
padding: 15px 0;
border-top: 1px solid #ddd;
}
#footer .inner {
padding-left: 10px;
width: 750px;
/* ie5 box model hack */
width: 760px;
voice-family: "\"}\"";
voice-family:inherit;
/* unhack */
width: 750px;
}
/* be nice to Opera */
html>#footer .inner {
width: 750px;
}
/***********************
* Text
***********************/
h1 {
margin-top: 12px;
margin-left: 10px;
margin-bottom: 0;
padding: 0;
font-size: 24px;
font-weight: normal;
color: #a0a0a0;
}
ul {
margin-top: 0px;
}
.sep {
font-size: 10px;
font-weight: bold;
line-height: 12px;
color: #ccc;
padding: 0 2px;
}
.headerlabel {
padding-right: 2px;
}
/* LINKS */
a, a:link, a:visited {
text-decoration: none;
font-weight: normal;
color: #85A3C2;
}
a:hover {
color: #596C80;
text-decoration: underline;
}
a:active {
color: #85A3C2;
}
/***********************
* Forms
***********************/
form {
margin: 0;
padding: 0;
}
form#existingguest {
display: inline;
}
.selectnull {
font-style: italic;
color: grey;
}
.textinput, .dropdown {
border: 1px solid #999;
color: #333;
background: #fff;
font-size: 11px;
}
#guestid {
width: 150px;
}
#guesttask {
margin: 0 5px;
width: 150px;
}
.inputsubmit
{
color: #666;
font-size: 12px;
background: #fc0;
font-weight: bold;
}
/* HEADER FORM */
#existingguest .textinput, #existingguest .dropdown {
background: #DFE7EB;
border: 1px solid #85A3C2;
height: 15px;
}
#existingguest a, #existingguest a:link, #existingguest a:visited {
color: #85A3C2;
text-decoration: none;
font-weight: bold;
}
#existingguest a:active {color: #85A3C2;}
#existingguest a:hover {
color: #596C80;
text-decoration: underline;
font-weight: bold;
}
.inputsubmitHead {
padding: 0 5px;
color: #666;
font-size: 11px;
background: #DFE7EB;
border: 1px solid #85A3C2;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

View file

@ -0,0 +1,84 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.rdf.model.*" %>
<%@ page import="com.hp.hpl.jena.ontology.OntModel" %>
<%@ page import="com.hp.hpl.jena.shared.Lock" %>
<%@ page import="com.thoughtworks.xstream.XStream" %>
<%@ page import="com.thoughtworks.xstream.io.xml.DomDriver" %>
<%@ page import="edu.cornell.mannlib.vedit.beans.LoginFormBean" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Individual" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.EditLiteral" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditN3Generator" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditSubmission" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.Field" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.filters.VitroRequestPrep" %>
<%@ page import="org.apache.commons.logging.Log" %>
<%@ page import="org.apache.commons.logging.LogFactory" %>
<%@ page import="java.io.StringReader" %>
<%@ page import="java.util.*" %>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.NetIdIdentifierFactory.NetId"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.NetIdIdentifierFactory"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.SelfEditingUriFactory.SelfEditing"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.SelfEditingUriFactory"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.ArrayIdentifierBundle"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle"%>
<%@page import="java.io.IOException"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<http>
Testing getIndividualURIFromNetId()
<%
String[] netids = {"bdc34", "jc55", "bjl24" , "mhd6" , "tpb2" };
for( String netid : netids){
%><h2>Checking <%=netid %></h2><%
checkNetId( netid, out, request, (WebappDaoFactory)application.getAttribute("webappDaoFactory"));
}
%>
</http>
<%!
final String CUWEBAUTH_REMOTE_USER_HEADER = "REMOTE_USER";
private void checkNetId( String inNetId, JspWriter out, HttpServletRequest request, WebappDaoFactory wdf ) throws IOException{
if( inNetId != null
&& inNetId.length() > 0
&& inNetId.length() < 100 ){
NetIdIdentifierFactory.NetId netid = new NetId(inNetId);
SelfEditingUriFactory.SelfEditing selfE = null;
IdentifierBundle idb = new ArrayIdentifierBundle();
idb.add(netid);
//out.println("added NetId object to IdentifierBundle from CUWEBAUTH header");
//VitroRequest vreq = new VitroRequest((HttpServletRequest)request);
String uri = wdf.getIndividualDao().getIndividualURIFromNetId(inNetId);
if( uri != null){
Individual ind = wdf.getIndividualDao().getIndividualByURI(uri);
if( ind != null ){
selfE = new SelfEditing( ind, null );
idb.add( selfE );
out.println("found a URI and an Individual for " + inNetId + " URI: " + ind.getURI());
}else{
out.println("found a URI for the netid " + inNetId + " but could not build Individual");
}
}else{
out.println("could not find a Individual with the neditd of " + inNetId );
}
//putNetIdInSession(session, selfE, netid);
}else{
out.println("no remote user value found or value was longer than 100 chars.");
}
}
%>

42
webapp/web/authtest.jsp Executable file
View file

@ -0,0 +1,42 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="edu.cornell.mannlib.vitro.webapp.web.MiscWebUtils" %>
<html>
<head>
<title>Authroization Test</title>
<link rel="stylesheet" type="text/css" href="css/edit.css">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<table width="90%" cellpadding="1" cellspacing="1" border="0" align="center">
<tr><td colspan="4" height="1"><img src="site_icons/transparent.gif" width="100%" height="1" border="0"></td></tr>
<%
out.println("here");
java.util.Map params = request.getParameterMap();
java.util.Iterator keys = params.keySet().iterator();
%> <tr><td><b>params</b></td></tr> <%
while (keys.hasNext()){
String name = (String) keys.next();
String val = (String) params.get(name);
out.println("<tr><td>"+ name + "</td><td>"+ val +"</td></tr>");
}
%> <tr><td><b>headers</b></td></tr> <%
java.util.Enumeration hnames = request.getHeaderNames();
while( hnames.hasMoreElements() ){
String name = (String) hnames.nextElement();
String val = request.getHeader(name);
out.println("<tr><td>"+ name + "</td><td>"+ val +"</td></tr>");
}%>
</table>
<%= MiscWebUtils.getReqInfo(request) %>
</body>
</html>

View file

@ -0,0 +1,54 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="java.util.*, java.lang.String.*"%>
<%@ page import="edu.cornell.mannlib.vedit.beans.ButtonForm" %>
<%
if (request.getAttribute("title") != null) { %>
<h2><%=request.getAttribute("title")%></h2><%
}
ArrayList<String> logResults = (ArrayList<String>)request.getAttribute("results");
%>
<div class="editingForm">
<table style="margin-bottom:1.5ex;">
<tr>
<td>
<%=logResults.get(logResults.size()-3)%>
</td>
</tr>
<tr>
<td>
<%=logResults.get(logResults.size()-2)%>
</td>
</tr>
<tr>
<td>
<%=logResults.get(logResults.size()-1)%>
</td>
</tr>
<tr>
<td><p></p></td>
</tr>
<tr>
<td>
Log:
</td>
</tr>
<tr>
<td><p></p></td>
</tr>
<%
for(int i=0; i< logResults.size()-3; i++)
{
%><tr>
<td><%=logResults.get(i)%></td>
</tr>
<%
}
%>
</table>
</div>

View file

@ -0,0 +1,76 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<div id="content" class="staticPageBackground">
<div class="feedbackForm">
<h2>${siteName} Feedback and Comments Form</h2>
<p>
<c:choose>
<c:when test='${portalType eq "CALSResearch"}'>
Thank you for your interest in the Cornell University College of Agriculture and Life Sciences Research Portal.
</c:when>
<c:when test='${portalType eq "VIVO"}'>
Thank you for your interest in VIVO.
</c:when>
<c:otherwise>
Thank you for your interest in the ${siteName} portal.
</c:otherwise>
</c:choose>
<p>
<c:if test='${portalType != "clone"}'>
<p>If you are looking for information on:</p>
<ul>
<li>Undergraduate admissions: contact <a href="http://admissions.cornell.edu/">http://admissions.cornell.edu/</a></li>
<li>Undergraduate financial aid: contact <a href="http://finaid.cornell.edu/">http://finaid.cornell.edu/</a></li>
<li>Graduate admissions and information: contact <a href="http://www.gradschool.cornell.edu/">http://www.gradschool.cornell.edu/</a></li>
<li>International Students and Scholars Office: contact <a href="http://www.isso.cornell.edu/">http://www.isso.cornell.edu/</a></li>
<li>Faculty, staff and student directory: contact <a href="http://www.cornell.edu/search?tab=people">http://www.cornell.edu/search/?tab=people</a></li>
<li>General information about Cornell University: <a href="http://www.cornell.edu/">http://www.cornell.edu/</a></li>
</ul>
</c:if>
<p>
If you have a question regarding the content of this portal, please submit the form below.
<c:if test='${(siteName eq "CALSResearch" || siteName eq "CALSImpact")}'>
The reference librarians at Albert R. Mann Library will be in touch with you soon.
</c:if>
</p>
<hr/>
<form name = "contact_form" action="sendmail" method="post" onsubmit="return ValidateForm('contact_form');">
<input type="hidden" name="home" value="${portalId}"/>
<input type="hidden" name="RequiredFields" value="webuseremail,webusername,comments"/>
<input type="hidden" name="RequiredFieldsNames" value="Email address,Name,Comments"/>
<input type="hidden" name="EmailFields" value="webuseremail"/>
<input type="hidden" name="EmailFieldsNames" value="emailaddress"/>
<input type="hidden" name="DeliveryType" value="comment"/>
<p class="normal">My email address is (e.g., userid<b>@institution.edu</b>):</p>
<input style="width:25%;" type="text" name="webuseremail" maxlength="255"/><br/><br/>
<p class="normal">My full name is:</p>
<input style="width:33%;" type="text" name="webusername" maxlength="255"/><br/><br/>
<p class="normal"><i>${siteName} is a service that depends on regular updates and feedback.
Please help us out by providing any necessary corrections and suggestions for additional content (people, departments, courses, research services, etc.)
that you would like to see represented.</i></p>
<h3>Enter your comments, questions, or suggestions in the box below.</h3>
<textarea name="s34gfd88p9x1" rows="10" cols="90"></textarea>
<div>
<input type="submit" value="Send Mail" class="yellowbutton"/>
<input type="reset" value="Clear Form" class="plainbutton"/>
</div
<p style="font-weight: bold; margin-top: 1em">Thank you!</p>
</form>
</div><!--feedbackForm-->
</div><!--content, staticPageBackground-->

View file

@ -0,0 +1,31 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<%@ page language="java" %>
<%@ page import="java.util.*" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Portal" %>
<%
VitroRequest vreq = new VitroRequest(request);
String errorString=request.getParameter("ERR");
if (errorString == null || errorString.equals("")) {
errorString = (String)request.getAttribute("ERR");
}
%>
<table>
<tr>
<td align="center" colspan="3">
<img src="site_icons/bomb.gif" alt="failed email"/><br/>
<% if ( errorString != null && !errorString.equals("")) {%>
<p class="normal">We report the following error in processing your request:<br/>
<b><%=errorString%></b>
</p>
<% } %>
<p class="normal">Return to the <a href="index.jsp">home page</a>.</p>
</td>
</tr>
</table>

View file

@ -0,0 +1,76 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.filters.VitroRequestPrep"%>
<c:set var='themeDir'><c:out value='${portalBean.themeDir}' /></c:set>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head> <!-- from formPrefix.jsp -->
<link rel="stylesheet" type="text/css" href="<c:url value="/${themeDir}css/screen.css"/>" media="screen"/>
<title>VIVO Correction Form</title>
</head>
<body class="formsEdit">
<div id="wrap">
<jsp:include page="/${themeDir}jsp/identity.jsp" flush="true"/>
<div id="contentwrap">
<jsp:include page="/${themeDir}jsp/menu.jsp" flush="true"/>
<!-- end of formPrefix.jsp -->
<div id="content" class="staticPageBackground">
<div class="feedbackForm">
<h2>VIVO Correction and Update Form</h2>
<p/>
<p>
Please submit corrections and/or updates on the form below.
</p>
<p>
Staff on duty during regular business hours will contact you as soon as possible
to confirm or clarify your requested changes.
</p>
<hr/>
<form name = "contact_form" action="sendmail" method="post" onsubmit="return ValidateForm('contact_form');">
<input type="hidden" name="home" value="${portalBean.portalId}"/>
<input type="hidden" name="RequiredFields" value="webuseremail,webusername,comments"/>
<input type="hidden" name="RequiredFieldsNames" value="Email address,Name,Comments"/>
<input type="hidden" name="EmailFields" value="webuseremail"/>
<input type="hidden" name="EmailFieldsNames" value="emailaddress"/>
<input type="hidden" name="DeliveryType" value="correction"/>
<p class="normal">My email address (e.g., userid<b>@institution.edu</b>) is:</p>
<input style="width:25%;" type="text" name="webuseremail" maxlength="255"/><br/><br/>
<p class="normal">My full name is:</p>
<input style="width:33%;" type="text" name="webusername" maxlength="255"/><br/><br/>
<p class="normal">
<i>
Please also optionally include any suggestions for additional content (people, departments, courses, research services, etc.)
that you would like to see represented in VIVO.
</i>
</p>
<h3>Enter your corrections, questions, or suggestions in the box below.</h3>
<textarea name="s34gfd88p9x1" rows="10" cols="90"></textarea>
<p/>
<input type="submit" value="Send Mail" class="yellowbutton"/>
<input type="reset" value="Clear Form" class="plainbutton"/>
<h3>Thank you!</h3>
</form>
</div><!--feedbackForm-->
</div><!--staticPageBackground-->
<c:set var='themeDir'><c:out value='${portalBean.themeDir}'/></c:set>
</div> <!-- contentwrap -->
<jsp:include page="/${themeDir}jsp/footer.jsp" flush="true"/>
</div><!-- wrap -->
</body>
</html>

169
webapp/web/displayRSS.jsp Normal file
View file

@ -0,0 +1,169 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ taglib uri='WEB-INF/tlds/database.tld' prefix='database'%>
<%@ page import="java.util.*,java.io.*,javax.xml.parsers.*,java.net.*,org.gnu.stealthp.rsslib.*" %>
<%
/**
* @version 1 2005-08-04
* @author Jon Corson-Rikert
*
* CHANGE HISTORY
* 2005-08-18 jc55 added "raw" mode for inclusion in tabs
*/
final int DEFAULT_PORTAL_ID=1;
String portalIdStr=(portalIdStr=request.getParameter("home"))==null?String.valueOf(DEFAULT_PORTAL_ID): portalIdStr.equals("")?String.valueOf(DEFAULT_PORTAL_ID):portalIdStr;
int incomingPortalId=Integer.parseInt(portalIdStr);
final String DEFAULT_RSS_URL="http://www.nsf.gov/mynsf/RSS/rss2news.xml"; //http://www.nsf.gov/mynsf/RSS/rss2discoveries.xml
boolean includeHeaders=true;
String rawStr=(rawStr=request.getParameter("raw"))==null?"false": rawStr.equals("")?"false":rawStr;
if (rawStr!=null && rawStr.equalsIgnoreCase("true")) {
includeHeaders=false;
}
if (includeHeaders) {%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<link rel="stylesheet" type="text/css" href="css/edit.css">
<title>RSS</title>
<% final String DEFAULT_APPNAME="RSS";
final String DEFAULT_STYLESHEET="portal";
String appName=DEFAULT_APPNAME;
String styleSheet=DEFAULT_STYLESHEET;%>
<database:query id="portal" scope="page">
SELECT appName,styleSheet FROM portals WHERE id='<%=portalIdStr%>'
</database:query>
<database:rows query="portal">
<% int portal_col=0; %>
<database:columns query="portal" id="theValue">
<% switch (portal_col) {
case 0: appName=theValue; break;
case 1: styleSheet="portal"; break;
}
++portal_col; %>
</database:columns>
</database:rows>
<database:release query="portal" />
</head>
<body><%
}%>
<table width="90%" border="0" cellspacing="0" cellpadding="0" align="center">
<%
if (includeHeaders) {%>
<tr><td colspan="7">
<jsp:include page="header.jsp" flush="true" >
<jsp:param name="home" value="<%=portalIdStr%>" />
</jsp:include>
</td>
</tr>
<tr><td colspan="7" height="1"><img src="site_icons/transparent.gif" width="100%" height="1" border="0"></td></tr><%
} %>
<tr><td colspan="7">
<% String noisyStr=(noisyStr=(String)request.getAttribute("noisy"))==null || noisyStr.equals("")?((noisyStr=request.getParameter("noisy"))==null || noisyStr.equals("")?"false":noisyStr):noisyStr;
boolean NOISY=(noisyStr.equalsIgnoreCase("true"))?true:false;
String urlStr=(urlStr=(String)request.getAttribute("url"))==null || urlStr.equals("")?((urlStr=request.getParameter("url"))==null || urlStr.equals("")?DEFAULT_RSS_URL:urlStr):urlStr;
if (urlStr==null || urlStr.equals("")) {%>
<h3>Error in URL parameter</h3>
<p>System could not decode <%=urlStr%> as a URL</p>
<% } else {
URL u=null;
try {
u = new URL(urlStr);
RSSHandler hand=new RSSHandler();
try {
RSSParser.parseXmlFile(u,hand,false);
RSSChannel ch= hand.getRSSChannel();%>
<h3><%=ch.getTitle()%></h3>
<% String lastDateStr=ch.getLastBuildDate();
if (lastDateStr==null || lastDateStr.equals("")) {
RSSDoublinCoreModule dcModule=ch.getRSSDoublinCoreModule();
if (dcModule!=null){
lastDateStr=dcModule.getDcDate();
if (lastDateStr!=null && !lastDateStr.equals("")){
int timeStartPos=lastDateStr.indexOf("T");
int timeEndPos=lastDateStr.indexOf("Z");
if (timeStartPos>0 && timeEndPos>0){ %>
<p><i>listings current as of <%=lastDateStr.substring(0,timeStartPos)%> at <%=lastDateStr.substring(timeStartPos+1,timeEndPos)%></i></p>
<% } else {%>
<p><i>listings current as of: <%=lastDateStr%></i></p>
<% }
} else {%>
<p>RSSDoublinCoreModule.getDcDate() returns null or blank String</p>
<% }
} else {%>
<p>RSSDoublinCoreModule is null</p>
<% }
}
String copyrightStr=ch.getCopyright();
if (copyrightStr!=null && !copyrightStr.equals("")){%>
<p><%=ch.getCopyright()%></p>
<% }
if (NOISY && ch.getRSSImage()!=null) {%>
<p>IMAGE INFO:<br/><%=ch.getRSSImage().toString()%></p>
<p>IMAGE IN HTML:<br/><%=ch.getRSSImage().toHTML()%></p>
<% } else if (NOISY) {%>
<p>CHANNEL HAS NO IMAGE</p>
<% }
if (NOISY && ch.getRSSTextInput()!=null) {%>
<p>INPUT INFO:<br/><%=ch.getRSSTextInput().toString()%></p>
<p>HTML INPUT:<br/><%=ch.getRSSTextInput().toHTML()%></p>
<% } else if (NOISY) {%>
<p>CHANNEL HAS NO FORM INPUT</p>
<% }
if (NOISY && ch.getDoublinCoreElements()!=null) {%>
<p>DUBLIN CORE INFO:<br/><%=ch.getDoublinCoreElements().toString()%></p>
<% } else if (NOISY) {%>
<p>CHANNEL HAS NO DUBLIN CORE TAGS</p>
<% }%>
<% if (NOISY) {%>
<h3>SEQUENCE INFO</h3>
<% if (ch.getItemsSequence()!=null) {%>
<p><%=hand.getRSSChannel().getItemsSequence().toString()%></p>
<% } else if (NOISY) {%>
<p>CHANNEL HAS NO SEQUENCE; MAYBE VERSION 0.9 or 2+?</p>
<% }
}
LinkedList lst = hand.getRSSChannel().getItems();%>
<h3>ITEMS INFO (<%=lst.size()%>)</h3>
<ul>
<% for (int i = 0; i < lst.size(); i++){
RSSItem itm = (RSSItem)lst.get(i);%>
<li><%=itm.toString()%></li>
<% if (itm.getDoublinCoreElements()!=null) {%>
<br/>DUBLIN CORE INFO FOR ITEM: <%=itm.getDoublinCoreElements().toString()%>
<% } else if (NOISY) {%>
<br/>ITEM HAS NO DUBLIN CORE TAGS
<% }%>
</li>
<% } // end for
} catch (org.gnu.stealthp.rsslib.RSSException ex) {%>
<h3>error initializing RSSHandler</h3>
<p><%=ex.getMessage()%></p>
<% }
} catch (java.net.MalformedURLException ex) {%>
<h3>Error in URL parameter</h3>
<p>System could not convert <%=urlStr%> to a Java URL: <%=ex.getMessage()%></p>
<% }
} // end else URLstr not null or blank%>
</td>
</tr>
<%
if (includeHeaders) {%>
<tr><td colspan="7">
<jsp:include page="footer.jsp" flush="true">
<jsp:param name="home" value="<%=portalIdStr%>" />
</jsp:include>
</td>
</tr><%
}%>
</table><%
if (includeHeaders) {%>
</body>
</html><%
}%>

5593
webapp/web/dojo.js vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,107 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%@ taglib uri="http://vitro.mannlib.cornell.edu/vitro/tags/PropertyEditLink" prefix="edLnk" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Individual" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Property" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.PropertyGroup" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.DataProperty" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.KeywordProperty" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.dao.PropertyGroupDao" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="org.apache.commons.logging.Log" %>
<%@ page import="org.apache.commons.logging.LogFactory" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.filters.VitroRequestPrep" %>
<%@ page import="edu.cornell.mannlib.vedit.beans.LoginFormBean" %>
<jsp:useBean id="loginHandler" class="edu.cornell.mannlib.vedit.beans.LoginFormBean" scope="session" />
<%!
public static Log log = LogFactory.getLog("edu.cornell.mannlib.vitro.webapp.jsp.edit.dashboardPropsList.jsp");
%>
<%
boolean showSelfEdits=false;
boolean showCuratorEdits=false;
if( VitroRequestPrep.isSelfEditing(request) ) {
showSelfEdits=true;
log.debug("self editing active");
} else {
log.debug("self editing inactive");
}
if (loginHandler!=null && loginHandler.getLoginStatus()=="authenticated" && Integer.parseInt(loginHandler.getLoginRole())>=loginHandler.getEditor()) {
showCuratorEdits=true;
log.debug("curator editing active");
} else {
log.debug("curator editing inactive");
}%>
<c:set var='entity' value='${requestScope.entity}'/><%-- just moving this into page scope for easy use --%>
<c:set var='portal' value='${requestScope.portalBean}'/><%-- likewise --%>
<%
log.debug("Starting dashboardPropsList.jsp");
// The goal here is to retrieve a list of object and data properties appropriate for the vclass
// of the individual, by property group, and sorted the same way they would be in the public interface
Individual subject = (Individual) request.getAttribute("entity");
if (subject==null) {
throw new Error("Subject individual must be in request scope for dashboardPropsList.jsp");
}
String defaultGroupName=null;
String unassignedGroupName = (String) request.getAttribute("unassignedPropsGroupName");
if (unassignedGroupName != null && unassignedGroupName.length()>0) {
defaultGroupName = unassignedGroupName;
log.debug("found temp group attribute \""+unassignedGroupName+"\" for unassigned properties");
}
VitroRequest vreq = new VitroRequest(request);
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
PropertyGroupDao pgDao = wdf.getPropertyGroupDao();
ArrayList<PropertyGroup> groupsList = (ArrayList) request.getAttribute("groupsList");
if (groupsList != null) {
if (groupsList.size()>1) {%>
<ul id="propGroupNav">
<% for (PropertyGroup g : groupsList) { %>
<li><h2><a href="#<%=g.getLocalName()%>" title="<%=g.getName()%>"><%=g.getName()%></a></h2></li>
<% }%>
</ul>
<% }
} else {
ArrayList<Property> mergedList = (ArrayList) request.getAttribute("dashboardPropertyList");
if (mergedList!=null) {
String lastGroupName = null;
int groupCount=0;%>
<ul id="propGroupNav">
<% for (Property p : mergedList) {
String groupName = defaultGroupName; // may be null
String groupLocalName = defaultGroupName; // may be null
String groupPublicDescription=null;
String propertyLocalName = p.getLocalName() == null ? "unspecified" : p.getLocalName();
String openingGroupLocalName = (String) request.getParameter("curgroup");
if (p.getGroupURI()!=null) {
PropertyGroup pg = pgDao.getGroupByURI(p.getGroupURI());
if (pg != null) {
groupName=pg.getName();
groupLocalName=pg.getLocalName();
groupPublicDescription=pg.getPublicDescription();
}
}
if (groupName != null && !groupName.equals(lastGroupName)) {
lastGroupName=groupName;
++groupCount;
if (openingGroupLocalName == null || openingGroupLocalName.equals("")) {
openingGroupLocalName = groupLocalName;
}
if (openingGroupLocalName.equals(groupLocalName)) {%>
<li class="currentCat"><h2><a href="#<%=groupLocalName%>" title="<%=groupName%>"><%=groupName%></a></h2></li>
<% } else { %>
<li><h2><a href="#<%=groupLocalName%>" title="<%=groupName%>"><%=groupName%></a></h2></li>
<% }
}
}%>
</ul>
<% }
}%>

View file

@ -0,0 +1,152 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.DataProperty" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Individual" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.RdfLiteralHash" %>
<%@ page import="edu.cornell.mannlib.vedit.beans.LoginFormBean" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.filters.VitroRequestPrep" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.web.MiscWebUtils" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.Controllers" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Portal" %>
<%@ page import="java.util.HashMap" %>
<%
org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog("edu.cornell.mannlib.vitro.webapp.jsp.edit.editDatapropStmtRequestDispatch");
//Log log = LogFactory.getLog("edu.cornell.mannlib.vitro.webapp.jsp.edit.editDatapropStmtRequestDispatch");
%>
<%
// Decide which form to forward to, set subjectUri, subjectUriJson, predicateUri, predicateUriJson in request
// Also get the Individual for the subjectUri and put it in the request scope
// If a datapropKey is sent it as an http parameter, then set datapropKey and datapropKeyJson in request, and
// also get the DataPropertyStatement matching the key and put it in the request scope
/* *************************************
Parameters:
subjectUri
predicateUri
datapropKey (optional)
cmd (optional -- deletion)
formParam (optional)
************************************** */
final String DEFAULT_DATA_FORM = "defaultDatapropForm.jsp";
final String DEFAULT_ERROR_FORM = "error.jsp";
if (!VitroRequestPrep.isSelfEditing(request) && !LoginFormBean.loggedIn(request, LoginFormBean.NON_EDITOR)) {
%> <c:redirect url="<%= Controllers.LOGIN %>" /> <%
}
VitroRequest vreq = new VitroRequest(request);
if( EditConfiguration.getEditKey( vreq ) == null ){
vreq.setAttribute("editKey",EditConfiguration.newEditKey(session));
}else{
vreq.setAttribute("editKey", EditConfiguration.getEditKey( vreq ));
}
String subjectUri = vreq.getParameter("subjectUri");
String predicateUri = vreq.getParameter("predicateUri");
String formParam = vreq.getParameter("editForm");
String command = vreq.getParameter("cmd");
if( subjectUri == null || subjectUri.trim().length() == 0 ) {
log.error("required subjectUri parameter missing");
throw new Error("subjectUri was empty, it is required by editDatapropStmtRequestDispatch");
}
if( predicateUri == null || predicateUri.trim().length() == 0) {
log.error("required subjectUri parameter missing");
throw new Error("predicateUri was empty, it is required by editDatapropStmtRequestDispatch");
}
vreq.setAttribute("subjectUri", subjectUri);
vreq.setAttribute("subjectUriJson", MiscWebUtils.escape(subjectUri));
vreq.setAttribute("predicateUri", predicateUri);
vreq.setAttribute("predicateUriJson", MiscWebUtils.escape(predicateUri));
/* since we have the URIs let's put the individual, data property, and optional data property statement in the request */
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
Individual subject = wdf.getIndividualDao().getIndividualByURI(subjectUri);
if( subject == null ) {
log.error("Could not find subject Individual '"+subjectUri+"' in model");
throw new Error("editDatapropStmtRequest.jsp: Could not find subject Individual in model: '" + subjectUri + "'");
}
vreq.setAttribute("subject", subject);
DataProperty dataproperty = wdf.getDataPropertyDao().getDataPropertyByURI( predicateUri );
if( dataproperty == null ) {
log.error("Could not find data property '"+predicateUri+"' in model");
throw new Error("editDatapropStmtRequest.jsp: Could not find DataProperty in model: " + predicateUri);
}
vreq.setAttribute("predicate", dataproperty);
String url= "/edit/editDatapropStmtRequestDispatch.jsp"; //I'd like to get this from the request but...
vreq.setAttribute("formUrl", url + "?" + vreq.getQueryString());
String datapropKeyStr = vreq.getParameter("datapropKey");
int dataHash = 0;
if( datapropKeyStr != null ){
try {
dataHash = Integer.parseInt(datapropKeyStr);
vreq.setAttribute("datahash", dataHash);
log.debug("Found a datapropKey in parameters and parsed it to int: " + dataHash);
} catch (NumberFormatException ex) {
throw new JspException("Cannot decode incoming datapropKey value "+datapropKeyStr+" as an integer hash in editDatapropStmtRequestDispatch.jsp");
}
}
DataPropertyStatement dps = null;
if( dataHash != 0) {
dps = RdfLiteralHash.getDataPropertyStmtByHash( subject ,dataHash);
if (dps==null) {
log.error("No match to existing data property \""+predicateUri+"\" statement for subject \""+subjectUri+"\" via key "+datapropKeyStr);
%><jsp:forward page="/edit/messages/dataPropertyStatementMissing.jsp"></jsp:forward> <%
return;
}
vreq.setAttribute("dataprop", dps );
}
if( log.isDebugEnabled() ){
log.debug("predicate for DataProperty from request is " + dataproperty.getURI() + " with rangeDatatypeUri of '" + dataproperty.getRangeDatatypeURI() + "'");
if( dps == null )
log.debug("no exisitng DataPropertyStatement statement was found, making a new statemet");
else{
log.debug("Found an existing DataPropertyStatement");
String msg = "existing datapropstmt: ";
msg += " subject uri: <"+dps.getIndividualURI() + ">\n";
msg += " prop uri: <"+dps.getDatapropURI() + ">\n";
msg += " prop data: \"" + dps.getData() + "\"\n";
msg += " datatype: <" + dps.getDatatypeURI() + ">\n";
msg += " hash of this stmt: " + RdfLiteralHash.makeRdfLiteralHash(dps);
log.debug(msg);
}
}
vreq.setAttribute("preForm", "/edit/formPrefix.jsp");
vreq.setAttribute("postForm", "/edit/formSuffix.jsp");
if( "delete".equals(command) ){ %>
<jsp:forward page="/edit/forms/datapropStmtDelete.jsp"/>
<% return;
}
if( formParam == null ){
String form = dataproperty.getCustomEntryForm();
if (form != null && form.length()>0) {
log.warn("have a custom form for this data property: "+form);
vreq.setAttribute("hasCustomForm","true");
} else {
form = DEFAULT_DATA_FORM;
}
vreq.setAttribute("form" ,form);
} else {
vreq.setAttribute("form", formParam);
}
if( session.getAttribute("requestedFromEntity") == null )
session.setAttribute("requestedFromEntity", subjectUri );
%>
<jsp:forward page="/edit/forms/${form}" />

View file

@ -0,0 +1,247 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Individual" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.web.MiscWebUtils" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.filters.VitroRequestPrep" %>
<%@ page import="edu.cornell.mannlib.vedit.beans.LoginFormBean" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.Controllers" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Portal" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="org.apache.commons.logging.Log" %>
<%@ page import="org.apache.commons.logging.LogFactory" %>
<%@ page errorPage="/error.jsp" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%!
public static Log log = LogFactory.getLog("edu.cornell.mannlib.vitro.webapp.jsp.edit.editRequestDispatch.jsp");
%>
<%
/*
Decide which form to forward to, set subjectUri, subjectUriJson, predicateUri, and predicateUriJson in request.
Also get the Individual for the subjectUri and put it in the request scope.
If objectUri is set as a http parameter, then set objectUri and objectUriJson in request, also get the
Individual for the objectUri and put it in the request.
/* *************************************
Parameters:
subjectUri
predicateUri
objectUri (optional)
cmd (optional)
typeOfNew (optional)
************************************** */
final String DEFAULT_OBJ_FORM = "defaultObjPropForm.jsp";
final String DEFAULT_ERROR_FORM = "error.jsp";
final String DEFAULT_ADD_INDIVIDUAL = "defaultAddMissingIndividualForm.jsp";
request.getSession(true);
if (!VitroRequestPrep.isSelfEditing(request)
&& !LoginFormBean.loggedIn(request, LoginFormBean.NON_EDITOR)) {
%> <c:redirect url="<%= Controllers.LOGIN %>" /> <%
}
String editKey = (EditConfiguration.getEditKey(request) == null)
? EditConfiguration.newEditKey(session)
: EditConfiguration.getEditKey(request);
request.setAttribute("editKey", editKey);
// set the referrer URL, if available
setEditReferer(editKey, request.getHeader("Referer"), request.getSession());
/* Figure out what type of edit is being requested,
setup for that type of edit OR forward to some
thing that can do the setup */
String subjectUri = request.getParameter("subjectUri");
String predicateUri = request.getParameter("predicateUri");
String formParam = request.getParameter("editform");
String command = request.getParameter("cmd");
String typeOfNew = request.getParameter("typeOfNew");
//If there is no specified editForm then the subjectURI and the predicate
//are needed to determin which form to use for this edit.
if (formParam == null || "".equals(formParam)) {
if (subjectUri == null || subjectUri.trim().length() == 0)
throw new Error(
"subjectUri was empty, it is required by editRequestDispatch");
if ((predicateUri == null || predicateUri.trim().length() == 0)
&& (formParam == null || formParam.trim().length() == 0)) {
throw new Error(
"No form was specified, since both predicateUri and"
+ " editform are empty, One of these is required"
+ " by editRequestDispatch to choose a form.");
}
}else{
log.debug("Found editform in http parameters.");
}
request.setAttribute("subjectUri", subjectUri);
request.setAttribute("subjectUriJson", MiscWebUtils.escape(subjectUri));
if (predicateUri != null) {
request.setAttribute("predicateUri", predicateUri);
request.setAttribute("predicateUriJson", MiscWebUtils.escape(predicateUri));
}
if (formParam != null && formParam.length() > 0) {
request.setAttribute("editForm", formParam);
} else {
formParam = null;
}
String objectUri = request.getParameter("objectUri");
if (objectUri != null) {
request.setAttribute("objectUri", objectUri);
request.setAttribute("objectUriJson", MiscWebUtils
.escape(objectUri));
}
if( typeOfNew != null )
request.setAttribute("typeOfNew", typeOfNew);
request.setAttribute("urlPatternToReturnTo", request
.getParameter("urlPattern") == null ? "/entity" : request
.getParameter("urlPattern"));
log.debug("setting urlPatternToReturnTo as "
+ request.getAttribute("urlPatternToReturnTo"));
/* since we have the URIs lets put the individuals in the request */
/* get some data to make the form more useful */
VitroRequest vreq = new VitroRequest(request);
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
if( subjectUri != null ){
Individual subject = wdf.getIndividualDao().getIndividualByURI(subjectUri);
//if (subject == null && formParam == null)
// throw new Error("In editRequestDispatch.jsp, could not find subject in model: '"
// + subjectUri + "'");
if( subject != null ){
request.setAttribute("subject", subject);
}
}
boolean isEditOfExistingStmt = false;
if (objectUri != null) {
Individual object = wdf.getIndividualDao().getIndividualByURI(
objectUri);
if (object != null) {
request.setAttribute("object", object);
isEditOfExistingStmt = true;
}
}
/* keep track of what form we are using so it can be returned to after a failed validation */
String url = "/edit/editRequestDispatch.jsp"; //I'd like to get this from the request but...
request.setAttribute("formUrl", url + "?"
+ request.getQueryString());
request.setAttribute("preForm", "/edit/formPrefix.jsp");
request.setAttribute("postForm", "/edit/formSuffix.jsp");
if ("delete".equals(command)) {
%><jsp:forward page="/edit/forms/propDelete.jsp"/><%
return;
}
//Certain predicates may be annotated to change the behavior of the edit
//link. Check for this annnotation and, if present, simply redirect
//to the normal individual display for the object URI instead of bringing
//up an editing form.
//Note that we do not want this behavior for the delete link (handled above).
if ( (predicateUri != null) && (objectUri != null) && (wdf.getObjectPropertyDao().skipEditForm(predicateUri)) ) {
%><c:redirect url="/individual">
<c:param name="uri" value="${param.objectUri}"/>
<c:param name="relatedSubjectUri" value="${param.subjectUri}"/>
<c:param name="relatingPredicateUri" value="${param.predicateUri}"/>
</c:redirect>
<%
return;
}
if (session.getAttribute("requestedFromEntity") == null)
session.setAttribute("requestedFromEntity", subjectUri);
ObjectProperty objectProp = null;
String customForm = null;
String form = DEFAULT_OBJ_FORM;
if( predicateUri != null ){
objectProp = wdf.getObjectPropertyDao().getObjectPropertyByURI(predicateUri);
request.setAttribute("predicate", objectProp);
boolean isForwardToCreateNew =
( objectProp != null && objectProp.getOfferCreateNewOption() && objectProp.getSelectFromExisting() == false)
|| ( objectProp != null && objectProp.getOfferCreateNewOption() && "create".equals(command));
if (isForwardToCreateNew) {
request.setAttribute("isForwardToCreateNew", new Boolean(true));
if (customForm != null && customForm.length() > 0) {
//bdc34: maybe this should be the custom form on the class, not the property.
form = objectProp.getCustomEntryForm();
} else {
//If a objectProperty is both provideSelect and offerCreateNewOption
// and a user gos to a defaultObjectProperty.jsp form then the user is
// offered the option to create a new Individual and replace the
// object in the existing objectPropertyStatement with this new individual.
boolean isReplaceWithNew =
isEditOfExistingStmt && "create".equals(command)
&& objectProp != null && objectProp.getOfferCreateNewOption() == true;
// If an objectProperty is selectFromExisitng==false and offerCreateNewOption == true
// the we want to forward to the create new form but edit the existing object
// of the objPropStmt.
boolean isForwardToCreateButEdit =
isEditOfExistingStmt && objectProp != null
&& objectProp.getOfferCreateNewOption() == true
&& objectProp.getSelectFromExisting() == false
&& ! "create".equals(command);
if( isReplaceWithNew ){
request.setAttribute("isReplaceWithNew", new Boolean(true));
form = DEFAULT_ADD_INDIVIDUAL;
}else if( isForwardToCreateButEdit ){
request.setAttribute("isForwardToCreateButEdit", new Boolean(true));
form = DEFAULT_ADD_INDIVIDUAL;
}else {
form = DEFAULT_ADD_INDIVIDUAL;
}
}
}
if( ! isForwardToCreateNew ){
if( objectProp != null && objectProp.getCustomEntryForm() != null && objectProp.getCustomEntryForm().length() > 0){
form = objectProp.getCustomEntryForm();
}else{
form = DEFAULT_OBJ_FORM ;
}
}
} else {
//case where a form was passed as a http parameter
form = formParam;
}
request.setAttribute("form", form);
%>
<jsp:forward page="/edit/forms/${form}"/>
<%!
private static synchronized void setEditReferer(String editKey, String refererUrl, HttpSession session) {
if (refererUrl != null) {
Object editRefererObj = session.getAttribute("editRefererMap");
HashMap<String,String> editRefererMap =
(editRefererObj != null && (editRefererObj instanceof HashMap))
? (HashMap<String,String>) editRefererObj
: new HashMap<String,String>();
session.setAttribute("editRefererMap", editRefererMap);
editRefererMap.put(editKey, refererUrl);
}
}
%>

View file

@ -0,0 +1,14 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<jsp:include page="/edit/formPrefix.jsp" >
<jsp:param name="useTinyMCE" value="false"/>
<jsp:param name="useAutoComplete" value="false"/>
</jsp:include>
<h2>There was a problem uploading your file.</h2>
<div>
${errors}
</div>
<jsp:include page="/edit/formSuffix.jsp" />

View file

@ -0,0 +1,85 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.filters.VitroRequestPrep"%>
<c:set var='themeDir'><c:out value='${portalBean.themeDir}'/></c:set>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head> <!-- formPrefix.jsp -->
<%
String useTinyMCE = (useTinyMCE=request.getParameter("useTinyMCE")) != null && !(useTinyMCE.equals("")) ? useTinyMCE : "false";
if (useTinyMCE.equalsIgnoreCase("true")) {
String height = (height=request.getParameter("height")) != null && !(height.equals("")) ? height : "200";
String width = (width=request.getParameter("width")) != null && !(width.equals("")) ? width : "75%";
String defaultButtons="bold,italic,underline,separator,link,bullist,numlist,separator,sub,sup,charmap,separator,undo,redo,separator,code";
String buttons = (buttons=request.getParameter("buttons")) != null && !(buttons.equals("")) ? buttons : defaultButtons;
String tbLocation = (tbLocation=request.getParameter("toolbarLocation")) != null && !(tbLocation.equals("")) ? tbLocation : "top";
%>
<script language="javascript" type="text/javascript" src="../js/tiny_mce/tiny_mce.js"></script>
<script language="javascript" type="text/javascript">
tinyMCE.init({
theme : "advanced",
mode : "textareas",
theme_advanced_buttons1 : "<%=buttons%>",
theme_advanced_buttons2 : "",
theme_advanced_buttons3 : "",
theme_advanced_toolbar_location : "<%=tbLocation%>",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_path : false,
theme_advanced_resizing : true,
height : "<%=height%>",
width : "<%=width%>",
valid_elements : "a[href|name|title],br,p,i,em,cite,strong/b,u,sub,sup,ul,ol,li",
fix_list_elements : true,
fix_nesting : true,
cleanup_on_startup : true,
gecko_spellcheck : true,
forced_root_block: false
//forced_root_block : 'p',
// plugins: "paste",
// theme_advanced_buttons1_add : "pastetext,pasteword,selectall",
// paste_create_paragraphs: false,
// paste_create_linebreaks: false,
// paste_use_dialog : true,
// paste_auto_cleanup_on_paste: true,
// paste_convert_headers_to_strong : true
// save_callback : "customSave",
// content_css : "example_advanced.css",
// extended_valid_elements : "a[href|target|name]",
// plugins : "table",
// theme_advanced_buttons3_add_before : "tablecontrols,separator",
// invalid_elements : "li",
// theme_advanced_styles : "Header 1=header1;Header 2=header2;Header 3=header3;Table Row=tableRow1", // Theme specific setting CSS classes
});
</script>
<% } %>
<script language="javascript" type="text/javascript" src="../js/jquery.js"></script>
<script language="javascript" type="text/javascript" src="../js/jquery_plugins/jquery.bgiframe.pack.js"></script>
<script language="javascript" type="text/javascript" src="../js/jquery_plugins/thickbox/thickbox-compressed.js"></script>
<!-- <script language="javascript" type="text/javascript" src="../js/jquery_plugins/ui.datepicker.js"></script> -->
<script language="javascript" type="text/javascript" src="../js/jquery_plugins/jquery-autocomplete/jquery.autocomplete.pack.js"></script>
<% String useAutoComplete = (useAutoComplete=request.getParameter("useAutoComplete")) != null && !(useAutoComplete.equals("")) ? useAutoComplete : "false";
if (useAutoComplete.equalsIgnoreCase("true")) { %>
<link rel="stylesheet" type="text/css" href="../js/jquery_plugins/jquery-autocomplete/jquery.autocomplete.css"/>
<% } %>
<!-- <link rel="stylesheet" type="text/css" href="../js/jquery_plugins/ui.datepicker.css"/> -->
<link rel="stylesheet" type="text/css" href="../js/jquery_plugins/thickbox/thickbox.css"/>
<link rel="stylesheet" type="text/css" href="<c:url value="/${themeDir}css/screen.css"/>" media="screen"/>
<link rel="stylesheet" type="text/css" href="<c:url value="/${themeDir}css/formedit.css" />" media="screen"/>
<title>Edit</title>
</head>
<body class="formsEdit">
<div id="wrap" class="container">
<jsp:include page="/${themeDir}jsp/identity.jsp" flush="true"/>
<jsp:include page="/${themeDir}jsp/menu.jsp" flush="true"/>
<div id="contentwrap">
<div id="content" class="form">
<!-- end of formPrefix.jsp -->

View file

@ -0,0 +1,17 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.filters.VitroRequestPrep"%>
<c:set var='themeDir'><c:out value='${portalBean.themeDir}' /></c:set>
</div> <!-- #content.form -->
</div>
<div class="push"></div>
<jsp:include page="/${themeDir}jsp/footer.jsp" flush="true"/>
</div><!-- end wrap -->
</body>
</html>

View file

@ -0,0 +1,270 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.VClass" %>
<%@ page import="com.hp.hpl.jena.rdf.model.Literal" %>
<%@ page import="com.hp.hpl.jena.rdf.model.Model" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Individual" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="v" uri="http://vitro.mannlib.cornell.edu/vitro/tags" %>
<%
Individual subject = (Individual)request.getAttribute("subject");
ObjectProperty prop = (ObjectProperty)request.getAttribute("predicate");
if (prop == null) throw new Error("no object property specified via incoming predicate attribute in defaultAddMissingIndividualForm.jsp");
String propDomainPublic = (prop.getDomainPublic() == null) ? "affiliation" : prop.getDomainPublic();
VitroRequest vreq = new VitroRequest(request);
//String contextPath = vreq.getContextPath();
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
if( prop.getRangeVClassURI() == null )throw new Error("Property has null for its range class URI");
VClass rangeClass = wdf.getVClassDao().getVClassByURI(prop.getRangeVClassURI());
if( rangeClass == null ) throw new Error ("Cannot find class for range for property. Looking for " + prop.getRangeVClassURI() );
//vreq.setAttribute("rangeClassLocalName",rangeClass.getLocalName());
//vreq.setAttribute("rangeClassNamespace",rangeClass.getNamespace());
vreq.setAttribute("rangeClassUri",prop.getRangeVClassURI());
vreq.setAttribute("curatorReviewUri","http://vivo.library.cornell.edu/ns/0.1#CuratorReview");
//get the current portal and make this new individual a member of that portal
vreq.setAttribute("portalUri", vreq.getPortal().getTypeUri());
%>
<v:jsonset var="queryForInverse" >
PREFIX owl: <http://www.w3.org/2002/07/owl#>
SELECT ?inverse_property
WHERE { ?inverse_property owl:inverseOf ?predicate }
</v:jsonset>
<%-- Enter here the class names to be used for constructing MONIKERS_VIA_VCLASS pick lists
These are then referenced in the field's ObjectClassUri but not elsewhere.
Note that you can't reference a jsonset variable inside another jsonset expression
or you get double escaping problems --%>
<v:jsonset var="newIndividualVClassUri">${rangeClassUri}</v:jsonset>
<%-- Then enter a SPARQL query for each field, by convention concatenating the field id with "Existing"
to convey that the expression is used to retrieve any existing value for the field in an existing individual.
Each of these must then be referenced in the sparqlForExistingLiterals section of the JSON block below
and in the literalsOnForm --%>
<v:jsonset var="nameExisting" >
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?existingName
WHERE { ?newIndividual rdfs:label ?existingName }
</v:jsonset>
<%-- Pair the "existing" query with the skeleton of what will be asserted for a new statement involving this field.
the actual assertion inserted in the model will be created via string substitution into the ? variables.
NOTE the pattern of punctuation (a period after the prefix URI and after the ?field) --%>
<v:jsonset var="nameAssertion" >
@prefix vivo: <http://vivo.library.cornell.edu/ns/0.1#> .
?newIndividual rdfs:label ?name .
</v:jsonset>
<v:jsonset var="monikerExisting" >
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?existingMoniker
WHERE { ?newIndividual vitro:moniker ?existingMoniker }
</v:jsonset>
<v:jsonset var="monikerAssertion" >
@prefix vivo: <http://vivo.library.cornell.edu/ns/0.1#> .
?newIndividual vitro:moniker ?moniker .
</v:jsonset>
<v:jsonset var="linkUrlExisting" >
PREFIX vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#>
SELECT ?existingLinkUrl
WHERE { ?newIndividual vitro:primaryLink ?newLink ;
?newLink vitro:linkURL ?existingLinkUrl .
}
</v:jsonset>
<v:jsonset var="linkUrlAssertion" >
@prefix vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> .
?newLink vitro:linkURL ?linkUrl .
</v:jsonset>
<v:jsonset var="n3ForEdit" >
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix vivo: <http://vivo.library.cornell.edu/ns/0.1#> .
@prefix vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> .
?newIndividual rdf:type <${curatorReviewUri}> .
?newIndividual rdf:type <${rangeClassUri}> .
?subject ?predicate ?newIndividual .
?newIndividual rdfs:label ?name .
</v:jsonset>
<v:jsonset var="n3Inverse" >
?newIndividual ?inverseProp ?subject .
</v:jsonset>
<%-- make sure you have all the @prefix entries to cover the statements in each block --%>
<v:jsonset var="n3optional" >
@prefix vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> .
?newIndividual vitro:moniker ?moniker .
</v:jsonset>
<%-- set the portal of the new individual to the current portal. --%>
<v:jsonset var="n3portal">
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
?newIndividual rdf:type <${portalUri}> .
</v:jsonset>
<%-- note that it's safer to have multiple distinct optional blocks so that a failure in one
will not prevent correct sections from being inserted --%>
<v:jsonset var="n3link" >
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> .
?newLink
rdf:type vitro:Link ;
vitro:linkURL ?linkUrl ;
vitro:linkAnchor ?name ;
vitro:linkDisplayRank "1" .
?newIndividual vitro:primaryLink ?newLink .
</v:jsonset>
<c:set var="editjson" scope="request">
{
"formUrl" : "${formUrl}",
"editKey" : "${editKey}",
"urlPatternToReturnTo" : "/entity",
"subject" : [ "subject", "${subjectUriJson}" ],
"predicate" : [ "predicate", "${predicateUriJson}" ],
"object" : [ "newIndividual", "${objectUriJson}", "URI" ],
"n3required" : [ "${n3ForEdit}" ],
"n3optional" : [ "${n3optional}", "${n3Inverse}", "${n3link}", "${n3portal}" ],
"newResources" : {
"newIndividual" : "http://vivo.library.cornell.edu/ns/0.1#individual",
"newLink" : "http://vitro.mannlib.cornell.edu/ns/vitro/0.7#Link"
},
"urisInScope" : { },
"literalsInScope" : { },
"urisOnForm" : [ ],
"literalsOnForm" : [ "name","moniker","linkUrl" ],
"filesOnForm" : [ ],
"sparqlForLiterals" : { },
"sparqlForUris" : { "inverseProp" : "${queryForInverse}" },
"sparqlForExistingLiterals" : {
"name" : "${nameExisting}",
"moniker" : "${monikerExisting}",
"linkUrl" : "${linkUrlExisting}"
},
"sparqlForExistingUris" : { },
"fields" : {
"name" : {
"newResource" : "false",
"validators" : [ "nonempty" ],
"optionsType" : "UNDEFINED",
"literalOptions" : [ ],
"predicateUri" : "",
"objectClassUri" : "",
"rangeDatatypeUri" : "",
"rangeLang" : "",
"assertions" : [ "${nameAssertion}" ]
},
"moniker" : {
"newResource" : "false",
"validators" : [ ],
"optionsType" : "MONIKERS_VIA_VCLASS",
"literalOptions" : [ ],
"predicateUri" : "",
"objectClassUri" : "${newIndividualVClassUri}",
"rangeDatatypeUri" : "",
"rangeLang" : "",
"assertions" : [ "${monikerAssertion}" ]
},
"linkUrl" : {
"newResource" : "false",
"validators" : [],
"optionsType" : "UNDEFINED",
"literalOptions" : [],
"predicateUri" : "",
"objectClassUri" : "",
"rangeDatatypeUri" : "",
"rangeLang" : "",
"assertions" : [ "${linkUrlAssertion}" ]
}
}
}
</c:set>
<%
EditConfiguration editConfig = EditConfiguration.getConfigFromSession(session,request);
if( editConfig == null ){
editConfig = new EditConfiguration((String)request.getAttribute("editjson"));
EditConfiguration.putConfigInSession(editConfig, session);
}
Model model = (Model)application.getAttribute("jenaOntModel");
String objectUri = (String)request.getAttribute("objectUri");
if( objectUri != null ){
editConfig.prepareForObjPropUpdate(model);
}else{
editConfig.prepareForNonUpdate(model);
}
String submitButtonLabel=""; // don't put local variables into the request
/* title is used by pre and post form fragments */
if (objectUri != null) {
request.setAttribute("title", "Edit \""+propDomainPublic+"\" entry for " + subject.getName());
submitButtonLabel = "Save changes";
} else {
request.setAttribute("title","Create a new \""+propDomainPublic+"\" entry for " + subject.getName());
submitButtonLabel = "Create new \""+propDomainPublic+"\" entry";
}
%>
<jsp:include page="${preForm}">
<jsp:param name="useTinyMCE" value="false"/>
<jsp:param name="useAutoComplete" value="true"/>
</jsp:include>
<script type="text/javascript" language="javascript">
$(this).load($(this).parent().children('a').attr('src')+" .editForm");
$(document).ready(function() {
var key = $("input[name='editKey']").attr("value");
$.getJSON("<c:url value="/dataservice"/>", {getN3EditOptionList:"1", field: "moniker", editKey: key}, function(json){
$("select#moniker").replaceWith("<input type='text' id='moniker' name='moniker' />");
$("#moniker").autocomplete(json, {
minChars: 0,
width: 320,
matchContains: true,
mustMatch: 0,
autoFill: false,
formatItem: function(row, i, max) {
return row[0];
},
formatMatch: function(row, i, max) {
return row[0];
},
formatResult: function(row) {
return row[0];
}
}).result(function(event, data, formatted) {
$("input#moniker").attr("value", data[1]);
});
}
);
})
</script>
<h2>${title}</h2>
<form action="<c:url value="/edit/processRdfForm2.jsp"/>" >
<v:input type="text" label="name (required)" id="name" size="30"/>
<hr/>
<v:input type="select" label="label (optional)" id="moniker"/> <em>start typing to see existing choices, or add a new label</em>
<v:input type="text" label="associated web page (optional)" id="linkUrl" size="50"/>
<v:input type="submit" id="submit" value="<%=submitButtonLabel%>" cancel="${param.subjectUri}"/>
</form>
<jsp:include page="${postForm}"/>

View file

@ -0,0 +1,118 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.rdf.model.Model" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Individual" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.VClass" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.web.MiscWebUtils" %>
<%@ page import="org.apache.commons.logging.Log" %>
<%@ page import="org.apache.commons.logging.LogFactory" %>
<%@page import="edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="v" uri="http://vitro.mannlib.cornell.edu/vitro/tags" %>
<%!
public static Log log = LogFactory.getLog("edu.cornell.mannlib.vitro.webapp.jsp.edit.forms.admin.mayEditAs.jsp");
public static String RANGE_CLASS = "http://xmlns.com/foaf/0.1/Agent";
public static String PREDICATE = VitroVocabulary.MAY_EDIT_AS;
%>
<%
String subjectUri = (String)request.getAttribute("subjectUri");
VitroRequest vreq = new VitroRequest(request);
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
VClass rangeClass = wdf.getVClassDao().getVClassByURI( RANGE_CLASS );
if( rangeClass == null ) log.debug("Cannot find class for range for property."
+ " Looking for " + RANGE_CLASS);
request.setAttribute("rangeClassUriJson", MiscWebUtils.escape(RANGE_CLASS));
request.setAttribute("predicateUriJson", MiscWebUtils.escape(PREDICATE));
%>
<v:jsonset var="n3ForEdit" >
?subject ?predicate ?objectVar.
</v:jsonset>
<c:set var="editjson" scope="request">
{
"formUrl" : "${formUrl}",
"editKey" : "${editKey}",
"urlPatternToReturnTo" : "/userEdit",
"subject" : [ "subject", "${subjectUriJson}" ] ,
"predicate" : [ "predicate", "${predicateUriJson}" ],
"object" : [ "objectVar" , "${objectUriJson}" , "URI"],
"n3required" : [ "${n3ForEdit}" ],
"n3optional" : [ ],
"newResources" : { },
"urisInScope" : { },
"literalsInScope" : { },
"urisOnForm" : ["objectVar"],
"literalsOnForm" : [ ],
"filesOnForm" : [ ],
"sparqlForLiterals" : { },
"sparqlForUris" : { },
"sparqlForExistingLiterals" : { },
"sparqlForExistingUris" : { },
"fields" : { "objectVar" : {
"newResource" : "false",
"queryForExisting" : { },
"validators" : [ ],
"optionsType" : "INDIVIDUALS_VIA_VCLASS",
"subjectUri" : "${subjectUriJson}",
"subjectClassUri" : "",
"predicateUri" : "",
"objectClassUri" : "${rangeClassUriJson}",
"rangeDatatypeUri" : "",
"rangeLang" : "",
"literalOptions" : [ ] ,
"assertions" : ["${n3ForEdit}"]
}
}
}
</c:set>
<% /* now put edit configuration Json object into session */
EditConfiguration editConfig = new EditConfiguration((String)request.getAttribute("editjson"));
EditConfiguration.putConfigInSession(editConfig, session);
String formTitle ="";
String submitLabel ="";
Model model = (Model)application.getAttribute("jenaOntModel");
if( request.getAttribute("object") != null ){//this block is for an edit of an existing object property statement
editConfig.prepareForObjPropUpdate( model );
formTitle = "Change person that user may edit as";
submitLabel = "save change";
} else {
editConfig.prepareForNonUpdate( model );
formTitle = "Add person that user may edit as";
submitLabel = "add edit right";
}
%>
<jsp:include page="${preForm}"/>
<h2><%=formTitle%></h2>
<form class="editForm" action="<c:url value="/edit/processRdfForm2.jsp"/>" method="post">
<v:input type="select" id="objectVar" size="80" />
<v:input type="submit" id="submit" value="<%=submitLabel%>" cancel="${param.subjectUri}"/>
</form>
<c:if test="${!empty param.objectUri}" >
<form class="deleteForm" action="<c:url value="/edit/n3Delete.jsp"/>" method="post">
<label for="delete"><h3>Remove the right to edit as this person?</h3></label>
<input type="hidden" name="subjectUri" value="${param.subjectUri}"/>
<input type="hidden" name="predicateUri" value="${param.predicateUri}"/>
<input type="hidden" name="objectUri" value="${param.objectUri}"/>
<input type="hidden" name="editform" value="edit/admin/mayEditAs.jsp"/>
<v:input type="submit" id="delete" value="Remove" cancel="" />
</form>
</c:if>
<jsp:include page="${postForm}"/>

View file

@ -0,0 +1,135 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.rdf.model.Model" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Individual" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.VClass" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration" %>
<%@ page import="org.apache.commons.logging.Log" %>
<%@ page import="org.apache.commons.logging.LogFactory" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="v" uri="http://vitro.mannlib.cornell.edu/vitro/tags" %>
<%!
public static Log log = LogFactory.getLog("edu.cornell.mannlib.vitro.webapp.jsp.edit.admin.resourceDisplayVisibility.jsp");
%>
<% /* Here is the calling form, as implemented for props_edit.jsp */
// <form action="edit/editRequestDispatch.jsp" method="get"> */
// <input name="home" type="hidden" value="${portalBean.portalId}" />
// <input name="subjectUri" type= "hidden" value="${property.URI}" />
// <input name="urlPattern" type="hidden" value="/propertyEdit" />
// <input name="editform" type="hidden" value="admin/resourceDisplayVisibility.jsp"/>
// <input type="submit" class="form-button" value="Set Property Display Visibility"/>
// </form>
// <form action="edit/editRequestDispatch.jsp" method="get">
// <input name="home" type="hidden" value="${portalBean.portalId}" />
// <input name="subjectUri" type="hidden" value="${property.URI}" />
// <input name="urlPattern" type="hidden" value="/propertyEdit" />
// <input name="editform" type="hidden" value="admin/resourceEditVisibility.jsp"/>
// <input type="submit" class="form-button" value="Set Property Editing Visibility"/>
// </form>
/* This form uses the unusual tactic of always configuring itself as if it were doing an update. */
Individual subject = (Individual)request.getAttribute("subject");
VitroRequest vreq = new VitroRequest(request);
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
String urlPatternToReturnTo = (String)request.getAttribute("urlPatternToReturnTo");
if (urlPatternToReturnTo==null || urlPatternToReturnTo.length()==0) {
log.warn("urlPatternToReturnTo is null when starting resourceDisplayVisibility.jsp");
System.out.println("urlPatternToReturnTo is null when starting resourceDisplayVisibility.jsp");
} else {
log.warn("urlPatternToReturnTo is "+urlPatternToReturnTo+" when starting resourceDisplayVisibility.jsp");
System.out.println("urlPatternToReturnTo is "+urlPatternToReturnTo+" when starting resourceDisplayVisibility.jsp");
}
%>
<c:choose>
<c:when test="${!empty urlPatternToReturnTo}"><c:set var="urlPattern" value="${urlPatternToReturnTo}"/></c:when>
<c:otherwise><c:set var="urlPattern" value="/entity" /></c:otherwise>
</c:choose>
<c:set var="roleOptions">
["<%=BaseResourceBean.RoleLevel.PUBLIC.getURI()%>","<%=BaseResourceBean.RoleLevel.PUBLIC.getLabel() %>" ],
["<%=BaseResourceBean.RoleLevel.SELF.getURI()%>","<%=BaseResourceBean.RoleLevel.SELF.getLabel() %>" ],
["<%=BaseResourceBean.RoleLevel.EDITOR.getURI()%>","<%=BaseResourceBean.RoleLevel.EDITOR.getLabel() %>" ],
["<%=BaseResourceBean.RoleLevel.CURATOR.getURI()%>","<%=BaseResourceBean.RoleLevel.CURATOR.getLabel() %>" ],
["<%=BaseResourceBean.RoleLevel.DB_ADMIN.getURI()%>","<%=BaseResourceBean.RoleLevel.DB_ADMIN.getLabel() %>" ],
["<%=BaseResourceBean.RoleLevel.NOBODY.getURI()%>","<%=BaseResourceBean.RoleLevel.NOBODY.getLabel() %>" ]
</c:set>
<v:jsonset var="displayRoleAssertions">
@prefix vitro: <http://vitro.mannlib.connell.edu/ns/vitro/0.7#> .
?subject vitro:hiddenFromDisplayBelowRoleLevelAnnot ?displayRole .
</v:jsonset>
<v:jsonset var="displayRoleExisting">
prefix vitro: <http://vitro.mannlib.connell.edu/ns/vitro/0.7#>
SELECT ?existingDisplayRole
WHERE {
?subject vitro:hiddenFromDisplayBelowRoleLevelAnnot ?displayRole .
}
</v:jsonset>
<c:set var="editjson" scope="request">
{
"formUrl" : "${formUrl}",
"editKey" : "${editKey}",
"urlPatternToReturnTo" : "${urlPattern}",
"subject" : [ "subject", "${subjectUriJson}" ] ,
"predicate" : [ "predicate", "${predicateUriJson}" ],
"object" : [ "objectVar" , "http://example.org/valueJustToMakeItLookLikeAnUpdate" , "URI"],
"n3required" : [ "" ],
"n3optional" : [ "" ],
"newResources" : { },
"urisInScope" : { "displayRole" : "http://vitro.mannlib.cornell.edu/ns/vitro/role#public" },
"literalsInScope" : { },
"urisOnForm" : ["displayRole"],
"literalsOnForm" : [ ],
"filesOnForm" : [ ],
"sparqlForLiterals" : { },
"sparqlForUris" : { },
"sparqlForExistingLiterals" : { },
"sparqlForExistingUris" : { "displayRole" : "${displayRoleExisting}" },
"fields" : { "displayRole" : {
"newResource" : "false",
"validators" : [ ],
"optionsType" : "LITERALS",
"predicateUri" : "${predicateUriJson}",
"objectClassUri" : "",
"rangeDatatypeUri" : "",
"rangeLang" : "",
"literalOptions" : [ ${roleOptions} ],
"assertions" : ["${displayRoleAssertions}"]
}
}
}
</c:set>
<% /* now put edit configuration Json object into session */
EditConfiguration editConfig = new EditConfiguration((String)request.getAttribute("editjson"));
if (editConfig.getUrlPatternToReturnTo()==null) {
System.out.println("urlPatternToReturnTo not initialized in resourceDisplayVisibility.jsp");
log.debug("urlPatternToReturnTo not initialized");
} else {
System.out.println("urlPatternToReturnTo initialized to "+editConfig.getUrlPatternToReturnTo()+" in resourceDisplayVisibility.jsp");
log.debug("urlPatternToReturnTo initialized to "+editConfig.getUrlPatternToReturnTo()+"\n");
}
EditConfiguration.putConfigInSession(editConfig, session);
Model model = (Model)application.getAttribute("jenaOntModel");
editConfig.prepareForObjPropUpdate( model );
%>
<jsp:include page="${preForm}"/>
<h2>Set Display Visibility</h2>
<form action="<c:url value="/edit/processRdfForm2.jsp"/>" >
<v:input type="select" id="displayRole" size="80" />
<v:input type="submit" id="submit" value="submit" cancel="${param.subjectUri}"/>
</form>
<jsp:include page="${postForm}"/>

View file

@ -0,0 +1,179 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.rdf.model.Model" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Individual" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.DataProperty" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration" %>
<%@ taglib prefix="v" uri="http://vitro.mannlib.cornell.edu/vitro/tags" %>
<%@page import="edu.cornell.mannlib.vitro.webapp.web.MiscWebUtils"%>
<%
org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger("edu.cornell.mannlib.vitro.jsp.edit.forms.autoCompleteDatapropForm.jsp");
log.debug("Starting autoCompleteDatapropForm.jsp");
String subjectUri = request.getParameter("subjectUri");
String predicateUri = request.getParameter("predicateUri");
DataPropertyStatement dps = (DataPropertyStatement)request.getAttribute("dataprop");
String datapropKeyStr = request.getParameter("datapropKey");
int dataHash=0;
DataProperty prop = (DataProperty)request.getAttribute("predicate");
if( prop == null ) throw new Error("In autoCompleteDatapropForm.jsp, could not find predicate " + predicateUri);
request.setAttribute("propertyName",prop.getPublicName());
Individual subject = (Individual)request.getAttribute("subject");
if( subject == null ) throw new Error("In autoCompleteDatapropForm.jsp, could not find subject " + subjectUri);
request.setAttribute("subjectName",subject.getName());
String rangeDatatypeUri = prop.getRangeDatatypeURI();
request.setAttribute("rangeDatatypeUriJson", MiscWebUtils.escape(rangeDatatypeUri));
if( dps != null ){
try {
dataHash = Integer.parseInt(datapropKeyStr);
log.debug("dataHash is " + dataHash);
} catch (NumberFormatException ex) {
log.debug("could not parse dataprop hash "+
"but there was a dataproperty; hash: '"+datapropKeyStr+"'");
}
String rangeDatatype = dps.getDatatypeURI();
if( rangeDatatype == null ){
log.debug("no range datatype uri set on data property statement when property's range datatype is "+prop.getRangeDatatypeURI()+" in autoCompleteDatapropForm.jsp");
request.setAttribute("rangeDatatypeUriJson","");
}else{
log.debug("range datatype uri of ["+rangeDatatype+"] on data property statement in autoCompleteDatapropForm.jsp");
request.setAttribute("rangeDatatypeUriJson",rangeDatatype);
}
String rangeLang = dps.getLanguage();
if( rangeLang == null ) {
log.debug("no language attribute on data property statement in autoCompleteDatapropForm.jsp");
request.setAttribute("rangeLangJson","");
}else{
log.debug("language attribute of ["+rangeLang+"] on data property statement in autoCompleteDatapropForm.jsp");
request.setAttribute("rangeLangJson", rangeLang);
}
} else {
log.error("No incoming dataproperty statement attribute in autoCompleteDatapropForm.jsp");
}
%>
<c:set var="dataLiteral" value="<%=prop.getLocalName()%>"/>
<v:jsonset var="n3ForEdit" >
?subject ?predicate ?${dataLiteral}.
</v:jsonset>
<c:set var="editjson" scope="request">
{
"formUrl" : "${formUrl}",
"editKey" : "${editKey}",
"datapropKey" : "<%=datapropKeyStr==null?"":datapropKeyStr%>",
"urlPatternToReturnTo" : "/entity",
"subject" : ["subject", "${subjectUriJson}" ],
"predicate" : ["predicate", "${predicateUriJson}"],
"object" : ["${dataLiteral}","","DATAPROPHASH"],
"n3required" : ["${n3ForEdit}"],
"n3optional" : [ ],
"newResources" : { },
"urisInScope" : { },
"literalsInScope" : { },
"urisOnForm" : [ ],
"literalsOnForm" : ["${dataLiteral}"],
"filesOnForm" : [ ],
"sparqlForLiterals" : { },
"sparqlForUris" : { },
"sparqlForExistingLiterals" : { },
"sparqlForExistingUris" : { },
"optionsForFields" : { },
"fields" : { "${dataLiteral}" : {
"newResource" : "false",
"validators" : ["nonempty"],
"optionsType" : "STRINGS_VIA_DATATYPE_PROPERTY",
"literalOptions" : [],
"predicateUri" : "${predicateUriJson}",
"objectClassUri" : "",
"rangeDatatypeUri" : "${rangeDatatypeUriJson}" ,
"rangeLang" : "${rangeLangJson}",
"assertions" : ["${n3ForEdit}"]
}
}
}
</c:set>
<%
if( log.isDebugEnabled()) log.debug(request.getAttribute("editjson"));
EditConfiguration editConfig = new EditConfiguration((String)request.getAttribute("editjson"));
EditConfiguration.putConfigInSession(editConfig, session);
String formTitle =""; // dont add local page variables to the request
String submitLabel ="";
if( datapropKeyStr != null && datapropKeyStr.trim().length() > 0 ) {
Model model = (Model)application.getAttribute("jenaOntModel");
editConfig.prepareForDataPropUpdate(model,dps);
formTitle = "Change text for: <em>"+prop.getPublicName()+"</em>";
submitLabel = "save change";
} else {
formTitle = "Add new entry for: <em>"+prop.getPublicName()+"</em>";
submitLabel = "save entry";
}
%>
<jsp:include page="${preForm}">
<jsp:param name="useTinyMCE" value="false"/>
<jsp:param name="useAutoComplete" value="true"/>
</jsp:include>
<script type="text/javascript" language="javascript">
$(this).load($(this).parent().children('a').attr('src')+" .editForm");
$(document).ready(function() {
var key = $("input[name='editKey']").attr("value");
$.getJSON("<c:url value="/dataservice"/>", {getN3EditOptionList:"1", field: "${dataLiteral}", editKey: key}, function(json){
$("select#${dataLiteral}").replaceWith("<input type='hidden' id='${dataLiteral}' name='${dataLiteral}' /><input type='text' id='${dataLiteral}-entry' name='${dataLiteral}-entry' />");
$("#${dataLiteral}-entry").autocomplete(json, {
minChars: 1,
width: 320,
matchContains: true,
mustMatch: 0,
autoFill: false,
// formatItem: function(row, i, max) {
// return row[0];
// },
// formatMatch: function(row, i, max) {
// return row[0];
// },
// formatResult: function(row) {
// return row[0];
// }
}).result(function(event, data, formatted) {
$("input#${dataLiteral}-entry").attr("value", data[0]); // dump the string into the text box
$("input#${dataLiteral}").attr("value", data[1]); // dump the uri into the hidden form input
});
}
);
})
</script>
<h2><%=formTitle%></h2>
<form class="editForm" action="<c:url value="/edit/processDatapropRdfForm.jsp"/>" >
<c:if test="${!empty predicate.publicDescription}">
<p class="propEntryHelpText">${predicate.publicDescription}</p>
</c:if>
<v:input type="select" id="${dataLiteral}"/>
<v:input type="submit" id="submit" value="<%=submitLabel%>" cancel="${param.subjectUri}"/>
</form>
<jsp:include page="${postForm}"/>

View file

@ -0,0 +1,193 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.rdf.model.Model" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Individual" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.VClass" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration" %>
<%@ page import="org.apache.commons.logging.Log" %>
<%@ page import="org.apache.commons.logging.LogFactory" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="v" uri="http://vitro.mannlib.cornell.edu/vitro/tags" %>
<%!
public static Log log = LogFactory.getLog("edu.cornell.mannlib.vitro.webapp.jsp.edit.forms.autoCompleteObjPropForm.jsp");
%>
<%
log.warn("Starting autoCompleteObjPropForm.jsp");
Individual subject = (Individual)request.getAttribute("subject");
ObjectProperty prop = (ObjectProperty)request.getAttribute("predicate");
VitroRequest vreq = new VitroRequest(request);
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
if( prop.getRangeVClassURI() == null ) {
log.debug("Property has null for its range class URI");
// If property has no explicit range, we will use e.g. owl:Thing.
// Typically an allValuesFrom restriction will come into play later.
VClass top = wdf.getVClassDao().getTopConcept();
prop.setRangeVClassURI(top.getURI());
log.debug("Using "+prop.getRangeVClassURI());
}
VClass rangeClass = wdf.getVClassDao().getVClassByURI( prop.getRangeVClassURI());
if( rangeClass == null ) log.debug("Cannot find class for range for property. Looking for " + prop.getRangeVClassURI() );
%>
<v:jsonset var="queryForInverse" >
PREFIX owl: <http://www.w3.org/2002/07/owl#>
SELECT ?inverse_property
WHERE {
?inverse_property owl:inverseOf ?predicate
}
</v:jsonset>
<c:set var="objectVar" value="<%=prop.getLocalName()%>"/>
<v:jsonset var="n3ForEdit" >
?subject ?predicate ?${objectVar}.
</v:jsonset>
<v:jsonset var="n3Inverse" >
?${objectVar} ?inverseProp ?subject.
</v:jsonset>
<c:set var="editjson" scope="request">
{
"formUrl" : "${formUrl}",
"editKey" : "${editKey}",
"urlPatternToReturnTo" : "/entity",
"subject" : [ "subject", "${subjectUriJson}" ] ,
"predicate" : [ "predicate", "${predicateUriJson}" ],
"object" : [ "${objectVar}" , "${objectUriJson}" , "URI"],
"n3required" : [ "${n3ForEdit}" ],
"n3optional" : [ "${n3Inverse}" ],
"newResources" : { },
"urisInScope" : { },
"literalsInScope" : { },
"urisOnForm" : ["${objectVar}"],
"literalsOnForm" : [ ],
"filesOnForm" : [ ],
"sparqlForLiterals" : { },
"sparqlForUris" : {"inverseProp" : "${queryForInverse}" },
"sparqlForExistingLiterals" : { },
"sparqlForExistingUris" : { },
"fields" : { "${objectVar}" : {
"newResource" : "false",
"queryForExisting" : { },
"validators" : [ ],
"optionsType" : "INDIVIDUALS_VIA_OBJECT_PROPERTY",
"subjectUri" : "${subjectUriJson}",
"subjectClassUri" : "",
"predicateUri" : "${predicateUriJson}",
"objectClassUri" : "",
"rangeDatatypeUri" : "",
"rangeLang" : "",
"literalOptions" : [ ] ,
"assertions" : ["${n3ForEdit}"]
}
}
}
</c:set>
<% /* now put edit configuration Json object into session */
EditConfiguration editConfig = new EditConfiguration((String)request.getAttribute("editjson"));
EditConfiguration.putConfigInSession(editConfig, session);
String formTitle ="";
String submitLabel ="";
Model model = (Model)application.getAttribute("jenaOntModel");
if( request.getAttribute("object") != null ){//this block is for an edit of an existing object property statement
editConfig.prepareForObjPropUpdate( model );
formTitle = "Change entry for: <em>"+prop.getDomainPublic()+"</em>";
submitLabel = "save change";
} else {
editConfig.prepareForNonUpdate( model );
if ( prop.getOfferCreateNewOption() ) {
log.debug("property set to offer \"create new\" option; custom form: ["+prop.getCustomEntryForm()+"]");
formTitle = "Select an existing "+rangeClass.getName()+" for "+subject.getName();
submitLabel = "select existing";
} else {
formTitle = "Add an entry to: <em>"+prop.getDomainPublic()+"</em>";
submitLabel = "save entry";
}
}
%>
<jsp:include page="${preForm}">
<jsp:param name="useTinyMCE" value="false"/>
<jsp:param name="useAutoComplete" value="true"/>
</jsp:include>
<script type="text/javascript" language="javascript">
$(this).load($(this).parent().children('a').attr('src')+" .editForm");
$(document).ready(function() {
var key = $("input[name='editKey']").attr("value");
$.getJSON("<c:url value="/dataservice"/>", {getN3EditOptionList:"1", field: "${objectVar}", editKey: key}, function(json){
$("select#${objectVar}").replaceWith("<input type='hidden' id='${objectVar}' name='${objectVar}' /><input type='text' id='${objectVar}-entry' name='${objectVar}-entry' />");
$("#${objectVar}-entry").autocomplete(json, {
minChars: 1,
width: 320,
matchContains: true,
mustMatch: 1,
autoFill: true,
// formatItem: function(row, i, max) {
// return row[0];
// },
// formatMatch: function(row, i, max) {
// return row[0];
// },
// formatResult: function(row) {
// return row[0];
// }
}).result(function(event, data, formatted) {
$("input#${objectVar}-entry").attr("value", data[0]); // dump the string into the text box
$("input#${objectVar}").attr("value", data[1]); // dump the uri into the hidden form input
});
}
);
})
</script>
<h2><%=formTitle%></h2>
<form class="editForm" action="<c:url value="/edit/processRdfForm2.jsp"/>" >
<c:if test="${predicate.offerCreateNewOption == true}">
<c:url var="createNewUrl" value="/edit/editRequestDispatch.jsp">
<c:param name="subjectUri" value="${param.subjectUri}"/>
<c:param name="predicateUri" value="${param.predicateUri}"/>
<c:param name="clearEditConfig" value="true"/>
<c:param name="cmd" value="create"/>
</c:url>
</c:if>
<c:if test="${!empty predicate.publicDescription}">
<p>${predicate.publicDescription}</p>
</c:if>
<v:input type="select" id="${objectVar}" size="80" />
<v:input type="submit" id="submit" value="<%=submitLabel%>" cancel="${param.subjectUri}"/>
<c:if test="${predicate.offerCreateNewOption == true}">
<p>If you don't find the appropriate entry on the selection list,
<button type="button" onclick="javascript:document.location.href='${createNewUrl}'">add a new item to this list</button>
</p>
</c:if>
</form>
<c:if test="${!empty param.objectUri}" >
<form class="deleteForm" action="editRequestDispatch.jsp" method="get">
<label for="delete"><h3>Delete this entry?</h3></label>
<input type="hidden" name="subjectUri" value="${param.subjectUri}"/>
<input type="hidden" name="predicateUri" value="${param.predicateUri}"/>
<input type="hidden" name="objectUri" value="${param.objectUri}"/>
<input type="hidden" name="cmd" value="delete"/>
<v:input type="submit" id="delete" value="Delete" cancel="" />
</form>
</c:if>
<jsp:include page="${postForm}"/>

View file

@ -0,0 +1,100 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="edu.cornell.mannlib.vedit.beans.LoginFormBean" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.DataProperty" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement" %>
<%@page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditN3Utils"%>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Individual" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory"%>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.RdfLiteralHash" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.filters.VitroRequestPrep" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.Controllers" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jstl/functions" %>
<%@ taglib prefix="v" uri="http://vitro.mannlib.cornell.edu/vitro/tags" %>
<%
org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger("edu.cornell.mannlib.vitro.jsp.edit.forms.datapropStmtDelete");
if( session == null)
throw new Error("need to have session");
if (!VitroRequestPrep.isSelfEditing(request) && !LoginFormBean.loggedIn(request, LoginFormBean.NON_EDITOR)) {%>
<c:redirect url="<%= Controllers.LOGIN %>" />
<% }
String subjectUri = request.getParameter("subjectUri");
String predicateUri = request.getParameter("predicateUri");
String datapropKeyStr = request.getParameter("datapropKey");
int dataHash = 0;
if (datapropKeyStr!=null && datapropKeyStr.trim().length()>0) {
try {
dataHash = Integer.parseInt(datapropKeyStr);
} catch (NumberFormatException ex) {
throw new JspException("Cannot decode incoming datapropKey String value "+datapropKeyStr+" as an integer hash in datapropStmtDelete.jsp");
}
}
VitroRequest vreq = new VitroRequest(request);
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
String editorUri = EditN3Utils.getEditorUri(request,session,application);
wdf = wdf.getUserAwareDaoFactory(editorUri);
DataProperty prop = wdf.getDataPropertyDao().getDataPropertyByURI(predicateUri);
if( prop == null ) throw new Error("In datapropStmtDelete.jsp, could not find property " + predicateUri);
request.setAttribute("propertyName",prop.getPublicName());
Individual subject = wdf.getIndividualDao().getIndividualByURI(subjectUri);
if( subject == null ) throw new Error("could not find subject " + subjectUri);
request.setAttribute("subjectName",subject.getName());
String dataValue=null;
// DataPropertyStatement dps=EditConfiguration.findDataPropertyStatementViaHashcode(subject,predicateUri,dataHash);
DataPropertyStatement dps= RdfLiteralHash.getDataPropertyStmtByHash(subject,dataHash);
if( log.isDebugEnabled() ){
log.debug("attempting to delete dataPropertyStatement: subjectURI <" + dps.getIndividualURI() +">");
log.debug( "predicateURI <" + dps.getDatapropURI() + ">");
log.debug( "literal \"" + dps.getData() + "\"" );
log.debug( "lang @" + (dps.getLanguage() == null ? "null" : dps.getLanguage()));
log.debug( "datatype ^^" + (dps.getDatatypeURI() == null ? "null" : dps.getDatatypeURI() ));
}
if( dps.getIndividualURI() == null || dps.getIndividualURI().trim().length() == 0){
log.debug("adding missing subjectURI to DataPropertyStatement" );
dps.setIndividualURI( subjectUri );
}
if( dps.getDatapropURI() == null || dps.getDatapropURI().trim().length() == 0){
log.debug("adding missing datapropUri to DataPropertyStatement");
dps.setDatapropURI( predicateUri );
}
if (dps!=null) {
dataValue = dps.getData().trim();
if( request.getParameter("y") != null ) { //do the delete
wdf.getDataPropertyStatementDao().deleteDataPropertyStatement(dps);%>
<%-- grab the predicate URI and trim it down to get the Local Name so we can send the user back to the appropriate property --%>
<c:set var="predicateUri" value="${param.predicateUri}" />
<c:set var="localName" value="${fn:substringAfter(predicateUri, '#')}" />
<c:url var="redirectUrl" value="../entity">
<c:param name="uri" value="${param.subjectUri}"/>
</c:url>
<c:redirect url="${redirectUrl}${'#'}${localName}"/>
<% } else { %>
<jsp:include page="${preForm}"/>
<form action="editDatapropStmtRequestDispatch.jsp" method="get">
<label for="submit"><h2>Are you sure you want to delete the following entry from <em>${propertyName}</em>?</h2></label>
<div class="toBeDeleted dataProp"><%=dataValue%></div>
<input type="hidden" name="subjectUri" value="${param.subjectUri}"/>
<input type="hidden" name="predicateUri" value="${param.predicateUri}"/>
<input type="hidden" name="datapropKey" value="${param.datapropKey}"/>
<input type="hidden" name="y" value="1"/>
<input type="hidden" name="cmd" value="delete"/>
<v:input type="submit" id="submit" value="Delete" cancel="${param.subjectUri}" />
</form>
<jsp:include page="${postForm}"/>
<% }
} else {
throw new Error("In datapropStmtDelete.jsp, no match via hashcode to existing datatype property "+predicateUri+" for subject "+subject.getName()+"\n");
}%>

View file

@ -0,0 +1,255 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.VClass" %>
<%@ page import="com.hp.hpl.jena.rdf.model.Literal" %>
<%@ page import="com.hp.hpl.jena.rdf.model.Model" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Individual" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.ModelChangePreprocessor"%>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.DefaultAddMissingIndividualFormModelPreprocessor"%>
<%@ page import="edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary"%>
<%@ page import="edu.cornell.mannlib.vitro.webapp.dao.jena.WebappDaoFactoryJena"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="v" uri="http://vitro.mannlib.cornell.edu/vitro/tags" %>
<%
Individual subject = (Individual)request.getAttribute("subject");
ObjectProperty prop = (ObjectProperty)request.getAttribute("predicate");
if (prop == null) throw new Error("no object property specified via incoming predicate attribute in defaultAddMissingIndividualForm.jsp");
String propDomainPublic = (prop.getDomainPublic() == null) ? "affiliation" : prop.getDomainPublic();
VitroRequest vreq = new VitroRequest(request);
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
if( prop.getRangeVClassURI() == null ) {
// If property has no explicit range, we will use e.g. owl:Thing.
// Typically an allValuesFrom restriction will come into play later.
VClass top = wdf.getVClassDao().getTopConcept();
prop.setRangeVClassURI(top.getURI());
}
String objectUri = (String)request.getAttribute("objectUri");
String predicateUri = (String)request.getAttribute("predicateUri");
boolean isForwardToCreateNew = request.getAttribute("isForwardToCreateNew") != null &&
(Boolean)request.getAttribute("isForwardToCreateNew") == true;
// If this request is the first forward to this form we need to create a new
// edit key because the request will be coming from a defaultObjPropForm and
// will have an edit key that will be reused by the EditConfiguration that
// is being created below. This also preserves back button functionality to
// the form this request is coming from. If the edit key was not cleared
// the new editConfig below would overwrite the previous form's editConfig
// in the Session.
if( isForwardToCreateNew )
request.setAttribute("editKey", EditConfiguration.newEditKey(session));
//If a objectProperty is both provideSelect and offerCreateNewOption
// then when the user gos to a default ObjectProperty edit for an existing
// object property statement then the user can create a new Individual,
// and replace the object in the existing objectPropertyStatement with
// this new individual.
boolean isReplaceWithNew = request.getAttribute("isReplaceWithNew") != null &&
(Boolean)request.getAttribute("isReplaceWithNew") == true;
// If an objectProperty is selectFromExisitng==false and offerCreateNewOption == true
// the we want to forward to the create new form but edit the existing object
// of the objPropStmt.
boolean isForwardToCreateButEdit = request.getAttribute("isForwardToCreateButEdit") != null
&& (Boolean)request.getAttribute("isForwardToCreateButEdit") == true;
vreq.setAttribute("defaultNamespace",wdf.getDefaultNamespace());
StringBuffer n3AssertedTypesUnescapedBuffer = new StringBuffer();
// TODO: redo to query restrictions directly. getVClassesForProperty returns the subclasses, which we don't want.
//for ( VClass vclass : assertionsWdf.getVClassDao().getVClassesForProperty(subject.getVClassURI(),prop.getURI()) ) {
// if (vclass.getURI()!=null) {
// n3AssertedTypesUnescapedBuffer.append("?newIndividual ").append(" rdf:type <")
// .append(vclass.getURI()).append("> .\n");
// }
//}
vreq.setAttribute("n3AssertedTypesUnescaped",n3AssertedTypesUnescapedBuffer.toString());
// if we don't check it into the portal, we won't be able to see it
vreq.setAttribute("portalUri", vreq.getPortal().getTypeUri());
String flagURI = null;
if (vreq.getAppBean().isFlag1Active()) {
flagURI = VitroVocabulary.vitroURI+"Flag1Value"+vreq.getPortal().getPortalId()+"Thing";
} else {
flagURI = wdf.getVClassDao().getTopConcept().getURI(); // fall back to owl:Thing if not portal filtering
}
vreq.setAttribute("flagURI",flagURI);
VClass rangeClass = null;
String typeOfNew = (String)vreq.getAttribute("typeOfNew");
if(typeOfNew != null )
rangeClass = wdf.getVClassDao().getVClassByURI( typeOfNew );
if( rangeClass == null ){
rangeClass = wdf.getVClassDao().getVClassByURI(prop.getRangeVClassURI());
if( rangeClass == null ) throw new Error ("Cannot find class for range for property. Looking for " + prop.getRangeVClassURI() );
}
//vreq.setAttribute("rangeClassLocalName",rangeClass.getLocalName());
//vreq.setAttribute("rangeClassNamespace",rangeClass.getNamespace());
vreq.setAttribute("rangeClassUri",rangeClass.getURI());
//todo: set additional ranges using allValuesFrom.
//vreq.setAttribute("curatorReviewUri","http://vivo.library.cornell.edu/ns/0.1#CuratorReview");
%>
<v:jsonset var="queryForInverse" >
PREFIX owl: <http://www.w3.org/2002/07/owl#>
SELECT ?inverse_property
WHERE {
?inverse_property owl:inverseOf ?predicate
}
</v:jsonset>
<%-- Enter a SPARQL query for each field, by convention concatenating the field id with "Existing"
to convey that the expression is used to retrieve any existing value for the field in an existing individual.
Each of these must then be referenced in the sparqlForExistingLiterals section of the JSON block below
and in the literalsOnForm --%>
<v:jsonset var="nameExisting" >
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?existingName
WHERE { ?newIndividual rdfs:label ?existingName }
</v:jsonset>
<%-- Pair the "existing" query with the skeleton of what will be asserted for a new statement involving this field.
the actual assertion inserted in the model will be created via string substitution into the ? variables.
NOTE the pattern of punctuation (a period after the prefix URI and after the ?field) --%>
<v:jsonset var="n3ForName" >
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
?newIndividual rdfs:label ?name .
</v:jsonset>
<v:jsonset var="n3ForRelation" >
?subject ?predicate ?newIndividual .
</v:jsonset>
<v:jsonset var="n3ForType" >
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
?newIndividual rdf:type <${rangeClassUri}> .
</v:jsonset>
<v:jsonset var="n3ForFlag" >
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
?newIndividual rdf:type <${flagURI}> .
</v:jsonset>
<%-- using v:jsonset here so everything goes through the same JSON escaping --%>
<v:jsonset var="n3AssertedTypes">
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
${n3AssertedTypesUnescaped}
</v:jsonset>
<v:jsonset var="n3Inverse" >
?newIndividual ?inverseProp ?subject .
</v:jsonset>
<%-- note that it's safer to have multiple distinct optional blocks so that a failure in one
will not prevent correct sections from being inserted --%>
<c:set var="editjson" scope="request">
{
"formUrl" : "${formUrl}",
"editKey" : "${editKey}",
"urlPatternToReturnTo" : "/entity",
"subject" : [ "subject", "${subjectUriJson}" ],
"predicate" : [ "predicate", "${predicateUriJson}" ],
"object" : [ "newIndividual", "${objectUriJson}", "URI" ],
"n3required" : [ "${n3ForName}" , "${n3ForRelation}", "${n3ForType}"],
"n3optional" : [ "${n3Inverse}", "${n3AssertedTypes}", "${n3ForFlag}" ],
"newResources" : {
"newIndividual" : "${defaultNamespace}individual"
},
"urisInScope" : { },
"literalsInScope" : { },
"urisOnForm" : [ ],
"literalsOnForm" : [ "name" ],
"filesOnForm" : [ ],
"sparqlForLiterals" : { },
"sparqlForUris" : { "inverseProp" : "${queryForInverse}" },
"sparqlForExistingLiterals" : {
"name" : "${nameExisting}"
},
"sparqlForExistingUris" : { },
"fields" : {
"name" : {
"newResource" : "false",
"validators" : ["nonempty"],
"optionsType" : "UNDEFINED",
"literalOptions" : [ ],
"predicateUri" : "",
"objectClassUri" : "",
"rangeDatatypeUri" : "",
"rangeLang" : "",
"assertions" : [ "${n3ForName}" ]
}
}
}
</c:set>
<%
EditConfiguration editConfig = null;
if( ! isForwardToCreateNew )
editConfig = EditConfiguration.getConfigFromSession(session,request);
//else
// don't want to get the editConfig because it was for the defaultObjPropForm
if( editConfig == null ){
editConfig = new EditConfiguration((String)request.getAttribute("editjson"));
EditConfiguration.putConfigInSession(editConfig, session);
}
Model model = (Model)application.getAttribute("jenaOntModel");
if( isReplaceWithNew){
// this is very specialized for the defaultAddMissingIndividual.jsp
// to support objPropStmt edits where the user wants to
// create a new Individual. Here we trick the processRdfForm2 into
// creating a new Individual and use the preprocessor to do the
// removal of the old objPropStmt
editConfig.addModelChangePreprocessor(
new DefaultAddMissingIndividualFormModelPreprocessor(
subject.getURI(),predicateUri ,objectUri ) );
editConfig.setObject(null);
editConfig.prepareForNonUpdate(model);
}else if ( isForwardToCreateButEdit) {
editConfig.prepareForObjPropUpdate(model);
}else if(request.getAttribute("object") != null ){
editConfig.prepareForObjPropUpdate(model);
} else{
editConfig.prepareForNonUpdate(model);
}
String submitButtonLabel="";
/* title is used by pre and post form fragments */
if (objectUri != null) {
request.setAttribute("title", "Edit \""+propDomainPublic+"\" entry for " + subject.getName());
submitButtonLabel = "Save changes";
} else {
request.setAttribute("title","Create a new \""+propDomainPublic+"\" entry for " + subject.getName());
submitButtonLabel = "Create new \""+propDomainPublic+"\" entry";
}
%>
<jsp:include page="${preForm}">
<jsp:param name="useTinyMCE" value="false"/>
<jsp:param name="useAutoComplete" value="false"/>
</jsp:include>
<h2>${title}</h2>
<form action="<c:url value="/edit/processRdfForm2.jsp"/>" ><br/>
<v:input type="text" label="name (required)" id="name" size="30"/><br/>
<v:input type="submit" id="submit" value="<%=submitButtonLabel%>" cancel="${param.subjectUri}"/>
</form>
<jsp:include page="${postForm}"/>

View file

@ -0,0 +1,176 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.rdf.model.Model" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Individual" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.DataProperty" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest"%>
<%@ page import="java.util.HashMap"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration" %>
<%@ taglib prefix="v" uri="http://vitro.mannlib.cornell.edu/vitro/tags" %>
<%@page import="edu.cornell.mannlib.vitro.webapp.web.MiscWebUtils"%>
<%! private static HashMap<String,String> defaultsForXSDtypes ;
static {
defaultsForXSDtypes = new HashMap<String,String>();
//defaultsForXSDtypes.put("http://www.w3.org/2001/XMLSchema#dateTime","2001-01-01T12:00:00");
defaultsForXSDtypes.put("http://www.w3.org/2001/XMLSchema#dateTime","#Unparseable datetime defaults to now");
}
%>
<%
org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger("edu.cornell.mannlib.vitro.jsp.edit.forms.defaultDatapropForm.jsp");
log.debug("Starting defaultDatapropForm.jsp");
VitroRequest vreq = new VitroRequest(request);
String subjectUri = vreq.getParameter("subjectUri");
String predicateUri = vreq.getParameter("predicateUri");
DataPropertyStatement dps = (DataPropertyStatement)vreq.getAttribute("dataprop");
String datapropKeyStr = vreq.getParameter("datapropKey");
int dataHash=0;
DataProperty prop = (DataProperty)vreq.getAttribute("predicate");
if( prop == null ) throw new Error("In defaultDatapropForm.jsp, could not find predicate " + predicateUri);
vreq.setAttribute("propertyName",prop.getPublicName());
Individual subject = (Individual)vreq.getAttribute("subject");
if( subject == null ) throw new Error("In defaultDatapropForm.jsp, could not find subject " + subjectUri);
vreq.setAttribute("subjectName",subject.getName());
String rangeDatatypeUri = vreq.getWebappDaoFactory().getDataPropertyDao().getRequiredDatatypeURI(subject, prop);
//String rangeDatatypeUri = prop.getRangeDatatypeURI();
vreq.setAttribute("rangeDatatypeUriJson", MiscWebUtils.escape(rangeDatatypeUri));
if( dps != null ){
try {
dataHash = Integer.parseInt(datapropKeyStr);
log.debug("dataHash is " + dataHash);
} catch (NumberFormatException ex) {
log.debug("could not parse dataprop hash "+
"but there was a dataproperty; hash: '"+datapropKeyStr+"'");
}
String rangeDatatype = dps.getDatatypeURI();
if( rangeDatatype == null ){
log.debug("no range datatype uri set on data property statement when property's range datatype is "+prop.getRangeDatatypeURI()+" in defaultDatapropForm.jsp");
vreq.setAttribute("rangeDatatypeUriJson","");
} else {
log.debug("range datatype uri of ["+rangeDatatype+"] on data property statement in defaultDatapropForm.jsp");
vreq.setAttribute("rangeDatatypeUriJson",rangeDatatype);
}
String rangeLang = dps.getLanguage();
if( rangeLang == null ) {
log.debug("no language attribute on data property statement in defaultDatapropForm.jsp");
vreq.setAttribute("rangeLangJson","");
}else{
log.debug("language attribute of ["+rangeLang+"] on data property statement in defaultDatapropForm.jsp");
vreq.setAttribute("rangeLangJson", rangeLang);
}
} else {
log.debug("No incoming dataproperty statement attribute for property "+prop.getPublicName()+", adding a new statement");
if(rangeDatatypeUri != null && rangeDatatypeUri.length() > 0) {
String defaultVal = defaultsForXSDtypes.get(rangeDatatypeUri);
if( defaultVal == null )
vreq.setAttribute("rangeDefaultJson", "");
else
vreq.setAttribute("rangeDefaultJson", '"' + MiscWebUtils.escape(defaultVal) + '"' );
}
}
%>
<c:set var="localName" value="<%=prop.getLocalName()%>"/>
<c:set var="dataLiteral" value="${localName}Edited"/>
<v:jsonset var="n3ForEdit" >
?subject ?predicate ?${dataLiteral}.
</v:jsonset>
<c:set var="editjson" scope="request">
{
"formUrl" : "${formUrl}",
"editKey" : "${editKey}",
"datapropKey" : "<%=datapropKeyStr==null?"":datapropKeyStr%>",
"urlPatternToReturnTo" : "/entity",
"subject" : ["subject", "${subjectUriJson}" ],
"predicate" : ["predicate", "${predicateUriJson}"],
"object" : ["${dataLiteral}","","DATAPROPHASH"],
"n3required" : ["${n3ForEdit}"],
"n3optional" : [ ],
"newResources" : { },
"urisInScope" : { },
"literalsInScope" : { },
"urisOnForm" : [ ],
"literalsOnForm" : ["${dataLiteral}"],
"filesOnForm" : [ ],
"sparqlForLiterals" : { },
"sparqlForUris" : { },
"sparqlForExistingLiterals" : { },
"sparqlForExistingUris" : { },
"optionsForFields" : { },
"fields" : { "${dataLiteral}" : {
"newResource" : "false",
"validators" : ["datatype:${rangeDatatypeUriJson}"],
"optionsType" : "LITERALS",
"literalOptions" : [ ${rangeDefaultJson} ],
"predicateUri" : "",
"objectClassUri" : "",
"rangeDatatypeUri" : "${rangeDatatypeUriJson}" ,
"rangeLang" : "${rangeLangJson}",
"assertions" : ["${n3ForEdit}"]
}
}
}
</c:set>
<%
if( log.isDebugEnabled()) log.debug(request.getAttribute("editjson"));
EditConfiguration editConfig = new EditConfiguration((String)vreq.getAttribute("editjson"));
EditConfiguration.putConfigInSession(editConfig, session);
String formTitle =""; // don't add local page variables to the request
String submitLabel ="";
if( datapropKeyStr != null && datapropKeyStr.trim().length() > 0 ) {
Model model = (Model)application.getAttribute("jenaOntModel");
editConfig.prepareForDataPropUpdate(model,dps);
formTitle = "Change text for: <em>"+prop.getPublicName()+"</em>";
submitLabel = "save change";
} else {
formTitle ="Add new entry for: <em>"+prop.getPublicName()+"</em>";
submitLabel ="save entry";
}
%>
<%--the following parameters configure the tinymce textarea --%>
<jsp:include page="${preForm}">
<jsp:param name="useTinyMCE" value="true"/>
</jsp:include>
<h2><%=formTitle%></h2>
<form class="editForm" action="<c:url value="/edit/processDatapropRdfForm.jsp"/>" method="post" > <%-- see VITRO-435 Jira issue: need POST, not GET --%>
<c:if test="${!empty predicate.publicDescription}">
<label for="${dataLiteral}"><p class="propEntryHelpText">${predicate.publicDescription}</p></label>
</c:if>
<v:input type="textarea" id="${dataLiteral}" rows="2"/>
<v:input type="submit" id="submit" value="<%=submitLabel%>" cancel="${param.subjectUri}"/>
</form>
<c:if test="${ (!empty param.datapropKey) && (empty param.deleteProhibited) }">
<form class="deleteForm" action="editDatapropStmtRequestDispatch.jsp" method="post">
<label for="delete"><h3>Delete this entry?</h3></label>
<input type="hidden" name="subjectUri" value="${param.subjectUri}"/>
<input type="hidden" name="predicateUri" value="${param.predicateUri}"/>
<input type="hidden" name="datapropKey" value="${param.datapropKey}"/>
<input type="hidden" name="cmd" value="delete"/>
<v:input type="submit" id="delete" value="Delete" cancel="" />
</form>
</c:if>
<jsp:include page="${postForm}"/>

View file

@ -0,0 +1,167 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.rdf.model.Literal" %>
<%@ page import="com.hp.hpl.jena.rdf.model.Model" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Individual" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.VClass" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.DataProperty" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao" %>
<%@ page import="java.util.List" %>
<%@ page import="org.apache.commons.logging.Log" %>
<%@ page import="org.apache.commons.logging.LogFactory" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="v" uri="http://vitro.mannlib.cornell.edu/vitro/tags" %>
<%!
public static Log log = LogFactory.getLog("edu.cornell.mannlib.vitro.webapp.jsp.edit.forms.defaultLinkForm.jsp");
%>
<%-- Enter here any class names to be used for constructing INDIVIDUALS_VIA_VCLASS pick lists
These are then referenced in the field's ObjectClassUri but not elsewhere.
NOTE that this class may not exist in the model, in which the only choice of type
that will show up is "web page", which will insert no new statements and just create
links of type vitro:Link --%>
<%-- Then enter a SPARQL query for each field, by convention concatenating the field id with "Existing"
to convey that the expression is used to retrieve any existing value for the field in an existing individual.
Each of these must then be referenced in the sparqlForExistingLiterals section of the JSON block below
and in the literalsOnForm --%>
<v:jsonset var="urlExisting" >
PREFIX vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#>
SELECT ?urlExisting
WHERE { ?link vitro:linkURL ?urlExisting }
</v:jsonset>
<%-- Pair the "existing" query with the skeleton of what will be asserted for a new statement involving this field.
The actual assertion inserted in the model will be created via string substitution into the ? variables.
NOTE the pattern of punctuation (a period after the prefix URI and after the ?field) --%>
<v:jsonset var="urlAssertion" >
@prefix vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> .
?link vitro:linkURL ?url .
</v:jsonset>
<v:jsonset var="anchorExisting" >
PREFIX vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#>
SELECT ?anchorExisting
WHERE { ?link vitro:linkAnchor ?anchorExisting }
</v:jsonset>
<v:jsonset var="anchorAssertion" >
@prefix vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> .
?link vitro:linkAnchor ?anchor .
</v:jsonset>
<%-- When not retrieving a literal via a datatype property, put the SPARQL statement into
the SparqlForExistingUris --%>
<v:jsonset var="n3ForEdit">
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> .
?subject vitro:additionalLink ?link .
?link rdf:type vitro:Link .
?link
vitro:linkURL ?url ;
vitro:linkAnchor ?anchor .
</v:jsonset>
<v:jsonset var="n3Optional">
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
?link rdf:type ?type .
</v:jsonset>
<c:set var="editjson" scope="request">
{
"formUrl" : "${formUrl}",
"editKey" : "${editKey}",
"urlPatternToReturnTo" : "/entity",
"subject" : ["subject", "${subjectUriJson}" ],
"predicate" : ["predicate", "${predicateUriJson}" ],
"object" : ["link", "${objectUriJson}", "URI" ],
"n3required" : [ "${n3ForEdit}" ],
"n3optional" : [ "${n3Optional}" ],
"newResources" : { "link" : "http://vivo.library.cornell.edu/ns/0.1#individual" },
"urisInScope" : { },
"literalsInScope" : { },
"urisOnForm" : [ ],
"literalsOnForm" : [ "url", "anchor" ],
"filesOnForm" : [ ],
"sparqlForLiterals" : { },
"sparqlForUris" : { },
"sparqlForExistingLiterals" : {
"url" : "${urlExisting}",
"anchor" : "${anchorExisting}"
},
"sparqlForExistingUris" : { },
"fields" : {
"url" : {
"newResource" : "false",
"validators" : [ "nonempty" ],
"optionsType" : "UNDEFINED",
"literalOptions" : [ ],
"predicateUri" : "",
"objectClassUri" : "",
"rangeDatatypeUri" : "",
"rangeLang" : "",
"assertions" : [ "${urlAssertion}" ]
},
"anchor" : {
"newResource" : "false",
"validators" : [ "nonempty" ],
"optionsType" : "UNDEFINED",
"literalOptions" : [ ],
"predicateUri" : "",
"objectClassUri" : "",
"rangeDatatypeUri" : "",
"rangeLang" : "",
"assertions" : [ "${anchorAssertion}" ]
}
}
}
</c:set>
<%
EditConfiguration editConfig = EditConfiguration.getConfigFromSession(session,request);
if( editConfig == null ){
editConfig = new EditConfiguration((String)request.getAttribute("editjson"));
EditConfiguration.putConfigInSession(editConfig, session);
}
Model model = (Model)application.getAttribute("jenaOntModel");
String objectUri = (String)request.getAttribute("objectUri");
if( objectUri != null ){
editConfig.prepareForObjPropUpdate(model);
}else{
editConfig.prepareForNonUpdate(model);
}
/* get some data to make the form more useful */
Individual subject = (Individual)request.getAttribute("subject");
String submitLabel=""; // don't put local variables into the request
/* title is used by pre and post form fragments */
if (objectUri != null) {
request.setAttribute("title", "Edit link for " + subject.getName());
submitLabel = "Save changes";
} else {
request.setAttribute("title","Create a new link for " + subject.getName());
submitLabel = "Create new link";
}
%>
<jsp:include page="${preForm}"/>
<h2>${title}</h2>
<form action="<c:url value="/edit/processRdfForm2.jsp"/>" >
<v:input type="text" label="URL" id="url" size="70"/>
<v:input type="text" label="label" id="anchor" size="60"/>
<v:input type="submit" id="submit" value="<%=submitLabel%>" cancel="${param.subjectUri}"/>
</form>
<jsp:include page="${postForm}"/>

View file

@ -0,0 +1,188 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.rdf.model.Model" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Individual" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.VClass" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration" %>
<%@ page import="org.apache.commons.logging.Log" %>
<%@ page import="java.util.List" %>
<%@ page import="org.apache.commons.logging.LogFactory" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="v" uri="http://vitro.mannlib.cornell.edu/vitro/tags" %>
<%!
public static Log log = LogFactory.getLog("edu.cornell.mannlib.vitro.webapp.jsp.edit.forms.defaultObjPropForm.jsp");
%>
<%
Individual subject = (Individual)request.getAttribute("subject");
ObjectProperty prop = (ObjectProperty)request.getAttribute("predicate");
VitroRequest vreq = new VitroRequest(request);
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
if( prop.getRangeVClassURI() == null ) {
log.debug("Property has null for its range class URI");
// If property has no explicit range, we will use e.g. owl:Thing.
// Typically an allValuesFrom restriction will come into play later.
VClass top = wdf.getVClassDao().getTopConcept();
prop.setRangeVClassURI(top.getURI());
log.debug("Using "+prop.getRangeVClassURI());
}
VClass rangeClass = wdf.getVClassDao().getVClassByURI( prop.getRangeVClassURI());
if( rangeClass == null ) log.debug("Cannot find class for range for property. Looking for " + prop.getRangeVClassURI() );
%>
<%@page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.SelectListGenerator"%>
<%@page import="java.util.Map"%><v:jsonset var="queryForInverse" >
PREFIX owl: <http://www.w3.org/2002/07/owl#>
SELECT ?inverse_property
WHERE {
?inverse_property owl:inverseOf ?predicate
}
</v:jsonset>
<v:jsonset var="n3ForEdit" >
?subject ?predicate ?objectVar.
</v:jsonset>
<v:jsonset var="n3Inverse" >
?objectVar ?inverseProp ?subject.
</v:jsonset>
<c:set var="editjson" scope="request">
{
"formUrl" : "${formUrl}",
"editKey" : "${editKey}",
"urlPatternToReturnTo" : "/entity",
"subject" : [ "subject", "${subjectUriJson}" ] ,
"predicate" : [ "predicate", "${predicateUriJson}" ],
"object" : [ "objectVar" , "${objectUriJson}" , "URI"],
"n3required" : [ "${n3ForEdit}" ],
"n3optional" : [ "${n3Inverse}" ],
"newResources" : { },
"urisInScope" : { },
"literalsInScope" : { },
"urisOnForm" : ["objectVar"],
"literalsOnForm" : [ ],
"filesOnForm" : [ ],
"sparqlForLiterals" : { },
"sparqlForUris" : {"inverseProp" : "${queryForInverse}" },
"sparqlForExistingLiterals" : { },
"sparqlForExistingUris" : { },
"fields" : { "objectVar" : {
"newResource" : "false",
"queryForExisting" : { },
"validators" : [ "nonempty" ],
"optionsType" : "INDIVIDUALS_VIA_OBJECT_PROPERTY",
"subjectUri" : "${subjectUriJson}",
"subjectClassUri" : "",
"predicateUri" : "${predicateUriJson}",
"objectClassUri" : "",
"rangeDatatypeUri" : "",
"rangeLang" : "",
"literalOptions" : [ ] ,
"assertions" : ["${n3ForEdit}", "${n3Inverse}"]
}
}
}
</c:set>
<% /* now put edit configuration Json object into session */
EditConfiguration editConfig = new EditConfiguration((String)request.getAttribute("editjson"));
EditConfiguration.putConfigInSession(editConfig, session);
String formTitle ="";
String submitLabel ="";
Model model = (Model)application.getAttribute("jenaOntModel");
if( request.getAttribute("object") != null ){//this block is for an edit of an existing object property statement
editConfig.prepareForObjPropUpdate( model );
formTitle = "Change entry for: <em>"+prop.getDomainPublic()+"</em>";
submitLabel = "save change";
} else {
editConfig.prepareForNonUpdate( model );
if ( prop.getOfferCreateNewOption() ) {
log.debug("property set to offer \"create new\" option; custom form: ["+prop.getCustomEntryForm()+"]");
formTitle = "Select an existing "+rangeClass.getName()+" for "+subject.getName();
submitLabel = "select existing";
} else {
formTitle = "Add an entry to: <em>"+prop.getDomainPublic()+"</em>";
submitLabel = "save entry";
}
}
if( prop.getSelectFromExisting() ){
Map<String,String> rangeOptions = SelectListGenerator.getOptions(editConfig, "objectVar" , wdf);
if( rangeOptions != null && rangeOptions.size() > 0 )
request.setAttribute("rangeOptionsExist", true);
else
request.setAttribute("rangeOptionsExist",false);
}
%>
<jsp:include page="${preForm}"/>
<h2><%=formTitle%></h2>
<c:if test="${requestScope.predicate.selectFromExisting == true }">
<c:if test="${requestScope.rangeOptionsExist == true }">
<form class="editForm" action="<c:url value="/edit/processRdfForm2.jsp"/>" >
<c:if test="${!empty predicate.publicDescription}">
<p>${predicate.publicDescription}</p>
</c:if>
<v:input type="select" id="objectVar" size="80" />
<div style="margin-top: 1em">
<v:input type="submit" id="submit" value="<%=submitLabel%>" cancel="${param.subjectUri}"/>
</div>
</form>
</c:if>
<c:if test="${requestScope.rangeOptionsExist == false }">
<p>There are no entries in the system to select from.</p>
</c:if>
</c:if>
<c:if test="${requestScope.predicate.offerCreateNewOption == true}">
<c:if test="${requestScope.rangeOptionsExist == true }">
<p>If you don't find the appropriate entry on the selection list:</p>
</c:if>
<c:if test="${requestScope.rangeOptionsExist == false }">
<p style="margin-top: 5em">Please create a new entry.</p>
</c:if>
<c:url var="createNewUrl" value="/edit/editRequestDispatch.jsp"/>
<form class="editForm" action="${createNewUrl}">
<input type="hidden" value="${param.subjectUri}" name="subjectUri"/>
<input type="hidden" value="${param.predicateUri}" name="predicateUri"/>
<input type="hidden" value="${param.objectUri}" name="objectUri"/>
<input type="hidden" value="create" name="cmd"/>
<v:input type="typesForCreateNew" id="typeOfNew" />
<v:input type="submit" id="submit" value="add a new item to this list"/>
</form>
</c:if>
<c:if test="${(requestScope.predicate.offerCreateNewOption == false) && (requestScope.predicate.selectFromExisting == false)}">
<p>This property is currently configured to prohibit editing. </p>
</c:if>
<c:if test="${ (!empty param.objectUri) && (empty param.deleteProhibited) }" >
<form class="deleteForm" action="editRequestDispatch.jsp" method="get">
<label for="delete"><h3>Delete this entry?</h3></label>
<input type="hidden" name="subjectUri" value="${param.subjectUri}"/>
<input type="hidden" name="predicateUri" value="${param.predicateUri}"/>
<input type="hidden" name="objectUri" value="${param.objectUri}"/>
<input type="hidden" name="cmd" value="delete"/>
<c:if test="${(requestScope.predicate.offerCreateNewOption == false) && (requestScope.predicate.selectFromExisting == false)}">
<v:input type="submit" id="delete" value="Delete" cancel="cancel" />
</c:if>
<c:if test="${(requestScope.predicate.offerCreateNewOption == true) || (requestScope.predicate.selectFromExisting == true)}">
<v:input type="submit" id="delete" value="Delete" cancel="" />
</c:if>
</form>
</c:if>
<jsp:include page="${postForm}"/>

View file

@ -0,0 +1,153 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.ServletIdentifierBundleFactory"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.SelfEditingIdentifierFactory.SelfEditing"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.SelfEditingIdentifierFactory"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.RoleIdentifier"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditN3Utils"%><%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="v" uri="http://vitro.mannlib.cornell.edu/vitro/tags" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jstl/functions" %>
<%@ page import="edu.cornell.mannlib.vedit.beans.LoginFormBean" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Individual" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement"%>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty"%>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.VClass" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Link" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.dao.LinksDao" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.filters.VitroRequestPrep" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.Controllers" %>
<%@ page import="java.util.List" %>
<%@ page import="org.apache.commons.logging.Log" %>
<%@ page import="org.apache.commons.logging.LogFactory" %>
<%!
public static Log log = LogFactory.getLog("edu.cornell.mannlib.vitro.webapp.jsp.edit.forms.propDelete.jsp");
public WebappDaoFactory getUnfilteredDaoFactory() {
return (WebappDaoFactory) getServletContext().getAttribute("webappDaoFactory");
}
%>
<%-- grab the predicate URI and trim it down to get the Local Name so we can send the user back to the appropriate property --%>
<c:set var="predicateUri" value="${param.predicateUri}" />
<c:set var="localName" value="${fn:substringAfter(predicateUri, '#')}" />
<c:url var="redirectUrl" value="../entity">
<c:param name="uri" value="${param.subjectUri}"/>
</c:url>
<%
if( session == null) {
throw new Error("need to have session");
}
boolean selfEditing = VitroRequestPrep.isSelfEditing(request);
if (!selfEditing && !LoginFormBean.loggedIn(request, LoginFormBean.NON_EDITOR)) {%>
<c:redirect url="<%= Controllers.LOGIN %>" />
<% }
String subjectUri = request.getParameter("subjectUri");
String predicateUri = request.getParameter("predicateUri");
String objectUri = request.getParameter("objectUri");
VitroRequest vreq = new VitroRequest(request);
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
if( wdf == null ) {
throw new Error("could not get a WebappDaoFactory");
}
ObjectProperty prop = wdf.getObjectPropertyDao().getObjectPropertyByURI(predicateUri);
if( prop == null ) {
throw new Error("In propDelete.jsp, could not find property " + predicateUri);
}
request.setAttribute("propertyName",prop.getDomainPublic());
//do the delete
if( request.getParameter("y") != null ) {
String editorUri = EditN3Utils.getEditorUri(request,session,application);
wdf = wdf.getUserAwareDaoFactory(editorUri);
if (prop.getForceStubObjectDeletion()) {
Individual object = (Individual)request.getAttribute("object");
if (object==null) {
object = getUnfilteredDaoFactory().getIndividualDao().getIndividualByURI(objectUri);
}
if( object != null ) {
log.warn("Deleting individual "+object.getName()+" since property has been set to force range object deletion");
wdf.getIndividualDao().deleteIndividual(object);
} else {
throw new Error("Could not find object as request attribute or in model: '" + objectUri + "'");
}
}
wdf.getPropertyInstanceDao().deleteObjectPropertyStatement(subjectUri,predicateUri,objectUri); %>
<c:redirect url="${redirectUrl}${'#'}${localName}"/>
<% }
Individual subject = wdf.getIndividualDao().getIndividualByURI(subjectUri);
if( subject == null ) throw new Error("could not find subject " + subjectUri);
request.setAttribute("subjectName",subject.getName());
boolean foundClass = false;
String customShortView = null;
String shortViewPrefix = "/templates/entity/";
Individual object = getUnfilteredDaoFactory().getIndividualDao().getIndividualByURI(objectUri);
if( object == null ) {
log.warn("Could not find object individual "+objectUri+" via wdf.getIndividualDao().getIndividualByURI(objectUri)");
request.setAttribute("objectName","(name unspecified)");
} else {
for (VClass clas : object.getVClasses(true)) { // direct VClasses, not inferred, and not including Vitro namespace
request.setAttribute("rangeClassName", clas.getName());
foundClass = true;
customShortView = clas.getCustomShortView();
if (customShortView != null && customShortView.trim().length()>0) {
log.debug("setting object name from VClass custom short view");
request.setAttribute("customShortView",shortViewPrefix + customShortView.trim());
request.setAttribute("individual",object);
} else {
log.debug("No custom short view for class, so setting object name from object individual name");
request.setAttribute("objectName",object.getName());
}
}
if (!foundClass) {
VClass clas = prop.getRangeVClass();
if (clas != null) {
customShortView = clas.getCustomShortView();
if (customShortView != null && customShortView.trim().length()>0) {
log.warn("setting object name from VClass custom short view \""+customShortView.trim()+"\"");
request.setAttribute("customShortView",shortViewPrefix + customShortView.trim());
request.setAttribute("individual",object);
} else {
log.error("No custom short view jsp set for VClass "+clas.getName()+" so cannot render link name correctly");
request.setAttribute("objectName",object.getName());
}
}
}
}%>
<jsp:include page="${preForm}"/>
<form action="editRequestDispatch.jsp" method="get">
<label for="submit"><h2>Are you sure you want to delete the following entry from <em>${propertyName}</em>?</h2></label>
<div class="toBeDeleted objProp">
<c:choose>
<c:when test="${!empty customShortView}">
<c:set scope="request" var="individual" value="${individual}"/>
<jsp:include page="${customShortView}" flush="true"/>
<c:remove var="customShortView"/>
</c:when>
<c:otherwise>${objectName}</c:otherwise>
</c:choose>
</div>
<input type="hidden" name="subjectUri" value="${param.subjectUri}"/>
<input type="hidden" name="predicateUri" value="${param.predicateUri}"/>
<input type="hidden" name="objectUri" value="${param.objectUri}"/>
<input type="hidden" name="y" value="1"/>
<input type="hidden" name="cmd" value="delete"/>
<v:input type="submit" id="submit" value="Delete" cancel="${param.subjectUri}" />
</form>
<jsp:include page="${postForm}"/>

View file

@ -0,0 +1,104 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.rdf.model.Model" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Individual" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.VClass" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="v" uri="http://vitro.mannlib.cornell.edu/vitro/tags" %>
<%
/* Prompts the user for a file to upload and adds a statement between a newly created
file resource and the Subject using the incoming predicate. Also try to make
an inverse statement. */
Individual subject = (Individual)request.getAttribute("subject");
ObjectProperty prop = (ObjectProperty)request.getAttribute("predicate");
VitroRequest vreq = new VitroRequest(request);
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
%>
<v:jsonset var="queryForInverse" >
PREFIX owl: <http://www.w3.org/2002/07/owl#>
SELECT ?inverse_property
WHERE {
?inverse_property owl:inverseOf ?predicate
}
</v:jsonset>
<v:jsonset var="n3ForEdit" >
?subject ?predicate ?fileResource .
</v:jsonset>
<v:jsonset var="n3Inverse" >
?fileResource ?inverseProp ?subject.
</v:jsonset>
<c:set var="editjson" scope="request">
{
"formUrl" : "${formUrl}",
"editKey" : "${editKey}",
"urlPatternToReturnTo" : "/entity",
"subject" : [ "subject", "${subjectUriJson}" ] ,
"predicate" : [ "predicate", "${predicateUriJson}" ],
"object" : [ "fileResource" , "${objectUriJson}" , "URI"],
"n3required" : [ "${n3ForEdit}" ],
"n3optional" : [ "${n3Inverse}" ],
"newResources" : { },
"urisInScope" : { },
"literalsInScope" : { },
"urisOnForm" : [ ],
"literalsOnForm" : [ ],
"filesOnForm" : [ "fileResource" ],
"sparqlForLiterals" : { },
"sparqlForUris" : {"inverseProp" : "${queryForInverse}" },
"sparqlForExistingLiterals" : { },
"sparqlForExistingUris" : { },
"fields" : { "fileResource" : {
"newResource" : "false",
"queryForExisting" : { },
"validators" : [ "nonempty" ],
"optionsType" : "FILE_UPLOAD",
"subjectUri" : "",
"subjectClassUri" : "",
"predicateUri" : "",
"objectClassUri" : "${fileResourceClass}",
"rangeDatatypeUri" : "",
"rangeLang" : "",
"literalOptions" : [ ] ,
"assertions" : ["${n3ForEdit}"]
}
}
}
</c:set>
<% /* now put edit configuration Json object into session */
EditConfiguration editConfig = new EditConfiguration((String)request.getAttribute("editjson"));
EditConfiguration.putConfigInSession(editConfig, session);
Model model = (Model)application.getAttribute("jenaOntModel");
if( request.getAttribute("object") != null ){//this block is for an edit of an existing object property statement
editConfig.prepareForObjPropUpdate( model );
} else {
editConfig.prepareForNonUpdate( model );
}
%>
<jsp:include page="${preForm}"/>
<h2>Upload a File</h2>
<form action="<c:url value="/edit/processRdfForm2.jsp"/>" ENCTYPE="multipart/form-data" method="POST">
File <v:input type="file" id="fileResource" />
<v:input type="submit" id="submit" value="submit" cancel="${param.subjectUri}"/>
</form>
<jsp:include page="${postForm}"/>

12
webapp/web/edit/login.jsp Normal file
View file

@ -0,0 +1,12 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<div align="center">The experimental in-line editing is disabled for this system.</div>
<c:url value="/" var="siteRoot"/>
<div align="center">
<button type="button"
onclick="javascript:document.location.href='${siteRoot}'">
Return to main site</button>

View file

@ -0,0 +1,42 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Individual" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%@ page errorPage="/error.jsp"%>
<c:set var="errorMsg">
The text you are trying to edit cannot be found.
</c:set>
<jsp:include page="/edit/formPrefix.jsp"/>
<div id="content" class="full">
<div align="center">${errorMsg}</div>
<%
VitroRequest vreq = new VitroRequest(request);
if( vreq.getParameter("subjectUri") != null ){
Individual individual = vreq.getWebappDaoFactory().getIndividualDao().getIndividualByURI(vreq.getParameter("subjectUri"));
String name = "the individual you were trying to edit.";
if( individual != null && individual.getName() != null ){
name = individual.getName() + ".";
} %>
<c:url value="/entity" var="entityPage">
<c:param name="uri"><%=vreq.getParameter("subjectUri")%></c:param>
</c:url>
<div align="center">
<button type="button"
onclick="javascript:document.location.href='${entityPage}'">
Return to <%=name%></button>
</div>
<%}else{ %>
<c:url value="/" var="siteRoot"/>
<div align="center">
<button type="button"
onclick="javascript:document.location.href='${siteRoot}'">
Return to main site</button>
</div>
<%} %>
<jsp:include page="/edit/formSuffix.jsp"/>

View file

@ -0,0 +1,265 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.rdf.model.*" %>
<%@ page import="com.hp.hpl.jena.ontology.OntModel" %>
<%@ page import="com.hp.hpl.jena.shared.Lock" %>
<%@ page import="com.thoughtworks.xstream.XStream" %>
<%@ page import="com.thoughtworks.xstream.io.xml.DomDriver" %>
<%@ page import="edu.cornell.mannlib.vedit.beans.LoginFormBean" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Individual" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.EditLiteral" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditN3Generator" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditSubmission" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.Field" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.filters.VitroRequestPrep" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.Controllers" %>
<%@ page import="org.apache.commons.logging.Log" %>
<%@ page import="org.apache.commons.logging.LogFactory" %>
<%@ page import="java.io.StringReader" %>
<%@ page import="java.util.*" %>
<%@page import="edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatementImpl"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.RdfLiteralHash"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.beans.DataProperty"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%--
Current stop gap solution for back button problems
the data property statement to replace cannot be found:
Just add the new data property statement, do not remove any statements
and set a flag in the request to indicate "back button confusion"
--%>
<%!
public static Log log = LogFactory.getLog("edu.cornell.mannlib.vitro.webapp.jsp.edit.datapropertyBackButtonProblems.jsp");
%>
<%
log.debug("Starting datapropertyBackButtonProblems.jsp");
if( session == null)
throw new Error("need to have session");
%>
<%
if (!VitroRequestPrep.isSelfEditing(request) && !LoginFormBean.loggedIn(request, LoginFormBean.CURATOR)) {
%><c:redirect url="<%= Controllers.LOGIN %>" /><%
}
List<String> errorMessages = new ArrayList<String>();
Object sessionOntModel = request.getSession().getAttribute("jenaOntModel");
OntModel jenaOntModel = (sessionOntModel != null && sessionOntModel instanceof OntModel) ? (OntModel)sessionOntModel:
(OntModel)application.getAttribute("jenaOntModel");
VitroRequest vreq = new VitroRequest(request);
EditConfiguration editConfig = EditConfiguration.getConfigFromSession(session,vreq);
EditSubmission submission = new EditSubmission(vreq, vreq.getParameterMap(), editConfig);
EditN3Generator n3Subber = editConfig.getN3Generator();
List<String> n3Required = editConfig.getN3Required();
Map<String,List<String>> fieldAssertions = null;
String subjectUri=null, predicateUri=null;
Individual subject=null;
if( editConfig.getDatapropKey() != null && editConfig.getDatapropKey().length() > 0){
// we are editing an existing data property statement
subjectUri = editConfig.getSubjectUri();
if (subjectUri == null || subjectUri.trim().length()==0) {
log.error("No subjectUri parameter available via editConfig for datapropKey "+editConfig.getDatapropKey());
throw new Error("No subjectUri parameter available via editConfig in processDatapropRdfForm.jsp");
}
predicateUri = editConfig.getPredicateUri();
if (predicateUri == null || predicateUri.trim().length()==0) {
log.error("No predicateUri parameter available via editConfig for datapropKey "+editConfig.getDatapropKey());
throw new Error("No predicateUri parameter available via editConfig in processDatapropRdfForm.jsp");
}
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
// need to get subject because have to iterate through all its data property statements to match datapropKey hashcode
subject = wdf.getIndividualDao().getIndividualByURI(subjectUri);
if( subject == null ) {
log.error("Could not find subject Individual via editConfig's subjectUri while proceessing update to datapropKey "+editConfig.getDatapropKey());
throw new Error("In processDatapropRdfForm.jsp, could not find subject Individual via uri " + subjectUri);
}
fieldAssertions = fieldsToMap(editConfig.getFields());
}
/* ********** URIs and Literals on Form/Parameters *********** */
//sub in resource uris off form
n3Required = n3Subber.subInUris(submission.getUrisFromForm(), n3Required);
//sub in literals from form
n3Required = n3Subber.subInLiterals(submission.getLiteralsFromForm(), n3Required);
fieldAssertions = n3Subber.substituteIntoValues(submission.getUrisFromForm(), submission.getLiteralsFromForm(), fieldAssertions );
/* ****************** URIs and Literals in Scope ************** */
n3Required = n3Subber.subInUris( editConfig.getUrisInScope(), n3Required);
n3Required = n3Subber.subInLiterals( editConfig.getLiteralsInScope(), n3Required);
fieldAssertions = n3Subber.substituteIntoValues(editConfig.getUrisInScope(),editConfig.getLiteralsInScope(), fieldAssertions );
/* ****************** New Resources ********************** */
Map<String,String> varToNewResource = newToUriMap(editConfig.getNewResources(),jenaOntModel);
//if we are editing an existing prop, no new resources will be substituted since the var will
//have already been substituted in by urisInScope.
n3Required = n3Subber.subInUris( varToNewResource, n3Required);
fieldAssertions = n3Subber.substituteIntoValues(varToNewResource, null, fieldAssertions );
/* ***************** Build Models ******************* */
/* bdc34: we should check if this is an edit of an existing
or a new individual. If this is a edit of an existing then
we don't need to do the n3required or the n3optional; only the
the assertions and retractions from the fields are needed.
*/
List<Model> requiredAssertions = null;
List<Model> requiredRetractions = null;
if( editConfig.getDatapropKey() != null && editConfig.getDatapropKey().trim().length() > 0 ){
//editing an existing statement
List<Model> requiredFieldAssertions = new ArrayList<Model>();
List<Model> requiredFieldRetractions = new ArrayList<Model>();
for(String fieldName: fieldAssertions.keySet()){
Field field = editConfig.getFields().get(fieldName);
/* CHECK that field changed, then add assertions and retractions */
if( hasFieldChanged(fieldName, editConfig, submission) ){
log.debug("Field "+fieldName+" has changed for datapropKey "+editConfig.getDatapropKey());
List<String> assertions = fieldAssertions.get(fieldName);
for( String n3 : assertions){
try{
log.debug("Adding assertion '"+n3+"' to requiredFieldAssertions");
Model model = ModelFactory.createDefaultModel();
StringReader reader = new StringReader(n3);
model.read(reader, "", "N3");
requiredFieldAssertions.add(model);
}catch(Throwable t){
log.warn("processing N3 assertions string from field "+fieldName+"\n"+t.getMessage()+'\n'+"n3: \n"+n3);
errorMessages.add("error processing N3 assertion string from field " + fieldName + "\n"+
t.getMessage() + '\n' +
"n3: \n" + n3 );
}
}
if (field.getRetractions()!=null) {
for( String n3 : field.getRetractions()){
try{
log.debug("Adding retraction '"+n3+"' to requiredFieldRetractions");
Model model = ModelFactory.createDefaultModel();
StringReader reader = new StringReader(n3);
model.read(reader, "", "N3");
requiredFieldRetractions.add(model);
}catch(Throwable t){
log.warn("processing N3 retraction string from field "+fieldName+"\n"+t.getMessage()+'\n'+"n3: \n"+n3);
errorMessages.add("error in processDatapropRdfForm.jsp processing N3 retraction string from field "+fieldName+"\n"+t.getMessage()+'\n'+"n3: \n"+n3);
}
}
}
}
}
requiredAssertions = requiredFieldAssertions;
requiredRetractions = requiredFieldRetractions;
}
Lock lock = null;
try{
lock = jenaOntModel.getLock();
lock.enterCriticalSection(Lock.WRITE);
for( Model model : requiredAssertions) {
jenaOntModel.add(model);
}
for(Model model : requiredRetractions ){
jenaOntModel.remove( model );
}
}catch(Throwable t){
errorMessages.add("In processDatapropRdfForm.jsp, error adding edit change n3required model to in memory model \n"+ t.getMessage() );
}finally{
lock.leaveCriticalSection();
}
%>
<jsp:forward page="postEditCleanUp.jsp"/>
<%!
/* ********************************************************* */
/* ******************** utility functions ****************** */
/* ********************************************************* */
public Map<String,List<String>> fieldsToMap( Map<String,Field> fields){
Map<String,List<String>> out = new HashMap<String,List<String>>();
for( String fieldName : fields.keySet()){
Field field = fields.get(fieldName);
List<String> copyOfN3 = new ArrayList<String>();
for( String str : field.getAssertions()){
copyOfN3.add(str);
}
out.put( fieldName, copyOfN3 );
}
return out;
}
public Map<String,String> newToUriMap(Map<String,String> newResources, Model model){
HashMap<String,String> newUris = new HashMap<String,String>();
for( String key : newResources.keySet()){
newUris.put(key,makeNewUri(newResources.get(key), model));
}
return newUris;
}
public String makeNewUri(String prefix, Model model){
if( prefix == null || prefix.length() == 0 )
prefix = defaultUriPrefix;
String uri = prefix + random.nextInt();
Resource r = ResourceFactory.createResource(uri);
while( model.containsResource(r) ){
uri = prefix + random.nextInt();
r = ResourceFactory.createResource(uri);
}
return uri;
}
static Random random = new Random();
static String defaultUriPrefix = "http://vivo.library.cornell.edu/ns/0.1#individual";
%>
<%!
private boolean hasFieldChanged(String fieldName, EditConfiguration editConfig, EditSubmission submission) {
String orgValue = editConfig.getUrisInScope().get(fieldName);
String newValue = submission.getUrisFromForm().get(fieldName);
if( orgValue != null && newValue != null){
if( orgValue.equals(newValue))
return false;
else
return true;
}
Literal orgLit = editConfig.getLiteralsInScope().get(fieldName);
Literal newLit = submission.getLiteralsFromForm().get(fieldName);
boolean fieldChanged = !EditLiteral.equalLiterals( orgLit, newLit);
log.debug( "field " + fieldName + " " + (fieldChanged ? "did Change" : "did NOT change") );
return fieldChanged;
}
private void dump(String name, Object fff){
XStream xstream = new XStream(new DomDriver());
Log log = LogFactory.getLog("edu.cornell.mannlib.vitro.webapp.jsp.edit.forms.processDatapropRdfForm.jsp");
log.debug( "*******************************************************************" );
log.debug( name );
log.debug(xstream.toXML( fff ));
}
%>

View file

@ -0,0 +1,42 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Individual" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%@ page errorPage="/error.jsp"%>
<c:set var="errorMsg">
We are not sure what you would like to edit.
</c:set>
<jsp:include page="/edit/formPrefix.jsp"/>
<div id="content" class="full">
<div align="center">${errorMsg}</div>
<%
VitroRequest vreq = new VitroRequest(request);
if( vreq.getParameter("subjectUri") != null ){
Individual individual = vreq.getWebappDaoFactory().getIndividualDao().getIndividualByURI(vreq.getParameter("subjectUri"));
String name = "the individual you were trying to edit.";
if( individual != null && individual.getName() != null ){ %>
name = individual.getName() + ".";
<% } %>
<c:url value="/entity" var="entityPage">
<c:param name="uri"><%=vreq.getParameter("subjectUri")%></c:param>
</c:url>
<div align="center">
<button type="button"
onclick="javascript:document.location.href='${entityPage}'">
Return to <%=name%></button>
</div>
<%}else{ %>
<c:url value="/" var="siteRoot"/>
<div align="center">
<button type="button"
onclick="javascript:document.location.href='${siteRoot}'">
Return to main site</button>
</div>
<%} %>
<jsp:include page="/edit/formSuffix.jsp"/>

View file

@ -0,0 +1,472 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.ontology.OntModel" %>
<%@ page import="com.hp.hpl.jena.rdf.model.Model" %>
<%@ page import="com.hp.hpl.jena.rdf.model.ModelFactory" %>
<%@ page import="com.hp.hpl.jena.rdf.model.Resource" %>
<%@ page import="com.hp.hpl.jena.rdf.model.Literal" %>
<%@ page import="com.hp.hpl.jena.rdf.model.ResourceFactory" %>
<%@ page import="com.hp.hpl.jena.shared.Lock" %>
<%@ page import="com.thoughtworks.xstream.XStream" %>
<%@ page import="com.thoughtworks.xstream.io.xml.DomDriver" %>
<%@ page import="edu.cornell.mannlib.vedit.beans.LoginFormBean" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditN3Generator" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditSubmission" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.Field" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.Controllers" %>
<%@ page import="java.io.StringReader" %>
<%@ page import="java.util.*" %>
<%@page import="org.apache.commons.logging.LogFactory"%>
<%@page import="org.apache.commons.logging.Log"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="java.io.InputStream"%>
<%@page import="org.apache.commons.fileupload.FileItemIterator"%>
<%@page import="org.apache.commons.fileupload.FileItemStream"%>
<%@page import="org.apache.commons.fileupload.util.Streams"%>
<%@page import="com.hp.hpl.jena.rdf.model.Property"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary"%>
<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="org.apache.commons.fileupload.FileItemFactory"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.dao.jena.event.EditEvent"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.ServletIdentifierBundleFactory"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.SelfEditingIdentifierFactory"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.RoleIdentifier"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditN3Utils"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.filters.VitroRequestPrep"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.dao.jena.DependentResourceDeleteJena"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%-- 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.
--%>
<%
if( session == null)
throw new Error("need to have session");
boolean selfEditing = VitroRequestPrep.isSelfEditing(request);
if (!selfEditing && !LoginFormBean.loggedIn(request, LoginFormBean.NON_EDITOR)) {
%><c:redirect url="<%= Controllers.LOGIN %>" /><%
}
/* the post parameters seem to get consumed by the parsing so
* we have to make a copy. */
Map <String,List<String>> queryParameters = null;
queryParameters = request.getParameterMap();
List<String> errorMessages = new ArrayList<String>();
EditConfiguration editConfig = EditConfiguration.getConfigFromSession(session,request,queryParameters);
if( editConfig == null ){
%><jsp:forward page="/edit/messages/noEditConfigFound.jsp"/><%
}
EditN3Generator n3Subber = editConfig.getN3Generator();
EditSubmission submission = new EditSubmission(queryParameters, editConfig);
Map<String,String> errors = submission.getValidationErrors();
EditSubmission.putEditSubmissionInSession(session,submission);
if( errors != null && ! errors.isEmpty() ){
String form = editConfig.getFormUrl();
request.setAttribute("formUrl", form);
%><jsp:forward page="${formUrl}"/><%
return;
}
List<Model> requiredAssertionsToDelete = new ArrayList<Model>();
List<Model> optionalAssertionsToDelete = new ArrayList<Model>();
boolean requestIsAnValidDelete = editConfig.getObject() != null && editConfig.getObject().trim().length() > 0;
if( requestIsAnValidDelete ){
if( log.isDebugEnabled()) log.debug("deleting using n3Delete.jsp; resource: " + editConfig.getObject() );
List<String> n3Required = editConfig.getN3Required();
List<String> n3Optional = editConfig.getN3Optional();
/* ****************** URIs and Literals in Scope ************** */
n3Required = subInUris( editConfig.getUrisInScope(), n3Required);
n3Optional = subInUris( editConfig.getUrisInScope(), n3Optional);
if(log.isDebugEnabled()) logRequuiredOpt("subsititued in URIs from scope ",n3Required,n3Optional);
n3Required = n3Subber.subInLiterals( editConfig.getLiteralsInScope(), n3Required);
n3Optional = n3Subber.subInLiterals( editConfig.getLiteralsInScope(), n3Optional);
if(log.isDebugEnabled()) logRequuiredOpt("subsititued in Literals from scope ",n3Required,n3Optional);
//no new resources
//deal with required N3
List<Model> requiredNewModels = new ArrayList<Model>();
for(String n3 : n3Required){
try{
Model model = ModelFactory.createDefaultModel();
StringReader reader = new StringReader(n3);
model.read(reader, "", "N3");
requiredNewModels.add( model );
}catch(Throwable t){
errorMessages.add("error processing required n3 string \n"+
t.getMessage() + '\n' +
"n3: \n" + n3 );
}
}
if( !errorMessages.isEmpty() ){
String error = "problems processing required n3: \n";
for( String errorMsg : errorMessages){
error += errorMsg + '\n';
}
throw new JspException("errors processing required N3,\n" + error );
}
requiredAssertionsToDelete.addAll(requiredNewModels);
//deal with optional N3
List<Model> optionalNewModels = new ArrayList<Model>();
for(String n3 : n3Optional){
try{
Model model = ModelFactory.createDefaultModel();
StringReader reader = new StringReader(n3);
model.read(reader, "", "N3");
optionalNewModels.add(model);
}catch(Throwable t){
errorMessages.add("error processing optional n3 string \n"+
t.getMessage() + '\n' +
"n3: \n" + n3);
}
}
optionalAssertionsToDelete.addAll(optionalNewModels);
//////////////// from update of processRdfForm2.jsp /////////////
Map<String,List<String>> fieldAssertions = null;
if( editConfig.getObject() != null && editConfig.getObject().length() > 0){
fieldAssertions = fieldsToAssertionMap(editConfig.getFields());
}else{
fieldAssertions = new HashMap<String,List<String>>();
}
Map<String,List<String>> fieldRetractions = null;
if( editConfig.getObject() != null && editConfig.getObject().length() > 0){
fieldRetractions = fieldsToRetractionMap(editConfig.getFields());
}else{
fieldRetractions = new HashMap<String,List<String>>();
}
/* ********** URIs and Literals on Form/Parameters *********** */
fieldAssertions = n3Subber.substituteIntoValues( submission.getUrisFromForm(), submission.getLiteralsFromForm(), fieldAssertions);
if(log.isDebugEnabled()) logAddRetract("subsititued in literals from form",fieldAssertions,fieldRetractions);
//fieldRetractions does NOT get values from form.
/* ****************** URIs and Literals in Scope ************** */
fieldAssertions = n3Subber.substituteIntoValues(editConfig.getUrisInScope(), editConfig.getLiteralsInScope(), fieldAssertions );
fieldRetractions = n3Subber.substituteIntoValues(editConfig.getUrisInScope(), editConfig.getLiteralsInScope(), fieldRetractions);
if(log.isDebugEnabled()) logAddRetract("subsititued in URIs and Literals from scope",fieldAssertions,fieldRetractions);
//editing an existing statement
List<Model> requiredFieldAssertions = new ArrayList<Model>();
List<Model> requiredFieldRetractions = new ArrayList<Model>();
for(String fieldName: fieldAssertions.keySet()){
Field field = editConfig.getFields().get(fieldName);
/* For the delete don't check that field changed, just build assertions */
log.debug("making delete graph for field " + fieldName );
/* if the field was a checkbox then we need to something special, don't know what that is yet */
List<String> assertions = fieldAssertions.get(fieldName);
for( String n3 : assertions){
try{
Model model = ModelFactory.createDefaultModel();
StringReader reader = new StringReader(n3);
model.read(reader, "", "N3");
requiredFieldAssertions.add(model);
}catch(Throwable t){
errorMessages.add("error processing N3 assertion string from field " + fieldName + "\n"+
t.getMessage() + '\n' +
"n3: \n" + n3 );
}
}
}
requiredAssertionsToDelete.addAll( requiredFieldAssertions );
} else {
throw new Error("No object specified, cannot do delete");
}
//The requiredNewModels and the optionalNewModels could be handled differently
//but for now we'll just do them the same
requiredAssertionsToDelete.addAll(optionalAssertionsToDelete);
Model allPossibleToDelete = ModelFactory.createDefaultModel();
for( Model model : requiredAssertionsToDelete ) {
allPossibleToDelete.add( model );
}
OntModel queryModel = editConfig.getQueryModelSelector().getModel(request,application);
if( editConfig.isUseDependentResourceDelete() ){
Model depResRetractions =
DependentResourceDeleteJena
.getDependentResourceDeleteForChange(null,allPossibleToDelete,queryModel);
allPossibleToDelete.add( depResRetractions );
}
OntModel writeModel = editConfig.getWriteModelSelector().getModel(request,application);
String editorUri = EditN3Utils.getEditorUri(request,session,application);
Lock lock = null;
try{
lock = writeModel.getLock();
lock.enterCriticalSection(Lock.WRITE);
writeModel.getBaseModel().notifyEvent(new EditEvent(editorUri,true));
writeModel.remove(allPossibleToDelete);
}catch(Throwable t){
errorMessages.add("error adding edit change n3required model to in memory model \n"+ t.getMessage() );
}finally{
writeModel.getBaseModel().notifyEvent(new EditEvent(editorUri,false));
lock.leaveCriticalSection();
}
%>
<jsp:forward page="postEditCleanUp.jsp"/>
<%!
/* ********************************************************* */
/* ******************** utility functions ****************** */
/* ********************************************************* */
public Map<String,List<String>> fieldsToAssertionMap( Map<String,Field> fields){
Map<String,List<String>> out = new HashMap<String,List<String>>();
for( String fieldName : fields.keySet()){
Field field = fields.get(fieldName);
List<String> copyOfN3 = new ArrayList<String>();
for( String str : field.getAssertions()){
copyOfN3.add(str);
}
out.put( fieldName, copyOfN3 );
}
return out;
}
public Map<String,List<String>> fieldsToRetractionMap( Map<String,Field> fields){
Map<String,List<String>> out = new HashMap<String,List<String>>();
for( String fieldName : fields.keySet()){
Field field = fields.get(fieldName);
List<String> copyOfN3 = new ArrayList<String>();
for( String str : field.getRetractions()){
copyOfN3.add(str);
}
out.put( fieldName, copyOfN3 );
}
return out;
}
//******************************************
//Use N3Subber instead of these utility methods
public Map<String,List<String>> substituteIntoValues(Map<String,String> varsToUris,
Map<String,String> varsToLiterals,
Map<String,List<String>> namesToN3 ){
Map<String,List<String>> outHash = new HashMap<String,List<String>>();
for(String fieldName : namesToN3.keySet()){
List<String> n3strings = namesToN3.get(fieldName);
List<String> newList = new ArrayList<String>();
if( varsToUris != null)
newList = subInUris(varsToUris, n3strings);
if( varsToLiterals != null)
newList = subInLiterals(varsToLiterals, newList);
outHash.put(fieldName, newList);
}
return outHash;
}
public List<String> subInUris(Map<String,String> varsToVals, List<String> targets){
if( varsToVals == null || varsToVals.isEmpty() ) return targets;
ArrayList<String> outv = new ArrayList<String>();
for( String target : targets){
String temp = target;
for( String key : varsToVals.keySet()) {
temp = subInUris( key, varsToVals.get(key), temp) ;
}
outv.add(temp);
}
return outv;
}
public String subInUris(String var, String value, String target){
if( var == null || var.length() == 0 || value==null )
return target;
String varRegex = "\\?" + var;
String out = target.replaceAll(varRegex,"<"+value+">");
if( out != null && out.length() > 0 )
return out;
else
return target;
}
public List<String>subInUris(String var, String value, List<String> targets){
ArrayList<String> outv =new ArrayList<String>();
for( String target : targets){
outv.add( subInUris( var,value, target) ) ;
}
return outv;
}
public List<String> subInLiterals(Map<String,String> varsToVals, List<String> targets){
if( varsToVals == null || varsToVals.isEmpty()) return targets;
ArrayList<String> outv =new ArrayList<String>();
for( String target : targets){
String temp = target;
for( String key : varsToVals.keySet()) {
temp = subInLiterals( key, varsToVals.get(key), temp);
}
outv.add(temp);
}
return outv;
}
public List<String>subInLiterals(String var, String value, List<String> targets){
ArrayList<String> outv =new ArrayList<String>();
for( String target : targets){
outv.add( subInLiterals( var,value, target) ) ;
}
return outv;
}
public String subInLiterals(String var, String value, String target){
String varRegex = "\\?" + var;
String out = target.replaceAll(varRegex,'"'+value+'"'); //*** THIS NEEDS TO BE ESCAPED for N3 (thats python escaping)
if( out != null && out.length() > 0 )
return out ;
else
return target;
}
public Map<String,String> newToUriMap(Map<String,String> newResources, Model model){
HashMap<String,String> newUris = new HashMap<String,String>();
for( String key : newResources.keySet()){
newUris.put(key,makeNewUri(newResources.get(key), model));
}
return newUris;
}
public String makeNewUri(String prefix, Model model){
if( prefix == null || prefix.length() == 0 )
prefix = defaultUriPrefix;
String uri = prefix + Math.abs( random.nextInt() );
Resource r = ResourceFactory.createResource(uri);
while( model.containsResource(r) ){
uri = prefix + random.nextInt();
r = ResourceFactory.createResource(uri);
}
return uri;
}
static Random random = new Random();
//we should get this from the application
static String defaultUriPrefix = "http://vivo.library.cornell.edu/ns/0.1#individual";
public static final String baseDirectoryForFiles = "/usr/local/vitrofiles";
private static Property RDF_TYPE = ResourceFactory.createProperty(VitroVocabulary.RDF_TYPE);
private static Property RDFS_LABEL = ResourceFactory.createProperty(VitroVocabulary.RDFS+"label");
Log log = LogFactory.getLog("edu.cornell.mannlib.vitro.webapp.edit.processRdfForm2.jsp");
%>
<%!
/* What are the posibilities and what do they mean?
field is a Uri:
orgValue formValue
null null Optional object property, maybe a un-filled out checkbox or radio button.
non-null null There was an object property and it was unset on the form
null non-null There was an objProp that was not set and is now set.
non-null non-null If they are the same then there was no edit, if the differ then form field was changed
field is a Literal:
orgValue formValue
null null Optional value that was not set.
non-null null Optional value that was unset on form
null non-null Optional value that was unset but was set on form
non-null non-null If same, there was no edit, if different, there was a change to the form field.
What about checkboxes?
*/
private boolean hasFieldChanged(String fieldName, EditConfiguration editConfig, EditSubmission submission) {
String orgValue = editConfig.getUrisInScope().get(fieldName);
String newValue = submission.getUrisFromForm().get(fieldName);
// see possibilities list in comments just above
if (orgValue == null && newValue != null) {
log.debug("Note: Setting previously null object property for field '"+fieldName+"' to new value ["+newValue+"]");
return true;
}
if( orgValue != null && newValue != null){
if( orgValue.equals(newValue))
return false;
else
return true;
}
//This does NOT use the semantics of the literal's Datatype or the language.
Literal orgLit = editConfig.getLiteralsInScope().get(fieldName);
Literal newLit = submission.getLiteralsFromForm().get(fieldName);
if( orgLit != null ) {
orgValue = orgLit.getValue().toString();
}
if( newLit != null ) {
newValue = newLit.getValue().toString();
}
// added for links, where linkDisplayRank will frequently come in null
if (orgValue == null && newValue != null) {
return true;
}
if( orgValue != null && newValue != null ){
if( orgValue.equals(newValue))
return false;
else
return true;
}
//value wasn't set originally because the field is optional
return false;
}
private boolean logAddRetract(String msg, Map<String,List<String>>add, Map<String,List<String>>retract){
log.debug(msg);
if( add != null ) log.debug( "assertions: " + add.toString() );
if( retract != null ) log.debug( "retractions: " + retract.toString() );
return true;
}
private boolean logRequuiredOpt(String msg, List<String>required, List<String>optional){
log.debug(msg);
if( required != null ) log.debug( "required: " + required.toString() );
if( optional != null ) log.debug( "optional: " + optional.toString() );
return true;
}
private void dump(String name, Object fff){
XStream xstream = new XStream(new DomDriver());
System.out.println( "*******************************************************************" );
System.out.println( name );
System.out.println(xstream.toXML( fff ));
}
%>

View file

@ -0,0 +1,76 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditSubmission" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.Controllers" %>
<%@page import="org.apache.commons.logging.Log"%>
<%@page import="org.apache.commons.logging.LogFactory"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jstl/functions" %>
<%@ taglib uri="http://jakarta.apache.org/taglibs/string-1.1" prefix="str" %>
<%
/* Clear any cruft from session. */
String redirectTo = null;
String urlPattern = null;
if( session != null ) {
EditConfiguration editConfig = EditConfiguration.getConfigFromSession(session,request);
//In order to support back button resubmissions, don't remove the editConfig from session.
//EditConfiguration.clearEditConfigurationInSession(session, editConfig);
EditSubmission editSub = EditSubmission.getEditSubmissionFromSession(session,editConfig);
EditSubmission.clearEditSubmissionInSession(session, editSub);
if( editConfig != null && editConfig.getEntityToReturnTo() != null ){
String predicateUri = editConfig.getPredicateUri();
log.debug("Return to property after submitting form: " + predicateUri);
%>
<c:set var="predicateUri" value="<%=predicateUri%>" />
<c:set var="localName" value="${fn:substringAfter(predicateUri, '#')}" />
<%
if( editConfig.getEntityToReturnTo().startsWith("?") ){
redirectTo = (String)request.getAttribute("entityToReturnTo");
}else{
redirectTo = editConfig.getEntityToReturnTo();
}
}
if( editConfig != null && editConfig.getUrlPatternToReturnTo() != null){
urlPattern = editConfig.getUrlPatternToReturnTo();
}
}
if( redirectTo != null ){
request.setAttribute("redirectTo",redirectTo); %>
<%-- <c:redirect url="/entity">
<c:param name="uri" value="${redirectTo}" />
<c:param name="property" value="${localName}" />
</c:redirect> --%>
<% if( urlPattern != null && urlPattern.endsWith("entity")){ %>
<%-- Here we're building the redirect URL to include an (unencoded) fragment identifier such as: #propertyName --%>
<c:url context="/" var="encodedUrl" value="/entity">
<c:param name="uri" value="${redirectTo}" />
</c:url>
<c:redirect url="${encodedUrl}${'#'}${localName}" />
<% } else {
request.setAttribute("urlPattern",urlPattern);%>
<c:url context="/" var="encodedUrl" value="${urlPattern}">
<c:param name="uri" value="${redirectTo}" />
</c:url>
<c:redirect url="${encodedUrl}${'#'}${localName}" />
<%} %>
<% } else { %>
<c:redirect url="<%= Controllers.LOGIN %>" />
<% } %>
<%!
Log log = LogFactory.getLog("edu.cornell.mannlib.vitro.webapp.edit.postEditCleanUp.jsp");
%>

View file

@ -0,0 +1,419 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.rdf.model.*" %>
<%@ page import="com.hp.hpl.jena.ontology.OntModel" %>
<%@ page import="com.hp.hpl.jena.shared.Lock" %>
<%@ page import="com.thoughtworks.xstream.XStream" %>
<%@ page import="com.thoughtworks.xstream.io.xml.DomDriver" %>
<%@ page import="edu.cornell.mannlib.vedit.beans.LoginFormBean" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.beans.Individual" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.EditLiteral" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditN3Generator" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditSubmission" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.Field" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.filters.VitroRequestPrep" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.Controllers" %>
<%@ page import="org.apache.commons.logging.Log" %>
<%@ page import="org.apache.commons.logging.LogFactory" %>
<%@ page import="java.io.StringReader" %>
<%@ page import="java.util.*" %>
<%@page import="edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatementImpl"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.RdfLiteralHash"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.beans.DataProperty"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.ServletIdentifierBundleFactory"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.SelfEditingIdentifierFactory"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.RoleIdentifier"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.dao.jena.event.EditEvent"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditN3Utils"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%-- 2nd prototype of processing, adapted for data property editing
This one takes one list of n3 for a single data property statement field,
and there will be no optional fields. If the variables in the required n3
are not bound or it cannot be processed as n3 by Jena then it is an error
in processing the form.
Handling back button submissions:
As of 2008-08 this code can handle a single back button submission. Deeper
back button submissions are handled by just creating the requested property
with the requested literal value and setting a request attribute to indicate
"back button confusion" It is painful to the user to just give them an error
page since they might have just spent 5 min. typing in a value.
When an data property edit submission is POSTed it includes the subjectURI,
the predicateURI, the new Literal and a hash of the Literal to be replaced.
When a client POSTs a form that they received after several other POSTs
involving the same data property and Literal, there is a chance that the
data property statement to be replaced, with the Literal identified by the hash
in the POST, is no longer in the model.
Current stop gap solution:
If we cannot find the data property statement to replace:
If the data property is functional then just delete the single existing statement
and replace with he new one.
Otherwise, just add the new data property statement, don't remove any statements
and set a flag in the request to indicate "back button confusion"
--%>
<%!
public static Log log = LogFactory.getLog("edu.cornell.mannlib.vitro.webapp.jsp.edit.processDatapropRdfForm.jsp");
%>
<%
log.debug("Starting processDatapropRdfForm.jsp");
if( session == null)
throw new Error("need to have session");
%>
<%
boolean selfEditing = VitroRequestPrep.isSelfEditing(request);
if (!selfEditing && !LoginFormBean.loggedIn(request, LoginFormBean.NON_EDITOR)) {
%><c:redirect url="<%= Controllers.LOGIN %>" /><%
}
List<String> errorMessages = new ArrayList<String>();
//Object sessionOntModel = request.getSession().getAttribute("jenaOntModel");
//OntModel jenaOntModel = (sessionOntModel != null && sessionOntModel instanceof OntModel) ? (OntModel)sessionOntModel:
// (OntModel)application.getAttribute("jenaOntModel");
VitroRequest vreq = new VitroRequest(request);
EditConfiguration editConfig = EditConfiguration.getConfigFromSession(session,vreq);
if( editConfig == null ){
%><jsp:forward page="/edit/messages/noEditConfigFound.jsp"/><%
return;
}
EditSubmission submission = new EditSubmission(vreq.getParameterMap(), editConfig);
Map<String,String> errors = submission.getValidationErrors();
EditSubmission.putEditSubmissionInSession(session,submission);
if( errors != null && ! errors.isEmpty() ){
String form = editConfig.getFormUrl();
vreq.setAttribute("formUrl", form);
%><jsp:forward page="${formUrl}"/><%
return;
}
OntModel queryModel = editConfig.getQueryModelSelector().getModel(request,application);
OntModel resourcesModel = editConfig.getResourceModelSelector().getModel(request,application);
EditN3Generator n3Subber = editConfig.getN3Generator();
List<String> n3Required = editConfig.getN3Required();
Map<String,List<String>> fieldAssertions = null;
String subjectUri=null, predicateUri=null;
Individual subject=null;
if( editConfig.getDatapropKey() != null && editConfig.getDatapropKey().length() > 0){
// we are editing an existing data property statement
subjectUri = editConfig.getSubjectUri();
if (subjectUri == null || subjectUri.trim().length()==0) {
log.error("No subjectUri parameter available via editConfig for datapropKey "+editConfig.getDatapropKey());
throw new Error("No subjectUri parameter available via editConfig in processDatapropRdfForm.jsp");
}
predicateUri = editConfig.getPredicateUri();
if (predicateUri == null || predicateUri.trim().length()==0) {
log.error("No predicateUri parameter available via editConfig for datapropKey "+editConfig.getDatapropKey());
throw new Error("No predicateUri parameter available via editConfig in processDatapropRdfForm.jsp");
}
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
// need to get subject because have to iterate through all its data property statements to match datapropKey hashcode
subject = wdf.getIndividualDao().getIndividualByURI(subjectUri);
if( subject == null ) {
log.error("Could not find subject Individual via editConfig's subjectUri while proceessing update to datapropKey "+editConfig.getDatapropKey());
throw new Error("In processDatapropRdfForm.jsp, could not find subject Individual via uri " + subjectUri);
}
boolean backButtonProblems = checkForBackButtonConfusion( submission, editConfig, subject, wdf);
if( backButtonProblems ){
%><jsp:forward page="/edit/messages/datapropertyBackButtonProblems.jsp"/><%
return;
}
fieldAssertions = fieldsToMap(editConfig.getFields());
}
/* ********** URIs and Literals on Form/Parameters *********** */
//sub in resource uris off form
n3Required = n3Subber.subInUris(submission.getUrisFromForm(), n3Required);
//sub in literals from form
n3Required = n3Subber.subInLiterals(submission.getLiteralsFromForm(), n3Required);
fieldAssertions = n3Subber.substituteIntoValues(submission.getUrisFromForm(), submission.getLiteralsFromForm(), fieldAssertions );
/* ****************** URIs and Literals in Scope ************** */
n3Required = n3Subber.subInUris( editConfig.getUrisInScope(), n3Required);
n3Required = n3Subber.subInLiterals( editConfig.getLiteralsInScope(), n3Required);
fieldAssertions = n3Subber.substituteIntoValues(editConfig.getUrisInScope(),editConfig.getLiteralsInScope(), fieldAssertions );
/* ****************** New Resources ********************** */
Map<String,String> varToNewResource = newToUriMap(editConfig.getNewResources(),resourcesModel);
//if we are editing an existing prop, no new resources will be substituted since the var will
//have already been substituted in by urisInScope.
n3Required = n3Subber.subInUris( varToNewResource, n3Required);
fieldAssertions = n3Subber.substituteIntoValues(varToNewResource, null, fieldAssertions );
/* ***************** Build Models ******************* */
/* bdc34: we should check if this is an edit of an existing
or a new individual. If this is a edit of an existing then
we don't need to do the n3required or the n3optional; only the
the assertions and retractions from the fields are needed.
*/
List<Model> requiredAssertions = null;
List<Model> requiredRetractions = null;
boolean submissionWasAnUpdate = false;
if( editConfig.getDatapropKey() != null && editConfig.getDatapropKey().trim().length() > 0 ){
//editing an existing statement
submissionWasAnUpdate = true;
List<Model> requiredFieldAssertions = new ArrayList<Model>();
List<Model> requiredFieldRetractions = new ArrayList<Model>();
for(String fieldName: fieldAssertions.keySet()){
Field field = editConfig.getFields().get(fieldName);
/* CHECK that field changed, then add assertions and retractions */
if( hasFieldChanged(fieldName, editConfig, submission) ){
log.debug("Field "+fieldName+" has changed for datapropKey "+editConfig.getDatapropKey());
List<String> assertions = fieldAssertions.get(fieldName);
for( String n3 : assertions){
try{
log.debug("Adding assertion '"+n3+"' to requiredFieldAssertions");
Model model = ModelFactory.createDefaultModel();
StringReader reader = new StringReader(n3);
model.read(reader, "", "N3");
requiredFieldAssertions.add(model);
}catch(Throwable t){
log.warn("processing N3 assertions string from field "+fieldName+"\n"+t.getMessage()+'\n'+"n3: \n"+n3);
errorMessages.add("error processing N3 assertion string from field " + fieldName + "\n"+
t.getMessage() + '\n' +
"n3: \n" + n3 );
}
}
if (field.getRetractions()!=null) {
for( String n3 : field.getRetractions()){
try{
log.debug("Adding retraction '"+n3+"' to requiredFieldRetractions");
Model model = ModelFactory.createDefaultModel();
StringReader reader = new StringReader(n3);
model.read(reader, "", "N3");
requiredFieldRetractions.add(model);
}catch(Throwable t){
log.warn("processing N3 retraction string from field "+fieldName+"\n"+t.getMessage()+'\n'+"n3: \n"+n3);
errorMessages.add("error in processDatapropRdfForm.jsp processing N3 retraction string from field "+fieldName+"\n"+t.getMessage()+'\n'+"n3: \n"+n3);
}
}
}
if(checkForEmptyString(submission, editConfig)){
//don't assert the empty string dataproperty
requiredFieldAssertions.clear();
}
}
}
requiredAssertions = requiredFieldAssertions;
requiredRetractions = requiredFieldRetractions;
} else { //deal with required N3
submissionWasAnUpdate = false;
log.debug("Not editing an existing statement since no datapropKey in editConfig");
List<Model> requiredNewModels = new ArrayList<Model>();
for(String n3 : n3Required){
try{
log.debug("Adding assertion '"+n3+"' to requiredNewModels");
Model model = ModelFactory.createDefaultModel();
StringReader reader = new StringReader(n3);
model.read(reader, "", "N3");
requiredNewModels.add( model );
}catch(Throwable t){
log.warn("error processing required n3 string \n"+t.getMessage()+'\n'+"n3: \n"+n3);
errorMessages.add("error processing required n3 string \n"+t.getMessage()+'\n'+"n3: \n"+n3);
}
}
requiredRetractions = Collections.EMPTY_LIST;
if( !checkForEmptyString(submission, editConfig) ){
requiredAssertions = requiredNewModels;
if( !errorMessages.isEmpty() ){
for( String error : errorMessages){
log.debug(error);
}
}
}else{
//doing an empty field delete, see Issue VITRO-432
requiredAssertions = Collections.EMPTY_LIST;
}
}
OntModel writeModel = editConfig.getWriteModelSelector().getModel(request,application);
Lock lock = null;
String editorUri = EditN3Utils.getEditorUri(request,session,application);
try{
lock = writeModel.getLock();
lock.enterCriticalSection(Lock.WRITE);
writeModel.getBaseModel().notifyEvent(new EditEvent(editorUri,true));
for( Model model : requiredAssertions) {
writeModel.add(model);
}
for(Model model : requiredRetractions ){
writeModel.remove( model );
}
}catch(Throwable t){
errorMessages.add("In processDatapropRdfForm.jsp, error adding edit change n3required model to in memory model \n"+ t.getMessage() );
}finally{
writeModel.getBaseModel().notifyEvent(new EditEvent(editorUri,false));
lock.leaveCriticalSection();
}
//now setup an EditConfiguration so a single back button submissions can be handled
EditConfiguration copy = editConfig.copy();
//need a new DataPropHash and a new editConfig that uses that, and replace
//the editConfig used for this submission in the session. The same thing
//is done for an update or a new insert since it will convert the insert
//EditConfig into an update EditConfig.
log.debug("attempting to make an updated copy of the editConfig for browser back button support");
Field dataField = copy.getField(copy.getVarNameForObject());
DataPropertyStatement dps = new DataPropertyStatementImpl();
Literal submitted = submission.getLiteralsFromForm().get(copy.getVarNameForObject());
dps.setIndividualURI( copy.getSubjectUri() );
dps.setDatapropURI( copy.getPredicateUri() );
dps.setDatatypeURI( submitted.getDatatypeURI());
dps.setLanguage( submitted.getLanguage() );
dps.setData( submitted.getLexicalForm() );
copy.prepareForDataPropUpdate(writeModel, dps);
copy.setDatapropKey( Integer.toString(RdfLiteralHash.makeRdfLiteralHash(dps)) );
EditConfiguration.putConfigInSession(copy,session);
%>
<jsp:forward page="postEditCleanUp.jsp"/>
<%!/* ********************************************************* */
/* ******************** utility functions ****************** */
/* ********************************************************* */
public Map<String, List<String>> fieldsToMap(Map<String, Field> fields) {
Map<String, List<String>> out = new HashMap<String, List<String>>();
for (String fieldName : fields.keySet()) {
Field field = fields.get(fieldName);
List<String> copyOfN3 = new ArrayList<String>();
for (String str : field.getAssertions()) {
copyOfN3.add(str);
}
out.put(fieldName, copyOfN3);
}
return out;
}
public Map<String, String> newToUriMap(Map<String, String> newResources,
Model model) {
HashMap<String, String> newUris = new HashMap<String, String>();
for (String key : newResources.keySet()) {
newUris.put(key, makeNewUri(newResources.get(key), model));
}
return newUris;
}
public String makeNewUri(String prefix, Model model) {
if (prefix == null || prefix.length() == 0)
prefix = defaultUriPrefix;
String uri = prefix + random.nextInt();
Resource r = ResourceFactory.createResource(uri);
while (model.containsResource(r)) {
uri = prefix + random.nextInt();
r = ResourceFactory.createResource(uri);
}
return uri;
}
static Random random = new Random();
static String defaultUriPrefix = "http://vivo.library.cornell.edu/ns/0.1#individual";%>
<%!private boolean hasFieldChanged(String fieldName,
EditConfiguration editConfig, EditSubmission submission) {
String orgValue = editConfig.getUrisInScope().get(fieldName);
String newValue = submission.getUrisFromForm().get(fieldName);
if (orgValue != null && newValue != null) {
if (orgValue.equals(newValue))
return false;
else
return true;
}
Literal orgLit = editConfig.getLiteralsInScope().get(fieldName);
Literal newLit = submission.getLiteralsFromForm().get(fieldName);
boolean fieldChanged = !EditLiteral.equalLiterals(orgLit, newLit);
log.debug("field " + fieldName + " "
+ (fieldChanged ? "did Change" : "did NOT change"));
return fieldChanged;
}
private boolean checkForBackButtonConfusion(EditSubmission submission,
EditConfiguration editConfig, Individual subject,
WebappDaoFactory wdf) {
if (editConfig.getDatapropKey() == null
|| editConfig.getDatapropKey().length() == 0)
return false;
DataPropertyStatement dps = RdfLiteralHash.getDataPropertyStmtByHash(
subject, Integer.parseInt(editConfig.getDatapropKey()));
if (dps != null)
return false;
DataProperty dp = wdf.getDataPropertyDao().getDataPropertyByURI(
editConfig.getPredicateUri());
if (dp != null) {
if (dp.getDisplayLimit() == 1 /* || dp.isFunctional() */)
return false;
else
return true;
}
return false;
}
// Our editors have gotten into the habbit of clearing the text from the
// textarea and saving it to invoke a delete. see Issue VITRO-432
private boolean checkForEmptyString(EditSubmission submission,
EditConfiguration editConfig) {
if (editConfig.getFields().size() == 1) {
String onlyField = editConfig.getFields().keySet().iterator()
.next();
Literal value = submission.getLiteralsFromForm().get(onlyField);
if ("".equals(value.getLexicalForm())) {
log.debug("Submission was a single field with an empty string");
return true;
}
}
return false;
}
private void dump(String name, Object fff) {
XStream xstream = new XStream(new DomDriver());
Log log = LogFactory
.getLog("edu.cornell.mannlib.vitro.webapp.jsp.edit.forms.processDatapropRdfForm.jsp");
log
.debug("*******************************************************************");
log.debug(name);
log.debug(xstream.toXML(fff));
}%>

View file

@ -0,0 +1,484 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.ontology.OntModel" %>
<%@ page import="com.hp.hpl.jena.rdf.model.Model" %>
<%@ page import="com.hp.hpl.jena.rdf.model.ModelFactory" %>
<%@ page import="com.hp.hpl.jena.rdf.model.Resource" %>
<%@ page import="com.hp.hpl.jena.rdf.model.Literal" %>
<%@ page import="com.hp.hpl.jena.rdf.model.ResourceFactory" %>
<%@ page import="com.hp.hpl.jena.shared.Lock" %>
<%@ page import="com.thoughtworks.xstream.XStream" %>
<%@ page import="com.thoughtworks.xstream.io.xml.DomDriver" %>
<%@ page import="edu.cornell.mannlib.vedit.beans.LoginFormBean" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditN3Generator" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditSubmission" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.Field" %>
<%@ page import="java.io.StringReader" %>
<%@ page import="java.util.*" %>
<%@page import="org.apache.commons.logging.LogFactory"%>
<%@page import="org.apache.commons.logging.Log"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="java.io.InputStream"%>
<%@page import="org.apache.commons.fileupload.FileItemIterator"%>
<%@page import="org.apache.commons.fileupload.FileItemStream"%>
<%@page import="org.apache.commons.fileupload.util.Streams"%>
<%@page import="com.hp.hpl.jena.rdf.model.Property"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary"%>
<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="org.apache.commons.fileupload.FileItemFactory"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.dao.jena.event.EditEvent"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.ServletIdentifierBundleFactory"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.SelfEditingIdentifierFactory"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.RoleIdentifier"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditN3Utils"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.filters.VitroRequestPrep"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.ModelChangePreprocessor"%>
<%@ page import="edu.cornell.mannlib.vitro.webapp.controller.Controllers" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%-- 2nd prototype of processing.
This one takes two lists of n3, on required and one optional. If
all of the variables in the required n3 are not bound or it cannot
be processed as n3 by Jena then it is an error in processing the form.
The optional n3 blocks will proccessed if their variables are bound and
are well formed.
--%>
<%
if( session == null)
throw new Error("need to have session");
boolean selfEditing = VitroRequestPrep.isSelfEditing(request);
if (!selfEditing && !LoginFormBean.loggedIn(request, LoginFormBean.NON_EDITOR)) {
%>
<%@page import="edu.cornell.mannlib.vitro.webapp.dao.jena.DependentResourceDeleteJena"%><c:redirect url="<%= Controllers.LOGIN %>" />
<%
}
VitroRequest vreq = new VitroRequest(request);
/* the post parameters seem to get consumed by the parsing so
* we have to make a copy. */
Map <String,String[]> queryParameters = null;
queryParameters = vreq.getParameterMap();
List<String> errorMessages = new ArrayList<String>();
EditConfiguration editConfig = EditConfiguration.getConfigFromSession(session,vreq,queryParameters);
if( editConfig == null ){
%><jsp:forward page="/edit/messages/noEditConfigFound.jsp"/><%
}
EditN3Generator n3Subber = editConfig.getN3Generator();
EditSubmission submission = new EditSubmission(queryParameters,editConfig);
/* entity to return to may be a variable */
List<String> entToReturnTo = new ArrayList<String>(1);
if( editConfig.getEntityToReturnTo() != null ){
entToReturnTo.add(" "+editConfig.getEntityToReturnTo()+" ");
}
Map<String,String> errors = submission.getValidationErrors();
EditSubmission.putEditSubmissionInSession(session,submission);
if( errors != null && ! errors.isEmpty() ){
String form = editConfig.getFormUrl();
vreq.setAttribute("formUrl", form);
%><jsp:forward page="${formUrl}"/><%
return;
}
OntModel queryModel = editConfig.getQueryModelSelector().getModel(request,application);
OntModel resourcesModel = editConfig.getResourceModelSelector().getModel(request,application);
List<Model> requiredAssertions = null;
List<Model> requiredRetractions = null;
List<Model> optionalAssertions = null;
boolean requestIsAnUpdate = editConfig.getObject() != null && editConfig.getObject().trim().length() > 0;
if( requestIsAnUpdate ){
//handle a update of an existing object
if( log.isDebugEnabled()) log.debug("editing an existing resource: " + editConfig.getObject() );
Map<String,List<String>> fieldAssertions = fieldsToAssertionMap(editConfig.getFields());
Map<String,List<String>> fieldRetractions= fieldsToRetractionMap(editConfig.getFields());
/* ********** URIs and Literals on Form/Parameters *********** */
fieldAssertions = n3Subber.substituteIntoValues( submission.getUrisFromForm(), submission.getLiteralsFromForm(), fieldAssertions);
if(log.isDebugEnabled()) logAddRetract("subsititued in literals from form",fieldAssertions,fieldRetractions);
entToReturnTo = n3Subber.subInUris(submission.getUrisFromForm(),entToReturnTo);
//fieldRetractions does NOT get values from form.
/* ****************** URIs and Literals in Scope ************** */
fieldAssertions = n3Subber.substituteIntoValues(editConfig.getUrisInScope(), editConfig.getLiteralsInScope(), fieldAssertions );
fieldRetractions = n3Subber.substituteIntoValues(editConfig.getUrisInScope(), editConfig.getLiteralsInScope(), fieldRetractions);
if(log.isDebugEnabled()) logAddRetract("subsititued in URIs and Literals from scope",fieldAssertions,fieldRetractions);
entToReturnTo = n3Subber.subInUris(editConfig.getUrisInScope(),entToReturnTo);
//do edits ever need new resources? (YES)
Map<String,String> varToNewResource = newToUriMap(editConfig.getNewResources(),resourcesModel);
fieldAssertions = n3Subber.substituteIntoValues(varToNewResource, null, fieldAssertions);
if(log.isDebugEnabled()) logAddRetract("subsititued in URIs for new resources",fieldAssertions,fieldRetractions);
entToReturnTo = n3Subber.subInUris(varToNewResource,entToReturnTo);
//fieldRetractions does NOT get values from form.
//editing an existing statement
List<Model> requiredFieldAssertions = new ArrayList<Model>();
List<Model> requiredFieldRetractions = new ArrayList<Model>();
for(String fieldName: fieldAssertions.keySet()){
Field field = editConfig.getFields().get(fieldName);
/* CHECK that field changed, then add assertions and retractions */
// No longer checking if field has changed, because assertions and retractions
// are mutually diffed before statements are added to or removed from the model.
// The explicit change check can cause problems
// in more complex setups, like the automatic form building in DataStaR.
if (true) { // ( hasFieldChanged(fieldName, editConfig, submission) ){
//log.debug("field "+fieldName+" has changed ...");
/* if the field was a checkbox then we need to something special */
List<String> assertions = fieldAssertions.get(fieldName);
List<String> retractions = fieldRetractions.get(fieldName);
for( String n3 : assertions){
try{
Model model = ModelFactory.createDefaultModel();
StringReader reader = new StringReader(n3);
model.read(reader, "", "N3");
requiredFieldAssertions.add(model);
}catch(Throwable t){
String errMsg = "error processing N3 assertion string from field " + fieldName + "\n"+
t.getMessage() + '\n' + "n3: \n" + n3;
errorMessages.add(errMsg);
if ( log.isDebugEnabled() ) {
log.debug( errMsg );
}
}
}
for( String n3 : retractions ){
try{
Model model = ModelFactory.createDefaultModel();
StringReader reader = new StringReader(n3);
model.read(reader, "", "N3");
requiredFieldRetractions.add(model);
}catch(Throwable t){
String errMsg = "error processing N3 retraction string from field " + fieldName + "\n"+
t.getMessage() + '\n' +
"n3: \n" + n3;
errorMessages.add(errMsg);
if ( log.isDebugEnabled() ) {
log.debug( errMsg );
}
}
}
}
}
requiredAssertions = requiredFieldAssertions;
requiredRetractions = requiredFieldRetractions;
optionalAssertions = Collections.EMPTY_LIST;
} else {
if( log.isDebugEnabled()) log.debug("creating a new relation " + editConfig.getPredicateUri() );
//handle creation of a new object property and maybe a resource
List<String> n3Required = editConfig.getN3Required();
List<String> n3Optional = editConfig.getN3Optional();
/* ********** URIs and Literals on Form/Parameters *********** */
//sub in resource uris off form
n3Required = n3Subber.subInUris(submission.getUrisFromForm(), n3Required);
n3Optional = n3Subber.subInUris(submission.getUrisFromForm(), n3Optional);
if(log.isDebugEnabled()) logRequuiredOpt("subsititued in URIs off from ",n3Required,n3Optional);
entToReturnTo = n3Subber.subInUris(submission.getUrisFromForm(), entToReturnTo);
//sub in literals from form
n3Required = n3Subber.subInLiterals(submission.getLiteralsFromForm(), n3Required);
n3Optional = n3Subber.subInLiterals(submission.getLiteralsFromForm(), n3Optional);
if(log.isDebugEnabled()) logRequuiredOpt("subsititued in literals off from ",n3Required,n3Optional);
/* ****************** URIs and Literals in Scope ************** */
n3Required = n3Subber.subInUris( editConfig.getUrisInScope(), n3Required);
n3Optional = n3Subber.subInUris( editConfig.getUrisInScope(), n3Optional);
if(log.isDebugEnabled()) logRequuiredOpt("subsititued in URIs from scope ",n3Required,n3Optional);
entToReturnTo = n3Subber.subInUris(editConfig.getUrisInScope(), entToReturnTo);
n3Required = n3Subber.subInLiterals( editConfig.getLiteralsInScope(), n3Required);
n3Optional = n3Subber.subInLiterals( editConfig.getLiteralsInScope(), n3Optional);
if(log.isDebugEnabled()) logRequuiredOpt("subsititued in Literals from scope ",n3Required,n3Optional);
/* ****************** New Resources ********************** */
Map<String,String> varToNewResource = newToUriMap(editConfig.getNewResources(),resourcesModel);
//if we are editing an existing prop, no new resources will be substituted since the var will
//have already been substituted in by urisInScope.
n3Required = n3Subber.subInUris( varToNewResource, n3Required);
n3Optional = n3Subber.subInUris( varToNewResource, n3Optional);
if(log.isDebugEnabled()) logRequuiredOpt("subsititued in URIs for new resources ",n3Required,n3Optional);
entToReturnTo = n3Subber.subInUris(varToNewResource, entToReturnTo);
//deal with required N3
List<Model> requiredNewModels = new ArrayList<Model>();
for(String n3 : n3Required){
try{
Model model = ModelFactory.createDefaultModel();
StringReader reader = new StringReader(n3);
model.read(reader, "", "N3");
requiredNewModels.add( model );
}catch(Throwable t){
errorMessages.add("error processing required n3 string \n"+
t.getMessage() + '\n' +
"n3: \n" + n3 );
}
}
if( !errorMessages.isEmpty() ){
String error = "problems processing required n3: \n";
for( String errorMsg : errorMessages){
error += errorMsg + '\n';
}
throw new JspException("errors processing required N3,\n" + error );
}
requiredAssertions = requiredNewModels;
requiredRetractions = Collections.EMPTY_LIST;
//deal with optional N3
List<Model> optionalNewModels = new ArrayList<Model>();
for(String n3 : n3Optional){
try{
Model model = ModelFactory.createDefaultModel();
StringReader reader = new StringReader(n3);
model.read(reader, "", "N3");
optionalNewModels.add(model);
}catch(Throwable t){
errorMessages.add("error processing optional n3 string \n"+
t.getMessage() + '\n' +
"n3: \n" + n3);
}
}
optionalAssertions = optionalNewModels;
}
//The requiredNewModels and the optionalNewModels could be handled differently
//but for now we'll just do them the same
requiredAssertions.addAll(optionalAssertions);
//************************************************************
//make a model with all the assertions and a model with all the
//retractions, do a diff on those and then only add those to the
//jenaOntModel
//************************************************************
Model allPossibleAssertions = ModelFactory.createDefaultModel();
Model allPossibleRetractions = ModelFactory.createDefaultModel();
for( Model model : requiredAssertions ) {
allPossibleAssertions.add( model );
}
for( Model model : requiredRetractions ){
allPossibleRetractions.add( model );
}
Model actualAssertions = allPossibleAssertions.difference( allPossibleRetractions );
Model actualRetractions = allPossibleRetractions.difference( allPossibleAssertions );
if( editConfig.isUseDependentResourceDelete() ){
Model depResRetractions =
DependentResourceDeleteJena
.getDependentResourceDeleteForChange(actualAssertions,actualRetractions,queryModel);
actualRetractions.add( depResRetractions );
}
List<ModelChangePreprocessor> modelChangePreprocessors = editConfig.getModelChangePreprocessors();
if ( modelChangePreprocessors != null ) {
for ( ModelChangePreprocessor pp : modelChangePreprocessors ) {
pp.preprocess( actualRetractions, actualAssertions );
}
}
// get the model to write to here in case a preprocessor has switched the write layer
OntModel writeModel = editConfig.getWriteModelSelector().getModel(request,application);
String editorUri = EditN3Utils.getEditorUri(vreq,session,application);
Lock lock = null;
try{
lock = writeModel.getLock();
lock.enterCriticalSection(Lock.WRITE);
writeModel.getBaseModel().notifyEvent(new EditEvent(editorUri,true));
writeModel.add( actualAssertions );
writeModel.remove( actualRetractions );
}catch(Throwable t){
errorMessages.add("error adding edit change n3required model to in memory model \n"+ t.getMessage() );
}finally{
writeModel.getBaseModel().notifyEvent(new EditEvent(editorUri,false));
lock.leaveCriticalSection();
}
if( entToReturnTo.size() >= 1 && entToReturnTo.get(0) != null){
request.setAttribute("entityToReturnTo",
entToReturnTo.get(0).trim().replaceAll("<","").replaceAll(">",""));
}
%>
<jsp:forward page="postEditCleanUp.jsp"/>
<%!
/* ********************************************************* */
/* ******************** utility functions ****************** */
/* ********************************************************* */
public Map<String,List<String>> fieldsToAssertionMap( Map<String,Field> fields){
Map<String,List<String>> out = new HashMap<String,List<String>>();
for( String fieldName : fields.keySet()){
Field field = fields.get(fieldName);
List<String> copyOfN3 = new ArrayList<String>();
for( String str : field.getAssertions()){
copyOfN3.add(str);
}
out.put( fieldName, copyOfN3 );
}
return out;
}
public Map<String,List<String>> fieldsToRetractionMap( Map<String,Field> fields){
Map<String,List<String>> out = new HashMap<String,List<String>>();
for( String fieldName : fields.keySet()){
Field field = fields.get(fieldName);
List<String> copyOfN3 = new ArrayList<String>();
for( String str : field.getRetractions()){
copyOfN3.add(str);
}
out.put( fieldName, copyOfN3 );
}
return out;
}
/* ******************** Utility methods ********************** */
public Map<String,String> newToUriMap(Map<String,String> newResources, Model model){
HashMap<String,String> newUris = new HashMap<String,String>();
for( String key : newResources.keySet()){
newUris.put(key,makeNewUri(newResources.get(key), model));
}
return newUris;
}
public String makeNewUri(String prefix, Model model){
if( prefix == null || prefix.length() == 0 )
prefix = defaultUriPrefix;
String uri = prefix + Math.abs( random.nextInt() );
Resource r = ResourceFactory.createResource(uri);
while( model.containsResource(r) ){
uri = prefix + random.nextInt();
r = ResourceFactory.createResource(uri);
}
return uri;
}
static Random random = new Random();
//we should get this from the application
static String defaultUriPrefix = "http://vivo.library.cornell.edu/ns/0.1#individual";
public static final String baseDirectoryForFiles = "/usr/local/vitrofiles";
private static Property RDF_TYPE = ResourceFactory.createProperty(VitroVocabulary.RDF_TYPE);
private static Property RDFS_LABEL = ResourceFactory.createProperty(VitroVocabulary.RDFS+"label");
Log log = LogFactory.getLog("edu.cornell.mannlib.vitro.webapp.edit.processRdfForm2.jsp");
%>
<%!
/* What are the posibilities and what do they mean?
field is a Uri:
orgValue formValue
null null Optional object property, maybe a un-filled out checkbox or radio button.
non-null null There was an object property and it was unset on the form
null non-null There was an objProp that was not set and is now set.
non-null non-null If they are the same then there was no edit, if the differ then form field was changed
field is a Literal:
orgValue formValue
null null Optional value that was not set.
non-null null Optional value that was unset on form
null non-null Optional value that was unset but was set on form
non-null non-null If same, there was no edit, if different, there was a change to the form field.
What about checkboxes?
*/
private boolean hasFieldChanged(String fieldName, EditConfiguration editConfig, EditSubmission submission) {
String orgValue = editConfig.getUrisInScope().get(fieldName);
String newValue = submission.getUrisFromForm().get(fieldName);
// see possibilities list in comments just above
if (orgValue == null && newValue != null) {
log.debug("Note: Setting previously null object property for field '"+fieldName+"' to new value ["+newValue+"]");
return true;
}
if( orgValue != null && newValue != null){
if( orgValue.equals(newValue))
return false;
else
return true;
}
//This does NOT use the semantics of the literal's Datatype or the language.
Literal orgLit = editConfig.getLiteralsInScope().get(fieldName);
Literal newLit = submission.getLiteralsFromForm().get(fieldName);
if( orgLit != null ) {
orgValue = orgLit.getValue().toString();
}
if( newLit != null ) {
newValue = newLit.getValue().toString();
}
// added for links, where linkDisplayRank will frequently come in null
if (orgValue == null && newValue != null) {
return true;
}
if( orgValue != null && newValue != null ){
if( orgValue.equals(newValue)) {
return false;
}
else {
return true;
}
}
//value wasn't set originally because the field is optional
return false;
}
private boolean logAddRetract(String msg, Map<String,List<String>>add, Map<String,List<String>>retract){
log.debug(msg);
if( add != null ) log.debug( "assertions: " + add.toString() );
if( retract != null ) log.debug( "retractions: " + retract.toString() );
return true;
}
private boolean logRequuiredOpt(String msg, List<String>required, List<String>optional){
log.debug(msg);
if( required != null ) log.debug( "required: " + required.toString() );
if( optional != null ) log.debug( "optional: " + optional.toString() );
return true;
}
private void dump(String name, Object fff){
XStream xstream = new XStream(new DomDriver());
System.out.println( "*******************************************************************" );
System.out.println( name );
System.out.println(xstream.toXML( fff ));
}
%>

View file

@ -0,0 +1,113 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditSubmission" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.edit.n3editing.Field" %>
<%@ page import="edu.cornell.mannlib.vitro.webapp.filters.VitroRequestPrep" %>
<%@ page import="org.apache.commons.logging.Log" %>
<%@ page import="org.apache.commons.logging.LogFactory" %>
<%@ page import="java.io.StringReader" %>
<%@ page import="java.util.*" %>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.SelfEditingIdentifierFactory.NetId"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.SelfEditingIdentifierFactory"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.SelfEditingIdentifierFactory.SelfEditing"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.ServletIdentifierBundleFactory"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.ArrayIdentifierBundle"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle"%>
<%@page import="java.io.IOException"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundleFactory"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.policy.ServletPolicyList"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyIface"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.policy.SelfEditingPolicy"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.requestedAction.AddObjectPropStmt"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<h1>SelfEditing Sanity Check</h1>
<h3>Is there a Factory that will create self editing identifiers?</h3>
<%
ServletIdentifierBundleFactory sibf = ServletIdentifierBundleFactory.getIdentifierBundleFactory(application);
String found = "Self editing identifier factory found.";
for( IdentifierBundleFactory ibf : sibf ){
if( ibf instanceof SelfEditingIdentifierFactory ){
found = "Found a self editing identifier factory.";
break;
}
}
%>
<%= found %>
<h3>Is there a self editing policy in the context?</h3>
<%
ServletPolicyList spl = ServletPolicyList.getPolicies(application);
SelfEditingPolicy sePolicy = null;
ListIterator it = spl.listIterator();
found = "Could not find a SelfEditingPolicy";
while(it.hasNext()){
PolicyIface p = (PolicyIface)it.next();
if( p instanceof SelfEditingPolicy ){
found = "Found a SelfEditingPolicy";
sePolicy = (SelfEditingPolicy)p;
}
}
%>
<%= found %>
<h3>Do you have a REMOTE_USER header from CUWebAuth?</h3>
<% String user = request.getHeader("REMOTE_USER");
if( user != null && user.length() > 0){
%> Found a remote user of <%= user %>. <%
}else{
%> Could not find a remote user. Maybe you are not logged into CUWebAutn? <%
}
%>
<h3>Check if we can get a SelfEditingIdentifer for <%= user %></h3>
<%
SelfEditingIdentifierFactory.SelfEditing selfEditingId = null;
IdentifierBundle ib = null;
if( user != null && user.length() > 0){
ib = sibf.getIdentifierBundle(request,session,application);
if( ib != null ) {
for( Object obj : ib){
if( obj instanceof SelfEditingIdentifierFactory.SelfEditing )
selfEditingId = (SelfEditingIdentifierFactory.SelfEditing) obj;
}
if( selfEditingId != null )
found = "found a SelfEditingId " + selfEditingId.getValue();
else
found = "Cound not find a SelfEditingId";
}else{
found = "Could not get any identififers";
}
%>
<%= found %>
<%}else{%>
Cannot check becaue user is <%= user %>.
<%} %>
<h3>Is that SelfEditingIdentifer blacklisted?</h3>
<% if( user == null || user.length() == 0 ){ %>
No REMOTE_USER to check
<% }else if( selfEditingId == null ){ %>
no SelfEditingId to check
<% }else if( selfEditingId.getBlacklisted() != null){%>
SelfEditingId blacklisted because of <%= selfEditingId.getBlacklisted() %>
<% } else {%>
SelfEditingId is not blacklisted.
<% } %>
<h3>Can an object property be edited with this SelfEditingId and Policy?</h3>
<% if( user == null || selfEditingId == null ){ %>
No
<% }else{
AddObjectPropStmt whatToAuth = new AddObjectPropStmt(
selfEditingId.getValue(),"http://mannlib.cornell.edu/fine#prp999" ,"http://mannlib.cornell.edu/fine#prp999");
PolicyDecision pdecison = sePolicy.isAuthorized(ib, whatToAuth);
%> The policy decision was <%= pdecison %>
<% } %>

2
webapp/web/empty.jsp Normal file
View file

@ -0,0 +1,2 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>

65
webapp/web/error.jsp Executable file
View file

@ -0,0 +1,65 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%@ page isErrorPage="true" %>
<%@ page import="com.oreilly.servlet.ServletUtils,edu.cornell.mannlib.vitro.webapp.web.*" %>
<%@page import="edu.cornell.mannlib.vitro.webapp.controller.VitroRequest"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.beans.ApplicationBean"%>
<%@page import="edu.cornell.mannlib.vitro.webapp.beans.Portal"%>
<%
VitroRequest vreq = new VitroRequest(request);
ApplicationBean appBean = vreq.getAppBean();
Portal portal = vreq.getPortal();
String themeDir = portal!=null ? portal.getThemeDir() : Portal.DEFAULT_THEME_DIR_FROM_CONTEXT;
request.setAttribute("bodyJsp", "/errorbody.jsp");
request.setAttribute("title", "Error");
request.setAttribute("css", "");
request.setAttribute("portalBean", portal);
request.setAttribute("appBean", appBean);
request.setAttribute("themeDir", themeDir);
%>
<jsp:include page="/templates/page/doctype.jsp"/>
<head>
<jsp:include page="/templates/page/headContent.jsp"/>
</head>
<body> <!-- generated by error.jsp -->
<div id="wrap">
<jsp:include page="/${themeDir}jsp/identity.jsp" flush="true"/>
<div id="contentwrap">
<jsp:include page="/${themeDir}jsp/menu.jsp" flush="true"/>
<p>There was an error in the system; please try again later.</p>
<div>
<h3>Exception: </h3><%= exception %>
</div>
<div>
<% try{ %>
<h3>Trace:</h3><pre><%= ServletUtils.getStackTraceAsString(exception) %></pre>
<% }catch (Exception e){ %>
No trace is available.
<% } %>
</div>
<div>
<% try{ %>
<h3>Request Info:</h3><%= MiscWebUtils.getReqInfo(request) %>
<% }catch (Exception e){ %>
No request information is available.
<% } %>
</div>
</div> <!-- contentwrap -->
<jsp:include page="/${themeDir}jsp/footer.jsp" flush="true"/>
</div> <!-- wrap -->
</body>
</html>

View file

@ -0,0 +1,23 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%/* this is used by the FedoraDatastreamController and not by the N3 editing system.*/%>
<h2>Upload a replacement for ${fileName}</h2>
<form action="<c:url value="/fedoraDatastreamController"/>"
enctype="multipart/form-data" method="POST">
<p>File <input type="file" id="fileRes" name="fileRes" /></p>
<%/* <p><input type="radio" name="useNewName" value="false" checked/>
use existing file name</p>
<p><input type="radio" name="useNewName" value="true"/>
rename file to name of file being uploaded</p> */%>
<input type="hidden" name="fileUri" value="${fileUri}"/>
<input type="hidden" name="pid" value="${pid}"/>
<input type="hidden" name="dsid" value="${dsid}"/>
<input type="submit" id="submit" value="submit" />
</form>

View file

@ -0,0 +1,16 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<div>The file ${orginalFileName} was updated. The file received from you had the MD5 checksum ${checksum}.</div>
<c:if test="${useNewName}">
<div>The name of the file was also changed to ${newFileName}.</div>
</c:if>
<c:url value="/individual" var="url">
<c:param name="uri" value="${fileUri}"/>
</c:url>
<div>Goto <a href="${url}">${newFileName}</a></div>

View file

@ -0,0 +1,23 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="../js/jquery.js" type="text/javascript" language="javascript"></script>
<script src="../js/jquery_plugins/jquery.MultiFile.js" type="text/javascript" language="javascript"></script>
<title> file upload for ${projectName} </title>
</head>
<body>
<form action="fileUploadProcess.jsp" method="post" enctype="multipart/form-data">
<input type="text" name="creator" value="Brian Caruso"/></br>
<input type="file" class="multi" name="file1" value="file1"/></br>
<input type="submit" name="submit" value="Submit"/>
</form>
<form action="" class="P10">
<input type="file" class="multi" accept="gif|jpg"/>
</form>
</body>
</html>

View file

@ -0,0 +1,128 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>
<%@ page import="org.apache.commons.fileupload.FileItem" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.List" %>
<%@ page import="java.io.File" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%-- This is a jsp to handle uploading files. --%>
<%-- It was written with Datastar in mind --%>
<%-- This JSP code expects that the user is logged in,
that a datastar project is specified, and that the
request is a multipart POST. --%>
<%-- Since this is for Datastar we need the URI of the user
who is uploading this file, the URI of the project it is
associated with and a project spcific directory to save
the file to. %>
<%! static final int MAX_IN_MEM_SIZE = 1024*1024 * 50 ; //50 Mbyte file limit %>
<%-- http://vivo.library.cornell.edu/ns/0.1#coordinatorOf --%>
<%-- http://vivo.library.cornell.edu/ns/0.1#resourceAuthor --%>
<%! static final int MAX_IN_MEM_SIZE = 1024*1024 * 50; %>
<%
if( ! ServletFileUpload.isMultipartContent(request) ){
//return an error message0.
out.write("<html><p>you need to submit a file.</p></html>");
return;
}
//Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(MAX_IN_MEM_SIZE);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(MAX_IN_MEM_SIZE);
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
String user = getUserUri(request);
String project = getProjectUri(request);
String dir = getDirectory(user,project,request);
if( ! canWriteDirectory( dir )){
out.write( doDirectoryWriteError( dir ) );
return;
}
Iterator iter = items.iterator();
while( iter.hasNext()){
FileItem item = (FileItem)iter.next();
if( item.isFormField()){
out.write("<p>");
out.write("fieldname: " + item.getFieldName() + " value: " + item.getString() );
out.write("</p>");
}else{
System.out.println("fileUPloadProcess.jsp: attempting to upload a file" );
out.write("<p>");
out.write("form field name: " + item.getFieldName()
+" filename: " + item.getName()
+" type: " + item.getContentType()
+" isInMem: " + item.isInMemory() );
out.write("</p>");
String fileLocation = dir + '/' + item.getName();
if( fileWithNameAlreadyExists( fileLocation ) ){
doFileExistsError( fileLocation );
return;
}
File uploadedFile = new File( fileLocation );
item.write( uploadedFile );
}
}
%>
<%!
public String getDirectory(String userUri, String projectUri, HttpServletRequest request){
//this should be stored in the model as a dataproperty on the project
return "/usr/local/datastar/data";
}
public String getUserUri( HttpServletRequest request ){
return "http://vivo.library.cornell.edu/ns/0.1#individual762"; //Medha Devare
}
public String getProjectUri( HttpServletRequest request ){
return "http://vivo.library.cornell.edu/ns/0.1#individual1"; //Mann Lib.
}
%>
<%!
public boolean canWriteDirectory( String dir ){
File df = new File(dir);
//attempt to create directory if not found
if( ! df.exists() ){
if( !df.mkdir() )
return false;
}
return df.canWrite();
}
public String doDirectoryWriteError( String dir ) {
return "The system could not save your file, contact you system"
+" administrators and inform them that the directory "
+ dir + " is not writeable";
}
public boolean fileWithNameAlreadyExists( String fileLocation ){
File f = new File(fileLocation);
return f.exists();
}
public String doFileExistsError( String file ) {
return "There is already a file named " + file + " on the system. Please rename your file " ;
}
%>

View file

@ -0,0 +1,11 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<div>${checksum} "${fileName}"</div>
<c:url value="/individual" var="url">
<c:param name="uri" value="${uri}"/>
</c:url>
<div>return to <a href="${url}">${name}</a></div>

250
webapp/web/horizontal.jsp Normal file
View file

@ -0,0 +1,250 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="java.util.*, java.lang.String.*"%>
<%@ page import="edu.cornell.mannlib.vedit.beans.ButtonForm" %>
<%
if (request.getAttribute("title") != null) { %>
<h2><%=request.getAttribute("title")%></h2><%
}
%>
<table style="margin-bottom:1.5ex;">
<tr>
<td style="width:0;padding:0;margin:0;"/>
<%if (request.getAttribute("horizontalJspAddButtonUrl") != null) {%>
<td>
<form action="<%=request.getAttribute("horizontalJspAddButtonUrl")%>" method="get"><input type="submit" class="form-button" value="<%=request.getAttribute("horizontalJspAddButtonText")%>"/>
<% if (request.getAttribute("horizontalJspAddButtonControllerParam") != null) {%>
<input type="hidden" name="controller" value="<%=request.getAttribute("horizontalJspAddButtonControllerParam")%>"/>
<% }
if (request.getAttribute("home") != null) {%>
<input type="hidden" name="home" value="<%=request.getAttribute("home")%>"/>
<% }%>
</form>
</td>
<%
}
List <ButtonForm> topButtons = (List)request.getAttribute("topButtons");
if (topButtons!=null) {
Iterator iter = topButtons.iterator();
while (iter.hasNext()){
ButtonForm b = (ButtonForm)iter.next();%>
<td>
<form <%=b.getCssClass()%> action="<%=b.getAction()%>" method="get">
<% HashMap<String,String> params=b.getParams();
if (params!=null) {
for (String key : b.getParams().keySet()) {%>
<input type="hidden" name="<%=key%>" value="<%=params.get(key)%>"/>
<% }
}%>
<input type="submit" class="form-button" value="<%=b.getLabel()%>"/>
</form>
</td>
<% }
}%>
</tr></table>
<div class="editingForm">
<jsp:useBean id="results" class="java.util.ArrayList" scope="request" />
<% int columns = 0;
boolean havePostQueryData = false;
String editFormStr = (String)request.getAttribute("editform");
String minEditRoleStr = (String)request.getAttribute("min_edit_role");
String firstValue = "null", secondValue = "null";
Integer columnCount = (Integer)request.getAttribute("columncount");
columns = columnCount.intValue();
String clickSortStr = (String)request.getAttribute("clicksort");
if ( columns > 0 && results.size() > 0) { // avoid divide by zero error in next statement
/* start enclosing table cell that holds all results */
%>
<% String suppressStr = null;
boolean isPostQHeaderRow = false;
if ( ( suppressStr = (String)request.getAttribute("suppressquery")) == null ) { // only inserted into request if true
%>
<i><b><%=(results.size() - columns) / columns %></b> rows of results were retrieved in <b><%= columns %></b> columns for query "<%=request.getAttribute("querystring")%>".</i>
<br/>
<% }
Iterator iter = results.iterator();
int resultCount = 0, primaryRowNumber=0, pageRowNumber=0;
while (iter.hasNext()) {
String classString;
String thisResult = (String)iter.next();
if ( "+".equals(thisResult) ) {
havePostQueryData = true;
classString = "database_postheader";
isPostQHeaderRow = true;
thisResult = "&nbsp;";
} else if ( thisResult != null && thisResult.indexOf("@@")== 0) {
classString=thisResult.substring(2);
thisResult ="&nbsp;"; //leave as follows for diagnostics: thisResult.substring(2);
isPostQHeaderRow = false;
} else {
classString = isPostQHeaderRow ? "database_postheader" : "row";
if ( thisResult == null || "".equals(thisResult) )
thisResult = "&nbsp;";
}
if ( resultCount == 0 ) { // first pass : column names
%>
<table border="0" cellpadding="2" cellspacing="0" width = "100%">
<% if ( clickSortStr != null && "true".equals(clickSortStr) ) {
if ( (results.size() - columns) / columns > 2 ) {
%>
<tr>
<td class="database_upperleftcorner" colspan="<%=columns%>">
<i>Click on the column header to sort rows by that column.</i>
</td>
</tr>
<% }
}
%>
<tr>
<td class="rownumheader">#</td>
<% if ( !("XX".equals(thisResult) )) {
%>
<td class="database_header">
<% }
} else if ( resultCount == columns ) { // end column names and start numbered list
++ primaryRowNumber;
++ pageRowNumber;
firstValue = thisResult;
%>
</tr>
<tr valign="top" class="row">
<td class="rownum">1</td>
<% if ( !("XX".equals(thisResult) )) { %>
<td class="row">
<% }
} else if ( resultCount % columns == 0 ) { // end row and start next row with calculated row number
++ pageRowNumber;
%>
</tr>
<!-- <tr valign="top" class="<%=classString%>" > -->
<% if ( "row".equals(classString) ) {
if ( havePostQueryData ) {
%>
<tr><td>&nbsp;</td></tr>
<% havePostQueryData = false;
}
++ primaryRowNumber;
%>
<tr valign="top" class="row">
<td class="rownum"><%= primaryRowNumber /*resultCount / columns*/%></td>
<% } else { // classString does not equal "row"
%>
<tr valign="top" class="<%=classString%>" >
<% }
if ( !("XX".equals(thisResult) )) {
%>
<td class="<%=classString%>">
<% }
} else { // not the end of a row
if ( resultCount <= columns ) { // header rows
if ( !("XX".equals(thisResult) )) {
%>
<td class="database_header">
<%
}
} else if ( resultCount == columns + 1 ) {
secondValue=thisResult;
if ( !( "XX".equals(thisResult) )) {
%>
<td class="row">
<%
}
} else { // cells in later rows
if ( !( "XX".equals(thisResult) )) {
if ( "row".equals(classString) ) {
if ( primaryRowNumber % 2 == 0 ) {
if ( pageRowNumber % 2 == 0 ) {
%>
<td class="rowalternate">
<% } else {
%>
<td class="row">
<% }
} else if ( pageRowNumber % 2 == 0 ) {
%>
<td class="rowalternate">
<% } else {
%>
<td class="row">
<% }
} else {
%>
<td class="<%=classString%>" >
<% }
}
}
}
if ( !( "XX".equals(thisResult) )) {
%>
<%= thisResult %>
</td>
<%
}
++ resultCount;
}
%>
</tr>
</table>
<%
} else { /* results not > 0 */
Iterator errorIter = results.iterator();
while ( errorIter.hasNext()) {
String errorResult = (String)errorIter.next();
%>
<p>Error returned: <%= errorResult%></p>
<%
}
}
%>
<%
if ( editFormStr != null && minEditRoleStr != null ) {
String loginStatus =(String)session.getAttribute("loginStatus");
if ( loginStatus != null && "authenticated".equals(loginStatus) ) {
String currentRemoteAddrStr = request.getRemoteAddr();
String storedRemoteAddr = (String)session.getAttribute("loginRemoteAddr");
if ( storedRemoteAddr != null && currentRemoteAddrStr.equals( storedRemoteAddr ) ) {
int minEditRole = Integer.parseInt( minEditRoleStr );
String authorizedRoleStr = (String)session.getAttribute("loginRole");
if ( authorizedRoleStr != null ) {
int authorizedRole = Integer.parseInt( authorizedRoleStr );
if ( authorizedRole >= minEditRole ) { %>
<jsp:include page="<%=editFormStr%>" flush="true">
<jsp:param name="firstvalue" value="<%=firstValue%>" />
<jsp:param name="secondvalue" value="<%=secondValue%>" />
</jsp:include>
<% } else { %>
<% }
} else { %>
<% }
} else { %>
<% }
} else { %>
<% }
} else { %>
<%
} %>
</div>

Binary file not shown.

After

Width:  |  Height:  |  Size: 996 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 307 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 515 B

View file

@ -0,0 +1,30 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<h2>Connect to Jena Database</h2>
<form action="ingest" method="post">
<input type="hidden" name="action" value="connectDB"/>
<input type="text" style="width:80%;" name="jdbcUrl" value="jdbc:mysql://localhost/"/>
<p>JDBC URL</p>
<input type="text" name="username"/>
<p>username</p>
<input type="password" name="password"/>
<p>password</p>
<input id="tripleStoreRDB" name="tripleStore" type="radio" checked="checked" value="RDB"/>
<label for="tripleStoreRDB">Jena RDB</label>
<input id="tripleStoreSDB" name="tripleStore" type="radio" value="SDB"/>
<label for="tripleStoreRDB">Jena SDB (hash layout)</label>
<select name="dbType">
<option value="MySQL">MySQL</option>
</select>
<p>database type</p>
<input type="submit" value="Connect Database"/>

View file

@ -0,0 +1,9 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<h2>Create New Model</h2>
<form style="margin-bottom:2ex;" action="ingest" method="post">
<input type="hidden" name="action" value="createModel"/>
Model name: <input type="text" size="32" name="modelName"/>
<input type="submit" name="submit" value="Create Model"/>
</form>

View file

@ -0,0 +1,66 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.ontology.Individual" %>
<%@ page import="com.hp.hpl.jena.ontology.OntModel" %>
<%@ page import="com.hp.hpl.jena.rdf.model.ModelMaker" %>
<%@ page import="com.hp.hpl.jena.shared.Lock" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.List" %>
<%@ page import="java.net.URLEncoder" %>
<%
ModelMaker maker = (ModelMaker) request.getSession().getAttribute("vitroJenaModelMaker");
if (maker == null) {
maker = (ModelMaker) getServletContext().getAttribute("vitroJenaModelMaker");
}
%>
<h2>Convert CSV to RDF</h2>
<form action="ingest" method="get"i>
<input type="hidden" name="action" value="csv2rdf"/>
<p><input type="radio" name="separatorChar" value="comma" checked="checked"/> comma separated
<input type="radio" name="separatorChar" value="tab"/> tab separated </p>
<input type="text" style="width:80%;" name="csvUrl"/>
<p>CSV file URL (e.g. "file:///")</p>
<input type="text" name="namespace"/>
<p>Namespace in which to generate resources</p>
<input type="text" name="tboxNamespace"/>
<p>Namespace in which to generate class and properties</p>
<!--
<input type="checkbox" name="discardTbox"/> do not add TBox or RBox to result model
-->
<input type="text" name="typeName"/>
<p>Class Name for Resources</p>
<select name="destinationModelName">
<%
for (Iterator it = maker.listModels(); it.hasNext(); ) {
String modelName = (String) it.next();
%> <option value="<%=modelName%>"><%=modelName%></option>
<%
}
%> <option value="">(none)</option>
</select>
<p>Destination Model</p>
<select name="tboxDestinationModelName">
<%
for (Iterator it = maker.listModels(); it.hasNext(); ) {
String modelName = (String) it.next();
%> <option value="<%=modelName%>"><%=modelName%></option>
<%
}
%> <option value="">(none)</option>
</select>
<p>Destination Model for TBox</p>
<input type="submit" value="Convert CSV"/>

View file

@ -0,0 +1,46 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.ontology.Individual" %>
<%@ page import="com.hp.hpl.jena.ontology.OntModel" %>
<%@ page import="com.hp.hpl.jena.rdf.model.ModelMaker" %>
<%@ page import="com.hp.hpl.jena.shared.Lock" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.List" %>
<%@ page import="java.net.URLEncoder" %>
<%
ModelMaker maker = (ModelMaker) request.getSession().getAttribute("vitroJenaModelMaker");
if (maker == null) {
maker = (ModelMaker) getServletContext().getAttribute("vitroJenaModelMaker");
}
%>
<h2>Execute RDF-Encoded Ingest Workflow</h2>
<form action="ingest" method="get"i>
<input type="hidden" name="action" value="executeWorkflow"/>
<h3>Workflow</h3>
<select name="workflowURI">
<%
OntModel jenaOntModel = (OntModel) getServletContext().getAttribute("jenaOntModel");
jenaOntModel.enterCriticalSection(Lock.READ);
try {
List savedQueries = (List) request.getAttribute("workflows");
for (Iterator it = savedQueries.iterator(); it.hasNext();) {
Individual savedQuery = (Individual) it.next();
String queryURI = savedQuery.getURI();
String queryLabel = savedQuery.getLabel(null);
%> <option value="<%=queryURI%>"><%=queryLabel%></option> <%
}
} finally {
jenaOntModel.leaveCriticalSection();
}
%>
</select>
<input type="submit" value="Next &gt;"/>

View file

@ -0,0 +1,36 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<div class="staticPageBackground">
<h2> Export to RDF </h2>
<form action="" method="get">
<ul>
<li style="list-style-type:none;"><input type="radio" name="subgraph" checked="checked" value="full"/> Export entire RDF model (including application metadata)</li>
<li style="list-style-type:none;"><input type="radio" name="subgraph" value="tbox"/> Export ontology/ontologies (TBox)</li>
<li style="list-style-type:none;"><input type="radio" name="subgraph" value="abox"/> Export instance data (ABox)</li>
</ul>
<hr/>
<ul>
<li style="list-style-type:none;"><input type="radio" name="assertedOrInferred" checked="checked" value="asserted"/> Export only asserted statements </li>
<li style="list-style-type:none;"><input type="radio" name="assertedOrInferred" value="inferred"/> Export only inferred statements </li>
<li style="list-style-type:none;"><input type="radio" name="assertedOrInferred" value="full"/> Export asserted and inferred statements together </li>
</ul>
<h3>Select format</h3>
<select name="format">
<option value="RDF/XML">RDF/XML</option>
<option value="RDF/XML-ABBREV">RDF/XML abbrev.</option>
<option value="N3">N3</option>
<option value="N-TRIPLES">N-Triples</option>
<option value="TURTLE">Turtle</option>
</select>
<input type="submit" name="submit" value="Export"/>
</form>
</div>

View file

@ -0,0 +1,53 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.ontology.Individual" %>
<%@ page import="com.hp.hpl.jena.ontology.OntModel" %>
<%@ page import="com.hp.hpl.jena.rdf.model.ModelMaker" %>
<%@ page import="com.hp.hpl.jena.shared.Lock" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.List" %>
<%@ page import="java.net.URLEncoder" %>
<%
ModelMaker maker = (ModelMaker) request.getSession().getAttribute("vitroJenaModelMaker");
if (maker == null) {
maker = (ModelMaker) getServletContext().getAttribute("vitroJenaModelMaker");
}
%>
<h2>Generate TBox from Assertions Data</h2>
<form action="ingest" method="get">
<input type="hidden" name="action" value="generateTBox"/>
<h3>Select Source Models for Assertions Data</h3>
<ul>
<li><input type="checkbox" name="sourceModelName" value="vitro:jenaOntModel"/>webapp model</li>
<li><input type="checkbox" name="sourceModelName" value="vitro:baseOntModel"/>webapp assertions</li>
<%
for (Iterator it = maker.listModels(); it.hasNext(); ) {
String modelName = (String) it.next();
%> <li> <input type="checkbox" name="sourceModelName" value="<%=modelName%>"/><%=modelName%></li>
<%
}
%>
</ul>
<h3>Select Destination Model for Generated TBox</h3>
<select name="destinationModelName">
<option value="vitro:jenaOntModel"/>webapp model</option>
<option value="vitro:baseOntModel"/>webapp assertions</option>
<%
for (Iterator it = maker.listModels(); it.hasNext(); ) {
String modelName = (String) it.next();
%> <option value="<%=modelName%>"/><%=modelName%></option>
<%
}
%>
</select>
<input type="submit" value="Generate TBox"/>

View file

@ -0,0 +1,20 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<h2>Ingest Menu</h2>
<ul>
<li><a href="ingest?action=connectDB">Connect DB</a></li>
<li><a href="ingest?action=listModels">Manage Jena Models</a></li>
<li><a href="ingest?action=subtractModels">Subtract One Model from Another</a></li>
<li><a href="ingest?action=csv2rdf">Convert CSV to RDF</a></li>
<li><a href="jenaXmlFileUpload">Load XML and convert to RDF</a></li>
<li><a href="ingest?action=renameBNodes">Name Blank Nodes</a></li>
<li><a href="ingest?action=smushSingleModel">Smush Resources</a></li>
<li><a href="ingest?action=generateTBox">Generate TBox</a></li>
<li><a href="ingest?action=executeSparql">Execute SPARQL CONSTRUCT</a></li>
<li><a href="ingest?action=processStrings">Process Property Value Strings</a></li>
<li><a href="ingest?action=splitPropertyValues">Split Property Value Strings into Multiple Property Values</a></li>
<li><a href="ingest?action=executeWorkflow">Execute Workflow</a></li>
</ul>

View file

@ -0,0 +1,89 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.rdf.model.ModelMaker" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.net.URLEncoder" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%
ModelMaker maker = (ModelMaker) request.getSession().getAttribute("vitroJenaModelMaker");
if (maker == null) {
maker = (ModelMaker) getServletContext().getAttribute("vitroJenaModelMaker");
}
%>
<p><a href="ingest">Ingest Home</a></p>
<h2>Available Jena Models</h2>
<form action="ingest" method="get">
<input type="hidden" name="action" value="createModel"/>
<input type="submit" name="submit" value="Create Model"/>
</form>
<ul>
<%
for (Iterator it = maker.listModels(); it.hasNext(); ) {
String modelName = (String) it.next();
%> <li style="padding-bottom:2em;padding-top:2em;"> <%=modelName%>
<table style="margin-left:2em;"><tr>
<td>
<form action="ingest" method="get">
<input type="hidden" name="action" value="loadRDFData"/>
<input type="hidden" name="modelName" value="<%=modelName%>"/>
<input type="submit" name="submit" value="load RDF data"/>
</form>
</td>
<td>
<c:url var="outputModelURL" value="ingest">
<c:param name="action" value="outputModel"/>
<c:param name="modelName" value="<%=modelName%>"/>
</c:url>
<a href="${outputModelURL}">output model</a>
</td>
<td>
<form action="ingest" method="post">
<input type="hidden" name="action" value="clearModel"/>
<input type="hidden" name="modelName" value="<%=modelName%>"/>
<input type="submit" name="submit" value="clear statements"/>
</form>
</td>
<td>
<form action="ingest" method="post">
<input type="hidden" name="action" value="removeModel"/>
<input type="hidden" name="modelName" value="<%=modelName%>"/>
<input type="submit" name="submit" value="remove"/>
</form>
</td>
</tr>
<tr>
<td>
<form action="ingest" method="post">
<input type="hidden" name="action" value="setWriteLayer"/>
<input type="hidden" name="modelName" value="<%=modelName%>"/>
<input type="submit" name="submit" value="set as current write layer"/>
</form>
<td>
<form action="ingest" method="post">
<input type="hidden" name="action" value="attachModel"/>
<input type="hidden" name="modelName" value="<%=modelName%>"/>
<input type="submit" name="submit" value="attach to webapp"/>
</form>
</td>
<td>
<form action="ingest" method="post">
<input type="hidden" name="action" value="detachModel"/>
<input type="hidden" name="modelName" value="<%=modelName%>"/>
<input type="submit" name="submit" value="detach from webapp"/>
</form>
</td>
<td>&nbsp;</td>
</tr>
</table>
</li> <%
}
%>
</ul>

View file

@ -0,0 +1,21 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<h2>Load RDF Data</h2>
<form style="margin-bottom:2ex;" action="ingest" method="post">
<input type="hidden" name="modelName" value="<%=request.getParameter("modelName")%>"/>
<input type="hidden" name="action" value="loadRDFData"/>
<p>RDF document URI: <input type="text" size="32" name="docLoc"/></p>
<p>Or local filesystem path: <input type="text" size="32" name="filePath"/>
(If a directory is supplied, will attempt to load all files therein)</p>
<p>
<select name="language">
<option value="RDF/XML">RDF/XML</option>
<option value="N3">N3</option>
<option value="N-TRIPLE">N-Triples</option>
<option value="TTL">Turtle</option>
</select>
<input type="submit" name="submit" value="Load Data"/>
</p>
</form>

View file

@ -0,0 +1,73 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.ontology.Individual" %>
<%@ page import="com.hp.hpl.jena.ontology.OntModel" %>
<%@ page import="com.hp.hpl.jena.rdf.model.ModelMaker" %>
<%@ page import="com.hp.hpl.jena.shared.Lock" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.List" %>
<%@ page import="java.net.URLEncoder" %>
<%
ModelMaker maker = (ModelMaker) request.getSession().getAttribute("vitroJenaModelMaker");
if (maker == null) {
maker = (ModelMaker) getServletContext().getAttribute("vitroJenaModelMaker");
}
%>
<h2>Process Property Value Strings</h2>
<form action="ingest" method="get"i>
<input type="hidden" name="action" value="processStrings"/>
<input type="text" style="width:80%;" name="className"/>
<p>String processor class</p>
<input type="text" name="methodName"/>
<p>String processor method</p>
<input type="text" name="propertyName"/>
<p>Property URI</p>
<input type="text" name="newPropertyName"/>
<p>New Property URI</p>
<select name="destinationModelName">
<%
for (Iterator it = maker.listModels(); it.hasNext(); ) {
String modelName = (String) it.next();
%> <option value="<%=modelName%>"/><%=modelName%></option>
<%
}
%>
</select>
<input type="checkbox" name="processModel" value="TRUE"/> apply changes directly to this model
<p>model to use</p>
<select name="additionsModel">
<option value="">none</option>
<%
for (Iterator it = maker.listModels(); it.hasNext(); ) {
String modelName = (String) it.next();
%> <option value="<%=modelName%>"><%=modelName%></option>
<%
}
%>
</select>
<p>model in which to save added statements</p>
<select name="retractionsModel">
<option value="">none</option>
<%
for (Iterator it = maker.listModels(); it.hasNext(); ) {
String modelName = (String) it.next();
%> <option value="<%=modelName%>"><%=modelName%></option>
<%
}
%>
</select>
<p>model in which to save retracted statements</p>
<input type="submit" value="Process property values"/>

View file

@ -0,0 +1,57 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.ontology.Individual" %>
<%@ page import="com.hp.hpl.jena.ontology.OntModel" %>
<%@ page import="com.hp.hpl.jena.rdf.model.ModelMaker" %>
<%@ page import="com.hp.hpl.jena.shared.Lock" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.List" %>
<%@ page import="java.net.URLEncoder" %>
<%
ModelMaker maker = (ModelMaker) request.getSession().getAttribute("vitroJenaModelMaker");
if (maker == null) {
maker = (ModelMaker) getServletContext().getAttribute("vitroJenaModelMaker");
}
%>
<h2>Convert Blank Nodes to Named Resources</h2>
<form action="ingest" method="get"i>
<input type="hidden" name="action" value="renameBNodes"/>
<h3>Select URI prefix</h3>
<p>URIs will be constructed from the following string concatenated with a random integer:</p>
<input type="text" name="namespaceEtcStr"/>
<p/>
<h3>Select Source Models</h3>
<ul>
<%
for (Iterator it = maker.listModels(); it.hasNext(); ) {
String modelName = (String) it.next();
%> <li> <input type="checkbox" name="sourceModelName" value="<%=modelName%>"/><%=modelName%></li>
<%
}
%>
</ul>
<h3>Select Destination Model</h3>
<select name="destinationModelName">
<%
for (Iterator it = maker.listModels(); it.hasNext(); ) {
String modelName = (String) it.next();
%> <option value="<%=modelName%>"/><%=modelName%></option>
<%
}
%>
</select>
<input type="submit" value="Rename Blank Nodes"/>

View file

@ -0,0 +1,53 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.ontology.Individual" %>
<%@ page import="com.hp.hpl.jena.ontology.OntModel" %>
<%@ page import="com.hp.hpl.jena.rdf.model.ModelMaker" %>
<%@ page import="com.hp.hpl.jena.shared.Lock" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.List" %>
<%@ page import="java.net.URLEncoder" %>
<%
ModelMaker maker = (ModelMaker) request.getSession().getAttribute("vitroJenaModelMaker");
if (maker == null) {
maker = (ModelMaker) getServletContext().getAttribute("vitroJenaModelMaker");
}
%>
<h2>Smush Resources</h2>
<form action="ingest" method="get"i>
<input type="hidden" name="action" value="smushSingleModel"/>
<h3>URI of Property with which To Smush
<input type="text" name="propertyURI"/>
<h3>Select Source Models</h3>
<ul>
<%
for (Iterator it = maker.listModels(); it.hasNext(); ) {
String modelName = (String) it.next();
%> <li> <input type="checkbox" name="sourceModelName" value="<%=modelName%>"/><%=modelName%></li>
<%
}
%>
</ul>
<h3>Select Destination Model</h3>
<select name="destinationModelName">
<%
for (Iterator it = maker.listModels(); it.hasNext(); ) {
String modelName = (String) it.next();
%> <option value="<%=modelName%>"/><%=modelName%></option>
<%
}
%>
</select>
<input type="submit" value="Smush Resources"/>

View file

@ -0,0 +1,166 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.ontology.Individual" %>
<%@ page import="com.hp.hpl.jena.ontology.OntModel" %>
<%@ page import="com.hp.hpl.jena.rdf.model.ModelMaker" %>
<%@ page import="com.hp.hpl.jena.shared.Lock" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.List" %>
<%@ page import="java.net.URLEncoder" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%
ModelMaker maker = (ModelMaker) request.getSession().getAttribute("vitroJenaModelMaker");
if (maker == null) {
maker = (ModelMaker) getServletContext().getAttribute("vitroJenaModelMaker");
}
%>
<%@page import="java.util.HashSet"%>
<%@page import="java.util.Set"%>
<%@page import="java.util.Arrays"%>
<%@page import="java.util.ArrayList"%><h2>Execute SPARQL CONSTRUCT Query</h2>
<p><a href="ingest">Ingest Home</a></p>
<c:if test="${requestScope.constructedStmtCount != null}">
<h3 class="notice">${requestScope.constructedStmtCount} statements CONSTRUCTed</h3>
</c:if>
<c:if test="${errorMsg != null}">
<h3 class="error">${requestScope.errorMsg}</h3>
</c:if>
<c:if test="${requestScope.validationMessage != null}">
<h3 class="notice">${requestScope.validationMessage}</h3>
</c:if>
<form action="ingest" method="post">
<input type="hidden" name="action" value="executeSparql"/>
<h3>SPARQL Query
<select name="savedQuery">
<option value="">select saved query</option>
<%
OntModel jenaOntModel = (OntModel) getServletContext().getAttribute("jenaOntModel");
jenaOntModel.enterCriticalSection(Lock.READ);
try {
List savedQueries = (List) request.getAttribute("savedQueries");
for (Iterator it = savedQueries.iterator(); it.hasNext();) {
Individual savedQuery = (Individual) it.next();
String queryURI = savedQuery.getURI();
String queryLabel = savedQuery.getLabel(null);
%> <option value="<%=queryURI%>"><%=queryLabel%></option> <%
}
} finally {
jenaOntModel.leaveCriticalSection();
}
%>
</select>
<textarea rows="16" cols="40" name="sparqlQueryStr"><c:choose>
<c:when test="${param.sparqlQueryStr != null}">
${param.sparqlQueryStr}
</c:when>
<c:otherwise>
PREFIX rdf: &lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&gt;
PREFIX rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#&gt;
PREFIX owl: &lt;http://www.w3.org/2002/07/owl#&gt;
PREFIX xsd: &lt;http://www.w3.org/2001/XMLSchema#&gt;
PREFIX vitro: &lt;http://vitro.mannlib.cornell.edu/ns/vitro/0.7#&gt;
</c:otherwise>
</c:choose>
</textarea>
<h3>Select Source Models</h3>
<ul>
<%
List<String> sourceModelNameList = new ArrayList<String>();
String[] sourceModelParamVals = request.getParameterValues("sourceModelName");
if (sourceModelParamVals != null) {
sourceModelNameList.addAll(Arrays.asList(sourceModelParamVals));
}
%>
<li><input type="checkbox" name="sourceModelName" value="vitro:jenaOntModel"
<%
if (sourceModelNameList.contains("vitro:jenaOntModel")) {
%>checked="checked"<%
}
%>
/>webapp model</li>
<li><input type="checkbox" name="sourceModelName" value="vitro:baseOntModel"
<%
if (sourceModelNameList.contains("vitro:baseOntModel")) {
%>checked="checked"<%
}
%>
/>webapp assertions</li>
<%
for (Iterator it = maker.listModels(); it.hasNext(); ) {
String modelName = (String) it.next();
%> <li> <input type="checkbox" name="sourceModelName" value="<%=modelName%>"
<%
if (sourceModelNameList.contains(modelName)) {
%> checked="checked" <%
}
%>
/><%=modelName%></li>
<%
}
%>
</ul>
<h3>Select Destination Model</h3>
<select name="destinationModelName">
<option value="vitro:jenaOntModel"
<% if ("vitro:jenaOntModel".equals(request.getParameter("destinationModelName"))) {
%> selected="selected" <%
}
%>
/>webapp model</option>
<option value="vitro:baseOntModel"
<% if ("vitro:baseOntModel".equals(request.getParameter("destinationModelName"))) {
%> selected="selected" <%
}
%>
/>webapp assertions</option>
<%
for (Iterator it = maker.listModels(); it.hasNext(); ) {
String modelName = (String) it.next();
%> <option value="<%=modelName%>"
<%
if (modelName.equals(request.getParameter("destinationModelName"))) {
%> selected="selected" <%
}
%>
/><%=modelName%></option>
<%
}
%>
</select>
<c:choose>
<c:when test="${paramValues['reasoning'] != null}">
<c:forEach var="paramValue" items="${paramValues['reasoning']}">
<c:if test="${paramValue eq 'pellet'}">
<p><input type="checkbox" name="reasoning" value="pellet" checked="checked"/> include pellet reasoning </p>
</c:if>
</c:forEach>
</c:when>
<c:otherwise>
<p><input type="checkbox" name="reasoning" value="pellet" /> include Pellet OWL-DL reasoning </p>
</c:otherwise>
</c:choose>
<input type="submit" value="Execute CONSTRUCT"/>

View file

@ -0,0 +1,65 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.ontology.Individual" %>
<%@ page import="com.hp.hpl.jena.ontology.OntModel" %>
<%@ page import="com.hp.hpl.jena.rdf.model.ModelMaker" %>
<%@ page import="com.hp.hpl.jena.shared.Lock" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.List" %>
<%@ page import="java.net.URLEncoder" %>
<%
ModelMaker maker = (ModelMaker) request.getSession().getAttribute("vitroJenaModelMaker");
if (maker == null) {
maker = (ModelMaker) getServletContext().getAttribute("vitroJenaModelMaker");
}
%>
<h2>Split Property Value Strings into Multiple Property Values</h2>
<form action="ingest" method="get">
<input type="hidden" name="action" value="splitPropertyValues"/>
<h3>Select Source Models</h3>
<ul>
<li><input type="checkbox" name="sourceModelName" value="vitro:jenaOntModel"/>webapp model</li>
<li><input type="checkbox" name="sourceModelName" value="vitro:baseOntModel"/>webapp assertions</li>
<%
for (Iterator it = maker.listModels(); it.hasNext(); ) {
String modelName = (String) it.next();
%> <li> <input type="checkbox" name="sourceModelName" value="<%=modelName%>"/><%=modelName%></li>
<%
}
%>
</ul>
<input type="text" name="propertyURI"/>
<p>Property URI for which Values Should Be Split</p>
<input type="text" name="splitRegex"/>
<p>Regex Pattern on which To Split</p>
<input type="text" name="newPropertyURI"/>
<p>Property URI To Be Used with the Newly-Split Values</p>
<h3></h3>
<p>
<input type="checkbox" name="trim" value="true"/> trim bordering whitespace
</p>
<h3>Select Destination Model</h3>
<select name="destinationModelName">
<%
for (Iterator it = maker.listModels(); it.hasNext(); ) {
String modelName = (String) it.next();
%> <option value="<%=modelName%>"/><%=modelName%></option>
<%
}
%>
</select>
<input type="submit" value="Split Values"/>

View file

@ -0,0 +1,58 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.ontology.Individual" %>
<%@ page import="com.hp.hpl.jena.ontology.OntModel" %>
<%@ page import="com.hp.hpl.jena.rdf.model.ModelMaker" %>
<%@ page import="com.hp.hpl.jena.shared.Lock" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.List" %>
<%@ page import="java.net.URLEncoder" %>
<%
ModelMaker maker = (ModelMaker) request.getSession().getAttribute("vitroJenaModelMaker");
if (maker == null) {
maker = (ModelMaker) getServletContext().getAttribute("vitroJenaModelMaker");
}
%>
<h2>Subtract One Model from Another</h2>
<form action="ingest" method="get"i>
<input type="hidden" name="action" value="subtractModels"/>
<select name="modela">
<%
for (Iterator it = maker.listModels(); it.hasNext(); ) {
String modelName = (String) it.next();
%> <option value="<%=modelName%>"/><%=modelName%></option>
<%
}
%>
</select>
<p>model to be subtracted from</p>
<select name="modelb">
<%
for (Iterator it = maker.listModels(); it.hasNext(); ) {
String modelName = (String) it.next();
%> <option value="<%=modelName%>"><%=modelName%></option>
<%
}
%>
</select>
<p>model to subtract</p>
<select name="destinationModelName">
<%
for (Iterator it = maker.listModels(); it.hasNext(); ) {
String modelName = (String) it.next();
%> <option value="<%=modelName%>"><%=modelName%></option>
<%
}
%>
</select>
<p>model in which difference should be saved</p>
<input type="submit" value="Subtract models"/>

View file

@ -0,0 +1,49 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.ontology.Individual" %>
<%@ page import="com.hp.hpl.jena.ontology.OntModel" %>
<%@ page import="com.hp.hpl.jena.rdf.model.ModelMaker" %>
<%@ page import="com.hp.hpl.jena.shared.Lock" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.List" %>
<%@ page import="java.net.URLEncoder" %>
<%
ModelMaker maker = (ModelMaker) request.getSession().getAttribute("vitroJenaModelMaker");
if (maker == null) {
maker = (ModelMaker) getServletContext().getAttribute("vitroJenaModelMaker");
}
%>
<h2>Execute RDF-Encoded Ingest Workflow</h2>
<form action="ingest" method="get"i>
<input type="hidden" name="action" value="executeWorkflow"/>
<h3>Choose a Workflow Step at Which To Start</h3>
<input type="hidden" name="workflowURI" value="${param.workflowURI}"/>
<select name="workflowStepURI">
<%
OntModel jenaOntModel = (OntModel) getServletContext().getAttribute("jenaOntModel");
jenaOntModel.enterCriticalSection(Lock.READ);
try {
List workflowSteps = (List) request.getAttribute("workflowSteps");
for (Iterator it = workflowSteps.iterator(); it.hasNext();) {
Individual workflowStep = (Individual) it.next();
String workflowStepURI = workflowStep.getURI();
String workflowStepLabel = workflowStep.getLabel(null);
String workflowStepString = (workflowStepLabel != null) ? workflowStepLabel : workflowStepURI;
%> <option value="<%=workflowStepURI%>"><%=workflowStepString%></option> <%
}
} finally {
jenaOntModel.leaveCriticalSection();
}
%>
</select>
<input type="submit" value="Execute Workflow"/>

View file

@ -0,0 +1,33 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.rdf.model.ModelMaker" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.net.URLEncoder" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%
ModelMaker maker = (ModelMaker) request.getSession().getAttribute("vitroJenaModelMaker");
if (maker == null) {
maker = (ModelMaker) getServletContext().getAttribute("vitroJenaModelMaker");
}
%>
<p><a href="ingest">Ingest Home</a></p>
<form action="jenaXmlFileUpload" method="post" enctype="multipart/form-data">
<input type="file" name="xmlfile"/>
<select name="targetModel">
<% for (Iterator it = maker.listModels(); it.hasNext(); ) {
String modelName = (String) it.next(); %>
<option value="<%=modelName%>"><%= modelName %></option>
<% } %>
</select>
<input type="submit" name="submit" value="upload XML and convert to RDF"/>
</form>

View file

@ -0,0 +1,17 @@
<%-- $This file is distributed under the terms of the license in /doc/license.txt$ --%>
<%@ page import="com.hp.hpl.jena.rdf.model.ModelMaker" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.net.URLEncoder" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%
%>
<p>Uploaded XML files and converted to RDF.</p>
<p>Loaded <%= request.getAttribute("statementCount") %> statements to the model <%= request.getAttribute("targetModel") %>.</p>
<p><a href="ingest">Ingest Home</a></p>

View file

@ -0,0 +1,211 @@
/* 'Magic' date parsing, by Simon Willison (6th October 2003)
http://simon.incutio.com/archive/2003/10/06/betterDateInput
example of usage:
<form action="" method="get"><div>
<input type="text" size="10" id="dateField" onblur="magicDate(this)"
onfocus="if (this.className != 'error') this.select()">
<div id="dateFieldMsg">mm/dd/yyyy</div>
</div></form>
*/
/* Finds the index of the first occurence of item in the array, or -1 if not found */
Array.prototype.indexOf = function(item) {
for (var i = 0; i < this.length; i++) {
if (this[i] == item) {
return i;
}
}
return -1;
};
/* Returns an array of items judged 'true' by the passed in test function */
Array.prototype.filter = function(test) {
var matches = [];
for (var i = 0; i < this.length; i++) {
if (test(this[i])) {
matches[matches.length] = this[i];
}
}
return matches;
};
var monthNames = "January February March April May June July August September October November December".split(" ");
var weekdayNames = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");
/* Takes a string, returns the index of the month matching that string, throws
an error if 0 or more than 1 matches
*/
function parseMonth(month) {
var matches = monthNames.filter(function(item) {
return new RegExp("^" + month, "i").test(item);
});
if (matches.length == 0) {
throw new Error("Invalid month string");
}
if (matches.length > 1) {
throw new Error("Ambiguous month");
}
return monthNames.indexOf(matches[0]);
}
/* Same as parseMonth but for days of the week */
function parseWeekday(weekday) {
var matches = weekdayNames.filter(function(item) {
return new RegExp("^" + weekday, "i").test(item);
});
if (matches.length == 0) {
throw new Error("Invalid day string");
}
if (matches.length > 1) {
throw new Error("Ambiguous weekday");
}
return weekdayNames.indexOf(matches[0]);
}
/* Array of objects, each has 're', a regular expression and 'handler', a
function for creating a date from something that matches the regular
expression. Handlers may throw errors if string is unparseable.
*/
var dateParsePatterns = [
// Today
{ re: /^tod/i,
handler: function() {
return new Date();
}
},
// Tomorrow
{ re: /^tom/i,
handler: function() {
var d = new Date();
d.setDate(d.getDate() + 1);
return d;
}
},
// Yesterday
{ re: /^yes/i,
handler: function() {
var d = new Date();
d.setDate(d.getDate() - 1);
return d;
}
},
// 4th
{ re: /^(\d{1,2})(st|nd|rd|th)?$/i,
handler: function(bits) {
var d = new Date();
d.setDate(parseInt(bits[1], 10));
return d;
}
},
// 4th Jan
{ re: /^(\d{1,2})(?:st|nd|rd|th)? (\w+)$/i,
handler: function(bits) {
var d = new Date();
d.setDate(parseInt(bits[1], 10));
d.setMonth(parseMonth(bits[2]));
return d;
}
},
// 4th Jan 2003
{ re: /^(\d{1,2})(?:st|nd|rd|th)? (\w+),? (\d{4})$/i,
handler: function(bits) {
var d = new Date();
d.setDate(parseInt(bits[1], 10));
d.setMonth(parseMonth(bits[2]));
d.setYear(bits[3]);
return d;
}
},
// Jan 4th
{ re: /^(\w+) (\d{1,2})(?:st|nd|rd|th)?$/i,
handler: function(bits) {
var d = new Date();
d.setDate(parseInt(bits[2], 10));
d.setMonth(parseMonth(bits[1]));
return d;
}
},
// Jan 4th 2003
{ re: /^(\w+) (\d{1,2})(?:st|nd|rd|th)?,? (\d{4})$/i,
handler: function(bits) {
var d = new Date();
d.setDate(parseInt(bits[2], 10));
d.setMonth(parseMonth(bits[1]));
d.setYear(bits[3]);
return d;
}
},
// next Tuesday - this is suspect due to weird meaning of "next"
{ re: /^next (\w+)$/i,
handler: function(bits) {
var d = new Date();
var day = d.getDay();
var newDay = parseWeekday(bits[1]);
var addDays = newDay - day;
if (newDay <= day) {
addDays += 7;
}
d.setDate(d.getDate() + addDays);
return d;
}
},
// last Tuesday
{ re: /^last (\w+)$/i,
handler: function(bits) {
throw new Error("Not yet implemented");
}
},
// mm/dd/yyyy (American style)
{ re: /(\d{1,2})\/(\d{1,2})\/(\d{4})/,
handler: function(bits) {
var d = new Date();
d.setYear(bits[3]);
d.setDate(parseInt(bits[2], 10));
d.setMonth(parseInt(bits[1], 10) - 1); // Because months indexed from 0
return d;
}
},
// yyyy-mm-dd (ISO style)
{ re: /(\d{4})-(\d{1,2})-(\d{1,2})/,
handler: function(bits) {
var d = new Date();
d.setYear(parseInt(bits[1]));
d.setDate(parseInt(bits[3], 10));
d.setMonth(parseInt(bits[2], 10) - 1);
return d;
}
},
];
function parseDateString(s) {
for (var i = 0; i < dateParsePatterns.length; i++) {
var re = dateParsePatterns[i].re;
var handler = dateParsePatterns[i].handler;
var bits = re.exec(s);
if (bits) {
return handler(bits);
}
}
throw new Error("Invalid date string" + s);
}
function magicDate(input) {
var messagespan = input.id + 'Msg';
try {
var d = parseDateString(input.value);
input.value = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();
input.className = '';
// Human readable date
document.getElementById(messagespan).firstChild.nodeValue = d.toDateString();
document.getElementById(messagespan).className = 'normal';
}
catch (e) {
input.className = 'error';
var message = e.message;
// Fix for IE6 bug
if (message.indexOf('is null or not an object') > -1) {
message = 'Invalid date string';
}
document.getElementById(messagespan).firstChild.nodeValue = message;
document.getElementById(messagespan).className = 'error';
}
}

View file

@ -0,0 +1,79 @@
<!-- /* $This file is distributed under the terms of the license in /doc/license.txt$ */ -->
<script language="JavaScript" type="text/javascript">
<!--
function ValidateForm(formName) {
var x = 0; // counts form elements - used as array index
var y = 0; // counts required fields - used as array index
errors = false;
var errorList;
if (document.forms[formName].RequiredFields) {
errorList = 'Please fill out the following required fields:\n';
// build array of required fields
reqStr = document.forms[formName].RequiredFields.value;
requiredFields = reqStr.split(',');
// build array holding the names of required fields as
// displayed in error box
if (document.forms[formName].RequiredFieldsNames) {
reqNameStr = document.forms[formName].RequiredFieldsNames.value;
} else {
reqNameStr = document.forms[formName].RequiredFields.value;
}
requiredNames = reqNameStr.split(',');
// Loop through form elements, checking for required fields
while ((x < document.forms[formName].elements.length)) {
if (document.forms[formName].elements[x].name == requiredFields[y]) {
if (document.forms[formName].elements[x].value == '') {
errorList += requiredNames[y] + '\n';
errors = true;
}
y++;
}
x++;
}
if (errors) {
alert(errorList);
return false;
}
x = 0;
y = 0;
}
// Check for Email formatting
if (document.forms[formName].EmailFields) {
errorList = 'Please format your e-mail address as: \"userid@institution.edu\" or enter another complete email address';
// build array of required fields
emailStr = document.forms[formName].EmailFields.value;
emailFields = emailStr.split(',');
// build array holding the names of required fields as
// displayed in error box
if (document.forms[formName].EmailFieldsNames) {
emailNameStr = document.forms[formName].EmailFieldsNames.value;
} else {
emailNameStr = document.forms[formName].EmailFields.value;
}
emailNames = emailNameStr.split(',');
// Loop through form elements, checking for required fields
while ((x < document.forms[formName].elements.length)) {
if (document.forms[formName].elements[x].name == emailFields[y]) {
if ((document.forms[formName].elements[x].value.indexOf('@') < 1)
|| (document.forms[formName].elements[x].value.lastIndexOf('.') < document.forms[formName].elements[x].value.indexOf('@')+1)) {
errors = true;
}
y++;
}
x++;
}
if (errors) {
alert(errorList);
return false;
}
x = 0;
y = 0;
}
return true;
}
-->
</script>

20
webapp/web/js/controls.js vendored Normal file
View file

@ -0,0 +1,20 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
/*
toggles admin panel using jQuery
*/
$(document).ready(function(){
// Sliding admin panel
$("div.admin .toggle").css("cursor","pointer");
$("div.admin .toggle").click(function(){
$(this).parent().children("div.panelContents").slideToggle("fast");
})
$("div.navlinkblock").removeClass("navlinkblock").addClass("navlinkblock-collapsed").click(function(){
$(this).removeClass("navlinkblock-collapsed").toggleClass("navlinkblock-expanded");
});
})

174
webapp/web/js/detect.js Executable file
View file

@ -0,0 +1,174 @@
/* from Nicholas C. Zakas 2005 */
/* ch 10 browser detection */
/* downloaded from wrox.com by bdc34 */
var sUserAgent = navigator.userAgent;
var fAppVersion = parseFloat(navigator.appVersion);
function compareVersions(sVersion1, sVersion2) {
var aVersion1 = sVersion1.split(".");
var aVersion2 = sVersion2.split(".");
if (aVersion1.length > aVersion2.length) {
for (var i=0; i < aVersion1.length - aVersion2.length; i++) {
aVersion2.push("0");
}
} else if (aVersion1.length < aVersion2.length) {
for (var i=0; i < aVersion2.length - aVersion1.length; i++) {
aVersion1.push("0");
}
}
for (var i=0; i < aVersion1.length; i++) {
if (aVersion1[i] < aVersion2[i]) {
return -1;
} else if (aVersion1[i] > aVersion2[i]) {
return 1;
}
}
return 0;
}
var isOpera = sUserAgent.indexOf("Opera") > -1;
var isMinOpera4 = isMinOpera5 = isMinOpera6 = isMinOpera7 = isMinOpera7_5 = false;
if (isOpera) {
var fOperaVersion;
if(navigator.appName == "Opera") {
fOperaVersion = fAppVersion;
} else {
var reOperaVersion = new RegExp("Opera (\\d+\\.\\d+)");
reOperaVersion.test(sUserAgent);
fOperaVersion = parseFloat(RegExp["$1"]);
}
isMinOpera4 = fOperaVersion >= 4;
isMinOpera5 = fOperaVersion >= 5;
isMinOpera6 = fOperaVersion >= 6;
isMinOpera7 = fOperaVersion >= 7;
isMinOpera7_5 = fOperaVersion >= 7.5;
}
var isKHTML = sUserAgent.indexOf("KHTML") > -1
|| sUserAgent.indexOf("Konqueror") > -1
|| sUserAgent.indexOf("AppleWebKit") > -1;
var isMinSafari1 = isMinSafari1_2 = false;
var isMinKonq2_2 = isMinKonq3 = isMinKonq3_1 = isMinKonq3_2 = false;
if (isKHTML) {
isSafari = sUserAgent.indexOf("AppleWebKit") > -1;
isKonq = sUserAgent.indexOf("Konqueror") > -1;
if (isSafari) {
var reAppleWebKit = new RegExp("AppleWebKit\\/(\\d+(?:\\.\\d*)?)");
reAppleWebKit.test(sUserAgent);
var fAppleWebKitVersion = parseFloat(RegExp["$1"]);
isMinSafari1 = fAppleWebKitVersion >= 85;
isMinSafari1_2 = fAppleWebKitVersion >= 124;
} else if (isKonq) {
var reKonq = new RegExp("Konqueror\\/(\\d+(?:\\.\\d+(?:\\.\\d)?)?)");
reKonq.test(sUserAgent);
isMinKonq2_2 = compareVersions(RegExp["$1"], "2.2") >= 0;
isMinKonq3 = compareVersions(RegExp["$1"], "3.0") >= 0;
isMinKonq3_1 = compareVersions(RegExp["$1"], "3.1") >= 0;
isMinKonq3_2 = compareVersions(RegExp["$1"], "3.2") >= 0;
}
}
var isIE = sUserAgent.indexOf("compatible") > -1
&& sUserAgent.indexOf("MSIE") > -1
&& !isOpera;
var isMinIE4 = isMinIE5 = isMinIE5_5 = isMinIE6 = false;
if (isIE) {
var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
reIE.test(sUserAgent);
var fIEVersion = parseFloat(RegExp["$1"]);
isMinIE4 = fIEVersion >= 4;
isMinIE5 = fIEVersion >= 5;
isMinIE5_5 = fIEVersion >= 5.5;
isMinIE6 = fIEVersion >= 6.0;
}
var isMoz = sUserAgent.indexOf("Gecko") > -1
&& !isKHTML;
var isMinMoz1 = sMinMoz1_4 = isMinMoz1_5 = false;
if (isMoz) {
var reMoz = new RegExp("rv:(\\d+\\.\\d+(?:\\.\\d+)?)");
reMoz.test(sUserAgent);
isMinMoz1 = compareVersions(RegExp["$1"], "1.0") >= 0;
isMinMoz1_4 = compareVersions(RegExp["$1"], "1.4") >= 0;
isMinMoz1_5 = compareVersions(RegExp["$1"], "1.5") >= 0;
}
var isNS4 = !isIE && !isOpera && !isMoz && !isKHTML
&& (sUserAgent.indexOf("Mozilla") == 0)
&& (navigator.appName == "Netscape")
&& (fAppVersion >= 4.0 && fAppVersion < 5.0);
var isMinNS4 = isMinNS4_5 = isMinNS4_7 = isMinNS4_8 = false;
if (isNS4) {
isMinNS4 = true;
isMinNS4_5 = fAppVersion >= 4.5;
isMinNS4_7 = fAppVersion >= 4.7;
isMinNS4_8 = fAppVersion >= 4.8;
}
var isWin = (navigator.platform == "Win32") || (navigator.platform == "Windows");
var isMac = (navigator.platform == "Mac68K") || (navigator.platform == "MacPPC")
|| (navigator.platform == "Macintosh");
var isUnix = (navigator.platform == "X11") && !isWin && !isMac;
var isWin95 = isWin98 = isWinNT4 = isWin2K = isWinME = isWinXP = false;
var isMac68K = isMacPPC = false;
var isSunOS = isMinSunOS4 = isMinSunOS5 = isMinSunOS5_5 = false;
if (isWin) {
isWin95 = sUserAgent.indexOf("Win95") > -1
|| sUserAgent.indexOf("Windows 95") > -1;
isWin98 = sUserAgent.indexOf("Win98") > -1
|| sUserAgent.indexOf("Windows 98") > -1;
isWinME = sUserAgent.indexOf("Win 9x 4.90") > -1
|| sUserAgent.indexOf("Windows ME") > -1;
isWin2K = sUserAgent.indexOf("Windows NT 5.0") > -1
|| sUserAgent.indexOf("Windows 2000") > -1;
isWinXP = sUserAgent.indexOf("Windows NT 5.1") > -1
|| sUserAgent.indexOf("Windows XP") > -1;
isWinNT4 = sUserAgent.indexOf("WinNT") > -1
|| sUserAgent.indexOf("Windows NT") > -1
|| sUserAgent.indexOf("WinNT4.0") > -1
|| sUserAgent.indexOf("Windows NT 4.0") > -1
&& (!isWinME && !isWin2K && !isWinXP);
}
if (isMac) {
isMac68K = sUserAgent.indexOf("Mac_68000") > -1
|| sUserAgent.indexOf("68K") > -1;
isMacPPC = sUserAgent.indexOf("Mac_PowerPC") > -1
|| sUserAgent.indexOf("PPC") > -1;
}
if (isUnix) {
isSunOS = sUserAgent.indexOf("SunOS") > -1;
if (isSunOS) {
var reSunOS = new RegExp("SunOS (\\d+\\.\\d+(?:\\.\\d+)?)");
reSunOS.test(sUserAgent);
isMinSunOS4 = compareVersions(RegExp["$1"], "4.0") >= 0;
isMinSunOS5 = compareVersions(RegExp["$1"], "5.0") >= 0;
isMinSunOS5_5 = compareVersions(RegExp["$1"], "5.5") >= 0;
}
}

View file

@ -0,0 +1,334 @@
<!-- $This file is distributed under the terms of the license in /doc/license.txt$ -->
<!-- <script type='text/javascript' src='dojo.js'></script> -->
<script language="JavaScript">
function confirmDelete() {
var msg="Are you SURE you want to delete this entity? If in doubt, CANCEL."
return confirm(msg);
}
</script>
<script type='text/javascript' src='dwr/interface/EntityDWR.js'></script>
<script type='text/javascript' src='dwr/engine.js'></script>
<script type='text/javascript' src='dwr/util.js'></script>
<script type='text/javascript' src='js/vitro.js'></script>
<script language="javascript" type="text/javascript">
if( vitroJsLoaded == null ){
alert("seminar.js needs to have the code from vitro.js loaded first");
}
// addEvent(window, 'load', monikerInit);
function monikerInit(){
// if ($('monikerSelect').options.length=1) {
// $('monikerSelectAlt').disabled = false;
// }else{
// $('monikerSelectAlt').disabled = true;
// }
$('Moniker').onchange = checkMonikers;
update();
}
function update(){ //updates moniker list when type is changed
DWRUtil.useLoadingMessage();
EntityDWR.monikers(createList, document.getElementById("VClassURI").value );
}
function createList(data) { //puts options in moniker select list
fillList("Moniker", data, getCurrentMoniker() );
var ele = $("Moniker");
var opt = new Option("none","");
ele.options[ele.options.length] = opt;
var opt = new Option("[new moniker]","");
ele.options[ele.options.length] = opt;
DWRUtil.setValue("Moniker",getCurrentMoniker()); // getCurrentMoniker() is defined on jsp
checkMonikers();
}
function getCurrentMoniker() {
return document.getElementById("MonikerSelectAlt").value;
}
function checkMonikers(){ //checks if monikers is on [new moniker] and enables alt field
var sel = $('Moniker');
if( sel.value == "" || sel.options.length <= 1){
$('MonikerSelectAlt').disabled = false;
}else{
$('MonikerSelectAlt').disabled = true;
}
}
function fillList(id, data, selectedtext) {
var ele = $(id);
if (ele == null) {
alert("fillList() can't find an element with id: " + id + ".");
throw id;
}
ele.options.length = 0; // Empty the list
if (data == null) { return; }
for (var i = 0; i < data.length; i++) {
var text = DWRUtil.toDescriptiveString(data[i]);
var value = text;
var opt = new Option(text, value);
if (selectedtext != null && selectedtext == text){
opt.selected=true;
}
ele.options[ele.options.length] = opt;
}
}
</script>
<script language="javascript" type="text/javascript" src="js/toggle.js"></script>
<script language="javascript" type="text/javascript" src="js/tiny_mce/tiny_mce.js"></script>
<script language="javascript" type="text/javascript">
// Notice: The simple theme does not use all options some of them are limited to the advanced theme
tinyMCE.init({
theme : "advanced",
mode : "exact",
elements : "Description",
theme_advanced_buttons1 : "bold,italic,underline,separator,link,bullist,numlist,separator,sub,sup,charmap,separator,undo,redo,separator,removeformat,cleanup,help,code",
theme_advanced_buttons2 : "",
theme_advanced_buttons3 : "",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_resizing : true,
height : "10",
width : "95%",
valid_elements : "a[href|target|name|title],br,p,i,em,cite,strong/b,u,sub,sup,ul,ol,li,h2,h3,h4,h5,h6",
forced_root_block: false
// elements : "elm1,elm2",
// save_callback : "customSave",
// content_css : "example_advanced.css",
// extended_valid_elements : "a[href|target|name]",
// plugins : "table",
// theme_advanced_buttons3_add_before : "tablecontrols,separator",
// invalid_elements : "li",
// theme_advanced_styles : "Header 1=header1;Header 2=header2;Header 3=header3;Table Row=tableRow1", // Theme specific setting CSS classes
});
</script>
<script type="text/javascript">
<!--
/*
dojo.require("dojo.dom.*");
*/
nextId=99999;
// fix this with separate values per type
function getAllChildren(theNode, childArray) {
var ImmediateChildren = theNode.childNodes;
if (ImmediateChildren) {
for (var i=0;i<ImmediateChildren.length;i++) {
childArray.push(ImmediateChildren[i]);
getAllChildren(ImmediateChildren[i],childArray);
}
}
}
function addLine(baseNode, typeStr)
{
baseId = baseNode.id.substr(0,baseNode.id.length-7);
newTaName = document.getElementById(baseId+"genTaName").firstChild.nodeValue;
theList = document.getElementById(baseId+"ul");
nextId++;
TrId = nextId;
templateRoot = document.getElementById(typeStr+"NN");
newRow = templateRoot.cloneNode(true);
// newRow.id = newRow.id.substr(0,newRow.id.length-2)+TrId;
newRow.id=TrId;
newRowChildren = new Array();
getAllChildren(newRow,newRowChildren);
for (i=0;i<newRowChildren.length;i++) {
if (newRowChildren[i].id) {
if(newRowChildren[i].id.substr(0,typeStr.length+2)==typeStr+"NN") {
newRowChildren[i].id=TrId+newRowChildren[i].id.substr(typeStr.length+2,newRowChildren[i].id.length-typeStr.length-2);
}
}
}
theList.appendChild(newRow);
theContent=document.getElementById(TrId+"content");
theContent.style.display="none";
theContentValue=document.getElementById(TrId+"contentValue");
theTaTa = document.getElementById(TrId+"tata");
theTaTa.name=newTaName;
theTaTa.style.display="block";
theTa = document.getElementById(TrId+"ta");
theTa.style.display="block";
// scroll the window to make sure the user sees our new textarea
var coors = findPos(theTaTa);
window.scrollTo(coors[0]-150,coors[1]-150);
// switch the textarea to a TinyMCE instance
tinyMCE.execCommand('mceAddControl',false,TrId+"tata");
return false;
}
function deleteLine(deleteLinkNode, typeStr) {
TrId = deleteLinkNode.id.substr(0,deleteLinkNode.id.length-10);
clickedRowContentValue = document.getElementById(TrId+"contentValue");
clickedRowContentValue.style.textDecoration="line-through";
//tinyMCE.execCommand('mceAddControl',false,TrId+'tata');
//tinyMCE.activeEditor.setContent('', {format : 'raw'});
//tinyMCE.execCommand('mceSetContent',false,'');
//tinyMCE.execCommand('mceRemoveControl',false,TrId+'tata');
document.getElementById(TrId+'tata').innerHTML = '';
clickedRowEditLink = document.getElementById(TrId+"editLink");
clickedRowEditLink.style.display="none";
clickedRowDeleteLink = document.getElementById(TrId+"deleteLink");
clickedRowDeleteLink.style.display="none";
clickedRowUndeleteLink = document.getElementById(TrId+"undeleteLink");
clickedRowUndeleteLink.style.display="inline";
}
function undeleteLine(undeleteLinkNode, typeStr) {
index = undeleteLinkNode.id.substr(0,undeleteLinkNode.id.length-12);
theContentValue=document.getElementById(index+"contentValue");
//theContentValueBackup=document.getElementById(index+"contentValueBackup");
//theContentValue.innerHTML = theContentValueBackup.innerHTML;
theContentValue.style.textDecoration="none";
theTaTa = document.getElementById(index+"tata");
theTaTa.innerHTML=theContentValue.innerHTML;
clickedRowEditLink = document.getElementById(TrId+"editLink");
clickedRowEditLink.style.display="inline";
clickedRowDeleteLink = document.getElementById(TrId+"deleteLink");
clickedRowDeleteLink.style.display="inline";
clickedRowUndeleteLink = document.getElementById(TrId+"undeleteLink");
clickedRowUndeleteLink.style.display="none";
}
function convertLiToTextarea(linkNode, typeStr) {
LiId = linkNode.id.substr(0,linkNode.id.length-8);
theLic = document.getElementById(LiId+"content");
theLic.style.display="none";
theTa = document.getElementById(LiId+"ta");
theTa.style.display="block";
tinyMCE.execCommand('mceAddControl',false,LiId+'tata');
return false;
}
function backToLi(okLinkNode) {
index = okLinkNode.id.substr(0,okLinkNode.id.length-6);
textareaDivId = index+"ta";
liDivId = index+"contentValue";
content = tinyMCE.activeEditor.getContent();
tinyMCE.execCommand('mceRemoveControl',false,textareaDivId+'ta');
theTextarea = document.getElementById(textareaDivId);
theTextarea.style.display="none";
theLi = document.getElementById(liDivId);
// replace this:
theLi.innerHTML = content;
theLi.parentNode.style.display = 'block';
return false;
}
function cancelBackToLi(cancelLinkNode) {
index = cancelLinkNode.id.substr(0,cancelLinkNode.id.length-10);
textareaDivId = index+"ta";
liDivId = index+"contentValue";
tinyMCE.execCommand('mceRemoveControl',false,textareaDivId+'ta');
theTextarea = document.getElementById(textareaDivId);
theTextarea.style.display="none";
theTaTa = document.getElementById(textareaDivId+"ta");
theLi = document.getElementById(liDivId);
theLi.parentNode.style.display = 'block';
theTaTa.innerHTML = theLi.innerHTML;
// if unused new row, just hide it completely (delete?)
if (theLi.innerHTML=="") {
theUnusedRow = document.getElementById(index);
theUnusedRow.style.display="none";
}
return false;
}
function submitPage() {
theForm = document.getElementById("editForm");
theButtonWeWantToClick = document.getElementById("primaryAction");
theHiddenInput = document.createElement("input")
theHiddenInput.type="hidden";
theHiddenInput.name=theButtonWeWantToClick.name;
theHiddenInput.value=theButtonWeWantToClick.name;
theForm.appendChild(theHiddenInput);
theForm.submit();
}
function findPos(obj)
{
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft
curtop = obj.offsetTop
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
}
return [curleft,curtop];
}
-->
</script>

706
webapp/web/js/ents_edit.js Normal file
View file

@ -0,0 +1,706 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
/* this code uses:
dwrutil in util.js
vitro.js
detect.js
*/
dojo.require("dojo.io.*");
dojo.require("dojo.event.*");
//DWREngine.setErrorHandler(function(data){alert("DWREngine error: " + data);});
//DWREngine.setWarningHandler(function(data){alert("DWREngine warning: " + data);});
/*
ents_edit.js has several tasks:
1) fill up the property table with one row for each ents2ents record
2) delete ents2ents if requested to
3) add a form to allow a new ents2ents relations to be created
4) bring up a form to edit an existing ents2ents
The html form for tasks 3 and 4 is from a div with id="propertydiv" on
the ents_edit.JSP ( <-- notice, it's on the JSP ). See the js function
getForm().
There was a problem where the DWR calls were throwing error messages
for larger (but not unreasonably large) sets of entity data. Updating to DWR
2.0rc2.8 did not fix this. The current solution is a servlet that
returns a JSON string for just the entitiy list.
DWR is still used to get info about the entity and the list of ents2ents.
CHANGES
2006-11-21 bdc34: removing the 'new entity' button, added comments
*/
var gEntityUri; //used to hold the URI of the entity being edited
var gProperty; // used to hold property on form
var gEntity; //entity that this page is editing
var editingNewProp = false; //true when editing a new property
var gVClassUri = null;
//hash: PropertyDWR.propertyId+"D" or "R" (for domain or range) --> obj: PropertyDWR
var gPropertyHash;
//holds the xhtmlrequest so we can do an abort
var gEntRequest = null;
var justwritenProp = null;
var justwritenTr = null;
if( vitroJsLoaded === undefined || vitroJsLoaded === null ){
alert("ents_edit.js needs to have the code from vitro.js loaded first");
}
var rowId = 1;
function getNextRowId() {
rowId++;
return rowId;
}
/** This refreshes the dynamic parts of the page.
It is also called on page load. */
function update( ) {
gEntityUri = getEntityUriFromPage();
abortExistingEntRequest();
clearProp();
updateTable();
updateEntityAndPropHash();
var but = $("newPropButton");
if( but ) { but.disabled = false; }
}
/** called when the property editing form is dismissed */
function clearProp() {
abortExistingEntRequest();
var clearMap={sunrise:"",sunset: ""};
editingNewProp = false;
gVClassUri = null;
DWRUtil.setValues( clearMap );
clear($("propertyList"));
clear($("vClassList"));
var ele = $("entitiesList");
while( ele != null && ele.length > 0){
ele.remove(0);
}
}
/*****************************************************************
* This updates the gPropertyHash and gEntity.
*****************************************************************/
function updateEntityAndPropHash(){
gPropertyHash = null;
gProperty = null;
gEntity = null;
/* This is the method that is called to set gEntity and then get ents2ents properties */
var setGEntity = function(entityObj){
gEntity=entityObj;
//once we set the gEntity we can get the ents2ents properties.
//PropertyDWR.getAllPropInstByVClass(setPropertyHash, entityObj.VClassURI );
if( entityObj != null && 'URI' in entityObj )
PropertyDWR.getAllPossiblePropInstForIndividual(setPropertyHash, entityObj.URI);
//else
//alert("could not find an individual, usually this means that there is no type for the URI");
};
/* This is the method that builds the gPropertyHash. It is called by setGEntity() */
var setPropertyHash = function(propArray) {
if( propArray == null || propArray.length < 1 ) {
gPropertyHash = null; /* propArray might be null if we have no properties in the system */
}else{
gPropertyHash = new Object();
for(var i = 0; i < propArray.length; i++) {
var hashid = propArray[i]["propertyURI"] ;
if( propArray[i].subjectSide ){
hashid = hashid + 'D';
} else {
hashid = hashid + 'R';
}
gPropertyHash[ hashid ] = propArray[i];
}
}
};
//get the gEntity and then build the gPropertyHash
EntityDWR.entityByURI(setGEntity, gEntityURI);
}
/*****************************************************************
set up some kind of warning that there are no properties in the system
*****************************************************************/
function doNoPropsWarning(){
alert(
"There are no object properties in the system.\n\n"+
"This is most likely because you have just finished installing. "+
"The button you have clicked adds a new object property statement relating this individual " +
"to another individual. If you are looking to add new object properties to the " +
"system, look under the 'About' menu.");
var but = $("newPropButton");
if( but ) { but.disabled = true; }
}
/*****************************************************************
because dwr calls are async we have a callback
*****************************************************************/
function updateTable(callback) {
var cb = callback;
function fillTable(props) {
DWRUtil.removeAllRows("propbody");
/* This makes the row that gets added to the ents_edit form for each ents2ents object. */
addRows($("propbody"), props,
[getDomain, getProperty, getRange, getEdit, getDelete],
makeTr);
var newPropTr = $("justwritenTr");
if( newPropTr != null ){
Fat.fade_element( "justwritenTr" );
}
if(cb !== undefined && cb !== null ) { cb(); }
}
PropertyDWR.getExistingProperties(fillTable,gEntityURI);
}
/**************************************************************************/
/* ******************** table column builders *****************************/
/* Change these functions to change the way the html table gets built *****/
/* in the addRows() func each of these will get called and wrapped in a <tr>
to make the row to stick into the table */
var getDomain = function(prop) {
return prop.subjectName;
};
var getProperty = function(prop) {
return makePropLinkElement(prop.propertyURI, prop.domainPublic);
};
var getRange = function(prop) {
return makeEntLinkElement(prop.objectEntURI, prop.objectName);
};
var getDelete = function(prop) {
var quote = new RegExp('\'','g');
var dquote = new RegExp('"','g');
return '<input type="button" value="Delete" class="form-button" ' +
'onclick="deleteProp(' +
'\'' + cleanForString(prop.subjectEntURI) + '\', ' +
'\'' + cleanForString(prop.propertyURI) + '\', ' +
'\'' + cleanForString(prop.objectEntURI) + '\', ' +
'\'' + cleanForString(prop.objectName) + '\', ' +
'\'' + cleanForString(prop.domainPublic) + '\' )">';
};
var getEdit = function(prop){
var quote = new RegExp('\'','g');
return '<input type="button" value="Edit" class="form-button" '+
'onclick="editTable(this,' +
'\''+ cleanForString(prop.subjectEntURI)+'\', ' +
'\''+ cleanForString(prop.propertyURI) +'\', ' +
'\''+ cleanForString(prop.objectEntURI) +'\')">';
};
var quote = new RegExp('\'','g');
var dquote = new RegExp('"','g');
function cleanForString(strIn){
var strOut = strIn.replace(quote, '\\\'');
strOut = strOut.replace(dquote, '&quot;');
return strOut;
}
/****************************************************************
This makeTr is a function with access to a closure that
includes the vars previousPropName and currentClass.
All of this work is to get the table row color to change when
we start drawing a row for a property that is different than the
previous row.
*****************************************************************/
var makeTr = (function(){ /* outer func */
// the reason for the outer func is to capture these values in a closure
// This allows us to have a func that has state associated with it
var previousPropName = "-1";
var currentClass = "form-row-even";
//each time makeTr() is called this is the code that gets executed.
return (function(prop) {/* inner func */
if( getProperty(prop) != previousPropName ){
previousPropName = getProperty(prop);
currentClass=(currentClass=="form-row-even"?"form-row-odd":"form-row-even");
}
tr = document.createElement("tr");
//tr.id = "proprow" + prop.ents2entsId;
tr.className = currentClass;
if( justwritenProp != null &&
justwritenProp.subjectEntURI == prop.subjectEntURI &&
justwritenProp.propertyURI == prop.propertyURI &&
justwritenProp.objectEntURI == prop.objectEntURI){
tr.id ="justwritenTr";
justwritenProp = null;
}
return tr;
});/*close inner function*/
} )(); /*close and call outer function to return the inner function */
/* **************** end table column builders **************** */
/****************************************************************
******** Functions for the Property Editing Form **************
*****************************************************************/
/* called when Edit button is clicked */
function editTable(inputElement, subjectURI, predicateURI, objectURI){
var rowIndex = inputElement.parentNode.parentNode.rowIndex-1 ;
var table = $("propbody");
table.deleteRow( rowIndex );
table.insertRow(rowIndex);
table.rows[rowIndex].insertCell(0);
var vform = getForm();
table.rows[rowIndex].cells[0].appendChild( vform );
table.rows[rowIndex].cells[0].colSpan = tableMaxColspan( table );
vform.style.display="block";
PropertyDWR.getProperty(fillForm, subjectURI, predicateURI, objectURI);
inputElement.parentNode.parentNode.style.display="none";
}
/** called when Delete button is clicked */
function deleteProp( subjectURI, predicateURI, objectURI, objectName, predicateName) {
if( PropertyDWR.deleteProp ){
if (confirm("Are you sure you want to delete the property\n"
+ objectName + " " + predicateName + "?")) {
PropertyDWR.deleteProp(update, subjectURI, predicateURI, objectURI);
}
} else {
alert("Deletion of object property statements is disabled.");
}
}
/*****************************************************************
adds the editing form <tr> to the propeties table
*****************************************************************/
function appendPropForm(tr, colspan ){
var form = getForm();
while(tr.cells.length > 0 ){
tr.deleteCell(0);
}
var td = tr.insertCell(-1);
td.appendChild( form );
if( colspan !== undefined && colspan > 0){
td.colSpan=colspan;
}
form.style.display="block";
}
/*****************************************************************
This gets called when the button to make a new property
for the entity is pressed.
*****************************************************************/
function newProp() {
if( gPropertyHash == null || gPropertyHash.length < 1 ) {
/* propArray might be null if we have no properties in the system */
doNoPropsWarning();
}else{
var innerNew = function (){
var newP = {};
newP.domainClass = gEntity.vClassId;
newP.subjectName = gEntity.name;
newP.subjectEntURI = gEntity.URI;
fillForm( newP );
editingNewProp = true;
fillRangeVClassList();
var table = $("propbody");
var tr = table.insertRow(0);
tr.id = "newrow";
appendPropForm( tr, tableMaxColspan( table ) );
//table.insertBefore(tr, table.rows[0]);
};
updateTable( innerNew );
}
}
/****************************************************************
Fills out the property edit form with the given property
*****************************************************************/
function fillForm(aprop) {
clearProp();
gProperty = aprop;
var vclass = gProperty.domainClass;
DWRUtil.setValues(gProperty);
setDateValue("sunset", gProperty.sunset );
setDateValue("sunrise", gProperty.sunrise );
toggleDisabled("newPropButton");
fillPropList(vclass); // this will also fill the vclass and ents lists
}
/****************************************************************
This will fill the select list will all of the properties found
in the gPropertyHash and then trigger a update of the vClasList
******************************************************************/
function fillPropList(classId) {
/* This function fills up the form's select list with options
Notice that the option id is the propertyid + 'D' or 'R'
so that domain and range properties can be distinguished */
var propList = $("propertyList");
clear(propList);
//add properties as options
for( var i in gPropertyHash ) {
var prop = gPropertyHash[i];
var text = "";
var value = prop.propertyURI;
if(prop.subjectSide){
text= prop.domainPublic;
if (prop.rangeClassName != null) {
text += " ("+prop.rangeClassName +")";
}
value = value + 'D';
} else {
text= prop.rangePublic;
if (prop.domainClassName != null) {
text += " ("+prop.domainClassName+")";
}
value = value + 'R';
}
var opt = new Option(text, value);
if( gProperty.propertyURI == prop.propertyURI ){
opt.selected = true;
}
propList.options[propList.options.length] = opt;
}
fillRangeVClassList( null );
}
/*****************************************************************
Fill up the range VClass list on the property editing form.
If propId is null then the one on the property select list will be used
*****************************************************************/
function fillRangeVClassList( propId ){
//If propId is null then the one on the property select list will be used
if( propId == null ) { propId = DWRUtil.getValue("propertyList");}
//clear the list and put the loading message up
var vclassListEle = $("vClassList");
clear(vclassListEle);
vclassListEle.options[vclassListEle.options.length] = new Option("Loading...",-10);
//vclassListEle.options[0].selected = true;
//vclassListEle.options[vclassListEle.options.length] = new Option("Crapping...",-15);
var prop = gPropertyHash[propId];
VClassDWR.getVClasses(
function(vclasses){
addVClassOptions( vclasses );
},
prop.domainClassURI, prop.propertyURI, prop.subjectSide);
}
/****************************************************************
Adds vClasses to the vClassList and trigger an update of
the entitiesList.
****************************************************************/
function addVClassOptions( vclassArray ){
// DWRUtil.addOptions("entitiesList",null);
var vclassEle = $("vClassList");
clear( vclassEle );
vclassEle.disabled = false;
if( vclassArray == null || vclassArray.length < 1){
vclassEle.disabled = true;
entsEle = $("entitiesList");
clear(entsEle);
var msg="There are no entities defined yet that could fill this role";
var opt = new Option(msg,-1);
entsEle.options[entsEle.options.length] = opt;
entsEle.disabled = true;
return;
}
addOptions("vClassList", vclassArray,
function(vclass){ return vclass.URI; },
function(vclass){
var count = "";
if( vclass.entityCount != null &&
vclass.entityCount >= 0){
count = " ("+vclass.entityCount+")";
}
return vclass.name+count;
});
//attempt to set the selected option to the current vclass
var vclassURI = null;
var prop = gPropertyHash[ DWRUtil.getValue("propertyList") ];
if( gProperty.propertyURI == prop.propertyURI ){
vclassURI = gProperty.rangeClassURI;
DWRUtil.setValue(vclassEle, vclassURI );
//here we were unable to set the vclass select option to the vclassid
//of the entity. this means that the vclass of the entity is not one that
//is permited by the PropertyInheritance and other restrictions.
if( DWRUtil.getValue(vclassEle) != vclassURI){
alert("This entity's class does not match the class of this property. This is usually the "+
"result of the class of the entity having been changed. Properties that were added when " +
"this entity had the old class still reflect that value.\n" +
"In general the vitro system handles this but the editing of these misaligned records "+
"is not fully supported.\n" );
}
}
fillEntsList(vclassEle );
}
/*****************************************************************
Fill up the entity list in a property editing form.
The propId should have the id + 'D' or 'R' to
indicate domain or range.
*****************************************************************/
function fillEntsList( vclassEle ){
if( vclassEle == null )
vclassEle = $("vClassList");
var vclassUri = DWRUtil.getValue( vclassEle );
if( vclassUri == gVClassUri )
return;
else
gVClassUri = vclassUri;
var entsListEle = $("entitiesList");
clear(entsListEle);
entityOptToSelect = null;
entsListEle.disabled = true;
entsListEle.options[entsListEle.options.length] = new Option("Loading...",-12);
entsListEle.options[entsListEle.options.length-1].selected = true;
if( vclassUri ){
//Notice that this is using the edu.cornell.mannlib.vitro.JSONServlet
var base = getURLandContext();
//these are parameters to the dojo JSON call
var bindArgs = {
url: "dataservice?getEntitiesByVClass=1&vclassURI="+encodeUrl(vclassUri),
error: function(type, data, evt){
if( type == null ){ type = "none" ; }
if( data == null ){ data = "none" ; }
if( evt == null ){ evt = "none" ; }
alert("An error occurred while attempting to get the individuals of vclass "
+ vclassUri + "\ntype: " + type +"\ndata: "+
data +"\nevt: " + evt );
},
load: function(type, data, evt){
//clear here since we will be using addEntOptions for multiple adds
// var entsListEle = $("entitiesList");
// clear(entsListEle);
addEntOptions(data, -1);
},
mimetype: "text/json"
};
abortExistingEntRequest();
gEntRequest = dojo.io.bind(bindArgs);
} else {
clear(entsListEle);
}
}
/** add entities in entArray as options elements to select element "Individual" */
function addEntOptions( entArray ){
var entsListEle = $("entitiesList");
if( entArray == null || entArray.length == 0){
clear(entsListEle);
return;
}
var previouslySelectedEntUri = gProperty.objectEntURI;
//check if the last element indicates that there are more results to get
contObj = null;
if( entArray != null && entArray[entArray.length-1].nextUrl != null ){
contObj = entArray.pop();
}
var CUTOFF = 110; //shorten entity names longer then this value.
var foundEntity = false;
var text;
var value;
var opt;
for (var i = 0; i < entArray.length; i++) {
text = entArray[i].name;
if( text.length > CUTOFF){ text = text.substr(0,CUTOFF) + "..."; }
value = entArray[i].URI;
opt = new Option(text, value);
entsListEle.options[entsListEle.options.length] = opt;
if( previouslySelectedEntUri == value ){
entityOptToSelect = opt;
}
}
if( contObj != null ){
entsListEle.item(0).text = entsListEle.item(0).text + ".";
addMoreEntOptions( contObj );
} else {
gEntRequests = [];
entsListEle.disabled = false;
if( entsListEle.length > 0 && entsListEle.item(0).value == -12){
entsListEle.remove(0);
}
if( entityOptToSelect != null ){
entityOptToSelect.selected = true;
}
}
}
var entityOptToSelect =null;
/*
* Add more entity options to the list if there are more on the request
*
example of a continueObj
{"nextUrl":"http://localhost:8080/vivo/dataService?getEntitiesByVClass=1&vclassId=318",
"entsInVClass":2773}
*/
function addMoreEntOptions( continueObj ){
if( continueObj.nextUrl != null ){
var bindArgs = {
url: continueObj.nextUrl,
error: function(type, data, evt){
if( type == null ){ type = "none" ; }
if( data == null ){ data = "none" ; }
if( evt == null ){ evt = "none" ; }
alert("An error addMoreEntOptions()"+"\ntype: " + type +"\ndata: "+
data +"\nevt: " + evt );
},
load: function(type, data, evt){
addEntOptions( data );
},
mimetype: "text/json"
};
abortExistingEntRequest();
gEntRequest = dojo.io.bind(bindArgs);
}
}
/*
Entities are now sent back as JSON in groups of 556. This is to defend against
odd network effects and browser flakyness. DWR was choaking on large datasets
and isn't very flexable so I moved to JSON. That still caused problems with
large data sets ( size > 1500 ) so I'm breaking them up.
The reply from the JSON servlet is a JSON array. If the last item in the
array lacks a "id" property then it is information about additional entites.
If the last item in the JSON array has an id then you don't have to go back
for more results.
Example:
[ ...
{"moniker":"recent journal article", "name":"{beta}2 and {beta}4
Subunits of BK Channels Confer Differential Sensitivity to Acute
Modulation by Steroid Hormones.", "vClassId":318, "id":18120},
{"resultGroup":3,"entsInVClass":2773,"nextResultGroup":4,"standardReplySize":556}
]
*/
/****************************************************************
Check to see if property edit form is valid
*****************************************************************/
function validateForm(){
var dateEx = "\nDates should be in the format YYYY-MM-DD";
var value = DWRUtil.getValue("sunrise");
try{
var date = parseDateString(value);
}catch(e){ date = null; }
if( value && value.length > 0 && ! isDate(date)) {
alert( "Surise date " + value + " is invalid: \n" + date + dateEx);
return false;
}
value = DWRUtil.getValue("sunset");
try{
date = parseDateString(value);
}catch(e){ date = null; }
if( value && value.length > 0 && ! isDate(date)) {
alert( "Sunset date " + value + " is invalid: \n" + date + dateEx);
return false;
}
return true;
}
/**************************************************************
Write or update ents2ents row.
***************************************************************/
function writeProp() {
if( PropertyDWR.insertProp == null ){
alert("Writing of properties disabled for security reasons.");
return;
}
if( !validateForm() ) { return; }
var prop = gPropertyHash[DWRUtil.getValue("propertyList")];
var newP = {};
var oldP = gProperty;
newP.propertyURI = prop.propertyURI;
var selected = DWRUtil.getValue("entitiesList");
newP.subjectEntURI= gEntity.URI;
newP.objectEntURI = selected ;
try{
var date = parseDateString( DWRUtil.getValue("sunrise") );
newP.sunrise = ( isDate( date ) ? date : null );
}catch(e){ newP.sunrise = null; }
try{
var date = parseDateString( DWRUtil.getValue("sunset") );
newP.sunset = ( isDate( date ) ? date : null );
}catch(e){ newP.sunset = null; }
var callback = function(result){
editingNewProp = false;
justwritenProp = newP;
update(); };
if( editingNewProp ){
newP.ents2entsId = -1;
PropertyDWR.insertProp(callback, newP );
} else {
var afterDelete=
function(result){
PropertyDWR.insertProp(callback, newP);
};
PropertyDWR.deleteProp(afterDelete,
gProperty.subjectEntURI,
gProperty.propertyURI,
gProperty.objectEntURI);
}
}
/************ Things that happen on load *****************************/
addEvent(window, 'load', update);
/********************* some utilities ***********************************/
/* this clones the property edit from a div on the ents_edit.jsp */
function getForm(){ return $("propeditdiv").cloneNode(true); }
/* a function to display a lot of info about an object */
function disy( obj, note ){ alert( (note!==null?note:"") + DWRUtil.toDescriptiveString(obj, 3));}
/* attempts to get the URI of the entity being edited */
function getEntityUriFromPage(){
return document.getElementById("entityUriForDwr").nodeValue;
}
function abortExistingEntRequest(){
if( gEntRequest != null ){
if( gEntRequest.abort ){
gEntRequest.abort();
}else{
alert("No abort function found on gEntRequest");
}
gEntRequest = null;
}
}

118
webapp/web/js/ents_retry.js Normal file
View file

@ -0,0 +1,118 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
if( vitroJsLoaded == null ){
alert("seminar.js needs to have the code from vitro.js loaded first");
}
addEvent(window, 'load', init);
function init(){
// if ($('monikerSelect').options.length=1) {
// $('monikerSelectAlt').disabled = false;
// }else{
// $('monikerSelectAlt').disabled = true;
// }
$('monikerSelect').onchange = checkMonikers;
update();
}
function update(){ //updates moniker list when type is changed
DWRUtil.useLoadingMessage();
EntityDWR.monikers(createList, document.getElementById("field2Value").value );
}
function createList(data) { //puts options in moniker select list
fillList("monikerSelect", data, getCurrentMoniker() );
var ele = $("monikerSelect");
var opt = new Option("none","");
ele.options[ele.options.length] = opt;
var opt = new Option("[new moniker]","");
ele.options[ele.options.length] = opt;
DWRUtil.setValue("monikerSelect",getCurrentMoniker()); // getCurrentMoniker() is defined on jsp
checkMonikers();
}
function checkMonikers(){ //checks if monikers is on [new moniker] and enables alt field
var sel = $('monikerSelect');
if( sel.value == "" || sel.options.length <= 1){
$('monikerSelectAlt').disabled = false;
}else{
$('monikerSelectAlt').disabled = true;
}
}
function fillList(id, data, selectedtext) {
var ele = $(id);
if (ele == null) {
alert("fillList() can't find an element with id: " + id + ".");
throw id;
}
ele.options.length = 0; // Empty the list
if (data == null) { return; }
for (var i = 0; i < data.length; i++) {
var text = DWRUtil.toDescriptiveString(data[i]);
var value = text;
var opt = new Option(text, value);
if (selectedtext != null && selectedtext == text){
opt.selected=true;
}
ele.options[ele.options.length] = opt;
}
}

11
webapp/web/js/jquery.js vendored Normal file

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,123 @@
/*
* jQuery Color Animations
* Copyright 2007 John Resig
* Released under the MIT and GPL licenses.
*/
(function(jQuery){
// We override the animation for all of these color styles
jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
jQuery.fx.step[attr] = function(fx){
if ( fx.state == 0 ) {
fx.start = getColor( fx.elem, attr );
fx.end = getRGB( fx.end );
}
fx.elem.style[attr] = "rgb(" + [
Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
].join(",") + ")";
}
});
// Color Conversion functions from highlightFade
// By Blair Mitchelmore
// http://jquery.offput.ca/highlightFade/
// Parse strings looking for color tuples [255,255,255]
function getRGB(color) {
var result;
// Check if we're already dealing with an array of colors
if ( color && color.constructor == Array && color.length == 3 )
return color;
// Look for rgb(num,num,num)
if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];
// Look for rgb(num%,num%,num%)
if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];
// Look for #a0b1c2
if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];
// Look for #fff
if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];
// Otherwise, we're most likely dealing with a named color
return colors[jQuery.trim(color).toLowerCase()];
}
function getColor(elem, attr) {
var color;
do {
color = jQuery.curCSS(elem, attr);
// Keep going until we find an element that has color, or we hit the body
if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
break;
attr = "backgroundColor";
} while ( elem = elem.parentNode );
return getRGB(color);
};
// Some named colors to work with
// From Interface by Stefan Petre
// http://interface.eyecon.ro/
var colors = {
aqua:[0,255,255],
azure:[240,255,255],
beige:[245,245,220],
black:[0,0,0],
blue:[0,0,255],
brown:[165,42,42],
cyan:[0,255,255],
darkblue:[0,0,139],
darkcyan:[0,139,139],
darkgrey:[169,169,169],
darkgreen:[0,100,0],
darkkhaki:[189,183,107],
darkmagenta:[139,0,139],
darkolivegreen:[85,107,47],
darkorange:[255,140,0],
darkorchid:[153,50,204],
darkred:[139,0,0],
darksalmon:[233,150,122],
darkviolet:[148,0,211],
fuchsia:[255,0,255],
gold:[255,215,0],
green:[0,128,0],
indigo:[75,0,130],
khaki:[240,230,140],
lightblue:[173,216,230],
lightcyan:[224,255,255],
lightgreen:[144,238,144],
lightgrey:[211,211,211],
lightpink:[255,182,193],
lightyellow:[255,255,224],
lime:[0,255,0],
magenta:[255,0,255],
maroon:[128,0,0],
navy:[0,0,128],
olive:[128,128,0],
orange:[255,165,0],
pink:[255,192,203],
purple:[128,0,128],
violet:[128,0,128],
red:[255,0,0],
silver:[192,192,192],
white:[255,255,255],
yellow:[255,255,0]
};
})(jQuery);

View file

@ -0,0 +1,39 @@
/* Copyright (c) 2006 Mathias Bank (http://www.mathias-bank.de)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* Thanks to Hinnerk Ruemenapf - http://hinnerk.ruemenapf.de/ for bug reporting and fixing.
*/
jQuery.extend({
/**
* Returns get parameters.
*
* If the desired param does not exist, null will be returned
*
* @example value = $.getURLParam("paramName");
*/
getURLParam: function(strParamName){
var strReturn = "";
var strHref = window.location.href;
var bFound=false;
var cmpstring = strParamName + "=";
var cmplen = cmpstring.length;
if ( strHref.indexOf("?") > -1 ){
var strQueryString = strHref.substr(strHref.indexOf("?")+1);
var aQueryString = strQueryString.split("&");
for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
if (aQueryString[iParam].substr(0,cmplen)==cmpstring){
var aParam = aQueryString[iParam].split("=");
strReturn = aParam[1];
bFound=true;
break;
}
}
}
if (bFound==false) return null;
return strReturn;
}
});

View file

@ -0,0 +1,48 @@
.ac_results {
padding: 0px;
border: 1px solid black;
background-color: white;
overflow: hidden;
z-index: 99999;
}
.ac_results ul {
width: 100%;
list-style-position: outside;
list-style: none;
padding: 0;
margin: 0;
}
.ac_results li {
margin: 0px;
padding: 2px 5px;
cursor: default;
display: block;
/*
if width will be 100% horizontal scrollbar will apear
when scroll mode will be used
*/
/*width: 100%;*/
font: menu;
font-size: 12px;
/*
it is very important, if line-height not setted or setted
in relative units scroll will be broken in firefox
*/
line-height: 16px;
overflow: hidden;
}
.ac_loading {
background: white url('indicator.gif') right center no-repeat;
}
.ac_odd {
background-color: #eee;
}
.ac_over {
background-color: #0A246A;
color: white;
}

Some files were not shown because too many files have changed in this diff Show more