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

This commit is contained in:
hudajkhan 2014-04-04 14:45:33 -04:00
commit e1ad4bc21b
134 changed files with 5120 additions and 2986 deletions

View file

@ -497,7 +497,7 @@
target: distribute
================================= -->
<target name="distribute"
depends="revisionInfo, prepareSolr"
depends="revisionInfo, prepareVitroHomeDir, prepareSolr"
description="--> Build the app and create a distribution bundle">
<mkdir dir="${distribution.dir}" />

View file

@ -35,7 +35,6 @@ log4j.rootLogger=INFO, AllAppender
# These classes are too chatty to display INFO messages.
log4j.logger.edu.cornell.mannlib.vitro.webapp.startup.StartupStatus=WARN
log4j.logger.edu.cornell.mannlib.vitro.webapp.controller.freemarker.BrowseController=WARN
log4j.logger.edu.cornell.mannlib.vitro.webapp.dao.jena.pellet.PelletListener=WARN
log4j.logger.edu.cornell.mannlib.vitro.webapp.dao.jena.RDBGraphGenerator=WARN
log4j.logger.edu.cornell.mannlib.vitro.webapp.servlet.setup.UpdateKnowledgeBase=DEBUG

View file

@ -5,6 +5,7 @@
@prefix simplePermission: <java:edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission#> .
@prefix displayByRole: <java:edu.cornell.mannlib.vitro.webapp.auth.permissions.DisplayByRolePermission#> .
@prefix editByRole: <java:edu.cornell.mannlib.vitro.webapp.auth.permissions.EditByRolePermission#> .
@prefix publishByRole: <java:edu.cornell.mannlib.vitro.webapp.auth.permissions.PublishByRolePermission#> .
auth:ADMIN
a auth:PermissionSet ;
@ -18,7 +19,6 @@ auth:ADMIN
auth:hasPermission simplePermission:ManageProxies ;
auth:hasPermission simplePermission:ManageSearchIndex ;
auth:hasPermission simplePermission:ManageUserAccounts ;
auth:hasPermission simplePermission:RebuildVClassGroupCache ;
auth:hasPermission simplePermission:RefreshVisualizationCache ;
auth:hasPermission simplePermission:SeeConfiguration ;
auth:hasPermission simplePermission:SeeStartupStatus ;
@ -35,8 +35,6 @@ auth:ADMIN
# permissions for CURATOR and above.
auth:hasPermission simplePermission:EditOntology ;
auth:hasPermission simplePermission:EditSiteInformation ;
auth:hasPermission simplePermission:ManagePortals ;
auth:hasPermission simplePermission:ManageTabs ;
auth:hasPermission simplePermission:SeeVerbosePropertyInformation ;
auth:hasPermission simplePermission:UseMiscellaneousCuratorPages ;
auth:hasPermission simplePermission:PageViewableCurator ;
@ -46,7 +44,7 @@ auth:ADMIN
auth:hasPermission simplePermission:SeeIndividualEditingPanel ;
auth:hasPermission simplePermission:SeeRevisionInfo ;
auth:hasPermission simplePermission:SeeSiteAdminPage ;
auth:hasPermission simplePermission:UseMiscellaneousEditorPages ;
auth:hasPermission simplePermission:UseIndividualControlPanel ;
auth:hasPermission simplePermission:PageViewableEditor ;
# permissions for ANY logged-in user.
@ -65,6 +63,7 @@ auth:ADMIN
# role-based permissions for ADMIN
auth:hasPermission displayByRole:Admin ;
auth:hasPermission editByRole:Admin ;
auth:hasPermission publishByRole:Admin ;
.
auth:CURATOR
@ -74,8 +73,6 @@ auth:CURATOR
# permissions for CURATOR and above.
auth:hasPermission simplePermission:EditOntology ;
auth:hasPermission simplePermission:EditSiteInformation ;
auth:hasPermission simplePermission:ManagePortals ;
auth:hasPermission simplePermission:ManageTabs ;
auth:hasPermission simplePermission:SeeVerbosePropertyInformation ;
auth:hasPermission simplePermission:UseMiscellaneousCuratorPages ;
auth:hasPermission simplePermission:PageViewableCurator ;
@ -85,7 +82,7 @@ auth:CURATOR
auth:hasPermission simplePermission:SeeIndividualEditingPanel ;
auth:hasPermission simplePermission:SeeRevisionInfo ;
auth:hasPermission simplePermission:SeeSiteAdminPage ;
auth:hasPermission simplePermission:UseMiscellaneousEditorPages ;
auth:hasPermission simplePermission:UseIndividualControlPanel ;
auth:hasPermission simplePermission:PageViewableEditor ;
# permissions for ANY logged-in user.
@ -104,6 +101,7 @@ auth:CURATOR
# role-based permissions for CURATOR
auth:hasPermission displayByRole:Curator ;
auth:hasPermission editByRole:Curator ;
auth:hasPermission publishByRole:Curator ;
.
auth:EDITOR
@ -115,7 +113,7 @@ auth:EDITOR
auth:hasPermission simplePermission:SeeIndividualEditingPanel ;
auth:hasPermission simplePermission:SeeRevisionInfo ;
auth:hasPermission simplePermission:SeeSiteAdminPage ;
auth:hasPermission simplePermission:UseMiscellaneousEditorPages ;
auth:hasPermission simplePermission:UseIndividualControlPanel ;
auth:hasPermission simplePermission:PageViewableEditor ;
# permissions for ANY logged-in user.
@ -134,6 +132,7 @@ auth:EDITOR
# role-based permissions for EDITOR
auth:hasPermission displayByRole:Editor ;
auth:hasPermission editByRole:Editor ;
auth:hasPermission publishByRole:Editor ;
.
auth:SELF_EDITOR
@ -158,6 +157,7 @@ auth:SELF_EDITOR
# For role-based display and editing, SelfEditor is like Public.
# SelfEditor uses its special permissions to edit/display its own values.
auth:hasPermission displayByRole:Public ;
auth:hasPermission publishByRole:Public ;
.
auth:PUBLIC
@ -171,4 +171,5 @@ auth:PUBLIC
# role-based permissions for PUBLIC
auth:hasPermission displayByRole:Public ;
auth:hasPermission publishByRole:Public ;
.

View file

@ -53,11 +53,6 @@ action:ManageOwnProxies
rdfs:label "MANAGE_OWN_PROXIES" .
action:ManagePortals
a display:RequiredAction ;
rdfs:label "MANAGE_PORTALS" .
action:ManageProxies
a display:RequiredAction ;
rdfs:label "MANAGE_PROXIES" .
@ -68,11 +63,6 @@ action:ManageSearchIndex
rdfs:label "MANAGE_SEARCH_INDEX" .
action:ManageTabs
a display:RequiredAction ;
rdfs:label "MANAGE_TABS" .
action:ManageUserAccounts
a display:RequiredAction ;
rdfs:label "MANAGE_USER_ACCOUNTS" .
@ -88,11 +78,6 @@ action:QueryUserAccountsModel
rdfs:label "QUERY_USER_ACCOUNTS_MODEL" .
action:RebuildVClassGroupCache
a display:RequiredAction ;
rdfs:label "REBUILD_VCLASS_GROUP_CACHE" .
action:RefreshVisualizationCache
a display:RequiredAction ;
rdfs:label "REFRESH_VISUALIZATION_CACHE" .
@ -148,9 +133,9 @@ action:UseMiscellaneousCuratorPages
rdfs:label "USE_MISCELLANEOUS_CURATOR_PAGES" .
action:UseMiscellaneousEditorPages
action:UseIndividualControlPanel
a display:RequiredAction ;
rdfs:label "USE_MISCELLANEOUS_EDITOR_PAGES" .
rdfs:label "USE_INDIVIDUAL_CONTROL_PANEL" .
action:UseMiscellaneousPages

View file

@ -109,6 +109,9 @@ xmlns:vitro="&vitro;"
<rdf:Description rdf:about="http://vitro.mannlib.cornell.edu/ns/vitro/0.7#hiddenFromDisplayBelowRoleLevelAnnot">
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#AnnotationProperty"/>
</rdf:Description>
<rdf:Description rdf:about="http://vitro.mannlib.cornell.edu/ns/vitro/0.7#hiddenFromPublishBelowRoleLevelAnnot">
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#AnnotationProperty"/>
</rdf:Description>
<rdf:Description rdf:about="http://vitro.mannlib.cornell.edu/ns/vitro/0.7#forceStubDeletionAnnot">
<rdf:type rdf:resource="http://www.w3.org/2002/07/owl#AnnotationProperty"/>
</rdf:Description>

View file

