Normalize line endings VIVO-101
This commit is contained in:
parent
b097a4d754
commit
54f79f2ea7
587 changed files with 91501 additions and 91501 deletions
|
@ -1,146 +1,146 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.auth.policy;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.log4j.Level;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import stubs.javax.servlet.ServletContextStub;
|
||||
import stubs.javax.servlet.http.HttpServletRequestStub;
|
||||
import stubs.javax.servlet.http.HttpSessionStub;
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization;
|
||||
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.Actions;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction;
|
||||
|
||||
/**
|
||||
* Test the function of PolicyHelper in authorizing simple actions.
|
||||
*/
|
||||
public class PolicyHelper_ActionsTest extends AbstractTestClass {
|
||||
private ServletContextStub ctx;
|
||||
private HttpSessionStub session;
|
||||
private HttpServletRequestStub req;
|
||||
|
||||
@Before
|
||||
public void setLogging() {
|
||||
setLoggerLevel(ServletPolicyList.class, Level.WARN);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
ctx = new ServletContextStub();
|
||||
|
||||
session = new HttpSessionStub();
|
||||
session.setServletContext(ctx);
|
||||
|
||||
req = new HttpServletRequestStub();
|
||||
req.setSession(session);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Action-level tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void authorizedForActionsNull() {
|
||||
createPolicy();
|
||||
assertEquals("null actions", true,
|
||||
PolicyHelper.isAuthorizedForActions(req, (Actions) null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authorizedForActionsEmpty() {
|
||||
createPolicy();
|
||||
assertEquals("empty actions", true,
|
||||
PolicyHelper.isAuthorizedForActions(req, new Actions()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authorizedForActionsOneClausePass() {
|
||||
createPolicy(new Action1(), new Action2());
|
||||
assertEquals("one clause pass", true,
|
||||
PolicyHelper.isAuthorizedForActions(req, new Actions(
|
||||
new Action1(), new Action2())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authorizedForActionsOneClauseFail() {
|
||||
createPolicy(new Action2());
|
||||
assertEquals("one clause fail", false,
|
||||
PolicyHelper.isAuthorizedForActions(req, new Actions(
|
||||
new Action1(), new Action2())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authorizedForActionsMultipleClausesPass() {
|
||||
createPolicy(new Action3());
|
||||
assertEquals("multiple clauses pass", true,
|
||||
PolicyHelper.isAuthorizedForActions(req, new Actions(
|
||||
new Action1(), new Action2()).or(new Action3())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authorizedForActionsMultipleClausesFail() {
|
||||
createPolicy(new Action1());
|
||||
assertEquals("multiple clauses fail", false,
|
||||
PolicyHelper.isAuthorizedForActions(req, new Actions(
|
||||
new Action1(), new Action2()).or(new Action3())));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private void createPolicy(RequestedAction... authorizedActions) {
|
||||
ServletPolicyList.addPolicy(ctx, new MySimplePolicy(authorizedActions));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Helper Classes
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
public static class Action1 extends RequestedAction {
|
||||
// actions must be public, with public constructor
|
||||
}
|
||||
|
||||
public static class Action2 extends RequestedAction {
|
||||
// actions must be public, with public constructor
|
||||
}
|
||||
|
||||
public static class Action3 extends RequestedAction {
|
||||
// actions must be public, with public constructor
|
||||
}
|
||||
|
||||
private static class MySimplePolicy implements PolicyIface {
|
||||
private final Set<RequestedAction> authorizedActions;
|
||||
|
||||
public MySimplePolicy(RequestedAction... authorizedActions) {
|
||||
this.authorizedActions = new HashSet<RequestedAction>(
|
||||
Arrays.asList(authorizedActions));
|
||||
}
|
||||
|
||||
@Override
|
||||
public PolicyDecision isAuthorized(IdentifierBundle whoToAuth,
|
||||
RequestedAction whatToAuth) {
|
||||
for (RequestedAction authorized : authorizedActions) {
|
||||
if (authorized.getClass().equals(whatToAuth.getClass())) {
|
||||
return new BasicPolicyDecision(Authorization.AUTHORIZED,
|
||||
"matched " + authorized.getClass().getSimpleName());
|
||||
}
|
||||
|
||||
}
|
||||
return new BasicPolicyDecision(Authorization.INCONCLUSIVE, "nope");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.auth.policy;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.log4j.Level;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import stubs.javax.servlet.ServletContextStub;
|
||||
import stubs.javax.servlet.http.HttpServletRequestStub;
|
||||
import stubs.javax.servlet.http.HttpSessionStub;
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization;
|
||||
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.Actions;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction;
|
||||
|
||||
/**
|
||||
* Test the function of PolicyHelper in authorizing simple actions.
|
||||
*/
|
||||
public class PolicyHelper_ActionsTest extends AbstractTestClass {
|
||||
private ServletContextStub ctx;
|
||||
private HttpSessionStub session;
|
||||
private HttpServletRequestStub req;
|
||||
|
||||
@Before
|
||||
public void setLogging() {
|
||||
setLoggerLevel(ServletPolicyList.class, Level.WARN);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
ctx = new ServletContextStub();
|
||||
|
||||
session = new HttpSessionStub();
|
||||
session.setServletContext(ctx);
|
||||
|
||||
req = new HttpServletRequestStub();
|
||||
req.setSession(session);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Action-level tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void authorizedForActionsNull() {
|
||||
createPolicy();
|
||||
assertEquals("null actions", true,
|
||||
PolicyHelper.isAuthorizedForActions(req, (Actions) null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authorizedForActionsEmpty() {
|
||||
createPolicy();
|
||||
assertEquals("empty actions", true,
|
||||
PolicyHelper.isAuthorizedForActions(req, new Actions()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authorizedForActionsOneClausePass() {
|
||||
createPolicy(new Action1(), new Action2());
|
||||
assertEquals("one clause pass", true,
|
||||
PolicyHelper.isAuthorizedForActions(req, new Actions(
|
||||
new Action1(), new Action2())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authorizedForActionsOneClauseFail() {
|
||||
createPolicy(new Action2());
|
||||
assertEquals("one clause fail", false,
|
||||
PolicyHelper.isAuthorizedForActions(req, new Actions(
|
||||
new Action1(), new Action2())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authorizedForActionsMultipleClausesPass() {
|
||||
createPolicy(new Action3());
|
||||
assertEquals("multiple clauses pass", true,
|
||||
PolicyHelper.isAuthorizedForActions(req, new Actions(
|
||||
new Action1(), new Action2()).or(new Action3())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authorizedForActionsMultipleClausesFail() {
|
||||
createPolicy(new Action1());
|
||||
assertEquals("multiple clauses fail", false,
|
||||
PolicyHelper.isAuthorizedForActions(req, new Actions(
|
||||
new Action1(), new Action2()).or(new Action3())));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private void createPolicy(RequestedAction... authorizedActions) {
|
||||
ServletPolicyList.addPolicy(ctx, new MySimplePolicy(authorizedActions));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Helper Classes
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
public static class Action1 extends RequestedAction {
|
||||
// actions must be public, with public constructor
|
||||
}
|
||||
|
||||
public static class Action2 extends RequestedAction {
|
||||
// actions must be public, with public constructor
|
||||
}
|
||||
|
||||
public static class Action3 extends RequestedAction {
|
||||
// actions must be public, with public constructor
|
||||
}
|
||||
|
||||
private static class MySimplePolicy implements PolicyIface {
|
||||
private final Set<RequestedAction> authorizedActions;
|
||||
|
||||
public MySimplePolicy(RequestedAction... authorizedActions) {
|
||||
this.authorizedActions = new HashSet<RequestedAction>(
|
||||
Arrays.asList(authorizedActions));
|
||||
}
|
||||
|
||||
@Override
|
||||
public PolicyDecision isAuthorized(IdentifierBundle whoToAuth,
|
||||
RequestedAction whatToAuth) {
|
||||
for (RequestedAction authorized : authorizedActions) {
|
||||
if (authorized.getClass().equals(whatToAuth.getClass())) {
|
||||
return new BasicPolicyDecision(Authorization.AUTHORIZED,
|
||||
"matched " + authorized.getClass().getSimpleName());
|
||||
}
|
||||
|
||||
}
|
||||
return new BasicPolicyDecision(Authorization.INCONCLUSIVE, "nope");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,370 +1,370 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.auth.policy;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
import org.apache.log4j.Level;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import stubs.javax.servlet.ServletContextStub;
|
||||
import stubs.javax.servlet.http.HttpServletRequestStub;
|
||||
import stubs.javax.servlet.http.HttpSessionStub;
|
||||
|
||||
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 com.hp.hpl.jena.rdf.model.Property;
|
||||
import com.hp.hpl.jena.rdf.model.Resource;
|
||||
import com.hp.hpl.jena.rdf.model.Statement;
|
||||
import com.hp.hpl.jena.rdf.model.StmtIterator;
|
||||
import com.hp.hpl.jena.util.iterator.NiceIterator;
|
||||
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization;
|
||||
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.auth.requestedAction.propstmt.AbstractPropertyStatementAction;
|
||||
|
||||
/**
|
||||
* Test the function of PolicyHelper in authorizing models of additions and
|
||||
* retractions.
|
||||
*
|
||||
* It is vital that these methods work even if the statements are presented in
|
||||
* the "wrong" order: one statement being authorized by a statement that appears
|
||||
* later in the list.
|
||||
*
|
||||
* In order to test that, we need to create a Model that will list the
|
||||
* statements in an order that we can predict, vis. the order in which they were
|
||||
* added.
|
||||
*
|
||||
* To avoid creating a SortedModel that implements dozens of methods, we instead
|
||||
* create a Proxy class that keeps the statements in order and lists them on
|
||||
* demand.
|
||||
*/
|
||||
public class PolicyHelper_ModelsTest extends AbstractTestClass {
|
||||
private static final String PRIMARY_RESOURCE_URI = "http://primaryResource";
|
||||
private static final String OTHER_RESOURCE_URI = "http://otherResource";
|
||||
private static final String FRIEND_PREDICATE_URI = "http://friend";
|
||||
private static final String SOME_PREDICATE_URI = "http://something";
|
||||
|
||||
private ServletContextStub ctx;
|
||||
private HttpSessionStub session;
|
||||
private HttpServletRequestStub req;
|
||||
private OntModel ontModel = ModelFactory
|
||||
.createOntologyModel(OntModelSpec.OWL_MEM);
|
||||
|
||||
private Model additions;
|
||||
private Model retractions;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
ctx = new ServletContextStub();
|
||||
|
||||
session = new HttpSessionStub();
|
||||
session.setServletContext(ctx);
|
||||
|
||||
req = new HttpServletRequestStub();
|
||||
req.setSession(session);
|
||||
|
||||
setLoggerLevel(ServletPolicyList.class, Level.WARN);
|
||||
ServletPolicyList.addPolicy(ctx, new MySimplePolicy());
|
||||
|
||||
// setLoggerLevel(PolicyHelper.class, Level.DEBUG);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The tests.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void rejectNullRequest() {
|
||||
setLoggerLevel(PolicyHelper.class, Level.ERROR); // suppress warning
|
||||
req = null;
|
||||
additions = model();
|
||||
retractions = model();
|
||||
assertAuthorized("reject null request", false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectNullAdditions() {
|
||||
setLoggerLevel(PolicyHelper.class, Level.ERROR); // suppress warning
|
||||
additions = null;
|
||||
retractions = model();
|
||||
assertAuthorized("reject null additions", false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectNullRetractions() {
|
||||
setLoggerLevel(PolicyHelper.class, Level.ERROR); // suppress warning
|
||||
additions = model();
|
||||
retractions = null;
|
||||
assertAuthorized("reject null retractions", false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectNullOntModel() {
|
||||
setLoggerLevel(PolicyHelper.class, Level.ERROR); // suppress warning
|
||||
additions = model();
|
||||
retractions = model();
|
||||
ontModel = null;
|
||||
assertAuthorized("reject null OntModel", false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void acceptEmptyChanges() {
|
||||
additions = model();
|
||||
retractions = model();
|
||||
assertAuthorized("accept empty changes add", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void acceptSimpleAdd() {
|
||||
additions = model(dataStatement(PRIMARY_RESOURCE_URI,
|
||||
SOME_PREDICATE_URI));
|
||||
retractions = model();
|
||||
assertAuthorized("accept simple add", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void acceptSimpleDrop() {
|
||||
additions = model();
|
||||
retractions = model(dataStatement(PRIMARY_RESOURCE_URI,
|
||||
SOME_PREDICATE_URI));
|
||||
assertAuthorized("accept simple add", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectSimpleAdd() {
|
||||
setLoggerLevel(PolicyHelper.class, Level.ERROR); // suppress warning
|
||||
additions = model(dataStatement(OTHER_RESOURCE_URI, SOME_PREDICATE_URI));
|
||||
retractions = model();
|
||||
assertAuthorized("reject simple add", false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectSimpleDrop() {
|
||||
setLoggerLevel(PolicyHelper.class, Level.ERROR); // suppress warning
|
||||
additions = model();
|
||||
retractions = model(dataStatement(OTHER_RESOURCE_URI,
|
||||
SOME_PREDICATE_URI));
|
||||
assertAuthorized("reject simple drop", false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void acceptAddBecauseOfExistingStatement() {
|
||||
ontModel.add(objectStatement(PRIMARY_RESOURCE_URI,
|
||||
FRIEND_PREDICATE_URI, OTHER_RESOURCE_URI));
|
||||
additions = model(dataStatement(OTHER_RESOURCE_URI, SOME_PREDICATE_URI));
|
||||
retractions = model();
|
||||
assertAuthorized("accept add because of existing statement", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void acceptDropBecauseOfExistingStatement() {
|
||||
ontModel.add(objectStatement(PRIMARY_RESOURCE_URI,
|
||||
FRIEND_PREDICATE_URI, OTHER_RESOURCE_URI));
|
||||
additions = model();
|
||||
retractions = model(dataStatement(OTHER_RESOURCE_URI,
|
||||
SOME_PREDICATE_URI));
|
||||
assertAuthorized("accept drop because of existing statement", true);
|
||||
}
|
||||
|
||||
/**
|
||||
* This test is the whole reason for the funky model that lists statements
|
||||
* in a known order. We need to know that the DataStatement is authorized
|
||||
* even though it relies on an ObjectStatement that appears later in the
|
||||
* list.
|
||||
*/
|
||||
@Test
|
||||
public void acceptAddBecauseOfOtherAdd() {
|
||||
additions = model(
|
||||
dataStatement(OTHER_RESOURCE_URI, SOME_PREDICATE_URI),
|
||||
objectStatement(PRIMARY_RESOURCE_URI, FRIEND_PREDICATE_URI,
|
||||
OTHER_RESOURCE_URI));
|
||||
retractions = model();
|
||||
assertAuthorized("accept add because of other add", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void acceptDropBecauseOfAdd() {
|
||||
additions = model(objectStatement(PRIMARY_RESOURCE_URI,
|
||||
FRIEND_PREDICATE_URI, OTHER_RESOURCE_URI));
|
||||
retractions = model(dataStatement(OTHER_RESOURCE_URI,
|
||||
SOME_PREDICATE_URI));
|
||||
assertAuthorized("accept drop because of add", true);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/** Build a data statement. */
|
||||
private Statement dataStatement(String subjectUri, String predicateUri) {
|
||||
Model model = ModelFactory.createDefaultModel();
|
||||
Resource subject = model.createResource(subjectUri);
|
||||
Property predicate = model.createProperty(predicateUri);
|
||||
return model.createStatement(subject, predicate, "whoCares?");
|
||||
}
|
||||
|
||||
/** Build an object statement. */
|
||||
private Statement objectStatement(String subjectUri, String predicateUri,
|
||||
String objectUri) {
|
||||
Model model = ModelFactory.createDefaultModel();
|
||||
Resource subject = model.createResource(subjectUri);
|
||||
Resource object = model.createResource(objectUri);
|
||||
Property predicate = model.createProperty(predicateUri);
|
||||
return model.createStatement(subject, predicate, object);
|
||||
}
|
||||
|
||||
/** Build a model. */
|
||||
private Model model(Statement... stmts) {
|
||||
Model innerModel = ModelFactory.createDefaultModel();
|
||||
Model proxy = (Model) Proxy.newProxyInstance(
|
||||
OrderedModelInvocationHandler.class.getClassLoader(),
|
||||
new Class[] { Model.class }, new OrderedModelInvocationHandler(
|
||||
innerModel));
|
||||
proxy.add(stmts);
|
||||
return proxy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether we are authorized to make the additions and retractions to
|
||||
* the model.
|
||||
*/
|
||||
private void assertAuthorized(String message, boolean expected) {
|
||||
boolean actual = PolicyHelper.isAuthorizedAsExpected(req, additions,
|
||||
retractions, ontModel);
|
||||
assertEquals(message, expected, actual);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Helper classes
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A model Proxy object built around this will list statements in the order
|
||||
* they were added.
|
||||
*
|
||||
* This only works if the statements were added by a call to
|
||||
* add(Statement[]), and if they are listed by a call to listStatements().
|
||||
* If the test used other methods to add statements, or if the PolicyHelper
|
||||
* used a different method to query the model, we would not be assured of
|
||||
* the order of the statements from the iterator.
|
||||
*/
|
||||
public static class OrderedModelInvocationHandler implements
|
||||
InvocationHandler {
|
||||
private final Model proxied;
|
||||
private final List<Statement> stmts = new ArrayList<Statement>();
|
||||
|
||||
public OrderedModelInvocationHandler(Model proxied) {
|
||||
this.proxied = proxied;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object invoke(Object proxy, Method method, Object[] args)
|
||||
throws Throwable {
|
||||
if (method.getName().equals("add") && (args.length == 1)
|
||||
&& (args[0] instanceof Statement[])) {
|
||||
stmts.addAll(Arrays.asList((Statement[]) args[0]));
|
||||
return method.invoke(proxied, args);
|
||||
}
|
||||
if (method.getName().equals("listStatements")
|
||||
&& ((args == null) || (args.length == 0))) {
|
||||
return new StatementListIterator(stmts);
|
||||
}
|
||||
|
||||
return method.invoke(proxied, args);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A StmtIterator that iterates over a list of statements.
|
||||
*/
|
||||
public static class StatementListIterator extends NiceIterator<Statement>
|
||||
implements StmtIterator {
|
||||
private final Iterator<Statement> innerIterator;
|
||||
|
||||
public StatementListIterator(List<Statement> stmts) {
|
||||
this.innerIterator = new ArrayList<Statement>(stmts).iterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Statement nextStatement() throws NoSuchElementException {
|
||||
return next();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return innerIterator.hasNext();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Statement next() {
|
||||
return innerIterator.next();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* A Policy that authorizes a statement iff (1) The subject is the primary
|
||||
* resource, or (2) The subject is related to the primary resource by a
|
||||
* "friend" property statement.
|
||||
*/
|
||||
private class MySimplePolicy implements PolicyIface {
|
||||
@Override
|
||||
public PolicyDecision isAuthorized(IdentifierBundle whoToAuth,
|
||||
RequestedAction whatToAuth) {
|
||||
if (!(whatToAuth instanceof AbstractPropertyStatementAction)) {
|
||||
return inconclusive();
|
||||
}
|
||||
|
||||
AbstractPropertyStatementAction action = (AbstractPropertyStatementAction) whatToAuth;
|
||||
|
||||
String subjectUri = action.getResourceUris()[0];
|
||||
if (PRIMARY_RESOURCE_URI.equals(subjectUri)) {
|
||||
return authorized();
|
||||
}
|
||||
|
||||
Statement friendStmt = objectStatement(PRIMARY_RESOURCE_URI,
|
||||
FRIEND_PREDICATE_URI, subjectUri);
|
||||
if (statementExists(action.getOntModel(), friendStmt)) {
|
||||
return authorized();
|
||||
}
|
||||
|
||||
return inconclusive();
|
||||
}
|
||||
|
||||
private boolean statementExists(OntModel oModel, Statement stmt) {
|
||||
StmtIterator stmts = oModel.listStatements(stmt.getSubject(),
|
||||
stmt.getPredicate(), stmt.getObject());
|
||||
try {
|
||||
return stmts.hasNext();
|
||||
} finally {
|
||||
stmts.close();
|
||||
}
|
||||
}
|
||||
|
||||
private PolicyDecision authorized() {
|
||||
return new BasicPolicyDecision(Authorization.AUTHORIZED, "");
|
||||
}
|
||||
|
||||
private PolicyDecision inconclusive() {
|
||||
return new BasicPolicyDecision(Authorization.INCONCLUSIVE, "");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.auth.policy;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
import org.apache.log4j.Level;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import stubs.javax.servlet.ServletContextStub;
|
||||
import stubs.javax.servlet.http.HttpServletRequestStub;
|
||||
import stubs.javax.servlet.http.HttpSessionStub;
|
||||
|
||||
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 com.hp.hpl.jena.rdf.model.Property;
|
||||
import com.hp.hpl.jena.rdf.model.Resource;
|
||||
import com.hp.hpl.jena.rdf.model.Statement;
|
||||
import com.hp.hpl.jena.rdf.model.StmtIterator;
|
||||
import com.hp.hpl.jena.util.iterator.NiceIterator;
|
||||
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization;
|
||||
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.auth.requestedAction.propstmt.AbstractPropertyStatementAction;
|
||||
|
||||
/**
|
||||
* Test the function of PolicyHelper in authorizing models of additions and
|
||||
* retractions.
|
||||
*
|
||||
* It is vital that these methods work even if the statements are presented in
|
||||
* the "wrong" order: one statement being authorized by a statement that appears
|
||||
* later in the list.
|
||||
*
|
||||
* In order to test that, we need to create a Model that will list the
|
||||
* statements in an order that we can predict, vis. the order in which they were
|
||||
* added.
|
||||
*
|
||||
* To avoid creating a SortedModel that implements dozens of methods, we instead
|
||||
* create a Proxy class that keeps the statements in order and lists them on
|
||||
* demand.
|
||||
*/
|
||||
public class PolicyHelper_ModelsTest extends AbstractTestClass {
|
||||
private static final String PRIMARY_RESOURCE_URI = "http://primaryResource";
|
||||
private static final String OTHER_RESOURCE_URI = "http://otherResource";
|
||||
private static final String FRIEND_PREDICATE_URI = "http://friend";
|
||||
private static final String SOME_PREDICATE_URI = "http://something";
|
||||
|
||||
private ServletContextStub ctx;
|
||||
private HttpSessionStub session;
|
||||
private HttpServletRequestStub req;
|
||||
private OntModel ontModel = ModelFactory
|
||||
.createOntologyModel(OntModelSpec.OWL_MEM);
|
||||
|
||||
private Model additions;
|
||||
private Model retractions;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
ctx = new ServletContextStub();
|
||||
|
||||
session = new HttpSessionStub();
|
||||
session.setServletContext(ctx);
|
||||
|
||||
req = new HttpServletRequestStub();
|
||||
req.setSession(session);
|
||||
|
||||
setLoggerLevel(ServletPolicyList.class, Level.WARN);
|
||||
ServletPolicyList.addPolicy(ctx, new MySimplePolicy());
|
||||
|
||||
// setLoggerLevel(PolicyHelper.class, Level.DEBUG);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The tests.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void rejectNullRequest() {
|
||||
setLoggerLevel(PolicyHelper.class, Level.ERROR); // suppress warning
|
||||
req = null;
|
||||
additions = model();
|
||||
retractions = model();
|
||||
assertAuthorized("reject null request", false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectNullAdditions() {
|
||||
setLoggerLevel(PolicyHelper.class, Level.ERROR); // suppress warning
|
||||
additions = null;
|
||||
retractions = model();
|
||||
assertAuthorized("reject null additions", false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectNullRetractions() {
|
||||
setLoggerLevel(PolicyHelper.class, Level.ERROR); // suppress warning
|
||||
additions = model();
|
||||
retractions = null;
|
||||
assertAuthorized("reject null retractions", false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectNullOntModel() {
|
||||
setLoggerLevel(PolicyHelper.class, Level.ERROR); // suppress warning
|
||||
additions = model();
|
||||
retractions = model();
|
||||
ontModel = null;
|
||||
assertAuthorized("reject null OntModel", false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void acceptEmptyChanges() {
|
||||
additions = model();
|
||||
retractions = model();
|
||||
assertAuthorized("accept empty changes add", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void acceptSimpleAdd() {
|
||||
additions = model(dataStatement(PRIMARY_RESOURCE_URI,
|
||||
SOME_PREDICATE_URI));
|
||||
retractions = model();
|
||||
assertAuthorized("accept simple add", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void acceptSimpleDrop() {
|
||||
additions = model();
|
||||
retractions = model(dataStatement(PRIMARY_RESOURCE_URI,
|
||||
SOME_PREDICATE_URI));
|
||||
assertAuthorized("accept simple add", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectSimpleAdd() {
|
||||
setLoggerLevel(PolicyHelper.class, Level.ERROR); // suppress warning
|
||||
additions = model(dataStatement(OTHER_RESOURCE_URI, SOME_PREDICATE_URI));
|
||||
retractions = model();
|
||||
assertAuthorized("reject simple add", false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectSimpleDrop() {
|
||||
setLoggerLevel(PolicyHelper.class, Level.ERROR); // suppress warning
|
||||
additions = model();
|
||||
retractions = model(dataStatement(OTHER_RESOURCE_URI,
|
||||
SOME_PREDICATE_URI));
|
||||
assertAuthorized("reject simple drop", false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void acceptAddBecauseOfExistingStatement() {
|
||||
ontModel.add(objectStatement(PRIMARY_RESOURCE_URI,
|
||||
FRIEND_PREDICATE_URI, OTHER_RESOURCE_URI));
|
||||
additions = model(dataStatement(OTHER_RESOURCE_URI, SOME_PREDICATE_URI));
|
||||
retractions = model();
|
||||
assertAuthorized("accept add because of existing statement", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void acceptDropBecauseOfExistingStatement() {
|
||||
ontModel.add(objectStatement(PRIMARY_RESOURCE_URI,
|
||||
FRIEND_PREDICATE_URI, OTHER_RESOURCE_URI));
|
||||
additions = model();
|
||||
retractions = model(dataStatement(OTHER_RESOURCE_URI,
|
||||
SOME_PREDICATE_URI));
|
||||
assertAuthorized("accept drop because of existing statement", true);
|
||||
}
|
||||
|
||||
/**
|
||||
* This test is the whole reason for the funky model that lists statements
|
||||
* in a known order. We need to know that the DataStatement is authorized
|
||||
* even though it relies on an ObjectStatement that appears later in the
|
||||
* list.
|
||||
*/
|
||||
@Test
|
||||
public void acceptAddBecauseOfOtherAdd() {
|
||||
additions = model(
|
||||
dataStatement(OTHER_RESOURCE_URI, SOME_PREDICATE_URI),
|
||||
objectStatement(PRIMARY_RESOURCE_URI, FRIEND_PREDICATE_URI,
|
||||
OTHER_RESOURCE_URI));
|
||||
retractions = model();
|
||||
assertAuthorized("accept add because of other add", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void acceptDropBecauseOfAdd() {
|
||||
additions = model(objectStatement(PRIMARY_RESOURCE_URI,
|
||||
FRIEND_PREDICATE_URI, OTHER_RESOURCE_URI));
|
||||
retractions = model(dataStatement(OTHER_RESOURCE_URI,
|
||||
SOME_PREDICATE_URI));
|
||||
assertAuthorized("accept drop because of add", true);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/** Build a data statement. */
|
||||
private Statement dataStatement(String subjectUri, String predicateUri) {
|
||||
Model model = ModelFactory.createDefaultModel();
|
||||
Resource subject = model.createResource(subjectUri);
|
||||
Property predicate = model.createProperty(predicateUri);
|
||||
return model.createStatement(subject, predicate, "whoCares?");
|
||||
}
|
||||
|
||||
/** Build an object statement. */
|
||||
private Statement objectStatement(String subjectUri, String predicateUri,
|
||||
String objectUri) {
|
||||
Model model = ModelFactory.createDefaultModel();
|
||||
Resource subject = model.createResource(subjectUri);
|
||||
Resource object = model.createResource(objectUri);
|
||||
Property predicate = model.createProperty(predicateUri);
|
||||
return model.createStatement(subject, predicate, object);
|
||||
}
|
||||
|
||||
/** Build a model. */
|
||||
private Model model(Statement... stmts) {
|
||||
Model innerModel = ModelFactory.createDefaultModel();
|
||||
Model proxy = (Model) Proxy.newProxyInstance(
|
||||
OrderedModelInvocationHandler.class.getClassLoader(),
|
||||
new Class[] { Model.class }, new OrderedModelInvocationHandler(
|
||||
innerModel));
|
||||
proxy.add(stmts);
|
||||
return proxy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether we are authorized to make the additions and retractions to
|
||||
* the model.
|
||||
*/
|
||||
private void assertAuthorized(String message, boolean expected) {
|
||||
boolean actual = PolicyHelper.isAuthorizedAsExpected(req, additions,
|
||||
retractions, ontModel);
|
||||
assertEquals(message, expected, actual);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Helper classes
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A model Proxy object built around this will list statements in the order
|
||||
* they were added.
|
||||
*
|
||||
* This only works if the statements were added by a call to
|
||||
* add(Statement[]), and if they are listed by a call to listStatements().
|
||||
* If the test used other methods to add statements, or if the PolicyHelper
|
||||
* used a different method to query the model, we would not be assured of
|
||||
* the order of the statements from the iterator.
|
||||
*/
|
||||
public static class OrderedModelInvocationHandler implements
|
||||
InvocationHandler {
|
||||
private final Model proxied;
|
||||
private final List<Statement> stmts = new ArrayList<Statement>();
|
||||
|
||||
public OrderedModelInvocationHandler(Model proxied) {
|
||||
this.proxied = proxied;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object invoke(Object proxy, Method method, Object[] args)
|
||||
throws Throwable {
|
||||
if (method.getName().equals("add") && (args.length == 1)
|
||||
&& (args[0] instanceof Statement[])) {
|
||||
stmts.addAll(Arrays.asList((Statement[]) args[0]));
|
||||
return method.invoke(proxied, args);
|
||||
}
|
||||
if (method.getName().equals("listStatements")
|
||||
&& ((args == null) || (args.length == 0))) {
|
||||
return new StatementListIterator(stmts);
|
||||
}
|
||||
|
||||
return method.invoke(proxied, args);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A StmtIterator that iterates over a list of statements.
|
||||
*/
|
||||
public static class StatementListIterator extends NiceIterator<Statement>
|
||||
implements StmtIterator {
|
||||
private final Iterator<Statement> innerIterator;
|
||||
|
||||
public StatementListIterator(List<Statement> stmts) {
|
||||
this.innerIterator = new ArrayList<Statement>(stmts).iterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Statement nextStatement() throws NoSuchElementException {
|
||||
return next();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return innerIterator.hasNext();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Statement next() {
|
||||
return innerIterator.next();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* A Policy that authorizes a statement iff (1) The subject is the primary
|
||||
* resource, or (2) The subject is related to the primary resource by a
|
||||
* "friend" property statement.
|
||||
*/
|
||||
private class MySimplePolicy implements PolicyIface {
|
||||
@Override
|
||||
public PolicyDecision isAuthorized(IdentifierBundle whoToAuth,
|
||||
RequestedAction whatToAuth) {
|
||||
if (!(whatToAuth instanceof AbstractPropertyStatementAction)) {
|
||||
return inconclusive();
|
||||
}
|
||||
|
||||
AbstractPropertyStatementAction action = (AbstractPropertyStatementAction) whatToAuth;
|
||||
|
||||
String subjectUri = action.getResourceUris()[0];
|
||||
if (PRIMARY_RESOURCE_URI.equals(subjectUri)) {
|
||||
return authorized();
|
||||
}
|
||||
|
||||
Statement friendStmt = objectStatement(PRIMARY_RESOURCE_URI,
|
||||
FRIEND_PREDICATE_URI, subjectUri);
|
||||
if (statementExists(action.getOntModel(), friendStmt)) {
|
||||
return authorized();
|
||||
}
|
||||
|
||||
return inconclusive();
|
||||
}
|
||||
|
||||
private boolean statementExists(OntModel oModel, Statement stmt) {
|
||||
StmtIterator stmts = oModel.listStatements(stmt.getSubject(),
|
||||
stmt.getPredicate(), stmt.getObject());
|
||||
try {
|
||||
return stmts.hasNext();
|
||||
} finally {
|
||||
stmts.close();
|
||||
}
|
||||
}
|
||||
|
||||
private PolicyDecision authorized() {
|
||||
return new BasicPolicyDecision(Authorization.AUTHORIZED, "");
|
||||
}
|
||||
|
||||
private PolicyDecision inconclusive() {
|
||||
return new BasicPolicyDecision(Authorization.INCONCLUSIVE, "");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,242 +1,242 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.auth.policy;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.apache.log4j.Level;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import stubs.javax.servlet.ServletContextStub;
|
||||
import stubs.javax.servlet.http.HttpServletRequestStub;
|
||||
import stubs.javax.servlet.http.HttpSessionStub;
|
||||
|
||||
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.Property;
|
||||
import com.hp.hpl.jena.rdf.model.Resource;
|
||||
import com.hp.hpl.jena.rdf.model.Statement;
|
||||
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization;
|
||||
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.auth.requestedAction.propstmt.AbstractDataPropertyStatementAction;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.AbstractObjectPropertyStatementAction;
|
||||
|
||||
/**
|
||||
* Test the function of PolicyHelper in authorizing statements and models.
|
||||
*/
|
||||
public class PolicyHelper_StatementsTest extends AbstractTestClass {
|
||||
private static final String APPROVED_SUBJECT_URI = "test://approvedSubjectUri";
|
||||
private static final String APPROVED_PREDICATE_URI = "test://approvedPredicateUri";
|
||||
private static final String UNAPPROVED_PREDICATE_URI = "test://bogusPredicateUri";
|
||||
private static final String APPROVED_OBJECT_URI = "test://approvedObjectUri";
|
||||
|
||||
private ServletContextStub ctx;
|
||||
private HttpSessionStub session;
|
||||
private HttpServletRequestStub req;
|
||||
private OntModel ontModel;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
ctx = new ServletContextStub();
|
||||
|
||||
session = new HttpSessionStub();
|
||||
session.setServletContext(ctx);
|
||||
|
||||
req = new HttpServletRequestStub();
|
||||
req.setSession(session);
|
||||
|
||||
ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
|
||||
|
||||
setLoggerLevel(ServletPolicyList.class, Level.WARN);
|
||||
ServletPolicyList.addPolicy(ctx, new MySimplePolicy());
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The tests.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void addNullStatement() {
|
||||
assertEquals("null statement", false,
|
||||
PolicyHelper.isAuthorizedToAdd(req, null, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addStatementWithNullRequest() {
|
||||
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
|
||||
APPROVED_PREDICATE_URI);
|
||||
assertEquals("null request", false,
|
||||
PolicyHelper.isAuthorizedToAdd(null, stmt, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addStatementToNullModel() {
|
||||
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
|
||||
APPROVED_PREDICATE_URI);
|
||||
assertEquals("authorized", false,
|
||||
PolicyHelper.isAuthorizedToAdd(req, stmt, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addAuthorizedDataStatement() {
|
||||
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
|
||||
APPROVED_PREDICATE_URI);
|
||||
assertEquals("authorized", true,
|
||||
PolicyHelper.isAuthorizedToAdd(req, stmt, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addAuthorizedObjectStatement() {
|
||||
Statement stmt = objectStatement(APPROVED_SUBJECT_URI,
|
||||
APPROVED_PREDICATE_URI, APPROVED_OBJECT_URI);
|
||||
assertEquals("authorized", true,
|
||||
PolicyHelper.isAuthorizedToAdd(req, stmt, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addUnauthorizedDataStatement() {
|
||||
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
|
||||
UNAPPROVED_PREDICATE_URI);
|
||||
assertEquals("not authorized", false,
|
||||
PolicyHelper.isAuthorizedToAdd(req, stmt, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addUnauthorizedObjectStatement() {
|
||||
Statement stmt = objectStatement(APPROVED_SUBJECT_URI,
|
||||
UNAPPROVED_PREDICATE_URI, APPROVED_OBJECT_URI);
|
||||
assertEquals("not authorized", false,
|
||||
PolicyHelper.isAuthorizedToAdd(req, stmt, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dropNullStatement() {
|
||||
assertEquals("null statement", false, PolicyHelper.isAuthorizedToDrop(
|
||||
req, (Statement) null, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dropStatementWithNullRequest() {
|
||||
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
|
||||
APPROVED_PREDICATE_URI);
|
||||
assertEquals("null request", false,
|
||||
PolicyHelper.isAuthorizedToDrop(null, stmt, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dropStatementFromNullModel() {
|
||||
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
|
||||
APPROVED_PREDICATE_URI);
|
||||
assertEquals("authorized", false,
|
||||
PolicyHelper.isAuthorizedToDrop(req, stmt, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dropAuthorizedDataStatement() {
|
||||
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
|
||||
APPROVED_PREDICATE_URI);
|
||||
assertEquals("authorized", true,
|
||||
PolicyHelper.isAuthorizedToDrop(req, stmt, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dropAuthorizedObjectStatement() {
|
||||
Statement stmt = objectStatement(APPROVED_SUBJECT_URI,
|
||||
APPROVED_PREDICATE_URI, APPROVED_OBJECT_URI);
|
||||
assertEquals("authorized", true,
|
||||
PolicyHelper.isAuthorizedToDrop(req, stmt, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dropUnauthorizedDataStatement() {
|
||||
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
|
||||
UNAPPROVED_PREDICATE_URI);
|
||||
assertEquals("not authorized", false,
|
||||
PolicyHelper.isAuthorizedToDrop(req, stmt, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dropUnauthorizedObjectStatement() {
|
||||
Statement stmt = objectStatement(APPROVED_SUBJECT_URI,
|
||||
UNAPPROVED_PREDICATE_URI, APPROVED_OBJECT_URI);
|
||||
assertEquals("not authorized", false,
|
||||
PolicyHelper.isAuthorizedToDrop(req, stmt, ontModel));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/** Build a data statement. */
|
||||
private Statement dataStatement(String subjectUri, String predicateUri) {
|
||||
Resource subject = ontModel.createResource(subjectUri);
|
||||
Property predicate = ontModel.createProperty(predicateUri);
|
||||
return ontModel.createStatement(subject, predicate, "whoCares?");
|
||||
}
|
||||
|
||||
/** Build a object statement. */
|
||||
private Statement objectStatement(String subjectUri, String predicateUri,
|
||||
String objectUri) {
|
||||
Resource subject = ontModel.createResource(subjectUri);
|
||||
Resource object = ontModel.createResource(objectUri);
|
||||
Property predicate = ontModel.createProperty(predicateUri);
|
||||
return ontModel.createStatement(subject, predicate, object);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Helper classes
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private static class MySimplePolicy implements PolicyIface {
|
||||
@Override
|
||||
public PolicyDecision isAuthorized(IdentifierBundle whoToAuth,
|
||||
RequestedAction whatToAuth) {
|
||||
if (whatToAuth instanceof AbstractDataPropertyStatementAction) {
|
||||
return isAuthorized((AbstractDataPropertyStatementAction) whatToAuth);
|
||||
} else if (whatToAuth instanceof AbstractObjectPropertyStatementAction) {
|
||||
return isAuthorized((AbstractObjectPropertyStatementAction) whatToAuth);
|
||||
} else {
|
||||
return inconclusive();
|
||||
}
|
||||
}
|
||||
|
||||
private PolicyDecision isAuthorized(
|
||||
AbstractDataPropertyStatementAction whatToAuth) {
|
||||
if ((APPROVED_SUBJECT_URI.equals(whatToAuth.getSubjectUri()))
|
||||
&& (APPROVED_PREDICATE_URI.equals(whatToAuth
|
||||
.getPredicateUri()))) {
|
||||
return authorized();
|
||||
} else {
|
||||
return inconclusive();
|
||||
}
|
||||
}
|
||||
|
||||
private PolicyDecision isAuthorized(
|
||||
AbstractObjectPropertyStatementAction whatToAuth) {
|
||||
if ((APPROVED_SUBJECT_URI.equals(whatToAuth.getSubjectUri()))
|
||||
&& (APPROVED_PREDICATE_URI.equals(whatToAuth
|
||||
.getPredicateUri()))
|
||||
&& (APPROVED_OBJECT_URI.equals(whatToAuth.getObjectUri()))) {
|
||||
return authorized();
|
||||
} else {
|
||||
return inconclusive();
|
||||
}
|
||||
}
|
||||
|
||||
private PolicyDecision authorized() {
|
||||
return new BasicPolicyDecision(Authorization.AUTHORIZED, "");
|
||||
}
|
||||
|
||||
private PolicyDecision inconclusive() {
|
||||
return new BasicPolicyDecision(Authorization.INCONCLUSIVE, "");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.auth.policy;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.apache.log4j.Level;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import stubs.javax.servlet.ServletContextStub;
|
||||
import stubs.javax.servlet.http.HttpServletRequestStub;
|
||||
import stubs.javax.servlet.http.HttpSessionStub;
|
||||
|
||||
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.Property;
|
||||
import com.hp.hpl.jena.rdf.model.Resource;
|
||||
import com.hp.hpl.jena.rdf.model.Statement;
|
||||
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization;
|
||||
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.auth.requestedAction.propstmt.AbstractDataPropertyStatementAction;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.AbstractObjectPropertyStatementAction;
|
||||
|
||||
/**
|
||||
* Test the function of PolicyHelper in authorizing statements and models.
|
||||
*/
|
||||
public class PolicyHelper_StatementsTest extends AbstractTestClass {
|
||||
private static final String APPROVED_SUBJECT_URI = "test://approvedSubjectUri";
|
||||
private static final String APPROVED_PREDICATE_URI = "test://approvedPredicateUri";
|
||||
private static final String UNAPPROVED_PREDICATE_URI = "test://bogusPredicateUri";
|
||||
private static final String APPROVED_OBJECT_URI = "test://approvedObjectUri";
|
||||
|
||||
private ServletContextStub ctx;
|
||||
private HttpSessionStub session;
|
||||
private HttpServletRequestStub req;
|
||||
private OntModel ontModel;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
ctx = new ServletContextStub();
|
||||
|
||||
session = new HttpSessionStub();
|
||||
session.setServletContext(ctx);
|
||||
|
||||
req = new HttpServletRequestStub();
|
||||
req.setSession(session);
|
||||
|
||||
ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
|
||||
|
||||
setLoggerLevel(ServletPolicyList.class, Level.WARN);
|
||||
ServletPolicyList.addPolicy(ctx, new MySimplePolicy());
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The tests.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void addNullStatement() {
|
||||
assertEquals("null statement", false,
|
||||
PolicyHelper.isAuthorizedToAdd(req, null, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addStatementWithNullRequest() {
|
||||
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
|
||||
APPROVED_PREDICATE_URI);
|
||||
assertEquals("null request", false,
|
||||
PolicyHelper.isAuthorizedToAdd(null, stmt, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addStatementToNullModel() {
|
||||
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
|
||||
APPROVED_PREDICATE_URI);
|
||||
assertEquals("authorized", false,
|
||||
PolicyHelper.isAuthorizedToAdd(req, stmt, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addAuthorizedDataStatement() {
|
||||
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
|
||||
APPROVED_PREDICATE_URI);
|
||||
assertEquals("authorized", true,
|
||||
PolicyHelper.isAuthorizedToAdd(req, stmt, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addAuthorizedObjectStatement() {
|
||||
Statement stmt = objectStatement(APPROVED_SUBJECT_URI,
|
||||
APPROVED_PREDICATE_URI, APPROVED_OBJECT_URI);
|
||||
assertEquals("authorized", true,
|
||||
PolicyHelper.isAuthorizedToAdd(req, stmt, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addUnauthorizedDataStatement() {
|
||||
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
|
||||
UNAPPROVED_PREDICATE_URI);
|
||||
assertEquals("not authorized", false,
|
||||
PolicyHelper.isAuthorizedToAdd(req, stmt, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addUnauthorizedObjectStatement() {
|
||||
Statement stmt = objectStatement(APPROVED_SUBJECT_URI,
|
||||
UNAPPROVED_PREDICATE_URI, APPROVED_OBJECT_URI);
|
||||
assertEquals("not authorized", false,
|
||||
PolicyHelper.isAuthorizedToAdd(req, stmt, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dropNullStatement() {
|
||||
assertEquals("null statement", false, PolicyHelper.isAuthorizedToDrop(
|
||||
req, (Statement) null, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dropStatementWithNullRequest() {
|
||||
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
|
||||
APPROVED_PREDICATE_URI);
|
||||
assertEquals("null request", false,
|
||||
PolicyHelper.isAuthorizedToDrop(null, stmt, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dropStatementFromNullModel() {
|
||||
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
|
||||
APPROVED_PREDICATE_URI);
|
||||
assertEquals("authorized", false,
|
||||
PolicyHelper.isAuthorizedToDrop(req, stmt, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dropAuthorizedDataStatement() {
|
||||
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
|
||||
APPROVED_PREDICATE_URI);
|
||||
assertEquals("authorized", true,
|
||||
PolicyHelper.isAuthorizedToDrop(req, stmt, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dropAuthorizedObjectStatement() {
|
||||
Statement stmt = objectStatement(APPROVED_SUBJECT_URI,
|
||||
APPROVED_PREDICATE_URI, APPROVED_OBJECT_URI);
|
||||
assertEquals("authorized", true,
|
||||
PolicyHelper.isAuthorizedToDrop(req, stmt, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dropUnauthorizedDataStatement() {
|
||||
Statement stmt = dataStatement(APPROVED_SUBJECT_URI,
|
||||
UNAPPROVED_PREDICATE_URI);
|
||||
assertEquals("not authorized", false,
|
||||
PolicyHelper.isAuthorizedToDrop(req, stmt, ontModel));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dropUnauthorizedObjectStatement() {
|
||||
Statement stmt = objectStatement(APPROVED_SUBJECT_URI,
|
||||
UNAPPROVED_PREDICATE_URI, APPROVED_OBJECT_URI);
|
||||
assertEquals("not authorized", false,
|
||||
PolicyHelper.isAuthorizedToDrop(req, stmt, ontModel));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/** Build a data statement. */
|
||||
private Statement dataStatement(String subjectUri, String predicateUri) {
|
||||
Resource subject = ontModel.createResource(subjectUri);
|
||||
Property predicate = ontModel.createProperty(predicateUri);
|
||||
return ontModel.createStatement(subject, predicate, "whoCares?");
|
||||
}
|
||||
|
||||
/** Build a object statement. */
|
||||
private Statement objectStatement(String subjectUri, String predicateUri,
|
||||
String objectUri) {
|
||||
Resource subject = ontModel.createResource(subjectUri);
|
||||
Resource object = ontModel.createResource(objectUri);
|
||||
Property predicate = ontModel.createProperty(predicateUri);
|
||||
return ontModel.createStatement(subject, predicate, object);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Helper classes
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private static class MySimplePolicy implements PolicyIface {
|
||||
@Override
|
||||
public PolicyDecision isAuthorized(IdentifierBundle whoToAuth,
|
||||
RequestedAction whatToAuth) {
|
||||
if (whatToAuth instanceof AbstractDataPropertyStatementAction) {
|
||||
return isAuthorized((AbstractDataPropertyStatementAction) whatToAuth);
|
||||
} else if (whatToAuth instanceof AbstractObjectPropertyStatementAction) {
|
||||
return isAuthorized((AbstractObjectPropertyStatementAction) whatToAuth);
|
||||
} else {
|
||||
return inconclusive();
|
||||
}
|
||||
}
|
||||
|
||||
private PolicyDecision isAuthorized(
|
||||
AbstractDataPropertyStatementAction whatToAuth) {
|
||||
if ((APPROVED_SUBJECT_URI.equals(whatToAuth.getSubjectUri()))
|
||||
&& (APPROVED_PREDICATE_URI.equals(whatToAuth
|
||||
.getPredicateUri()))) {
|
||||
return authorized();
|
||||
} else {
|
||||
return inconclusive();
|
||||
}
|
||||
}
|
||||
|
||||
private PolicyDecision isAuthorized(
|
||||
AbstractObjectPropertyStatementAction whatToAuth) {
|
||||
if ((APPROVED_SUBJECT_URI.equals(whatToAuth.getSubjectUri()))
|
||||
&& (APPROVED_PREDICATE_URI.equals(whatToAuth
|
||||
.getPredicateUri()))
|
||||
&& (APPROVED_OBJECT_URI.equals(whatToAuth.getObjectUri()))) {
|
||||
return authorized();
|
||||
} else {
|
||||
return inconclusive();
|
||||
}
|
||||
}
|
||||
|
||||
private PolicyDecision authorized() {
|
||||
return new BasicPolicyDecision(Authorization.AUTHORIZED, "");
|
||||
}
|
||||
|
||||
private PolicyDecision inconclusive() {
|
||||
return new BasicPolicyDecision(Authorization.INCONCLUSIVE, "");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,314 +1,314 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.auth.policy;
|
||||
|
||||
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;
|
||||
|
||||
import stubs.edu.cornell.mannlib.vitro.webapp.auth.policy.bean.PropertyRestrictionPolicyHelperStub;
|
||||
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;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.identifier.Identifier;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.identifier.common.HasProfile;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.policy.bean.PropertyRestrictionPolicyHelper;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.AddObjectPropertyStatement;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.EditDataPropertyStatement;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.EditObjectPropertyStatement;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.IndividualImpl;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
|
||||
public class SelfEditingPolicy_2_Test extends AbstractTestClass {
|
||||
private static final Log log = LogFactory
|
||||
.getLog(SelfEditingPolicy_2_Test.class);
|
||||
|
||||
/** We may edit objects in this arbitrary namespace. */
|
||||
private static final String SAFE_NS = "http://test.mannlib.cornell.edu/ns/01#";
|
||||
|
||||
/** We are not allowed to edit objects in the administrative namespace. */
|
||||
private static final String ADMIN_NS = VitroVocabulary.vitroURI;
|
||||
|
||||
/** The URI of a SelfEditor. */
|
||||
private static final String SELFEDITOR_URI = SAFE_NS + "individual000";
|
||||
|
||||
/** Some things that are safe to edit. */
|
||||
private static final String SAFE_RESOURCE = SAFE_NS + "individual123";
|
||||
private static final String SAFE_PREDICATE = SAFE_NS + "hasHairStyle";
|
||||
|
||||
/** Some things that are not safe to edit. */
|
||||
private static final String ADMIN_RESOURCE = ADMIN_NS + "individual666";
|
||||
private static final String ADMIN_PREDICATE_1 = ADMIN_NS + "hasSuperPowers";
|
||||
private static final String ADMIN_PREDICATE_2 = ADMIN_NS + "mayPrintMoney";
|
||||
private static final String ADMIN_PREDICATE_3 = ADMIN_NS
|
||||
+ "getsOutOfJailFree";
|
||||
private static final String ADMIN_PREDICATE_4 = ADMIN_NS + "canDeleteModel";
|
||||
|
||||
/** The policy we are testing. */
|
||||
SelfEditingPolicy policy;
|
||||
|
||||
/** A SelfEditing individual identifier. */
|
||||
Individual seIndividual;
|
||||
|
||||
/** A bundle that contains a SelfEditing individual. */
|
||||
IdentifierBundle ids;
|
||||
|
||||
/**
|
||||
* An empty model that acts as a placeholder in the requested actions. The
|
||||
* SelfEditingPolicy does not base its decisions on the contents of the
|
||||
* model.
|
||||
*/
|
||||
private OntModel ontModel;
|
||||
|
||||
|
||||
@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
|
||||
.getInstance(new String[] { ADMIN_NS }));
|
||||
|
||||
policy = new SelfEditingPolicy(ctx);
|
||||
Assert.assertNotNull(policy);
|
||||
|
||||
seIndividual = new IndividualImpl();
|
||||
seIndividual.setURI(SELFEDITOR_URI);
|
||||
|
||||
ids = new ArrayIdentifierBundle(new HasProfile(SELFEDITOR_URI));
|
||||
|
||||
ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
|
||||
|
||||
// setLoggerLevel(SelfEditingPolicySetupTest.class, Level.DEBUG);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// General tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void nullRequestedAction() {
|
||||
PolicyDecision dec = policy.isAuthorized(ids, null);
|
||||
Assert.assertNotNull(dec);
|
||||
Assert.assertEquals(Authorization.INCONCLUSIVE, dec.getAuthorized());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nullIdentifierBundle() {
|
||||
AddObjectPropertyStatement whatToAuth = new AddObjectPropertyStatement(
|
||||
ontModel, SELFEDITOR_URI, SAFE_PREDICATE, SAFE_RESOURCE);
|
||||
PolicyDecision dec = policy.isAuthorized(null, whatToAuth);
|
||||
Assert.assertNotNull(dec);
|
||||
Assert.assertEquals(Authorization.INCONCLUSIVE, dec.getAuthorized());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noSelfEditorIdentifier() {
|
||||
ids.clear();
|
||||
ids.add(new Identifier() { /* empty identifier */
|
||||
});
|
||||
assertAddObjectPropStmt(SELFEDITOR_URI, SAFE_PREDICATE, SAFE_RESOURCE,
|
||||
Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Tests against AddObjectPropStmt
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void addObjectPropStmtSuccess1() {
|
||||
assertAddObjectPropStmt(SELFEDITOR_URI, SAFE_PREDICATE, SAFE_RESOURCE,
|
||||
Authorization.AUTHORIZED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addObjectPropStmtSuccess2() {
|
||||
assertAddObjectPropStmt(SAFE_RESOURCE, SAFE_PREDICATE, SELFEDITOR_URI,
|
||||
Authorization.AUTHORIZED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addObjectPropStmtUnsafePredicate1() {
|
||||
assertAddObjectPropStmt(SELFEDITOR_URI, ADMIN_PREDICATE_1,
|
||||
SAFE_RESOURCE, Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addObjectPropStmtUnsafePredicate2() {
|
||||
assertAddObjectPropStmt(SAFE_RESOURCE, ADMIN_PREDICATE_1,
|
||||
SELFEDITOR_URI, Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addObjectPropStmtUnsafePredicate3() {
|
||||
assertAddObjectPropStmt(SELFEDITOR_URI, ADMIN_PREDICATE_2,
|
||||
SAFE_RESOURCE, Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addObjectPropStmtUnsafePredicate4() {
|
||||
assertAddObjectPropStmt(SELFEDITOR_URI, ADMIN_PREDICATE_3,
|
||||
SAFE_RESOURCE, Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addObjectPropStmtUnsafePredicate5() {
|
||||
assertAddObjectPropStmt(SELFEDITOR_URI, ADMIN_PREDICATE_4,
|
||||
SAFE_RESOURCE, Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Tests against EditObjPropStmt
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void editObjectPropStmtSuccess1() {
|
||||
assertEditObjPropStmt(SELFEDITOR_URI, SAFE_PREDICATE, SAFE_RESOURCE,
|
||||
Authorization.AUTHORIZED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void editObjectPropStmtSuccess2() {
|
||||
assertEditObjPropStmt(SAFE_RESOURCE, SAFE_PREDICATE, SELFEDITOR_URI,
|
||||
Authorization.AUTHORIZED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void editObjectPropStmtEditorNotInvolved() {
|
||||
// this is the case where the editor is not part of the stmt
|
||||
assertEditObjPropStmt(SAFE_RESOURCE, SAFE_PREDICATE, SAFE_RESOURCE,
|
||||
Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void editObjectPropStmtUnsafeResource() {
|
||||
assertEditObjPropStmt(SELFEDITOR_URI, SAFE_PREDICATE, ADMIN_RESOURCE,
|
||||
Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void editObjectPropStmtUnsafePredicate1() {
|
||||
assertEditObjPropStmt(SELFEDITOR_URI, ADMIN_PREDICATE_4, SAFE_RESOURCE,
|
||||
Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void editObjectPropStmtUnsafePredicate2() {
|
||||
assertEditObjPropStmt(SAFE_RESOURCE, ADMIN_PREDICATE_4, SELFEDITOR_URI,
|
||||
Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void editObjectPropStmtUnsafeBoth() {
|
||||
assertEditObjPropStmt(SELFEDITOR_URI, ADMIN_PREDICATE_4,
|
||||
ADMIN_RESOURCE, Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Tests against EditDataPropStmt
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void editDataPropSuccess() {
|
||||
assertEditDataPropStmt(SELFEDITOR_URI, SAFE_PREDICATE, "junk",
|
||||
Authorization.AUTHORIZED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void editDataPropUnsafePredicate() {
|
||||
assertEditDataPropStmt(SELFEDITOR_URI, ADMIN_PREDICATE_1, "junk",
|
||||
Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void editDataPropUnsafeResource() {
|
||||
assertEditDataPropStmt(ADMIN_RESOURCE, SAFE_PREDICATE, null,
|
||||
Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void editDataPropNoCloseRelation() {
|
||||
assertEditDataPropStmt(SAFE_RESOURCE, SAFE_PREDICATE, null,
|
||||
Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void editDataPropModelProhibited() {
|
||||
// model prohibited
|
||||
assertEditDataPropStmt(SAFE_RESOURCE, ADMIN_PREDICATE_1, null,
|
||||
Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// Support methods
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Create an {@link AddObjectPropertyStatement}, test it, and compare to
|
||||
* expected results.
|
||||
*/
|
||||
private void assertAddObjectPropStmt(String uriOfSub, String uriOfPred,
|
||||
String uriOfObj, Authorization expectedAuthorization) {
|
||||
AddObjectPropertyStatement whatToAuth = new AddObjectPropertyStatement(
|
||||
ontModel, uriOfSub, uriOfPred, uriOfObj);
|
||||
PolicyDecision dec = policy.isAuthorized(ids, whatToAuth);
|
||||
log.debug(dec);
|
||||
Assert.assertNotNull(dec);
|
||||
Assert.assertEquals(expectedAuthorization, dec.getAuthorized());
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an {@link EditObjectPropertyStatement}, test it, and compare to
|
||||
* expected results.
|
||||
*/
|
||||
private void assertEditObjPropStmt(String uriOfSub, String uriOfPred,
|
||||
String uriOfObj, Authorization expectedAuthorization) {
|
||||
EditObjectPropertyStatement whatToAuth = new EditObjectPropertyStatement(
|
||||
ontModel, uriOfSub, uriOfPred, uriOfObj);
|
||||
PolicyDecision dec = policy.isAuthorized(ids, whatToAuth);
|
||||
log.debug(dec);
|
||||
Assert.assertNotNull(dec);
|
||||
Assert.assertEquals(expectedAuthorization, dec.getAuthorized());
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an {@link EditDataPropertyStatement}, test it, and compare to
|
||||
* expected results.
|
||||
*/
|
||||
private void assertEditDataPropStmt(String individualURI,
|
||||
String datapropURI, String data, Authorization expectedAuthorization) {
|
||||
EditDataPropertyStatement whatToAuth = new EditDataPropertyStatement(
|
||||
ontModel, individualURI, datapropURI);
|
||||
PolicyDecision dec = policy.isAuthorized(ids, whatToAuth);
|
||||
log.debug(dec);
|
||||
Assert.assertNotNull(dec);
|
||||
Assert.assertEquals(expectedAuthorization, dec.getAuthorized());
|
||||
}
|
||||
}
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.auth.policy;
|
||||
|
||||
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;
|
||||
|
||||
import stubs.edu.cornell.mannlib.vitro.webapp.auth.policy.bean.PropertyRestrictionPolicyHelperStub;
|
||||
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;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.identifier.Identifier;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.identifier.common.HasProfile;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.policy.bean.PropertyRestrictionPolicyHelper;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.AddObjectPropertyStatement;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.EditDataPropertyStatement;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.EditObjectPropertyStatement;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.IndividualImpl;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
|
||||
public class SelfEditingPolicy_2_Test extends AbstractTestClass {
|
||||
private static final Log log = LogFactory
|
||||
.getLog(SelfEditingPolicy_2_Test.class);
|
||||
|
||||
/** We may edit objects in this arbitrary namespace. */
|
||||
private static final String SAFE_NS = "http://test.mannlib.cornell.edu/ns/01#";
|
||||
|
||||
/** We are not allowed to edit objects in the administrative namespace. */
|
||||
private static final String ADMIN_NS = VitroVocabulary.vitroURI;
|
||||
|
||||
/** The URI of a SelfEditor. */
|
||||
private static final String SELFEDITOR_URI = SAFE_NS + "individual000";
|
||||
|
||||
/** Some things that are safe to edit. */
|
||||
private static final String SAFE_RESOURCE = SAFE_NS + "individual123";
|
||||
private static final String SAFE_PREDICATE = SAFE_NS + "hasHairStyle";
|
||||
|
||||
/** Some things that are not safe to edit. */
|
||||
private static final String ADMIN_RESOURCE = ADMIN_NS + "individual666";
|
||||
private static final String ADMIN_PREDICATE_1 = ADMIN_NS + "hasSuperPowers";
|
||||
private static final String ADMIN_PREDICATE_2 = ADMIN_NS + "mayPrintMoney";
|
||||
private static final String ADMIN_PREDICATE_3 = ADMIN_NS
|
||||
+ "getsOutOfJailFree";
|
||||
private static final String ADMIN_PREDICATE_4 = ADMIN_NS + "canDeleteModel";
|
||||
|
||||
/** The policy we are testing. */
|
||||
SelfEditingPolicy policy;
|
||||
|
||||
/** A SelfEditing individual identifier. */
|
||||
Individual seIndividual;
|
||||
|
||||
/** A bundle that contains a SelfEditing individual. */
|
||||
IdentifierBundle ids;
|
||||
|
||||
/**
|
||||
* An empty model that acts as a placeholder in the requested actions. The
|
||||
* SelfEditingPolicy does not base its decisions on the contents of the
|
||||
* model.
|
||||
*/
|
||||
private OntModel ontModel;
|
||||
|
||||
|
||||
@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
|
||||
.getInstance(new String[] { ADMIN_NS }));
|
||||
|
||||
policy = new SelfEditingPolicy(ctx);
|
||||
Assert.assertNotNull(policy);
|
||||
|
||||
seIndividual = new IndividualImpl();
|
||||
seIndividual.setURI(SELFEDITOR_URI);
|
||||
|
||||
ids = new ArrayIdentifierBundle(new HasProfile(SELFEDITOR_URI));
|
||||
|
||||
ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
|
||||
|
||||
// setLoggerLevel(SelfEditingPolicySetupTest.class, Level.DEBUG);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// General tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void nullRequestedAction() {
|
||||
PolicyDecision dec = policy.isAuthorized(ids, null);
|
||||
Assert.assertNotNull(dec);
|
||||
Assert.assertEquals(Authorization.INCONCLUSIVE, dec.getAuthorized());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nullIdentifierBundle() {
|
||||
AddObjectPropertyStatement whatToAuth = new AddObjectPropertyStatement(
|
||||
ontModel, SELFEDITOR_URI, SAFE_PREDICATE, SAFE_RESOURCE);
|
||||
PolicyDecision dec = policy.isAuthorized(null, whatToAuth);
|
||||
Assert.assertNotNull(dec);
|
||||
Assert.assertEquals(Authorization.INCONCLUSIVE, dec.getAuthorized());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noSelfEditorIdentifier() {
|
||||
ids.clear();
|
||||
ids.add(new Identifier() { /* empty identifier */
|
||||
});
|
||||
assertAddObjectPropStmt(SELFEDITOR_URI, SAFE_PREDICATE, SAFE_RESOURCE,
|
||||
Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Tests against AddObjectPropStmt
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void addObjectPropStmtSuccess1() {
|
||||
assertAddObjectPropStmt(SELFEDITOR_URI, SAFE_PREDICATE, SAFE_RESOURCE,
|
||||
Authorization.AUTHORIZED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addObjectPropStmtSuccess2() {
|
||||
assertAddObjectPropStmt(SAFE_RESOURCE, SAFE_PREDICATE, SELFEDITOR_URI,
|
||||
Authorization.AUTHORIZED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addObjectPropStmtUnsafePredicate1() {
|
||||
assertAddObjectPropStmt(SELFEDITOR_URI, ADMIN_PREDICATE_1,
|
||||
SAFE_RESOURCE, Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addObjectPropStmtUnsafePredicate2() {
|
||||
assertAddObjectPropStmt(SAFE_RESOURCE, ADMIN_PREDICATE_1,
|
||||
SELFEDITOR_URI, Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addObjectPropStmtUnsafePredicate3() {
|
||||
assertAddObjectPropStmt(SELFEDITOR_URI, ADMIN_PREDICATE_2,
|
||||
SAFE_RESOURCE, Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addObjectPropStmtUnsafePredicate4() {
|
||||
assertAddObjectPropStmt(SELFEDITOR_URI, ADMIN_PREDICATE_3,
|
||||
SAFE_RESOURCE, Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addObjectPropStmtUnsafePredicate5() {
|
||||
assertAddObjectPropStmt(SELFEDITOR_URI, ADMIN_PREDICATE_4,
|
||||
SAFE_RESOURCE, Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Tests against EditObjPropStmt
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void editObjectPropStmtSuccess1() {
|
||||
assertEditObjPropStmt(SELFEDITOR_URI, SAFE_PREDICATE, SAFE_RESOURCE,
|
||||
Authorization.AUTHORIZED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void editObjectPropStmtSuccess2() {
|
||||
assertEditObjPropStmt(SAFE_RESOURCE, SAFE_PREDICATE, SELFEDITOR_URI,
|
||||
Authorization.AUTHORIZED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void editObjectPropStmtEditorNotInvolved() {
|
||||
// this is the case where the editor is not part of the stmt
|
||||
assertEditObjPropStmt(SAFE_RESOURCE, SAFE_PREDICATE, SAFE_RESOURCE,
|
||||
Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void editObjectPropStmtUnsafeResource() {
|
||||
assertEditObjPropStmt(SELFEDITOR_URI, SAFE_PREDICATE, ADMIN_RESOURCE,
|
||||
Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void editObjectPropStmtUnsafePredicate1() {
|
||||
assertEditObjPropStmt(SELFEDITOR_URI, ADMIN_PREDICATE_4, SAFE_RESOURCE,
|
||||
Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void editObjectPropStmtUnsafePredicate2() {
|
||||
assertEditObjPropStmt(SAFE_RESOURCE, ADMIN_PREDICATE_4, SELFEDITOR_URI,
|
||||
Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void editObjectPropStmtUnsafeBoth() {
|
||||
assertEditObjPropStmt(SELFEDITOR_URI, ADMIN_PREDICATE_4,
|
||||
ADMIN_RESOURCE, Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Tests against EditDataPropStmt
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void editDataPropSuccess() {
|
||||
assertEditDataPropStmt(SELFEDITOR_URI, SAFE_PREDICATE, "junk",
|
||||
Authorization.AUTHORIZED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void editDataPropUnsafePredicate() {
|
||||
assertEditDataPropStmt(SELFEDITOR_URI, ADMIN_PREDICATE_1, "junk",
|
||||
Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void editDataPropUnsafeResource() {
|
||||
assertEditDataPropStmt(ADMIN_RESOURCE, SAFE_PREDICATE, null,
|
||||
Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void editDataPropNoCloseRelation() {
|
||||
assertEditDataPropStmt(SAFE_RESOURCE, SAFE_PREDICATE, null,
|
||||
Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void editDataPropModelProhibited() {
|
||||
// model prohibited
|
||||
assertEditDataPropStmt(SAFE_RESOURCE, ADMIN_PREDICATE_1, null,
|
||||
Authorization.INCONCLUSIVE);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// Support methods
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Create an {@link AddObjectPropertyStatement}, test it, and compare to
|
||||
* expected results.
|
||||
*/
|
||||
private void assertAddObjectPropStmt(String uriOfSub, String uriOfPred,
|
||||
String uriOfObj, Authorization expectedAuthorization) {
|
||||
AddObjectPropertyStatement whatToAuth = new AddObjectPropertyStatement(
|
||||
ontModel, uriOfSub, uriOfPred, uriOfObj);
|
||||
PolicyDecision dec = policy.isAuthorized(ids, whatToAuth);
|
||||
log.debug(dec);
|
||||
Assert.assertNotNull(dec);
|
||||
Assert.assertEquals(expectedAuthorization, dec.getAuthorized());
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an {@link EditObjectPropertyStatement}, test it, and compare to
|
||||
* expected results.
|
||||
*/
|
||||
private void assertEditObjPropStmt(String uriOfSub, String uriOfPred,
|
||||
String uriOfObj, Authorization expectedAuthorization) {
|
||||
EditObjectPropertyStatement whatToAuth = new EditObjectPropertyStatement(
|
||||
ontModel, uriOfSub, uriOfPred, uriOfObj);
|
||||
PolicyDecision dec = policy.isAuthorized(ids, whatToAuth);
|
||||
log.debug(dec);
|
||||
Assert.assertNotNull(dec);
|
||||
Assert.assertEquals(expectedAuthorization, dec.getAuthorized());
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an {@link EditDataPropertyStatement}, test it, and compare to
|
||||
* expected results.
|
||||
*/
|
||||
private void assertEditDataPropStmt(String individualURI,
|
||||
String datapropURI, String data, Authorization expectedAuthorization) {
|
||||
EditDataPropertyStatement whatToAuth = new EditDataPropertyStatement(
|
||||
ontModel, individualURI, datapropURI);
|
||||
PolicyDecision dec = policy.isAuthorized(ids, whatToAuth);
|
||||
log.debug(dec);
|
||||
Assert.assertNotNull(dec);
|
||||
Assert.assertEquals(expectedAuthorization, dec.getAuthorized());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,45 +1,45 @@
|
|||
<?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>
|
||||
|
||||
<?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>
|
||||
|
||||
|
|
|
@ -1,247 +1,247 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.auth.policy.bean;
|
||||
|
||||
import static edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel.CURATOR;
|
||||
import static edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel.DB_ADMIN;
|
||||
import static edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel.EDITOR;
|
||||
import static edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel.NOBODY;
|
||||
import static edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel.PUBLIC;
|
||||
import static edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel.SELF;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.log4j.Level;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
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.Property;
|
||||
import com.hp.hpl.jena.rdf.model.Resource;
|
||||
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
|
||||
/**
|
||||
* Check that the bean gets built properly, and check that the bean works properly.
|
||||
*/
|
||||
public class PropertyRestrictionPolicyHelperTest extends AbstractTestClass {
|
||||
private static final Log log = LogFactory
|
||||
.getLog(PropertyRestrictionPolicyHelperTest.class);
|
||||
|
||||
private static final String PROPERTY_DISPLAY_THRESHOLD = VitroVocabulary.HIDDEN_FROM_DISPLAY_BELOW_ROLE_LEVEL_ANNOT;
|
||||
private static final String PROPERTY_MODIFY_THRESHOLD = VitroVocabulary.PROHIBITED_FROM_UPDATE_BELOW_ROLE_LEVEL_ANNOT;
|
||||
|
||||
private static final String[] PROHIBITED_NAMESPACES = new String[] {
|
||||
VitroVocabulary.vitroURI, "" };
|
||||
|
||||
private static final String[] PERMITTED_EXCEPTIONS = new String[] {
|
||||
VitroVocabulary.MONIKER };
|
||||
|
||||
private OntModel ontModel;
|
||||
private ModelWrapper wrapper;
|
||||
private PropertyRestrictionPolicyHelper bean;
|
||||
|
||||
@Before
|
||||
public void setLoggingLevel() {
|
||||
// setLoggerLevel(PropertyRestrictionPolicyHelper.class, Level.DEBUG);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void createTheBean() {
|
||||
Map<String, RoleLevel> displayLevels = new HashMap<String, BaseResourceBean.RoleLevel>();
|
||||
displayLevels.put("http://predicates#display_self", SELF);
|
||||
displayLevels.put("http://predicates#display_curator", CURATOR);
|
||||
displayLevels.put("http://predicates#display_hidden", NOBODY);
|
||||
|
||||
Map<String, RoleLevel> modifyLevels = new HashMap<String, BaseResourceBean.RoleLevel>();
|
||||
modifyLevels.put("http://predicates#modify_self", SELF);
|
||||
modifyLevels.put("http://predicates#modify_curator", CURATOR);
|
||||
modifyLevels.put("http://predicates#modify_hidden", NOBODY);
|
||||
|
||||
bean = new PropertyRestrictionPolicyHelper(
|
||||
Arrays.asList(PROHIBITED_NAMESPACES),
|
||||
Arrays.asList(PERMITTED_EXCEPTIONS), displayLevels,
|
||||
modifyLevels, ModelFactory.createDefaultModel());
|
||||
}
|
||||
|
||||
@Before
|
||||
public void createTheModel() {
|
||||
ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);
|
||||
|
||||
wrapper = new ModelWrapper(ontModel);
|
||||
|
||||
wrapper.add("http://thresholds#display_public",
|
||||
PROPERTY_DISPLAY_THRESHOLD, PUBLIC.getURI());
|
||||
wrapper.add("http://thresholds#display_hidden",
|
||||
PROPERTY_DISPLAY_THRESHOLD, NOBODY.getURI());
|
||||
|
||||
wrapper.add("http://thresholds#modify_editor",
|
||||
PROPERTY_MODIFY_THRESHOLD, EDITOR.getURI());
|
||||
wrapper.add("http://thresholds#modify_curator",
|
||||
PROPERTY_MODIFY_THRESHOLD, CURATOR.getURI());
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// test the bean
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void displayResource() {
|
||||
assertEquals("display a random resource", true,
|
||||
bean.canDisplayResource("http://someRandom#string", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modifyResourceNoRestriction() {
|
||||
assertEquals("modify a random resource", true,
|
||||
bean.canModifyResource("http://someRandom#string", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modifyResourceProhibitedNamespace() {
|
||||
assertEquals("modify a prohibited resource", false,
|
||||
bean.canModifyResource(PROHIBITED_NAMESPACES[0] + "random",
|
||||
null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modifyResourcePermittedException() {
|
||||
assertEquals("modify a exception resource", true,
|
||||
bean.canModifyResource(PERMITTED_EXCEPTIONS[0], null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void displayPredicateNoRestriction() {
|
||||
assertEquals("displayPredicate: open", true,
|
||||
bean.canDisplayPredicate("http://predicates#open", PUBLIC));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void displayPredicateRestrictionLower() {
|
||||
assertEquals("displayPredicate: lower restriction", true,
|
||||
bean.canDisplayPredicate("http://predicates#display_self",
|
||||
CURATOR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void displayPredicateRestrictionEqual() {
|
||||
assertEquals("displayPredicate: equal restriction", true,
|
||||
bean.canDisplayPredicate("http://predicates#display_curator",
|
||||
CURATOR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void displayPredicateRestrictionHigher() {
|
||||
assertEquals("displayPredicate: higher restriction", false,
|
||||
bean.canDisplayPredicate("http://predicates#display_hidden",
|
||||
CURATOR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modifyPredicateNoRestriction() {
|
||||
assertEquals("modifyPredicate: open", true,
|
||||
bean.canModifyPredicate("http://predicates#open", PUBLIC));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modifyPredicateRestrictionLower() {
|
||||
assertEquals("modifyPredicate: lower restriction", true,
|
||||
bean.canModifyPredicate("http://predicates#modify_self",
|
||||
CURATOR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modifyPredicateRestrictionEqual() {
|
||||
assertEquals("modifyPredicate: equal restriction", true,
|
||||
bean.canModifyPredicate("http://predicates#modify_curator",
|
||||
CURATOR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modifyPredicateRestrictionHigher() {
|
||||
assertEquals("modifyPredicate: higher restriction", false,
|
||||
bean.canModifyPredicate("http://predicates#modify_hidden",
|
||||
CURATOR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modifyPredicateProhibitedNamespace() {
|
||||
assertEquals("modifyPredicate: prohibited namespace", false,
|
||||
bean.canModifyPredicate(PROHIBITED_NAMESPACES[0] + "randoom",
|
||||
DB_ADMIN));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modifyPredicatePermittedException() {
|
||||
assertEquals("modifyPredicate: permitted exception", true,
|
||||
bean.canModifyPredicate(PERMITTED_EXCEPTIONS[0], DB_ADMIN));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// test the bean builder
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void buildDisplayThresholds() {
|
||||
Map<String, RoleLevel> expectedMap = new HashMap<String, BaseResourceBean.RoleLevel>();
|
||||
expectedMap.put("http://thresholds#display_public", PUBLIC);
|
||||
expectedMap.put("http://thresholds#display_hidden", NOBODY);
|
||||
|
||||
Map<String, RoleLevel> actualMap = populateThresholdMap(PROPERTY_DISPLAY_THRESHOLD);
|
||||
assertEquals("display thresholds", expectedMap, actualMap);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void buildModifyThresholds() {
|
||||
Map<String, RoleLevel> expectedMap = new HashMap<String, BaseResourceBean.RoleLevel>();
|
||||
expectedMap.put("http://thresholds#modify_editor", EDITOR);
|
||||
expectedMap.put("http://thresholds#modify_curator", CURATOR);
|
||||
|
||||
Map<String, RoleLevel> actualMap = populateThresholdMap(PROPERTY_MODIFY_THRESHOLD);
|
||||
assertEquals("modify thresholds", expectedMap, actualMap);
|
||||
}
|
||||
|
||||
/** Invoke the private static method "populateThresholdMap" */
|
||||
private Map<String, RoleLevel> populateThresholdMap(String propertyUri) {
|
||||
Map<String, RoleLevel> map = new HashMap<String, BaseResourceBean.RoleLevel>();
|
||||
try {
|
||||
Class<?> clazz = PropertyRestrictionPolicyHelper.class;
|
||||
Method method = clazz.getDeclaredMethod("populateThresholdMap",
|
||||
OntModel.class, Map.class, String.class);
|
||||
method.setAccessible(true);
|
||||
method.invoke(null, ontModel, map, propertyUri);
|
||||
return map;
|
||||
} catch (Exception e) {
|
||||
fail("failed to populate the map: propertyUri='" + propertyUri
|
||||
+ "', " + e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static class ModelWrapper {
|
||||
private final OntModel model;
|
||||
|
||||
public ModelWrapper(OntModel model) {
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
public void add(String subjectUri, String propertyUri, String objectUri) {
|
||||
Resource subject = model.getResource(subjectUri);
|
||||
Property property = model.getProperty(propertyUri);
|
||||
Resource object = model.getResource(objectUri);
|
||||
model.add(subject, property, object);
|
||||
}
|
||||
}
|
||||
}
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.auth.policy.bean;
|
||||
|
||||
import static edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel.CURATOR;
|
||||
import static edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel.DB_ADMIN;
|
||||
import static edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel.EDITOR;
|
||||
import static edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel.NOBODY;
|
||||
import static edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel.PUBLIC;
|
||||
import static edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel.SELF;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.log4j.Level;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
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.Property;
|
||||
import com.hp.hpl.jena.rdf.model.Resource;
|
||||
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
|
||||
|
||||
/**
|
||||
* Check that the bean gets built properly, and check that the bean works properly.
|
||||
*/
|
||||
public class PropertyRestrictionPolicyHelperTest extends AbstractTestClass {
|
||||
private static final Log log = LogFactory
|
||||
.getLog(PropertyRestrictionPolicyHelperTest.class);
|
||||
|
||||
private static final String PROPERTY_DISPLAY_THRESHOLD = VitroVocabulary.HIDDEN_FROM_DISPLAY_BELOW_ROLE_LEVEL_ANNOT;
|
||||
private static final String PROPERTY_MODIFY_THRESHOLD = VitroVocabulary.PROHIBITED_FROM_UPDATE_BELOW_ROLE_LEVEL_ANNOT;
|
||||
|
||||
private static final String[] PROHIBITED_NAMESPACES = new String[] {
|
||||
VitroVocabulary.vitroURI, "" };
|
||||
|
||||
private static final String[] PERMITTED_EXCEPTIONS = new String[] {
|
||||
VitroVocabulary.MONIKER };
|
||||
|
||||
private OntModel ontModel;
|
||||
private ModelWrapper wrapper;
|
||||
private PropertyRestrictionPolicyHelper bean;
|
||||
|
||||
@Before
|
||||
public void setLoggingLevel() {
|
||||
// setLoggerLevel(PropertyRestrictionPolicyHelper.class, Level.DEBUG);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void createTheBean() {
|
||||
Map<String, RoleLevel> displayLevels = new HashMap<String, BaseResourceBean.RoleLevel>();
|
||||
displayLevels.put("http://predicates#display_self", SELF);
|
||||
displayLevels.put("http://predicates#display_curator", CURATOR);
|
||||
displayLevels.put("http://predicates#display_hidden", NOBODY);
|
||||
|
||||
Map<String, RoleLevel> modifyLevels = new HashMap<String, BaseResourceBean.RoleLevel>();
|
||||
modifyLevels.put("http://predicates#modify_self", SELF);
|
||||
modifyLevels.put("http://predicates#modify_curator", CURATOR);
|
||||
modifyLevels.put("http://predicates#modify_hidden", NOBODY);
|
||||
|
||||
bean = new PropertyRestrictionPolicyHelper(
|
||||
Arrays.asList(PROHIBITED_NAMESPACES),
|
||||
Arrays.asList(PERMITTED_EXCEPTIONS), displayLevels,
|
||||
modifyLevels, ModelFactory.createDefaultModel());
|
||||
}
|
||||
|
||||
@Before
|
||||
public void createTheModel() {
|
||||
ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);
|
||||
|
||||
wrapper = new ModelWrapper(ontModel);
|
||||
|
||||
wrapper.add("http://thresholds#display_public",
|
||||
PROPERTY_DISPLAY_THRESHOLD, PUBLIC.getURI());
|
||||
wrapper.add("http://thresholds#display_hidden",
|
||||
PROPERTY_DISPLAY_THRESHOLD, NOBODY.getURI());
|
||||
|
||||
wrapper.add("http://thresholds#modify_editor",
|
||||
PROPERTY_MODIFY_THRESHOLD, EDITOR.getURI());
|
||||
wrapper.add("http://thresholds#modify_curator",
|
||||
PROPERTY_MODIFY_THRESHOLD, CURATOR.getURI());
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// test the bean
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void displayResource() {
|
||||
assertEquals("display a random resource", true,
|
||||
bean.canDisplayResource("http://someRandom#string", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modifyResourceNoRestriction() {
|
||||
assertEquals("modify a random resource", true,
|
||||
bean.canModifyResource("http://someRandom#string", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modifyResourceProhibitedNamespace() {
|
||||
assertEquals("modify a prohibited resource", false,
|
||||
bean.canModifyResource(PROHIBITED_NAMESPACES[0] + "random",
|
||||
null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modifyResourcePermittedException() {
|
||||
assertEquals("modify a exception resource", true,
|
||||
bean.canModifyResource(PERMITTED_EXCEPTIONS[0], null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void displayPredicateNoRestriction() {
|
||||
assertEquals("displayPredicate: open", true,
|
||||
bean.canDisplayPredicate("http://predicates#open", PUBLIC));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void displayPredicateRestrictionLower() {
|
||||
assertEquals("displayPredicate: lower restriction", true,
|
||||
bean.canDisplayPredicate("http://predicates#display_self",
|
||||
CURATOR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void displayPredicateRestrictionEqual() {
|
||||
assertEquals("displayPredicate: equal restriction", true,
|
||||
bean.canDisplayPredicate("http://predicates#display_curator",
|
||||
CURATOR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void displayPredicateRestrictionHigher() {
|
||||
assertEquals("displayPredicate: higher restriction", false,
|
||||
bean.canDisplayPredicate("http://predicates#display_hidden",
|
||||
CURATOR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modifyPredicateNoRestriction() {
|
||||
assertEquals("modifyPredicate: open", true,
|
||||
bean.canModifyPredicate("http://predicates#open", PUBLIC));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modifyPredicateRestrictionLower() {
|
||||
assertEquals("modifyPredicate: lower restriction", true,
|
||||
bean.canModifyPredicate("http://predicates#modify_self",
|
||||
CURATOR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modifyPredicateRestrictionEqual() {
|
||||
assertEquals("modifyPredicate: equal restriction", true,
|
||||
bean.canModifyPredicate("http://predicates#modify_curator",
|
||||
CURATOR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modifyPredicateRestrictionHigher() {
|
||||
assertEquals("modifyPredicate: higher restriction", false,
|
||||
bean.canModifyPredicate("http://predicates#modify_hidden",
|
||||
CURATOR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modifyPredicateProhibitedNamespace() {
|
||||
assertEquals("modifyPredicate: prohibited namespace", false,
|
||||
bean.canModifyPredicate(PROHIBITED_NAMESPACES[0] + "randoom",
|
||||
DB_ADMIN));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modifyPredicatePermittedException() {
|
||||
assertEquals("modifyPredicate: permitted exception", true,
|
||||
bean.canModifyPredicate(PERMITTED_EXCEPTIONS[0], DB_ADMIN));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// test the bean builder
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void buildDisplayThresholds() {
|
||||
Map<String, RoleLevel> expectedMap = new HashMap<String, BaseResourceBean.RoleLevel>();
|
||||
expectedMap.put("http://thresholds#display_public", PUBLIC);
|
||||
expectedMap.put("http://thresholds#display_hidden", NOBODY);
|
||||
|
||||
Map<String, RoleLevel> actualMap = populateThresholdMap(PROPERTY_DISPLAY_THRESHOLD);
|
||||
assertEquals("display thresholds", expectedMap, actualMap);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void buildModifyThresholds() {
|
||||
Map<String, RoleLevel> expectedMap = new HashMap<String, BaseResourceBean.RoleLevel>();
|
||||
expectedMap.put("http://thresholds#modify_editor", EDITOR);
|
||||
expectedMap.put("http://thresholds#modify_curator", CURATOR);
|
||||
|
||||
Map<String, RoleLevel> actualMap = populateThresholdMap(PROPERTY_MODIFY_THRESHOLD);
|
||||
assertEquals("modify thresholds", expectedMap, actualMap);
|
||||
}
|
||||
|
||||
/** Invoke the private static method "populateThresholdMap" */
|
||||
private Map<String, RoleLevel> populateThresholdMap(String propertyUri) {
|
||||
Map<String, RoleLevel> map = new HashMap<String, BaseResourceBean.RoleLevel>();
|
||||
try {
|
||||
Class<?> clazz = PropertyRestrictionPolicyHelper.class;
|
||||
Method method = clazz.getDeclaredMethod("populateThresholdMap",
|
||||
OntModel.class, Map.class, String.class);
|
||||
method.setAccessible(true);
|
||||
method.invoke(null, ontModel, map, propertyUri);
|
||||
return map;
|
||||
} catch (Exception e) {
|
||||
fail("failed to populate the map: propertyUri='" + propertyUri
|
||||
+ "', " + e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static class ModelWrapper {
|
||||
private final OntModel model;
|
||||
|
||||
public ModelWrapper(OntModel model) {
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
public void add(String subjectUri, String propertyUri, String objectUri) {
|
||||
Resource subject = model.getResource(subjectUri);
|
||||
Property property = model.getProperty(propertyUri);
|
||||
Resource object = model.getResource(objectUri);
|
||||
model.add(subject, property, object);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,143 +1,143 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.config;
|
||||
|
||||
import static edu.cornell.mannlib.vitro.webapp.config.RevisionInfoBean.DUMMY_BEAN;
|
||||
import static edu.cornell.mannlib.vitro.webapp.config.RevisionInfoBean.LevelRevisionInfo.DUMMY_LEVEL;
|
||||
import static junit.framework.Assert.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.apache.log4j.Level;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import stubs.javax.servlet.ServletContextStub;
|
||||
import stubs.javax.servlet.http.HttpSessionStub;
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.config.RevisionInfoBean.LevelRevisionInfo;
|
||||
|
||||
/**
|
||||
* Tests for RevisionInfoBean
|
||||
*/
|
||||
public class RevisionInfoBeanTest extends AbstractTestClass {
|
||||
private static final Date SAMPLE_DATE = new Date();
|
||||
|
||||
private static final LevelRevisionInfo LEVEL_1_INFO = new LevelRevisionInfo(
|
||||
"level1name", "level1release", "level1revision");
|
||||
private static final LevelRevisionInfo LEVEL_2_INFO = new LevelRevisionInfo(
|
||||
"level2name", "level2release", "level2revision");
|
||||
private static final LevelRevisionInfo LEVEL_3_INFO = new LevelRevisionInfo(
|
||||
"level3name", "level3release", "level3revision");
|
||||
|
||||
private static final RevisionInfoBean BEAN_NO_LEVEL = buildBean(SAMPLE_DATE);
|
||||
private static final RevisionInfoBean BEAN_1_LEVEL = buildBean(SAMPLE_DATE,
|
||||
LEVEL_1_INFO);
|
||||
private static final RevisionInfoBean BEAN_MULTI_LEVEL = buildBean(
|
||||
SAMPLE_DATE, LEVEL_1_INFO, LEVEL_2_INFO, LEVEL_3_INFO);
|
||||
|
||||
private static RevisionInfoBean buildBean(Date date,
|
||||
LevelRevisionInfo... levels) {
|
||||
return new RevisionInfoBean(date, Arrays.asList(levels));
|
||||
}
|
||||
|
||||
private ServletContextStub context;
|
||||
private HttpSessionStub session;
|
||||
|
||||
@Before
|
||||
public void setupContext() {
|
||||
context = new ServletContextStub();
|
||||
session = new HttpSessionStub();
|
||||
session.setServletContext(context);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void suppressInfoMessages() {
|
||||
setLoggerLevel(RevisionInfoBean.class, Level.WARN);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setBeanNormal() {
|
||||
RevisionInfoBean.setBean(context, BEAN_1_LEVEL);
|
||||
assertEquals("stored bean", BEAN_1_LEVEL,
|
||||
RevisionInfoBean.getBean(session));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setBeanNull() {
|
||||
RevisionInfoBean.setBean(context, null);
|
||||
assertEquals("dummy bean", DUMMY_BEAN,
|
||||
RevisionInfoBean.getBean(session));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getBeanNoSession() {
|
||||
setLoggerLevel(RevisionInfoBean.class, Level.ERROR);
|
||||
|
||||
assertEquals("noBean", DUMMY_BEAN,
|
||||
RevisionInfoBean.getBean((HttpSession) null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getBeanNoAttribute() {
|
||||
setLoggerLevel(RevisionInfoBean.class, Level.ERROR);
|
||||
|
||||
assertEquals("noAttribute", DUMMY_BEAN,
|
||||
RevisionInfoBean.getBean(session));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getBeanAttributeIsWrongClass() {
|
||||
setLoggerLevel(RevisionInfoBean.class, Level.OFF);
|
||||
|
||||
context.setAttribute(RevisionInfoBean.ATTRIBUTE_NAME, "A string!");
|
||||
assertEquals("noAttribute", DUMMY_BEAN,
|
||||
RevisionInfoBean.getBean(session));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void removeBean() {
|
||||
RevisionInfoBean.setBean(context, BEAN_1_LEVEL);
|
||||
assertEquals("stored bean", BEAN_1_LEVEL,
|
||||
RevisionInfoBean.getBean(session));
|
||||
|
||||
setLoggerLevel(RevisionInfoBean.class, Level.ERROR);
|
||||
|
||||
RevisionInfoBean.removeBean(context);
|
||||
assertEquals("dummy bean", DUMMY_BEAN,
|
||||
RevisionInfoBean.getBean(session));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getReleaseLabelOneLevel() {
|
||||
RevisionInfoBean.setBean(context, BEAN_1_LEVEL);
|
||||
assertEquals("1 level release", LEVEL_1_INFO.getRelease(),
|
||||
RevisionInfoBean.getBean(session).getReleaseLabel());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getReleaseLabelManyLevels() {
|
||||
RevisionInfoBean.setBean(context, BEAN_MULTI_LEVEL);
|
||||
assertEquals("many level release", LEVEL_3_INFO.getRelease(),
|
||||
RevisionInfoBean.getBean(session).getReleaseLabel());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getReleaseLabelNoLevels() {
|
||||
RevisionInfoBean.setBean(context, BEAN_NO_LEVEL);
|
||||
assertEquals("0 level release", DUMMY_LEVEL.getRelease(),
|
||||
RevisionInfoBean.getBean(session).getReleaseLabel());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getReleaseLabelNoBean() {
|
||||
setLoggerLevel(RevisionInfoBean.class, Level.ERROR);
|
||||
|
||||
assertEquals("no bean release", DUMMY_LEVEL.getRelease(),
|
||||
RevisionInfoBean.getBean(session).getReleaseLabel());
|
||||
}
|
||||
|
||||
}
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.config;
|
||||
|
||||
import static edu.cornell.mannlib.vitro.webapp.config.RevisionInfoBean.DUMMY_BEAN;
|
||||
import static edu.cornell.mannlib.vitro.webapp.config.RevisionInfoBean.LevelRevisionInfo.DUMMY_LEVEL;
|
||||
import static junit.framework.Assert.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.apache.log4j.Level;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import stubs.javax.servlet.ServletContextStub;
|
||||
import stubs.javax.servlet.http.HttpSessionStub;
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.config.RevisionInfoBean.LevelRevisionInfo;
|
||||
|
||||
/**
|
||||
* Tests for RevisionInfoBean
|
||||
*/
|
||||
public class RevisionInfoBeanTest extends AbstractTestClass {
|
||||
private static final Date SAMPLE_DATE = new Date();
|
||||
|
||||
private static final LevelRevisionInfo LEVEL_1_INFO = new LevelRevisionInfo(
|
||||
"level1name", "level1release", "level1revision");
|
||||
private static final LevelRevisionInfo LEVEL_2_INFO = new LevelRevisionInfo(
|
||||
"level2name", "level2release", "level2revision");
|
||||
private static final LevelRevisionInfo LEVEL_3_INFO = new LevelRevisionInfo(
|
||||
"level3name", "level3release", "level3revision");
|
||||
|
||||
private static final RevisionInfoBean BEAN_NO_LEVEL = buildBean(SAMPLE_DATE);
|
||||
private static final RevisionInfoBean BEAN_1_LEVEL = buildBean(SAMPLE_DATE,
|
||||
LEVEL_1_INFO);
|
||||
private static final RevisionInfoBean BEAN_MULTI_LEVEL = buildBean(
|
||||
SAMPLE_DATE, LEVEL_1_INFO, LEVEL_2_INFO, LEVEL_3_INFO);
|
||||
|
||||
private static RevisionInfoBean buildBean(Date date,
|
||||
LevelRevisionInfo... levels) {
|
||||
return new RevisionInfoBean(date, Arrays.asList(levels));
|
||||
}
|
||||
|
||||
private ServletContextStub context;
|
||||
private HttpSessionStub session;
|
||||
|
||||
@Before
|
||||
public void setupContext() {
|
||||
context = new ServletContextStub();
|
||||
session = new HttpSessionStub();
|
||||
session.setServletContext(context);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void suppressInfoMessages() {
|
||||
setLoggerLevel(RevisionInfoBean.class, Level.WARN);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setBeanNormal() {
|
||||
RevisionInfoBean.setBean(context, BEAN_1_LEVEL);
|
||||
assertEquals("stored bean", BEAN_1_LEVEL,
|
||||
RevisionInfoBean.getBean(session));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setBeanNull() {
|
||||
RevisionInfoBean.setBean(context, null);
|
||||
assertEquals("dummy bean", DUMMY_BEAN,
|
||||
RevisionInfoBean.getBean(session));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getBeanNoSession() {
|
||||
setLoggerLevel(RevisionInfoBean.class, Level.ERROR);
|
||||
|
||||
assertEquals("noBean", DUMMY_BEAN,
|
||||
RevisionInfoBean.getBean((HttpSession) null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getBeanNoAttribute() {
|
||||
setLoggerLevel(RevisionInfoBean.class, Level.ERROR);
|
||||
|
||||
assertEquals("noAttribute", DUMMY_BEAN,
|
||||
RevisionInfoBean.getBean(session));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getBeanAttributeIsWrongClass() {
|
||||
setLoggerLevel(RevisionInfoBean.class, Level.OFF);
|
||||
|
||||
context.setAttribute(RevisionInfoBean.ATTRIBUTE_NAME, "A string!");
|
||||
assertEquals("noAttribute", DUMMY_BEAN,
|
||||
RevisionInfoBean.getBean(session));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void removeBean() {
|
||||
RevisionInfoBean.setBean(context, BEAN_1_LEVEL);
|
||||
assertEquals("stored bean", BEAN_1_LEVEL,
|
||||
RevisionInfoBean.getBean(session));
|
||||
|
||||
setLoggerLevel(RevisionInfoBean.class, Level.ERROR);
|
||||
|
||||
RevisionInfoBean.removeBean(context);
|
||||
assertEquals("dummy bean", DUMMY_BEAN,
|
||||
RevisionInfoBean.getBean(session));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getReleaseLabelOneLevel() {
|
||||
RevisionInfoBean.setBean(context, BEAN_1_LEVEL);
|
||||
assertEquals("1 level release", LEVEL_1_INFO.getRelease(),
|
||||
RevisionInfoBean.getBean(session).getReleaseLabel());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getReleaseLabelManyLevels() {
|
||||
RevisionInfoBean.setBean(context, BEAN_MULTI_LEVEL);
|
||||
assertEquals("many level release", LEVEL_3_INFO.getRelease(),
|
||||
RevisionInfoBean.getBean(session).getReleaseLabel());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getReleaseLabelNoLevels() {
|
||||
RevisionInfoBean.setBean(context, BEAN_NO_LEVEL);
|
||||
assertEquals("0 level release", DUMMY_LEVEL.getRelease(),
|
||||
RevisionInfoBean.getBean(session).getReleaseLabel());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getReleaseLabelNoBean() {
|
||||
setLoggerLevel(RevisionInfoBean.class, Level.ERROR);
|
||||
|
||||
assertEquals("no bean release", DUMMY_LEVEL.getRelease(),
|
||||
RevisionInfoBean.getBean(session).getReleaseLabel());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,189 +1,189 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.config;
|
||||
|
||||
import static edu.cornell.mannlib.vitro.webapp.config.RevisionInfoBean.DUMMY_BEAN;
|
||||
import static edu.cornell.mannlib.vitro.webapp.config.RevisionInfoSetup.DATE_FORMAT;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
|
||||
import javax.servlet.ServletContextEvent;
|
||||
import javax.servlet.ServletContextListener;
|
||||
|
||||
import org.apache.log4j.Level;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import stubs.javax.servlet.ServletContextStub;
|
||||
import stubs.javax.servlet.http.HttpSessionStub;
|
||||
|
||||
import com.ibm.icu.text.SimpleDateFormat;
|
||||
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.config.RevisionInfoBean.LevelRevisionInfo;
|
||||
import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus;
|
||||
|
||||
/**
|
||||
* Test for RevisionInfoSetup
|
||||
*/
|
||||
public class RevisionInfoSetupTest extends AbstractTestClass {
|
||||
private ServletContextStub context;
|
||||
private HttpSessionStub session;
|
||||
private ServletContextListener listener;
|
||||
private ServletContextEvent event;
|
||||
|
||||
@Before
|
||||
public void setupContext() {
|
||||
context = new ServletContextStub();
|
||||
|
||||
session = new HttpSessionStub();
|
||||
session.setServletContext(context);
|
||||
|
||||
event = new ServletContextEvent(context);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void createContextListener() {
|
||||
listener = new RevisionInfoSetup();
|
||||
}
|
||||
|
||||
@Before
|
||||
public void suppressInfoMessages() {
|
||||
setLoggerLevel(RevisionInfoBean.class, Level.WARN);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void suppressMessagesFromStartupStatus() {
|
||||
setLoggerLevel(StartupStatus.class, Level.OFF);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noResourceFile() {
|
||||
setLoggerLevel(RevisionInfoSetup.class, Level.OFF);
|
||||
testThisExpectedFailure("no resource", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resourceFileIsEmpty() {
|
||||
setLoggerLevel(RevisionInfoSetup.class, Level.OFF);
|
||||
testThisExpectedFailure("empty resource", "");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resourceFileHasNoSignificantLines() {
|
||||
setLoggerLevel(RevisionInfoSetup.class, Level.OFF);
|
||||
testThisExpectedFailure("no siginificant lines", " \n # \n\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resourceFileHasInvalidDateLine() {
|
||||
setLoggerLevel(RevisionInfoSetup.class, Level.OFF);
|
||||
testThisExpectedFailure("invalid date line", "BOGUS DATE LINE\n"
|
||||
+ "name ~ release ~ revision");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resourceFileHasInvalidLevelLine() {
|
||||
setLoggerLevel(RevisionInfoSetup.class, Level.OFF);
|
||||
testThisExpectedFailure("invalid level line", "2010-02-13 23:55:00\n"
|
||||
+ "name ~ release ~revision");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void simpleSingleLevel() {
|
||||
testThisResourceFile(
|
||||
"simple single level",
|
||||
"2010-02-13 23:55:00\n" + "name ~ release ~ revision",
|
||||
bean(date("2010-02-13 23:55:00"),
|
||||
level("name", "release", "revision")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ignoreWhiteSpaceAroundDate() {
|
||||
testThisResourceFile(
|
||||
"white space around date",
|
||||
" 1999-01-01 00:00:00 \n" + "name ~ release ~ revision",
|
||||
bean(date("1999-01-01 00:00:00"),
|
||||
level("name", "release", "revision")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ignoreWhiteSpaceInLevelInfo() {
|
||||
testThisResourceFile(
|
||||
"white space in level info",
|
||||
"2010-02-13 23:55:00\n"
|
||||
+ " name ~ release ~ revision ",
|
||||
bean(date("2010-02-13 23:55:00"),
|
||||
level("name", "release", "revision")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ignoreBlankLinesAndComments() {
|
||||
testThisResourceFile(
|
||||
"ignore empty lines",
|
||||
"2010-02-13 23:55:00\n" + "\n" + " \n" + " # \n"
|
||||
+ "name ~ release ~ revision",
|
||||
bean(date("2010-02-13 23:55:00"),
|
||||
level("name", "release", "revision")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseMultipleLevels() {
|
||||
testThisResourceFile(
|
||||
"multiple levels",
|
||||
"2010-02-13 23:55:00\n" + "name ~ release ~ revision\n"
|
||||
+ "name2 ~ release2 ~ revision2\n",
|
||||
bean(date("2010-02-13 23:55:00"),
|
||||
level("name", "release", "revision"),
|
||||
level("name2", "release2", "revision2")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseNoLevels() {
|
||||
testThisResourceFile("no levels", "2010-02-13 23:55:00\n",
|
||||
bean(date("2010-02-13 23:55:00")));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private RevisionInfoBean bean(Date date, LevelRevisionInfo... levels) {
|
||||
return new RevisionInfoBean(date, Arrays.asList(levels));
|
||||
}
|
||||
|
||||
private LevelRevisionInfo level(String name, String release, String revision) {
|
||||
return new LevelRevisionInfo(name, release, revision);
|
||||
}
|
||||
|
||||
private Date date(String string) {
|
||||
try {
|
||||
return new SimpleDateFormat(DATE_FORMAT).parse(string);
|
||||
} catch (ParseException e) {
|
||||
throw new IllegalArgumentException(
|
||||
"Can't parse this date string: '" + string + "'");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test these file contents, compare to this expected bean.
|
||||
*/
|
||||
private void testThisResourceFile(String message, String fileContents,
|
||||
RevisionInfoBean expected) {
|
||||
context.setMockResource(RevisionInfoSetup.RESOURCE_PATH, fileContents);
|
||||
|
||||
listener.contextInitialized(event);
|
||||
assertEquals(message, expected, RevisionInfoBean.getBean(session));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test these file contents, expect the dummy bean as a result.
|
||||
*/
|
||||
private void testThisExpectedFailure(String message, String fileContents) {
|
||||
testThisResourceFile(message, fileContents, DUMMY_BEAN);
|
||||
}
|
||||
|
||||
}
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.config;
|
||||
|
||||
import static edu.cornell.mannlib.vitro.webapp.config.RevisionInfoBean.DUMMY_BEAN;
|
||||
import static edu.cornell.mannlib.vitro.webapp.config.RevisionInfoSetup.DATE_FORMAT;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
|
||||
import javax.servlet.ServletContextEvent;
|
||||
import javax.servlet.ServletContextListener;
|
||||
|
||||
import org.apache.log4j.Level;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import stubs.javax.servlet.ServletContextStub;
|
||||
import stubs.javax.servlet.http.HttpSessionStub;
|
||||
|
||||
import com.ibm.icu.text.SimpleDateFormat;
|
||||
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.config.RevisionInfoBean.LevelRevisionInfo;
|
||||
import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus;
|
||||
|
||||
/**
|
||||
* Test for RevisionInfoSetup
|
||||
*/
|
||||
public class RevisionInfoSetupTest extends AbstractTestClass {
|
||||
private ServletContextStub context;
|
||||
private HttpSessionStub session;
|
||||
private ServletContextListener listener;
|
||||
private ServletContextEvent event;
|
||||
|
||||
@Before
|
||||
public void setupContext() {
|
||||
context = new ServletContextStub();
|
||||
|
||||
session = new HttpSessionStub();
|
||||
session.setServletContext(context);
|
||||
|
||||
event = new ServletContextEvent(context);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void createContextListener() {
|
||||
listener = new RevisionInfoSetup();
|
||||
}
|
||||
|
||||
@Before
|
||||
public void suppressInfoMessages() {
|
||||
setLoggerLevel(RevisionInfoBean.class, Level.WARN);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void suppressMessagesFromStartupStatus() {
|
||||
setLoggerLevel(StartupStatus.class, Level.OFF);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noResourceFile() {
|
||||
setLoggerLevel(RevisionInfoSetup.class, Level.OFF);
|
||||
testThisExpectedFailure("no resource", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resourceFileIsEmpty() {
|
||||
setLoggerLevel(RevisionInfoSetup.class, Level.OFF);
|
||||
testThisExpectedFailure("empty resource", "");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resourceFileHasNoSignificantLines() {
|
||||
setLoggerLevel(RevisionInfoSetup.class, Level.OFF);
|
||||
testThisExpectedFailure("no siginificant lines", " \n # \n\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resourceFileHasInvalidDateLine() {
|
||||
setLoggerLevel(RevisionInfoSetup.class, Level.OFF);
|
||||
testThisExpectedFailure("invalid date line", "BOGUS DATE LINE\n"
|
||||
+ "name ~ release ~ revision");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resourceFileHasInvalidLevelLine() {
|
||||
setLoggerLevel(RevisionInfoSetup.class, Level.OFF);
|
||||
testThisExpectedFailure("invalid level line", "2010-02-13 23:55:00\n"
|
||||
+ "name ~ release ~revision");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void simpleSingleLevel() {
|
||||
testThisResourceFile(
|
||||
"simple single level",
|
||||
"2010-02-13 23:55:00\n" + "name ~ release ~ revision",
|
||||
bean(date("2010-02-13 23:55:00"),
|
||||
level("name", "release", "revision")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ignoreWhiteSpaceAroundDate() {
|
||||
testThisResourceFile(
|
||||
"white space around date",
|
||||
" 1999-01-01 00:00:00 \n" + "name ~ release ~ revision",
|
||||
bean(date("1999-01-01 00:00:00"),
|
||||
level("name", "release", "revision")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ignoreWhiteSpaceInLevelInfo() {
|
||||
testThisResourceFile(
|
||||
"white space in level info",
|
||||
"2010-02-13 23:55:00\n"
|
||||
+ " name ~ release ~ revision ",
|
||||
bean(date("2010-02-13 23:55:00"),
|
||||
level("name", "release", "revision")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ignoreBlankLinesAndComments() {
|
||||
testThisResourceFile(
|
||||
"ignore empty lines",
|
||||
"2010-02-13 23:55:00\n" + "\n" + " \n" + " # \n"
|
||||
+ "name ~ release ~ revision",
|
||||
bean(date("2010-02-13 23:55:00"),
|
||||
level("name", "release", "revision")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseMultipleLevels() {
|
||||
testThisResourceFile(
|
||||
"multiple levels",
|
||||
"2010-02-13 23:55:00\n" + "name ~ release ~ revision\n"
|
||||
+ "name2 ~ release2 ~ revision2\n",
|
||||
bean(date("2010-02-13 23:55:00"),
|
||||
level("name", "release", "revision"),
|
||||
level("name2", "release2", "revision2")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseNoLevels() {
|
||||
testThisResourceFile("no levels", "2010-02-13 23:55:00\n",
|
||||
bean(date("2010-02-13 23:55:00")));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private RevisionInfoBean bean(Date date, LevelRevisionInfo... levels) {
|
||||
return new RevisionInfoBean(date, Arrays.asList(levels));
|
||||
}
|
||||
|
||||
private LevelRevisionInfo level(String name, String release, String revision) {
|
||||
return new LevelRevisionInfo(name, release, revision);
|
||||
}
|
||||
|
||||
private Date date(String string) {
|
||||
try {
|
||||
return new SimpleDateFormat(DATE_FORMAT).parse(string);
|
||||
} catch (ParseException e) {
|
||||
throw new IllegalArgumentException(
|
||||
"Can't parse this date string: '" + string + "'");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test these file contents, compare to this expected bean.
|
||||
*/
|
||||
private void testThisResourceFile(String message, String fileContents,
|
||||
RevisionInfoBean expected) {
|
||||
context.setMockResource(RevisionInfoSetup.RESOURCE_PATH, fileContents);
|
||||
|
||||
listener.contextInitialized(event);
|
||||
assertEquals(message, expected, RevisionInfoBean.getBean(session));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test these file contents, expect the dummy bean as a result.
|
||||
*/
|
||||
private void testThisExpectedFailure(String message, String fileContents) {
|
||||
testThisResourceFile(message, fileContents, DUMMY_BEAN);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,52 +1,52 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.accounts;
|
||||
|
||||
import static edu.cornell.mannlib.vitro.webapp.controller.accounts.UserAccountsOrdering.DEFAULT_ORDERING;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.accounts.UserAccountsOrdering;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.accounts.UserAccountsSelectionCriteria;
|
||||
|
||||
public class UserAccountsSelectionCriteriaTest {
|
||||
private UserAccountsSelectionCriteria criteria;
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void accountsPerPageOutOfRange() {
|
||||
criteria = create(0, 10, DEFAULT_ORDERING, "role", "search");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void pageIndexOutOfRange() {
|
||||
criteria = create(10, -1, DEFAULT_ORDERING, "role", "search");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void orderByIsNull() {
|
||||
criteria = create(10, 1, null, "role", "search");
|
||||
assertEquals("ordering", UserAccountsOrdering.DEFAULT_ORDERING,
|
||||
criteria.getOrderBy());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void roleFilterUriIsNull() {
|
||||
criteria = create(10, 1, DEFAULT_ORDERING, null, "search");
|
||||
assertEquals("roleFilter", "", criteria.getRoleFilterUri());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void searchTermIsNull() {
|
||||
criteria = create(10, 1, DEFAULT_ORDERING, "role", null);
|
||||
assertEquals("searchTerm", "", criteria.getSearchTerm());
|
||||
}
|
||||
|
||||
private UserAccountsSelectionCriteria create(int accountsPerPage,
|
||||
int pageIndex, UserAccountsOrdering orderBy, String roleFilterUri,
|
||||
String searchTerm) {
|
||||
return new UserAccountsSelectionCriteria(accountsPerPage, pageIndex,
|
||||
orderBy, roleFilterUri, searchTerm);
|
||||
}
|
||||
|
||||
}
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.accounts;
|
||||
|
||||
import static edu.cornell.mannlib.vitro.webapp.controller.accounts.UserAccountsOrdering.DEFAULT_ORDERING;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.accounts.UserAccountsOrdering;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.accounts.UserAccountsSelectionCriteria;
|
||||
|
||||
public class UserAccountsSelectionCriteriaTest {
|
||||
private UserAccountsSelectionCriteria criteria;
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void accountsPerPageOutOfRange() {
|
||||
criteria = create(0, 10, DEFAULT_ORDERING, "role", "search");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void pageIndexOutOfRange() {
|
||||
criteria = create(10, -1, DEFAULT_ORDERING, "role", "search");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void orderByIsNull() {
|
||||
criteria = create(10, 1, null, "role", "search");
|
||||
assertEquals("ordering", UserAccountsOrdering.DEFAULT_ORDERING,
|
||||
criteria.getOrderBy());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void roleFilterUriIsNull() {
|
||||
criteria = create(10, 1, DEFAULT_ORDERING, null, "search");
|
||||
assertEquals("roleFilter", "", criteria.getRoleFilterUri());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void searchTermIsNull() {
|
||||
criteria = create(10, 1, DEFAULT_ORDERING, "role", null);
|
||||
assertEquals("searchTerm", "", criteria.getSearchTerm());
|
||||
}
|
||||
|
||||
private UserAccountsSelectionCriteria create(int accountsPerPage,
|
||||
int pageIndex, UserAccountsOrdering orderBy, String roleFilterUri,
|
||||
String searchTerm) {
|
||||
return new UserAccountsSelectionCriteria(accountsPerPage, pageIndex,
|
||||
orderBy, roleFilterUri, searchTerm);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,359 +1,359 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.accounts;
|
||||
|
||||
import static edu.cornell.mannlib.vitro.webapp.controller.accounts.UserAccountsOrdering.DEFAULT_ORDERING;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
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.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.accounts.UserAccountsOrdering.Direction;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.accounts.UserAccountsOrdering.Field;
|
||||
|
||||
public class UserAccountsSelectorTest extends AbstractTestClass {
|
||||
/**
|
||||
* Where the model statements are stored for this test.
|
||||
*/
|
||||
private static final String N3_DATA_FILENAME = "UserAccountsSelectorTest.n3";
|
||||
|
||||
private static final String NS_MINE = "http://vivo.mydomain.edu/individual/";
|
||||
|
||||
private static OntModel ontModel;
|
||||
|
||||
@BeforeClass
|
||||
public static void setupModel() throws IOException {
|
||||
InputStream stream = UserAccountsSelectorTest.class
|
||||
.getResourceAsStream(N3_DATA_FILENAME);
|
||||
Model model = ModelFactory.createDefaultModel();
|
||||
model.read(stream, null, "N3");
|
||||
stream.close();
|
||||
|
||||
ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM,
|
||||
model);
|
||||
ontModel.prepare();
|
||||
}
|
||||
|
||||
private UserAccountsSelection selection;
|
||||
private UserAccountsSelectionCriteria criteria;
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// exceptions tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void modelIsNull() {
|
||||
UserAccountsSelector.select(null,
|
||||
criteria(10, 1, DEFAULT_ORDERING, "", ""));
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void criteriaIsNull() {
|
||||
UserAccountsSelector.select(ontModel, null);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// fields tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void checkAllFields() {
|
||||
selectOnCriteria(1, 10, DEFAULT_ORDERING, "", "");
|
||||
assertSelectedUris(10, "user10");
|
||||
|
||||
UserAccount acct = selection.getUserAccounts().get(0);
|
||||
assertEquals("uri", "http://vivo.mydomain.edu/individual/user10",
|
||||
acct.getUri());
|
||||
assertEquals("email", "email@jones.edu", acct.getEmailAddress());
|
||||
assertEquals("firstName", "Bob", acct.getFirstName());
|
||||
assertEquals("lastName", "Caruso", acct.getLastName());
|
||||
assertEquals("password", "garbage", acct.getMd5Password());
|
||||
assertEquals("expires", 1100234965897L, acct.getPasswordLinkExpires());
|
||||
assertEquals("loginCount", 50, acct.getLoginCount());
|
||||
assertEquals("lastLogin", 1020304050607080L, acct.getLastLoginTime());
|
||||
assertEquals("status", UserAccount.Status.ACTIVE, acct.getStatus());
|
||||
assertEqualSets(
|
||||
"permissions",
|
||||
Collections
|
||||
.singleton("http://vivo.mydomain.edu/individual/role2"),
|
||||
acct.getPermissionSetUris());
|
||||
assertEquals("rootUser", false, acct.isRootUser());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkFieldsForRootUser() {
|
||||
selectOnCriteria(1, 8, DEFAULT_ORDERING, "", "");
|
||||
assertSelectedUris(10, "user08");
|
||||
|
||||
UserAccount acct = selection.getUserAccounts().get(0);
|
||||
assertEquals("uri", "http://vivo.mydomain.edu/individual/user08",
|
||||
acct.getUri());
|
||||
assertEquals("email", "email@henry.edu", acct.getEmailAddress());
|
||||
assertEquals("firstName", "Mary", acct.getFirstName());
|
||||
assertEquals("lastName", "McInerney", acct.getLastName());
|
||||
assertEquals("password", "garbage", acct.getMd5Password());
|
||||
assertEquals("expires", 0L, acct.getPasswordLinkExpires());
|
||||
assertEquals("loginCount", 7, acct.getLoginCount());
|
||||
assertEquals("lastLogin", 1122334455667788L, acct.getLastLoginTime());
|
||||
assertEquals("status", UserAccount.Status.ACTIVE, acct.getStatus());
|
||||
assertEqualSets("permissions", Collections.<String> emptySet(),
|
||||
acct.getPermissionSetUris());
|
||||
assertEquals("rootUser", true, acct.isRootUser());
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// pagination tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void showFirstPageOfFifteen() {
|
||||
selectOnCriteria(15, 1, DEFAULT_ORDERING, "", "");
|
||||
assertSelectedUris(10, "user01", "user02", "user03", "user04",
|
||||
"user05", "user06", "user07", "user08", "user09", "user10");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void showFirstPageOfOne() {
|
||||
selectOnCriteria(1, 1, DEFAULT_ORDERING, "", "");
|
||||
assertSelectedUris(10, "user01");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void showFirstPageOfFive() {
|
||||
selectOnCriteria(5, 1, DEFAULT_ORDERING, "", "");
|
||||
assertSelectedUris(10, "user01", "user02", "user03", "user04", "user05");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void showSecondPageOfSeven() {
|
||||
selectOnCriteria(7, 2, DEFAULT_ORDERING, "", "");
|
||||
assertSelectedUris(10, "user08", "user09", "user10");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void showTenthPageOfThree() {
|
||||
selectOnCriteria(3, 10, DEFAULT_ORDERING, "", "");
|
||||
assertSelectedUris(10);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// sorting tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void sortByEmailAscending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(Field.EMAIL,
|
||||
Direction.ASCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
assertSelectedUris(10, "user01", "user02", "user03");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByEmailDescending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(Field.EMAIL,
|
||||
Direction.DESCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
assertSelectedUris(10, "user10", "user09", "user08");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByFirstNameAscending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(
|
||||
Field.FIRST_NAME, Direction.ASCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
// user02 has no first name: collates as least value.
|
||||
assertSelectedUris(10, "user02", "user10", "user09");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByFirstNameDescending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(
|
||||
Field.FIRST_NAME, Direction.DESCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
// user02 has no first name: collates as least value.
|
||||
assertSelectedUris(10, "user01", "user03", "user04");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByLastNameAscending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(
|
||||
Field.LAST_NAME, Direction.ASCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
// user03 has no last name: collates as least value.
|
||||
assertSelectedUris(10, "user03", "user05", "user09");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByLastNameDescending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(
|
||||
Field.LAST_NAME, Direction.DESCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
assertSelectedUris(10, "user06", "user07", "user01");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByStatusAscending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(Field.STATUS,
|
||||
Direction.ASCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
// user07 has no status: collates as least value.
|
||||
assertSelectedUris(10, "user07", "user01", "user04");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByStatusDescending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(Field.STATUS,
|
||||
Direction.DESCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
assertSelectedUris(10, "user02", "user03", "user06");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByLoginCountAscending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(
|
||||
Field.LOGIN_COUNT, Direction.ASCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
// user06 has no login count: reads as 0.
|
||||
assertSelectedUris(10, "user06", "user03", "user07");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByLoginCountDescending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(
|
||||
Field.LOGIN_COUNT, Direction.DESCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
assertSelectedUris(10, "user10", "user04", "user08");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByLastLoginTimeAscending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(
|
||||
Field.LAST_LOGIN_TIME, Direction.ASCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
// user06 has no login count: reads as 0.
|
||||
assertSelectedUris(10, "user07", "user03", "user06");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByLastLoginTimeDescending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(
|
||||
Field.LAST_LOGIN_TIME, Direction.DESCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
assertSelectedUris(10, "user08", "user10", "user09");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// filtering tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void filterAgainstRole1() {
|
||||
selectOnCriteria(20, 1, DEFAULT_ORDERING, NS_MINE + "role1", "");
|
||||
assertSelectedUris(6, "user01", "user02", "user03", "user05", "user06",
|
||||
"user09");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterAgainstRole2() {
|
||||
selectOnCriteria(20, 1, DEFAULT_ORDERING, NS_MINE + "role2", "");
|
||||
assertSelectedUris(2, "user03", "user10");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterAgainstNoSuchRole() {
|
||||
selectOnCriteria(20, 1, DEFAULT_ORDERING, "BogusRole", "");
|
||||
assertSelectedUris(0);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// search tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void searchTermFoundInAllThreeFields() {
|
||||
selectOnCriteria(20, 1, DEFAULT_ORDERING, "", "bob");
|
||||
assertSelectedUris(3, "user02", "user05", "user10");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void searchTermNotFound() {
|
||||
selectOnCriteria(20, 1, DEFAULT_ORDERING, "", "bogus");
|
||||
assertSelectedUris(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* If the special characters were allowed into the Regex, this would have 3
|
||||
* matches. If they are escaped properly, it will have none.
|
||||
*/
|
||||
@Test
|
||||
public void searchTermContainsSpecialRegexCharacters() {
|
||||
selectOnCriteria(20, 1, DEFAULT_ORDERING, "", "b.b");
|
||||
assertSelectedUris(0);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// combination tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void searchWithFilter() {
|
||||
selectOnCriteria(20, 1, DEFAULT_ORDERING, NS_MINE + "role1", "bob");
|
||||
assertSelectedUris(2, "user02", "user05");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void searchWithFilterPaginatedWithFunkySortOrder() {
|
||||
selectOnCriteria(1, 2, new UserAccountsOrdering(Field.STATUS,
|
||||
Direction.ASCENDING), NS_MINE + "role1", "bob");
|
||||
assertSelectedUris(2, "user02");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/** Create a new criteria object */
|
||||
private UserAccountsSelectionCriteria criteria(int accountsPerPage,
|
||||
int pageIndex, UserAccountsOrdering orderBy, String roleFilterUri,
|
||||
String searchTerm) {
|
||||
return new UserAccountsSelectionCriteria(accountsPerPage, pageIndex,
|
||||
orderBy, roleFilterUri, searchTerm);
|
||||
}
|
||||
|
||||
/** Create a criteria object and select against it. */
|
||||
private void selectOnCriteria(int accountsPerPage, int pageIndex,
|
||||
UserAccountsOrdering orderBy, String roleFilterUri,
|
||||
String searchTerm) {
|
||||
criteria = new UserAccountsSelectionCriteria(accountsPerPage,
|
||||
pageIndex, orderBy, roleFilterUri, searchTerm);
|
||||
selection = UserAccountsSelector.select(ontModel, criteria);
|
||||
}
|
||||
|
||||
/** How many URIs should we expect, and which ones (local names only). */
|
||||
private void assertSelectedUris(int resultCount, String... uris) {
|
||||
assertEquals("result count", resultCount, selection.getResultCount());
|
||||
|
||||
List<String> expectedList = Arrays.asList(uris);
|
||||
List<String> actualList = new ArrayList<String>();
|
||||
for (UserAccount a : selection.getUserAccounts()) {
|
||||
String[] uriParts = a.getUri().split("/");
|
||||
actualList.add(uriParts[uriParts.length - 1]);
|
||||
}
|
||||
assertEquals("uris", expectedList, actualList);
|
||||
}
|
||||
|
||||
}
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.accounts;
|
||||
|
||||
import static edu.cornell.mannlib.vitro.webapp.controller.accounts.UserAccountsOrdering.DEFAULT_ORDERING;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
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.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.accounts.UserAccountsOrdering.Direction;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.accounts.UserAccountsOrdering.Field;
|
||||
|
||||
public class UserAccountsSelectorTest extends AbstractTestClass {
|
||||
/**
|
||||
* Where the model statements are stored for this test.
|
||||
*/
|
||||
private static final String N3_DATA_FILENAME = "UserAccountsSelectorTest.n3";
|
||||
|
||||
private static final String NS_MINE = "http://vivo.mydomain.edu/individual/";
|
||||
|
||||
private static OntModel ontModel;
|
||||
|
||||
@BeforeClass
|
||||
public static void setupModel() throws IOException {
|
||||
InputStream stream = UserAccountsSelectorTest.class
|
||||
.getResourceAsStream(N3_DATA_FILENAME);
|
||||
Model model = ModelFactory.createDefaultModel();
|
||||
model.read(stream, null, "N3");
|
||||
stream.close();
|
||||
|
||||
ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM,
|
||||
model);
|
||||
ontModel.prepare();
|
||||
}
|
||||
|
||||
private UserAccountsSelection selection;
|
||||
private UserAccountsSelectionCriteria criteria;
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// exceptions tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void modelIsNull() {
|
||||
UserAccountsSelector.select(null,
|
||||
criteria(10, 1, DEFAULT_ORDERING, "", ""));
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void criteriaIsNull() {
|
||||
UserAccountsSelector.select(ontModel, null);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// fields tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void checkAllFields() {
|
||||
selectOnCriteria(1, 10, DEFAULT_ORDERING, "", "");
|
||||
assertSelectedUris(10, "user10");
|
||||
|
||||
UserAccount acct = selection.getUserAccounts().get(0);
|
||||
assertEquals("uri", "http://vivo.mydomain.edu/individual/user10",
|
||||
acct.getUri());
|
||||
assertEquals("email", "email@jones.edu", acct.getEmailAddress());
|
||||
assertEquals("firstName", "Bob", acct.getFirstName());
|
||||
assertEquals("lastName", "Caruso", acct.getLastName());
|
||||
assertEquals("password", "garbage", acct.getMd5Password());
|
||||
assertEquals("expires", 1100234965897L, acct.getPasswordLinkExpires());
|
||||
assertEquals("loginCount", 50, acct.getLoginCount());
|
||||
assertEquals("lastLogin", 1020304050607080L, acct.getLastLoginTime());
|
||||
assertEquals("status", UserAccount.Status.ACTIVE, acct.getStatus());
|
||||
assertEqualSets(
|
||||
"permissions",
|
||||
Collections
|
||||
.singleton("http://vivo.mydomain.edu/individual/role2"),
|
||||
acct.getPermissionSetUris());
|
||||
assertEquals("rootUser", false, acct.isRootUser());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkFieldsForRootUser() {
|
||||
selectOnCriteria(1, 8, DEFAULT_ORDERING, "", "");
|
||||
assertSelectedUris(10, "user08");
|
||||
|
||||
UserAccount acct = selection.getUserAccounts().get(0);
|
||||
assertEquals("uri", "http://vivo.mydomain.edu/individual/user08",
|
||||
acct.getUri());
|
||||
assertEquals("email", "email@henry.edu", acct.getEmailAddress());
|
||||
assertEquals("firstName", "Mary", acct.getFirstName());
|
||||
assertEquals("lastName", "McInerney", acct.getLastName());
|
||||
assertEquals("password", "garbage", acct.getMd5Password());
|
||||
assertEquals("expires", 0L, acct.getPasswordLinkExpires());
|
||||
assertEquals("loginCount", 7, acct.getLoginCount());
|
||||
assertEquals("lastLogin", 1122334455667788L, acct.getLastLoginTime());
|
||||
assertEquals("status", UserAccount.Status.ACTIVE, acct.getStatus());
|
||||
assertEqualSets("permissions", Collections.<String> emptySet(),
|
||||
acct.getPermissionSetUris());
|
||||
assertEquals("rootUser", true, acct.isRootUser());
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// pagination tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void showFirstPageOfFifteen() {
|
||||
selectOnCriteria(15, 1, DEFAULT_ORDERING, "", "");
|
||||
assertSelectedUris(10, "user01", "user02", "user03", "user04",
|
||||
"user05", "user06", "user07", "user08", "user09", "user10");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void showFirstPageOfOne() {
|
||||
selectOnCriteria(1, 1, DEFAULT_ORDERING, "", "");
|
||||
assertSelectedUris(10, "user01");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void showFirstPageOfFive() {
|
||||
selectOnCriteria(5, 1, DEFAULT_ORDERING, "", "");
|
||||
assertSelectedUris(10, "user01", "user02", "user03", "user04", "user05");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void showSecondPageOfSeven() {
|
||||
selectOnCriteria(7, 2, DEFAULT_ORDERING, "", "");
|
||||
assertSelectedUris(10, "user08", "user09", "user10");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void showTenthPageOfThree() {
|
||||
selectOnCriteria(3, 10, DEFAULT_ORDERING, "", "");
|
||||
assertSelectedUris(10);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// sorting tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void sortByEmailAscending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(Field.EMAIL,
|
||||
Direction.ASCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
assertSelectedUris(10, "user01", "user02", "user03");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByEmailDescending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(Field.EMAIL,
|
||||
Direction.DESCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
assertSelectedUris(10, "user10", "user09", "user08");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByFirstNameAscending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(
|
||||
Field.FIRST_NAME, Direction.ASCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
// user02 has no first name: collates as least value.
|
||||
assertSelectedUris(10, "user02", "user10", "user09");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByFirstNameDescending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(
|
||||
Field.FIRST_NAME, Direction.DESCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
// user02 has no first name: collates as least value.
|
||||
assertSelectedUris(10, "user01", "user03", "user04");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByLastNameAscending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(
|
||||
Field.LAST_NAME, Direction.ASCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
// user03 has no last name: collates as least value.
|
||||
assertSelectedUris(10, "user03", "user05", "user09");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByLastNameDescending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(
|
||||
Field.LAST_NAME, Direction.DESCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
assertSelectedUris(10, "user06", "user07", "user01");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByStatusAscending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(Field.STATUS,
|
||||
Direction.ASCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
// user07 has no status: collates as least value.
|
||||
assertSelectedUris(10, "user07", "user01", "user04");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByStatusDescending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(Field.STATUS,
|
||||
Direction.DESCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
assertSelectedUris(10, "user02", "user03", "user06");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByLoginCountAscending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(
|
||||
Field.LOGIN_COUNT, Direction.ASCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
// user06 has no login count: reads as 0.
|
||||
assertSelectedUris(10, "user06", "user03", "user07");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByLoginCountDescending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(
|
||||
Field.LOGIN_COUNT, Direction.DESCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
assertSelectedUris(10, "user10", "user04", "user08");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByLastLoginTimeAscending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(
|
||||
Field.LAST_LOGIN_TIME, Direction.ASCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
// user06 has no login count: reads as 0.
|
||||
assertSelectedUris(10, "user07", "user03", "user06");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByLastLoginTimeDescending() {
|
||||
UserAccountsOrdering orderBy = new UserAccountsOrdering(
|
||||
Field.LAST_LOGIN_TIME, Direction.DESCENDING);
|
||||
selectOnCriteria(3, 1, orderBy, "", "");
|
||||
assertSelectedUris(10, "user08", "user10", "user09");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// filtering tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void filterAgainstRole1() {
|
||||
selectOnCriteria(20, 1, DEFAULT_ORDERING, NS_MINE + "role1", "");
|
||||
assertSelectedUris(6, "user01", "user02", "user03", "user05", "user06",
|
||||
"user09");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterAgainstRole2() {
|
||||
selectOnCriteria(20, 1, DEFAULT_ORDERING, NS_MINE + "role2", "");
|
||||
assertSelectedUris(2, "user03", "user10");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterAgainstNoSuchRole() {
|
||||
selectOnCriteria(20, 1, DEFAULT_ORDERING, "BogusRole", "");
|
||||
assertSelectedUris(0);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// search tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void searchTermFoundInAllThreeFields() {
|
||||
selectOnCriteria(20, 1, DEFAULT_ORDERING, "", "bob");
|
||||
assertSelectedUris(3, "user02", "user05", "user10");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void searchTermNotFound() {
|
||||
selectOnCriteria(20, 1, DEFAULT_ORDERING, "", "bogus");
|
||||
assertSelectedUris(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* If the special characters were allowed into the Regex, this would have 3
|
||||
* matches. If they are escaped properly, it will have none.
|
||||
*/
|
||||
@Test
|
||||
public void searchTermContainsSpecialRegexCharacters() {
|
||||
selectOnCriteria(20, 1, DEFAULT_ORDERING, "", "b.b");
|
||||
assertSelectedUris(0);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// combination tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void searchWithFilter() {
|
||||
selectOnCriteria(20, 1, DEFAULT_ORDERING, NS_MINE + "role1", "bob");
|
||||
assertSelectedUris(2, "user02", "user05");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void searchWithFilterPaginatedWithFunkySortOrder() {
|
||||
selectOnCriteria(1, 2, new UserAccountsOrdering(Field.STATUS,
|
||||
Direction.ASCENDING), NS_MINE + "role1", "bob");
|
||||
assertSelectedUris(2, "user02");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/** Create a new criteria object */
|
||||
private UserAccountsSelectionCriteria criteria(int accountsPerPage,
|
||||
int pageIndex, UserAccountsOrdering orderBy, String roleFilterUri,
|
||||
String searchTerm) {
|
||||
return new UserAccountsSelectionCriteria(accountsPerPage, pageIndex,
|
||||
orderBy, roleFilterUri, searchTerm);
|
||||
}
|
||||
|
||||
/** Create a criteria object and select against it. */
|
||||
private void selectOnCriteria(int accountsPerPage, int pageIndex,
|
||||
UserAccountsOrdering orderBy, String roleFilterUri,
|
||||
String searchTerm) {
|
||||
criteria = new UserAccountsSelectionCriteria(accountsPerPage,
|
||||
pageIndex, orderBy, roleFilterUri, searchTerm);
|
||||
selection = UserAccountsSelector.select(ontModel, criteria);
|
||||
}
|
||||
|
||||
/** How many URIs should we expect, and which ones (local names only). */
|
||||
private void assertSelectedUris(int resultCount, String... uris) {
|
||||
assertEquals("result count", resultCount, selection.getResultCount());
|
||||
|
||||
List<String> expectedList = Arrays.asList(uris);
|
||||
List<String> actualList = new ArrayList<String>();
|
||||
for (UserAccount a : selection.getUserAccounts()) {
|
||||
String[] uriParts = a.getUri().split("/");
|
||||
actualList.add(uriParts[uriParts.length - 1]);
|
||||
}
|
||||
assertEquals("uris", expectedList, actualList);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,164 +1,164 @@
|
|||
# $This file is distributed under the terms of the license in /doc/license.txt$
|
||||
|
||||
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
|
||||
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
|
||||
@prefix owl: <http://www.w3.org/2002/07/owl#> .
|
||||
@prefix auth: <http://vitro.mannlib.cornell.edu/ns/vitro/authorization#> .
|
||||
@prefix mydomain: <http://vivo.mydomain.edu/individual/> .
|
||||
|
||||
### This file is for the test UserAccountsSelectorTest.java.
|
||||
|
||||
#
|
||||
# Note: each optional field (everything except URI and emailAddress) is missing
|
||||
# from some user account.
|
||||
#
|
||||
# Note: user accounts have 0, 1, or 2 permission sets.
|
||||
#
|
||||
|
||||
mydomain:user01
|
||||
a auth:UserAccount ;
|
||||
auth:emailAddress "email@able.edu" ;
|
||||
auth:firstName "Zack" ;
|
||||
auth:lastName "Roberts" ;
|
||||
auth:md5password "garbage" ;
|
||||
auth:passwordChangeExpires 0 ;
|
||||
auth:loginCount 5 ;
|
||||
auth:lastLoginTime 100 ;
|
||||
auth:status "ACTIVE" ;
|
||||
auth:hasPermissionSet mydomain:role1 ;
|
||||
.
|
||||
|
||||
mydomain:user02
|
||||
a auth:UserAccount ;
|
||||
auth:emailAddress "email@bob.edu" ;
|
||||
# auth:firstName NONE ;
|
||||
auth:lastName "Cole" ;
|
||||
auth:md5password "garbage" ;
|
||||
auth:passwordChangeExpires 0 ;
|
||||
auth:loginCount 5 ;
|
||||
auth:lastLoginTime 100 ;
|
||||
auth:status "INACTIVE" ;
|
||||
auth:hasPermissionSet mydomain:role1 ;
|
||||
.
|
||||
|
||||
mydomain:user03
|
||||
a auth:UserAccount ;
|
||||
auth:emailAddress "email@charlie.edu" ;
|
||||
auth:firstName "Ralph" ;
|
||||
# auth:lastName NONE ;
|
||||
auth:md5password "garbage" ;
|
||||
auth:passwordChangeExpires 0 ;
|
||||
auth:loginCount 0 ;
|
||||
auth:lastLoginTime 1 ;
|
||||
auth:status "INACTIVE" ;
|
||||
auth:hasPermissionSet mydomain:role1 ;
|
||||
auth:hasPermissionSet mydomain:role2 ;
|
||||
.
|
||||
|
||||
mydomain:user04
|
||||
a auth:UserAccount ;
|
||||
auth:emailAddress "email@delta.edu" ;
|
||||
auth:firstName "Queen" ;
|
||||
auth:lastName "Latifah" ;
|
||||
# auth:md5password NONE ;
|
||||
auth:passwordChangeExpires 0 ;
|
||||
auth:loginCount 9 ;
|
||||
auth:lastLoginTime 3 ;
|
||||
auth:status "ACTIVE" ;
|
||||
.
|
||||
|
||||
mydomain:user05
|
||||
a auth:UserAccount ;
|
||||
auth:emailAddress "email@echo.edu" ;
|
||||
auth:firstName "Paul" ;
|
||||
auth:lastName "Archibob" ;
|
||||
auth:md5password "garbage" ;
|
||||
# auth:passwordChangeExpires NONE ;
|
||||
auth:loginCount 2 ;
|
||||
auth:lastLoginTime 100 ;
|
||||
auth:status "ACTIVE" ;
|
||||
auth:hasPermissionSet mydomain:role1 ;
|
||||
.
|
||||
|
||||
mydomain:user06
|
||||
a auth:UserAccount ;
|
||||
auth:emailAddress "email@foxtrot.edu" ;
|
||||
auth:firstName "Nancy" ;
|
||||
auth:lastName "Xavier" ;
|
||||
auth:md5password "garbage" ;
|
||||
auth:passwordChangeExpires 0 ;
|
||||
# auth:loginCount NONE ;
|
||||
auth:lastLoginTime 2 ;
|
||||
auth:status "INACTIVE" ;
|
||||
auth:hasPermissionSet mydomain:role1 ;
|
||||
.
|
||||
|
||||
mydomain:user07
|
||||
a auth:UserAccount ;
|
||||
auth:emailAddress "email@golf.edu" ;
|
||||
auth:firstName "Oprah" ;
|
||||
auth:lastName "Winfrey" ;
|
||||
auth:md5password "garbage" ;
|
||||
auth:passwordChangeExpires 0 ;
|
||||
auth:loginCount 1 ;
|
||||
# auth:lastLoginTime NONE ;
|
||||
# auth:status NONE ;
|
||||
auth:hasPermissionSet mydomain:role22 ;
|
||||
.
|
||||
|
||||
mydomain:user08
|
||||
a auth:UserAccount ;
|
||||
a auth:RootUserAccount ;
|
||||
auth:emailAddress "email@henry.edu" ;
|
||||
auth:firstName "Mary" ;
|
||||
auth:lastName "McInerney" ;
|
||||
auth:md5password "garbage" ;
|
||||
auth:passwordChangeExpires 0 ;
|
||||
auth:loginCount 7 ;
|
||||
auth:lastLoginTime 1122334455667788 ;
|
||||
auth:status "ACTIVE" ;
|
||||
.
|
||||
|
||||
mydomain:user09
|
||||
a auth:UserAccount ;
|
||||
auth:emailAddress "email@indigo.edu" ;
|
||||
auth:firstName "Jim" ;
|
||||
auth:lastName "Blake" ;
|
||||
auth:md5password "garbage" ;
|
||||
auth:passwordChangeExpires 0 ;
|
||||
auth:loginCount 3 ;
|
||||
auth:lastLoginTime 1000000000000000 ;
|
||||
auth:status "ACTIVE" ;
|
||||
auth:hasPermissionSet mydomain:role1 ;
|
||||
.
|
||||
|
||||
mydomain:user10
|
||||
a auth:UserAccount ;
|
||||
auth:emailAddress "email@jones.edu" ;
|
||||
auth:firstName "Bob" ;
|
||||
auth:lastName "Caruso" ;
|
||||
auth:md5password "garbage" ;
|
||||
auth:passwordChangeExpires 1100234965897 ;
|
||||
auth:loginCount 50 ;
|
||||
auth:lastLoginTime 1020304050607080 ;
|
||||
auth:status "ACTIVE" ;
|
||||
auth:hasPermissionSet mydomain:role2 ;
|
||||
.
|
||||
|
||||
mydomain:role1
|
||||
a auth:PermissionSet ;
|
||||
rdfs:label "Role 1" ;
|
||||
.
|
||||
|
||||
mydomain:role2
|
||||
a auth:PermissionSet ;
|
||||
rdfs:label "Role 2" ;
|
||||
.
|
||||
|
||||
# this is intentionally a typographical extension of mydomain:role2
|
||||
# to test that our reg-exp filters correctly.
|
||||
mydomain:role22
|
||||
a auth:PermissionSet ;
|
||||
rdfs:label "Role 22" ;
|
||||
.
|
||||
|
||||
# $This file is distributed under the terms of the license in /doc/license.txt$
|
||||
|
||||
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
|
||||
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
|
||||
@prefix owl: <http://www.w3.org/2002/07/owl#> .
|
||||
@prefix auth: <http://vitro.mannlib.cornell.edu/ns/vitro/authorization#> .
|
||||
@prefix mydomain: <http://vivo.mydomain.edu/individual/> .
|
||||
|
||||
### This file is for the test UserAccountsSelectorTest.java.
|
||||
|
||||
#
|
||||
# Note: each optional field (everything except URI and emailAddress) is missing
|
||||
# from some user account.
|
||||
#
|
||||
# Note: user accounts have 0, 1, or 2 permission sets.
|
||||
#
|
||||
|
||||
mydomain:user01
|
||||
a auth:UserAccount ;
|
||||
auth:emailAddress "email@able.edu" ;
|
||||
auth:firstName "Zack" ;
|
||||
auth:lastName "Roberts" ;
|
||||
auth:md5password "garbage" ;
|
||||
auth:passwordChangeExpires 0 ;
|
||||
auth:loginCount 5 ;
|
||||
auth:lastLoginTime 100 ;
|
||||
auth:status "ACTIVE" ;
|
||||
auth:hasPermissionSet mydomain:role1 ;
|
||||
.
|
||||
|
||||
mydomain:user02
|
||||
a auth:UserAccount ;
|
||||
auth:emailAddress "email@bob.edu" ;
|
||||
# auth:firstName NONE ;
|
||||
auth:lastName "Cole" ;
|
||||
auth:md5password "garbage" ;
|
||||
auth:passwordChangeExpires 0 ;
|
||||
auth:loginCount 5 ;
|
||||
auth:lastLoginTime 100 ;
|
||||
auth:status "INACTIVE" ;
|
||||
auth:hasPermissionSet mydomain:role1 ;
|
||||
.
|
||||
|
||||
mydomain:user03
|
||||
a auth:UserAccount ;
|
||||
auth:emailAddress "email@charlie.edu" ;
|
||||
auth:firstName "Ralph" ;
|
||||
# auth:lastName NONE ;
|
||||
auth:md5password "garbage" ;
|
||||
auth:passwordChangeExpires 0 ;
|
||||
auth:loginCount 0 ;
|
||||
auth:lastLoginTime 1 ;
|
||||
auth:status "INACTIVE" ;
|
||||
auth:hasPermissionSet mydomain:role1 ;
|
||||
auth:hasPermissionSet mydomain:role2 ;
|
||||
.
|
||||
|
||||
mydomain:user04
|
||||
a auth:UserAccount ;
|
||||
auth:emailAddress "email@delta.edu" ;
|
||||
auth:firstName "Queen" ;
|
||||
auth:lastName "Latifah" ;
|
||||
# auth:md5password NONE ;
|
||||
auth:passwordChangeExpires 0 ;
|
||||
auth:loginCount 9 ;
|
||||
auth:lastLoginTime 3 ;
|
||||
auth:status "ACTIVE" ;
|
||||
.
|
||||
|
||||
mydomain:user05
|
||||
a auth:UserAccount ;
|
||||
auth:emailAddress "email@echo.edu" ;
|
||||
auth:firstName "Paul" ;
|
||||
auth:lastName "Archibob" ;
|
||||
auth:md5password "garbage" ;
|
||||
# auth:passwordChangeExpires NONE ;
|
||||
auth:loginCount 2 ;
|
||||
auth:lastLoginTime 100 ;
|
||||
auth:status "ACTIVE" ;
|
||||
auth:hasPermissionSet mydomain:role1 ;
|
||||
.
|
||||
|
||||
mydomain:user06
|
||||
a auth:UserAccount ;
|
||||
auth:emailAddress "email@foxtrot.edu" ;
|
||||
auth:firstName "Nancy" ;
|
||||
auth:lastName "Xavier" ;
|
||||
auth:md5password "garbage" ;
|
||||
auth:passwordChangeExpires 0 ;
|
||||
# auth:loginCount NONE ;
|
||||
auth:lastLoginTime 2 ;
|
||||
auth:status "INACTIVE" ;
|
||||
auth:hasPermissionSet mydomain:role1 ;
|
||||
.
|
||||
|
||||
mydomain:user07
|
||||
a auth:UserAccount ;
|
||||
auth:emailAddress "email@golf.edu" ;
|
||||
auth:firstName "Oprah" ;
|
||||
auth:lastName "Winfrey" ;
|
||||
auth:md5password "garbage" ;
|
||||
auth:passwordChangeExpires 0 ;
|
||||
auth:loginCount 1 ;
|
||||
# auth:lastLoginTime NONE ;
|
||||
# auth:status NONE ;
|
||||
auth:hasPermissionSet mydomain:role22 ;
|
||||
.
|
||||
|
||||
mydomain:user08
|
||||
a auth:UserAccount ;
|
||||
a auth:RootUserAccount ;
|
||||
auth:emailAddress "email@henry.edu" ;
|
||||
auth:firstName "Mary" ;
|
||||
auth:lastName "McInerney" ;
|
||||
auth:md5password "garbage" ;
|
||||
auth:passwordChangeExpires 0 ;
|
||||
auth:loginCount 7 ;
|
||||
auth:lastLoginTime 1122334455667788 ;
|
||||
auth:status "ACTIVE" ;
|
||||
.
|
||||
|
||||
mydomain:user09
|
||||
a auth:UserAccount ;
|
||||
auth:emailAddress "email@indigo.edu" ;
|
||||
auth:firstName "Jim" ;
|
||||
auth:lastName "Blake" ;
|
||||
auth:md5password "garbage" ;
|
||||
auth:passwordChangeExpires 0 ;
|
||||
auth:loginCount 3 ;
|
||||
auth:lastLoginTime 1000000000000000 ;
|
||||
auth:status "ACTIVE" ;
|
||||
auth:hasPermissionSet mydomain:role1 ;
|
||||
.
|
||||
|
||||
mydomain:user10
|
||||
a auth:UserAccount ;
|
||||
auth:emailAddress "email@jones.edu" ;
|
||||
auth:firstName "Bob" ;
|
||||
auth:lastName "Caruso" ;
|
||||
auth:md5password "garbage" ;
|
||||
auth:passwordChangeExpires 1100234965897 ;
|
||||
auth:loginCount 50 ;
|
||||
auth:lastLoginTime 1020304050607080 ;
|
||||
auth:status "ACTIVE" ;
|
||||
auth:hasPermissionSet mydomain:role2 ;
|
||||
.
|
||||
|
||||
mydomain:role1
|
||||
a auth:PermissionSet ;
|
||||
rdfs:label "Role 1" ;
|
||||
.
|
||||
|
||||
mydomain:role2
|
||||
a auth:PermissionSet ;
|
||||
rdfs:label "Role 2" ;
|
||||
.
|
||||
|
||||
# this is intentionally a typographical extension of mydomain:role2
|
||||
# to test that our reg-exp filters correctly.
|
||||
mydomain:role22
|
||||
a auth:PermissionSet ;
|
||||
rdfs:label "Role 22" ;
|
||||
.
|
||||
|
||||
|
|
|
@ -1,168 +1,168 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.authenticate;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import edu.cornell.mannlib.vedit.beans.LoginStatusBean;
|
||||
import edu.cornell.mannlib.vedit.beans.LoginStatusBean.AuthenticationSource;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
|
||||
|
||||
/**
|
||||
* A simple stub for unit tests that require an Authenticator. Call setup() to
|
||||
* put it into place.
|
||||
*/
|
||||
public class AuthenticatorStub extends Authenticator {
|
||||
public static final String FACTORY_ATTRIBUTE_NAME = AuthenticatorFactory.class
|
||||
.getName();
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// factory - store this in the context.
|
||||
//
|
||||
// Creates a single instance of the stub and returns it for all requests.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
public static class Factory implements Authenticator.AuthenticatorFactory {
|
||||
private final AuthenticatorStub instance = new AuthenticatorStub();
|
||||
|
||||
@Override
|
||||
public AuthenticatorStub getInstance(HttpServletRequest request) {
|
||||
instance.setRequest(request);
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Stub infrastructure
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private final Map<String, UserAccount> usersByEmail = new HashMap<String, UserAccount>();
|
||||
private final Map<String, UserAccount> usersByExternalAuthId = new HashMap<String, UserAccount>();
|
||||
|
||||
private final Map<String, List<String>> editingPermissions = new HashMap<String, List<String>>();
|
||||
private final Map<String, String> associatedUris = new HashMap<String, String>();
|
||||
private final List<String> recordedLogins = new ArrayList<String>();
|
||||
private final Map<String, String> newPasswords = new HashMap<String, String>();
|
||||
|
||||
private HttpServletRequest request;
|
||||
|
||||
private void setRequest(HttpServletRequest request) {
|
||||
this.request = request;
|
||||
}
|
||||
|
||||
public void addUser(UserAccount user) {
|
||||
usersByEmail.put(user.getEmailAddress(), user);
|
||||
|
||||
String externalAuthId = user.getExternalAuthId();
|
||||
if (!externalAuthId.isEmpty()) {
|
||||
usersByExternalAuthId.put(user.getExternalAuthId(), user);
|
||||
}
|
||||
}
|
||||
|
||||
public void addEditingPermission(String username, String personUri) {
|
||||
if (!editingPermissions.containsKey(username)) {
|
||||
editingPermissions.put(username, new ArrayList<String>());
|
||||
}
|
||||
editingPermissions.get(username).add(personUri);
|
||||
}
|
||||
|
||||
public void setAssociatedUri(String username, String individualUri) {
|
||||
associatedUris.put(username, individualUri);
|
||||
}
|
||||
|
||||
public List<String> getRecordedLoginUsernames() {
|
||||
return recordedLogins;
|
||||
}
|
||||
|
||||
public Map<String, String> getNewPasswordMap() {
|
||||
return newPasswords;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Stub methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Override
|
||||
public UserAccount getAccountForInternalAuth(String emailAddress) {
|
||||
return usersByEmail.get(emailAddress);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserAccount getAccountForExternalAuth(String externalAuthId) {
|
||||
return usersByExternalAuthId.get(externalAuthId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUserPermittedToLogin(UserAccount userAccount) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCurrentPassword(UserAccount userAccount,
|
||||
String clearTextPassword) {
|
||||
if (userAccount == null) {
|
||||
return false;
|
||||
} else {
|
||||
return userAccount.getMd5Password().equals(
|
||||
Authenticator.applyMd5Encoding(clearTextPassword));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getAssociatedIndividualUris(UserAccount userAccount) {
|
||||
List<String> uris = new ArrayList<String>();
|
||||
|
||||
String emailAddress = userAccount.getEmailAddress();
|
||||
if (associatedUris.containsKey(emailAddress)) {
|
||||
uris.add(associatedUris.get(emailAddress));
|
||||
}
|
||||
|
||||
if (editingPermissions.containsKey(emailAddress)) {
|
||||
uris.addAll(editingPermissions.get(emailAddress));
|
||||
}
|
||||
|
||||
return uris;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void recordNewPassword(UserAccount userAccount,
|
||||
String newClearTextPassword) {
|
||||
newPasswords.put(userAccount.getEmailAddress(), newClearTextPassword);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void recordLoginAgainstUserAccount(UserAccount userAccount,
|
||||
AuthenticationSource authSource) throws LoginNotPermitted {
|
||||
if (!isUserPermittedToLogin(userAccount)) {
|
||||
throw new LoginNotPermitted();
|
||||
}
|
||||
|
||||
recordedLogins.add(userAccount.getEmailAddress());
|
||||
|
||||
LoginStatusBean lsb = new LoginStatusBean(userAccount.getUri(),
|
||||
authSource);
|
||||
LoginStatusBean.setBean(request.getSession(), lsb);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Un-implemented methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Override
|
||||
public void recordUserIsLoggedOut() {
|
||||
throw new RuntimeException(
|
||||
"AuthenticatorStub.recordUserIsLoggedOut() not implemented.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean accountRequiresEditing(UserAccount userAccount) {
|
||||
throw new RuntimeException(
|
||||
"AuthenticatorStub.accountRequiresEditing() not implemented.");
|
||||
}
|
||||
|
||||
}
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.authenticate;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import edu.cornell.mannlib.vedit.beans.LoginStatusBean;
|
||||
import edu.cornell.mannlib.vedit.beans.LoginStatusBean.AuthenticationSource;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
|
||||
|
||||
/**
|
||||
* A simple stub for unit tests that require an Authenticator. Call setup() to
|
||||
* put it into place.
|
||||
*/
|
||||
public class AuthenticatorStub extends Authenticator {
|
||||
public static final String FACTORY_ATTRIBUTE_NAME = AuthenticatorFactory.class
|
||||
.getName();
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// factory - store this in the context.
|
||||
//
|
||||
// Creates a single instance of the stub and returns it for all requests.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
public static class Factory implements Authenticator.AuthenticatorFactory {
|
||||
private final AuthenticatorStub instance = new AuthenticatorStub();
|
||||
|
||||
@Override
|
||||
public AuthenticatorStub getInstance(HttpServletRequest request) {
|
||||
instance.setRequest(request);
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Stub infrastructure
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private final Map<String, UserAccount> usersByEmail = new HashMap<String, UserAccount>();
|
||||
private final Map<String, UserAccount> usersByExternalAuthId = new HashMap<String, UserAccount>();
|
||||
|
||||
private final Map<String, List<String>> editingPermissions = new HashMap<String, List<String>>();
|
||||
private final Map<String, String> associatedUris = new HashMap<String, String>();
|
||||
private final List<String> recordedLogins = new ArrayList<String>();
|
||||
private final Map<String, String> newPasswords = new HashMap<String, String>();
|
||||
|
||||
private HttpServletRequest request;
|
||||
|
||||
private void setRequest(HttpServletRequest request) {
|
||||
this.request = request;
|
||||
}
|
||||
|
||||
public void addUser(UserAccount user) {
|
||||
usersByEmail.put(user.getEmailAddress(), user);
|
||||
|
||||
String externalAuthId = user.getExternalAuthId();
|
||||
if (!externalAuthId.isEmpty()) {
|
||||
usersByExternalAuthId.put(user.getExternalAuthId(), user);
|
||||
}
|
||||
}
|
||||
|
||||
public void addEditingPermission(String username, String personUri) {
|
||||
if (!editingPermissions.containsKey(username)) {
|
||||
editingPermissions.put(username, new ArrayList<String>());
|
||||
}
|
||||
editingPermissions.get(username).add(personUri);
|
||||
}
|
||||
|
||||
public void setAssociatedUri(String username, String individualUri) {
|
||||
associatedUris.put(username, individualUri);
|
||||
}
|
||||
|
||||
public List<String> getRecordedLoginUsernames() {
|
||||
return recordedLogins;
|
||||
}
|
||||
|
||||
public Map<String, String> getNewPasswordMap() {
|
||||
return newPasswords;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Stub methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Override
|
||||
public UserAccount getAccountForInternalAuth(String emailAddress) {
|
||||
return usersByEmail.get(emailAddress);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserAccount getAccountForExternalAuth(String externalAuthId) {
|
||||
return usersByExternalAuthId.get(externalAuthId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUserPermittedToLogin(UserAccount userAccount) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCurrentPassword(UserAccount userAccount,
|
||||
String clearTextPassword) {
|
||||
if (userAccount == null) {
|
||||
return false;
|
||||
} else {
|
||||
return userAccount.getMd5Password().equals(
|
||||
Authenticator.applyMd5Encoding(clearTextPassword));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getAssociatedIndividualUris(UserAccount userAccount) {
|
||||
List<String> uris = new ArrayList<String>();
|
||||
|
||||
String emailAddress = userAccount.getEmailAddress();
|
||||
if (associatedUris.containsKey(emailAddress)) {
|
||||
uris.add(associatedUris.get(emailAddress));
|
||||
}
|
||||
|
||||
if (editingPermissions.containsKey(emailAddress)) {
|
||||
uris.addAll(editingPermissions.get(emailAddress));
|
||||
}
|
||||
|
||||
return uris;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void recordNewPassword(UserAccount userAccount,
|
||||
String newClearTextPassword) {
|
||||
newPasswords.put(userAccount.getEmailAddress(), newClearTextPassword);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void recordLoginAgainstUserAccount(UserAccount userAccount,
|
||||
AuthenticationSource authSource) throws LoginNotPermitted {
|
||||
if (!isUserPermittedToLogin(userAccount)) {
|
||||
throw new LoginNotPermitted();
|
||||
}
|
||||
|
||||
recordedLogins.add(userAccount.getEmailAddress());
|
||||
|
||||
LoginStatusBean lsb = new LoginStatusBean(userAccount.getUri(),
|
||||
authSource);
|
||||
LoginStatusBean.setBean(request.getSession(), lsb);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Un-implemented methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Override
|
||||
public void recordUserIsLoggedOut() {
|
||||
throw new RuntimeException(
|
||||
"AuthenticatorStub.recordUserIsLoggedOut() not implemented.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean accountRequiresEditing(UserAccount userAccount) {
|
||||
throw new RuntimeException(
|
||||
"AuthenticatorStub.accountRequiresEditing() not implemented.");
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,214 +1,214 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.authenticate;
|
||||
|
||||
import static edu.cornell.mannlib.vitro.webapp.controller.authenticate.ProgramLogin.ProgramLoginCore.PARAM_EMAIL_ADDRESS;
|
||||
import static edu.cornell.mannlib.vitro.webapp.controller.authenticate.ProgramLogin.ProgramLoginCore.PARAM_NEW_PASSWORD;
|
||||
import static edu.cornell.mannlib.vitro.webapp.controller.authenticate.ProgramLogin.ProgramLoginCore.PARAM_PASSWORD;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Collections;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import stubs.javax.servlet.ServletConfigStub;
|
||||
import stubs.javax.servlet.ServletContextStub;
|
||||
import stubs.javax.servlet.http.HttpServletRequestStub;
|
||||
import stubs.javax.servlet.http.HttpServletResponseStub;
|
||||
import stubs.javax.servlet.http.HttpSessionStub;
|
||||
import edu.cornell.mannlib.vedit.beans.LoginStatusBean;
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.permissions.PermissionSetsLoader;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
|
||||
|
||||
/**
|
||||
* Test the basic features of ProgramTest.
|
||||
*/
|
||||
public class ProgramLoginTest extends AbstractTestClass {
|
||||
private static final Log log = LogFactory.getLog(ProgramLoginTest.class);
|
||||
|
||||
private static final String NEW_USER_URI = "new_user_uri";
|
||||
private static final String NEW_USER_NAME = "new_user";
|
||||
private static final String NEW_USER_PASSWORD = "new_user_pw";
|
||||
private static final UserAccount NEW_USER = createUserAccount(NEW_USER_URI,
|
||||
NEW_USER_NAME, NEW_USER_PASSWORD, 0);
|
||||
|
||||
private static final String OLD_USER_URI = "old_user_uri";
|
||||
private static final String OLD_USER_NAME = "old_user";
|
||||
private static final String OLD_USER_PASSWORD = "old_user_pw";
|
||||
private static final UserAccount OLD_USER = createUserAccount(OLD_USER_URI,
|
||||
OLD_USER_NAME, OLD_USER_PASSWORD, 10);
|
||||
|
||||
private AuthenticatorStub.Factory authenticatorFactory;
|
||||
private AuthenticatorStub authenticator;
|
||||
private ServletContextStub servletContext;
|
||||
private ServletConfigStub servletConfig;
|
||||
private HttpSessionStub session;
|
||||
private HttpServletRequestStub request;
|
||||
private HttpServletResponseStub response;
|
||||
private ProgramLogin servlet;
|
||||
|
||||
@Before
|
||||
public void setLogging() {
|
||||
// setLoggerLevel(this.getClass(), Level.DEBUG);
|
||||
// setLoggerLevel(ProgramLogin.class, Level.DEBUG);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setup() throws Exception {
|
||||
authenticatorFactory = new AuthenticatorStub.Factory();
|
||||
authenticator = authenticatorFactory.getInstance(request);
|
||||
authenticator.addUser(NEW_USER);
|
||||
authenticator.addUser(OLD_USER);
|
||||
|
||||
servletContext = new ServletContextStub();
|
||||
servletContext.setAttribute(AuthenticatorStub.FACTORY_ATTRIBUTE_NAME,
|
||||
authenticatorFactory);
|
||||
|
||||
servletConfig = new ServletConfigStub();
|
||||
servletConfig.setServletContext(servletContext);
|
||||
|
||||
servlet = new ProgramLogin();
|
||||
servlet.init(servletConfig);
|
||||
|
||||
session = new HttpSessionStub();
|
||||
session.setServletContext(servletContext);
|
||||
|
||||
request = new HttpServletRequestStub();
|
||||
request.setSession(session);
|
||||
request.setRequestUrl(new URL("http://this.that/vivo/programLogin"));
|
||||
request.setMethod("GET");
|
||||
|
||||
response = new HttpServletResponseStub();
|
||||
}
|
||||
|
||||
private static UserAccount createUserAccount(String uri, String name,
|
||||
String password, int loginCount) {
|
||||
UserAccount user = new UserAccount();
|
||||
user.setEmailAddress(name);
|
||||
user.setUri(uri);
|
||||
user.setPermissionSetUris(Collections
|
||||
.singleton(PermissionSetsLoader.URI_DBA));
|
||||
user.setMd5Password(Authenticator.applyMd5Encoding(password));
|
||||
user.setLoginCount(loginCount);
|
||||
user.setPasswordChangeRequired(loginCount == 0);
|
||||
return user;
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() {
|
||||
if (servlet != null) {
|
||||
servlet.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noUsername() {
|
||||
executeRequest(null, null, null);
|
||||
assert403();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noPassword() {
|
||||
executeRequest(OLD_USER_NAME, null, null);
|
||||
assert403();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unrecognizedUser() {
|
||||
executeRequest("bogusUsername", "bogusPassword", null);
|
||||
assert403();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void wrongPassword() {
|
||||
executeRequest(OLD_USER_NAME, "bogusPassword", null);
|
||||
assert403();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void success() {
|
||||
executeRequest(OLD_USER_NAME, OLD_USER_PASSWORD, null);
|
||||
assertSuccess();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void newPasswordNotNeeded() {
|
||||
executeRequest(OLD_USER_NAME, OLD_USER_PASSWORD, "unneededPW");
|
||||
assert403();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void newPasswordMissing() {
|
||||
executeRequest(NEW_USER_NAME, NEW_USER_PASSWORD, null);
|
||||
assert403();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void newPasswordTooLong() {
|
||||
executeRequest(NEW_USER_NAME, NEW_USER_PASSWORD, "reallyLongPassword");
|
||||
assert403();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void newPasswordEqualsOldPassword() {
|
||||
executeRequest(NEW_USER_NAME, NEW_USER_PASSWORD, NEW_USER_PASSWORD);
|
||||
assert403();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void successWithNewPassword() {
|
||||
executeRequest(NEW_USER_NAME, NEW_USER_PASSWORD, "newerBetter");
|
||||
assertSuccess();
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private void executeRequest(String email, String password,
|
||||
String newPassword) {
|
||||
if (email != null) {
|
||||
request.addParameter(PARAM_EMAIL_ADDRESS, email);
|
||||
}
|
||||
if (password != null) {
|
||||
request.addParameter(PARAM_PASSWORD, password);
|
||||
}
|
||||
if (newPassword != null) {
|
||||
request.addParameter(PARAM_NEW_PASSWORD, newPassword);
|
||||
}
|
||||
|
||||
try {
|
||||
servlet.doGet(request, response);
|
||||
} catch (ServletException e) {
|
||||
log.error(e, e);
|
||||
fail(e.toString());
|
||||
} catch (IOException e) {
|
||||
log.error(e, e);
|
||||
fail(e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
private void assert403() {
|
||||
assertEquals("status", 403, response.getStatus());
|
||||
log.debug("Message was '" + response.getErrorMessage() + "'");
|
||||
assertEquals("logged in", false, LoginStatusBean.getBean(session)
|
||||
.isLoggedIn());
|
||||
}
|
||||
|
||||
private void assertSuccess() {
|
||||
assertEquals("status", 200, response.getStatus());
|
||||
assertEquals("logged in", true, LoginStatusBean.getBean(session)
|
||||
.isLoggedIn());
|
||||
}
|
||||
|
||||
}
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.authenticate;
|
||||
|
||||
import static edu.cornell.mannlib.vitro.webapp.controller.authenticate.ProgramLogin.ProgramLoginCore.PARAM_EMAIL_ADDRESS;
|
||||
import static edu.cornell.mannlib.vitro.webapp.controller.authenticate.ProgramLogin.ProgramLoginCore.PARAM_NEW_PASSWORD;
|
||||
import static edu.cornell.mannlib.vitro.webapp.controller.authenticate.ProgramLogin.ProgramLoginCore.PARAM_PASSWORD;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Collections;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import stubs.javax.servlet.ServletConfigStub;
|
||||
import stubs.javax.servlet.ServletContextStub;
|
||||
import stubs.javax.servlet.http.HttpServletRequestStub;
|
||||
import stubs.javax.servlet.http.HttpServletResponseStub;
|
||||
import stubs.javax.servlet.http.HttpSessionStub;
|
||||
import edu.cornell.mannlib.vedit.beans.LoginStatusBean;
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.auth.permissions.PermissionSetsLoader;
|
||||
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
|
||||
|
||||
/**
|
||||
* Test the basic features of ProgramTest.
|
||||
*/
|
||||
public class ProgramLoginTest extends AbstractTestClass {
|
||||
private static final Log log = LogFactory.getLog(ProgramLoginTest.class);
|
||||
|
||||
private static final String NEW_USER_URI = "new_user_uri";
|
||||
private static final String NEW_USER_NAME = "new_user";
|
||||
private static final String NEW_USER_PASSWORD = "new_user_pw";
|
||||
private static final UserAccount NEW_USER = createUserAccount(NEW_USER_URI,
|
||||
NEW_USER_NAME, NEW_USER_PASSWORD, 0);
|
||||
|
||||
private static final String OLD_USER_URI = "old_user_uri";
|
||||
private static final String OLD_USER_NAME = "old_user";
|
||||
private static final String OLD_USER_PASSWORD = "old_user_pw";
|
||||
private static final UserAccount OLD_USER = createUserAccount(OLD_USER_URI,
|
||||
OLD_USER_NAME, OLD_USER_PASSWORD, 10);
|
||||
|
||||
private AuthenticatorStub.Factory authenticatorFactory;
|
||||
private AuthenticatorStub authenticator;
|
||||
private ServletContextStub servletContext;
|
||||
private ServletConfigStub servletConfig;
|
||||
private HttpSessionStub session;
|
||||
private HttpServletRequestStub request;
|
||||
private HttpServletResponseStub response;
|
||||
private ProgramLogin servlet;
|
||||
|
||||
@Before
|
||||
public void setLogging() {
|
||||
// setLoggerLevel(this.getClass(), Level.DEBUG);
|
||||
// setLoggerLevel(ProgramLogin.class, Level.DEBUG);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setup() throws Exception {
|
||||
authenticatorFactory = new AuthenticatorStub.Factory();
|
||||
authenticator = authenticatorFactory.getInstance(request);
|
||||
authenticator.addUser(NEW_USER);
|
||||
authenticator.addUser(OLD_USER);
|
||||
|
||||
servletContext = new ServletContextStub();
|
||||
servletContext.setAttribute(AuthenticatorStub.FACTORY_ATTRIBUTE_NAME,
|
||||
authenticatorFactory);
|
||||
|
||||
servletConfig = new ServletConfigStub();
|
||||
servletConfig.setServletContext(servletContext);
|
||||
|
||||
servlet = new ProgramLogin();
|
||||
servlet.init(servletConfig);
|
||||
|
||||
session = new HttpSessionStub();
|
||||
session.setServletContext(servletContext);
|
||||
|
||||
request = new HttpServletRequestStub();
|
||||
request.setSession(session);
|
||||
request.setRequestUrl(new URL("http://this.that/vivo/programLogin"));
|
||||
request.setMethod("GET");
|
||||
|
||||
response = new HttpServletResponseStub();
|
||||
}
|
||||
|
||||
private static UserAccount createUserAccount(String uri, String name,
|
||||
String password, int loginCount) {
|
||||
UserAccount user = new UserAccount();
|
||||
user.setEmailAddress(name);
|
||||
user.setUri(uri);
|
||||
user.setPermissionSetUris(Collections
|
||||
.singleton(PermissionSetsLoader.URI_DBA));
|
||||
user.setMd5Password(Authenticator.applyMd5Encoding(password));
|
||||
user.setLoginCount(loginCount);
|
||||
user.setPasswordChangeRequired(loginCount == 0);
|
||||
return user;
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() {
|
||||
if (servlet != null) {
|
||||
servlet.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noUsername() {
|
||||
executeRequest(null, null, null);
|
||||
assert403();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noPassword() {
|
||||
executeRequest(OLD_USER_NAME, null, null);
|
||||
assert403();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unrecognizedUser() {
|
||||
executeRequest("bogusUsername", "bogusPassword", null);
|
||||
assert403();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void wrongPassword() {
|
||||
executeRequest(OLD_USER_NAME, "bogusPassword", null);
|
||||
assert403();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void success() {
|
||||
executeRequest(OLD_USER_NAME, OLD_USER_PASSWORD, null);
|
||||
assertSuccess();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void newPasswordNotNeeded() {
|
||||
executeRequest(OLD_USER_NAME, OLD_USER_PASSWORD, "unneededPW");
|
||||
assert403();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void newPasswordMissing() {
|
||||
executeRequest(NEW_USER_NAME, NEW_USER_PASSWORD, null);
|
||||
assert403();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void newPasswordTooLong() {
|
||||
executeRequest(NEW_USER_NAME, NEW_USER_PASSWORD, "reallyLongPassword");
|
||||
assert403();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void newPasswordEqualsOldPassword() {
|
||||
executeRequest(NEW_USER_NAME, NEW_USER_PASSWORD, NEW_USER_PASSWORD);
|
||||
assert403();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void successWithNewPassword() {
|
||||
executeRequest(NEW_USER_NAME, NEW_USER_PASSWORD, "newerBetter");
|
||||
assertSuccess();
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private void executeRequest(String email, String password,
|
||||
String newPassword) {
|
||||
if (email != null) {
|
||||
request.addParameter(PARAM_EMAIL_ADDRESS, email);
|
||||
}
|
||||
if (password != null) {
|
||||
request.addParameter(PARAM_PASSWORD, password);
|
||||
}
|
||||
if (newPassword != null) {
|
||||
request.addParameter(PARAM_NEW_PASSWORD, newPassword);
|
||||
}
|
||||
|
||||
try {
|
||||
servlet.doGet(request, response);
|
||||
} catch (ServletException e) {
|
||||
log.error(e, e);
|
||||
fail(e.toString());
|
||||
} catch (IOException e) {
|
||||
log.error(e, e);
|
||||
fail(e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
private void assert403() {
|
||||
assertEquals("status", 403, response.getStatus());
|
||||
log.debug("Message was '" + response.getErrorMessage() + "'");
|
||||
assertEquals("logged in", false, LoginStatusBean.getBean(session)
|
||||
.isLoggedIn());
|
||||
}
|
||||
|
||||
private void assertSuccess() {
|
||||
assertEquals("status", 200, response.getStatus());
|
||||
assertEquals("logged in", true, LoginStatusBean.getBean(session)
|
||||
.isLoggedIn());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -1,183 +1,183 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.text.SimpleDateFormat;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
|
||||
/**
|
||||
* Test the methods of {@link FlatteningTemplateLoader}.
|
||||
*/
|
||||
public class FlatteningTemplateLoaderTest extends AbstractTestClass {
|
||||
/**
|
||||
* TODO test plan
|
||||
*
|
||||
* <pre>
|
||||
* findTemplateSource
|
||||
* null arg
|
||||
* not found
|
||||
* found in top level
|
||||
* found in lower level
|
||||
* with path
|
||||
*
|
||||
* getReader
|
||||
* get it, read it, check it, close it.
|
||||
*
|
||||
* getLastModified
|
||||
* check the create date within a range
|
||||
* modify it and check again.
|
||||
*
|
||||
* </pre>
|
||||
*/
|
||||
// ----------------------------------------------------------------------
|
||||
// setup and teardown
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private static final String SUBDIRECTORY_NAME = "sub";
|
||||
|
||||
private static final String TEMPLATE_NAME_UPPER = "template.ftl";
|
||||
private static final String TEMPLATE_NAME_UPPER_WITH_PATH = "path/template.ftl";
|
||||
private static final String TEMPLATE_UPPER_CONTENTS = "The contents of the file.";
|
||||
|
||||
private static final String TEMPLATE_NAME_LOWER = "another.ftl";
|
||||
private static final String TEMPLATE_LOWER_CONTENTS = "Another template file.";
|
||||
|
||||
private static File tempDir;
|
||||
private static File notADirectory;
|
||||
private static File upperTemplate;
|
||||
private static File lowerTemplate;
|
||||
|
||||
private FlatteningTemplateLoader loader;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpFiles() throws IOException {
|
||||
notADirectory = File.createTempFile(
|
||||
FlatteningTemplateLoader.class.getSimpleName(), "");
|
||||
|
||||
tempDir = createTempDirectory(FlatteningTemplateLoader.class
|
||||
.getSimpleName());
|
||||
upperTemplate = createFile(tempDir, TEMPLATE_NAME_UPPER,
|
||||
TEMPLATE_UPPER_CONTENTS);
|
||||
|
||||
File subdirectory = new File(tempDir, SUBDIRECTORY_NAME);
|
||||
subdirectory.mkdir();
|
||||
lowerTemplate = createFile(subdirectory, TEMPLATE_NAME_LOWER,
|
||||
TEMPLATE_LOWER_CONTENTS);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void initializeLoader() {
|
||||
loader = new FlatteningTemplateLoader(tempDir);
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void cleanUpFiles() throws IOException {
|
||||
purgeDirectoryRecursively(tempDir);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void constructorNull() {
|
||||
new FlatteningTemplateLoader(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNonExistent() {
|
||||
new FlatteningTemplateLoader(new File("bogusDirName"));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNotADirectory() {
|
||||
new FlatteningTemplateLoader(notADirectory);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findNull() throws IOException {
|
||||
Object source = loader.findTemplateSource(null);
|
||||
assertNull("find null", source);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findNotFound() throws IOException {
|
||||
Object source = loader.findTemplateSource("bogus");
|
||||
assertNull("not found", source);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findInTopLevel() throws IOException {
|
||||
Object source = loader.findTemplateSource(TEMPLATE_NAME_UPPER);
|
||||
assertEquals("top level", upperTemplate, source);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findInLowerLevel() throws IOException {
|
||||
Object source = loader.findTemplateSource(TEMPLATE_NAME_LOWER);
|
||||
assertEquals("lower level", lowerTemplate, source);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findIgnoringPath() throws IOException {
|
||||
Object source = loader
|
||||
.findTemplateSource(TEMPLATE_NAME_UPPER_WITH_PATH);
|
||||
assertEquals("top level", upperTemplate, source);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkTheReader() throws IOException {
|
||||
Object source = loader.findTemplateSource(TEMPLATE_NAME_UPPER);
|
||||
Reader reader = loader.getReader(source, "UTF-8");
|
||||
String contents = readAll(reader);
|
||||
assertEquals("read the contents", contents, TEMPLATE_UPPER_CONTENTS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Some systems only record last-modified times to the nearest second, so we
|
||||
* can't rely on them changing during the course of the test. Force the
|
||||
* change, and test for it.
|
||||
*/
|
||||
@Test
|
||||
public void teplateLastModified() throws IOException {
|
||||
Object source = loader.findTemplateSource(TEMPLATE_NAME_UPPER);
|
||||
long modified = loader.getLastModified(source);
|
||||
long now = System.currentTimeMillis();
|
||||
assertTrue("near to now: modified=" + formatTimeStamp(modified)
|
||||
+ ", now=" + formatTimeStamp(now),
|
||||
2000 > Math.abs(modified - now));
|
||||
|
||||
upperTemplate.setLastModified(5000);
|
||||
assertEquals("modified modified", 5000, loader.getLastModified(source));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void closeDoesntCrash() throws IOException {
|
||||
Object source = loader.findTemplateSource(TEMPLATE_NAME_UPPER);
|
||||
loader.closeTemplateSource(source);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private String formatTimeStamp(long time) {
|
||||
SimpleDateFormat formatter = new SimpleDateFormat(
|
||||
"yyyy-MM-dd HH:mm:ss.SSS");
|
||||
return formatter.format(time);
|
||||
}
|
||||
|
||||
}
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.text.SimpleDateFormat;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
|
||||
/**
|
||||
* Test the methods of {@link FlatteningTemplateLoader}.
|
||||
*/
|
||||
public class FlatteningTemplateLoaderTest extends AbstractTestClass {
|
||||
/**
|
||||
* TODO test plan
|
||||
*
|
||||
* <pre>
|
||||
* findTemplateSource
|
||||
* null arg
|
||||
* not found
|
||||
* found in top level
|
||||
* found in lower level
|
||||
* with path
|
||||
*
|
||||
* getReader
|
||||
* get it, read it, check it, close it.
|
||||
*
|
||||
* getLastModified
|
||||
* check the create date within a range
|
||||
* modify it and check again.
|
||||
*
|
||||
* </pre>
|
||||
*/
|
||||
// ----------------------------------------------------------------------
|
||||
// setup and teardown
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private static final String SUBDIRECTORY_NAME = "sub";
|
||||
|
||||
private static final String TEMPLATE_NAME_UPPER = "template.ftl";
|
||||
private static final String TEMPLATE_NAME_UPPER_WITH_PATH = "path/template.ftl";
|
||||
private static final String TEMPLATE_UPPER_CONTENTS = "The contents of the file.";
|
||||
|
||||
private static final String TEMPLATE_NAME_LOWER = "another.ftl";
|
||||
private static final String TEMPLATE_LOWER_CONTENTS = "Another template file.";
|
||||
|
||||
private static File tempDir;
|
||||
private static File notADirectory;
|
||||
private static File upperTemplate;
|
||||
private static File lowerTemplate;
|
||||
|
||||
private FlatteningTemplateLoader loader;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpFiles() throws IOException {
|
||||
notADirectory = File.createTempFile(
|
||||
FlatteningTemplateLoader.class.getSimpleName(), "");
|
||||
|
||||
tempDir = createTempDirectory(FlatteningTemplateLoader.class
|
||||
.getSimpleName());
|
||||
upperTemplate = createFile(tempDir, TEMPLATE_NAME_UPPER,
|
||||
TEMPLATE_UPPER_CONTENTS);
|
||||
|
||||
File subdirectory = new File(tempDir, SUBDIRECTORY_NAME);
|
||||
subdirectory.mkdir();
|
||||
lowerTemplate = createFile(subdirectory, TEMPLATE_NAME_LOWER,
|
||||
TEMPLATE_LOWER_CONTENTS);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void initializeLoader() {
|
||||
loader = new FlatteningTemplateLoader(tempDir);
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void cleanUpFiles() throws IOException {
|
||||
purgeDirectoryRecursively(tempDir);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void constructorNull() {
|
||||
new FlatteningTemplateLoader(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNonExistent() {
|
||||
new FlatteningTemplateLoader(new File("bogusDirName"));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNotADirectory() {
|
||||
new FlatteningTemplateLoader(notADirectory);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findNull() throws IOException {
|
||||
Object source = loader.findTemplateSource(null);
|
||||
assertNull("find null", source);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findNotFound() throws IOException {
|
||||
Object source = loader.findTemplateSource("bogus");
|
||||
assertNull("not found", source);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findInTopLevel() throws IOException {
|
||||
Object source = loader.findTemplateSource(TEMPLATE_NAME_UPPER);
|
||||
assertEquals("top level", upperTemplate, source);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findInLowerLevel() throws IOException {
|
||||
Object source = loader.findTemplateSource(TEMPLATE_NAME_LOWER);
|
||||
assertEquals("lower level", lowerTemplate, source);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findIgnoringPath() throws IOException {
|
||||
Object source = loader
|
||||
.findTemplateSource(TEMPLATE_NAME_UPPER_WITH_PATH);
|
||||
assertEquals("top level", upperTemplate, source);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkTheReader() throws IOException {
|
||||
Object source = loader.findTemplateSource(TEMPLATE_NAME_UPPER);
|
||||
Reader reader = loader.getReader(source, "UTF-8");
|
||||
String contents = readAll(reader);
|
||||
assertEquals("read the contents", contents, TEMPLATE_UPPER_CONTENTS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Some systems only record last-modified times to the nearest second, so we
|
||||
* can't rely on them changing during the course of the test. Force the
|
||||
* change, and test for it.
|
||||
*/
|
||||
@Test
|
||||
public void teplateLastModified() throws IOException {
|
||||
Object source = loader.findTemplateSource(TEMPLATE_NAME_UPPER);
|
||||
long modified = loader.getLastModified(source);
|
||||
long now = System.currentTimeMillis();
|
||||
assertTrue("near to now: modified=" + formatTimeStamp(modified)
|
||||
+ ", now=" + formatTimeStamp(now),
|
||||
2000 > Math.abs(modified - now));
|
||||
|
||||
upperTemplate.setLastModified(5000);
|
||||
assertEquals("modified modified", 5000, loader.getLastModified(source));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void closeDoesntCrash() throws IOException {
|
||||
Object source = loader.findTemplateSource(TEMPLATE_NAME_UPPER);
|
||||
loader.closeTemplateSource(source);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private String formatTimeStamp(long time) {
|
||||
SimpleDateFormat formatter = new SimpleDateFormat(
|
||||
"yyyy-MM-dd HH:mm:ss.SSS");
|
||||
return formatter.format(time);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,135 +1,135 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
|
||||
|
||||
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 java.awt.Frame;
|
||||
import java.awt.GridLayout;
|
||||
import java.awt.event.WindowAdapter;
|
||||
import java.awt.event.WindowEvent;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
|
||||
import javax.media.jai.JAI;
|
||||
import javax.media.jai.RenderedOp;
|
||||
import javax.media.jai.operator.StreamDescriptor;
|
||||
|
||||
import org.apache.log4j.Level;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.sun.media.jai.codec.MemoryCacheSeekableStream;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.ImageUploadHelper.NonNoisyImagingListener;
|
||||
|
||||
/**
|
||||
* This is not a unit test, so it is not named BlahBlahTest.
|
||||
*
|
||||
* Instead, it's a test harness that creates thumbnails and writes them to
|
||||
* files, while also displaying them in a window on the screen. It takes human
|
||||
* intervention to evaluate.
|
||||
*
|
||||
* This is especially true because the images on the screen look color-correct,
|
||||
* but when viewed in the browser, they might not be.
|
||||
*/
|
||||
public class ImageUploaderThumbnailerTester extends Frame {
|
||||
static {
|
||||
JAI.getDefaultInstance().setImagingListener(
|
||||
new NonNoisyImagingListener());
|
||||
}
|
||||
|
||||
/** Big enough to hold the JPEG file, certainly. */
|
||||
private final static int BUFFER_SIZE = 200 * 200 * 4;
|
||||
|
||||
private final static ImageCropData[] THUMBNAIL_DATA = new ImageCropData[] {
|
||||
new ImageCropData("/Users/jeb228/Pictures/JimBlake_20010915.jpg",
|
||||
50, 50, 115),
|
||||
new ImageCropData("/Users/jeb228/Pictures/brazil_collab.png", 600,
|
||||
250, 400),
|
||||
new ImageCropData("/Users/jeb228/Pictures/wheel.png", 0, 0, 195),
|
||||
new ImageCropData("/Users/jeb228/Pictures/DSC04203w-trans.gif",
|
||||
400, 1200, 800) };
|
||||
|
||||
private final ImageUploadThumbnailer thumbnailer = new ImageUploadThumbnailer(
|
||||
THUMBNAIL_HEIGHT, THUMBNAIL_WIDTH);
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private ImageUploaderThumbnailerTester() {
|
||||
setTitle("Alpha Killer Test");
|
||||
addWindowListener(new CloseWindowListener());
|
||||
setLayout(createLayout());
|
||||
for (ImageCropData icd : THUMBNAIL_DATA) {
|
||||
try {
|
||||
InputStream mainStream = new FileInputStream(icd.filename);
|
||||
File thumbFile = writeToTempFile(thumbnailer.cropAndScale(
|
||||
mainStream, icd.crop));
|
||||
System.out.println(thumbFile.getAbsolutePath());
|
||||
|
||||
MemoryCacheSeekableStream thumbFileStream = new MemoryCacheSeekableStream(
|
||||
new FileInputStream(thumbFile));
|
||||
RenderedOp thumbImage = StreamDescriptor.create(
|
||||
thumbFileStream, null, null);
|
||||
add(new javax.media.jai.widget.ImageCanvas(thumbImage));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
pack();
|
||||
setVisible(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param thumbStream
|
||||
* @return
|
||||
* @throws IOException
|
||||
* @throws FileNotFoundException
|
||||
*/
|
||||
private File writeToTempFile(InputStream thumbStream) throws IOException,
|
||||
FileNotFoundException {
|
||||
File thumbFile = File.createTempFile("ImageUploaderThumbnailerTester",
|
||||
"");
|
||||
OutputStream imageOutputStream = new FileOutputStream(thumbFile);
|
||||
byte[] buffer = new byte[BUFFER_SIZE];
|
||||
int howMany = thumbStream.read(buffer);
|
||||
imageOutputStream.write(buffer, 0, howMany);
|
||||
imageOutputStream.close();
|
||||
return thumbFile;
|
||||
}
|
||||
|
||||
private GridLayout createLayout() {
|
||||
GridLayout layout = new GridLayout(1, THUMBNAIL_DATA.length);
|
||||
layout.setHgap(10);
|
||||
return layout;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Logger.getLogger(ImageUploadThumbnailer.class).setLevel(Level.DEBUG);
|
||||
new ImageUploaderThumbnailerTester();
|
||||
}
|
||||
|
||||
private static class ImageCropData {
|
||||
final String filename;
|
||||
final ImageUploadController.CropRectangle crop;
|
||||
|
||||
ImageCropData(String filename, int x, int y, int size) {
|
||||
this.filename = filename;
|
||||
this.crop = new ImageUploadController.CropRectangle(x, y, size,
|
||||
size);
|
||||
}
|
||||
}
|
||||
|
||||
private class CloseWindowListener extends WindowAdapter {
|
||||
@Override
|
||||
public void windowClosing(WindowEvent e) {
|
||||
setVisible(false);
|
||||
dispose();
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
|
||||
|
||||
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 java.awt.Frame;
|
||||
import java.awt.GridLayout;
|
||||
import java.awt.event.WindowAdapter;
|
||||
import java.awt.event.WindowEvent;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
|
||||
import javax.media.jai.JAI;
|
||||
import javax.media.jai.RenderedOp;
|
||||
import javax.media.jai.operator.StreamDescriptor;
|
||||
|
||||
import org.apache.log4j.Level;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.sun.media.jai.codec.MemoryCacheSeekableStream;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.ImageUploadHelper.NonNoisyImagingListener;
|
||||
|
||||
/**
|
||||
* This is not a unit test, so it is not named BlahBlahTest.
|
||||
*
|
||||
* Instead, it's a test harness that creates thumbnails and writes them to
|
||||
* files, while also displaying them in a window on the screen. It takes human
|
||||
* intervention to evaluate.
|
||||
*
|
||||
* This is especially true because the images on the screen look color-correct,
|
||||
* but when viewed in the browser, they might not be.
|
||||
*/
|
||||
public class ImageUploaderThumbnailerTester extends Frame {
|
||||
static {
|
||||
JAI.getDefaultInstance().setImagingListener(
|
||||
new NonNoisyImagingListener());
|
||||
}
|
||||
|
||||
/** Big enough to hold the JPEG file, certainly. */
|
||||
private final static int BUFFER_SIZE = 200 * 200 * 4;
|
||||
|
||||
private final static ImageCropData[] THUMBNAIL_DATA = new ImageCropData[] {
|
||||
new ImageCropData("/Users/jeb228/Pictures/JimBlake_20010915.jpg",
|
||||
50, 50, 115),
|
||||
new ImageCropData("/Users/jeb228/Pictures/brazil_collab.png", 600,
|
||||
250, 400),
|
||||
new ImageCropData("/Users/jeb228/Pictures/wheel.png", 0, 0, 195),
|
||||
new ImageCropData("/Users/jeb228/Pictures/DSC04203w-trans.gif",
|
||||
400, 1200, 800) };
|
||||
|
||||
private final ImageUploadThumbnailer thumbnailer = new ImageUploadThumbnailer(
|
||||
THUMBNAIL_HEIGHT, THUMBNAIL_WIDTH);
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private ImageUploaderThumbnailerTester() {
|
||||
setTitle("Alpha Killer Test");
|
||||
addWindowListener(new CloseWindowListener());
|
||||
setLayout(createLayout());
|
||||
for (ImageCropData icd : THUMBNAIL_DATA) {
|
||||
try {
|
||||
InputStream mainStream = new FileInputStream(icd.filename);
|
||||
File thumbFile = writeToTempFile(thumbnailer.cropAndScale(
|
||||
mainStream, icd.crop));
|
||||
System.out.println(thumbFile.getAbsolutePath());
|
||||
|
||||
MemoryCacheSeekableStream thumbFileStream = new MemoryCacheSeekableStream(
|
||||
new FileInputStream(thumbFile));
|
||||
RenderedOp thumbImage = StreamDescriptor.create(
|
||||
thumbFileStream, null, null);
|
||||
add(new javax.media.jai.widget.ImageCanvas(thumbImage));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
pack();
|
||||
setVisible(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param thumbStream
|
||||
* @return
|
||||
* @throws IOException
|
||||
* @throws FileNotFoundException
|
||||
*/
|
||||
private File writeToTempFile(InputStream thumbStream) throws IOException,
|
||||
FileNotFoundException {
|
||||
File thumbFile = File.createTempFile("ImageUploaderThumbnailerTester",
|
||||
"");
|
||||
OutputStream imageOutputStream = new FileOutputStream(thumbFile);
|
||||
byte[] buffer = new byte[BUFFER_SIZE];
|
||||
int howMany = thumbStream.read(buffer);
|
||||
imageOutputStream.write(buffer, 0, howMany);
|
||||
imageOutputStream.close();
|
||||
return thumbFile;
|
||||
}
|
||||
|
||||
private GridLayout createLayout() {
|
||||
GridLayout layout = new GridLayout(1, THUMBNAIL_DATA.length);
|
||||
layout.setHgap(10);
|
||||
return layout;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Logger.getLogger(ImageUploadThumbnailer.class).setLevel(Level.DEBUG);
|
||||
new ImageUploaderThumbnailerTester();
|
||||
}
|
||||
|
||||
private static class ImageCropData {
|
||||
final String filename;
|
||||
final ImageUploadController.CropRectangle crop;
|
||||
|
||||
ImageCropData(String filename, int x, int y, int size) {
|
||||
this.filename = filename;
|
||||
this.crop = new ImageUploadController.CropRectangle(x, y, size,
|
||||
size);
|
||||
}
|
||||
}
|
||||
|
||||
private class CloseWindowListener extends WindowAdapter {
|
||||
@Override
|
||||
public void windowClosing(WindowEvent e) {
|
||||
setVisible(false);
|
||||
dispose();
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,269 +1,269 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
|
||||
|
||||
import java.awt.BorderLayout;
|
||||
import java.awt.Color;
|
||||
import java.awt.Component;
|
||||
import java.awt.Frame;
|
||||
import java.awt.GridLayout;
|
||||
import java.awt.Label;
|
||||
import java.awt.event.WindowAdapter;
|
||||
import java.awt.event.WindowEvent;
|
||||
import java.awt.image.Raster;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.media.jai.JAI;
|
||||
import javax.media.jai.RenderedOp;
|
||||
import javax.media.jai.operator.StreamDescriptor;
|
||||
import javax.media.jai.widget.ImageCanvas;
|
||||
import javax.swing.BorderFactory;
|
||||
import javax.swing.JPanel;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.log4j.Appender;
|
||||
import org.apache.log4j.Level;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.apache.log4j.PatternLayout;
|
||||
|
||||
import com.sun.media.jai.codec.MemoryCacheSeekableStream;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.ImageUploadController.CropRectangle;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.ImageUploadHelper.NonNoisyImagingListener;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.ImageUploaderThumbnailerTester_2.CropDataSet.CropData;
|
||||
|
||||
/**
|
||||
* This is not a unit test, so it is not named BlahBlahTest.
|
||||
*
|
||||
* Instead, it's a test harness that creates thumbnails and displays them in a
|
||||
* window on the screen. It takes human intervention to evaluate.
|
||||
*
|
||||
* The goal here is to see whether differences in crop dimensions might cause
|
||||
* one or more black edges on the thumbnails.
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
public class ImageUploaderThumbnailerTester_2 extends Frame {
|
||||
private static final Log log = LogFactory
|
||||
.getLog(ImageUploaderThumbnailerTester_2.class);
|
||||
|
||||
private static final int ROWS = 6;
|
||||
private static final int COLUMNS = 9;
|
||||
|
||||
private static final int EDGE_THRESHOLD = 6000;
|
||||
|
||||
/** Keep things quiet. */
|
||||
static {
|
||||
JAI.getDefaultInstance().setImagingListener(
|
||||
new NonNoisyImagingListener());
|
||||
}
|
||||
|
||||
private final String imagePath;
|
||||
private final ImageUploadThumbnailer thumbnailer;
|
||||
|
||||
public ImageUploaderThumbnailerTester_2(String imagePath,
|
||||
CropDataSet cropDataSet) {
|
||||
this.imagePath = imagePath;
|
||||
this.thumbnailer = new ImageUploadThumbnailer(200, 200);
|
||||
|
||||
setTitle("Cropping edging test");
|
||||
addWindowListener(new CloseWindowListener());
|
||||
setLayout(new GridLayout(ROWS, COLUMNS));
|
||||
|
||||
for (CropData cropData : cropDataSet.crops()) {
|
||||
add(createImagePanel(cropData));
|
||||
}
|
||||
|
||||
pack();
|
||||
setVisible(true);
|
||||
}
|
||||
|
||||
private Component createImagePanel(CropData cropData) {
|
||||
RenderedOp image = createCroppedImage(cropData);
|
||||
|
||||
|
||||
Set<String> blackSides = checkBlackEdges(image);
|
||||
if (!blackSides.isEmpty()) {
|
||||
log.warn("edges at " + cropData + ", " + blackSides);
|
||||
}
|
||||
|
||||
String legend = "left=" + cropData.left + ", top=" + cropData.top
|
||||
+ ", size=" + cropData.size;
|
||||
Label l = new Label();
|
||||
l.setAlignment(Label.CENTER);
|
||||
if (!blackSides.isEmpty()) {
|
||||
l.setBackground(new Color(0xFFDDDD));
|
||||
legend += " " + blackSides;
|
||||
}
|
||||
l.setText(legend);
|
||||
|
||||
JPanel p = new JPanel();
|
||||
p.setLayout(new BorderLayout());
|
||||
p.add("South", l);
|
||||
p.add("Center", new ImageCanvas(image));
|
||||
p.setBackground(new Color(0xFFFFFF));
|
||||
p.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
|
||||
|
||||
return p;
|
||||
}
|
||||
|
||||
private RenderedOp createCroppedImage(CropData cropData) {
|
||||
try {
|
||||
InputStream mainStream = new FileInputStream(imagePath);
|
||||
CropRectangle rectangle = new CropRectangle(cropData.left,
|
||||
cropData.top, cropData.size, cropData.size);
|
||||
InputStream thumbnailStream = thumbnailer.cropAndScale(mainStream,
|
||||
rectangle);
|
||||
|
||||
return StreamDescriptor.create(new MemoryCacheSeekableStream(
|
||||
thumbnailStream), null, null);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private Set<String> checkBlackEdges(RenderedOp image) {
|
||||
Raster imageData = image.getData();
|
||||
|
||||
int minX = imageData.getMinX();
|
||||
int minY = imageData.getMinY();
|
||||
int maxX = minX + imageData.getWidth() - 1;
|
||||
int maxY = minY + imageData.getHeight() - 1;
|
||||
|
||||
Set<String> blackSides = new HashSet<String>();
|
||||
if (isBlackEdge(minX, minX, minY, maxY, imageData)) {
|
||||
blackSides.add("left");
|
||||
}
|
||||
if (isBlackEdge(minX, maxX, minY, minY, imageData)) {
|
||||
blackSides.add("top");
|
||||
}
|
||||
if (isBlackEdge(maxX, maxX, minY, maxY, imageData)) {
|
||||
blackSides.add("right");
|
||||
}
|
||||
if (isBlackEdge(minX, maxX, maxY, maxY, imageData)) {
|
||||
blackSides.add("bottom");
|
||||
}
|
||||
return blackSides;
|
||||
}
|
||||
|
||||
private boolean isBlackEdge(int fromX, int toX, int fromY, int toY,
|
||||
Raster imageData) {
|
||||
int edgeTotal = 0;
|
||||
try {
|
||||
for (int col = fromX; col <= toX; col++) {
|
||||
for (int row = fromY; row <= toY; row++) {
|
||||
edgeTotal += sumPixel(imageData, col, row);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("can't sum edge: fromX=" + fromX + ", toX=" + toX
|
||||
+ ", fromY=" + fromY + ", toY=" + toY + ", imageWidth="
|
||||
+ imageData.getWidth() + ", imageHeight="
|
||||
+ imageData.getHeight() + ": " + e);
|
||||
}
|
||||
|
||||
log.debug("edge total = " + edgeTotal);
|
||||
return edgeTotal < EDGE_THRESHOLD;
|
||||
}
|
||||
|
||||
private int sumPixel(Raster imageData, int col, int row) {
|
||||
int pixelSum = 0;
|
||||
int[] pixel = imageData.getPixel(col, row, new int[0]);
|
||||
for (int value : pixel) {
|
||||
pixelSum += value;
|
||||
}
|
||||
return pixelSum;
|
||||
}
|
||||
|
||||
/**
|
||||
* <pre>
|
||||
* The plan:
|
||||
*
|
||||
* Provide the path to an image file.
|
||||
* Figure how many images can fit on the screen.
|
||||
* Crop in increments, starting at 0,0 and varying the size of the crop.
|
||||
* Crop in increments, incrementing from 0,0 downward, and varying the size of the crop.
|
||||
*
|
||||
* Start by creating 4 x 4 images in a window, and incrementing from 201 to 216.
|
||||
* </pre>
|
||||
*/
|
||||
|
||||
public static void main(String[] args) {
|
||||
Logger rootLogger = Logger.getRootLogger();
|
||||
Appender appender = (Appender) rootLogger.getAllAppenders()
|
||||
.nextElement();
|
||||
appender.setLayout(new PatternLayout("%-5p [%c{1}] %m%n"));
|
||||
|
||||
Logger.getLogger(ImageUploadThumbnailer.class).setLevel(Level.DEBUG);
|
||||
Logger.getLogger(ImageUploaderThumbnailerTester_2.class).setLevel(
|
||||
Level.INFO);
|
||||
|
||||
CropDataSet cropDataSet = new CropDataSet();
|
||||
for (int i = 0; i < ROWS * COLUMNS; i++) {
|
||||
// cropDataSet.add(i, i, 201 + i);
|
||||
cropDataSet.add(0, 0, 201 + i);
|
||||
}
|
||||
|
||||
new ImageUploaderThumbnailerTester_2(
|
||||
"C:/Users/jeb228/Pictures/wheel.png", cropDataSet);
|
||||
|
||||
// new ImageUploaderThumbnailerTester_2(
|
||||
// "C:/Users/jeb228/Pictures/DSC04203w-trans.jpg", cropDataSet);
|
||||
|
||||
// new ImageUploaderThumbnailerTester_2(
|
||||
// "C:/Development/JIRA issues/NIHVIVO-2477 Black borders on thumbnails/"
|
||||
// + "images from Alex/uploads/file_storage_root/a~n/411/9/"
|
||||
// + "De^20Bartolome^2c^20Charles^20A^20M_100037581.jpg",
|
||||
// cropDataSet);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// helper classes
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private class CloseWindowListener extends WindowAdapter {
|
||||
@Override
|
||||
public void windowClosing(WindowEvent e) {
|
||||
setVisible(false);
|
||||
dispose();
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
public static class CropDataSet {
|
||||
private final List<CropData> crops = new ArrayList<CropData>();
|
||||
|
||||
CropDataSet add(int left, int top, int size) {
|
||||
crops.add(new CropData(left, top, size));
|
||||
return this;
|
||||
}
|
||||
|
||||
Collection<CropData> crops() {
|
||||
return Collections.unmodifiableCollection(crops);
|
||||
}
|
||||
|
||||
public static class CropData {
|
||||
final int left;
|
||||
final int top;
|
||||
final int size;
|
||||
|
||||
CropData(int left, int top, int size) {
|
||||
this.left = left;
|
||||
this.top = top;
|
||||
this.size = size;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "CropData[" + left + ", " + top + ", " + size + "]";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
|
||||
|
||||
import java.awt.BorderLayout;
|
||||
import java.awt.Color;
|
||||
import java.awt.Component;
|
||||
import java.awt.Frame;
|
||||
import java.awt.GridLayout;
|
||||
import java.awt.Label;
|
||||
import java.awt.event.WindowAdapter;
|
||||
import java.awt.event.WindowEvent;
|
||||
import java.awt.image.Raster;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.media.jai.JAI;
|
||||
import javax.media.jai.RenderedOp;
|
||||
import javax.media.jai.operator.StreamDescriptor;
|
||||
import javax.media.jai.widget.ImageCanvas;
|
||||
import javax.swing.BorderFactory;
|
||||
import javax.swing.JPanel;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.log4j.Appender;
|
||||
import org.apache.log4j.Level;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.apache.log4j.PatternLayout;
|
||||
|
||||
import com.sun.media.jai.codec.MemoryCacheSeekableStream;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.ImageUploadController.CropRectangle;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.ImageUploadHelper.NonNoisyImagingListener;
|
||||
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.ImageUploaderThumbnailerTester_2.CropDataSet.CropData;
|
||||
|
||||
/**
|
||||
* This is not a unit test, so it is not named BlahBlahTest.
|
||||
*
|
||||
* Instead, it's a test harness that creates thumbnails and displays them in a
|
||||
* window on the screen. It takes human intervention to evaluate.
|
||||
*
|
||||
* The goal here is to see whether differences in crop dimensions might cause
|
||||
* one or more black edges on the thumbnails.
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
public class ImageUploaderThumbnailerTester_2 extends Frame {
|
||||
private static final Log log = LogFactory
|
||||
.getLog(ImageUploaderThumbnailerTester_2.class);
|
||||
|
||||
private static final int ROWS = 6;
|
||||
private static final int COLUMNS = 9;
|
||||
|
||||
private static final int EDGE_THRESHOLD = 6000;
|
||||
|
||||
/** Keep things quiet. */
|
||||
static {
|
||||
JAI.getDefaultInstance().setImagingListener(
|
||||
new NonNoisyImagingListener());
|
||||
}
|
||||
|
||||
private final String imagePath;
|
||||
private final ImageUploadThumbnailer thumbnailer;
|
||||
|
||||
public ImageUploaderThumbnailerTester_2(String imagePath,
|
||||
CropDataSet cropDataSet) {
|
||||
this.imagePath = imagePath;
|
||||
this.thumbnailer = new ImageUploadThumbnailer(200, 200);
|
||||
|
||||
setTitle("Cropping edging test");
|
||||
addWindowListener(new CloseWindowListener());
|
||||
setLayout(new GridLayout(ROWS, COLUMNS));
|
||||
|
||||
for (CropData cropData : cropDataSet.crops()) {
|
||||
add(createImagePanel(cropData));
|
||||
}
|
||||
|
||||
pack();
|
||||
setVisible(true);
|
||||
}
|
||||
|
||||
private Component createImagePanel(CropData cropData) {
|
||||
RenderedOp image = createCroppedImage(cropData);
|
||||
|
||||
|
||||
Set<String> blackSides = checkBlackEdges(image);
|
||||
if (!blackSides.isEmpty()) {
|
||||
log.warn("edges at " + cropData + ", " + blackSides);
|
||||
}
|
||||
|
||||
String legend = "left=" + cropData.left + ", top=" + cropData.top
|
||||
+ ", size=" + cropData.size;
|
||||
Label l = new Label();
|
||||
l.setAlignment(Label.CENTER);
|
||||
if (!blackSides.isEmpty()) {
|
||||
l.setBackground(new Color(0xFFDDDD));
|
||||
legend += " " + blackSides;
|
||||
}
|
||||
l.setText(legend);
|
||||
|
||||
JPanel p = new JPanel();
|
||||
p.setLayout(new BorderLayout());
|
||||
p.add("South", l);
|
||||
p.add("Center", new ImageCanvas(image));
|
||||
p.setBackground(new Color(0xFFFFFF));
|
||||
p.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
|
||||
|
||||
return p;
|
||||
}
|
||||
|
||||
private RenderedOp createCroppedImage(CropData cropData) {
|
||||
try {
|
||||
InputStream mainStream = new FileInputStream(imagePath);
|
||||
CropRectangle rectangle = new CropRectangle(cropData.left,
|
||||
cropData.top, cropData.size, cropData.size);
|
||||
InputStream thumbnailStream = thumbnailer.cropAndScale(mainStream,
|
||||
rectangle);
|
||||
|
||||
return StreamDescriptor.create(new MemoryCacheSeekableStream(
|
||||
thumbnailStream), null, null);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private Set<String> checkBlackEdges(RenderedOp image) {
|
||||
Raster imageData = image.getData();
|
||||
|
||||
int minX = imageData.getMinX();
|
||||
int minY = imageData.getMinY();
|
||||
int maxX = minX + imageData.getWidth() - 1;
|
||||
int maxY = minY + imageData.getHeight() - 1;
|
||||
|
||||
Set<String> blackSides = new HashSet<String>();
|
||||
if (isBlackEdge(minX, minX, minY, maxY, imageData)) {
|
||||
blackSides.add("left");
|
||||
}
|
||||
if (isBlackEdge(minX, maxX, minY, minY, imageData)) {
|
||||
blackSides.add("top");
|
||||
}
|
||||
if (isBlackEdge(maxX, maxX, minY, maxY, imageData)) {
|
||||
blackSides.add("right");
|
||||
}
|
||||
if (isBlackEdge(minX, maxX, maxY, maxY, imageData)) {
|
||||
blackSides.add("bottom");
|
||||
}
|
||||
return blackSides;
|
||||
}
|
||||
|
||||
private boolean isBlackEdge(int fromX, int toX, int fromY, int toY,
|
||||
Raster imageData) {
|
||||
int edgeTotal = 0;
|
||||
try {
|
||||
for (int col = fromX; col <= toX; col++) {
|
||||
for (int row = fromY; row <= toY; row++) {
|
||||
edgeTotal += sumPixel(imageData, col, row);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("can't sum edge: fromX=" + fromX + ", toX=" + toX
|
||||
+ ", fromY=" + fromY + ", toY=" + toY + ", imageWidth="
|
||||
+ imageData.getWidth() + ", imageHeight="
|
||||
+ imageData.getHeight() + ": " + e);
|
||||
}
|
||||
|
||||
log.debug("edge total = " + edgeTotal);
|
||||
return edgeTotal < EDGE_THRESHOLD;
|
||||
}
|
||||
|
||||
private int sumPixel(Raster imageData, int col, int row) {
|
||||
int pixelSum = 0;
|
||||
int[] pixel = imageData.getPixel(col, row, new int[0]);
|
||||
for (int value : pixel) {
|
||||
pixelSum += value;
|
||||
}
|
||||
return pixelSum;
|
||||
}
|
||||
|
||||
/**
|
||||
* <pre>
|
||||
* The plan:
|
||||
*
|
||||
* Provide the path to an image file.
|
||||
* Figure how many images can fit on the screen.
|
||||
* Crop in increments, starting at 0,0 and varying the size of the crop.
|
||||
* Crop in increments, incrementing from 0,0 downward, and varying the size of the crop.
|
||||
*
|
||||
* Start by creating 4 x 4 images in a window, and incrementing from 201 to 216.
|
||||
* </pre>
|
||||
*/
|
||||
|
||||
public static void main(String[] args) {
|
||||
Logger rootLogger = Logger.getRootLogger();
|
||||
Appender appender = (Appender) rootLogger.getAllAppenders()
|
||||
.nextElement();
|
||||
appender.setLayout(new PatternLayout("%-5p [%c{1}] %m%n"));
|
||||
|
||||
Logger.getLogger(ImageUploadThumbnailer.class).setLevel(Level.DEBUG);
|
||||
Logger.getLogger(ImageUploaderThumbnailerTester_2.class).setLevel(
|
||||
Level.INFO);
|
||||
|
||||
CropDataSet cropDataSet = new CropDataSet();
|
||||
for (int i = 0; i < ROWS * COLUMNS; i++) {
|
||||
// cropDataSet.add(i, i, 201 + i);
|
||||
cropDataSet.add(0, 0, 201 + i);
|
||||
}
|
||||
|
||||
new ImageUploaderThumbnailerTester_2(
|
||||
"C:/Users/jeb228/Pictures/wheel.png", cropDataSet);
|
||||
|
||||
// new ImageUploaderThumbnailerTester_2(
|
||||
// "C:/Users/jeb228/Pictures/DSC04203w-trans.jpg", cropDataSet);
|
||||
|
||||
// new ImageUploaderThumbnailerTester_2(
|
||||
// "C:/Development/JIRA issues/NIHVIVO-2477 Black borders on thumbnails/"
|
||||
// + "images from Alex/uploads/file_storage_root/a~n/411/9/"
|
||||
// + "De^20Bartolome^2c^20Charles^20A^20M_100037581.jpg",
|
||||
// cropDataSet);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// helper classes
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private class CloseWindowListener extends WindowAdapter {
|
||||
@Override
|
||||
public void windowClosing(WindowEvent e) {
|
||||
setVisible(false);
|
||||
dispose();
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
public static class CropDataSet {
|
||||
private final List<CropData> crops = new ArrayList<CropData>();
|
||||
|
||||
CropDataSet add(int left, int top, int size) {
|
||||
crops.add(new CropData(left, top, size));
|
||||
return this;
|
||||
}
|
||||
|
||||
Collection<CropData> crops() {
|
||||
return Collections.unmodifiableCollection(crops);
|
||||
}
|
||||
|
||||
public static class CropData {
|
||||
final int left;
|
||||
final int top;
|
||||
final int size;
|
||||
|
||||
CropData(int left, int top, int size) {
|
||||
this.left = left;
|
||||
this.top = top;
|
||||
this.size = size;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "CropData[" + left + ", " + top + ", " + size + "]";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,111 +1,111 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
package edu.cornell.mannlib.vitro.webapp.dao;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
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.vocabulary.OWL;
|
||||
import com.hp.hpl.jena.vocabulary.RDF;
|
||||
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.jena.OntModelSelector;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.jena.SimpleOntModelSelector;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.jena.WebappDaoFactoryJena;
|
||||
|
||||
public class NewURIMakerVitroTest extends AbstractTestClass{
|
||||
|
||||
@Test
|
||||
public void testMultipleNewURIs() {
|
||||
//Three items needs new URIs assigned in the default namespace
|
||||
//Var name to namespace, in this case null to denote default namespace
|
||||
Map<String,String> newResources = new HashMap<String, String>();
|
||||
newResources.put("page", null);
|
||||
newResources.put("menuItem", null);
|
||||
newResources.put("dataGetter", null);
|
||||
|
||||
//Setup webappdaofactory
|
||||
WebappDaoFactoryJena wadf = this.setupWebappDaoFactory();
|
||||
NewURIMakerVitro nv = new NewURIMakerVitro(wadf);
|
||||
|
||||
//Now test for new URI
|
||||
HashMap<String,String> varToNewURIs = new HashMap<String,String>();
|
||||
try {
|
||||
for (String key : newResources.keySet()) {
|
||||
String prefix = newResources.get(key);
|
||||
String uri = nv.getUnusedNewURI(prefix);
|
||||
varToNewURIs.put(key, uri);
|
||||
}
|
||||
} catch(Exception ex) {
|
||||
System.out.println("Error occurred " + ex);
|
||||
}
|
||||
|
||||
//Ensure that URIs are not included more than once
|
||||
List<String> values = new ArrayList<String>(varToNewURIs.values());
|
||||
Set<String> valuesSet = new HashSet<String>(varToNewURIs.values());
|
||||
assertTrue(valuesSet.size() == values.size());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNonNullNamespace() {
|
||||
//Three items needs new URIs assigned in the default namespace
|
||||
//Var name to namespace, in this case null to denote default namespace
|
||||
Map<String,String> newResources = new HashMap<String, String>();
|
||||
newResources.put("page", "http://displayOntology/test/n12");
|
||||
|
||||
|
||||
//Setup webappdaofactory
|
||||
WebappDaoFactoryJena wadf = this.setupWebappDaoFactory();
|
||||
NewURIMakerVitro nv = new NewURIMakerVitro(wadf);
|
||||
|
||||
//Now test for new URI
|
||||
HashMap<String,String> varToNewURIs = new HashMap<String,String>();
|
||||
try {
|
||||
for (String key : newResources.keySet()) {
|
||||
String prefix = newResources.get(key);
|
||||
String uri = nv.getUnusedNewURI(prefix);
|
||||
varToNewURIs.put(key, uri);
|
||||
}
|
||||
} catch(Exception ex) {
|
||||
System.out.println("Error occurred " + ex);
|
||||
}
|
||||
|
||||
//Ensure that URIs are not included more than once
|
||||
List<String> values = new ArrayList<String>(varToNewURIs.values());
|
||||
Set<String> valuesSet = new HashSet<String>(varToNewURIs.values());
|
||||
assertTrue(valuesSet.size() == values.size());
|
||||
}
|
||||
|
||||
private WebappDaoFactoryJena setupWebappDaoFactory() {
|
||||
String defaultNamespace= "http://vivo.mannlib.cornell.edu/individual/";
|
||||
String testNamespace = "http://displayOntology/test/";
|
||||
OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
|
||||
ontModel.add(
|
||||
ontModel.createResource(defaultNamespace + "n234"),
|
||||
RDF.type,
|
||||
OWL.Thing);
|
||||
ontModel.add(
|
||||
ontModel.createResource(testNamespace + "n234"),
|
||||
RDF.type,
|
||||
OWL.Thing);
|
||||
OntModelSelector selector = new SimpleOntModelSelector(ontModel);
|
||||
//Set up default namespace somewhere?
|
||||
WebappDaoFactoryConfig config = new WebappDaoFactoryConfig();
|
||||
config.setDefaultNamespace(defaultNamespace);
|
||||
//Set up some test uris
|
||||
WebappDaoFactoryJena wadf = new WebappDaoFactoryJena(selector, config);
|
||||
return wadf;
|
||||
}
|
||||
|
||||
}
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
package edu.cornell.mannlib.vitro.webapp.dao;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
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.vocabulary.OWL;
|
||||
import com.hp.hpl.jena.vocabulary.RDF;
|
||||
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.jena.OntModelSelector;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.jena.SimpleOntModelSelector;
|
||||
import edu.cornell.mannlib.vitro.webapp.dao.jena.WebappDaoFactoryJena;
|
||||
|
||||
public class NewURIMakerVitroTest extends AbstractTestClass{
|
||||
|
||||
@Test
|
||||
public void testMultipleNewURIs() {
|
||||
//Three items needs new URIs assigned in the default namespace
|
||||
//Var name to namespace, in this case null to denote default namespace
|
||||
Map<String,String> newResources = new HashMap<String, String>();
|
||||
newResources.put("page", null);
|
||||
newResources.put("menuItem", null);
|
||||
newResources.put("dataGetter", null);
|
||||
|
||||
//Setup webappdaofactory
|
||||
WebappDaoFactoryJena wadf = this.setupWebappDaoFactory();
|
||||
NewURIMakerVitro nv = new NewURIMakerVitro(wadf);
|
||||
|
||||
//Now test for new URI
|
||||
HashMap<String,String> varToNewURIs = new HashMap<String,String>();
|
||||
try {
|
||||
for (String key : newResources.keySet()) {
|
||||
String prefix = newResources.get(key);
|
||||
String uri = nv.getUnusedNewURI(prefix);
|
||||
varToNewURIs.put(key, uri);
|
||||
}
|
||||
} catch(Exception ex) {
|
||||
System.out.println("Error occurred " + ex);
|
||||
}
|
||||
|
||||
//Ensure that URIs are not included more than once
|
||||
List<String> values = new ArrayList<String>(varToNewURIs.values());
|
||||
Set<String> valuesSet = new HashSet<String>(varToNewURIs.values());
|
||||
assertTrue(valuesSet.size() == values.size());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNonNullNamespace() {
|
||||
//Three items needs new URIs assigned in the default namespace
|
||||
//Var name to namespace, in this case null to denote default namespace
|
||||
Map<String,String> newResources = new HashMap<String, String>();
|
||||
newResources.put("page", "http://displayOntology/test/n12");
|
||||
|
||||
|
||||
//Setup webappdaofactory
|
||||
WebappDaoFactoryJena wadf = this.setupWebappDaoFactory();
|
||||
NewURIMakerVitro nv = new NewURIMakerVitro(wadf);
|
||||
|
||||
//Now test for new URI
|
||||
HashMap<String,String> varToNewURIs = new HashMap<String,String>();
|
||||
try {
|
||||
for (String key : newResources.keySet()) {
|
||||
String prefix = newResources.get(key);
|
||||
String uri = nv.getUnusedNewURI(prefix);
|
||||
varToNewURIs.put(key, uri);
|
||||
}
|
||||
} catch(Exception ex) {
|
||||
System.out.println("Error occurred " + ex);
|
||||
}
|
||||
|
||||
//Ensure that URIs are not included more than once
|
||||
List<String> values = new ArrayList<String>(varToNewURIs.values());
|
||||
Set<String> valuesSet = new HashSet<String>(varToNewURIs.values());
|
||||
assertTrue(valuesSet.size() == values.size());
|
||||
}
|
||||
|
||||
private WebappDaoFactoryJena setupWebappDaoFactory() {
|
||||
String defaultNamespace= "http://vivo.mannlib.cornell.edu/individual/";
|
||||
String testNamespace = "http://displayOntology/test/";
|
||||
OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
|
||||
ontModel.add(
|
||||
ontModel.createResource(defaultNamespace + "n234"),
|
||||
RDF.type,
|
||||
OWL.Thing);
|
||||
ontModel.add(
|
||||
ontModel.createResource(testNamespace + "n234"),
|
||||
RDF.type,
|
||||
OWL.Thing);
|
||||
OntModelSelector selector = new SimpleOntModelSelector(ontModel);
|
||||
//Set up default namespace somewhere?
|
||||
WebappDaoFactoryConfig config = new WebappDaoFactoryConfig();
|
||||
config.setDefaultNamespace(defaultNamespace);
|
||||
//Set up some test uris
|
||||
WebappDaoFactoryJena wadf = new WebappDaoFactoryJena(selector, config);
|
||||
return wadf;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -1,138 +1,138 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.dao.jena;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.log4j.Level;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.hp.hpl.jena.ontology.OntModel;
|
||||
import com.hp.hpl.jena.rdf.model.ModelFactory;
|
||||
import com.hp.hpl.jena.rdf.model.Property;
|
||||
import com.hp.hpl.jena.rdf.model.RDFNode;
|
||||
import com.hp.hpl.jena.rdf.model.Resource;
|
||||
import com.hp.hpl.jena.rdf.model.Statement;
|
||||
import com.hp.hpl.jena.rdf.model.StmtIterator;
|
||||
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
|
||||
/**
|
||||
* Another set of tests for JenaBaseDao.
|
||||
*/
|
||||
public class JenaBaseDao_2_Test extends AbstractTestClass {
|
||||
private static final String NS_MINE = "http://my.namespace.edu/";
|
||||
|
||||
private static final String EMPTY_RESOURCE_URI = NS_MINE + "emptyResource";
|
||||
private static final String FULL_RESOURCE_URI = NS_MINE + "fullResource";
|
||||
|
||||
private static final String OLD_URI_1 = NS_MINE + "oldUri1";
|
||||
private static final String OLD_URI_2 = NS_MINE + "oldUri2";
|
||||
private static final String NEW_URI_1 = NS_MINE + "newUri1";
|
||||
private static final String NEW_URI_2 = NS_MINE + "newUri2";
|
||||
private static final String BOGUS_URI = "bogusUri";
|
||||
|
||||
private OntModel ontModel;
|
||||
|
||||
private Property prop1;
|
||||
|
||||
private Resource emptyResource;
|
||||
private Resource fullResource;
|
||||
|
||||
private JenaBaseDao dao;
|
||||
|
||||
@Before
|
||||
public void initializeThings() {
|
||||
ontModel = ModelFactory.createOntologyModel();
|
||||
|
||||
prop1 = ontModel.createProperty("property1");
|
||||
|
||||
emptyResource = ontModel.createResource(EMPTY_RESOURCE_URI);
|
||||
|
||||
fullResource = ontModel.createResource(FULL_RESOURCE_URI);
|
||||
ontModel.createStatement(fullResource, prop1,
|
||||
ontModel.createResource(OLD_URI_1));
|
||||
ontModel.createStatement(fullResource, prop1,
|
||||
ontModel.createResource(OLD_URI_2));
|
||||
|
||||
WebappDaoFactoryJena wdfj = new WebappDaoFactoryJena(ontModel);
|
||||
dao = new JenaBaseDao(wdfj);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// tests of updatePropertyResourceURIValues()
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void updatePropertyResourceURIValuesFromNothing() {
|
||||
updateAndConfirm(emptyResource, prop1,
|
||||
buildSet(NEW_URI_1, NEW_URI_2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updatePropertyResourceURIValuesToNothing() {
|
||||
updateAndConfirm(fullResource, prop1, Collections.<String>emptySet());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updatePropertyResourceURIValuesNoChange() {
|
||||
updateAndConfirm(fullResource, prop1,
|
||||
buildSet(OLD_URI_1, OLD_URI_2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updatePropertyResourceURIValuesReplaceSome() {
|
||||
updateAndConfirm(fullResource, prop1,
|
||||
buildSet(OLD_URI_1, NEW_URI_2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updatePropertyResourceURIValuesReplaceAll() {
|
||||
updateAndConfirm(fullResource, prop1, buildSet(NEW_URI_1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updatePropertyResourceURIValuesTryToAddEmptyURI() {
|
||||
Set<String> uris = buildSet("");
|
||||
dao.updatePropertyResourceURIValues(emptyResource, prop1, uris,
|
||||
ontModel);
|
||||
assertExpectedUriValues("update URIs", emptyResource, prop1,
|
||||
Collections.<String> emptySet());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updatePropertyResourceURIValuesTryToAddInvalidURI() {
|
||||
setLoggerLevel(JenaBaseDao.class, Level.ERROR);
|
||||
Set<String> uris = buildSet(BOGUS_URI);
|
||||
dao.updatePropertyResourceURIValues(emptyResource, prop1, uris,
|
||||
ontModel);
|
||||
assertExpectedUriValues("update URIs", emptyResource, prop1,
|
||||
Collections.<String> emptySet());
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private void updateAndConfirm(Resource res, Property prop, Set<String> uris) {
|
||||
dao.updatePropertyResourceURIValues(res, prop, uris, ontModel);
|
||||
assertExpectedUriValues("update URIs", res, prop, uris);
|
||||
}
|
||||
|
||||
private void assertExpectedUriValues(String message, Resource res,
|
||||
Property prop, Set<String> expectedUris) {
|
||||
Set<String> actualUris = new HashSet<String>();
|
||||
StmtIterator stmts = ontModel.listStatements(res, prop, (RDFNode) null);
|
||||
while (stmts.hasNext()) {
|
||||
Statement stmt = stmts.next();
|
||||
actualUris.add(stmt.getObject().asResource().getURI());
|
||||
}
|
||||
|
||||
assertEquals(message, expectedUris, actualUris);
|
||||
}
|
||||
}
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.dao.jena;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.log4j.Level;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.hp.hpl.jena.ontology.OntModel;
|
||||
import com.hp.hpl.jena.rdf.model.ModelFactory;
|
||||
import com.hp.hpl.jena.rdf.model.Property;
|
||||
import com.hp.hpl.jena.rdf.model.RDFNode;
|
||||
import com.hp.hpl.jena.rdf.model.Resource;
|
||||
import com.hp.hpl.jena.rdf.model.Statement;
|
||||
import com.hp.hpl.jena.rdf.model.StmtIterator;
|
||||
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
|
||||
/**
|
||||
* Another set of tests for JenaBaseDao.
|
||||
*/
|
||||
public class JenaBaseDao_2_Test extends AbstractTestClass {
|
||||
private static final String NS_MINE = "http://my.namespace.edu/";
|
||||
|
||||
private static final String EMPTY_RESOURCE_URI = NS_MINE + "emptyResource";
|
||||
private static final String FULL_RESOURCE_URI = NS_MINE + "fullResource";
|
||||
|
||||
private static final String OLD_URI_1 = NS_MINE + "oldUri1";
|
||||
private static final String OLD_URI_2 = NS_MINE + "oldUri2";
|
||||
private static final String NEW_URI_1 = NS_MINE + "newUri1";
|
||||
private static final String NEW_URI_2 = NS_MINE + "newUri2";
|
||||
private static final String BOGUS_URI = "bogusUri";
|
||||
|
||||
private OntModel ontModel;
|
||||
|
||||
private Property prop1;
|
||||
|
||||
private Resource emptyResource;
|
||||
private Resource fullResource;
|
||||
|
||||
private JenaBaseDao dao;
|
||||
|
||||
@Before
|
||||
public void initializeThings() {
|
||||
ontModel = ModelFactory.createOntologyModel();
|
||||
|
||||
prop1 = ontModel.createProperty("property1");
|
||||
|
||||
emptyResource = ontModel.createResource(EMPTY_RESOURCE_URI);
|
||||
|
||||
fullResource = ontModel.createResource(FULL_RESOURCE_URI);
|
||||
ontModel.createStatement(fullResource, prop1,
|
||||
ontModel.createResource(OLD_URI_1));
|
||||
ontModel.createStatement(fullResource, prop1,
|
||||
ontModel.createResource(OLD_URI_2));
|
||||
|
||||
WebappDaoFactoryJena wdfj = new WebappDaoFactoryJena(ontModel);
|
||||
dao = new JenaBaseDao(wdfj);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// tests of updatePropertyResourceURIValues()
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void updatePropertyResourceURIValuesFromNothing() {
|
||||
updateAndConfirm(emptyResource, prop1,
|
||||
buildSet(NEW_URI_1, NEW_URI_2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updatePropertyResourceURIValuesToNothing() {
|
||||
updateAndConfirm(fullResource, prop1, Collections.<String>emptySet());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updatePropertyResourceURIValuesNoChange() {
|
||||
updateAndConfirm(fullResource, prop1,
|
||||
buildSet(OLD_URI_1, OLD_URI_2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updatePropertyResourceURIValuesReplaceSome() {
|
||||
updateAndConfirm(fullResource, prop1,
|
||||
buildSet(OLD_URI_1, NEW_URI_2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updatePropertyResourceURIValuesReplaceAll() {
|
||||
updateAndConfirm(fullResource, prop1, buildSet(NEW_URI_1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updatePropertyResourceURIValuesTryToAddEmptyURI() {
|
||||
Set<String> uris = buildSet("");
|
||||
dao.updatePropertyResourceURIValues(emptyResource, prop1, uris,
|
||||
ontModel);
|
||||
assertExpectedUriValues("update URIs", emptyResource, prop1,
|
||||
Collections.<String> emptySet());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updatePropertyResourceURIValuesTryToAddInvalidURI() {
|
||||
setLoggerLevel(JenaBaseDao.class, Level.ERROR);
|
||||
Set<String> uris = buildSet(BOGUS_URI);
|
||||
dao.updatePropertyResourceURIValues(emptyResource, prop1, uris,
|
||||
ontModel);
|
||||
assertExpectedUriValues("update URIs", emptyResource, prop1,
|
||||
Collections.<String> emptySet());
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private void updateAndConfirm(Resource res, Property prop, Set<String> uris) {
|
||||
dao.updatePropertyResourceURIValues(res, prop, uris, ontModel);
|
||||
assertExpectedUriValues("update URIs", res, prop, uris);
|
||||
}
|
||||
|
||||
private void assertExpectedUriValues(String message, Resource res,
|
||||
Property prop, Set<String> expectedUris) {
|
||||
Set<String> actualUris = new HashSet<String>();
|
||||
StmtIterator stmts = ontModel.listStatements(res, prop, (RDFNode) null);
|
||||
while (stmts.hasNext()) {
|
||||
Statement stmt = stmts.next();
|
||||
actualUris.add(stmt.getObject().asResource().getURI());
|
||||
}
|
||||
|
||||
assertEquals(message, expectedUris, actualUris);
|
||||
}
|
||||
}
|
||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -1,48 +1,48 @@
|
|||
# $This file is distributed under the terms of the license in /doc/license.txt$
|
||||
|
||||
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
|
||||
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
|
||||
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
|
||||
@prefix owl: <http://www.w3.org/2002/07/owl#> .
|
||||
@prefix auth: <http://vitro.mannlib.cornell.edu/ns/vitro/authorization#> .
|
||||
@prefix mydomain: <http://vivo.mydomain.edu/individual/> .
|
||||
|
||||
### This file is for the test UserAccountsSelectorTest.java.
|
||||
|
||||
mydomain:user01
|
||||
a auth:UserAccount ;
|
||||
auth:emailAddress "email@able.edu" ;
|
||||
auth:firstName "Zack" ;
|
||||
auth:lastName "Roberts" ;
|
||||
auth:md5password "garbage" ;
|
||||
auth:passwordChangeExpires 0 ;
|
||||
auth:loginCount 5 ;
|
||||
auth:lastLoginTime 12345678 ;
|
||||
auth:status "ACTIVE" ;
|
||||
auth:externalAuthId "user1";
|
||||
auth:hasPermissionSet mydomain:role1 ;
|
||||
.
|
||||
|
||||
mydomain:role1
|
||||
a auth:PermissionSet ;
|
||||
rdfs:label "Role 1" ;
|
||||
auth:hasPermission mydomain:permissionA ;
|
||||
.
|
||||
|
||||
mydomain:role2
|
||||
a auth:PermissionSet ;
|
||||
a auth:PermissionSetForNewUsers ;
|
||||
rdfs:label "Role 2" ;
|
||||
.
|
||||
|
||||
mydomain:role3
|
||||
a auth:PermissionSet ;
|
||||
a auth:PermissionSetForPublic ;
|
||||
rdfs:label "Role 3" ;
|
||||
.
|
||||
|
||||
mydomain:permissionA
|
||||
a auth:Permission ;
|
||||
rdfs:label "Permission A" ;
|
||||
.
|
||||
# $This file is distributed under the terms of the license in /doc/license.txt$
|
||||
|
||||
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
|
||||
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
|
||||
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
|
||||
@prefix owl: <http://www.w3.org/2002/07/owl#> .
|
||||
@prefix auth: <http://vitro.mannlib.cornell.edu/ns/vitro/authorization#> .
|
||||
@prefix mydomain: <http://vivo.mydomain.edu/individual/> .
|
||||
|
||||
### This file is for the test UserAccountsSelectorTest.java.
|
||||
|
||||
mydomain:user01
|
||||
a auth:UserAccount ;
|
||||
auth:emailAddress "email@able.edu" ;
|
||||
auth:firstName "Zack" ;
|
||||
auth:lastName "Roberts" ;
|
||||
auth:md5password "garbage" ;
|
||||
auth:passwordChangeExpires 0 ;
|
||||
auth:loginCount 5 ;
|
||||
auth:lastLoginTime 12345678 ;
|
||||
auth:status "ACTIVE" ;
|
||||
auth:externalAuthId "user1";
|
||||
auth:hasPermissionSet mydomain:role1 ;
|
||||
.
|
||||
|
||||
mydomain:role1
|
||||
a auth:PermissionSet ;
|
||||
rdfs:label "Role 1" ;
|
||||
auth:hasPermission mydomain:permissionA ;
|
||||
.
|
||||
|
||||
mydomain:role2
|
||||
a auth:PermissionSet ;
|
||||
a auth:PermissionSetForNewUsers ;
|
||||
rdfs:label "Role 2" ;
|
||||
.
|
||||
|
||||
mydomain:role3
|
||||
a auth:PermissionSet ;
|
||||
a auth:PermissionSetForPublic ;
|
||||
rdfs:label "Role 3" ;
|
||||
.
|
||||
|
||||
mydomain:permissionA
|
||||
a auth:Permission ;
|
||||
rdfs:label "Permission A" ;
|
||||
.
|
||||
|
|
@ -1,276 +1,276 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo;
|
||||
|
||||
import java.io.StringReader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
import com.hp.hpl.jena.rdf.model.Model;
|
||||
import com.hp.hpl.jena.rdf.model.ModelFactory;
|
||||
import com.hp.hpl.jena.rdf.model.ResourceFactory;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.EditLiteral;
|
||||
|
||||
|
||||
public class EditN3GeneratorVTwoTest {
|
||||
static EditN3GeneratorVTwo gen = new EditN3GeneratorVTwo();
|
||||
|
||||
@Test
|
||||
public void testVarAtEndOfString(){
|
||||
String result = gen.subInNonBracketedURIS("newRes", "<http://someuri.com/n23", "?newRes");
|
||||
Assert.assertEquals("<http://someuri.com/n23", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNullTarget(){
|
||||
List<String> targets = Arrays.asList("?var",null,null,"?var");
|
||||
|
||||
Map<String,List<String>> keyToValues = new HashMap<String,List<String>>();
|
||||
keyToValues.put("var", Arrays.asList("ABC"));
|
||||
keyToValues.put("var2", Arrays.asList((String)null));
|
||||
/* test for exception */
|
||||
gen.subInMultiUris(null, targets);
|
||||
gen.subInMultiUris(keyToValues, null);
|
||||
gen.subInMultiUris(keyToValues, targets);
|
||||
|
||||
Map<String,List<Literal>> keyToLiterals = new HashMap<String,List<Literal>>();
|
||||
keyToLiterals.put("var", Arrays.asList( ResourceFactory.createTypedLiteral("String")));
|
||||
keyToLiterals.put("var2", Arrays.asList( (Literal)null));
|
||||
/* test for exception */
|
||||
gen.subInMultiLiterals(keyToLiterals, targets);
|
||||
gen.subInMultiLiterals(keyToLiterals, null);
|
||||
gen.subInMultiLiterals(null, targets);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testPunctAfterVarName(){
|
||||
List<String> targets = Arrays.asList("?var.","?var;","?var]","?var,");
|
||||
|
||||
Map<String,List<String>> keyToValues = new HashMap<String,List<String>>();
|
||||
keyToValues.put("var", Arrays.asList("ABC"));
|
||||
|
||||
gen.subInMultiUris(keyToValues, targets);
|
||||
Assert.assertNotNull(targets);
|
||||
Assert.assertEquals(4,targets.size());
|
||||
|
||||
Assert.assertEquals("<ABC>.", targets.get(0));
|
||||
Assert.assertEquals("<ABC>;", targets.get(1));
|
||||
Assert.assertEquals("<ABC>]", targets.get(2));
|
||||
Assert.assertEquals("<ABC>,", targets.get(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPunctAfterVarNameForLiterals(){
|
||||
List<String> targets = Arrays.asList("?var.","?var;","?var]","?var,");
|
||||
|
||||
Map keyToValues = new HashMap();
|
||||
keyToValues.put("var", Arrays.asList(new EditLiteral("ABC", null, null)));
|
||||
|
||||
gen.subInMultiLiterals(keyToValues, targets);
|
||||
Assert.assertNotNull(targets);
|
||||
Assert.assertEquals(4,targets.size());
|
||||
|
||||
Assert.assertEquals("\"ABC\".", targets.get(0));
|
||||
Assert.assertEquals("\"ABC\";", targets.get(1));
|
||||
Assert.assertEquals("\"ABC\"]", targets.get(2));
|
||||
Assert.assertEquals("\"ABC\",", targets.get(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLiterlasWithDatatypes(){
|
||||
List<String> targets = Arrays.asList("?var.","?var;","?var]","?var,","?var", " ?var ");
|
||||
|
||||
String value = "ABC";
|
||||
String datatype = "http://someDataType.com/bleck";
|
||||
String expected = '"' + value + '"' + "^^<" + datatype + ">";
|
||||
|
||||
Map keyToValues = new HashMap();
|
||||
keyToValues.put("var", Arrays.asList(new EditLiteral(value,datatype,null)));
|
||||
|
||||
gen.subInMultiLiterals(keyToValues, targets);
|
||||
Assert.assertNotNull(targets);
|
||||
Assert.assertEquals(6,targets.size());
|
||||
|
||||
Assert.assertEquals( expected + ".", targets.get(0));
|
||||
Assert.assertEquals(expected + ";", targets.get(1));
|
||||
Assert.assertEquals(expected + "]", targets.get(2));
|
||||
Assert.assertEquals(expected + ",", targets.get(3));
|
||||
Assert.assertEquals(expected , targets.get(4));
|
||||
Assert.assertEquals(" " + expected + " ", targets.get(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLiterlasWithLang(){
|
||||
List<String> targets = Arrays.asList("?var.","?var;","?var]","?var,","?var", " ?var ");
|
||||
|
||||
String value = "ABC";
|
||||
String datatype = null;
|
||||
String lang = "XYZ";
|
||||
String expected = '"' + value + '"' + "@" + lang + "";
|
||||
|
||||
Map keyToValues = new HashMap();
|
||||
keyToValues.put("var", Arrays.asList(new EditLiteral(value,datatype,lang)));
|
||||
|
||||
gen.subInMultiLiterals(keyToValues, targets);
|
||||
Assert.assertNotNull(targets);
|
||||
Assert.assertEquals(6,targets.size());
|
||||
|
||||
Assert.assertEquals( expected + ".", targets.get(0));
|
||||
Assert.assertEquals(expected + ";", targets.get(1));
|
||||
Assert.assertEquals(expected + "]", targets.get(2));
|
||||
Assert.assertEquals(expected + ",", targets.get(3));
|
||||
Assert.assertEquals(expected , targets.get(4));
|
||||
Assert.assertEquals(" " + expected + " ", targets.get(5));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testSubInMultiUrisNull(){
|
||||
String n3 = "?varXYZ" ;
|
||||
List<String> targets = new ArrayList<String>();
|
||||
targets.add(n3);
|
||||
|
||||
Map<String,List<String>> keyToValues = new HashMap<String,List<String>>();
|
||||
List<String> targetValue = new ArrayList<String>();
|
||||
targetValue.add(null);
|
||||
keyToValues.put("varXYZ", targetValue);
|
||||
|
||||
gen.subInMultiUris(keyToValues, targets);
|
||||
Assert.assertNotNull(targets);
|
||||
Assert.assertEquals(1,targets.size());
|
||||
|
||||
String resultN3 = targets.get(0);
|
||||
Assert.assertNotNull(resultN3);
|
||||
Assert.assertTrue("String was empty", !resultN3.isEmpty());
|
||||
|
||||
String not_expected = "<null>";
|
||||
Assert.assertTrue("must not sub in <null>", !not_expected.equals(resultN3));
|
||||
|
||||
not_expected = "<>";
|
||||
Assert.assertTrue("must not sub in <>", !not_expected.equals(resultN3));
|
||||
|
||||
Assert.assertEquals("?varXYZ", resultN3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSubInMultiUrisEmptyString(){
|
||||
String n3 = "?varXYZ" ;
|
||||
List<String> targets = new ArrayList<String>();
|
||||
targets.add(n3);
|
||||
|
||||
Map<String,List<String>> keyToValues = new HashMap<String,List<String>>();
|
||||
List<String> targetValue = new ArrayList<String>();
|
||||
targetValue.add("");
|
||||
keyToValues.put("varXYZ", targetValue);
|
||||
|
||||
gen.subInMultiUris(keyToValues, targets);
|
||||
Assert.assertNotNull(targets);
|
||||
Assert.assertEquals(1,targets.size());
|
||||
|
||||
String resultN3 = targets.get(0);
|
||||
Assert.assertNotNull(resultN3);
|
||||
Assert.assertTrue("String was empty", !resultN3.isEmpty());
|
||||
|
||||
Assert.assertEquals("?varXYZ", resultN3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSubInUrisNull(){
|
||||
String n3 = " ?varXYZ " ;
|
||||
List<String> targets = new ArrayList<String>();
|
||||
targets.add(n3);
|
||||
|
||||
Map<String,String> keyToValues = new HashMap<String,String>();
|
||||
keyToValues.put("varXYZ", "xyzURI");
|
||||
|
||||
gen.subInUris(keyToValues, targets);
|
||||
List<String> result = targets;
|
||||
Assert.assertNotNull(result);
|
||||
Assert.assertEquals(1,result.size());
|
||||
|
||||
String resultN3 = result.get(0);
|
||||
Assert.assertNotNull(resultN3);
|
||||
Assert.assertTrue("String was empty", !resultN3.isEmpty());
|
||||
Assert.assertEquals(" <xyzURI> ", resultN3);
|
||||
|
||||
keyToValues = new HashMap<String,String>();
|
||||
keyToValues.put("varXYZ", null);
|
||||
|
||||
List<String> targets2 = new ArrayList<String>();
|
||||
targets2.add(n3);
|
||||
|
||||
gen.subInUris(keyToValues, targets2);
|
||||
Assert.assertNotNull(targets2);
|
||||
Assert.assertEquals(1,targets2.size());
|
||||
|
||||
resultN3 = targets2.get(0);
|
||||
Assert.assertNotNull(resultN3);
|
||||
Assert.assertTrue("String was empty", !resultN3.isEmpty());
|
||||
Assert.assertEquals(" ?varXYZ ", resultN3);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*
|
||||
|
||||
|
||||
[@prefix core: <http://vivoweb.org/ontology/core#> .
|
||||
?person core:educationalTraining ?edTraining .
|
||||
?edTraining a core:EducationalTraining ;
|
||||
core:educationalTrainingOf ?person ;
|
||||
<http://vivoweb.org/ontology/core#trainingAtOrganization> ?org .
|
||||
, ?org <http://www.w3.org/2000/01/rdf-schema#label> ?orgLabel ., ?org a ?orgType .]
|
||||
|
||||
*/
|
||||
|
||||
//{person=http://caruso-laptop.mannlib.cornell.edu:8090/vivo/individual/n2576, predicate=http://vivoweb.org/ontology/core#educationalTraining, edTraining=null}
|
||||
|
||||
|
||||
@Test
|
||||
public void testSubInMultiUris() {
|
||||
String n3 = "?subject ?predicate ?multivalue ." ;
|
||||
List<String> strs = new ArrayList<String>();
|
||||
strs.add(n3);
|
||||
|
||||
Map<String,List<String>> keyToValues = new HashMap<String,List<String>>();
|
||||
List<String> values = new ArrayList<String>();
|
||||
values.add("http://a.com/2");
|
||||
values.add("http://b.com/ont#2");
|
||||
values.add("http://c.com/individual/n23431");
|
||||
keyToValues.put("multivalue", values);
|
||||
|
||||
List<String> subject = new ArrayList<String>();
|
||||
List<String> predicate = new ArrayList<String>();
|
||||
subject.add("http://testsubject.com/1");
|
||||
predicate.add("http://testpredicate.com/2");
|
||||
keyToValues.put("subject", subject);
|
||||
keyToValues.put("predicate", predicate);
|
||||
|
||||
gen.subInMultiUris(keyToValues, strs);
|
||||
|
||||
Assert.assertNotNull(strs);
|
||||
Assert.assertTrue( strs.size() == 1 );
|
||||
String expected ="<http://testsubject.com/1> <http://testpredicate.com/2> <http://a.com/2>, <http://b.com/ont#2>, <http://c.com/individual/n23431> .";
|
||||
Assert.assertEquals(expected, strs.get(0));
|
||||
|
||||
//Replace subject and predicate with other variables
|
||||
|
||||
//make a model,
|
||||
Model expectedModel = ModelFactory.createDefaultModel();
|
||||
StringReader expectedReader = new StringReader(expected);
|
||||
StringReader resultReader = new StringReader(strs.get(0));
|
||||
expectedModel.read(expectedReader, null, "N3");
|
||||
Model resultModel = ModelFactory.createDefaultModel();
|
||||
resultModel.read(resultReader, null, "N3");
|
||||
Assert.assertTrue(expectedModel.isIsomorphicWith(resultModel));
|
||||
}
|
||||
}
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo;
|
||||
|
||||
import java.io.StringReader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.hp.hpl.jena.rdf.model.Literal;
|
||||
import com.hp.hpl.jena.rdf.model.Model;
|
||||
import com.hp.hpl.jena.rdf.model.ModelFactory;
|
||||
import com.hp.hpl.jena.rdf.model.ResourceFactory;
|
||||
|
||||
import edu.cornell.mannlib.vitro.webapp.edit.EditLiteral;
|
||||
|
||||
|
||||
public class EditN3GeneratorVTwoTest {
|
||||
static EditN3GeneratorVTwo gen = new EditN3GeneratorVTwo();
|
||||
|
||||
@Test
|
||||
public void testVarAtEndOfString(){
|
||||
String result = gen.subInNonBracketedURIS("newRes", "<http://someuri.com/n23", "?newRes");
|
||||
Assert.assertEquals("<http://someuri.com/n23", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNullTarget(){
|
||||
List<String> targets = Arrays.asList("?var",null,null,"?var");
|
||||
|
||||
Map<String,List<String>> keyToValues = new HashMap<String,List<String>>();
|
||||
keyToValues.put("var", Arrays.asList("ABC"));
|
||||
keyToValues.put("var2", Arrays.asList((String)null));
|
||||
/* test for exception */
|
||||
gen.subInMultiUris(null, targets);
|
||||
gen.subInMultiUris(keyToValues, null);
|
||||
gen.subInMultiUris(keyToValues, targets);
|
||||
|
||||
Map<String,List<Literal>> keyToLiterals = new HashMap<String,List<Literal>>();
|
||||
keyToLiterals.put("var", Arrays.asList( ResourceFactory.createTypedLiteral("String")));
|
||||
keyToLiterals.put("var2", Arrays.asList( (Literal)null));
|
||||
/* test for exception */
|
||||
gen.subInMultiLiterals(keyToLiterals, targets);
|
||||
gen.subInMultiLiterals(keyToLiterals, null);
|
||||
gen.subInMultiLiterals(null, targets);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testPunctAfterVarName(){
|
||||
List<String> targets = Arrays.asList("?var.","?var;","?var]","?var,");
|
||||
|
||||
Map<String,List<String>> keyToValues = new HashMap<String,List<String>>();
|
||||
keyToValues.put("var", Arrays.asList("ABC"));
|
||||
|
||||
gen.subInMultiUris(keyToValues, targets);
|
||||
Assert.assertNotNull(targets);
|
||||
Assert.assertEquals(4,targets.size());
|
||||
|
||||
Assert.assertEquals("<ABC>.", targets.get(0));
|
||||
Assert.assertEquals("<ABC>;", targets.get(1));
|
||||
Assert.assertEquals("<ABC>]", targets.get(2));
|
||||
Assert.assertEquals("<ABC>,", targets.get(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPunctAfterVarNameForLiterals(){
|
||||
List<String> targets = Arrays.asList("?var.","?var;","?var]","?var,");
|
||||
|
||||
Map keyToValues = new HashMap();
|
||||
keyToValues.put("var", Arrays.asList(new EditLiteral("ABC", null, null)));
|
||||
|
||||
gen.subInMultiLiterals(keyToValues, targets);
|
||||
Assert.assertNotNull(targets);
|
||||
Assert.assertEquals(4,targets.size());
|
||||
|
||||
Assert.assertEquals("\"ABC\".", targets.get(0));
|
||||
Assert.assertEquals("\"ABC\";", targets.get(1));
|
||||
Assert.assertEquals("\"ABC\"]", targets.get(2));
|
||||
Assert.assertEquals("\"ABC\",", targets.get(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLiterlasWithDatatypes(){
|
||||
List<String> targets = Arrays.asList("?var.","?var;","?var]","?var,","?var", " ?var ");
|
||||
|
||||
String value = "ABC";
|
||||
String datatype = "http://someDataType.com/bleck";
|
||||
String expected = '"' + value + '"' + "^^<" + datatype + ">";
|
||||
|
||||
Map keyToValues = new HashMap();
|
||||
keyToValues.put("var", Arrays.asList(new EditLiteral(value,datatype,null)));
|
||||
|
||||
gen.subInMultiLiterals(keyToValues, targets);
|
||||
Assert.assertNotNull(targets);
|
||||
Assert.assertEquals(6,targets.size());
|
||||
|
||||
Assert.assertEquals( expected + ".", targets.get(0));
|
||||
Assert.assertEquals(expected + ";", targets.get(1));
|
||||
Assert.assertEquals(expected + "]", targets.get(2));
|
||||
Assert.assertEquals(expected + ",", targets.get(3));
|
||||
Assert.assertEquals(expected , targets.get(4));
|
||||
Assert.assertEquals(" " + expected + " ", targets.get(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLiterlasWithLang(){
|
||||
List<String> targets = Arrays.asList("?var.","?var;","?var]","?var,","?var", " ?var ");
|
||||
|
||||
String value = "ABC";
|
||||
String datatype = null;
|
||||
String lang = "XYZ";
|
||||
String expected = '"' + value + '"' + "@" + lang + "";
|
||||
|
||||
Map keyToValues = new HashMap();
|
||||
keyToValues.put("var", Arrays.asList(new EditLiteral(value,datatype,lang)));
|
||||
|
||||
gen.subInMultiLiterals(keyToValues, targets);
|
||||
Assert.assertNotNull(targets);
|
||||
Assert.assertEquals(6,targets.size());
|
||||
|
||||
Assert.assertEquals( expected + ".", targets.get(0));
|
||||
Assert.assertEquals(expected + ";", targets.get(1));
|
||||
Assert.assertEquals(expected + "]", targets.get(2));
|
||||
Assert.assertEquals(expected + ",", targets.get(3));
|
||||
Assert.assertEquals(expected , targets.get(4));
|
||||
Assert.assertEquals(" " + expected + " ", targets.get(5));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testSubInMultiUrisNull(){
|
||||
String n3 = "?varXYZ" ;
|
||||
List<String> targets = new ArrayList<String>();
|
||||
targets.add(n3);
|
||||
|
||||
Map<String,List<String>> keyToValues = new HashMap<String,List<String>>();
|
||||
List<String> targetValue = new ArrayList<String>();
|
||||
targetValue.add(null);
|
||||
keyToValues.put("varXYZ", targetValue);
|
||||
|
||||
gen.subInMultiUris(keyToValues, targets);
|
||||
Assert.assertNotNull(targets);
|
||||
Assert.assertEquals(1,targets.size());
|
||||
|
||||
String resultN3 = targets.get(0);
|
||||
Assert.assertNotNull(resultN3);
|
||||
Assert.assertTrue("String was empty", !resultN3.isEmpty());
|
||||
|
||||
String not_expected = "<null>";
|
||||
Assert.assertTrue("must not sub in <null>", !not_expected.equals(resultN3));
|
||||
|
||||
not_expected = "<>";
|
||||
Assert.assertTrue("must not sub in <>", !not_expected.equals(resultN3));
|
||||
|
||||
Assert.assertEquals("?varXYZ", resultN3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSubInMultiUrisEmptyString(){
|
||||
String n3 = "?varXYZ" ;
|
||||
List<String> targets = new ArrayList<String>();
|
||||
targets.add(n3);
|
||||
|
||||
Map<String,List<String>> keyToValues = new HashMap<String,List<String>>();
|
||||
List<String> targetValue = new ArrayList<String>();
|
||||
targetValue.add("");
|
||||
keyToValues.put("varXYZ", targetValue);
|
||||
|
||||
gen.subInMultiUris(keyToValues, targets);
|
||||
Assert.assertNotNull(targets);
|
||||
Assert.assertEquals(1,targets.size());
|
||||
|
||||
String resultN3 = targets.get(0);
|
||||
Assert.assertNotNull(resultN3);
|
||||
Assert.assertTrue("String was empty", !resultN3.isEmpty());
|
||||
|
||||
Assert.assertEquals("?varXYZ", resultN3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSubInUrisNull(){
|
||||
String n3 = " ?varXYZ " ;
|
||||
List<String> targets = new ArrayList<String>();
|
||||
targets.add(n3);
|
||||
|
||||
Map<String,String> keyToValues = new HashMap<String,String>();
|
||||
keyToValues.put("varXYZ", "xyzURI");
|
||||
|
||||
gen.subInUris(keyToValues, targets);
|
||||
List<String> result = targets;
|
||||
Assert.assertNotNull(result);
|
||||
Assert.assertEquals(1,result.size());
|
||||
|
||||
String resultN3 = result.get(0);
|
||||
Assert.assertNotNull(resultN3);
|
||||
Assert.assertTrue("String was empty", !resultN3.isEmpty());
|
||||
Assert.assertEquals(" <xyzURI> ", resultN3);
|
||||
|
||||
keyToValues = new HashMap<String,String>();
|
||||
keyToValues.put("varXYZ", null);
|
||||
|
||||
List<String> targets2 = new ArrayList<String>();
|
||||
targets2.add(n3);
|
||||
|
||||
gen.subInUris(keyToValues, targets2);
|
||||
Assert.assertNotNull(targets2);
|
||||
Assert.assertEquals(1,targets2.size());
|
||||
|
||||
resultN3 = targets2.get(0);
|
||||
Assert.assertNotNull(resultN3);
|
||||
Assert.assertTrue("String was empty", !resultN3.isEmpty());
|
||||
Assert.assertEquals(" ?varXYZ ", resultN3);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*
|
||||
|
||||
|
||||
[@prefix core: <http://vivoweb.org/ontology/core#> .
|
||||
?person core:educationalTraining ?edTraining .
|
||||
?edTraining a core:EducationalTraining ;
|
||||
core:educationalTrainingOf ?person ;
|
||||
<http://vivoweb.org/ontology/core#trainingAtOrganization> ?org .
|
||||
, ?org <http://www.w3.org/2000/01/rdf-schema#label> ?orgLabel ., ?org a ?orgType .]
|
||||
|
||||
*/
|
||||
|
||||
//{person=http://caruso-laptop.mannlib.cornell.edu:8090/vivo/individual/n2576, predicate=http://vivoweb.org/ontology/core#educationalTraining, edTraining=null}
|
||||
|
||||
|
||||
@Test
|
||||
public void testSubInMultiUris() {
|
||||
String n3 = "?subject ?predicate ?multivalue ." ;
|
||||
List<String> strs = new ArrayList<String>();
|
||||
strs.add(n3);
|
||||
|
||||
Map<String,List<String>> keyToValues = new HashMap<String,List<String>>();
|
||||
List<String> values = new ArrayList<String>();
|
||||
values.add("http://a.com/2");
|
||||
values.add("http://b.com/ont#2");
|
||||
values.add("http://c.com/individual/n23431");
|
||||
keyToValues.put("multivalue", values);
|
||||
|
||||
List<String> subject = new ArrayList<String>();
|
||||
List<String> predicate = new ArrayList<String>();
|
||||
subject.add("http://testsubject.com/1");
|
||||
predicate.add("http://testpredicate.com/2");
|
||||
keyToValues.put("subject", subject);
|
||||
keyToValues.put("predicate", predicate);
|
||||
|
||||
gen.subInMultiUris(keyToValues, strs);
|
||||
|
||||
Assert.assertNotNull(strs);
|
||||
Assert.assertTrue( strs.size() == 1 );
|
||||
String expected ="<http://testsubject.com/1> <http://testpredicate.com/2> <http://a.com/2>, <http://b.com/ont#2>, <http://c.com/individual/n23431> .";
|
||||
Assert.assertEquals(expected, strs.get(0));
|
||||
|
||||
//Replace subject and predicate with other variables
|
||||
|
||||
//make a model,
|
||||
Model expectedModel = ModelFactory.createDefaultModel();
|
||||
StringReader expectedReader = new StringReader(expected);
|
||||
StringReader resultReader = new StringReader(strs.get(0));
|
||||
expectedModel.read(expectedReader, null, "N3");
|
||||
Model resultModel = ModelFactory.createDefaultModel();
|
||||
resultModel.read(resultReader, null, "N3");
|
||||
Assert.assertTrue(expectedModel.isIsomorphicWith(resultModel));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,87 +1,87 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.filestorage;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.apache.log4j.Level;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import stubs.edu.cornell.mannlib.vitro.webapp.config.ConfigurationPropertiesStub;
|
||||
import stubs.javax.servlet.ServletContextStub;
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties;
|
||||
import edu.cornell.mannlib.vitro.webapp.filestorage.backend.FileStorageSetup;
|
||||
|
||||
/**
|
||||
*/
|
||||
public class FileServingHelperTest extends AbstractTestClass {
|
||||
private static final String DEFAULT_NAMESPACE = "http://some.crazy.domain/individual/";
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// framework
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private ServletContextStub ctx;
|
||||
|
||||
/**
|
||||
* Set the desired default namespace into the ConfigurationProperties.
|
||||
*/
|
||||
@Before
|
||||
public void createConfigurationProperties() throws Exception {
|
||||
setLoggerLevel(ConfigurationProperties.class, Level.WARN);
|
||||
|
||||
ctx = new ServletContextStub();
|
||||
|
||||
ConfigurationPropertiesStub props = new ConfigurationPropertiesStub();
|
||||
props.setProperty(FileStorageSetup.PROPERTY_DEFAULT_NAMESPACE,
|
||||
DEFAULT_NAMESPACE);
|
||||
props.setBean(ctx);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void nullUri() {
|
||||
assertCorrectUrl(null, "somefilename.ext", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nullFilename() {
|
||||
assertCorrectUrl("http://some.crazy.domain/individual/n4324", null,
|
||||
null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void notInDefaultNamespace() {
|
||||
setLoggerLevel(FileServingHelper.class, Level.ERROR);
|
||||
assertCorrectUrl("notInTheNamespace", "somefilename.ext",
|
||||
"notInTheNamespace");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void inDefaultNamespaceNoTrailingSlash() {
|
||||
assertCorrectUrl("http://some.crazy.domain/individual/n4324",
|
||||
"somefilename.ext", "/file/n4324/somefilename.ext");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void inDefaultNamespaceTrailingSlash() {
|
||||
assertCorrectUrl("http://some.crazy.domain/individual/n4324/",
|
||||
"somefilename.ext", "/file/n4324/somefilename.ext");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private void assertCorrectUrl(String uri, String filename, String expected) {
|
||||
String actual = FileServingHelper.getBytestreamAliasUrl(uri, filename,
|
||||
ctx);
|
||||
assertEquals("url", expected, actual);
|
||||
}
|
||||
|
||||
}
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.filestorage;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.apache.log4j.Level;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import stubs.edu.cornell.mannlib.vitro.webapp.config.ConfigurationPropertiesStub;
|
||||
import stubs.javax.servlet.ServletContextStub;
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties;
|
||||
import edu.cornell.mannlib.vitro.webapp.filestorage.backend.FileStorageSetup;
|
||||
|
||||
/**
|
||||
*/
|
||||
public class FileServingHelperTest extends AbstractTestClass {
|
||||
private static final String DEFAULT_NAMESPACE = "http://some.crazy.domain/individual/";
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// framework
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private ServletContextStub ctx;
|
||||
|
||||
/**
|
||||
* Set the desired default namespace into the ConfigurationProperties.
|
||||
*/
|
||||
@Before
|
||||
public void createConfigurationProperties() throws Exception {
|
||||
setLoggerLevel(ConfigurationProperties.class, Level.WARN);
|
||||
|
||||
ctx = new ServletContextStub();
|
||||
|
||||
ConfigurationPropertiesStub props = new ConfigurationPropertiesStub();
|
||||
props.setProperty(FileStorageSetup.PROPERTY_DEFAULT_NAMESPACE,
|
||||
DEFAULT_NAMESPACE);
|
||||
props.setBean(ctx);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void nullUri() {
|
||||
assertCorrectUrl(null, "somefilename.ext", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nullFilename() {
|
||||
assertCorrectUrl("http://some.crazy.domain/individual/n4324", null,
|
||||
null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void notInDefaultNamespace() {
|
||||
setLoggerLevel(FileServingHelper.class, Level.ERROR);
|
||||
assertCorrectUrl("notInTheNamespace", "somefilename.ext",
|
||||
"notInTheNamespace");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void inDefaultNamespaceNoTrailingSlash() {
|
||||
assertCorrectUrl("http://some.crazy.domain/individual/n4324",
|
||||
"somefilename.ext", "/file/n4324/somefilename.ext");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void inDefaultNamespaceTrailingSlash() {
|
||||
assertCorrectUrl("http://some.crazy.domain/individual/n4324/",
|
||||
"somefilename.ext", "/file/n4324/somefilename.ext");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private void assertCorrectUrl(String uri, String filename, String expected) {
|
||||
String actual = FileServingHelper.getBytestreamAliasUrl(uri, filename,
|
||||
ctx);
|
||||
assertEquals("url", expected, actual);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,225 +1,225 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.filestorage.backend;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public class FileStorageHelperTest {
|
||||
private static String RAW_NAME_1 = "simpleName";
|
||||
private static String ENCODED_NAME_1 = "simpleName";
|
||||
private static String RAW_NAME_2 = "common:/Chars.pdf";
|
||||
private static String ENCODED_NAME_2 = "common+=Chars.pdf";
|
||||
private static String RAW_NAME_3 = "rare\"+~chars";
|
||||
private static String ENCODED_NAME_3 = "rare^22^2b^7echars";
|
||||
private static String RAW_NAME_4 = "combination+<of^:both";
|
||||
private static String ENCODED_NAME_4 = "combination^2b^3cof^5e+both";
|
||||
private static String RAW_NAME_5 = " invisibles\u0001\u007f";
|
||||
private static String ENCODED_NAME_5 = "^20invisibles^01^7f";
|
||||
private static String RAW_NAME_6 = "out of range\u0101";
|
||||
|
||||
private static String ID_1 = "simpleName";
|
||||
private static String RELATIVE_PATH_1 = "sim/ple/Nam/e";
|
||||
private static String ID_2 = "combination+<of^:both";
|
||||
private static String RELATIVE_PATH_2 = "com/bin/ati/on^/2b^/3co/f^5/e+b/oth";
|
||||
private static String ID_3 = "http://vivo.myDomain.edu/file/n3234";
|
||||
private static String RELATIVE_PATH_3 = "htt/p+=/=vi/vo,/myD/oma/in,/edu/=fi/le=/n32/34";
|
||||
private static String RELATIVE_PREFIXED_PATH_3 = "b~n/323/4";
|
||||
|
||||
private static File ROOT_DIR_1 = new File("/root");
|
||||
private static File ABSOLUTE_PATH_1 = new File("/root/sim/ple/Nam/e");
|
||||
private static File ROOT_DIR_2 = new File("/this/that/slash/");
|
||||
private static File ABSOLUTE_PATH_2 = new File(
|
||||
"/this/that/slash/sim/ple/Nam/e");
|
||||
|
||||
private static String FULL_NAME = "myPhoto.jpg";
|
||||
private static String FULL_ID = "http://vivo.myDomain.edu/file/n3234.XXX";
|
||||
private static File FULL_ROOT = new File(
|
||||
"/usr/local/vivo/uploads/file_storage_root");
|
||||
private static File FULL_RESULT_PATH = new File(
|
||||
"/usr/local/vivo/uploads/file_storage_root/b~n/323/4,X/XX/myPhoto.jpg");
|
||||
|
||||
private static Map<Character, String> WINDOWS_PREFIX_MAP = initWindowsPrefixMap();
|
||||
/** This reserved word will be modified. */
|
||||
private static String WINDOWS_NAME = "lpT8";
|
||||
/** This ID would translate to a path with a reserved word. */
|
||||
private static String WINDOWS_ID = "prefix:createdConflict";
|
||||
/** Not allowed to change the root, even if it contains reserved words. */
|
||||
private static File WINDOWS_ROOT = new File("/usr/aux/root/");
|
||||
private static File WINDOWS_FULL_PATH = new File(
|
||||
"/usr/aux/root/a~c/rea/ted/~Con/fli/ct/~lpT8");
|
||||
|
||||
private static Map<Character, String> EMPTY_NAMESPACES = Collections
|
||||
.emptyMap();
|
||||
private static Map<Character, String> NAMESPACES = initPrefixMap();
|
||||
|
||||
private static Map<Character, String> initPrefixMap() {
|
||||
Map<Character, String> map = new HashMap<Character, String>();
|
||||
map.put('a', "junk");
|
||||
map.put('b', "http://vivo.myDomain.edu/file/");
|
||||
return map;
|
||||
}
|
||||
|
||||
private static Map<Character, String> initWindowsPrefixMap() {
|
||||
Map<Character, String> map = new HashMap<Character, String>();
|
||||
map.put('a', "prefix:");
|
||||
return map;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// encodeName
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void encodeName1() {
|
||||
assertNameEncoding(RAW_NAME_1, ENCODED_NAME_1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void encodeName2() {
|
||||
assertNameEncoding(RAW_NAME_2, ENCODED_NAME_2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void encodeName3() {
|
||||
assertNameEncoding(RAW_NAME_3, ENCODED_NAME_3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void encodeName4() {
|
||||
assertNameEncoding(RAW_NAME_4, ENCODED_NAME_4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void encodeName5() {
|
||||
assertNameEncoding(RAW_NAME_5, ENCODED_NAME_5);
|
||||
}
|
||||
|
||||
@Test(expected = InvalidCharacterException.class)
|
||||
public void encodeName6() {
|
||||
FileStorageHelper.encodeName(RAW_NAME_6);
|
||||
}
|
||||
|
||||
private void assertNameEncoding(String rawName, String expected) {
|
||||
String encoded = FileStorageHelper.encodeName(rawName);
|
||||
assertEquals("encoded name", expected, encoded);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// decodeName
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void decodeName1() {
|
||||
assertNameDecoding(ENCODED_NAME_1, RAW_NAME_1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void decodeName2() {
|
||||
assertNameDecoding(ENCODED_NAME_2, RAW_NAME_2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void decodeName3() {
|
||||
assertNameDecoding(ENCODED_NAME_3, RAW_NAME_3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void decodeName4() {
|
||||
assertNameDecoding(ENCODED_NAME_4, RAW_NAME_4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void decodeName5() {
|
||||
assertNameDecoding(ENCODED_NAME_5, RAW_NAME_5);
|
||||
}
|
||||
|
||||
private void assertNameDecoding(String encodedName, String expected) {
|
||||
String decoded = FileStorageHelper.decodeName(encodedName);
|
||||
assertEquals("decodedName", expected, decoded);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// idToPath
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void idToPath1() {
|
||||
assertIdToPath(ID_1, EMPTY_NAMESPACES, RELATIVE_PATH_1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void idToPath2() {
|
||||
assertIdToPath(ID_2, EMPTY_NAMESPACES, RELATIVE_PATH_2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void idToPath3() {
|
||||
assertIdToPath(ID_3, EMPTY_NAMESPACES, RELATIVE_PATH_3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void idToPath3WithNamespace() {
|
||||
assertIdToPath(ID_3, NAMESPACES, RELATIVE_PREFIXED_PATH_3);
|
||||
}
|
||||
|
||||
private void assertIdToPath(String id, Map<Character, String> namespaces,
|
||||
String expected) {
|
||||
String adjustedExpected = expected.replace('/', File.separatorChar);
|
||||
String relativePath = FileStorageHelper.id2Path(id, namespaces);
|
||||
assertEquals("idToPath", adjustedExpected, relativePath);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// getPathToIdDirectory
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void getPathToIdDirectory1() {
|
||||
assertPathToIdDirectory(ID_1, EMPTY_NAMESPACES, ROOT_DIR_1,
|
||||
ABSOLUTE_PATH_1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getPathToIdDirectory2() {
|
||||
assertPathToIdDirectory(ID_1, EMPTY_NAMESPACES, ROOT_DIR_2,
|
||||
ABSOLUTE_PATH_2);
|
||||
}
|
||||
|
||||
private void assertPathToIdDirectory(String id,
|
||||
Map<Character, String> namespaces, File rootDir, File expected) {
|
||||
File actual = FileStorageHelper.getPathToIdDirectory(id, namespaces,
|
||||
rootDir);
|
||||
File adjustedExpected = new File(expected.getPath().replace('/',
|
||||
File.separatorChar));
|
||||
assertEquals("pathToIdDirectory", adjustedExpected, actual);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// getFullPath
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void getFullPath() {
|
||||
File actual = FileStorageHelper.getFullPath(FULL_ROOT, FULL_ID,
|
||||
FULL_NAME, NAMESPACES);
|
||||
assertEquals("fullPath", FULL_RESULT_PATH, actual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkWindowsExclusions() {
|
||||
File actual = FileStorageHelper.getFullPath(WINDOWS_ROOT, WINDOWS_ID,
|
||||
WINDOWS_NAME, WINDOWS_PREFIX_MAP);
|
||||
assertEquals("windows exclusion", WINDOWS_FULL_PATH, actual);
|
||||
}
|
||||
|
||||
}
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.filestorage.backend;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public class FileStorageHelperTest {
|
||||
private static String RAW_NAME_1 = "simpleName";
|
||||
private static String ENCODED_NAME_1 = "simpleName";
|
||||
private static String RAW_NAME_2 = "common:/Chars.pdf";
|
||||
private static String ENCODED_NAME_2 = "common+=Chars.pdf";
|
||||
private static String RAW_NAME_3 = "rare\"+~chars";
|
||||
private static String ENCODED_NAME_3 = "rare^22^2b^7echars";
|
||||
private static String RAW_NAME_4 = "combination+<of^:both";
|
||||
private static String ENCODED_NAME_4 = "combination^2b^3cof^5e+both";
|
||||
private static String RAW_NAME_5 = " invisibles\u0001\u007f";
|
||||
private static String ENCODED_NAME_5 = "^20invisibles^01^7f";
|
||||
private static String RAW_NAME_6 = "out of range\u0101";
|
||||
|
||||
private static String ID_1 = "simpleName";
|
||||
private static String RELATIVE_PATH_1 = "sim/ple/Nam/e";
|
||||
private static String ID_2 = "combination+<of^:both";
|
||||
private static String RELATIVE_PATH_2 = "com/bin/ati/on^/2b^/3co/f^5/e+b/oth";
|
||||
private static String ID_3 = "http://vivo.myDomain.edu/file/n3234";
|
||||
private static String RELATIVE_PATH_3 = "htt/p+=/=vi/vo,/myD/oma/in,/edu/=fi/le=/n32/34";
|
||||
private static String RELATIVE_PREFIXED_PATH_3 = "b~n/323/4";
|
||||
|
||||
private static File ROOT_DIR_1 = new File("/root");
|
||||
private static File ABSOLUTE_PATH_1 = new File("/root/sim/ple/Nam/e");
|
||||
private static File ROOT_DIR_2 = new File("/this/that/slash/");
|
||||
private static File ABSOLUTE_PATH_2 = new File(
|
||||
"/this/that/slash/sim/ple/Nam/e");
|
||||
|
||||
private static String FULL_NAME = "myPhoto.jpg";
|
||||
private static String FULL_ID = "http://vivo.myDomain.edu/file/n3234.XXX";
|
||||
private static File FULL_ROOT = new File(
|
||||
"/usr/local/vivo/uploads/file_storage_root");
|
||||
private static File FULL_RESULT_PATH = new File(
|
||||
"/usr/local/vivo/uploads/file_storage_root/b~n/323/4,X/XX/myPhoto.jpg");
|
||||
|
||||
private static Map<Character, String> WINDOWS_PREFIX_MAP = initWindowsPrefixMap();
|
||||
/** This reserved word will be modified. */
|
||||
private static String WINDOWS_NAME = "lpT8";
|
||||
/** This ID would translate to a path with a reserved word. */
|
||||
private static String WINDOWS_ID = "prefix:createdConflict";
|
||||
/** Not allowed to change the root, even if it contains reserved words. */
|
||||
private static File WINDOWS_ROOT = new File("/usr/aux/root/");
|
||||
private static File WINDOWS_FULL_PATH = new File(
|
||||
"/usr/aux/root/a~c/rea/ted/~Con/fli/ct/~lpT8");
|
||||
|
||||
private static Map<Character, String> EMPTY_NAMESPACES = Collections
|
||||
.emptyMap();
|
||||
private static Map<Character, String> NAMESPACES = initPrefixMap();
|
||||
|
||||
private static Map<Character, String> initPrefixMap() {
|
||||
Map<Character, String> map = new HashMap<Character, String>();
|
||||
map.put('a', "junk");
|
||||
map.put('b', "http://vivo.myDomain.edu/file/");
|
||||
return map;
|
||||
}
|
||||
|
||||
private static Map<Character, String> initWindowsPrefixMap() {
|
||||
Map<Character, String> map = new HashMap<Character, String>();
|
||||
map.put('a', "prefix:");
|
||||
return map;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// encodeName
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void encodeName1() {
|
||||
assertNameEncoding(RAW_NAME_1, ENCODED_NAME_1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void encodeName2() {
|
||||
assertNameEncoding(RAW_NAME_2, ENCODED_NAME_2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void encodeName3() {
|
||||
assertNameEncoding(RAW_NAME_3, ENCODED_NAME_3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void encodeName4() {
|
||||
assertNameEncoding(RAW_NAME_4, ENCODED_NAME_4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void encodeName5() {
|
||||
assertNameEncoding(RAW_NAME_5, ENCODED_NAME_5);
|
||||
}
|
||||
|
||||
@Test(expected = InvalidCharacterException.class)
|
||||
public void encodeName6() {
|
||||
FileStorageHelper.encodeName(RAW_NAME_6);
|
||||
}
|
||||
|
||||
private void assertNameEncoding(String rawName, String expected) {
|
||||
String encoded = FileStorageHelper.encodeName(rawName);
|
||||
assertEquals("encoded name", expected, encoded);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// decodeName
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void decodeName1() {
|
||||
assertNameDecoding(ENCODED_NAME_1, RAW_NAME_1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void decodeName2() {
|
||||
assertNameDecoding(ENCODED_NAME_2, RAW_NAME_2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void decodeName3() {
|
||||
assertNameDecoding(ENCODED_NAME_3, RAW_NAME_3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void decodeName4() {
|
||||
assertNameDecoding(ENCODED_NAME_4, RAW_NAME_4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void decodeName5() {
|
||||
assertNameDecoding(ENCODED_NAME_5, RAW_NAME_5);
|
||||
}
|
||||
|
||||
private void assertNameDecoding(String encodedName, String expected) {
|
||||
String decoded = FileStorageHelper.decodeName(encodedName);
|
||||
assertEquals("decodedName", expected, decoded);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// idToPath
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void idToPath1() {
|
||||
assertIdToPath(ID_1, EMPTY_NAMESPACES, RELATIVE_PATH_1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void idToPath2() {
|
||||
assertIdToPath(ID_2, EMPTY_NAMESPACES, RELATIVE_PATH_2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void idToPath3() {
|
||||
assertIdToPath(ID_3, EMPTY_NAMESPACES, RELATIVE_PATH_3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void idToPath3WithNamespace() {
|
||||
assertIdToPath(ID_3, NAMESPACES, RELATIVE_PREFIXED_PATH_3);
|
||||
}
|
||||
|
||||
private void assertIdToPath(String id, Map<Character, String> namespaces,
|
||||
String expected) {
|
||||
String adjustedExpected = expected.replace('/', File.separatorChar);
|
||||
String relativePath = FileStorageHelper.id2Path(id, namespaces);
|
||||
assertEquals("idToPath", adjustedExpected, relativePath);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// getPathToIdDirectory
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void getPathToIdDirectory1() {
|
||||
assertPathToIdDirectory(ID_1, EMPTY_NAMESPACES, ROOT_DIR_1,
|
||||
ABSOLUTE_PATH_1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getPathToIdDirectory2() {
|
||||
assertPathToIdDirectory(ID_1, EMPTY_NAMESPACES, ROOT_DIR_2,
|
||||
ABSOLUTE_PATH_2);
|
||||
}
|
||||
|
||||
private void assertPathToIdDirectory(String id,
|
||||
Map<Character, String> namespaces, File rootDir, File expected) {
|
||||
File actual = FileStorageHelper.getPathToIdDirectory(id, namespaces,
|
||||
rootDir);
|
||||
File adjustedExpected = new File(expected.getPath().replace('/',
|
||||
File.separatorChar));
|
||||
assertEquals("pathToIdDirectory", adjustedExpected, actual);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// getFullPath
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
public void getFullPath() {
|
||||
File actual = FileStorageHelper.getFullPath(FULL_ROOT, FULL_ID,
|
||||
FULL_NAME, NAMESPACES);
|
||||
assertEquals("fullPath", FULL_RESULT_PATH, actual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkWindowsExclusions() {
|
||||
File actual = FileStorageHelper.getFullPath(WINDOWS_ROOT, WINDOWS_ID,
|
||||
WINDOWS_NAME, WINDOWS_PREFIX_MAP);
|
||||
assertEquals("windows exclusion", WINDOWS_FULL_PATH, actual);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,289 +1,289 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.filestorage.backend;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.log4j.Level;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
|
||||
/**
|
||||
* Test the FileStorage methods. The zero-argument constructor was tested in
|
||||
* {@link FileStorageFactoryTest}.
|
||||
*/
|
||||
public class FileStorageImplTest extends AbstractTestClass {
|
||||
private static final List<String> EMPTY_NAMESPACES = Collections
|
||||
.emptyList();
|
||||
|
||||
private static File tempDir;
|
||||
private static FileStorageImpl generalFs;
|
||||
|
||||
@BeforeClass
|
||||
public static void createSomeDirectories() throws IOException {
|
||||
tempDir = createTempDirectory(FileStorageImplTest.class.getSimpleName());
|
||||
generalFs = createFileStorage("general");
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void cleanUp() {
|
||||
if (tempDir != null) {
|
||||
purgeDirectoryRecursively(tempDir);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void baseDirDoesntExist() throws IOException {
|
||||
File baseDir = new File(tempDir, "doesntExist");
|
||||
new FileStorageImpl(baseDir, EMPTY_NAMESPACES);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void partialInitializationRoot() throws IOException {
|
||||
File baseDir = new File(tempDir, "partialWithRoot");
|
||||
baseDir.mkdir();
|
||||
new File(baseDir, FileStorage.FILE_STORAGE_ROOT).mkdir();
|
||||
|
||||
new FileStorageImpl(baseDir, EMPTY_NAMESPACES);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void partialInitializationNamespaces() throws IOException {
|
||||
File baseDir = new File(tempDir, "partialWithNamespaces");
|
||||
baseDir.mkdir();
|
||||
new File(baseDir, FileStorage.FILE_STORAGE_NAMESPACES_PROPERTIES)
|
||||
.createNewFile();
|
||||
|
||||
new FileStorageImpl(baseDir, EMPTY_NAMESPACES);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void notInitializedNoNamespaces() throws IOException {
|
||||
File baseDir = new File(tempDir, "emptyNoNamespaces");
|
||||
baseDir.mkdir();
|
||||
|
||||
FileStorageImpl fs = new FileStorageImpl(baseDir,
|
||||
new ArrayList<String>());
|
||||
assertEquals("baseDir", baseDir, fs.getBaseDir());
|
||||
assertEqualSets("namespaces", new String[0], fs.getNamespaces()
|
||||
.values());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void notInitializedNamespaces() throws IOException {
|
||||
String[] namespaces = new String[] { "ns1", "ns2" };
|
||||
String dirName = "emptyWithNamespaces";
|
||||
|
||||
FileStorageImpl fs = createFileStorage(dirName, namespaces);
|
||||
|
||||
assertEquals("baseDir", new File(tempDir, dirName), fs.getBaseDir());
|
||||
assertEqualSets("namespaces", namespaces, fs.getNamespaces().values());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void initializedOK() throws IOException {
|
||||
createFileStorage("initializeTwiceTheSame", "ns1", "ns2");
|
||||
createFileStorage("initializeTwiceTheSame", "ns2", "ns1");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void namespaceDisappears() throws IOException {
|
||||
createFileStorage("namespaceDisappears", "ns1", "ns2");
|
||||
FileStorageImpl fs = createFileStorage("namespaceDisappears", "ns2");
|
||||
assertEqualSets("namespaces", new String[] { "ns1", "ns2" }, fs
|
||||
.getNamespaces().values());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void namespaceChanged() throws IOException {
|
||||
setLoggerLevel(FileStorageImpl.class, Level.ERROR);
|
||||
createFileStorage("namespaceChanges", "ns1", "ns2");
|
||||
FileStorageImpl fs = createFileStorage("namespaceChanges", "ns3", "ns1");
|
||||
assertEqualSets("namespaces", new String[] { "ns1", "ns2", "ns3" }, fs
|
||||
.getNamespaces().values());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createFileOriginal() throws IOException {
|
||||
String id = "createOriginal";
|
||||
String filename = "someName.txt";
|
||||
String contents = "these contents";
|
||||
InputStream bytes = new ByteArrayInputStream(contents.getBytes());
|
||||
|
||||
generalFs.createFile(id, filename, bytes);
|
||||
|
||||
assertFileContents(generalFs, id, filename, contents);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createFileOverwrite() throws IOException {
|
||||
String id = "createOverwrite";
|
||||
String filename = "someName.txt";
|
||||
|
||||
String contents1 = "these contents";
|
||||
InputStream bytes1 = new ByteArrayInputStream(contents1.getBytes());
|
||||
|
||||
String contents2 = "a different string";
|
||||
InputStream bytes2 = new ByteArrayInputStream(contents2.getBytes());
|
||||
|
||||
generalFs.createFile(id, filename, bytes1);
|
||||
generalFs.createFile(id, filename, bytes2);
|
||||
|
||||
assertFileContents(generalFs, id, filename, contents2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createFileConflictingName() throws IOException {
|
||||
String id = "createConflict";
|
||||
String filename1 = "someName.txt";
|
||||
String filename2 = "secondFileName.txt";
|
||||
String contents = "these contents";
|
||||
InputStream bytes = new ByteArrayInputStream(contents.getBytes());
|
||||
|
||||
generalFs.createFile(id, filename1, bytes);
|
||||
try {
|
||||
generalFs.createFile(id, filename2, bytes);
|
||||
fail("Expected FileAlreadyExistsException.");
|
||||
} catch (FileAlreadyExistsException e) {
|
||||
// expected it.
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getFilenameExists() throws IOException {
|
||||
String id = "filenameExists";
|
||||
String filename = "theName.txt";
|
||||
String contents = "the contents";
|
||||
InputStream bytes = new ByteArrayInputStream(contents.getBytes());
|
||||
|
||||
generalFs.createFile(id, filename, bytes);
|
||||
|
||||
assertEquals("filename", filename, generalFs.getFilename(id));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getFilenameDoesntExist() throws IOException {
|
||||
assertNull("null filename", generalFs.getFilename("neverHeardOfIt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getInputStreamFound() throws IOException {
|
||||
String id = "inputStreamExists";
|
||||
String filename = "myFile";
|
||||
String contents = "Some stuff to put into my file.";
|
||||
InputStream bytes = new ByteArrayInputStream(contents.getBytes());
|
||||
|
||||
generalFs.createFile(id, filename, bytes);
|
||||
|
||||
assertFileContents(generalFs, id, filename, contents);
|
||||
assertEquals("getInputStream", contents,
|
||||
readAll(generalFs.getInputStream(id, filename)));
|
||||
}
|
||||
|
||||
@Test(expected = FileNotFoundException.class)
|
||||
public void getInputStreamNotFound() throws IOException {
|
||||
generalFs.getInputStream("notFound", "nothing");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deleteFileExists() throws IOException {
|
||||
String id = "deleteMe";
|
||||
String filename = "deadFile";
|
||||
String contents = "Some stuff to put into my file.";
|
||||
InputStream bytes = new ByteArrayInputStream(contents.getBytes());
|
||||
|
||||
generalFs.createFile(id, filename, bytes);
|
||||
generalFs.deleteFile(id);
|
||||
assertNull("deleted filename", generalFs.getFilename(id));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deleteFileDoesntExist() throws IOException {
|
||||
generalFs.deleteFile("totallyBogus");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exerciseWindowsExclusions() throws FileAlreadyExistsException,
|
||||
IOException {
|
||||
// setLoggerLevel(FileStorageHelper.class, Level.DEBUG);
|
||||
String id = "nul";
|
||||
String filename = "COM1";
|
||||
String contents = "Windows doesn't like certain names.";
|
||||
InputStream bytes = new ByteArrayInputStream(contents.getBytes());
|
||||
|
||||
generalFs.createFile(id, filename, bytes);
|
||||
|
||||
assertFileContents(generalFs, id, filename, contents);
|
||||
assertEquals("filename", filename, generalFs.getFilename(id));
|
||||
assertEquals("getInputStream", contents,
|
||||
readAll(generalFs.getInputStream(id, filename)));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private static FileStorageImpl createFileStorage(String dirName,
|
||||
String... namespaces) throws IOException {
|
||||
File baseDir = new File(tempDir, dirName);
|
||||
baseDir.mkdir();
|
||||
return new FileStorageImpl(baseDir, Arrays.asList(namespaces));
|
||||
}
|
||||
|
||||
private <T> void assertEqualSets(String message, T[] expected,
|
||||
Collection<T> actual) {
|
||||
Set<T> expectedSet = new HashSet<T>(Arrays.asList(expected));
|
||||
if (expectedSet.size() != expected.length) {
|
||||
fail("message: expected array contains duplicate elements: "
|
||||
+ Arrays.deepToString(expected));
|
||||
}
|
||||
|
||||
Set<T> actualSet = new HashSet<T>(actual);
|
||||
if (actualSet.size() != actual.size()) {
|
||||
fail("message: actual collection contains duplicate elements: "
|
||||
+ actual);
|
||||
}
|
||||
|
||||
assertEquals(message, expectedSet, actualSet);
|
||||
}
|
||||
|
||||
/**
|
||||
* This file storage should contain a file with this ID and this name, and
|
||||
* it should have these contents.
|
||||
*/
|
||||
private void assertFileContents(FileStorageImpl fs, String id,
|
||||
String filename, String expectedContents) throws IOException {
|
||||
File rootDir = new File(fs.getBaseDir(), FileStorage.FILE_STORAGE_ROOT);
|
||||
File path = FileStorageHelper.getFullPath(rootDir, id, filename,
|
||||
fs.getNamespaces());
|
||||
|
||||
assertTrue("file exists: " + path, path.exists());
|
||||
|
||||
String actualContents = readFile(path);
|
||||
|
||||
assertEquals("file contents", expectedContents, actualContents);
|
||||
}
|
||||
}
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.filestorage.backend;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.log4j.Level;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
|
||||
/**
|
||||
* Test the FileStorage methods. The zero-argument constructor was tested in
|
||||
* {@link FileStorageFactoryTest}.
|
||||
*/
|
||||
public class FileStorageImplTest extends AbstractTestClass {
|
||||
private static final List<String> EMPTY_NAMESPACES = Collections
|
||||
.emptyList();
|
||||
|
||||
private static File tempDir;
|
||||
private static FileStorageImpl generalFs;
|
||||
|
||||
@BeforeClass
|
||||
public static void createSomeDirectories() throws IOException {
|
||||
tempDir = createTempDirectory(FileStorageImplTest.class.getSimpleName());
|
||||
generalFs = createFileStorage("general");
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void cleanUp() {
|
||||
if (tempDir != null) {
|
||||
purgeDirectoryRecursively(tempDir);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// tests
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void baseDirDoesntExist() throws IOException {
|
||||
File baseDir = new File(tempDir, "doesntExist");
|
||||
new FileStorageImpl(baseDir, EMPTY_NAMESPACES);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void partialInitializationRoot() throws IOException {
|
||||
File baseDir = new File(tempDir, "partialWithRoot");
|
||||
baseDir.mkdir();
|
||||
new File(baseDir, FileStorage.FILE_STORAGE_ROOT).mkdir();
|
||||
|
||||
new FileStorageImpl(baseDir, EMPTY_NAMESPACES);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void partialInitializationNamespaces() throws IOException {
|
||||
File baseDir = new File(tempDir, "partialWithNamespaces");
|
||||
baseDir.mkdir();
|
||||
new File(baseDir, FileStorage.FILE_STORAGE_NAMESPACES_PROPERTIES)
|
||||
.createNewFile();
|
||||
|
||||
new FileStorageImpl(baseDir, EMPTY_NAMESPACES);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void notInitializedNoNamespaces() throws IOException {
|
||||
File baseDir = new File(tempDir, "emptyNoNamespaces");
|
||||
baseDir.mkdir();
|
||||
|
||||
FileStorageImpl fs = new FileStorageImpl(baseDir,
|
||||
new ArrayList<String>());
|
||||
assertEquals("baseDir", baseDir, fs.getBaseDir());
|
||||
assertEqualSets("namespaces", new String[0], fs.getNamespaces()
|
||||
.values());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void notInitializedNamespaces() throws IOException {
|
||||
String[] namespaces = new String[] { "ns1", "ns2" };
|
||||
String dirName = "emptyWithNamespaces";
|
||||
|
||||
FileStorageImpl fs = createFileStorage(dirName, namespaces);
|
||||
|
||||
assertEquals("baseDir", new File(tempDir, dirName), fs.getBaseDir());
|
||||
assertEqualSets("namespaces", namespaces, fs.getNamespaces().values());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void initializedOK() throws IOException {
|
||||
createFileStorage("initializeTwiceTheSame", "ns1", "ns2");
|
||||
createFileStorage("initializeTwiceTheSame", "ns2", "ns1");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void namespaceDisappears() throws IOException {
|
||||
createFileStorage("namespaceDisappears", "ns1", "ns2");
|
||||
FileStorageImpl fs = createFileStorage("namespaceDisappears", "ns2");
|
||||
assertEqualSets("namespaces", new String[] { "ns1", "ns2" }, fs
|
||||
.getNamespaces().values());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void namespaceChanged() throws IOException {
|
||||
setLoggerLevel(FileStorageImpl.class, Level.ERROR);
|
||||
createFileStorage("namespaceChanges", "ns1", "ns2");
|
||||
FileStorageImpl fs = createFileStorage("namespaceChanges", "ns3", "ns1");
|
||||
assertEqualSets("namespaces", new String[] { "ns1", "ns2", "ns3" }, fs
|
||||
.getNamespaces().values());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createFileOriginal() throws IOException {
|
||||
String id = "createOriginal";
|
||||
String filename = "someName.txt";
|
||||
String contents = "these contents";
|
||||
InputStream bytes = new ByteArrayInputStream(contents.getBytes());
|
||||
|
||||
generalFs.createFile(id, filename, bytes);
|
||||
|
||||
assertFileContents(generalFs, id, filename, contents);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createFileOverwrite() throws IOException {
|
||||
String id = "createOverwrite";
|
||||
String filename = "someName.txt";
|
||||
|
||||
String contents1 = "these contents";
|
||||
InputStream bytes1 = new ByteArrayInputStream(contents1.getBytes());
|
||||
|
||||
String contents2 = "a different string";
|
||||
InputStream bytes2 = new ByteArrayInputStream(contents2.getBytes());
|
||||
|
||||
generalFs.createFile(id, filename, bytes1);
|
||||
generalFs.createFile(id, filename, bytes2);
|
||||
|
||||
assertFileContents(generalFs, id, filename, contents2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createFileConflictingName() throws IOException {
|
||||
String id = "createConflict";
|
||||
String filename1 = "someName.txt";
|
||||
String filename2 = "secondFileName.txt";
|
||||
String contents = "these contents";
|
||||
InputStream bytes = new ByteArrayInputStream(contents.getBytes());
|
||||
|
||||
generalFs.createFile(id, filename1, bytes);
|
||||
try {
|
||||
generalFs.createFile(id, filename2, bytes);
|
||||
fail("Expected FileAlreadyExistsException.");
|
||||
} catch (FileAlreadyExistsException e) {
|
||||
// expected it.
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getFilenameExists() throws IOException {
|
||||
String id = "filenameExists";
|
||||
String filename = "theName.txt";
|
||||
String contents = "the contents";
|
||||
InputStream bytes = new ByteArrayInputStream(contents.getBytes());
|
||||
|
||||
generalFs.createFile(id, filename, bytes);
|
||||
|
||||
assertEquals("filename", filename, generalFs.getFilename(id));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getFilenameDoesntExist() throws IOException {
|
||||
assertNull("null filename", generalFs.getFilename("neverHeardOfIt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getInputStreamFound() throws IOException {
|
||||
String id = "inputStreamExists";
|
||||
String filename = "myFile";
|
||||
String contents = "Some stuff to put into my file.";
|
||||
InputStream bytes = new ByteArrayInputStream(contents.getBytes());
|
||||
|
||||
generalFs.createFile(id, filename, bytes);
|
||||
|
||||
assertFileContents(generalFs, id, filename, contents);
|
||||
assertEquals("getInputStream", contents,
|
||||
readAll(generalFs.getInputStream(id, filename)));
|
||||
}
|
||||
|
||||
@Test(expected = FileNotFoundException.class)
|
||||
public void getInputStreamNotFound() throws IOException {
|
||||
generalFs.getInputStream("notFound", "nothing");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deleteFileExists() throws IOException {
|
||||
String id = "deleteMe";
|
||||
String filename = "deadFile";
|
||||
String contents = "Some stuff to put into my file.";
|
||||
InputStream bytes = new ByteArrayInputStream(contents.getBytes());
|
||||
|
||||
generalFs.createFile(id, filename, bytes);
|
||||
generalFs.deleteFile(id);
|
||||
assertNull("deleted filename", generalFs.getFilename(id));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deleteFileDoesntExist() throws IOException {
|
||||
generalFs.deleteFile("totallyBogus");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exerciseWindowsExclusions() throws FileAlreadyExistsException,
|
||||
IOException {
|
||||
// setLoggerLevel(FileStorageHelper.class, Level.DEBUG);
|
||||
String id = "nul";
|
||||
String filename = "COM1";
|
||||
String contents = "Windows doesn't like certain names.";
|
||||
InputStream bytes = new ByteArrayInputStream(contents.getBytes());
|
||||
|
||||
generalFs.createFile(id, filename, bytes);
|
||||
|
||||
assertFileContents(generalFs, id, filename, contents);
|
||||
assertEquals("filename", filename, generalFs.getFilename(id));
|
||||
assertEquals("getInputStream", contents,
|
||||
readAll(generalFs.getInputStream(id, filename)));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private static FileStorageImpl createFileStorage(String dirName,
|
||||
String... namespaces) throws IOException {
|
||||
File baseDir = new File(tempDir, dirName);
|
||||
baseDir.mkdir();
|
||||
return new FileStorageImpl(baseDir, Arrays.asList(namespaces));
|
||||
}
|
||||
|
||||
private <T> void assertEqualSets(String message, T[] expected,
|
||||
Collection<T> actual) {
|
||||
Set<T> expectedSet = new HashSet<T>(Arrays.asList(expected));
|
||||
if (expectedSet.size() != expected.length) {
|
||||
fail("message: expected array contains duplicate elements: "
|
||||
+ Arrays.deepToString(expected));
|
||||
}
|
||||
|
||||
Set<T> actualSet = new HashSet<T>(actual);
|
||||
if (actualSet.size() != actual.size()) {
|
||||
fail("message: actual collection contains duplicate elements: "
|
||||
+ actual);
|
||||
}
|
||||
|
||||
assertEquals(message, expectedSet, actualSet);
|
||||
}
|
||||
|
||||
/**
|
||||
* This file storage should contain a file with this ID and this name, and
|
||||
* it should have these contents.
|
||||
*/
|
||||
private void assertFileContents(FileStorageImpl fs, String id,
|
||||
String filename, String expectedContents) throws IOException {
|
||||
File rootDir = new File(fs.getBaseDir(), FileStorage.FILE_STORAGE_ROOT);
|
||||
File path = FileStorageHelper.getFullPath(rootDir, id, filename,
|
||||
fs.getNamespaces());
|
||||
|
||||
assertTrue("file exists: " + path, path.exists());
|
||||
|
||||
String actualContents = readFile(path);
|
||||
|
||||
assertEquals("file contents", expectedContents, actualContents);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,319 +1,319 @@
|
|||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.startup;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.ServletContextEvent;
|
||||
import javax.servlet.ServletContextListener;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.log4j.Level;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import stubs.javax.servlet.ServletContextStub;
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus.StatusItem;
|
||||
|
||||
/**
|
||||
* TODO
|
||||
*/
|
||||
public class StartupManagerTest extends AbstractTestClass {
|
||||
private static final Log log = LogFactory.getLog(StartupManagerTest.class);
|
||||
|
||||
private ServletContextStub ctx;
|
||||
private ServletContextEvent sce;
|
||||
|
||||
private StartupManager sm;
|
||||
private StartupStatus ss;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
ctx = new ServletContextStub();
|
||||
sce = new ServletContextEvent(ctx);
|
||||
|
||||
sm = new StartupManager();
|
||||
ss = StartupStatus.getBean(ctx);
|
||||
|
||||
// setLoggerLevel(this.getClass(), Level.DEBUG);
|
||||
setLoggerLevel(StartupStatus.class, Level.OFF);
|
||||
setLoggerLevel(StartupManager.class, Level.OFF);
|
||||
}
|
||||
|
||||
@After
|
||||
public void dumpForDebug() {
|
||||
if (log.isDebugEnabled()) {
|
||||
dumpStatus();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noSuchFile() {
|
||||
assertStartupFails((String) null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void emptyFile() {
|
||||
assertStartupSucceeds();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void blankLine() {
|
||||
assertStartupSucceeds(" \n");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void commentLines() {
|
||||
assertStartupSucceeds("# comment line \n"
|
||||
+ " # comment line starting with spaces\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void classDoesNotExist() {
|
||||
assertStartupFails("no.such.class\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void classThrowsExceptionWhenLoading() {
|
||||
assertStartupFails(ThrowsExceptionWhenLoading.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void classIsPrivate() {
|
||||
assertStartupFails(PrivateClass.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noDefaultConstructor() {
|
||||
assertStartupFails(NoDefaultConstructor.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructorIsPrivate() {
|
||||
assertStartupFails(PrivateConstructor.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructorThrowsException() {
|
||||
assertStartupFails(ConstructorThrowsException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void notAServletContextListener() {
|
||||
assertStartupFails(NotAListener.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void listenerThrowsException() {
|
||||
assertStartupFails(InitThrowsException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void listenerSetsFatalStatus() {
|
||||
assertStartupFails(InitSetsFatalStatus.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void success() {
|
||||
String listener1Name = SucceedsWithInfo.class.getName();
|
||||
String listener2Name = SucceedsWithWarning.class.getName();
|
||||
|
||||
assertStartupSucceeds(SucceedsWithInfo.class, SucceedsWithWarning.class);
|
||||
|
||||
// Did they initialize in the correct order?
|
||||
List<StatusItem> items = ss.getStatusItems();
|
||||
assertEquals("how many", 2, items.size());
|
||||
assertEquals("init order 1", listener1Name, items.get(0)
|
||||
.getSourceName());
|
||||
assertEquals("init order 2", listener2Name, items.get(1)
|
||||
.getSourceName());
|
||||
|
||||
sm.contextDestroyed(sce);
|
||||
|
||||
// Did they destroy in reverse order?
|
||||
items = ss.getStatusItems();
|
||||
assertEquals("how many", 4, items.size());
|
||||
assertEquals("destroy order 1", listener2Name, items.get(2)
|
||||
.getSourceName());
|
||||
assertEquals("destroy order 2", listener1Name, items.get(3)
|
||||
.getSourceName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void duplicateListeners() {
|
||||
assertStartupFails(SucceedsWithInfo.class, SucceedsWithWarning.class,
|
||||
SucceedsWithInfo.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dontExecuteAfterFailure() {
|
||||
assertStartupFails(InitThrowsException.class, SucceedsWithInfo.class);
|
||||
|
||||
for (StatusItem item : ss.getStatusItems()) {
|
||||
if (item.getSourceName().equals(SucceedsWithInfo.class.getName())
|
||||
&& (item.getLevel() == StatusItem.Level.NOT_EXECUTED)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
fail("'" + SucceedsWithInfo.class.getName()
|
||||
+ "' should not have been run after '"
|
||||
+ PrivateConstructor.class.getName() + "' failed.");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Helper classes
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
public static class BasicListener implements ServletContextListener {
|
||||
@Override
|
||||
public void contextDestroyed(ServletContextEvent sce) {
|
||||
// does nothing
|
||||
}
|
||||
|
||||
@Override
|
||||
public void contextInitialized(ServletContextEvent sce) {
|
||||
// does nothing
|
||||
}
|
||||
}
|
||||
|
||||
public static class ThrowsExceptionWhenLoading extends BasicListener {
|
||||
static {
|
||||
if (true) {
|
||||
throw new IllegalStateException("can't load me.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class PrivateClass extends BasicListener {
|
||||
// no methods
|
||||
}
|
||||
|
||||
public static class NoDefaultConstructor extends BasicListener {
|
||||
public NoDefaultConstructor(String bogus) {
|
||||
bogus.length();
|
||||
}
|
||||
}
|
||||
|
||||
public static class PrivateConstructor extends BasicListener {
|
||||
private PrivateConstructor() {
|
||||
// does nothing
|
||||
}
|
||||
}
|
||||
|
||||
public static class ConstructorThrowsException extends BasicListener {
|
||||
public ConstructorThrowsException() {
|
||||
if (true) {
|
||||
throw new IllegalStateException("can't load me.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class NotAListener {
|
||||
// no methods
|
||||
}
|
||||
|
||||
public static class InitThrowsException extends BasicListener {
|
||||
@Override
|
||||
public void contextInitialized(ServletContextEvent sce) {
|
||||
throw new IllegalStateException("Initialization failed.");
|
||||
}
|
||||
}
|
||||
|
||||
public static class InitSetsFatalStatus extends BasicListener {
|
||||
@Override
|
||||
public void contextInitialized(ServletContextEvent sce) {
|
||||
StartupStatus.getBean(sce.getServletContext()).fatal(this,
|
||||
"Set fatal status");
|
||||
}
|
||||
}
|
||||
|
||||
public static class SucceedsWithInfo implements ServletContextListener {
|
||||
@Override
|
||||
public void contextInitialized(ServletContextEvent sce) {
|
||||
StartupStatus.getBean(sce.getServletContext()).info(this,
|
||||
"Set info message on init.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void contextDestroyed(ServletContextEvent sce) {
|
||||
StartupStatus.getBean(sce.getServletContext()).info(this,
|
||||
"Set info message on destroy.");
|
||||
}
|
||||
}
|
||||
|
||||
public static class SucceedsWithWarning implements ServletContextListener {
|
||||
@Override
|
||||
public void contextInitialized(ServletContextEvent sce) {
|
||||
StartupStatus.getBean(sce.getServletContext()).warning(this,
|
||||
"Set warning message on init.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void contextDestroyed(ServletContextEvent sce) {
|
||||
StartupStatus.getBean(sce.getServletContext()).warning(this,
|
||||
"Set warning message on destroy.");
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private void assertStartupFails(String fileContents) {
|
||||
if (fileContents != null) {
|
||||
ctx.setMockResource(StartupManager.FILE_OF_STARTUP_LISTENERS,
|
||||
fileContents);
|
||||
}
|
||||
sm.contextInitialized(sce);
|
||||
assertTrue("expecting abort", ss.isStartupAborted());
|
||||
}
|
||||
|
||||
private void assertStartupFails(Class<?>... classes) {
|
||||
assertStartupFails(joinClassNames(classes));
|
||||
}
|
||||
|
||||
private void assertStartupSucceeds(String fileContents) {
|
||||
if (fileContents != null) {
|
||||
ctx.setMockResource(StartupManager.FILE_OF_STARTUP_LISTENERS,
|
||||
fileContents);
|
||||
}
|
||||
sm.contextInitialized(sce);
|
||||
assertFalse("expecting success", ss.isStartupAborted());
|
||||
}
|
||||
|
||||
private void assertStartupSucceeds(Class<?>... classes) {
|
||||
assertStartupSucceeds(joinClassNames(classes));
|
||||
}
|
||||
|
||||
private String joinClassNames(Class<?>[] classes) {
|
||||
if (classes == null) {
|
||||
return null;
|
||||
}
|
||||
if (classes.length == 0) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (int i = 0; i < classes.length; i++) {
|
||||
result.append(classes[i].getName()).append('\n');
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
private void dumpStatus() {
|
||||
List<StatusItem> items = ss.getStatusItems();
|
||||
log.debug("-------------- " + items.size() + " items");
|
||||
for (StatusItem item : items) {
|
||||
log.debug(String.format("%8s %s \n %s \n %s", item.getLevel(),
|
||||
item.getSourceName(), item.getMessage(), item.getCause()));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
|
||||
|
||||
package edu.cornell.mannlib.vitro.webapp.startup;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.ServletContextEvent;
|
||||
import javax.servlet.ServletContextListener;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.log4j.Level;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import stubs.javax.servlet.ServletContextStub;
|
||||
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
|
||||
import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus.StatusItem;
|
||||
|
||||
/**
|
||||
* TODO
|
||||
*/
|
||||
public class StartupManagerTest extends AbstractTestClass {
|
||||
private static final Log log = LogFactory.getLog(StartupManagerTest.class);
|
||||
|
||||
private ServletContextStub ctx;
|
||||
private ServletContextEvent sce;
|
||||
|
||||
private StartupManager sm;
|
||||
private StartupStatus ss;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
ctx = new ServletContextStub();
|
||||
sce = new ServletContextEvent(ctx);
|
||||
|
||||
sm = new StartupManager();
|
||||
ss = StartupStatus.getBean(ctx);
|
||||
|
||||
// setLoggerLevel(this.getClass(), Level.DEBUG);
|
||||
setLoggerLevel(StartupStatus.class, Level.OFF);
|
||||
setLoggerLevel(StartupManager.class, Level.OFF);
|
||||
}
|
||||
|
||||
@After
|
||||
public void dumpForDebug() {
|
||||
if (log.isDebugEnabled()) {
|
||||
dumpStatus();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noSuchFile() {
|
||||
assertStartupFails((String) null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void emptyFile() {
|
||||
assertStartupSucceeds();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void blankLine() {
|
||||
assertStartupSucceeds(" \n");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void commentLines() {
|
||||
assertStartupSucceeds("# comment line \n"
|
||||
+ " # comment line starting with spaces\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void classDoesNotExist() {
|
||||
assertStartupFails("no.such.class\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void classThrowsExceptionWhenLoading() {
|
||||
assertStartupFails(ThrowsExceptionWhenLoading.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void classIsPrivate() {
|
||||
assertStartupFails(PrivateClass.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noDefaultConstructor() {
|
||||
assertStartupFails(NoDefaultConstructor.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructorIsPrivate() {
|
||||
assertStartupFails(PrivateConstructor.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructorThrowsException() {
|
||||
assertStartupFails(ConstructorThrowsException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void notAServletContextListener() {
|
||||
assertStartupFails(NotAListener.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void listenerThrowsException() {
|
||||
assertStartupFails(InitThrowsException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void listenerSetsFatalStatus() {
|
||||
assertStartupFails(InitSetsFatalStatus.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void success() {
|
||||
String listener1Name = SucceedsWithInfo.class.getName();
|
||||
String listener2Name = SucceedsWithWarning.class.getName();
|
||||
|
||||
assertStartupSucceeds(SucceedsWithInfo.class, SucceedsWithWarning.class);
|
||||
|
||||
// Did they initialize in the correct order?
|
||||
List<StatusItem> items = ss.getStatusItems();
|
||||
assertEquals("how many", 2, items.size());
|
||||
assertEquals("init order 1", listener1Name, items.get(0)
|
||||
.getSourceName());
|
||||
assertEquals("init order 2", listener2Name, items.get(1)
|
||||
.getSourceName());
|
||||
|
||||
sm.contextDestroyed(sce);
|
||||
|
||||
// Did they destroy in reverse order?
|
||||
items = ss.getStatusItems();
|
||||
assertEquals("how many", 4, items.size());
|
||||
assertEquals("destroy order 1", listener2Name, items.get(2)
|
||||
.getSourceName());
|
||||
assertEquals("destroy order 2", listener1Name, items.get(3)
|
||||
.getSourceName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void duplicateListeners() {
|
||||
assertStartupFails(SucceedsWithInfo.class, SucceedsWithWarning.class,
|
||||
SucceedsWithInfo.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dontExecuteAfterFailure() {
|
||||
assertStartupFails(InitThrowsException.class, SucceedsWithInfo.class);
|
||||
|
||||
for (StatusItem item : ss.getStatusItems()) {
|
||||
if (item.getSourceName().equals(SucceedsWithInfo.class.getName())
|
||||
&& (item.getLevel() == StatusItem.Level.NOT_EXECUTED)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
fail("'" + SucceedsWithInfo.class.getName()
|
||||
+ "' should not have been run after '"
|
||||
+ PrivateConstructor.class.getName() + "' failed.");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Helper classes
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
public static class BasicListener implements ServletContextListener {
|
||||
@Override
|
||||
public void contextDestroyed(ServletContextEvent sce) {
|
||||
// does nothing
|
||||
}
|
||||
|
||||
@Override
|
||||
public void contextInitialized(ServletContextEvent sce) {
|
||||
// does nothing
|
||||
}
|
||||
}
|
||||
|
||||
public static class ThrowsExceptionWhenLoading extends BasicListener {
|
||||
static {
|
||||
if (true) {
|
||||
throw new IllegalStateException("can't load me.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class PrivateClass extends BasicListener {
|
||||
// no methods
|
||||
}
|
||||
|
||||
public static class NoDefaultConstructor extends BasicListener {
|
||||
public NoDefaultConstructor(String bogus) {
|
||||
bogus.length();
|
||||
}
|
||||
}
|
||||
|
||||
public static class PrivateConstructor extends BasicListener {
|
||||
private PrivateConstructor() {
|
||||
// does nothing
|
||||
}
|
||||
}
|
||||
|
||||
public static class ConstructorThrowsException extends BasicListener {
|
||||
public ConstructorThrowsException() {
|
||||
if (true) {
|
||||
throw new IllegalStateException("can't load me.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class NotAListener {
|
||||
// no methods
|
||||
}
|
||||
|
||||
public static class InitThrowsException extends BasicListener {
|
||||
@Override
|
||||
public void contextInitialized(ServletContextEvent sce) {
|
||||
throw new IllegalStateException("Initialization failed.");
|
||||
}
|
||||
}
|
||||
|
||||
public static class InitSetsFatalStatus extends BasicListener {
|
||||
@Override
|
||||
public void contextInitialized(ServletContextEvent sce) {
|
||||
StartupStatus.getBean(sce.getServletContext()).fatal(this,
|
||||
"Set fatal status");
|
||||
}
|
||||
}
|
||||
|
||||
public static class SucceedsWithInfo implements ServletContextListener {
|
||||
@Override
|
||||
public void contextInitialized(ServletContextEvent sce) {
|
||||
StartupStatus.getBean(sce.getServletContext()).info(this,
|
||||
"Set info message on init.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void contextDestroyed(ServletContextEvent sce) {
|
||||
StartupStatus.getBean(sce.getServletContext()).info(this,
|
||||
"Set info message on destroy.");
|
||||
}
|
||||
}
|
||||
|
||||
public static class SucceedsWithWarning implements ServletContextListener {
|
||||
@Override
|
||||
public void contextInitialized(ServletContextEvent sce) {
|
||||
StartupStatus.getBean(sce.getServletContext()).warning(this,
|
||||
"Set warning message on init.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void contextDestroyed(ServletContextEvent sce) {
|
||||
StartupStatus.getBean(sce.getServletContext()).warning(this,
|
||||
"Set warning message on destroy.");
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Helper methods
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private void assertStartupFails(String fileContents) {
|
||||
if (fileContents != null) {
|
||||
ctx.setMockResource(StartupManager.FILE_OF_STARTUP_LISTENERS,
|
||||
fileContents);
|
||||
}
|
||||
sm.contextInitialized(sce);
|
||||
assertTrue("expecting abort", ss.isStartupAborted());
|
||||
}
|
||||
|
||||
private void assertStartupFails(Class<?>... classes) {
|
||||
assertStartupFails(joinClassNames(classes));
|
||||
}
|
||||
|
||||
private void assertStartupSucceeds(String fileContents) {
|
||||
if (fileContents != null) {
|
||||
ctx.setMockResource(StartupManager.FILE_OF_STARTUP_LISTENERS,
|
||||
fileContents);
|
||||
}
|
||||
sm.contextInitialized(sce);
|
||||
assertFalse("expecting success", ss.isStartupAborted());
|
||||
}
|
||||
|
||||
private void assertStartupSucceeds(Class<?>... classes) {
|
||||
assertStartupSucceeds(joinClassNames(classes));
|
||||
}
|
||||
|
||||
private String joinClassNames(Class<?>[] classes) {
|
||||
if (classes == null) {
|
||||
return null;
|
||||
}
|
||||
if (classes.length == 0) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (int i = 0; i < classes.length; i++) {
|
||||
result.append(classes[i].getName()).append('\n');
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
private void dumpStatus() {
|
||||
List<StatusItem> items = ss.getStatusItems();
|
||||
log.debug("-------------- " + items.size() + " items");
|
||||
for (StatusItem item : items) {
|
||||
log.debug(String.format("%8s %s \n %s \n %s", item.getLevel(),
|
||||
item.getSourceName(), item.getMessage(), item.getCause()));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
#
|
||||
# This is a data file for ConfigurationPropertiesTest.
|
||||
#
|
||||
whichfile = test_config
|
||||
#
|
||||
# This is a data file for ConfigurationPropertiesTest.
|
||||
#
|
||||
whichfile = test_config
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
#
|
||||
# This is a data file for ConfigurationPropertiesTest.
|
||||
#
|
||||
whichfile = test_config_default
|
||||
|
||||
# This ends with a blank, in order to test the removal of whitespace
|
||||
trimmed = whitespace_test\u0020
|
||||
#
|
||||
# This is a data file for ConfigurationPropertiesTest.
|
||||
#
|
||||
whichfile = test_config_default
|
||||
|
||||
# This ends with a blank, in order to test the removal of whitespace
|
||||
trimmed = whitespace_test\u0020
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
#
|
||||
# This is a data file for ConfigurationPropertiesTest.
|
||||
#
|
||||
whichfile = test_config_invalid
|
||||
source = bad Unicode constant \uu1045
|
||||
#
|
||||
# This is a data file for ConfigurationPropertiesTest.
|
||||
#
|
||||
whichfile = test_config_invalid
|
||||
source = bad Unicode constant \uu1045
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue