Merge branch 'develop' of github.com:vivo-project/Vitro into develop

This commit is contained in:
Brian Caruso 2013-07-08 13:52:05 -04:00
commit 467256e3ba
406 changed files with 8250 additions and 4587 deletions

View file

@ -649,6 +649,26 @@
remote_userID remote_userID
</td> </td>
</tr> </tr>
<tr>
<td colspan="2">
Tell Vitro to generate HTTP headers on its responses to facilitate caching the
profile pages that it creates. This can improve performance, but it can also
result in serving stale data. Default is false if not set.
For more information, see the VIVO wiki page:
<a href="https://wiki.duraspace.org/display/VIVO/Use+HTTP+caching+to+improve+performance">
Use HTTP caching to improve performance </a>
</td>
</tr>
<tr class="odd_row">
<td>
http.createCacheHeaders
</td>
<td>
true
</td>
</tr>
<tr> <tr>
<td colspan="2"> <td colspan="2">
Force VIVO to use a specific language or Locale instead of those Force VIVO to use a specific language or Locale instead of those

View file

@ -250,6 +250,11 @@
<copyField source="nameRaw" dest="acNameStemmed" /> <copyField source="nameRaw" dest="acNameStemmed" />
<copyField source="nameRaw" dest="nameText" /> <copyField source="nameRaw" dest="nameText" />
<!-- nameLowercaseSingleValued is not copied from nameRaw becasue nameRaw might have multiple values --> <!-- nameLowercaseSingleValued is not copied from nameRaw becasue nameRaw might have multiple values -->
<!-- field for hash signature, used for comparing to versions from external caches -->
<field name="etag" type="string" stored="true" indexed="false" multiValued="false" />
<!-- **************************** End Vitro Fields *************************** --> <!-- **************************** End Vitro Fields *************************** -->
<!-- **************************** Dynamic Fields *************************** --> <!-- **************************** Dynamic Fields *************************** -->

View file

@ -856,18 +856,14 @@
type header if posted in the body. For example, curl now type header if posted in the body. For example, curl now
requires: -H 'Content-type:text/xml; charset=utf-8' requires: -H 'Content-type:text/xml; charset=utf-8'
--> -->
<requestHandler name="/update" <requestHandler name="/update"
class="solr.XmlUpdateRequestHandler"> class="solr.XmlUpdateRequestHandler">
<!-- See below for information on defining <!-- Run the etag processor on each update request. -->
updateRequestProcessorChains that can be used by name
on each Update Request
-->
<!--
<lst name="defaults"> <lst name="defaults">
<str name="update.processor">dedupe</str> <str name="update.processor">etag</str>
</lst> </lst>
--> </requestHandler>
</requestHandler>
<!-- Binary Update Request Handler <!-- Binary Update Request Handler
http://wiki.apache.org/solr/javabin http://wiki.apache.org/solr/javabin
--> -->
@ -1480,6 +1476,23 @@
</updateRequestProcessorChain> </updateRequestProcessorChain>
--> -->
<!-- ETag generation
Creates the "etag" field on the fly based on a hash of all other
fields.
-->
<updateRequestProcessorChain name="etag">
<processor class="solr.processor.SignatureUpdateProcessorFactory">
<bool name="enabled">true</bool>
<str name="signatureField">etag</str>
<bool name="overwriteDupes">false</bool>
<str name="signatureClass">solr.processor.Lookup3Signature</str>
</processor>
<processor class="solr.LogUpdateProcessorFactory" />
<processor class="solr.RunUpdateProcessorFactory" />
</updateRequestProcessorChain>
<!-- Response Writers <!-- Response Writers
http://wiki.apache.org/solr/QueryResponseWriter http://wiki.apache.org/solr/QueryResponseWriter

View file