@ -15,8 +15,6 @@ import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayObje
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction;
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
/**
@ -112,11 +110,9 @@ public class DisplayByRolePermission extends Permission {
* subject, its predicate, and its object.
*/
private boolean isAuthorized(DisplayObjectPropertyStatement action) {
ObjectPropertyStatement stmt = action.getObjectPropertyStatement();
String subjectUri = stmt.getSubjectURI();
String objectUri = stmt.getObjectURI();
Property op = (stmt.getProperty() != null)
? stmt.getProperty() : new Property(stmt.getPropertyURI());
String subjectUri = action.getSubjectUri();
String objectUri = action.getObjectUri();
Property op = action.getProperty();
return canDisplayResource(subjectUri)
&& canDisplayPredicate(op)
&& canDisplayResource(objectUri);

View file

@ -134,6 +134,7 @@ public class PermissionRegistry {
permissions.addAll(SimplePermission.getAllInstances());
permissions.addAll(createDisplayByRolePermissions(ctx));
permissions.addAll(createEditByRolePermissions(ctx));
permissions.addAll(createPublishByRolePermissions(ctx));
PermissionRegistry.createRegistry(ctx, permissions);
@ -185,5 +186,24 @@ public class PermissionRegistry {
public void contextDestroyed(ServletContextEvent sce) {
sce.getServletContext().removeAttribute(ATTRIBUTE_NAME);
}
/**
* There is no PublishByRolePermission for self-editors. They get the
* same rights as PUBLIC. Other permissions give them their self-editing
* privileges.
*/
private Collection<Permission> createPublishByRolePermissions(
ServletContext ctx) {
List<Permission> list = new ArrayList<Permission>();
list.add(new PublishByRolePermission("Admin", RoleLevel.DB_ADMIN,
ctx));
list.add(new PublishByRolePermission("Curator", RoleLevel.CURATOR,
ctx));
list.add(new PublishByRolePermission("Editor", RoleLevel.EDITOR,
ctx));
list.add(new PublishByRolePermission("Public", RoleLevel.PUBLIC,
ctx));
return list;
}
}
}

View file

@ -0,0 +1,133 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.permissions;
import javax.servlet.ServletContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.auth.policy.bean.PropertyRestrictionPolicyHelper;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.publish.PublishDataProperty;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.publish.PublishDataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.publish.PublishObjectProperty;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.publish.PublishObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
/**
* Is the user authorized to publish properties that are marked as restricted to
* a certain "Role Level"?
*/
public class PublishByRolePermission extends Permission {
private static final Log log = LogFactory
.getLog(PublishByRolePermission.class);
public static final String NAMESPACE = "java:"
+ PublishByRolePermission.class.getName() + "#";
private final String roleName;
private final RoleLevel roleLevel;
private final ServletContext ctx;
public PublishByRolePermission(String roleName, RoleLevel roleLevel,
ServletContext ctx) {
super(NAMESPACE + roleName);
if (roleName == null) {
throw new NullPointerException("role may not be null.");
}
if (roleLevel == null) {
throw new NullPointerException("roleLevel may not be null.");
}
if (ctx == null) {
throw new NullPointerException("context may not be null.");
}
this.roleName = roleName;
this.roleLevel = roleLevel;
this.ctx = ctx;
}
@Override
public boolean isAuthorized(RequestedAction whatToAuth) {
boolean result;
if (whatToAuth instanceof PublishDataProperty) {
result = isAuthorized((PublishDataProperty) whatToAuth);
} else if (whatToAuth instanceof PublishObjectProperty) {
result = isAuthorized((PublishObjectProperty) whatToAuth);
} else if (whatToAuth instanceof PublishDataPropertyStatement) {
result = isAuthorized((PublishDataPropertyStatement) whatToAuth);
} else if (whatToAuth instanceof PublishObjectPropertyStatement) {
result = isAuthorized((PublishObjectPropertyStatement) whatToAuth);
} else {
result = false;
}
if (result) {
log.debug(this + " authorizes " + whatToAuth);
} else {
log.debug(this + " does not authorize " + whatToAuth);
}
return result;
}
/**
* The user may publish this data property if they are allowed to publish
* its predicate.
*/
private boolean isAuthorized(PublishDataProperty action) {
String predicateUri = action.getDataProperty().getURI();
return canPublishPredicate(new Property(predicateUri));
}
/**
* The user may publish this object property if they are allowed to publish
* its predicate.
*/
private boolean isAuthorized(PublishObjectProperty action) {
return canPublishPredicate(action.getObjectProperty());
}
/**
* The user may publish this data property if they are allowed to publish
* its subject and its predicate.
*/
private boolean isAuthorized(PublishDataPropertyStatement action) {
String subjectUri = action.getSubjectUri();
String predicateUri = action.getPredicateUri();
return canPublishResource(subjectUri)
&& canPublishPredicate(new Property(predicateUri));
}
/**
* The user may publish this data property if they are allowed to publish
* its subject, its predicate, and its object.
*/
private boolean isAuthorized(PublishObjectPropertyStatement action) {
String subjectUri = action.getSubjectUri();
Property predicate = action.getPredicate();
String objectUri = action.getObjectUri();
return canPublishResource(subjectUri) && canPublishPredicate(predicate)
&& canPublishResource(objectUri);
}
private boolean canPublishResource(String resourceUri) {
return PropertyRestrictionPolicyHelper.getBean(ctx).canPublishResource(
resourceUri, this.roleLevel);
}
private boolean canPublishPredicate(Property predicate) {
return PropertyRestrictionPolicyHelper.getBean(ctx)
.canPublishPredicate(predicate, this.roleLevel);
}
@Override
public String toString() {
return "PublishByRolePermission['" + roleName + "']";
}
}

View file

@ -46,22 +46,16 @@ public class SimplePermission extends Permission {
NAMESPACE + "ManageMenus");
public static final SimplePermission MANAGE_OWN_PROXIES = new SimplePermission(
NAMESPACE + "ManageOwnProxies");
public static final SimplePermission MANAGE_PORTALS = new SimplePermission(
NAMESPACE + "ManagePortals");
public static final SimplePermission MANAGE_PROXIES = new SimplePermission(
NAMESPACE + "ManageProxies");
public static final SimplePermission MANAGE_SEARCH_INDEX = new SimplePermission(
NAMESPACE + "ManageSearchIndex");
public static final SimplePermission MANAGE_TABS = new SimplePermission(
NAMESPACE + "ManageTabs");
public static final SimplePermission MANAGE_USER_ACCOUNTS = new SimplePermission(
NAMESPACE + "ManageUserAccounts");
public static final SimplePermission QUERY_FULL_MODEL = new SimplePermission(
NAMESPACE + "QueryFullModel");
public static final SimplePermission QUERY_USER_ACCOUNTS_MODEL = new SimplePermission(
NAMESPACE + "QueryUserAccountsModel");
public static final SimplePermission REBUILD_VCLASS_GROUP_CACHE = new SimplePermission(
NAMESPACE + "RebuildVClassGroupCache");
public static final SimplePermission REFRESH_VISUALIZATION_CACHE = new SimplePermission(
NAMESPACE + "RefreshVisualizationCache");
public static final SimplePermission SEE_CONFIGURATION = new SimplePermission(
@ -78,6 +72,8 @@ public class SimplePermission extends Permission {
NAMESPACE + "SeeVerbosePropertyInformation");
public static final SimplePermission USE_ADVANCED_DATA_TOOLS_PAGES = new SimplePermission(
NAMESPACE + "UseAdvancedDataToolsPages");
public static final SimplePermission USE_INDIVIDUAL_CONTROL_PANEL = new SimplePermission(
NAMESPACE + "UseIndividualControlPanel");
public static final SimplePermission USE_SPARQL_QUERY_PAGE = new SimplePermission(
NAMESPACE + "UseSparqlQueryPage");
public static final SimplePermission USE_SPARQL_UPDATE_API = new SimplePermission(
@ -95,8 +91,6 @@ public class SimplePermission extends Permission {
NAMESPACE + "UseMiscellaneousAdminPages");
public static final SimplePermission USE_MISCELLANEOUS_CURATOR_PAGES = new SimplePermission(
NAMESPACE + "UseMiscellaneousCuratorPages");
public static final SimplePermission USE_MISCELLANEOUS_EDITOR_PAGES = new SimplePermission(
NAMESPACE + "UseMiscellaneousEditorPages");
public static final SimplePermission USE_MISCELLANEOUS_PAGES = new SimplePermission(
NAMESPACE + "UseMiscellaneousPages");

View file

@ -95,7 +95,7 @@ public class DisplayRestrictedDataToSelfPolicy implements PolicyIface {
String subjectUri = stmt.getIndividualURI();
Property predicate = new Property(stmt.getDatapropURI());
if (canDisplayResource(subjectUri) && canDisplayPredicate(predicate)
&& isAboutAssociatedIndividual(individuals, stmt)) {
&& isAboutAssociatedIndividual(individuals, subjectUri)) {
return authorized("user may view DataPropertyStatement "
+ subjectUri + " ==> " + predicate.getURI());
} else {
@ -112,19 +112,17 @@ public class DisplayRestrictedDataToSelfPolicy implements PolicyIface {
*/
private PolicyDecision isAuthorized(DisplayObjectPropertyStatement action,
Collection<String> individuals) {
ObjectPropertyStatement stmt = action.getObjectPropertyStatement();
String subjectUri = stmt.getSubjectURI();
String predicateUri = stmt.getPropertyURI();
String objectUri = stmt.getObjectURI();
if (canDisplayResource(subjectUri) && canDisplayPredicate(new Property
(predicateUri))
String subjectUri = action.getSubjectUri();
Property predicate = action.getProperty();
String objectUri = action.getObjectUri();
if (canDisplayResource(subjectUri) && canDisplayPredicate(predicate)
&& canDisplayResource(objectUri)
&& isAboutAssociatedIndividual(individuals, stmt)) {
&& isAboutAssociatedIndividual(individuals, subjectUri, objectUri)) {
return authorized("user may view ObjectPropertyStatement "
+ subjectUri + " ==> " + predicateUri + " ==> " + objectUri);
+ subjectUri + " ==> " + predicate.getURI() + " ==> " + objectUri);
} else {
return defaultDecision("user may not view ObjectPropertyStatement "
+ subjectUri + " ==> " + predicateUri + " ==> " + objectUri);
+ subjectUri + " ==> " + predicate.getURI() + " ==> " + objectUri);
}
}
@ -151,9 +149,9 @@ public class DisplayRestrictedDataToSelfPolicy implements PolicyIface {
}
private boolean isAboutAssociatedIndividual(Collection<String> selves,
DataPropertyStatement stmt) {
String subjectUri) {
for (String self : selves) {
if (self.equals(stmt.getIndividualURI())) {
if (self.equals(subjectUri)) {
return true;
}
}
@ -161,10 +159,9 @@ public class DisplayRestrictedDataToSelfPolicy implements PolicyIface {
}
private boolean isAboutAssociatedIndividual(Collection<String> selves,
ObjectPropertyStatement stmt) {
String subjectUri, String objectUri) {
for (String self : selves) {
if (self.equals(stmt.getSubjectURI())
|| self.equals(stmt.getObjectURI())) {
if (self.equals(subjectUri) || self.equals(objectUri)) {
return true;
}
}

View file

@ -0,0 +1,176 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.policy;
import static edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization.INCONCLUSIVE;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyIface;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction;
import edu.cornell.mannlib.vitro.webapp.utils.developer.DeveloperSettings;
import edu.cornell.mannlib.vitro.webapp.utils.developer.Key;
/**
* If enabled in the developer settings (and log levels), log each
* PolicyDecision (subject to restrictions).
*
* Some restrictions apply to the logger as a whole. Others apply to the
* particular policy or the particular decision.
*/
public class PolicyDecisionLogger {
private static final Log log = LogFactory
.getLog(PolicyDecisionLogger.class);
private static final Pattern NEVER_MATCHES = Pattern.compile("^__NEVER__$");
private static final BasicPolicyDecision NULL_DECISION = new BasicPolicyDecision(
INCONCLUSIVE, "The decision was null.");
private final DeveloperSettings settings;
private final RequestedAction whatToAuth;
private final IdentifierBundle whoToAuth;
private final boolean enabled;
private final Pattern policyRestriction;
private final boolean skipInconclusive;
private final boolean includeIdentifiers;
public PolicyDecisionLogger(IdentifierBundle whoToAuth,
RequestedAction whatToAuth) {
this.settings = DeveloperSettings.getInstance();
this.whoToAuth = whoToAuth;
this.whatToAuth = whatToAuth;
this.enabled = figureEnabled();
this.policyRestriction = figurePolicyRestriction();
this.skipInconclusive = figureSkipInconclusive();
this.includeIdentifiers = figureIncludeIdentifiers();
}
private boolean figureEnabled() {
return log.isInfoEnabled()
&& settings.getBoolean(Key.AUTHORIZATION_LOG_DECISIONS_ENABLE)
&& passesUserRestriction() && passesActionRestriction();
}
/**
* The identifier bundle passes if there is no restriction, or if the
* restriction pattern is found within concatenated string of the identifier
* bundle.
*
* If the restriction is invalid, the action fails.
*/
private boolean passesUserRestriction() {
Pattern userRestriction = compilePatternFromSetting(Key.AUTHORIZATION_LOG_DECISIONS_USER_RESTRICTION);
return userRestriction == null
|| userRestriction.matcher(String.valueOf(whoToAuth)).find();
}
/**
* The requested action passes if there is no restriction, or if the
* restriction pattern is found within the class name of the action.
*
* If the restriction is invalid, the action fails.
*/
private boolean passesActionRestriction() {
Pattern actionRestriction = compilePatternFromSetting(Key.AUTHORIZATION_LOG_DECISIONS_ACTION_RESTRICTION);
return actionRestriction == null
|| actionRestriction.matcher(String.valueOf(whatToAuth)).find();
}
/**
* Only compile the policy restriction pattern once.
*/
private Pattern figurePolicyRestriction() {
return compilePatternFromSetting(Key.AUTHORIZATION_LOG_DECISIONS_POLICY_RESTRICTION);
}
/**
* Do we log inconclusive decisions?
*/
private boolean figureSkipInconclusive() {
return settings
.getBoolean(Key.AUTHORIZATION_LOG_DECISIONS_SKIP_INCONCLUSIVE);
}
/**
* Do we include Identifiers in the log record?
*/
private boolean figureIncludeIdentifiers() {
return settings
.getBoolean(Key.AUTHORIZATION_LOG_DECISIONS_ADD_IDENTIFERS);
}
/**
* If no pattern was provided, return null. If an invalid pattern was
* provided, return a pattern that never matches.
*/
private Pattern compilePatternFromSetting(Key key) {
String setting = settings.getString(key);
if (setting.isEmpty()) {
return null;
} else {
try {
return Pattern.compile(setting);
} catch (Exception e) {
return NEVER_MATCHES;
}
}
}
/**
* If the logger and the policy and the decision all pass the restrictions,
* write to the log. A null decision is treated as inconclusive.
*/
public void log(PolicyIface policy, PolicyDecision pd) {
if (passesRestrictions(String.valueOf(policy), pd)) {
if (this.includeIdentifiers) {
log.info(String.format(
"Decision on %s by %s was %s; user is %s",
this.whatToAuth, policy, pd, this.whoToAuth));
} else {
log.info(String.format("Decision on %s by %s was %s",
this.whatToAuth, policy, pd));
}
}
}
private boolean passesRestrictions(String policyString, PolicyDecision pd) {
if (pd == null) {
pd = NULL_DECISION;
}
return enabled && passesPolicyRestriction(policyString)
&& passesConclusiveRestriction(pd);
}
private boolean passesPolicyRestriction(String policyString) {
return this.policyRestriction == null
|| this.policyRestriction.matcher(policyString).find();
}
private boolean passesConclusiveRestriction(PolicyDecision pd) {
return !(skipInconclusive && isInconclusive(pd));
}
private boolean isInconclusive(PolicyDecision pd) {
return pd == null || pd.getAuthorized() == INCONCLUSIVE;
}
public void logNoDecision(PolicyDecision pd) {
if (enabled) {
if (this.includeIdentifiers) {
log.info(pd.getMessage() + "; user is " + this.whoToAuth);
} else {
log.info(pd.getMessage());
}
}
}
}

View file

@ -2,6 +2,8 @@
package edu.cornell.mannlib.vitro.webapp.auth.policy;
import static edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestActionConstants.SOME_URI;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
@ -26,6 +28,7 @@ import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.AddDataPro
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.AddObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.DropDataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.DropObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
import edu.cornell.mannlib.vitro.webapp.controller.authenticate.Authenticator;
@ -125,8 +128,7 @@ public class PolicyHelper {
}
Resource subject = stmt.getSubject();
edu.cornell.mannlib.vitro.webapp.beans.Property predicate = new edu.cornell.mannlib.vitro.webapp.beans.Property(
stmt.getPredicate().getURI());
com.hp.hpl.jena.rdf.model.Property predicate = stmt.getPredicate();
RDFNode objectNode = stmt.getObject();
if ((subject == null) || (predicate == null) || (objectNode == null)) {
return false;
@ -134,8 +136,11 @@ public class PolicyHelper {
RequestedAction action;
if (objectNode.isResource()) {
Property property = new Property(predicate.getURI());
property.setDomainVClassURI(SOME_URI);
property.setRangeVClassURI(SOME_URI);
action = new AddObjectPropertyStatement(modelToBeModified,
subject.getURI(), predicate, objectNode.asResource()
subject.getURI(), property, objectNode.asResource()
.getURI());
} else {
action = new AddDataPropertyStatement(modelToBeModified,
@ -158,8 +163,7 @@ public class PolicyHelper {
}
Resource subject = stmt.getSubject();
edu.cornell.mannlib.vitro.webapp.beans.Property predicate = new edu.cornell.mannlib.vitro.webapp.beans.Property();
predicate.setURI(stmt.getPredicate().getURI());
com.hp.hpl.jena.rdf.model.Property predicate = stmt.getPredicate();
RDFNode objectNode = stmt.getObject();
if ((subject == null) || (predicate == null) || (objectNode == null)) {
return false;
@ -167,8 +171,11 @@ public class PolicyHelper {
RequestedAction action;
if (objectNode.isResource()) {
Property property = new Property(predicate.getURI());
property.setDomainVClassURI(SOME_URI);
property.setRangeVClassURI(SOME_URI);
action = new DropObjectPropertyStatement(modelToBeModified,
subject.getURI(), predicate, objectNode.asResource()
subject.getURI(), property, objectNode.asResource()
.getURI());
} else {
action = new DropDataPropertyStatement(modelToBeModified,

View file

@ -103,14 +103,16 @@ public class PolicyList extends ArrayList<PolicyIface> implements PolicyIface{
protected PolicyDecision checkAgainstPolicys( IdentifierBundle whoToAuth, RequestedAction whatToAuth){
PolicyDecision pd = null;
PolicyDecisionLogger logger = new PolicyDecisionLogger(whoToAuth, whatToAuth);
for(PolicyIface policy : this){
try{
pd = policy.isAuthorized(whoToAuth, whatToAuth);
logger.log(policy, pd);
if( pd != null ){
if( pd.getAuthorized() == Authorization.AUTHORIZED )
break;
return pd;
if( pd.getAuthorized() == Authorization.UNAUTHORIZED )
break;
return pd;
if( pd.getAuthorized() == Authorization.INCONCLUSIVE )
continue;
} else{
@ -120,7 +122,10 @@ public class PolicyList extends ArrayList<PolicyIface> implements PolicyIface{
log.error("ignoring exception in policy " + policy.toString(), th );
}
}
log.debug("decision " + pd + " for " + whatToAuth);
pd = new BasicPolicyDecision(Authorization.INCONCLUSIVE,
"No policy returned a conclusive decision on " + whatToAuth);
logger.logNoDecision(pd);
return pd;
}

View file

@ -48,7 +48,6 @@ public class ServletPolicyList {
PolicyList policies = getPolicyList(sc);
if (!policies.contains(policy)) {
policies.add(policy);
log.info("Added policy: " + policy.getClass().getSimpleName());
log.debug("Added policy: " + policy.toString());
} else {
log.warn("Ignored attempt to add redundant policy.");
@ -67,7 +66,6 @@ public class ServletPolicyList {
PolicyList policies = getPolicyList(sc);
if (!policies.contains(policy)) {
policies.add(0, policy);
log.info("Added policy at front: " + policy.getClass().getSimpleName());
log.debug("Added policy at front: " + policy.toString());
} else {
log.warn("Ignored attempt to add redundant policy.");

View file

@ -37,8 +37,9 @@ public class PropertyRestrictionListener implements ChangeListener {
@Override
public void doDeleted(Object oldObj, EditProcessObject epo) {
Property p = (Property) oldObj;
if (eitherRoleChanged(p.getHiddenFromDisplayBelowRoleLevel(),
p.getProhibitedFromUpdateBelowRoleLevel(), null, null)) {
if (anyRoleChanged(p.getHiddenFromDisplayBelowRoleLevel(),
p.getProhibitedFromUpdateBelowRoleLevel(),
p.getHiddenFromPublishBelowRoleLevel(), null, null, null)) {
log.debug("rebuilding the PropertyRestrictionPolicyHelper after deletion");
createAndSetBean();
}
@ -50,9 +51,10 @@ public class PropertyRestrictionListener implements ChangeListener {
@Override
public void doInserted(Object newObj, EditProcessObject epo) {
Property p = (Property) newObj;
if (eitherRoleChanged(null, null,
if (anyRoleChanged(null, null, null,
p.getHiddenFromDisplayBelowRoleLevel(),
p.getProhibitedFromUpdateBelowRoleLevel())) {
p.getProhibitedFromUpdateBelowRoleLevel(),
p.getHiddenFromPublishBelowRoleLevel())) {
log.debug("rebuilding the PropertyRestrictionPolicyHelper after insertion");
createAndSetBean();
}
@ -65,20 +67,24 @@ public class PropertyRestrictionListener implements ChangeListener {
public void doUpdated(Object oldObj, Object newObj, EditProcessObject epo) {
Property oldP = (Property) oldObj;
Property newP = (Property) newObj;
if (eitherRoleChanged(oldP.getHiddenFromDisplayBelowRoleLevel(),
if (anyRoleChanged(oldP.getHiddenFromDisplayBelowRoleLevel(),
oldP.getProhibitedFromUpdateBelowRoleLevel(),
oldP.getHiddenFromPublishBelowRoleLevel(),
newP.getHiddenFromDisplayBelowRoleLevel(),
newP.getProhibitedFromUpdateBelowRoleLevel())) {
newP.getProhibitedFromUpdateBelowRoleLevel(),
newP.getHiddenFromPublishBelowRoleLevel())) {
log.debug("rebuilding the PropertyRestrictionPolicyHelper after update");
createAndSetBean();
}
}
private boolean eitherRoleChanged(RoleLevel oldDisplayRole,
RoleLevel oldUpdateRole, RoleLevel newDisplayRole,
RoleLevel newUpdateRole) {
private boolean anyRoleChanged(RoleLevel oldDisplayRole,
RoleLevel oldUpdateRole, RoleLevel oldPublishRole,
RoleLevel newDisplayRole, RoleLevel newUpdateRole,
RoleLevel newPublishRole) {
return (!isTheSame(oldDisplayRole, newDisplayRole))
|| (!isTheSame(oldUpdateRole, newUpdateRole));
|| (!isTheSame(oldUpdateRole, newUpdateRole))
|| (!isTheSame(oldPublishRole, newPublishRole));
}
private boolean isTheSame(RoleLevel oldRole, RoleLevel newRole) {

View file

@ -19,12 +19,6 @@ import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.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.ModelFactory;
import com.hp.hpl.jena.rdf.model.RDFNode;
@ -46,10 +40,10 @@ import edu.cornell.mannlib.vitro.webapp.utils.ApplicationConfigurationOntologyUt
/**
* Assists the role-based policies in determining whether a property or resource
* may be displayed or modified.
* may be displayed, modified, or published in linked open data.
*
* There is a bean in the context that holds the current threshold role levels
* for displaying and modifying restricted properties.
* for displaying, modifying, or publishing restricted properties.
*
* Create this bean after the Jena model is in place in the context.
*
@ -119,6 +113,8 @@ public class PropertyRestrictionPolicyHelper {
new HashMap<Pair<String, Pair<String,String>>, RoleLevel>();
Map<Pair<String, Pair<String,String>>, RoleLevel> modifyThresholdMap =
new HashMap<Pair<String, Pair<String,String>>, RoleLevel>();
Map<Pair<String, Pair<String,String>>, RoleLevel> publishThresholdMap =
new HashMap<Pair<String, Pair<String,String>>, RoleLevel>();
OntModel union = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM,
ModelFactory.createUnion(displayModel, model));
@ -126,15 +122,14 @@ public class PropertyRestrictionPolicyHelper {
populateThresholdMap(union, displayThresholdMap,
VitroVocabulary.HIDDEN_FROM_DISPLAY_BELOW_ROLE_LEVEL_ANNOT);
populateThresholdMap(
union,
modifyThresholdMap,
populateThresholdMap(union, modifyThresholdMap,
VitroVocabulary.PROHIBITED_FROM_UPDATE_BELOW_ROLE_LEVEL_ANNOT);
populateThresholdMap(union, publishThresholdMap,
VitroVocabulary.HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT);
PropertyRestrictionPolicyHelper bean = new PropertyRestrictionPolicyHelper(
PROHIBITED_NAMESPACES, PERMITTED_EXCEPTIONS,
displayThresholdMap, modifyThresholdMap, displayModel);
displayThresholdMap, modifyThresholdMap, publishThresholdMap);
return bean;
}
@ -209,9 +204,14 @@ public class PropertyRestrictionPolicyHelper {
} else if (VitroVocabulary.HIDDEN_FROM_DISPLAY_BELOW_ROLE_LEVEL_ANNOT
.equals(propertyUri)) {
role = faux.getHiddenFromDisplayBelowRoleLevel();
} else if (VitroVocabulary.HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT
.equals(propertyUri)) {
role = faux.getHiddenFromPublishBelowRoleLevel();
}
if (role != null) {
log.debug("Putting D:" + faux.getDomainVClassURI() + " P:" + faux.getURI() + " R:" + faux.getRangeVClassURI() + " ==> L:" + role);
log.debug("Putting D:" + faux.getDomainVClassURI() + " P:"
+ faux.getURI() + " R:" + faux.getRangeVClassURI()
+ " ==> L:" + role);
map.put(new Pair<String,Pair<String,String>>(
faux.getDomainVClassURI(), new Pair<String,String>(
faux.getURI(), faux.getRangeVClassURI())), role);
@ -251,6 +251,12 @@ public class PropertyRestrictionPolicyHelper {
*/
private final Map<Pair<String, Pair<String,String>>, RoleLevel> modifyThresholdMap;
/**
* These URIs can be published only if the user's role is at least as high as
* the threshold role.
*/
private final Map<Pair<String, Pair<String,String>>, RoleLevel> publishThresholdMap;
/**
* Store unmodifiable versions of the inputs.
@ -263,11 +269,14 @@ public class PropertyRestrictionPolicyHelper {
Collection<String> modifyExceptionsAllowedUris,
Map<Pair<String, Pair<String,String>>, RoleLevel> displayThresholdMap,
Map<Pair<String, Pair<String,String>>, RoleLevel> modifyThresholdMap,
Model displayModel) {
Map<Pair<String, Pair<String,String>>, RoleLevel> publishThresholdMap) {
this.modifyProhibitedNamespaces = unmodifiable(modifyProhibitedNamespaces);
this.modifyExceptionsAllowedUris = unmodifiable(modifyExceptionsAllowedUris);
this.displayThresholdMap = displayThresholdMap;
this.modifyThresholdMap = modifyThresholdMap;
this.publishThresholdMap = publishThresholdMap;
// TODO: why are these no longer unmodifiable? Brian changed during the
// TODO: ISF integration.
// this.displayThresholdMap = unmodifiable(displayThresholdMap);
// this.modifyThresholdMap = unmodifiable(modifyThresholdMap);
@ -276,6 +285,7 @@ public class PropertyRestrictionPolicyHelper {
log.debug("exceptions: " + this.modifyExceptionsAllowedUris);
log.debug("display thresholds: " + this.displayThresholdMap);
log.debug("modify thresholds: " + this.modifyThresholdMap);
log.debug("publish thresholds: " + this.publishThresholdMap);
}
}
@ -341,6 +351,22 @@ public class PropertyRestrictionPolicyHelper {
return true;
}
/**
* Any resource can be published.
*
* (Someday we may want to implement publish restrictions based on VClass.)
*/
@SuppressWarnings("unused")
public boolean canPublishResource(String resourceUri, RoleLevel userRole) {
if (resourceUri == null) {
log.debug("can't publish resource: resourceUri was null");
return false;
}
log.debug("can publish resource '" + resourceUri + "'");
return true;
}
/**
* If display of a predicate is restricted, the user's role must be at least
* as high as the restriction level.
@ -408,6 +434,33 @@ public class PropertyRestrictionPolicyHelper {
return false;
}
/**
* If publishing of a predicate is restricted, the user's role must be at least
* as high as the restriction level.
*/
public boolean canPublishPredicate(Property predicate, RoleLevel userRole) {
if (predicate == null) {
log.debug("can't publish predicate: predicate was null");
return false;
}
RoleLevel publishThreshold = getThreshold(predicate, publishThresholdMap);
if (isAuthorized(userRole, publishThreshold)) {
log.debug("can publish predicate: '" + predicate.getURI() + "', domain="
+ predicate.getDomainVClassURI() + ", range="
+ predicate.getRangeVClassURI() + ", userRole="
+ userRole + ", thresholdRole=" + publishThreshold);
return true;
}
log.debug("can't publish predicate: '" + predicate.getURI() + "', domain="
+ predicate.getDomainVClassURI() + ", range="
+ predicate.getRangeVClassURI() + ", userRole="
+ userRole + ", thresholdRole=" + publishThreshold);
return false;
}
private boolean isAuthorized(RoleLevel userRole, RoleLevel thresholdRole) {
if (userRole == null) {
return false;

View file

@ -3,27 +3,37 @@
package edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
/** Should we let the user see this ObjectPropertyStatement? */
public class DisplayObjectPropertyStatement extends RequestedAction {
private final ObjectPropertyStatement objectPropertyStatement;
private final String subjectUri;
private final ObjectProperty property;
private final String objectUri;
public DisplayObjectPropertyStatement(
ObjectPropertyStatement objectPropertyStatement) {
this.objectPropertyStatement = objectPropertyStatement;
public DisplayObjectPropertyStatement(String subjectUri,
ObjectProperty property, String objectUri) {
this.subjectUri = subjectUri;
this.property = property;
this.objectUri = objectUri;
}
public ObjectPropertyStatement getObjectPropertyStatement() {
return objectPropertyStatement;
public String getSubjectUri() {
return subjectUri;
}
public ObjectProperty getProperty() {
return property;
}
public String getObjectUri() {
return objectUri;
}
@Override
public String toString() {
return "DisplayObjectPropertyStatement["
+ objectPropertyStatement.getSubjectURI() + "==>"
+ objectPropertyStatement.getPropertyURI() + "==>"
+ objectPropertyStatement.getObjectURI() + "]";
return "DisplayObjectPropertyStatement[" + subjectUri + "==>"
+ property.getURI() + "==>" + objectUri + "]";
}
}

View file

@ -60,6 +60,10 @@ public abstract class AbstractDataPropertyStatementAction extends
return new String[] {subjectUri};
}
public String dataValue() {
return dataValue;
}
@Override
public String toString() {
return getClass().getSimpleName() + ": <" + subjectUri + "> <"

View file

@ -4,7 +4,6 @@ package edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt;
import com.hp.hpl.jena.ontology.OntModel;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
/**
@ -17,23 +16,14 @@ public abstract class AbstractObjectPropertyStatementAction extends
private final Property predicate;
private final String objectUri;
public AbstractObjectPropertyStatementAction(OntModel ontModel, String subjectUri,
Property predicate, String objectUri) {
public AbstractObjectPropertyStatementAction(OntModel ontModel,
String subjectUri, Property predicate, String objectUri) {
super(ontModel);
this.subjectUri = subjectUri;
this.predicate = predicate;
this.objectUri = objectUri;
}
public AbstractObjectPropertyStatementAction(OntModel ontModel, ObjectPropertyStatement ops) {
super(ontModel);
this.subjectUri = (ops.getSubject() == null) ? ops.getSubjectURI()
: ops.getSubject().getURI();
this.predicate = (ops.getProperty());
this.objectUri = (ops.getObject() == null) ? ops.getObjectURI() : ops
.getObject().getURI();
}
public String getSubjectUri() {
return subjectUri;
}
@ -42,6 +32,7 @@ public abstract class AbstractObjectPropertyStatementAction extends
return objectUri;
}
@Override
public Property getPredicate() {
return predicate;
}

View file

@ -4,7 +4,6 @@ package edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt;
import com.hp.hpl.jena.ontology.OntModel;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
/**
@ -17,8 +16,4 @@ public class AddObjectPropertyStatement extends
super(ontModel, uriOfSub, predicate, uriOfObj);
}
public AddObjectPropertyStatement(OntModel ontModel,
ObjectPropertyStatement ops) {
super(ontModel, ops);
}
}

View file

@ -4,7 +4,6 @@ package edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt;
import com.hp.hpl.jena.ontology.OntModel;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
/**
@ -17,9 +16,4 @@ public class DropObjectPropertyStatement extends
Property pred, String obj) {
super(ontModel, sub, pred, obj);
}
public DropObjectPropertyStatement(OntModel ontModel,
ObjectPropertyStatement ops) {
super(ontModel, ops);
}
}

View file

@ -4,7 +4,6 @@ package edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt;
import com.hp.hpl.jena.ontology.OntModel;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
/**
@ -16,9 +15,4 @@ public class EditObjectPropertyStatement extends
Property keywordPred, String objectUri) {
super(ontModel, subjectUri, keywordPred, objectUri);
}
public EditObjectPropertyStatement(OntModel ontModel,
ObjectPropertyStatement ops) {
super(ontModel, ops);
}
}

View file

@ -0,0 +1,24 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.requestedAction.publish;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
/** Should we allow the user to publish this DataProperty in Linked Open Data? */
public class PublishDataProperty extends RequestedAction {
private final DataProperty dataProperty;
public PublishDataProperty(DataProperty dataProperty) {
this.dataProperty = dataProperty;
}
public DataProperty getDataProperty() {
return dataProperty;
}
@Override
public String toString() {
return "PublishDataProperty[" + dataProperty + "]";
}
}

View file

@ -0,0 +1,26 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.requestedAction.publish;
import com.hp.hpl.jena.ontology.OntModel;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.AbstractDataPropertyStatementAction;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
/**
* Should we publish this DataPropertyStatement in a Linked Open Data request
* from the current user?
*/
public class PublishDataPropertyStatement extends
AbstractDataPropertyStatementAction {
public PublishDataPropertyStatement(OntModel ontModel, String subjectUri,
String predicateUri, String dataValue) {
super(ontModel, subjectUri, predicateUri, dataValue);
}
public PublishDataPropertyStatement(OntModel ontModel,
DataPropertyStatement dps) {
super(ontModel, dps);
}
}

View file

@ -0,0 +1,24 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.requestedAction.publish;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
/** Should we allow the user to publish this ObjectProperty in Linked Open Data? */
public class PublishObjectProperty extends RequestedAction {
private final ObjectProperty objectProperty;
public PublishObjectProperty(ObjectProperty objectProperty) {
this.objectProperty = objectProperty;
}
public ObjectProperty getObjectProperty() {
return objectProperty;
}
@Override
public String toString() {
return "PublishObjectProperty[" + objectProperty.getLocalName() + "]";
}
}

View file

@ -0,0 +1,39 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.requestedAction.publish;
import com.hp.hpl.jena.ontology.OntModel;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestActionConstants;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.AbstractObjectPropertyStatementAction;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
/**
* Should we publish this ObjectPropertyStatement in a Linked Open Data request
* from the current user?
*/
public class PublishObjectPropertyStatement extends
AbstractObjectPropertyStatementAction {
public PublishObjectPropertyStatement(OntModel ontModel, String subjectUri,
Property keywordPred, String objectUri) {
super(ontModel, subjectUri, keywordPred, objectUri);
}
/**
* We don't need to know range and domain because publishing never involves
* faux properties.
*/
public PublishObjectPropertyStatement(OntModel ontModel,
String subjectUri,
String predicateUri, String objectUri) {
this(ontModel, subjectUri, populateProperty(predicateUri), objectUri);
}
private static Property populateProperty(String predicateUri) {
Property prop = new Property(predicateUri);
prop.setDomainVClassURI(RequestActionConstants.SOME_URI);
prop.setRangeVClassURI(RequestActionConstants.SOME_URI);
return prop;
}
}

View file

@ -25,37 +25,54 @@ public class BaseResourceBean implements ResourceBean {
protected String localNameWithPrefix = null;
protected String pickListName = null;
// these will be phased in and used in the filters Brian C. has been setting up,
// with hiddenFromDisplay to control the level at which any class, individual, object property, or data property is displayed
// and prohibitedFromEditing to control when a control for editing is made available
protected RoleLevel hiddenFromDisplayBelowRoleLevel = null;
//protected RoleLevel prohibitedFromCreateBelowRoleLevel = null;
protected RoleLevel prohibitedFromUpdateBelowRoleLevel = null;
//protected RoleLevel prohibitedFromDeleteBelowRoleLevel = null;
protected RoleLevel hiddenFromPublishBelowRoleLevel = null;
public enum RoleLevel { PUBLIC("http://vitro.mannlib.cornell.edu/ns/vitro/role#public","public","public"),
SELF("http://vitro.mannlib.cornell.edu/ns/vitro/role#selfEditor","self-authenticated","self"),
EDITOR("http://vitro.mannlib.cornell.edu/ns/vitro/role#editor","editor, curator, site administrator","editor"),
CURATOR("http://vitro.mannlib.cornell.edu/ns/vitro/role#curator","curator, site administrator","curator"),
DB_ADMIN("http://vitro.mannlib.cornell.edu/ns/vitro/role#dbAdmin","site administrator","siteAdmin"),
NOBODY("http://vitro.mannlib.cornell.edu/ns/vitro/role#nobody","root user","root");
public enum RoleLevel {
PUBLIC("http://vitro.mannlib.cornell.edu/ns/vitro/role#public",
"all users, including public", "all users who can log in",
"public"),
SELF("http://vitro.mannlib.cornell.edu/ns/vitro/role#selfEditor",
"self-editor and above", "self-editor and above", "self"),
EDITOR("http://vitro.mannlib.cornell.edu/ns/vitro/role#editor",
"editor and above", "editor and above", "editor"),
CURATOR("http://vitro.mannlib.cornell.edu/ns/vitro/role#curator",
"curator and above", "curator and above", "curator"),
DB_ADMIN("http://vitro.mannlib.cornell.edu/ns/vitro/role#dbAdmin",
"site admin and root user", "site admin and root user",
"siteAdmin"),
NOBODY("http://vitro.mannlib.cornell.edu/ns/vitro/role#nobody",
"root user", "root user", "root");
private final String uri;
private final String label;
private final String displayLabel;
private final String updateLabel;
private final String shorthand;
RoleLevel(String uriStr,String labelStr, String shortStr) {
this.uri = uriStr;
this.label = labelStr;
this.shorthand = shortStr;
private RoleLevel(String uri, String displayLabel, String updateLabel,
String shorthand) {
this.uri = uri;
this.displayLabel = displayLabel;
this.updateLabel = updateLabel;
this.shorthand = shorthand;
}
public String getURI() {
return uri;
}
public String getLabel() {
return label;
public String getDisplayLabel() {
return displayLabel;
}
public String getUpdateLabel() {
return updateLabel;
}
public String getShorthand() {
@ -95,13 +112,16 @@ public class BaseResourceBean implements ResourceBean {
}
}
@Override
public boolean isAnonymous() {
return (this.URI==null || VitroVocabulary.PSEUDO_BNODE_NS.equals(this.getNamespace()));
}
@Override
public String getURI() {
return URI;
}
@Override
public void setURI(String URI) {
if( this.localName != null || this.namespace != null)
buildLocalAndNS(URI);
@ -122,11 +142,13 @@ public class BaseResourceBean implements ResourceBean {
}
}
@Override
public String getNamespace() {
if( namespace == null && this.URI != null)
buildLocalAndNS(this.URI);
return namespace;
}
@Override
public void setNamespace(String namespace) {
this.namespace = namespace;
if (namespace != null && localName != null ) {
@ -134,16 +156,19 @@ public class BaseResourceBean implements ResourceBean {
}
}
@Override
public String getLabel() {
return getLocalName();
}
@Override
public String getLocalName() {
if( localName == null && this.URI != null)
buildLocalAndNS(this.URI);
return localName;
}
@Override
public void setLocalName(String localName) {
this.localName = localName;
if (namespace != null && localName != null) {
@ -160,6 +185,7 @@ public class BaseResourceBean implements ResourceBean {
this.localNameWithPrefix = prefixedLocalName;
}
@Override
public String getPickListName() {
return pickListName==null ? getLocalName()==null ?
(URI==null ? "(no name)" : URI ): getLocalName() : pickListName;
@ -168,56 +194,50 @@ public class BaseResourceBean implements ResourceBean {
this.pickListName = pickListName;
}
@Override
public RoleLevel getHiddenFromDisplayBelowRoleLevel() {
return hiddenFromDisplayBelowRoleLevel;
}
@Override
public void setHiddenFromDisplayBelowRoleLevel(RoleLevel eR) {
hiddenFromDisplayBelowRoleLevel = eR;
}
@Override
public void setHiddenFromDisplayBelowRoleLevelUsingRoleUri(String roleUri) {
hiddenFromDisplayBelowRoleLevel = BaseResourceBean.RoleLevel.getRoleByUri(roleUri);
}
/*
public RoleLevel getProhibitedFromCreateBelowRoleLevel() {
return prohibitedFromCreateBelowRoleLevel;
}
public void setProhibitedFromCreateBelowRoleLevel(RoleLevel eR) {
prohibitedFromCreateBelowRoleLevel = eR;
}
public void setProhibitedFromCreateBelowRoleLevelUsingRoleUri(String roleUri) {
prohibitedFromCreateBelowRoleLevel = BaseResourceBean.RoleLevel.getRoleByUri(roleUri);
}
*/
@Override
public RoleLevel getProhibitedFromUpdateBelowRoleLevel() {
return prohibitedFromUpdateBelowRoleLevel;
}
@Override
public void setProhibitedFromUpdateBelowRoleLevel(RoleLevel eR) {
prohibitedFromUpdateBelowRoleLevel = eR;
}
@Override
public void setProhibitedFromUpdateBelowRoleLevelUsingRoleUri(String roleUri) {
prohibitedFromUpdateBelowRoleLevel = BaseResourceBean.RoleLevel.getRoleByUri(roleUri);
}
/*
public RoleLevel getProhibitedFromDeleteBelowRoleLevel() {
return prohibitedFromDeleteBelowRoleLevel;
@Override
public RoleLevel getHiddenFromPublishBelowRoleLevel() {
return hiddenFromPublishBelowRoleLevel;
}
public void setProhibitedFromDeleteBelowRoleLevel(RoleLevel eR) {
prohibitedFromDeleteBelowRoleLevel = eR;
@Override
public void setHiddenFromPublishBelowRoleLevel(RoleLevel eR) {
hiddenFromPublishBelowRoleLevel = eR;
}
public void setProhibitedFromDeleteBelowRoleLevelUsingRoleUri(String roleUri) {
prohibitedFromDeleteBelowRoleLevel = BaseResourceBean.RoleLevel.getRoleByUri(roleUri);
@Override
public void setHiddenFromPublishBelowRoleLevelUsingRoleUri(String roleUri) {
hiddenFromPublishBelowRoleLevel = BaseResourceBean.RoleLevel.getRoleByUri(roleUri);
}
*/
@Override
public boolean equals(Object obj) {

View file

@ -633,6 +633,7 @@ public class ObjectProperty extends Property implements Comparable<ObjectPropert
clone.setFunctional(this.getFunctional());
clone.setGroupURI(this.getGroupURI());
clone.setHiddenFromDisplayBelowRoleLevel(this.getHiddenFromDisplayBelowRoleLevel());
clone.setHiddenFromPublishBelowRoleLevel(this.getHiddenFromPublishBelowRoleLevel());
clone.setInverseFunctional(this.getInverseFunctional());
clone.setLabel(this.getLabel());
clone.setLocalName(this.getLocalName());

View file

@ -62,4 +62,13 @@ public class Ontology implements Comparable<Ontology>
return collator.compare(this.getName(), o2.getName());
}
@Override
public String toString() {
return "Ontology[myID=" + myID + ", myName=" + myName + ", myType="
+ myType + ", myPrefix=" + myPrefix + ", myNamespaceID="
+ myNamespaceID + ", myURI=" + myURI + ", myVClassesList="
+ myVClassesList + ", myPropsList=" + myPropsList
+ ", myEntitiesList=" + myEntitiesList + "]";
}
}

View file

@ -39,6 +39,12 @@ public interface ResourceBean {
public void setProhibitedFromUpdateBelowRoleLevelUsingRoleUri(String roleUri) ;
public RoleLevel getHiddenFromPublishBelowRoleLevel() ;
public void setHiddenFromPublishBelowRoleLevel(RoleLevel eR) ;
public void setHiddenFromPublishBelowRoleLevelUsingRoleUri(String roleUri) ;
public String getPickListName();
}

View file

@ -137,24 +137,30 @@ public class VClass extends BaseResourceBean implements Comparable<VClass>
/**
* 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;
public VClass copy() {
VClass that = new VClass();
copyFields(that);
return that;
}
protected void copyFields(VClass that) {
that.myName = this.myName;
that.namespace = this.namespace;
that.localName = this.localName;
that.URI = this.URI;
that.myExample = this.myExample;
that.myDescription = this.myDescription;
that.myShortDefinition = this.myShortDefinition;
that.myEntityCount = this.myEntityCount;
that.displayLimit = this.displayLimit;
that.displayRank = this.displayRank;
that.quickEditJsp = this.quickEditJsp;
that.groupURI = this.groupURI;
that.group = this.group;
that.customEntryForm = this.customEntryForm;
that.customDisplayView = this.customDisplayView;
that.customShortView = this.customShortView;
that.customSearchView = this.customSearchView;
}
/**

View file

@ -45,7 +45,6 @@ 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.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.FileUploadServletRequest;
import fedora.client.FedoraClient;
import fedora.common.Constants;
import fedora.server.management.FedoraAPIM;
@ -219,13 +218,23 @@ public class FedoraDatastreamController extends VitroHttpServlet implements Cons
}
}
@Override
public long maximumMultipartFileSize() {
return maxFileSize;
}
@Override
public boolean stashFileSizeException() {
return true;
}
@Override
public void doPost(HttpServletRequest rawRequest, HttpServletResponse res)
throws ServletException, IOException {
try{
FileUploadServletRequest req = FileUploadServletRequest.parseRequest(rawRequest, maxFileSize);
if (req.hasFileUploadException()) {
throw new FdcException("Size limit exceeded: " + req.getFileUploadException().getLocalizedMessage());
VitroRequest req = new VitroRequest(rawRequest);
if (req.hasFileSizeException()) {
throw new FdcException("Size limit exceeded: " + req.getFileSizeException().getLocalizedMessage());
}
if (!req.isMultipart()) {
throw new FdcException("Must POST a multipart encoded request");

View file

@ -0,0 +1,288 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Wraps a multipart HTTP request, and pre-parses it for file uploads, without
* losing the request parameters.
*
* Parsing through the request with an Apache ServletFileUpload builds a list of
* FileItems that includes the parameters and the file parts. After that,
* however, the parameters are no longer accessible from the request. This
* wrapper will see that they don't get lost.
*
* The List of FileItems includes both "formField" items and "file" items. As
* with the usual parameters on a request, we can have more than one value with
* the same name. So this creates a map of <String, List<String>> to hold the
* parameters, and a map of <String, List<FileItem>> to hold the files.
*
* The parameters will be available to the wrapper through the normal methods.
* The files will be available as an attribute that holds the map. Also, a
* separate attribute will hold a Boolean to indicate that this was indeed a
* multipart request.
*
* Conveninence methods in VitroRequest will make these easy to handle, without
* actually touching the attributes.
*/
public class MultipartRequestWrapper extends HttpServletRequestWrapper {
private static final Log log = LogFactory
.getLog(MultipartRequestWrapper.class);
private static final String CLASS_NAME = MultipartRequestWrapper.class
.getSimpleName();
public static final String ATTRIBUTE_IS_MULTIPART = CLASS_NAME
+ "_isMultipart";
public static final String ATTRIBUTE_FILE_ITEM_MAP = CLASS_NAME
+ "_fileItemMap";
public static final String ATTRIBUTE_FILE_SIZE_EXCEPTION = CLASS_NAME
+ "_fileSizeException";
private static final String[] EMPTY_ARRAY = new String[0];
// ----------------------------------------------------------------------
// The factory
// ----------------------------------------------------------------------
/**
* If this is a multipart request, wrap it. Otherwise, just return the
* request as it is.
*/
public static HttpServletRequest parse(HttpServletRequest req,
ParsingStrategy strategy) throws IOException {
if (!ServletFileUpload.isMultipartContent(req)) {
return req;
}
ListsMap<String> parameters = new ListsMap<>();
ListsMap<FileItem> files = new ListsMap<>();
parseQueryString(req.getQueryString(), parameters);
parseFileParts(req, parameters, files, strategy);
return new MultipartRequestWrapper(req, parameters, files);
}
/**
* Pull any parameters out of the URL.
*/
private static void parseQueryString(String queryString,
ListsMap<String> parameters) {
log.debug("Query string is : '" + queryString + "'");
if (queryString != null) {
String[] pieces = queryString.split("&");
for (String piece : pieces) {
int equalsHere = piece.indexOf('=');
if (piece.trim().isEmpty()) {
// Ignore an empty piece.
} else if (equalsHere <= 0) {
// A parameter without a value.
parameters.add(decode(piece), "");
} else {
// A parameter with a value.
String key = piece.substring(0, equalsHere);
String value = piece.substring(equalsHere + 1);
parameters.add(decode(key), decode(value));
}
}
}
log.debug("Parameters from query string are: " + parameters);
}
/**
* Remove any special URL-style encoding.
*/
private static String decode(String encoded) {
try {
return URLDecoder.decode(encoded, "UTF-8");
} catch (UnsupportedEncodingException e) {
log.error(e, e);
return encoded;
}
}
private static void parseFileParts(HttpServletRequest req,
ListsMap<String> parameters, ListsMap<FileItem> files,
ParsingStrategy strategy) throws IOException {
ServletFileUpload upload = createUploadHandler(req,
strategy.maximumMultipartFileSize());
List<FileItem> items = parseRequestIntoFileItems(req, upload, strategy);
for (FileItem item : items) {
// Process a regular form field
String name = item.getFieldName();
if (item.isFormField()) {
String value;
try {
value = item.getString("UTF-8");
} catch (UnsupportedEncodingException e) {
value = item.getString();
}
parameters.add(name, value);
log.debug("Form field (parameter) " + name + "=" + value);
} else {
files.add(name, item);
log.debug("File " + name + ": " + item.getSize() + " bytes.");
}
}
}
/**
* Create an upload handler that will throw an exception if the file is too
* large.
*/
private static ServletFileUpload createUploadHandler(
HttpServletRequest req, long maxFileSize) {
File tempDir = figureTemporaryDirectory(req);
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
factory.setRepository(tempDir);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxFileSize);
return upload;
}
/**
* Find the temporary storage directory for this webapp.
*/
private static File figureTemporaryDirectory(HttpServletRequest request) {
return (File) request.getSession().getServletContext()
.getAttribute("javax.servlet.context.tempdir");
}
/**
* Parse the raw request into a list of parts.
*
* If there is a parsing error, let the strategy handle it. If the strategy
* throws it back, wrap it in an IOException and throw it on up.
*/
@SuppressWarnings("unchecked")
private static List<FileItem> parseRequestIntoFileItems(
HttpServletRequest req, ServletFileUpload upload,
ParsingStrategy strategy) throws IOException {
try {
return upload.parseRequest(req);
} catch (FileSizeLimitExceededException e) {
if (strategy.stashFileSizeException()) {
req.setAttribute(ATTRIBUTE_FILE_SIZE_EXCEPTION, e);
return Collections.emptyList();
} else {
throw new IOException(e);
}
} catch (FileUploadException e) {
throw new IOException(e);
}
}
// ----------------------------------------------------------------------
// The instance
// ----------------------------------------------------------------------
private final ListsMap<String> parameters;
public MultipartRequestWrapper(HttpServletRequest req,
ListsMap<String> parameters, ListsMap<FileItem> files) {
super(req);
this.parameters = parameters;
req.setAttribute(ATTRIBUTE_IS_MULTIPART, Boolean.TRUE);
req.setAttribute(ATTRIBUTE_FILE_ITEM_MAP, files);
}
/**
* Look in the map of parsed parameters.
*/
@Override
public String getParameter(String name) {
if (parameters.containsKey(name)) {
return parameters.get(name).get(0);
} else {
return null;
}
}
/**
* Look in the map of parsed parameters. Make a protective copy.
*/
@Override
public Enumeration<?> getParameterNames() {
return Collections.enumeration(new HashSet<>(parameters.keySet()));
}
/**
* Look in the map of parsed parameters.
*/
@Override
public String[] getParameterValues(String name) {
if (parameters.containsKey(name)) {
return parameters.get(name).toArray(EMPTY_ARRAY);
} else {
return null;
}
}
/**
* Make a copy of the map of parsed parameters;
*/
@Override
public Map<String, String[]> getParameterMap() {
Map<String, String[]> result = new HashMap<String, String[]>();
for (String key : parameters.keySet()) {
result.put(key, parameters.get(key).toArray(EMPTY_ARRAY));
}
return result;
}
// ----------------------------------------------------------------------
// Helper classes
// ----------------------------------------------------------------------
private static class ListsMap<T> extends HashMap<String, List<T>> {
void add(String key, T value) {
if (!containsKey(key)) {
put(key, new ArrayList<T>());
}
get(key).add(value);
}
}
public interface ParsingStrategy {
long maximumMultipartFileSize();
/**
* Allows you to handle the exception in your code.
*
* Be aware that the multipart parameters have been lost, and that may
* include form fields.
*/
boolean stashFileSizeException();
}
}

View file

@ -134,7 +134,7 @@ public class SparqlQueryServlet extends BaseEditController {
doSelect(response, queryParam, formatConf, rdfService);
}else if( query.isAskType()){
doAsk( queryParam, rdfService, response );
}else if( query.isConstructType() ){
}else if( query.isConstructType() || query.isDescribeType() ){
String format = contentType != null ? contentType : vreq.getParameter("rdfResultFormat");
if (format== null) {
format= "RDF/XML-ABBREV";

View file

@ -30,14 +30,13 @@ import edu.cornell.mannlib.vedit.beans.LoginStatusBean;
import edu.cornell.mannlib.vitro.webapp.auth.policy.PolicyHelper;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.Actions;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction;
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean;
import edu.cornell.mannlib.vitro.webapp.beans.DisplayMessage;
import edu.cornell.mannlib.vitro.webapp.beans.ResourceBean;
import edu.cornell.mannlib.vitro.webapp.controller.authenticate.LogoutRedirector;
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 implements MultipartRequestWrapper.ParsingStrategy {
private static final long serialVersionUID = 1L;
protected static DateFormat publicDateFormat = new SimpleDateFormat(
@ -60,14 +59,36 @@ public class VitroHttpServlet extends HttpServlet {
if ((req instanceof HttpServletRequest)
&& (resp instanceof HttpServletResponse)) {
HttpServletRequest hreq = (HttpServletRequest) req;
HttpServletResponse hresp = (HttpServletResponse) resp;
hreq = MultipartRequestWrapper.parse(hreq, this);
if (log.isTraceEnabled()) {
dumpRequestHeaders(hreq);
}
super.service(hreq, resp);
} else {
super.service(req, resp);
}
}
super.service(req, resp);
/**
* Override this to change the maximum size of uploaded files in multipart
* requests.
*/
@Override
public long maximumMultipartFileSize() {
return 50 * 1024 * 1024; // default is 50 megabytes
}
/**
* Override this to change the way that exceptions are handled when parsing
* a multipart request. Be aware that multipart parameters have been lost,
* and that may include form fields.
*/
@Override
public boolean stashFileSizeException() {
return false;
}
/**

View file

@ -3,12 +3,20 @@
package edu.cornell.mannlib.vitro.webapp.controller;
import static edu.cornell.mannlib.vitro.webapp.controller.MultipartRequestWrapper.ATTRIBUTE_FILE_ITEM_MAP;
import static edu.cornell.mannlib.vitro.webapp.controller.MultipartRequestWrapper.ATTRIBUTE_FILE_SIZE_EXCEPTION;
import static edu.cornell.mannlib.vitro.webapp.controller.MultipartRequestWrapper.ATTRIBUTE_IS_MULTIPART;
import java.text.Collator;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -231,4 +239,59 @@ public class VitroRequest extends HttpServletRequestWrapper {
public WebappDaoFactory getLanguageNeutralWebappDaoFactory() {
return (WebappDaoFactory) getAttribute("languageNeutralWebappDaoFactory");
}
// ----------------------------------------------------------------------
// Deal with parsed multipart requests.
// ----------------------------------------------------------------------
public boolean isMultipart() {
return getAttribute(ATTRIBUTE_IS_MULTIPART) != null;
}
@SuppressWarnings("unchecked")
public Map<String, List<FileItem>> getFiles() {
Map<String, List<FileItem>> map;
map = (Map<String, List<FileItem>>) getAttribute(ATTRIBUTE_FILE_ITEM_MAP);
if (map == null) {
return Collections.emptyMap();
} else {
return map;
}
}
/**
* There may be more than one file item with the given name. If the first
* one is empty (size is zero), keep looking for a non-empty one.
*/
public FileItem getFileItem(String name) {
Map<String, List<FileItem>> map = getFiles();
List<FileItem> items = map.get(name);
if (items == null) {
return null;
}
for (FileItem item : items) {
if (item.getSize() > 0L) {
return item;
}
}
return null;
}
/**
* If the uploaded file exceeded the maximum size, and if the strategy said
* to stash the exception, it will be stored as a request attribute.
*/
public boolean hasFileSizeException() {
return getFileSizeException() != null;
}
public FileSizeLimitExceededException getFileSizeException() {
Object e = getAttribute(ATTRIBUTE_FILE_SIZE_EXCEPTION);
if (e instanceof FileSizeLimitExceededException) {
return (FileSizeLimitExceededException) e;
} else {
return null;
}
}
}

View file

@ -41,7 +41,7 @@ public class DatapropEditController extends BaseEditController {
VitroRequest vreq = new VitroRequest(request);
final int NUM_COLS=17;
final int NUM_COLS=18;
String datapropURI = request.getParameter("uri");
@ -73,6 +73,7 @@ public class DatapropEditController extends BaseEditController {
results.add("display limit"); // column 15
results.add("custom entry form"); // column 16
results.add("URI"); // column 17
results.add("publish level"); // column 18
RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
@ -135,12 +136,16 @@ public class DatapropEditController extends BaseEditController {
String descriptionStr = (dp.getDescription() == null) ? "" : dp.getDescription(); // column 11
results.add(descriptionStr);
results.add(dp.getHiddenFromDisplayBelowRoleLevel() == null ? "(unspecified)" : dp.getHiddenFromDisplayBelowRoleLevel().getLabel()); // column 12
results.add(dp.getProhibitedFromUpdateBelowRoleLevel() == null ? "(unspecified)" : dp.getProhibitedFromUpdateBelowRoleLevel().getLabel()); // column 13
results.add(dp.getHiddenFromDisplayBelowRoleLevel() == null ? "(unspecified)"
: dp.getHiddenFromDisplayBelowRoleLevel().getDisplayLabel()); // column 12
results.add(dp.getProhibitedFromUpdateBelowRoleLevel() == null ? "(unspecified)"
: dp.getProhibitedFromUpdateBelowRoleLevel().getUpdateLabel()); // column 13
results.add(String.valueOf(dp.getDisplayTier())); // column 14
results.add(String.valueOf(dp.getDisplayLimit())); // column 15
results.add(dp.getCustomEntryForm() == null ? "(unspecified)" : dp.getCustomEntryForm()); // column 16
results.add(dp.getURI() == null ? "" : dp.getURI()); // column 17
results.add(dp.getHiddenFromPublishBelowRoleLevel() == null ? "(unspecified)"
: dp.getHiddenFromPublishBelowRoleLevel().getDisplayLabel()); // column 18
request.setAttribute("results",results);
request.setAttribute("columncount",NUM_COLS);
request.setAttribute("suppressquery","true");

View file

@ -166,6 +166,7 @@ public class DatapropRetryController extends BaseEditController {
optionMap.put("HiddenFromDisplayBelowRoleLevelUsingRoleUri",RoleLevelOptionsSetup.getDisplayOptionsList(objectForEditing));
optionMap.put("ProhibitedFromUpdateBelowRoleLevelUsingRoleUri",RoleLevelOptionsSetup.getUpdateOptionsList(objectForEditing));
optionMap.put("HiddenFromPublishBelowRoleLevelUsingRoleUri",RoleLevelOptionsSetup.getPublishOptionsList(objectForEditing));
foo.setOptionLists(optionMap);

View file

@ -81,6 +81,8 @@ public class EntityEditController extends BaseEditController {
colCount++;
results.add("URI");
colCount++;
results.add("publish level");
colCount++;
String rName = null;
if (ent.getName() != null && ent.getName().length() > 0) {
@ -116,12 +118,16 @@ public class EntityEditController extends BaseEditController {
}
results.add(classStr);
results.add(ent.getHiddenFromDisplayBelowRoleLevel() == null ? "unspecified" : ent.getHiddenFromDisplayBelowRoleLevel().getLabel());
results.add(ent.getProhibitedFromUpdateBelowRoleLevel() == null ? "unspecified" : ent.getProhibitedFromUpdateBelowRoleLevel().getLabel());
results.add(ent.getHiddenFromDisplayBelowRoleLevel() == null ? "unspecified"
: ent.getHiddenFromDisplayBelowRoleLevel().getDisplayLabel());
results.add(ent.getProhibitedFromUpdateBelowRoleLevel() == null ? "unspecified"
: ent.getProhibitedFromUpdateBelowRoleLevel().getUpdateLabel());
String rModTime = (ent.getModTime()==null) ? "" : publicDateFormat.format(ent.getModTime());
results.add(rModTime);
results.add( (ent.getURI() == null) ? "[anonymous individual]" : ent.getURI() );
results.add(ent.getHiddenFromPublishBelowRoleLevel() == null ? "unspecified"
: ent.getHiddenFromPublishBelowRoleLevel().getDisplayLabel());
request.setAttribute("results",results);
request.setAttribute("columncount", colCount);
request.setAttribute("suppressquery","true");

View file

@ -170,6 +170,7 @@ public class EntityRetryController extends BaseEditController {
hash.put("HiddenFromDisplayBelowRoleLevelUsingRoleUri",RoleLevelOptionsSetup.getDisplayOptionsList(individualForEditing));
hash.put("ProhibitedFromUpdateBelowRoleLevelUsingRoleUri",RoleLevelOptionsSetup.getUpdateOptionsList(individualForEditing));
hash.put("HiddenFromPublishBelowRoleLevelUsingRoleUri",RoleLevelOptionsSetup.getPublishOptionsList(individualForEditing));
FormObject foo = new FormObject();
foo.setOptionLists(hash);

View file

@ -6,7 +6,6 @@ import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
@ -21,17 +20,14 @@ import edu.cornell.mannlib.vedit.beans.FormObject;
import edu.cornell.mannlib.vedit.controller.BaseEditController;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.Ontology;
import edu.cornell.mannlib.vitro.webapp.beans.PropertyGroup;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.PropertyGroupDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao;
public class PropertyEditController extends BaseEditController {
@ -43,7 +39,7 @@ public class PropertyEditController extends BaseEditController {
return;
}
final int NUM_COLS=24;
final int NUM_COLS=25;
VitroRequest vreq = new VitroRequest(request);
@ -81,6 +77,7 @@ public class PropertyEditController extends BaseEditController {
results.add("offer create new"); // column 22
results.add("sort direction"); // column 23
results.add("URI"); // column 24
results.add("publish level"); // column 25
results.add(p.getPickListName()); // column 1
@ -169,8 +166,10 @@ public class PropertyEditController extends BaseEditController {
String descriptionStr = (p.getDescription() == null) ? "" : p.getDescription();
results.add(descriptionStr); // column 15
results.add(p.getHiddenFromDisplayBelowRoleLevel() == null ? "(unspecified)" : p.getHiddenFromDisplayBelowRoleLevel().getLabel()); // column 16
results.add(p.getProhibitedFromUpdateBelowRoleLevel() == null ? "(unspecified)" : p.getProhibitedFromUpdateBelowRoleLevel().getLabel()); // column 17
results.add(p.getHiddenFromDisplayBelowRoleLevel() == null ? "(unspecified)"
: p.getHiddenFromDisplayBelowRoleLevel().getDisplayLabel()); // column 16
results.add(p.getProhibitedFromUpdateBelowRoleLevel() == null ? "(unspecified)"
: p.getProhibitedFromUpdateBelowRoleLevel().getUpdateLabel()); // column 17
results.add("property: "+p.getDomainDisplayTier() + ", inverse: "+p.getRangeDisplayTier()); // column 18
@ -183,6 +182,8 @@ public class PropertyEditController extends BaseEditController {
results.add(p.getDomainEntitySortDirection() == null ? "ascending" : p.getDomainEntitySortDirection()); // column 23
results.add(p.getURI()); // column 24
results.add(p.getHiddenFromPublishBelowRoleLevel() == null ? "(unspecified)"
: p.getHiddenFromPublishBelowRoleLevel().getDisplayLabel()); // column 25
request.setAttribute("results",results);
request.setAttribute("columncount",NUM_COLS);
request.setAttribute("suppressquery","true");

View file

@ -151,6 +151,7 @@ public class PropertyRetryController extends BaseEditController {
optionMap.put("HiddenFromDisplayBelowRoleLevelUsingRoleUri",RoleLevelOptionsSetup.getDisplayOptionsList(propertyForEditing));
optionMap.put("ProhibitedFromUpdateBelowRoleLevelUsingRoleUri",RoleLevelOptionsSetup.getUpdateOptionsList(propertyForEditing));
optionMap.put("HiddenFromPublishBelowRoleLevelUsingRoleUri",RoleLevelOptionsSetup.getPublishOptionsList(propertyForEditing));
List groupOptList = FormUtils.makeOptionListFromBeans(request.getUnfilteredWebappDaoFactory().getPropertyGroupDao().getPublicGroups(true),"URI","Name", ((propertyForEditing.getGroupURI()==null) ? "" : propertyForEditing.getGroupURI()), null, (propertyForEditing.getGroupURI()!=null));
HashMap<String,Option> hashMap = new HashMap<String,Option>();

View file

@ -33,7 +33,7 @@ import edu.cornell.mannlib.vitro.webapp.beans.Ontology;
public class VclassEditController extends BaseEditController {
private static final Log log = LogFactory.getLog(VclassEditController.class.getName());
private static final int NUM_COLS = 13;
private static final int NUM_COLS = 14;
public void doPost (HttpServletRequest req, HttpServletResponse response) {
if (!isAuthorizedToDisplayPage(req, response, SimplePermission.EDIT_ONTOLOGY.ACTIONS)) {
@ -70,6 +70,7 @@ public class VclassEditController extends BaseEditController {
results.add("display rank"); // 11
results.add("custom entry form"); // 12
results.add("URI"); // 13
results.add("publish level"); // 14
String ontologyName = null;
if (vcl.getNamespace() != null) {
@ -107,8 +108,13 @@ public class VclassEditController extends BaseEditController {
commSb = new StringBuffer("no comments yet");
}
String hiddenFromDisplay = (vcl.getHiddenFromDisplayBelowRoleLevel() == null ? "(unspecified)" : vcl.getHiddenFromDisplayBelowRoleLevel().getLabel());
String ProhibitedFromUpdate = (vcl.getProhibitedFromUpdateBelowRoleLevel() == null ? "(unspecified)" : vcl.getProhibitedFromUpdateBelowRoleLevel().getLabel());
String hiddenFromDisplay = (vcl.getHiddenFromDisplayBelowRoleLevel() == null ? "(unspecified)"
: vcl.getHiddenFromDisplayBelowRoleLevel().getDisplayLabel());
String ProhibitedFromUpdate = (vcl
.getProhibitedFromUpdateBelowRoleLevel() == null ? "(unspecified)"
: vcl.getProhibitedFromUpdateBelowRoleLevel().getUpdateLabel());
String hiddenFromPublish = (vcl.getHiddenFromPublishBelowRoleLevel() == null ? "(unspecified)"
: vcl.getHiddenFromPublishBelowRoleLevel().getDisplayLabel());
String customEntryForm = (vcl.getCustomEntryForm() == null ? "(unspecified)" : vcl.getCustomEntryForm());
@ -130,6 +136,7 @@ public class VclassEditController extends BaseEditController {
results.add(String.valueOf(vcl.getDisplayRank())); // 11
results.add(customEntryForm); // 12
results.add(uri); // 13
results.add(hiddenFromPublish); // 14
request.setAttribute("results", results);
request.setAttribute("columncount", NUM_COLS);
request.setAttribute("suppressquery", "true");

View file

@ -147,6 +147,7 @@ public class VclassRetryController extends BaseEditController {
optionMap.put("HiddenFromDisplayBelowRoleLevelUsingRoleUri",RoleLevelOptionsSetup.getDisplayOptionsList(vclassForEditing));
optionMap.put("ProhibitedFromUpdateBelowRoleLevelUsingRoleUri",RoleLevelOptionsSetup.getUpdateOptionsList(vclassForEditing));
optionMap.put("HiddenFromPublishBelowRoleLevelUsingRoleUri",RoleLevelOptionsSetup.getPublishOptionsList(vclassForEditing));
FormObject foo = new FormObject();
foo.setErrorMap(epo.getErrMsgMap());

View file

@ -23,7 +23,7 @@ public class RoleLevelOptionsSetup {
boolean someLevelSet=false;
Option publicOption = null;
for (BaseResourceBean.RoleLevel level : roles) {
Option option = new Option (level.getURI(),level.getLabel(),false);
Option option = new Option (level.getURI(),level.getDisplayLabel(),false);
if (level==BaseResourceBean.RoleLevel.PUBLIC) {
publicOption = option;
}
@ -50,7 +50,7 @@ public class RoleLevelOptionsSetup {
boolean someLevelSet=false;
Option publicOption = null;
for (BaseResourceBean.RoleLevel level : roles) {
Option option = new Option (level.getURI(),level.getLabel(),false);
Option option = new Option (level.getURI(),level.getUpdateLabel(),false);
if (level==BaseResourceBean.RoleLevel.PUBLIC) {
publicOption = option;
}
@ -68,4 +68,33 @@ public class RoleLevelOptionsSetup {
}
return prohibitedFromUpdateList;
}
public static List<Option> getPublishOptionsList(ResourceBean b) {
List<Option> hiddenFromPublishList = new LinkedList<Option>();
try {
BaseResourceBean.RoleLevel currentLevel = b.getHiddenFromPublishBelowRoleLevel();
BaseResourceBean.RoleLevel roles[] = BaseResourceBean.RoleLevel.values();
boolean someLevelSet=false;
Option publicOption = null;
for (BaseResourceBean.RoleLevel level : roles) {
Option option = new Option (level.getURI(),level.getDisplayLabel(),false);
if (level==BaseResourceBean.RoleLevel.PUBLIC) {
publicOption = option;
}
if (level==currentLevel) {
option.setSelected(true);
someLevelSet=true;
}
hiddenFromPublishList.add(option);
}
if (!someLevelSet) {
publicOption.setSelected(true);
}
} catch (Exception ex) {
log.error("cannot create HiddenFromPublishBelowRoleLevel options");
}
return hiddenFromPublishList;
}
}

View file

@ -66,7 +66,6 @@ public class BaseSiteAdminController extends FreemarkerHttpServlet {
if (PolicyHelper.isAuthorizedForActions(vreq, SimplePermission.USE_MISCELLANEOUS_ADMIN_PAGES.ACTIONS)) {
urls.put("recomputeInferences", UrlBuilder.getUrl("/RecomputeInferences"));
urls.put("rebuildClassGroupCache", UrlBuilder.getUrl("/browse?clearcache=1"));
}
if (PolicyHelper.isAuthorizedForActions(vreq, IndexController.REQUIRED_ACTIONS)) {
@ -78,7 +77,7 @@ public class BaseSiteAdminController extends FreemarkerHttpServlet {
}
if (PolicyHelper.isAuthorizedForActions(vreq, SimplePermission.ENABLE_DEVELOPER_PANEL.ACTIONS)) {
urls.put("activateDeveloperPanel", "javascript:new DeveloperPanel(developerAjaxUrl).setupDeveloperPanel({developerEnabled: true});");
urls.put("activateDeveloperPanel", "javascript:new DeveloperPanel(developerAjaxUrl).setupDeveloperPanel({developer_enabled: true});");
}
return urls;

View file

@ -10,9 +10,6 @@ import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.auth.policy.PolicyHelper;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.Actions;
import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
@ -33,29 +30,12 @@ public class BrowseController extends FreemarkerHttpServlet {
return "Index of Contents";
}
@Override
protected Actions requiredActions(VitroRequest vreq) {
if ( vreq.getParameter("clearcache") != null )
return SimplePermission.REBUILD_VCLASS_GROUP_CACHE.ACTIONS;
else
return Actions.AUTHORIZED;
}
@Override
protected ResponseValues processRequest(VitroRequest vreq) {
Map<String, Object> body = new HashMap<String, Object>();
String templateName = TEMPLATE_DEFAULT;
if ( vreq.getParameter("clearcache") != null ) {
//mainly for debugging
if( PolicyHelper.isAuthorizedForActions(vreq, SimplePermission.REBUILD_VCLASS_GROUP_CACHE.ACTIONS) ){
clearGroupCache();
}
}
List<VClassGroup> groups = null;
VClassGroupsForRequest vcgc = VClassGroupCache.getVClassGroups(vreq);
groups =vcgc.getGroups();
@ -67,8 +47,4 @@ public class BrowseController extends FreemarkerHttpServlet {
return new TemplateResponseValues(templateName, body);
}
protected void clearGroupCache(){
VClassGroupCache.getVClassGroupCache(getServletContext()).doSynchronousRebuild();
}
}

View file

@ -2,12 +2,6 @@
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServletRequest;
@ -36,7 +30,6 @@ import edu.cornell.mannlib.vitro.webapp.filestorage.backend.FileStorage;
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.ImageInfo;
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;
@ -52,6 +45,7 @@ public class ImageUploadController extends FreemarkerHttpServlet {
private static final String ERROR_CODE_UNRECOGNIZED_URI = "imageUpload.errorUnrecognizedURI";
private static final String ERROR_CODE_NO_URI = "imageUpload.errorNoURI";
private static final String ERROR_CODE_FILE_TOO_BIG = "imageUpload.errorFileTooBig";
/** Limit file size to 6 megabytes. */
public static final int MAXIMUM_FILE_SIZE = 6 * 1024 * 1024;
@ -137,6 +131,22 @@ public class ImageUploadController extends FreemarkerHttpServlet {
}
}
/**
* How large an image file will we accept?
*/
@Override
public long maximumMultipartFileSize() {
return MAXIMUM_FILE_SIZE;
}
/**
* What will we do if there is a problem parsing the request?
*/
@Override
public boolean stashFileSizeException() {
return true;
}
/**
* The required action depends on what we are trying to do.
*/
@ -171,52 +181,17 @@ public class ImageUploadController extends FreemarkerHttpServlet {
}
}
/**
* <p>
* Parse the multi-part request, process the request, and produce the
* output.
* </p>
* <p>
* If the request was a multi-part file upload, it will parse to a
* normal-looking request with a "file_item_map" attribute.
* </p>
* <p>
* The processing will produce a {@link ResponseValues} object, which
* represents either a request for a FreeMarker template or a forwarding
* operation.
* <ul>
* <li>If a FreeMarker template, we emulate the actions that
* FreeMarkerHttpServlet would have taken to produce the output.</li>
* <li>If a forwarding operation, we create a {@link RequestDispatcher} to
* do the forwarding.</li>
* </ul>
* </p>
*/
@Override
protected ResponseValues processRequest(VitroRequest vreq) {
try {
// Parse the multi-part request.
FileUploadServletRequest.parseRequest(vreq, MAXIMUM_FILE_SIZE);
if (log.isTraceEnabled()) {
dumpRequestDetails(vreq);
}
return buildTheResponse(vreq);
} catch (Exception e) {
// log.error("Could not produce response page", e);
return new ExceptionResponseValues(e);
}
}
/**
* Handle the different actions. If not specified, the default action is to
* show the intro screen.
*/
private ResponseValues buildTheResponse(VitroRequest vreq) {
@Override
protected ResponseValues processRequest(VitroRequest vreq) {
try {
checkForFileTooBigException(vreq);
String action = vreq.getParameter(PARAMETER_ACTION);
try {
Individual entity = validateEntityUri(vreq);
if (ACTION_UPLOAD.equals(action)) {
return doUploadImage(vreq, entity);
@ -240,6 +215,19 @@ public class ImageUploadController extends FreemarkerHttpServlet {
}
}
/**
* If our exception handler caught a "file too big" exception, we need to
* deal with it before anything else, since we can't trust the other
* parameters.
*/
private void checkForFileTooBigException(VitroRequest vreq)
throws UserMistakeException {
if (vreq.hasFileSizeException()) {
int limit = MAXIMUM_FILE_SIZE / (1024 * 1024);
throw new UserMistakeException(ERROR_CODE_FILE_TOO_BIG, limit);
}
}
/**
* We are just starting the upload process. Record where we came from, so if
* they hit "cancel" we know where to send them. If we have problems, just
@ -626,31 +614,6 @@ public class ImageUploadController extends FreemarkerHttpServlet {
}
/**
* For debugging, dump all sorts of information about the request.
*
* WARNING: if "req" represents a Multi-part request which has not yet been
* parsed, then reading these parameters will consume them.
*/
@SuppressWarnings("unchecked")
private void dumpRequestDetails(HttpServletRequest req) {
log.trace("Request is " + req.getClass().getName());
Map<String, String[]> parms = req.getParameterMap();
for (Entry<String, String[]> entry : parms.entrySet()) {
log.trace("Parameter '" + entry.getKey() + "'="
+ Arrays.deepToString(entry.getValue()));
}
Enumeration<String> attrs = req.getAttributeNames();
while (attrs.hasMoreElements()) {
String key = attrs.nextElement();
String valueString = String.valueOf(req.getAttribute(key));
String valueOneLine = valueString.replace("\n", " | ");
log.trace("Attribute '" + key + "'=" + valueOneLine);
}
}
static class Dimensions {
final int width;
final int height;

View file

@ -2,12 +2,9 @@
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
import static edu.cornell.mannlib.vitro.webapp.controller.freemarker.ImageUploadController.MAXIMUM_FILE_SIZE;
import static edu.cornell.mannlib.vitro.webapp.controller.freemarker.ImageUploadController.PARAMETER_UPLOADED_FILE;
import static edu.cornell.mannlib.vitro.webapp.controller.freemarker.ImageUploadController.THUMBNAIL_HEIGHT;
import static edu.cornell.mannlib.vitro.webapp.controller.freemarker.ImageUploadController.THUMBNAIL_WIDTH;
import static edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.FileUploadServletRequest.FILE_ITEM_MAP;
import static edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.FileUploadServletRequest.FILE_UPLOAD_EXCEPTION;
import java.io.FileNotFoundException;
import java.io.IOException;
@ -21,7 +18,6 @@ import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;
import javax.media.jai.util.ImagingListener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FilenameUtils;
@ -41,7 +37,6 @@ import edu.cornell.mannlib.vitro.webapp.filestorage.UploadedFileHelper;
import edu.cornell.mannlib.vitro.webapp.filestorage.backend.FileAlreadyExistsException;
import edu.cornell.mannlib.vitro.webapp.filestorage.backend.FileStorage;
import edu.cornell.mannlib.vitro.webapp.filestorage.model.FileInfo;
import edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.FileUploadServletRequest;
/**
* Handle the mechanics of validating, storing, and deleting file images.
@ -55,7 +50,6 @@ public class ImageUploadHelper {
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";
@ -133,20 +127,13 @@ public class ImageUploadHelper {
* if there is no file, if it is empty, or if it is not an image
* file.
*/
@SuppressWarnings("unchecked")
FileItem validateImageFromRequest(HttpServletRequest request)
FileItem validateImageFromRequest(VitroRequest vreq)
throws UserMistakeException {
Object exception = request.getAttribute(FILE_UPLOAD_EXCEPTION);
if (exception != null) {
int limit = MAXIMUM_FILE_SIZE / (1024 * 1024);
throw new UserMistakeException(ERROR_CODE_FILE_TOO_BIG, limit);
}
Map<String, List<FileItem>> map = (Map<String, List<FileItem>>) request
.getAttribute(FILE_ITEM_MAP);
Map<String, List<FileItem>> map = vreq.getFiles();
if (map == null) {
throw new IllegalStateException(ERROR_CODE_BAD_MULTIPART_REQUEST);
}
List<FileItem> list = map.get(PARAMETER_UPLOADED_FILE);
if ((list == null) || list.isEmpty()) {
throw new UserMistakeException(ERROR_CODE_FORM_FIELD_MISSING,

View file

@ -2,6 +2,7 @@
package edu.cornell.mannlib.vitro.webapp.controller.individual;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
@ -28,13 +29,11 @@ import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;
import edu.cornell.mannlib.vitro.webapp.auth.policy.PolicyHelper;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayDataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.publish.PublishDataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.publish.PublishObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatementImpl;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatementImpl;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.RdfResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
@ -61,7 +60,7 @@ import edu.cornell.mannlib.vitro.webapp.web.ContentType;
* Otherwise, show all triples, regardless of language.
*
* Filter the result based on the policy, removing any triples that should not
* be displayed to the public (or to the user, if logged in). Also remove any
* be published to the public (or to the user, if logged in). Also remove any
* objects which can only be reached by excluded triples.
*
* ----------------
@ -104,7 +103,6 @@ public class IndividualRdfAssembler {
this.individualUri = individualUri;
this.rdfFormat = rdfFormat;
String[] includes = vreq.getParameterValues("include");
this.richExportIncludes = (includes == null) ? new String[0] : includes;
@ -150,6 +148,11 @@ public class IndividualRdfAssembler {
m.add(runConstructQuery(String.format(
"CONSTRUCT { ?s ?predicate <%1$s> . } "
+ "WHERE { ?s ?predicate <%1$s> } ", individualUri)));
if (log.isDebugEnabled()) {
StringWriter sw = new StringWriter();
m.write(sw);
log.debug("Statements about '" + individualUri + "': " + sw);
}
return m;
}
@ -166,6 +169,16 @@ public class IndividualRdfAssembler {
+ "WHERE { <%1$s> ?predicate ?object ."
+ " ?object <%2$s> ?label . } ", individualUri,
RDFS.label)));
m.add(runConstructQuery(String.format(
"CONSTRUCT { ?subject <%2$s> ?type . } "
+ "WHERE { ?subject ?predicate <%1$s> ."
+ " ?subject <%2$s> ?type . } ", individualUri,
RDF.type)));
m.add(runConstructQuery(String.format(
"CONSTRUCT { ?subject <%2$s> ?label . } "
+ "WHERE { ?subject ?predicate <%1$s> ."
+ " ?subject <%2$s> ?label . } ", individualUri,
RDFS.label)));
return m;
}
@ -192,18 +205,17 @@ public class IndividualRdfAssembler {
String value = stmt.getObject().asLiteral().getString();
DataPropertyStatement dps = new DataPropertyStatementImpl(
subjectUri, predicateUri, value);
RequestedAction ddps = new DisplayDataPropertyStatement(dps);
if (!PolicyHelper.isAuthorizedForActions(vreq, ddps)) {
log.debug("not authorized: " + ddps);
RequestedAction pdps = new PublishDataPropertyStatement(o, dps);
if (!PolicyHelper.isAuthorizedForActions(vreq, pdps)) {
log.debug("not authorized: " + pdps);
stmts.remove();
}
} else if (stmt.getObject().isURIResource()) {
String objectUri = stmt.getObject().asResource().getURI();
ObjectPropertyStatement ops = new ObjectPropertyStatementImpl(
RequestedAction pops = new PublishObjectPropertyStatement(o,
subjectUri, predicateUri, objectUri);
RequestedAction dops = new DisplayObjectPropertyStatement(ops);
if (!PolicyHelper.isAuthorizedForActions(vreq, dops)) {
log.debug("not authorized: " + dops);
if (!PolicyHelper.isAuthorizedForActions(vreq, pops)) {
log.debug("not authorized: " + pops);
stmts.remove();
}
} else {

View file

@ -25,7 +25,6 @@ import com.hp.hpl.jena.rdf.model.ModelMaker;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.FileUploadServletRequest;
import edu.cornell.mannlib.vitro.webapp.utils.Csv2Rdf;
import edu.cornell.mannlib.vitro.webapp.utils.jena.JenaIngestUtils;
@ -37,6 +36,17 @@ public class JenaCsv2RdfController extends JenaIngestController {
private static final String CSV2RDF_SELECT_URI_JSP = "/jenaIngest/csv2rdfSelectUri.jsp";
private static int maxFileSizeInBytes = 1024 * 1024 * 2000; //2000mb
@Override
public long maximumMultipartFileSize() {
return maxFileSizeInBytes;
}
@Override
public boolean stashFileSizeException() {
return true;
}
@Override
public void doPost(HttpServletRequest rawRequest,
HttpServletResponse response) throws ServletException, IOException {
@ -45,15 +55,13 @@ public class JenaCsv2RdfController extends JenaIngestController {
return;
}
FileUploadServletRequest req = FileUploadServletRequest.parseRequest(rawRequest,
maxFileSizeInBytes);
if (req.hasFileUploadException()) {
forwardToFileUploadError(req.getFileUploadException().getLocalizedMessage(), req, response);
VitroRequest request = new VitroRequest(rawRequest);
if (request.hasFileSizeException()) {
forwardToFileUploadError(request.getFileSizeException().getLocalizedMessage(), request, response);
return;
}
VitroRequest request = new VitroRequest(req);
Map<String, List<FileItem>> fileStreams = req.getFiles();
Map<String, List<FileItem>> fileStreams = request.getFiles();
FileItem fileStream = fileStreams.get("filePath").get(0);
String filePath = fileStreams.get("filePath").get(0).getName();
@ -70,7 +78,7 @@ public class JenaCsv2RdfController extends JenaIngestController {
csv2rdfResult = doExecuteCsv2Rdf(
request, fileStream, filePath);
}catch(Exception ex){
forwardToFileUploadError(ex.getMessage(),req,response);
forwardToFileUploadError(ex.getMessage(),request,response);
return;
}
ModelMaker maker = getVitroJenaModelMaker(request);

View file

@ -36,7 +36,6 @@ import com.hp.hpl.jena.shared.Lock;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.FileUploadServletRequest;
public class JenaXMLFileUpload extends JenaIngestController {
Log log = LogFactory.getLog(JenaXMLFileUpload.class);
@ -76,6 +75,16 @@ public class JenaXMLFileUpload extends JenaIngestController {
}
}
@Override
public long maximumMultipartFileSize() {
return maxFileSize;
}
@Override
public boolean stashFileSizeException() {
return true;
}
/**
* Each file will be converted to RDF/XML and loaded to the target model.
* If any of the files fail, no data will be loaded.
@ -86,14 +95,14 @@ public class JenaXMLFileUpload extends JenaIngestController {
*
*/
@Override
public void doPost(HttpServletRequest rawRequest, HttpServletResponse resp)
public void doPost(HttpServletRequest request, HttpServletResponse resp)
throws ServletException, IOException {
FileUploadServletRequest request = FileUploadServletRequest.parseRequest(rawRequest, maxFileSize);
if (request.hasFileUploadException()) {
VitroRequest vreq = new VitroRequest(request);
if (vreq.hasFileSizeException()) {
throw new ServletException("Size limit exceeded: "
+ request.getFileUploadException().getLocalizedMessage());
+ vreq.getFileSizeException().getLocalizedMessage());
}
if (request.isMultipart()) {
if (vreq.isMultipart()) {
log.debug("multipart content detected");
} else {
// TODO: forward to error message
@ -105,7 +114,6 @@ public class JenaXMLFileUpload extends JenaIngestController {
return;
}
VitroRequest vreq = new VitroRequest(request);
ModelMaker modelMaker = getVitroJenaModelMaker(vreq);
String targetModel = request.getParameter("targetModel");
if (targetModel == null) {
@ -117,7 +125,7 @@ public class JenaXMLFileUpload extends JenaIngestController {
throw new ServletException("targetModel '" + targetModel + "' was not found.");
request.setAttribute("targetModel", targetModel);
List<File> filesToLoad = saveFiles( request.getFiles() );
List<File> filesToLoad = saveFiles( vreq.getFiles() );
List<File> rdfxmlToLoad = convertFiles( filesToLoad);
List<Model> modelsToLoad = loadRdfXml( rdfxmlToLoad );
@ -136,7 +144,7 @@ public class JenaXMLFileUpload extends JenaIngestController {
request.setAttribute("title","Uploaded files and converted to RDF");
request.setAttribute("bodyJsp","/jenaIngest/xmlFileUploadSuccess.jsp");
request.setAttribute("fileItems",request.getFiles());
request.setAttribute("fileItems",vreq.getFiles());
RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
request.setAttribute("css", "<link rel=\"stylesheet\" type=\"text/css\" href=\""+vreq.getAppBean().getThemeDir()+"css/edit.css\"/>");

View file

@ -42,7 +42,6 @@ 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.event.BulkUpdateEvent;
import edu.cornell.mannlib.vitro.webapp.dao.jena.event.EditEvent;
import edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.FileUploadServletRequest;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeSet;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFServiceException;
@ -56,31 +55,39 @@ public class RDFUploadController extends JenaIngestController {
private static FileItem fileStream = null;
private static final String LOAD_RDF_DATA_JSP="/jenaIngest/loadRDFData.jsp";
public void doPost(HttpServletRequest rawRequest,
@Override
public long maximumMultipartFileSize() {
return maxFileSizeInBytes;
}
@Override
public boolean stashFileSizeException() {
return true;
}
public void doPost(HttpServletRequest req,
HttpServletResponse response) throws ServletException, IOException {
if (!isAuthorizedToDisplayPage(rawRequest, response,
if (!isAuthorizedToDisplayPage(req, response,
SimplePermission.USE_ADVANCED_DATA_TOOLS_PAGES.ACTIONS)) {
return;
}
FileUploadServletRequest req = FileUploadServletRequest.parseRequest(
rawRequest, maxFileSizeInBytes);
if (req.hasFileUploadException()) {
VitroRequest request = new VitroRequest(req);
if (request.hasFileSizeException()) {
forwardToFileUploadError(
req.getFileUploadException().getLocalizedMessage(),
request.getFileSizeException().getLocalizedMessage(),
req, response);
return;
}
Map<String, List<FileItem>> fileStreams = req.getFiles();
Map<String, List<FileItem>> fileStreams = request.getFiles();
VitroRequest request = new VitroRequest(req);
LoginStatusBean loginBean = LoginStatusBean.getBean(request);
try {
String modelName = req.getParameter("modelName");
if(modelName!=null){
loadRDF(req,request,response);
loadRDF(request,response);
return;
}
} catch (Exception e) {
@ -234,15 +241,13 @@ public class RDFUploadController extends JenaIngestController {
}
}
public void loadRDF(FileUploadServletRequest req,
VitroRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Map<String, List<FileItem>> fileStreams = req.getFiles();
public void loadRDF(VitroRequest request, HttpServletResponse response)
throws ServletException {
Map<String, List<FileItem>> fileStreams = request.getFiles();
String filePath = fileStreams.get("filePath").get(0).getName();
fileStream = fileStreams.get("filePath").get(0);
String modelName = req.getParameter("modelName");
String docLoc = req.getParameter("docLoc");
String modelName = request.getParameter("modelName");
String docLoc = request.getParameter("docLoc");
String languageStr = request.getParameter("language");
ModelMaker maker = getVitroJenaModelMaker(request);

View file

@ -51,7 +51,7 @@ public abstract class JsonObjectProducer extends JsonProducer {
try {
jsonObject = process();
} catch (Exception e) {
log.error("Failed to create JSON response" + e);
log.error("Failed to create JSON response", e);
errorMessage = e.toString();
resp.setStatus(500 /* HttpURLConnection.HTTP_SERVER_ERROR */);
}

View file

@ -80,7 +80,7 @@ public abstract class JsonProducer {
VClass vclass = vreq.getWebappDaoFactory().getVClassDao()
.getVClassByURI(uri);
if (vclass == null) {
log.error("Couldn't retrieve vclass ");
log.error("Couldn't retrieve vclass '" + uri + "'");
throw new IllegalStateException("Class " + uri + " not found");
}
return vclass;

View file

@ -37,8 +37,8 @@ public class VClassGroupsForRequest {
}
if (log.isDebugEnabled()) {
log.debug("groups: " + groupMap);
log.debug("classes: " + classMap);
log.debug("groups: " + groupMap.values());
log.debug("classes: " + classMap.values());
}
}
@ -59,7 +59,7 @@ public class VClassGroupsForRequest {
}
private void loadClass(VClass vc, VClassGroup newVcg) {
VClass newVc = new VClass(vc);
VClass newVc = vc.copy();
newVc.setName(getNameForVClass(vc));
newVc.setGroup(newVcg);
newVcg.add(newVc);

View file

@ -54,10 +54,8 @@ public class VitroVocabulary {
public static final String DATAPROPERTY_ISEXTERNALID = vitroURI+"isExternalId";
public static final String HIDDEN_FROM_DISPLAY_BELOW_ROLE_LEVEL_ANNOT = vitroURI+"hiddenFromDisplayBelowRoleLevelAnnot";
//public static final String PROHIBITED_FROM_CREATE_BELOW_ROLE_LEVEL_ANNOT = vitroURI+"prohibitedFromCreateBelowRoleLevelAnnot";
public static final String PROHIBITED_FROM_UPDATE_BELOW_ROLE_LEVEL_ANNOT = vitroURI+"prohibitedFromUpdateBelowRoleLevelAnnot";
//public static final String PROHIBITED_FROM_DELETE_BELOW_ROLE_LEVEL_ANNOT = vitroURI+"prohibitedFromDeleteBelowRoleLevelAnnot";
public static final String HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT = vitroURI+"hiddenFromPublishBelowRoleLevelAnnot";
public static final String MOST_SPECIFIC_TYPE = vitroURI + "mostSpecificType";

View file

@ -101,6 +101,11 @@ public class DataPropertyFiltering extends DataProperty {
return innerDataProperty.getProhibitedFromUpdateBelowRoleLevel();
}
@Override
public RoleLevel getHiddenFromPublishBelowRoleLevel() {
return innerDataProperty.getHiddenFromPublishBelowRoleLevel();
}
@Override
public String getLocalName() {
return innerDataProperty.getLocalName();
@ -196,6 +201,16 @@ public class DataPropertyFiltering extends DataProperty {
innerDataProperty.setProhibitedFromUpdateBelowRoleLevel(BaseResourceBean.RoleLevel.getRoleByUri(roleUri));
}
@Override
public void setHiddenFromPublishBelowRoleLevel(RoleLevel eR) {
innerDataProperty.setHiddenFromPublishBelowRoleLevel(eR);
}
@Override
public void setHiddenFromPublishBelowRoleLevelUsingRoleUri(String roleUri) {
innerDataProperty.setHiddenFromPublishBelowRoleLevel(BaseResourceBean.RoleLevel.getRoleByUri(roleUri));
}
@Override
public void setLocalName(String localName) {
innerDataProperty.setLocalName(localName);

View file

@ -449,6 +449,21 @@ public class IndividualFiltering implements Individual {
_innerIndividual.setProhibitedFromUpdateBelowRoleLevel(BaseResourceBean.RoleLevel.getRoleByUri(roleUri));
}
@Override
public RoleLevel getHiddenFromPublishBelowRoleLevel() {
return _innerIndividual.getHiddenFromPublishBelowRoleLevel();
}
@Override
public void setHiddenFromPublishBelowRoleLevel(RoleLevel eR) {
_innerIndividual.setHiddenFromPublishBelowRoleLevel(eR);
}
@Override
public void setHiddenFromPublishBelowRoleLevelUsingRoleUri(String roleUri) {
_innerIndividual.setHiddenFromPublishBelowRoleLevel(BaseResourceBean.RoleLevel.getRoleByUri(roleUri));
}
@Override
public boolean isAnonymous() {
return _innerIndividual.isAnonymous();

View file

@ -140,6 +140,11 @@ public class ObjectPropertyFiltering extends ObjectProperty {
return innerObjectProperty.getProhibitedFromUpdateBelowRoleLevel();
}
@Override
public RoleLevel getHiddenFromPublishBelowRoleLevel() {
return innerObjectProperty.getHiddenFromPublishBelowRoleLevel();
}
@Override
public boolean getInverseFunctional() {
return innerObjectProperty.getInverseFunctional();
@ -368,6 +373,16 @@ public class ObjectPropertyFiltering extends ObjectProperty {
innerObjectProperty.setProhibitedFromUpdateBelowRoleLevel(BaseResourceBean.RoleLevel.getRoleByUri(roleUri));
}
@Override
public void setHiddenFromPublishBelowRoleLevel(RoleLevel eR) {
innerObjectProperty.setHiddenFromPublishBelowRoleLevel(eR);
}
@Override
public void setHiddenFromPublishBelowRoleLevelUsingRoleUri(String roleUri) {
innerObjectProperty.setHiddenFromPublishBelowRoleLevel(BaseResourceBean.RoleLevel.getRoleByUri(roleUri));
}
@Override
public void setInverseFunctional(boolean inverseFunctional) {
innerObjectProperty.setInverseFunctional(inverseFunctional);

View file

@ -20,11 +20,13 @@ import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayData
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayDataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayObjectProperty;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestActionConstants;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
/**
* Filter the properties depending on what DisplayByRolePermission is on the
@ -117,7 +119,30 @@ public class FilterByRoleLevelPermission extends VitroFiltersImpl {
UnaryFunctor<ObjectPropertyStatement, Boolean> {
@Override
public Boolean fn(ObjectPropertyStatement ops) {
return checkAuthorization(new DisplayObjectPropertyStatement(ops));
String subjectUri = ops.getSubjectURI();
ObjectProperty predicate = getOrCreateProperty(ops);
String objectUri = ops.getObjectURI();
return checkAuthorization(new DisplayObjectPropertyStatement(
subjectUri, predicate, objectUri));
}
/**
* It would be nice if every ObjectPropertyStatement held a real
* ObjectProperty. If it doesn't, we do the next best thing, but it
* won't recognize any applicaable Faux properties.
*/
private ObjectProperty getOrCreateProperty(ObjectPropertyStatement ops) {
if (ops.getProperty() != null) {
return ops.getProperty();
}
if (ops.getPropertyURI() == null) {
return null;
}
ObjectProperty op = new ObjectProperty();
op.setURI(ops.getPropertyURI());
op.setDomainVClassURI(RequestActionConstants.SOME_URI);
op.setRangeVClassURI(RequestActionConstants.SOME_URI);
return op;
}
}

View file

@ -14,6 +14,7 @@ import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayData
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayDataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayObjectProperty;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestActionConstants;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
@ -88,7 +89,31 @@ public class HideFromDisplayByPolicyFilter extends VitroFiltersImpl {
UnaryFunctor<ObjectPropertyStatement, Boolean> {
@Override
public Boolean fn(ObjectPropertyStatement ops) {
return checkAuthorization(new DisplayObjectPropertyStatement(ops));
}
String subjectUri = ops.getSubjectURI();
ObjectProperty predicate = getOrCreateProperty(ops);
String objectUri = ops.getObjectURI();
return checkAuthorization(new DisplayObjectPropertyStatement(
subjectUri, predicate, objectUri));
}
/**
* It would be nice if every ObjectPropertyStatement held a real
* ObjectProperty. If it doesn't, we do the next best thing, but it
* won't recognize any applicaable Faux properties.
*/
private ObjectProperty getOrCreateProperty(ObjectPropertyStatement ops) {
if (ops.getProperty() != null) {
return ops.getProperty();
}
if (ops.getPropertyURI() == null) {
return null;
}
ObjectProperty op = new ObjectProperty();
op.setURI(ops.getPropertyURI());
op.setDomainVClassURI(RequestActionConstants.SOME_URI);
op.setRangeVClassURI(RequestActionConstants.SOME_URI);
return op;
}
}
}

View file

@ -235,6 +235,26 @@ public class DataPropertyDaoJena extends PropertyDaoJena implements
}
}
dp.setProhibitedFromUpdateBelowRoleLevel(prohibitedRoleLevel);//this might get set to null
//There might be multiple HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT properties, only use the highest
it = op.listProperties(HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT);
BaseResourceBean.RoleLevel publishRoleLevel = null;
while( it.hasNext() ){
Statement stmt = it.nextStatement();
RDFNode obj;
if( stmt != null && (obj = stmt.getObject()) != null && obj.isURIResource() ){
Resource res = obj.as(Resource.class);
if( res != null && res.getURI() != null ){
BaseResourceBean.RoleLevel roleFromModel = BaseResourceBean.RoleLevel.getRoleByUri(res.getURI());
if( roleFromModel != null &&
(publishRoleLevel == null || roleFromModel.compareTo(publishRoleLevel) > 0 )){
publishRoleLevel = roleFromModel;
}
}
}
}
dp.setHiddenFromPublishBelowRoleLevel(publishRoleLevel);//this might get set to null
dp.setCustomEntryForm(getPropertyStringValue(op,PROPERTY_CUSTOMENTRYFORMANNOT));
dp.setExternalId( getOntModelSelector().getTBoxModel().contains(op, DATAPROPERTY_ISEXTERNALID, "TRUE") );
@ -504,6 +524,10 @@ public class DataPropertyDaoJena extends PropertyDaoJena implements
if (PROHIBITED_FROM_UPDATE_BELOW_ROLE_LEVEL_ANNOT != null && dtp.getProhibitedFromUpdateBelowRoleLevel() != null) { // only need to add if present
jDataprop.addProperty(PROHIBITED_FROM_UPDATE_BELOW_ROLE_LEVEL_ANNOT, ResourceFactory.createResource(dtp.getProhibitedFromUpdateBelowRoleLevel().getURI()));
}
jDataprop.removeAll(HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT);
if (HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT != null && dtp.getHiddenFromPublishBelowRoleLevel() != null) { // only need to add if present
jDataprop.addProperty(HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT, ResourceFactory.createResource(dtp.getHiddenFromPublishBelowRoleLevel().getURI()));
}
/*
if (dtp.isSelfEditProhibited()) { // only add the property if it's true
addPropertyBooleanValue(jDataprop, PROPERTY_SELFEDITPROHIBITEDANNOT, dtp.isSelfEditProhibited(), ontModel);
@ -570,6 +594,10 @@ public class DataPropertyDaoJena extends PropertyDaoJena implements
updatePropertyResourceURIValue(jDataprop,PROHIBITED_FROM_UPDATE_BELOW_ROLE_LEVEL_ANNOT,dtp.getProhibitedFromUpdateBelowRoleLevel().getURI(),ontModel);
}
if (dtp.getHiddenFromPublishBelowRoleLevel() != null) {
updatePropertyResourceURIValue(jDataprop,HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT,dtp.getHiddenFromPublishBelowRoleLevel().getURI(),ontModel);
}
if (dtp.getGroupURI() != null) {
updatePropertyResourceURIValue(jDataprop,PROPERTY_INPROPERTYGROUPANNOT,dtp.getGroupURI(),ontModel);
}

View file

@ -43,6 +43,7 @@ public class JenaBaseDaoCon {
protected AnnotationProperty HIDDEN_FROM_DISPLAY_BELOW_ROLE_LEVEL_ANNOT = _constModel.createAnnotationProperty(VitroVocabulary.HIDDEN_FROM_DISPLAY_BELOW_ROLE_LEVEL_ANNOT);
protected AnnotationProperty PROHIBITED_FROM_UPDATE_BELOW_ROLE_LEVEL_ANNOT = _constModel.createAnnotationProperty(VitroVocabulary.PROHIBITED_FROM_UPDATE_BELOW_ROLE_LEVEL_ANNOT);
protected AnnotationProperty HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT = _constModel.createAnnotationProperty(VitroVocabulary.HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT);
protected AnnotationProperty SEARCH_BOOST_ANNOT = _constModel.createAnnotationProperty(VitroVocabulary.SEARCH_BOOST_ANNOT);

View file

@ -190,7 +190,7 @@ public class JenaModelUtils {
// Perform possibly-redundant extraction to try ensure we don't miss
// individual axioms floating around. We still might miss things;
// this approach isn't perfect.
if (mode = AGGRESSIVE) {
if (mode == AGGRESSIVE) {
tboxModel.add(construct(dataset, namespace, graphURI, RDFS.subClassOf));
tboxModel.add(construct(dataset, namespace, graphURI, RDFS.subPropertyOf));
tboxModel.add(construct(dataset, namespace, graphURI, OWL.equivalentClass));
@ -219,6 +219,8 @@ public class JenaModelUtils {
VitroVocabulary.PROHIBITED_FROM_UPDATE_BELOW_ROLE_LEVEL_ANNOT)));
tboxModel.add(construct(dataset, namespace, graphURI, ResourceFactory.createResource(
VitroVocabulary.HIDDEN_FROM_DISPLAY_BELOW_ROLE_LEVEL_ANNOT)));
tboxModel.add(construct(dataset, namespace, graphURI, ResourceFactory.createResource(
VitroVocabulary.HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT)));
tboxModel.add(construct(dataset, namespace, graphURI, ResourceFactory.createResource(
VitroVocabulary.DESCRIPTION_ANNOT)));
tboxModel.add(construct(dataset, namespace, graphURI, ResourceFactory.createResource(

View file

@ -202,6 +202,25 @@ public class ObjectPropertyDaoJena extends PropertyDaoJena implements ObjectProp
}
p.setProhibitedFromUpdateBelowRoleLevel(prohibitedRoleLevel); //this might get set to null
//There might be multiple HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT properties, only use the highest
it = op.listProperties(HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT);
BaseResourceBean.RoleLevel publishRoleLevel = null;
while( it.hasNext() ){
Statement stmt = it.nextStatement();
RDFNode obj;
if( stmt != null && (obj = stmt.getObject()) != null && obj.isURIResource() ){
Resource res = obj.as(Resource.class);
if( res != null && res.getURI() != null ){
BaseResourceBean.RoleLevel roleFromModel = BaseResourceBean.RoleLevel.getRoleByUri(res.getURI());
if( roleFromModel != null &&
(publishRoleLevel == null || roleFromModel.compareTo(publishRoleLevel) > 0 )){
publishRoleLevel = roleFromModel;
}
}
}
}
p.setHiddenFromPublishBelowRoleLevel(publishRoleLevel); //this might get set to null
p.setCustomEntryForm(getPropertyStringValue(op,PROPERTY_CUSTOMENTRYFORMANNOT));
Boolean selectFromObj = getPropertyBooleanValue(op,PROPERTY_SELECTFROMEXISTINGANNOT);
p.setSelectFromExisting(selectFromObj==null ? true : selectFromObj);
@ -315,7 +334,7 @@ public class ObjectPropertyDaoJena extends PropertyDaoJena implements ObjectProp
"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 ?rangeRoot ?label ?group ?customForm ?displayRank ?displayLevel " +
" ?updateLevel ?editLinkSuppressed ?addLinkSuppressed ?deleteLinkSuppressed \n" +
" ?updateLevel ?publishLevel ?editLinkSuppressed ?addLinkSuppressed ?deleteLinkSuppressed \n" +
" ?collateBySubclass ?displayLimit ?individualSortProperty \n" +
" ?entitySortDirection ?selectFromExisting ?offerCreateNew \n" +
" ?publicDescription ?stubDeletion \n" +
@ -341,6 +360,7 @@ public class ObjectPropertyDaoJena extends PropertyDaoJena implements ObjectProp
" OPTIONAL { ?configuration vitro:customEntryFormAnnot ?customForm } \n" +
" OPTIONAL { ?configuration vitro:hiddenFromDisplayBelowRoleLevelAnnot ?displayLevel } \n" +
" OPTIONAL { ?configuration vitro:prohibitedFromUpdateBelowRoleLevelAnnot ?updateLevel } \n" +
" OPTIONAL { ?configuration vitro:hiddenFromPublishBelowRoleLevelAnnot ?publishLevel } \n" +
" OPTIONAL { ?configuration <" + PROPERTY_COLLATEBYSUBCLASSANNOT.getURI() + "> ?collateBySubclass } \n" +
" OPTIONAL { ?configuration <" + DISPLAY_LIMIT.getURI() + "> ?displayLimit } \n" +
" OPTIONAL { ?configuration <" + PROPERTY_OBJECTINDIVIDUALSORTPROPERTY.getURI() + "> ?individualSortProperty } \n " +
@ -392,6 +412,12 @@ public class ObjectPropertyDaoJena extends PropertyDaoJena implements ObjectProp
BaseResourceBean.RoleLevel.getRoleByUri(
updateLevelRes.getURI()));
}
Resource publishLevelRes = qsoln.getResource("publishLevel");
if (publishLevelRes != null) {
op.setHiddenFromPublishBelowRoleLevel(
BaseResourceBean.RoleLevel.getRoleByUri(
publishLevelRes.getURI()));
}
Literal labelLit = qsoln.getLiteral("label");
if (labelLit != null) {
op.setDomainPublic(labelLit.getLexicalForm());
@ -739,6 +765,10 @@ public class ObjectPropertyDaoJena extends PropertyDaoJena implements ObjectProp
updatePropertyResourceURIValue(p, PROHIBITED_FROM_UPDATE_BELOW_ROLE_LEVEL_ANNOT, prop.getProhibitedFromUpdateBelowRoleLevel().getURI());
}
if (prop.getHiddenFromPublishBelowRoleLevel() != null) {
updatePropertyResourceURIValue(p, HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT, prop.getHiddenFromPublishBelowRoleLevel().getURI());
}
updatePropertyStringValue(p,PROPERTY_CUSTOMENTRYFORMANNOT,prop.getCustomEntryForm(),ontModel);
updatePropertyBooleanValue(p,PROPERTY_SELECTFROMEXISTINGANNOT,prop.getSelectFromExisting(),ontModel,JenaBaseDao.KEEP_ONLY_IF_FALSE);
updatePropertyBooleanValue(p,PROPERTY_OFFERCREATENEWOPTIONANNOT,prop.getOfferCreateNewOption(),ontModel,JenaBaseDao.KEEP_ONLY_IF_TRUE);

View file

@ -2,6 +2,8 @@
package edu.cornell.mannlib.vitro.webapp.dao.jena;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@ -28,10 +30,12 @@ public class OntologyDaoJena extends JenaBaseDao implements OntologyDao {
}
public static synchronized String adjustOntologyURI(String ontologyURI) {
if ( (ontologyURI.length()>1) && (ontologyURI.charAt(ontologyURI.length()-1)=='#') ) {
return ontologyURI.substring(0,ontologyURI.length()-1);
String uri = ontologyURI.trim();
int length = uri.length();
if ( (length>1) && (uri.charAt(length-1)=='#') ) {
return uri.substring(0,length-1);
} else {
return ontologyURI;
return uri;
}
}
@ -124,10 +128,14 @@ public class OntologyDaoJena extends JenaBaseDao implements OntologyDao {
}
public String insertNewOntology(Ontology ontology, OntModel ontModel) {
if (ontology != null && ontology.getURI() != null && ontology.getURI().length()>0) {
if (ontology == null) {
return null;
}
try {
String ontologyURI = adjustAndValidateOntologyURI(ontology.getURI());
ontModel.enterCriticalSection(Lock.WRITE);
try {
com.hp.hpl.jena.ontology.Ontology o = ontModel.createOntology(adjustOntologyURI(ontology.getURI()));
com.hp.hpl.jena.ontology.Ontology o = ontModel.createOntology(ontologyURI);
if (ontology.getName() != null && ontology.getName().length()>0) {
o.setLabel(ontology.getName(), getDefaultLanguage());
}
@ -138,11 +146,20 @@ public class OntologyDaoJena extends JenaBaseDao implements OntologyDao {
} finally {
ontModel.leaveCriticalSection();
}
} else {
return null;
} catch (URISyntaxException e) {
log.warn("Failed to insert new ontology: " + ontology, e);
throw new RuntimeException(e);
}
}
private String adjustAndValidateOntologyURI(String uri) throws URISyntaxException {
if (uri == null || uri.isEmpty()) {
throw new URISyntaxException(uri, "URI is empty");
}
String adjusted = adjustOntologyURI(uri);
return new URI(adjusted).toString();
}
public void updateOntology(Ontology ontology) {
updateOntology(ontology,getOntModel());
}

View file

@ -193,7 +193,7 @@ public class PropertyDaoJena extends JenaBaseDao implements PropertyDao {
} catch (Exception cce) {}
}
} catch (Exception e) {
log.error(e, e);
log.error("Failed to get super-properties for " + propertyURI, e);
} finally {
getOntModel().leaveCriticalSection();
}

View file

@ -2,10 +2,14 @@
package edu.cornell.mannlib.vitro.webapp.dao.jena;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -56,6 +60,39 @@ public class QueryUtils {
return map;
}
/**
* If any pair of maps in the list has the same (non-null) value for any of
* these keys, call the maps duplicates and keep only the first of them.
*/
public static List<Map<String, String>> removeDuplicatesMapsFromList(
List<Map<String, String>> rawList, String... keys) {
List<Map<String, String>> filteredList = new ArrayList<>();
outerLoop: for (Map<String, String> rawMap : rawList) {
for (Map<String, String> filteredMap : filteredList) {
for (String key : keys) {
String rawValue = rawMap.get(key);
if (rawValue != null) {
if (rawValue.equals(filteredMap.get(key))) {
if (log.isDebugEnabled()) {
logDuplicateRows(rawMap, filteredMap, keys);
}
continue outerLoop;
}
}
}
}
filteredList.add(rawMap);
}
return filteredList;
}
private static void logDuplicateRows(Map<String, String> rawMap,
Map<String, String> filteredMap, String... keys) {
log.debug("Found duplicate rows, by at least one of these keys: "
+ Arrays.toString(keys) + ". Keeping " + filteredMap
+ ". Discarding " + rawMap + ".");
}
public static Object nodeToObject( RDFNode node ){
if( node == null ){
return "";

View file

@ -984,6 +984,15 @@ public class VClassDaoJena extends JenaBaseDao implements VClassDao {
}
}
ontCls.removeAll(HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT);
if (HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT != null && cls.getHiddenFromPublishBelowRoleLevel() != null) { // only need to add if present
try {
ontCls.addProperty(HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT, ResourceFactory.createResource(cls.getHiddenFromPublishBelowRoleLevel().getURI()));
} catch (Exception e) {
log.error("error adding HiddenFromPublishBelowRoleLevel annotation to class "+cls.getURI());
}
}
/* OPTIONAL annotation properties */
addPropertyStringValue(ontCls,PROPERTY_CUSTOMENTRYFORMANNOT,cls.getCustomEntryForm(),ontModel);
addPropertyStringValue(ontCls,PROPERTY_CUSTOMDISPLAYVIEWANNOT,cls.getCustomDisplayView(),ontModel);
@ -1025,6 +1034,10 @@ public class VClassDaoJena extends JenaBaseDao implements VClassDao {
updatePropertyResourceURIValue(ontCls,PROHIBITED_FROM_UPDATE_BELOW_ROLE_LEVEL_ANNOT,cls.getProhibitedFromUpdateBelowRoleLevel().getURI(),ontModel);
}
if (cls.getHiddenFromPublishBelowRoleLevel() != null) {
updatePropertyResourceURIValue(ontCls,HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT,cls.getHiddenFromPublishBelowRoleLevel().getURI(),ontModel);
}
updatePropertyStringValue(ontCls,PROPERTY_CUSTOMENTRYFORMANNOT,cls.getCustomEntryForm(),ontModel);
updatePropertyStringValue(ontCls,PROPERTY_CUSTOMDISPLAYVIEWANNOT,cls.getCustomDisplayView(),ontModel);
updatePropertyStringValue(ontCls,PROPERTY_CUSTOMSHORTVIEWANNOT,cls.getCustomShortView(),ontModel);

View file

@ -47,6 +47,16 @@ public class VClassJena extends VClass {
this.webappDaoFactory = wadf;
}
/**
* Constructs the VClassJena as a deep copy of an existing VClassJena.
*/
@Override
public VClassJena copy() {
VClassJena that = new VClassJena(this.cls, this.webappDaoFactory);
copyFields(that);
return that;
}
/**
* What this VClass is called
*/
@ -333,7 +343,7 @@ public class VClassJena extends VClass {
} else {
cls.getOntModel().enterCriticalSection(Lock.READ);
try {
//There might be multiple PROHIBITED_FROM_UPDATE_DISPLAY_ANNOT properties, only use the highest
//There might be multiple PROHIBITED_FROM_UPDATE_BELOW_ROLE_LEVEL_ANNOT properties, only use the highest
StmtIterator it = cls.listProperties(webappDaoFactory.getJenaBaseDao().PROHIBITED_FROM_UPDATE_BELOW_ROLE_LEVEL_ANNOT);
BaseResourceBean.RoleLevel prohibitedRoleLevel = null;
while( it.hasNext() ){
@ -359,6 +369,41 @@ public class VClassJena extends VClass {
}
}
@Override
public RoleLevel getHiddenFromPublishBelowRoleLevel() {
if (this.hiddenFromPublishBelowRoleLevel != null) {
return this.hiddenFromPublishBelowRoleLevel;
} else {
cls.getOntModel().enterCriticalSection(Lock.READ);
try {
//There might be multiple HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT properties, only use the highest
StmtIterator it = cls.listProperties(webappDaoFactory.getJenaBaseDao().HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT);
BaseResourceBean.RoleLevel publishRoleLevel = null;
while( it.hasNext() ){
Statement stmt = it.nextStatement();
RDFNode obj;
if( stmt != null && (obj = stmt.getObject()) != null && obj.isURIResource() ){
Resource res = obj.as(Resource.class);
if( res != null && res.getURI() != null ){
BaseResourceBean.RoleLevel roleFromModel = BaseResourceBean.RoleLevel.getRoleByUri(res.getURI());
if( roleFromModel != null &&
(publishRoleLevel == null || roleFromModel.compareTo(publishRoleLevel) > 0 )){
publishRoleLevel = roleFromModel;
}
}
}
}
setHiddenFromPublishBelowRoleLevel(publishRoleLevel); //this might get set to null
return this.hiddenFromPublishBelowRoleLevel;
} finally {
cls.getOntModel().leaveCriticalSection();
}
}
}
@Override
public boolean isUnion() {
return this.cls.isUnionClass();

View file

@ -1,112 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* <p>
* Wraps an HTTP request and parses it for file uploads, without losing the
* request parameters.
* </p>
* <p>
* The request will have an attribute named by {@link #FILE_ITEM_MAP}. Either
* this attribute or the call to {@link #getFiles()} will produce a map that may
* be empty but is never null. The keys to the map are the field names for the
* file fields. Since a form may have multiple fields with the same name, each
* field name maps to a list of items. If a user does not provide a file to be
* uploaded in a given field, the length of the file will be 0.
* </p>
* <p>
* If the uploaded file(s) would be larger than the <code>maxFileSize</code>,
* {@link #parseRequest(HttpServletRequest, int)} does not throw an Exception.
* Instead, it records the exception in a request attribute named by
* {@link #FILE_UPLOAD_EXCEPTION}. This attribute can be accessed directly, or
* indirectly via the methods {@link #hasFileUploadException()} and
* {@link #getFileUploadException()}. If there is an exception, the file item
* map (see above) will still be non-null, but it will be empty.
* </p>
* <p>
* Most methods are declared here simply delegate to the wrapped request.
* Methods that have to do with parameters, files, or parsing exceptions, are
* handled differently for simple requests and multipart request, and are
* implemented in the sub-classes.
* </p>
*/
public abstract class FileUploadServletRequest extends HttpServletRequestWrapper {
public static final String FILE_ITEM_MAP = "file_item_map";
public static final String FILE_UPLOAD_EXCEPTION = "file_upload_exception";
// ----------------------------------------------------------------------
// The factory method
// ----------------------------------------------------------------------
/**
* Wrap this {@link HttpServletRequest} in an appropriate wrapper class.
*/
public static FileUploadServletRequest parseRequest(
HttpServletRequest request, int maxFileSize) throws IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
return new MultipartHttpServletRequest(request, maxFileSize);
} else {
return new SimpleHttpServletRequestWrapper(request);
}
}
// ----------------------------------------------------------------------
// The constructor and the delegate.
// ----------------------------------------------------------------------
private final HttpServletRequest delegate;
public FileUploadServletRequest(HttpServletRequest delegate) {
super(delegate);
this.delegate = delegate;
}
protected HttpServletRequest getDelegate() {
return this.delegate;
}
// ----------------------------------------------------------------------
// New functionality to be implemented by the subclasses.
// ----------------------------------------------------------------------
/** Was this a multipart HTTP request? */
public abstract boolean isMultipart();
/**
* Get the map of file items, by name.
*/
public abstract Map<String, List<FileItem>> getFiles();
/**
* Find a non-empty file item with this name.
*
* @return the first such file item, or <code>null</code> if no matching,
* non-empty items were found.
*/
public abstract FileItem getFileItem(String string);
/**
* Was there an exception when uploading the file items?
*/
public abstract boolean hasFileUploadException();
/**
* Get the exception that occurred when uploading the file items. If no such
* exception, return <code>null</code>.
*/
public abstract FileUploadException getFileUploadException();
}

View file

@ -1,261 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* A wrapper for a servlet request that holds multipart content. Parsing the
* request will consume the parameters, so we need to hold them here to answer
* any parameter-related requests. File-related information will also be held
* here, to answer file-related requests.
*/
class MultipartHttpServletRequest extends FileUploadServletRequest {
private static final Log log = LogFactory
.getLog(MultipartHttpServletRequest.class);
private static final String[] EMPTY_ARRAY = new String[0];
private final Map<String, List<String>> parameters;
private final Map<String, List<FileItem>> files;
private FileUploadException fileUploadException;
/**
* Parse the multipart request. Store the info about the request parameters
* and the uploaded files.
*/
public MultipartHttpServletRequest(HttpServletRequest request,
int maxFileSize) throws IOException {
super(request);
Map<String, List<String>> parameters = new HashMap<String, List<String>>();
Map<String, List<FileItem>> files = new HashMap<String, List<FileItem>>();
File tempDir = figureTemporaryDirectory(request);
ServletFileUpload upload = createUploadHandler(maxFileSize, tempDir);
parseQueryString(request.getQueryString(), parameters);
try {
List<FileItem> items = parseRequestIntoFileItems(request, upload);
for (FileItem item : items) {
// Process a regular form field
if (item.isFormField()) {
addToParameters(parameters, item.getFieldName(), item
.getString("UTF-8"));
log.debug("Form field (parameter) " + item.getFieldName()
+ "=" + item.getString());
} else {
addToFileItems(files, item);
log.debug("File " + item.getFieldName() + ": "
+ item.getName());
}
}
} catch (FileUploadException e) {
fileUploadException = e;
request.setAttribute(
FileUploadServletRequest.FILE_UPLOAD_EXCEPTION, e);
}
this.parameters = Collections.unmodifiableMap(parameters);
log.debug("Parameters are: " + this.parameters);
this.files = Collections.unmodifiableMap(files);
log.debug("Files are: " + this.files);
request.setAttribute(FILE_ITEM_MAP, this.files);
}
/**
* Pull any parameters out of the URL.
*/
private void parseQueryString(String queryString,
Map<String, List<String>> parameters) {
log.debug("Query string is : '" + queryString + "'");
if (queryString != null) {
String[] pieces = queryString.split("&");
for (String piece : pieces) {
int equalsHere = piece.indexOf('=');
if (piece.trim().isEmpty()) {
// Ignore an empty piece.
} else if (equalsHere <= 0) {
// A parameter without a value.
addToParameters(parameters, decode(piece), "");
} else {
// A parameter with a value.
String key = piece.substring(0, equalsHere);
String value = piece.substring(equalsHere + 1);
addToParameters(parameters, decode(key), decode(value));
}
}
}
log.debug("Parameters from query string are: " + parameters);
}
/**
* Remove any special URL-style encoding.
*/
private String decode(String encoded) {
try {
return URLDecoder.decode(encoded, "UTF-8");
} catch (UnsupportedEncodingException e) {
log.error(e, e);
return encoded;
}
}
/**
* Find the temporary storage directory for this webapp.
*/
private File figureTemporaryDirectory(HttpServletRequest request) {
return (File) request.getSession().getServletContext().getAttribute(
"javax.servlet.context.tempdir");
}
/**
* Create an upload handler that will throw an exception if the file is too
* large.
*/
private ServletFileUpload createUploadHandler(int maxFileSize, File tempDir) {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
factory.setRepository(tempDir);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxFileSize);
return upload;
}
/** Either create a new List for the value, or add to an existing List. */
private void addToParameters(Map<String, List<String>> map, String name,
String value) {
if (!map.containsKey(name)) {
map.put(name, new ArrayList<String>());
}
map.get(name).add(value);
}
/** Either create a new List for the file, or add to an existing List. */
private void addToFileItems(Map<String, List<FileItem>> map, FileItem file) {
String name = file.getFieldName();
if (!map.containsKey(name)) {
map.put(name, new ArrayList<FileItem>());
}
map.get(name).add(file);
}
/** Minimize the code that uses the unchecked cast. */
@SuppressWarnings("unchecked")
private List<FileItem> parseRequestIntoFileItems(HttpServletRequest req,
ServletFileUpload upload) throws FileUploadException {
return upload.parseRequest(req);
}
// ----------------------------------------------------------------------
// This is a multipart request, so make the file info available. If there
// was an exception during parsing, make that available too.
// ----------------------------------------------------------------------
@Override
public boolean isMultipart() {
return true;
}
@Override
public Map<String, List<FileItem>> getFiles() {
return files;
}
/**
* {@inheritDoc}
* <p>
* There may be more than one file item with the given name. If the first
* one is empty (size is zero), keep looking for a non-empty one.
* </p>
*/
@Override
public FileItem getFileItem(String name) {
List<FileItem> items = files.get(name);
if (items == null) {
return null;
}
for (FileItem item : items) {
if (item.getSize() > 0L) {
return item;
}
}
return null;
}
@Override
public FileUploadException getFileUploadException() {
return fileUploadException;
}
@Override
public boolean hasFileUploadException() {
return fileUploadException != null;
}
// ----------------------------------------------------------------------
// Parameter-related methods won't find anything on the delegate request,
// since parsing consumed the parameters. So we need to look to the parsed
// info for the answers.
// ----------------------------------------------------------------------
@Override
public String getParameter(String name) {
if (parameters.containsKey(name)) {
return parameters.get(name).get(0);
} else {
return null;
}
}
@Override
public Enumeration<?> getParameterNames() {
return Collections.enumeration(parameters.keySet());
}
@Override
public String[] getParameterValues(String name) {
if (parameters.containsKey(name)) {
return parameters.get(name).toArray(EMPTY_ARRAY);
} else {
return null;
}
}
@Override
public Map<String, String[]> getParameterMap() {
Map<String, String[]> result = new HashMap<String, String[]>();
for (Entry<String, List<String>> entry : parameters.entrySet()) {
result.put(entry.getKey(), entry.getValue().toArray(EMPTY_ARRAY));
}
log.debug("resulting parameter map: " + result);
return result;
}
}

View file

@ -1,81 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
/**
* A wrapper for a servlet request that does not hold multipart content. Pass
* all parameter-related requests to the delegate, and give simple answers to
* all file-related requests.
*/
class SimpleHttpServletRequestWrapper extends FileUploadServletRequest {
SimpleHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
request.setAttribute(FILE_ITEM_MAP, Collections.EMPTY_MAP);
}
// ----------------------------------------------------------------------
// Not a multipart request, so there are no files or upload exceptions.
// ----------------------------------------------------------------------
@Override
public boolean isMultipart() {
return false;
}
@Override
public Map<String, List<FileItem>> getFiles() {
return Collections.emptyMap();
}
@Override
public FileItem getFileItem(String string) {
return null;
}
@Override
public FileUploadException getFileUploadException() {
return null;
}
@Override
public boolean hasFileUploadException() {
return false;
}
// ----------------------------------------------------------------------
// Since this is not a multipart request, the parameter methods can be
// delegated.
// ----------------------------------------------------------------------
@Override
public String getParameter(String name) {
return getDelegate().getParameter(name);
}
@Override
public Map<?, ?> getParameterMap() {
return getDelegate().getParameterMap();
}
@Override
public Enumeration<?> getParameterNames() {
return getDelegate().getParameterNames();
}
@Override
public String[] getParameterValues(String name) {
return getDelegate().getParameterValues(name);
}
}

View file

@ -26,7 +26,7 @@ import edu.cornell.mannlib.vitro.webapp.freemarker.loader.FreemarkerTemplateLoad
import edu.cornell.mannlib.vitro.webapp.i18n.freemarker.I18nMethodModel;
import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus;
import edu.cornell.mannlib.vitro.webapp.utils.developer.DeveloperSettings;
import edu.cornell.mannlib.vitro.webapp.utils.developer.DeveloperSettings.Keys;
import edu.cornell.mannlib.vitro.webapp.utils.developer.Key;
import edu.cornell.mannlib.vitro.webapp.web.directives.IndividualShortViewDirective;
import edu.cornell.mannlib.vitro.webapp.web.directives.UrlDirective;
import edu.cornell.mannlib.vitro.webapp.web.directives.WidgetDirective;
@ -70,7 +70,7 @@ public abstract class FreemarkerConfiguration {
confirmInstanceIsSet();
synchronized (instance) {
clearTemplateCacheIfRequested(req);
clearTemplateCacheIfRequested();
keepTemplateLoaderCurrentWithThemeDirectory(req);
setThreadLocalsForRequest(req);
return instance;
@ -84,21 +84,14 @@ public abstract class FreemarkerConfiguration {
}
}
private static void clearTemplateCacheIfRequested(HttpServletRequest req) {
if (isTemplateCacheInvalid(req)) {
/** If the developer doesn't want the cache, clear it every time. */
private static void clearTemplateCacheIfRequested() {
DeveloperSettings settings = DeveloperSettings.getInstance();
if (settings.getBoolean(Key.DEFEAT_FREEMARKER_CACHE)) {
instance.clearTemplateCache();
}
}
/** If the developer doesn't want the cache, it's invalid. */
private static boolean isTemplateCacheInvalid(HttpServletRequest req) {
DeveloperSettings settings = DeveloperSettings.getBean(req);
if (settings.getBoolean(Keys.DEFEAT_FREEMARKER_CACHE)) {
return true;
}
return false;
}
/**
* Keep track of the theme directory. If it changes, create an appropriate
* new TemplateLoader.
@ -110,7 +103,7 @@ public abstract class FreemarkerConfiguration {
HttpServletRequest req) {
String themeDir = getThemeDirectory(req);
if (hasThemeDirectoryChanged(themeDir)
|| haveDeveloperSettingsChanged(req)) {
|| haveDeveloperSettingsChanged()) {
TemplateLoader tl = createTemplateLoader(req, themeDir);
instance.setTemplateLoader(tl);
}
@ -131,9 +124,9 @@ public abstract class FreemarkerConfiguration {
}
}
private static boolean haveDeveloperSettingsChanged(HttpServletRequest req) {
Map<String, Object> settingsMap = DeveloperSettings.getBean(req)
.getSettingsMap();
private static boolean haveDeveloperSettingsChanged() {
Map<String, Object> settingsMap = DeveloperSettings.getInstance()
.getRawSettingsMap();
if (settingsMap.equals(previousSettingsMap)) {
return false;
} else {
@ -167,8 +160,8 @@ public abstract class FreemarkerConfiguration {
TemplateLoader tl = new MultiTemplateLoader(loaderArray);
// If requested, add delimiters to the templates.
DeveloperSettings settings = DeveloperSettings.getBean(req);
if (settings.getBoolean(Keys.INSERT_FREEMARKER_DELIMITERS)) {
DeveloperSettings settings = DeveloperSettings.getInstance();
if (settings.getBoolean(Key.INSERT_FREEMARKER_DELIMITERS)) {
tl = new DelimitingTemplateLoader(tl);
}

View file

@ -22,7 +22,7 @@ import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.i18n.selection.SelectedLocale;
import edu.cornell.mannlib.vitro.webapp.utils.developer.DeveloperSettings;
import edu.cornell.mannlib.vitro.webapp.utils.developer.DeveloperSettings.Keys;
import edu.cornell.mannlib.vitro.webapp.utils.developer.Key;
/**
* Provides access to a bundle of text strings, based on the name of the bundle,
@ -108,7 +108,7 @@ public class I18n {
protected I18nBundle getBundle(String bundleName, HttpServletRequest req) {
log.debug("Getting bundle '" + bundleName + "'");
I18nLogger i18nLogger = new I18nLogger(req);
I18nLogger i18nLogger = new I18nLogger();
try {
checkDevelopmentMode(req);
checkForChangeInThemeDirectory(req);
@ -133,7 +133,7 @@ public class I18n {
* If we are in development mode, clear the cache on each request.
*/
private void checkDevelopmentMode(HttpServletRequest req) {
if (DeveloperSettings.getBean(req).getBoolean(Keys.I18N_DEFEAT_CACHE)) {
if (DeveloperSettings.getInstance().getBoolean(Key.I18N_DEFEAT_CACHE)) {
log.debug("In development mode - clearing the cache.");
clearCacheOnRequest(req);
}

View file

@ -4,13 +4,11 @@ package edu.cornell.mannlib.vitro.webapp.i18n;
import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.utils.developer.DeveloperSettings;
import edu.cornell.mannlib.vitro.webapp.utils.developer.DeveloperSettings.Keys;
import edu.cornell.mannlib.vitro.webapp.utils.developer.Key;
/**
* If enabled in developer mode, write a message to the log each time someone
@ -23,10 +21,9 @@ public class I18nLogger {
private final boolean isLogging;
public I18nLogger(HttpServletRequest req) {
DeveloperSettings settings = DeveloperSettings.getBean(req);
this.isLogging = settings.getBoolean(Keys.ENABLED)
&& settings.getBoolean(Keys.I18N_LOG_STRINGS)
public I18nLogger() {
DeveloperSettings settings = DeveloperSettings.getInstance();
this.isLogging = settings.getBoolean(Key.I18N_LOG_STRINGS)
&& log.isInfoEnabled();
}

View file

@ -3,9 +3,9 @@
package edu.cornell.mannlib.vitro.webapp.i18n.selection;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import javax.servlet.Filter;
@ -17,7 +17,6 @@ import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.collections.EnumerationUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -68,13 +67,12 @@ public class LocaleSelectionFilter implements Filter {
// ----------------------------------------------------------------------
/**
* Uses the selected Locale as the preferred Locale of the request.
* Uses the selected Locale as the only acceptable Locale of the request.
*/
private static class LocaleSelectionRequestWrapper extends
HttpServletRequestWrapper {
private final List<Locale> locales;
private final Locale selectedLocale;
@SuppressWarnings("unchecked")
public LocaleSelectionRequestWrapper(HttpServletRequest request,
Locale selectedLocale) {
super(request);
@ -87,18 +85,12 @@ public class LocaleSelectionFilter implements Filter {
"selectedLocale may not be null.");
}
Locale selectedLanguage = new Locale(selectedLocale.getLanguage());
locales = EnumerationUtils.toList(request.getLocales());
locales.remove(selectedLanguage);
locales.add(0, selectedLanguage);
locales.remove(selectedLocale);
locales.add(0, selectedLocale);
this.selectedLocale = selectedLocale;
}
@Override
public Locale getLocale() {
return locales.get(0);
return selectedLocale;
}
/**
@ -107,7 +99,7 @@ public class LocaleSelectionFilter implements Filter {
@SuppressWarnings("rawtypes")
@Override
public Enumeration getLocales() {
return Collections.enumeration(locales);
return Collections.enumeration(Arrays.asList(selectedLocale));
}
}

View file

@ -52,6 +52,7 @@ public abstract class SelectedLocale {
* <ul>
* <li>The forced Locale in the servlet context</li>
* <li>The selected Locale in the session</li>
* <li>The first of the selectable Locales</li>
* <li>null</li>
* </ul>
*/
@ -80,6 +81,17 @@ public abstract class SelectedLocale {
}
}
if (ctxInfo instanceof ContextSelectedLocale) {
List<Locale> selectableLocales = ((ContextSelectedLocale) ctxInfo)
.getSelectableLocales();
if (selectableLocales != null && !selectableLocales.isEmpty()) {
Locale defaultLocale = selectableLocales.get(0);
log.debug("Using first selectable locale as default: "
+ defaultLocale);
return defaultLocale;
}
}
return null;
}

View file

@ -3,7 +3,6 @@
package edu.cornell.mannlib.vitro.webapp.ontology.update;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@ -18,15 +17,17 @@ import java.util.List;
import javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openrdf.model.impl.URIImpl;
import com.hp.hpl.jena.iri.IRI;
import com.hp.hpl.jena.iri.IRIFactory;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
@ -234,6 +235,7 @@ public class KnowledgeBaseUpdater {
Model dedupeModel = dataset.getDefaultModel();
Model additions = jiu.renameBNodes(
anonModel, settings.getDefaultNamespace() + "n", dedupeModel);
additions = stripBadURIs(additions);
Model actualAdditions = ModelFactory.createDefaultModel();
StmtIterator stmtIt = additions.listStatements();
while (stmtIt.hasNext()) {
@ -250,6 +252,36 @@ public class KnowledgeBaseUpdater {
}
}
private Model stripBadURIs(Model additions) {
Model badURITriples = ModelFactory.createDefaultModel();
StmtIterator stmtIt = additions.listStatements();
while (stmtIt.hasNext()) {
String[] uris = new String[3];
Statement stmt = stmtIt.nextStatement();
if(stmt.getSubject().isURIResource()) {
uris[0] = stmt.getSubject().getURI();
}
uris[1] = stmt.getPredicate().getURI();
if(stmt.getObject().isURIResource()) {
uris[2] = ((Resource) stmt.getObject()).getURI();
}
for (int i = 0; i < 3; i++) {
String uri = uris[i];
if (uri != null) {
IRIFactory factory = IRIFactory.jenaImplementation();
IRI iri = factory.create(uri);
if (iri.hasViolation(false)) {
badURITriples.add(stmt);
log.error("Discarding added triple " + stmt + " because " +
"it includes one or more invalid URIs.");
break;
}
}
}
}
additions.remove(badURITriples);
return additions;
}
private List<AtomicOntologyChange> getAtomicOntologyChanges()
throws IOException {

View file

@ -42,7 +42,7 @@ public class RDFServiceUtils {
* Every factory is wrapped in a logger, so we can dynamically
* enable or disable logging.
*/
return new LoggingRDFServiceFactory(context, factory);
return new LoggingRDFServiceFactory(factory);
} else {
log.error("Expecting an RDFServiceFactory on the context, but found " + o);
return null;

View file

@ -5,8 +5,6 @@ package edu.cornell.mannlib.vitro.webapp.rdfservice.impl.logging;
import java.io.InputStream;
import java.util.List;
import javax.servlet.ServletContext;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeListener;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeSet;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
@ -19,11 +17,9 @@ import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFServiceException;
* For the other methods, it just delegates to the inner RDFService.
*/
public class LoggingRDFService implements RDFService {
private final ServletContext ctx;
private final RDFService innerService;
LoggingRDFService(ServletContext ctx, RDFService innerService) {
this.ctx = ctx;
LoggingRDFService(RDFService innerService) {
this.innerService = innerService;
}
@ -34,7 +30,7 @@ public class LoggingRDFService implements RDFService {
@Override
public boolean changeSetUpdate(ChangeSet changeSet)
throws RDFServiceException {
try (RDFServiceLogger l = new RDFServiceLogger(ctx, changeSet)) {
try (RDFServiceLogger l = new RDFServiceLogger(changeSet)) {
return innerService.changeSetUpdate(changeSet);
}
}
@ -42,7 +38,7 @@ public class LoggingRDFService implements RDFService {
@Override
public InputStream sparqlConstructQuery(String query,
ModelSerializationFormat resultFormat) throws RDFServiceException {
try (RDFServiceLogger l = new RDFServiceLogger(ctx, resultFormat, query)) {
try (RDFServiceLogger l = new RDFServiceLogger(resultFormat, query)) {
return innerService.sparqlConstructQuery(query, resultFormat);
}
}
@ -50,7 +46,7 @@ public class LoggingRDFService implements RDFService {
@Override
public InputStream sparqlDescribeQuery(String query,
ModelSerializationFormat resultFormat) throws RDFServiceException {
try (RDFServiceLogger l = new RDFServiceLogger(ctx, resultFormat, query)) {
try (RDFServiceLogger l = new RDFServiceLogger(resultFormat, query)) {
return innerService.sparqlDescribeQuery(query, resultFormat);
}
}
@ -58,14 +54,14 @@ public class LoggingRDFService implements RDFService {
@Override
public InputStream sparqlSelectQuery(String query, ResultFormat resultFormat)
throws RDFServiceException {
try (RDFServiceLogger l = new RDFServiceLogger(ctx, resultFormat, query)) {
try (RDFServiceLogger l = new RDFServiceLogger(resultFormat, query)) {
return innerService.sparqlSelectQuery(query, resultFormat);
}
}
@Override
public boolean sparqlAskQuery(String query) throws RDFServiceException {
try (RDFServiceLogger l = new RDFServiceLogger(ctx, query)) {
try (RDFServiceLogger l = new RDFServiceLogger(query)) {
return innerService.sparqlAskQuery(query);
}
}

View file

@ -2,8 +2,6 @@
package edu.cornell.mannlib.vitro.webapp.rdfservice.impl.logging;
import javax.servlet.ServletContext;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeListener;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFServiceException;
@ -14,23 +12,20 @@ import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFServiceFactory;
* wrapped in a LoggingRDFService.
*/
public class LoggingRDFServiceFactory implements RDFServiceFactory {
private final ServletContext ctx;
private final RDFServiceFactory factory;
public LoggingRDFServiceFactory(ServletContext ctx,
RDFServiceFactory factory) {
this.ctx = ctx;
public LoggingRDFServiceFactory(RDFServiceFactory factory) {
this.factory = factory;
}
@Override
public RDFService getRDFService() {
return new LoggingRDFService(ctx, factory.getRDFService());
return new LoggingRDFService(factory.getRDFService());
}
@Override
public RDFService getShortTermRDFService() {
return new LoggingRDFService(ctx, factory.getShortTermRDFService());
return new LoggingRDFService(factory.getShortTermRDFService());
}
@Override

View file

@ -9,14 +9,12 @@ import java.util.List;
import java.util.ListIterator;
import java.util.regex.Pattern;
import javax.servlet.ServletContext;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.utils.developer.DeveloperSettings;
import edu.cornell.mannlib.vitro.webapp.utils.developer.DeveloperSettings.Keys;
import edu.cornell.mannlib.vitro.webapp.utils.developer.Key;
/**
* Writes the log message for the LoggingRDFService.
@ -45,7 +43,6 @@ import edu.cornell.mannlib.vitro.webapp.utils.developer.DeveloperSettings.Keys;
public class RDFServiceLogger implements AutoCloseable {
private static final Log log = LogFactory.getLog(RDFServiceLogger.class);
private final ServletContext ctx;
private final Object[] args;
private boolean isEnabled;
@ -58,31 +55,33 @@ public class RDFServiceLogger implements AutoCloseable {
private long startTime;
public RDFServiceLogger(ServletContext ctx, Object... args) {
this.ctx = ctx;
public RDFServiceLogger(Object... args) {
this.args = args;
try {
getProperties();
if (isEnabled && log.isInfoEnabled()) {
loadStackTrace();
if (passesQueryRestriction() && passesStackRestriction()) {
this.startTime = System.currentTimeMillis();
}
}
} catch (Exception e) {
log.error("Failed to create instance", e);
}
}
private void getProperties() {
DeveloperSettings settings = DeveloperSettings.getBean(ctx);
isEnabled = settings.getBoolean(Keys.LOGGING_RDF_ENABLE);
traceRequested = settings.getBoolean(Keys.LOGGING_RDF_STACK_TRACE);
DeveloperSettings settings = DeveloperSettings.getInstance();
isEnabled = settings.getBoolean(Key.LOGGING_RDF_ENABLE);
traceRequested = settings.getBoolean(Key.LOGGING_RDF_STACK_TRACE);
queryStringRestriction = patternFromSettings(settings,
Keys.LOGGING_RDF_QUERY_RESTRICTION);
Key.LOGGING_RDF_QUERY_RESTRICTION);
callStackRestriction = patternFromSettings(settings,
Keys.LOGGING_RDF_STACK_RESTRICTION);
Key.LOGGING_RDF_STACK_RESTRICTION);
}
private Pattern patternFromSettings(DeveloperSettings settings, Keys key) {
private Pattern patternFromSettings(DeveloperSettings settings, Key key) {
String patternString = settings.getString(key);
if (StringUtils.isBlank(patternString)) {
return null;
@ -160,13 +159,13 @@ public class RDFServiceLogger implements AutoCloseable {
}
private String assembleQueryString() {
StringBuilder query = new StringBuilder();
List<String> stringArgs = new ArrayList<>();
for (Object arg : args) {
if (arg instanceof String) {
query.append((String) arg).append(" ");
stringArgs.add((String) arg);
}
}
return query.deleteCharAt(query.length() - 1).toString();
return StringUtils.join(stringArgs, " ");
}
private boolean passesStackRestriction() {
@ -188,6 +187,7 @@ public class RDFServiceLogger implements AutoCloseable {
@Override
public void close() {
try {
if (startTime != 0L) {
long endTime = System.currentTimeMillis();
@ -199,6 +199,9 @@ public class RDFServiceLogger implements AutoCloseable {
log.info(String.format("%8.3f %s %s %s", elapsedSeconds,
methodName, cleanArgs, formattedTrace));
}
} catch (Exception e) {
log.error("Failed to write log record", e);
}
}
private String formatStackTrace() {

View file

@ -23,7 +23,6 @@ import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerHttpServ
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ExceptionResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
import edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.FileUploadServletRequest;
import edu.cornell.mannlib.vitro.webapp.search.indexing.IndexBuilder;
/**
@ -35,7 +34,10 @@ public class SearchServiceController extends FreemarkerHttpServlet {
.getLog(SearchServiceController.class);
/** Limit file size to 1 Gigabyte. */
public static final int MAXIMUM_FILE_SIZE = 1024 * 1024 * 1024;
@Override
public long maximumMultipartFileSize() {
return 1024 * 1024 * 1024;
}
/**
* Handle the different actions. If not specified, the default action is to
@ -44,9 +46,6 @@ public class SearchServiceController extends FreemarkerHttpServlet {
@Override
protected ResponseValues processRequest(VitroRequest req) {
try {
req = new VitroRequest(FileUploadServletRequest.parseRequest(req,
MAXIMUM_FILE_SIZE));
// Check the authorization here, because we don't want to redirect
// to the login page if they are not authorized. (The file upload
// would be lost.

View file

@ -2,8 +2,6 @@
package edu.cornell.mannlib.vitro.webapp.search.controller;
import static edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.FileUploadServletRequest.FILE_ITEM_MAP;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
@ -21,6 +19,7 @@ import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.search.indexing.IndexBuilder;
/**
@ -41,9 +40,7 @@ public class UpdateUrisInIndex {
*/
protected int doUpdateUris(HttpServletRequest req, IndexBuilder builder)
throws ServletException, IOException {
@SuppressWarnings("unchecked")
Map<String, List<FileItem>> map = (Map<String, List<FileItem>>) req
.getAttribute(FILE_ITEM_MAP);
Map<String, List<FileItem>> map = new VitroRequest(req).getFiles();
if (map == null) {
throw new ServletException("Expected Multipart Content");
}
@ -54,13 +51,13 @@ public class UpdateUrisInIndex {
for (String name : map.keySet()) {
for (FileItem item : map.get(name)) {
log.debug("Found " + item.getSize() + " byte file for '" + name + "'");
uriCount += processFileItem(builder, name, item, enc);
uriCount += processFileItem(builder, item, enc);
}
}
return uriCount;
}
private int processFileItem(IndexBuilder builder, String name,
private int processFileItem(IndexBuilder builder,
FileItem item, Charset enc) throws IOException {
int count = 0;
Reader reader = new InputStreamReader(item.getInputStream(), enc.name());

View file

@ -6,10 +6,9 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.services.shortview.FakeApplicationOntologyService.TemplateAndDataGetters;
import edu.cornell.mannlib.vitro.webapp.utils.developer.DeveloperSettings;
import edu.cornell.mannlib.vitro.webapp.utils.developer.DeveloperSettings.Keys;
import edu.cornell.mannlib.vitro.webapp.utils.developer.Key;
/**
* When we use a short view other than the default, log it.
@ -17,31 +16,26 @@ import edu.cornell.mannlib.vitro.webapp.utils.developer.DeveloperSettings.Keys;
public class ShortViewLogger {
private static final Log log = LogFactory.getLog(ShortViewLogger.class);
public static void log(VitroRequest vreq, String contextName,
Individual individual, String classUri, TemplateAndDataGetters tdg) {
if (isLogging(vreq)) {
public static void log(String contextName, Individual individual,
String classUri, TemplateAndDataGetters tdg) {
if (isLogging()) {
log.info("Using custom short view in " + contextName + " because '"
+ individual.getURI() + "' (" + individual.getLabel()
+ ") has type '" + classUri + "': " + tdg);
}
}
public static void log(VitroRequest vreq, String contextName,
Individual individual) {
if (isLogging(vreq)) {
public static void log(String contextName, Individual individual) {
if (isLogging()) {
log.info("Using default short view in " + contextName + " for '"
+ individual.getURI() + "' (" + individual.getLabel() + ")");
}
}
private static boolean isLogging(VitroRequest vreq) {
if (!log.isInfoEnabled()) {
return false;
}
DeveloperSettings settings = DeveloperSettings.getBean(vreq);
return settings.getBoolean(Keys.ENABLED)
&& settings
.getBoolean(Keys.PAGE_CONTENTS_LOG_CUSTOM_SHORT_VIEW);
private static boolean isLogging() {
return log.isInfoEnabled()
&& DeveloperSettings.getInstance().getBoolean(
Key.PAGE_CONTENTS_LOG_CUSTOM_SHORT_VIEW);
}
}

View file

@ -114,13 +114,13 @@ public class ShortViewServiceImpl implements ShortViewService {
TemplateAndDataGetters tdg = faker.getShortViewProperties(vreq,
individual, classUri, svContext.name());
if (tdg != null) {
ShortViewLogger.log(vreq, svContext.name(), individual, classUri, tdg);
ShortViewLogger.log(svContext.name(), individual, classUri, tdg);
return tdg;
}
}
// Didn't find one? Use the default values.
ShortViewLogger.log(vreq, svContext.name(), individual);
ShortViewLogger.log(svContext.name(), individual);
return new TemplateAndDataGetters(svContext.getDefaultTemplateName());
}

View file

@ -69,6 +69,9 @@ public class StartupManager implements ServletContextListener {
} catch (Exception e) {
ss.fatal(this, "Startup threw an unexpected exception.", e);
log.error("Startup threw an unexpected exception.", e);
} catch (Throwable t) {
log.fatal("Startup threw an unexpected error.", t);
throw t;
}
}
@ -177,6 +180,9 @@ public class StartupManager implements ServletContextListener {
ss.listenerExecuted(listener);
} catch (Exception e) {
ss.fatal(listener, "Threw unexpected exception", e);
} catch (Throwable t) {
log.fatal(listener + " Threw unexpected error", t);
throw t;
}
}
@ -214,6 +220,10 @@ public class StartupManager implements ServletContextListener {
} catch (Exception e) {
log.error("Unexpected exception from contextDestroyed() on '"
+ listener.getClass().getName() + "'", e);
} catch (Throwable t) {
log.fatal("Unexpected error from contextDestroyed() on '"
+ listener.getClass().getName() + "'", t);
throw t;
}
}
log.info("Called 'contextDestroyed' on all listeners.");

View file

@ -3,6 +3,7 @@
package edu.cornell.mannlib.vitro.webapp.utils.developer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.nio.file.Paths;
import java.util.Arrays;
@ -13,251 +14,92 @@ import java.util.Map;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties;
import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus;
/**
* Hold the global developer settings. Render to JSON when requested.
* A singleton holder for the developer settings.
*
* On first request, the "developer.properties" file is loaded from the Vitro
* home directory. If the file doesn't exist, or doesn't contain values for
* certain properties, those propertiew will keep their default values.
* Start with an empty settings map.
*
* The Setup class will read "developer.properties" from the Vitro home
* directory, and load its settings. If the file doesn't exist, or doesn't
* contain values for certain properties, those propertiew will keep their
* default values.
*
* An AJAX request can be used to update the properties. If the request has
* multiple values for a property, the first value will be used. If the request
* does not contain a value for a property, that property will keep its current
* value.
*
* The property names in "developer.properties" are not suitable as fields in
* the HTML panel, because they contain periods. For the HTML panel, we
* translate those periods to underscores.
*
* If the ENABLED flag is not set, then getBinary() will return false for all
* keys, and getString() will return the empty string. This simplifies the logic
* in the client code. Use getRawSettingsMap() to display the actual values in
* the developer panel.
*/
public class DeveloperSettings {
private static final Log log = LogFactory.getLog(DeveloperSettings.class);
public enum Keys {
/**
* Developer mode and developer panel is enabled.
*/
ENABLED("developer.enabled", true),
/**
* Users don't need authority to use the developer panel. But they still
* can't enable it without authority.
*/
PERMIT_ANONYMOUS_CONTROL("developer.permitAnonymousControl", true),
/**
* Load Freemarker templates every time they are requested.
*/
DEFEAT_FREEMARKER_CACHE("developer.defeatFreemarkerCache", true),
/**
* Show where each Freemarker template starts and stops.
*/
INSERT_FREEMARKER_DELIMITERS("developer.insertFreemarkerDelimiters",
true),
/**
* Load language property files every time they are requested.
*/
I18N_DEFEAT_CACHE("developer.i18n.defeatCache", true),
/**
* Enable the I18nLogger to log each string request.
*/
I18N_LOG_STRINGS("developer.i18n.logStringRequests", true),
/**
* Enable the LoggingRDFService
*/
LOGGING_RDF_ENABLE("developer.loggingRDFService.enable", true),
/**
* When logging with the LoggingRDFService, include a stack trace
*/
LOGGING_RDF_STACK_TRACE("developer.loggingRDFService.stackTrace", true),
/**
* Don't log with the LoggingRDFService unless the calling stack meets
* this restriction.
*/
LOGGING_RDF_QUERY_RESTRICTION(
"developer.loggingRDFService.queryRestriction", false),
/**
* Don't log with the LoggingRDFService unless the calling stack meets
* this restriction.
*/
LOGGING_RDF_STACK_RESTRICTION(
"developer.loggingRDFService.stackRestriction", false),
/**
* Tell the CustomListViewLogger to note the use of non-default custom
* list views.
*/
PAGE_CONTENTS_LOG_CUSTOM_LIST_VIEW(
"developer.pageContents.logCustomListView", true),
/**
* Tell the ShortViewLogger to note the use of non-default short views.
*/
PAGE_CONTENTS_LOG_CUSTOM_SHORT_VIEW(
"developer.pageContents.logCustomShortView", true);
private final String propertyName;
private final String elementId;
private final boolean bool;
private Keys(String propertyName, boolean bool) {
this.propertyName = propertyName;
this.elementId = produceElementId();
this.bool = bool;
}
public String propertyName() {
return propertyName;
}
public String elementId() {
return elementId;
}
boolean isBoolean() {
return bool;
}
/**
* The element ID is camel-case instead of period-delimited. So
* "developer.enabled" becomes "developerEnabled".
*/
String produceElementId() {
StringBuilder id = new StringBuilder(propertyName.length());
boolean capitalize = false;
for (int i = 0; i < propertyName.length(); i++) {
char c = propertyName.charAt(i);
if (c == '.') {
capitalize = true;
} else if (capitalize) {
id.append(Character.toUpperCase(c));
capitalize = false;
} else {
id.append(c);
}
}
return id.toString();
}
@Override
public String toString() {
return propertyName;
}
static Keys fromElementId(String id) {
for (Keys k : Keys.values()) {
if (k.elementId.equals(id)) {
return k;
}
}
log.error("Can't find key for element id: '" + id + "'");
return null;
}
static Keys fromPropertyName(String name) {
for (Keys k : Keys.values()) {
if (k.propertyName.equals(name)) {
return k;
}
}
log.error("Can't find key for property name: '" + name + "'");
return null;
}
}
// ----------------------------------------------------------------------
// The factory
// ----------------------------------------------------------------------
protected static final String ATTRIBUTE_NAME = DeveloperSettings.class
.getName();
private static final DeveloperSettings instance = new DeveloperSettings();
public static DeveloperSettings getBean(HttpServletRequest req) {
return getBean(req.getSession().getServletContext());
}
public static DeveloperSettings getBean(ServletContext ctx) {
Object o = ctx.getAttribute(ATTRIBUTE_NAME);
if (o instanceof DeveloperSettings) {
return (DeveloperSettings) o;
} else {
DeveloperSettings ds = new DeveloperSettings(ctx);
ctx.setAttribute(ATTRIBUTE_NAME, ds);
return ds;
}
public static DeveloperSettings getInstance() {
return instance;
}
// ----------------------------------------------------------------------
// The instance
// ----------------------------------------------------------------------
private final Map<Keys, Object> settings = new EnumMap<>(Keys.class);
private final Map<Key, String> settings;
protected DeveloperSettings(ServletContext ctx) {
updateFromFile(ctx);
private DeveloperSettings() {
this.settings = new EnumMap<>(Key.class);
}
/**
* Read the initial settings from "developer.properties" in the Vitro home
* directory.
*
* This method is "protected" so we can override it for unit tests.
*/
protected void updateFromFile(ServletContext ctx) {
Map<Keys, String> fromFile = new HashMap<>();
ConfigurationProperties props = ConfigurationProperties.getBean(ctx);
String home = props.getProperty("vitro.home");
File dsFile = Paths.get(home, "developer.properties").toFile();
if (dsFile.isFile()) {
try (FileReader reader = new FileReader(dsFile)) {
Properties dsProps = new Properties();
dsProps.load(reader);
for (String key : dsProps.stringPropertyNames()) {
fromFile.put(Keys.fromPropertyName(key),
dsProps.getProperty(key));
}
} catch (Exception e) {
log.warn("Failed to load 'developer.properties' file.", e);
}
} else {
log.debug("No developer.properties file.");
}
log.debug("Properties from file: " + fromFile);
update(fromFile);
}
/** Provide the parameter map from the HttpServletRequest */
public void updateFromRequest(Map<String, String[]> parameterMap) {
if (log.isDebugEnabled()) {
dumpParameterMap(parameterMap);
}
Map<Keys, String> fromRequest = new HashMap<>();
Map<Key, String> fromRequest = new HashMap<>();
for (String key : parameterMap.keySet()) {
fromRequest.put(Keys.fromElementId(key), parameterMap.get(key)[0]);
fromRequest.put(Key.fromElementId(key), parameterMap.get(key)[0]);
}
update(fromRequest);
}
private void update(Map<Keys, String> changedSettings) {
for (Keys key : Keys.values()) {
public void updateFromProperties(Properties properties) {
Map<Key, String> fromFile = new HashMap<>();
for (String key : properties.stringPropertyNames()) {
fromFile.put(Key.fromPropertyName(key), properties.getProperty(key));
}
update(fromFile);
}
/**
* Update by known keys, so we will ignore any irrelevant request
* parameters, or incorrect properties.
*/
private void update(Map<Key, String> changedSettings) {
for (Key key : Key.values()) {
String s = changedSettings.get(key);
if (s != null) {
if (key.isBoolean()) {
settings.put(key, Boolean.valueOf(s));
settings.put(key, Boolean.valueOf(s).toString());
} else {
settings.put(key, s);
}
@ -266,48 +108,68 @@ public class DeveloperSettings {
log.debug("DeveloperSettings: " + this);
}
public Object get(Keys key) {
if (key.isBoolean()) {
return getBoolean(key);
} else {
return getString(key);
}
}
public boolean getBoolean(Keys key) {
/**
* If developerMode is enabled, return the boolean value of the stored
* setting.
*/
public boolean getBoolean(Key key) {
if (!key.isBoolean()) {
throw new IllegalArgumentException("Key '" + key
+ "' does not take a boolean value.");
}
if (settings.containsKey(key)) {
if (Boolean.TRUE.equals(settings.get(Keys.ENABLED))) {
return (Boolean) settings.get(key);
}
log.warn("Key '" + key + "' does not take a boolean value.");
}
if (isDeveloperModeEnabled()) {
return Boolean.valueOf(settings.get(key));
} else {
return false;
}
}
public String getString(Keys key) {
/**
* If developerMode is enabled and the setting has a value, return that
* value. Otherwise, return the empty string.
*/
public String getString(Key key) {
if (key.isBoolean()) {
throw new IllegalArgumentException("Key '" + key
+ "' takes a boolean value.");
}
if (settings.containsKey(key)) {
if (Boolean.TRUE.equals(settings.get(Keys.ENABLED))) {
return (String) settings.get(key);
}
log.warn("Key '" + key + "' takes a boolean value.");
}
String value = settings.get(key);
if (value != null && isDeveloperModeEnabled()) {
return value;
} else {
return "";
}
}
public Map<String, Object> getSettingsMap() {
private boolean isDeveloperModeEnabled() {
return Boolean.valueOf(settings.get(Key.ENABLED));
}
/**
* Get the values of all the settings, by element ID, regardless of whether
* developerMode is enabled or not. Boolean settings are represented as
* actual Booleans, so Freemarker can perform logical tests on them.
*/
public Map<String, Object> getRawSettingsMap() {
Map<String, Object> map = new HashMap<>();
for (Keys key : Keys.values()) {
map.put(key.elementId(), get(key));
for (Key key : Key.values()) {
map.put(key.elementId(), getRawValue(key));
}
return map;
}
/**
* Get a String or Boolean value, as appropriate for the key. A boolean key
* with no value returns false. A non-boolean key with no value returns the
* empty string.
*/
private Object getRawValue(Key key) {
String value = settings.get(key);
if (key.isBoolean()) {
return Boolean.valueOf(value);
} else {
return (value == null) ? "" : value;
}
}
@Override
public String toString() {
return "DeveloperSettings" + settings;
@ -322,4 +184,43 @@ public class DeveloperSettings {
log.debug("Parameter map: " + map);
}
// ----------------------------------------------------------------------
// Setup class
// ----------------------------------------------------------------------
public static class Setup implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext ctx = sce.getServletContext();
StartupStatus ss = StartupStatus.getBean(ctx);
ConfigurationProperties props = ConfigurationProperties
.getBean(ctx);
DeveloperSettings devSettings = DeveloperSettings.getInstance();
String home = props.getProperty("vitro.home");
File dsFile = Paths.get(home, "developer.properties").toFile();
try (FileReader reader = new FileReader(dsFile)) {
Properties dsProps = new Properties();
dsProps.load(reader);
devSettings.updateFromProperties(dsProps);
log.info(devSettings);
ss.info(this, "Loaded the 'developer.properties' file: "
+ devSettings);
} catch (FileNotFoundException e) {
ss.info(this, "'developer.properties' file does not exist.");
} catch (Exception e) {
ss.warning(this,
"Failed to load the 'developer.properties' file.", e);
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// Nothing to remove.
}
}
}

View file

@ -2,7 +2,7 @@
package edu.cornell.mannlib.vitro.webapp.utils.developer;
import static edu.cornell.mannlib.vitro.webapp.utils.developer.DeveloperSettings.Keys.PERMIT_ANONYMOUS_CONTROL;
import static edu.cornell.mannlib.vitro.webapp.utils.developer.Key.PERMIT_ANONYMOUS_CONTROL;
import java.io.IOException;
import java.util.HashMap;
@ -42,7 +42,7 @@ public class DeveloperSettingsServlet extends VitroAjaxController {
@Override
protected void doRequest(VitroRequest vreq, HttpServletResponse resp)
throws ServletException, IOException {
DeveloperSettings settings = DeveloperSettings.getBean(vreq);
DeveloperSettings settings = DeveloperSettings.getInstance();
/*
* Are they allowed to control the panel?
@ -70,8 +70,9 @@ public class DeveloperSettingsServlet extends VitroAjaxController {
private Map<String, Object> buildBodyMap(boolean authorized,
DeveloperSettings settings) {
Map<String, Object> settingsMap = new HashMap<>();
settingsMap.putAll(settings.getSettingsMap());
settingsMap.putAll(settings.getRawSettingsMap());
settingsMap.put("mayControl", authorized);
Map<String, Object> bodyMap = new HashMap<>();
bodyMap.put("settings", settingsMap);
return bodyMap;
@ -84,7 +85,7 @@ public class DeveloperSettingsServlet extends VitroAjaxController {
}
private boolean isAuthorized(VitroRequest vreq) {
boolean authBySetting = DeveloperSettings.getBean(vreq).getBoolean(
boolean authBySetting = DeveloperSettings.getInstance().getBoolean(
PERMIT_ANONYMOUS_CONTROL);
boolean authByPolicy = PolicyHelper.isAuthorizedForActions(vreq,
SimplePermission.ENABLE_DEVELOPER_PANEL.ACTION);

View file

@ -0,0 +1,167 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.utils.developer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Keys for the DeveloperSettings. Each key holds these values:
*
* A property name, which specifies the key in developer.properties, like
* "this.thatThing"
*
* A flag to say whether this key controls a boolean value. If false, then the
* value is a string.
*
* We can derive the element ID for each key by replacing the periods in the
* property name with underscores.
*/
public enum Key {
/**
* Developer mode and developer panel is enabled.
*/
ENABLED("developer.enabled", true),
/**
* If the developer panel is enabled, may an anonymous user change the
* settings?
*/
PERMIT_ANONYMOUS_CONTROL("developer.permitAnonymousControl", true),
/**
* Load Freemarker templates every time they are requested.
*/
DEFEAT_FREEMARKER_CACHE("developer.defeatFreemarkerCache", true),
/**
* Show where each Freemarker template starts and stops.
*/
INSERT_FREEMARKER_DELIMITERS("developer.insertFreemarkerDelimiters", true),
/**
* Load language property files every time they are requested.
*/
I18N_DEFEAT_CACHE("developer.i18n.defeatCache", true),
/**
* Enable the I18nLogger to log each string request.
*/
I18N_LOG_STRINGS("developer.i18n.logStringRequests", true),
/**
* Enable the LoggingRDFService
*/
LOGGING_RDF_ENABLE("developer.loggingRDFService.enable", true),
/**
* When logging with the LoggingRDFService, include a stack trace
*/
LOGGING_RDF_STACK_TRACE("developer.loggingRDFService.stackTrace", true),
/**
* Don't log with the LoggingRDFService unless the calling stack meets this
* restriction.
*/
LOGGING_RDF_QUERY_RESTRICTION(
"developer.loggingRDFService.queryRestriction", false),
/**
* Don't log with the LoggingRDFService unless the calling stack meets this
* restriction.
*/
LOGGING_RDF_STACK_RESTRICTION(
"developer.loggingRDFService.stackRestriction", false),
/**
* Tell the CustomListViewLogger to note the use of non-default custom list
* views.
*/
PAGE_CONTENTS_LOG_CUSTOM_LIST_VIEW(
"developer.pageContents.logCustomListView", true),
/**
* Tell the ShortViewLogger to note the use of non-default short views.
*/
PAGE_CONTENTS_LOG_CUSTOM_SHORT_VIEW(
"developer.pageContents.logCustomShortView", true),
/**
* Enable the PolicyDecisionLogger.
*/
AUTHORIZATION_LOG_DECISIONS_ENABLE(
"developer.authorization.logDecisions.enable", true),
/**
* Enable the PolicyDecisionLogger.
*/
AUTHORIZATION_LOG_DECISIONS_ADD_IDENTIFERS(
"developer.authorization.logDecisions.addIdentifiers", true),
/**
* Enable the PolicyDecisionLogger.
*/
AUTHORIZATION_LOG_DECISIONS_SKIP_INCONCLUSIVE(
"developer.authorization.logDecisions.skipInconclusive", true),
/**
* Don't log policy decisions unless the requested action meets this
* restriction.
*/
AUTHORIZATION_LOG_DECISIONS_ACTION_RESTRICTION(
"developer.authorization.logDecisions.actionRestriction", false),
/**
* Don't log policy decisions unless the identifier bundle meets this
* restriction.
*/
AUTHORIZATION_LOG_DECISIONS_USER_RESTRICTION(
"developer.authorization.logDecisions.userRestriction", false),
/**
* Don't log policy decisions unless the policy meets this restriction.
*/
AUTHORIZATION_LOG_DECISIONS_POLICY_RESTRICTION(
"developer.authorization.logDecisions.policyRestriction", false);
private static final Log log = LogFactory.getLog(Key.class);
private final String propertyName;
private final boolean bool;
private Key(String propertyName, boolean bool) {
this.propertyName = propertyName;
this.bool = bool;
}
public String propertyName() {
return propertyName;
}
public String elementId() {
return propertyName.replace('.', '_');
}
boolean isBoolean() {
return bool;
}
@Override
public String toString() {
return propertyName;
}
static Key fromElementId(String id) {
return fromPropertyName(id.replace('_', '.'));
}
static Key fromPropertyName(String name) {
for (Key k : Key.values()) {
if (k.propertyName.equals(name)) {
return k;
}
}
log.error("Can't find key for property name: '" + name + "'");
return null;
}
}

View file

@ -6,9 +6,8 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.utils.developer.DeveloperSettings;
import edu.cornell.mannlib.vitro.webapp.utils.developer.DeveloperSettings.Keys;
import edu.cornell.mannlib.vitro.webapp.utils.developer.Key;
/**
* If enabled in the developer settings (and log levels), log every non-default
@ -18,21 +17,19 @@ public class CustomListViewLogger {
private static final Log log = LogFactory
.getLog(CustomListViewLogger.class);
public static void log(VitroRequest vreq, ObjectProperty op,
String configFileName) {
if (isLogging(vreq)) {
public static void log(ObjectProperty op, String configFileName) {
if (isLogging()) {
log.info("Using list view: '" + configFileName + "' for "
+ op.getURI() + " (" + op.getLabel() + ")");
}
}
private static boolean isLogging(VitroRequest vreq) {
private static boolean isLogging() {
if (!log.isInfoEnabled()) {
return false;
}
DeveloperSettings settings = DeveloperSettings.getBean(vreq);
return settings.getBoolean(Keys.ENABLED)
&& settings.getBoolean(Keys.PAGE_CONTENTS_LOG_CUSTOM_LIST_VIEW);
DeveloperSettings settings = DeveloperSettings.getInstance();
return settings.getBoolean(Key.PAGE_CONTENTS_LOG_CUSTOM_LIST_VIEW);
}
}

View file

@ -21,7 +21,6 @@ import edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.ObjectProp
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.ObjectPropertyTemplateModel;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.ObjectPropertyTemplateModel.ConfigError;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
public class PropertyListConfig {
private static final Log log = LogFactory.getLog(PropertyListConfig.class);
@ -62,7 +61,7 @@ public class PropertyListConfig {
if (configFileName == null) { // no custom config; use default config
configFileName = DEFAULT_CONFIG_FILE_NAME;
} else {
CustomListViewLogger.log(vreq, op, configFileName);
CustomListViewLogger.log(op, configFileName);
}
log.debug("Using list view config file " + configFileName + " for object property " + op.getURI());

View file

@ -14,9 +14,6 @@ import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAct
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.DropObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.EditObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatementImpl;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder.ParamMap;
@ -33,9 +30,9 @@ public class ObjectPropertyStatementTemplateModel extends PropertyStatementTempl
private final String editUrl;
private final String deleteUrl;
public ObjectPropertyStatementTemplateModel(String subjectUri, ObjectProperty predicate, String objectKey,
public ObjectPropertyStatementTemplateModel(String subjectUri, ObjectProperty property, String objectKey,
Map<String, String> data, String templateName, VitroRequest vreq) {
super(subjectUri, predicate, vreq);
super(subjectUri, property, vreq);
this.data = Collections.unmodifiableMap(new HashMap<String, String>(data));
this.objectUri = data.get(objectKey);
@ -43,15 +40,12 @@ public class ObjectPropertyStatementTemplateModel extends PropertyStatementTempl
//to keep track of later
this.objectKey = objectKey;
ObjectPropertyStatement ops = new ObjectPropertyStatementImpl(subjectUri, property.getURI(), objectUri);
ops.setProperty(predicate);
// Do delete url first, since it is used in building edit url
this.deleteUrl = makeDeleteUrl(ops);
this.editUrl = makeEditUrl(ops);
this.deleteUrl = makeDeleteUrl();
this.editUrl = makeEditUrl();
}
private String makeDeleteUrl(ObjectPropertyStatement ops) {
private String makeDeleteUrl() {
// Is the delete link suppressed for this property?
if (property.isDeleteLinkSuppressed()) {
return "";
@ -87,11 +81,11 @@ public class ObjectPropertyStatementTemplateModel extends PropertyStatementTempl
}
}
if (ops.getProperty()!= null && ops.getProperty().getDomainVClassURI() != null) {
params.put("domainUri", ops.getProperty().getDomainVClassURI());
if (property!= null && property.getDomainVClassURI() != null) {
params.put("domainUri", property.getDomainVClassURI());
}
if (ops.getProperty()!= null && ops.getProperty().getRangeVClassURI() != null) {
params.put("rangeUri", ops.getProperty().getRangeVClassURI());
if (property!= null && property.getRangeVClassURI() != null) {
params.put("rangeUri", property.getRangeVClassURI());
}
params.put("templateName", templateName);
@ -100,14 +94,14 @@ public class ObjectPropertyStatementTemplateModel extends PropertyStatementTempl
return UrlBuilder.getUrl(EDIT_PATH, params);
}
private String makeEditUrl(ObjectPropertyStatement ops) {
private String makeEditUrl() {
// Is the edit link suppressed for this property?
if (property.isEditLinkSuppressed()) {
return "";
}
// Determine whether the statement can be edited
RequestedAction action = new EditObjectPropertyStatement(vreq.getJenaOntModel(), ops);
RequestedAction action = new EditObjectPropertyStatement(vreq.getJenaOntModel(), subjectUri, property, objectUri);
if ( ! PolicyHelper.isAuthorizedForActions(vreq, action) ) {
return "";
}
@ -125,11 +119,11 @@ public class ObjectPropertyStatementTemplateModel extends PropertyStatementTempl
params.put("deleteProhibited", "prohibited");
}
if (ops.getProperty()!= null && ops.getProperty().getDomainVClassURI() != null) {
params.put("domainUri", ops.getProperty().getDomainVClassURI());
if (property!= null && property.getDomainVClassURI() != null) {
params.put("domainUri", property.getDomainVClassURI());
}
if (ops.getProperty()!= null && ops.getProperty().getRangeVClassURI() != null) {
params.put("rangeUri", ops.getProperty().getRangeVClassURI());
if (property!= null && property.getRangeVClassURI() != null) {
params.put("rangeUri", property.getRangeVClassURI());
}
params.putAll(UrlBuilder.getModelParams(vreq));

View file

@ -2,6 +2,9 @@
package edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual;
import static edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestActionConstants.SOME_LITERAL;
import static edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestActionConstants.SOME_URI;
import java.util.ArrayList;
import java.util.List;
@ -10,9 +13,12 @@ import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.auth.policy.PolicyHelper;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayDataProperty;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayDataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayObjectProperty;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatementImpl;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
@ -38,11 +44,11 @@ public class PropertyGroupTemplateModel extends BaseTemplateModel {
List<Property> propertyList = group.getPropertyList();
properties = new ArrayList<PropertyTemplateModel>(propertyList.size());
for (Property p : propertyList) {
if (p instanceof ObjectProperty) {
ObjectProperty op = (ObjectProperty) p;
RequestedAction dop = new DisplayObjectProperty(op);
if (!PolicyHelper.isAuthorizedForActions(vreq, dop)) {
if (!allowedToDisplay(vreq, op, subject)) {
continue;
}
ObjectPropertyTemplateModel tm = ObjectPropertyTemplateModel.getObjectPropertyTemplateModel(
@ -53,8 +59,7 @@ public class PropertyGroupTemplateModel extends BaseTemplateModel {
} else if (p instanceof DataProperty){
DataProperty dp = (DataProperty) p;
RequestedAction dop = new DisplayDataProperty(dp);
if (!PolicyHelper.isAuthorizedForActions(vreq, dop)) {
if (!allowedToDisplay(vreq, dp, subject)) {
continue;
}
properties.add(new DataPropertyTemplateModel(dp, subject, vreq, editing, populatedDataPropertyList));
@ -64,6 +69,47 @@ public class PropertyGroupTemplateModel extends BaseTemplateModel {
}
}
/**
* See if the property is permitted in its own right. If not, the property
* statement might still be permitted to a self-editor.
*/
private boolean allowedToDisplay(VitroRequest vreq, ObjectProperty op,
Individual subject) {
RequestedAction dop = new DisplayObjectProperty(op);
if (PolicyHelper.isAuthorizedForActions(vreq, dop)) {
return true;
}
RequestedAction dops = new DisplayObjectPropertyStatement(
subject.getURI(), op, SOME_URI);
if (PolicyHelper.isAuthorizedForActions(vreq, dops)) {
return true;
}
return false;
}
/**
* See if the property is permitted in its own right. If not, the property
* statement might still be permitted to a self-editor.
*/
private boolean allowedToDisplay(VitroRequest vreq, DataProperty dp,
Individual subject) {
RequestedAction dop = new DisplayDataProperty(dp);
if (PolicyHelper.isAuthorizedForActions(vreq, dop)) {
return true;
}
DataPropertyStatementImpl dps = new DataPropertyStatementImpl(
subject.getURI(), dp.getURI(), SOME_LITERAL);
RequestedAction dops = new DisplayDataPropertyStatement(dps);
if (PolicyHelper.isAuthorizedForActions(vreq, dops)) {
return true;
}
return false;
}
protected boolean isEmpty() {
return properties.isEmpty();
}
@ -73,6 +119,7 @@ public class PropertyGroupTemplateModel extends BaseTemplateModel {
}
@Override
public String toString(){
String ptmStr ="";
for( int i=0; i < properties.size() ; i ++ ){

View file

@ -85,13 +85,17 @@ public abstract class PropertyTemplateModel extends BaseTemplateModel {
verboseDisplay = new HashMap<String, Object>();
RoleLevel roleLevel = property.getHiddenFromDisplayBelowRoleLevel();
String roleLevelLabel = roleLevel != null ? roleLevel.getLabel() : "";
String roleLevelLabel = roleLevel != null ? roleLevel.getDisplayLabel() : "";
verboseDisplay.put("displayLevel", roleLevelLabel);
roleLevel = property.getProhibitedFromUpdateBelowRoleLevel();
roleLevelLabel = roleLevel != null ? roleLevel.getLabel() : "";
roleLevelLabel = roleLevel != null ? roleLevel.getUpdateLabel() : "";
verboseDisplay.put("updateLevel", roleLevelLabel);
roleLevel = property.getHiddenFromPublishBelowRoleLevel();
roleLevelLabel = roleLevel != null ? roleLevel.getDisplayLabel() : "";
verboseDisplay.put("publishLevel", roleLevelLabel);
verboseDisplay.put("localName", property.getLocalNameWithPrefix());
verboseDisplay.put("displayRank", getPropertyDisplayTier(property));

View file

@ -47,6 +47,13 @@ import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import edu.cornell.mannlib.vitro.webapp.controller.accounts.manageproxies.ProxyRelationshipSelectorTest;
/**
* A collection of useful routines to help when testing.
* <ul>
@ -404,8 +411,22 @@ public abstract class AbstractTestClass {
assertEquals(message, expected, actual);
}
@SuppressWarnings("unchecked")
protected <T> Set<T> buildSet(T... array) {
return new HashSet<T>(Arrays.asList(array));
}
protected OntModel readModelFromFile(String relativePath, String rdfType) throws IOException {
InputStream stream = this.getClass()
.getResourceAsStream(relativePath);
Model model = ModelFactory.createDefaultModel();
model.read(stream, null, rdfType);
stream.close();
OntModel ontModel = ModelFactory.createOntologyModel(
OntModelSpec.OWL_DL_MEM, model);
ontModel.prepare();
return ontModel;
}
}

View file

@ -4,11 +4,8 @@ package edu.cornell.mannlib.vitro.webapp.auth.policy;
import static edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestActionConstants.SOME_LITERAL;
import java.io.InputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Level;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@ -19,7 +16,6 @@ import stubs.javax.servlet.ServletContextStub;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.impl.RDFDefaultErrorHandler;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.ArrayIdentifierBundle;
@ -81,19 +77,6 @@ public class SelfEditingPolicy_2_Test extends AbstractTestClass {
@Before
public void setUp() throws Exception {
InputStream is = getClass().getResourceAsStream(
"./SelfEditingPolicy_2_Test.xml");
Assert.assertNotNull(is);
// suppress the warning messages from loading the model.
setLoggerLevel(RDFDefaultErrorHandler.class, Level.OFF);
// TODO This doesn't appear to be used for anything. Can it go away, along with the data file?
OntModel model = ModelFactory.createOntologyModel();
model.read(is, "");
Assert.assertNotNull(model);
Assert.assertTrue(model.size() > 0);
ServletContextStub ctx = new ServletContextStub();
PropertyRestrictionPolicyHelper.setBean(ctx,
PropertyRestrictionPolicyHelperStub

View file

@ -1,45 +0,0 @@
<?xml version='1.0' encoding='ISO-8859-1'?>
<!-- $This file is distributed under the terms of the license in /doc/license.txt$ -->
<rdf:RDF
xmlns:owl ="http://www.w3.org/2002/07/owl#"
xmlns:rdf ="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:rdfs ="http://www.w3.org/2000/01/rdf-schema#"
xmlns:xsd ="http://www.w3.org/2001/XMLSchema#"
xmlns:vitro="http://vitro.mannlib.cornell.edu/ns/vitro/0.7#"
xmlns =""
>
<owl:Ontology rdf:about="">
<rdfs:comment>
An ontology with a property with a prohibited annotation for unit testing.
</rdfs:comment>
</owl:Ontology>
<owl:AnnotationProperty rdf:about="vitro:selfEditProhibitedAnnot"/>
<owl:ObjectProperty rdf:about="vitro:hasSuperPowers">
<vitro:selfEditProhibitedAnnot rdf:datatype="xsd:boolean">true</vitro:selfEditProhibitedAnnot>
</owl:ObjectProperty>
<owl:ObjectProperty rdf:about="vitro:mayPrintMoney">
<vitro:selfEditProhibitedAnnot rdf:datatype="xsd:boolean">true</vitro:selfEditProhibitedAnnot>
</owl:ObjectProperty>
<owl:ObjectProperty rdf:about="vitro:getsOutOfJailFree">
<vitro:selfEditProhibitedAnnot rdf:datatype="xsd:boolean">true</vitro:selfEditProhibitedAnnot>
</owl:ObjectProperty>
<owl:ObjectProperty rdf:about="vitro:canDeleteModel">
<vitro:selfEditProhibitedAnnot rdf:datatype="xsd:boolean">true</vitro:selfEditProhibitedAnnot>
</owl:ObjectProperty>
<owl:DatatypeProperty rdf:about="vitro:felonies">
<vitro:selfEditProhibitedAnnot rdf:datatype="xsd:boolean">true</vitro:selfEditProhibitedAnnot>
</owl:DatatypeProperty>
</rdf:RDF>

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