Normalize line endings VIVO-101

This commit is contained in:
Brian Caruso 2013-07-18 15:19:53 -04:00
parent b097a4d754
commit 54f79f2ea7
587 changed files with 91501 additions and 91501 deletions

View file

@ -1,3 +1,3 @@
# Tell Apache Commons Logging that we want to use Log4J for the unit tests,
# even if other logging systems are available.
org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
# Tell Apache Commons Logging that we want to use Log4J for the unit tests,
# even if other logging systems are available.
org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger

View file

@ -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");
}
}
}

View file

@ -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, "");
}
}
}

View file

@ -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, "");
}
}
}

View file

@ -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());
}
}

View file

@ -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>

View file

@ -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);
}
}
}

View file

@ -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());
}
}

View file

@ -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);
}
}

View file

@ -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);
}
}

View file

@ -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);
}
}

View file

@ -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" ;
.

View file

@ -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.");
}
}

View file

@ -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());
}
}

View file

@ -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);
}
}

View file

@ -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);
}
}
}

View file

@ -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 + "]";
}
}
}
}

View file

@ -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;
}
}

View file

@ -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);
}
}

View file

@ -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" ;
.

View file

@ -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));
}
}

View file

@ -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);
}
}

View file

@ -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);
}
}

View file

@ -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);
}
}

View file

@ -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()));
}
}
}

View file

@ -1,4 +1,4 @@
#
# This is a data file for ConfigurationPropertiesTest.
#
whichfile = test_config
#
# This is a data file for ConfigurationPropertiesTest.
#
whichfile = test_config

View file

@ -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

View file

@ -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

View file

@ -1,10 +1,10 @@
#
# A simple Log4J configuration for unit tests.
#
# It's not very important, because the tests themselves will override this
# configuration in AbstractTestClass.initializeLogging().
#
log4j.rootLogger=WARN, AllAppender
log4j.appender.AllAppender=org.apache.log4j.ConsoleAppender
log4j.appender.AllAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.AllAppender.layout.ConversionPattern=%p %t %c - %m%n
#
# A simple Log4J configuration for unit tests.
#
# It's not very important, because the tests themselves will override this
# configuration in AbstractTestClass.initializeLogging().
#
log4j.rootLogger=WARN, AllAppender
log4j.appender.AllAppender=org.apache.log4j.ConsoleAppender
log4j.appender.AllAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.AllAppender.layout.ConversionPattern=%p %t %c - %m%n

View file

@ -1,66 +1,66 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.edu.cornell.mannlib.vitro.webapp.auth.policy.bean;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import edu.cornell.mannlib.vitro.webapp.auth.policy.bean.PropertyRestrictionPolicyHelper;
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel;
/**
* Allow the unit test to specify a variety of restrictions
*/
public class PropertyRestrictionPolicyHelperStub extends
PropertyRestrictionPolicyHelper {
/** Don't prohibit or restrict anything. */
public static PropertyRestrictionPolicyHelper getInstance() {
return getInstance(null, null);
}
/** Prohibit some namespaces. */
public static PropertyRestrictionPolicyHelperStub getInstance(
String[] restrictedNamespaces) {
return getInstance(restrictedNamespaces, null);
}
/**
* Prohibit some namespaces and restrict some properties from modification
* by anybody.
*/
public static PropertyRestrictionPolicyHelperStub getInstance(
String[] restrictedNamespaces, String[] restrictedProperties) {
Set<String> namespaceSet = new HashSet<String>();
if (restrictedNamespaces != null) {
namespaceSet.addAll(Arrays.asList(restrictedNamespaces));
}
Map<String, RoleLevel> thresholdMap = new HashMap<String, RoleLevel>();
if (restrictedProperties != null) {
for (String prop : restrictedProperties) {
thresholdMap.put(prop, RoleLevel.NOBODY);
}
}
return new PropertyRestrictionPolicyHelperStub(namespaceSet, null,
null, thresholdMap);
}
private PropertyRestrictionPolicyHelperStub(
Set<String> modifyRestrictedNamespaces,
Set<String> modifyPermittedExceptions,
Map<String, RoleLevel> displayThresholds,
Map<String, RoleLevel> modifyThresholds) {
super(modifyRestrictedNamespaces, modifyPermittedExceptions,
displayThresholds, modifyThresholds, ModelFactory.createDefaultModel());
}
}
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.edu.cornell.mannlib.vitro.webapp.auth.policy.bean;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import edu.cornell.mannlib.vitro.webapp.auth.policy.bean.PropertyRestrictionPolicyHelper;
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel;
/**
* Allow the unit test to specify a variety of restrictions
*/
public class PropertyRestrictionPolicyHelperStub extends
PropertyRestrictionPolicyHelper {
/** Don't prohibit or restrict anything. */
public static PropertyRestrictionPolicyHelper getInstance() {
return getInstance(null, null);
}
/** Prohibit some namespaces. */
public static PropertyRestrictionPolicyHelperStub getInstance(
String[] restrictedNamespaces) {
return getInstance(restrictedNamespaces, null);
}
/**
* Prohibit some namespaces and restrict some properties from modification
* by anybody.
*/
public static PropertyRestrictionPolicyHelperStub getInstance(
String[] restrictedNamespaces, String[] restrictedProperties) {
Set<String> namespaceSet = new HashSet<String>();
if (restrictedNamespaces != null) {
namespaceSet.addAll(Arrays.asList(restrictedNamespaces));
}
Map<String, RoleLevel> thresholdMap = new HashMap<String, RoleLevel>();
if (restrictedProperties != null) {
for (String prop : restrictedProperties) {
thresholdMap.put(prop, RoleLevel.NOBODY);
}
}
return new PropertyRestrictionPolicyHelperStub(namespaceSet, null,
null, thresholdMap);
}
private PropertyRestrictionPolicyHelperStub(
Set<String> modifyRestrictedNamespaces,
Set<String> modifyPermittedExceptions,
Map<String, RoleLevel> displayThresholds,
Map<String, RoleLevel> modifyThresholds) {
super(modifyRestrictedNamespaces, modifyPermittedExceptions,
displayThresholds, modifyThresholds, ModelFactory.createDefaultModel());
}
}

View file

@ -1,466 +1,466 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.edu.cornell.mannlib.vitro.webapp.beans;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.json.JSONException;
import org.json.JSONObject;
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatementImpl;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatementImpl;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
/**
* Mock the basic functions of Individual for unit tests.
*/
public class IndividualStub implements Individual {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private final String uri;
private final Set<DataPropertyStatement> dpsSet = new HashSet<DataPropertyStatement>();
private final Set<ObjectPropertyStatement> opsSet = new HashSet<ObjectPropertyStatement>();
private final Set<VClass> vClasses = new HashSet<VClass>();
private String name = "NoName";
public IndividualStub(String uri) {
this.uri = uri;
}
public void addDataPropertyStatement(String predicateUri, String object) {
dpsSet.add(new DataPropertyStatementImpl(this.uri, predicateUri, object));
}
public void addObjectPropertyStatement(String predicateUri, String objectUri) {
opsSet.add(new ObjectPropertyStatementImpl(this.uri, predicateUri,
objectUri));
}
public void addPopulatedObjectPropertyStatement(String predicateUri,
String objectUri, Individual object) {
ObjectPropertyStatementImpl stmt = new ObjectPropertyStatementImpl(
this.uri, predicateUri, objectUri);
stmt.setObject(object);
opsSet.add(stmt);
}
public void addVclass(String namespace, String localname, String vClassName) {
vClasses.add(new VClass(namespace, localname, vClassName));
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public String getURI() {
return uri;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public List<DataPropertyStatement> getDataPropertyStatements() {
return new ArrayList<DataPropertyStatement>(dpsSet);
}
@Override
public List<DataPropertyStatement> getDataPropertyStatements(
String propertyUri) {
List<DataPropertyStatement> list = new ArrayList<DataPropertyStatement>();
for (DataPropertyStatement dps : dpsSet) {
if (dps.getDatapropURI().equals(propertyUri)) {
list.add(dps);
}
}
return list;
}
@Override
public String getDataValue(String propertyUri) {
for (DataPropertyStatement dps : dpsSet) {
if (dps.getDatapropURI().equals(propertyUri)) {
return dps.getData();
}
}
return null;
}
@Override
public List<ObjectPropertyStatement> getObjectPropertyStatements() {
return new ArrayList<ObjectPropertyStatement>(opsSet);
}
@Override
public List<ObjectPropertyStatement> getObjectPropertyStatements(
String propertyUri) {
List<ObjectPropertyStatement> list = new ArrayList<ObjectPropertyStatement>();
for (ObjectPropertyStatement ops : opsSet) {
if (ops.getPropertyURI().equals(propertyUri)) {
list.add(ops);
}
}
return list;
}
@Override
public Individual getRelatedIndividual(String propertyUri) {
for (ObjectPropertyStatement ops : opsSet) {
if (ops.getPropertyURI().equals(propertyUri)) {
return ops.getObject();
}
}
return null;
}
@Override
public boolean isVClass(String vclassUri) {
for (VClass vc : vClasses) {
if (vc.getURI().equals(vclassUri)) {
return true;
}
}
return false;
}
@Override
public List<VClass> getVClasses(boolean direct) {
return new ArrayList<VClass>(vClasses);
}
@Override
public void sortForDisplay() {
// does nothing.
}
@Override
public String getLocalName() {
// Useless for now.
return "BOGUS Local Name";
}
@Override
public VClass getVClass() {
for (VClass vc : vClasses) {
return vc;
}
return null;
}
@Override
public String getVClassURI() {
for (VClass vc : vClasses) {
return vc.getURI();
}
return null;
}
@Override
public List<VClass> getVClasses() {
return new ArrayList<VClass>(vClasses);
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public boolean isAnonymous() {
throw new RuntimeException(
"ResourceBean.isAnonymous() not implemented.");
}
@Override
public void setURI(String URI) {
throw new RuntimeException("ResourceBean.setURI() not implemented.");
}
@Override
public String getNamespace() {
throw new RuntimeException(
"ResourceBean.getNamespace() not implemented.");
}
@Override
public void setNamespace(String namespace) {
throw new RuntimeException(
"ResourceBean.setNamespace() not implemented.");
}
@Override
public void setLocalName(String localName) {
throw new RuntimeException(
"ResourceBean.setLocalName() not implemented.");
}
@Override
public RoleLevel getHiddenFromDisplayBelowRoleLevel() {
throw new RuntimeException(
"ResourceBean.getHiddenFromDisplayBelowRoleLevel() not implemented.");
}
@Override
public void setHiddenFromDisplayBelowRoleLevel(RoleLevel eR) {
throw new RuntimeException(
"ResourceBean.setHiddenFromDisplayBelowRoleLevel() not implemented.");
}
@Override
public void setHiddenFromDisplayBelowRoleLevelUsingRoleUri(String roleUri) {
throw new RuntimeException(
"ResourceBean.setHiddenFromDisplayBelowRoleLevelUsingRoleUri() not implemented.");
}
@Override
public RoleLevel getProhibitedFromUpdateBelowRoleLevel() {
throw new RuntimeException(
"ResourceBean.getProhibitedFromUpdateBelowRoleLevel() not implemented.");
}
@Override
public void setProhibitedFromUpdateBelowRoleLevel(RoleLevel eR) {
throw new RuntimeException(
"ResourceBean.setProhibitedFromUpdateBelowRoleLevel() not implemented.");
}
@Override
public void setProhibitedFromUpdateBelowRoleLevelUsingRoleUri(String roleUri) {
throw new RuntimeException(
"ResourceBean.setProhibitedFromUpdateBelowRoleLevelUsingRoleUri() not implemented.");
}
@Override
public int compareTo(Individual o) {
throw new RuntimeException(
"Comparable<Individual>.compareTo() not implemented.");
}
@Override
public List<String> getMostSpecificTypeURIs() {
throw new RuntimeException("Individual.getMostSpecificTypeURIs() not implemented.");
}
@Override
public String getRdfsLabel() {
throw new RuntimeException("Individual.getRdfsLabel() not implemented.");
}
@Override
public void setVClassURI(String in) {
throw new RuntimeException("Individual.setVClassURI() not implemented.");
}
@Override
public Timestamp getModTime() {
throw new RuntimeException("Individual.getModTime() not implemented.");
}
@Override
public void setModTime(Timestamp in) {
throw new RuntimeException("Individual.setModTime() not implemented.");
}
@Override
public List<ObjectProperty> getObjectPropertyList() {
throw new RuntimeException(
"Individual.getObjectPropertyList() not implemented.");
}
@Override
public void setPropertyList(List<ObjectProperty> propertyList) {
throw new RuntimeException(
"Individual.setPropertyList() not implemented.");
}
@Override
public List<ObjectProperty> getPopulatedObjectPropertyList() {
throw new RuntimeException(
"Individual.getPopulatedObjectPropertyList() not implemented.");
}
@Override
public void setPopulatedObjectPropertyList(List<ObjectProperty> propertyList) {
throw new RuntimeException(
"Individual.setPopulatedObjectPropertyList() not implemented.");
}
@Override
public Map<String, ObjectProperty> getObjectPropertyMap() {
throw new RuntimeException(
"Individual.getObjectPropertyMap() not implemented.");
}
@Override
public void setObjectPropertyMap(Map<String, ObjectProperty> propertyMap) {
throw new RuntimeException(
"Individual.setObjectPropertyMap() not implemented.");
}
@Override
public List<DataProperty> getDataPropertyList() {
throw new RuntimeException(
"Individual.getDataPropertyList() not implemented.");
}
@Override
public void setDatatypePropertyList(List<DataProperty> datatypePropertyList) {
throw new RuntimeException(
"Individual.setDatatypePropertyList() not implemented.");
}
@Override
public List<DataProperty> getPopulatedDataPropertyList() {
throw new RuntimeException(
"Individual.getPopulatedDataPropertyList() not implemented.");
}
@Override
public void setPopulatedDataPropertyList(List<DataProperty> dataPropertyList) {
throw new RuntimeException(
"Individual.setPopulatedDataPropertyList() not implemented.");
}
@Override
public Map<String, DataProperty> getDataPropertyMap() {
throw new RuntimeException(
"Individual.getDataPropertyMap() not implemented.");
}
@Override
public void setDataPropertyMap(Map<String, DataProperty> propertyMap) {
throw new RuntimeException(
"Individual.setDataPropertyMap() not implemented.");
}
@Override
public void setDataPropertyStatements(List<DataPropertyStatement> list) {
throw new RuntimeException(
"Individual.setDataPropertyStatements() not implemented.");
}
@Override
public DataPropertyStatement getDataPropertyStatement(String propertyUri) {
throw new RuntimeException(
"Individual.getDataPropertyStatement() not implemented.");
}
@Override
public List<String> getDataValues(String propertyUri) {
throw new RuntimeException(
"Individual.getDataValues() not implemented.");
}
@Override
public void setVClass(VClass class1) {
throw new RuntimeException("Individual.setVClass() not implemented.");
}
@Override
public void setVClasses(List<VClass> vClassList, boolean direct) {
throw new RuntimeException("Individual.setVClasses() not implemented.");
}
@Override
public void setObjectPropertyStatements(List<ObjectPropertyStatement> list) {
throw new RuntimeException(
"Individual.setObjectPropertyStatements() not implemented.");
}
@Override
public List<Individual> getRelatedIndividuals(String propertyUri) {
throw new RuntimeException(
"Individual.getRelatedIndividuals() not implemented.");
}
@Override
public List<DataPropertyStatement> getExternalIds() {
throw new RuntimeException(
"Individual.getExternalIds() not implemented.");
}
@Override
public void setExternalIds(List<DataPropertyStatement> externalIds) {
throw new RuntimeException(
"Individual.setExternalIds() not implemented.");
}
@Override
public void setMainImageUri(String mainImageUri) {
throw new RuntimeException(
"Individual.setMainImageUri() not implemented.");
}
@Override
public String getMainImageUri() {
throw new RuntimeException(
"Individual.getMainImageUri() not implemented.");
}
@Override
public String getImageUrl() {
throw new RuntimeException("Individual.getImageUrl() not implemented.");
}
@Override
public String getThumbUrl() {
throw new RuntimeException("Individual.getThumbUrl() not implemented.");
}
@Override
public boolean hasThumb() {
throw new RuntimeException("Individual.hasThumb() not implemented.");
}
@Override
public JSONObject toJSON() throws JSONException {
throw new RuntimeException("Individual.toJSON() not implemented.");
}
@Override
public Float getSearchBoost() {
throw new RuntimeException(
"Individual.getSearchBoost() not implemented.");
}
@Override
public void setSearchBoost(Float boost) {
throw new RuntimeException(
"Individual.setSearchBoost() not implemented.");
}
@Override
public String getSearchSnippet() {
throw new RuntimeException(
"Individual.getSearchSnippet() not implemented.");
}
@Override
public void setSearchSnippet(String snippet) {
throw new RuntimeException(
"Individual.setSearchSnippet() not implemented.");
}
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.edu.cornell.mannlib.vitro.webapp.beans;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.json.JSONException;
import org.json.JSONObject;
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatementImpl;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatementImpl;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
/**
* Mock the basic functions of Individual for unit tests.
*/
public class IndividualStub implements Individual {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private final String uri;
private final Set<DataPropertyStatement> dpsSet = new HashSet<DataPropertyStatement>();
private final Set<ObjectPropertyStatement> opsSet = new HashSet<ObjectPropertyStatement>();
private final Set<VClass> vClasses = new HashSet<VClass>();
private String name = "NoName";
public IndividualStub(String uri) {
this.uri = uri;
}
public void addDataPropertyStatement(String predicateUri, String object) {
dpsSet.add(new DataPropertyStatementImpl(this.uri, predicateUri, object));
}
public void addObjectPropertyStatement(String predicateUri, String objectUri) {
opsSet.add(new ObjectPropertyStatementImpl(this.uri, predicateUri,
objectUri));
}
public void addPopulatedObjectPropertyStatement(String predicateUri,
String objectUri, Individual object) {
ObjectPropertyStatementImpl stmt = new ObjectPropertyStatementImpl(
this.uri, predicateUri, objectUri);
stmt.setObject(object);
opsSet.add(stmt);
}
public void addVclass(String namespace, String localname, String vClassName) {
vClasses.add(new VClass(namespace, localname, vClassName));
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public String getURI() {
return uri;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public List<DataPropertyStatement> getDataPropertyStatements() {
return new ArrayList<DataPropertyStatement>(dpsSet);
}
@Override
public List<DataPropertyStatement> getDataPropertyStatements(
String propertyUri) {
List<DataPropertyStatement> list = new ArrayList<DataPropertyStatement>();
for (DataPropertyStatement dps : dpsSet) {
if (dps.getDatapropURI().equals(propertyUri)) {
list.add(dps);
}
}
return list;
}
@Override
public String getDataValue(String propertyUri) {
for (DataPropertyStatement dps : dpsSet) {
if (dps.getDatapropURI().equals(propertyUri)) {
return dps.getData();
}
}
return null;
}
@Override
public List<ObjectPropertyStatement> getObjectPropertyStatements() {
return new ArrayList<ObjectPropertyStatement>(opsSet);
}
@Override
public List<ObjectPropertyStatement> getObjectPropertyStatements(
String propertyUri) {
List<ObjectPropertyStatement> list = new ArrayList<ObjectPropertyStatement>();
for (ObjectPropertyStatement ops : opsSet) {
if (ops.getPropertyURI().equals(propertyUri)) {
list.add(ops);
}
}
return list;
}
@Override
public Individual getRelatedIndividual(String propertyUri) {
for (ObjectPropertyStatement ops : opsSet) {
if (ops.getPropertyURI().equals(propertyUri)) {
return ops.getObject();
}
}
return null;
}
@Override
public boolean isVClass(String vclassUri) {
for (VClass vc : vClasses) {
if (vc.getURI().equals(vclassUri)) {
return true;
}
}
return false;
}
@Override
public List<VClass> getVClasses(boolean direct) {
return new ArrayList<VClass>(vClasses);
}
@Override
public void sortForDisplay() {
// does nothing.
}
@Override
public String getLocalName() {
// Useless for now.
return "BOGUS Local Name";
}
@Override
public VClass getVClass() {
for (VClass vc : vClasses) {
return vc;
}
return null;
}
@Override
public String getVClassURI() {
for (VClass vc : vClasses) {
return vc.getURI();
}
return null;
}
@Override
public List<VClass> getVClasses() {
return new ArrayList<VClass>(vClasses);
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public boolean isAnonymous() {
throw new RuntimeException(
"ResourceBean.isAnonymous() not implemented.");
}
@Override
public void setURI(String URI) {
throw new RuntimeException("ResourceBean.setURI() not implemented.");
}
@Override
public String getNamespace() {
throw new RuntimeException(
"ResourceBean.getNamespace() not implemented.");
}
@Override
public void setNamespace(String namespace) {
throw new RuntimeException(
"ResourceBean.setNamespace() not implemented.");
}
@Override
public void setLocalName(String localName) {
throw new RuntimeException(
"ResourceBean.setLocalName() not implemented.");
}
@Override
public RoleLevel getHiddenFromDisplayBelowRoleLevel() {
throw new RuntimeException(
"ResourceBean.getHiddenFromDisplayBelowRoleLevel() not implemented.");
}
@Override
public void setHiddenFromDisplayBelowRoleLevel(RoleLevel eR) {
throw new RuntimeException(
"ResourceBean.setHiddenFromDisplayBelowRoleLevel() not implemented.");
}
@Override
public void setHiddenFromDisplayBelowRoleLevelUsingRoleUri(String roleUri) {
throw new RuntimeException(
"ResourceBean.setHiddenFromDisplayBelowRoleLevelUsingRoleUri() not implemented.");
}
@Override
public RoleLevel getProhibitedFromUpdateBelowRoleLevel() {
throw new RuntimeException(
"ResourceBean.getProhibitedFromUpdateBelowRoleLevel() not implemented.");
}
@Override
public void setProhibitedFromUpdateBelowRoleLevel(RoleLevel eR) {
throw new RuntimeException(
"ResourceBean.setProhibitedFromUpdateBelowRoleLevel() not implemented.");
}
@Override
public void setProhibitedFromUpdateBelowRoleLevelUsingRoleUri(String roleUri) {
throw new RuntimeException(
"ResourceBean.setProhibitedFromUpdateBelowRoleLevelUsingRoleUri() not implemented.");
}
@Override
public int compareTo(Individual o) {
throw new RuntimeException(
"Comparable<Individual>.compareTo() not implemented.");
}
@Override
public List<String> getMostSpecificTypeURIs() {
throw new RuntimeException("Individual.getMostSpecificTypeURIs() not implemented.");
}
@Override
public String getRdfsLabel() {
throw new RuntimeException("Individual.getRdfsLabel() not implemented.");
}
@Override
public void setVClassURI(String in) {
throw new RuntimeException("Individual.setVClassURI() not implemented.");
}
@Override
public Timestamp getModTime() {
throw new RuntimeException("Individual.getModTime() not implemented.");
}
@Override
public void setModTime(Timestamp in) {
throw new RuntimeException("Individual.setModTime() not implemented.");
}
@Override
public List<ObjectProperty> getObjectPropertyList() {
throw new RuntimeException(
"Individual.getObjectPropertyList() not implemented.");
}
@Override
public void setPropertyList(List<ObjectProperty> propertyList) {
throw new RuntimeException(
"Individual.setPropertyList() not implemented.");
}
@Override
public List<ObjectProperty> getPopulatedObjectPropertyList() {
throw new RuntimeException(
"Individual.getPopulatedObjectPropertyList() not implemented.");
}
@Override
public void setPopulatedObjectPropertyList(List<ObjectProperty> propertyList) {
throw new RuntimeException(
"Individual.setPopulatedObjectPropertyList() not implemented.");
}
@Override
public Map<String, ObjectProperty> getObjectPropertyMap() {
throw new RuntimeException(
"Individual.getObjectPropertyMap() not implemented.");
}
@Override
public void setObjectPropertyMap(Map<String, ObjectProperty> propertyMap) {
throw new RuntimeException(
"Individual.setObjectPropertyMap() not implemented.");
}
@Override
public List<DataProperty> getDataPropertyList() {
throw new RuntimeException(
"Individual.getDataPropertyList() not implemented.");
}
@Override
public void setDatatypePropertyList(List<DataProperty> datatypePropertyList) {
throw new RuntimeException(
"Individual.setDatatypePropertyList() not implemented.");
}
@Override
public List<DataProperty> getPopulatedDataPropertyList() {
throw new RuntimeException(
"Individual.getPopulatedDataPropertyList() not implemented.");
}
@Override
public void setPopulatedDataPropertyList(List<DataProperty> dataPropertyList) {
throw new RuntimeException(
"Individual.setPopulatedDataPropertyList() not implemented.");
}
@Override
public Map<String, DataProperty> getDataPropertyMap() {
throw new RuntimeException(
"Individual.getDataPropertyMap() not implemented.");
}
@Override
public void setDataPropertyMap(Map<String, DataProperty> propertyMap) {
throw new RuntimeException(
"Individual.setDataPropertyMap() not implemented.");
}
@Override
public void setDataPropertyStatements(List<DataPropertyStatement> list) {
throw new RuntimeException(
"Individual.setDataPropertyStatements() not implemented.");
}
@Override
public DataPropertyStatement getDataPropertyStatement(String propertyUri) {
throw new RuntimeException(
"Individual.getDataPropertyStatement() not implemented.");
}
@Override
public List<String> getDataValues(String propertyUri) {
throw new RuntimeException(
"Individual.getDataValues() not implemented.");
}
@Override
public void setVClass(VClass class1) {
throw new RuntimeException("Individual.setVClass() not implemented.");
}
@Override
public void setVClasses(List<VClass> vClassList, boolean direct) {
throw new RuntimeException("Individual.setVClasses() not implemented.");
}
@Override
public void setObjectPropertyStatements(List<ObjectPropertyStatement> list) {
throw new RuntimeException(
"Individual.setObjectPropertyStatements() not implemented.");
}
@Override
public List<Individual> getRelatedIndividuals(String propertyUri) {
throw new RuntimeException(
"Individual.getRelatedIndividuals() not implemented.");
}
@Override
public List<DataPropertyStatement> getExternalIds() {
throw new RuntimeException(
"Individual.getExternalIds() not implemented.");
}
@Override
public void setExternalIds(List<DataPropertyStatement> externalIds) {
throw new RuntimeException(
"Individual.setExternalIds() not implemented.");
}
@Override
public void setMainImageUri(String mainImageUri) {
throw new RuntimeException(
"Individual.setMainImageUri() not implemented.");
}
@Override
public String getMainImageUri() {
throw new RuntimeException(
"Individual.getMainImageUri() not implemented.");
}
@Override
public String getImageUrl() {
throw new RuntimeException("Individual.getImageUrl() not implemented.");
}
@Override
public String getThumbUrl() {
throw new RuntimeException("Individual.getThumbUrl() not implemented.");
}
@Override
public boolean hasThumb() {
throw new RuntimeException("Individual.hasThumb() not implemented.");
}
@Override
public JSONObject toJSON() throws JSONException {
throw new RuntimeException("Individual.toJSON() not implemented.");
}
@Override
public Float getSearchBoost() {
throw new RuntimeException(
"Individual.getSearchBoost() not implemented.");
}
@Override
public void setSearchBoost(Float boost) {
throw new RuntimeException(
"Individual.setSearchBoost() not implemented.");
}
@Override
public String getSearchSnippet() {
throw new RuntimeException(
"Individual.getSearchSnippet() not implemented.");
}
@Override
public void setSearchSnippet(String snippet) {
throw new RuntimeException(
"Individual.setSearchSnippet() not implemented.");
}
}

View file

@ -1,66 +1,66 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.edu.cornell.mannlib.vitro.webapp.config;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties;
/**
* A version of ConfigurationProperties that we can use for unit tests. Unlike
* the basic implementation, this starts as an empty map, and allows the user to
* add properties as desired.
*
* Call setBean() to store these properties in the ServletContext.
*/
public class ConfigurationPropertiesStub extends ConfigurationProperties {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private final Map<String, String> propertyMap = new HashMap<String, String>();
public void setProperty(String key, String value) {
propertyMap.put(key, value);
}
public void setBean(ServletContext ctx) {
setBean(ctx, this);
}
@Override
public String toString() {
return "ConfigurationPropertiesStub[map=" + propertyMap + "]";
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public String getProperty(String key) {
return propertyMap.get(key);
}
@Override
public String getProperty(String key, String defaultValue) {
if (propertyMap.containsKey(key)) {
return propertyMap.get(key);
} else {
return defaultValue;
}
}
@Override
public Map<String, String> getPropertyMap() {
return new HashMap<String, String>(propertyMap);
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
}
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.edu.cornell.mannlib.vitro.webapp.config;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties;
/**
* A version of ConfigurationProperties that we can use for unit tests. Unlike
* the basic implementation, this starts as an empty map, and allows the user to
* add properties as desired.
*
* Call setBean() to store these properties in the ServletContext.
*/
public class ConfigurationPropertiesStub extends ConfigurationProperties {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private final Map<String, String> propertyMap = new HashMap<String, String>();
public void setProperty(String key, String value) {
propertyMap.put(key, value);
}
public void setBean(ServletContext ctx) {
setBean(ctx, this);
}
@Override
public String toString() {
return "ConfigurationPropertiesStub[map=" + propertyMap + "]";
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public String getProperty(String key) {
return propertyMap.get(key);
}
@Override
public String getProperty(String key, String defaultValue) {
if (propertyMap.containsKey(key)) {
return propertyMap.get(key);
} else {
return defaultValue;
}
}
@Override
public Map<String, String> getPropertyMap() {
return new HashMap<String, String>(propertyMap);
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
}

View file

@ -1,280 +1,280 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.edu.cornell.mannlib.vitro.webapp.dao;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.InsertException;
/**
* A minimal implementation of the DataPropertyDao.
*
* I have only implemented the methods that I needed. Feel free to implement
* others.
*/
public class DataPropertyDaoStub implements DataPropertyDao {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private final Map<String, DataProperty> dpMap = new HashMap<String, DataProperty>();
private final Map<String, String> configFilesMap = new HashMap<String, String>();
public void addDataProperty(DataProperty dataProperty) {
if (dataProperty == null) {
throw new NullPointerException("dataProperty may not be null.");
}
String uri = dataProperty.getURI();
if (uri == null) {
throw new NullPointerException("uri may not be null.");
}
dpMap.put(uri, dataProperty);
}
public void setCustomListViewConfigFileName(DataProperty property, String filename) {
if (property == null) {
throw new NullPointerException("property may not be null.");
}
String uri = property.getURI();
if (uri == null) {
throw new NullPointerException("uri may not be null.");
}
configFilesMap.put(uri, filename);
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public DataProperty getDataPropertyByURI(String dataPropertyURI) {
return dpMap.get(dataPropertyURI);
}
@Override
public String getCustomListViewConfigFileName(DataProperty dataProperty) {
if (dataProperty == null) {
return null;
}
String uri = dataProperty.getURI();
if (uri == null) {
return null;
}
return configFilesMap.get(uri);
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public void addSuperproperty(Property property, Property superproperty) {
throw new RuntimeException(
"PropertyDao.addSuperproperty() not implemented.");
}
@Override
public void addSuperproperty(String propertyURI, String superpropertyURI) {
throw new RuntimeException(
"PropertyDao.addSuperproperty() not implemented.");
}
@Override
public void removeSuperproperty(Property property, Property superproperty) {
throw new RuntimeException(
"PropertyDao.removeSuperproperty() not implemented.");
}
@Override
public void removeSuperproperty(String propertyURI, String superpropertyURI) {
throw new RuntimeException(
"PropertyDao.removeSuperproperty() not implemented.");
}
@Override
public void addSubproperty(Property property, Property subproperty) {
throw new RuntimeException(
"PropertyDao.addSubproperty() not implemented.");
}
@Override
public void addSubproperty(String propertyURI, String subpropertyURI) {
throw new RuntimeException(
"PropertyDao.addSubproperty() not implemented.");
}
@Override
public void removeSubproperty(Property property, Property subproperty) {
throw new RuntimeException(
"PropertyDao.removeSubproperty() not implemented.");
}
@Override
public void removeSubproperty(String propertyURI, String subpropertyURI) {
throw new RuntimeException(
"PropertyDao.removeSubproperty() not implemented.");
}
@Override
public void addEquivalentProperty(String propertyURI,
String equivalentPropertyURI) {
throw new RuntimeException(
"PropertyDao.addEquivalentProperty() not implemented.");
}
@Override
public void addEquivalentProperty(Property property,
Property equivalentProperty) {
throw new RuntimeException(
"PropertyDao.addEquivalentProperty() not implemented.");
}
@Override
public void removeEquivalentProperty(String propertyURI,
String equivalentPropertyURI) {
throw new RuntimeException(
"PropertyDao.removeEquivalentProperty() not implemented.");
}
@Override
public void removeEquivalentProperty(Property property,
Property equivalentProperty) {
throw new RuntimeException(
"PropertyDao.removeEquivalentProperty() not implemented.");
}
@Override
public List<String> getSubPropertyURIs(String propertyURI) {
throw new RuntimeException(
"PropertyDao.getSubPropertyURIs() not implemented.");
}
@Override
public List<String> getAllSubPropertyURIs(String propertyURI) {
throw new RuntimeException(
"PropertyDao.getAllSubPropertyURIs() not implemented.");
}
@Override
public List<String> getSuperPropertyURIs(String propertyURI, boolean direct) {
throw new RuntimeException(
"PropertyDao.getSuperPropertyURIs() not implemented.");
}
@Override
public List<String> getAllSuperPropertyURIs(String propertyURI) {
throw new RuntimeException(
"PropertyDao.getAllSuperPropertyURIs() not implemented.");
}
@Override
public List<String> getEquivalentPropertyURIs(String propertyURI) {
throw new RuntimeException(
"PropertyDao.getEquivalentPropertyURIs() not implemented.");
}
@Override
public List<VClass> getClassesWithRestrictionOnProperty(String propertyURI) {
throw new RuntimeException(
"PropertyDao.getClassesWithRestrictionOnProperty() not implemented.");
}
@Override
public List getAllDataProperties() {
throw new RuntimeException(
"DataPropertyDao.getAllDataProperties() not implemented.");
}
@Override
public List getAllExternalIdDataProperties() {
throw new RuntimeException(
"DataPropertyDao.getAllExternalIdDataProperties() not implemented.");
}
@Override
public void fillDataPropertiesForIndividual(Individual individual) {
throw new RuntimeException(
"DataPropertyDao.fillDataPropertiesForIndividual() not implemented.");
}
@Override
public List<DataProperty> getDataPropertiesForVClass(String vClassURI) {
throw new RuntimeException(
"DataPropertyDao.getDataPropertiesForVClass() not implemented.");
}
@Override
public Collection<DataProperty> getAllPossibleDatapropsForIndividual(
String individualURI) {
throw new RuntimeException(
"DataPropertyDao.getAllPossibleDatapropsForIndividual() not implemented.");
}
@Override
public String getRequiredDatatypeURI(Individual individual,
DataProperty dataProperty) {
throw new RuntimeException(
"DataPropertyDao.getRequiredDatatypeURI() not implemented.");
}
@Override
public String insertDataProperty(DataProperty dataProperty)
throws InsertException {
throw new RuntimeException(
"DataPropertyDao.insertDataProperty() not implemented.");
}
@Override
public void updateDataProperty(DataProperty dataProperty) {
throw new RuntimeException(
"DataPropertyDao.updateDataProperty() not implemented.");
}
@Override
public void deleteDataProperty(DataProperty dataProperty) {
throw new RuntimeException(
"DataPropertyDao.deleteDataProperty() not implemented.");
}
@Override
public void deleteDataProperty(String dataPropertyURI) {
throw new RuntimeException(
"DataPropertyDao.deleteDataProperty() not implemented.");
}
@Override
public List<DataProperty> getRootDataProperties() {
throw new RuntimeException(
"DataPropertyDao.getRootDataProperties() not implemented.");
}
@Override
public boolean annotateDataPropertyAsExternalIdentifier(
String dataPropertyURI) {
throw new RuntimeException(
"DataPropertyDao.annotateDataPropertyAsExternalIdentifier() not implemented.");
}
@Override
public List<DataProperty> getDataPropertyList(Individual subject) {
throw new RuntimeException(
"DataPropertyDao.getDataPropertyList() not implemented.");
}
@Override
public List<DataProperty> getDataPropertyList(String subjectUri) {
throw new RuntimeException(
"DataPropertyDao.getDataPropertyList() not implemented.");
}
}
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.edu.cornell.mannlib.vitro.webapp.dao;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.InsertException;
/**
* A minimal implementation of the DataPropertyDao.
*
* I have only implemented the methods that I needed. Feel free to implement
* others.
*/
public class DataPropertyDaoStub implements DataPropertyDao {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private final Map<String, DataProperty> dpMap = new HashMap<String, DataProperty>();
private final Map<String, String> configFilesMap = new HashMap<String, String>();
public void addDataProperty(DataProperty dataProperty) {
if (dataProperty == null) {
throw new NullPointerException("dataProperty may not be null.");
}
String uri = dataProperty.getURI();
if (uri == null) {
throw new NullPointerException("uri may not be null.");
}
dpMap.put(uri, dataProperty);
}
public void setCustomListViewConfigFileName(DataProperty property, String filename) {
if (property == null) {
throw new NullPointerException("property may not be null.");
}
String uri = property.getURI();
if (uri == null) {
throw new NullPointerException("uri may not be null.");
}
configFilesMap.put(uri, filename);
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public DataProperty getDataPropertyByURI(String dataPropertyURI) {
return dpMap.get(dataPropertyURI);
}
@Override
public String getCustomListViewConfigFileName(DataProperty dataProperty) {
if (dataProperty == null) {
return null;
}
String uri = dataProperty.getURI();
if (uri == null) {
return null;
}
return configFilesMap.get(uri);
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public void addSuperproperty(Property property, Property superproperty) {
throw new RuntimeException(
"PropertyDao.addSuperproperty() not implemented.");
}
@Override
public void addSuperproperty(String propertyURI, String superpropertyURI) {
throw new RuntimeException(
"PropertyDao.addSuperproperty() not implemented.");
}
@Override
public void removeSuperproperty(Property property, Property superproperty) {
throw new RuntimeException(
"PropertyDao.removeSuperproperty() not implemented.");
}
@Override
public void removeSuperproperty(String propertyURI, String superpropertyURI) {
throw new RuntimeException(
"PropertyDao.removeSuperproperty() not implemented.");
}
@Override
public void addSubproperty(Property property, Property subproperty) {
throw new RuntimeException(
"PropertyDao.addSubproperty() not implemented.");
}
@Override
public void addSubproperty(String propertyURI, String subpropertyURI) {
throw new RuntimeException(
"PropertyDao.addSubproperty() not implemented.");
}
@Override
public void removeSubproperty(Property property, Property subproperty) {
throw new RuntimeException(
"PropertyDao.removeSubproperty() not implemented.");
}
@Override
public void removeSubproperty(String propertyURI, String subpropertyURI) {
throw new RuntimeException(
"PropertyDao.removeSubproperty() not implemented.");
}
@Override
public void addEquivalentProperty(String propertyURI,
String equivalentPropertyURI) {
throw new RuntimeException(
"PropertyDao.addEquivalentProperty() not implemented.");
}
@Override
public void addEquivalentProperty(Property property,
Property equivalentProperty) {
throw new RuntimeException(
"PropertyDao.addEquivalentProperty() not implemented.");
}
@Override
public void removeEquivalentProperty(String propertyURI,
String equivalentPropertyURI) {
throw new RuntimeException(
"PropertyDao.removeEquivalentProperty() not implemented.");
}
@Override
public void removeEquivalentProperty(Property property,
Property equivalentProperty) {
throw new RuntimeException(
"PropertyDao.removeEquivalentProperty() not implemented.");
}
@Override
public List<String> getSubPropertyURIs(String propertyURI) {
throw new RuntimeException(
"PropertyDao.getSubPropertyURIs() not implemented.");
}
@Override
public List<String> getAllSubPropertyURIs(String propertyURI) {
throw new RuntimeException(
"PropertyDao.getAllSubPropertyURIs() not implemented.");
}
@Override
public List<String> getSuperPropertyURIs(String propertyURI, boolean direct) {
throw new RuntimeException(
"PropertyDao.getSuperPropertyURIs() not implemented.");
}
@Override
public List<String> getAllSuperPropertyURIs(String propertyURI) {
throw new RuntimeException(
"PropertyDao.getAllSuperPropertyURIs() not implemented.");
}
@Override
public List<String> getEquivalentPropertyURIs(String propertyURI) {
throw new RuntimeException(
"PropertyDao.getEquivalentPropertyURIs() not implemented.");
}
@Override
public List<VClass> getClassesWithRestrictionOnProperty(String propertyURI) {
throw new RuntimeException(
"PropertyDao.getClassesWithRestrictionOnProperty() not implemented.");
}
@Override
public List getAllDataProperties() {
throw new RuntimeException(
"DataPropertyDao.getAllDataProperties() not implemented.");
}
@Override
public List getAllExternalIdDataProperties() {
throw new RuntimeException(
"DataPropertyDao.getAllExternalIdDataProperties() not implemented.");
}
@Override
public void fillDataPropertiesForIndividual(Individual individual) {
throw new RuntimeException(
"DataPropertyDao.fillDataPropertiesForIndividual() not implemented.");
}
@Override
public List<DataProperty> getDataPropertiesForVClass(String vClassURI) {
throw new RuntimeException(
"DataPropertyDao.getDataPropertiesForVClass() not implemented.");
}
@Override
public Collection<DataProperty> getAllPossibleDatapropsForIndividual(
String individualURI) {
throw new RuntimeException(
"DataPropertyDao.getAllPossibleDatapropsForIndividual() not implemented.");
}
@Override
public String getRequiredDatatypeURI(Individual individual,
DataProperty dataProperty) {
throw new RuntimeException(
"DataPropertyDao.getRequiredDatatypeURI() not implemented.");
}
@Override
public String insertDataProperty(DataProperty dataProperty)
throws InsertException {
throw new RuntimeException(
"DataPropertyDao.insertDataProperty() not implemented.");
}
@Override
public void updateDataProperty(DataProperty dataProperty) {
throw new RuntimeException(
"DataPropertyDao.updateDataProperty() not implemented.");
}
@Override
public void deleteDataProperty(DataProperty dataProperty) {
throw new RuntimeException(
"DataPropertyDao.deleteDataProperty() not implemented.");
}
@Override
public void deleteDataProperty(String dataPropertyURI) {
throw new RuntimeException(
"DataPropertyDao.deleteDataProperty() not implemented.");
}
@Override
public List<DataProperty> getRootDataProperties() {
throw new RuntimeException(
"DataPropertyDao.getRootDataProperties() not implemented.");
}
@Override
public boolean annotateDataPropertyAsExternalIdentifier(
String dataPropertyURI) {
throw new RuntimeException(
"DataPropertyDao.annotateDataPropertyAsExternalIdentifier() not implemented.");
}
@Override
public List<DataProperty> getDataPropertyList(Individual subject) {
throw new RuntimeException(
"DataPropertyDao.getDataPropertyList() not implemented.");
}
@Override
public List<DataProperty> getDataPropertyList(String subjectUri) {
throw new RuntimeException(
"DataPropertyDao.getDataPropertyList() not implemented.");
}
}

View file

@ -1,183 +1,183 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.edu.cornell.mannlib.vitro.webapp.dao;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao;
import edu.cornell.mannlib.vitro.webapp.dao.InsertException;
import edu.cornell.mannlib.vitro.webapp.edit.EditLiteral;
/**
* A minimal implementation of the IndividualDao.
*
* I have only implemented the methods that I needed. Feel free to implement
* others.
*/
public class IndividualDaoStub implements IndividualDao {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private final Map<String, Individual> indMap = new HashMap<String, Individual>();
public void addIndividual(Individual individual) {
if (individual == null) {
throw new NullPointerException("individual may not be null.");
}
String uri = individual.getURI();
if (uri == null) {
throw new NullPointerException("uri may not be null.");
}
indMap.put(uri, individual);
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public Individual getIndividualByURI(String individualURI) {
return indMap.get(individualURI);
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public Collection<DataPropertyStatement> getExternalIds(String individualURI) {
throw new RuntimeException(
"IndividualDaoStub.getExternalIds() not implemented.");
}
@Override
public Collection<DataPropertyStatement> getExternalIds(
String individualURI, String dataPropertyURI) {
throw new RuntimeException(
"IndividualDaoStub.getExternalIds() not implemented.");
}
@Override
public void addVClass(String individualURI, String vclassURI) {
throw new RuntimeException(
"IndividualDaoStub.addVClass() not implemented.");
}
@Override
public void removeVClass(String individualURI, String vclassURI) {
throw new RuntimeException(
"IndividualDaoStub.removeVClass() not implemented.");
}
@Override
public List<Individual> getIndividualsByVClass(VClass vclass) {
throw new RuntimeException(
"IndividualDaoStub.getIndividualsByVClass() not implemented.");
}
@Override
public List<Individual> getIndividualsByVClassURI(String vclassURI) {
throw new RuntimeException(
"IndividualDaoStub.getIndividualsByVClassURI() not implemented.");
}
@Override
public List<Individual> getIndividualsByVClassURI(String vclassURI,
int offset, int quantity) {
throw new RuntimeException(
"IndividualDaoStub.getIndividualsByVClassURI() not implemented.");
}
@Override
public String insertNewIndividual(Individual individual)
throws InsertException {
throw new RuntimeException(
"IndividualDaoStub.insertNewIndividual() not implemented.");
}
@Override
public int updateIndividual(Individual individual) {
throw new RuntimeException(
"IndividualDaoStub.updateIndividual() not implemented.");
}
@Override
public int deleteIndividual(String individualURI) {
throw new RuntimeException(
"IndividualDaoStub.deleteIndividual() not implemented.");
}
@Override
public int deleteIndividual(Individual individual) {
throw new RuntimeException(
"IndividualDaoStub.deleteIndividual() not implemented.");
}
@Override
public void markModified(Individual individual) {
throw new RuntimeException(
"IndividualDaoStub.markModified() not implemented.");
}
@Override
public Iterator<String> getAllOfThisTypeIterator() {
throw new RuntimeException(
"IndividualDaoStub.getAllOfThisTypeIterator() not implemented.");
}
@Override
public Iterator<String> getUpdatedSinceIterator(long updatedSince) {
throw new RuntimeException(
"IndividualDaoStub.getUpdatedSinceIterator() not implemented.");
}
@Override
public boolean isIndividualOfClass(String vclassURI, String indURI) {
throw new RuntimeException(
"IndividualDaoStub.isIndividualOfClass() not implemented.");
}
@Override
public List<Individual> getIndividualsByDataProperty(
String dataPropertyUri, String value) {
throw new RuntimeException(
"IndividualDaoStub.getIndividualsByDataProperty() not implemented.");
}
@Override
public List<Individual> getIndividualsByDataProperty(
String dataPropertyUri, String value, String datatypeUri,
String lang) {
throw new RuntimeException(
"IndividualDaoStub.getIndividualsByDataProperty() not implemented.");
}
@Override
public void fillVClassForIndividual(Individual individual) {
throw new RuntimeException(
"IndividualDaoStub.fillVClassForIndividual() not implemented.");
}
@Override
public String getUnusedURI(Individual individual) throws InsertException {
throw new RuntimeException(
"IndividualDaoStub.getUnusedURI() not implemented.");
}
@Override
public EditLiteral getLabelEditLiteral(String individualUri) {
throw new RuntimeException(
"IndividualDaoStub.getLabelLiteral() not implemented.");
}
}
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.edu.cornell.mannlib.vitro.webapp.dao;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao;
import edu.cornell.mannlib.vitro.webapp.dao.InsertException;
import edu.cornell.mannlib.vitro.webapp.edit.EditLiteral;
/**
* A minimal implementation of the IndividualDao.
*
* I have only implemented the methods that I needed. Feel free to implement
* others.
*/
public class IndividualDaoStub implements IndividualDao {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private final Map<String, Individual> indMap = new HashMap<String, Individual>();
public void addIndividual(Individual individual) {
if (individual == null) {
throw new NullPointerException("individual may not be null.");
}
String uri = individual.getURI();
if (uri == null) {
throw new NullPointerException("uri may not be null.");
}
indMap.put(uri, individual);
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public Individual getIndividualByURI(String individualURI) {
return indMap.get(individualURI);
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public Collection<DataPropertyStatement> getExternalIds(String individualURI) {
throw new RuntimeException(
"IndividualDaoStub.getExternalIds() not implemented.");
}
@Override
public Collection<DataPropertyStatement> getExternalIds(
String individualURI, String dataPropertyURI) {
throw new RuntimeException(
"IndividualDaoStub.getExternalIds() not implemented.");
}
@Override
public void addVClass(String individualURI, String vclassURI) {
throw new RuntimeException(
"IndividualDaoStub.addVClass() not implemented.");
}
@Override
public void removeVClass(String individualURI, String vclassURI) {
throw new RuntimeException(
"IndividualDaoStub.removeVClass() not implemented.");
}
@Override
public List<Individual> getIndividualsByVClass(VClass vclass) {
throw new RuntimeException(
"IndividualDaoStub.getIndividualsByVClass() not implemented.");
}
@Override
public List<Individual> getIndividualsByVClassURI(String vclassURI) {
throw new RuntimeException(
"IndividualDaoStub.getIndividualsByVClassURI() not implemented.");
}
@Override
public List<Individual> getIndividualsByVClassURI(String vclassURI,
int offset, int quantity) {
throw new RuntimeException(
"IndividualDaoStub.getIndividualsByVClassURI() not implemented.");
}
@Override
public String insertNewIndividual(Individual individual)
throws InsertException {
throw new RuntimeException(
"IndividualDaoStub.insertNewIndividual() not implemented.");
}
@Override
public int updateIndividual(Individual individual) {
throw new RuntimeException(
"IndividualDaoStub.updateIndividual() not implemented.");
}
@Override
public int deleteIndividual(String individualURI) {
throw new RuntimeException(
"IndividualDaoStub.deleteIndividual() not implemented.");
}
@Override
public int deleteIndividual(Individual individual) {
throw new RuntimeException(
"IndividualDaoStub.deleteIndividual() not implemented.");
}
@Override
public void markModified(Individual individual) {
throw new RuntimeException(
"IndividualDaoStub.markModified() not implemented.");
}
@Override
public Iterator<String> getAllOfThisTypeIterator() {
throw new RuntimeException(
"IndividualDaoStub.getAllOfThisTypeIterator() not implemented.");
}
@Override
public Iterator<String> getUpdatedSinceIterator(long updatedSince) {
throw new RuntimeException(
"IndividualDaoStub.getUpdatedSinceIterator() not implemented.");
}
@Override
public boolean isIndividualOfClass(String vclassURI, String indURI) {
throw new RuntimeException(
"IndividualDaoStub.isIndividualOfClass() not implemented.");
}
@Override
public List<Individual> getIndividualsByDataProperty(
String dataPropertyUri, String value) {
throw new RuntimeException(
"IndividualDaoStub.getIndividualsByDataProperty() not implemented.");
}
@Override
public List<Individual> getIndividualsByDataProperty(
String dataPropertyUri, String value, String datatypeUri,
String lang) {
throw new RuntimeException(
"IndividualDaoStub.getIndividualsByDataProperty() not implemented.");
}
@Override
public void fillVClassForIndividual(Individual individual) {
throw new RuntimeException(
"IndividualDaoStub.fillVClassForIndividual() not implemented.");
}
@Override
public String getUnusedURI(Individual individual) throws InsertException {
throw new RuntimeException(
"IndividualDaoStub.getUnusedURI() not implemented.");
}
@Override
public EditLiteral getLabelEditLiteral(String individualUri) {
throw new RuntimeException(
"IndividualDaoStub.getLabelLiteral() not implemented.");
}
}

View file

@ -1,278 +1,278 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.edu.cornell.mannlib.vitro.webapp.dao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.InsertException;
import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyDao;
/**
* A minimal implementation of the ObjectPropertyDao.
*
* I have only implemented the methods that I needed. Feel free to implement
* others.
*/
public class ObjectPropertyDaoStub implements ObjectPropertyDao {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private final Map<String, ObjectProperty> opMap = new HashMap<String, ObjectProperty>();
private final Map<String, String> configFilesMap = new HashMap<String, String>();
public void addObjectProperty(ObjectProperty property) {
if (property == null) {
throw new NullPointerException("predicate may not be null.");
}
String uri = property.getURI();
if (uri == null) {
throw new NullPointerException("uri may not be null.");
}
opMap.put(uri, property);
}
public void setCustomListViewConfigFileName(ObjectProperty property, String filename) {
if (property == null) {
throw new NullPointerException("property may not be null.");
}
String uri = property.getURI();
if (uri == null) {
throw new NullPointerException("uri may not be null.");
}
configFilesMap.put(uri, filename);
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public ObjectProperty getObjectPropertyByURI(String objectPropertyURI) {
if (objectPropertyURI == null) {
return null;
}
return opMap.get(objectPropertyURI);
}
@Override
public ObjectProperty getObjectPropertyByURIAndRangeURI(String objectPropertyURI, String rangeURI) {
return getObjectPropertyByURI(objectPropertyURI);
}
@Override
public String getCustomListViewConfigFileName(ObjectProperty objectProperty) {
if (objectProperty == null) {
return null;
}
String uri = objectProperty.getURI();
if (uri == null) {
return null;
}
return configFilesMap.get(uri);
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public void addSuperproperty(Property property, Property superproperty) {
throw new RuntimeException(
"ObjectPropertyDaoStub.addSuperproperty() not implemented.");
}
@Override
public void addSuperproperty(String propertyURI, String superpropertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.addSuperproperty() not implemented.");
}
@Override
public void removeSuperproperty(Property property, Property superproperty) {
throw new RuntimeException(
"ObjectPropertyDaoStub.removeSuperproperty() not implemented.");
}
@Override
public void removeSuperproperty(String propertyURI, String superpropertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.removeSuperproperty() not implemented.");
}
@Override
public void addSubproperty(Property property, Property subproperty) {
throw new RuntimeException(
"ObjectPropertyDaoStub.addSubproperty() not implemented.");
}
@Override
public void addSubproperty(String propertyURI, String subpropertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.addSubproperty() not implemented.");
}
@Override
public void removeSubproperty(Property property, Property subproperty) {
throw new RuntimeException(
"ObjectPropertyDaoStub.removeSubproperty() not implemented.");
}
@Override
public void removeSubproperty(String propertyURI, String subpropertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.removeSubproperty() not implemented.");
}
@Override
public void addEquivalentProperty(String propertyURI,
String equivalentPropertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.addEquivalentProperty() not implemented.");
}
@Override
public void addEquivalentProperty(Property property,
Property equivalentProperty) {
throw new RuntimeException(
"ObjectPropertyDaoStub.addEquivalentProperty() not implemented.");
}
@Override
public void removeEquivalentProperty(String propertyURI,
String equivalentPropertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.removeEquivalentProperty() not implemented.");
}
@Override
public void removeEquivalentProperty(Property property,
Property equivalentProperty) {
throw new RuntimeException(
"ObjectPropertyDaoStub.removeEquivalentProperty() not implemented.");
}
@Override
public List<String> getAllSubPropertyURIs(String propertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.getAllSubPropertyURIs() not implemented.");
}
@Override
public List<String> getAllSuperPropertyURIs(String propertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.getAllSuperPropertyURIs() not implemented.");
}
@Override
public List<String> getEquivalentPropertyURIs(String propertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.getEquivalentPropertyURIs() not implemented.");
}
@Override
public List<VClass> getClassesWithRestrictionOnProperty(String propertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.getClassesWithRestrictionOnProperty() not implemented.");
}
@Override
public List<ObjectProperty> getAllObjectProperties() {
throw new RuntimeException(
"ObjectPropertyDaoStub.getAllObjectProperties() not implemented.");
}
@Override
public List<ObjectProperty> getObjectPropertiesForObjectPropertyStatements(
List objectPropertyStatements) {
throw new RuntimeException(
"ObjectPropertyDaoStub.getObjectPropertiesForObjectPropertyStatements() not implemented.");
}
@Override
public List<String> getSuperPropertyURIs(String objectPropertyURI,
boolean direct) {
throw new RuntimeException(
"ObjectPropertyDaoStub.getSuperPropertyURIs() not implemented.");
}
@Override
public List<String> getSubPropertyURIs(String objectPropertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.getSubPropertyURIs() not implemented.");
}
@Override
public List<ObjectPropertyStatement> getStatementsUsingObjectProperty(
ObjectProperty op) {
throw new RuntimeException(
"ObjectPropertyDaoStub.getStatementsUsingObjectProperty() not implemented.");
}
@Override
public void fillObjectPropertiesForIndividual(Individual individual) {
throw new RuntimeException(
"ObjectPropertyDaoStub.fillObjectPropertiesForIndividual() not implemented.");
}
@Override
public int insertObjectProperty(ObjectProperty objectProperty)
throws InsertException {
throw new RuntimeException(
"ObjectPropertyDaoStub.insertObjectProperty() not implemented.");
}
@Override
public void updateObjectProperty(ObjectProperty objectProperty) {
throw new RuntimeException(
"ObjectPropertyDaoStub.updateObjectProperty() not implemented.");
}
@Override
public void deleteObjectProperty(String objectPropertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.deleteObjectProperty() not implemented.");
}
@Override
public void deleteObjectProperty(ObjectProperty objectProperty) {
throw new RuntimeException(
"ObjectPropertyDaoStub.deleteObjectProperty() not implemented.");
}
@Override
public boolean skipEditForm(String predicateURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.skipEditForm() not implemented.");
}
@Override
public List<ObjectProperty> getRootObjectProperties() {
throw new RuntimeException(
"ObjectPropertyDaoStub.getRootObjectProperties() not implemented.");
}
@Override
public List<ObjectProperty> getObjectPropertyList(Individual subject) {
throw new RuntimeException(
"ObjectPropertyDaoStub.getObjectPropertyList() not implemented.");
}
@Override
public List<ObjectProperty> getObjectPropertyList(String subjectUri) {
throw new RuntimeException(
"ObjectPropertyDaoStub.getObjectPropertyList() not implemented.");
}
}
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.edu.cornell.mannlib.vitro.webapp.dao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.InsertException;
import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyDao;
/**
* A minimal implementation of the ObjectPropertyDao.
*
* I have only implemented the methods that I needed. Feel free to implement
* others.
*/
public class ObjectPropertyDaoStub implements ObjectPropertyDao {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private final Map<String, ObjectProperty> opMap = new HashMap<String, ObjectProperty>();
private final Map<String, String> configFilesMap = new HashMap<String, String>();
public void addObjectProperty(ObjectProperty property) {
if (property == null) {
throw new NullPointerException("predicate may not be null.");
}
String uri = property.getURI();
if (uri == null) {
throw new NullPointerException("uri may not be null.");
}
opMap.put(uri, property);
}
public void setCustomListViewConfigFileName(ObjectProperty property, String filename) {
if (property == null) {
throw new NullPointerException("property may not be null.");
}
String uri = property.getURI();
if (uri == null) {
throw new NullPointerException("uri may not be null.");
}
configFilesMap.put(uri, filename);
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public ObjectProperty getObjectPropertyByURI(String objectPropertyURI) {
if (objectPropertyURI == null) {
return null;
}
return opMap.get(objectPropertyURI);
}
@Override
public ObjectProperty getObjectPropertyByURIAndRangeURI(String objectPropertyURI, String rangeURI) {
return getObjectPropertyByURI(objectPropertyURI);
}
@Override
public String getCustomListViewConfigFileName(ObjectProperty objectProperty) {
if (objectProperty == null) {
return null;
}
String uri = objectProperty.getURI();
if (uri == null) {
return null;
}
return configFilesMap.get(uri);
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public void addSuperproperty(Property property, Property superproperty) {
throw new RuntimeException(
"ObjectPropertyDaoStub.addSuperproperty() not implemented.");
}
@Override
public void addSuperproperty(String propertyURI, String superpropertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.addSuperproperty() not implemented.");
}
@Override
public void removeSuperproperty(Property property, Property superproperty) {
throw new RuntimeException(
"ObjectPropertyDaoStub.removeSuperproperty() not implemented.");
}
@Override
public void removeSuperproperty(String propertyURI, String superpropertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.removeSuperproperty() not implemented.");
}
@Override
public void addSubproperty(Property property, Property subproperty) {
throw new RuntimeException(
"ObjectPropertyDaoStub.addSubproperty() not implemented.");
}
@Override
public void addSubproperty(String propertyURI, String subpropertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.addSubproperty() not implemented.");
}
@Override
public void removeSubproperty(Property property, Property subproperty) {
throw new RuntimeException(
"ObjectPropertyDaoStub.removeSubproperty() not implemented.");
}
@Override
public void removeSubproperty(String propertyURI, String subpropertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.removeSubproperty() not implemented.");
}
@Override
public void addEquivalentProperty(String propertyURI,
String equivalentPropertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.addEquivalentProperty() not implemented.");
}
@Override
public void addEquivalentProperty(Property property,
Property equivalentProperty) {
throw new RuntimeException(
"ObjectPropertyDaoStub.addEquivalentProperty() not implemented.");
}
@Override
public void removeEquivalentProperty(String propertyURI,
String equivalentPropertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.removeEquivalentProperty() not implemented.");
}
@Override
public void removeEquivalentProperty(Property property,
Property equivalentProperty) {
throw new RuntimeException(
"ObjectPropertyDaoStub.removeEquivalentProperty() not implemented.");
}
@Override
public List<String> getAllSubPropertyURIs(String propertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.getAllSubPropertyURIs() not implemented.");
}
@Override
public List<String> getAllSuperPropertyURIs(String propertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.getAllSuperPropertyURIs() not implemented.");
}
@Override
public List<String> getEquivalentPropertyURIs(String propertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.getEquivalentPropertyURIs() not implemented.");
}
@Override
public List<VClass> getClassesWithRestrictionOnProperty(String propertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.getClassesWithRestrictionOnProperty() not implemented.");
}
@Override
public List<ObjectProperty> getAllObjectProperties() {
throw new RuntimeException(
"ObjectPropertyDaoStub.getAllObjectProperties() not implemented.");
}
@Override
public List<ObjectProperty> getObjectPropertiesForObjectPropertyStatements(
List objectPropertyStatements) {
throw new RuntimeException(
"ObjectPropertyDaoStub.getObjectPropertiesForObjectPropertyStatements() not implemented.");
}
@Override
public List<String> getSuperPropertyURIs(String objectPropertyURI,
boolean direct) {
throw new RuntimeException(
"ObjectPropertyDaoStub.getSuperPropertyURIs() not implemented.");
}
@Override
public List<String> getSubPropertyURIs(String objectPropertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.getSubPropertyURIs() not implemented.");
}
@Override
public List<ObjectPropertyStatement> getStatementsUsingObjectProperty(
ObjectProperty op) {
throw new RuntimeException(
"ObjectPropertyDaoStub.getStatementsUsingObjectProperty() not implemented.");
}
@Override
public void fillObjectPropertiesForIndividual(Individual individual) {
throw new RuntimeException(
"ObjectPropertyDaoStub.fillObjectPropertiesForIndividual() not implemented.");
}
@Override
public int insertObjectProperty(ObjectProperty objectProperty)
throws InsertException {
throw new RuntimeException(
"ObjectPropertyDaoStub.insertObjectProperty() not implemented.");
}
@Override
public void updateObjectProperty(ObjectProperty objectProperty) {
throw new RuntimeException(
"ObjectPropertyDaoStub.updateObjectProperty() not implemented.");
}
@Override
public void deleteObjectProperty(String objectPropertyURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.deleteObjectProperty() not implemented.");
}
@Override
public void deleteObjectProperty(ObjectProperty objectProperty) {
throw new RuntimeException(
"ObjectPropertyDaoStub.deleteObjectProperty() not implemented.");
}
@Override
public boolean skipEditForm(String predicateURI) {
throw new RuntimeException(
"ObjectPropertyDaoStub.skipEditForm() not implemented.");
}
@Override
public List<ObjectProperty> getRootObjectProperties() {
throw new RuntimeException(
"ObjectPropertyDaoStub.getRootObjectProperties() not implemented.");
}
@Override
public List<ObjectProperty> getObjectPropertyList(Individual subject) {
throw new RuntimeException(
"ObjectPropertyDaoStub.getObjectPropertyList() not implemented.");
}
@Override
public List<ObjectProperty> getObjectPropertyList(String subjectUri) {
throw new RuntimeException(
"ObjectPropertyDaoStub.getObjectPropertyList() not implemented.");
}
}

View file

@ -1,111 +1,111 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.edu.cornell.mannlib.vitro.webapp.dao;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.beans.PermissionSet;
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
import edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDao;
/**
* TODO
*/
public class UserAccountsDaoStub implements UserAccountsDao {
private static final Log log = LogFactory.getLog(UserAccountsDaoStub.class);
private final Map<String, UserAccount> userAccountsByUri = new HashMap<String, UserAccount>();
private final Map<String, PermissionSet> permissionSetsByUri = new HashMap<String, PermissionSet>();
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
public void addUser(UserAccount user) {
userAccountsByUri.put(user.getUri(), user);
}
public void addPermissionSet(PermissionSet ps) {
permissionSetsByUri.put(ps.getUri(), ps);
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public UserAccount getUserAccountByUri(String uri) {
return userAccountsByUri.get(uri);
}
@Override
public Collection<PermissionSet> getAllPermissionSets() {
return new ArrayList<PermissionSet>(permissionSetsByUri.values());
}
@Override
public PermissionSet getPermissionSetByUri(String uri) {
return permissionSetsByUri.get(uri);
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public UserAccount getUserAccountByEmail(String emailAddress) {
throw new RuntimeException(
"UserAccountsDaoStub.getUserAccountByEmail() not implemented.");
}
@Override
public String insertUserAccount(UserAccount userAccount) {
throw new RuntimeException(
"UserAccountsDaoStub.insertUserAccount() not implemented.");
}
@Override
public void updateUserAccount(UserAccount userAccount) {
throw new RuntimeException(
"UserAccountsDaoStub.updateUserAccount() not implemented.");
}
@Override
public void deleteUserAccount(String userAccountUri) {
throw new RuntimeException(
"UserAccountsDaoStub.deleteUserAccount() not implemented.");
}
@Override
public UserAccount getUserAccountByExternalAuthId(String externalAuthId) {
throw new RuntimeException(
"UserAccountsDao.getUserAccountByExternalAuthId() not implemented.");
}
@Override
public Collection<UserAccount> getAllUserAccounts() {
throw new RuntimeException(
"UserAccountsDao.getAllUserAccounts() not implemented.");
}
@Override
public Collection<UserAccount> getUserAccountsWhoProxyForPage(
String profilePageUri) {
throw new RuntimeException(
"UserAccountsDaoStub.getUserAccountsWhoProxyForPage() not implemented.");
}
@Override
public void setProxyAccountsOnProfile(String profilePageUri,
Collection<String> userAccountUris) {
throw new RuntimeException(
"UserAccountsDaoStub.setProxyAccountsOnProfile() not implemented.");
}
}
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.edu.cornell.mannlib.vitro.webapp.dao;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.beans.PermissionSet;
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
import edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDao;
/**
* TODO
*/
public class UserAccountsDaoStub implements UserAccountsDao {
private static final Log log = LogFactory.getLog(UserAccountsDaoStub.class);
private final Map<String, UserAccount> userAccountsByUri = new HashMap<String, UserAccount>();
private final Map<String, PermissionSet> permissionSetsByUri = new HashMap<String, PermissionSet>();
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
public void addUser(UserAccount user) {
userAccountsByUri.put(user.getUri(), user);
}
public void addPermissionSet(PermissionSet ps) {
permissionSetsByUri.put(ps.getUri(), ps);
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public UserAccount getUserAccountByUri(String uri) {
return userAccountsByUri.get(uri);
}
@Override
public Collection<PermissionSet> getAllPermissionSets() {
return new ArrayList<PermissionSet>(permissionSetsByUri.values());
}
@Override
public PermissionSet getPermissionSetByUri(String uri) {
return permissionSetsByUri.get(uri);
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public UserAccount getUserAccountByEmail(String emailAddress) {
throw new RuntimeException(
"UserAccountsDaoStub.getUserAccountByEmail() not implemented.");
}
@Override
public String insertUserAccount(UserAccount userAccount) {
throw new RuntimeException(
"UserAccountsDaoStub.insertUserAccount() not implemented.");
}
@Override
public void updateUserAccount(UserAccount userAccount) {
throw new RuntimeException(
"UserAccountsDaoStub.updateUserAccount() not implemented.");
}
@Override
public void deleteUserAccount(String userAccountUri) {
throw new RuntimeException(
"UserAccountsDaoStub.deleteUserAccount() not implemented.");
}
@Override
public UserAccount getUserAccountByExternalAuthId(String externalAuthId) {
throw new RuntimeException(
"UserAccountsDao.getUserAccountByExternalAuthId() not implemented.");
}
@Override
public Collection<UserAccount> getAllUserAccounts() {
throw new RuntimeException(
"UserAccountsDao.getAllUserAccounts() not implemented.");
}
@Override
public Collection<UserAccount> getUserAccountsWhoProxyForPage(
String profilePageUri) {
throw new RuntimeException(
"UserAccountsDaoStub.getUserAccountsWhoProxyForPage() not implemented.");
}
@Override
public void setProxyAccountsOnProfile(String profilePageUri,
Collection<String> userAccountUris) {
throw new RuntimeException(
"UserAccountsDaoStub.setProxyAccountsOnProfile() not implemented.");
}
}

View file

@ -1,235 +1,235 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.edu.cornell.mannlib.vitro.webapp.dao;
import java.util.List;
import java.util.Map;
import java.util.Set;
import edu.cornell.mannlib.vitro.webapp.dao.ApplicationDao;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyStatementDao;
import edu.cornell.mannlib.vitro.webapp.dao.DatatypeDao;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayModelDao;
import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao;
import edu.cornell.mannlib.vitro.webapp.dao.MenuDao;
import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyStatementDao;
import edu.cornell.mannlib.vitro.webapp.dao.OntologyDao;
import edu.cornell.mannlib.vitro.webapp.dao.PageDao;
import edu.cornell.mannlib.vitro.webapp.dao.PropertyGroupDao;
import edu.cornell.mannlib.vitro.webapp.dao.PropertyInstanceDao;
import edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassGroupDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
/**
* A minimal implementation of the WebappDaoFactory.
*
* I have only implemented the methods that I needed. Feel free to implement
* others.
*/
public class WebappDaoFactoryStub implements WebappDaoFactory {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private String defaultNamespace;
private ApplicationDao applicationDao;
private DataPropertyDao dataPropertyDao;
private IndividualDao individualDao;
private MenuDao menuDao;
private ObjectPropertyDao objectPropertyDao;
private ObjectPropertyStatementDao objectPropertyStatementDao;
private OntologyDao ontologyDao;
private UserAccountsDao userAccountsDao;
private VClassDao vClassDao;
public void setDefaultNamespace(String defaultNamespace) {
this.defaultNamespace = defaultNamespace;
}
public void setApplicationDao(ApplicationDao applicationDao) {
this.applicationDao = applicationDao;
}
public void setDataPropertyDao(DataPropertyDao dataPropertyDao) {
this.dataPropertyDao = dataPropertyDao;
}
public void setIndividualDao(IndividualDao individualDao) {
this.individualDao = individualDao;
}
public void setMenuDao(MenuDao menuDao) {
this.menuDao = menuDao;
}
public void setObjectPropertyDao(ObjectPropertyDao objectPropertyDao) {
this.objectPropertyDao = objectPropertyDao;
}
public void setObjectPropertyStatementDao(ObjectPropertyStatementDao objectPropertyStatementDao) {
this.objectPropertyStatementDao = objectPropertyStatementDao;
}
public void setOntologyDao(OntologyDao ontologyDao) {
this.ontologyDao = ontologyDao;
}
public void setUserAccountsDao(UserAccountsDao userAccountsDao) {
this.userAccountsDao = userAccountsDao;
}
public void setVClassDao(VClassDao vClassDao) {
this.vClassDao = vClassDao;
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public String getDefaultNamespace() {
return this.defaultNamespace;
}
@Override
public ApplicationDao getApplicationDao() {
return this.applicationDao;
}
@Override
public DataPropertyDao getDataPropertyDao() {
return this.dataPropertyDao;
}
@Override
public IndividualDao getIndividualDao() {
return this.individualDao;
}
@Override
public MenuDao getMenuDao() {
return this.menuDao;
}
@Override
public ObjectPropertyDao getObjectPropertyDao() {
return this.objectPropertyDao;
}
@Override
public ObjectPropertyStatementDao getObjectPropertyStatementDao() {
return this.objectPropertyStatementDao; }
@Override
public OntologyDao getOntologyDao() {
return this.ontologyDao;
}
@Override
public UserAccountsDao getUserAccountsDao() {
return this.userAccountsDao;
}
@Override
public VClassDao getVClassDao() {
return this.vClassDao;
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public String checkURI(String uriStr) {
throw new RuntimeException(
"WebappDaoFactory.checkURI() not implemented.");
}
@Override
public String checkURI(String uriStr, boolean checkUniqueness) {
throw new RuntimeException(
"WebappDaoFactory.checkURI() not implemented.");
}
@Override
public Set<String> getNonuserNamespaces() {
throw new RuntimeException(
"WebappDaoFactory.getNonuserNamespaces() not implemented.");
}
@Override
public List<String> getPreferredLanguages() {
throw new RuntimeException(
"WebappDaoFactory.getPreferredLanguages() not implemented.");
}
@Override
public List<String> getCommentsForResource(String resourceURI) {
throw new RuntimeException(
"WebappDaoFactory.getCommentsForResource() not implemented.");
}
@Override
public WebappDaoFactory getUserAwareDaoFactory(String userURI) {
throw new RuntimeException(
"WebappDaoFactory.getUserAwareDaoFactory() not implemented.");
}
@Override
public String getUserURI() {
throw new RuntimeException(
"WebappDaoFactory.getUserURI() not implemented.");
}
@Override
public DatatypeDao getDatatypeDao() {
throw new RuntimeException(
"WebappDaoFactory.getDatatypeDao() not implemented.");
}
@Override
public DataPropertyStatementDao getDataPropertyStatementDao() {
throw new RuntimeException(
"WebappDaoFactory.getDataPropertyStatementDao() not implemented.");
}
@Override
public DisplayModelDao getDisplayModelDao() {
throw new RuntimeException(
"WebappDaoFactory.getDisplayModelDao() not implemented.");
}
@Override
public VClassGroupDao getVClassGroupDao() {
throw new RuntimeException(
"WebappDaoFactory.getVClassGroupDao() not implemented.");
}
@Override
public PropertyGroupDao getPropertyGroupDao() {
throw new RuntimeException(
"WebappDaoFactory.getPropertyGroupDao() not implemented.");
}
@Override
public PropertyInstanceDao getPropertyInstanceDao() {
throw new RuntimeException(
"WebappDaoFactory.getPropertyInstanceDao() not implemented.");
}
@Override
public PageDao getPageDao() {
throw new RuntimeException(
"WebappDaoFactory.getPageDao() not implemented.");
}
@Override
public void close() {
throw new RuntimeException("WebappDaoFactory.close() not implemented.");
}
}
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.edu.cornell.mannlib.vitro.webapp.dao;
import java.util.List;
import java.util.Map;
import java.util.Set;
import edu.cornell.mannlib.vitro.webapp.dao.ApplicationDao;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyStatementDao;
import edu.cornell.mannlib.vitro.webapp.dao.DatatypeDao;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayModelDao;
import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao;
import edu.cornell.mannlib.vitro.webapp.dao.MenuDao;
import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyStatementDao;
import edu.cornell.mannlib.vitro.webapp.dao.OntologyDao;
import edu.cornell.mannlib.vitro.webapp.dao.PageDao;
import edu.cornell.mannlib.vitro.webapp.dao.PropertyGroupDao;
import edu.cornell.mannlib.vitro.webapp.dao.PropertyInstanceDao;
import edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassGroupDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
/**
* A minimal implementation of the WebappDaoFactory.
*
* I have only implemented the methods that I needed. Feel free to implement
* others.
*/
public class WebappDaoFactoryStub implements WebappDaoFactory {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private String defaultNamespace;
private ApplicationDao applicationDao;
private DataPropertyDao dataPropertyDao;
private IndividualDao individualDao;
private MenuDao menuDao;
private ObjectPropertyDao objectPropertyDao;
private ObjectPropertyStatementDao objectPropertyStatementDao;
private OntologyDao ontologyDao;
private UserAccountsDao userAccountsDao;
private VClassDao vClassDao;
public void setDefaultNamespace(String defaultNamespace) {
this.defaultNamespace = defaultNamespace;
}
public void setApplicationDao(ApplicationDao applicationDao) {
this.applicationDao = applicationDao;
}
public void setDataPropertyDao(DataPropertyDao dataPropertyDao) {
this.dataPropertyDao = dataPropertyDao;
}
public void setIndividualDao(IndividualDao individualDao) {
this.individualDao = individualDao;
}
public void setMenuDao(MenuDao menuDao) {
this.menuDao = menuDao;
}
public void setObjectPropertyDao(ObjectPropertyDao objectPropertyDao) {
this.objectPropertyDao = objectPropertyDao;
}
public void setObjectPropertyStatementDao(ObjectPropertyStatementDao objectPropertyStatementDao) {
this.objectPropertyStatementDao = objectPropertyStatementDao;
}
public void setOntologyDao(OntologyDao ontologyDao) {
this.ontologyDao = ontologyDao;
}
public void setUserAccountsDao(UserAccountsDao userAccountsDao) {
this.userAccountsDao = userAccountsDao;
}
public void setVClassDao(VClassDao vClassDao) {
this.vClassDao = vClassDao;
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public String getDefaultNamespace() {
return this.defaultNamespace;
}
@Override
public ApplicationDao getApplicationDao() {
return this.applicationDao;
}
@Override
public DataPropertyDao getDataPropertyDao() {
return this.dataPropertyDao;
}
@Override
public IndividualDao getIndividualDao() {
return this.individualDao;
}
@Override
public MenuDao getMenuDao() {
return this.menuDao;
}
@Override
public ObjectPropertyDao getObjectPropertyDao() {
return this.objectPropertyDao;
}
@Override
public ObjectPropertyStatementDao getObjectPropertyStatementDao() {
return this.objectPropertyStatementDao; }
@Override
public OntologyDao getOntologyDao() {
return this.ontologyDao;
}
@Override
public UserAccountsDao getUserAccountsDao() {
return this.userAccountsDao;
}
@Override
public VClassDao getVClassDao() {
return this.vClassDao;
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public String checkURI(String uriStr) {
throw new RuntimeException(
"WebappDaoFactory.checkURI() not implemented.");
}
@Override
public String checkURI(String uriStr, boolean checkUniqueness) {
throw new RuntimeException(
"WebappDaoFactory.checkURI() not implemented.");
}
@Override
public Set<String> getNonuserNamespaces() {
throw new RuntimeException(
"WebappDaoFactory.getNonuserNamespaces() not implemented.");
}
@Override
public List<String> getPreferredLanguages() {
throw new RuntimeException(
"WebappDaoFactory.getPreferredLanguages() not implemented.");
}
@Override
public List<String> getCommentsForResource(String resourceURI) {
throw new RuntimeException(
"WebappDaoFactory.getCommentsForResource() not implemented.");
}
@Override
public WebappDaoFactory getUserAwareDaoFactory(String userURI) {
throw new RuntimeException(
"WebappDaoFactory.getUserAwareDaoFactory() not implemented.");
}
@Override
public String getUserURI() {
throw new RuntimeException(
"WebappDaoFactory.getUserURI() not implemented.");
}
@Override
public DatatypeDao getDatatypeDao() {
throw new RuntimeException(
"WebappDaoFactory.getDatatypeDao() not implemented.");
}
@Override
public DataPropertyStatementDao getDataPropertyStatementDao() {
throw new RuntimeException(
"WebappDaoFactory.getDataPropertyStatementDao() not implemented.");
}
@Override
public DisplayModelDao getDisplayModelDao() {
throw new RuntimeException(
"WebappDaoFactory.getDisplayModelDao() not implemented.");
}
@Override
public VClassGroupDao getVClassGroupDao() {
throw new RuntimeException(
"WebappDaoFactory.getVClassGroupDao() not implemented.");
}
@Override
public PropertyGroupDao getPropertyGroupDao() {
throw new RuntimeException(
"WebappDaoFactory.getPropertyGroupDao() not implemented.");
}
@Override
public PropertyInstanceDao getPropertyInstanceDao() {
throw new RuntimeException(
"WebappDaoFactory.getPropertyInstanceDao() not implemented.");
}
@Override
public PageDao getPageDao() {
throw new RuntimeException(
"WebappDaoFactory.getPageDao() not implemented.");
}
@Override
public void close() {
throw new RuntimeException("WebappDaoFactory.close() not implemented.");
}
}

View file

@ -1,219 +1,219 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.javax.naming;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
/**
* In order to use this and the other naming stubs.javax.naming classes, do
* this:
*
* <pre>
* System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
* InitialContextFactoryStub.class.getName());
* </pre>
*/
public class ContextStub implements Context {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
/**
* Keep a single context instance for each path.
*/
private static final Map<String, ContextStub> instances = new HashMap<String, ContextStub>();
/**
* Get the context instance for this path. Create one if necessary.
*/
static ContextStub getInstance(String contextPath, InitialContextStub parent) {
if (!instances.containsKey(contextPath)) {
instances.put(contextPath, new ContextStub(contextPath, parent));
}
return instances.get(contextPath);
}
private final String contextPath;
private final InitialContextStub parent;
private ContextStub(String contextPath, InitialContextStub parent) {
this.contextPath = contextPath;
this.parent = parent;
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
/**
* Let the parent handle it.
*/
public void rebind(String name, Object obj) throws NamingException {
if (name == null) {
throw new NullPointerException("ContextStub: name may not be null.");
}
if (isEmpty(name)) {
throw new NamingException("ContextStub: name may not be empty.");
}
parent.rebind(contextPath + "/" + name, obj);
}
/**
* In most cases, just let the parent handle it.
*/
public Object lookup(String name) throws NamingException {
if (name == null) {
throw new NamingException("ContextStub: name may not be null.");
}
if (isEmpty(name)) {
return this;
}
return parent.lookup(contextPath + "/" + name);
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
public Object addToEnvironment(String propName, Object propVal)
throws NamingException {
throw new RuntimeException(
"ContextStub.addToEnvironment() not implemented.");
}
public void bind(Name name, Object obj) throws NamingException {
throw new RuntimeException("ContextStub.bind() not implemented.");
}
public void bind(String name, Object obj) throws NamingException {
throw new RuntimeException("ContextStub.bind() not implemented.");
}
public void close() throws NamingException {
throw new RuntimeException("ContextStub.close() not implemented.");
}
public Name composeName(Name name, Name prefix) throws NamingException {
throw new RuntimeException("ContextStub.composeName() not implemented.");
}
public String composeName(String name, String prefix)
throws NamingException {
throw new RuntimeException("ContextStub.composeName() not implemented.");
}
public Context createSubcontext(Name name) throws NamingException {
throw new RuntimeException(
"ContextStub.createSubcontext() not implemented.");
}
public Context createSubcontext(String name) throws NamingException {
throw new RuntimeException(
"ContextStub.createSubcontext() not implemented.");
}
public void destroySubcontext(Name name) throws NamingException {
throw new RuntimeException(
"ContextStub.destroySubcontext() not implemented.");
}
public void destroySubcontext(String name) throws NamingException {
throw new RuntimeException(
"ContextStub.destroySubcontext() not implemented.");
}
public Hashtable<?, ?> getEnvironment() throws NamingException {
throw new RuntimeException(
"ContextStub.getEnvironment() not implemented.");
}
public String getNameInNamespace() throws NamingException {
throw new RuntimeException(
"ContextStub.getNameInNamespace() not implemented.");
}
public NameParser getNameParser(Name name) throws NamingException {
throw new RuntimeException(
"ContextStub.getNameParser() not implemented.");
}
public NameParser getNameParser(String name) throws NamingException {
throw new RuntimeException(
"ContextStub.getNameParser() not implemented.");
}
public NamingEnumeration<NameClassPair> list(Name name)
throws NamingException {
throw new RuntimeException("ContextStub.list() not implemented.");
}
public NamingEnumeration<NameClassPair> list(String name)
throws NamingException {
throw new RuntimeException("ContextStub.list() not implemented.");
}
public NamingEnumeration<Binding> listBindings(Name name)
throws NamingException {
throw new RuntimeException(
"ContextStub.listBindings() not implemented.");
}
public NamingEnumeration<Binding> listBindings(String name)
throws NamingException {
throw new RuntimeException(
"ContextStub.listBindings() not implemented.");
}
public Object lookup(Name name) throws NamingException {
throw new RuntimeException("ContextStub.lookup() not implemented.");
}
public Object lookupLink(Name name) throws NamingException {
throw new RuntimeException("ContextStub.lookupLink() not implemented.");
}
public Object lookupLink(String name) throws NamingException {
throw new RuntimeException("ContextStub.lookupLink() not implemented.");
}
public void rebind(Name name, Object obj) throws NamingException {
throw new RuntimeException("ContextStub.rebind() not implemented.");
}
public Object removeFromEnvironment(String propName) throws NamingException {
throw new RuntimeException(
"ContextStub.removeFromEnvironment() not implemented.");
}
public void rename(Name oldName, Name newName) throws NamingException {
throw new RuntimeException("ContextStub.rename() not implemented.");
}
public void rename(String oldName, String newName) throws NamingException {
throw new RuntimeException("ContextStub.rename() not implemented.");
}
public void unbind(Name name) throws NamingException {
throw new RuntimeException("ContextStub.unbind() not implemented.");
}
public void unbind(String name) throws NamingException {
throw new RuntimeException("ContextStub.unbind() not implemented.");
}
private boolean isEmpty(String string) {
return (string == null || string.trim().length() == 0);
}
}
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.javax.naming;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
/**
* In order to use this and the other naming stubs.javax.naming classes, do
* this:
*
* <pre>
* System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
* InitialContextFactoryStub.class.getName());
* </pre>
*/
public class ContextStub implements Context {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
/**
* Keep a single context instance for each path.
*/
private static final Map<String, ContextStub> instances = new HashMap<String, ContextStub>();
/**
* Get the context instance for this path. Create one if necessary.
*/
static ContextStub getInstance(String contextPath, InitialContextStub parent) {
if (!instances.containsKey(contextPath)) {
instances.put(contextPath, new ContextStub(contextPath, parent));
}
return instances.get(contextPath);
}
private final String contextPath;
private final InitialContextStub parent;
private ContextStub(String contextPath, InitialContextStub parent) {
this.contextPath = contextPath;
this.parent = parent;
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
/**
* Let the parent handle it.
*/
public void rebind(String name, Object obj) throws NamingException {
if (name == null) {
throw new NullPointerException("ContextStub: name may not be null.");
}
if (isEmpty(name)) {
throw new NamingException("ContextStub: name may not be empty.");
}
parent.rebind(contextPath + "/" + name, obj);
}
/**
* In most cases, just let the parent handle it.
*/
public Object lookup(String name) throws NamingException {
if (name == null) {
throw new NamingException("ContextStub: name may not be null.");
}
if (isEmpty(name)) {
return this;
}
return parent.lookup(contextPath + "/" + name);
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
public Object addToEnvironment(String propName, Object propVal)
throws NamingException {
throw new RuntimeException(
"ContextStub.addToEnvironment() not implemented.");
}
public void bind(Name name, Object obj) throws NamingException {
throw new RuntimeException("ContextStub.bind() not implemented.");
}
public void bind(String name, Object obj) throws NamingException {
throw new RuntimeException("ContextStub.bind() not implemented.");
}
public void close() throws NamingException {
throw new RuntimeException("ContextStub.close() not implemented.");
}
public Name composeName(Name name, Name prefix) throws NamingException {
throw new RuntimeException("ContextStub.composeName() not implemented.");
}
public String composeName(String name, String prefix)
throws NamingException {
throw new RuntimeException("ContextStub.composeName() not implemented.");
}
public Context createSubcontext(Name name) throws NamingException {
throw new RuntimeException(
"ContextStub.createSubcontext() not implemented.");
}
public Context createSubcontext(String name) throws NamingException {
throw new RuntimeException(
"ContextStub.createSubcontext() not implemented.");
}
public void destroySubcontext(Name name) throws NamingException {
throw new RuntimeException(
"ContextStub.destroySubcontext() not implemented.");
}
public void destroySubcontext(String name) throws NamingException {
throw new RuntimeException(
"ContextStub.destroySubcontext() not implemented.");
}
public Hashtable<?, ?> getEnvironment() throws NamingException {
throw new RuntimeException(
"ContextStub.getEnvironment() not implemented.");
}
public String getNameInNamespace() throws NamingException {
throw new RuntimeException(
"ContextStub.getNameInNamespace() not implemented.");
}
public NameParser getNameParser(Name name) throws NamingException {
throw new RuntimeException(
"ContextStub.getNameParser() not implemented.");
}
public NameParser getNameParser(String name) throws NamingException {
throw new RuntimeException(
"ContextStub.getNameParser() not implemented.");
}
public NamingEnumeration<NameClassPair> list(Name name)
throws NamingException {
throw new RuntimeException("ContextStub.list() not implemented.");
}
public NamingEnumeration<NameClassPair> list(String name)
throws NamingException {
throw new RuntimeException("ContextStub.list() not implemented.");
}
public NamingEnumeration<Binding> listBindings(Name name)
throws NamingException {
throw new RuntimeException(
"ContextStub.listBindings() not implemented.");
}
public NamingEnumeration<Binding> listBindings(String name)
throws NamingException {
throw new RuntimeException(
"ContextStub.listBindings() not implemented.");
}
public Object lookup(Name name) throws NamingException {
throw new RuntimeException("ContextStub.lookup() not implemented.");
}
public Object lookupLink(Name name) throws NamingException {
throw new RuntimeException("ContextStub.lookupLink() not implemented.");
}
public Object lookupLink(String name) throws NamingException {
throw new RuntimeException("ContextStub.lookupLink() not implemented.");
}
public void rebind(Name name, Object obj) throws NamingException {
throw new RuntimeException("ContextStub.rebind() not implemented.");
}
public Object removeFromEnvironment(String propName) throws NamingException {
throw new RuntimeException(
"ContextStub.removeFromEnvironment() not implemented.");
}
public void rename(Name oldName, Name newName) throws NamingException {
throw new RuntimeException("ContextStub.rename() not implemented.");
}
public void rename(String oldName, String newName) throws NamingException {
throw new RuntimeException("ContextStub.rename() not implemented.");
}
public void unbind(Name name) throws NamingException {
throw new RuntimeException("ContextStub.unbind() not implemented.");
}
public void unbind(String name) throws NamingException {
throw new RuntimeException("ContextStub.unbind() not implemented.");
}
private boolean isEmpty(String string) {
return (string == null || string.trim().length() == 0);
}
}

View file

@ -1,308 +1,308 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.javax.naming;
import java.util.Hashtable;
import java.util.Map;
import java.util.TreeMap;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
/**
* In order to use this and the other naming stubs.javax.naming classes, do
* this:
*
* <pre>
* System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
* InitialContextFactoryStub.class.getName());
* </pre>
*
* The bindings are static, so you will probablly want to call {@link #reset()}
* before each test.
*/
public class InitialContextStub extends InitialContext {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private static Map<String, Object> bindings = new TreeMap<String, Object>();
/**
* Make sure we start the next test with a fresh instance.
*/
public static void reset() {
bindings.clear();
}
/**
* If we have properties that are bound to a level below this name, then
* this name represents a sub-context.
*/
private boolean isSubContext(String name) {
String path = name.endsWith("/") ? name : name + "/";
for (String key : bindings.keySet()) {
if (key.startsWith(path)) {
return true;
}
}
return false;
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
public InitialContextStub() throws NamingException {
super();
}
@Override
protected void init(Hashtable<?, ?> environment) throws NamingException {
}
@Override
protected Context getURLOrDefaultInitCtx(String name)
throws NamingException {
return super.getURLOrDefaultInitCtx(name);
}
@Override
protected Context getDefaultInitCtx() throws NamingException {
return ContextStub.getInstance("", this);
}
private boolean isEmpty(String string) {
return (string == null || string.trim().length() == 0);
}
@Override
public void bind(String name, Object obj) throws NamingException {
if (name == null) {
throw new NullPointerException(
"InitialContextStub: name may not be null.");
}
if (isEmpty(name)) {
throw new NamingException(
"InitialContextStub: name may not be empty.");
}
if (bindings.containsKey(name)) {
throw new NamingException(
"InitialContextStub: name is already bound.");
}
bindings.put(name, obj);
}
@Override
public void rebind(String name, Object obj) throws NamingException {
if (name == null) {
throw new NullPointerException(
"InitialContextStub: name may not be null.");
}
if (isEmpty(name)) {
throw new NamingException(
"InitialContextStub: name may not be empty.");
}
bindings.put(name, obj);
}
@Override
public Object lookup(String name) throws NamingException {
if (name == null) {
throw new NullPointerException(
"InitialContextStub: name may not be null");
}
if (isEmpty(name)) {
return this;
}
if (bindings.containsKey(name)) {
return bindings.get(name);
}
if (isSubContext(name)) {
return ContextStub.getInstance(name, this);
}
throw new NamingException("InitialContextStub: No binding for '" + name
+ "'");
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public Object addToEnvironment(String propName, Object propVal)
throws NamingException {
throw new RuntimeException(
"InitialContextStub.addToEnvironment() not implemented.");
}
@Override
public void bind(Name name, Object obj) throws NamingException {
throw new RuntimeException("InitialContextStub.bind() not implemented.");
}
@Override
public void close() throws NamingException {
throw new RuntimeException(
"InitialContextStub.close() not implemented.");
}
@Override
public Name composeName(Name name, Name prefix) throws NamingException {
throw new RuntimeException(
"InitialContextStub.composeName() not implemented.");
}
@Override
public String composeName(String name, String prefix)
throws NamingException {
throw new RuntimeException(
"InitialContextStub.composeName() not implemented.");
}
@Override
public Context createSubcontext(Name name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.createSubcontext() not implemented.");
}
@Override
public Context createSubcontext(String name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.createSubcontext() not implemented.");
}
@Override
public void destroySubcontext(Name name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.destroySubcontext() not implemented.");
}
@Override
public void destroySubcontext(String name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.destroySubcontext() not implemented.");
}
@Override
public Hashtable<?, ?> getEnvironment() throws NamingException {
throw new RuntimeException(
"InitialContextStub.getEnvironment() not implemented.");
}
@Override
public String getNameInNamespace() throws NamingException {
throw new RuntimeException(
"InitialContextStub.getNameInNamespace() not implemented.");
}
@Override
public NameParser getNameParser(Name name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.getNameParser() not implemented.");
}
@Override
public NameParser getNameParser(String name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.getNameParser() not implemented.");
}
@Override
protected Context getURLOrDefaultInitCtx(Name name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.getURLOrDefaultInitCtx() not implemented.");
}
@Override
public NamingEnumeration<NameClassPair> list(Name name)
throws NamingException {
throw new RuntimeException("InitialContextStub.list() not implemented.");
}
@Override
public NamingEnumeration<NameClassPair> list(String name)
throws NamingException {
throw new RuntimeException("InitialContextStub.list() not implemented.");
}
@Override
public NamingEnumeration<Binding> listBindings(Name name)
throws NamingException {
throw new RuntimeException(
"InitialContextStub.listBindings() not implemented.");
}
@Override
public NamingEnumeration<Binding> listBindings(String name)
throws NamingException {
throw new RuntimeException(
"InitialContextStub.listBindings() not implemented.");
}
@Override
public Object lookup(Name name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.lookup() not implemented.");
}
@Override
public Object lookupLink(Name name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.lookupLink() not implemented.");
}
@Override
public Object lookupLink(String name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.lookupLink() not implemented.");
}
@Override
public void rebind(Name name, Object obj) throws NamingException {
throw new RuntimeException(
"InitialContextStub.rebind() not implemented.");
}
@Override
public Object removeFromEnvironment(String propName) throws NamingException {
throw new RuntimeException(
"InitialContextStub.removeFromEnvironment() not implemented.");
}
@Override
public void rename(Name oldName, Name newName) throws NamingException {
throw new RuntimeException(
"InitialContextStub.rename() not implemented.");
}
@Override
public void rename(String oldName, String newName) throws NamingException {
throw new RuntimeException(
"InitialContextStub.rename() not implemented.");
}
@Override
public void unbind(Name name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.unbind() not implemented.");
}
@Override
public void unbind(String name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.unbind() not implemented.");
}
}
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.javax.naming;
import java.util.Hashtable;
import java.util.Map;
import java.util.TreeMap;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
/**
* In order to use this and the other naming stubs.javax.naming classes, do
* this:
*
* <pre>
* System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
* InitialContextFactoryStub.class.getName());
* </pre>
*
* The bindings are static, so you will probablly want to call {@link #reset()}
* before each test.
*/
public class InitialContextStub extends InitialContext {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private static Map<String, Object> bindings = new TreeMap<String, Object>();
/**
* Make sure we start the next test with a fresh instance.
*/
public static void reset() {
bindings.clear();
}
/**
* If we have properties that are bound to a level below this name, then
* this name represents a sub-context.
*/
private boolean isSubContext(String name) {
String path = name.endsWith("/") ? name : name + "/";
for (String key : bindings.keySet()) {
if (key.startsWith(path)) {
return true;
}
}
return false;
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
public InitialContextStub() throws NamingException {
super();
}
@Override
protected void init(Hashtable<?, ?> environment) throws NamingException {
}
@Override
protected Context getURLOrDefaultInitCtx(String name)
throws NamingException {
return super.getURLOrDefaultInitCtx(name);
}
@Override
protected Context getDefaultInitCtx() throws NamingException {
return ContextStub.getInstance("", this);
}
private boolean isEmpty(String string) {
return (string == null || string.trim().length() == 0);
}
@Override
public void bind(String name, Object obj) throws NamingException {
if (name == null) {
throw new NullPointerException(
"InitialContextStub: name may not be null.");
}
if (isEmpty(name)) {
throw new NamingException(
"InitialContextStub: name may not be empty.");
}
if (bindings.containsKey(name)) {
throw new NamingException(
"InitialContextStub: name is already bound.");
}
bindings.put(name, obj);
}
@Override
public void rebind(String name, Object obj) throws NamingException {
if (name == null) {
throw new NullPointerException(
"InitialContextStub: name may not be null.");
}
if (isEmpty(name)) {
throw new NamingException(
"InitialContextStub: name may not be empty.");
}
bindings.put(name, obj);
}
@Override
public Object lookup(String name) throws NamingException {
if (name == null) {
throw new NullPointerException(
"InitialContextStub: name may not be null");
}
if (isEmpty(name)) {
return this;
}
if (bindings.containsKey(name)) {
return bindings.get(name);
}
if (isSubContext(name)) {
return ContextStub.getInstance(name, this);
}
throw new NamingException("InitialContextStub: No binding for '" + name
+ "'");
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public Object addToEnvironment(String propName, Object propVal)
throws NamingException {
throw new RuntimeException(
"InitialContextStub.addToEnvironment() not implemented.");
}
@Override
public void bind(Name name, Object obj) throws NamingException {
throw new RuntimeException("InitialContextStub.bind() not implemented.");
}
@Override
public void close() throws NamingException {
throw new RuntimeException(
"InitialContextStub.close() not implemented.");
}
@Override
public Name composeName(Name name, Name prefix) throws NamingException {
throw new RuntimeException(
"InitialContextStub.composeName() not implemented.");
}
@Override
public String composeName(String name, String prefix)
throws NamingException {
throw new RuntimeException(
"InitialContextStub.composeName() not implemented.");
}
@Override
public Context createSubcontext(Name name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.createSubcontext() not implemented.");
}
@Override
public Context createSubcontext(String name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.createSubcontext() not implemented.");
}
@Override
public void destroySubcontext(Name name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.destroySubcontext() not implemented.");
}
@Override
public void destroySubcontext(String name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.destroySubcontext() not implemented.");
}
@Override
public Hashtable<?, ?> getEnvironment() throws NamingException {
throw new RuntimeException(
"InitialContextStub.getEnvironment() not implemented.");
}
@Override
public String getNameInNamespace() throws NamingException {
throw new RuntimeException(
"InitialContextStub.getNameInNamespace() not implemented.");
}
@Override
public NameParser getNameParser(Name name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.getNameParser() not implemented.");
}
@Override
public NameParser getNameParser(String name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.getNameParser() not implemented.");
}
@Override
protected Context getURLOrDefaultInitCtx(Name name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.getURLOrDefaultInitCtx() not implemented.");
}
@Override
public NamingEnumeration<NameClassPair> list(Name name)
throws NamingException {
throw new RuntimeException("InitialContextStub.list() not implemented.");
}
@Override
public NamingEnumeration<NameClassPair> list(String name)
throws NamingException {
throw new RuntimeException("InitialContextStub.list() not implemented.");
}
@Override
public NamingEnumeration<Binding> listBindings(Name name)
throws NamingException {
throw new RuntimeException(
"InitialContextStub.listBindings() not implemented.");
}
@Override
public NamingEnumeration<Binding> listBindings(String name)
throws NamingException {
throw new RuntimeException(
"InitialContextStub.listBindings() not implemented.");
}
@Override
public Object lookup(Name name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.lookup() not implemented.");
}
@Override
public Object lookupLink(Name name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.lookupLink() not implemented.");
}
@Override
public Object lookupLink(String name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.lookupLink() not implemented.");
}
@Override
public void rebind(Name name, Object obj) throws NamingException {
throw new RuntimeException(
"InitialContextStub.rebind() not implemented.");
}
@Override
public Object removeFromEnvironment(String propName) throws NamingException {
throw new RuntimeException(
"InitialContextStub.removeFromEnvironment() not implemented.");
}
@Override
public void rename(Name oldName, Name newName) throws NamingException {
throw new RuntimeException(
"InitialContextStub.rename() not implemented.");
}
@Override
public void rename(String oldName, String newName) throws NamingException {
throw new RuntimeException(
"InitialContextStub.rename() not implemented.");
}
@Override
public void unbind(Name name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.unbind() not implemented.");
}
@Override
public void unbind(String name) throws NamingException {
throw new RuntimeException(
"InitialContextStub.unbind() not implemented.");
}
}

View file

@ -1,30 +1,30 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.javax.naming.spi;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.spi.InitialContextFactory;
import stubs.javax.naming.InitialContextStub;
/**
* In order to use this and the other naming stubs.javax.naming classes, do
* this:
*
* <pre>
* System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
* InitialContextFactoryStub.class.getName());
* </pre>
*/
public class InitialContextFactoryStub implements InitialContextFactory {
/**
* It's just this easy.
*/
public Context getInitialContext(Hashtable<?, ?> environment)
throws NamingException {
return new InitialContextStub();
}
}
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.javax.naming.spi;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.spi.InitialContextFactory;
import stubs.javax.naming.InitialContextStub;
/**
* In order to use this and the other naming stubs.javax.naming classes, do
* this:
*
* <pre>
* System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
* InitialContextFactoryStub.class.getName());
* </pre>
*/
public class InitialContextFactoryStub implements InitialContextFactory {
/**
* It's just this easy.
*/
public Context getInitialContext(Hashtable<?, ?> environment)
throws NamingException {
return new InitialContextStub();
}
}

View file

@ -1,56 +1,56 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.javax.servlet;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
/**
* A simple stub for testing servlets.
*/
public class ServletConfigStub implements ServletConfig {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private ServletContext servletContext;
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public ServletContext getServletContext() {
return servletContext;
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public String getInitParameter(String arg0) {
throw new RuntimeException(
"ServletConfigStub.getInitParameter() not implemented.");
}
@Override
@SuppressWarnings("rawtypes")
public Enumeration getInitParameterNames() {
throw new RuntimeException(
"ServletConfigStub.getInitParameterNames() not implemented.");
}
@Override
public String getServletName() {
throw new RuntimeException(
"ServletConfigStub.getServletName() not implemented.");
}
}
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.javax.servlet;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
/**
* A simple stub for testing servlets.
*/
public class ServletConfigStub implements ServletConfig {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private ServletContext servletContext;
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public ServletContext getServletContext() {
return servletContext;
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public String getInitParameter(String arg0) {
throw new RuntimeException(
"ServletConfigStub.getInitParameter() not implemented.");
}
@Override
@SuppressWarnings("rawtypes")
public Enumeration getInitParameterNames() {
throw new RuntimeException(
"ServletConfigStub.getInitParameterNames() not implemented.");
}
@Override
public String getServletName() {
throw new RuntimeException(
"ServletConfigStub.getServletName() not implemented.");
}
}

View file

@ -1,243 +1,243 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.javax.servlet;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* A simple stand-in for the {@link ServletContext}, for use in unit tests.
*/
public class ServletContextStub implements ServletContext {
private static final Log log = LogFactory.getLog(ServletContextStub.class);
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private String contextPath = ""; // root context returns ""
private final Map<String, Object> attributes = new HashMap<String, Object>();
private final Map<String, String> mockResources = new HashMap<String, String>();
private final Map<String, String> realPaths = new HashMap<String, String>();
public void setContextPath(String contextPath) {
if (contextPath == null) {
throw new NullPointerException("contextPath may not be null.");
}
}
public void setMockResource(String path, String contents) {
if (path == null) {
throw new NullPointerException("path may not be null.");
}
if (contents == null) {
mockResources.remove(path);
} else {
mockResources.put(path, contents);
}
}
public void setRealPath(String path, String filepath) {
if (path == null) {
throw new NullPointerException("path may not be null.");
}
if (filepath == null) {
log.debug("removing real path for '" + path + "'");
realPaths.remove(path);
} else {
log.debug("adding real path for '" + path + "' = '" + filepath
+ "'");
realPaths.put(path, filepath);
}
}
/**
* Call setRealPath for each of the files in this directory (non-recursive).
* The prefix is the "pretend" location that we're mapping these files to,
* e.g. "/config/". Use the prefix and the filename as the path.
*/
public void setRealPaths(String pathPrefix, File dir) {
for (File file : dir.listFiles()) {
setRealPath(pathPrefix + file.getName(), file.getPath());
}
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public String getContextPath() {
return contextPath;
}
@Override
public Object getAttribute(String name) {
return attributes.get(name);
}
@Override
public Enumeration<String> getAttributeNames() {
return Collections.enumeration(attributes.keySet());
}
@Override
public void removeAttribute(String name) {
attributes.remove(name);
}
@Override
public void setAttribute(String name, Object object) {
if (object == null) {
removeAttribute(name);
} else {
attributes.put(name, object);
}
}
@Override
public InputStream getResourceAsStream(String path) {
if (mockResources.containsKey(path)) {
return new ByteArrayInputStream(mockResources.get(path).getBytes());
} else {
return null;
}
}
@Override
public String getRealPath(String path) {
String real = realPaths.get(path);
log.debug("Real path for '" + path + "' is '" + real + "'");
return real;
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public ServletContext getContext(String arg0) {
throw new RuntimeException(
"ServletContextStub.getContext() not implemented.");
}
@Override
public String getInitParameter(String arg0) {
throw new RuntimeException(
"ServletContextStub.getInitParameter() not implemented.");
}
@Override
@SuppressWarnings("rawtypes")
public Enumeration getInitParameterNames() {
throw new RuntimeException(
"ServletContextStub.getInitParameterNames() not implemented.");
}
@Override
public int getMajorVersion() {
throw new RuntimeException(
"ServletContextStub.getMajorVersion() not implemented.");
}
@Override
public String getMimeType(String arg0) {
throw new RuntimeException(
"ServletContextStub.getMimeType() not implemented.");
}
@Override
public int getMinorVersion() {
throw new RuntimeException(
"ServletContextStub.getMinorVersion() not implemented.");
}
@Override
public RequestDispatcher getNamedDispatcher(String arg0) {
throw new RuntimeException(
"ServletContextStub.getNamedDispatcher() not implemented.");
}
@Override
public RequestDispatcher getRequestDispatcher(String arg0) {
throw new RuntimeException(
"ServletContextStub.getRequestDispatcher() not implemented.");
}
@Override
public URL getResource(String arg0) throws MalformedURLException {
throw new RuntimeException(
"ServletContextStub.getResource() not implemented.");
}
@Override
@SuppressWarnings("rawtypes")
public Set getResourcePaths(String arg0) {
throw new RuntimeException(
"ServletContextStub.getResourcePaths() not implemented.");
}
@Override
public String getServerInfo() {
throw new RuntimeException(
"ServletContextStub.getServerInfo() not implemented.");
}
@Override
public Servlet getServlet(String arg0) throws ServletException {
throw new RuntimeException(
"ServletContextStub.getServlet() not implemented.");
}
@Override
public String getServletContextName() {
throw new RuntimeException(
"ServletContextStub.getServletContextName() not implemented.");
}
@Override
@SuppressWarnings("rawtypes")
public Enumeration getServletNames() {
throw new RuntimeException(
"ServletContextStub.getServletNames() not implemented.");
}
@Override
@SuppressWarnings("rawtypes")
public Enumeration getServlets() {
throw new RuntimeException(
"ServletContextStub.getServlets() not implemented.");
}
@Override
public void log(String arg0) {
throw new RuntimeException("ServletContextStub.log() not implemented.");
}
@Override
public void log(Exception arg0, String arg1) {
throw new RuntimeException("ServletContextStub.log() not implemented.");
}
@Override
public void log(String arg0, Throwable arg1) {
throw new RuntimeException("ServletContextStub.log() not implemented.");
}
}
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.javax.servlet;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* A simple stand-in for the {@link ServletContext}, for use in unit tests.
*/
public class ServletContextStub implements ServletContext {
private static final Log log = LogFactory.getLog(ServletContextStub.class);
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private String contextPath = ""; // root context returns ""
private final Map<String, Object> attributes = new HashMap<String, Object>();
private final Map<String, String> mockResources = new HashMap<String, String>();
private final Map<String, String> realPaths = new HashMap<String, String>();
public void setContextPath(String contextPath) {
if (contextPath == null) {
throw new NullPointerException("contextPath may not be null.");
}
}
public void setMockResource(String path, String contents) {
if (path == null) {
throw new NullPointerException("path may not be null.");
}
if (contents == null) {
mockResources.remove(path);
} else {
mockResources.put(path, contents);
}
}
public void setRealPath(String path, String filepath) {
if (path == null) {
throw new NullPointerException("path may not be null.");
}
if (filepath == null) {
log.debug("removing real path for '" + path + "'");
realPaths.remove(path);
} else {
log.debug("adding real path for '" + path + "' = '" + filepath
+ "'");
realPaths.put(path, filepath);
}
}
/**
* Call setRealPath for each of the files in this directory (non-recursive).
* The prefix is the "pretend" location that we're mapping these files to,
* e.g. "/config/". Use the prefix and the filename as the path.
*/
public void setRealPaths(String pathPrefix, File dir) {
for (File file : dir.listFiles()) {
setRealPath(pathPrefix + file.getName(), file.getPath());
}
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public String getContextPath() {
return contextPath;
}
@Override
public Object getAttribute(String name) {
return attributes.get(name);
}
@Override
public Enumeration<String> getAttributeNames() {
return Collections.enumeration(attributes.keySet());
}
@Override
public void removeAttribute(String name) {
attributes.remove(name);
}
@Override
public void setAttribute(String name, Object object) {
if (object == null) {
removeAttribute(name);
} else {
attributes.put(name, object);
}
}
@Override
public InputStream getResourceAsStream(String path) {
if (mockResources.containsKey(path)) {
return new ByteArrayInputStream(mockResources.get(path).getBytes());
} else {
return null;
}
}
@Override
public String getRealPath(String path) {
String real = realPaths.get(path);
log.debug("Real path for '" + path + "' is '" + real + "'");
return real;
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public ServletContext getContext(String arg0) {
throw new RuntimeException(
"ServletContextStub.getContext() not implemented.");
}
@Override
public String getInitParameter(String arg0) {
throw new RuntimeException(
"ServletContextStub.getInitParameter() not implemented.");
}
@Override
@SuppressWarnings("rawtypes")
public Enumeration getInitParameterNames() {
throw new RuntimeException(
"ServletContextStub.getInitParameterNames() not implemented.");
}
@Override
public int getMajorVersion() {
throw new RuntimeException(
"ServletContextStub.getMajorVersion() not implemented.");
}
@Override
public String getMimeType(String arg0) {
throw new RuntimeException(
"ServletContextStub.getMimeType() not implemented.");
}
@Override
public int getMinorVersion() {
throw new RuntimeException(
"ServletContextStub.getMinorVersion() not implemented.");
}
@Override
public RequestDispatcher getNamedDispatcher(String arg0) {
throw new RuntimeException(
"ServletContextStub.getNamedDispatcher() not implemented.");
}
@Override
public RequestDispatcher getRequestDispatcher(String arg0) {
throw new RuntimeException(
"ServletContextStub.getRequestDispatcher() not implemented.");
}
@Override
public URL getResource(String arg0) throws MalformedURLException {
throw new RuntimeException(
"ServletContextStub.getResource() not implemented.");
}
@Override
@SuppressWarnings("rawtypes")
public Set getResourcePaths(String arg0) {
throw new RuntimeException(
"ServletContextStub.getResourcePaths() not implemented.");
}
@Override
public String getServerInfo() {
throw new RuntimeException(
"ServletContextStub.getServerInfo() not implemented.");
}
@Override
public Servlet getServlet(String arg0) throws ServletException {
throw new RuntimeException(
"ServletContextStub.getServlet() not implemented.");
}
@Override
public String getServletContextName() {
throw new RuntimeException(
"ServletContextStub.getServletContextName() not implemented.");
}
@Override
@SuppressWarnings("rawtypes")
public Enumeration getServletNames() {
throw new RuntimeException(
"ServletContextStub.getServletNames() not implemented.");
}
@Override
@SuppressWarnings("rawtypes")
public Enumeration getServlets() {
throw new RuntimeException(
"ServletContextStub.getServlets() not implemented.");
}
@Override
public void log(String arg0) {
throw new RuntimeException("ServletContextStub.log() not implemented.");
}
@Override
public void log(Exception arg0, String arg1) {
throw new RuntimeException("ServletContextStub.log() not implemented.");
}
@Override
public void log(String arg0, Throwable arg1) {
throw new RuntimeException("ServletContextStub.log() not implemented.");
}
}

View file

@ -1,289 +1,289 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.javax.servlet.http;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
/**
* A simple stub for HttpServletResponse
*/
@SuppressWarnings("deprecation")
public class HttpServletResponseStub implements HttpServletResponse {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private String redirectLocation;
private int status = 200;
private String errorMessage;
private Map<String, String> headers = new HashMap<String, String>();
private String contentType;
private String charset = "";
private ByteArrayOutputStream outputStream;
private StringWriter outputWriter;
public String getRedirectLocation() {
return redirectLocation;
}
public int getStatus() {
return status;
}
public String getErrorMessage() {
return errorMessage;
}
public String getOutput() {
if (outputStream != null) {
return outputStream.toString();
} else if (outputWriter != null) {
return outputWriter.toString();
} else {
return "";
}
}
public String getHeader(String name) {
return headers.get(name);
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public void sendRedirect(String location) throws IOException {
this.redirectLocation = location;
}
@Override
public void setStatus(int status) {
this.status = status;
}
@Override
@SuppressWarnings("hiding")
public void sendError(int status) throws IOException {
this.status = status;
}
@Override
@SuppressWarnings("hiding")
public void sendError(int status, String message) throws IOException {
this.status = status;
this.errorMessage = message;
}
@Override
public PrintWriter getWriter() throws IOException {
if (outputStream != null) {
throw new IllegalStateException(
"Can't get a Writer after getting an OutputStream.");
}
if (outputWriter == null) {
outputWriter = new StringWriter();
}
return new PrintWriter(outputWriter, true);
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
if (outputWriter != null) {
throw new IllegalStateException(
"Can't get an OutputStream after getting a Writer.");
}
if (outputStream == null) {
outputStream = new ByteArrayOutputStream();
}
return new ServletOutputStream() {
@Override
public void write(int thisChar) throws IOException {
outputStream.write(thisChar);
}
};
}
@Override
public void setHeader(String name, String value) {
headers.put(name, value);
}
@Override
public boolean containsHeader(String name) {
return headers.containsKey(name);
}
/**
* Calling setContentType("this/type;charset=UTF-8") is the same as calling
* setContentType("this/type;charset=UTF-8"); setCharacterEncoding("UTF-8")
*/
@Override
public void setContentType(String contentType) {
this.contentType = contentType;
Pattern p = Pattern.compile(";\\scharset=([^;]+)");
Matcher m = p.matcher(contentType);
if (m.find()) {
this.charset = m.group(1);
}
}
@Override
public String getContentType() {
return contentType;
}
@Override
public void setCharacterEncoding(String charset) {
this.charset = charset;
}
@Override
public String getCharacterEncoding() {
return charset;
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public void flushBuffer() throws IOException {
throw new RuntimeException(
"HttpServletResponseStub.flushBuffer() not implemented.");
}
@Override
public int getBufferSize() {
throw new RuntimeException(
"HttpServletResponseStub.getBufferSize() not implemented.");
}
@Override
public Locale getLocale() {
throw new RuntimeException(
"HttpServletResponseStub.getLocale() not implemented.");
}
@Override
public boolean isCommitted() {
throw new RuntimeException(
"HttpServletResponseStub.isCommitted() not implemented.");
}
@Override
public void reset() {
throw new RuntimeException(
"HttpServletResponseStub.reset() not implemented.");
}
@Override
public void resetBuffer() {
throw new RuntimeException(
"HttpServletResponseStub.resetBuffer() not implemented.");
}
@Override
public void setBufferSize(int arg0) {
throw new RuntimeException(
"HttpServletResponseStub.setBufferSize() not implemented.");
}
@Override
public void setContentLength(int arg0) {
throw new RuntimeException(
"HttpServletResponseStub.setContentLength() not implemented.");
}
@Override
public void setLocale(Locale arg0) {
throw new RuntimeException(
"HttpServletResponseStub.setLocale() not implemented.");
}
@Override
public void addCookie(Cookie arg0) {
throw new RuntimeException(
"HttpServletResponseStub.addCookie() not implemented.");
}
@Override
public void addDateHeader(String arg0, long arg1) {
throw new RuntimeException(
"HttpServletResponseStub.addDateHeader() not implemented.");
}
@Override
public void addHeader(String arg0, String arg1) {
throw new RuntimeException(
"HttpServletResponseStub.addHeader() not implemented.");
}
@Override
public void addIntHeader(String arg0, int arg1) {
throw new RuntimeException(
"HttpServletResponseStub.addIntHeader() not implemented.");
}
@Override
public String encodeRedirectURL(String arg0) {
throw new RuntimeException(
"HttpServletResponseStub.encodeRedirectURL() not implemented.");
}
@Override
public String encodeRedirectUrl(String arg0) {
throw new RuntimeException(
"HttpServletResponseStub.encodeRedirectUrl() not implemented.");
}
@Override
public String encodeURL(String arg0) {
throw new RuntimeException(
"HttpServletResponseStub.encodeURL() not implemented.");
}
@Override
public String encodeUrl(String arg0) {
throw new RuntimeException(
"HttpServletResponseStub.encodeUrl() not implemented.");
}
@Override
public void setDateHeader(String arg0, long arg1) {
throw new RuntimeException(
"HttpServletResponseStub.setDateHeader() not implemented.");
}
@Override
public void setIntHeader(String arg0, int arg1) {
throw new RuntimeException(
"HttpServletResponseStub.setIntHeader() not implemented.");
}
@Override
public void setStatus(int arg0, String arg1) {
throw new RuntimeException(
"HttpServletResponseStub.setStatus() not implemented.");
}
}
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.javax.servlet.http;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
/**
* A simple stub for HttpServletResponse
*/
@SuppressWarnings("deprecation")
public class HttpServletResponseStub implements HttpServletResponse {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private String redirectLocation;
private int status = 200;
private String errorMessage;
private Map<String, String> headers = new HashMap<String, String>();
private String contentType;
private String charset = "";
private ByteArrayOutputStream outputStream;
private StringWriter outputWriter;
public String getRedirectLocation() {
return redirectLocation;
}
public int getStatus() {
return status;
}
public String getErrorMessage() {
return errorMessage;
}
public String getOutput() {
if (outputStream != null) {
return outputStream.toString();
} else if (outputWriter != null) {
return outputWriter.toString();
} else {
return "";
}
}
public String getHeader(String name) {
return headers.get(name);
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public void sendRedirect(String location) throws IOException {
this.redirectLocation = location;
}
@Override
public void setStatus(int status) {
this.status = status;
}
@Override
@SuppressWarnings("hiding")
public void sendError(int status) throws IOException {
this.status = status;
}
@Override
@SuppressWarnings("hiding")
public void sendError(int status, String message) throws IOException {
this.status = status;
this.errorMessage = message;
}
@Override
public PrintWriter getWriter() throws IOException {
if (outputStream != null) {
throw new IllegalStateException(
"Can't get a Writer after getting an OutputStream.");
}
if (outputWriter == null) {
outputWriter = new StringWriter();
}
return new PrintWriter(outputWriter, true);
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
if (outputWriter != null) {
throw new IllegalStateException(
"Can't get an OutputStream after getting a Writer.");
}
if (outputStream == null) {
outputStream = new ByteArrayOutputStream();
}
return new ServletOutputStream() {
@Override
public void write(int thisChar) throws IOException {
outputStream.write(thisChar);
}
};
}
@Override
public void setHeader(String name, String value) {
headers.put(name, value);
}
@Override
public boolean containsHeader(String name) {
return headers.containsKey(name);
}
/**
* Calling setContentType("this/type;charset=UTF-8") is the same as calling
* setContentType("this/type;charset=UTF-8"); setCharacterEncoding("UTF-8")
*/
@Override
public void setContentType(String contentType) {
this.contentType = contentType;
Pattern p = Pattern.compile(";\\scharset=([^;]+)");
Matcher m = p.matcher(contentType);
if (m.find()) {
this.charset = m.group(1);
}
}
@Override
public String getContentType() {
return contentType;
}
@Override
public void setCharacterEncoding(String charset) {
this.charset = charset;
}
@Override
public String getCharacterEncoding() {
return charset;
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public void flushBuffer() throws IOException {
throw new RuntimeException(
"HttpServletResponseStub.flushBuffer() not implemented.");
}
@Override
public int getBufferSize() {
throw new RuntimeException(
"HttpServletResponseStub.getBufferSize() not implemented.");
}
@Override
public Locale getLocale() {
throw new RuntimeException(
"HttpServletResponseStub.getLocale() not implemented.");
}
@Override
public boolean isCommitted() {
throw new RuntimeException(
"HttpServletResponseStub.isCommitted() not implemented.");
}
@Override
public void reset() {
throw new RuntimeException(
"HttpServletResponseStub.reset() not implemented.");
}
@Override
public void resetBuffer() {
throw new RuntimeException(
"HttpServletResponseStub.resetBuffer() not implemented.");
}
@Override
public void setBufferSize(int arg0) {
throw new RuntimeException(
"HttpServletResponseStub.setBufferSize() not implemented.");
}
@Override
public void setContentLength(int arg0) {
throw new RuntimeException(
"HttpServletResponseStub.setContentLength() not implemented.");
}
@Override
public void setLocale(Locale arg0) {
throw new RuntimeException(
"HttpServletResponseStub.setLocale() not implemented.");
}
@Override
public void addCookie(Cookie arg0) {
throw new RuntimeException(
"HttpServletResponseStub.addCookie() not implemented.");
}
@Override
public void addDateHeader(String arg0, long arg1) {
throw new RuntimeException(
"HttpServletResponseStub.addDateHeader() not implemented.");
}
@Override
public void addHeader(String arg0, String arg1) {
throw new RuntimeException(
"HttpServletResponseStub.addHeader() not implemented.");
}
@Override
public void addIntHeader(String arg0, int arg1) {
throw new RuntimeException(
"HttpServletResponseStub.addIntHeader() not implemented.");
}
@Override
public String encodeRedirectURL(String arg0) {
throw new RuntimeException(
"HttpServletResponseStub.encodeRedirectURL() not implemented.");
}
@Override
public String encodeRedirectUrl(String arg0) {
throw new RuntimeException(
"HttpServletResponseStub.encodeRedirectUrl() not implemented.");
}
@Override
public String encodeURL(String arg0) {
throw new RuntimeException(
"HttpServletResponseStub.encodeURL() not implemented.");
}
@Override
public String encodeUrl(String arg0) {
throw new RuntimeException(
"HttpServletResponseStub.encodeUrl() not implemented.");
}
@Override
public void setDateHeader(String arg0, long arg1) {
throw new RuntimeException(
"HttpServletResponseStub.setDateHeader() not implemented.");
}
@Override
public void setIntHeader(String arg0, int arg1) {
throw new RuntimeException(
"HttpServletResponseStub.setIntHeader() not implemented.");
}
@Override
public void setStatus(int arg0, String arg1) {
throw new RuntimeException(
"HttpServletResponseStub.setStatus() not implemented.");
}
}

View file

@ -1,163 +1,163 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.javax.servlet.http;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import stubs.javax.servlet.ServletContextStub;
/**
* A simple stand-in for the HttpSession, for use in unit tests.
*/
public class HttpSessionStub implements HttpSession {
private static final Log log = LogFactory.getLog(HttpSessionStub.class);
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private String id = "arbitraryId";
private ServletContext context;
private final Map<String, Object> attributes = new HashMap<String, Object>();
@SuppressWarnings("unused")
private int maxInactiveInterval;
public void setId(String id) {
this.id = id;
}
public void setServletContext(ServletContext context) {
this.context = context;
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public String getId() {
return this.id;
}
@Override
public ServletContext getServletContext() {
if (this.context == null) {
return new ServletContextStub();
} else {
return this.context;
}
}
@Override
public void setAttribute(String name, Object value) {
if (name == null) {
throw new NullPointerException("name may not be null.");
}
if (value == null) {
removeAttribute(name);
}
attributes.put(name, value);
log.debug("setAttribute: " + name + "=" + value);
}
@Override
public void removeAttribute(String name) {
attributes.remove(name);
log.debug("removeAttribute: " + name);
}
@Override
public Object getAttribute(String name) {
return attributes.get(name);
}
/**
* So far, we don't do anything with this, or even confirm that it has been
* set. We just don't throw an exception if someone wants to set it.
*/
@Override
public void setMaxInactiveInterval(int seconds) {
this.maxInactiveInterval = seconds;
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
@SuppressWarnings("rawtypes")
public Enumeration getAttributeNames() {
throw new RuntimeException(
"HttpSessionStub.getAttributeNames() not implemented.");
}
@Override
public long getCreationTime() {
throw new RuntimeException(
"HttpSessionStub.getCreationTime() not implemented.");
}
@Override
public long getLastAccessedTime() {
throw new RuntimeException(
"HttpSessionStub.getLastAccessedTime() not implemented.");
}
@Override
public int getMaxInactiveInterval() {
throw new RuntimeException(
"HttpSessionStub.getMaxInactiveInterval() not implemented.");
}
@Deprecated
@Override
public javax.servlet.http.HttpSessionContext getSessionContext() {
throw new RuntimeException(
"HttpSessionStub.getSessionContext() not implemented.");
}
@Override
public Object getValue(String arg0) {
throw new RuntimeException(
"HttpSessionStub.getValue() not implemented.");
}
@Override
public String[] getValueNames() {
throw new RuntimeException(
"HttpSessionStub.getValueNames() not implemented.");
}
@Override
public void invalidate() {
throw new RuntimeException(
"HttpSessionStub.invalidate() not implemented.");
}
@Override
public boolean isNew() {
throw new RuntimeException("HttpSessionStub.isNew() not implemented.");
}
@Override
public void putValue(String arg0, Object arg1) {
throw new RuntimeException(
"HttpSessionStub.putValue() not implemented.");
}
@Override
public void removeValue(String arg0) {
throw new RuntimeException(
"HttpSessionStub.removeValue() not implemented.");
}
}
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.javax.servlet.http;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import stubs.javax.servlet.ServletContextStub;
/**
* A simple stand-in for the HttpSession, for use in unit tests.
*/
public class HttpSessionStub implements HttpSession {
private static final Log log = LogFactory.getLog(HttpSessionStub.class);
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private String id = "arbitraryId";
private ServletContext context;
private final Map<String, Object> attributes = new HashMap<String, Object>();
@SuppressWarnings("unused")
private int maxInactiveInterval;
public void setId(String id) {
this.id = id;
}
public void setServletContext(ServletContext context) {
this.context = context;
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public String getId() {
return this.id;
}
@Override
public ServletContext getServletContext() {
if (this.context == null) {
return new ServletContextStub();
} else {
return this.context;
}
}
@Override
public void setAttribute(String name, Object value) {
if (name == null) {
throw new NullPointerException("name may not be null.");
}
if (value == null) {
removeAttribute(name);
}
attributes.put(name, value);
log.debug("setAttribute: " + name + "=" + value);
}
@Override
public void removeAttribute(String name) {
attributes.remove(name);
log.debug("removeAttribute: " + name);
}
@Override
public Object getAttribute(String name) {
return attributes.get(name);
}
/**
* So far, we don't do anything with this, or even confirm that it has been
* set. We just don't throw an exception if someone wants to set it.
*/
@Override
public void setMaxInactiveInterval(int seconds) {
this.maxInactiveInterval = seconds;
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
@SuppressWarnings("rawtypes")
public Enumeration getAttributeNames() {
throw new RuntimeException(
"HttpSessionStub.getAttributeNames() not implemented.");
}
@Override
public long getCreationTime() {
throw new RuntimeException(
"HttpSessionStub.getCreationTime() not implemented.");
}
@Override
public long getLastAccessedTime() {
throw new RuntimeException(
"HttpSessionStub.getLastAccessedTime() not implemented.");
}
@Override
public int getMaxInactiveInterval() {
throw new RuntimeException(
"HttpSessionStub.getMaxInactiveInterval() not implemented.");
}
@Deprecated
@Override
public javax.servlet.http.HttpSessionContext getSessionContext() {
throw new RuntimeException(
"HttpSessionStub.getSessionContext() not implemented.");
}
@Override
public Object getValue(String arg0) {
throw new RuntimeException(
"HttpSessionStub.getValue() not implemented.");
}
@Override
public String[] getValueNames() {
throw new RuntimeException(
"HttpSessionStub.getValueNames() not implemented.");
}
@Override
public void invalidate() {
throw new RuntimeException(
"HttpSessionStub.invalidate() not implemented.");
}
@Override
public boolean isNew() {
throw new RuntimeException("HttpSessionStub.isNew() not implemented.");
}
@Override
public void putValue(String arg0, Object arg1) {
throw new RuntimeException(
"HttpSessionStub.putValue() not implemented.");
}
@Override
public void removeValue(String arg0) {
throw new RuntimeException(
"HttpSessionStub.removeValue() not implemented.");
}
}