@ -8,8 +8,10 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Set;
import javax.servlet.Filter; import javax.servlet.Filter;
import javax.servlet.ServletContextListener; import javax.servlet.ServletContextListener;
@ -90,6 +92,18 @@ import org.xml.sax.SAXException;
* Check each <filter-class/> to insure that the class can be loaded and * Check each <filter-class/> to insure that the class can be loaded and
* instantiated and assigned to Filter. * instantiated and assigned to Filter.
* *
* ------
*
* A <servlet/> tag for every <servlet-mapping/> tag
*
* I can't find a mention of this in the spec, but Tomcat complains and refuses
* to load the app if there is a <servlet-mapping/> tag whose <servlet-name/> is
* not matched by a <servlet-name/> in a <servlet/> tag.
*
* Get sets of all <servlet-name/> tags that are specified in <servlet/> and
* <servlet-mapping/> tags. There should not be any names in the
* servlet-mappings that are not in the servlets.
*
* --------------------------------------------------------------------- * ---------------------------------------------------------------------
* *
* Although this class is executed as a JUnit test, it doesn't have the usual * Although this class is executed as a JUnit test, it doesn't have the usual
@ -101,7 +115,7 @@ import org.xml.sax.SAXException;
* *
* --------------------------------------------------------------------- * ---------------------------------------------------------------------
* *
* Since this is not executed as part of the standard Vitro unit tests, it also * Since this is not executed as part of the standard Vitro unit tests, it also
* cannot use the standard logging mechanism. Log4J has not been initialized. * cannot use the standard logging mechanism. Log4J has not been initialized.
* *
*/ */
@ -166,6 +180,7 @@ public class CheckContainerNeutrality {
checkListenerClasses(); checkListenerClasses();
checkFilterClasses(); checkFilterClasses();
checkTaglibLocations(); checkTaglibLocations();
checkServletNames();
if (!messages.isEmpty()) { if (!messages.isEmpty()) {
fail("Found these problems with '" + webXmlFile.getCanonicalPath() fail("Found these problems with '" + webXmlFile.getCanonicalPath()
@ -234,6 +249,25 @@ public class CheckContainerNeutrality {
} }
} }
private void checkServletNames() {
Set<String> servletNames = new HashSet<String>();
for (Node n : findNodes("//j2ee:servlet/j2ee:servlet-name")) {
servletNames.add(n.getTextContent());
}
Set<String> servletMappingNames = new HashSet<String>();
for (Node n : findNodes("//j2ee:servlet-mapping/j2ee:servlet-name")) {
servletMappingNames.add(n.getTextContent());
}
servletMappingNames.removeAll(servletNames);
for (String name : servletMappingNames) {
messages.add("There is a <servlet-mapping> tag for <servlet-name>"
+ name + "</servlet-name>, but there is "
+ "no matching <servlet> tag.");
}
}
private String checkTaglibUri(String taglibUri, String taglibLocation) { private String checkTaglibUri(String taglibUri, String taglibLocation) {
File taglibFile = new File(webappDir, taglibLocation); File taglibFile = new File(webappDir, taglibLocation);
if (!taglibFile.isFile()) { if (!taglibFile.isFile()) {

View file

@ -9,6 +9,36 @@
====================================================================== --> ====================================================================== -->
<project name="vitroCore" default="describe"> <project name="vitroCore" default="describe">
<property environment="env" />
<!-- We must be using a suitable version of Java. -->
<fail>
<condition>
<not>
<or>
<equals arg1="1.7" arg2="${ant.java.version}" />
<equals arg1="1.8" arg2="${ant.java.version}" />
</or>
</not>
</condition>
The Vitro build script requires Java 7 or later.
Java system property java.version = ${java.version}
Java system property java.home = ${java.home}
JAVA_HOME environment variable = ${env.JAVA_HOME}
</fail>
<!-- We must be using a suitable version of Ant. -->
<fail>
<condition>
<not>
<antversion atleast="1.8" />
</not>
</condition>
The Vitro build script requires Ant 1.8 or later.
Ant property ant.version = ${ant.version}
Ant property ant.home = ${ant.home}
ANT_HOME environment variable = ${env.ANT_HOME}
</fail>
<!-- A product script will override appbase.dir, but not corebase.dir --> <!-- A product script will override appbase.dir, but not corebase.dir -->
<dirname property="corebase.dir" file="${ant.file.vitroCore}" /> <dirname property="corebase.dir" file="${ant.file.vitroCore}" />
@ -99,7 +129,7 @@
encoding="UTF8" encoding="UTF8"
includeantruntime="false" includeantruntime="false"
optimize="false" optimize="false"
source="1.6"> source="1.7">
<classpath refid="utility.compile.classpath" /> <classpath refid="utility.compile.classpath" />
</javac> </javac>
@ -137,7 +167,7 @@
</copy> </copy>
<!-- use the production Log4J properties, unless a debug version exists. --> <!-- use the production Log4J properties, unless a debug version exists. -->
<condition property="log4j.properties.file" value="debug.log4j.properties" else="default.log4j.properties"> <condition property="log4j.properties.file" value="debug.log4j.properties" else="log4j.properties">
<available file="${appbase.dir}/config/debug.log4j.properties" /> <available file="${appbase.dir}/config/debug.log4j.properties" />
</condition> </condition>
<copy file="${appbase.dir}/config/${log4j.properties.file}" <copy file="${appbase.dir}/config/${log4j.properties.file}"
@ -202,7 +232,7 @@
encoding="UTF8" encoding="UTF8"
includeantruntime="false" includeantruntime="false"
optimize="true" optimize="true"
source="1.6"> source="1.7">
<classpath refid="main.compile.classpath" /> <classpath refid="main.compile.classpath" />
</javac> </javac>
</target> </target>
@ -224,7 +254,7 @@
encoding="UTF8" encoding="UTF8"
includeantruntime="false" includeantruntime="false"
optimize="false" optimize="false"
source="1.6"> source="1.7">
<classpath refid="test.compile.classpath" /> <classpath refid="test.compile.classpath" />
</javac> </javac>

View file

@ -120,6 +120,19 @@ proxy.eligibleTypeList = http://www.w3.org/2002/07/owl#Thing
# #
RDFService.languageFilter = true RDFService.languageFilter = true
#
# Tell VIVO to generate HTTP headers on its responses to facilitate caching the
# profile pages that it creates.
#
# For more information, see
# https://wiki.duraspace.org/display/VIVO/Use+HTTP+caching+to+improve+performance
#
# Developers will likely want to leave caching disabled, since a change to a
# Freemarker template or to a Java class would not cause the page to be
# considered stale.
#
# http.createCacheHeaders = true
# #
# Force VIVO to use a specific language or Locale instead of those # Force VIVO to use a specific language or Locale instead of those
# specified by the browser. This affects RDF data retrieved from the model, # specified by the browser. This affects RDF data retrieved from the model,

View file

@ -20,7 +20,7 @@
# More information can be found here: # More information can be found here:
# http://logging.apache.org/log4j/1.2/manual.html # http://logging.apache.org/log4j/1.2/manual.html
# #
# The "production" version of this file is default.log4j.properties. # The "production" version of this file is log4j.properties.
# debug.log4j.properties exists will be used instead, if it exists, but is not stored in Subversion. # debug.log4j.properties exists will be used instead, if it exists, but is not stored in Subversion.
log4j.appender.AllAppender=org.apache.log4j.RollingFileAppender log4j.appender.AllAppender=org.apache.log4j.RollingFileAppender

View file

@ -10,6 +10,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount; import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDao; import edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
@ -101,13 +102,7 @@ public class LoginStatusBean {
} }
ServletContext ctx = session.getServletContext(); ServletContext ctx = session.getServletContext();
WebappDaoFactory wadf = (WebappDaoFactory) ctx WebappDaoFactory wadf = ModelAccess.on(ctx).getWebappDaoFactory();
.getAttribute("webappDaoFactory");
if (wadf == null) {
log.error("No WebappDaoFactory");
return null;
}
UserAccountsDao userAccountsDao = wadf.getUserAccountsDao(); UserAccountsDao userAccountsDao = wadf.getUserAccountsDao();
if (userAccountsDao == null) { if (userAccountsDao == null) {
log.error("No UserAccountsDao"); log.error("No UserAccountsDao");

View file

@ -25,7 +25,9 @@ import edu.cornell.mannlib.vedit.util.FormUtils;
import edu.cornell.mannlib.vitro.webapp.controller.Controllers; import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet; import edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess.ModelID;
import edu.cornell.mannlib.vitro.webapp.dao.jena.ModelContext; import edu.cornell.mannlib.vitro.webapp.dao.jena.ModelContext;
public class BaseEditController extends VitroHttpServlet { public class BaseEditController extends VitroHttpServlet {
@ -153,39 +155,32 @@ public class BaseEditController extends VitroHttpServlet {
} }
} }
protected String MODEL_ATTR_NAME = "jenaOntModel";
protected OntModel getOntModel( HttpServletRequest request, ServletContext ctx ) { protected OntModel getOntModel( HttpServletRequest request, ServletContext ctx ) {
// TODO: JB - This method gets the UNION FULL model from the session, if there is one,
// TODO and the BASE_TBOX model otherwise.
OntModel ontModel = null; OntModel ontModel = null;
try {
try { ontModel = ModelAccess.on(request.getSession()).getJenaOntModel();
ontModel = (OntModel) request.getSession().getAttribute(MODEL_ATTR_NAME);
} catch (Exception e) { } catch (Exception e) {
// ignoring any problems here - we're not really expecting // ignoring any problems here - we're not really expecting
// this attribute to be populated anyway // this attribute to be populated anyway
} }
if ( ontModel == null ) { if ( ontModel == null ) {
ontModel = (OntModel) ModelContext.getBaseOntModelSelector(ctx).getTBoxModel(); ontModel = ModelAccess.on(ctx).getOntModel(ModelID.BASE_TBOX);
} }
return ontModel; return ontModel;
} }
protected WebappDaoFactory getWebappDaoFactory(VitroRequest vreq) { protected WebappDaoFactory getWebappDaoFactory() {
WebappDaoFactory wadf = (WebappDaoFactory) getServletContext().getAttribute( return ModelAccess.on(getServletContext()).getBaseWebappDaoFactory();
"assertionsWebappDaoFactory");
if (wadf == null) {
log.info("Using vreq.getFullWebappDaoFactory()");
wadf = vreq.getFullWebappDaoFactory();
}
return wadf;
} }
protected WebappDaoFactory getWebappDaoFactory(VitroRequest vreq, String userURI) { protected WebappDaoFactory getWebappDaoFactory(String userURI) {
return getWebappDaoFactory(vreq).getUserAwareDaoFactory(userURI); return getWebappDaoFactory().getUserAwareDaoFactory(userURI);
} }
public String getDefaultLandingPage(HttpServletRequest request) { public String getDefaultLandingPage(HttpServletRequest request) {

View file

@ -1,7 +1,7 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ /* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vedit.util; package edu.cornell.mannlib.vedit.util;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -9,141 +9,145 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vedit.beans.EditProcessObject; import edu.cornell.mannlib.vedit.beans.EditProcessObject;
public class OperationUtils {
public class OperationUtils{
private static final Log log = LogFactory.getLog(OperationUtils.class
private static final Log log = LogFactory.getLog(OperationUtils.class.getName()); .getName());
public static void beanSetAndValidate(Object newObj, String field, String value, EditProcessObject epo){ public static void beanSetAndValidate(Object newObj, String field,
Class cls = (epo.getBeanClass() != null) ? epo.getBeanClass() : newObj.getClass(); String value, EditProcessObject epo) {
Class[] paramList = new Class[1]; Class<?> cls = (epo.getBeanClass() != null) ? epo.getBeanClass() : newObj
paramList[0] = String.class; .getClass();
boolean isInt = false; Class<?>[] paramList = new Class[1];
boolean isBoolean = false; paramList[0] = String.class;
Method setterMethod = null; boolean isInt = false;
try { boolean isBoolean = false;
setterMethod = cls.getMethod("set"+field,paramList); Method setterMethod = null;
} catch (NoSuchMethodException e) { try {
//let's try int setterMethod = cls.getMethod("set" + field, paramList);
paramList[0] = int.class; } catch (NoSuchMethodException e) {
try { // let's try int
setterMethod = cls.getMethod("set"+field,paramList); paramList[0] = int.class;
isInt = true; try {
} catch (NoSuchMethodException f) { setterMethod = cls.getMethod("set" + field, paramList);
//let's try boolean isInt = true;
paramList[0]=boolean.class; } catch (NoSuchMethodException f) {
try { // let's try boolean
setterMethod = cls.getMethod("set"+field,paramList); paramList[0] = boolean.class;
isBoolean = true; try {
log.debug("found boolean field "+field); setterMethod = cls.getMethod("set" + field, paramList);
} catch (NoSuchMethodException g) { isBoolean = true;
log.error("beanSet could not find an appropriate String, int, or boolean setter method for "+field); log.debug("found boolean field " + field);
} } catch (NoSuchMethodException g) {
log.error("beanSet could not find an appropriate String, int, or boolean setter method for "
} + field);
} }
Object[] arglist = new Object[1];
if (isInt) }
arglist[0] = Integer.decode(value); }
else if (isBoolean) Object[] arglist = new Object[1];
arglist[0] = (value.equalsIgnoreCase("TRUE")); if (isInt)
else arglist[0] = Integer.decode(value);
arglist[0] = value; else if (isBoolean)
try { arglist[0] = (value.equalsIgnoreCase("TRUE"));
setterMethod.invoke(newObj,arglist); else
} catch (Exception e) { arglist[0] = value;
log.error("Couldn't invoke method"); try {
log.error(e.getMessage()); setterMethod.invoke(newObj, arglist);
log.error(field+" "+arglist[0]); } catch (Exception e) {
} log.error("Couldn't invoke method");
} log.error(e.getMessage());
log.error(field + " " + arglist[0]);
/** }
* Takes a bean and clones it using reflection. }
* Any fields without standard getter/setter methods will not be copied.
* @param bean /**
* @return * Takes a bean and clones it using reflection. Any fields without standard
*/ * getter/setter methods will not be copied.
public static Object cloneBean (Object bean) { */
return cloneBean(bean, bean.getClass(), bean.getClass()); public static Object cloneBean(Object bean) {
} if (bean == null) {
throw new NullPointerException("bean may not be null.");
/** }
* Takes a bean and clones it using reflection. return cloneBean(bean, bean.getClass(), bean.getClass());
* Any fields without standard getter/setter methods will not be copied. }
* @param bean
* @return /**
*/ * Takes a bean and clones it using reflection. Any fields without standard
public static Object cloneBean (Object bean, Class beanClass, Class iface){ * getter/setter methods will not be copied.
Object newBean = null; */
try { public static Object cloneBean(final Object bean, final Class<?> beanClass,
newBean = beanClass.newInstance(); final Class<?> iface) {
Method[] beanMeths = iface.getMethods(); if (bean == null) {
for (int i=0; i<beanMeths.length ; ++i) { throw new NullPointerException("bean may not be null.");
Method beanMeth = beanMeths[i]; }
String methName = beanMeth.getName(); if (beanClass == null) {
if (methName.startsWith("get") throw new NullPointerException("beanClass may not be null.");
&& beanMeth.getParameterTypes().length == 0 ) { }
String fieldName = methName.substring(3,methName.length()); if (iface == null) {
Class returnType = beanMeth.getReturnType(); throw new NullPointerException("iface may not be null.");
try { }
Class[] args = new Class[1];
args[0] = returnType; class CloneBeanException extends RuntimeException {
Method setterMethod = iface.getMethod("set"+fieldName,args); public CloneBeanException(String message, Throwable cause) {
try { super(message + " <" + cause.getClass().getSimpleName()
Object fieldVal = beanMeth.invoke(bean,(Object[])null); + ">: bean=" + bean + ", beanClass="
try { + beanClass.getName() + ", iface=" + iface.getName(),
Object[] setArgs = new Object[1]; cause);
setArgs[0] = fieldVal; }
setterMethod.invoke(newBean,setArgs); }
} catch (IllegalAccessException iae) {
log.error(OperationUtils.class.getName() + Object newBean;
".cloneBean() " + try {
" encountered IllegalAccessException " + newBean = beanClass.getConstructor().newInstance();
" invoking " + } catch (NoSuchMethodException e) {
setterMethod.getName(), iae); throw new CloneBeanException("bean has no 'nullary' constructor.", e);
throw new RuntimeException(iae); } catch (InstantiationException e) {
} catch (InvocationTargetException ite) { throw new CloneBeanException("tried to create instance of an abstract class.", e);
log.error(OperationUtils.class.getName() + } catch (IllegalAccessException e) {
".cloneBean() " + throw new CloneBeanException("bean constructor is not accessible.", e);
" encountered InvocationTargetException" } catch (InvocationTargetException e) {
+ " invoking " throw new CloneBeanException("bean constructor threw an exception.", e);
+ setterMethod.getName(), ite); } catch (Exception e) {
throw new RuntimeException(ite); throw new CloneBeanException("failed to instantiate a new bean.", e);
} }
} catch (IllegalAccessException iae) {
log.error(OperationUtils.class.getName() + for (Method beanMeth : iface.getMethods()) {
".cloneBean() encountered " + String methName = beanMeth.getName();
" IllegalAccessException invoking " + if (!methName.startsWith("get")) {
beanMeths[i].getName(), iae); continue;
throw new RuntimeException(iae); }
} catch (InvocationTargetException ite) { if (beanMeth.getParameterTypes().length != 0) {
log.error(OperationUtils.class.getName() + continue;
".cloneBean() encountered " + }
" InvocationTargetException invoking " + String fieldName = methName.substring(3, methName.length());
beanMeths[i].getName(), ite); Class<?> returnType = beanMeth.getReturnType();
throw new RuntimeException(ite);
} catch (IllegalArgumentException iae) { Method setterMethod;
log.error(OperationUtils.class.getName() + try {
".cloneBean() encountered " + setterMethod = iface.getMethod("set" + fieldName, returnType);
" IllegalArgumentException invoking " + } catch (NoSuchMethodException nsme) {
beanMeths[i].getName(), iae); continue;
throw new RuntimeException(iae); }
}
} catch (NoSuchMethodException nsme){ Object fieldVal;
// ignore this field because there is no setter method try {
} fieldVal = beanMeth.invoke(bean, (Object[]) null);
} } catch (Exception e) {
} throw new CloneBeanException("failed to invoke " + beanMeth, e);
} catch (InstantiationException ie){ }
log.error("edu.cornell.mannlib.vitro.edit.utils.OperationUtils.cloneBean("+bean.getClass().toString()+") could not instantiate new instance of bean.");
log.error(ie.getStackTrace()); try {
} catch (IllegalAccessException iae){ Object[] setArgs = new Object[1];
log.error("edu.cornell.mannlib.vitro.edit.utils.OperationUtils.cloneBean("+bean.getClass().toString()+") encountered illegal access exception instantiating new bean."); setArgs[0] = fieldVal;
log.error(iae.getStackTrace()); setterMethod.invoke(newBean, setArgs);
} } catch (Exception e) {
return newBean; throw new CloneBeanException(
} "failed to invoke " + setterMethod, e);
}
}
return newBean;
}
} }

View file

@ -16,18 +16,19 @@ import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution; import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.RDFNode;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.Identifier; import edu.cornell.mannlib.vitro.webapp.auth.identifier.Identifier;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle; import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.beans.Individual; import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
/** /**
* The current user is blacklisted for this reason. * The current user is blacklisted for this reason.
@ -152,7 +153,7 @@ public class IsBlacklisted extends AbstractCommonIdentifier implements
return NOT_BLACKLISTED; return NOT_BLACKLISTED;
} }
Model model = (Model) context.getAttribute("jenaOntModel"); OntModel model = ModelAccess.on(context).getJenaOntModel();
queryString = queryString.replaceAll("\\?individualURI", queryString = queryString.replaceAll("\\?individualURI",
"<" + ind.getURI() + ">"); "<" + ind.getURI() + ">");

View file

@ -6,6 +6,7 @@ import javax.servlet.ServletContext;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundleFactory; import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundleFactory;
import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao; import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDao; import edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
@ -24,16 +25,7 @@ public abstract class BaseIdentifierBundleFactory implements
throw new NullPointerException("ctx may not be null."); throw new NullPointerException("ctx may not be null.");
} }
this.ctx = ctx; this.ctx = ctx;
this.wdf = ModelAccess.on(ctx).getWebappDaoFactory();
Object wdfObject = ctx.getAttribute("webappDaoFactory");
if (wdfObject instanceof WebappDaoFactory) {
this.wdf = (WebappDaoFactory) wdfObject;
} else {
throw new IllegalStateException(
"Didn't find a WebappDaoFactory in the context. Found '"
+ wdfObject + "' instead.");
}
this.uaDao = wdf.getUserAccountsDao(); this.uaDao = wdf.getUserAccountsDao();
this.indDao = wdf.getIndividualDao(); this.indDao = wdf.getIndividualDao();
} }

View file

@ -114,9 +114,11 @@ public class DisplayByRolePermission extends Permission {
ObjectPropertyStatement stmt = action.getObjectPropertyStatement(); ObjectPropertyStatement stmt = action.getObjectPropertyStatement();
String subjectUri = stmt.getSubjectURI(); String subjectUri = stmt.getSubjectURI();
String predicateUri = stmt.getPropertyURI(); String predicateUri = stmt.getPropertyURI();
String rangeUri = (stmt.getProperty() == null) ? null
: stmt.getProperty().getRangeVClassURI();
String objectUri = stmt.getObjectURI(); String objectUri = stmt.getObjectURI();
return canDisplayResource(subjectUri) return canDisplayResource(subjectUri)
&& canDisplayPredicate(predicateUri) && canDisplayPredicate(predicateUri, rangeUri)
&& canDisplayResource(objectUri); && canDisplayResource(objectUri);
} }
@ -124,10 +126,14 @@ public class DisplayByRolePermission extends Permission {
return PropertyRestrictionPolicyHelper.getBean(ctx).canDisplayResource( return PropertyRestrictionPolicyHelper.getBean(ctx).canDisplayResource(
resourceUri, this.roleLevel); resourceUri, this.roleLevel);
} }
private boolean canDisplayPredicate(String predicateUri) { private boolean canDisplayPredicate(String predicateUri) {
return canDisplayPredicate(predicateUri, null);
}
private boolean canDisplayPredicate(String predicateUri, String rangeUri) {
return PropertyRestrictionPolicyHelper.getBean(ctx) return PropertyRestrictionPolicyHelper.getBean(ctx)
.canDisplayPredicate(predicateUri, this.roleLevel); .canDisplayPredicate(predicateUri, rangeUri, this.roleLevel);
} }
@Override @Override

View file

@ -32,10 +32,10 @@ import com.hp.hpl.jena.vocabulary.RDFS;
import edu.cornell.mannlib.vitro.webapp.beans.PermissionSet; import edu.cornell.mannlib.vitro.webapp.beans.PermissionSet;
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount; import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDao; import edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDao;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.jena.ModelContext;
import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus; import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus;
/** /**
@ -100,8 +100,7 @@ public class PermissionSetsLoader implements ServletContextListener {
this.ctx = ctx; this.ctx = ctx;
this.ss = ss; this.ss = ss;
this.userAccountsModel = ModelContext.getBaseOntModelSelector(ctx) this.userAccountsModel = ModelAccess.on(ctx).getUserAccountsModel();
.getUserAccountsModel();
this.permissionSetType = this.userAccountsModel this.permissionSetType = this.userAccountsModel
.getProperty(VitroVocabulary.PERMISSIONSET); .getProperty(VitroVocabulary.PERMISSIONSET);
@ -274,8 +273,7 @@ public class PermissionSetsLoader implements ServletContextListener {
this.ctx = ctx; this.ctx = ctx;
this.ss = ss; this.ss = ss;
WebappDaoFactory wadf = (WebappDaoFactory) ctx WebappDaoFactory wadf = ModelAccess.on(ctx).getWebappDaoFactory();
.getAttribute("webappDaoFactory");
if (wadf == null) { if (wadf == null) {
throw new IllegalStateException( throw new IllegalStateException(
"No webappDaoFactory on the servlet context"); "No webappDaoFactory on the servlet context");

View file

@ -2,8 +2,6 @@
package edu.cornell.mannlib.vitro.webapp.auth.policy; package edu.cornell.mannlib.vitro.webapp.auth.policy;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet; import java.util.TreeSet;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
@ -23,8 +21,8 @@ import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount.Status; import edu.cornell.mannlib.vitro.webapp.beans.UserAccount.Status;
import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties; import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties;
import edu.cornell.mannlib.vitro.webapp.controller.authenticate.Authenticator; import edu.cornell.mannlib.vitro.webapp.controller.authenticate.Authenticator;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDao; import edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus; import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus;
/** /**
@ -79,7 +77,8 @@ public class RootUserPolicy implements PolicyIface {
ss = StartupStatus.getBean(ctx); ss = StartupStatus.getBean(ctx);
try { try {
uaDao = getUserAccountsDao(); uaDao = ModelAccess.on(ctx).getWebappDaoFactory()
.getUserAccountsDao();
configuredRootUser = getRootEmailFromConfig(); configuredRootUser = getRootEmailFromConfig();
otherRootUsers = getEmailsOfAllRootUsers(); otherRootUsers = getEmailsOfAllRootUsers();
@ -105,16 +104,6 @@ public class RootUserPolicy implements PolicyIface {
} }
} }
private UserAccountsDao getUserAccountsDao() {
WebappDaoFactory wadf = (WebappDaoFactory) ctx
.getAttribute("webappDaoFactory");
if (wadf == null) {
throw new IllegalStateException(
"No webappDaoFactory on the servlet context");
}
return wadf.getUserAccountsDao();
}
private String getRootEmailFromConfig() { private String getRootEmailFromConfig() {
String email = ConfigurationProperties.getBean(ctx).getProperty( String email = ConfigurationProperties.getBean(ctx).getProperty(
PROPERTY_ROOT_USER_EMAIL); PROPERTY_ROOT_USER_EMAIL);

View file

@ -8,11 +8,13 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.Model;
import edu.cornell.mannlib.vedit.beans.EditProcessObject; import edu.cornell.mannlib.vedit.beans.EditProcessObject;
import edu.cornell.mannlib.vedit.listener.ChangeListener; import edu.cornell.mannlib.vedit.listener.ChangeListener;
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel; import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel;
import edu.cornell.mannlib.vitro.webapp.beans.Property; import edu.cornell.mannlib.vitro.webapp.beans.Property;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
/** /**
* Add this ChangeListener to your EditProcessObject when modifying the * Add this ChangeListener to your EditProcessObject when modifying the
@ -90,9 +92,10 @@ public class PropertyRestrictionListener implements ChangeListener {
} }
private void createAndSetBean() { private void createAndSetBean() {
OntModel model = (OntModel) ctx.getAttribute("jenaOntModel"); OntModel model = ModelAccess.on(ctx).getJenaOntModel();
Model displayModel = ModelAccess.on(ctx).getDisplayModel();
PropertyRestrictionPolicyHelper bean = PropertyRestrictionPolicyHelper PropertyRestrictionPolicyHelper bean = PropertyRestrictionPolicyHelper
.createBean(model); .createBean(model, displayModel);
PropertyRestrictionPolicyHelper.setBean(ctx, bean); PropertyRestrictionPolicyHelper.setBean(ctx, bean);
} }
} }

View file

@ -17,6 +17,13 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Resource;
@ -26,6 +33,7 @@ import com.hp.hpl.jena.rdf.model.impl.Util;
import com.hp.hpl.jena.shared.Lock; import com.hp.hpl.jena.shared.Lock;
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel; import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus; import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus;
@ -96,7 +104,10 @@ public class PropertyRestrictionPolicyHelper {
* Initialize the bean with the standard prohibitions and exceptions, and * Initialize the bean with the standard prohibitions and exceptions, and
* with the thresholds obtained from the model. * with the thresholds obtained from the model.
*/ */
public static PropertyRestrictionPolicyHelper createBean(OntModel model) { public static PropertyRestrictionPolicyHelper createBean(OntModel model,
Model displayModel) {
Map<String, RoleLevel> displayThresholdMap = new HashMap<String, RoleLevel>(); Map<String, RoleLevel> displayThresholdMap = new HashMap<String, RoleLevel>();
Map<String, RoleLevel> modifyThresholdMap = new HashMap<String, RoleLevel>(); Map<String, RoleLevel> modifyThresholdMap = new HashMap<String, RoleLevel>();
@ -111,7 +122,7 @@ public class PropertyRestrictionPolicyHelper {
PropertyRestrictionPolicyHelper bean = new PropertyRestrictionPolicyHelper( PropertyRestrictionPolicyHelper bean = new PropertyRestrictionPolicyHelper(
PROHIBITED_NAMESPACES, PERMITTED_EXCEPTIONS, PROHIBITED_NAMESPACES, PERMITTED_EXCEPTIONS,
displayThresholdMap, modifyThresholdMap); displayThresholdMap, modifyThresholdMap, displayModel);
return bean; return bean;
} }
@ -171,6 +182,8 @@ public class PropertyRestrictionPolicyHelper {
* the threshold role. * the threshold role.
*/ */
private final Map<String, RoleLevel> modifyThresholdMap; private final Map<String, RoleLevel> modifyThresholdMap;
private final Model displayModel;
/** /**
* Store unmodifiable versions of the inputs. * Store unmodifiable versions of the inputs.
@ -182,11 +195,13 @@ public class PropertyRestrictionPolicyHelper {
Collection<String> modifyProhibitedNamespaces, Collection<String> modifyProhibitedNamespaces,
Collection<String> modifyExceptionsAllowedUris, Collection<String> modifyExceptionsAllowedUris,
Map<String, RoleLevel> displayThresholdMap, Map<String, RoleLevel> displayThresholdMap,
Map<String, RoleLevel> modifyThresholdMap) { Map<String, RoleLevel> modifyThresholdMap,
Model displayModel) {
this.modifyProhibitedNamespaces = unmodifiable(modifyProhibitedNamespaces); this.modifyProhibitedNamespaces = unmodifiable(modifyProhibitedNamespaces);
this.modifyExceptionsAllowedUris = unmodifiable(modifyExceptionsAllowedUris); this.modifyExceptionsAllowedUris = unmodifiable(modifyExceptionsAllowedUris);
this.displayThresholdMap = unmodifiable(displayThresholdMap); this.displayThresholdMap = unmodifiable(displayThresholdMap);
this.modifyThresholdMap = unmodifiable(modifyThresholdMap); this.modifyThresholdMap = unmodifiable(modifyThresholdMap);
this.displayModel = displayModel;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("prohibited: " + this.modifyProhibitedNamespaces); log.debug("prohibited: " + this.modifyProhibitedNamespaces);
@ -256,18 +271,33 @@ public class PropertyRestrictionPolicyHelper {
log.debug("can modify resource '" + resourceUri + "'"); log.debug("can modify resource '" + resourceUri + "'");
return true; return true;
} }
public boolean canDisplayPredicate(String predicateUri, RoleLevel userRole) {
return canDisplayPredicate(predicateUri, null, userRole);
}
/** /**
* If display of a predicate is restricted, the user's role must be at least * If display of a predicate is restricted, the user's role must be at least
* as high as the restriction level. * as high as the restriction level.
*/ */
public boolean canDisplayPredicate(String predicateUri, RoleLevel userRole) { public boolean canDisplayPredicate(String predicateUri, String rangeUri, RoleLevel userRole) {
if (predicateUri == null) { if (predicateUri == null) {
log.debug("can't display predicate: predicateUri was null"); log.debug("can't display predicate: predicateUri was null");
return false; return false;
} }
RoleLevel displayThreshold = displayThresholdMap.get(predicateUri); RoleLevel displayThreshold = RoleLevel.NOBODY;
if (rangeUri == null) {
displayThreshold = displayThresholdMap.get(predicateUri);
} else {
log.debug("Getting display threshold for " + predicateUri + " " + rangeUri);
displayThreshold = getDisplayThreshold(predicateUri, rangeUri);
if (displayThreshold == null) {
displayThreshold = displayThresholdMap.get(predicateUri);
}
log.debug(displayThreshold);
}
if (isAuthorized(userRole, displayThreshold)) { if (isAuthorized(userRole, displayThreshold)) {
log.debug("can display predicate: '" + predicateUri log.debug("can display predicate: '" + predicateUri
+ "', userRole=" + userRole + ", thresholdRole=" + "', userRole=" + userRole + ", thresholdRole="
@ -279,7 +309,45 @@ public class PropertyRestrictionPolicyHelper {
+ userRole + ", thresholdRole=" + displayThreshold); + userRole + ", thresholdRole=" + displayThreshold);
return false; return false;
} }
/**
* Gets the role level threshold for displaying a predicate with a particular
* object class
* @param predicateUri
* @param rangeUri
* @return RoleLevel threshold
*/
private RoleLevel getDisplayThreshold(String predicateUri, String rangeUri) {
String query = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n" +
"PREFIX config: <http://vitro.mannlib.cornell.edu/ns/vitro/ApplicationConfiguration#> \n" +
"PREFIX vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> \n" +
"SELECT ?level WHERE { \n" +
// " ?p rdfs:subPropertyOf ?property . \n" +
" ?context config:configContextFor ?p . \n" +
" ?context config:qualifiedBy ?range . \n" +
" ?context config:hasConfiguration ?configuration . \n" +
" ?configuration vitro:hiddenFromDisplayBelowRoleLevelAnnot ?level \n" +
"}";
Query q = QueryFactory.create(query);
QueryExecution qe = QueryExecutionFactory.create(q, displayModel);
try {
ResultSet rs = qe.execSelect();
if (!rs.hasNext()) {
return null;
}
while(rs.hasNext()) {
QuerySolution qsoln = rs.nextSolution();
Resource levelRes = qsoln.getResource("level");
if (levelRes != null) {
return RoleLevel.getRoleByUri(levelRes.getURI());
}
}
} finally {
qe.close();
}
return null;
}
/** /**
* A predicate cannot be modified if its namespace is in the prohibited list * A predicate cannot be modified if its namespace is in the prohibited list
* (some exceptions are allowed). * (some exceptions are allowed).
@ -344,14 +412,19 @@ public class PropertyRestrictionPolicyHelper {
StartupStatus ss = StartupStatus.getBean(ctx); StartupStatus ss = StartupStatus.getBean(ctx);
try { try {
OntModel model = (OntModel) ctx.getAttribute("jenaOntModel"); OntModel model = ModelAccess.on(ctx).getJenaOntModel();
if (model == null) { if (model == null) {
throw new NullPointerException( throw new NullPointerException(
"jenaOntModel has not been initialized."); "jenaOntModel has not been initialized.");
} }
Model displayModel = ModelAccess.on(ctx).getDisplayModel();
if (displayModel == null) {
throw new NullPointerException(
"display model has not been initialized.");
}
PropertyRestrictionPolicyHelper bean = PropertyRestrictionPolicyHelper PropertyRestrictionPolicyHelper bean = PropertyRestrictionPolicyHelper
.createBean(model); .createBean(model, displayModel);
PropertyRestrictionPolicyHelper.setBean(ctx, bean); PropertyRestrictionPolicyHelper.setBean(ctx, bean);
} catch (Exception e) { } catch (Exception e) {
ss.fatal(this, "could not set up PropertyRestrictionPolicyHelper", e); ss.fatal(this, "could not set up PropertyRestrictionPolicyHelper", e);

View file

@ -44,8 +44,8 @@ public class DataPropertyComparator implements Comparator<Individual> {
} }
if (datatype == null) { if (datatype == null) {
log.warn("Can't compare data property statements: no datatype specified."); log.warn("Can't compare data property statements: no datatype specified.");
// Perhaps we should throw an error here, but for now we need it to return 0 // Perhaps we should throw an error here, but for now we need it to set the datatype
return 0; datatype = XSD.xint.toString();
} }
if (XSD.xint.toString().equals(datatype)) { if (XSD.xint.toString().equals(datatype)) {

View file

@ -129,6 +129,29 @@ public class VClass extends BaseResourceBean implements Comparable<VClass>
localName = uri.getLocalName(); localName = uri.getLocalName();
} }
/**
* Constructs the VClass as a deep copy of an existing VClass.
*/
public VClass( VClass vc) {
this.URI = vc.URI;
this.namespace = vc.namespace;
this.localName = vc.localName;
this.myName = vc.myName;
this.myExample = vc.myExample;
this.myDescription = vc.myDescription;
this.myShortDefinition = vc.myShortDefinition;
this.myEntityCount = vc.myEntityCount;
this.displayLimit = vc.displayLimit;
this.displayRank = vc.displayRank;
this.quickEditJsp = vc.quickEditJsp;
this.groupURI = vc.groupURI;
this.group = (vc.group == null) ? null : new VClassGroup(vc.group);
this.customEntryForm = vc.customEntryForm;
this.customDisplayView = vc.customDisplayView;
this.customShortView = vc.customShortView;
this.customSearchView = vc.customSearchView;
}
/** /**
* Sorts alphabetically by name * Sorts alphabetically by name
*/ */

View file

@ -62,6 +62,15 @@ public class VClassGroup extends LinkedList <VClass> implements Comparable<VClas
this.displayRank = rank; this.displayRank = rank;
this.publicName = name; this.publicName = name;
} }
public VClassGroup(VClassGroup vcg) {
this.URI = vcg.URI;
this.namespace = vcg.namespace;
this.localName = vcg.localName;
this.publicName = vcg.publicName;
this.displayRank = vcg.displayRank;
this.individualCount = vcg.individualCount;
}
public String getURI() { public String getURI() {
return URI; return URI;

View file

@ -19,12 +19,14 @@ import com.hp.hpl.jena.ontology.OntModel;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyStatementDao; import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyStatementDao;
import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao; import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess.ModelID;
import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyStatementDao; import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyStatementDao;
import edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDao; import edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao; import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.jena.ModelContext; import edu.cornell.mannlib.vitro.webapp.i18n.I18n;
import edu.cornell.mannlib.vitro.webapp.dao.jena.OntModelSelector; import edu.cornell.mannlib.vitro.webapp.i18n.I18nBundle;
/** /**
* A base class with some utility routines for page handler (created by * A base class with some utility routines for page handler (created by
@ -39,6 +41,7 @@ public abstract class AbstractPageHandler {
private static final Log log = LogFactory.getLog(AbstractPageHandler.class); private static final Log log = LogFactory.getLog(AbstractPageHandler.class);
protected final VitroRequest vreq; protected final VitroRequest vreq;
protected final I18nBundle i18n;
protected final ServletContext ctx; protected final ServletContext ctx;
protected final OntModel userAccountsModel; protected final OntModel userAccountsModel;
protected final OntModel unionModel; protected final OntModel unionModel;
@ -50,14 +53,13 @@ public abstract class AbstractPageHandler {
protected AbstractPageHandler(VitroRequest vreq) { protected AbstractPageHandler(VitroRequest vreq) {
this.vreq = vreq; this.vreq = vreq;
this.i18n = I18n.bundle(vreq);
this.ctx = vreq.getSession().getServletContext(); this.ctx = vreq.getSession().getServletContext();
OntModelSelector oms = ModelContext.getUnionOntModelSelector(ctx); userAccountsModel = ModelAccess.on(ctx).getUserAccountsModel();
userAccountsModel = oms.getUserAccountsModel(); unionModel = ModelAccess.on(ctx).getOntModel(ModelID.UNION_FULL);
unionModel = oms.getFullModel();
WebappDaoFactory wdf = (WebappDaoFactory) this.ctx WebappDaoFactory wdf = ModelAccess.on(ctx).getWebappDaoFactory();
.getAttribute("webappDaoFactory");
userAccountsDao = wdf.getUserAccountsDao(); userAccountsDao = wdf.getUserAccountsDao();
vclassDao = wdf.getVClassDao(); vclassDao = wdf.getVClassDao();
indDao = wdf.getIndividualDao(); indDao = wdf.getIndividualDao();
@ -154,7 +156,8 @@ public abstract class AbstractPageHandler {
private static final String ATTRIBUTE = Message.class.getName(); private static final String ATTRIBUTE = Message.class.getName();
public static void setMessage(HttpServletRequest req, Message message) { public static void setMessage(HttpServletRequest req, Message message) {
log.debug("Added message to session: " + message.getMessageInfoMap()); log.debug("Added message to session: "
+ message.getMessageInfoMap());
req.getSession().setAttribute(ATTRIBUTE, message); req.getSession().setAttribute(ATTRIBUTE, message);
} }

View file

@ -42,6 +42,7 @@ import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement; import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties; import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties;
import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao; import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.FileUploadServletRequest; import edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.FileUploadServletRequest;
@ -101,7 +102,7 @@ public class FedoraDatastreamController extends VitroHttpServlet implements Cons
log.debug("In doGet"); log.debug("In doGet");
VitroRequest vreq = new VitroRequest(req); VitroRequest vreq = new VitroRequest(req);
OntModel sessionOntModel = (OntModel)vreq.getSession().getAttribute("jenaOntModel"); OntModel sessionOntModel = ModelAccess.on(vreq.getSession()).getJenaOntModel();
synchronized (FedoraDatastreamController.class) { synchronized (FedoraDatastreamController.class) {
if( fedoraUrl == null ){ if( fedoraUrl == null ){
@ -231,7 +232,7 @@ public class FedoraDatastreamController extends VitroHttpServlet implements Cons
} }
//check if fedora is on line //check if fedora is on line
OntModel sessionOntModel = (OntModel)rawRequest.getSession().getAttribute("jenaOntModel"); OntModel sessionOntModel = ModelAccess.on(rawRequest.getSession()).getJenaOntModel();
synchronized (FedoraDatastreamController.class) { synchronized (FedoraDatastreamController.class) {
if( fedoraUrl == null ){ if( fedoraUrl == null ){
setup( sessionOntModel, getServletContext() ); setup( sessionOntModel, getServletContext() );

View file

@ -27,6 +27,7 @@ import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.shared.Lock; import com.hp.hpl.jena.shared.Lock;
import edu.cornell.mannlib.vitro.webapp.beans.ApplicationBean; import edu.cornell.mannlib.vitro.webapp.beans.ApplicationBean;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.utils.jena.JenaOutputUtils; import edu.cornell.mannlib.vitro.webapp.utils.jena.JenaOutputUtils;
import edu.cornell.mannlib.vitro.webapp.web.ContentType; import edu.cornell.mannlib.vitro.webapp.web.ContentType;
@ -127,12 +128,7 @@ public class OntologyController extends VitroHttpServlet{
String url = ontology; String url = ontology;
OntModel ontModel = null; OntModel ontModel = ModelAccess.on(vreq.getSession()).getJenaOntModel();
HttpSession session = vreq.getSession(false);
if( session != null )
ontModel =(OntModel)session.getAttribute("jenaOntModel");
if( ontModel == null)
ontModel = (OntModel)getServletContext().getAttribute("jenaOntModel");
boolean found = false; boolean found = false;
Model newModel = ModelFactory.createDefaultModel(); Model newModel = ModelFactory.createDefaultModel();

View file

@ -30,6 +30,7 @@ import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAct
import edu.cornell.mannlib.vitro.webapp.beans.DisplayMessage; import edu.cornell.mannlib.vitro.webapp.beans.DisplayMessage;
import edu.cornell.mannlib.vitro.webapp.controller.authenticate.LogoutRedirector; import edu.cornell.mannlib.vitro.webapp.controller.authenticate.LogoutRedirector;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder;
import edu.cornell.mannlib.vitro.webapp.i18n.I18n;
public class VitroHttpServlet extends HttpServlet { public class VitroHttpServlet extends HttpServlet {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@ -63,15 +64,6 @@ public class VitroHttpServlet extends HttpServlet {
super.service(req, resp); super.service(req, resp);
} }
/**
* Show this to the user if they are logged in, but still not authorized to
* view the page.
*/
private static final String INSUFFICIENT_AUTHORIZATION_MESSAGE = "We're sorry, "
+ "but you are not authorized to view the page you requested. "
+ "If you think this is an error, "
+ "please contact us and we'll be happy to help.";
/** /**
* doGet does nothing. * doGet does nothing.
*/ */
@ -148,7 +140,7 @@ public class VitroHttpServlet extends HttpServlet {
HttpServletRequest request, HttpServletResponse response) { HttpServletRequest request, HttpServletResponse response) {
try { try {
DisplayMessage.setMessage(request, DisplayMessage.setMessage(request,
INSUFFICIENT_AUTHORIZATION_MESSAGE); I18n.bundle(request).text("insufficient_authorization"));
response.sendRedirect(request.getContextPath()); response.sendRedirect(request.getContextPath());
} catch (IOException e) { } catch (IOException e) {
log.error("Could not redirect to show insufficient authorization."); log.error("Could not redirect to show insufficient authorization.");

View file

@ -2,13 +2,11 @@
package edu.cornell.mannlib.vitro.webapp.controller; package edu.cornell.mannlib.vitro.webapp.controller;
import static edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary.DISPLAY_ONT_MODEL;
import java.util.Map; import java.util.Map;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -17,8 +15,8 @@ import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.query.Dataset; import com.hp.hpl.jena.query.Dataset;
import edu.cornell.mannlib.vitro.webapp.beans.ApplicationBean; import edu.cornell.mannlib.vitro.webapp.beans.ApplicationBean;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.jena.JenaBaseDao;
import edu.cornell.mannlib.vitro.webapp.dao.jena.OntModelSelector; import edu.cornell.mannlib.vitro.webapp.dao.jena.OntModelSelector;
import edu.cornell.mannlib.vitro.webapp.dao.jena.VitroModelSource.ModelName; import edu.cornell.mannlib.vitro.webapp.dao.jena.VitroModelSource.ModelName;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService; import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
@ -73,13 +71,9 @@ public class VitroRequest extends HttpServletRequestWrapper {
setAttribute("unfilteredRDFService", rdfService); setAttribute("unfilteredRDFService", rdfService);
} }
public void setWebappDaoFactory( WebappDaoFactory wdf){
setAttribute("webappDaoFactory",wdf);
}
/** gets WebappDaoFactory with appropriate filtering for the request */ /** gets WebappDaoFactory with appropriate filtering for the request */
public WebappDaoFactory getWebappDaoFactory(){ public WebappDaoFactory getWebappDaoFactory(){
return (WebappDaoFactory) getAttribute("webappDaoFactory"); return ModelAccess.on(this).getWebappDaoFactory();
} }
public void setUnfilteredWebappDaoFactory(WebappDaoFactory wdf) { public void setUnfilteredWebappDaoFactory(WebappDaoFactory wdf) {
@ -94,10 +88,6 @@ public class VitroRequest extends HttpServletRequestWrapper {
return (WebappDaoFactory) getAttribute("unfilteredWebappDaoFactory"); return (WebappDaoFactory) getAttribute("unfilteredWebappDaoFactory");
} }
public void setFullWebappDaoFactory(WebappDaoFactory wdf) {
setAttribute("fullWebappDaoFactory", wdf);
}
public Dataset getDataset() { public Dataset getDataset() {
return (Dataset) getAttribute("dataset"); return (Dataset) getAttribute("dataset");
} }
@ -106,63 +96,16 @@ public class VitroRequest extends HttpServletRequestWrapper {
setAttribute("dataset", dataset); setAttribute("dataset", dataset);
} }
public void setJenaOntModel(OntModel ontModel) {
setAttribute("jenaOntModel", ontModel);
}
public void setOntModelSelector(OntModelSelector oms) {
setAttribute("ontModelSelector", oms);
}
/** gets assertions + inferences WebappDaoFactory with no filtering **/ /** gets assertions + inferences WebappDaoFactory with no filtering **/
public WebappDaoFactory getFullWebappDaoFactory() { public WebappDaoFactory getFullWebappDaoFactory() {
Object webappDaoFactoryAttr = _req.getAttribute("fullWebappDaoFactory"); return getUnfilteredWebappDaoFactory();
if (webappDaoFactoryAttr instanceof WebappDaoFactory) {
return (WebappDaoFactory) webappDaoFactoryAttr;
} else {
webappDaoFactoryAttr = _req.getSession().getAttribute("webappDaoFactory");
if (webappDaoFactoryAttr instanceof WebappDaoFactory) {
return (WebappDaoFactory) webappDaoFactoryAttr;
} else {
return (WebappDaoFactory) _req.getSession().getServletContext().getAttribute("webappDaoFactory");
}
}
} }
/** gets assertions-only WebappDaoFactory with no filtering */ /** gets assertions-only WebappDaoFactory with no filtering */
public WebappDaoFactory getAssertionsWebappDaoFactory() { public WebappDaoFactory getAssertionsWebappDaoFactory() {
Object webappDaoFactoryAttr = _req.getSession().getAttribute("assertionsWebappDaoFactory"); return ModelAccess.on(this).getBaseWebappDaoFactory();
if (webappDaoFactoryAttr instanceof WebappDaoFactory) {
log.debug("Returning assertionsWebappDaoFactory from session");
return (WebappDaoFactory) webappDaoFactoryAttr;
} else {
webappDaoFactoryAttr = getAttribute("assertionsWebappDaoFactory");
if (webappDaoFactoryAttr instanceof WebappDaoFactory) {
log.debug("returning assertionsWebappDaoFactory from request attribute");
return (WebappDaoFactory) webappDaoFactoryAttr;
} else {
log.debug("Returning assertionsWebappDaoFactory from context");
return (WebappDaoFactory) _req.getSession().getServletContext().getAttribute("assertionsWebappDaoFactory");
}
}
} }
/** gets assertions-only WebappDaoFactory with no filtering */
public void setAssertionsWebappDaoFactory(WebappDaoFactory wadf) {
setAttribute("assertionsWebappDaoFactory", wadf);
}
/** gets inferences-only WebappDaoFactory with no filtering */
public WebappDaoFactory getDeductionsWebappDaoFactory() {
Object webappDaoFactoryAttr = _req.getSession().getAttribute("deductionsWebappDaoFactory");
if (webappDaoFactoryAttr instanceof WebappDaoFactory) {
return (WebappDaoFactory) webappDaoFactoryAttr;
} else {
return (WebappDaoFactory) _req.getSession().getServletContext().getAttribute("deductionsWebappDaoFactory");
}
}
//Method that retrieves write model, returns special model in case of write model //Method that retrieves write model, returns special model in case of write model
public OntModel getWriteModel() { public OntModel getWriteModel() {
//if special write model doesn't exist use get ont model //if special write model doesn't exist use get ont model
@ -173,73 +116,26 @@ public class VitroRequest extends HttpServletRequestWrapper {
} }
} }
public OntModelSelector getOntModelSelector() {
return ModelAccess.on(this).getOntModelSelector();
}
public OntModel getJenaOntModel() { public OntModel getJenaOntModel() {
Object ontModel = getAttribute("jenaOntModel"); return ModelAccess.on(this).getJenaOntModel();
if (ontModel instanceof OntModel) {
return (OntModel) ontModel;
}
OntModel jenaOntModel = (OntModel)_req.getSession().getAttribute( JenaBaseDao.JENA_ONT_MODEL_ATTRIBUTE_NAME );
if ( jenaOntModel == null ) {
jenaOntModel = (OntModel)_req.getSession().getServletContext().getAttribute( JenaBaseDao.JENA_ONT_MODEL_ATTRIBUTE_NAME );
}
return jenaOntModel;
} }
public OntModelSelector getOntModelSelector() { /** JB - surprising that this comes from session. */
Object o = this.getAttribute("ontModelSelector");
if (o instanceof OntModelSelector) {
return (OntModelSelector) o;
} else {
return null;
}
}
public OntModel getAssertionsOntModel() { public OntModel getAssertionsOntModel() {
OntModel jenaOntModel = (OntModel)_req.getSession().getAttribute( JenaBaseDao.ASSERTIONS_ONT_MODEL_ATTRIBUTE_NAME ); return ModelAccess.on(this.getSession()).getBaseOntModel();
if ( jenaOntModel == null ) {
jenaOntModel = (OntModel)_req.getSession().getServletContext().getAttribute( JenaBaseDao.ASSERTIONS_ONT_MODEL_ATTRIBUTE_NAME );
}
return jenaOntModel;
} }
/** JB - surprising that this comes from session. */
public OntModel getInferenceOntModel() { public OntModel getInferenceOntModel() {
OntModel jenaOntModel = (OntModel)_req.getSession().getAttribute( JenaBaseDao.INFERENCE_ONT_MODEL_ATTRIBUTE_NAME ); return ModelAccess.on(this.getSession()).getInferenceOntModel();
if ( jenaOntModel == null ) {
jenaOntModel = (OntModel)_req.getSession().getServletContext().getAttribute( JenaBaseDao.INFERENCE_ONT_MODEL_ATTRIBUTE_NAME );
}
return jenaOntModel;
} }
//Get the display and editing configuration model public OntModel getDisplayModel(){
public OntModel getDisplayModel(){ return ModelAccess.on(this).getDisplayModel();
//bdc34: I have no idea what the correct way to get this model is
//try from the request
if( _req.getAttribute("displayOntModel") != null ){
return (OntModel) _req.getAttribute(DISPLAY_ONT_MODEL);
//try from the session
} else {
HttpSession session = _req.getSession(false);
if( session != null ){
if( session.getAttribute(DISPLAY_ONT_MODEL) != null ){
return (OntModel) session.getAttribute(DISPLAY_ONT_MODEL);
//try from the context
}else{
if( session.getServletContext().getAttribute(DISPLAY_ONT_MODEL) != null){
return (OntModel)session.getServletContext().getAttribute(DISPLAY_ONT_MODEL);
}
}
}
}
//nothing worked, could not find display model
log.error("No display model could be found.");
return null;
} }
/** /**

View file

@ -103,7 +103,7 @@ public abstract class UserAccountsAddPageStrategy extends UserAccountsPage {
FreemarkerEmailMessage email = FreemarkerEmailFactory FreemarkerEmailMessage email = FreemarkerEmailFactory
.createNewMessage(vreq); .createNewMessage(vreq);
email.addRecipient(TO, page.getAddedAccount().getEmailAddress()); email.addRecipient(TO, page.getAddedAccount().getEmailAddress());
email.setSubject("Your VIVO account has been created."); email.setSubject(i18n.text("account_created_subject", getSiteName()));
if (page.isExternalAuthOnly()) { if (page.isExternalAuthOnly()) {
email.setTemplate(EMAIL_TEMPLATE_NO_PASSWORD); email.setTemplate(EMAIL_TEMPLATE_NO_PASSWORD);
} else { } else {

View file

@ -2,6 +2,8 @@
package edu.cornell.mannlib.vitro.webapp.controller.accounts.admin; package edu.cornell.mannlib.vitro.webapp.controller.accounts.admin;
import static edu.cornell.mannlib.vitro.webapp.controller.accounts.user.UserAccountsUserController.getBogusStandardMessage;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
@ -15,7 +17,6 @@ import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.usepages.ManageRoot
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount; import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.accounts.UserAccountsPage; import edu.cornell.mannlib.vitro.webapp.controller.accounts.UserAccountsPage;
import edu.cornell.mannlib.vitro.webapp.controller.accounts.user.UserAccountsUserController;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
/** /**
@ -51,7 +52,7 @@ public class UserAccountsDeleter extends UserAccountsPage {
UserAccount loggedInAccount = LoginStatusBean.getCurrentUser(vreq); UserAccount loggedInAccount = LoginStatusBean.getCurrentUser(vreq);
if (loggedInAccount == null) { if (loggedInAccount == null) {
log.warn("Trying to delete accounts while not logged in!"); log.warn("Trying to delete accounts while not logged in!");
bogusMessage = UserAccountsUserController.BOGUS_STANDARD_MESSAGE; bogusMessage = getBogusStandardMessage(vreq);
return; return;
} }
@ -61,14 +62,14 @@ public class UserAccountsDeleter extends UserAccountsPage {
if (u == null) { if (u == null) {
log.warn("Delete account for '" + uri log.warn("Delete account for '" + uri
+ "' is bogus: no such user"); + "' is bogus: no such user");
bogusMessage = UserAccountsUserController.BOGUS_STANDARD_MESSAGE; bogusMessage = getBogusStandardMessage(vreq);
return; return;
} }
if (u.getUri().equals(loggedInAccount.getUri())) { if (u.getUri().equals(loggedInAccount.getUri())) {
log.warn("'" + u.getUri() log.warn("'" + u.getUri()
+ "' is trying to delete his own account."); + "' is trying to delete his own account.");
bogusMessage = UserAccountsUserController.BOGUS_STANDARD_MESSAGE; bogusMessage = getBogusStandardMessage(vreq);
return; return;
} }
@ -78,7 +79,7 @@ public class UserAccountsDeleter extends UserAccountsPage {
log.warn("Attempting to delete the root account, " log.warn("Attempting to delete the root account, "
+ "but not authorized. Logged in as " + "but not authorized. Logged in as "
+ LoginStatusBean.getCurrentUser(vreq)); + LoginStatusBean.getCurrentUser(vreq));
bogusMessage = UserAccountsUserController.BOGUS_STANDARD_MESSAGE; bogusMessage = getBogusStandardMessage(vreq);
return; return;
} }
} }

View file

@ -2,6 +2,8 @@
package edu.cornell.mannlib.vitro.webapp.controller.accounts.admin; package edu.cornell.mannlib.vitro.webapp.controller.accounts.admin;
import static edu.cornell.mannlib.vitro.webapp.controller.accounts.user.UserAccountsUserController.getBogusStandardMessage;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
@ -20,7 +22,6 @@ import edu.cornell.mannlib.vitro.webapp.beans.SelfEditingConfiguration;
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount; import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.accounts.UserAccountsPage; import edu.cornell.mannlib.vitro.webapp.controller.accounts.UserAccountsPage;
import edu.cornell.mannlib.vitro.webapp.controller.accounts.user.UserAccountsUserController;
import edu.cornell.mannlib.vitro.webapp.controller.authenticate.Authenticator; import edu.cornell.mannlib.vitro.webapp.controller.authenticate.Authenticator;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
@ -116,7 +117,7 @@ public class UserAccountsEditPage extends UserAccountsPage {
if (userAccount == null) { if (userAccount == null) {
log.warn("Edit account for '" + userUri log.warn("Edit account for '" + userUri
+ "' is bogus: no such user"); + "' is bogus: no such user");
bogusMessage = UserAccountsUserController.BOGUS_STANDARD_MESSAGE; bogusMessage = getBogusStandardMessage(vreq);
return; return;
} }
if (userAccount.isRootUser()) { if (userAccount.isRootUser()) {
@ -125,7 +126,7 @@ public class UserAccountsEditPage extends UserAccountsPage {
log.warn("User is attempting to edit the root account, " log.warn("User is attempting to edit the root account, "
+ "but is not authorized to do so. Logged in as: " + "but is not authorized to do so. Logged in as: "
+ LoginStatusBean.getCurrentUser(vreq)); + LoginStatusBean.getCurrentUser(vreq));
bogusMessage = UserAccountsUserController.BOGUS_STANDARD_MESSAGE; bogusMessage = getBogusStandardMessage(vreq);
return; return;
} }
} }

View file

@ -6,7 +6,6 @@ import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
@ -21,9 +20,8 @@ import com.hp.hpl.jena.query.QuerySolution;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.ajax.AbstractAjaxResponder; import edu.cornell.mannlib.vitro.webapp.controller.ajax.AbstractAjaxResponder;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.jena.ModelContext;
import edu.cornell.mannlib.vitro.webapp.dao.jena.OntModelSelector;
import edu.cornell.mannlib.vitro.webapp.utils.SparqlQueryRunner; import edu.cornell.mannlib.vitro.webapp.utils.SparqlQueryRunner;
import edu.cornell.mannlib.vitro.webapp.utils.SparqlQueryUtils; import edu.cornell.mannlib.vitro.webapp.utils.SparqlQueryUtils;
import edu.cornell.mannlib.vitro.webapp.web.images.PlaceholderUtil; import edu.cornell.mannlib.vitro.webapp.web.images.PlaceholderUtil;
@ -60,9 +58,7 @@ public class BasicProxiesGetter extends AbstractAjaxResponder {
super(servlet, vreq, resp); super(servlet, vreq, resp);
term = getStringParameter(PARAMETER_SEARCH_TERM, ""); term = getStringParameter(PARAMETER_SEARCH_TERM, "");
ServletContext ctx = vreq.getSession().getServletContext(); userAccountsModel = ModelAccess.on(vreq).getUserAccountsModel();
OntModelSelector oms = ModelContext.getUnionOntModelSelector(ctx);
userAccountsModel = oms.getUserAccountsModel();
placeholderImageUrl = UrlBuilder.getUrl(PlaceholderUtil placeholderImageUrl = UrlBuilder.getUrl(PlaceholderUtil
.getPlaceholderImagePathForType(vreq, .getPlaceholderImagePathForType(vreq,

View file

@ -46,14 +46,12 @@ public class UserAccountsCreatePasswordPage extends
@Override @Override
protected String alreadyLoggedInMessage(String currentUserEmail) { protected String alreadyLoggedInMessage(String currentUserEmail) {
return "You may not activate the account for " + userEmail return i18n.text("cant_activate_while_logged_in", userEmail, currentUserEmail);
+ " while you are logged in as " + currentUserEmail
+ ". Please log out and try again.";
} }
@Override @Override
protected String passwordChangeNotPendingMessage() { protected String passwordChangeNotPendingMessage() {
return "The account for " + userEmail + " has already been activated."; return i18n.text("account_already_activated", userEmail);
} }
@Override @Override
@ -69,7 +67,7 @@ public class UserAccountsCreatePasswordPage extends
FreemarkerEmailMessage email = FreemarkerEmailFactory FreemarkerEmailMessage email = FreemarkerEmailFactory
.createNewMessage(vreq); .createNewMessage(vreq);
email.addRecipient(TO, userAccount.getEmailAddress()); email.addRecipient(TO, userAccount.getEmailAddress());
email.setSubject("Password successfully created."); email.setSubject(i18n.text("password_created_subject", getSiteName()));
email.setTemplate(EMAIL_TEMPLATE); email.setTemplate(EMAIL_TEMPLATE);
email.setBodyMap(body); email.setBodyMap(body);
email.processTemplate(); email.processTemplate();

View file

@ -115,18 +115,17 @@ public class UserAccountsFirstTimeExternalPage extends UserAccountsPage {
private void validateExternalAuthId() { private void validateExternalAuthId() {
if (externalAuthId.isEmpty()) { if (externalAuthId.isEmpty()) {
bogusMessage = "Login failed - External ID is not found."; bogusMessage = i18n.text("external_id_not_provided");
return; return;
} }
if (null != userAccountsDao if (null != userAccountsDao
.getUserAccountByExternalAuthId(externalAuthId)) { .getUserAccountByExternalAuthId(externalAuthId)) {
bogusMessage = "User account already exists for '" + externalAuthId bogusMessage = i18n.text("external_id_already_in_use",
+ "'"; externalAuthId);
return; return;
} }
if (!Authenticator.getInstance(vreq).isUserPermittedToLogin(null)) { if (!Authenticator.getInstance(vreq).isUserPermittedToLogin(null)) {
bogusMessage = "User logins are temporarily disabled " bogusMessage = i18n.text("logins_disabled_for_maintenance");
+ "while the system is being maintained.";
return; return;
} }
} }

View file

@ -73,7 +73,7 @@ public abstract class UserAccountsFirstTimeExternalPageStrategy extends
FreemarkerEmailMessage email = FreemarkerEmailFactory FreemarkerEmailMessage email = FreemarkerEmailFactory
.createNewMessage(vreq); .createNewMessage(vreq);
email.addRecipient(TO, ua.getEmailAddress()); email.addRecipient(TO, ua.getEmailAddress());
email.setSubject("Your VIVO account has been created."); email.setSubject(i18n.text("account_created_subject", getSiteName()));
email.setTemplate(EMAIL_TEMPLATE); email.setTemplate(EMAIL_TEMPLATE);
email.setBodyMap(body); email.setBodyMap(body);
email.processTemplate(); email.processTemplate();

View file

@ -178,7 +178,7 @@ public abstract class UserAccountsMyAccountPageStrategy extends
FreemarkerEmailMessage email = FreemarkerEmailFactory FreemarkerEmailMessage email = FreemarkerEmailFactory
.createNewMessage(vreq); .createNewMessage(vreq);
email.addRecipient(TO, page.getUserAccount().getEmailAddress()); email.addRecipient(TO, page.getUserAccount().getEmailAddress());
email.setSubject("Your VIVO email account has been changed."); email.setSubject(i18n.text("email_changed_subject", getSiteName()));
email.setTemplate(EMAIL_TEMPLATE); email.setTemplate(EMAIL_TEMPLATE);
email.setBodyMap(body); email.setBodyMap(body);
email.processTemplate(); email.processTemplate();

View file

@ -23,8 +23,6 @@ public abstract class UserAccountsPasswordBasePage extends UserAccountsPage {
private static final Log log = LogFactory private static final Log log = LogFactory
.getLog(UserAccountsPasswordBasePage.class); .getLog(UserAccountsPasswordBasePage.class);
public static final String BOGUS_MESSAGE_NO_SUCH_ACCOUNT = "The account you are trying to set a password on is no longer available. Please contact your system administrator if you think this is an error.";
private static final String PARAMETER_SUBMIT = "submit"; private static final String PARAMETER_SUBMIT = "submit";
private static final String PARAMETER_USER = "user"; private static final String PARAMETER_USER = "user";
private static final String PARAMETER_KEY = "key"; private static final String PARAMETER_KEY = "key";
@ -79,7 +77,7 @@ public abstract class UserAccountsPasswordBasePage extends UserAccountsPage {
if (userAccount == null) { if (userAccount == null) {
log.warn("Password request for '" + userEmail log.warn("Password request for '" + userEmail
+ "' is bogus: no such user"); + "' is bogus: no such user");
bogusMessage = BOGUS_MESSAGE_NO_SUCH_ACCOUNT; bogusMessage = i18n.text("account_no_longer_exists");
return; return;
} }
@ -170,9 +168,9 @@ public abstract class UserAccountsPasswordBasePage extends UserAccountsPage {
public String getSuccessMessage() { public String getSuccessMessage() {
if (loggedIn) { if (loggedIn) {
return "Your password has been saved."; return i18n.text("password_saved");
} else { } else {
return "Your password has been saved. Please log in."; return i18n.text("password_saved_please_login");
} }
} }

View file

@ -46,14 +46,13 @@ public class UserAccountsResetPasswordPage extends UserAccountsPasswordBasePage
@Override @Override
protected String alreadyLoggedInMessage(String currentUserEmail) { protected String alreadyLoggedInMessage(String currentUserEmail) {
return "You may not reset the password for " + userEmail return i18n.text("cant_change_password_while_logged_in", userEmail,
+ " while you are logged in as " + currentUserEmail currentUserEmail);
+ ". Please log out and try again.";
} }
@Override @Override
protected String passwordChangeNotPendingMessage() { protected String passwordChangeNotPendingMessage() {
return "The password for " + userEmail + " has already been reset."; return i18n.text("password_change_not_pending", userEmail);
} }
@Override @Override
@ -69,7 +68,7 @@ public class UserAccountsResetPasswordPage extends UserAccountsPasswordBasePage
FreemarkerEmailMessage email = FreemarkerEmailFactory FreemarkerEmailMessage email = FreemarkerEmailFactory
.createNewMessage(vreq); .createNewMessage(vreq);
email.addRecipient(TO, userAccount.getEmailAddress()); email.addRecipient(TO, userAccount.getEmailAddress());
email.setSubject("Password changed."); email.setSubject(i18n.text("password_changed_subject"));
email.setTemplate(EMAIL_TEMPLATE); email.setTemplate(EMAIL_TEMPLATE);
email.setBodyMap(body); email.setBodyMap(body);
email.processTemplate(); email.processTemplate();

View file

@ -4,6 +4,8 @@ package edu.cornell.mannlib.vitro.webapp.controller.accounts.user;
import static edu.cornell.mannlib.vedit.beans.LoginStatusBean.AuthenticationSource.EXTERNAL; import static edu.cornell.mannlib.vedit.beans.LoginStatusBean.AuthenticationSource.EXTERNAL;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -18,6 +20,7 @@ import edu.cornell.mannlib.vitro.webapp.controller.authenticate.LoginRedirector;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerHttpServlet; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerHttpServlet;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.RedirectResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.RedirectResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
import edu.cornell.mannlib.vitro.webapp.i18n.I18n;
/** /**
* Parcel out the different actions required of the UserAccounts GUI. * Parcel out the different actions required of the UserAccounts GUI.
@ -26,8 +29,6 @@ public class UserAccountsUserController extends FreemarkerHttpServlet {
private static final Log log = LogFactory private static final Log log = LogFactory
.getLog(UserAccountsUserController.class); .getLog(UserAccountsUserController.class);
public static final String BOGUS_STANDARD_MESSAGE = "Request failed. Please contact your system administrator.";
private static final String ACTION_CREATE_PASSWORD = "/createPassword"; private static final String ACTION_CREATE_PASSWORD = "/createPassword";
private static final String ACTION_RESET_PASSWORD = "/resetPassword"; private static final String ACTION_RESET_PASSWORD = "/resetPassword";
private static final String ACTION_MY_ACCOUNT = "/myAccount"; private static final String ACTION_MY_ACCOUNT = "/myAccount";
@ -116,7 +117,7 @@ public class UserAccountsUserController extends FreemarkerHttpServlet {
return showLoginRedirection(vreq, page.getAfterLoginUrl()); return showLoginRedirection(vreq, page.getAfterLoginUrl());
} catch (LoginNotPermitted e) { } catch (LoginNotPermitted e) {
// This should have been anticipated by the page. // This should have been anticipated by the page.
return showHomePage(vreq, BOGUS_STANDARD_MESSAGE); return showHomePage(vreq, getBogusStandardMessage(vreq));
} }
} else { } else {
return page.showPage(); return page.showPage();
@ -124,7 +125,7 @@ public class UserAccountsUserController extends FreemarkerHttpServlet {
} }
private ResponseValues handleInvalidRequest(VitroRequest vreq) { private ResponseValues handleInvalidRequest(VitroRequest vreq) {
return showHomePage(vreq, BOGUS_STANDARD_MESSAGE); return showHomePage(vreq, getBogusStandardMessage(vreq));
} }
private ResponseValues showHomePage(VitroRequest vreq, String message) { private ResponseValues showHomePage(VitroRequest vreq, String message) {
@ -159,4 +160,8 @@ public class UserAccountsUserController extends FreemarkerHttpServlet {
} }
return uri; return uri;
} }
public static String getBogusStandardMessage(HttpServletRequest req) {
return I18n.bundle(req).text("request_failed");
}
} }

View file

@ -2,11 +2,9 @@
package edu.cornell.mannlib.vitro.webapp.controller.ajax; package edu.cornell.mannlib.vitro.webapp.controller.ajax;
import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -15,22 +13,14 @@ import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.query.DatasetFactory;
import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.query.Syntax;
import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Model;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission; import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.Actions; import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.Actions;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.ajax.SparqlUtils.AjaxControllerException; import edu.cornell.mannlib.vitro.webapp.controller.ajax.SparqlUtils.AjaxControllerException;
import edu.cornell.mannlib.vitro.webapp.dao.jena.OntModelSelector; import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
/** /**
* Handle an AJAX request for a SPARQL query. On entry, the "query" parameter * Handle an AJAX request for a SPARQL query. On entry, the "query" parameter
@ -86,29 +76,12 @@ public class SparqlQueryAjaxController extends VitroAjaxController {
} }
private Model locateModel(VitroRequest vreq, String modelParam) private Model locateModel(VitroRequest vreq, String modelParam) {
throws AjaxControllerException {
Object o = getServletContext().getAttribute("baseOntModelSelector");
if (!(o instanceof OntModelSelector)) {
throw new AjaxControllerException(SC_INTERNAL_SERVER_ERROR,
"OntModelSelector not found");
}
OntModelSelector oms = (OntModelSelector) o;
Model model = null;
if (OPTION_MODEL_USER_ACCOUNTS.equals(modelParam)) { if (OPTION_MODEL_USER_ACCOUNTS.equals(modelParam)) {
model = oms.getUserAccountsModel(); return ModelAccess.on(vreq).getUserAccountsModel();
} else { } else {
// TODO What is the appropriate way to do this? return ModelAccess.on(vreq).getJenaOntModel();
// model = oms.getFullModel();
model = vreq.getJenaOntModel();
} }
if (model == null) {
throw new AjaxControllerException(SC_INTERNAL_SERVER_ERROR,
"Model '' not found.");
}
return model;
} }
private String locateQueryParam(VitroRequest vreq) private String locateQueryParam(VitroRequest vreq)

View file

@ -171,6 +171,9 @@ public class AdminLoginController extends FreemarkerHttpServlet {
body.put("password", password); body.put("password", password);
body.put("newPassword", newPassword); body.put("newPassword", newPassword);
body.put("confirmPassword", confirmPassword); body.put("confirmPassword", confirmPassword);
body.put("minPasswordLength", MIN_PASSWORD_LENGTH);
body.put("maxPasswordLength", MAX_PASSWORD_LENGTH);
for (String code : codes) { for (String code : codes) {
body.put(code, Boolean.TRUE); body.put(code, Boolean.TRUE);

View file

@ -12,6 +12,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean; import edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean;
import edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean.MLevel;
import edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean.Message; import edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean.Message;
/** /**
@ -21,14 +22,15 @@ public class BaseLoginServlet extends HttpServlet {
private static final Log log = LogFactory.getLog(BaseLoginServlet.class); private static final Log log = LogFactory.getLog(BaseLoginServlet.class);
/** A general purpose error message for the user to see. */ /** A general purpose error message for the user to see. */
protected static final Message MESSAGE_LOGIN_FAILED = new LoginProcessBean.Message( protected static Message messageLoginFailed(HttpServletRequest req) {
"External login failed.", LoginProcessBean.MLevel.ERROR); return new LoginProcessBean.Message(req, MLevel.ERROR, "external_login_failed");
}
/** Tell the user that it's nothing personal, they just aren't allowed in. */ /** Tell the user that it's nothing personal, they just aren't allowed in. */
protected static final Message MESSAGE_LOGIN_DISABLED = new LoginProcessBean.Message( protected static Message messageLoginDisabled(HttpServletRequest req) {
"User logins are temporarily disabled while the system is being maintained.", return new LoginProcessBean.Message(req, MLevel.ERROR, "logins_temporarily_disabled");
LoginProcessBean.MLevel.ERROR); }
protected Authenticator getAuthenticator(HttpServletRequest req) { protected Authenticator getAuthenticator(HttpServletRequest req) {
return Authenticator.getInstance(req); return Authenticator.getInstance(req);
} }
@ -40,10 +42,9 @@ public class BaseLoginServlet extends HttpServlet {
*/ */
protected void complainAndReturnToReferrer(HttpServletRequest req, protected void complainAndReturnToReferrer(HttpServletRequest req,
HttpServletResponse resp, String sessionAttributeForReferrer, HttpServletResponse resp, String sessionAttributeForReferrer,
Message message, Object... args) throws IOException { Message message) throws IOException {
log.debug(message.getMessageLevel() + ": " log.debug(message);
+ message.formatMessage(args)); LoginProcessBean.getBean(req).setMessage(message);
LoginProcessBean.getBean(req).setMessage(message, args);
String referrer = (String) req.getSession().getAttribute( String referrer = (String) req.getSession().getAttribute(
sessionAttributeForReferrer); sessionAttributeForReferrer);

View file

@ -25,6 +25,7 @@ import edu.cornell.mannlib.vitro.webapp.beans.SelfEditingConfiguration;
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount; import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
import edu.cornell.mannlib.vitro.webapp.controller.edit.Authenticate; import edu.cornell.mannlib.vitro.webapp.controller.edit.Authenticate;
import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao; import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDao; import edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.jena.LoginEvent; import edu.cornell.mannlib.vitro.webapp.dao.jena.LoginEvent;
@ -302,14 +303,7 @@ public class BasicAuthenticator extends Authenticator {
} }
ServletContext servletContext = session.getServletContext(); ServletContext servletContext = session.getServletContext();
WebappDaoFactory wadf = (WebappDaoFactory) servletContext return ModelAccess.on(servletContext).getWebappDaoFactory();
.getAttribute("webappDaoFactory");
if (wadf == null) {
log.error("no WebappDaoFactory");
return null;
}
return wadf;
} }
@Override @Override

View file

@ -71,7 +71,7 @@ public class LoginExternalAuthReturn extends BaseLoginServlet {
if (externalAuthId == null) { if (externalAuthId == null) {
complainAndReturnToReferrer(req, resp, ATTRIBUTE_REFERRER, complainAndReturnToReferrer(req, resp, ATTRIBUTE_REFERRER,
MESSAGE_LOGIN_FAILED); messageLoginFailed(req));
return; return;
} }
@ -84,7 +84,7 @@ public class LoginExternalAuthReturn extends BaseLoginServlet {
if (!getAuthenticator(req).isUserPermittedToLogin(userAccount)) { if (!getAuthenticator(req).isUserPermittedToLogin(userAccount)) {
log.debug("Logins disabled for " + userAccount); log.debug("Logins disabled for " + userAccount);
complainAndReturnToReferrer(req, resp, ATTRIBUTE_REFERRER, complainAndReturnToReferrer(req, resp, ATTRIBUTE_REFERRER,
MESSAGE_LOGIN_DISABLED); messageLoginDisabled(req));
return; return;
} }
@ -107,7 +107,7 @@ public class LoginExternalAuthReturn extends BaseLoginServlet {
// should have been caught by isUserPermittedToLogin() // should have been caught by isUserPermittedToLogin()
log.debug("Logins disabled for " + userAccount); log.debug("Logins disabled for " + userAccount);
complainAndReturnToReferrer(req, resp, ATTRIBUTE_REFERRER, complainAndReturnToReferrer(req, resp, ATTRIBUTE_REFERRER,
MESSAGE_LOGIN_DISABLED); messageLoginDisabled(req));
return; return;
} }
} }
@ -115,10 +115,10 @@ public class LoginExternalAuthReturn extends BaseLoginServlet {
@Override @Override
protected void complainAndReturnToReferrer(HttpServletRequest req, protected void complainAndReturnToReferrer(HttpServletRequest req,
HttpServletResponse resp, String sessionAttributeForReferrer, HttpServletResponse resp, String sessionAttributeForReferrer,
Message message, Object... args) throws IOException { Message message) throws IOException {
DisplayMessage.setMessage(req, message.formatMessage(args)); DisplayMessage.setMessage(req, message.getText());
super.complainAndReturnToReferrer(req, resp, super.complainAndReturnToReferrer(req, resp,
sessionAttributeForReferrer, message, args); sessionAttributeForReferrer, message);
} }
private void removeLoginProcessArtifacts(HttpServletRequest req) { private void removeLoginProcessArtifacts(HttpServletRequest req) {

View file

@ -53,7 +53,7 @@ public class LoginExternalAuthSetup extends BaseLoginServlet {
if (redirectUrl == null) { if (redirectUrl == null) {
complainAndReturnToReferrer(req, resp, ATTRIBUTE_REFERRER, complainAndReturnToReferrer(req, resp, ATTRIBUTE_REFERRER,
MESSAGE_LOGIN_FAILED); messageLoginFailed(req));
} }
log.debug("redirecting to '" + redirectUrl + "'"); log.debug("redirecting to '" + redirectUrl + "'");

View file

@ -21,6 +21,8 @@ import edu.cornell.mannlib.vitro.webapp.auth.policy.PolicyHelper;
import edu.cornell.mannlib.vitro.webapp.beans.DisplayMessage; import edu.cornell.mannlib.vitro.webapp.beans.DisplayMessage;
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount; import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
import edu.cornell.mannlib.vitro.webapp.controller.Controllers; import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.i18n.I18n;
import edu.cornell.mannlib.vitro.webapp.i18n.I18nBundle;
/** /**
* A user has just completed the login process. What page do we direct them to? * A user has just completed the login process. What page do we direct them to?
@ -30,6 +32,7 @@ public class LoginRedirector {
private final HttpServletRequest request; private final HttpServletRequest request;
private final HttpSession session; private final HttpSession session;
private final I18nBundle i18n;
private final String uriOfAssociatedIndividual; private final String uriOfAssociatedIndividual;
private final String afterLoginPage; private final String afterLoginPage;
@ -37,6 +40,7 @@ public class LoginRedirector {
public LoginRedirector(HttpServletRequest request, String afterLoginPage) { public LoginRedirector(HttpServletRequest request, String afterLoginPage) {
this.request = request; this.request = request;
this.session = request.getSession(); this.session = request.getSession();
this.i18n = I18n.bundle(request);
this.afterLoginPage = afterLoginPage; this.afterLoginPage = afterLoginPage;
uriOfAssociatedIndividual = getAssociatedIndividualUri(); uriOfAssociatedIndividual = getAssociatedIndividualUri();
@ -114,26 +118,23 @@ public class LoginRedirector {
public String assembleWelcomeMessage() { public String assembleWelcomeMessage() {
if (!canSeeSiteAdminPage() && !isSelfEditorWithIndividual()) { if (!canSeeSiteAdminPage() && !isSelfEditorWithIndividual()) {
// A special message for unrecognized self-editors: // A special message for unrecognized self-editors:
return "You have logged in, " return i18n.text("logged_in_but_no_profile");
+ "but the system contains no profile for you.";
} }
String backString = ""; String greeting = i18n.text("unknown_user_name");
String greeting = ""; int loginCount = 0;
UserAccount userAccount = LoginStatusBean.getCurrentUser(request); UserAccount userAccount = LoginStatusBean.getCurrentUser(request);
if (userAccount != null) { if (userAccount != null) {
greeting = userAccount.getEmailAddress(); loginCount = userAccount.getLoginCount();
if (userAccount.getLoginCount() > 1) { if (StringUtils.isNotEmpty(userAccount.getFirstName())) {
backString = " back"; greeting = userAccount.getFirstName();
} } else if (StringUtils.isNotEmpty(userAccount.getEmailAddress())) {
String name = userAccount.getFirstName(); greeting = userAccount.getEmailAddress();
if (!StringUtils.isEmpty(name)) {
greeting = name;
} }
} }
return "Welcome" + backString + ", " + greeting; return i18n.text("login_welcome_message", greeting, loginCount);
} }
public void redirectCancellingUser(HttpServletResponse response) public void redirectCancellingUser(HttpServletResponse response)

View file

@ -4,6 +4,7 @@ package edu.cornell.mannlib.vitro.webapp.controller.edit;
import static edu.cornell.mannlib.vitro.webapp.beans.UserAccount.MAX_PASSWORD_LENGTH; import static edu.cornell.mannlib.vitro.webapp.beans.UserAccount.MAX_PASSWORD_LENGTH;
import static edu.cornell.mannlib.vitro.webapp.beans.UserAccount.MIN_PASSWORD_LENGTH; import static edu.cornell.mannlib.vitro.webapp.beans.UserAccount.MIN_PASSWORD_LENGTH;
import static edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean.MLevel.ERROR;
import static edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean.State.FORCED_PASSWORD_CHANGE; import static edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean.State.FORCED_PASSWORD_CHANGE;
import static edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean.State.LOGGED_IN; import static edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean.State.LOGGED_IN;
import static edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean.State.LOGGING_IN; import static edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean.State.LOGGING_IN;
@ -37,8 +38,8 @@ import edu.cornell.mannlib.vitro.webapp.controller.authenticate.Authenticator.Lo
import edu.cornell.mannlib.vitro.webapp.controller.authenticate.LoginInProcessFlag; import edu.cornell.mannlib.vitro.webapp.controller.authenticate.LoginInProcessFlag;
import edu.cornell.mannlib.vitro.webapp.controller.authenticate.LoginRedirector; import edu.cornell.mannlib.vitro.webapp.controller.authenticate.LoginRedirector;
import edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean; import edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean;
import edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean.Message;
import edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean.State; import edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean.State;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.jena.LoginLogoutEvent; import edu.cornell.mannlib.vitro.webapp.dao.jena.LoginLogoutEvent;
public class Authenticate extends VitroHttpServlet { public class Authenticate extends VitroHttpServlet {
@ -308,7 +309,7 @@ public class Authenticate extends VitroHttpServlet {
+ bean); + bean);
if ((username == null) || username.isEmpty()) { if ((username == null) || username.isEmpty()) {
bean.setMessage(Message.NO_USERNAME); bean.setMessage(request, ERROR, "error_no_email_address");
return; return;
} }
@ -319,22 +320,22 @@ public class Authenticate extends VitroHttpServlet {
log.trace("User is " + (user == null ? "null" : user.getUri())); log.trace("User is " + (user == null ? "null" : user.getUri()));
if (user == null) { if (user == null) {
bean.setMessage(Message.UNKNOWN_USERNAME, username); bean.setMessage(request, ERROR, "error_incorrect_credentials");
return; return;
} }
if ((password == null) || password.isEmpty()) { if ((password == null) || password.isEmpty()) {
bean.setMessage(Message.NO_PASSWORD); bean.setMessage(request, ERROR, "error_no_password");
return; return;
} }
if (!getAuthenticator(request).isUserPermittedToLogin(user)) { if (!getAuthenticator(request).isUserPermittedToLogin(user)) {
bean.setMessage(Message.LOGIN_DISABLED); bean.setMessage(request, ERROR, "logins_disabled_for_maintenance");
return; return;
} }
if (!getAuthenticator(request).isCurrentPassword(user, password)) { if (!getAuthenticator(request).isCurrentPassword(user, password)) {
bean.setMessage(Message.INCORRECT_PASSWORD); bean.setMessage(request, ERROR, "error_incorrect_credentials");
return; return;
} }
@ -346,7 +347,8 @@ public class Authenticate extends VitroHttpServlet {
transitionToLoggedIn(request, user); transitionToLoggedIn(request, user);
} catch (LoginNotPermitted e) { } catch (LoginNotPermitted e) {
// This should have been caught by isUserPermittedToLogin() // This should have been caught by isUserPermittedToLogin()
bean.setMessage(Message.LOGIN_DISABLED); bean.setMessage(request, ERROR,
"logins_disabled_for_maintenance");
return; return;
} }
} }
@ -378,19 +380,19 @@ public class Authenticate extends VitroHttpServlet {
+ ", bean=" + bean); + ", bean=" + bean);
if ((newPassword == null) || newPassword.isEmpty()) { if ((newPassword == null) || newPassword.isEmpty()) {
bean.setMessage(Message.NO_NEW_PASSWORD); bean.setMessage(request, ERROR, "error_no_new_password");
return; return;
} }
if (!newPassword.equals(confirm)) { if (!newPassword.equals(confirm)) {
bean.setMessage(Message.MISMATCH_PASSWORD); bean.setMessage(request, ERROR, "error_passwords_dont_match");
return; return;
} }
if ((newPassword.length() < MIN_PASSWORD_LENGTH) if ((newPassword.length() < MIN_PASSWORD_LENGTH)
|| (newPassword.length() > MAX_PASSWORD_LENGTH)) { || (newPassword.length() > MAX_PASSWORD_LENGTH)) {
bean.setMessage(Message.PASSWORD_LENGTH, MIN_PASSWORD_LENGTH, bean.setMessage(request, ERROR, "error_password_length",
MAX_PASSWORD_LENGTH); MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH);
return; return;
} }
@ -399,7 +401,7 @@ public class Authenticate extends VitroHttpServlet {
UserAccount user = getAuthenticator(request).getAccountForInternalAuth( UserAccount user = getAuthenticator(request).getAccountForInternalAuth(
username); username);
if (getAuthenticator(request).isCurrentPassword(user, newPassword)) { if (getAuthenticator(request).isCurrentPassword(user, newPassword)) {
bean.setMessage(Message.USING_OLD_PASSWORD); bean.setMessage(request, ERROR, "error_previous_password");
return; return;
} }
@ -408,7 +410,7 @@ public class Authenticate extends VitroHttpServlet {
transitionToLoggedIn(request, user, newPassword); transitionToLoggedIn(request, user, newPassword);
} catch (LoginNotPermitted e) { } catch (LoginNotPermitted e) {
// This should have been caught by isUserPermittedToLogin() // This should have been caught by isUserPermittedToLogin()
bean.setMessage(Message.LOGIN_DISABLED); bean.setMessage(request, ERROR, "logins_disabled_for_maintenance");
return; return;
} }
} }
@ -557,16 +559,7 @@ public class Authenticate extends VitroHttpServlet {
return; return;
} }
OntModel jenaOntModel = (OntModel) session.getAttribute("jenaOntModel"); OntModel jenaOntModel = ModelAccess.on(session).getJenaOntModel();
if (jenaOntModel == null) {
jenaOntModel = (OntModel) context.getAttribute("jenaOntModel");
}
if (jenaOntModel == null) {
log.error("Unable to notify audit model of login event "
+ "because no model could be found");
return;
}
jenaOntModel.getBaseModel().notifyEvent(event); jenaOntModel.getBaseModel().notifyEvent(event);
} }

View file

@ -23,6 +23,7 @@ import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.shared.Lock; import com.hp.hpl.jena.shared.Lock;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet; import edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
@ -38,6 +39,9 @@ public class DeletePageController extends VitroHttpServlet {
@Override @Override
protected void doPost(HttpServletRequest rawRequest, HttpServletResponse resp) protected void doPost(HttpServletRequest rawRequest, HttpServletResponse resp)
throws ServletException, IOException { throws ServletException, IOException {
if (!isAuthorizedToDisplayPage(rawRequest, resp, SimplePermission.MANAGE_MENUS.ACTION)) {
return;
}
removeStatements = ModelFactory.createDefaultModel(); removeStatements = ModelFactory.createDefaultModel();
VitroRequest vreq = new VitroRequest(rawRequest); VitroRequest vreq = new VitroRequest(rawRequest);
String pageUri = vreq.getParameter("pageURI"); String pageUri = vreq.getParameter("pageURI");

View file

@ -79,8 +79,7 @@ public class EntityRetryController extends BaseEditController {
} }
LoginStatusBean loginBean = LoginStatusBean.getBean(request); LoginStatusBean loginBean = LoginStatusBean.getBean(request);
WebappDaoFactory myWebappDaoFactory = getWebappDaoFactory( WebappDaoFactory myWebappDaoFactory = getWebappDaoFactory(loginBean.getUserURI());
vreq, loginBean.getUserURI());
IndividualDao ewDao = myWebappDaoFactory.getIndividualDao(); IndividualDao ewDao = myWebappDaoFactory.getIndividualDao();
epo.setDataAccessObject(ewDao); epo.setDataAccessObject(ewDao);

View file

@ -12,6 +12,7 @@ import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.beans.DisplayMessage; import edu.cornell.mannlib.vitro.webapp.beans.DisplayMessage;
import edu.cornell.mannlib.vitro.webapp.controller.authenticate.Authenticator; import edu.cornell.mannlib.vitro.webapp.controller.authenticate.Authenticator;
import edu.cornell.mannlib.vitro.webapp.controller.authenticate.LogoutRedirector; import edu.cornell.mannlib.vitro.webapp.controller.authenticate.LogoutRedirector;
import edu.cornell.mannlib.vitro.webapp.i18n.I18n;
/** /**
* Provide a means for programmatic logout. * Provide a means for programmatic logout.
@ -22,13 +23,14 @@ public class Logout extends HttpServlet {
/** This http header holds the referring page. */ /** This http header holds the referring page. */
private static final String HEADING_REFERRER = "referer"; private static final String HEADING_REFERRER = "referer";
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) { public void doPost(HttpServletRequest request, HttpServletResponse response) {
try { try {
String referrer = getReferringPage(request); String referrer = getReferringPage(request);
String redirectUrl = LogoutRedirector.getRedirectUrl(request, response, referrer); String redirectUrl = LogoutRedirector.getRedirectUrl(request, response, referrer);
Authenticator.getInstance(request).recordUserIsLoggedOut(); Authenticator.getInstance(request).recordUserIsLoggedOut();
DisplayMessage.setMessage(request, "You have logged out."); DisplayMessage.setMessage(request, I18n.bundle(request).text("logged_out"));
response.sendRedirect(redirectUrl); response.sendRedirect(redirectUrl);
} catch (Exception ex) { } catch (Exception ex) {
@ -45,6 +47,7 @@ public class Logout extends HttpServlet {
return referrer; return referrer;
} }
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) { public void doGet(HttpServletRequest request, HttpServletResponse response) {
doPost(request, response); doPost(request, response);
} }

View file

@ -24,6 +24,7 @@ import edu.cornell.mannlib.vedit.beans.EditProcessObject;
import edu.cornell.mannlib.vedit.controller.BaseEditController; import edu.cornell.mannlib.vedit.controller.BaseEditController;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission; import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
public class NamespacePrefixOperationController extends BaseEditController { public class NamespacePrefixOperationController extends BaseEditController {
@ -68,7 +69,7 @@ public class NamespacePrefixOperationController extends BaseEditController {
if (request.getParameter("_cancel") == null) { if (request.getParameter("_cancel") == null) {
OntModel ontModel = (OntModel) getServletContext().getAttribute("jenaOntModel"); OntModel ontModel = ModelAccess.on(getServletContext()).getJenaOntModel();
String namespaceStr = request.getParameter("namespace"); String namespaceStr = request.getParameter("namespace");
String prefixStr = request.getParameter("prefix"); String prefixStr = request.getParameter("prefix");

View file

@ -7,7 +7,6 @@ import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import javax.servlet.RequestDispatcher; import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -40,7 +39,6 @@ import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.shared.InvalidPropertyURIException; import com.hp.hpl.jena.shared.InvalidPropertyURIException;
import com.hp.hpl.jena.shared.Lock; import com.hp.hpl.jena.shared.Lock;
import com.hp.hpl.jena.util.ResourceUtils; import com.hp.hpl.jena.util.ResourceUtils;
import com.hp.hpl.jena.util.iterator.ClosableIterator;
import com.hp.hpl.jena.util.iterator.ExtendedIterator; import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDF;
@ -50,7 +48,8 @@ import edu.cornell.mannlib.vedit.controller.BaseEditController;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission; import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.controller.Controllers; import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.jena.ModelContext; import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess.ModelID;
import edu.cornell.mannlib.vitro.webapp.dao.jena.event.EditEvent; import edu.cornell.mannlib.vitro.webapp.dao.jena.event.EditEvent;
import edu.cornell.mannlib.vitro.webapp.servlet.setup.FileGraphSetup; import edu.cornell.mannlib.vitro.webapp.servlet.setup.FileGraphSetup;
import edu.cornell.mannlib.vitro.webapp.servlet.setup.JenaDataSourceSetupBase; import edu.cornell.mannlib.vitro.webapp.servlet.setup.JenaDataSourceSetupBase;
@ -74,7 +73,7 @@ public class RefactorOperationController extends BaseEditController {
request.setAttribute("title","Check Datatype Properties"); request.setAttribute("title","Check Datatype Properties");
request.setAttribute("css", "<link rel=\"stylesheet\" type=\"text/css\" href=\""+vreq.getAppBean().getThemeDir()+"css/edit.css\"/>"); request.setAttribute("css", "<link rel=\"stylesheet\" type=\"text/css\" href=\""+vreq.getAppBean().getThemeDir()+"css/edit.css\"/>");
OntModel ontModel = (OntModel) getServletContext().getAttribute("baseOntModel"); OntModel ontModel = ModelAccess.on(getServletContext()).getBaseOntModel();
ontModel.enterCriticalSection(Lock.WRITE); ontModel.enterCriticalSection(Lock.WRITE);
ArrayList<String> results = new ArrayList<String>(); ArrayList<String> results = new ArrayList<String>();
@ -236,10 +235,10 @@ public class RefactorOperationController extends BaseEditController {
Model model = null; Model model = null;
if (JenaDataSourceSetupBase.JENA_TBOX_ASSERTIONS_MODEL.equals(graphURI)) { if (JenaDataSourceSetupBase.JENA_TBOX_ASSERTIONS_MODEL.equals(graphURI)) {
model = ModelContext.getBaseOntModelSelector(getServletContext()).getTBoxModel(); model = ModelAccess.on(getServletContext()).getOntModel(ModelID.BASE_TBOX);
doNotify = true; doNotify = true;
} else if (JenaDataSourceSetupBase.JENA_DB_MODEL.equals(graphURI)) { } else if (JenaDataSourceSetupBase.JENA_DB_MODEL.equals(graphURI)) {
model = ModelContext.getBaseOntModelSelector(getServletContext()).getABoxModel(); model = ModelAccess.on(getServletContext()).getOntModel(ModelID.BASE_ABOX);
doNotify = true; doNotify = true;
} else { } else {
model = dataset.getNamedModel(graphURI); model = dataset.getNamedModel(graphURI);
@ -252,8 +251,7 @@ public class RefactorOperationController extends BaseEditController {
dataset.getLock().leaveCriticalSection(); dataset.getLock().leaveCriticalSection();
} }
renameResourceInModel(ModelContext.getOntModelSelector( renameResourceInModel(ModelAccess.on(getServletContext()).getUserAccountsModel(),
getServletContext()).getUserAccountsModel(),
userURI, oldURIStr, newURIStr, !NOTIFY); userURI, oldURIStr, newURIStr, !NOTIFY);
// there are no statements to delete, but we want indexes updated appropriately // there are no statements to delete, but we want indexes updated appropriately
@ -330,7 +328,7 @@ public class RefactorOperationController extends BaseEditController {
private void doMovePropertyStatements(VitroRequest request, HttpServletResponse response, EditProcessObject epo) { private void doMovePropertyStatements(VitroRequest request, HttpServletResponse response, EditProcessObject epo) {
String userURI = LoginStatusBean.getBean(request).getUserURI(); String userURI = LoginStatusBean.getBean(request).getUserURI();
OntModel ontModel = ModelContext.getBaseOntModel(getServletContext()); OntModel ontModel = ModelAccess.on(getServletContext()).getBaseOntModel();
Model tempRetractModel = ModelFactory.createDefaultModel(); Model tempRetractModel = ModelFactory.createDefaultModel();
Model tempAddModel = ModelFactory.createDefaultModel(); Model tempAddModel = ModelFactory.createDefaultModel();
@ -414,7 +412,7 @@ public class RefactorOperationController extends BaseEditController {
private void doMoveInstances(VitroRequest request, HttpServletResponse response, EditProcessObject epo) { private void doMoveInstances(VitroRequest request, HttpServletResponse response, EditProcessObject epo) {
String userURI = LoginStatusBean.getBean(request).getUserURI(); String userURI = LoginStatusBean.getBean(request).getUserURI();
OntModel ontModel = ModelContext.getBaseOntModel(getServletContext()); OntModel ontModel = ModelAccess.on(getServletContext()).getBaseOntModel();
String oldClassURIStr = (String) epo.getAttribute("VClassURI"); String oldClassURIStr = (String) epo.getAttribute("VClassURI");
String newClassURIStr = (String) request.getParameter("NewVClassURI"); String newClassURIStr = (String) request.getParameter("NewVClassURI");

View file

@ -27,6 +27,7 @@ import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup; import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup;
import edu.cornell.mannlib.vitro.webapp.controller.Controllers; import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.OntologyDao; import edu.cornell.mannlib.vitro.webapp.dao.OntologyDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao; import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassGroupDao; import edu.cornell.mannlib.vitro.webapp.dao.VClassGroupDao;
@ -52,8 +53,8 @@ public class ClassHierarchyListingController extends BaseEditController {
try { try {
boolean inferred = (vrequest.getParameter("inferred") != null); boolean inferred = (vrequest.getParameter("inferred") != null);
if (vrequest.getAssertionsWebappDaoFactory() != null && !inferred) { if (!inferred) {
vcDao = vrequest.getAssertionsWebappDaoFactory().getVClassDao(); vcDao = ModelAccess.on(vrequest).getBaseWebappDaoFactory().getVClassDao();
} else { } else {
vcDao = vrequest.getFullWebappDaoFactory().getVClassDao(); vcDao = vrequest.getFullWebappDaoFactory().getVClassDao();
} }

View file

@ -22,6 +22,7 @@ import edu.cornell.mannlib.vedit.controller.BaseEditController;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission; import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.controller.Controllers; import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
public class NamespacesListingController extends BaseEditController { public class NamespacesListingController extends BaseEditController {
@ -34,7 +35,7 @@ public class NamespacesListingController extends BaseEditController {
VitroRequest vrequest = new VitroRequest(request); VitroRequest vrequest = new VitroRequest(request);
OntModel ontModel = (OntModel) getServletContext().getAttribute("jenaOntModel"); OntModel ontModel = ModelAccess.on(getServletContext()).getJenaOntModel();
ArrayList results = new ArrayList(); ArrayList results = new ArrayList();
request.setAttribute("results",results); request.setAttribute("results",results);

View file

@ -33,6 +33,7 @@ import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.controller.Controllers; import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao; import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyDao; import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao; import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
@ -51,8 +52,8 @@ public class RestrictionsListingController extends BaseEditController {
epo = super.createEpo(request); epo = super.createEpo(request);
OntModel ontModel = (OntModel) getServletContext().getAttribute("jenaOntModel"); OntModel ontModel = ModelAccess.on(getServletContext()).getJenaOntModel();
ObjectPropertyDao opDao = vrequest.getFullWebappDaoFactory().getObjectPropertyDao(); ObjectPropertyDao opDao = vrequest.getFullWebappDaoFactory().getObjectPropertyDao();
VClassDao vcDao = vrequest.getFullWebappDaoFactory().getVClassDao(); VClassDao vcDao = vrequest.getFullWebappDaoFactory().getVClassDao();
IndividualDao iDao = vrequest.getFullWebappDaoFactory().getIndividualDao(); IndividualDao iDao = vrequest.getFullWebappDaoFactory().getIndividualDao();

View file

@ -17,6 +17,7 @@ import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
import edu.cornell.mannlib.vitro.webapp.dao.VClassGroupsForRequest;
import edu.cornell.mannlib.vitro.webapp.dao.jena.VClassGroupCache; import edu.cornell.mannlib.vitro.webapp.dao.jena.VClassGroupCache;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.VClassGroupTemplateModel; import edu.cornell.mannlib.vitro.webapp.web.templatemodels.VClassGroupTemplateModel;
@ -46,7 +47,6 @@ public class BrowseController extends FreemarkerHttpServlet {
protected ResponseValues processRequest(VitroRequest vreq) { protected ResponseValues processRequest(VitroRequest vreq) {
Map<String, Object> body = new HashMap<String, Object>(); Map<String, Object> body = new HashMap<String, Object>();
String message = null;
String templateName = TEMPLATE_DEFAULT; String templateName = TEMPLATE_DEFAULT;
if ( vreq.getParameter("clearcache") != null ) { if ( vreq.getParameter("clearcache") != null ) {
@ -57,25 +57,13 @@ public class BrowseController extends FreemarkerHttpServlet {
} }
List<VClassGroup> groups = null; List<VClassGroup> groups = null;
VClassGroupCache vcgc = VClassGroupCache.getVClassGroupCache(getServletContext()); VClassGroupsForRequest vcgc = VClassGroupCache.getVClassGroups(vreq);
if ( vcgc == null ) { groups =vcgc.getGroups();
log.error("Could not get VClassGroupCache"); List<VClassGroupTemplateModel> vcgroups = new ArrayList<VClassGroupTemplateModel>(groups.size());
message = "The system is not configured correctly. Please check your logs for error messages."; for (VClassGroup group : groups) {
} else { vcgroups.add(new VClassGroupTemplateModel(group));
groups =vcgc.getGroups();
List<VClassGroupTemplateModel> vcgroups = new ArrayList<VClassGroupTemplateModel>(groups.size());
for (VClassGroup group : groups) {
vcgroups.add(new VClassGroupTemplateModel(group));
}
body.put("classGroups", vcgroups);
} }
body.put("classGroups", vcgroups);
if (message != null) {
body.put("message", message);
templateName = Template.TITLED_MESSAGE.toString();
}
return new TemplateResponseValues(templateName, body); return new TemplateResponseValues(templateName, body);
} }

View file

@ -17,6 +17,7 @@ import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.RedirectResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.RedirectResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditN3Utils; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditN3Utils;
@ -200,7 +201,7 @@ public class DeletePropertyController extends FreemarkerHttpServlet {
Individual object = EditConfigurationUtils.getIndividual(vreq, objectUri); Individual object = EditConfigurationUtils.getIndividual(vreq, objectUri);
if(object == null) { if(object == null) {
WebappDaoFactory wadf = (WebappDaoFactory) vreq.getSession().getServletContext().getAttribute("webappDaoFactory"); WebappDaoFactory wadf = ModelAccess.on(vreq.getSession().getServletContext()).getWebappDaoFactory();
object = wadf.getIndividualDao().getIndividualByURI(objectUri); object = wadf.getIndividualDao().getIndividualByURI(objectUri);
} }

View file

@ -9,6 +9,7 @@ import java.util.List;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
@ -48,6 +49,7 @@ public class HomePageController extends FreemarkerHttpServlet {
} }
}*/ }*/
body.put("dataServiceUrlVClassesForVClassGroup", UrlBuilder.getUrl("/dataservice?getVClassesForVClassGroup=1&classgroupUri=")); body.put("dataServiceUrlVClassesForVClassGroup", UrlBuilder.getUrl("/dataservice?getVClassesForVClassGroup=1&classgroupUri="));
body.put("geoFocusMapsEnabled", getGeoFocusMapsFlag(vreq));
return new TemplateResponseValues(BODY_TEMPLATE, body); return new TemplateResponseValues(BODY_TEMPLATE, body);
} }
@ -61,4 +63,11 @@ public class HomePageController extends FreemarkerHttpServlet {
protected String getPageTemplateName() { protected String getPageTemplateName() {
return PAGE_TEMPLATE; return PAGE_TEMPLATE;
} }
private boolean getGeoFocusMapsFlag(VitroRequest vreq) {
String property = ConfigurationProperties.getBean(vreq).getProperty(
"homePage.geoFocusMaps");
return "enabled".equals(property);
}
} }

View file

@ -36,6 +36,7 @@ import edu.cornell.mannlib.vitro.webapp.filestorage.backend.FileStorageSetup;
import edu.cornell.mannlib.vitro.webapp.filestorage.model.FileInfo; import edu.cornell.mannlib.vitro.webapp.filestorage.model.FileInfo;
import edu.cornell.mannlib.vitro.webapp.filestorage.model.ImageInfo; import edu.cornell.mannlib.vitro.webapp.filestorage.model.ImageInfo;
import edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.FileUploadServletRequest; import edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.FileUploadServletRequest;
import edu.cornell.mannlib.vitro.webapp.i18n.I18n;
import edu.cornell.mannlib.vitro.webapp.web.images.PlaceholderUtil; import edu.cornell.mannlib.vitro.webapp.web.images.PlaceholderUtil;
/** /**
@ -48,6 +49,9 @@ public class ImageUploadController extends FreemarkerHttpServlet {
private static final String ATTRIBUTE_REFERRING_PAGE = "ImageUploadController.referringPage"; private static final String ATTRIBUTE_REFERRING_PAGE = "ImageUploadController.referringPage";
private static final String ERROR_CODE_UNRECOGNIZED_URI = "imageUpload.errorUnrecognizedURI";
private static final String ERROR_CODE_NO_URI = "imageUpload.errorNoURI";
/** Limit file size to 6 megabytes. */ /** Limit file size to 6 megabytes. */
public static final int MAXIMUM_FILE_SIZE = 6 * 1024 * 1024; public static final int MAXIMUM_FILE_SIZE = 6 * 1024 * 1024;
@ -97,6 +101,14 @@ public class ImageUploadController extends FreemarkerHttpServlet {
private static final String URL_HERE = UrlBuilder.getUrl("/uploadImages"); private static final String URL_HERE = UrlBuilder.getUrl("/uploadImages");
private static final String TEXT_BUNDLE = "imageUpload";
private static final String TEXT_STRING_UPLOAD_TITLE = "upload_page_title";
private static final String TEXT_STRING_UPLOAD_TITLE_WITH_NAME = "upload_page_title_with_name";
private static final String TEXT_STRING_REPLACE_TITLE = "replace_page_title";
private static final String TEXT_STRING_REPLACE_TITLE_WITH_NAME = "replace_page_title_with_name";
private static final String TEXT_STRING_CROP_TITLE = "crop_page_title";
private static final String TEXT_STRING_CROP_TITLE_WITH_NAME = "crop_page_title_with_name";
private FileStorage fileStorage; private FileStorage fileStorage;
/** /**
@ -218,7 +230,7 @@ public class ImageUploadController extends FreemarkerHttpServlet {
} }
} catch (UserMistakeException e) { } catch (UserMistakeException e) {
// Can't find the entity? Complain. // Can't find the entity? Complain.
return showAddImagePageWithError(vreq, null, e.getMessage()); return showAddImagePageWithError(vreq, null, e.formatMessage(vreq));
} catch (Exception e) { } catch (Exception e) {
// We weren't expecting this - log it, and apologize to the user. // We weren't expecting this - log it, and apologize to the user.
return new ExceptionResponseValues(e); return new ExceptionResponseValues(e);
@ -274,7 +286,7 @@ public class ImageUploadController extends FreemarkerHttpServlet {
return showCropImagePage(vreq, entity, return showCropImagePage(vreq, entity,
fileInfo.getBytestreamAliasUrl(), size); fileInfo.getBytestreamAliasUrl(), size);
} catch (UserMistakeException e) { } catch (UserMistakeException e) {
return showErrorMessage(vreq, entity, e.getMessage()); return showErrorMessage(vreq, entity, e.formatMessage(vreq));
} }
} }
@ -284,6 +296,7 @@ public class ImageUploadController extends FreemarkerHttpServlet {
*/ */
private ResponseValues showErrorMessage(VitroRequest vreq, private ResponseValues showErrorMessage(VitroRequest vreq,
Individual entity, String message) { Individual entity, String message) {
ImageInfo imageInfo = ImageInfo.instanceFromEntityUri( ImageInfo imageInfo = ImageInfo.instanceFromEntityUri(
vreq.getFullWebappDaoFactory(), entity); vreq.getFullWebappDaoFactory(), entity);
if (imageInfo == null) { if (imageInfo == null) {
@ -313,7 +326,7 @@ public class ImageUploadController extends FreemarkerHttpServlet {
return showExitPage(vreq, entity); return showExitPage(vreq, entity);
} catch (UserMistakeException e) { } catch (UserMistakeException e) {
return showErrorMessage(vreq, entity, e.getMessage()); return showErrorMessage(vreq, entity, e.formatMessage(vreq));
} }
} }
@ -350,15 +363,14 @@ public class ImageUploadController extends FreemarkerHttpServlet {
throws UserMistakeException { throws UserMistakeException {
String entityUri = vreq.getParameter(PARAMETER_ENTITY_URI); String entityUri = vreq.getParameter(PARAMETER_ENTITY_URI);
if (entityUri == null) { if (entityUri == null) {
throw new UserMistakeException("No entity URI was provided"); throw new UserMistakeException(ERROR_CODE_NO_URI);
} }
Individual entity = vreq.getFullWebappDaoFactory().getIndividualDao() Individual entity = vreq.getFullWebappDaoFactory().getIndividualDao()
.getIndividualByURI(entityUri); .getIndividualByURI(entityUri);
if (entity == null) { if (entity == null) {
throw new UserMistakeException( throw new UserMistakeException(ERROR_CODE_UNRECOGNIZED_URI,
"This URI is not recognized as belonging to anyone: '" entityUri);
+ entityUri + "'");
} }
return entity; return entity;
} }
@ -416,7 +428,7 @@ public class ImageUploadController extends FreemarkerHttpServlet {
rv.put(BODY_THUMBNAIL_URL, placeholderUrl); rv.put(BODY_THUMBNAIL_URL, placeholderUrl);
rv.put(BODY_FORM_ACTION, formAction); rv.put(BODY_FORM_ACTION, formAction);
rv.put(BODY_CANCEL_URL, cancelUrl); rv.put(BODY_CANCEL_URL, cancelUrl);
rv.put(BODY_TITLE, "Upload image" + forName(entity)); rv.put(BODY_TITLE, figureUploadPageTitle(vreq, entity));
rv.put(BODY_MAX_FILE_SIZE, MAXIMUM_FILE_SIZE / (1024 * 1024)); rv.put(BODY_MAX_FILE_SIZE, MAXIMUM_FILE_SIZE / (1024 * 1024));
rv.put(BODY_THUMBNAIL_HEIGHT, THUMBNAIL_HEIGHT); rv.put(BODY_THUMBNAIL_HEIGHT, THUMBNAIL_HEIGHT);
rv.put(BODY_THUMBNAIL_WIDTH, THUMBNAIL_WIDTH); rv.put(BODY_THUMBNAIL_WIDTH, THUMBNAIL_WIDTH);
@ -442,7 +454,7 @@ public class ImageUploadController extends FreemarkerHttpServlet {
rv.put(BODY_DELETE_URL, formAction(entity.getURI(), ACTION_DELETE_EDIT)); rv.put(BODY_DELETE_URL, formAction(entity.getURI(), ACTION_DELETE_EDIT));
rv.put(BODY_FORM_ACTION, formAction(entity.getURI(), ACTION_UPLOAD)); rv.put(BODY_FORM_ACTION, formAction(entity.getURI(), ACTION_UPLOAD));
rv.put(BODY_CANCEL_URL, exitPageUrl(vreq, entity.getURI())); rv.put(BODY_CANCEL_URL, exitPageUrl(vreq, entity.getURI()));
rv.put(BODY_TITLE, "Replace image" + forName(entity)); rv.put(BODY_TITLE, figureReplacePageTitle(vreq, entity));
rv.put(BODY_MAX_FILE_SIZE, MAXIMUM_FILE_SIZE / (1024 * 1024)); rv.put(BODY_MAX_FILE_SIZE, MAXIMUM_FILE_SIZE / (1024 * 1024));
rv.put(BODY_THUMBNAIL_HEIGHT, THUMBNAIL_HEIGHT); rv.put(BODY_THUMBNAIL_HEIGHT, THUMBNAIL_HEIGHT);
rv.put(BODY_THUMBNAIL_WIDTH, THUMBNAIL_WIDTH); rv.put(BODY_THUMBNAIL_WIDTH, THUMBNAIL_WIDTH);
@ -472,7 +484,7 @@ public class ImageUploadController extends FreemarkerHttpServlet {
rv.put(BODY_MAIN_IMAGE_WIDTH, dimensions.width); rv.put(BODY_MAIN_IMAGE_WIDTH, dimensions.width);
rv.put(BODY_FORM_ACTION, formAction(entity.getURI(), ACTION_SAVE)); rv.put(BODY_FORM_ACTION, formAction(entity.getURI(), ACTION_SAVE));
rv.put(BODY_CANCEL_URL, exitPageUrl(vreq, entity.getURI())); rv.put(BODY_CANCEL_URL, exitPageUrl(vreq, entity.getURI()));
rv.put(BODY_TITLE, "Crop Photo" + forName(entity)); rv.put(BODY_TITLE, figureCropPageTitle(vreq, entity));
return rv; return rv;
} }
@ -522,24 +534,59 @@ public class ImageUploadController extends FreemarkerHttpServlet {
} }
/** /**
* Format the entity's name for display as part of the page title. * Format the title for the Upload page.
*/ */
private String forName(Individual entity) { private String figureUploadPageTitle(HttpServletRequest req,
Individual entity) {
return figurePageTitle(req, entity, TEXT_STRING_UPLOAD_TITLE,
TEXT_STRING_UPLOAD_TITLE_WITH_NAME);
}
/**
* Format the title for the Replace page.
*/
private String figureReplacePageTitle(HttpServletRequest req,
Individual entity) {
return figurePageTitle(req, entity, TEXT_STRING_REPLACE_TITLE,
TEXT_STRING_REPLACE_TITLE_WITH_NAME);
}
/**
* Format the title for the Crop page.
*/
private String figureCropPageTitle(HttpServletRequest req, Individual entity) {
return figurePageTitle(req, entity, TEXT_STRING_CROP_TITLE,
TEXT_STRING_CROP_TITLE_WITH_NAME);
}
/**
* Format one of two page titles, depending on whether the entity has a
* name.
*/
private String figurePageTitle(HttpServletRequest req, Individual entity,
String noNameTitleKey, String nameTitleKey) {
if (entity != null) { if (entity != null) {
String name = entity.getName(); String name = entity.getName();
if (name != null) { if (name != null) {
return " for " + name; return I18n.text(req, TEXT_BUNDLE, nameTitleKey, name);
} }
} }
return ""; return I18n.text(req, TEXT_BUNDLE, noNameTitleKey);
} }
/** /**
* Holds an error message to use as a complaint to the user. * Holds an error message to use as a complaint to the user.
*/ */
static class UserMistakeException extends Exception { static class UserMistakeException extends Exception {
UserMistakeException(String message) { private final Object[] parameters;
UserMistakeException(String message, Object... parameters) {
super(message); super(message);
this.parameters = parameters;
}
public String formatMessage(HttpServletRequest req) {
return I18n.text(req, getMessage(), parameters);
} }
} }

View file

@ -49,6 +49,18 @@ import edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.FileUploadServ
public class ImageUploadHelper { public class ImageUploadHelper {
private static final Log log = LogFactory.getLog(ImageUploadHelper.class); private static final Log log = LogFactory.getLog(ImageUploadHelper.class);
/*
* Keys to text strings for error messages.
*/
private static final String ERROR_CODE_NO_IMAGE_TO_CROP = "imageUpload.errorNoImageForCropping";
private static final String ERROR_CODE_IMAGE_TOO_SMALL = "imageUpload.errorImageTooSmall";
private static final String ERROR_CODE_UNKNOWN = "imageUpload.errorUnknown";
private static final String ERROR_CODE_FILE_TOO_BIG = "imageUpload.errorFileTooBig";
private static final String ERROR_CODE_UNRECOGNIZED_FILE_TYPE = "imageUpload.errorUnrecognizedFileType";
private static final String ERROR_CODE_NO_PHOTO_SELECTED = "imageUpload.errorNoPhotoSelected";
private static final String ERROR_CODE_BAD_MULTIPART_REQUEST = "imageUpload.errorBadMultipartRequest";
private static final String ERROR_CODE_FORM_FIELD_MISSING = "imageUpload.errorFormFieldMissing";
/** /**
* When they upload a new image, store it as this session attribute until * When they upload a new image, store it as this session attribute until
* we're ready to attach it to the Individual. * we're ready to attach it to the Individual.
@ -127,35 +139,31 @@ public class ImageUploadHelper {
Object exception = request.getAttribute(FILE_UPLOAD_EXCEPTION); Object exception = request.getAttribute(FILE_UPLOAD_EXCEPTION);
if (exception != null) { if (exception != null) {
int limit = MAXIMUM_FILE_SIZE / (1024 * 1024); int limit = MAXIMUM_FILE_SIZE / (1024 * 1024);
throw new UserMistakeException( throw new UserMistakeException(ERROR_CODE_FILE_TOO_BIG, limit);
"Please upload an image smaller than " + limit
+ " megabytes");
} }
Map<String, List<FileItem>> map = (Map<String, List<FileItem>>) request Map<String, List<FileItem>> map = (Map<String, List<FileItem>>) request
.getAttribute(FILE_ITEM_MAP); .getAttribute(FILE_ITEM_MAP);
if (map == null) { if (map == null) {
throw new IllegalStateException("Failed to parse the " throw new IllegalStateException(ERROR_CODE_BAD_MULTIPART_REQUEST);
+ "multi-part request for uploading an image.");
} }
List<FileItem> list = map.get(PARAMETER_UPLOADED_FILE); List<FileItem> list = map.get(PARAMETER_UPLOADED_FILE);
if ((list == null) || list.isEmpty()) { if ((list == null) || list.isEmpty()) {
throw new UserMistakeException("The form did not contain a '" throw new UserMistakeException(ERROR_CODE_FORM_FIELD_MISSING,
+ PARAMETER_UPLOADED_FILE + "' field."); PARAMETER_UPLOADED_FILE);
} }
FileItem file = list.get(0); FileItem file = list.get(0);
if (file.getSize() == 0) { if (file.getSize() == 0) {
throw new UserMistakeException("Please browse and select a photo."); throw new UserMistakeException(ERROR_CODE_NO_PHOTO_SELECTED);
} }
String filename = getSimpleFilename(file); String filename = getSimpleFilename(file);
String mimeType = getMimeType(file); String mimeType = getMimeType(file);
if (!RECOGNIZED_FILE_TYPES.containsValue(mimeType)) { if (!RECOGNIZED_FILE_TYPES.containsValue(mimeType)) {
log.debug("Unrecognized MIME type: '" + mimeType + "'"); log.debug("Unrecognized MIME type: '" + mimeType + "'");
throw new UserMistakeException("'" + filename throw new UserMistakeException(ERROR_CODE_UNRECOGNIZED_FILE_TYPE,
+ "' is not a recognized image file type. " filename);
+ "Please upload JPEG, GIF, or PNG files only.");
} }
return file; return file;
@ -221,10 +229,8 @@ public class ImageUploadHelper {
if ((size.height < THUMBNAIL_HEIGHT) if ((size.height < THUMBNAIL_HEIGHT)
|| (size.width < THUMBNAIL_WIDTH)) { || (size.width < THUMBNAIL_WIDTH)) {
throw new UserMistakeException( throw new UserMistakeException(ERROR_CODE_IMAGE_TOO_SMALL,
"The uploaded image should be at least " THUMBNAIL_HEIGHT, THUMBNAIL_WIDTH);
+ THUMBNAIL_HEIGHT + " pixels high and "
+ THUMBNAIL_WIDTH + " pixels wide.");
} }
return size; return size;
@ -237,8 +243,7 @@ public class ImageUploadHelper {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
log.warn("Unexpected exception in image handling", e); log.warn("Unexpected exception in image handling", e);
throw new UserMistakeException("Sorry, we were unable to process " throw new UserMistakeException(ERROR_CODE_UNKNOWN);
+ "the photo you provided. Please try another photo.");
} finally { } finally {
if (source != null) { if (source != null) {
try { try {
@ -261,8 +266,7 @@ public class ImageUploadHelper {
ATTRIBUTE_TEMP_FILE); ATTRIBUTE_TEMP_FILE);
if (fileInfo == null) { if (fileInfo == null) {
throw new UserMistakeException( throw new UserMistakeException(ERROR_CODE_NO_IMAGE_TO_CROP);
"There is no image file to be cropped.");
} }
return fileInfo; return fileInfo;

View file

@ -182,8 +182,19 @@ public class IndividualListController extends FreemarkerHttpServlet {
} }
return rvMap; return rvMap;
} }
public static Map<String,Object> getRandomResultsForVClass(String vclassURI, int page, int pageSize, IndividualDao indDao, ServletContext context) {
Map<String,Object> rvMap = new HashMap<String,Object>();
try{
List<String> classUris = Collections.singletonList(vclassURI);
IndividualListQueryResults results = SolrQueryUtils.buildAndExecuteRandomVClassQuery(classUris, page, pageSize, context, indDao);
rvMap = getResultsForVClassQuery(results, page, pageSize, "");
} catch(Throwable th) {
log.error("An error occurred retrieving random results for vclass query", th);
}
return rvMap;
}
//TODO: Get rid of this method and utilize SolrQueryUtils - currently appears to be referenced //TODO: Get rid of this method and utilize SolrQueryUtils - currently appears to be referenced
//only within DataGetterUtils //only within DataGetterUtils
public static long getIndividualCount(List<String> vclassUris, IndividualDao indDao, ServletContext context) { public static long getIndividualCount(List<String> vclassUris, IndividualDao indDao, ServletContext context) {

View file

@ -73,7 +73,7 @@ public class ListPropertyGroupsController extends FreemarkerHttpServlet {
publicName = publicName.replace("\"","\\\""); publicName = publicName.replace("\"","\\\"");
publicName = publicName.replace("\'","\\\'"); publicName = publicName.replace("\'","\\\'");
try { try {
json += "{ \"name\": \"<a href='./editForm?uri="+URLEncoder.encode(pg.getURI(),"UTF-8")+"&amp;controller=Classgroup'>" + publicName + "</a>\", "; json += "{ \"name\": \"<a href='./editForm?uri="+URLEncoder.encode(pg.getURI(),"UTF-8")+"&amp;controller=PropertyGroup'>" + publicName + "</a>\", ";
} catch (Exception e) { } catch (Exception e) {
json += "{ \"name\": \"" + publicName + "\", "; json += "{ \"name\": \"" + publicName + "\", ";
} }

View file

@ -1,216 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.listeners.StatementListener;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.NodeIterator;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
import freemarker.template.Configuration;
import static edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary.DISPLAY_ONT_MODEL;
public class NavigationController extends FreemarkerHttpServlet {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(NavigationController.class.getName());
//private Map<Pattern,String> urlPatternToURI;
private NavigationURLPatternListener urlPatterns;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
OntModel displayOntModel = (OntModel)config.getServletContext().getAttribute(DISPLAY_ONT_MODEL);
this.urlPatterns = new NavigationURLPatternListener( );
displayOntModel.getBaseModel().register( urlPatterns );
}
@Override
protected ResponseValues processRequest(VitroRequest vreq) {
OntModel displayOntModel = (OntModel)getServletContext().getAttribute(DISPLAY_ONT_MODEL);
OntModel jenaOntModel = (OntModel)getServletContext().getAttribute("jenaOntModel");
//figure out what is being requested
Individual ind = urlPatterns.getDisplayIndividual(vreq.getPathInfo(),displayOntModel);
Map<String,Object> values = getValues(ind, displayOntModel,jenaOntModel, getValuesFromRequest(/*?*/) );
String template = getTemplate(ind, displayOntModel);
return new TemplateResponseValues(template, values);
}
private Map<String,Object>getValuesFromRequest(){
// TODO: figure out how to get request for FreeMarkerHttpServlet.
return Collections.emptyMap();
}
private String getTemplate(Individual ind, OntModel displayOntModel) {
if( ind == null ) return "defaultBody";
// check vitroDisplay:requiresBodyTemplate
displayOntModel.enterCriticalSection(Model.READ);
StmtIterator it = displayOntModel.listStatements(ind, DisplayVocabulary.REQUIRES_BODY_TEMPLATE, (RDFNode) null);
//NodeIterator it = ind.listPropertyValues(DisplayVocabulary.REQUIRES_BODY_TEMPLATE);
try{
while(it.hasNext()){
Statement stmt = it.nextStatement();
if( stmt.getObject().isLiteral() ){
String template = ((Literal)stmt.getObject().as(Literal.class)).getLexicalForm();
if( template != null && template.length() > 0 ){
return template;
}
}
}
}finally{
it.close();
displayOntModel.leaveCriticalSection();
}
return "defaultBody";
}
Map<String,Object> getValues(Individual ind, OntModel displayOntModel, OntModel assertionModel, Map<String,Object> baseValues){
if( ind == null ) return Collections.emptyMap();
/* Figure out what ValueFactories are specified in the display ontology for this individual. */
Set<ValueFactory> valueFactories = new HashSet<ValueFactory>();
displayOntModel.enterCriticalSection(Model.READ);
StmtIterator stmts = ind.listProperties(DisplayVocabulary.REQUIRES_VALUES);
try{
while(stmts.hasNext()){
Statement stmt = stmts.nextStatement();
RDFNode obj = stmt.getObject();
valueFactories.addAll(getValueFactory(obj,displayOntModel));
}
}finally{
stmts.close();
displayOntModel.leaveCriticalSection();
}
/* Get values from the ValueFactories. */
HashMap<String,Object> values = new HashMap<String,Object>();
values.putAll(baseValues);
for(ValueFactory vf : valueFactories){
values.putAll( vf.getValues(assertionModel, values));
}
return values;
}
protected Set<ValueFactory> getValueFactory( RDFNode valueNode, OntModel displayOntModel) {
//maybe use jenabean or owl2java for this?
if( valueNode.isResource() ){
Resource res = (Resource)valueNode.as(Resource.class);
Statement stmt = res.getProperty(DisplayVocabulary.JAVA_CLASS_NAME);
if( stmt == null || !stmt.getObject().isLiteral() ){
log.debug("Cannot build value factory: java class was " + stmt.getObject());
return Collections.emptySet();
}
String javaClassName = ((Literal)stmt.getObject().as(Literal.class)).getLexicalForm();
if( javaClassName == null || javaClassName.length() == 0 ){
log.debug("Cannot build value factory: no java class was set.");
return Collections.emptySet();
}
Class<?> clazz;
Object newObj;
try {
clazz = Class.forName(javaClassName);
} catch (ClassNotFoundException e) {
log.debug("Cannot build value factory: no class found for " + javaClassName);
return Collections.emptySet();
}
try {
newObj = clazz.newInstance();
} catch (Exception e) {
log.debug("Cannot build value factory: exception while creating object of java class " + javaClassName + " " + e.getMessage());
return Collections.emptySet();
}
if( newObj instanceof ValueFactory){
ValueFactory valueFactory = (ValueFactory)newObj;
return Collections.singleton( valueFactory );
}else{
log.debug("Cannot build value factory: " + javaClassName + " does not implement " + ValueFactory.class.getName() );
return Collections.emptySet();
}
}else{
log.debug("Cannot build value factory for " + valueNode);
return Collections.emptySet();
}
}
interface ValueFactory {
void configure( Map<String,String> config);
Map<String,Object> getValues(OntModel model, Map<String,Object> values);
}
private class NavigationURLPatternListener extends StatementListener {
private Map<Pattern,String> urlPatternToURI;
public synchronized Map<Pattern,String> getUrlPatternToURIMap(){
if( urlPatternToURI == null || urlPatternToURI.isEmpty() ){
this.urlPatternToURI = buildUrlPatternToURI();
}
return urlPatternToURI;
}
protected synchronized void invalidateURLPatternMap(){
this.urlPatternToURI = null;
}
public Individual getDisplayIndividual( String pathInfo , OntModel displayModel){
Map<Pattern,String> map = getUrlPatternToURIMap();
for( Pattern regex : map.keySet()){
Matcher m = regex.matcher(pathInfo);
if(m.matches() ){
return displayModel.getIndividual(map.get(regex));
}
}
return null;
}
protected synchronized Map<Pattern,String> buildUrlPatternToURI(){
OntModel displayModel = (OntModel)getServletContext().getAttribute("displayOntModel");
Map<Pattern,String> map = new HashMap<Pattern,String>();
StmtIterator stmts = displayModel.listStatements(null, DisplayVocabulary.URL_MAPPING,(Literal)null);
while(stmts.hasNext()){
Statement stmt = stmts.nextStatement();
if( stmt.getSubject().isURIResource() && stmt.getObject().isLiteral()){
Resource r = (Resource)stmt.getSubject().as( Resource.class);
Pattern regex = Pattern.compile(stmt.getLiteral().getLexicalForm());
map.put(regex,r.getURI());
}
}
return map;
}
@Override
public void addedStatement(Statement s) {
invalidateURLPatternMap();
}
@Override
public void removedStatement(Statement s) {
invalidateURLPatternMap();
}
}
}

View file

@ -303,7 +303,7 @@ public class UrlBuilder {
} }
public static String urlEncode(String str) { public static String urlEncode(String str) {
String encoding = "ISO-8859-1"; String encoding = "UTF-8";
String encodedUrl = null; String encodedUrl = null;
try { try {
encodedUrl = URLEncoder.encode(str, encoding); encodedUrl = URLEncoder.encode(str, encoding);
@ -314,7 +314,7 @@ public class UrlBuilder {
} }
public static String urlDecode(String str) { public static String urlDecode(String str) {
String encoding = "ISO-8859-1"; String encoding = "UTF-8";
String decodedUrl = null; String decodedUrl = null;
try { try {
decodedUrl = URLDecoder.decode(str, encoding); decodedUrl = URLDecoder.decode(str, encoding);

View file

@ -180,7 +180,7 @@ class IndividualResponseBuilder {
private boolean getprofilePageTypesFlag() { private boolean getprofilePageTypesFlag() {
String property = ConfigurationProperties.getBean(vreq).getProperty( String property = ConfigurationProperties.getBean(vreq).getProperty(
"MultiViews.profilePageTypes"); "multiViews.profilePageTypes");
return "enabled".equals(property); return "enabled".equals(property);
} }

View file

@ -18,12 +18,10 @@ import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.iri.IRI; import com.hp.hpl.jena.iri.IRI;
import com.hp.hpl.jena.iri.IRIFactory; import com.hp.hpl.jena.iri.IRIFactory;
import com.hp.hpl.jena.iri.Violation;
import com.hp.hpl.jena.ontology.AllValuesFromRestriction; import com.hp.hpl.jena.ontology.AllValuesFromRestriction;
import com.hp.hpl.jena.ontology.OntClass; import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec; import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.ontology.OntResource;
import com.hp.hpl.jena.ontology.Restriction; import com.hp.hpl.jena.ontology.Restriction;
import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryExecution;
@ -35,11 +33,9 @@ import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.shared.Lock; import com.hp.hpl.jena.shared.Lock;
import com.hp.hpl.jena.util.iterator.ClosableIterator;
import com.hp.hpl.jena.vocabulary.OWL; import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS; import com.hp.hpl.jena.vocabulary.RDFS;
@ -47,6 +43,7 @@ import com.hp.hpl.jena.vocabulary.RDFS;
import edu.cornell.mannlib.vedit.controller.BaseEditController; import edu.cornell.mannlib.vedit.controller.BaseEditController;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission; import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
public class JenaAdminActions extends BaseEditController { public class JenaAdminActions extends BaseEditController {
@ -59,7 +56,7 @@ public class JenaAdminActions extends BaseEditController {
if (iri.hasViolation(false) ) { if (iri.hasViolation(false) ) {
log.error("Bad URI: "+uri); log.error("Bad URI: "+uri);
log.error( "Only well-formed absolute URIrefs can be included in RDF/XML output: " log.error( "Only well-formed absolute URIrefs can be included in RDF/XML output: "
+ ((Violation)iri.violations(false).next()).getShortMessage()); + iri.violations(false).next().getShortMessage());
return true; return true;
} else { } else {
return false; return false;
@ -71,8 +68,7 @@ public class JenaAdminActions extends BaseEditController {
private static final String AKT_PORTAL = "http://www.aktors.org/ontology/portal#"; private static final String AKT_PORTAL = "http://www.aktors.org/ontology/portal#";
private void copyStatements(Model src, Model dest, Resource subj, Property pred, RDFNode obj) { private void copyStatements(Model src, Model dest, Resource subj, Property pred, RDFNode obj) {
for (Iterator i = src.listStatements(subj,pred,obj); i.hasNext();) { for (Statement stmt : src.listStatements(subj,pred,obj).toList()) {
Statement stmt = (Statement) i.next();
String subjNs = stmt.getSubject().getNameSpace(); String subjNs = stmt.getSubject().getNameSpace();
if (subjNs == null || (! (subjNs.equals(VITRO) || subjNs.equals(AKT_SUPPORT) || subjNs.equals(AKT_PORTAL) ) ) ) { if (subjNs == null || (! (subjNs.equals(VITRO) || subjNs.equals(AKT_SUPPORT) || subjNs.equals(AKT_PORTAL) ) ) ) {
if (stmt.getObject().isLiteral()) { if (stmt.getObject().isLiteral()) {
@ -90,14 +86,11 @@ public class JenaAdminActions extends BaseEditController {
/** /**
* This doesn't really print just the TBox. It takes a copy of the model, removes all the individuals, and writes the result. * This doesn't really print just the TBox. It takes a copy of the model, removes all the individuals, and writes the result.
* @param response
*/ */
private void outputTbox(HttpServletResponse response) { private void outputTbox(HttpServletResponse response) {
OntModel memoryModel = (OntModel) getServletContext().getAttribute("baseOntModel"); OntModel memoryModel = ModelAccess.on(getServletContext()).getBaseOntModel();
try { try {
OntModel tempOntModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM); OntModel tempOntModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);
Property DescriptionProp = ResourceFactory.createProperty(VitroVocabulary.DESCRIPTION_ANNOT);
Property ExampleProp = ResourceFactory.createProperty(VitroVocabulary.EXAMPLE_ANNOT);
memoryModel.enterCriticalSection(Lock.READ); memoryModel.enterCriticalSection(Lock.READ);
try { try {
copyStatements(memoryModel,tempOntModel,null,RDF.type,OWL.Class); copyStatements(memoryModel,tempOntModel,null,RDF.type,OWL.Class);
@ -109,8 +102,6 @@ public class JenaAdminActions extends BaseEditController {
copyStatements(memoryModel,tempOntModel,null,RDFS.domain,null); copyStatements(memoryModel,tempOntModel,null,RDFS.domain,null);
copyStatements(memoryModel,tempOntModel,null,RDFS.range,null); copyStatements(memoryModel,tempOntModel,null,RDFS.range,null);
copyStatements(memoryModel,tempOntModel,null,OWL.inverseOf,null); copyStatements(memoryModel,tempOntModel,null,OWL.inverseOf,null);
//copyStatements(memoryModel,tempOntModel,null,DescriptionProp,null);
//copyStatements(memoryModel,tempOntModel,null,ExampleProp,null);
} finally { } finally {
memoryModel.leaveCriticalSection(); memoryModel.leaveCriticalSection();
} }
@ -130,28 +121,24 @@ public class JenaAdminActions extends BaseEditController {
Model taxonomyModel = ModelFactory.createDefaultModel(); Model taxonomyModel = ModelFactory.createDefaultModel();
try { try {
HashSet<Resource> typeSet = new HashSet<Resource>(); HashSet<Resource> typeSet = new HashSet<Resource>();
for (Iterator classIt = ontModel.listStatements((Resource)null,RDF.type,(RDFNode)null); classIt.hasNext();) { for (Statement stmt : ontModel.listStatements((Resource)null,RDF.type,(RDFNode)null).toList()) {
Statement stmt = (Statement) classIt.next();
if (stmt.getObject().isResource()) { if (stmt.getObject().isResource()) {
Resource ontClass = (Resource) stmt.getObject(); typeSet.add((Resource) stmt.getObject());
typeSet.add(ontClass);
} }
} }
for (Iterator classIt = ontModel.listClasses(); classIt.hasNext();) { for (Resource classRes : ontModel.listClasses().toList()) {
Resource classRes = (Resource) classIt.next();
typeSet.add(classRes); typeSet.add(classRes);
} }
for (Iterator<Resource> typeIt = typeSet.iterator(); typeIt.hasNext();) { for (Resource ontClass : typeSet) {
Resource ontClass = typeIt.next(); if (!ontClass.isAnon()) { // Only query for named classes
if (!ontClass.isAnon()) { // Only query for named classes System.out.println("Describing "+ontClass.getURI());
System.out.println("Describing "+ontClass.getURI()); // We want a subgraph describing this class, including related BNodes
// We want a subgraph describing this class, including related BNodes String queryStr = "DESCRIBE <"+ontClass.getURI()+">";
String queryStr = "DESCRIBE <"+ontClass.getURI()+">"; Query describeQuery = QueryFactory.create(queryStr);
Query describeQuery = QueryFactory.create(queryStr); QueryExecution qe = QueryExecutionFactory.create(describeQuery,ontModel);
QueryExecution qe = QueryExecutionFactory.create(describeQuery,ontModel); qe.execDescribe(taxonomyModel);
qe.execDescribe(taxonomyModel);
}
} }
}
} finally { } finally {
ontModel.leaveCriticalSection(); ontModel.leaveCriticalSection();
} }
@ -171,10 +158,10 @@ public class JenaAdminActions extends BaseEditController {
private String testWriteXML() { private String testWriteXML() {
StringBuffer output = new StringBuffer(); StringBuffer output = new StringBuffer();
output.append("<html><head><title>Test Write XML</title></head><body><pre>\n"); output.append("<html><head><title>Test Write XML</title></head><body><pre>\n");
Model model = (Model) getServletContext().getAttribute("jenaOntModel"); OntModel model = ModelAccess.on(getServletContext()).getJenaOntModel();
Model tmp = ModelFactory.createDefaultModel(); Model tmp = ModelFactory.createDefaultModel();
boolean valid = true; boolean valid = true;
for (Statement stmt : ((List<Statement>)model.listStatements().toList()) ) { for (Statement stmt : model.listStatements().toList() ) {
tmp.add(stmt); tmp.add(stmt);
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
try { try {
@ -201,17 +188,15 @@ public class JenaAdminActions extends BaseEditController {
private void printRestrictions() { private void printRestrictions() {
OntModel memoryModel = (OntModel) getServletContext().getAttribute("pelletOntModel"); OntModel memoryModel = (OntModel) getServletContext().getAttribute("pelletOntModel");
for (Iterator i = memoryModel.listRestrictions(); i.hasNext(); ) { for (Restriction rest : memoryModel.listRestrictions().toList() ) {
Restriction rest = (Restriction) i.next();
//System.out.println(); //System.out.println();
if (rest.isAllValuesFromRestriction()) { if (rest.isAllValuesFromRestriction()) {
log.trace("All values from: "); log.trace("All values from: ");
AllValuesFromRestriction avfr = rest.asAllValuesFromRestriction(); AllValuesFromRestriction avfr = rest.asAllValuesFromRestriction();
Resource res = avfr.getAllValuesFrom(); Resource res = avfr.getAllValuesFrom();
if (res.canAs(OntClass.class)) { if (res.canAs(OntClass.class)) {
OntClass resClass = (OntClass) res.as(OntClass.class); OntClass resClass = res.as(OntClass.class);
for (Iterator resInstIt = resClass.listInstances(); resInstIt.hasNext(); ) { for (Resource inst : resClass.listInstances().toList() ) {
Resource inst = (Resource) resInstIt.next();
log.trace(" -"+inst.getURI()); log.trace(" -"+inst.getURI());
} }
} }
@ -221,8 +206,7 @@ public class JenaAdminActions extends BaseEditController {
log.trace("Has value: "); log.trace("Has value: ");
} }
log.trace("On property "+rest.getOnProperty().getURI()); log.trace("On property "+rest.getOnProperty().getURI());
for (Iterator indIt = rest.listInstances(); indIt.hasNext(); ) { for (Resource inst : rest.listInstances().toList() ) {
Resource inst = (Resource) indIt.next();
log.trace(" "+inst.getURI()); log.trace(" "+inst.getURI());
} }
@ -230,12 +214,11 @@ public class JenaAdminActions extends BaseEditController {
} }
private void removeLongLiterals() { private void removeLongLiterals() {
OntModel memoryModel = (OntModel) getServletContext().getAttribute("jenaOntModel"); OntModel memoryModel = ModelAccess.on(getServletContext()).getJenaOntModel();
memoryModel.enterCriticalSection(Lock.WRITE); memoryModel.enterCriticalSection(Lock.WRITE);
try { try {
List<Statement> statementsToRemove = new LinkedList<Statement>(); List<Statement> statementsToRemove = new LinkedList<Statement>();
for (Iterator i = memoryModel.listStatements(null,null,(Literal)null); i.hasNext(); ) { for (Statement stmt : memoryModel.listStatements(null,null,(Literal)null).toList() ) {
Statement stmt = (Statement) i.next();
if (stmt.getObject().isLiteral()) { if (stmt.getObject().isLiteral()) {
Literal lit = (Literal) stmt.getObject(); Literal lit = (Literal) stmt.getObject();
if ( lit.getString().length() > 24) { if ( lit.getString().length() > 24) {
@ -252,7 +235,8 @@ public class JenaAdminActions extends BaseEditController {
} }
} }
public void doGet(HttpServletRequest req, HttpServletResponse response) { @Override
public void doGet(HttpServletRequest req, HttpServletResponse response) {
if (!isAuthorizedToDisplayPage(req, response, SimplePermission.USE_MISCELLANEOUS_ADMIN_PAGES.ACTIONS)) { if (!isAuthorizedToDisplayPage(req, response, SimplePermission.USE_MISCELLANEOUS_ADMIN_PAGES.ACTIONS)) {
return; return;
} }
@ -273,17 +257,16 @@ public class JenaAdminActions extends BaseEditController {
} }
if (actionStr.equals("checkURIs")) { if (actionStr.equals("checkURIs")) {
OntModel memoryModel = (OntModel) getServletContext().getAttribute("jenaOntModel"); OntModel memoryModel = ModelAccess.on(getServletContext()).getJenaOntModel();
ClosableIterator stmtIt = memoryModel.listStatements(); StmtIterator stmtIt = memoryModel.listStatements();
try { try {
for (Iterator i = stmtIt; i.hasNext(); ) { for (Statement stmt : stmtIt.toList() ) {
boolean sFailed = false; boolean sFailed = false;
boolean pFailed = false; boolean pFailed = false;
boolean oFailed = false; boolean oFailed = false;
String sURI = "<bNode>"; String sURI = "<bNode>";
String pURI = "???"; String pURI = "???";
String oURI = "<bNode>"; String oURI = "<bNode>";
Statement stmt = (Statement) i.next();
if (stmt.getSubject().getURI() != null) { if (stmt.getSubject().getURI() != null) {
sFailed = checkURI(sURI = stmt.getSubject().getURI()); sFailed = checkURI(sURI = stmt.getSubject().getURI());
} }
@ -305,23 +288,19 @@ public class JenaAdminActions extends BaseEditController {
if (actionStr.equals("output")) { if (actionStr.equals("output")) {
OntModel memoryModel = null; OntModel memoryModel = null;
if (request.getParameter("assertionsOnly") != null) { if (request.getParameter("assertionsOnly") != null) {
memoryModel = (OntModel) getServletContext().getAttribute("baseOntModel"); memoryModel = ModelAccess.on(getServletContext()).getBaseOntModel();
System.out.println("baseOntModel"); System.out.println("baseOntModel");
} else if (request.getParameter("inferences") != null) { } else if (request.getParameter("inferences") != null) {
memoryModel = (OntModel) getServletContext().getAttribute("inferenceOntModel"); memoryModel = ModelAccess.on(getServletContext()).getInferenceOntModel();
System.out.println("inferenceOntModel"); System.out.println("inferenceOntModel");
} else if (request.getParameter("pellet") != null) { } else if (request.getParameter("pellet") != null) {
memoryModel = (OntModel) getServletContext().getAttribute("pelletOntModel"); memoryModel = (OntModel) getServletContext().getAttribute("pelletOntModel");
System.out.println("pelletOntModel"); System.out.println("pelletOntModel");
} else { } else {
memoryModel = (OntModel) getServletContext().getAttribute("jenaOntModel"); memoryModel = ModelAccess.on(getServletContext()).getJenaOntModel();
System.out.println("jenaOntModel"); System.out.println("jenaOntModel");
} }
int subModelCount = 0; int subModelCount = memoryModel.listSubModels().toList().size();
for (Iterator subIt = memoryModel.listSubModels(); subIt.hasNext();) {
subIt.next();
++subModelCount;
}
System.out.println("Submodels: "+subModelCount); System.out.println("Submodels: "+subModelCount);
try { try {
//response.setContentType("application/rdf+xml"); //response.setContentType("application/rdf+xml");
@ -339,42 +318,8 @@ public class JenaAdminActions extends BaseEditController {
removeLongLiterals(); removeLongLiterals();
} }
if (actionStr.equals("isIsomorphic")) { if (actionStr.equals("outputTaxonomy")) {
OntModel memoryModel = (OntModel) getServletContext().getAttribute("jenaOntModel"); OntModel ontModel = ModelAccess.on(getServletContext()).getBaseOntModel();
OntModel persistentModel = (OntModel) getServletContext().getAttribute("jenaPersistentOntModel");
if ((memoryModel != null) && (persistentModel != null)) {
long startTime = System.currentTimeMillis();
if (memoryModel.isIsomorphicWith(persistentModel)) {
log.trace("In-memory and persistent models are isomorphic");
} else {
log.trace("In-memory and persistent models are NOT isomorphic");
log.trace("In-memory model has "+memoryModel.size()+" statements");
log.trace("Persistent model has "+persistentModel.size()+" statements");
Model diff = memoryModel.difference(persistentModel);
ClosableIterator stmtIt = diff.listStatements();
log.trace("Delta = "+diff.size()+" statments");
while (stmtIt.hasNext()) {
Statement s = (Statement) stmtIt.next();
try {
log.trace(s.getSubject().getURI()+" : "+s.getPredicate().getURI()); // + ((Literal)s.getObject()).getString());
} catch (ClassCastException cce) {}
}
}
log.trace((System.currentTimeMillis()-startTime)/1000+" seconds to check isomorphism");
}
} else if (actionStr.equals("removeUntypedResources")) {
OntModel memoryModel = (OntModel) getServletContext().getAttribute("jenaOntModel");
OntModel persistentModel = (OntModel) getServletContext().getAttribute("jenaPersistentOntModel");
ClosableIterator rIt = memoryModel.listSubjects();
clean(rIt,memoryModel);
ClosableIterator oIt = memoryModel.listObjects();
clean(oIt,memoryModel);
ClosableIterator rrIt = persistentModel.listSubjects();
clean(rIt,persistentModel);
ClosableIterator ooIt = persistentModel.listObjects();
clean(oIt,persistentModel);
} else if (actionStr.equals("outputTaxonomy")) {
OntModel ontModel = (OntModel) getServletContext().getAttribute("baseOntModel");
Model taxonomyModel = extractTaxonomy(ontModel); Model taxonomyModel = extractTaxonomy(ontModel);
try { try {
taxonomyModel.write(response.getOutputStream()); taxonomyModel.write(response.getOutputStream());
@ -385,32 +330,8 @@ public class JenaAdminActions extends BaseEditController {
} }
private void clean(ClosableIterator rIt, OntModel model) { @Override
try { public void doPost(HttpServletRequest request, HttpServletResponse response) {
while (rIt.hasNext()) {
try {
OntResource r = (OntResource) rIt.next();
try {
Resource t = r.getRDFType();
if (t == null) {
r.remove();
}
} catch (Exception e) {
r.remove();
}
} catch (ClassCastException cce) {
Resource r = (Resource) rIt.next();
model.removeAll(r,null,null);
model.removeAll(null,null,r);
}
}
} finally {
rIt.close();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) {
doGet(request ,response); doGet(request ,response);
} }

View file

@ -5,8 +5,6 @@ package edu.cornell.mannlib.vitro.webapp.controller.jena;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -30,8 +28,9 @@ import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.Actions; import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.Actions;
import edu.cornell.mannlib.vitro.webapp.controller.Controllers; import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess.ModelID;
import edu.cornell.mannlib.vitro.webapp.dao.jena.JenaModelUtils; import edu.cornell.mannlib.vitro.webapp.dao.jena.JenaModelUtils;
import edu.cornell.mannlib.vitro.webapp.dao.jena.ModelContext;
import edu.cornell.mannlib.vitro.webapp.dao.jena.RDFServiceModelMaker; import edu.cornell.mannlib.vitro.webapp.dao.jena.RDFServiceModelMaker;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService; import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFServiceException; import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFServiceException;
@ -121,8 +120,7 @@ public class JenaExportController extends BaseEditController {
if( "abox".equals(subgraphParam)){ if( "abox".equals(subgraphParam)){
model = ModelFactory.createDefaultModel(); model = ModelFactory.createDefaultModel();
if("inferred".equals(assertedOrInferredParam)){ if("inferred".equals(assertedOrInferredParam)){
model = ModelContext.getInferenceOntModelSelector( model = ModelAccess.on(getServletContext()).getOntModel(ModelID.INFERRED_ABOX);
getServletContext()).getABoxModel();
} }
else if("full".equals(assertedOrInferredParam)){ else if("full".equals(assertedOrInferredParam)){
outputSparqlConstruct(ABOX_FULL_CONSTRUCT, formatParam, response); outputSparqlConstruct(ABOX_FULL_CONSTRUCT, formatParam, response);
@ -137,10 +135,9 @@ public class JenaExportController extends BaseEditController {
// so we'll extract the whole ontology and then include // so we'll extract the whole ontology and then include
// only those statements that are in the inferred graph // only those statements that are in the inferred graph
Model tempModel = xutil.extractTBox( Model tempModel = xutil.extractTBox(
ModelContext.getUnionOntModelSelector( ModelAccess.on(getServletContext()).getOntModel(ModelID.UNION_TBOX),
getServletContext()).getTBoxModel(), ontologyURI); ontologyURI);
Model inferenceModel = ModelContext.getInferenceOntModelSelector( Model inferenceModel = ModelAccess.on(getServletContext()).getOntModel(ModelID.INFERRED_TBOX);
getServletContext()).getTBoxModel();
inferenceModel.enterCriticalSection(Lock.READ); inferenceModel.enterCriticalSection(Lock.READ);
try { try {
model = tempModel.intersection(inferenceModel); model = tempModel.intersection(inferenceModel);
@ -149,12 +146,11 @@ public class JenaExportController extends BaseEditController {
} }
} else if ("full".equals(assertedOrInferredParam)) { } else if ("full".equals(assertedOrInferredParam)) {
model = xutil.extractTBox( model = xutil.extractTBox(
ModelContext.getUnionOntModelSelector( ModelAccess.on(getServletContext()).getOntModel(ModelID.UNION_TBOX),
getServletContext()).getTBoxModel(), ontologyURI); ontologyURI);
} else { } else {
model = xutil.extractTBox( model = xutil.extractTBox(
ModelContext.getBaseOntModelSelector( ModelAccess.on(getServletContext()).getOntModel(ModelID.BASE_TBOX), ontologyURI);
getServletContext()).getTBoxModel(), ontologyURI);
} }
} }
@ -162,10 +158,8 @@ public class JenaExportController extends BaseEditController {
if("inferred".equals(assertedOrInferredParam)){ if("inferred".equals(assertedOrInferredParam)){
ontModel = xutil.extractTBox( ontModel = xutil.extractTBox(
dataset, ontologyURI, INFERENCE_GRAPH); dataset, ontologyURI, INFERENCE_GRAPH);
ontModel.addSubModel(ModelContext.getInferenceOntModelSelector( ontModel.addSubModel(ModelAccess.on(getServletContext()).getOntModel(ModelID.INFERRED_ABOX));
getServletContext()).getABoxModel()); ontModel.addSubModel(ModelAccess.on(getServletContext()).getOntModel(ModelID.INFERRED_TBOX));
ontModel.addSubModel(ModelContext.getInferenceOntModelSelector(
getServletContext()).getTBoxModel());
} }
else if("full".equals(assertedOrInferredParam)){ else if("full".equals(assertedOrInferredParam)){
outputSparqlConstruct(FULL_FULL_CONSTRUCT, formatParam, response); outputSparqlConstruct(FULL_FULL_CONSTRUCT, formatParam, response);
@ -283,9 +277,6 @@ public class JenaExportController extends BaseEditController {
} }
} }
static final String FULL_ONT_MODEL_ATTR = "jenaOntModel";
static final String ASSERTIONS_ONT_MODEL_ATTR = "baseOntModel";
static final String INFERENCES_ONT_MODEL_ATTR = "inferenceOntModel";
static final String FULL_GRAPH = "?g"; static final String FULL_GRAPH = "?g";
static final String ASSERTIONS_GRAPH = "<http://vitro.mannlib.cornell.edu/default/vitro-kb-2>"; static final String ASSERTIONS_GRAPH = "<http://vitro.mannlib.cornell.edu/default/vitro-kb-2>";
static final String INFERENCE_GRAPH = "<http://vitro.mannlib.cornell.edu/default/vitro-kb-inf>"; static final String INFERENCE_GRAPH = "<http://vitro.mannlib.cornell.edu/default/vitro-kb-inf>";

View file

@ -67,8 +67,9 @@ import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.beans.Ontology; import edu.cornell.mannlib.vitro.webapp.beans.Ontology;
import edu.cornell.mannlib.vitro.webapp.controller.Controllers; import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess.ModelID;
import edu.cornell.mannlib.vitro.webapp.dao.OntologyDao; import edu.cornell.mannlib.vitro.webapp.dao.OntologyDao;
import edu.cornell.mannlib.vitro.webapp.dao.jena.ModelContext;
import edu.cornell.mannlib.vitro.webapp.dao.jena.RDFServiceGraph; import edu.cornell.mannlib.vitro.webapp.dao.jena.RDFServiceGraph;
import edu.cornell.mannlib.vitro.webapp.dao.jena.RDFServiceModelMaker; import edu.cornell.mannlib.vitro.webapp.dao.jena.RDFServiceModelMaker;
import edu.cornell.mannlib.vitro.webapp.dao.jena.VitroJenaModelMaker; import edu.cornell.mannlib.vitro.webapp.dao.jena.VitroJenaModelMaker;
@ -79,8 +80,8 @@ import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeSet;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService; import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFServiceException; import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFServiceException;
import edu.cornell.mannlib.vitro.webapp.rdfservice.impl.RDFServiceUtils; import edu.cornell.mannlib.vitro.webapp.rdfservice.impl.RDFServiceUtils;
import edu.cornell.mannlib.vitro.webapp.servlet.setup.ContentModelSetup;
import edu.cornell.mannlib.vitro.webapp.servlet.setup.JenaDataSourceSetupBase; import edu.cornell.mannlib.vitro.webapp.servlet.setup.JenaDataSourceSetupBase;
import edu.cornell.mannlib.vitro.webapp.servlet.setup.WebappDaoSetup;
import edu.cornell.mannlib.vitro.webapp.utils.SparqlQueryUtils; import edu.cornell.mannlib.vitro.webapp.utils.SparqlQueryUtils;
import edu.cornell.mannlib.vitro.webapp.utils.jena.JenaIngestUtils; import edu.cornell.mannlib.vitro.webapp.utils.jena.JenaIngestUtils;
import edu.cornell.mannlib.vitro.webapp.utils.jena.JenaIngestUtils.MergeResult; import edu.cornell.mannlib.vitro.webapp.utils.jena.JenaIngestUtils.MergeResult;
@ -520,7 +521,7 @@ public class JenaIngestController extends BaseEditController {
vreq.setAttribute("title", "Choose Workflow Step"); vreq.setAttribute("title", "Choose Workflow Step");
vreq.setAttribute("bodyJsp", WORKFLOW_STEP_JSP); vreq.setAttribute("bodyJsp", WORKFLOW_STEP_JSP);
} else { } else {
OntModel jenaOntModel = (OntModel) getServletContext().getAttribute("jenaOntModel"); OntModel jenaOntModel = ModelAccess.on(getServletContext()).getJenaOntModel();
jenaOntModel.enterCriticalSection(Lock.READ); jenaOntModel.enterCriticalSection(Lock.READ);
List<Individual> savedQueryList = new LinkedList<Individual>(); List<Individual> savedQueryList = new LinkedList<Individual>();
try { try {
@ -537,7 +538,7 @@ public class JenaIngestController extends BaseEditController {
private void processExecuteSparqlRequest(VitroRequest vreq, ModelMaker maker, String modelType) { private void processExecuteSparqlRequest(VitroRequest vreq, ModelMaker maker, String modelType) {
String sparqlQueryStr = vreq.getParameter("sparqlQueryStr"); String sparqlQueryStr = vreq.getParameter("sparqlQueryStr");
OntModel jenaOntModel = (OntModel) getServletContext().getAttribute("jenaOntModel"); OntModel jenaOntModel = ModelAccess.on(getServletContext()).getJenaOntModel();
jenaOntModel.enterCriticalSection(Lock.READ); jenaOntModel.enterCriticalSection(Lock.READ);
List<Individual> savedQueryList = new LinkedList<Individual>(); List<Individual> savedQueryList = new LinkedList<Individual>();
try { try {
@ -660,10 +661,8 @@ public class JenaIngestController extends BaseEditController {
/* /*
* get baseOnt and infOnt models * get baseOnt and infOnt models
*/ */
OntModel baseOntModel = ModelContext.getBaseOntModel( OntModel baseOntModel = ModelAccess.on(getServletContext()).getBaseOntModel();
getServletContext()); OntModel tboxOntModel = ModelAccess.on(getServletContext()).getOntModel(ModelID.UNION_TBOX);
OntModel tboxOntModel = ModelContext.getUnionOntModelSelector(
getServletContext()).getTBoxModel();
/* /*
* calling method that does the merge operation. * calling method that does the merge operation.
@ -826,10 +825,10 @@ public class JenaIngestController extends BaseEditController {
return; return;
} }
Model m = modelMaker.getModel(modelName); Model m = modelMaker.getModel(modelName);
ModelContext.getBaseOntModelSelector(getServletContext()).getTBoxModel().addSubModel(m); ModelAccess.on(getServletContext()).getOntModel(ModelID.BASE_ABOX).addSubModel(m);
ModelContext.getBaseOntModelSelector(getServletContext()).getABoxModel().addSubModel(m); ModelAccess.on(getServletContext()).getOntModel(ModelID.BASE_TBOX).addSubModel(m);
ModelContext.getUnionOntModelSelector(getServletContext()).getABoxModel().addSubModel(m); ModelAccess.on(getServletContext()).getOntModel(ModelID.UNION_ABOX).addSubModel(m);
ModelContext.getUnionOntModelSelector(getServletContext()).getTBoxModel().addSubModel(m); ModelAccess.on(getServletContext()).getOntModel(ModelID.UNION_TBOX).addSubModel(m);
attachedModels.put(modelName, m); attachedModels.put(modelName, m);
log.info("Attached " + modelName + " (" + m.hashCode() + ") to webapp"); log.info("Attached " + modelName + " (" + m.hashCode() + ") to webapp");
} }
@ -839,10 +838,10 @@ public class JenaIngestController extends BaseEditController {
if (m == null) { if (m == null) {
return; return;
} }
ModelContext.getBaseOntModelSelector(getServletContext()).getTBoxModel().removeSubModel(m); ModelAccess.on(getServletContext()).getOntModel(ModelID.BASE_ABOX).removeSubModel(m);
ModelContext.getBaseOntModelSelector(getServletContext()).getABoxModel().removeSubModel(m); ModelAccess.on(getServletContext()).getOntModel(ModelID.BASE_TBOX).removeSubModel(m);
ModelContext.getUnionOntModelSelector(getServletContext()).getABoxModel().removeSubModel(m); ModelAccess.on(getServletContext()).getOntModel(ModelID.UNION_ABOX).removeSubModel(m);
ModelContext.getUnionOntModelSelector(getServletContext()).getTBoxModel().removeSubModel(m); ModelAccess.on(getServletContext()).getOntModel(ModelID.UNION_TBOX).removeSubModel(m);
attachedModels.remove(modelName); attachedModels.remove(modelName);
log.info("Detached " + modelName + " (" + m.hashCode() + ") from webapp"); log.info("Detached " + modelName + " (" + m.hashCode() + ") from webapp");
} }
@ -910,7 +909,7 @@ public class JenaIngestController extends BaseEditController {
} }
private long doExecuteSparql(VitroRequest vreq) { private long doExecuteSparql(VitroRequest vreq) {
OntModel jenaOntModel = (OntModel) getServletContext().getAttribute("jenaOntModel"); OntModel jenaOntModel = ModelAccess.on(getServletContext()).getJenaOntModel();
OntModel source = null; OntModel source = null;
if ("pellet".equals(vreq.getParameter("reasoning"))) { if ("pellet".equals(vreq.getParameter("reasoning"))) {
source = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC); source = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC);
@ -984,7 +983,7 @@ public class JenaIngestController extends BaseEditController {
log.debug("Connecting to DB at "+jdbcUrl); log.debug("Connecting to DB at "+jdbcUrl);
StoreDesc storeDesc = new StoreDesc(LayoutType.LayoutTripleNodesHash,dbTypeObj) ; StoreDesc storeDesc = new StoreDesc(LayoutType.LayoutTripleNodesHash,dbTypeObj) ;
ServletContext ctx = vreq.getSession().getServletContext(); ServletContext ctx = vreq.getSession().getServletContext();
DataSource bds = WebappDaoSetup.makeBasicDataSource( DataSource bds = ContentModelSetup.makeBasicDataSource(
driver, jdbcUrl, username, password, ctx); driver, jdbcUrl, username, password, ctx);
try { try {
VitroJenaSDBModelMaker vsmm = new VitroJenaSDBModelMaker(storeDesc, bds); VitroJenaSDBModelMaker vsmm = new VitroJenaSDBModelMaker(storeDesc, bds);
@ -1193,8 +1192,7 @@ public class JenaIngestController extends BaseEditController {
Model baseOntModel = RDFServiceGraph.createRDFServiceModel Model baseOntModel = RDFServiceGraph.createRDFServiceModel
(new RDFServiceGraph( (new RDFServiceGraph(
rdfService, JenaDataSourceSetupBase.JENA_DB_MODEL)); rdfService, JenaDataSourceSetupBase.JENA_DB_MODEL));
OntModel ontModel = (OntModel) OntModel ontModel = ModelAccess.on(getServletContext()).getJenaOntModel();
getServletContext().getAttribute("jenaOntModel");
List<String> urisToChange = new LinkedList<String>(); List<String> urisToChange = new LinkedList<String>();
ontModel.enterCriticalSection(Lock.READ); ontModel.enterCriticalSection(Lock.READ);
try { try {
@ -1312,26 +1310,11 @@ public class JenaIngestController extends BaseEditController {
public static Model getModel(String name, HttpServletRequest request, ServletContext context) { public static Model getModel(String name, HttpServletRequest request, ServletContext context) {
if ("vitro:jenaOntModel".equals(name)) { if ("vitro:jenaOntModel".equals(name)) {
Object sessionOntModel = request.getSession().getAttribute("jenaOntModel"); return ModelAccess.on(request.getSession()).getJenaOntModel();
if (sessionOntModel != null && sessionOntModel instanceof OntModel) {
return (OntModel) sessionOntModel;
} else {
return (OntModel) context.getAttribute("jenaOntModel");
}
} else if ("vitro:baseOntModel".equals(name)) { } else if ("vitro:baseOntModel".equals(name)) {
Object sessionOntModel = request.getSession().getAttribute("baseOntModel"); return ModelAccess.on(request.getSession()).getBaseOntModel();
if (sessionOntModel != null && sessionOntModel instanceof OntModel) {
return (OntModel) sessionOntModel;
} else {
return (OntModel) context.getAttribute("baseOntModel");
}
} else if ("vitro:inferenceOntModel".equals(name)) { } else if ("vitro:inferenceOntModel".equals(name)) {
Object sessionOntModel = request.getSession().getAttribute("inferenceOntModel"); return ModelAccess.on(request.getSession()).getInferenceOntModel();
if (sessionOntModel != null && sessionOntModel instanceof OntModel) {
return (OntModel) sessionOntModel;
} else {
return (OntModel) context.getAttribute("inferenceOntModel");
}
} else { } else {
return getVitroJenaModelMaker(request,context).getModel(name); return getVitroJenaModelMaker(request,context).getModel(name);
} }

View file

@ -34,9 +34,10 @@ import edu.cornell.mannlib.vedit.beans.LoginStatusBean;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission; import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.controller.Controllers; import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess.ModelID;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.jena.JenaModelUtils; import edu.cornell.mannlib.vitro.webapp.dao.jena.JenaModelUtils;
import edu.cornell.mannlib.vitro.webapp.dao.jena.ModelContext;
import edu.cornell.mannlib.vitro.webapp.dao.jena.OntModelSelector; import edu.cornell.mannlib.vitro.webapp.dao.jena.OntModelSelector;
import edu.cornell.mannlib.vitro.webapp.dao.jena.RDFServiceGraph; import edu.cornell.mannlib.vitro.webapp.dao.jena.RDFServiceGraph;
import edu.cornell.mannlib.vitro.webapp.dao.jena.event.BulkUpdateEvent; import edu.cornell.mannlib.vitro.webapp.dao.jena.event.BulkUpdateEvent;
@ -170,14 +171,12 @@ public class RDFUploadController extends JenaIngestController {
JenaModelUtils xutil = new JenaModelUtils(); JenaModelUtils xutil = new JenaModelUtils();
OntModel tboxModel = getTBoxModel( OntModel tboxModel = getTBoxModel(request.getSession());
request.getSession(), getServletContext());
OntModel aboxModel = getABoxModel( OntModel aboxModel = getABoxModel(
request.getSession(), getServletContext()); request.getSession(), getServletContext());
OntModel tboxChangeModel = null; OntModel tboxChangeModel = null;
Model aboxChangeModel = null; Model aboxChangeModel = null;
OntModelSelector ontModelSelector = ModelContext.getOntModelSelector( OntModelSelector ontModelSelector = ModelAccess.on(getServletContext()).getOntModelSelector();
getServletContext());
if (tboxModel != null) { if (tboxModel != null) {
boolean AGGRESSIVE = true; boolean AGGRESSIVE = true;
@ -428,17 +427,8 @@ public class RDFUploadController extends JenaIngestController {
return ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, abox); return ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, abox);
} }
private OntModel getTBoxModel(HttpSession session, ServletContext ctx) { private OntModel getTBoxModel(HttpSession session) {
if (session != null return ModelAccess.on(session).getOntModel(ModelID.BASE_TBOX);
&& session.getAttribute("baseOntModelSelector")
instanceof OntModelSelector) {
return ((OntModelSelector)
session.getAttribute("baseOntModelSelector"))
.getTBoxModel();
} else {
return ((OntModelSelector)
ctx.getAttribute("baseOntModelSelector")).getTBoxModel();
}
} }
private static final Log log = LogFactory.getLog( private static final Log log = LogFactory.getLog(

View file

@ -0,0 +1,84 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.json;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao;
import edu.cornell.mannlib.vitro.webapp.services.shortview.ShortViewService;
import edu.cornell.mannlib.vitro.webapp.services.shortview.ShortViewService.ShortViewContext;
import edu.cornell.mannlib.vitro.webapp.services.shortview.ShortViewServiceSetup;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.IndividualTemplateModel;
/**
* Does a Solr search for individuals, and uses the short view to render each of
* the results.
*/
public class GetRandomSolrIndividualsByVClass extends GetSolrIndividualsByVClass {
private static final Log log = LogFactory
.getLog(GetRandomSolrIndividualsByVClass.class);
protected GetRandomSolrIndividualsByVClass(VitroRequest vreq) {
super(vreq);
}
/**
* Search for individuals by VClass.
*/
@Override
protected JSONObject process() throws Exception {
JSONObject rObj = null;
//This gets the first vclass value and sets that as display type.
List<String> vclassIds = super.getVclassIds(vreq);
String vclassId = vclassIds.get(0);
vreq.setAttribute("queryType", "random");
// vreq.setAttribute("displayType", vclassId);
//This will get all the solr individuals by VClass (if one value) or the intersection
//i.e. individuals that have all the types for the different vclasses entered
rObj = super.process();
addShortViewRenderings(rObj);
return rObj;
}
/**
* Look through the return object. For each individual, render the short
* view and insert the resulting HTML into the object.
*/
private void addShortViewRenderings(JSONObject rObj) throws JSONException {
JSONArray individuals = rObj.getJSONArray("individuals");
String vclassName = rObj.getJSONObject("vclass").getString("name");
for (int i = 0; i < individuals.length(); i++) {
JSONObject individual = individuals.getJSONObject(i);
individual.put("shortViewHtml",
renderShortView(individual.getString("URI"), vclassName));
}
}
private String renderShortView(String individualUri, String vclassName) {
IndividualDao iDao = vreq.getWebappDaoFactory().getIndividualDao();
Individual individual = iDao.getIndividualByURI(individualUri);
Map<String, Object> modelMap = new HashMap<String, Object>();
modelMap.put("individual",
new IndividualTemplateModel(individual, vreq));
modelMap.put("vclass", vclassName);
ShortViewService svs = ShortViewServiceSetup.getService(ctx);
return svs.renderShortView(individual, ShortViewContext.BROWSE,
modelMap, vreq);
}
}

View file

@ -24,6 +24,7 @@ public class GetSolrIndividualsByVClass extends JsonObjectProducer {
protected JSONObject process() throws Exception { protected JSONObject process() throws Exception {
VClass vclass=null; VClass vclass=null;
String queryType = (String) vreq.getAttribute("queryType");
String vitroClassIdStr = vreq.getParameter("vclassId"); String vitroClassIdStr = vreq.getParameter("vclassId");
if ( vitroClassIdStr != null && !vitroClassIdStr.isEmpty()){ if ( vitroClassIdStr != null && !vitroClassIdStr.isEmpty()){
vclass = vreq.getWebappDaoFactory().getVClassDao().getVClassByURI(vitroClassIdStr); vclass = vreq.getWebappDaoFactory().getVClassDao().getVClassByURI(vitroClassIdStr);
@ -35,8 +36,13 @@ public class GetSolrIndividualsByVClass extends JsonObjectProducer {
log.debug("parameter vclassId URI parameter expected "); log.debug("parameter vclassId URI parameter expected ");
throw new Exception("parameter vclassId URI parameter expected "); throw new Exception("parameter vclassId URI parameter expected ");
} }
vreq.setAttribute("displayType", vitroClassIdStr); vreq.setAttribute("displayType", vitroClassIdStr);
return JsonServlet.getSolrIndividualsByVClass(vclass.getURI(), vreq, ctx); if ( queryType != null && queryType.equals("random")){
return JsonServlet.getRandomSolrIndividualsByVClass(vclass.getURI(), vreq, ctx);
} else {
return JsonServlet.getSolrIndividualsByVClass(vclass.getURI(), vreq, ctx);
}
} }
} }

View file

@ -11,6 +11,7 @@ import org.json.JSONObject;
import edu.cornell.mannlib.vitro.webapp.beans.VClass; import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup; import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.VClassGroupsForRequest;
import edu.cornell.mannlib.vitro.webapp.dao.jena.VClassGroupCache; import edu.cornell.mannlib.vitro.webapp.dao.jena.VClassGroupCache;
/** /**
@ -32,7 +33,7 @@ public class GetVClassesForVClassGroup extends JsonObjectProducer {
throw new Exception("no URI passed for classgroupUri"); throw new Exception("no URI passed for classgroupUri");
} }
VClassGroupCache vcgc = VClassGroupCache.getVClassGroupCache(ctx); VClassGroupsForRequest vcgc = VClassGroupCache.getVClassGroups(vreq);
VClassGroup vcg = vcgc.getGroup(vcgUri); VClassGroup vcg = vcgc.getGroup(vcgUri);
if( vcg == null ){ if( vcg == null ){
throw new Exception("Could not find vclassgroup: " + vcgUri); throw new Exception("Could not find vclassgroup: " + vcgUri);

View file

@ -72,7 +72,10 @@ public class JsonServlet extends VitroHttpServlet {
new GetDataForPage(vreq).process(resp); new GetDataForPage(vreq).process(resp);
}else if( vreq.getParameter("getRenderedSolrIndividualsByVClass") != null ){ }else if( vreq.getParameter("getRenderedSolrIndividualsByVClass") != null ){
new GetRenderedSolrIndividualsByVClass(vreq).process(resp); new GetRenderedSolrIndividualsByVClass(vreq).process(resp);
}else if( vreq.getParameter("getRandomSolrIndividualsByVClass") != null ){
new GetRandomSolrIndividualsByVClass(vreq).process(resp);
} }
} }
@ -135,7 +138,35 @@ public class JsonServlet extends VitroHttpServlet {
return value; return value;
} }
public static JSONObject getRandomSolrIndividualsByVClass(String vclassURI, HttpServletRequest req, ServletContext context) throws Exception {
VitroRequest vreq = new VitroRequest(req);
Map<String, Object> map = getRandomSolrVClassResults(vclassURI, vreq, context);
//last parameter indicates single vclass instead of multiple vclasses
return processVClassResults(map, vreq, context, false);
}
//Including version for Random Solr query for Vclass Intersections
private static Map<String,Object> getRandomSolrVClassResults(String vclassURI, VitroRequest vreq, ServletContext context){
log.debug("Retrieving random Solr intersection results for " + vclassURI);
int page = IndividualListController.getPageParameter(vreq);
int pageSize = Integer.parseInt(vreq.getParameter("pageSize"));
log.debug("page and pageSize parameters = " + page + " and " + pageSize);
Map<String,Object> map = null;
try {
map = IndividualListController.getRandomResultsForVClass(
vclassURI,
page,
pageSize,
vreq.getWebappDaoFactory().getIndividualDao(),
context);
} catch(Exception ex) {
log.error("Error in retrieval of search results for VClass " + vclassURI, ex);
}
return map;
}
} }

View file

@ -2,7 +2,6 @@
package edu.cornell.mannlib.vitro.webapp.controller.login; package edu.cornell.mannlib.vitro.webapp.controller.login;
import java.text.MessageFormat;
import java.util.Arrays; import java.util.Arrays;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -11,6 +10,8 @@ import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.i18n.I18n;
/** /**
* Where are we in the process of logging on? What message should we show to the * Where are we in the process of logging on? What message should we show to the
* user? * user?
@ -110,60 +111,32 @@ public class LoginProcessBean {
} }
public static class Message { public static class Message {
public static final Message NO_MESSAGE = new Message("", MLevel.NONE); public static final Message NO_MESSAGE = new Message();
public static final Message PASSWORD_CHANGE_SAVED = new Message( private final String text;
"Your password has been saved.<br/>" + "Please log in.",
MLevel.INFO);
public static final Message NO_USERNAME = new Message(
"Please enter your email address.", MLevel.ERROR);
public static final Message NO_PASSWORD = new Message(
"Please enter your password.", MLevel.ERROR);
public static final Message UNKNOWN_USERNAME = new Message(
"The email or password you entered is incorrect.", MLevel.ERROR);
public static final Message LOGIN_DISABLED = new Message(
"User logins are temporarily disabled while the system is being maintained.",
MLevel.ERROR);
public static final Message INCORRECT_PASSWORD = new Message(
"The email or password you entered is incorrect.", MLevel.ERROR);
public static final Message NO_NEW_PASSWORD = new Message(
"Please enter your new password.", MLevel.ERROR);
public static final Message MISMATCH_PASSWORD = new Message(
"The passwords entered do not match.", MLevel.ERROR);
public static final Message PASSWORD_LENGTH = new Message(
"Please enter a password between {0} and {1} characters in length.",
MLevel.ERROR);
public static final Message USING_OLD_PASSWORD = new Message(
"Your new password cannot match the current one.", MLevel.ERROR);
private final String format;
private final MLevel messageLevel; private final MLevel messageLevel;
public Message(String format, MLevel messageLevel) { public Message() {
this.format = format; this.messageLevel = MLevel.NONE;
this.messageLevel = messageLevel; this.text = "";
} }
public Message(HttpServletRequest req, MLevel messageLevel, String textKey, Object... parameters) {
this.messageLevel = messageLevel;
this.text = I18n.bundle(req).text(textKey, parameters);
}
public MLevel getMessageLevel() { public MLevel getMessageLevel() {
return this.messageLevel; return this.messageLevel;
} }
public String formatMessage(Object[] args) { public String getText() {
return new MessageFormat(this.format).format(args); return text;
} }
@Override @Override
public String toString() { public String toString() {
return "Message[" + messageLevel + ", '" + format + "']"; return "Message[" + messageLevel + ", '" + text + "']";
} }
} }
@ -210,10 +183,15 @@ public class LoginProcessBean {
} }
} }
public void setMessage(Message message, Object... args) { public void setMessage(Message message) {
synchronized (messageSynchronizer) { synchronized (messageSynchronizer) {
this.message = message; this.message = message;
this.messageArguments = args; }
}
public void setMessage(HttpServletRequest req, MLevel level, String textKey, Object... parameters) {
synchronized (messageSynchronizer) {
this.message = new Message(req, level, textKey, parameters);
} }
} }
@ -221,7 +199,7 @@ public class LoginProcessBean {
synchronized (messageSynchronizer) { synchronized (messageSynchronizer) {
String text = ""; String text = "";
if (message.getMessageLevel() == MLevel.INFO) { if (message.getMessageLevel() == MLevel.INFO) {
text = message.formatMessage(messageArguments); text = message.getText();
clearMessage(); clearMessage();
} }
return text; return text;
@ -232,7 +210,7 @@ public class LoginProcessBean {
synchronized (messageSynchronizer) { synchronized (messageSynchronizer) {
String text = ""; String text = "";
if (message.getMessageLevel() == MLevel.ERROR) { if (message.getMessageLevel() == MLevel.ERROR) {
text = message.formatMessage(messageArguments); text = message.getText();
clearMessage(); clearMessage();
} }
return text; return text;

View file

@ -115,13 +115,6 @@ public class DisplayVocabulary {
public static final String USE_TBOX_MODEL_PARAM = "useThisTboxModel"; public static final String USE_TBOX_MODEL_PARAM = "useThisTboxModel";
public static final String USE_DISPLAY_MODEL_PARAM = "useThisDisplayModel"; public static final String USE_DISPLAY_MODEL_PARAM = "useThisDisplayModel";
//Attribute values used to store display tbox/display display model in servlet context
public static final String CONTEXT_DISPLAY_TBOX = "displayOntModelTBOX";
public static final String CONTEXT_DISPLAY_DISPLAY = "displayOntModelDisplayModel";
/** Key for display model in request, session or context attributes */
public static final String DISPLAY_ONT_MODEL = "displayOntModel";
//URL for menu management //URL for menu management
public static final String PROCESS_MENU_MANAGEMENT_URL = "/menuManagementEdit"; public static final String PROCESS_MENU_MANAGEMENT_URL = "/menuManagementEdit";
public static final String REORDER_MENU_URL = PROCESS_MENU_MANAGEMENT_URL + "?cmd=Reorder&" + SWITCH_TO_DISPLAY_MODEL + "=true"; public static final String REORDER_MENU_URL = PROCESS_MENU_MANAGEMENT_URL + "?cmd=Reorder&" + SWITCH_TO_DISPLAY_MODEL + "=true";

View file

@ -0,0 +1,322 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.dao;
import java.util.EnumMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.ontology.OntModel;
import edu.cornell.mannlib.vitro.webapp.dao.jena.OntModelSelector;
/**
* Hierarchical storage for models. TODO
*
* Could this be extended? Could it be used to replace or implement these
* methods?
*
* <pre>
* VitroRequest.getAssertionsWebappDaoFactory()
* VitroRequest.getFullWebappDaoFactory()
* VitroRequest.getRDFService()
* VitroRequest.getUnfilteredRDFService()
* VitroRequest.getWebappDaoFactory()
* VitroRequest.getWriteModel()
* vreq.setUnfilteredWebappDaoFactory(wadf);
*
* OntModelSelector.getABoxModel
* OntModelSelector.getFullModel()
* OntModelSelector.getTBoxModel()
* VitroModelSource.getModel(URL)
* VitroModelSource.getModel(URL, loadIfAbsent)
* VitroModelSource.openModel(name)
* VitroModelSource.openModelIfPresent(string)
* ServletContext.getAttribute("pelletOntModel")
* VitroJenaModelMaker
* VitroJenaSpecialModelMaker
* JenaDataSourceSetupBase.getApplicationDataSource(ctx)
* JenaDataSourceSetupBase.getStartupDataset()
* HttpSession.getAttribute("jenaAuditModel")
* </pre>
*/
public class ModelAccess {
private static final Log log = LogFactory.getLog(ModelAccess.class);
/** These attributes should only be accessed through this class. */
private static final String ATTRIBUTE_NAME = ModelAccess.class.getName();
public enum ModelID {
APPLICATION_METADATA,
USER_ACCOUNTS,
DISPLAY, DISPLAY_DISPLAY, DISPLAY_TBOX,
BASE_ABOX, BASE_TBOX, BASE_FULL,
INFERRED_ABOX, INFERRED_TBOX, INFERRED_FULL,
UNION_ABOX, UNION_TBOX, UNION_FULL
}
public enum FactoryID {
BASE, UNION
}
private enum Scope {
CONTEXT, SESSION, REQUEST
}
// ----------------------------------------------------------------------
// Factory methods
// ----------------------------------------------------------------------
public static ModelAccess on(HttpServletRequest req) {
Object o = req.getAttribute(ATTRIBUTE_NAME);
if (o instanceof ModelAccess) {
return (ModelAccess) o;
} else {
ModelAccess parent = on(req.getSession());
ModelAccess ma = new ModelAccess(Scope.REQUEST, parent);
req.setAttribute(ATTRIBUTE_NAME, ma);
return ma;
}
}
public static ModelAccess on(HttpSession session) {
Object o = session.getAttribute(ATTRIBUTE_NAME);
if (o instanceof ModelAccess) {
return (ModelAccess) o;
} else {
ModelAccess parent = on(session.getServletContext());
ModelAccess ma = new ModelAccess(Scope.SESSION, parent);
session.setAttribute(ATTRIBUTE_NAME, ma);
return ma;
}
}
public static ModelAccess on(ServletContext ctx) {
Object o = ctx.getAttribute(ATTRIBUTE_NAME);
if (o instanceof ModelAccess) {
return (ModelAccess) o;
} else {
ModelAccess ma = new ModelAccess(Scope.CONTEXT, null);
ctx.setAttribute(ATTRIBUTE_NAME, ma);
return ma;
}
}
// ----------------------------------------------------------------------
// The instance
// ----------------------------------------------------------------------
private final Scope scope;
private final ModelAccess parent;
private final Map<ModelID, OntModel> modelMap = new EnumMap<>(ModelID.class);
private final Map<FactoryID, WebappDaoFactory> factoryMap = new EnumMap<>(
FactoryID.class);
public ModelAccess(Scope scope, ModelAccess parent) {
this.scope = scope;
this.parent = parent;
}
// ----------------------------------------------------------------------
// Accessing the models
// ----------------------------------------------------------------------
public OntModel getApplicationMetadataModel() {
return getOntModel(ModelID.APPLICATION_METADATA);
}
public void setUserAccountsModel(OntModel m) {
setOntModel(ModelID.USER_ACCOUNTS, m);
}
public OntModel getUserAccountsModel() {
return getOntModel(ModelID.USER_ACCOUNTS);
}
public void setDisplayModel(OntModel m) {
setOntModel(ModelID.DISPLAY, m);
}
public OntModel getDisplayModel() {
return getOntModel(ModelID.DISPLAY);
}
public void setJenaOntModel(OntModel m) {
setOntModel(ModelID.UNION_FULL, m);
}
public OntModel getJenaOntModel() {
return getOntModel(ModelID.UNION_FULL);
}
public void setBaseOntModel(OntModel m) {
setOntModel(ModelID.BASE_FULL, m);
}
public OntModel getBaseOntModel() {
return getOntModel(ModelID.BASE_FULL);
}
public OntModel getInferenceOntModel() {
return getOntModel(ModelID.INFERRED_FULL);
}
public void setOntModel(ModelID id, OntModel ontModel) {
if (ontModel == null) {
modelMap.remove(id);
} else {
modelMap.put(id, ontModel);
}
}
public void removeOntModel(ModelID id) {
setOntModel(id, null);
}
public OntModel getOntModel(ModelID id) {
if (modelMap.containsKey(id)) {
log.debug("Using " + id + " model from " + scope);
return modelMap.get(id);
} else if (parent != null) {
return parent.getOntModel(id);
} else {
log.warn("No model found for " + id);
return null;
}
}
// ----------------------------------------------------------------------
// Accessing the Webapp DAO factories.
// ----------------------------------------------------------------------
public void setWebappDaoFactory(WebappDaoFactory wadf) {
setWebappDaoFactory(FactoryID.UNION, wadf);
}
public WebappDaoFactory getWebappDaoFactory() {
return getWebappDaoFactory(FactoryID.UNION);
}
public void setBaseWebappDaoFactory(WebappDaoFactory wadf) {
setWebappDaoFactory(FactoryID.BASE, wadf);
}
public WebappDaoFactory getBaseWebappDaoFactory() {
return getWebappDaoFactory(FactoryID.BASE);
}
public void setWebappDaoFactory(FactoryID id, WebappDaoFactory wadf) {
if (wadf == null) {
factoryMap.remove(id);
} else {
factoryMap.put(id, wadf);
}
}
public void removeWebappDaoFactory(FactoryID id) {
setWebappDaoFactory(id, null);
}
public WebappDaoFactory getWebappDaoFactory(FactoryID id) {
if (factoryMap.containsKey(id)) {
log.debug("Using " + id + " DAO factory from " + scope);
return factoryMap.get(id);
} else if (parent != null) {
return parent.getWebappDaoFactory(id);
} else {
log.warn("No DAO factory found for " + id);
return null;
}
}
// ----------------------------------------------------------------------
// Accessing the OntModelSelectors
// ----------------------------------------------------------------------
public OntModelSelector getOntModelSelector() {
return getUnionOntModelSelector();
}
public OntModelSelector getBaseOntModelSelector() {
return new FacadeOntModelSelector(this, ModelID.BASE_ABOX,
ModelID.BASE_TBOX, ModelID.BASE_FULL);
}
public OntModelSelector getInferenceOntModelSelector() {
return new FacadeOntModelSelector(this, ModelID.INFERRED_ABOX,
ModelID.INFERRED_TBOX, ModelID.INFERRED_FULL);
}
public OntModelSelector getUnionOntModelSelector() {
return new FacadeOntModelSelector(this, ModelID.UNION_ABOX,
ModelID.UNION_TBOX, ModelID.UNION_FULL);
}
// ----------------------------------------------------------------------
// Helper classes
// ----------------------------------------------------------------------
/**
* This OntModelSelector doesn't actually hold any OntModels. Instead, it
* links back to the ModelAccess that it was created from. So, if you change
* a model on the ModelAccess, it will change on the OntModelSelector also.
* Even if the OntModelSelector was created first.
*/
private static class FacadeOntModelSelector implements OntModelSelector {
private final ModelAccess parent;
private final ModelID aboxID;
private final ModelID tboxID;
private final ModelID fullID;
public FacadeOntModelSelector(ModelAccess parent, ModelID aboxID,
ModelID tboxID, ModelID fullID) {
this.parent = parent;
this.aboxID = aboxID;
this.tboxID = tboxID;
this.fullID = fullID;
}
@Override
public OntModel getABoxModel() {
return parent.getOntModel(aboxID);
}
@Override
public OntModel getTBoxModel() {
return parent.getOntModel(tboxID);
}
@Override
public OntModel getFullModel() {
return parent.getOntModel(fullID);
}
@Override
public OntModel getApplicationMetadataModel() {
return parent.getOntModel(ModelID.APPLICATION_METADATA);
}
@Override
public OntModel getUserAccountsModel() {
return parent.getOntModel(ModelID.USER_ACCOUNTS);
}
@Override
public OntModel getDisplayModel() {
return parent.getOntModel(ModelID.DISPLAY);
}
}
}

View file

@ -13,7 +13,9 @@ public interface ObjectPropertyDao extends PropertyDao {
public abstract List<ObjectProperty> getAllObjectProperties(); public abstract List<ObjectProperty> getAllObjectProperties();
public ObjectProperty getObjectPropertyByURI(String objectPropertyURI); public ObjectProperty getObjectPropertyByURI(String objectPropertyURI);
public ObjectProperty getObjectPropertyByURIAndRangeURI(String objectPropertyURI, String rangeURI);
public List <ObjectProperty> getObjectPropertiesForObjectPropertyStatements(List /*of ObjectPropertyStatement */ objectPropertyStatements); public List <ObjectProperty> getObjectPropertiesForObjectPropertyStatements(List /*of ObjectPropertyStatement */ objectPropertyStatements);

View file

@ -41,7 +41,7 @@ public interface ObjectPropertyStatementDao {
public Map<String, String> getMostSpecificTypesInClassgroupsForIndividual(String subjectUri); public Map<String, String> getMostSpecificTypesInClassgroupsForIndividual(String subjectUri);
List<Map<String, String>> getObjectPropertyStatementsForIndividualByProperty( List<Map<String, String>> getObjectPropertyStatementsForIndividualByProperty(
String subjectUri, String propertyUri, String objectKey, String subjectUri, String propertyUri, String objectKey, String rangeUri,
String queryString, Set<String> constructQueryStrings, String queryString, Set<String> constructQueryStrings,
String sortDirection); String sortDirection);

View file

@ -0,0 +1,93 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.dao;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup;
import edu.cornell.mannlib.vitro.webapp.dao.jena.VClassGroupCache;
/**
* A request-based image of the VClassGroupCache. That means that the names of
* the classes and groups are in the correct language for this request.
*/
public class VClassGroupsForRequest {
private static final Log log = LogFactory
.getLog(VClassGroupsForRequest.class);
private final HttpServletRequest req;
private final Map<String, VClassGroup> groupMap = new LinkedHashMap<>();
private final Map<String, VClass> classMap = new HashMap<>();
public VClassGroupsForRequest(HttpServletRequest req, VClassGroupCache cache) {
this.req = req;
for (VClassGroup vcGroup : cache.getGroups()) {
loadGroup(vcGroup);
}
if (log.isDebugEnabled()) {
log.debug("groups: " + groupMap);
log.debug("classes: " + classMap);
}
}
private void loadGroup(VClassGroup vcg) {
VClassGroup newVcg = new VClassGroup(vcg);
newVcg.setPublicName(getNameForGroup(vcg));
groupMap.put(newVcg.getURI(), newVcg);
for (VClass vClass : vcg) {
loadClass(vClass, newVcg);
}
}
private String getNameForGroup(VClassGroup vcGroup) {
VClassGroup g = ModelAccess.on(req).getWebappDaoFactory()
.getVClassGroupDao().getGroupByURI(vcGroup.getURI());
return (g == null) ? vcGroup.getPublicName() : g.getPublicName();
}
private void loadClass(VClass vc, VClassGroup newVcg) {
VClass newVc = new VClass(vc);
newVc.setName(getNameForVClass(vc));
newVc.setGroup(newVcg);
newVcg.add(newVc);
classMap.put(newVc.getURI(), newVc);
}
private String getNameForVClass(VClass vClass) {
VClass vc = ModelAccess.on(req).getWebappDaoFactory().getVClassDao()
.getVClassByURI(vClass.getURI());
return (vc == null) ? vClass.getName() : vc.getName();
}
public VClassGroup getGroup(String vClassGroupURI) {
VClassGroup vcg = groupMap.get(vClassGroupURI);
log.debug("getGroup(" + vClassGroupURI + ") = " + vcg);
return vcg;
}
public List<VClassGroup> getGroups() {
ArrayList<VClassGroup> groups = new ArrayList<>(groupMap.values());
log.debug("getGroups() returned " + groups.size() + " groups.");
return groups;
}
public VClass getCachedVClass(String classUri) {
VClass vc = classMap.get(classUri);
log.debug("getCachedVClass(" + classUri + ") = " + vc);
return vc;
}
}

View file

@ -12,6 +12,7 @@ public class WebappDaoFactoryConfig {
private List<String> preferredLanguages; private List<String> preferredLanguages;
private String defaultNamespace; private String defaultNamespace;
private Set<String> nonUserNamespaces; private Set<String> nonUserNamespaces;
private boolean isUnderlyingStoreReasoned = false;
public WebappDaoFactoryConfig() { public WebappDaoFactoryConfig() {
preferredLanguages = Arrays.asList("en-US", "en", "EN"); preferredLanguages = Arrays.asList("en-US", "en", "EN");
@ -44,4 +45,12 @@ public class WebappDaoFactoryConfig {
this.nonUserNamespaces = nonUserNamespaces; this.nonUserNamespaces = nonUserNamespaces;
} }
public void setUnderlyingStoreReasoned(boolean isReasoned) {
this.isUnderlyingStoreReasoned = isReasoned;
}
public boolean isUnderlyingStoreReasoned() {
return this.isUnderlyingStoreReasoned;
}
} }

View file

@ -8,12 +8,9 @@ import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import net.sf.jga.fn.UnaryFunctor;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty; import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatementImpl; import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatementImpl;
import edu.cornell.mannlib.vitro.webapp.beans.Individual; import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.Property; import edu.cornell.mannlib.vitro.webapp.beans.Property;
import edu.cornell.mannlib.vitro.webapp.beans.VClass; import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao; import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao;
@ -31,21 +28,12 @@ class DataPropertyDaoFiltering extends BaseFiltering implements DataPropertyDao{
this.filters = filters; this.filters = filters;
} }
public void deleteDataProperty(DataProperty dataProperty) { // ----------------------------------------------------------------------
innerDataPropertyDao.deleteDataProperty(dataProperty); // Filtered operations
} // ----------------------------------------------------------------------
@Override
public void deleteDataProperty(String dataPropertyURI) { public void fillDataPropertiesForIndividual(Individual individual) {
innerDataPropertyDao.deleteDataProperty(dataPropertyURI);
}
public boolean annotateDataPropertyAsExternalIdentifier(String dataPropertyURI) {
return innerDataPropertyDao.annotateDataPropertyAsExternalIdentifier(dataPropertyURI);
}
public void fillDataPropertiesForIndividual(Individual individual) {
innerDataPropertyDao.fillDataPropertiesForIndividual(individual); innerDataPropertyDao.fillDataPropertiesForIndividual(individual);
List<DataProperty> props = individual.getDataPropertyList(); List<DataProperty> props = individual.getDataPropertyList();
if(props != null && props.size() > 0){ if(props != null && props.size() > 0){
@ -53,21 +41,23 @@ class DataPropertyDaoFiltering extends BaseFiltering implements DataPropertyDao{
} }
} }
@Override
public List getAllDataProperties() { public List<DataProperty> getAllDataProperties() {
return filter(innerDataPropertyDao.getAllDataProperties(), filters.getDataPropertyFilter()); return filter(innerDataPropertyDao.getAllDataProperties(), filters.getDataPropertyFilter());
} }
public List getAllExternalIdDataProperties() { @Override
public List<DataProperty> getAllExternalIdDataProperties() {
return filter(innerDataPropertyDao.getAllDataProperties(), filters.getDataPropertyFilter()); return filter(innerDataPropertyDao.getAllDataProperties(), filters.getDataPropertyFilter());
} }
@Override
public List<DataProperty> getDataPropertiesForVClass(String classURI) { public List<DataProperty> getDataPropertiesForVClass(String classURI) {
return filter(innerDataPropertyDao.getDataPropertiesForVClass(classURI), return filter(innerDataPropertyDao.getDataPropertiesForVClass(classURI),
filters.getDataPropertyFilter()); filters.getDataPropertyFilter());
} }
@Override
public Collection<DataProperty> getAllPossibleDatapropsForIndividual(String individualURI) { public Collection<DataProperty> getAllPossibleDatapropsForIndividual(String individualURI) {
List<DataProperty> filteredProps = new ArrayList<DataProperty>(); List<DataProperty> filteredProps = new ArrayList<DataProperty>();
for (DataProperty dp: innerDataPropertyDao.getAllPossibleDatapropsForIndividual(individualURI)) { for (DataProperty dp: innerDataPropertyDao.getAllPossibleDatapropsForIndividual(individualURI)) {
@ -79,125 +69,137 @@ class DataPropertyDaoFiltering extends BaseFiltering implements DataPropertyDao{
return filteredProps; return filteredProps;
} }
// ----------------------------------------------------------------------
// Unfiltered operations
// ----------------------------------------------------------------------
@Override
public void deleteDataProperty(DataProperty dataProperty) {
innerDataPropertyDao.deleteDataProperty(dataProperty);
}
@Override
public void deleteDataProperty(String dataPropertyURI) {
innerDataPropertyDao.deleteDataProperty(dataPropertyURI);
}
@Override
public boolean annotateDataPropertyAsExternalIdentifier(String dataPropertyURI) {
return innerDataPropertyDao.annotateDataPropertyAsExternalIdentifier(dataPropertyURI);
}
@Override
public String getRequiredDatatypeURI(Individual individual, DataProperty dataProperty) { public String getRequiredDatatypeURI(Individual individual, DataProperty dataProperty) {
return innerDataPropertyDao.getRequiredDatatypeURI(individual, dataProperty); return innerDataPropertyDao.getRequiredDatatypeURI(individual, dataProperty);
} }
@Override
public DataProperty getDataPropertyByURI(String dataPropertyURI) { public DataProperty getDataPropertyByURI(String dataPropertyURI) {
DataProperty prop = innerDataPropertyDao.getDataPropertyByURI(dataPropertyURI); return innerDataPropertyDao.getDataPropertyByURI(dataPropertyURI);
if( prop != null ){
Boolean acceptable = filters.getDataPropertyFilter().fn(prop);
if( acceptable == Boolean.TRUE )
return prop;
else
return null;
}
return null;
} }
@Override
public String insertDataProperty(DataProperty dataProperty) throws InsertException { public String insertDataProperty(DataProperty dataProperty) throws InsertException {
return innerDataPropertyDao.insertDataProperty(dataProperty); return innerDataPropertyDao.insertDataProperty(dataProperty);
} }
@Override
public void updateDataProperty(DataProperty dataProperty) { public void updateDataProperty(DataProperty dataProperty) {
innerDataPropertyDao.updateDataProperty(dataProperty); innerDataPropertyDao.updateDataProperty(dataProperty);
} }
public void addSuperproperty(ObjectProperty property, ObjectProperty superproperty) { @Override
innerDataPropertyDao.addSuperproperty(property, superproperty);
}
public void addSuperproperty(String propertyURI, String superpropertyURI) { public void addSuperproperty(String propertyURI, String superpropertyURI) {
innerDataPropertyDao.addSuperproperty(propertyURI, superpropertyURI); innerDataPropertyDao.addSuperproperty(propertyURI, superpropertyURI);
} }
public void removeSuperproperty(ObjectProperty property, ObjectProperty superproperty) { @Override
innerDataPropertyDao.removeSuperproperty(property, superproperty);
}
public void removeSuperproperty(String propertyURI, String superpropertyURI) { public void removeSuperproperty(String propertyURI, String superpropertyURI) {
innerDataPropertyDao.removeSuperproperty(propertyURI, superpropertyURI); innerDataPropertyDao.removeSuperproperty(propertyURI, superpropertyURI);
} }
public void addSubproperty(ObjectProperty property, ObjectProperty subproperty) { @Override
innerDataPropertyDao.addSubproperty(property, subproperty);
}
public void addSubproperty(String propertyURI, String subpropertyURI) { public void addSubproperty(String propertyURI, String subpropertyURI) {
innerDataPropertyDao.addSubproperty(propertyURI, subpropertyURI); innerDataPropertyDao.addSubproperty(propertyURI, subpropertyURI);
} }
public void removeSubproperty(ObjectProperty property, ObjectProperty subproperty) { @Override
innerDataPropertyDao.removeSubproperty(property, subproperty);
}
public void removeSubproperty(String propertyURI, String subpropertyURI) { public void removeSubproperty(String propertyURI, String subpropertyURI) {
innerDataPropertyDao.removeSubproperty(propertyURI, subpropertyURI); innerDataPropertyDao.removeSubproperty(propertyURI, subpropertyURI);
} }
@Override
public List <String> getSubPropertyURIs(String propertyURI) { public List <String> getSubPropertyURIs(String propertyURI) {
return innerDataPropertyDao.getSubPropertyURIs(propertyURI); return innerDataPropertyDao.getSubPropertyURIs(propertyURI);
} }
@Override
public List <String> getAllSubPropertyURIs(String propertyURI) { public List <String> getAllSubPropertyURIs(String propertyURI) {
return innerDataPropertyDao.getAllSubPropertyURIs(propertyURI); return innerDataPropertyDao.getAllSubPropertyURIs(propertyURI);
} }
@Override
public List <String> getSuperPropertyURIs(String propertyURI, boolean direct) { public List <String> getSuperPropertyURIs(String propertyURI, boolean direct) {
return innerDataPropertyDao.getSuperPropertyURIs(propertyURI, direct); return innerDataPropertyDao.getSuperPropertyURIs(propertyURI, direct);
} }
@Override
public List <String> getAllSuperPropertyURIs(String propertyURI) { public List <String> getAllSuperPropertyURIs(String propertyURI) {
return innerDataPropertyDao.getAllSuperPropertyURIs(propertyURI); return innerDataPropertyDao.getAllSuperPropertyURIs(propertyURI);
} }
@Override
public List<DataProperty> getRootDataProperties() { public List<DataProperty> getRootDataProperties() {
return innerDataPropertyDao.getRootDataProperties(); return innerDataPropertyDao.getRootDataProperties();
} }
@Override
public void addSubproperty(Property property, Property subproperty) { public void addSubproperty(Property property, Property subproperty) {
innerDataPropertyDao.addSubproperty(property, subproperty); innerDataPropertyDao.addSubproperty(property, subproperty);
} }
@Override
public void addSuperproperty(Property property, Property superproperty) { public void addSuperproperty(Property property, Property superproperty) {
innerDataPropertyDao.addSuperproperty(property, superproperty); innerDataPropertyDao.addSuperproperty(property, superproperty);
} }
@Override
public void removeSubproperty(Property property, Property subproperty) { public void removeSubproperty(Property property, Property subproperty) {
innerDataPropertyDao.removeSubproperty(property, subproperty); innerDataPropertyDao.removeSubproperty(property, subproperty);
} }
@Override
public void removeSuperproperty(Property property, Property superproperty) { public void removeSuperproperty(Property property, Property superproperty) {
innerDataPropertyDao.removeSuperproperty(property, superproperty); innerDataPropertyDao.removeSuperproperty(property, superproperty);
} }
public void addEquivalentProperty(String propertyURI, @Override
String equivalentPropertyURI) { public void addEquivalentProperty(String propertyURI, String equivalentPropertyURI) {
innerDataPropertyDao.addEquivalentProperty(propertyURI, equivalentPropertyURI); innerDataPropertyDao.addEquivalentProperty(propertyURI, equivalentPropertyURI);
} }
public void addEquivalentProperty(Property property, @Override
Property equivalentProperty) { public void addEquivalentProperty(Property property, Property equivalentProperty) {
innerDataPropertyDao.addEquivalentProperty(property, equivalentProperty); innerDataPropertyDao.addEquivalentProperty(property, equivalentProperty);
} }
@Override
public List<String> getEquivalentPropertyURIs(String propertyURI) { public List<String> getEquivalentPropertyURIs(String propertyURI) {
return innerDataPropertyDao.getEquivalentPropertyURIs(propertyURI); return innerDataPropertyDao.getEquivalentPropertyURIs(propertyURI);
} }
public void removeEquivalentProperty(String propertyURI, @Override
String equivalentPropertyURI) { public void removeEquivalentProperty(String propertyURI, String equivalentPropertyURI) {
innerDataPropertyDao.removeEquivalentProperty(propertyURI, equivalentPropertyURI); innerDataPropertyDao.removeEquivalentProperty(propertyURI, equivalentPropertyURI);
} }
public void removeEquivalentProperty(Property property, @Override
Property equivalentProperty) { public void removeEquivalentProperty(Property property, Property equivalentProperty) {
innerDataPropertyDao.removeEquivalentProperty(property, equivalentProperty); innerDataPropertyDao.removeEquivalentProperty(property, equivalentProperty);
} }
public List <VClass> getClassesWithRestrictionOnProperty(String propertyURI) { @Override
public List <VClass> getClassesWithRestrictionOnProperty(String propertyURI) {
return innerDataPropertyDao.getClassesWithRestrictionOnProperty(propertyURI); return innerDataPropertyDao.getClassesWithRestrictionOnProperty(propertyURI);
} }

View file

@ -15,6 +15,8 @@ import java.util.Map;
import net.sf.jga.algorithms.Filter; import net.sf.jga.algorithms.Filter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
@ -29,7 +31,6 @@ import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatementImpl; import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatementImpl;
import edu.cornell.mannlib.vitro.webapp.beans.VClass; import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.filtering.filters.VitroFilters; import edu.cornell.mannlib.vitro.webapp.dao.filtering.filters.VitroFilters;
import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch;
/** /**
* A Individual object that will delegate to an inner Individual * A Individual object that will delegate to an inner Individual
@ -42,6 +43,8 @@ import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch;
public class IndividualFiltering implements Individual { public class IndividualFiltering implements Individual {
private final Individual _innerIndividual; private final Individual _innerIndividual;
private final VitroFilters _filters; private final VitroFilters _filters;
private static final Log log = LogFactory.getLog(IndividualFiltering.class);
public IndividualFiltering(Individual individual, VitroFilters filters) { public IndividualFiltering(Individual individual, VitroFilters filters) {
super(); super();
@ -143,10 +146,18 @@ public class IndividualFiltering implements Individual {
// I'd rather filter on the actual ObjectPropertyStatements here, but // I'd rather filter on the actual ObjectPropertyStatements here, but
// Individual.getPopulatedObjectPropertyList doesn't actually populate // Individual.getPopulatedObjectPropertyList doesn't actually populate
// the ObjectProperty with statements. - jblake // the ObjectProperty with statements. - jblake
// bjl23: disabling this filtering because the individual statements are
// filtered later, and we need to allow for the possibility that a particular
// predicate + range class combination is allowed even if the predicate is
// hidden on its own.
// Will revisit filtering at this level if it turns out to be truly necessary.
List<ObjectProperty> outOProps = new ArrayList<ObjectProperty>(); List<ObjectProperty> outOProps = new ArrayList<ObjectProperty>();
List<ObjectProperty> oProps = _innerIndividual.getPopulatedObjectPropertyList(); List<ObjectProperty> oProps = _innerIndividual.getPopulatedObjectPropertyList();
for (ObjectProperty op: oProps) { for (ObjectProperty op: oProps) {
if (_filters.getObjectPropertyStatementFilter().fn( if (true || _filters.getObjectPropertyStatementFilter().fn(
new ObjectPropertyStatementImpl(this._innerIndividual.getURI(), op.getURI(), SOME_LITERAL))) { new ObjectPropertyStatementImpl(this._innerIndividual.getURI(), op.getURI(), SOME_LITERAL))) {
outOProps.add(op); outOProps.add(op);
} }

View file

@ -48,6 +48,11 @@ class ObjectPropertyDaoFiltering extends BaseFiltering implements ObjectProperty
ObjectProperty newOprop=innerObjectPropertyDao.getObjectPropertyByURI(objectPropertyURI); ObjectProperty newOprop=innerObjectPropertyDao.getObjectPropertyByURI(objectPropertyURI);
return (newOprop == null) ? null : new ObjectPropertyFiltering(newOprop, filters); return (newOprop == null) ? null : new ObjectPropertyFiltering(newOprop, filters);
} }
public ObjectProperty getObjectPropertyByURIAndRangeURI(String objectPropertyURI, String rangeURI) {
ObjectProperty newOprop=innerObjectPropertyDao.getObjectPropertyByURIAndRangeURI(objectPropertyURI, rangeURI);
return (newOprop == null) ? null : new ObjectPropertyFiltering(newOprop, filters);
}
public List<ObjectPropertyStatement> getStatementsUsingObjectProperty(ObjectProperty op) { public List<ObjectPropertyStatement> getStatementsUsingObjectProperty(ObjectProperty op) {
return ObjectPropertyStatementDaoFiltering.filterAndWrapList(innerObjectPropertyDao.getStatementsUsingObjectProperty(op),filters); return ObjectPropertyStatementDaoFiltering.filterAndWrapList(innerObjectPropertyDao.getStatementsUsingObjectProperty(op),filters);

View file

@ -86,12 +86,12 @@ class ObjectPropertyStatementDaoFiltering extends BaseFiltering implements Objec
@Override @Override
public List<Map<String, String>> getObjectPropertyStatementsForIndividualByProperty( public List<Map<String, String>> getObjectPropertyStatementsForIndividualByProperty(
String subjectUri, String propertyUri, String objectKey, String query, String subjectUri, String propertyUri, String objectKey, String rangeUri,
Set<String> queryStrings, String sortDirection) { String query, Set<String> queryStrings, String sortDirection) {
List<Map<String, String>> data = List<Map<String, String>> data =
innerObjectPropertyStatementDao.getObjectPropertyStatementsForIndividualByProperty( innerObjectPropertyStatementDao.getObjectPropertyStatementsForIndividualByProperty(
subjectUri, propertyUri, objectKey, query, queryStrings,sortDirection); subjectUri, propertyUri, objectKey, rangeUri, query, queryStrings,sortDirection);
/* Filter the data /* Filter the data
* *
@ -105,6 +105,10 @@ class ObjectPropertyStatementDaoFiltering extends BaseFiltering implements Objec
for (Map<String, String> map : data) { for (Map<String, String> map : data) {
String objectUri = map.get(objectKey); String objectUri = map.get(objectKey);
ObjectPropertyStatement statement = new ObjectPropertyStatementImpl(subjectUri, propertyUri, objectUri); ObjectPropertyStatement statement = new ObjectPropertyStatementImpl(subjectUri, propertyUri, objectUri);
ObjectProperty op = new ObjectProperty();
op.setURI(propertyUri);
op.setRangeVClassURI(rangeUri);
statement.setProperty(op);
stmtsToData.put(statement, map); stmtsToData.put(statement, map);
} }

View file

@ -8,7 +8,6 @@ import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -24,7 +23,6 @@ import com.hp.hpl.jena.ontology.OntProperty;
import com.hp.hpl.jena.ontology.OntResource; import com.hp.hpl.jena.ontology.OntResource;
import com.hp.hpl.jena.ontology.ProfileException; import com.hp.hpl.jena.ontology.ProfileException;
import com.hp.hpl.jena.ontology.Restriction; import com.hp.hpl.jena.ontology.Restriction;
import com.hp.hpl.jena.ontology.SomeValuesFromRestriction;
import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.query.QueryExecutionFactory;
@ -53,7 +51,6 @@ import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao; import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.InsertException; import edu.cornell.mannlib.vitro.webapp.dao.InsertException;
import edu.cornell.mannlib.vitro.webapp.dao.OntologyDao; import edu.cornell.mannlib.vitro.webapp.dao.OntologyDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.jena.event.EditEvent; import edu.cornell.mannlib.vitro.webapp.dao.jena.event.EditEvent;
import edu.cornell.mannlib.vitro.webapp.dao.jena.pellet.PelletListener; import edu.cornell.mannlib.vitro.webapp.dao.jena.pellet.PelletListener;
@ -93,7 +90,7 @@ public class DataPropertyDaoJena extends PropertyDaoJena implements
try { try {
com.hp.hpl.jena.ontology.OntResource ind = ontModel.getOntResource(dataPropertyURI); com.hp.hpl.jena.ontology.OntResource ind = ontModel.getOntResource(dataPropertyURI);
if( ind != null ){ if( ind != null ){
ontModel.add(ind,(Property)DATAPROPERTY_ISEXTERNALID, "TRUE"); ontModel.add(ind, DATAPROPERTY_ISEXTERNALID, "TRUE");
return true; return true;
}else{ }else{
return false; return false;
@ -114,7 +111,7 @@ public class DataPropertyDaoJena extends PropertyDaoJena implements
while(restIt.hasNext()) { while(restIt.hasNext()) {
Resource restRes = restIt.next(); Resource restRes = restIt.next();
if (restRes.canAs(OntResource.class)) { if (restRes.canAs(OntResource.class)) {
OntResource restOntRes = (OntResource) restRes.as(OntResource.class); OntResource restOntRes = restRes.as(OntResource.class);
smartRemove(restOntRes, ontModel); smartRemove(restOntRes, ontModel);
} }
} }
@ -181,7 +178,7 @@ public class DataPropertyDaoJena extends PropertyDaoJena implements
dp.setNamespace(op.getNameSpace()); dp.setNamespace(op.getNameSpace());
dp.setLocalName(op.getLocalName()); dp.setLocalName(op.getLocalName());
OntologyDao oDao=getWebappDaoFactory().getOntologyDao(); OntologyDao oDao=getWebappDaoFactory().getOntologyDao();
Ontology o = (Ontology)oDao.getOntologyByURI(dp.getNamespace()); Ontology o = oDao.getOntologyByURI(dp.getNamespace());
if (o==null) { if (o==null) {
if (!VitroVocabulary.vitroURI.equals(dp.getNamespace())) { if (!VitroVocabulary.vitroURI.equals(dp.getNamespace())) {
log.debug("datapropFromOntProperty(): no ontology object found for the namespace "+dp.getNamespace()); log.debug("datapropFromOntProperty(): no ontology object found for the namespace "+dp.getNamespace());
@ -206,8 +203,8 @@ public class DataPropertyDaoJena extends PropertyDaoJena implements
dp.setExample(getPropertyStringValue(op,EXAMPLE_ANNOT)); dp.setExample(getPropertyStringValue(op,EXAMPLE_ANNOT));
dp.setDescription(getPropertyStringValue(op,DESCRIPTION_ANNOT)); dp.setDescription(getPropertyStringValue(op,DESCRIPTION_ANNOT));
dp.setPublicDescription(getPropertyStringValue(op,PUBLIC_DESCRIPTION_ANNOT)); dp.setPublicDescription(getPropertyStringValue(op,PUBLIC_DESCRIPTION_ANNOT));
dp.setDisplayTier(((WebappDaoFactoryJena)getWebappDaoFactory()).getJenaBaseDao().getPropertyNonNegativeIntValue(op, DISPLAY_RANK_ANNOT)); dp.setDisplayTier((getWebappDaoFactory()).getJenaBaseDao().getPropertyNonNegativeIntValue(op, DISPLAY_RANK_ANNOT));
dp.setDisplayLimit(((WebappDaoFactoryJena)getWebappDaoFactory()).getJenaBaseDao().getPropertyNonNegativeIntValue(op, DISPLAY_LIMIT)); dp.setDisplayLimit((getWebappDaoFactory()).getJenaBaseDao().getPropertyNonNegativeIntValue(op, DISPLAY_LIMIT));
//There might be multiple HIDDEN_FROM_DISPLAY_BELOW_ROLE_LEVEL_ANNOT properties, only use the highest //There might be multiple HIDDEN_FROM_DISPLAY_BELOW_ROLE_LEVEL_ANNOT properties, only use the highest
StmtIterator it = op.listProperties(HIDDEN_FROM_DISPLAY_BELOW_ROLE_LEVEL_ANNOT); StmtIterator it = op.listProperties(HIDDEN_FROM_DISPLAY_BELOW_ROLE_LEVEL_ANNOT);
@ -216,7 +213,7 @@ public class DataPropertyDaoJena extends PropertyDaoJena implements
Statement stmt = it.nextStatement(); Statement stmt = it.nextStatement();
RDFNode obj; RDFNode obj;
if( stmt != null && (obj = stmt.getObject()) != null && obj.isURIResource() ){ if( stmt != null && (obj = stmt.getObject()) != null && obj.isURIResource() ){
Resource res = (Resource)obj.as(Resource.class); Resource res = obj.as(Resource.class);
if( res != null && res.getURI() != null ){ if( res != null && res.getURI() != null ){
BaseResourceBean.RoleLevel roleFromModel = BaseResourceBean.RoleLevel.getRoleByUri(res.getURI()); BaseResourceBean.RoleLevel roleFromModel = BaseResourceBean.RoleLevel.getRoleByUri(res.getURI());
if( roleFromModel != null && if( roleFromModel != null &&
@ -235,7 +232,7 @@ public class DataPropertyDaoJena extends PropertyDaoJena implements
Statement stmt = it.nextStatement(); Statement stmt = it.nextStatement();
RDFNode obj; RDFNode obj;
if( stmt != null && (obj = stmt.getObject()) != null && obj.isURIResource() ){ if( stmt != null && (obj = stmt.getObject()) != null && obj.isURIResource() ){
Resource res = (Resource)obj.as(Resource.class); Resource res = obj.as(Resource.class);
if( res != null && res.getURI() != null ){ if( res != null && res.getURI() != null ){
BaseResourceBean.RoleLevel roleFromModel = BaseResourceBean.RoleLevel.getRoleByUri(res.getURI()); BaseResourceBean.RoleLevel roleFromModel = BaseResourceBean.RoleLevel.getRoleByUri(res.getURI());
if( roleFromModel != null && if( roleFromModel != null &&
@ -365,7 +362,7 @@ public class DataPropertyDaoJena extends PropertyDaoJena implements
while (restIt.hasNext()) { while (restIt.hasNext()) {
Resource restRes = restIt.next(); Resource restRes = restIt.next();
if (restRes.canAs(Restriction.class)) { if (restRes.canAs(Restriction.class)) {
Restriction rest = (Restriction) restRes.as(Restriction.class); Restriction rest = restRes.as(Restriction.class);
if (rest.isAllValuesFromRestriction()) { if (rest.isAllValuesFromRestriction()) {
AllValuesFromRestriction avfrest = rest.asAllValuesFromRestriction(); AllValuesFromRestriction avfrest = rest.asAllValuesFromRestriction();
if (avfrest.getAllValuesFrom() != null) { if (avfrest.getAllValuesFrom() != null) {
@ -485,7 +482,7 @@ public class DataPropertyDaoJena extends PropertyDaoJena implements
} }
com.hp.hpl.jena.ontology.DatatypeProperty jDataprop = ontModel.createDatatypeProperty(dtp.getURI()); com.hp.hpl.jena.ontology.DatatypeProperty jDataprop = ontModel.createDatatypeProperty(dtp.getURI());
if (dtp.getPublicName() != null && dtp.getPublicName().length() > 0) { if (dtp.getPublicName() != null && dtp.getPublicName().length() > 0) {
jDataprop.setLabel(dtp.getPublicName(), (String) getDefaultLanguage()); jDataprop.setLabel(dtp.getPublicName(), getDefaultLanguage());
} else { } else {
jDataprop.removeAll(RDFS.label); jDataprop.removeAll(RDFS.label);
} }
@ -609,7 +606,7 @@ public class DataPropertyDaoJena extends PropertyDaoJena implements
while (parentNodeIt.hasNext()) { while (parentNodeIt.hasNext()) {
RDFNode parentNode = parentNodeIt.next(); RDFNode parentNode = parentNodeIt.next();
if (parentNode.canAs(Property.class)) { if (parentNode.canAs(Property.class)) {
parentList.add((Property) parentNode.as(Property.class)); parentList.add(parentNode.as(Property.class));
} }
} }
if (parentList.size()==0) { if (parentList.size()==0) {

View file

@ -10,6 +10,9 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.datatypes.TypeMapper; import com.hp.hpl.jena.datatypes.TypeMapper;
import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntResource; import com.hp.hpl.jena.ontology.OntResource;
@ -27,7 +30,6 @@ import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory; import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.Statement;
@ -40,14 +42,9 @@ import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement; import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatementImpl; import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatementImpl;
import edu.cornell.mannlib.vitro.webapp.beans.Individual; import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.controller.edit.ReorderController;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyStatementDao; import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyStatementDao;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.jena.event.IndividualUpdateEvent; import edu.cornell.mannlib.vitro.webapp.dao.jena.event.IndividualUpdateEvent;
import edu.cornell.mannlib.vitro.webapp.dao.jena.ObjectPropertyStatementDaoJena;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class DataPropertyStatementDaoJena extends JenaBaseDao implements DataPropertyStatementDao public class DataPropertyStatementDaoJena extends JenaBaseDao implements DataPropertyStatementDao
{ {
@ -114,7 +111,7 @@ public class DataPropertyStatementDaoJena extends JenaBaseDao implements DataPro
StmtIterator stmtIt = ind.listProperties(); StmtIterator stmtIt = ind.listProperties();
while( stmtIt.hasNext() ) while( stmtIt.hasNext() )
{ {
Statement st = (Statement)stmtIt.next(); Statement st = stmtIt.next();
boolean addToList = /*allowAnyNameSpace ? st.getObject().canAs(Literal.class) :*/ st.getObject().isLiteral() && boolean addToList = /*allowAnyNameSpace ? st.getObject().canAs(Literal.class) :*/ st.getObject().isLiteral() &&
( (
(RDF.value.equals(st.getPredicate()) || VitroVocabulary.value.equals(st.getPredicate().getURI())) (RDF.value.equals(st.getPredicate()) || VitroVocabulary.value.equals(st.getPredicate().getURI()))
@ -210,7 +207,7 @@ public class DataPropertyStatementDaoJena extends JenaBaseDao implements DataPro
// do something annoying if we are dealing with a blank node // do something annoying if we are dealing with a blank node
try { try {
getOntModel().enterCriticalSection(Lock.READ); getOntModel().enterCriticalSection(Lock.READ);
OntResource ontRes = (OntResource) getOntModel().createResource( OntResource ontRes = getOntModel().createResource(
new AnonId(entity.getLocalName())).as(OntResource.class); new AnonId(entity.getLocalName())).as(OntResource.class);
if (ontRes == null) { if (ontRes == null) {
return edList; return edList;

View file

@ -3,7 +3,6 @@
package edu.cornell.mannlib.vitro.webapp.dao.jena; package edu.cornell.mannlib.vitro.webapp.dao.jena;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.List; import java.util.List;
import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntModel;
@ -12,20 +11,15 @@ import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.QuerySolutionMap;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.shared.Lock; import com.hp.hpl.jena.shared.Lock;
import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDF;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement; import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatementImpl; import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatementImpl;
import edu.cornell.mannlib.vitro.webapp.beans.Individual; import edu.cornell.mannlib.vitro.webapp.beans.Individual;
@ -85,7 +79,7 @@ public class DataPropertyStatementDaoSDB extends DataPropertyStatementDaoJena
StmtIterator stmtIt = ind.listProperties(); StmtIterator stmtIt = ind.listProperties();
while( stmtIt.hasNext() ) while( stmtIt.hasNext() )
{ {
Statement st = (Statement)stmtIt.next(); Statement st = stmtIt.next();
boolean addToList = /*allowAnyNameSpace ? st.getObject().canAs(Literal.class) :*/ st.getObject().isLiteral() && boolean addToList = /*allowAnyNameSpace ? st.getObject().canAs(Literal.class) :*/ st.getObject().isLiteral() &&
( (
(RDF.value.equals(st.getPredicate()) || VitroVocabulary.value.equals(st.getPredicate().getURI())) (RDF.value.equals(st.getPredicate()) || VitroVocabulary.value.equals(st.getPredicate().getURI()))

View file

@ -4,14 +4,10 @@ package edu.cornell.mannlib.vitro.webapp.dao.jena;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.List; import java.util.List;
import com.hp.hpl.jena.ontology.OntModel;
import edu.cornell.mannlib.vitro.webapp.beans.Datatype; import edu.cornell.mannlib.vitro.webapp.beans.Datatype;
import edu.cornell.mannlib.vitro.webapp.dao.DatatypeDao; import edu.cornell.mannlib.vitro.webapp.dao.DatatypeDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
public class DatatypeDaoJena extends JenaBaseDao implements DatatypeDao { public class DatatypeDaoJena extends JenaBaseDao implements DatatypeDao {

View file

@ -9,7 +9,6 @@ import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
import java.util.Set; import java.util.Set;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.Property;
@ -89,14 +88,13 @@ public class DependentResourceDeleteJena {
* Find all statements where for a given statement in the assertions, * Find all statements where for a given statement in the assertions,
* there is at least one statement in the retractions that has * there is at least one statement in the retractions that has
* the same predicate and object. */ * the same predicate and object. */
@SuppressWarnings("unchecked")
private static List<Statement> getChangedStmts(Model assertions, Model retractions){ private static List<Statement> getChangedStmts(Model assertions, Model retractions){
List<Statement> changedStmts = new LinkedList<Statement>(); List<Statement> changedStmts = new LinkedList<Statement>();
StmtIterator it = assertions.listStatements(); StmtIterator it = assertions.listStatements();
while(it.hasNext()){ while(it.hasNext()){
Statement assertionStmtStatement = it.nextStatement(); Statement assertionStmtStatement = it.nextStatement();
if( assertionStmtStatement.getObject().canAs( Resource.class )){ if( assertionStmtStatement.getObject().canAs( Resource.class )){
Resource asserObj = (Resource) assertionStmtStatement.getObject().as(Resource.class); Resource asserObj = assertionStmtStatement.getObject().as(Resource.class);
StmtIterator retractionStmts = StmtIterator retractionStmts =
retractions.listStatements( retractions.listStatements(
(Resource)null, (Resource)null,
@ -138,7 +136,7 @@ public class DependentResourceDeleteJena {
if( ( obj.canAs(Resource.class) && isPredicateDependencyRelation(stmt.getPredicate(), model) ) if( ( obj.canAs(Resource.class) && isPredicateDependencyRelation(stmt.getPredicate(), model) )
|| ( obj.isAnon() && perviousWasDependentResource ) ){ || ( obj.isAnon() && perviousWasDependentResource ) ){
Resource res = (Resource)obj.as(Resource.class); Resource res = obj.as(Resource.class);
String id = res.isAnon()?res.getId().toString():res.getURI(); String id = res.isAnon()?res.getId().toString():res.getURI();
if( !visitedUris.contains(id) ){ if( !visitedUris.contains(id) ){

View file

@ -7,9 +7,7 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.FileReader; import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader; import java.io.StringReader;
import java.nio.channels.FileChannel; import java.nio.channels.FileChannel;
@ -22,7 +20,6 @@ import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory; import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.util.FileManager;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayModelDao; import edu.cornell.mannlib.vitro.webapp.dao.DisplayModelDao;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;

View file

@ -2,7 +2,6 @@
package edu.cornell.mannlib.vitro.webapp.dao.jena; package edu.cornell.mannlib.vitro.webapp.dao.jena;
import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import org.apache.commons.collections.iterators.EmptyIterator; import org.apache.commons.collections.iterators.EmptyIterator;

View file

@ -146,7 +146,7 @@ public class IndividualDaoJena extends JenaBaseDao implements IndividualDao {
if (theClass.isAnon() && theClass.canAs(UnionClass.class)) { if (theClass.isAnon() && theClass.canAs(UnionClass.class)) {
UnionClass u = (UnionClass) theClass.as(UnionClass.class); UnionClass u = theClass.as(UnionClass.class);
for (OntClass operand : u.listOperands().toList()) { for (OntClass operand : u.listOperands().toList()) {
VClass vc = new VClassJena(operand, getWebappDaoFactory()); VClass vc = new VClassJena(operand, getWebappDaoFactory());
ents.addAll(getIndividualsByVClass(vc)); ents.addAll(getIndividualsByVClass(vc));
@ -159,8 +159,8 @@ public class IndividualDaoJena extends JenaBaseDao implements IndividualDao {
try { try {
while (stmtIt.hasNext()) { while (stmtIt.hasNext()) {
Statement stmt = stmtIt.nextStatement(); Statement stmt = stmtIt.nextStatement();
OntResource ind = (OntResource) stmt.getSubject().as(OntResource.class); OntResource ind = stmt.getSubject().as(OntResource.class);
ents.add(new IndividualJena(ind, (WebappDaoFactoryJena) getWebappDaoFactory())); ents.add(new IndividualJena(ind, getWebappDaoFactory()));
} }
} finally { } finally {
stmtIt.close(); stmtIt.close();
@ -232,7 +232,7 @@ public class IndividualDaoJena extends JenaBaseDao implements IndividualDao {
ontModel.getBaseModel().notifyEvent(new IndividualCreationEvent(getWebappDaoFactory().getUserURI(),true,entURI)); ontModel.getBaseModel().notifyEvent(new IndividualCreationEvent(getWebappDaoFactory().getUserURI(),true,entURI));
com.hp.hpl.jena.ontology.Individual ind = ontModel.createIndividual(entURI,cls); com.hp.hpl.jena.ontology.Individual ind = ontModel.createIndividual(entURI,cls);
if (ent.getName() != null) { if (ent.getName() != null) {
ind.setLabel(ent.getName(), (String) getDefaultLanguage()); ind.setLabel(ent.getName(), getDefaultLanguage());
} }
List<VClass> vclasses = ent.getVClasses(false); List<VClass> vclasses = ent.getVClasses(false);
if (vclasses != null) { if (vclasses != null) {
@ -388,7 +388,7 @@ public class IndividualDaoJena extends JenaBaseDao implements IndividualDao {
return 1; return 1;
} }
if (res.canAs(OntResource.class)) { if (res.canAs(OntResource.class)) {
OntResource ontRes = (OntResource) res.as(OntResource.class); OntResource ontRes = res.as(OntResource.class);
smartRemove(ontRes, ontModel); smartRemove(ontRes, ontModel);
} else { } else {
ontModel.removeAll(res,null,null); ontModel.removeAll(res,null,null);
@ -420,7 +420,7 @@ public class IndividualDaoJena extends JenaBaseDao implements IndividualDao {
OntResource ontRes = (entityURI.startsWith(VitroVocabulary.PSEUDO_BNODE_NS)) OntResource ontRes = (entityURI.startsWith(VitroVocabulary.PSEUDO_BNODE_NS))
? (OntResource) ontModel.createResource(new AnonId(entityURI.substring(VitroVocabulary.PSEUDO_BNODE_NS.length()))).as(OntResource.class) ? (OntResource) ontModel.createResource(new AnonId(entityURI.substring(VitroVocabulary.PSEUDO_BNODE_NS.length()))).as(OntResource.class)
: ontModel.getOntResource(entityURI); : ontModel.getOntResource(entityURI);
Individual ent = new IndividualJena(ontRes, (WebappDaoFactoryJena) getWebappDaoFactory()); Individual ent = new IndividualJena(ontRes, getWebappDaoFactory());
return ent; return ent;
} catch (Exception ex) { } catch (Exception ex) {
return null; return null;
@ -494,7 +494,7 @@ public class IndividualDaoJena extends JenaBaseDao implements IndividualDao {
String subUri = ((Resource)sub).getURI(); String subUri = ((Resource)sub).getURI();
if( ! individualsMap.containsKey(subUri)){ if( ! individualsMap.containsKey(subUri)){
com.hp.hpl.jena.ontology.Individual ind = getOntModel().getIndividual(subUri); com.hp.hpl.jena.ontology.Individual ind = getOntModel().getIndividual(subUri);
individualsMap.put(subUri,new IndividualJena(ind, (WebappDaoFactoryJena) getWebappDaoFactory())); individualsMap.put(subUri,new IndividualJena(ind, getWebappDaoFactory()));
} }
} }
@ -519,7 +519,7 @@ public class IndividualDaoJena extends JenaBaseDao implements IndividualDao {
String subUri = ((Resource)sub).getURI(); String subUri = ((Resource)sub).getURI();
if( ! individualsMap.containsKey(subUri)){ if( ! individualsMap.containsKey(subUri)){
com.hp.hpl.jena.ontology.Individual ind = getOntModel().getIndividual(subUri); com.hp.hpl.jena.ontology.Individual ind = getOntModel().getIndividual(subUri);
individualsMap.put(subUri,new IndividualJena(ind, (WebappDaoFactoryJena) getWebappDaoFactory())); individualsMap.put(subUri,new IndividualJena(ind, getWebappDaoFactory()));
} }
} }
@ -544,7 +544,7 @@ public class IndividualDaoJena extends JenaBaseDao implements IndividualDao {
String subUri = ((Resource)sub).getURI(); String subUri = ((Resource)sub).getURI();
if( ! individualsMap.containsKey(subUri)){ if( ! individualsMap.containsKey(subUri)){
com.hp.hpl.jena.ontology.Individual ind = getOntModel().getIndividual(subUri); com.hp.hpl.jena.ontology.Individual ind = getOntModel().getIndividual(subUri);
individualsMap.put(subUri,new IndividualJena(ind, (WebappDaoFactoryJena) getWebappDaoFactory())); individualsMap.put(subUri,new IndividualJena(ind, getWebappDaoFactory()));
} }
} }
} finally { } finally {
@ -594,7 +594,7 @@ public class IndividualDaoJena extends JenaBaseDao implements IndividualDao {
continue; continue;
} }
com.hp.hpl.jena.ontology.Individual ind = getOntModel().getIndividual(st.getURI()); com.hp.hpl.jena.ontology.Individual ind = getOntModel().getIndividual(st.getURI());
inds.add(new IndividualJena(ind, (WebappDaoFactoryJena) getWebappDaoFactory())); inds.add(new IndividualJena(ind, getWebappDaoFactory()));
} }
} finally { } finally {
if( stmts != null ) stmts.close(); if( stmts != null ) stmts.close();

View file

@ -106,7 +106,7 @@ public class IndividualDaoSDB extends IndividualDaoJena {
: ResourceFactory.createResource(vclassURI); : ResourceFactory.createResource(vclassURI);
if (theClass.isAnon() && theClass.canAs(UnionClass.class)) { if (theClass.isAnon() && theClass.canAs(UnionClass.class)) {
UnionClass u = (UnionClass) theClass.as(UnionClass.class); UnionClass u = theClass.as(UnionClass.class);
for (OntClass operand : u.listOperands().toList()) { for (OntClass operand : u.listOperands().toList()) {
VClass vc = new VClassJena(operand, getWebappDaoFactory()); VClass vc = new VClassJena(operand, getWebappDaoFactory());
ents.addAll(getIndividualsByVClass(vc)); ents.addAll(getIndividualsByVClass(vc));
@ -523,7 +523,7 @@ public class IndividualDaoSDB extends IndividualDaoJena {
try { try {
ResultSet results = qe.execSelect(); ResultSet results = qe.execSelect();
while (results.hasNext()) { while (results.hasNext()) {
QuerySolution qs = (QuerySolution) results.next(); QuerySolution qs = results.next();
Resource res = (Resource) qs.get("?ent"); Resource res = (Resource) qs.get("?ent");
if (res.getURI() != null) { if (res.getURI() != null) {
individualURIs.add(res.getURI()); individualURIs.add(res.getURI());

View file

@ -254,8 +254,8 @@ public class IndividualJena extends IndividualImpl implements Individual {
if (!s.getSubject().canAs(OntResource.class) || !s.getObject().canAs(OntResource.class)) { if (!s.getSubject().canAs(OntResource.class) || !s.getObject().canAs(OntResource.class)) {
continue; continue;
} }
Individual subj = new IndividualJena((OntResource) s.getSubject().as(OntResource.class), webappDaoFactory); Individual subj = new IndividualJena(s.getSubject().as(OntResource.class), webappDaoFactory);
Individual obj = new IndividualJena((OntResource) s.getObject().as(OntResource.class), webappDaoFactory); Individual obj = new IndividualJena(s.getObject().as(OntResource.class), webappDaoFactory);
ObjectProperty op = webappDaoFactory.getObjectPropertyDao().getObjectPropertyByURI(s.getPredicate().getURI()); ObjectProperty op = webappDaoFactory.getObjectPropertyDao().getObjectPropertyByURI(s.getPredicate().getURI());
if (subj != null && obj != null && op != null) { if (subj != null && obj != null && op != null) {
ObjectPropertyStatement ops = new ObjectPropertyStatementImpl(); ObjectPropertyStatement ops = new ObjectPropertyStatementImpl();
@ -287,7 +287,7 @@ public class IndividualJena extends IndividualImpl implements Individual {
RDFNode value = values.nextNode(); RDFNode value = values.nextNode();
if (value.canAs(OntResource.class)) { if (value.canAs(OntResource.class)) {
relatedIndividuals.add( relatedIndividuals.add(
new IndividualJena((OntResource) value.as(OntResource.class), webappDaoFactory) ); new IndividualJena(value.as(OntResource.class), webappDaoFactory) );
} }
} }
} finally { } finally {
@ -305,7 +305,7 @@ public class IndividualJena extends IndividualImpl implements Individual {
try { try {
RDFNode value = ind.getPropertyValue(ind.getModel().getProperty(propertyURI)); RDFNode value = ind.getPropertyValue(ind.getModel().getProperty(propertyURI));
if (value != null && value.canAs(OntResource.class)) { if (value != null && value.canAs(OntResource.class)) {
return new IndividualJena((OntResource) value.as(OntResource.class), webappDaoFactory); return new IndividualJena(value.as(OntResource.class), webappDaoFactory);
} else { } else {
return null; return null;
} }
@ -582,11 +582,11 @@ public class IndividualJena extends IndividualImpl implements Individual {
int rv = 0; int rv = 0;
try { try {
if( val1 instanceof String ) if( val1 instanceof String )
rv = collator.compare( ((String)val1) , ((String)val2) ); rv = collator.compare(val1 , val2);
//rv = ((String)val1).compareTo((String)val2); //rv = ((String)val1).compareTo((String)val2);
else if( val1 instanceof Date ) { else if( val1 instanceof Date ) {
DateTime dt1 = new DateTime((Date)val1); DateTime dt1 = new DateTime(val1);
DateTime dt2 = new DateTime((Date)val2); DateTime dt2 = new DateTime(val2);
rv = dt1.compareTo(dt2); rv = dt1.compareTo(dt2);
} }
else else

View file

@ -478,8 +478,7 @@ public class IndividualSDB extends IndividualImpl implements Individual {
Individual subj = null; Individual subj = null;
try { try {
subj = new IndividualSDB( subj = new IndividualSDB(
((OntResource) s.getSubject().as(OntResource.class)) s.getSubject().as(OntResource.class).getURI(),
.getURI(),
this.dwf, datasetMode, webappDaoFactory); this.dwf, datasetMode, webappDaoFactory);
} catch (IndividualNotFoundException e) { } catch (IndividualNotFoundException e) {
// leave null subject // leave null subject
@ -487,8 +486,7 @@ public class IndividualSDB extends IndividualImpl implements Individual {
Individual obj = null; Individual obj = null;
try { try {
obj = new IndividualSDB( obj = new IndividualSDB(
((OntResource) s.getObject().as(OntResource.class)) s.getObject().as(OntResource.class).getURI(),
.getURI(),
this.dwf, datasetMode, webappDaoFactory); this.dwf, datasetMode, webappDaoFactory);
} catch (IndividualNotFoundException e) { } catch (IndividualNotFoundException e) {
// leave null object // leave null object
@ -548,8 +546,7 @@ public class IndividualSDB extends IndividualImpl implements Individual {
if (value.canAs(OntResource.class)) { if (value.canAs(OntResource.class)) {
relatedIndividuals.add( relatedIndividuals.add(
new IndividualSDB( new IndividualSDB(
((OntResource) value.as(OntResource.class)) value.as(OntResource.class).getURI(),
.getURI(),
this.dwf, this.dwf,
datasetMode, datasetMode,
webappDaoFactory) ); webappDaoFactory) );
@ -588,7 +585,7 @@ public class IndividualSDB extends IndividualImpl implements Individual {
if (value != null && value.canAs(OntResource.class)) { if (value != null && value.canAs(OntResource.class)) {
try { try {
return new IndividualSDB( return new IndividualSDB(
((OntResource) value.as(OntResource.class)).getURI(), value.as(OntResource.class).getURI(),
dwf, datasetMode, webappDaoFactory); dwf, datasetMode, webappDaoFactory);
} catch (IndividualNotFoundException e) { } catch (IndividualNotFoundException e) {
return null; return null;
@ -1045,8 +1042,8 @@ public class IndividualSDB extends IndividualImpl implements Individual {
rv = collator.compare( ((String)val1) , ((String)val2) ); rv = collator.compare( ((String)val1) , ((String)val2) );
//rv = ((String)val1).compareTo((String)val2); //rv = ((String)val1).compareTo((String)val2);
else if( val1 instanceof Date ) { else if( val1 instanceof Date ) {
DateTime dt1 = new DateTime((Date)val1); DateTime dt1 = new DateTime(val1);
DateTime dt2 = new DateTime((Date)val2); DateTime dt2 = new DateTime(val2);
rv = dt1.compareTo(dt2); rv = dt1.compareTo(dt2);
} }
else else

View file

@ -12,7 +12,6 @@ import java.util.Date;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set; import java.util.Set;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -23,7 +22,6 @@ import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.iri.IRI; import com.hp.hpl.jena.iri.IRI;
import com.hp.hpl.jena.iri.IRIFactory; import com.hp.hpl.jena.iri.IRIFactory;
import com.hp.hpl.jena.iri.Violation;
import com.hp.hpl.jena.ontology.DatatypeProperty; import com.hp.hpl.jena.ontology.DatatypeProperty;
import com.hp.hpl.jena.ontology.ObjectProperty; import com.hp.hpl.jena.ontology.ObjectProperty;
import com.hp.hpl.jena.ontology.OntClass; import com.hp.hpl.jena.ontology.OntClass;
@ -56,10 +54,6 @@ public class JenaBaseDao extends JenaBaseDaoCon {
public static final boolean KEEP_ONLY_IF_TRUE = true; //used for updatePropertyBooleanValue() public static final boolean KEEP_ONLY_IF_TRUE = true; //used for updatePropertyBooleanValue()
public static final boolean KEEP_ONLY_IF_FALSE = false; //used for updatePropertyBooleanValue() public static final boolean KEEP_ONLY_IF_FALSE = false; //used for updatePropertyBooleanValue()
public static final String JENA_ONT_MODEL_ATTRIBUTE_NAME = "jenaOntModel";
public static final String ASSERTIONS_ONT_MODEL_ATTRIBUTE_NAME = "baseOntModel";
public static final String INFERENCE_ONT_MODEL_ATTRIBUTE_NAME = "inferenceOntModel";
protected static final Log log = LogFactory.getLog(JenaBaseDao.class.getName()); protected static final Log log = LogFactory.getLog(JenaBaseDao.class.getName());
/* ******************* static constants ****************** */ /* ******************* static constants ****************** */
@ -749,10 +743,10 @@ public class JenaBaseDao extends JenaBaseDaoCon {
if (label != null && label.length() > 0) { if (label != null && label.length() > 0) {
String existingValue = ontRes.getLabel((String) getDefaultLanguage()); String existingValue = ontRes.getLabel(getDefaultLanguage());
if (existingValue == null || !existingValue.equals(label)) { if (existingValue == null || !existingValue.equals(label)) {
ontRes.setLabel(label, (String) getDefaultLanguage()); ontRes.setLabel(label, getDefaultLanguage());
} }
} else { } else {
ontRes.removeAll(RDFS.label); ontRes.removeAll(RDFS.label);
@ -910,7 +904,7 @@ public class JenaBaseDao extends JenaBaseDaoCon {
if (iri.hasViolation(false) ) { if (iri.hasViolation(false) ) {
String errorStr = ("Bad URI: "+ uri + String errorStr = ("Bad URI: "+ uri +
"\nOnly well-formed absolute URIrefs can be included in RDF/XML output: " "\nOnly well-formed absolute URIrefs can be included in RDF/XML output: "
+ ((Violation)iri.violations(false).next()).getShortMessage()); + (iri.violations(false).next()).getShortMessage());
return errorStr; return errorStr;
} else { } else {
return null; return null;
@ -933,7 +927,7 @@ public class JenaBaseDao extends JenaBaseDaoCon {
String idStr = vitroURIStr.split("#")[1]; String idStr = vitroURIStr.split("#")[1];
RDFNode rdfNode = ontModel.getRDFNode(Node.createAnon(AnonId.create(idStr))); RDFNode rdfNode = ontModel.getRDFNode(Node.createAnon(AnonId.create(idStr)));
if ( (rdfNode != null) && (rdfNode.canAs(OntClass.class)) ) { if ( (rdfNode != null) && (rdfNode.canAs(OntClass.class)) ) {
cls = (OntClass) rdfNode.as(OntClass.class); cls = rdfNode.as(OntClass.class);
} }
} else { } else {
try { try {
@ -1006,7 +1000,7 @@ public class JenaBaseDao extends JenaBaseDaoCon {
StmtIterator stmtIt = getOntModel().listStatements((Resource)null, prop, value); StmtIterator stmtIt = getOntModel().listStatements((Resource)null, prop, value);
while (stmtIt.hasNext()) { while (stmtIt.hasNext()) {
Statement stmt = stmtIt.nextStatement(); Statement stmt = stmtIt.nextStatement();
possibleSubjectSet.add((Resource)stmt.getSubject()); possibleSubjectSet.add(stmt.getSubject());
} }
Iterator<Resource> possibleSubjectIt = possibleSubjectSet.iterator(); Iterator<Resource> possibleSubjectIt = possibleSubjectSet.iterator();
@ -1016,7 +1010,7 @@ public class JenaBaseDao extends JenaBaseDaoCon {
boolean hasAlternatePath = false; boolean hasAlternatePath = false;
while (stmtIt.hasNext()) { while (stmtIt.hasNext()) {
Statement stmt = stmtIt.nextStatement(); Statement stmt = stmtIt.nextStatement();
if (stmt.getObject().isResource() && possibleSubjectSet.contains((Resource)stmt.getObject())) { if (stmt.getObject().isResource() && possibleSubjectSet.contains(stmt.getObject())) {
hasAlternatePath = true; hasAlternatePath = true;
break; break;
} }

View file

@ -8,7 +8,6 @@ import java.util.HashSet;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.openjena.riot.RiotException;
import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelChangedListener; import com.hp.hpl.jena.rdf.model.ModelChangedListener;
@ -17,7 +16,6 @@ import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.rdf.model.StmtIterator;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeListener; import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeListener;
import edu.cornell.mannlib.vitro.webapp.servlet.setup.JenaDataSourceSetupBase;
import edu.cornell.mannlib.vitro.webapp.servlet.setup.SimpleReasonerSetup; import edu.cornell.mannlib.vitro.webapp.servlet.setup.SimpleReasonerSetup;
/** /**

View file

@ -95,7 +95,7 @@ public class JenaModelUtils {
.getRootClasses(); .getRootClasses();
for (Iterator<VClass> rootClassIt = rootClasses.iterator(); for (Iterator<VClass> rootClassIt = rootClasses.iterator();
rootClassIt.hasNext(); ) { rootClassIt.hasNext(); ) {
VClass rootClass = (VClass) rootClassIt.next(); VClass rootClass = rootClassIt.next();
Individual classGroup = modelForClassgroups.createIndividual( Individual classGroup = modelForClassgroups.createIndividual(
wadf.getDefaultNamespace() + "vitroClassGroup" + wadf.getDefaultNamespace() + "vitroClassGroup" +
rootClass.getLocalName(), classGroupClass); rootClass.getLocalName(), classGroupClass);
@ -108,7 +108,7 @@ public class JenaModelUtils {
for (Iterator<String> childIt = myWebappDaoFactory.getVClassDao() for (Iterator<String> childIt = myWebappDaoFactory.getVClassDao()
.getAllSubClassURIs(rootClass.getURI()).iterator(); .getAllSubClassURIs(rootClass.getURI()).iterator();
childIt.hasNext(); ) { childIt.hasNext(); ) {
String childURI = (String) childIt.next(); String childURI = childIt.next();
Resource childClass = modelForClassgroupAnnotations Resource childClass = modelForClassgroupAnnotations
.getResource(childURI); .getResource(childURI);
if (!modelForClassgroupAnnotations.contains( if (!modelForClassgroupAnnotations.contains(

View file

@ -7,84 +7,14 @@ import javax.servlet.ServletContext;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.ModelChangedListener; import com.hp.hpl.jena.rdf.model.ModelChangedListener;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFServiceException; import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFServiceException;
import edu.cornell.mannlib.vitro.webapp.rdfservice.impl.RDFServiceUtils; import edu.cornell.mannlib.vitro.webapp.rdfservice.impl.RDFServiceUtils;
public class ModelContext { public class ModelContext {
private static final Log log = LogFactory.getLog(ModelContext.class); private static final Log log = LogFactory.getLog(ModelContext.class);
private static final String ONT_MODEL_SELECTOR = "ontModelSelector";
private static final String UNION_ONT_MODEL_SELECTOR = "unionOntModelSelector";
private static final String BASE_ONT_MODEL_SELECTOR = "baseOntModelSelector";
private static final String INFERENCE_ONT_MODEL_SELECTOR = "inferenceOntModelSelector";
private static final String JENA_ONT_MODEL = "jenaOntModel";
private static final String BASE_ONT_MODEL = "baseOntModel";
private static final String INFERENCE_ONT_MODEL = "inferenceOntModel";
public ModelContext() {}
public static OntModelSelector getOntModelSelector(ServletContext ctx) {
return (OntModelSelector) ctx.getAttribute(ONT_MODEL_SELECTOR);
}
public static void setOntModelSelector(OntModelSelector oms, ServletContext ctx) {
ctx.setAttribute(ONT_MODEL_SELECTOR, oms);
}
public static OntModelSelector getUnionOntModelSelector(ServletContext ctx) {
return (OntModelSelector) ctx.getAttribute(UNION_ONT_MODEL_SELECTOR);
}
public static void setUnionOntModelSelector(OntModelSelector oms, ServletContext ctx) {
ctx.setAttribute(UNION_ONT_MODEL_SELECTOR, oms);
}
public static OntModelSelector getBaseOntModelSelector(ServletContext ctx) {
return (OntModelSelector) ctx.getAttribute(BASE_ONT_MODEL_SELECTOR);
}
public static void setBaseOntModelSelector(OntModelSelector oms, ServletContext ctx) {
ctx.setAttribute(BASE_ONT_MODEL_SELECTOR, oms);
}
public static OntModelSelector getInferenceOntModelSelector(ServletContext ctx) {
return (OntModelSelector) ctx.getAttribute(INFERENCE_ONT_MODEL_SELECTOR);
}
public static void setInferenceOntModelSelector(OntModelSelector oms, ServletContext ctx) {
ctx.setAttribute(INFERENCE_ONT_MODEL_SELECTOR, oms);
}
public static OntModel getJenaOntModel(ServletContext ctx) {
return (OntModel) ctx.getAttribute(JENA_ONT_MODEL);
}
public static void setJenaOntModel(OntModel ontModel, ServletContext ctx) {
ctx.setAttribute(JENA_ONT_MODEL, ontModel);
}
public static OntModel getBaseOntModel(ServletContext ctx) {
return (OntModel) ctx.getAttribute(BASE_ONT_MODEL);
}
public static void setBaseOntModel(OntModel ontModel, ServletContext ctx) {
ctx.setAttribute(BASE_ONT_MODEL, ontModel);
}
public static OntModel getInferenceOntModel(ServletContext ctx) {
return (OntModel) ctx.getAttribute(INFERENCE_ONT_MODEL);
}
public static void setInferenceOntModel(OntModel ontModel, ServletContext ctx) {
ctx.setAttribute(INFERENCE_ONT_MODEL, ontModel);
}
/** /**
* Register a listener to the models needed to get changes to: * Register a listener to the models needed to get changes to:
* Basic abox statemetns: * Basic abox statemetns:
@ -113,10 +43,4 @@ public class ModelContext {
} }
public static OntModel getDisplayModel(ServletContext ctx){
return(OntModel) ctx.getAttribute( DisplayVocabulary.DISPLAY_ONT_MODEL );
}
public static void setDisplayModel(OntModel ontModel, ServletContext ctx){
ctx.setAttribute(DisplayVocabulary.DISPLAY_ONT_MODEL,ontModel);
}
} }

View file

@ -27,6 +27,9 @@ import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution; import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Resource;
@ -38,6 +41,7 @@ import com.hp.hpl.jena.util.iterator.ClosableIterator;
import com.hp.hpl.jena.vocabulary.OWL; import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS; import com.hp.hpl.jena.vocabulary.RDFS;
import com.hp.hpl.jena.sdb.util.Pair;
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean; import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean;
import edu.cornell.mannlib.vitro.webapp.beans.Individual; import edu.cornell.mannlib.vitro.webapp.beans.Individual;
@ -90,7 +94,7 @@ public class ObjectPropertyDaoJena extends PropertyDaoJena implements ObjectProp
p.setNamespace(op.getNameSpace()); p.setNamespace(op.getNameSpace());
p.setLocalName(op.getLocalName()); p.setLocalName(op.getLocalName());
OntologyDao oDao=getWebappDaoFactory().getOntologyDao(); OntologyDao oDao=getWebappDaoFactory().getOntologyDao();
Ontology o = (Ontology)oDao.getOntologyByURI(p.getNamespace()); Ontology o = oDao.getOntologyByURI(p.getNamespace());
if (o==null) { if (o==null) {
if (!VitroVocabulary.vitroURI.equals(p.getNamespace())) { if (!VitroVocabulary.vitroURI.equals(p.getNamespace())) {
log.debug("propertyFromOntProperty(): no ontology object found for the namespace "+p.getNamespace()); log.debug("propertyFromOntProperty(): no ontology object found for the namespace "+p.getNamespace());
@ -178,7 +182,7 @@ public class ObjectPropertyDaoJena extends PropertyDaoJena implements ObjectProp
Statement stmt = it.nextStatement(); Statement stmt = it.nextStatement();
RDFNode obj; RDFNode obj;
if( stmt != null && (obj = stmt.getObject()) != null && obj.isURIResource() ){ if( stmt != null && (obj = stmt.getObject()) != null && obj.isURIResource() ){
Resource res = (Resource)obj.as(Resource.class); Resource res = obj.as(Resource.class);
if( res != null && res.getURI() != null ){ if( res != null && res.getURI() != null ){
BaseResourceBean.RoleLevel roleFromModel = BaseResourceBean.RoleLevel.getRoleByUri(res.getURI()); BaseResourceBean.RoleLevel roleFromModel = BaseResourceBean.RoleLevel.getRoleByUri(res.getURI());
if( roleFromModel != null && if( roleFromModel != null &&
@ -197,7 +201,7 @@ public class ObjectPropertyDaoJena extends PropertyDaoJena implements ObjectProp
Statement stmt = it.nextStatement(); Statement stmt = it.nextStatement();
RDFNode obj; RDFNode obj;
if( stmt != null && (obj = stmt.getObject()) != null && obj.isURIResource() ){ if( stmt != null && (obj = stmt.getObject()) != null && obj.isURIResource() ){
Resource res = (Resource)obj.as(Resource.class); Resource res = obj.as(Resource.class);
if( res != null && res.getURI() != null ){ if( res != null && res.getURI() != null ){
BaseResourceBean.RoleLevel roleFromModel = BaseResourceBean.RoleLevel.getRoleByUri(res.getURI()); BaseResourceBean.RoleLevel roleFromModel = BaseResourceBean.RoleLevel.getRoleByUri(res.getURI());
if( roleFromModel != null && if( roleFromModel != null &&
@ -229,12 +233,6 @@ public class ObjectPropertyDaoJena extends PropertyDaoJena implements ObjectProp
} }
return p; return p;
} }
private String stripItalics(String in) {
String out = in.replaceAll("\\<i\\>","");
out = out.replaceAll("\\<\\/i\\>","");
return out;
}
public List getAllObjectProperties() { public List getAllObjectProperties() {
getOntModel().enterCriticalSection(Lock.READ); getOntModel().enterCriticalSection(Lock.READ);
@ -257,7 +255,7 @@ public class ObjectPropertyDaoJena extends PropertyDaoJena implements ObjectProp
while (opIt.hasNext()) { while (opIt.hasNext()) {
Resource res = (Resource) opIt.next(); Resource res = (Resource) opIt.next();
if ( (res.canAs(OntProperty.class)) && (!NONUSER_NAMESPACES.contains(res.getNameSpace())) ) { if ( (res.canAs(OntProperty.class)) && (!NONUSER_NAMESPACES.contains(res.getNameSpace())) ) {
props.add(propertyFromOntProperty((OntProperty)res.as(OntProperty.class))); props.add(propertyFromOntProperty(res.as(OntProperty.class)));
} }
} }
} finally { } finally {
@ -285,6 +283,64 @@ public class ObjectPropertyDaoJena extends PropertyDaoJena implements ObjectProp
getOntModel().leaveCriticalSection(); getOntModel().leaveCriticalSection();
} }
} }
public ObjectProperty getObjectPropertyByURIAndRangeURI(String propertyURI, String rangeURI) {
ObjectProperty op = getObjectPropertyByURI(propertyURI);
if (op == null) {
return op;
}
op.setRangeVClassURI(rangeURI);
String propQuery = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n" +
"PREFIX config: <http://vitro.mannlib.cornell.edu/ns/vitro/ApplicationConfiguration#> \n" +
"PREFIX vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> \n" +
"SELECT ?range ?label ?group ?customForm ?displayLevel ?updateLevel WHERE { \n" +
" ?context config:configContextFor <" + propertyURI + "> . \n" +
" ?context config:qualifiedBy <" + rangeURI + "> . \n" +
" ?context config:hasConfiguration ?configuration . \n" +
" OPTIONAL { ?configuration config:propertyGroup ?group } \n" +
" OPTIONAL { ?configuration config:displayName ?label } \n" +
" OPTIONAL { ?configuration vitro:customEntryFormAnnot ?customForm } \n" +
" OPTIONAL { ?configuration vitro:hiddenFromDisplayBelowRoleLevelAnnot ?displayLevel } \n" +
" OPTIONAL { ?configuration vitro:prohibitedFromUpdateBelowRoleLevelAnnot ?updateLevel } \n" +
"}";
Query q = QueryFactory.create(propQuery);
QueryExecution qe = QueryExecutionFactory.create(q, getOntModelSelector().getDisplayModel());
try {
ResultSet rs = qe.execSelect();
if (rs.hasNext()) {
QuerySolution qsoln = rs.nextSolution();
Resource groupRes = qsoln.getResource("group");
if (groupRes != null) {
op.setGroupURI(groupRes.getURI());
}
Resource displayLevelRes = qsoln.getResource("displayLevel");
if (displayLevelRes != null) {
op.setHiddenFromDisplayBelowRoleLevel(
BaseResourceBean.RoleLevel.getRoleByUri(
displayLevelRes.getURI()));
}
Resource updateLevelRes = qsoln.getResource("updateLevel");
if (updateLevelRes != null) {
op.setProhibitedFromUpdateBelowRoleLevel(
BaseResourceBean.RoleLevel.getRoleByUri(
updateLevelRes.getURI()));
}
Literal labelLit = qsoln.getLiteral("label");
if (labelLit != null) {
op.setDomainPublic(labelLit.getLexicalForm());
}
Literal customFormLit = qsoln.getLiteral("customForm");
if (customFormLit != null) {
op.setCustomEntryForm(customFormLit.getLexicalForm());
}
}
} finally {
qe.close();
}
return op;
}
public List<ObjectProperty> getObjectPropertiesForObjectPropertyStatements(List objPropertyStmts) { public List<ObjectProperty> getObjectPropertiesForObjectPropertyStatements(List objPropertyStmts) {
if( objPropertyStmts == null || objPropertyStmts.size() < 1) return new ArrayList(); if( objPropertyStmts == null || objPropertyStmts.size() < 1) return new ArrayList();
@ -296,7 +352,7 @@ public class ObjectPropertyDaoJena extends PropertyDaoJena implements ObjectProp
while(it.hasNext()){ while(it.hasNext()){
ObjectPropertyStatement objPropertyStmt = (ObjectPropertyStatement)it.next(); ObjectPropertyStatement objPropertyStmt = (ObjectPropertyStatement)it.next();
if (hash.containsKey(objPropertyStmt.getPropertyURI())) { if (hash.containsKey(objPropertyStmt.getPropertyURI())) {
ObjectProperty p = (ObjectProperty) hash.get(objPropertyStmt.getPropertyURI()); ObjectProperty p = hash.get(objPropertyStmt.getPropertyURI());
p.addObjectPropertyStatement(objPropertyStmt); p.addObjectPropertyStatement(objPropertyStmt);
} else { } else {
OntProperty op = getOntModel().getOntProperty(objPropertyStmt.getPropertyURI()); OntProperty op = getOntModel().getOntProperty(objPropertyStmt.getPropertyURI());
@ -601,7 +657,7 @@ public class ObjectPropertyDaoJena extends PropertyDaoJena implements ObjectProp
while(restIt.hasNext()) { while(restIt.hasNext()) {
Resource restRes = restIt.next(); Resource restRes = restIt.next();
if (restRes.canAs(OntResource.class)) { if (restRes.canAs(OntResource.class)) {
OntResource restOntRes = (OntResource) restRes.as(OntResource.class); OntResource restOntRes = restRes.as(OntResource.class);
smartRemove(restOntRes, ontModel); smartRemove(restOntRes, ontModel);
} }
} }
@ -625,7 +681,7 @@ public class ObjectPropertyDaoJena extends PropertyDaoJena implements ObjectProp
while(restIt.hasNext()) { while(restIt.hasNext()) {
Resource restRes = restIt.next(); Resource restRes = restIt.next();
if (restRes.canAs(OntResource.class)) { if (restRes.canAs(OntResource.class)) {
OntResource restOntRes = (OntResource) restRes.as(OntResource.class); OntResource restOntRes = restRes.as(OntResource.class);
smartRemove(restOntRes, ontModel); smartRemove(restOntRes, ontModel);
} }
} }
@ -658,7 +714,7 @@ public class ObjectPropertyDaoJena extends PropertyDaoJena implements ObjectProp
while (propIt.hasNext()) { while (propIt.hasNext()) {
Resource res = (Resource) propIt.next(); Resource res = (Resource) propIt.next();
if (res.canAs(OntProperty.class)) { if (res.canAs(OntProperty.class)) {
com.hp.hpl.jena.ontology.OntProperty op = (com.hp.hpl.jena.ontology.OntProperty) res.as(OntProperty.class); com.hp.hpl.jena.ontology.OntProperty op = res.as(OntProperty.class);
boolean isRoot = false; boolean isRoot = false;
Iterator parentIt = op.listSuperProperties(); Iterator parentIt = op.listSuperProperties();
if (parentIt != null) { if (parentIt != null) {
@ -798,7 +854,7 @@ public class ObjectPropertyDaoJena extends PropertyDaoJena implements ObjectProp
PREFIXES + "\n" + PREFIXES + "\n" +
"SELECT DISTINCT ?property WHERE { \n" + "SELECT DISTINCT ?property WHERE { \n" +
" ?subject ?property ?object . \n" + " ?subject ?property ?object . \n" +
" ?property a owl:ObjectProperty . \n" + // " ?property a owl:ObjectProperty . \n" +
" FILTER ( \n" + " FILTER ( \n" +
" isURI(?object) && \n" + " isURI(?object) && \n" +
PROPERTY_FILTERS + "\n" + PROPERTY_FILTERS + "\n" +
@ -844,11 +900,19 @@ public class ObjectPropertyDaoJena extends PropertyDaoJena implements ObjectProp
} }
protected static final String LIST_VIEW_CONFIG_FILE_QUERY_STRING = protected static final String LIST_VIEW_CONFIG_FILE_QUERY_STRING =
"PREFIX display: <http://vitro.mannlib.cornell.edu/ontologies/display/1.1#>" + "PREFIX display: <http://vitro.mannlib.cornell.edu/ontologies/display/1.1#> \n" +
"SELECT ?property ?filename WHERE { \n" + "PREFIX config: <http://vitro.mannlib.cornell.edu/ns/vitro/ApplicationConfiguration#> \n" +
" ?property display:listViewConfigFile ?filename . \n" + "SELECT ?property ?range ?filename WHERE { \n" +
" { ?property display:listViewConfigFile ?filename \n" +
" } UNION { \n" +
" ?lv config:listViewConfigFile ?filename . \n " +
" ?configuration config:hasListView ?lv . " +
" ?context config:hasConfiguration ?configuration . \n" +
" ?context config:configContextFor ?property . \n" +
" ?context config:qualifiedBy ?range . \n" +
" } \n" +
"}"; "}";
protected static Query listViewConfigFileQuery = null; protected static Query listViewConfigFileQuery = null;
static { static {
try { try {
@ -859,12 +923,16 @@ public class ObjectPropertyDaoJena extends PropertyDaoJena implements ObjectProp
} }
} }
Map<ObjectProperty, String> customListViewConfigFileMap = null; //TODO private void addPropertyClassCombinationsToListViewMap(HashMap)
// Map key is pair of object property and range class URI
// If range is unspecified, OWL.Thing.getURI() is used in the key.
Map<Pair<ObjectProperty, String>, String> customListViewConfigFileMap = null;
@Override @Override
public String getCustomListViewConfigFileName(ObjectProperty op) { public String getCustomListViewConfigFileName(ObjectProperty op) {
if (customListViewConfigFileMap == null) { if (customListViewConfigFileMap == null) {
customListViewConfigFileMap = new HashMap<ObjectProperty, String>(); customListViewConfigFileMap = new HashMap<Pair<ObjectProperty, String>, String>();
OntModel displayModel = getOntModelSelector().getDisplayModel(); OntModel displayModel = getOntModelSelector().getDisplayModel();
//Get all property to list view config file mappings in the system //Get all property to list view config file mappings in the system
QueryExecution qexec = QueryExecutionFactory.create(listViewConfigFileQuery, displayModel); QueryExecution qexec = QueryExecutionFactory.create(listViewConfigFileQuery, displayModel);
@ -873,6 +941,10 @@ public class ObjectPropertyDaoJena extends PropertyDaoJena implements ObjectProp
while (results.hasNext()) { while (results.hasNext()) {
QuerySolution soln = results.next(); QuerySolution soln = results.next();
String propertyUri = soln.getResource("property").getURI(); String propertyUri = soln.getResource("property").getURI();
RDFNode rangeNode = soln.get("range");
String rangeUri = (rangeNode != null)
? ((Resource) rangeNode).getURI()
: OWL.Thing.getURI();
ObjectProperty prop = getObjectPropertyByURI(propertyUri); ObjectProperty prop = getObjectPropertyByURI(propertyUri);
if (prop == null) { if (prop == null) {
//This is a warning only if this property is the one for which we're searching //This is a warning only if this property is the one for which we're searching
@ -883,12 +955,18 @@ public class ObjectPropertyDaoJena extends PropertyDaoJena implements ObjectProp
} }
} else { } else {
String filename = soln.getLiteral("filename").getLexicalForm(); String filename = soln.getLiteral("filename").getLexicalForm();
customListViewConfigFileMap.put(prop, filename); customListViewConfigFileMap.put(new Pair<ObjectProperty, String>(prop, rangeUri), filename);
} }
} }
qexec.close(); qexec.close();
} }
return customListViewConfigFileMap.get(op);
String customListViewConfigFileName = customListViewConfigFileMap.get(new Pair<ObjectProperty, String>(op, op.getRangeVClassURI()));
if (customListViewConfigFileName == null) {
customListViewConfigFileName = customListViewConfigFileMap.get(new Pair<ObjectProperty, String>(op, OWL.Thing.getURI()));
}
return customListViewConfigFileName;
} }
} }

View file

@ -99,7 +99,7 @@ public class ObjectPropertyStatementDaoJena extends JenaBaseDao implements Objec
ClosableIterator<Statement> propIt = ind.listProperties(); ClosableIterator<Statement> propIt = ind.listProperties();
try { try {
while (propIt.hasNext()) { while (propIt.hasNext()) {
Statement st = (Statement) propIt.next(); Statement st = propIt.next();
if (st.getObject().isResource() && !(NONUSER_NAMESPACES.contains(st.getPredicate().getNameSpace()))) { if (st.getObject().isResource() && !(NONUSER_NAMESPACES.contains(st.getPredicate().getNameSpace()))) {
try { try {
@ -173,7 +173,7 @@ public class ObjectPropertyStatementDaoJena extends JenaBaseDao implements Objec
try { try {
int count = 0; int count = 0;
while ( (opsIt.hasNext()) && ((endIndex<0) || (count<endIndex)) ) { while ( (opsIt.hasNext()) && ((endIndex<0) || (count<endIndex)) ) {
Statement stmt = (Statement) opsIt.next(); Statement stmt = opsIt.next();
if (stmt.getObject().isResource()) { if (stmt.getObject().isResource()) {
++count; ++count;
if (startIndex<0 || startIndex<=count) { if (startIndex<0 || startIndex<=count) {
@ -271,6 +271,7 @@ public class ObjectPropertyStatementDaoJena extends JenaBaseDao implements Objec
String subjectUri, String subjectUri,
String propertyUri, String propertyUri,
String objectKey, String objectKey,
String rangeUri,
String queryString, String queryString,
Set<String> constructQueryStrings, Set<String> constructQueryStrings,
String sortDirection) { String sortDirection) {
@ -296,6 +297,9 @@ public class ObjectPropertyStatementDaoJena extends JenaBaseDao implements Objec
QuerySolutionMap initialBindings = new QuerySolutionMap(); QuerySolutionMap initialBindings = new QuerySolutionMap();
initialBindings.add("subject", ResourceFactory.createResource(subjectUri)); initialBindings.add("subject", ResourceFactory.createResource(subjectUri));
initialBindings.add("property", ResourceFactory.createResource(propertyUri)); initialBindings.add("property", ResourceFactory.createResource(propertyUri));
if (rangeUri != null) {
initialBindings.add("objectType", ResourceFactory.createResource(rangeUri));
}
// Run the SPARQL query to get the properties // Run the SPARQL query to get the properties
List<Map<String, String>> list = new ArrayList<Map<String, String>>(); List<Map<String, String>> list = new ArrayList<Map<String, String>>();

View file

@ -102,7 +102,7 @@ public class ObjectPropertyStatementDaoSDB extends
ClosableIterator<Statement> propIt = ind.listProperties(); ClosableIterator<Statement> propIt = ind.listProperties();
try { try {
while (propIt.hasNext()) { while (propIt.hasNext()) {
Statement st = (Statement) propIt.next(); Statement st = propIt.next();
if (st.getObject().isResource() && !(NONUSER_NAMESPACES.contains(st.getPredicate().getNameSpace()))) { if (st.getObject().isResource() && !(NONUSER_NAMESPACES.contains(st.getPredicate().getNameSpace()))) {
try { try {
ObjectPropertyStatement objPropertyStmt = new ObjectPropertyStatementImpl(); ObjectPropertyStatement objPropertyStmt = new ObjectPropertyStatementImpl();

View file

@ -35,13 +35,9 @@ public interface OntModelSelector {
* @return OntModel containing all TBox axioms * @return OntModel containing all TBox axioms
*/ */
public OntModel getTBoxModel(); public OntModel getTBoxModel();
/** /**
* @param ontologyURI * @return OntModel containing all RDF statements in the Display model.
* @return OntModel containing TBox axioms for the specified ontology
*/ */
public OntModel getTBoxModel(String ontologyURI);
public OntModel getDisplayModel(); public OntModel getDisplayModel();
} }

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