Maven migration (first draft)

This commit is contained in:
Graham Triggs 2015-11-19 23:47:12 +00:00
parent 5e0329908c
commit e1ff94ccaf
2866 changed files with 1112 additions and 616 deletions

View file

@ -0,0 +1,431 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vedit.util;
import static org.junit.Assert.assertEquals;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
/**
* All of these tests are for OperationUtils.cloneBean()
*/
public class OperationUtils_CloneBeanTest extends AbstractTestClass {
// ----------------------------------------------------------------------
// Allow the tests to expect a RuntimeException with a particular cause.
// ----------------------------------------------------------------------
@Rule
public ExpectedException thrown = ExpectedException.none();
Matcher<?> causedBy(Class<? extends Throwable> causeClass) {
return new CausedByMatcher(causeClass);
}
class CausedByMatcher extends BaseMatcher<Throwable> {
private final Class<? extends Throwable> causeClass;
public CausedByMatcher(Class<? extends Throwable> causeClass) {
this.causeClass = causeClass;
}
@Override
public boolean matches(Object actualThrowable) {
if (!(actualThrowable instanceof RuntimeException)) {
return false;
}
Throwable cause = ((RuntimeException) actualThrowable).getCause();
return causeClass.isInstance(cause);
}
@Override
public void describeTo(Description d) {
d.appendText("RuntimeException caused by " + causeClass.getName());
}
}
// ----------------------------------------------------------------------
// Test for invalid classes
// ----------------------------------------------------------------------
@Test(expected = NullPointerException.class)
public void nullArgument() {
OperationUtils.cloneBean(null);
}
@Test(expected = NullPointerException.class)
public void nullBean() {
OperationUtils
.cloneBean(null, SimpleSuccess.class, SimpleSuccess.class);
}
@Test(expected = NullPointerException.class)
public void nullBeanClass() {
OperationUtils
.cloneBean(new SimpleSuccess(), null, SimpleSuccess.class);
}
@Test(expected = NullPointerException.class)
public void nullInterfaceClass() {
OperationUtils
.cloneBean(new SimpleSuccess(), SimpleSuccess.class, null);
}
@Test(expected = IllegalAccessException.class)
@Ignore("Why doesn't this throw an exception?")
public void privateClass() {
OperationUtils.cloneBean(new PrivateClass());
}
@Test
public void privateConstructor() {
thrown.expect(causedBy(NoSuchMethodException.class));
OperationUtils.cloneBean(new PrivateConstructor());
}
@Test
public void abstractClass() {
thrown.expect(causedBy(InstantiationException.class));
OperationUtils.cloneBean(new ConcreteOfAbstractClass(),
AbstractClass.class, AbstractClass.class);
}
@Test
public void interfaceClass() {
thrown.expect(causedBy(InstantiationException.class));
OperationUtils.cloneBean(new ConcreteOfInterfaceClass(),
InterfaceClass.class, InterfaceClass.class);
}
@Test
public void arrayClass() {
thrown.expect(causedBy(NoSuchMethodException.class));
OperationUtils.cloneBean(new String[0]);
}
@Test
public void primitiveTypeClass() {
thrown.expect(causedBy(NoSuchMethodException.class));
OperationUtils.cloneBean(1, Integer.TYPE, Integer.TYPE);
}
@Test
public void voidClass() {
thrown.expect(causedBy(NoSuchMethodException.class));
OperationUtils.cloneBean(new Object(), Void.TYPE, Void.TYPE);
}
@Test
public void noNullaryConstructor() {
thrown.expect(causedBy(NoSuchMethodException.class));
OperationUtils.cloneBean(new NoNullaryConstructor(1));
}
@Test(expected = ExceptionInInitializerError.class)
public void classThrowsExceptionWhenLoaded() {
OperationUtils.cloneBean(new ThrowsExceptionWhenLoaded());
}
@Test
public void initializerThrowsException() {
thrown.expect(causedBy(InvocationTargetException.class));
OperationUtils.cloneBean("random object",
InitializerThrowsException.class,
InitializerThrowsException.class);
}
@Test
public void wrongInterfaceClass() {
thrown.expect(causedBy(IllegalArgumentException.class));
OperationUtils.cloneBean(new WrongConcreteClass(),
WrongConcreteClass.class, WrongInterface.class);
}
@Test
public void getThrowsException() {
thrown.expect(causedBy(InvocationTargetException.class));
OperationUtils.cloneBean(new GetMethodThrowsException());
}
@Test
public void setThrowsException() {
thrown.expect(causedBy(InvocationTargetException.class));
OperationUtils.cloneBean(new SetMethodThrowsException());
}
private static class PrivateClass {
public PrivateClass() {
}
}
private static class PrivateConstructor {
private PrivateConstructor() {
}
}
public abstract static class AbstractClass {
public AbstractClass() {
}
}
public static class ConcreteOfAbstractClass extends AbstractClass {
public ConcreteOfAbstractClass() {
}
}
public abstract static class InterfaceClass {
public InterfaceClass() {
}
}
public static class ConcreteOfInterfaceClass extends InterfaceClass {
public ConcreteOfInterfaceClass() {
}
}
public static class NoNullaryConstructor {
@SuppressWarnings("unused")
public NoNullaryConstructor(int i) {
// nothing to do
}
}
public static class ThrowsExceptionWhenLoaded {
static {
if (true)
throw new IllegalArgumentException();
}
}
public static class InitializerThrowsException {
{
if (true)
throw new IllegalStateException("Initializer throws exception");
}
}
public static class WrongConcreteClass {
private String junk = "junk";
public String getJunk() {
return this.junk;
}
@SuppressWarnings("unused")
private void setJunk(String junk) {
this.junk = junk;
}
}
public static interface WrongInterface {
String getJunk();
void setJunk(String junk);
}
public static class GetMethodThrowsException {
@SuppressWarnings("unused")
private String junk = "junk";
public String getJunk() {
throw new UnsupportedOperationException();
}
public void setJunk(String junk) {
this.junk = junk;
}
}
public static class SetMethodThrowsException {
private String junk = "junk";
public String getJunk() {
return this.junk;
}
@SuppressWarnings("unused")
public void setJunk(String junk) {
throw new UnsupportedOperationException();
}
}
// ----------------------------------------------------------------------
// Test simple success and innocuous variations
// ----------------------------------------------------------------------
@Test
public void simpleSuccess() {
expectSuccess(new SimpleSuccess().insertField("label", "a prize"));
}
@Test
public void getButNoSet() {
expectSuccess(new GetButNoSet().insertField("label", "shouldBeEqual"));
}
@Test
public void getTakesParameters() {
expectSuccess(new GetTakesParameters().insertField("label", "fine"));
}
@Test
public void getReturnsVoid() {
expectSuccess(new GetReturnsVoid().insertField("label", "fine"));
}
@Test
public void getAndSetDontMatch() {
expectSuccess(new GetAndSetDontMatch().insertField("label", "fine"));
}
@Test
public void getIsStatic() {
expectSuccess(new GetIsStatic().insertField("label", "fine")
.insertField("instanceJunk", "the junk"));
}
@Test
public void getMethodIsPrivate() {
expectSuccess(new GetMethodIsPrivate().insertField("label", "fine"));
}
@Test
public void setMethodIsPrivate() {
expectSuccess(new SetMethodIsPrivate().insertField("label", "fine"));
}
private void expectSuccess(BeanBase original) {
BeanBase cloned = (BeanBase) OperationUtils.cloneBean(original);
assertEquals("Simple success", original, cloned);
}
public static abstract class BeanBase {
protected final Map<String, Object> fields = new HashMap<>();
public BeanBase insertField(String key, Object value) {
if (value != null) {
fields.put(key, value);
}
return this;
}
@Override
public int hashCode() {
return fields.hashCode();
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o == null) {
return false;
}
if (!this.getClass().equals(o.getClass())) {
return false;
}
return this.fields.equals(((BeanBase) o).fields);
}
@Override
public String toString() {
return this.getClass().getSimpleName() + fields;
}
}
public static class SimpleSuccess extends BeanBase {
public String getLabel() {
return (String) fields.get("label");
}
public void setLabel(String label) {
insertField("label", label);
}
}
public static class GetButNoSet extends SimpleSuccess {
public String getJunk() {
throw new UnsupportedOperationException();
}
}
public static class GetTakesParameters extends SimpleSuccess {
@SuppressWarnings("unused")
public String getJunk(String why) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unused")
public void setJunk(String junk) {
throw new UnsupportedOperationException();
}
}
public static class GetReturnsVoid extends SimpleSuccess {
public void getJunk() {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unused")
public void setJunk(String junk) {
throw new UnsupportedOperationException();
}
}
public static class GetAndSetDontMatch extends SimpleSuccess {
public String getJunk() {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unused")
public void setJunk(Integer junk) {
throw new UnsupportedOperationException();
}
}
public static class GetIsStatic extends SimpleSuccess {
public static String getJunk() {
return ("the junk");
}
public void setJunk(String junk) {
insertField("instanceJunk", junk);
}
}
public static class GetMethodIsPrivate extends SimpleSuccess {
@SuppressWarnings("unused")
private String getJunk() {
return ("the junk");
}
public void setJunk(String junk) {
insertField("instanceJunk", junk);
}
}
public static class SetMethodIsPrivate extends SimpleSuccess {
public String getJunk() {
return ("the junk");
}
@SuppressWarnings("unused")
private void setJunk(String junk) {
insertField("instanceJunk", junk);
}
}
}

View file

@ -0,0 +1,475 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.testing;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
/**
* A collection of useful routines to help when testing.
* <ul>
* <li>Permit tests to control the Logging levels of individual classes.</li>
* <li>Permit tests to control system properties.</li>
* <li>Suppress, capture or test standard output and/or error output.</li>
* <li>Create and delete temporary files and directories.</li>
* <li>Create URLs from Strings without throwing checked exceptions.</li>
* <li>Compare the contents of XML documents.</li>
* </ul>
*
* @author jeb228
*/
public abstract class AbstractTestClass {
// ----------------------------------------------------------------------
// Control the level of logging output.
// ----------------------------------------------------------------------
/** The layout we use for logging. */
private static final PatternLayout patternLayout = new PatternLayout(
"%p %d{yyyy-MM-dd' 'HH:mm:ss.SSS} [%t] (%c{1}) %m%n");
/**
* Unless modified, all Logging will be done to the console at
* {@link Level#INFO}.
*/
@Before
@After
public void initializeLogging() {
LogManager.resetConfiguration();
Logger.getRootLogger().addAppender(new ConsoleAppender(patternLayout));
Logger.getRootLogger().setLevel(Level.INFO);
}
/**
* Call this in a "@Before" or "@BeforeClass" method to change the logging
* level of a particular class.
*/
protected static void setLoggerLevel(Class<?> clazz, Level level) {
Logger.getLogger(clazz).setLevel(level);
}
/**
* Same thing, but for a logger that is not named directly after a class.
*/
protected static void setLoggerLevel(String category, Level level) {
Logger.getLogger(category).setLevel(level);
}
/**
* Capture the log for this class to this Writer. Choose whether or not to
* suppress it from the console.
*/
protected void captureLogOutput(Class<?> clazz, Writer writer,
boolean suppress) {
PatternLayout layout = new PatternLayout("%p %m%n");
ConsoleAppender appender = new ConsoleAppender();
appender.setWriter(writer);
appender.setLayout(layout);
Logger logger = Logger.getLogger(clazz);
logger.removeAllAppenders();
logger.setAdditivity(!suppress);
logger.addAppender(appender);
}
// ----------------------------------------------------------------------
// Control standard output or error output.
// ----------------------------------------------------------------------
private static final PrintStream originalSysout = System.out;
private static final PrintStream originalSyserr = System.err;
private final ByteArrayOutputStream capturedSysout = new ByteArrayOutputStream();
private final ByteArrayOutputStream capturedSyserr = new ByteArrayOutputStream();
@Before
@After
public void restoreOutputStreams() {
System.setOut(originalSysout);
System.setErr(originalSyserr);
capturedSysout.reset();
capturedSyserr.reset();
}
protected void suppressSysout() {
System.setOut(new PrintStream(capturedSysout, true));
}
protected void suppressSyserr() {
System.setErr(new PrintStream(capturedSyserr, true));
}
protected String getSysoutForTest() {
return capturedSysout.toString();
}
protected String getSyserrForTest() {
return capturedSyserr.toString();
}
// ----------------------------------------------------------------------
// Set values on System properties for individual tests.
// ----------------------------------------------------------------------
private static Properties originalSystemProperties = (Properties) System
.getProperties().clone();
@Before
@After
public void restoreSystemProperties() {
System.setProperties((Properties) originalSystemProperties.clone());
}
// ----------------------------------------------------------------------
// Manage temporary files.
// ----------------------------------------------------------------------
/**
* Delete a file, either before or after the test. If it can't be deleted,
* complain.
*/
protected static void deleteFile(File file) {
if (file.exists()) {
file.delete();
}
if (!file.exists()) {
return;
}
/*
* If we were unable to delete the file, is it because it's a non-empty
* directory?
*/
if (!file.isDirectory()) {
final StringBuffer message = new StringBuffer(
"Unable to delete directory '" + file.getPath() + "'\n");
file.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
message.append(" contains file '" + pathname + "'\n");
return true;
}
});
fail(message.toString().trim());
} else {
fail("Unable to delete file '" + file.getPath() + "'");
}
}
/**
* Delete all of the files in a directory, and the directory itself. Will
* not work if there are sub-directories.
*/
protected static void purgeDirectory(File directory) {
if (directory.exists()) {
File[] files = directory.listFiles();
for (File file : files) {
if (file.isDirectory()) {
fail("Directory '" + directory
+ "' contains at least one nested directory.");
}
}
for (File file : files) {
deleteFile(file);
}
deleteFile(directory);
}
}
/**
* Delete all of the files in a directory, any sub-directories, and the
* directory itself.
*/
protected static void purgeDirectoryRecursively(File directory) {
if (directory.exists()) {
File[] files = directory.listFiles();
for (File file : files) {
if (file.isDirectory()) {
purgeDirectoryRecursively(file);
} else {
deleteFile(file);
}
}
deleteFile(directory);
}
}
/**
* Create a directory of a given name inside the Temp directory. If such a
* directory already exists, purge it and its contents and create it fresh.
*/
protected static File createTempDirectory(String name) throws IOException {
File tempDirectory = new File(System.getProperty("java.io.tmpdir"),
name);
// If it already exists, remove it, so we start clean.
if (tempDirectory.exists()) {
purgeDirectoryRecursively(tempDirectory);
}
if (!tempDirectory.mkdir()) {
throw new IOException("failed to create temp directory '"
+ tempDirectory.getPath() + "'");
}
return tempDirectory;
}
// ----------------------------------------------------------------------
// A better way of handling expected exceptions.
// ----------------------------------------------------------------------
@Rule
public ExpectedException exception = ExpectedException.none();
protected void expectException(Class<? extends Throwable> type,
String messageSubstring) {
exception.expect(type);
exception.expectMessage(messageSubstring);
}
protected void expectException(Class<? extends Throwable> type,
Matcher<String> messageMatcher) {
exception.expect(type);
exception.expectMessage(messageMatcher);
}
protected void expectExceptionCause(Class<? extends Throwable> type,
String messageSubstring) {
exception.expectCause(Matchers.<Throwable> instanceOf(type));
exception.expectCause(Matchers.<Throwable> hasProperty("message",
containsString(messageSubstring)));
}
protected void expectExceptionCause(Class<? extends Throwable> type,
Matcher<String> messageMatcher) {
exception.expectCause(Matchers.<Throwable> instanceOf(type));
exception.expectCause(Matchers.<Throwable> hasProperty("message",
messageMatcher));
}
protected void expectException(Class<? extends Throwable> clazz,
String messageSubstring, Class<? extends Throwable> causeClazz,
String causeMessageSubstring) {
expectException(clazz, messageSubstring);
expectExceptionCause(causeClazz, causeMessageSubstring);
}
// ----------------------------------------------------------------------
// Other utilities.
// ----------------------------------------------------------------------
/**
* Create a file and fill it with the contents provided.
*/
protected static File createFile(File directory, String filename,
String contents) throws IOException {
Writer writer = null;
try {
File file = new File(directory, filename);
if (file.exists()) {
throw new IOException("File '" + file.getPath()
+ "' already exists.");
}
file.createNewFile();
writer = new FileWriter(file);
writer.write(contents);
return file;
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Read the entire contents of a file, or throw an exception if it's not
* there.
*/
protected static String readFile(File file) throws IOException {
if (!file.exists()) {
throw new IOException("file '" + file.getPath() + "' ('"
+ file.getAbsolutePath() + "') does not exist.");
}
FileReader fileReader = new FileReader(file);
String result = readAll(fileReader);
return result;
}
/**
* Suck all the data from a {@link Reader} into a {@link String}.
*/
protected static String readAll(Reader reader) throws IOException {
StringBuilder result = new StringBuilder();
BufferedReader buffered = new BufferedReader(reader);
char[] chunk = new char[4096];
int howMany;
try {
while (-1 != (howMany = buffered.read(chunk))) {
result.append(chunk, 0, howMany);
}
} finally {
reader.close();
}
return result.toString();
}
/**
* Suck all the data from a {@link InputStream} into a {@link String}.
*/
protected static String readAll(InputStream stream) throws IOException {
return readAll(new InputStreamReader(stream));
}
/**
* Convert a string to a URL without a checked exception.
*/
protected static URL url(String string) {
try {
return new URL(string);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
}
/**
* Read each string into an XML document and then write it again. This
* should discard any differences that are not syntactically significant.
* Will they be identical?
*/
protected void assertEquivalentXmlDocs(String string1, String string2) {
String out1 = launderXmlDocument(string1);
String out2 = launderXmlDocument(string2);
if (!out1.equals(out2)) {
fail("XML documents are not equivalent: expected <" + string1
+ "> but was <" + string2 + ">");
}
}
/**
* Read a string of XML into a document and write it again. This should
* result in a canonical form that can be compared to other such strings.
*/
private String launderXmlDocument(String docString) {
StringWriter result = new StringWriter();
try {
DocumentBuilderFactory bFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = bFactory.newDocumentBuilder();
TransformerFactory xFactory = TransformerFactory.newInstance();
Transformer xformer = xFactory.newTransformer();
StringReader reader = new StringReader(docString);
Document doc = builder.parse(new InputSource(reader));
xformer.transform(new DOMSource(doc), new StreamResult(result));
} catch (ParserConfigurationException e) {
fail(e.toString());
} catch (SAXException e) {
fail(e.toString());
} catch (IOException e) {
fail(e.toString());
} catch (TransformerException e) {
fail(e.toString());
}
return result.toString().replaceAll(">\\s+<", "><");
}
protected <T extends Comparable<T>> void assertEqualSets(String label,
Set<T> expected, Set<T> actual) {
if (expected.equals(actual)) {
return;
}
Set<T> missing = new TreeSet<T>(expected);
missing.removeAll(actual);
Set<T> extras = new TreeSet<T>(actual);
extras.removeAll(expected);
String message = label;
if (!missing.isEmpty()) {
message += ", missing: " + missing;
}
if (!extras.isEmpty()) {
message += ", extra: " + extras;
}
assertEquals(message, expected, actual);
}
@SuppressWarnings("unchecked")
protected <T> Set<T> buildSet(T... array) {
return new HashSet<T>(Arrays.asList(array));
}
protected OntModel readModelFromFile(String relativePath, String rdfType)
throws IOException {
InputStream stream = this.getClass().getResourceAsStream(relativePath);
Model model = ModelFactory.createDefaultModel();
model.read(stream, null, rdfType);
stream.close();
OntModel ontModel = ModelFactory.createOntologyModel(
OntModelSpec.OWL_DL_MEM, model);
ontModel.prepare();
return ontModel;
}
}

View file

@ -0,0 +1,68 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.testing;
import static com.hp.hpl.jena.rdf.model.ResourceFactory.createLangLiteral;
import static com.hp.hpl.jena.rdf.model.ResourceFactory.createPlainLiteral;
import static com.hp.hpl.jena.rdf.model.ResourceFactory.createProperty;
import static com.hp.hpl.jena.rdf.model.ResourceFactory.createResource;
import static com.hp.hpl.jena.rdf.model.ResourceFactory.createStatement;
import static com.hp.hpl.jena.rdf.model.ResourceFactory.createTypedLiteral;
import java.util.SortedSet;
import java.util.TreeSet;
import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.vocabulary.RDF;
/**
* Just some helper methods for Test classes that work with models.
*/
public class ModelUtilitiesTestHelper {
public static Model model(Statement... stmts) {
return ModelFactory.createDefaultModel().add(stmts);
}
public static Statement typeStatement(String subjectUri, String classUri) {
return createStatement(createResource(subjectUri), RDF.type,
createResource(classUri));
}
public static Statement objectProperty(String subjectUri,
String propertyUri, String objectUri) {
return createStatement(createResource(subjectUri),
createProperty(propertyUri), createResource(objectUri));
}
public static Statement dataProperty(String subjectUri, String propertyUri,
String objectValue) {
return createStatement(createResource(subjectUri),
createProperty(propertyUri), createPlainLiteral(objectValue));
}
public static Statement dataProperty(String subjectUri, String propertyUri,
Object objectValue, XSDDatatype dataType) {
return createStatement(createResource(subjectUri),
createProperty(propertyUri),
createTypedLiteral(String.valueOf(objectValue), dataType));
}
public static Statement dataProperty(String subjectUri, String propertyUri,
String objectValue, String language) {
return createStatement(createResource(subjectUri),
createProperty(propertyUri),
createLangLiteral(objectValue, language));
}
public static SortedSet<String> modelToStrings(Model m) {
SortedSet<String> set = new TreeSet<>();
for (Statement stmt : m.listStatements().toList()) {
set.add(stmt.toString());
}
return set;
}
}

View file

@ -0,0 +1,116 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.testing;
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.Collections;
import java.util.List;
/**
* The create() method creates a dynamic Proxy that wraps your inner object, and
* implements your interfaze.
*
* It also implements the MethodCallRecorder interface (although you will need
* to cast it), so you can find out what methods were called on the proxy.
*/
public class RecordingProxy {
public static <T> T create(T inner, Class<T> interfaze) {
RecordingInvocationHandler handler = new RecordingInvocationHandler(
inner);
ClassLoader classLoader = interfaze.getClassLoader();
Class<?>[] interfaces = new Class<?>[] { interfaze,
MethodCallRecorder.class };
return interfaze.cast(Proxy.newProxyInstance(classLoader, interfaces,
handler));
}
/**
* The "add-on" interface that allows us to ask what methods were called on
* the proxy since it was created, or since it was reset.
*/
public interface MethodCallRecorder {
List<MethodCall> getMethodCalls();
List<String> getMethodCallNames();
void resetMethodCalls();
}
public static class MethodCall {
/** a convenience method to get just the names of the methods called. */
public static Object justNames(List<MethodCall> methodCalls) {
List<String> names = new ArrayList<>();
for (MethodCall methodCall : methodCalls) {
names.add(methodCall.getName());
}
return names;
}
private final String name;
private final List<Object> argList;
public MethodCall(String name, Object[] args) {
this.name = name;
if (args == null) {
this.argList = Collections.emptyList();
} else {
this.argList = Collections.unmodifiableList(new ArrayList<>(
Arrays.asList(args)));
}
}
public String getName() {
return name;
}
public List<Object> getArgList() {
return argList;
}
}
public static class RecordingInvocationHandler implements InvocationHandler {
private final Object inner;
private final List<MethodCall> methodCalls = new ArrayList<>();
RecordingInvocationHandler(Object inner) {
this.inner = inner;
}
List<MethodCall> getMethodCalls() {
return new ArrayList<>(methodCalls);
}
void reset() {
methodCalls.clear();
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
switch (method.getName()) {
case "getMethodCalls":
return new ArrayList<MethodCall>(methodCalls);
case "getMethodCallNames":
return MethodCall.justNames(methodCalls);
case "resetMethodCalls":
methodCalls.clear();
return null;
case "equals":
if (args == null) return false;
if (args.length == 0) return false;
return args[0].equals(inner);
default:
methodCalls.add(new MethodCall(method.getName(), args));
return method.invoke(inner, args);
}
}
}
}

View file

@ -0,0 +1,278 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.identifier.factory;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import stubs.edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDaoStub;
import stubs.edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactoryStub;
import stubs.edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccessFactoryStub;
import stubs.javax.servlet.ServletContextStub;
import stubs.javax.servlet.http.HttpServletRequestStub;
import stubs.javax.servlet.http.HttpSessionStub;
import edu.cornell.mannlib.vedit.beans.LoginStatusBean;
import edu.cornell.mannlib.vedit.beans.LoginStatusBean.AuthenticationSource;
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.HasPermission;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.Permission;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.PermissionRegistry;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.RequestedAction;
import edu.cornell.mannlib.vitro.webapp.beans.PermissionSet;
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
/**
* Can we tell whether a user is logged in as root?
*/
public class HasPermissionFactoryTest extends AbstractTestClass {
private static final String USER_URI = "http://userUri";
private UserAccount user;
private LoginStatusBean lsb;
private PermissionSet emptyPublicPermissionSet;
private PermissionSet publicPermissionSet1;
private PermissionSet publicPermissionSet2;
private PermissionSet emptyLoggedInPermissionSet;
private PermissionSet loggedInPermissionSet1;
private PermissionSet loggedInPermissionSet2;
private Permission permissionP1a;
private Permission permissionP1b;
private Permission permissionP2;
private Permission permissionLI1;
private Permission permissionLI2a;
private Permission permissionLI2b;
private WebappDaoFactoryStub wdf;
private UserAccountsDaoStub uaDao;
private ServletContextStub ctx;
private HttpSessionStub session;
private HttpServletRequestStub req;
private HasPermissionFactory factory;
private IdentifierBundle actualIds;
private IdentifierBundle expectedIds;
@Before
public void setup() {
user = new UserAccount();
user.setUri(USER_URI);
lsb = new LoginStatusBean(USER_URI, AuthenticationSource.INTERNAL);
uaDao = new UserAccountsDaoStub();
uaDao.addUser(user);
wdf = new WebappDaoFactoryStub();
wdf.setUserAccountsDao(uaDao);
ctx = new ServletContextStub();
new ModelAccessFactoryStub().get(ctx).setWebappDaoFactory(wdf);
session = new HttpSessionStub();
session.setServletContext(ctx);
req = new HttpServletRequestStub();
req.setSession(session);
factory = new HasPermissionFactory(ctx);
preparePermissions();
preparePermissionSets();
}
private void preparePermissions() {
permissionP1a = new MyPermission("permissionP1a");
permissionP1b = new MyPermission("permissionP1b");
permissionP2 = new MyPermission("permissionP2");
permissionLI1 = new MyPermission("permissionLI1");
permissionLI2a = new MyPermission("permissionLI2a");
permissionLI2b = new MyPermission("permissionLI2b");
PermissionRegistry.createRegistry(
ctx,
list(permissionP1a, permissionP1b, permissionP2, permissionLI1,
permissionLI2a, permissionLI2b));
}
private void preparePermissionSets() {
emptyPublicPermissionSet = new PermissionSet();
emptyPublicPermissionSet.setUri("java:emptyPS");
emptyPublicPermissionSet.setLabel("emptyPublicPermissionSet");
emptyPublicPermissionSet.setForPublic(true);
publicPermissionSet1 = new PermissionSet();
publicPermissionSet1.setUri("java:publicPS1");
publicPermissionSet1.setLabel("publicPermissionSet1");
publicPermissionSet1.setForPublic(true);
setPermissions(publicPermissionSet1, permissionP1a, permissionP1b);
publicPermissionSet2 = new PermissionSet();
publicPermissionSet2.setUri("java:publicPS2");
publicPermissionSet2.setLabel("publicPermissionSet2");
publicPermissionSet2.setForPublic(true);
setPermissions(publicPermissionSet2, permissionP2);
emptyLoggedInPermissionSet = new PermissionSet();
emptyLoggedInPermissionSet.setUri("java:emptyPS");
emptyLoggedInPermissionSet.setLabel("emptyLoggedInPermissionSet");
loggedInPermissionSet1 = new PermissionSet();
loggedInPermissionSet1.setUri("java:loggedInPS1");
loggedInPermissionSet1.setLabel("loggedInPermissionSet1");
setPermissions(loggedInPermissionSet1, permissionLI1);
loggedInPermissionSet2 = new PermissionSet();
loggedInPermissionSet2.setUri("java:loggedInPS2");
loggedInPermissionSet2.setLabel("loggedInPermissionSet2");
setPermissions(loggedInPermissionSet2, permissionLI2a, permissionLI2b);
uaDao.addPermissionSet(emptyLoggedInPermissionSet);
uaDao.addPermissionSet(loggedInPermissionSet1);
uaDao.addPermissionSet(loggedInPermissionSet2);
// "public" permission sets are added for specific tests.
}
// ----------------------------------------------------------------------
// the tests
// ----------------------------------------------------------------------
@Test
public void notLoggedInNoPublicSets() {
expectedIds = new ArrayIdentifierBundle();
actualIds = factory.getIdentifierBundle(req);
assertEquals("no public sets", expectedIds, actualIds);
}
@Test
public void notLoggedInEmptyPublicSet() {
uaDao.addPermissionSet(emptyPublicPermissionSet);
expectedIds = new ArrayIdentifierBundle();
actualIds = factory.getIdentifierBundle(req);
assertEquals("empty public set", expectedIds, actualIds);
}
@Test
public void notLoggedInOnePublicSet() {
uaDao.addPermissionSet(publicPermissionSet1);
expectedIds = new ArrayIdentifierBundle(id(permissionP1a),
id(permissionP1b));
actualIds = factory.getIdentifierBundle(req);
assertEqualIds("one public set", expectedIds, actualIds);
}
@Test
public void notLoggedInTwoPublicSets() {
uaDao.addPermissionSet(publicPermissionSet1);
uaDao.addPermissionSet(publicPermissionSet2);
expectedIds = new ArrayIdentifierBundle(id(permissionP1a),
id(permissionP1b), id(permissionP2));
actualIds = factory.getIdentifierBundle(req);
assertEqualIds("two public sets", expectedIds, actualIds);
}
@Test
public void loggedInNoSets() {
LoginStatusBean.setBean(session, lsb);
expectedIds = new ArrayIdentifierBundle();
actualIds = factory.getIdentifierBundle(req);
assertEquals("no logged in sets", expectedIds, actualIds);
}
@Test
public void loggedInEmptySet() {
LoginStatusBean.setBean(session, lsb);
user.setPermissionSetUris(list(emptyLoggedInPermissionSet.getUri()));
expectedIds = new ArrayIdentifierBundle();
actualIds = factory.getIdentifierBundle(req);
assertEquals("empty logged in set", expectedIds, actualIds);
}
@Test
public void loggedInOneSet() {
LoginStatusBean.setBean(session, lsb);
user.setPermissionSetUris(list(loggedInPermissionSet1.getUri()));
expectedIds = new ArrayIdentifierBundle(id(permissionLI1));
actualIds = factory.getIdentifierBundle(req);
assertEqualIds("one logged in set", expectedIds, actualIds);
}
@Test
public void loggedInTwoSets() {
LoginStatusBean.setBean(session, lsb);
user.setPermissionSetUris(list(loggedInPermissionSet1.getUri(),
loggedInPermissionSet2.getUri()));
expectedIds = new ArrayIdentifierBundle(id(permissionLI1),
id(permissionLI2a), id(permissionLI2b));
actualIds = factory.getIdentifierBundle(req);
assertEqualIds("two logged in sets", expectedIds, actualIds);
}
// ----------------------------------------------------------------------
// helper methods
// ----------------------------------------------------------------------
private void setPermissions(PermissionSet ps, Permission... permissions) {
List<String> uris = new ArrayList<String>();
for (Permission p : permissions) {
uris.add(p.getUri());
}
ps.setPermissionUris(uris);
}
private HasPermission id(Permission p) {
return new HasPermission(p);
}
private <T> List<T> list(T... elements) {
List<T> l = new ArrayList<T>();
for (T element : elements) {
l.add(element);
}
return l;
}
private void assertEqualIds(String message, IdentifierBundle expected,
IdentifierBundle actual) {
Set<HasPermission> expectedSet = new HashSet<HasPermission>();
for (Identifier id : expected) {
expectedSet.add((HasPermission) id);
}
Set<HasPermission> actualSet = new HashSet<HasPermission>();
for (Identifier id : actual) {
actualSet.add((HasPermission) id);
}
assertEqualSets(message, expectedSet, actualSet);
}
private static class MyPermission extends Permission {
public MyPermission(String uri) {
super(uri);
}
@Override
public boolean isAuthorized(RequestedAction whatToAuth) {
return false;
}
}
}

View file

@ -0,0 +1,100 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.identifier.factory;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import stubs.edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDaoStub;
import stubs.edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactoryStub;
import stubs.edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccessFactoryStub;
import stubs.javax.servlet.ServletContextStub;
import stubs.javax.servlet.http.HttpServletRequestStub;
import stubs.javax.servlet.http.HttpSessionStub;
import edu.cornell.mannlib.vedit.beans.LoginStatusBean;
import edu.cornell.mannlib.vedit.beans.LoginStatusBean.AuthenticationSource;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.ArrayIdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.common.IsRootUser;
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
/**
* Can we tell whether a user is logged in as root?
*/
public class IsRootUserFactoryTest extends AbstractTestClass {
private static final String PLAIN_USER_URI = "http://userUri";
private static final String ROOT_USER_URI = "http://rootUri";
private WebappDaoFactoryStub wdf;
private UserAccountsDaoStub uaDao;
private ServletContextStub ctx;
private HttpSessionStub session;
private HttpServletRequestStub req;
private IsRootUserFactory factory;
private IdentifierBundle actualIds;
private IdentifierBundle expectedIds;
@Before
public void setup() {
UserAccount plainUser = new UserAccount();
plainUser.setUri(PLAIN_USER_URI);
UserAccount rootUser = new UserAccount();
rootUser.setUri(ROOT_USER_URI);
rootUser.setRootUser(true);
uaDao = new UserAccountsDaoStub();
uaDao.addUser(plainUser);
uaDao.addUser(rootUser);
wdf = new WebappDaoFactoryStub();
wdf.setUserAccountsDao(uaDao);
ctx = new ServletContextStub();
new ModelAccessFactoryStub().get(ctx).setWebappDaoFactory(wdf);
session = new HttpSessionStub();
session.setServletContext(ctx);
req = new HttpServletRequestStub();
req.setSession(session);
factory = new IsRootUserFactory(ctx);
}
@Test
public void notLoggedIn() {
expectedIds = new ArrayIdentifierBundle();
actualIds = factory.getIdentifierBundle(req);
assertEquals("empty bundle", expectedIds, actualIds);
}
@Test
public void loggedInNotRoot() {
LoginStatusBean lsb = new LoginStatusBean(PLAIN_USER_URI,
AuthenticationSource.EXTERNAL);
LoginStatusBean.setBean(session, lsb);
expectedIds = new ArrayIdentifierBundle();
actualIds = factory.getIdentifierBundle(req);
assertEquals("not root", expectedIds, actualIds);
}
@Test
public void loggedInAsRoot() {
LoginStatusBean lsb = new LoginStatusBean(ROOT_USER_URI,
AuthenticationSource.EXTERNAL);
LoginStatusBean.setBean(session, lsb);
expectedIds = new ArrayIdentifierBundle(IsRootUser.INSTANCE);
actualIds = factory.getIdentifierBundle(req);
assertEquals("root", expectedIds, actualIds);
}
}

View file

@ -0,0 +1,83 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.identifier.factory;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import stubs.edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDaoStub;
import stubs.edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactoryStub;
import stubs.edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccessFactoryStub;
import stubs.javax.servlet.ServletContextStub;
import stubs.javax.servlet.http.HttpServletRequestStub;
import stubs.javax.servlet.http.HttpSessionStub;
import edu.cornell.mannlib.vedit.beans.LoginStatusBean;
import edu.cornell.mannlib.vedit.beans.LoginStatusBean.AuthenticationSource;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.ArrayIdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.common.IsUser;
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
/**
* The simplest of the IdentifierBundleFactory classes.
*/
public class IsUserFactoryTest extends AbstractTestClass {
private static final String USER_URI = "http://userUri";
private WebappDaoFactoryStub wdf;
private UserAccountsDaoStub uaDao;
private ServletContextStub ctx;
private HttpSessionStub session;
private HttpServletRequestStub req;
private IsUserFactory factory;
private IdentifierBundle actualIds;
private IdentifierBundle expectedIds;
@Before
public void setup() {
uaDao = new UserAccountsDaoStub();
wdf = new WebappDaoFactoryStub();
wdf.setUserAccountsDao(uaDao);
ctx = new ServletContextStub();
new ModelAccessFactoryStub().get(ctx).setWebappDaoFactory(wdf);
session = new HttpSessionStub();
session.setServletContext(ctx);
req = new HttpServletRequestStub();
req.setSession(session);
factory = new IsUserFactory(ctx);
}
@Test
public void notLoggedIn() {
expectedIds = new ArrayIdentifierBundle();
actualIds = factory.getIdentifierBundle(req);
assertEquals("empty bundle", expectedIds, actualIds);
}
@Test
public void loggedIn() {
LoginStatusBean lsb = new LoginStatusBean(USER_URI,
AuthenticationSource.EXTERNAL);
LoginStatusBean.setBean(session, lsb);
UserAccount user = new UserAccount();
user.setUri(USER_URI);
uaDao.addUser(user);
expectedIds = new ArrayIdentifierBundle(new IsUser(USER_URI));
actualIds = factory.getIdentifierBundle(req);
assertEquals("user id", expectedIds, actualIds);
}
}

View file

@ -0,0 +1,145 @@
/* $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.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
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.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.AuthorizationRequest;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.RequestedAction;
/**
* Test the ability of the Policy Helper to authorize a variety of simple or
* complex AuthorizationRequests
*/
public class PolicyHelper_AuthorizationRequestTest {
private ServletContextStub ctx;
private HttpServletRequestStub req;
private AuthorizationRequest nullAr = null;
@Before
public void setup() {
ctx = new ServletContextStub();
HttpSessionStub session = new HttpSessionStub();
session.setServletContext(ctx);
req = new HttpServletRequestStub();
req.setSession(session);
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
private void createPolicy(RequestedAction... authorizedActions) {
ServletPolicyList.addPolicy(ctx, new MySimplePolicy(authorizedActions));
}
@Test
public void authorizedForActionsNull() {
createPolicy();
assertTrue("null actions",
PolicyHelper.isAuthorizedForActions(req, nullAr));
}
@Test
public void authorizedForActionsEmpty() {
createPolicy();
assertTrue("empty actions", PolicyHelper.isAuthorizedForActions(req));
}
@Test
public void authorizedForActionsAndPass() {
createPolicy(new Action1(), new Action2());
assertTrue("and pass", PolicyHelper.isAuthorizedForActions(req,
new Action1(), new Action2()));
}
@Test
public void authorizedForActionsAndFail() {
createPolicy(new Action2());
assertFalse("and fail", PolicyHelper.isAuthorizedForActions(req,
new Action1(), new Action2()));
}
@Test
public void authorizedForActionsAndOrPass() {
createPolicy(new Action3());
assertTrue(
"and-or pass",
PolicyHelper.isAuthorizedForActions(req,
new Action1().and(new Action2()).or(new Action3())));
}
@Test
public void authorizedForActionsAndOrFail() {
createPolicy(new Action1());
assertFalse(
"and-or fail",
PolicyHelper.isAuthorizedForActions(req,
new Action1().and(new Action2()).or(new Action3())));
}
@Test
public void authorizedByACombinationOfPolicies() {
ServletPolicyList.addPolicy(ctx, new MySimplePolicy(new Action1()));
ServletPolicyList.addPolicy(ctx, new MySimplePolicy(new Action2()));
assertTrue("combination of policies",
PolicyHelper.isAuthorizedForActions(req, new Action2(),
new Action1()));
}
// ----------------------------------------------------------------------
// 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

@ -0,0 +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.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

@ -0,0 +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.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

@ -0,0 +1,393 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.policy;
import static edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization.AUTHORIZED;
import static edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization.INCONCLUSIVE;
import static edu.cornell.mannlib.vitro.webapp.auth.requestedAction.RequestedAction.SOME_LITERAL;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.Before;
import org.junit.Test;
import stubs.edu.cornell.mannlib.vitro.webapp.auth.policy.bean.PropertyRestrictionBeanStub;
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 edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.ArrayIdentifierBundle;
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.ifaces.Authorization;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.RequestedAction;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.admin.AddNewUser;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.admin.LoadOntology;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.admin.RebuildTextIndex;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.admin.RemoveUser;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.admin.ServerStatus;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.admin.UpdateTextIndex;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ontology.CreateOwlClass;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ontology.DefineDataProperty;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ontology.DefineObjectProperty;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ontology.RemoveOwlClass;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.AddDataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.AddObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.DropObjectPropertyStatement;
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.IndividualImpl;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
public class SelfEditingPolicyTest extends AbstractTestClass {
private static final String SAFE_NS = "http://test.mannlib.cornell.edu/ns/01#";
private static final String UNSAFE_NS = VitroVocabulary.vitroURI;
private static final String SELFEDITOR_URI = SAFE_NS + "individual244";
private static final String SAFE_RESOURCE = SAFE_NS
+ "otherIndividual77777";
private static final String UNSAFE_RESOURCE = UNSAFE_NS
+ "otherIndividual99999";
private static final Property SAFE_PREDICATE = new Property(SAFE_NS + "hasHairStyle");
private static final Property UNSAFE_PREDICATE = new Property(UNSAFE_NS + "hasSuperPowers");
private ServletContextStub ctx;
private SelfEditingPolicy policy;
private IdentifierBundle ids;
private RequestedAction whatToAuth;
private OntModel ontModel;
@Before
public void setUp() throws Exception {
ctx = new ServletContextStub();
PropertyRestrictionBeanStub
.getInstance(new String[] { UNSAFE_NS });
policy = new SelfEditingPolicy(ctx);
IndividualImpl ind = new IndividualImpl();
ind.setURI(SELFEDITOR_URI);
ids = new ArrayIdentifierBundle(new HasProfile(SELFEDITOR_URI));
ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
}
@Test
public void testProhibitedProperties() {
PropertyRestrictionBeanStub
.getInstance(new String[] { UNSAFE_NS }, new String[] {
"http://mannlib.cornell.edu/bad#prp234",
"http://mannlib.cornell.edu/bad#prp999",
"http://mannlib.cornell.edu/bad#prp333",
"http://mannlib.cornell.edu/bad#prp777",
"http://mannlib.cornell.edu/bad#prp0020" });
whatToAuth = new AddObjectPropertyStatement(ontModel, SELFEDITOR_URI,
new Property("http://mannlib.cornell.edu/bad#prp234"), SAFE_RESOURCE);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
whatToAuth = new AddObjectPropertyStatement(ontModel, SAFE_RESOURCE,
new Property("http://mannlib.cornell.edu/bad#prp234"), SELFEDITOR_URI);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
whatToAuth = new AddObjectPropertyStatement(ontModel, SELFEDITOR_URI,
new Property("http://mannlib.cornell.edu/bad#prp999"), SAFE_RESOURCE);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
whatToAuth = new AddObjectPropertyStatement(ontModel, SAFE_RESOURCE,
new Property("http://mannlib.cornell.edu/bad#prp999"), SELFEDITOR_URI);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
whatToAuth = new AddObjectPropertyStatement(ontModel, SAFE_RESOURCE,
SAFE_PREDICATE, SELFEDITOR_URI);
assertDecision(AUTHORIZED, policy.isAuthorized(ids, whatToAuth));
whatToAuth = new AddObjectPropertyStatement(ontModel, SELFEDITOR_URI,
SAFE_PREDICATE, SAFE_RESOURCE);
assertDecision(AUTHORIZED, policy.isAuthorized(ids, whatToAuth));
whatToAuth = new AddObjectPropertyStatement(ontModel, SELFEDITOR_URI,
UNSAFE_PREDICATE, SAFE_RESOURCE);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
// now with dataprop statements
whatToAuth = new AddDataPropertyStatement(ontModel, SELFEDITOR_URI,
"http://mannlib.cornell.edu/bad#prp234", SOME_LITERAL);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
whatToAuth = new AddDataPropertyStatement(ontModel, SELFEDITOR_URI,
"http://mannlib.cornell.edu/bad#prp999", SOME_LITERAL);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
whatToAuth = new AddDataPropertyStatement(ontModel, SELFEDITOR_URI,
SAFE_PREDICATE.getURI(), SOME_LITERAL);
assertDecision(AUTHORIZED, policy.isAuthorized(ids, whatToAuth));
whatToAuth = new AddDataPropertyStatement(ontModel, SELFEDITOR_URI,
UNSAFE_PREDICATE.getURI(), SOME_LITERAL);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
}
@Test
public void testVisitIdentifierBundleAddObjectPropStmt() {
whatToAuth = new AddObjectPropertyStatement(ontModel, SELFEDITOR_URI,
SAFE_PREDICATE, SAFE_RESOURCE);
assertDecision(AUTHORIZED, policy.isAuthorized(ids, whatToAuth));
whatToAuth = new AddObjectPropertyStatement(ontModel, SAFE_RESOURCE,
SAFE_PREDICATE, SELFEDITOR_URI);
assertDecision(AUTHORIZED, policy.isAuthorized(ids, whatToAuth));
// this is the case where the editor is not part of the stmt
whatToAuth = new AddObjectPropertyStatement(ontModel, SAFE_RESOURCE,
SAFE_PREDICATE, SAFE_RESOURCE);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
whatToAuth = new AddObjectPropertyStatement(ontModel, SELFEDITOR_URI,
UNSAFE_PREDICATE, SAFE_RESOURCE);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
whatToAuth = new AddObjectPropertyStatement(ontModel, SELFEDITOR_URI,
SAFE_PREDICATE, UNSAFE_RESOURCE);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
}
//
// @Test
// public void testVisitIdentifierBundleDropResource() {
// fail("Not yet implemented");
// }
//
// @Test
// public void testVisitIdentifierBundleDropDataPropStmt() {
// fail("Not yet implemented");
// }
//
@Test
public void testVisitIdentifierBundleDropObjectPropStmt() {
whatToAuth = new DropObjectPropertyStatement(ontModel, SELFEDITOR_URI,
SAFE_PREDICATE, SAFE_RESOURCE);
assertDecision(AUTHORIZED, policy.isAuthorized(ids, whatToAuth));
whatToAuth = new DropObjectPropertyStatement(ontModel, SAFE_RESOURCE,
SAFE_PREDICATE, SELFEDITOR_URI);
assertDecision(AUTHORIZED, policy.isAuthorized(ids, whatToAuth));
// this is the case where the editor is not part of the stmt
whatToAuth = new DropObjectPropertyStatement(ontModel, SAFE_RESOURCE,
SAFE_PREDICATE, SAFE_RESOURCE);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
whatToAuth = new DropObjectPropertyStatement(ontModel, SELFEDITOR_URI,
UNSAFE_PREDICATE, SAFE_RESOURCE);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
whatToAuth = new DropObjectPropertyStatement(ontModel, SELFEDITOR_URI,
SAFE_PREDICATE, UNSAFE_RESOURCE);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
}
//
// @Test
// public void testVisitIdentifierBundleAddResource() {
// fail("Not yet implemented");
// }
//
// @Test
// public void testVisitIdentifierBundleAddDataPropStmt() {
// fail("Not yet implemented");
// }
//
// @Test
// public void testVisitIdentifierBundleUploadFile() {
// fail("Not yet implemented");
// }
//
//
@Test
public void testVisitIdentifierBundleEditDataPropStmt() {
whatToAuth = new EditDataPropertyStatement(ontModel, SELFEDITOR_URI,SAFE_PREDICATE.getURI(), SOME_LITERAL);
assertDecision(AUTHORIZED, policy.isAuthorized(ids, whatToAuth));
whatToAuth = new EditDataPropertyStatement(ontModel, SELFEDITOR_URI, UNSAFE_PREDICATE.getURI(), SOME_LITERAL);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
whatToAuth = new EditDataPropertyStatement(ontModel, UNSAFE_RESOURCE, SAFE_PREDICATE.getURI(), SOME_LITERAL);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
whatToAuth = new EditDataPropertyStatement(ontModel, SAFE_RESOURCE, SAFE_PREDICATE.getURI(), SOME_LITERAL);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
}
@Test
public void testVisitIdentifierBundleEditObjPropStmt() {
whatToAuth = new EditObjectPropertyStatement(ontModel, SELFEDITOR_URI,
SAFE_PREDICATE, SAFE_RESOURCE);
assertDecision(AUTHORIZED, policy.isAuthorized(ids, whatToAuth));
whatToAuth = new EditObjectPropertyStatement(ontModel, SAFE_RESOURCE,
SAFE_PREDICATE, SELFEDITOR_URI);
assertDecision(AUTHORIZED, policy.isAuthorized(ids, whatToAuth));
// this is the case where the editor is not part of the stmt
whatToAuth = new EditObjectPropertyStatement(ontModel, SAFE_RESOURCE,
SAFE_PREDICATE, SAFE_RESOURCE);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
whatToAuth = new EditObjectPropertyStatement(ontModel, SELFEDITOR_URI,
UNSAFE_PREDICATE, SAFE_RESOURCE);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
whatToAuth = new EditObjectPropertyStatement(ontModel, SELFEDITOR_URI,
SAFE_PREDICATE, UNSAFE_RESOURCE);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
}
// ----------------------------------------------------------------------
// What if there are two SelfEditor Identifiers?
// ----------------------------------------------------------------------
@Test
public void twoSEIsFindObjectPropertySubject() {
setUpTwoSEIs();
whatToAuth = new DropObjectPropertyStatement(ontModel, SELFEDITOR_URI,
SAFE_PREDICATE, SAFE_RESOURCE);
assertDecision(AUTHORIZED, policy.isAuthorized(ids, whatToAuth));
}
@Test
public void twoSEIsFindObjectPropertyObject() {
setUpTwoSEIs();
whatToAuth = new DropObjectPropertyStatement(ontModel, SAFE_RESOURCE,
SAFE_PREDICATE, SELFEDITOR_URI);
assertDecision(AUTHORIZED, policy.isAuthorized(ids, whatToAuth));
}
@Test
public void twoSEIsDontFindInObjectProperty() {
setUpTwoSEIs();
whatToAuth = new DropObjectPropertyStatement(ontModel, SAFE_RESOURCE,
SAFE_PREDICATE, SAFE_RESOURCE);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
}
@Test
public void twoSEIsFindDataPropertySubject() {
setUpTwoSEIs();
whatToAuth = new EditDataPropertyStatement(ontModel, SELFEDITOR_URI, SAFE_PREDICATE.getURI(), SOME_LITERAL);
assertDecision(AUTHORIZED, policy.isAuthorized(ids, whatToAuth));
}
@Test
public void twoSEIsDontFindInDataProperty() {
setUpTwoSEIs();
whatToAuth = new EditDataPropertyStatement(ontModel, SAFE_RESOURCE, SAFE_PREDICATE.getURI(), SOME_LITERAL);
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, whatToAuth));
}
private void setUpTwoSEIs() {
ids = new ArrayIdentifierBundle();
IndividualImpl ind1 = new IndividualImpl();
ind1.setURI(SAFE_NS + "bozoUri");
ids.add(new HasProfile(ind1.getURI()));
IndividualImpl ind2 = new IndividualImpl();
ind2.setURI(SELFEDITOR_URI);
ids.add(new HasProfile(ind2.getURI()));
}
// ----------------------------------------------------------------------
// Ignore administrative requests.
// ----------------------------------------------------------------------
@Test
public void testServerStatus() {
assertDecision(INCONCLUSIVE,
policy.isAuthorized(ids, new ServerStatus()));
}
@Test
public void testCreateOwlClass() {
CreateOwlClass a = new CreateOwlClass();
a.setSubjectUri("http://someClass/test");
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, a));
}
@Test
public void testRemoveOwlClass() {
RemoveOwlClass a = new RemoveOwlClass();
a.setSubjectUri("http://someClass/test");
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, a));
}
@Test
public void testDefineDataProperty() {
DefineDataProperty a = new DefineDataProperty();
a.setSubjectUri("http://someClass/test");
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, a));
}
@Test
public void testDefineObjectProperty() {
DefineObjectProperty a = new DefineObjectProperty();
a.setSubjectUri("http://someClass/test");
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, a));
}
@Test
public void testAddNewUser() {
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, new AddNewUser()));
}
@Test
public void testRemoveUser() {
assertDecision(INCONCLUSIVE, policy.isAuthorized(ids, new RemoveUser()));
}
@Test
public void testLoadOntology() {
assertDecision(INCONCLUSIVE,
policy.isAuthorized(ids, new LoadOntology()));
}
@Test
public void testRebuildTextIndex() {
assertDecision(INCONCLUSIVE,
policy.isAuthorized(ids, new RebuildTextIndex()));
}
@Test
public void testVisitIdentifierBundleUpdateTextIndex() {
assertDecision(INCONCLUSIVE,
policy.isAuthorized(ids, new UpdateTextIndex()));
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
private void assertDecision(Authorization expectedAuth,
PolicyDecision decision) {
if (expectedAuth == null) {
assertNull("expecting null decision", decision);
} else {
assertNotNull("expecting a decision", decision);
assertEquals("wrong authorization", expectedAuth,
decision.getAuthorized());
}
}
}

View file

@ -0,0 +1,297 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.policy;
import static edu.cornell.mannlib.vitro.webapp.auth.requestedAction.RequestedAction.SOME_LITERAL;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import stubs.edu.cornell.mannlib.vitro.webapp.auth.policy.bean.PropertyRestrictionBeanStub;
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 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.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.beans.Property;
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 {
ServletContextStub ctx = new ServletContextStub();
PropertyRestrictionBeanStub.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, new Property(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, new Property(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, new Property(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, SOME_LITERAL);
PolicyDecision dec = policy.isAuthorized(ids, whatToAuth);
log.debug(dec);
Assert.assertNotNull(dec);
Assert.assertEquals(expectedAuthorization, dec.getAuthorized());
}
}

View file

@ -0,0 +1,511 @@
/* $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.auth.policy.bean.PropertyRestrictionLevels.Which.DISPLAY;
import static edu.cornell.mannlib.vitro.webapp.auth.policy.bean.PropertyRestrictionLevels.Which.MODIFY;
import static edu.cornell.mannlib.vitro.webapp.auth.policy.bean.PropertyRestrictionLevels.Which.PUBLISH;
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 org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import stubs.edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDaoStub;
import stubs.edu.cornell.mannlib.vitro.webapp.dao.FauxPropertyDaoStub;
import stubs.edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyDaoStub;
import stubs.edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactoryStub;
import stubs.edu.cornell.mannlib.vitro.webapp.modelaccess.ContextModelAccessStub;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.auth.policy.bean.PropertyRestrictionLevels.Which;
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel;
import edu.cornell.mannlib.vitro.webapp.beans.FauxProperty;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
import edu.cornell.mannlib.vitro.webapp.dao.PropertyDao.FullPropertyKey;
/**
* If we believe that authorization will succeed regardless of user role, check
* that it succeeds with the lowest role.
*
* If we believe that authorization will fail regardless of user role, check
* that it fails with the highest role.
*
* If we believe that authorization depends on the user role, it should pass if
* the user role is higher than or equal to the threshold, and fail if the user
* role is less than the threshold.
*
* Note that we can't set a threshold to be tested to either the lowest or
* highest role, or the attempt to test with higher or lower role will throw an
* exception.
*/
public class PropertyRestrictionBeanImplTest extends AbstractTestClass {
private static final String NS_PROHIBITED = "http://prbi.prohibited/";
private static final String URI_RESOURCE_EXCEPTIONAL = NS_PROHIBITED
+ "exceptionalResource";
private static final String URI_PREDICATE_EXCEPTIONAL = NS_PROHIBITED
+ "exceptionalPredicate";
private static final List<String> PROHIBITED_NAMESPACES = Arrays
.asList(new String[] { NS_PROHIBITED });
private static final List<String> PERMITTED_EXCEPTIONS = Arrays
.asList(new String[] { URI_RESOURCE_EXCEPTIONAL,
URI_PREDICATE_EXCEPTIONAL });
private static final String URI_RESOURCE_ANY = "http://prbi.test/anyResource";
private static final String URI_RESOURCE_PROHIBITED = NS_PROHIBITED
+ "resource";
private static final String URI_PREDICATE_BARE = "http://prbi.test/barePredicate";
private static final String URI_PREDICATE_PROHIBITED = NS_PROHIBITED
+ "predicate";
private static final String URI_PREDICATE_UNKNOWN = "http://prbi.test/unknownPredicate";
private static final String URI_DOMAIN_1 = "http://prbi.test/domain1";
private static final String URI_RANGE_1 = "http://prbi.test/range1";
private static final String URI_DOMAIN_2 = "http://prbi.test/domain2";
private static final String URI_RANGE_2 = "http://prbi.test/range2";
private PropertyRestrictionBeanImpl bean;
private ObjectProperty barePredicate;
private ObjectProperty prohibitedPredicate;
private ObjectProperty exceptionalPredicate;
private ObjectProperty unknownPredicate;
private FauxProperty emptyFaux;
private FauxProperty restrictedFaux;
private FauxProperty unknownFaux;
@Before
public void setup() {
barePredicate = createObjectProperty(null, URI_PREDICATE_BARE, null,
EDITOR, CURATOR, DB_ADMIN);
unknownPredicate = createObjectProperty(null, URI_PREDICATE_UNKNOWN,
null, null, null, null);
prohibitedPredicate = createObjectProperty(null,
URI_PREDICATE_PROHIBITED, null, null, null, null);
exceptionalPredicate = createObjectProperty(null,
URI_PREDICATE_EXCEPTIONAL, null, CURATOR, EDITOR, EDITOR);
emptyFaux = createFauxProperty(URI_DOMAIN_1, URI_PREDICATE_BARE,
URI_RANGE_1, null, null, null);
restrictedFaux = createFauxProperty(URI_DOMAIN_2, URI_PREDICATE_BARE,
URI_RANGE_2, EDITOR, DB_ADMIN, CURATOR);
unknownFaux = createFauxProperty(URI_DOMAIN_1, URI_PREDICATE_UNKNOWN,
URI_RANGE_1, NOBODY, NOBODY, NOBODY);
ObjectPropertyDaoStub opDao = new ObjectPropertyDaoStub();
opDao.addObjectProperty(barePredicate);
opDao.addObjectProperty(prohibitedPredicate);
opDao.addObjectProperty(exceptionalPredicate);
DataPropertyDaoStub dpDao = new DataPropertyDaoStub();
FauxPropertyDaoStub fpDao = new FauxPropertyDaoStub();
fpDao.insertFauxProperty(emptyFaux);
fpDao.insertFauxProperty(restrictedFaux);
WebappDaoFactoryStub wadf = new WebappDaoFactoryStub();
wadf.setObjectPropertyDao(opDao);
wadf.setDataPropertyDao(dpDao);
wadf.setFauxPropertyDao(fpDao);
ContextModelAccessStub models = new ContextModelAccessStub();
models.setWebappDaoFactory(wadf);
bean = new PropertyRestrictionBeanImpl(PROHIBITED_NAMESPACES,
PERMITTED_EXCEPTIONS, models);
}
private ObjectProperty createObjectProperty(String domainUri, String uri,
String rangeUri, RoleLevel displayThreshold,
RoleLevel modifyThreshold, RoleLevel publishThreshold) {
ObjectProperty op = new ObjectProperty();
op.setURI(uri);
op.setDomainVClassURI(domainUri);
op.setRangeVClassURI(rangeUri);
op.setHiddenFromDisplayBelowRoleLevel(displayThreshold);
op.setProhibitedFromUpdateBelowRoleLevel(modifyThreshold);
op.setHiddenFromPublishBelowRoleLevel(publishThreshold);
return op;
}
private FauxProperty createFauxProperty(String domainUri, String uri,
String rangeUri, RoleLevel displayThreshold,
RoleLevel modifyThreshold, RoleLevel publishThreshold) {
FauxProperty fp = new FauxProperty(domainUri, uri, rangeUri);
fp.setHiddenFromDisplayBelowRoleLevel(displayThreshold);
fp.setProhibitedFromUpdateBelowRoleLevel(modifyThreshold);
fp.setHiddenFromPublishBelowRoleLevel(publishThreshold);
return fp;
}
// ----------------------------------------------------------------------
// Resources
// ----------------------------------------------------------------------
@Test
public void nullResource_display_false() {
assertFalse(bean.canDisplayResource(null, highestRole()));
}
@Test
public void anyResource_display_true() {
assertTrue(bean.canDisplayResource(URI_RESOURCE_ANY, lowestRole()));
}
@Test
public void anyResource_nullUserRole_display_false() {
assertFalse(bean.canDisplayResource(URI_RESOURCE_ANY, null));
}
@Test
public void nullResource_modify_false() {
assertFalse(bean.canModifyResource(null, highestRole()));
}
@Test
public void prohibitedResource_modify_false() {
assertFalse(bean.canModifyResource(URI_RESOURCE_PROHIBITED,
highestRole()));
}
@Test
public void exceptionalResource_modify_true() {
assertTrue(bean.canModifyResource(URI_RESOURCE_EXCEPTIONAL,
lowestRole()));
}
@Test
public void unremarkableResource_modify_true() {
assertTrue(bean.canModifyResource(URI_RESOURCE_ANY, lowestRole()));
}
@Test
public void unremarkableResource_nullUserRole_modify_false() {
assertFalse(bean.canModifyResource(URI_RESOURCE_ANY, null));
}
@Test
public void nullResource_publish_false() {
assertFalse(bean.canPublishResource(null, highestRole()));
}
@Test
public void anyResource_publish_true() {
assertTrue(bean.canPublishResource(URI_RESOURCE_ANY, lowestRole()));
}
@Test
public void anyResource_nullUserRole_publish_false() {
assertFalse(bean.canPublishResource(URI_RESOURCE_ANY, null));
}
// ----------------------------------------------------------------------
// Predicates
// ----------------------------------------------------------------------
// ----- display
@Test
public void nullPredicate_display_false() {
assertFalse(bean.canDisplayPredicate(null, highestRole()));
}
@Test
public void barePredicate_display_byRole() {
assertTrue(bean.canDisplayPredicate(barePredicate,
higherRole(barePredicate, DISPLAY)));
assertTrue(bean.canDisplayPredicate(barePredicate,
sameRole(barePredicate, DISPLAY)));
assertFalse(bean.canDisplayPredicate(barePredicate,
lowerRole(barePredicate, DISPLAY)));
}
@Test
public void unknownBarePredicate_display_true() {
assertTrue(bean.canDisplayPredicate(unknownPredicate, lowestRole()));
}
@Test
public void emptyQualifiedPredicate_display_byBareRole() {
assertTrue(bean.canDisplayPredicate(asProperty(emptyFaux),
higherRole(barePredicate, DISPLAY)));
assertTrue(bean.canDisplayPredicate(asProperty(emptyFaux),
sameRole(barePredicate, DISPLAY)));
assertFalse(bean.canDisplayPredicate(asProperty(emptyFaux),
lowerRole(barePredicate, DISPLAY)));
}
@Test
public void restrictedQualifiedPredicate_display_byRole() {
assertTrue(bean.canDisplayPredicate(asProperty(restrictedFaux),
higherRole(restrictedFaux, DISPLAY)));
assertTrue(bean.canDisplayPredicate(asProperty(restrictedFaux),
sameRole(restrictedFaux, DISPLAY)));
assertFalse(bean.canDisplayPredicate(asProperty(restrictedFaux),
lowerRole(restrictedFaux, DISPLAY)));
}
@Test
public void unknownQualifiedPredicate_display_true() {
assertTrue(bean.canDisplayPredicate(asProperty(unknownFaux),
lowestRole()));
}
// ----- modify
@Test
public void nullPredicate_modify_false() {
assertFalse(bean.canModifyPredicate(null, highestRole()));
}
@Test
public void prohibitedPredicate_modify_false() {
assertFalse(bean.canModifyPredicate(prohibitedPredicate, lowestRole()));
}
@Test
public void exceptionalPredicate_modify_byRole() {
assertTrue(bean.canModifyPredicate(exceptionalPredicate,
higherRole(exceptionalPredicate, MODIFY)));
assertTrue(bean.canModifyPredicate(exceptionalPredicate,
sameRole(exceptionalPredicate, MODIFY)));
assertFalse(bean.canModifyPredicate(exceptionalPredicate,
lowerRole(exceptionalPredicate, MODIFY)));
}
@Test
public void barePredicate_modify_byRole() {
assertTrue(bean.canModifyPredicate(barePredicate,
higherRole(barePredicate, MODIFY)));
assertTrue(bean.canModifyPredicate(barePredicate,
sameRole(barePredicate, MODIFY)));
assertFalse(bean.canModifyPredicate(barePredicate,
lowerRole(barePredicate, MODIFY)));
}
@Test
public void unknownBarePredicate_modify_true() {
assertTrue(bean.canModifyPredicate(unknownPredicate, lowestRole()));
}
@Test
public void emptyQualifiedPredicate_modify_byBareRole() {
assertTrue(bean.canModifyPredicate(asProperty(emptyFaux),
higherRole(barePredicate, MODIFY)));
assertTrue(bean.canModifyPredicate(asProperty(emptyFaux),
sameRole(barePredicate, MODIFY)));
assertFalse(bean.canModifyPredicate(asProperty(emptyFaux),
lowerRole(barePredicate, MODIFY)));
}
@Test
public void restrictedQualifiedPredicate_modify_byRole() {
assertTrue(bean.canModifyPredicate(asProperty(restrictedFaux),
higherRole(restrictedFaux, MODIFY)));
assertTrue(bean.canModifyPredicate(asProperty(restrictedFaux),
sameRole(restrictedFaux, MODIFY)));
assertFalse(bean.canModifyPredicate(asProperty(restrictedFaux),
lowerRole(restrictedFaux, MODIFY)));
}
@Test
public void unknownQualifiedPredicate_modify_true() {
assertTrue(bean.canModifyPredicate(asProperty(unknownFaux),
lowestRole()));
}
// ----- publish
@Test
public void nullPredicate_publish_false() {
assertFalse(bean.canPublishPredicate(null, highestRole()));
}
@Test
public void barePredicate_publish_byRole() {
assertTrue(bean.canPublishPredicate(barePredicate,
higherRole(barePredicate, PUBLISH)));
assertTrue(bean.canPublishPredicate(barePredicate,
sameRole(barePredicate, PUBLISH)));
assertFalse(bean.canPublishPredicate(barePredicate,
lowerRole(barePredicate, PUBLISH)));
}
@Test
public void unknownBarePredicate_publish_true() {
assertTrue(bean.canPublishPredicate(unknownPredicate, lowestRole()));
}
@Test
public void emptyQualifiedPredicate_publish_byBareRole() {
assertTrue(bean.canPublishPredicate(asProperty(emptyFaux),
higherRole(barePredicate, PUBLISH)));
assertTrue(bean.canPublishPredicate(asProperty(emptyFaux),
sameRole(barePredicate, PUBLISH)));
assertFalse(bean.canPublishPredicate(asProperty(emptyFaux),
lowerRole(barePredicate, PUBLISH)));
}
@Test
public void restrictedQualifiedPredicate_publish_byRole() {
assertTrue(bean.canPublishPredicate(asProperty(restrictedFaux),
higherRole(restrictedFaux, PUBLISH)));
assertTrue(bean.canPublishPredicate(asProperty(restrictedFaux),
sameRole(restrictedFaux, PUBLISH)));
assertFalse(bean.canPublishPredicate(asProperty(restrictedFaux),
lowerRole(restrictedFaux, PUBLISH)));
}
@Test
public void unknownQualifiedPredicate_publish_true() {
assertTrue(bean.canPublishPredicate(asProperty(unknownFaux),
lowestRole()));
}
// ----------------------------------------------------------------------
// update permissions
// ----------------------------------------------------------------------
@Test
public void updateToAllowDisplay() {
RoleLevel desiredDisplayLevel = lowerRole(barePredicate, DISPLAY);
assertFalse(bean
.canDisplayPredicate(barePredicate, desiredDisplayLevel));
bean.updateProperty(updatedLevels(barePredicate, desiredDisplayLevel,
sameRole(barePredicate, MODIFY),
sameRole(barePredicate, PUBLISH)));
assertTrue(bean.canDisplayPredicate(barePredicate, desiredDisplayLevel));
}
@Test
public void updateToAllowModify() {
RoleLevel desiredModifyLevel = lowerRole(barePredicate, MODIFY);
assertFalse(bean.canModifyPredicate(barePredicate, desiredModifyLevel));
bean.updateProperty(updatedLevels(barePredicate,
sameRole(barePredicate, DISPLAY), desiredModifyLevel,
sameRole(barePredicate, PUBLISH)));
assertTrue(bean.canModifyPredicate(barePredicate, desiredModifyLevel));
}
@Test
public void updateToAllowPublish() {
RoleLevel desiredPublishLevel = lowerRole(barePredicate, PUBLISH);
assertFalse(bean
.canPublishPredicate(barePredicate, desiredPublishLevel));
bean.updateProperty(updatedLevels(barePredicate,
sameRole(barePredicate, DISPLAY),
sameRole(barePredicate, MODIFY), desiredPublishLevel));
assertTrue(bean.canPublishPredicate(barePredicate, desiredPublishLevel));
}
@Test
public void updateToDisallowDisplay() {
RoleLevel desiredDisplayLevel = sameRole(barePredicate, DISPLAY);
assertTrue(bean.canDisplayPredicate(barePredicate, desiredDisplayLevel));
bean.updateProperty(updatedLevels(barePredicate,
higherRole(barePredicate, DISPLAY),
sameRole(barePredicate, MODIFY),
sameRole(barePredicate, PUBLISH)));
assertFalse(bean
.canDisplayPredicate(barePredicate, desiredDisplayLevel));
}
@Test
public void updateToDisallowModify() {
RoleLevel desiredModifyLevel = sameRole(barePredicate, MODIFY);
assertTrue(bean.canModifyPredicate(barePredicate, desiredModifyLevel));
bean.updateProperty(updatedLevels(barePredicate,
sameRole(barePredicate, DISPLAY),
higherRole(barePredicate, MODIFY),
sameRole(barePredicate, PUBLISH)));
assertFalse(bean.canModifyPredicate(barePredicate, desiredModifyLevel));
}
@Test
public void updateToDisallowPublish() {
RoleLevel desiredPublishLevel = sameRole(barePredicate, PUBLISH);
assertTrue(bean.canPublishPredicate(barePredicate, desiredPublishLevel));
bean.updateProperty(updatedLevels(barePredicate,
sameRole(barePredicate, DISPLAY),
sameRole(barePredicate, MODIFY),
higherRole(barePredicate, PUBLISH)));
assertFalse(bean
.canPublishPredicate(barePredicate, desiredPublishLevel));
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
private RoleLevel lowestRole() {
return RoleLevel.values()[0];
}
private RoleLevel highestRole() {
RoleLevel[] values = RoleLevel.values();
return values[values.length - 1];
}
private RoleLevel sameRole(RoleRestrictedProperty p, Which which) {
switch (which) {
case DISPLAY:
return p.getHiddenFromDisplayBelowRoleLevel();
case MODIFY:
return p.getProhibitedFromUpdateBelowRoleLevel();
default: // PUBLISH
return p.getHiddenFromPublishBelowRoleLevel();
}
}
private RoleLevel lowerRole(RoleRestrictedProperty p, Which which) {
return RoleLevel.values()[sameRole(p, which).ordinal() - 1];
}
private RoleLevel higherRole(RoleRestrictedProperty p, Which which) {
return RoleLevel.values()[sameRole(p, which).ordinal() + 1];
}
private Property asProperty(FauxProperty fp) {
Property p = new Property();
p.setURI(fp.getBaseURI());
p.setDomainVClassURI(fp.getDomainURI());
p.setRangeVClassURI(fp.getRangeURI());
return p;
}
private PropertyRestrictionLevels updatedLevels(RoleRestrictedProperty p,
RoleLevel displayLevel, RoleLevel modifyLevel,
RoleLevel publishLevel) {
return new PropertyRestrictionLevels(new FullPropertyKey(p),
displayLevel, modifyLevel, publishLevel);
}
}

View file

@ -0,0 +1,65 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.requestedAction;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
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.PolicyIface;
/**
* Test the functions of the base class.
*/
public class AuthorizationRequestTest extends AbstractTestClass {
private MyAuth one = new MyAuth("one");
private MyAuth two = new MyAuth("two");
@Test
public void and() {
assertEquals("and", "(MyAuth[one] && MyAuth[two])", one.and(two)
.toString());
}
@Test
public void andNull() {
assertEquals("andNull", "MyAuth[one]", one.and(null).toString());
}
@Test
public void or() {
assertEquals("or", "(MyAuth[one] || MyAuth[two])", one.or(two)
.toString());
}
@Test
public void orNull() {
assertEquals("orNull", "MyAuth[one]", one.or(null).toString());
}
// ----------------------------------------------------------------------
// Helper classes
// ----------------------------------------------------------------------
private static class MyAuth extends AuthorizationRequest {
private final String name;
public MyAuth(String name) {
this.name = name;
}
@Override
public boolean isAuthorized(IdentifierBundle ids, PolicyIface policy) {
throw new RuntimeException(
"AuthorizationRequest.isAuthorized() not implemented.");
}
@Override
public String toString() {
return "MyAuth[" + name + "]";
}
}
}

View file

@ -0,0 +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 org.junit.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

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

View file

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

View file

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

View file

@ -0,0 +1,380 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.accounts.manageproxies;
import static edu.cornell.mannlib.vitro.webapp.controller.accounts.manageproxies.ProxyRelationshipSelectionCriteria.ProxyRelationshipView.BY_PROFILE;
import static edu.cornell.mannlib.vitro.webapp.controller.accounts.manageproxies.ProxyRelationshipSelectionCriteria.ProxyRelationshipView.BY_PROXY;
import static edu.cornell.mannlib.vitro.webapp.controller.accounts.manageproxies.ProxyRelationshipSelectionCriteria.ProxyRelationshipView.DEFAULT_VIEW;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Level;
import org.junit.BeforeClass;
import org.junit.Ignore;
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.controller.accounts.manageproxies.ProxyRelationshipSelectionCriteria.ProxyRelationshipView;
import edu.cornell.mannlib.vitro.webapp.controller.accounts.manageproxies.ProxyRelationshipSelector.Context;
import edu.cornell.mannlib.vitro.webapp.utils.SparqlQueryRunner;
/**
* TODO
*/
public class ProxyRelationshipSelectorTest extends AbstractTestClass {
private static final Log log = LogFactory
.getLog(ProxyRelationshipSelectorTest.class);
private static final String USER_ACCOUNT_DATA_FILENAME = "ProxyRelationshipSelectorTest_UserAccountsModel.n3";
private static final String UNION_DATA_FILENAME = "ProxyRelationshipSelectorTest_UnionModel.n3";
private static final String NS_MINE = "http://vivo.mydomain.edu/individual/";
private static final String MATCHING_PROPERTY = NS_MINE + "matching";
private static final String URL_PROFILE_IMAGE = "http://mydomain.edu/profileImage.jpg";
private static final String URL_SELF_IMAGE = "http://mydomain.edu/selfImage.jpg";
private static OntModel userAccountsModel;
private static OntModel unionModel;
private static Context context;
/** 1, when sorted by proxy */
private static final Relation RELATION_1 = relation(
list(mydomain("userFirstProxy")), list(mydomain("firstProfile")));
/** 2, when sorted by proxy */
private static final Relation RELATION_2 = relation(
list(mydomain("userProxyWithSelfWithBoth")),
list(mydomain("popularProfile")));
/** 3, when sorted by proxy */
private static final Relation RELATION_3 = relation(
list(mydomain("userProxyWithSelfWithNeither")),
list(mydomain("popularProfile")));
/** 4, when sorted by proxy */
private static final Relation RELATION_4 = relation(
list(mydomain("userProxyWithSelfWithNoClassLabel")),
list(mydomain("popularProfile")));
/** 5, when sorted by proxy */
private static final Relation RELATION_5 = relation(
list(mydomain("userProxyWithSelfWithNoImageUrl")),
list(mydomain("popularProfile")));
/** 6, when sorted by proxy */
private static final Relation RELATION_6 = relation(
list(mydomain("userProxyWithNoSelf")),
list(mydomain("popularProfile")));
/** 7, when sorted by proxy */
private static final Relation RELATION_7 = relation(
list(mydomain("userPopularProxy")),
list(mydomain("profileWithBoth"), mydomain("profileWithNeither"),
mydomain("profileWithNoImageUrl"),
mydomain("profileWithNoClassLabel")));
private ProxyRelationshipSelection selection;
private ProxyRelationshipSelectionCriteria criteria;
@BeforeClass
public static void setupModel() throws IOException {
userAccountsModel = prepareModel(USER_ACCOUNT_DATA_FILENAME);
unionModel = prepareModel(UNION_DATA_FILENAME);
context = new Context(userAccountsModel, unionModel, MATCHING_PROPERTY);
}
private static OntModel prepareModel(String filename) throws IOException {
InputStream stream = ProxyRelationshipSelectorTest.class
.getResourceAsStream(filename);
Model model = ModelFactory.createDefaultModel();
model.read(stream, null, "N3");
stream.close();
OntModel ontModel = ModelFactory.createOntologyModel(
OntModelSpec.OWL_DL_MEM, model);
ontModel.prepare();
return ontModel;
}
// ----------------------------------------------------------------------
// exceptions tests
// ----------------------------------------------------------------------
@Test(expected = NullPointerException.class)
public void contextIsNull() {
ProxyRelationshipSelector.select(null,
criteria(10, 1, DEFAULT_VIEW, ""));
}
@Test(expected = NullPointerException.class)
public void userAccountsModelIsNull_select_nullPointerException() {
Context brokenContext = new Context(null, unionModel, MATCHING_PROPERTY);
ProxyRelationshipSelector.select(brokenContext,
criteria(10, 1, DEFAULT_VIEW, ""));
}
@Test(expected = NullPointerException.class)
public void unionModelIsNull_select_nullPointerException() {
Context brokenContext = new Context(userAccountsModel, null,
MATCHING_PROPERTY);
ProxyRelationshipSelector.select(brokenContext,
criteria(10, 1, DEFAULT_VIEW, ""));
}
@Test(expected = NullPointerException.class)
public void criteriaIsNull() {
ProxyRelationshipSelector.select(context, null);
}
// ----------------------------------------------------------------------
// fields tests
// ----------------------------------------------------------------------
@Test
public void checkAllFieldsOnFirstRelationshipByProxy() {
selectOnCriteria(1, 1, BY_PROXY, "");
log.debug("SELECTION: " + selection);
assertExpectedCounts(7, counts(1, 1));
ProxyRelationship pr = selection.getProxyRelationships().get(0);
assertEquals(
"proxy",
item(mydomain("userFirstProxy"), "AAAA, FirstProxy", "Self",
URL_SELF_IMAGE), pr.getProxyInfos().get(0));
assertEquals(
"profile",
item(mydomain("firstProfile"), "AAAA, FirstProfile", "Profile",
URL_PROFILE_IMAGE), pr.getProfileInfos().get(0));
}
@Test
@Ignore
public void checkAllFieldsOnFirstRelationshipByProfile() {
selectOnCriteria(1, 1, BY_PROFILE, "");
assertExpectedCounts(7, counts(1, 1));
ProxyRelationship pr = selection.getProxyRelationships().get(0);
assertEquals(
"proxy",
item(mydomain("userFirstProxy"), "AAAA, FirstProxy", "Self",
URL_SELF_IMAGE), pr.getProxyInfos().get(0));
assertEquals(
"profile",
item(mydomain("firstProfile"), "AAAA, FirstProfile", "Profile",
URL_PROFILE_IMAGE), pr.getProfileInfos().get(0));
}
// ----------------------------------------------------------------------
// pagination tests
// TODO -- also by profile
// ----------------------------------------------------------------------
@Test
public void paginationFirstOfSeveralByProxy() {
selectOnCriteria(3, 1, BY_PROXY, "");
assertExpectedRelations(7, RELATION_1, RELATION_2, RELATION_3);
}
@Test
public void paginationOnlyPageByProxy() {
selectOnCriteria(10, 1, BY_PROXY, "");
assertExpectedRelations(7, RELATION_1, RELATION_2, RELATION_3,
RELATION_4, RELATION_5, RELATION_6, RELATION_7);
}
@Test
public void paginationSecondOfSeveralByProxy() {
selectOnCriteria(3, 2, BY_PROXY, "");
assertExpectedRelations(7, RELATION_4, RELATION_5, RELATION_6);
}
@Test
public void paginationOutOfRangeTooHighByProxy() {
selectOnCriteria(3, 7, BY_PROXY, "");
assertExpectedRelations(7);
}
@Test
@Ignore
public void paginationLastFullPageByProxy() {
fail("paginationLastFullPageByProxy not implemented");
}
@Test
public void paginationLastPartialPageByProxy() {
selectOnCriteria(3, 3, BY_PROXY, "");
assertExpectedRelations(7, RELATION_7);
}
/**
* test plan:
*
* <pre>
* search tests: (repeat both views)
* some results
* no results
* special REGEX characters
*
* profile w/no proxies
* profile w/proxies
* no associated profile
* profile w/no classLabel
* profile w/no imageUrl
* profile w/neither
* profile w/both
*
* proxy w/no profiles
* proxy w profiles:
* no classLabel
* no imageUrl
* neither
* both
* </pre>
*/
// ----------------------------------------------------------------------
// search tests
// TODO search by Profile also
// ----------------------------------------------------------------------
@Test
public void searchFirstProxy() {
selectOnCriteria(10, 1, BY_PROXY, "AA");
assertExpectedRelations(1, RELATION_1);
}
@Test
public void searchAccountWithNoProxy() {
selectOnCriteria(10, 1, BY_PROXY, "None");
assertExpectedRelations(0);
}
@Test
public void searchMultipleProxies() {
selectOnCriteria(10, 1, BY_PROXY, "No");
assertExpectedRelations(3, RELATION_4, RELATION_5, RELATION_6);
}
// ----------------------------------------------------------------------
// combination tests
// ----------------------------------------------------------------------
@Test
public void searchPopularWithPagination() {
selectOnCriteria(2, 2, BY_PROXY, "No");
assertExpectedRelations(3, RELATION_6);
}
// ----------------------------------------------------------------------
// helper methods
// ----------------------------------------------------------------------
/** Create a new criteria object */
private ProxyRelationshipSelectionCriteria criteria(int accountsPerPage,
int pageIndex, ProxyRelationshipView view, String searchTerm) {
return new ProxyRelationshipSelectionCriteria(accountsPerPage,
pageIndex, view, searchTerm);
}
/** Create a criteria object and select against it. */
private void selectOnCriteria(int relationshipsPerPage, int pageIndex,
ProxyRelationshipView viewBy, String searchTerm) {
criteria = new ProxyRelationshipSelectionCriteria(relationshipsPerPage,
pageIndex, viewBy, searchTerm);
selection = ProxyRelationshipSelector.select(context, criteria);
}
private int[] counts(int proxyCount, int profileCount) {
return new int[] { proxyCount, profileCount };
}
private ProxyItemInfo item(String uri, String label, String classLabel,
String imageUrl) {
return new ProxyItemInfo(uri, label, classLabel, imageUrl);
}
private static List<String> list(String... uris) {
return Arrays.asList(uris);
}
private static Relation relation(List<String> proxyUris,
List<String> profileUris) {
return new Relation(proxyUris, profileUris);
}
private static String mydomain(String localName) {
return NS_MINE + localName;
}
private void assertExpectedCounts(int total, int[]... counts) {
assertEquals("total result count", total,
selection.getTotalResultCount());
List<ProxyRelationship> relationships = selection
.getProxyRelationships();
assertEquals("number of returns", counts.length, relationships.size());
for (int i = 0; i < counts.length; i++) {
ProxyRelationship r = relationships.get(i);
assertEquals("number of proxies in result " + i, counts[i][0], r
.getProxyInfos().size());
assertEquals("number of profiles in result " + i, counts[i][1], r
.getProfileInfos().size());
}
}
private void assertExpectedRelations(int total, Relation... relations) {
assertEquals("total result count", total,
selection.getTotalResultCount());
assertEquals("page result count", relations.length, selection
.getProxyRelationships().size());
for (int i = 0; i < relations.length; i++) {
assertEqualUris(i, relations[i], selection.getProxyRelationships()
.get(i));
}
}
private void assertEqualUris(int i, Relation relation,
ProxyRelationship proxyRelationship) {
List<String> expectedProxyUris = relation.proxyUris;
List<String> actualProxyUris = new ArrayList<String>();
for (ProxyItemInfo proxyInfo : proxyRelationship.getProxyInfos()) {
actualProxyUris.add(proxyInfo.getUri());
}
assertEquals("proxies for relationship " + i, expectedProxyUris,
actualProxyUris);
List<String> expectedProfileUris = relation.profileUris;
List<String> actualProfileUris = new ArrayList<String>();
for (ProxyItemInfo profileInfo : proxyRelationship.getProfileInfos()) {
actualProfileUris.add(profileInfo.getUri());
}
assertEquals("profiles for relationship " + i, expectedProfileUris,
actualProfileUris);
}
private static class Relation {
final List<String> proxyUris;
final List<String> profileUris;
public Relation(List<String> proxyUris, List<String> profileUris) {
this.proxyUris = proxyUris;
this.profileUris = profileUris;
}
}
}

View file

@ -0,0 +1,540 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.api.sparqlquery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
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.query.QueryParseException;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
import edu.cornell.mannlib.vitro.webapp.rdfservice.impl.jena.model.RDFServiceModel;
import edu.cornell.mannlib.vitro.webapp.utils.http.NotAcceptableException;
/**
* Test that the SparqlQueryApiExecutor can handle all query types and all
* formats.
*/
public class SparqlQueryApiExecutorTest extends AbstractTestClass {
/* SPARQL response types */
private static final String ACCEPT_TEXT = "text/plain";
private static final String ACCEPT_CSV = "text/csv";
private static final String ACCEPT_TSV = "text/tab-separated-values";
private static final String ACCEPT_SPARQL_XML = "application/sparql-results+xml";
private static final String ACCEPT_SPARQL_JSON = "application/sparql-results+json";
/* RDF result types */
private static final String ACCEPT_RDFXML = "application/rdf+xml";
private static final String ACCEPT_N3 = "text/n3";
private static final String ACCEPT_TURTLE = "text/turtle";
private static final String ACCEPT_JSON = "application/json";
private static final String MODEL_CONTENTS_N3 = "" //
+ "<http://here.edu/subject> \n"
+ " <http://here.edu/predicate> <http://here.edu/object> ."
+ "<http://here.edu/s2> \n"
+ " <http://here.edu/p2> <http://here.edu/o2> .";
private static final String BASE_URI = "http://here.edu";
private static final String SELECT_ALL_QUERY = "SELECT ?s ?p ?o WHERE {?s ?p ?o} ORDER BY DESC(?s)";
private static final String SELECT_RESULT_TEXT = ""
+ "--------------------------------------------------------------------------------------\n"
+ "| s | p | o |\n"
+ "======================================================================================\n"
+ "| <http://here.edu/subject> | <http://here.edu/predicate> | <http://here.edu/object> |\n"
+ "| <http://here.edu/s2> | <http://here.edu/p2> | <http://here.edu/o2> |\n"
+ "--------------------------------------------------------------------------------------\n";
private static final String SELECT_RESULT_CSV = "s,p,o\n"
+ "http://here.edu/subject,http://here.edu/predicate,http://here.edu/object\n"
+ "http://here.edu/s2,http://here.edu/p2,http://here.edu/o2\n";
private static final String SELECT_RESULT_TSV = "s\tp\to\n"
+ "http://here.edu/subject\thttp://here.edu/predicate\thttp://here.edu/object\n"
+ "http://here.edu/s2\thttp://here.edu/p2\thttp://here.edu/o2\n";
private static final String SELECT_RESULT_XML = "" //
+ "<?xml version=\"1.0\"?>\n" //
+ "<sparql xmlns=\"http://www.w3.org/2005/sparql-results#\">\n" //
+ " <head>\n" //
+ " <variable name=\"s\"/>\n" //
+ " <variable name=\"p\"/>\n" //
+ " <variable name=\"o\"/>\n" //
+ " </head>\n" //
+ " <results>\n" //
+ " <result>\n" //
+ " <binding name=\"s\">\n" //
+ " <uri>http://here.edu/subject</uri>\n" //
+ " </binding>\n" //
+ " <binding name=\"p\">\n" //
+ " <uri>http://here.edu/predicate</uri>\n" //
+ " </binding>\n" //
+ " <binding name=\"o\">\n" //
+ " <uri>http://here.edu/object</uri>\n" //
+ " </binding>\n" //
+ " </result>\n" //
+ " <result>\n" //
+ " <binding name=\"s\">\n" //
+ " <uri>http://here.edu/s2</uri>\n" //
+ " </binding>\n" //
+ " <binding name=\"p\">\n" //
+ " <uri>http://here.edu/p2</uri>\n" //
+ " </binding>\n" //
+ " <binding name=\"o\">\n" //
+ " <uri>http://here.edu/o2</uri>\n" //
+ " </binding>\n" //
+ " </result>\n" //
+ " </results>\n" //
+ "</sparql>\n";
private static final String SELECT_RESULT_JSON = "" //
+ "{\n" //
+ " \"head\": {\n" //
+ " \"vars\": [ \"s\" , \"p\" , \"o\" ]\n" //
+ " } ,\n" //
+ " \"results\": {\n" //
+ " \"bindings\": [\n" //
+ " {\n" //
+ " \"s\": { \"type\": \"uri\" , \"value\": \"http://here.edu/subject\" } ,\n"
+ " \"p\": { \"type\": \"uri\" , \"value\": \"http://here.edu/predicate\" } ,\n"
+ " \"o\": { \"type\": \"uri\" , \"value\": \"http://here.edu/object\" }\n"
+ " } ,\n" //
+ " {\n" //
+ " \"s\": { \"type\": \"uri\" , \"value\": \"http://here.edu/s2\" } ,\n"
+ " \"p\": { \"type\": \"uri\" , \"value\": \"http://here.edu/p2\" } ,\n"
+ " \"o\": { \"type\": \"uri\" , \"value\": \"http://here.edu/o2\" }\n"
+ " }\n" //
+ " ]\n" //
+ " }\n" //
+ "}\n";
private static final String ASK_ALL_QUERY = "ASK WHERE {?s ?p ?o}";
private static final String ASK_RESULT_TEXT = "true";
private static final String ASK_RESULT_CSV = "true";
private static final String ASK_RESULT_TSV = "true";
private static final String ASK_RESULT_XML = "" //
+ "<?xml version=\"1.0\"?>\n" //
+ "<sparql xmlns=\"http://www.w3.org/2005/sparql-results#\">\n" //
+ " <head></head>\n" //
+ " <boolean>true</boolean>\n" //
+ "</sparql>";
private static final String ASK_RESULT_JSON = "" //
+ "{\n" //
+ " \"head\" : { } ,\n" //
+ " \"boolean\" : true\n" //
+ "}\n";
private static final String CONSTRUCT_ALL_QUERY = "CONSTRUCT {?s ?p ?o} WHERE { LET (?s := <http://here.edu/subject>) <http://here.edu/subject> ?p ?o}";
private static final String CONSTRUCT_RESULT_TEXT = "" //
+ "<http://here.edu/subject> <http://here.edu/predicate> <http://here.edu/object> .\n";
private static final String CONSTRUCT_RESULT_TURTLE = "" //
+ "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n" //
+ "@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n" //
+ "@prefix owl: <http://www.w3.org/2002/07/owl#> .\n" //
+ "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n" //
+ "\n" //
+ "<http://here.edu/subject>\n" //
+ " <http://here.edu/predicate>\n" //
+ " <http://here.edu/object> .\n";
private static final String CONSTRUCT_RESULT_N3 = "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n"
+ "@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n"
+ "@prefix owl: <http://www.w3.org/2002/07/owl#> .\n"
+ "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n"
+ "\n"
+ "<http://here.edu/subject>\n"
+ " <http://here.edu/predicate>\n"
+ " <http://here.edu/object> .\n";
private static final String CONSTRUCT_RESULT_RDFXML = "<rdf:RDF\n"
+ " xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n"
+ " xmlns:owl=\"http://www.w3.org/2002/07/owl#\"\n"
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"\n"
+ " xmlns:j.0=\"http://here.edu/\"\n"
+ " xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\" > \n"
+ " <rdf:Description rdf:about=\"http://here.edu/subject\">\n"
+ " <j.0:predicate rdf:resource=\"http://here.edu/object\"/>\n"
+ " </rdf:Description>\n" //
+ "</rdf:RDF>\n";
private static final String CONSTRUCT_RESULT_JSONLD = "["
+ "{\"@id\":\"http://here.edu/object\"},"
+ "{\"@id\":\"http://here.edu/subject\",\"http://here.edu/predicate\":[{\"@id\":\"http://here.edu/object\"}]}"
+ "]";
private static final String DESCRIBE_ALL_QUERY = "DESCRIBE <http://here.edu/subject>";
private static final String DESCRIBE_RESULT_TEXT = "<http://here.edu/subject> "
+ "<http://here.edu/predicate> <http://here.edu/object> .\n";
private static final String DESCRIBE_RESULT_RDFXML = "<rdf:RDF\n"
+ " xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n"
+ " xmlns:owl=\"http://www.w3.org/2002/07/owl#\"\n"
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"\n"
+ " xmlns:j.0=\"http://here.edu/\"\n"
+ " xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\" > \n"
+ " <rdf:Description rdf:about=\"http://here.edu/subject\">\n"
+ " <j.0:predicate rdf:resource=\"http://here.edu/object\"/>\n"
+ " </rdf:Description>\n" + "</rdf:RDF>\n";
private static final String DESCRIBE_RESULT_N3 = "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n"
+ "@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n"
+ "@prefix owl: <http://www.w3.org/2002/07/owl#> .\n"
+ "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n"
+ "\n"
+ "<http://here.edu/subject>\n"
+ " <http://here.edu/predicate>\n"
+ " <http://here.edu/object> .\n";
private static final String DESCRIBE_RESULT_TURTLE = "" //
+ "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n" //
+ "@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n" //
+ "@prefix owl: <http://www.w3.org/2002/07/owl#> .\n" //
+ "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n" //
+ "\n" //
+ "<http://here.edu/subject>\n" //
+ " <http://here.edu/predicate>\n" //
+ " <http://here.edu/object> .\n";
private static final String DESCRIBE_RESULT_JSONLD = "["
+ "{\"@id\":\"http://here.edu/object\"},"
+ "{\"@id\":\"http://here.edu/subject\",\"http://here.edu/predicate\":[{\"@id\":\"http://here.edu/object\"}]}"
+ "]";
private OntModel model;
private RDFService rdfService;
@Before
public void setup() {
model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
model.read(new StringReader(MODEL_CONTENTS_N3), BASE_URI, "N3");
rdfService = new RDFServiceModel(model);
}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
@Test(expected = NullPointerException.class)
public void nullRdfService() throws Exception {
SparqlQueryApiExecutor.instance(null, SELECT_ALL_QUERY, ACCEPT_TEXT);
}
@Test(expected = NullPointerException.class)
public void nullQuery() throws Exception {
SparqlQueryApiExecutor.instance(rdfService, null, ACCEPT_TEXT);
fail("nullQuery not implemented");
}
@Test(expected = QueryParseException.class)
public void emptyQuery() throws Exception {
SparqlQueryApiExecutor.instance(rdfService, "", ACCEPT_TEXT);
fail("emptyQuery not implemented");
}
@Test(expected = QueryParseException.class)
public void cantParseQuery() throws Exception {
SparqlQueryApiExecutor.instance(rdfService, "BOGUS", ACCEPT_TEXT);
fail("cantParseQuery not implemented");
}
// Can't figure out how to create a Query of a type other than SELECT, ASK,
// CONSTRUCT and DESCRIBE.
// Null accept header is treated as "*/*"
@Test(expected = NotAcceptableException.class)
public void noAcceptableContentType() throws Exception {
SparqlQueryApiExecutor.instance(rdfService, SELECT_ALL_QUERY, "bogus");
fail("noAcceptableContentType not implemented");
}
// ----------------------------------------------------------------------
@Test
public void selectToText() throws Exception {
executeQuery("select to text", SELECT_ALL_QUERY, ACCEPT_TEXT,
SELECT_RESULT_TEXT);
}
@Test
public void selectToCsv() throws Exception {
executeQuery("select to csv", SELECT_ALL_QUERY, ACCEPT_CSV,
SELECT_RESULT_CSV);
}
@Test
public void selectToTsv() throws Exception {
executeQuery("select to tsv", SELECT_ALL_QUERY, ACCEPT_TSV,
SELECT_RESULT_TSV);
}
@Test
public void selectToXml() throws Exception {
executeQuery("select to xml", SELECT_ALL_QUERY, ACCEPT_SPARQL_XML,
SELECT_RESULT_XML);
}
@Test
public void selectToJson() throws Exception {
executeQuery("select to json", SELECT_ALL_QUERY, ACCEPT_SPARQL_JSON,
SELECT_RESULT_JSON);
}
@Test
public void selectWithInvalidContentType() throws Exception {
executeWithInvalidAcceptHeader("select with application/rdf+xml",
SELECT_ALL_QUERY, ACCEPT_RDFXML);
executeWithInvalidAcceptHeader("select with text/n3", SELECT_ALL_QUERY,
ACCEPT_N3);
executeWithInvalidAcceptHeader("select with text/turtle",
SELECT_ALL_QUERY, ACCEPT_TURTLE);
executeWithInvalidAcceptHeader("select with application/json",
SELECT_ALL_QUERY, ACCEPT_JSON);
}
// ----------------------------------------------------------------------
@Test
public void askToText() throws Exception {
executeQuery("ask to text", ASK_ALL_QUERY, ACCEPT_TEXT, ASK_RESULT_TEXT);
}
@Test
public void askToCsv() throws Exception {
executeQuery("ask to csv", ASK_ALL_QUERY, ACCEPT_CSV, ASK_RESULT_CSV);
}
@Test
public void askToTsv() throws Exception {
executeQuery("ask to tsv", ASK_ALL_QUERY, ACCEPT_TSV, ASK_RESULT_TSV);
}
@Test
public void askToXml() throws Exception {
executeQuery("ask to xml", ASK_ALL_QUERY, ACCEPT_SPARQL_XML,
ASK_RESULT_XML);
}
@Test
public void askToJson() throws Exception {
executeQuery("ask to json", ASK_ALL_QUERY, ACCEPT_SPARQL_JSON,
ASK_RESULT_JSON);
}
@Test
public void askWithInvalidAcceptHeader() throws Exception {
executeWithInvalidAcceptHeader("ask with application/rdf+xml",
ASK_ALL_QUERY, ACCEPT_RDFXML);
executeWithInvalidAcceptHeader("ask with text/n3", ASK_ALL_QUERY,
ACCEPT_N3);
executeWithInvalidAcceptHeader("ask with text/turtle", ASK_ALL_QUERY,
ACCEPT_TURTLE);
executeWithInvalidAcceptHeader("ask with application/json",
ASK_ALL_QUERY, ACCEPT_JSON);
}
// ----------------------------------------------------------------------
@Test
public void constructToText() throws Exception {
executeQuery("construct to text", CONSTRUCT_ALL_QUERY, ACCEPT_TEXT,
CONSTRUCT_RESULT_TEXT);
}
@Test
public void constructToRdfXml() throws Exception {
executeQuery("construct to rdf/xml", CONSTRUCT_ALL_QUERY,
ACCEPT_RDFXML, CONSTRUCT_RESULT_RDFXML);
}
@Test
public void constructToN3() throws Exception {
executeQuery("construct to n3", CONSTRUCT_ALL_QUERY, ACCEPT_N3,
CONSTRUCT_RESULT_N3);
}
@Test
public void constructToTurtle() throws Exception {
executeQuery("construct to turtle", CONSTRUCT_ALL_QUERY, ACCEPT_TURTLE,
CONSTRUCT_RESULT_TURTLE);
}
@Test
public void constructToJsonld() throws Exception {
executeQuery("construct to JSON-LD", CONSTRUCT_ALL_QUERY, ACCEPT_JSON,
CONSTRUCT_RESULT_JSONLD);
}
@Test
public void constructWithInvalidAcceptHeader() throws Exception {
executeWithInvalidAcceptHeader("construct with text/csv",
CONSTRUCT_ALL_QUERY, ACCEPT_CSV);
executeWithInvalidAcceptHeader("construct with text/tsv",
CONSTRUCT_ALL_QUERY, "text/tsv");
executeWithInvalidAcceptHeader(
"construct with application/sparql-results+xml",
CONSTRUCT_ALL_QUERY, ACCEPT_SPARQL_XML);
executeWithInvalidAcceptHeader(
"construct with application/sparql-results+json",
CONSTRUCT_ALL_QUERY, ACCEPT_SPARQL_JSON);
}
// ----------------------------------------------------------------------
@Test
public void describeToText() throws Exception {
executeQuery("describe to text", DESCRIBE_ALL_QUERY, ACCEPT_TEXT,
DESCRIBE_RESULT_TEXT);
}
@Test
public void describeToRdfXml() throws Exception {
executeQuery("describe to rdf/xml", DESCRIBE_ALL_QUERY, ACCEPT_RDFXML,
DESCRIBE_RESULT_RDFXML);
}
@Test
public void describeToN3() throws Exception {
executeQuery("describe to n3", DESCRIBE_ALL_QUERY, ACCEPT_N3,
DESCRIBE_RESULT_N3);
}
@Test
public void describeToTurtle() throws Exception {
executeQuery("describe to turtle", DESCRIBE_ALL_QUERY, ACCEPT_TURTLE,
DESCRIBE_RESULT_TURTLE);
}
@Test
public void describeToJsonld() throws Exception {
executeQuery("describe to JSON-LD", DESCRIBE_ALL_QUERY, ACCEPT_JSON,
DESCRIBE_RESULT_JSONLD);
}
@Test
public void describeWithInvalidAcceptHeader() throws Exception {
executeWithInvalidAcceptHeader("describe with text/csv",
DESCRIBE_ALL_QUERY, ACCEPT_CSV);
executeWithInvalidAcceptHeader("describe with text/tsv",
DESCRIBE_ALL_QUERY, "text/tsv");
executeWithInvalidAcceptHeader(
"describe with application/sparql-results+xml",
DESCRIBE_ALL_QUERY, ACCEPT_SPARQL_XML);
executeWithInvalidAcceptHeader(
"describe with application/sparql-results+json",
DESCRIBE_ALL_QUERY, ACCEPT_SPARQL_JSON);
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
private void executeQuery(String message, String queryString,
String acceptHeader, String expected) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
SparqlQueryApiExecutor executor = SparqlQueryApiExecutor.instance(
rdfService, queryString, acceptHeader);
executor.executeAndFormat(out);
if (ACCEPT_RDFXML.equals(acceptHeader)) {
assertEquivalentRdfxml(message, expected, out.toString());
} else if (ACCEPT_TURTLE.equals(acceptHeader)) {
assertEquivalentTurtle(message, expected, out.toString());
} else if (ACCEPT_N3.equals(acceptHeader)) {
assertEquivalentN3(message, expected, out.toString());
} else {
assertEqualsIgnoreWhiteSpace(message, expected, out.toString());
}
}
/**
* RDF/XML namespaces may come in any order, so separate them out and test
* accordingly.
*/
private void assertEquivalentRdfxml(String message, String expected,
String actual) {
assertEquals(message, getRdfxmlNamespaces(expected),
getRdfxmlNamespaces(actual));
assertEqualsIgnoreWhiteSpace(message, omitRdfxmlNamespaces(expected),
omitRdfxmlNamespaces(actual));
}
private Set<String> getRdfxmlNamespaces(String rdfxml) {
Set<String> namespaces = new TreeSet<>();
Pattern p = Pattern.compile("xmlns:\\w+=\\\"[^\\\"]*\\\"");
Matcher m = p.matcher(rdfxml);
while (m.find()) {
namespaces.add(m.group());
}
return namespaces;
}
private String omitRdfxmlNamespaces(String rdfxml) {
return rdfxml.replaceAll("xmlns:\\w+=\\\"[^\\\"]*\\\"", "");
}
/**
* TTL prefix lines may come in any order, so separate them out and test
* accordingly.
*/
private void assertEquivalentTurtle(String message, String expected,
String actual) {
assertEquals(message, getTurtlePrefixes(expected),
getTurtlePrefixes(actual));
assertEqualsIgnoreWhiteSpace(message, getTurtleRemainder(expected),
getTurtleRemainder(actual));
}
/**
* N3 is like TTL, as far as prefix lines are concerned.
*/
private void assertEquivalentN3(String message, String expected,
String actual) {
assertEquivalentTurtle(message, expected, actual);
}
private Set<String> getTurtlePrefixes(String ttl) {
Set<String> prefixes = new TreeSet<>();
for (String line : ttl.split("[\\n\\r]+")) {
if (line.startsWith("@prefix")) {
prefixes.add(line.replaceAll("\\s+", " "));
}
}
return prefixes;
}
private String getTurtleRemainder(String ttl) {
List<String> remainder = new ArrayList<>();
for (String line : ttl.split("[\\n\\r]+")) {
if (!line.startsWith("@prefix")) {
remainder.add(line);
}
}
return StringUtils.join(remainder, "\n");
}
private void assertEqualsIgnoreWhiteSpace(String message, String expected,
String actual) {
assertEquals(message, expected.replaceAll("\\s+", " "),
actual.replaceAll("\\s+", " "));
}
private void executeWithInvalidAcceptHeader(String message,
String queryString, String acceptHeader) throws Exception {
try {
SparqlQueryApiExecutor.instance(rdfService, queryString,
acceptHeader);
fail(message + " - Expected a NotAcceptableException");
} catch (NotAcceptableException e) {
// expected
}
}
}

View file

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

View file

@ -0,0 +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.PermissionSets;
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(PermissionSets.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

@ -0,0 +1,62 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.datatools.dumprestore;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Level;
import org.junit.BeforeClass;
import org.junit.Test;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.controller.datatools.dumprestore.DumpNode.BadNodeException;
/**
* TODO
*/
public class NQuadLineSplitterTest extends AbstractTestClass {
private static List<String> testData;
@BeforeClass
public static void readTestData() throws IOException {
InputStream stream = NQuadLineSplitterTest.class
.getResourceAsStream("NQuadLineSplitterTest.nq");
testData = IOUtils.readLines(stream);
}
@Test
public void splitLine1() throws BadNodeException {
List<String> strings = new NQuadLineSplitter(getLine(1)).split();
assertEquals("count", 4, strings.size());
assertEquals("subject", "<http://purl.org/ontology/bibo/degree>",
strings.get(0));
assertEquals("predicate",
"<http://purl.obolibrary.org/obo/IAO_0000112>", strings.get(1));
assertEquals(
"object",
"\"The source of the public description and this info is found here: "
+ "http://bibotools.googlecode.com/svn/bibo-ontology/trunk/doc/index.html. "
+ "Bibo considers this term \\\"unstable\\\". "
+ "The bibo editorial note is: \\\"We are not defining, using an enumeration, "
+ "the range of the bibo:degree to the defined list of bibo:ThesisDegree. "
+ "We won't do it because we want people to be able to define new degress "
+ "if needed by some special usecases. "
+ "Creating such an enumeration would restrict this to "
+ "happen.\\\"\"^^<http://www.w3.org/2001/XMLSchema#string>",
strings.get(2));
assertEquals(
"graph",
"<http://vitro.mannlib.cornell.edu/filegraph/tbox/object-properties.owl>",
strings.get(3));
}
private String getLine(int i) {
return testData.get(i - 1);
}
}

View file

@ -0,0 +1,678 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.edit;
import static edu.cornell.mannlib.vitro.webapp.auth.permissions.PermissionSets.URI_DBA;
import static edu.cornell.mannlib.vitro.webapp.auth.permissions.PermissionSets.URI_SELF_EDITOR;
import static edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean.State.FORCED_PASSWORD_CHANGE;
import static edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean.State.LOGGING_IN;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Level;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import stubs.edu.cornell.mannlib.vitro.webapp.config.ConfigurationPropertiesStub;
import stubs.edu.cornell.mannlib.vitro.webapp.dao.IndividualDaoStub;
import stubs.edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDaoStub;
import stubs.edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactoryStub;
import stubs.edu.cornell.mannlib.vitro.webapp.i18n.I18nStub;
import stubs.edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccessFactoryStub;
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.vedit.beans.LoginStatusBean.AuthenticationSource;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.ActiveIdentifierBundleFactories;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.factory.HasPermissionFactory;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.PermissionRegistry;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.auth.policy.PermissionsPolicy;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ServletPolicyList;
import edu.cornell.mannlib.vitro.webapp.beans.PermissionSet;
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties;
import edu.cornell.mannlib.vitro.webapp.controller.authenticate.Authenticator;
import edu.cornell.mannlib.vitro.webapp.controller.authenticate.AuthenticatorStub;
import edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean;
import edu.cornell.mannlib.vitro.webapp.controller.login.LoginProcessBean.State;
/**
*/
public class AuthenticateTest extends AbstractTestClass {
private AuthenticatorStub.Factory authenticatorFactory;
private AuthenticatorStub authenticator;
private ServletContextStub servletContext;
private WebappDaoFactoryStub webappDaoFactory;
private UserAccountsDaoStub userAccountsDao;
private IndividualDaoStub individualDao;
private ServletConfigStub servletConfig;
private HttpSessionStub session;
private HttpServletRequestStub request;
private HttpServletResponseStub response;
private Authenticate auth;
private LoginProcessBean initialProcessBean;
// ----------------------------------------------------------------------
// Setup and data
// ----------------------------------------------------------------------
/** A DBA who has never logged in (forces password change). */
private static final String NEW_DBA_NAME = "new_dba_name";
private static final String NEW_DBA_PW = "new_dba_pw";
private static final UserInfo NEW_DBA = new UserInfo(NEW_DBA_NAME,
"new_dba_uri", NEW_DBA_PW, URI_DBA, 0);
/** A DBA who has logged in before. */
private static final String OLD_DBA_NAME = "old_dba_name";
private static final String OLD_DBA_PW = "old_dba_pw";
private static final String OLD_DBA_URI = "old_dba_uri";
private static final UserInfo OLD_DBA = new UserInfo(OLD_DBA_NAME,
OLD_DBA_URI, OLD_DBA_PW, URI_DBA, 5);
/** A self-editor who has logged in before and has a profile. */
private static final String OLD_SELF_NAME = "old_self_name";
private static final String OLD_SELF_PW = "old_self_pw";
private static final UserInfo OLD_SELF = new UserInfo(OLD_SELF_NAME,
"old_self_uri", OLD_SELF_PW, URI_SELF_EDITOR, 100);
/** A self-editor who has logged in before but has no profile. */
private static final String OLD_STRANGER_NAME = "old_stranger_name";
private static final String OLD_STRANGER_PW = "stranger_pw";
private static final UserInfo OLD_STRANGER = new UserInfo(
OLD_STRANGER_NAME, "old_stranger_uri", OLD_STRANGER_PW,
URI_SELF_EDITOR, 20);
/** the login page */
private static final String URL_LOGIN = "/vivo/login";
/** some page with a login widget on it. */
private static final String URL_WIDGET = "/vivo/widgetPage";
/** a restricted page that forces a login. */
private static final String URL_RESTRICTED = "/vivo/resrictedPage";
/** a page with a login link. */
private static final String URL_WITH_LINK = "/vivo/linkPage";
// pages that we might end up on.
private static final String URL_HOME = "/vivo";
private static final String URL_SITE_ADMIN = "/vivo/siteAdmin";
private static final String URL_SELF_PROFILE = "/vivo/individual?uri=old_self_associated_uri";
// A page we will never start from or end on.
private static final String URL_SOMEWHERE_ELSE = "/vivo/somewhereElse";
private static final String NO_USER = "";
private static final String NO_MSG = "";
@Before
public void setup() throws Exception {
I18nStub.setup();
authenticatorFactory = new AuthenticatorStub.Factory();
authenticator = authenticatorFactory.getInstance(request);
authenticator.addUser(createUserFromUserInfo(NEW_DBA));
authenticator.addUser(createUserFromUserInfo(OLD_DBA));
authenticator.addUser(createUserFromUserInfo(OLD_SELF));
authenticator.addUser(createUserFromUserInfo(OLD_STRANGER));
authenticator.setAssociatedUri(OLD_SELF.username,
"old_self_associated_uri");
servletContext = new ServletContextStub();
servletContext.setAttribute(AuthenticatorStub.FACTORY_ATTRIBUTE_NAME,
authenticatorFactory);
PermissionSet adminPermissionSet = new PermissionSet();
adminPermissionSet.setUri(URI_DBA);
adminPermissionSet.setPermissionUris(Collections
.singleton(SimplePermission.SEE_SITE_ADMIN_PAGE.getUri()));
userAccountsDao = new UserAccountsDaoStub();
userAccountsDao.addPermissionSet(adminPermissionSet);
userAccountsDao.addUser(createUserFromUserInfo(NEW_DBA));
userAccountsDao.addUser(createUserFromUserInfo(OLD_DBA));
userAccountsDao.addUser(createUserFromUserInfo(OLD_SELF));
userAccountsDao.addUser(createUserFromUserInfo(OLD_STRANGER));
individualDao = new IndividualDaoStub();
webappDaoFactory = new WebappDaoFactoryStub();
webappDaoFactory.setUserAccountsDao(userAccountsDao);
webappDaoFactory.setIndividualDao(individualDao);
ModelAccessFactoryStub mafs = new ModelAccessFactoryStub();
mafs.get(servletContext).setWebappDaoFactory(webappDaoFactory);
setLoggerLevel(ServletPolicyList.class, Level.WARN);
ServletPolicyList.addPolicy(servletContext, new PermissionsPolicy());
PermissionRegistry.createRegistry(servletContext,
Collections.singleton(SimplePermission.SEE_SITE_ADMIN_PAGE));
servletConfig = new ServletConfigStub();
servletConfig.setServletContext(servletContext);
session = new HttpSessionStub();
session.setServletContext(servletContext);
request = new HttpServletRequestStub();
request.setSession(session);
request.setRequestUrlByParts("http://this.that", "/vivo",
"/authenticate", null);
request.setMethod("POST");
response = new HttpServletResponseStub();
auth = new Authenticate();
auth.init(servletConfig);
setLoggerLevel(ConfigurationProperties.class, Level.WARN);
new ConfigurationPropertiesStub().setBean(servletContext);
ActiveIdentifierBundleFactories.addFactory(servletContext,
new HasPermissionFactory(servletContext));
}
private UserAccount createUserFromUserInfo(UserInfo userInfo) {
UserAccount user = new UserAccount();
user.setEmailAddress(userInfo.username);
user.setUri(userInfo.uri);
user.setPermissionSetUris(userInfo.permissionSetUris);
user.setMd5Password(Authenticator.applyMd5Encoding(userInfo.password));
user.setLoginCount(userInfo.loginCount);
user.setPasswordChangeRequired(userInfo.loginCount == 0);
return user;
}
// ----------------------------------------------------------------------
// ENTRY TESTS
// ----------------------------------------------------------------------
/** The "return" parameter is set, so we return to the referrer. */
@Test
public void enterFromALoginLink() {
setRequestFromLoginLink(URL_WITH_LINK);
doTheRequest();
assertProcessBean(LOGGING_IN, NO_USER, NO_MSG, NO_MSG, URL_LOGIN,
URL_WITH_LINK);
assertRedirect(URL_LOGIN);
}
/** The "return" parameter is set, but there is no referrer. */
@Test
public void enterFromABookmarkOfTheLoginLink() {
setRequestFromLoginLink(null);
doTheRequest();
assertProcessBean(LOGGING_IN, NO_USER, NO_MSG, NO_MSG, URL_LOGIN,
URL_LOGIN);
assertRedirect(URL_LOGIN);
}
/** The "afterLoginUrl" parameter is set, pointing to the restricted page. */
@Test
public void enterFromARestrictedPage() {
setRequestFromRestrictedPage(URL_RESTRICTED);
doTheRequest();
assertProcessBean(LOGGING_IN, NO_USER, NO_MSG, NO_MSG, URL_LOGIN,
URL_RESTRICTED);
assertRedirect(URL_LOGIN);
}
/** The user supplies username/password but there is no process bean. */
@Test
public void enterFromAWidgetPage() {
setRequestFromWidgetPage(URL_WIDGET);
doTheRequest();
assertProcessBean(LOGGING_IN, NO_USER, NO_MSG, NO_MSG, URL_WIDGET,
URL_WIDGET);
assertRedirect(URL_WIDGET);
}
/** A page with a widget, but treated specially. */
@Test
public void enterFromTheLoginPage() {
setRequestFromWidgetPage(URL_LOGIN);
doTheRequest();
assertProcessBean(LOGGING_IN, NO_USER, NO_MSG, NO_MSG, URL_LOGIN,
URL_LOGIN);
assertRedirect(URL_LOGIN);
}
// ----------------------------------------------------------------------
// RESTART LOGIN TESTS
//
// Each of these should "hijack" the login that was already in progress.
// ----------------------------------------------------------------------
/** The "return" parameter is set, so we detect the restart. */
@Ignore
@Test
public void restartFromALoginLink() {
setProcessBean(LOGGING_IN, "username", URL_LOGIN, URL_SOMEWHERE_ELSE);
enterFromALoginLink();
}
/** The "return" parameter is set, so we detect the restart. */
@Ignore
@Test
public void restartFromABookmarkOfTheLoginLink() {
setProcessBean(LOGGING_IN, "username", URL_LOGIN, URL_SOMEWHERE_ELSE);
enterFromABookmarkOfTheLoginLink();
}
/** The "afterLoginUrl" parameter is set, so we detect the restart. */
@Ignore
@Test
public void restartFromARestrictedPage() {
setProcessBean(LOGGING_IN, "username", URL_LOGIN, URL_SOMEWHERE_ELSE);
enterFromARestrictedPage();
}
/** The referrer is not the loginProcessPage, so we detect the restart. */
@Ignore
@Test
public void restartFromADifferentWidgetPage() {
setProcessBean(LOGGING_IN, "username", URL_LOGIN, URL_SOMEWHERE_ELSE);
enterFromAWidgetPage();
}
/** The referrer is not the loginProcessPage, so we detect the restart. */
@Ignore
@Test
public void restartFromTheLoginPageWhenWeWereUsingAWidgetPage() {
setProcessBean(LOGGING_IN, "username", URL_SOMEWHERE_ELSE,
URL_SOMEWHERE_ELSE);
enterFromTheLoginPage();
}
// ----------------------------------------------------------------------
// PROCESS TESTS
// ----------------------------------------------------------------------
@Test
public void loggingInNoUsername() {
setProcessBean(LOGGING_IN, NO_USER, URL_LOGIN, URL_WITH_LINK);
doTheRequest();
assertProcessBean(LOGGING_IN, NO_USER, NO_MSG,
"error_no_email_address", URL_LOGIN, URL_WITH_LINK);
assertRedirectToLoginProcessPage();
}
@Test
public void loggingInUsernameNotRecognized() {
setProcessBean(LOGGING_IN, NO_USER, URL_LOGIN, URL_WITH_LINK);
setLoginNameAndPassword("unknownBozo", null);
doTheRequest();
assertProcessBean(LOGGING_IN, "unknownBozo", NO_MSG,
"error_incorrect_credentials", URL_LOGIN, URL_WITH_LINK);
assertRedirectToLoginProcessPage();
}
@Test
public void loggingInNoPassword() {
setProcessBean(LOGGING_IN, NO_USER, URL_LOGIN, URL_WITH_LINK);
setLoginNameAndPassword(NEW_DBA_NAME, null);
doTheRequest();
assertProcessBean(LOGGING_IN, NEW_DBA_NAME, NO_MSG,
"error_no_password", URL_LOGIN, URL_WITH_LINK);
assertRedirectToLoginProcessPage();
}
@Test
public void loggingInPasswordIsIncorrect() {
setProcessBean(LOGGING_IN, NO_USER, URL_LOGIN, URL_WITH_LINK);
setLoginNameAndPassword(NEW_DBA_NAME, "bogus_password");
doTheRequest();
assertProcessBean(LOGGING_IN, NEW_DBA_NAME, NO_MSG,
"error_incorrect_credentials", URL_LOGIN, URL_WITH_LINK);
assertRedirectToLoginProcessPage();
}
@Test
public void loggingInSuccessful() {
setProcessBean(LOGGING_IN, NO_USER, URL_LOGIN, URL_WITH_LINK);
setLoginNameAndPassword(OLD_DBA_NAME, OLD_DBA_PW);
doTheRequest();
assertNoProcessBean();
assertNewLoginSessions(OLD_DBA_NAME);
assertRedirectToAfterLoginPage();
}
@Test
public void loggingInForcesPasswordChange() {
setProcessBean(LOGGING_IN, NO_USER, URL_LOGIN, URL_WITH_LINK);
setLoginNameAndPassword(NEW_DBA_NAME, NEW_DBA_PW);
doTheRequest();
assertProcessBean(FORCED_PASSWORD_CHANGE, NEW_DBA_NAME, NO_MSG, NO_MSG,
URL_LOGIN, URL_WITH_LINK);
assertNewLoginSessions();
assertRedirectToLoginProcessPage();
}
@Test
public void changingPasswordCancel() {
setProcessBean(FORCED_PASSWORD_CHANGE, NEW_DBA_NAME, URL_LOGIN,
URL_WITH_LINK);
setCancel();
doTheRequest();
assertNoProcessBean();
assertNewLoginSessions();
assertRedirectToCancelUrl();
}
@Test
public void changingPasswordWrongLength() {
setProcessBean(FORCED_PASSWORD_CHANGE, NEW_DBA_NAME, URL_LOGIN,
URL_WITH_LINK);
setNewPasswordAttempt("HI", "HI");
doTheRequest();
assertProcessBean(FORCED_PASSWORD_CHANGE, NEW_DBA_NAME, NO_MSG,
"error_password_length", URL_LOGIN, URL_WITH_LINK);
assertRedirectToLoginProcessPage();
}
@Test
public void changingPasswordDontMatch() {
setProcessBean(FORCED_PASSWORD_CHANGE, NEW_DBA_NAME, URL_LOGIN,
URL_WITH_LINK);
setNewPasswordAttempt("LongEnough", "DoesNotMatch");
doTheRequest();
assertProcessBean(FORCED_PASSWORD_CHANGE, NEW_DBA_NAME, NO_MSG,
"error_passwords_dont_match", URL_LOGIN, URL_WITH_LINK);
assertRedirectToLoginProcessPage();
}
@Test
public void changingPasswordSameAsBefore() {
setProcessBean(FORCED_PASSWORD_CHANGE, NEW_DBA_NAME, URL_LOGIN,
URL_WITH_LINK);
setNewPasswordAttempt(NEW_DBA_PW, NEW_DBA_PW);
doTheRequest();
assertProcessBean(FORCED_PASSWORD_CHANGE, NEW_DBA_NAME, NO_MSG,
"error_previous_password", URL_LOGIN,
URL_WITH_LINK);
assertRedirectToLoginProcessPage();
}
@Test
public void changingPasswordSuccess() {
setProcessBean(FORCED_PASSWORD_CHANGE, NEW_DBA_NAME, URL_LOGIN,
URL_WITH_LINK);
setNewPasswordAttempt("NewPassword", "NewPassword");
doTheRequest();
assertNoProcessBean();
assertNewLoginSessions(NEW_DBA_NAME);
assertPasswordChanges(NEW_DBA_NAME, "NewPassword");
assertRedirectToAfterLoginPage();
}
@Test
public void alreadyLoggedIn() {
LoginStatusBean statusBean = new LoginStatusBean(OLD_DBA_URI,
AuthenticationSource.INTERNAL);
LoginStatusBean.setBean(session, statusBean);
setRequestFromLoginLink(URL_WITH_LINK);
doTheRequest();
assertNoProcessBean();
assertNewLoginSessions();
assertRedirect(URL_WITH_LINK);
}
// ----------------------------------------------------------------------
// EXIT TESTS
// ----------------------------------------------------------------------
@Test
public void exitSelfEditor() {
setProcessBean(LOGGING_IN, NO_USER, URL_LOGIN, URL_WITH_LINK);
setLoginNameAndPassword(OLD_SELF_NAME, OLD_SELF_PW);
doTheRequest();
assertNoProcessBean();
assertNewLoginSessions(OLD_SELF_NAME);
assertRedirect(URL_SELF_PROFILE);
}
@Test
public void exitUnrecognizedSelfEditor() {
setProcessBean(LOGGING_IN, NO_USER, URL_LOGIN, URL_WITH_LINK);
setLoginNameAndPassword(OLD_STRANGER_NAME, OLD_STRANGER_PW);
doTheRequest();
assertNoProcessBean();
assertNewLoginSessions(OLD_STRANGER_NAME);
assertRedirect(URL_HOME);
}
@Test
public void exitDbaNormal() {
setProcessBean(LOGGING_IN, NO_USER, URL_LOGIN, URL_RESTRICTED);
setLoginNameAndPassword(OLD_DBA_NAME, OLD_DBA_PW);
doTheRequest();
assertNoProcessBean();
assertNewLoginSessions(OLD_DBA_NAME);
assertRedirect(URL_RESTRICTED);
}
@Test
public void exitDbaFromLoginPage() {
setProcessBean(LOGGING_IN, NO_USER, URL_LOGIN, URL_LOGIN);
setLoginNameAndPassword(OLD_DBA_NAME, OLD_DBA_PW);
doTheRequest();
assertNoProcessBean();
assertNewLoginSessions(OLD_DBA_NAME);
assertRedirect(URL_SITE_ADMIN);
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
private void setRequestFromLoginLink(String urlWithLink) {
request.addParameter("return", "");
request.setHeader("referer", urlWithLink);
}
private void setRequestFromRestrictedPage(String urlRestricted) {
request.addParameter("afterLogin", urlRestricted);
request.setHeader("referer", urlRestricted);
}
private void setRequestFromWidgetPage(String urlWidget) {
request.setHeader("referer", urlWidget);
}
/** Create a LoginProcessBean in the session, and keep a reference to it. */
private void setProcessBean(State state, String username,
String loginProcessUrl, String afterLoginUrl) {
LoginProcessBean bean = LoginProcessBean.getBean(request);
bean.setState(state);
bean.setUsername(username);
bean.setLoginPageUrl(loginProcessUrl);
bean.setAfterLoginUrl(afterLoginUrl);
initialProcessBean = bean;
}
private void setLoginNameAndPassword(String loginName, String password) {
request.addParameter("loginName", loginName);
request.addParameter("loginPassword", password);
}
private void setCancel() {
request.addParameter("cancel", "true");
}
private void setNewPasswordAttempt(String newPassword,
String confirmPassword) {
request.addParameter("newPassword", newPassword);
request.addParameter("confirmPassword", confirmPassword);
}
private void doTheRequest() {
auth.doPost(request, response);
}
private void assertNoProcessBean() {
if (LoginProcessBean.isBean(request)) {
fail("Process bean: expected <null>, but was <"
+ LoginProcessBean.getBean(request) + ">");
}
}
private void assertProcessBean(State state, String username,
String infoMessage, String errorMessage, String loginProcessUrl,
String afterLoginUrl) {
if (!LoginProcessBean.isBean(request)) {
fail("login process bean is null");
}
LoginProcessBean bean = LoginProcessBean.getBean(request);
assertEquals("state", state, bean.getState());
assertEquals("username", username, bean.getUsername());
assertEquals("info message", infoMessage, bean.getInfoMessageAndClear());
assertEquals("error message", errorMessage,
bean.getErrorMessageAndClear());
assertEquals("login process URL", loginProcessUrl,
bean.getLoginPageUrl());
assertEquals("after login URL", afterLoginUrl, bean.getAfterLoginUrl());
}
private void assertRedirect(String path) {
if (path.startsWith("http://")) {
assertEquals("absolute redirect", path,
response.getRedirectLocation());
} else {
assertEquals("relative redirect", path,
response.getRedirectLocation());
}
}
private void assertRedirectToLoginProcessPage() {
assertRedirect(LoginProcessBean.getBean(request).getLoginPageUrl());
}
private void assertRedirectToAfterLoginPage() {
assertNotNull("No reference to the initial LoginProcessBean",
initialProcessBean);
assertRedirect(initialProcessBean.getAfterLoginUrl());
}
private void assertRedirectToCancelUrl() {
String afterLoginUrl = initialProcessBean.getAfterLoginUrl();
if ((afterLoginUrl == null) || (afterLoginUrl.equals(URL_LOGIN))) {
assertRedirect(URL_HOME);
} else {
assertRedirect(afterLoginUrl);
}
}
/** What logins were completed in this test? */
private void assertNewLoginSessions(String... usernames) {
Set<String> expected = new HashSet<String>(Arrays.asList(usernames));
Set<String> actualRecorded = new HashSet<String>(
authenticator.getRecordedLoginUsernames());
assertEquals("recorded logins", expected, actualRecorded);
}
/** What passwords were changed in this test? */
private void assertPasswordChanges(String... strings) {
if ((strings.length % 2) != 0) {
throw new RuntimeException(
"supply even number of args: username and password");
}
Map<String, String> expected = new HashMap<String, String>();
for (int i = 0; i < strings.length; i += 2) {
expected.put(strings[i], strings[i + 1]);
}
assertEquals("password changes", expected,
authenticator.getNewPasswordMap());
}
// ----------------------------------------------------------------------
// Helper classes
// ----------------------------------------------------------------------
private static class UserInfo {
final String username;
final String uri;
final String password;
final Set<String> permissionSetUris;
final int loginCount;
public UserInfo(String username, String uri, String password,
String roleUri, int loginCount) {
this.username = username;
this.uri = uri;
this.password = password;
this.permissionSetUris = Collections.singleton(roleUri);
this.loginCount = loginCount;
}
@Override
public String toString() {
return "UserInfo[username=" + username + ", uri=" + uri
+ ", password=" + password + ", roleUri="
+ permissionSetUris + ", loginCount=" + loginCount + "]";
}
}
}

View file

@ -0,0 +1,67 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.edit;
import java.util.Set;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
public class PrimitiveRdfEditTest {
OntModel testModel;
WebappDaoFactory wdf;
private String testN3a =
"<http://example.com/motorcycles/honda/vtl1000> <http://example.com/engines/displacement> \"1000cm3\" ." +
"<http://example.com/motorcycles/honda/919> <http://example.com/engines/displacement> \"919cm3\" ." ;
private String testN3b =
"<http://example.com/motorcycles/honda/919> <http://example.com/motorcycles/relatedTo> <http://exmaple.com/motorcycle/honda/599> ." ;
@Before
public void setUp() throws Exception { }
@Test
public void testProcessChanges() throws Exception {
OntModel writeModel = ModelFactory.createOntologyModel();
int totalStmts = 3;
PrimitiveRdfEdit pre = new PrimitiveRdfEdit();
String params[] = { testN3a, testN3b };
Set<Model> models = pre.parseRdfParam(params, "N3");
Assert.assertNotNull(models);
Assert.assertTrue( models.size() == 2);
Assert.assertNotNull( writeModel );
long size = writeModel.size();
pre.processChanges("uri:fakeEditorUri", writeModel,
pre.mergeModels(models), ModelFactory.createDefaultModel());
Assert.assertEquals(size+totalStmts, writeModel.size());
String params3[] = { testN3b };
Set<Model> retracts = pre.parseRdfParam( params3, "N3");
pre.processChanges("uri:fakeEditorUri", writeModel,
ModelFactory.createDefaultModel(), pre.mergeModels(retracts));
Assert.assertEquals(size+totalStmts-1, writeModel.size());
}
@Test
public void testParseRdfParam() throws Exception {
PrimitiveRdfEdit pre = new PrimitiveRdfEdit();
String params[] = { testN3a, testN3b };
Set<Model> models = pre.parseRdfParam(params, "N3");
Assert.assertNotNull(models);
Assert.assertTrue( models.size() == 2);
}
}

View file

@ -0,0 +1,165 @@
/* $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.easymock.EasyMock.*;
import javax.servlet.http.HttpServletRequest;
import org.junit.Assert;
import org.junit.Test;
import stubs.edu.cornell.mannlib.vitro.webapp.dao.ApplicationDaoStub;
import stubs.edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactoryStub;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder.ParamMap;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.web.URLEncoder;
public class UrlBuilderTest extends AbstractTestClass {
@Test
public void testGetUrl() {
UrlBuilder.contextPath = "/vivo";
String path1 = "/individual";
Assert.assertEquals("/vivo/individual", UrlBuilder.getUrl(path1));
int portalId = 1;
String path2 = "/individual?home=" + portalId;
Assert.assertEquals("/vivo/individual?home=1", UrlBuilder.getUrl(path2));
}
@Test
public void testGetUrlWithEmptyContext() {
UrlBuilder.contextPath = "";
String path = "/individual";
Assert.assertEquals(path, UrlBuilder.getUrl(path));
}
@Test
public void testGetUrlWithParams() {
UrlBuilder.contextPath = "/vivo";
String path = "/individual";
ParamMap params = new ParamMap();
int portalId = 1;
params.put("home", "" + portalId);
params.put("name", "Tom");
Assert.assertEquals("/vivo/individual?home=1&name=Tom", UrlBuilder.getUrl(path, params));
}
@Test
public void testEncodeUrl() {
UrlBuilder.contextPath = "/vivo";
String path = "/individuallist";
ParamMap params = new ParamMap();
String vClassUri = "http://vivoweb.org/ontology/core#FacultyMember";
params.put("vclassId", vClassUri);
Assert.assertEquals("/vivo/individuallist?vclassId=http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23FacultyMember", UrlBuilder.getUrl(path, params));
}
@Test
public void testDecodeUrl() {
String vClassUri = "http://vivoweb.org/ontology/core#FacultyMember";
String vClassUriEncoded = "http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23FacultyMember";
Assert.assertEquals(vClassUri, UrlBuilder.urlDecode(vClassUriEncoded));
}
@Test
public void testUtf8Encode(){
UrlBuilder.contextPath = "/vivo";
String path = "/individual";
ParamMap params = new ParamMap();
params.put("name", "\u2605Tom\u2605"); // \u2605 is Unicode for a five-pointed star.
Assert.assertEquals("/vivo/individual?name=%E2%98%85Tom%E2%98%85", UrlBuilder.getUrl(path, params));
}
@Test
public void testDecodeUtf8Url() {
String vClassUri = "http://vivoweb.org/ontology/core#FacultyMember\u2605"; // \u2605 is Unicode for a five-pointed star.
String vClassUriEncoded = "http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23FacultyMember%E2%98%85";
Assert.assertEquals(vClassUri, UrlBuilder.urlDecode(vClassUriEncoded));
}
@Test
public void testGetIndividualProfileURI(){
VitroRequest vreq = makeMockVitroRequest( "http://example.com/individual/");
UrlBuilder.contextPath = "http://example.com";
String uri = "http://example.com/individual/n2343";
String url = UrlBuilder.getIndividualProfileUrl(uri, vreq);
Assert.assertEquals("http://example.com/display/n2343", url);
uri = "http://example.com/individual/bob";
url = UrlBuilder.getIndividualProfileUrl(uri, vreq);
Assert.assertEquals("http://example.com/display/bob",url);
uri = "http://nondefaultNS.com/individual/n2343";
url = UrlBuilder.getIndividualProfileUrl(uri, vreq);
Assert.assertEquals("http://example.com/individual?uri=" + URLEncoder.encode(uri), url);
uri = "http://example.com/individual#n2343";
url = UrlBuilder.getIndividualProfileUrl(uri, vreq);
Assert.assertEquals("http://example.com/individual?uri=" + URLEncoder.encode(uri), url);
uri = "http://example.com/individual/5LNCannotStartWithNumber";
url = UrlBuilder.getIndividualProfileUrl(uri, vreq);
Assert.assertEquals("http://example.com/individual?uri=" + URLEncoder.encode(uri), url);
}
protected VitroRequest makeMockVitroRequest( final String defaultNS){
HttpServletRequest req = createMock( HttpServletRequest.class );
return new VitroRequest(req){
@Override
public String getParameter(String key){ return null; }
@Override
public WebappDaoFactory getWebappDaoFactory(){
return makeMockWDF(defaultNS);
}
};
}
protected WebappDaoFactoryStub makeMockWDF( String defaultNS){
WebappDaoFactoryStub wdf = new WebappDaoFactoryStub();
wdf.setDefaultNamespace("http://example.com/individual/");
ApplicationDaoStub aDao = new ApplicationDaoStub(){
@Override
public boolean isExternallyLinkedNamespace(String ns){
return false;
}
};
wdf.setApplicationDao( aDao );
return wdf;
}
@Test
public void testIsUriInDefaultNamespace(){
String[][] examples = {
{ "http://example.com/individual/n3234", "http://example.com/individual/"},
{ "http://example.com/individual#n3234", "http://example.com/individual#"},
{ "http://example.com:8080/individual/n3234", "http://example.com:8080/individual/"},
{ "http://example.com:8080/individual#n3234", "http://example.com:8080/individual#"}
};
for( String[] example : examples ){
Assert.assertTrue("expected '"+ example[0] + "' to be in the default NS of '"+example[1]+"'",
UrlBuilder.isUriInDefaultNamespace(example[0], example[1]));
}
String[][] counterExamples = {
{ "http://example.com/individual/5LNCannotStartWithNumber", "http://example.com/individual/" }
};
for( String[] example : counterExamples ){
Assert.assertFalse("expected '"+ example[0] + "' to NOT be in the default NS of '"+example[1]+"'",
UrlBuilder.isUriInDefaultNamespace(example[0], example[1]));
}
}
}

View file

@ -0,0 +1,102 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.grefine;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.servlet.ServletException;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import stubs.edu.cornell.mannlib.vitro.webapp.modules.ApplicationStub;
import stubs.edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchEngineStub;
import stubs.javax.servlet.ServletContextStub;
import stubs.javax.servlet.http.HttpServletRequestStub;
import stubs.javax.servlet.http.HttpServletResponseStub;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchQuery;
/**
* Tests on various methods in the class.
* @author Eliza Chan (elc2013@med.cornell.edu)
*
*/
public class JSONReconcileServletTest extends AbstractTestClass {
private HttpServletRequestStub request;
private HttpServletResponseStub response;
private JSONReconcileServlet reconcile;
@Before
public void setup() throws Exception {
ApplicationStub.setup(new ServletContextStub(), new SearchEngineStub());
request = new HttpServletRequestStub();
request.setRequestUrl(new URL("http://vivo.this.that/reconcile"));
request.setMethod("POST");
response = new HttpServletResponseStub();
reconcile = new JSONReconcileServlet();
}
@Test
public void getMetadata() {
int serverPort = 8080;
String defaultNamespace = "http://vivo.this.that/individual/";
String defaultTypeList = null;
String serverName = null;
String schemaSpaceOutput = null;
JSONObject jsonResult = null;
try {
jsonResult = reconcile.getMetadata(request, response, defaultNamespace, defaultTypeList, serverName, serverPort);
schemaSpaceOutput = jsonResult.getString("schemaSpace");
} catch (ServletException e) {
System.err.println("JSONReconcileServletTest getMetadata ServletException: " + e);
} catch (JSONException e) {
System.err.println("JSONReconcileServletTest getMetadata JSONException: " + e);
}
Assert.assertNotNull("output should not be null", jsonResult);
Assert.assertEquals("schemaSpaceOutput", defaultNamespace, schemaSpaceOutput);
}
@Test
public void getQuery() {
// contruct query
int rowNum = 3;
String nameStr = "Joe";
String nameType = "http://xmlns.com/foaf/0.1/Person";
ArrayList<String[]> propertiesList = new ArrayList<String[]>();
String orgStr = "Something";
String orgType = "http://xmlns.com/foaf/0.1/Organization";
String[] properties = {orgType, orgStr};
propertiesList.add(properties);
// test getQuery
SearchQuery searchQuery = reconcile.getQuery(nameStr, nameType, rowNum, propertiesList);
String messagePrefix = "Query should contain the text: ";
testAssertTrue(messagePrefix + orgStr, orgStr, searchQuery.toString());
testAssertTrue(messagePrefix + nameStr, nameStr, searchQuery.toString());
testAssertTrue(messagePrefix + orgType, orgType, searchQuery.toString());
testAssertTrue(messagePrefix + nameType, orgType, searchQuery.toString());
}
private void testAssertTrue(String message, String inputStr, String resultStr) {
try {
Pattern regex = Pattern.compile(inputStr, Pattern.CASE_INSENSITIVE);
Matcher regexMatcher = regex.matcher(resultStr);
Assert.assertTrue(message, regexMatcher.find());
} catch (PatternSyntaxException e) {
// Syntax error in the regular expression
System.err.println("JSONReconcileServletTest testAssertTrue PatternSyntaxException: " + e);
}
}
}

View file

@ -0,0 +1,504 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.individual;
import static com.hp.hpl.jena.ontology.OntModelSpec.OWL_MEM;
import static edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary.LABEL;
import static edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary.RDF_TYPE;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess.LanguageOption.LANGUAGE_NEUTRAL;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.collections.IteratorUtils;
import org.apache.log4j.Level;
import org.junit.Before;
import org.junit.Test;
import stubs.edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccessFactoryStub;
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.rdf.model.Literal;
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.ResourceFactory;
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.BasicPolicyDecision;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ServletPolicyList;
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.RequestedAction;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.publish.PublishDataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.publish.PublishObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.rdfservice.impl.jena.model.RDFServiceModel;
import edu.cornell.mannlib.vitro.webapp.web.ContentType;
/**
* Start with a set of data and filter it appropriately.
*/
public class IndividualRdfAssemblerTest extends AbstractTestClass {
private static final String INDIVIDUAL_URI = "http://vivo.mydomain.edu/individual/n3639";
private static final String DOCUMENT_URI = "http://vivo.mydomain.edu/individual/n3639/n3639.n3";
/** When comparing, consider all date-stamps to be equal. */
private static final String DATE_DATA_PROPERTY = "http://purl.org/dc/elements/1.1/date";
private static final String DP1 = "http://dataPropertyUri1";
private static final String OP1 = "http://objectPropertyUri1";
private static final String C1 = "http://class1";
private static final String C2 = "http://class2";
private static final String I1 = "http://individual1";
private static final String RAW_RDF_FILENAME = "IndividualRdfAssemblerTest.rawRdf.n3";
private static final String FILTERED_RDF_FILENAME = "IndividualRdfAssemblerTest.filteredRdf.n3";
private static final String UNFILTERED_RDF_FILENAME = "IndividualRdfAssemblerTest.unfilteredRdf.n3";
private static final String[] REAL_WORLD_PROPERTIES = {
"http://vivoweb.org/ontology/core#overview",
"http://vivoweb.org/ontology/core#hasResearchArea",
"http://vivoweb.org/ontology/core#researchAreaOf" };
private OntModel rawRdf;
private OntModel expectedLod;
private OntModel actualLod;
private ServletContextStub ctx;
private HttpSessionStub session;
private HttpServletRequestStub req;
private VitroRequest vreq;
private RDFServiceModel rdfService;
private IndividualRdfAssembler ira;
@Before
public void setLoggingLevels() {
setLoggerLevel(ModelAccess.class, Level.ERROR);
// setLoggerLevel(IndividualRdfAssembler.class, Level.DEBUG);
// setLoggerLevel(RDFServiceStub.class, Level.DEBUG);
}
@Before
public void setup() throws IOException {
ctx = new ServletContextStub();
session = new HttpSessionStub();
session.setServletContext(ctx);
req = new HttpServletRequestStub();
req.setSession(session);
req.setRequestUrl(new URL(DOCUMENT_URI));
}
@Test
public void getOutgoingStatements() {
Statement s1 = dataStmt(INDIVIDUAL_URI, DP1, "value");
Statement s2 = objectStmt(INDIVIDUAL_URI, OP1, I1);
rawRdf = model(s1, s2);
expectedLod = includeDocInfo(model(s1, s2));
policyUnrestricted();
filterAndCompare("getOutgoingStatements");
}
@Test
public void filterOutgoingStatements() {
Statement s1 = dataStmt(INDIVIDUAL_URI, DP1, "value");
Statement s2 = objectStmt(INDIVIDUAL_URI, OP1, I1);
rawRdf = model(s1, s2);
expectedLod = includeDocInfo(model());
policyRestrictByPredicate(DP1, OP1);
filterAndCompare("filterOutgoingStatements");
}
@Test
public void getIncomingStatements() {
Statement s1 = objectStmt(I1, OP1, INDIVIDUAL_URI);
rawRdf = model(s1);
expectedLod = includeDocInfo(model(s1));
policyUnrestricted();
filterAndCompare("getIncomingStatements");
}
@Test
public void filterIncomingStatements() {
Statement s1 = objectStmt(I1, OP1, INDIVIDUAL_URI);
rawRdf = model(s1);
expectedLod = includeDocInfo(model());
policyRestrictByPredicate(OP1);
filterAndCompare("filterIncomingStatements");
}
@Test
public void getLabelAndTypeOfOutgoingObjects() {
Statement s1 = objectStmt(INDIVIDUAL_URI, OP1, I1);
Statement s2 = dataStmt(I1, LABEL, "silly label");
Statement s3 = objectStmt(I1, RDF_TYPE, C1);
rawRdf = model(s1, s2, s3);
expectedLod = includeDocInfo(model(s1, s2, s3));
policyUnrestricted();
filterAndCompare("getLabelAndTypeOfOutgoingObjects");
}
@Test
public void filterOrphanStatementsOfOutgoingObjects() {
Statement s1 = objectStmt(INDIVIDUAL_URI, OP1, I1);
Statement s2 = dataStmt(I1, LABEL, "silly label");
Statement s3 = objectStmt(I1, RDF_TYPE, C1);
rawRdf = model(s1, s2, s3);
expectedLod = includeDocInfo(model());
policyRestrictByPredicate(OP1);
filterAndCompare("filterOrphanStatementsOfOutgoingObjects");
}
@Test
public void getLabelAndTypeOfIncomingObjects() {
Statement s1 = objectStmt(I1, OP1, INDIVIDUAL_URI);
Statement s2 = dataStmt(I1, LABEL, "silly label");
Statement s3 = objectStmt(I1, RDF_TYPE, C1);
rawRdf = model(s1, s2, s3);
expectedLod = includeDocInfo(model(s1, s2, s3));
policyUnrestricted();
filterAndCompare("getLabelAndTypeOfIncomingObjects");
}
@Test
public void filterOrphanStatementsOfIncomingObjects() {
Statement s1 = objectStmt(I1, OP1, INDIVIDUAL_URI);
Statement s2 = dataStmt(I1, LABEL, "silly label");
Statement s3 = objectStmt(I1, RDF_TYPE, C1);
rawRdf = model(s1, s2, s3);
expectedLod = includeDocInfo(model());
policyRestrictByPredicate(OP1);
filterAndCompare("filterOrphanStatementsOfIncomingObjects");
}
@Test
public void getTypeStatements() {
Statement s1 = objectStmt(INDIVIDUAL_URI, RDF_TYPE, C1);
rawRdf = model(s1);
expectedLod = includeDocInfo(model(s1));
policyUnrestricted();
filterAndCompare("getTypeStatements");
}
@Test
public void filterTypeStatements() {
Statement s1 = objectStmt(INDIVIDUAL_URI, RDF_TYPE, C1);
rawRdf = model(s1);
expectedLod = includeDocInfo(model());
policyRestrictByClass(C1);
filterAndCompare("filterTypeStatements");
}
@Test
public void getTypeAndLabelOfType() {
Statement s1 = objectStmt(INDIVIDUAL_URI, RDF_TYPE, C1);
Statement s2 = dataStmt(C1, LABEL, "silly label");
Statement s3 = objectStmt(C1, RDF_TYPE, C2);
rawRdf = model(s1, s2, s3);
expectedLod = includeDocInfo(model(s1, s2, s3));
policyUnrestricted();
filterAndCompare("getTypeAndLabelOfType");
}
@Test
public void filterOrphanTypeAndLabelOfType() {
Statement s1 = objectStmt(INDIVIDUAL_URI, RDF_TYPE, C1);
Statement s2 = dataStmt(I1, LABEL, "silly label");
Statement s3 = objectStmt(I1, RDF_TYPE, C2);
rawRdf = model(s1, s2, s3);
expectedLod = includeDocInfo(model());
policyRestrictByClass(C1);
filterAndCompare("filterOrphanTypeAndLabelOfType");
}
@Test
public void dontGetOtherStatementsFromOutgoingObjects() {
Statement s1 = objectStmt(INDIVIDUAL_URI, OP1, I1);
Statement s2 = dataStmt(I1, DP1, "silly data property");
rawRdf = model(s1, s2);
expectedLod = includeDocInfo(model(s1));
policyUnrestricted();
filterAndCompare("dontGetOtherStatementsFromOutgoingObjects");
}
@Test
public void dontGetOtherStatementsFromIncomingObjects() {
Statement s1 = objectStmt(I1, OP1, INDIVIDUAL_URI);
Statement s2 = dataStmt(I1, DP1, "silly data property");
rawRdf = model(s1, s2);
expectedLod = includeDocInfo(model(s1));
policyUnrestricted();
filterAndCompare("dontGetOtherStatementsFromIncomingObjects");
}
@Test
public void dontGetUnrelatedStatements() {
Statement s1 = dataStmt(I1, DP1, "silly data property");
rawRdf = model(s1);
expectedLod = includeDocInfo(model());
policyUnrestricted();
filterAndCompare("dontGetUnrelatedStatements");
}
@Test
public void realWorldTestRoot() throws IOException {
rawRdf = readModelFromFile(RAW_RDF_FILENAME, "N3");
expectedLod = readModelFromFile(UNFILTERED_RDF_FILENAME, "N3");
policyUnrestricted();
filterAndCompare("real world test - root");
}
@Test
public void realWorldTestPublic() throws IOException {
rawRdf = readModelFromFile(RAW_RDF_FILENAME, "N3");
expectedLod = readModelFromFile(FILTERED_RDF_FILENAME, "N3");
policyRestrictByPredicate(REAL_WORLD_PROPERTIES);
filterAndCompare("real world test - public");
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
private Statement dataStmt(String subjectUri, String predicateUri,
String value) {
Resource subject = ResourceFactory.createResource(subjectUri);
Property predicate = ResourceFactory.createProperty(predicateUri);
Literal object = ResourceFactory.createPlainLiteral(value);
return ResourceFactory.createStatement(subject, predicate, object);
}
private Statement objectStmt(String subjectUri, String predicateUri,
String objectUri) {
Resource subject = ResourceFactory.createResource(subjectUri);
Property predicate = ResourceFactory.createProperty(predicateUri);
Resource object = ResourceFactory.createResource(objectUri);
return ResourceFactory.createStatement(subject, predicate, object);
}
private OntModel model(Statement... stmts) {
OntModel m = ModelFactory.createOntologyModel(OWL_MEM);
m.add(Arrays.asList(stmts));
return m;
}
private OntModel includeDocInfo(OntModel m) {
List<Statement> list = new ArrayList<>();
list.add(dataStmt(DOCUMENT_URI, LABEL, "RDF description of "
+ INDIVIDUAL_URI));
list.add(dataStmt(DOCUMENT_URI, DATE_DATA_PROPERTY, "bogusTimeStamp"));
list.add(objectStmt(DOCUMENT_URI, RDF_TYPE,
"http://xmlns.com/foaf/0.1/Document"));
list.add(objectStmt(DOCUMENT_URI,
"http://purl.org/dc/elements/1.1/publisher",
"http://vivo.mydomain.edu"));
list.add(objectStmt(DOCUMENT_URI,
"http://purl.org/dc/elements/1.1/rights",
"http://vivo.mydomain.edu/termsOfUse"));
m.add(list);
return m;
}
private void policyUnrestricted() {
ServletPolicyList.addPolicy(ctx, new UnrestrictedPolicy());
}
private void policyRestrictByPredicate(String... predicateUris) {
ServletPolicyList.addPolicy(ctx, new RestrictionsPolicy(predicateUris,
new String[0]));
}
private void policyRestrictByClass(String... classUris) {
ServletPolicyList.addPolicy(ctx, new RestrictionsPolicy(new String[0],
classUris));
}
private void filterAndCompare(String message) {
setupIndividualRdfAssembler();
actualLod = runGetRdf();
List<Statement> missing = modelDifference(expectedLod, actualLod);
List<Statement> extra = modelDifference(actualLod, expectedLod);
removeMatchingDateStatements(missing, extra);
if (missing.isEmpty() && extra.isEmpty()) {
return;
}
failComparison(message, missing, extra);
}
private void setupIndividualRdfAssembler() {
rdfService = new RDFServiceModel(rawRdf);
new ModelAccessFactoryStub().get(req).setRDFService(rdfService, LANGUAGE_NEUTRAL);
vreq = new VitroRequest(req);
ira = new IndividualRdfAssembler(vreq, INDIVIDUAL_URI, ContentType.N3);
}
private OntModel runGetRdf() {
try {
Method m = IndividualRdfAssembler.class.getDeclaredMethod("getRdf");
m.setAccessible(true);
return (OntModel) m.invoke(ira);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void failComparison(String message, List<Statement> missing,
List<Statement> extra) {
StringWriter sw = new StringWriter();
PrintWriter w = new PrintWriter(sw);
w.println(message);
writeStatementList("Missing statements:", missing, w);
writeStatementList("Extra statements:", extra, w);
System.err.print(sw.toString());
fail(sw.toString());
}
private void writeStatementList(String label, List<Statement> list,
PrintWriter w) {
if (list.isEmpty()) {
return;
}
w.println(label);
for (Statement s : list) {
w.println(" " + s);
}
}
private List<Statement> modelDifference(OntModel first, OntModel second) {
OntModel temp = ModelFactory.createOntologyModel(OWL_MEM);
temp.add(first);
temp.remove(statementList(second));
return statementList(temp);
}
@SuppressWarnings("unchecked")
private List<Statement> statementList(OntModel m) {
return IteratorUtils.toList(m.listStatements());
}
/**
* If two date statements have the same subject, then lets assume that their
* dates are the same. In fact, the actual date statement will have the
* current date/time.
*/
private void removeMatchingDateStatements(List<Statement> list1,
List<Statement> list2) {
for (Iterator<Statement> it1 = list1.iterator(); it1.hasNext();) {
Statement stmt1 = it1.next();
String subject1 = stmt1.getSubject().getURI();
String predicate1 = stmt1.getPredicate().getURI();
if (DATE_DATA_PROPERTY.equals(predicate1)) {
for (Iterator<Statement> it2 = list2.iterator(); it2.hasNext();) {
Statement stmt2 = it2.next();
String subject2 = stmt2.getSubject().getURI();
String predicate2 = stmt2.getPredicate().getURI();
if (predicate1.equals(predicate2)
&& subject1.equals(subject2)) {
it1.remove();
it2.remove();
}
}
}
}
}
// ----------------------------------------------------------------------
// Helper class
// ----------------------------------------------------------------------
private abstract static class AbstractTestPolicy implements PolicyIface {
@Override
public PolicyDecision isAuthorized(IdentifierBundle whoToAuth,
RequestedAction whatToAuth) {
if (whatToAuth instanceof PublishDataPropertyStatement) {
return filterDataProperty((PublishDataPropertyStatement) whatToAuth);
} else if (whatToAuth instanceof PublishObjectPropertyStatement) {
return filterObjectProperty((PublishObjectPropertyStatement) whatToAuth);
} else {
return inconclusive("Bogus");
}
}
private PolicyDecision filterDataProperty(
PublishDataPropertyStatement pdps) {
return filter(pdps.getPredicateUri(), null);
}
private PolicyDecision filterObjectProperty(
PublishObjectPropertyStatement pops) {
String propertyUri = pops.getPredicateUri();
if (VitroVocabulary.RDF_TYPE.equals(propertyUri)) {
return filter(propertyUri, pops.getObjectUri());
} else {
return filter(propertyUri, null);
}
}
protected abstract PolicyDecision filter(String propertyUri,
String classUri);
protected BasicPolicyDecision authorized(String message) {
return new BasicPolicyDecision(Authorization.AUTHORIZED, message);
}
protected BasicPolicyDecision inconclusive(String message) {
return new BasicPolicyDecision(Authorization.INCONCLUSIVE, message);
}
}
private static class UnrestrictedPolicy extends AbstractTestPolicy {
@Override
protected PolicyDecision filter(String propertyUri, String classUri) {
return authorized("Totally unrestricted");
}
}
private static class RestrictionsPolicy extends AbstractTestPolicy {
private final List<String> filteredPropertyUris;
private final List<String> filteredClassUris;
public RestrictionsPolicy(String[] filteredPropertyUris,
String[] filteredClassUris) {
this.filteredPropertyUris = Arrays.asList(filteredPropertyUris);
this.filteredClassUris = Arrays.asList(filteredClassUris);
}
@Override
protected PolicyDecision filter(String propertyUri, String classUri) {
if ((propertyUri != null)
&& filteredPropertyUris.contains(propertyUri)) {
return inconclusive("Filtered property: " + propertyUri);
}
if ((classUri != null) && filteredClassUris.contains(classUri)) {
return inconclusive("Filtered class: " + classUri);
}
return authorized("Passed the filters: " + propertyUri + ","
+ classUri);
}
}
}

View file

@ -0,0 +1,375 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.individual;
import static edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet.N3_MIMETYPE;
import static edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet.RDFXML_MIMETYPE;
import static edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet.TTL_MIMETYPE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.net.URL;
import org.junit.Before;
import org.junit.Test;
import stubs.edu.cornell.mannlib.vitro.webapp.beans.IndividualStub;
import stubs.edu.cornell.mannlib.vitro.webapp.controller.individual.IndividualRequestAnalysisContextStub;
import stubs.javax.servlet.http.HttpServletRequestStub;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.web.ContentType;
/**
* Are we able to figure out what sort of Individual request this is?
*/
public class IndividualRequestAnalyzerTest extends AbstractTestClass {
/**
* Info about the application.
*/
private static final String URL_HOME_PAGE = "http://vivo.mydomain.edu";
private static final String URL_INDIVIDUAL_PAGE = URL_HOME_PAGE
+ "/individual";
private static final String DEFAULT_NAMESPACE = URL_INDIVIDUAL_PAGE + "/";
/**
* Info about the individual that we're testing (mostly).
*/
private static final String ID_INDIVIDUAL_TEST = "testId";
private static final String URI_INDIVIDUAL_TEST = DEFAULT_NAMESPACE
+ ID_INDIVIDUAL_TEST;
private static final String NETID_USER_TEST = "joeUser";
/**
* Info about the file bytestream that appears in one test.
*/
/** The ID of an Individual that represents a FileBytestream object. */
private static final String ID_FILE_BYTESTREAM = "bytesId";
private static final String URI_FILE_BYTESTREAM = DEFAULT_NAMESPACE
+ ID_FILE_BYTESTREAM;
private static final String BYTESTREAM_FILENAME = "imageFilename.jpg";
private static final String URL_BYTESTREAM_ALIAS = URL_HOME_PAGE + "/file/"
+ ID_FILE_BYTESTREAM + "/" + BYTESTREAM_FILENAME;
private IndividualRequestAnalyzer analyzer;
private IndividualRequestAnalysisContextStub analysisContext;
private HttpServletRequestStub req;
private VitroRequest vreq;
private IndividualRequestInfo requestInfo;
private IndividualStub testIndividual;
private IndividualStub bytestreamIndividual;
@Before
public void setup() {
req = new HttpServletRequestStub();
analysisContext = new IndividualRequestAnalysisContextStub(DEFAULT_NAMESPACE);
testIndividual = new IndividualStub(URI_INDIVIDUAL_TEST);
analysisContext.addIndividual(testIndividual);
analysisContext.addProfilePage(NETID_USER_TEST, testIndividual);
bytestreamIndividual = new IndividualStub(URI_FILE_BYTESTREAM);
analysisContext.addIndividual(bytestreamIndividual);
analysisContext.setAliasUrl(URI_FILE_BYTESTREAM, URL_BYTESTREAM_ALIAS);
}
// ----------------------------------------------------------------------
// Tests - locate by parameter
// ----------------------------------------------------------------------
/** /individual?uri=urlencodedURI */
@Test
public void findIndividualByUriParameter() {
req.setRequestUrl(url(URL_INDIVIDUAL_PAGE));
req.addParameter("uri", URI_INDIVIDUAL_TEST);
analyzeIt();
assertDefaultRequestInfo("find by URI parameter", URI_INDIVIDUAL_TEST);
}
/** /individual?netId=bdc34 */
@Test
public void findIndividualByNetIdParameter() {
req.setRequestUrl(url(URL_INDIVIDUAL_PAGE));
req.addParameter("netId", NETID_USER_TEST);
analyzeIt();
assertDefaultRequestInfo("find by netId parameter", URI_INDIVIDUAL_TEST);
}
/** /individual?netid=bdc34 */
@Test
public void findIndividualByNetidParameter() {
req.setRequestUrl(url(URL_INDIVIDUAL_PAGE));
req.addParameter("netid", NETID_USER_TEST);
analyzeIt();
assertDefaultRequestInfo("find by netid parameter", URI_INDIVIDUAL_TEST);
}
// ----------------------------------------------------------------------
// Tests - miscellaneous
// ----------------------------------------------------------------------
/** /display/localname */
@Test
public void findIndividualByDisplayPath() {
req.setRequestUrl(url(URL_HOME_PAGE + "/display/" + ID_INDIVIDUAL_TEST));
analyzeIt();
assertDefaultRequestInfo("find by display path", URI_INDIVIDUAL_TEST);
}
/** /individual/a/b/c fails. */
@Test
public void unrecognizedPath() {
req.setRequestUrl(url(DEFAULT_NAMESPACE + "this/that/theOther"));
analyzeIt();
assertNoIndividualRequestInfo("unrecognized path");
}
/** /display/localname but no such individual */
@Test
public void findNoSuchIndividualByDisplayPath() {
req.setRequestUrl(url(URL_HOME_PAGE + "/display/" + "bogusID"));
analyzeIt();
assertNoIndividualRequestInfo("unrecognized ID");
}
// ----------------------------------------------------------------------
// Tests - redirect a FileBytestream
// ----------------------------------------------------------------------
@Test
public void redirectAFileBytestreamIndividual() {
req.setRequestUrl(url(URL_HOME_PAGE + "/display/" + ID_FILE_BYTESTREAM));
analyzeIt();
assertBytestreamRedirectInfo("bytestream redirect",
URL_BYTESTREAM_ALIAS);
}
// ----------------------------------------------------------------------
// Tests - redirect from a Linked Data path
// ----------------------------------------------------------------------
/** /individual/localname, accept=RDF redirects to /individual/id/id.rdf */
@Test
public void redirectFromLinkedDataPathAcceptRdf() {
req.setRequestUrl(url(DEFAULT_NAMESPACE + ID_INDIVIDUAL_TEST));
req.setHeader("accept", RDFXML_MIMETYPE);
analyzeIt();
assertRdfRedirectRequestInfo("by linked data path, accept RDF",
redirectUrlForRdfStream(ID_INDIVIDUAL_TEST, ".rdf"));
}
/** /individual/localname, accept=N3 redirects to /individual/id/id.n3 */
@Test
public void redirectFromLinkedDataPathAcceptN3() {
req.setRequestUrl(url(DEFAULT_NAMESPACE + ID_INDIVIDUAL_TEST));
req.setHeader("accept", N3_MIMETYPE);
analyzeIt();
assertRdfRedirectRequestInfo("by linked data path, accept N3",
redirectUrlForRdfStream(ID_INDIVIDUAL_TEST, ".n3"));
}
/** /individual/localname, accept=TTL redirects to /individual/id/id.ttl */
@Test
public void redirectFromLinkedDataPathAcceptTurtle() {
req.setRequestUrl(url(DEFAULT_NAMESPACE + ID_INDIVIDUAL_TEST));
req.setHeader("accept", TTL_MIMETYPE);
analyzeIt();
assertRdfRedirectRequestInfo("by linked data path, accept TTL",
redirectUrlForRdfStream(ID_INDIVIDUAL_TEST, ".ttl"));
}
/** /individual/localname, no accept, redirects to /display/id */
@Test
public void redirectFromLinkedDataPathNoAccept() {
req.setRequestUrl(url(DEFAULT_NAMESPACE + ID_INDIVIDUAL_TEST));
analyzeIt();
assertRdfRedirectRequestInfo("by linked data path with no accept",
"/display/" + ID_INDIVIDUAL_TEST);
}
/**
* If the accept header is set to a recognized value, but not one of the
* onese that we like, treat the same as no accept.
*/
@Test
public void redirectFromLinkedDataPathAcceptStrange() {
req.setRequestUrl(url(DEFAULT_NAMESPACE + ID_INDIVIDUAL_TEST));
req.setHeader("accept", "image/jpg");
analyzeIt();
assertRdfRedirectRequestInfo(
"by linked data path, accept a strange content type",
"/display/" + ID_INDIVIDUAL_TEST);
}
/**
* If the accept header is set to an unrecognized value, treat the same as
* no accept.
*/
@Test
public void redirectFromLinkedDataPathAcceptGarbage() {
req.setRequestUrl(url(DEFAULT_NAMESPACE + ID_INDIVIDUAL_TEST));
req.setHeader("accept", "a/b/c");
analyzeIt();
assertRdfRedirectRequestInfo(
"by linked data path, accept an unrecognized content type",
"/display/" + ID_INDIVIDUAL_TEST);
}
// ----------------------------------------------------------------------
// Tests - satisfy requests for RDF formats.
// ----------------------------------------------------------------------
@Test
public void getRdfByUriAndFormatParameters() {
req.setRequestUrl(url(URL_INDIVIDUAL_PAGE));
req.addParameter("uri", URI_INDIVIDUAL_TEST);
req.addParameter("format", "rdfxml");
analyzeIt();
assertLinkedDataRequestInfo("RDF by uri and format parameters",
URI_INDIVIDUAL_TEST, ContentType.RDFXML);
}
@Test
public void getN3ByUriAndFormatParameters() {
req.setRequestUrl(url(URL_INDIVIDUAL_PAGE));
req.addParameter("uri", URI_INDIVIDUAL_TEST);
req.addParameter("format", "n3");
analyzeIt();
assertLinkedDataRequestInfo("N3 by uri and format parameters",
URI_INDIVIDUAL_TEST, ContentType.N3);
}
@Test
public void getTurtleByUriAndFormatParameters() {
req.setRequestUrl(url(URL_INDIVIDUAL_PAGE));
req.addParameter("uri", URI_INDIVIDUAL_TEST);
req.addParameter("format", "ttl");
analyzeIt();
assertLinkedDataRequestInfo("Turtle by uri and format parameters",
URI_INDIVIDUAL_TEST, ContentType.TURTLE);
}
@Test
public void unrecognizedFormatParameter() {
req.setRequestUrl(url(URL_INDIVIDUAL_PAGE));
req.addParameter("uri", URI_INDIVIDUAL_TEST);
req.addParameter("format", "bogus");
analyzeIt();
assertDefaultRequestInfo("unrecognized format means HTML response",
URI_INDIVIDUAL_TEST);
}
/** http://vivo.cornell.edu/individual/n23/n23.rdf */
@Test
public void getRdfByStreamRequest() {
req.setRequestUrl(absoluteUrlForRdfStream(ID_INDIVIDUAL_TEST, ".rdf"));
analyzeIt();
assertLinkedDataRequestInfo("RDF by stream request",
URI_INDIVIDUAL_TEST, ContentType.RDFXML);
}
/** http://vivo.cornell.edu/individual/n23/n23.n3 */
@Test
public void getN3ByStreamRequest() {
req.setRequestUrl(absoluteUrlForRdfStream(ID_INDIVIDUAL_TEST, ".n3"));
analyzeIt();
assertLinkedDataRequestInfo("N3 by stream request",
URI_INDIVIDUAL_TEST, ContentType.N3);
}
/** http://vivo.cornell.edu/individual/n23/n23.rdf */
@Test
public void getTurtleByStreamRequest() {
req.setRequestUrl(absoluteUrlForRdfStream(ID_INDIVIDUAL_TEST, ".ttl"));
analyzeIt();
assertLinkedDataRequestInfo("Turtle by stream request",
URI_INDIVIDUAL_TEST, ContentType.TURTLE);
}
/** http://vivo.cornell.edu/individual/n23/n23.bogus is an error */
@Test
public void unrecognizedFormatForRdfStreamRequest() {
req.setRequestUrl(absoluteUrlForRdfStream(ID_INDIVIDUAL_TEST, ".bogus"));
analyzeIt();
assertNoIndividualRequestInfo("Unrecognized RDF stream request");
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
/** /individual/n23/n23.rdf, or the like */
private String redirectUrlForRdfStream(String id, String extension) {
return "/individual/" + id + "/" + id + extension;
}
/** http://vivo.mydomain.edu/individual/n23/n23.rdf, or the like */
private URL absoluteUrlForRdfStream(String id, String extension) {
return url(DEFAULT_NAMESPACE + id + "/" + id + extension);
}
private void analyzeIt() {
vreq = new VitroRequest(req);
analyzer = new IndividualRequestAnalyzer(vreq, analysisContext);
requestInfo = analyzer.analyze();
}
/** We should have a DEFAULT request with the expected Individual. */
private void assertDefaultRequestInfo(String message, String individualUri) {
assertEquals(message + ": expecting DEFAULT request type",
IndividualRequestInfo.Type.DEFAULT, requestInfo.getType());
assertNotNull(message + ": expected an individual",
requestInfo.getIndividual());
assertEquals(message + ": expected individual", individualUri,
requestInfo.getIndividual().getURI());
}
/** We should have a RDF_REDIRECT request with the expected URL. */
private void assertRdfRedirectRequestInfo(String message, String redirectUrl) {
assertEquals(message + ": expecting RDF_REDIRECT request type",
IndividualRequestInfo.Type.RDF_REDIRECT, requestInfo.getType());
assertEquals(message + ": expected redirect URL", redirectUrl,
requestInfo.getRedirectUrl());
}
/**
* We should have a BYTESTREAM_REDIRECT request with the expected Individual
* and alias URL.
*/
private void assertBytestreamRedirectInfo(String message, String aliasUrl) {
assertEquals(message + ": expecting BYTESTREAM_REDIRECT request type",
IndividualRequestInfo.Type.BYTESTREAM_REDIRECT,
requestInfo.getType());
assertEquals(message + ": expected alias URL", aliasUrl,
requestInfo.getRedirectUrl());
}
/**
* We should have a NO_INDIVIDUAL request.
*/
private void assertNoIndividualRequestInfo(String message) {
assertEquals(message + ": expecting NO_INDIVIDUAL request type",
IndividualRequestInfo.Type.NO_INDIVIDUAL, requestInfo.getType());
}
/**
* We should have a LINKED_DATA request, with the expected Individual and
* content type.
*/
private void assertLinkedDataRequestInfo(String message,
String individualUri, ContentType contentType) {
assertEquals(message + ": expecting LINKED_DATA request type",
IndividualRequestInfo.Type.LINKED_DATA, requestInfo.getType());
assertNotNull(message + ": expected an individual",
requestInfo.getIndividual());
assertEquals(message + ": expected individual", individualUri,
requestInfo.getIndividual().getURI());
assertNotNull(message + ": expected a content type",
requestInfo.getRdfFormat());
assertEquals(message + ": expected contentType", contentType,
requestInfo.getRdfFormat());
}
}

View file

@ -0,0 +1,255 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.json;
import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import javax.servlet.ServletException;
import org.apache.log4j.Level;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import stubs.edu.cornell.mannlib.vitro.webapp.dao.VClassDaoStub;
import stubs.edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactoryStub;
import stubs.edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccessFactoryStub;
import stubs.edu.cornell.mannlib.vitro.webapp.modules.ApplicationStub;
import stubs.edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchEngineStub;
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.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
/**
* TODO
*/
public class JsonServletTest extends AbstractTestClass {
private static final String GET_SEARCH_INDIVIDUALS_BY_VCLASS = "getSearchIndividualsByVClass";
private static final String GET_VCLASSES_FOR_VCLASS_GROUP = "getVClassesForVClassGroup";
private static final String VCLASS_ID = "vclassId";
/**
* Test plan
*
* <pre>
*
* GetEntitiesByVClass, GetEntitiesByVClassContinuation
* from ents_edit.js
* ents_edit_head.jsp
* (there is an ents_edit.jsp, invoked from EntityEditController, which does not seem to invoke ents_edit.js)
*
* GetSearchIndividualsByVClass
* Mock out search engine and IndividualDao
* invoked by BrowseDataGetter.java
* home page
* invoked by ClassGroupPageData.java
* >>>> Bring up "People" tab.
* invoked by BrowseWidget.java
*
* GetSearchIndividualsByVClasses
* Mock out search engine and IndividualDao
* invoked by IndividualsForClassesDataGetter.java
* ProcessIndividualsForClasses
* extended in vivo by ProcessInternalClasses
* SelectDataGetterUtils.java
* SelectDataGetterUtils
* MenuManagementEdit.java
* MenuManagementController.java
* extended in vivo by InternalClassesDataGetter, also invoked by SelectDataGetterUtils
*
* GetDataForPage
* Mock out PageDao
* </pre>
*/
private JsonServlet servlet;
private ServletConfigStub config;
private ServletContextStub ctx;
private HttpSessionStub session;
private HttpServletRequestStub req;
private HttpServletResponseStub resp;
private WebappDaoFactoryStub wadf;
private VClassDaoStub vcDao;
private SearchEngineStub search;
@Before
public void setup() throws ServletException {
ctx = new ServletContextStub();
session = new HttpSessionStub();
session.setServletContext(ctx);
config = new ServletConfigStub();
config.setServletContext(ctx);
servlet = new JsonServlet();
servlet.init(config);
req = new HttpServletRequestStub();
req.setMethod("GET");
req.setSession(session);
resp = new HttpServletResponseStub();
wadf = new WebappDaoFactoryStub();
new ModelAccessFactoryStub().get(req).setWebappDaoFactory(wadf);
vcDao = new VClassDaoStub();
wadf.setVClassDao(vcDao);
search = new SearchEngineStub();
ApplicationStub.setup(new ServletContextStub(), search);
}
@Test
public void noRecognizedRequestParameters() throws ServletException,
IOException {
servlet.service(req, resp);
assertEquals("empty response", "", resp.getOutput());
assertEquals("status=ok", SC_OK, resp.getStatus());
}
@Test
public void vclassesNoClassgroup() throws ServletException, IOException {
setLoggerLevel(JsonServlet.class, Level.FATAL);
setLoggerLevel(JsonObjectProducer.class, Level.FATAL);
req.addParameter(GET_VCLASSES_FOR_VCLASS_GROUP, "true");
servlet.service(req, resp);
assertFailureWithErrorMessage("java.lang.Exception: no URI passed for classgroupUri");
assertEquals("status=failure", SC_INTERNAL_SERVER_ERROR,
resp.getStatus());
}
/**
* TODO Modify VClassGroupCache so it can be stubbed out. JsonServlet asks
* VClassGroupCache for the current instance, and VClassGroupCache is a
* concrete class instead of an interface, so we can't replace the instance
* with one we like better. Furthermore, VClassGroupCache has a private
* constructor, so we can't change its behavior at all.
*
* Also test: success but no VClasses found, success with one VClass,
* success with multiple VClasses. In each case, confirm proper status,
* character encoding, and content type on the response.
*/
@Ignore
@Test
public void vclassesClassgroupNotRecognized() throws ServletException,
IOException {
req.addParameter(GET_VCLASSES_FOR_VCLASS_GROUP, "true");
req.addParameter("classgroupUri", "http://bogusUri");
servlet.service(req, resp);
assertEquals("empty response", "", resp.getOutput());
assertEquals("status=failure", SC_INTERNAL_SERVER_ERROR,
resp.getStatus());
}
@Test
public void individualsByClassNoVClass() throws ServletException,
IOException {
setLoggerLevel(JsonServlet.class, Level.FATAL);
setLoggerLevel(JsonObjectProducer.class, Level.FATAL);
req.addParameter(GET_SEARCH_INDIVIDUALS_BY_VCLASS, "true");
servlet.service(req, resp);
assertFailureWithErrorMessage("java.lang.Exception: "
+ "parameter vclassId URI parameter expected ");
}
@Test
public void individualsByClassUnrecognizedVClass() throws ServletException,
IOException {
setLoggerLevel(JsonServlet.class, Level.FATAL);
setLoggerLevel(JsonObjectProducer.class, Level.FATAL);
String vclassId = "http://bogusVclass";
req.addParameter(GET_SEARCH_INDIVIDUALS_BY_VCLASS, "true");
req.addParameter(VCLASS_ID, vclassId);
servlet.service(req, resp);
assertFailureWithErrorMessage("java.lang.Exception: " + "Class "
+ vclassId + " not found");
}
/**
* TODO test successful responses. This will require figuring out how to
* stub SearchEngine. Since we are no longer dealing with an abstract class
* (like SolrServer), so we just need to figure out what sort of NamedList
* is required as a response to a request.
*/
@Test
public void individualsByClassNoIndividuals() throws ServletException,
IOException {
setLoggerLevel(JsonServlet.class, Level.FATAL);
setLoggerLevel(ModelAccess.class, Level.ERROR);
String vclassId = "http://myVclass";
vcDao.setVClass(vclassId, new VClass(vclassId));
req.addParameter(GET_SEARCH_INDIVIDUALS_BY_VCLASS, "true");
req.addParameter(VCLASS_ID, vclassId);
servlet.service(req, resp);
assertSuccessWithIndividuals(vclassId, 0);
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
/**
* The response should be a JSONObject that contained this error-message,
* and the status should be set to INTERNAL_SERVER_ERROR.
*/
private void assertFailureWithErrorMessage(String expected) {
try {
JSONObject result = new JSONObject(resp.getOutput());
assertEquals("errorMessage", expected,
getFieldValue(result, "errorMessage"));
assertEquals("status", SC_INTERNAL_SERVER_ERROR, resp.getStatus());
} catch (JSONException e) {
fail(e.toString());
}
}
private void assertSuccessWithIndividuals(String vclassId, int count) {
try {
JSONObject actual = new JSONObject(resp.getOutput());
assertEquals("errorMessage", "",
getFieldValue(actual, "errorMessage"));
assertEquals("count", count, getFieldValue(actual, "totalCount"));
JSONObject vclassObj = (JSONObject) getFieldValue(actual, "vclass");
assertEquals("vclass name", vclassId.split("://")[1],
getFieldValue(vclassObj, "name"));
assertEquals("vclass uri", vclassId,
getFieldValue(vclassObj, "URI"));
assertEquals("status", SC_OK, resp.getStatus());
} catch (JSONException e) {
fail(e.toString());
}
}
private Object getFieldValue(JSONObject json, String fieldName) {
try {
assertEquals("find " + fieldName, true, json.has(fieldName));
return json.get(fieldName);
} catch (JSONException e) {
fail(e.toString());
return -1;
}
}
}

View file

@ -0,0 +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;
}
}

View file

@ -0,0 +1,878 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.dao.filtering;
import static edu.cornell.mannlib.vitro.webapp.auth.requestedAction.RequestedAction.SOME_URI;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
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 net.sf.jga.fn.UnaryFunctor;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import stubs.edu.cornell.mannlib.vitro.webapp.beans.IndividualStub;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
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.PropertyGroup;
import edu.cornell.mannlib.vitro.webapp.beans.PropertyInstance;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup;
import edu.cornell.mannlib.vitro.webapp.dao.filtering.filters.VitroFilters;
/**
* Test that the IndividualFiltering class filters by statements as much as
* possible. That way the filter can consider the subject of the statement as
* well as the predicate, when deciding whether to authorize the request.
*
* <pre>
* Start with six properties and a filter that recognizes them.
* DATA_HIDDEN -- never approved
* DATA_VISIBLE -- always approved
* DATA_MAYBE -- only approved in statements with subject of SPECIAL URI.
* OBJECT_HIDDEN -- never approved
* OBJECT_VISIBLE -- always approved
* OBJECT_MAYBE -- only approved in statements with subject or object of SPECIAL URI.
*
* Test all of the filtering methods on two filtered individuals.
* One is SPECIAL_URI, and should see the MAYBE properties.
* One is ordinary, and should not see the MAYBE properties.
* </pre>
*
* This is a simplification of a "self-editing" filter, which shows some
* properties, hides others, and allows some of the hidden ones in statements,
* depending on the subject and/or object of the statement.
*/
public class IndividualFilteringByStatementTest extends AbstractTestClass {
private static final String URI_INDIVIDUAL_SPECIAL = "specialUri";
private static final String URI_SUBJECT = "subject";
private static final String PROPERTY_DATA_HIDDEN = "hiddenDataProperty";
private static final String PROPERTY_DATA_VISIBLE = "visibleDataProperty";
private static final String PROPERTY_DATA_MAYBE = "maybeDataProperty";
private static final String PROPERTY_OBJECT_HIDDEN = "hiddenObjectProperty";
private static final String PROPERTY_OBJECT_VISIBLE = "visibleObjectProperty";
private static final String PROPERTY_OBJECT_MAYBE = "maybeObjectProperty";
private static final String VALUE_HIDDEN_DATA_SPECIAL = "hidden data on special";
private static final String VALUE_VISIBLE_DATA_SPECIAL = "visible data on special";
private static final String VALUE_MAYBE_DATA_SPECIAL = "maybe data on special";
private static final String URI_HIDDEN_OBJECT_SPECIAL = "object://hidden_on_special";
private static final String URI_VISIBLE_OBJECT_SPECIAL = "object://visible_on_special";
private static final String URI_MAYBE_OBJECT_SPECIAL = "object://maybe_on_special";
private static final String VALUE_HIDDEN_DATA_ORDINARY = "hidden data on ordinary";
private static final String VALUE_VISIBLE_DATA_ORDINARY = "visible data on ordinary";
private static final String VALUE_MAYBE_DATA_ORDINARY = "maybe data on ordinary";
private static final String URI_HIDDEN_OBJECT_ORDINARY = "object://hidden_on_ordinary";
private static final String URI_VISIBLE_OBJECT_ORDINARY = "object://visible_on_ordinary";
private static final String URI_MAYBE_OBJECT_ORDINARY = "object://maybe_on_ordinary";
private static final String FAUX_DOMAIN_VISIBLE = "faux://visibleDomain";
private static final String FAUX_RANGE_VISIBLE = "faux://visibleRange";
private static final String FAUX_DOMAIN_HIDDEN = "faux://hiddenDomain";
private static final String FAUX_RANGE_HIDDEN = "faux://hiddenRange";
private static final String URI_FAUX_VISIBLE_ORDINARY = "object://faux_visible_on_ordinary";
private static final String URI_FAUX_HIDDEN_ORDINARY = "object://faux_hidden_on_ordinary";
private IndividualStub indSpecial;
private IndividualStub indOrdinary;
private Individual filteredSpecial;
private Individual filteredOrdinary;
@Before
public void createIndividuals() {
indSpecial = new IndividualStub(URI_INDIVIDUAL_SPECIAL);
indSpecial.addDataPropertyStatement(PROPERTY_DATA_HIDDEN,
VALUE_HIDDEN_DATA_SPECIAL);
indSpecial.addDataPropertyStatement(PROPERTY_DATA_VISIBLE,
VALUE_VISIBLE_DATA_SPECIAL);
indSpecial.addDataPropertyStatement(PROPERTY_DATA_MAYBE,
VALUE_MAYBE_DATA_SPECIAL);
indSpecial.addObjectPropertyStatement(property(PROPERTY_OBJECT_HIDDEN),
URI_HIDDEN_OBJECT_SPECIAL);
indSpecial.addObjectPropertyStatement(
property(PROPERTY_OBJECT_VISIBLE), URI_VISIBLE_OBJECT_SPECIAL);
indSpecial.addObjectPropertyStatement(property(PROPERTY_OBJECT_MAYBE),
URI_MAYBE_OBJECT_SPECIAL);
filteredSpecial = new IndividualFiltering(indSpecial,
new IndividualBasedFilter());
indOrdinary = new IndividualStub("someOtherUri");
indOrdinary.addDataPropertyStatement(PROPERTY_DATA_HIDDEN,
VALUE_HIDDEN_DATA_ORDINARY);
indOrdinary.addDataPropertyStatement(PROPERTY_DATA_VISIBLE,
VALUE_VISIBLE_DATA_ORDINARY);
indOrdinary.addDataPropertyStatement(PROPERTY_DATA_MAYBE,
VALUE_MAYBE_DATA_ORDINARY);
indOrdinary.addObjectPropertyStatement(
property(PROPERTY_OBJECT_HIDDEN), URI_HIDDEN_OBJECT_ORDINARY);
indOrdinary.addObjectPropertyStatement(
property(PROPERTY_OBJECT_VISIBLE), URI_VISIBLE_OBJECT_ORDINARY);
indOrdinary.addObjectPropertyStatement(property(PROPERTY_OBJECT_MAYBE),
URI_MAYBE_OBJECT_ORDINARY);
filteredOrdinary = new IndividualFiltering(indOrdinary,
new IndividualBasedFilter());
}
private ObjectProperty property(String propertyUri) {
return property(propertyUri, SOME_URI, SOME_URI);
}
private ObjectProperty property(String propertyUri, String domainUri,
String rangeUri) {
ObjectProperty op = new ObjectProperty();
op.setURI(propertyUri);
op.setDomainVClassURI(domainUri);
op.setRangeVClassURI(rangeUri);
return op;
}
// ----------------------------------------------------------------------
// Tests on data properties
// ----------------------------------------------------------------------
@Test
public void onSpecial_getDataPropertyStatements() {
List<DataPropertyStatement> expected = dpsList(filteredSpecial,
dps(PROPERTY_DATA_MAYBE, VALUE_MAYBE_DATA_SPECIAL),
dps(PROPERTY_DATA_VISIBLE, VALUE_VISIBLE_DATA_SPECIAL));
List<DataPropertyStatement> actual = filteredSpecial
.getDataPropertyStatements();
assertEquivalentDpsList("data property statements", expected, actual);
}
@Test
public void onOrdinary_getDataPropertyStatements() {
List<DataPropertyStatement> expected = dpsList(filteredOrdinary,
dps(PROPERTY_DATA_VISIBLE, VALUE_VISIBLE_DATA_ORDINARY));
List<DataPropertyStatement> actual = filteredOrdinary
.getDataPropertyStatements();
assertEquivalentDpsList("data property statements", expected, actual);
}
@Test
public void onSpecial_getDataPropertyStatementsByProperty() {
List<DataPropertyStatement> visibleExpected = dpsList(filteredSpecial,
dps(PROPERTY_DATA_VISIBLE, VALUE_VISIBLE_DATA_SPECIAL));
List<DataPropertyStatement> visibleActual = filteredSpecial
.getDataPropertyStatements(PROPERTY_DATA_VISIBLE);
assertEquivalentDpsList("visible", visibleExpected, visibleActual);
List<DataPropertyStatement> hiddenExpected = Collections.emptyList();
List<DataPropertyStatement> hiddenActual = filteredSpecial
.getDataPropertyStatements(PROPERTY_DATA_HIDDEN);
assertEquivalentDpsList("hidden", hiddenExpected, hiddenActual);
List<DataPropertyStatement> maybeExpected = dpsList(filteredSpecial,
dps(PROPERTY_DATA_MAYBE, VALUE_MAYBE_DATA_SPECIAL));
List<DataPropertyStatement> maybeActual = filteredSpecial
.getDataPropertyStatements(PROPERTY_DATA_MAYBE);
assertEquivalentDpsList("maybe", maybeExpected, maybeActual);
}
@Test
public void onOrdinary_getDataPropertyStatementsByProperty() {
List<DataPropertyStatement> visibleExpected = dpsList(filteredOrdinary,
dps(PROPERTY_DATA_VISIBLE, VALUE_VISIBLE_DATA_ORDINARY));
List<DataPropertyStatement> visibleActual = filteredOrdinary
.getDataPropertyStatements(PROPERTY_DATA_VISIBLE);
assertEquivalentDpsList("visible", visibleExpected, visibleActual);
List<DataPropertyStatement> hiddenExpected = Collections.emptyList();
List<DataPropertyStatement> hiddenActual = filteredOrdinary
.getDataPropertyStatements(PROPERTY_DATA_HIDDEN);
assertEquivalentDpsList("hidden", hiddenExpected, hiddenActual);
List<DataPropertyStatement> maybeExpected = Collections.emptyList();
List<DataPropertyStatement> maybeActual = filteredOrdinary
.getDataPropertyStatements(PROPERTY_DATA_MAYBE);
assertEquivalentDpsList("maybe", maybeExpected, maybeActual);
}
@Test
public void onSpecial_getDataPropertyStatement() {
DataPropertyStatement visibleExpected = dps(filteredSpecial.getURI(),
PROPERTY_DATA_VISIBLE, VALUE_VISIBLE_DATA_SPECIAL);
DataPropertyStatement visibleActual = filteredSpecial
.getDataPropertyStatement(PROPERTY_DATA_VISIBLE);
assertEquivalentDps("visible", visibleExpected, visibleActual);
DataPropertyStatement hiddenExpected = null;
DataPropertyStatement hiddenActual = filteredSpecial
.getDataPropertyStatement(PROPERTY_DATA_HIDDEN);
assertEquivalentDps("hidden", hiddenExpected, hiddenActual);
DataPropertyStatement maybeExpected = dps(filteredSpecial.getURI(),
PROPERTY_DATA_MAYBE, VALUE_MAYBE_DATA_SPECIAL);
DataPropertyStatement maybeActual = filteredSpecial
.getDataPropertyStatement(PROPERTY_DATA_MAYBE);
assertEquivalentDps("maybe", maybeExpected, maybeActual);
}
@Test
public void onOrdinary_getDataPropertyStatement() {
DataPropertyStatement visibleExpected = dps(filteredOrdinary.getURI(),
PROPERTY_DATA_VISIBLE, VALUE_VISIBLE_DATA_ORDINARY);
DataPropertyStatement visibleActual = filteredOrdinary
.getDataPropertyStatement(PROPERTY_DATA_VISIBLE);
assertEquivalentDps("visible", visibleExpected, visibleActual);
DataPropertyStatement hiddenExpected = null;
DataPropertyStatement hiddenActual = filteredOrdinary
.getDataPropertyStatement(PROPERTY_DATA_HIDDEN);
assertEquivalentDps("hidden", hiddenExpected, hiddenActual);
DataPropertyStatement maybeExpected = null;
DataPropertyStatement maybeActual = filteredOrdinary
.getDataPropertyStatement(PROPERTY_DATA_MAYBE);
assertEquivalentDps("maybe", maybeExpected, maybeActual);
}
@Ignore
@Test
public void onSpecial_getDataPropertyList() {
fail("onSpecial_getDataPropertyList not implemented");
}
@Ignore
@Test
public void onOrdinary_getDataPropertyList() {
fail("onOrdinary_getDataPropertyList not implemented");
}
@Ignore
@Test
public void onSpecial_getPopulatedDataPropertyList() {
fail("onSpecial_getPopulatedDataPropertyList not implemented");
}
@Ignore
@Test
public void onOrdinary_getPopulatedDataPropertyList() {
fail("onOrdinary_getPopulatedDataPropertyList not implemented");
}
@Ignore
@Test
public void onSpecial_getDataPropertyMap() {
fail("onSpecial_getDataPropertyMap not implemented");
}
@Ignore
@Test
public void onOrdinary_getDataPropertyMap() {
fail("onOrdinary_getDataPropertyMap not implemented");
}
// ----------------------------------------------------------------------
// Tests on object properties
// ----------------------------------------------------------------------
@Test
public void onSpecial_getObjectPropertyStatementsByProperty() {
List<ObjectPropertyStatement> visibleExpected = opsList(
filteredSpecial,
ops(PROPERTY_OBJECT_VISIBLE, URI_VISIBLE_OBJECT_SPECIAL));
List<ObjectPropertyStatement> visibleActual = filteredSpecial
.getObjectPropertyStatements(PROPERTY_OBJECT_VISIBLE);
assertEquivalentOpsList("visible", visibleExpected, visibleActual);
List<ObjectPropertyStatement> hiddenExpected = Collections.emptyList();
List<ObjectPropertyStatement> hiddenActual = filteredSpecial
.getObjectPropertyStatements(PROPERTY_OBJECT_HIDDEN);
assertEquivalentOpsList("hidden", hiddenExpected, hiddenActual);
List<ObjectPropertyStatement> maybeExpected = opsList(filteredSpecial,
ops(PROPERTY_OBJECT_MAYBE, URI_MAYBE_OBJECT_SPECIAL));
List<ObjectPropertyStatement> maybeActual = filteredSpecial
.getObjectPropertyStatements(PROPERTY_OBJECT_MAYBE);
assertEquivalentOpsList("maybe", maybeExpected, maybeActual);
}
@Test
public void onOrdinary_getObjectPropertyStatementsByProperty() {
List<ObjectPropertyStatement> visibleExpected = opsList(
filteredOrdinary,
ops(PROPERTY_OBJECT_VISIBLE, URI_VISIBLE_OBJECT_ORDINARY));
List<ObjectPropertyStatement> visibleActual = filteredOrdinary
.getObjectPropertyStatements(PROPERTY_OBJECT_VISIBLE);
assertEquivalentOpsList("visible", visibleExpected, visibleActual);
List<ObjectPropertyStatement> hiddenExpected = Collections.emptyList();
List<ObjectPropertyStatement> hiddenActual = filteredOrdinary
.getObjectPropertyStatements(PROPERTY_OBJECT_HIDDEN);
assertEquivalentOpsList("hidden", hiddenExpected, hiddenActual);
List<ObjectPropertyStatement> maybeExpected = Collections.emptyList();
List<ObjectPropertyStatement> maybeActual = filteredOrdinary
.getObjectPropertyStatements(PROPERTY_OBJECT_MAYBE);
assertEquivalentOpsList("maybe", maybeExpected, maybeActual);
}
@Test
public void onSpecial_getObjectPropertyStatements() {
List<ObjectPropertyStatement> expected = opsList(filteredSpecial,
ops(PROPERTY_OBJECT_MAYBE, URI_MAYBE_OBJECT_SPECIAL),
ops(PROPERTY_OBJECT_VISIBLE, URI_VISIBLE_OBJECT_SPECIAL));
List<ObjectPropertyStatement> actual = filteredSpecial
.getObjectPropertyStatements();
assertEquivalentOpsList("object property statements", expected, actual);
}
@Test
public void onOrdinary_getObjectPropertyStatements() {
List<ObjectPropertyStatement> expected = opsList(filteredOrdinary,
ops(PROPERTY_OBJECT_VISIBLE, URI_VISIBLE_OBJECT_ORDINARY));
List<ObjectPropertyStatement> actual = filteredOrdinary
.getObjectPropertyStatements();
assertEquivalentOpsList("object property statements", expected, actual);
}
@Ignore
@Test
public void onSpecial_getObjectPropertyMap() {
fail("onSpecial_getObjectPropertyMap not implemented");
}
@Ignore
@Test
public void onOrdinary_getObjectPropertyMap() {
fail("onOrdinary_getObjectPropertyMap not implemented");
}
@Ignore
@Test
public void onSpecial_getObjectPropertyList() {
fail("onSpecial_getObjectPropertyList not implemented");
}
@Ignore
@Test
public void onOrdinary_getObjectPropertyList() {
fail("onOrdinary_getObjectPropertyList not implemented");
}
@Ignore
@Test
public void onSpecial_getPopulatedObjectPropertyList() {
fail("onSpecial_getPopulatedObjectPropertyList not implemented");
}
@Ignore
@Test
public void onOrdinary_getPopulatedObjectPropertyList() {
fail("onOrdinary_getPopulatedObjectPropertyList not implemented");
}
// ----------------------------------------------------------------------
// Tests on Faux object properties
// ----------------------------------------------------------------------
@Test
public void hiddenFauxWithVisibleBase() {
indOrdinary.addObjectPropertyStatement(
property(PROPERTY_OBJECT_VISIBLE, FAUX_DOMAIN_HIDDEN,
FAUX_RANGE_HIDDEN), URI_FAUX_HIDDEN_ORDINARY);
filteredOrdinary = new IndividualFiltering(indOrdinary,
new IndividualBasedFilter());
List<ObjectPropertyStatement> expected = opsList(filteredOrdinary,
ops(PROPERTY_OBJECT_VISIBLE, URI_VISIBLE_OBJECT_ORDINARY));
List<ObjectPropertyStatement> actual = filteredOrdinary
.getObjectPropertyStatements();
assertEquivalentOpsList("hidden faux is not visible", expected, actual);
}
@Test
public void visibleFauxWithHiddenBase() {
indOrdinary.addObjectPropertyStatement(
property(PROPERTY_OBJECT_HIDDEN, FAUX_DOMAIN_VISIBLE,
FAUX_RANGE_VISIBLE), URI_FAUX_VISIBLE_ORDINARY);
filteredOrdinary = new IndividualFiltering(indOrdinary,
new IndividualBasedFilter());
List<ObjectPropertyStatement> expected = opsList(filteredOrdinary,
ops(PROPERTY_OBJECT_VISIBLE, URI_VISIBLE_OBJECT_ORDINARY),
ops(PROPERTY_OBJECT_HIDDEN, URI_FAUX_VISIBLE_ORDINARY));
List<ObjectPropertyStatement> actual = filteredOrdinary
.getObjectPropertyStatements();
assertEquivalentOpsList("visible faux even if base is hidden",
expected, actual);
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
private DataPropertyStatement dps(String propertyUri, String value) {
return dps("", propertyUri, value);
}
private DataPropertyStatement dps(String subjectUri, String propertyUri,
String value) {
return new DPS(subjectUri, propertyUri, value);
}
private List<DataPropertyStatement> dpsList(Individual ind,
DataPropertyStatement... dpsArray) {
List<DataPropertyStatement> list = new ArrayList<DataPropertyStatement>();
for (DataPropertyStatement dps : dpsArray) {
list.add(new DPS(ind.getURI(), dps.getDatapropURI(), dps.getData()));
}
return list;
}
private void assertEquivalentDpsList(String label,
Collection<DataPropertyStatement> expected,
Collection<DataPropertyStatement> actual) {
Set<DPS> expectedSet = new HashSet<DPS>();
for (DataPropertyStatement dps : expected) {
expectedSet.add(new DPS(dps));
}
Set<DPS> actualSet = new HashSet<DPS>();
for (DataPropertyStatement dps : actual) {
actualSet.add(new DPS(dps));
}
assertEquals(label, expectedSet, actualSet);
}
private void assertEquivalentDps(String label,
DataPropertyStatement expected, DataPropertyStatement actual) {
DPS expectedDps = (expected == null) ? null : new DPS(expected);
DPS actualDps = (actual == null) ? null : new DPS(actual);
assertEquals(label, expectedDps, actualDps);
}
private ObjectPropertyStatement ops(String propertyUri, String objectUri) {
return ops("", propertyUri, objectUri);
}
private ObjectPropertyStatement ops(String subjectUri, String propertyUri,
String objectUri) {
return new OPS(subjectUri, propertyUri, objectUri);
}
private List<ObjectPropertyStatement> opsList(Individual ind,
ObjectPropertyStatement... opsArray) {
List<ObjectPropertyStatement> list = new ArrayList<ObjectPropertyStatement>();
for (ObjectPropertyStatement ops : opsArray) {
list.add(new OPS(ind.getURI(), ops.getPropertyURI(), ops
.getObjectURI()));
}
return list;
}
private void assertEquivalentOpsList(String label,
Collection<ObjectPropertyStatement> expected,
Collection<ObjectPropertyStatement> actual) {
Set<OPS> expectedSet = new HashSet<OPS>();
for (ObjectPropertyStatement ops : expected) {
expectedSet.add(new OPS(ops));
}
Set<OPS> actualSet = new HashSet<OPS>();
for (ObjectPropertyStatement ops : actual) {
actualSet.add(new OPS(ops));
}
assertEquals(label, expectedSet, actualSet);
}
// ----------------------------------------------------------------------
// Helper classes
// ----------------------------------------------------------------------
private static class DPS implements DataPropertyStatement {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private final String subjectUri;
private final String predicateUri;
private final String value;
public DPS(String subjectUri, String predicateUri, String value) {
this.subjectUri = subjectUri;
this.predicateUri = predicateUri;
this.value = value;
}
public DPS(DataPropertyStatement dps) {
this(dps.getIndividualURI(), dps.getDatapropURI(), dps.getData());
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public String getIndividualURI() {
return subjectUri;
}
@Override
public String getDatapropURI() {
return predicateUri;
}
@Override
public String getData() {
return value;
}
@Override
public int hashCode() {
return subjectUri.hashCode() ^ predicateUri.hashCode()
^ value.hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof DPS)) {
return false;
}
DPS that = (DPS) obj;
return this.subjectUri.equals(that.subjectUri)
&& this.predicateUri.equals(that.predicateUri)
&& this.value.equals(that.value);
}
@Override
public String toString() {
return "DPS[" + subjectUri + ", " + predicateUri + ", " + value
+ "]";
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public Individual getIndividual() {
throw new RuntimeException(
"DataPropertyStatement.getIndividual() not implemented.");
}
@Override
public void setIndividual(Individual individual) {
throw new RuntimeException(
"DataPropertyStatement.setIndividual() not implemented.");
}
@Override
public void setIndividualURI(String individualURI) {
throw new RuntimeException(
"DataPropertyStatement.setIndividualURI() not implemented.");
}
@Override
public void setData(String data) {
throw new RuntimeException(
"DataPropertyStatement.setData() not implemented.");
}
@Override
public void setDatapropURI(String propertyURI) {
throw new RuntimeException(
"DataPropertyStatement.setDatapropURI() not implemented.");
}
@Override
public String getDatatypeURI() {
throw new RuntimeException(
"DataPropertyStatement.getDatatypeURI() not implemented.");
}
@Override
public void setDatatypeURI(String datatypeURI) {
throw new RuntimeException(
"DataPropertyStatement.setDatatypeURI() not implemented.");
}
@Override
public String getLanguage() {
throw new RuntimeException(
"DataPropertyStatement.getLanguage() not implemented.");
}
@Override
public void setLanguage(String language) {
throw new RuntimeException(
"DataPropertyStatement.setLanguage() not implemented.");
}
@Override
public String getString() {
throw new RuntimeException(
"DataPropertyStatement.getString() not implemented.");
}
}
private static class OPS implements ObjectPropertyStatement {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private final String subjectUri;
private final String predicateUri;
private final String objectUri;
public OPS(String subjectUri, String predicateUri, String objectUri) {
this.subjectUri = subjectUri;
this.predicateUri = predicateUri;
this.objectUri = objectUri;
}
public OPS(ObjectPropertyStatement ops) {
this(ops.getSubjectURI(), ops.getPropertyURI(), ops.getObjectURI());
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public String getSubjectURI() {
return subjectUri;
}
@Override
public String getPropertyURI() {
return predicateUri;
}
@Override
public String getObjectURI() {
return objectUri;
}
@Override
public int hashCode() {
return subjectUri.hashCode() ^ predicateUri.hashCode()
^ objectUri.hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof OPS)) {
return false;
}
OPS that = (OPS) obj;
return this.subjectUri.equals(that.subjectUri)
&& this.predicateUri.equals(that.predicateUri)
&& this.objectUri.equals(that.objectUri);
}
@Override
public String toString() {
return "OPS[" + subjectUri + ", " + predicateUri + ", " + objectUri
+ "]";
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public void setSubjectURI(String subjectURI) {
throw new RuntimeException(
"ObjectPropertyStatement.setSubjectURI() not implemented.");
}
@Override
public void setObjectURI(String objectURI) {
throw new RuntimeException(
"ObjectPropertyStatement.setObjectURI() not implemented.");
}
@Override
public Individual getSubject() {
throw new RuntimeException(
"ObjectPropertyStatement.getSubject() not implemented.");
}
@Override
public void setSubject(Individual subject) {
throw new RuntimeException(
"ObjectPropertyStatement.setSubject() not implemented.");
}
@Override
public ObjectProperty getProperty() {
throw new RuntimeException(
"ObjectPropertyStatement.getProperty() not implemented.");
}
@Override
public void setProperty(ObjectProperty property) {
throw new RuntimeException(
"ObjectPropertyStatement.setProperty() not implemented.");
}
@Override
public Individual getObject() {
throw new RuntimeException(
"ObjectPropertyStatement.getObject() not implemented.");
}
@Override
public void setObject(Individual object) {
throw new RuntimeException(
"ObjectPropertyStatement.setObject() not implemented.");
}
@Override
public void setPropertyURI(String URI) {
throw new RuntimeException(
"ObjectPropertyStatement.setPropertyURI() not implemented.");
}
@Override
public PropertyInstance toPropertyInstance() {
throw new RuntimeException(
"ObjectPropertyStatement.toPropertyInstance() not implemented.");
}
}
private static class IndividualBasedFilter implements VitroFilters {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private static class DataPropertyStatementFilter extends
UnaryFunctor<DataPropertyStatement, Boolean> {
@Override
public Boolean fn(DataPropertyStatement dps) {
if (PROPERTY_DATA_VISIBLE.equals(dps.getDatapropURI())) {
return true;
}
if (PROPERTY_DATA_MAYBE.equals(dps.getDatapropURI())
&& URI_INDIVIDUAL_SPECIAL
.equals(dps.getIndividualURI())) {
return true;
}
return false;
}
}
private static class ObjectPropertyStatementFilter extends
UnaryFunctor<ObjectPropertyStatement, Boolean> {
@Override
public Boolean fn(ObjectPropertyStatement ops) {
if (PROPERTY_OBJECT_VISIBLE.equals(ops.getPropertyURI())) {
if (isFauxHidden(ops)) {
return false;
} else {
return true;
}
}
if (PROPERTY_OBJECT_MAYBE.equals(ops.getPropertyURI())
&& URI_INDIVIDUAL_SPECIAL.equals(ops.getSubjectURI())) {
return true;
}
if (isFauxVisible(ops)) {
return true;
}
return false;
}
private boolean isFauxHidden(ObjectPropertyStatement ops) {
ObjectProperty prop = ops.getProperty();
return FAUX_DOMAIN_HIDDEN.equals(prop.getDomainVClassURI())
&& FAUX_RANGE_HIDDEN.equals(prop.getRangeVClassURI());
}
private boolean isFauxVisible(ObjectPropertyStatement ops) {
ObjectProperty prop = ops.getProperty();
return FAUX_DOMAIN_VISIBLE.equals(prop.getDomainVClassURI())
&& FAUX_RANGE_VISIBLE.equals(prop.getRangeVClassURI());
}
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public UnaryFunctor<DataPropertyStatement, Boolean> getDataPropertyStatementFilter() {
return new DataPropertyStatementFilter();
}
@Override
public UnaryFunctor<ObjectPropertyStatement, Boolean> getObjectPropertyStatementFilter() {
return new ObjectPropertyStatementFilter();
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public VitroFilters and(VitroFilters other) {
throw new RuntimeException("VitroFilters.and() not implemented.");
}
@Override
public UnaryFunctor<Individual, Boolean> getIndividualFilter() {
throw new RuntimeException(
"VitroFilters.getIndividualFilter() not implemented.");
}
@Override
public UnaryFunctor<DataProperty, Boolean> getDataPropertyFilter() {
throw new RuntimeException(
"VitroFilters.getDataPropertyFilter() not implemented.");
}
@Override
public UnaryFunctor<ObjectProperty, Boolean> getObjectPropertyFilter() {
throw new RuntimeException(
"VitroFilters.getObjectPropertyFilter() not implemented.");
}
@Override
public UnaryFunctor<VClass, Boolean> getClassFilter() {
throw new RuntimeException(
"VitroFilters.getClassFilter() not implemented.");
}
@Override
public UnaryFunctor<VClassGroup, Boolean> getVClassGroupFilter() {
throw new RuntimeException(
"VitroFilters.getVClassGroupFilter() not implemented.");
}
@Override
public UnaryFunctor<PropertyGroup, Boolean> getPropertyGroupFilter() {
throw new RuntimeException(
"VitroFilters.getPropertyGroupFilter() not implemented.");
}
}
}

View file

@ -0,0 +1,215 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.dao.filtering.filters;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import net.sf.jga.algorithms.Summarize;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
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.IndividualImpl;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatementImpl;
import edu.cornell.mannlib.vitro.webapp.dao.filtering.BaseFiltering;
public class VitroFiltersFactoryTest {
@Before
public void setUp() throws Exception {
}
// @Test
// public void testSunsetWindowFilterOnListOfEnts() {
// DateTime easyDate = new org.joda.time.DateTime(2005,1,1,0,0,0,0); //2005-01-01
// Date givenDate = easyDate.toDate();
//
// VitroFilters vf = FiltersForTabs.getSunsetWindowFilter(givenDate);
// Assert.assertNotNull(vf);
// checkFilterForNull(vf);
//
// List<Individual> ents = new LinkedList();
// for( int i = 0; i< 10; i++){
// Individual ent = new IndividualImpl();
// ent.setSunrise( null );
// ent.setSunset( null );
// ents.add(ent);
// }
//
// BaseFiltering bf = new BaseFiltering();
// List filtered = bf.filter(ents,vf.getIndividualFilter());
// Assert.assertNotNull(filtered);
// Assert.assertTrue("expcted to filter no entities, filtered out " + (10-filtered.size()),
// filtered.size() == 10);
//
// Individual ent = new IndividualImpl();
// ent.setSunrise( easyDate.minusDays(3).toDate() );
// ent.setSunset( easyDate.plusDays(3).toDate() );
// ents.add(ent);
//
// filtered = bf.filter(ents,vf.getIndividualFilter());
// Assert.assertNotNull(filtered);
// Assert.assertTrue("expcted to filter no entities, filtered out " + (11-filtered.size()),
// filtered.size() == 11);
//
// ent = new IndividualImpl();
// ent.setSunrise( easyDate.minusDays(100).toDate() );
// ent.setSunset( easyDate.minusDays(110).toDate() );
// ents.add(ent);
//
// filtered = bf.filter(ents,vf.getIndividualFilter());
// Assert.assertNotNull(filtered);
// Assert.assertTrue("expcted to filter one entity, filtered out " + (12-filtered.size()),
// filtered.size() == 11);
//
// long count = Summarize.count(ents,vf.getIndividualFilter());
// Assert.assertTrue("expected 12, got " + ents.size(), ents.size() == 12);
// Assert.assertTrue("expected count of 11, got " + count , count == 11);
//
// long a = 20000;
// int b = (int)a;
// Assert.assertTrue( b == 20000);
// }
// @Test
// public void testGetSunsetWindowFilter() {
// DateTime easyDate = new org.joda.time.DateTime(2005,1,1,0,0,0,0); //2005-01-01
// Date givenDate = easyDate.toDate();
//
// VitroFilters vf = FiltersForTabs.getSunsetWindowFilter(givenDate);
// Assert.assertNotNull(vf);
// checkFilterForNull(vf);
//
// Individual ent = new IndividualImpl();
// ent.setSunrise( easyDate.minusDays(3).toDate() );
// ent.setSunset( easyDate.plusDays(3).toDate() );
// Assert.assertTrue(vf.getIndividualFilter().fn( ent ) );
//
// ent.setSunrise( easyDate.toDate() );
// Assert.assertTrue("items should be not filtered on first sunrise day", vf.getIndividualFilter().fn(ent));
//
// ent.setSunrise( easyDate.minusDays(3).toDate() );
// ent.setSunset( easyDate.minusDays( 2 ).toDate() );
// Assert.assertFalse("should be sunset and filtered out", vf.getIndividualFilter().fn( ent ));
//
// ent.setSunrise( easyDate.plusDays(3).toDate() );
// ent.setSunset( easyDate.plusDays( 10 ).toDate() );
// Assert.assertFalse("should not yet be sunrised and filtered out", vf.getIndividualFilter().fn( ent ));
//
// ent.setSunrise( null );
// ent.setSunset( null );
// Assert.assertTrue("nulls should not throw exceptions and and not be filtered out", vf.getIndividualFilter().fn( ent ));
//
// //should work with webapp too
// Individual entwa = new IndividualImpl();
// entwa.setSunrise( easyDate.minusDays(3).toDate() );
// entwa.setSunset( easyDate.plusDays(3).toDate() );
// Assert.assertTrue(vf.getIndividualFilter().fn( entwa ) );
//
// entwa.setSunrise( easyDate.toDate() );
// Assert.assertTrue("items should be not filtered on first sunrise day", vf.getIndividualFilter().fn(entwa));
//
// entwa.setSunrise( easyDate.minusDays(3).toDate() );
// entwa.setSunset( easyDate.minusDays( 2 ).toDate() );
// Assert.assertFalse("should be sunset and filtered out", vf.getIndividualFilter().fn( entwa ));
//
// entwa.setSunrise( easyDate.plusDays(3).toDate() );
// entwa.setSunset( easyDate.plusDays( 10 ).toDate() );
// Assert.assertFalse("should not yet be sunrised and filtered out", vf.getIndividualFilter().fn( entwa ));
//
// entwa.setSunrise( null );
// entwa.setSunset( null );
// Assert.assertTrue("null should not throw exceptions and should not be filtered out", vf.getIndividualFilter().fn( entwa ));
//
// //ObjectPropertyStatements
// ObjectPropertyStatement ops = new ObjectPropertyStatementImpl();
// ops.setObject(entwa);
//
// entwa.setSunrise( easyDate.minusDays(3).toDate() );
// entwa.setSunset( easyDate.plusDays(3).toDate() );
// Assert.assertTrue(vf.getIndividualFilter().fn( entwa ) );
//
// entwa.setSunrise( easyDate.toDate() );
// Assert.assertTrue("items should be not filtered on first sunrise day", vf.getObjectPropertyStatementFilter().fn(ops));
//
// entwa.setSunrise( easyDate.minusDays(3).toDate() );
// entwa.setSunset( easyDate.minusDays( 2 ).toDate() );
// Assert.assertFalse("should be sunset and filtered out", vf.getObjectPropertyStatementFilter().fn(ops));
//
// entwa.setSunrise( easyDate.plusDays(3).toDate() );
// entwa.setSunset( easyDate.plusDays( 10 ).toDate() );
// Assert.assertFalse("should not yet be sunrised and filtered out", vf.getObjectPropertyStatementFilter().fn(ops));
//
// entwa.setSunrise( null );
// entwa.setSunset( null );
// Assert.assertTrue("null should not throw exceptions and should not be filtered out", vf.getObjectPropertyStatementFilter().fn(ops));
//
// ops.setSunrise( null );
// ops.setSunset( null );
// Assert.assertTrue("null should not throw exceptions and should not be filtered out", vf.getObjectPropertyStatementFilter().fn( ops ) );
//
// //DataPropertyStatements
// DataPropertyStatement dps = new DataPropertyStatementImpl();
// dps.setSunrise( easyDate.minusDays(3).toDate() );
// dps.setSunset( easyDate.plusDays( 3).toDate() );
// Assert.assertTrue( vf.getDataPropertyStatementFilter().fn( dps ) );
//
// dps.setSunrise( easyDate.toDate() );
// dps.setSunset( easyDate.plusDays( 3).toDate() );
// Assert.assertTrue( vf.getDataPropertyStatementFilter().fn( dps ) );
//
// dps.setSunrise( null );
// dps.setSunset( null );
// Assert.assertTrue("should be not throw exceptions and should not be filtered out", vf.getDataPropertyStatementFilter().fn( dps ) );
//
// }
@Test
public void testGetTestFilter() {
VitroFilters vf = VitroFilterUtils.getTestFilter();
checkFilterForNull(vf);
ArrayList<Individual> ents = new ArrayList<Individual>();
String[] names = {"Greg", "gary", "bob", "Sue", "jim" };
for( String name : names){
Individual ent = new IndividualImpl();
ent.setName(name);
ents.add(ent);
}
BaseFiltering bf = new BaseFiltering();
List<Individual> filteredEnts = bf.filter(ents,vf.getIndividualFilter());
Assert.assertNotNull(filteredEnts);
Assert.assertEquals("did not filter correctly", 2, filteredEnts.size());
}
public void checkFilterForNull(VitroFilters vf){
Assert.assertNotNull("filter was null", vf);
Assert.assertNotNull("getClassFilter was null", vf.getClassFilter());
Assert.assertNotNull("getDataPropertyFilter was null", vf.getDataPropertyFilter());
Assert.assertNotNull("getDataPropertyStatementFilter was null", vf.getDataPropertyStatementFilter());
Assert.assertNotNull("getObjectPropertyFilter was null", vf.getObjectPropertyFilter());
Assert.assertNotNull("getObjectPropertyStatementFilter was null", vf.getObjectPropertyStatementFilter());
Assert.assertNotNull("getIndividualFilter was null", vf.getIndividualFilter());
Assert.assertNotNull("getVClassGroupFilter was null", vf.getVClassGroupFilter());
}
@Test
public void testRoleLevelFilter(){
}
private boolean ACCEPT= true;
private boolean REJECT= false;
}

View file

@ -0,0 +1,155 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.dao.jena;
import org.apache.log4j.Level;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.hp.hpl.jena.ontology.DatatypeProperty;
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.impl.RDFDefaultErrorHandler;
import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
/**
*
*
*/
public class DataPropertyDaoJenaTest extends AbstractTestClass {
@Test
// Test that the DataPropertyDaoJena::updateDataProperty method will only update the jena model for
// those properties in DataProperty that have a different value from what is already in the
// jena model for that property.
//
// Specifically, updateDataProperty method should not remove a statement from the model and
// then add the same statement back in. The reason for this is that in vitro the "immutable" properties
// are stored in a sub-model and the user-editable properties are stored in a super-model and
// all updates are performed against the super-model, so removing and then re-adding
// the same statement may result in a change of state (if the statement was in the sub-model
// it will migrate to the super-model) because of the way jena handles additions and
// deletions with respect to super and sub models. This migration of statements may cause
// undesirable behavior in the vitro application.
public void minimalUpdates(){
// 1. create two models and attach one as a sub-model of the other
// 2. populate the sub-model with one statement for each of the 13 properties represented in DataProperty
// 3. save the state of both the sub-model and the super-model
// 4. populate a DataProperty object with the data in the (combined) model and call the updateDataProperty
// (having made no changes to the DataProperty object)
// 5. verify that both the sub-model and the super-model are unchanged
String propertyURI = "http://vivoweb.org/ontology/core#addressCity";
OntModel superModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM); // this simulates the user-editable ontology in vivo
OntModel subModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM); // this simulates the core ontology in vivo
superModel.addSubModel(subModel);
String rdfsLabel = "this is the rdfs label";
String lang = "en-US";
// populate sub-model
DatatypeProperty property1 = subModel.createDatatypeProperty(propertyURI);
property1.setLabel(rdfsLabel,lang);
property1.setPropertyValue(RDFS.domain, subModel.createResource("http://thisIsTheDomainClassURI"));
property1.setPropertyValue(RDFS.range, subModel.createResource("http://thisIsTheRangeClassURI"));
property1.addProperty(RDF.type, OWL.FunctionalProperty);
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.EXAMPLE_ANNOT), subModel.createTypedLiteral("this is the example"));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.DESCRIPTION_ANNOT), subModel.createTypedLiteral("this is the description"));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.PUBLIC_DESCRIPTION_ANNOT), subModel.createTypedLiteral("this is the public description"));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.DISPLAY_RANK_ANNOT), subModel.createTypedLiteral(21));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.DISPLAY_LIMIT), subModel.createTypedLiteral(5));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.HIDDEN_FROM_DISPLAY_BELOW_ROLE_LEVEL_ANNOT), subModel.createResource("http://vitro.mannlib.cornell.edu/ns/vitro/role#curator"));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.PROHIBITED_FROM_UPDATE_BELOW_ROLE_LEVEL_ANNOT), subModel.createResource("http://vitro.mannlib.cornell.edu/ns/vitro/role#selfEditor"));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT), subModel.createResource("http://vitro.mannlib.cornell.edu/ns/vitro/role#editor"));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.PROPERTY_INPROPERTYGROUPANNOT), subModel.createResource("http://thisIsTheInPropertyGroupURI"));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.PROPERTY_CUSTOMENTRYFORMANNOT), subModel.createResource("http://thisIsTheCustomFormEntryURI"));
// Save copies of sub-model and super-model
// uncommment the next two lines to debug failures
//System.out.println("**Before updating data property:");
//printModels(superModel, subModel);
superModel.removeSubModel(subModel);
OntModel origSubModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
origSubModel.add(subModel);
OntModel origSuperModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
origSuperModel.add(superModel);
superModel.addSubModel(subModel);
// Populate the DataProperty with the data in the sub-model and then update the combined model
// (from the unchanged object).
WebappDaoFactoryJena wdfj = new WebappDaoFactoryJena(superModel);
DataPropertyDaoJena dpdj = (DataPropertyDaoJena) wdfj.getDataPropertyDao();
DataProperty dataProperty = dpdj.getDataPropertyByURI(propertyURI); // the DataProperty will be populated
// with the information already in
// the jena model.
Assert.assertEquals(dataProperty.getPublicName(), property1.getLabel(lang));
dpdj.updateDataProperty(dataProperty); // we haven't changed any values here, so
// the models should be unchanged.
// Verify that the sub-model and super-model are both unchanged
// uncommment the next two lines to debug failures
//System.out.println("\n**After updating data property:");
//printModels(superModel,subModel);
superModel.removeSubModel(subModel);
//modtime affects the diff but we don't care about that difference
wipeOutModTime(origSubModel);
wipeOutModTime(origSuperModel);
wipeOutModTime(subModel);
wipeOutModTime(superModel);
Assert.assertTrue(subModel.isIsomorphicWith(origSubModel));
Assert.assertTrue(superModel.isIsomorphicWith(origSuperModel));
}
void printModels(OntModel superModel, OntModel subModel) {
// Detach the submodel for printing to get an accurate
// account of what is in each.
superModel.removeSubModel(subModel);
System.out.println("\nThe sub-model has " + subModel.size() + " statements:");
System.out.println("---------------------------------------------------");
subModel.writeAll(System.out,"N3",null);
System.out.println("\nThe super-model has " + superModel.size() + " statements:");
System.out.println("---------------------------------------------------");
superModel.write(System.out,"N3",null);
superModel.addSubModel(subModel);
}
void wipeOutModTime(Model model){
model.removeAll(null, model.createProperty(VitroVocabulary.MODTIME), null);
}
}

View file

@ -0,0 +1,859 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.dao.jena;
import java.io.StringReader;
import java.util.List;
import org.junit.Assert;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.vocabulary.XSD;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
public class DependentResourceDeleteJenaTest {
String isDependentRelation =
" <"+VitroVocabulary.PROPERTY_STUBOBJECTPROPERTYANNOT+"> \"true\"^^xsd:boolean .\n" ;
String nosePropIsDependentRel =
"<"+VitroVocabulary.PROPERTY_STUBOBJECTPROPERTYANNOT+"> rdf:type owl:AnnotationProperty .\n" +
" ex:hasNose " + isDependentRelation;
String prefixesN3 =
"@prefix vitro: <" + VitroVocabulary.vitroURI + "> . \n" +
"@prefix xsd: <" + XSD.getURI() + "> . \n " +
"@prefix ex: <http://example.com/> . \n" +
"@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . \n"+
"@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . \n"+
"@prefix owl: <http://www.w3.org/2002/07/owl#> . \n";
void printModels(Model expected, Model result){
System.out.println("Expected:");
expected.write(System.out);
System.out.println("Result:");
result.write(System.out);
}
@org.junit.Test
public void testStmtNormalDelete() {
String n3 =
prefixesN3 +
" ex:bob ex:hasNose ex:nose1 . " ;
Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
List<Statement> deletes = DependentResourceDeleteJena.getDependentResourceDeleteList(
model.createStatement(
model.createResource("http://example.com/bob"),
model.createProperty("http://example.com/hasNose"),
model.createResource("http://example.com/nose1")),
model);
Model resultModel = ModelFactory.createDefaultModel();
resultModel.add(deletes);
//all statements should be deleted
Assert.assertTrue(resultModel.isIsomorphicWith( model ));
}
@org.junit.Test
public void testStmtSimpleForceDelete() {
String n3=
prefixesN3 +
nosePropIsDependentRel +
"ex:hasHair " + isDependentRelation +
" ex:bob ex:hasNose ex:nose1 . \n" +
" ex:nose1 ex:hasHair ex:hair23. \n" +
" ex:hair23 ex:hasHairCount \"23\". " ;
String expected =
prefixesN3 +
" ex:bob ex:hasNose ex:nose1 . \n" +
" ex:nose1 ex:hasHair ex:hair23. \n" +
" ex:hair23 ex:hasHairCount \"23\". " ;
Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
List<Statement> deletes = DependentResourceDeleteJena.getDependentResourceDeleteList(
model.createStatement(
model.createResource("http://example.com/bob"),
model.createProperty("http://example.com/hasNose"),
model.createResource("http://example.com/nose1")),
model);
Model resultModel = ModelFactory.createDefaultModel();
resultModel.add(deletes);
//all statements should be deleted
Assert.assertTrue( resultModel.isIsomorphicWith( expectedModel ) ) ;
}
@org.junit.Test
public void testStmtNonForceDelete() {
String n3 =
prefixesN3 +
" ex:bob ex:hasNose ex:nose1 . \n" +
" ex:nose1 ex:hasHair ex:hair23. \n" +
" ex:hair23 ex:hasHairCount \"23\". " ;
String expected =
prefixesN3 +
" ex:nose1 ex:hasHair ex:hair23. \n" +
" ex:hair23 ex:hasHairCount \"23\". " ;
Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
List<Statement> deletes = DependentResourceDeleteJena.getDependentResourceDeleteList(
model.createStatement(
model.createResource("http://example.com/bob"),
model.createProperty("http://example.com/hasNose"),
model.createResource("http://example.com/nose1")),
model);
model.remove(deletes);
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
boolean same = expectedModel.isIsomorphicWith( model );
if( ! same ) printModels( expectedModel, model);
Assert.assertTrue( same );
}
@org.junit.Test
public void testStmtForceDeleteWithLiterals() {
String n3 =
prefixesN3 +
nosePropIsDependentRel +
"ex:hasHair " + isDependentRelation +
" ex:bob ex:a \"Bob\". \n" +
" ex:bob ex:hasNose ex:nose1 . \n" +
" ex:nose1 ex:a \"this is a literal\". \n" +
" ex:nose1 ex:b \"2343\" . \n" +
" ex:nose1 ex:hasHair ex:hair23. \n" +
" ex:hair23 ex:hasHairCount \"23\". " ;
String expected =
prefixesN3 +
nosePropIsDependentRel +
"ex:hasHair " + isDependentRelation +
" ex:bob ex:a \"Bob\". \n" ;
Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
List<Statement> deletes = DependentResourceDeleteJena.getDependentResourceDeleteList(
model.createStatement(
model.createResource("http://example.com/bob"),
model.createProperty("http://example.com/hasNose"),
model.createResource("http://example.com/nose1")),
model);
model.remove(deletes);
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
boolean same = expectedModel.isIsomorphicWith( model );
if( ! same ) printModels( expectedModel, model);
Assert.assertTrue( same );
}
@org.junit.Test
public void testStmtForceDeleteWithSimpleCycles() {
String n3 =
prefixesN3 +
nosePropIsDependentRel +
"ex:hasHair " + isDependentRelation +
" ex:bob ex:a \"Bob\". \n" +
" ex:bob ex:hasNose ex:nose1 . \n" +
" ex:nose1 ex:c ex:bob ." ;
String expected =
prefixesN3 +
nosePropIsDependentRel +
"ex:hasHair " + isDependentRelation +
" ex:bob ex:a \"Bob\"." ;
Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
List<Statement> deletes = DependentResourceDeleteJena.getDependentResourceDeleteList(
model.createStatement(
model.createResource("http://example.com/bob"),
model.createProperty("http://example.com/hasNose"),
model.createResource("http://example.com/nose1")),
model);
model.remove(deletes);
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
boolean same = expectedModel.isIsomorphicWith( model );
if( ! same ) printModels( expectedModel, model);
Assert.assertTrue( same );
}
@org.junit.Test
public void testStmtForceDeleteWithCycles() {
String n3 =
prefixesN3 +
nosePropIsDependentRel +
"ex:hasHair " + isDependentRelation +
" ex:bob ex:a \"Bob\". \n" +
" ex:bob ex:hasNose ex:nose1 . \n" +
" ex:nose1 ex:a \"this is a literal\". \n" +
" ex:nose1 ex:b \"2343\" . \n" +
" ex:nose1 ex:c ex:bob . \n" +
" ex:nose1 ex:hasHair ex:hair23. \n" +
" ex:hair23 ex:c ex:bob . \n" +
" ex:hair23 ex:hasHairCount \"23\". " ;
String expected =
prefixesN3 +
nosePropIsDependentRel +
"ex:hasHair " + isDependentRelation +
" ex:bob ex:a \"Bob\". \n" ;
Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
List<Statement> deletes = DependentResourceDeleteJena.getDependentResourceDeleteList(
model.createStatement(
model.createResource("http://example.com/bob"),
model.createProperty("http://example.com/hasNose"),
model.createResource("http://example.com/nose1")),
model);
model.remove(deletes);
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
boolean same = expectedModel.isIsomorphicWith( model );
if( ! same ) printModels( expectedModel, model);
Assert.assertTrue( same );
}
@org.junit.Test
public void testStmtForceDeleteWithCycles2() {
String n3 =
prefixesN3 +
nosePropIsDependentRel +
" ex:bob ex:a \"Bob\". \n" +
" ex:bob ex:hasNose ex:nose1 . \n" +
" ex:nose1 ex:a \"this is a literal\". \n" +
" ex:nose1 ex:b \"2343\" . \n" +
" ex:nose1 ex:c ex:nose1 . \n" +
" ex:nose1 ex:c ex:bob . \n" ;
String expected =
prefixesN3 +
nosePropIsDependentRel +
" ex:bob ex:a \"Bob\". \n" ;
Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
List<Statement> deletes = DependentResourceDeleteJena.getDependentResourceDeleteList(
model.createStatement(
model.createResource("http://example.com/bob"),
model.createProperty("http://example.com/hasNose"),
model.createResource("http://example.com/nose1")),
model);
model.remove(deletes);
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
boolean same = expectedModel.isIsomorphicWith( model );
if( ! same ) printModels( expectedModel, model);
Assert.assertTrue( same );
}
@org.junit.Test
public void testStmtForceDeleteWithLinks() {
String n3 =
prefixesN3 +
nosePropIsDependentRel +
" ex:bob ex:a \"Bob\". \n" +
" ex:bob ex:hasNose ex:nose1 . \n" +
" ex:nose1 ex:c ex:glasses65 . \n" +
" ex:glasses65 ex:c ex:nose1 . \n" +
" ex:glasses65 ex:a \"glasses 65\" ." ;
String expected =
prefixesN3 +
nosePropIsDependentRel +
" ex:bob ex:a \"Bob\". \n" +
" ex:glasses65 ex:a \"glasses 65\" ." ;
Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
List<Statement> deletes = DependentResourceDeleteJena.getDependentResourceDeleteList(
model.createStatement(
model.createResource("http://example.com/bob"),
model.createProperty("http://example.com/hasNose"),
model.createResource("http://example.com/nose1")),
model);
model.remove(deletes);
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
boolean same = expectedModel.isIsomorphicWith( model );
if( ! same ) printModels( expectedModel, model);
Assert.assertTrue( same );
}
@org.junit.Test
public void testStmtForceDeleteWithBNodes() {
String n3 =
prefixesN3 +
nosePropIsDependentRel +
" ex:bob ex:a \"Bob\". \n" +
" ex:bob ex:hasNose [ \n" +
" ex:a \"this is a bnode\"; \n" +
" ex:c ex:glasses65 ] . \n" +
" ex:glasses65 ex:a \"glasses 65\" ." ;
String expected =
prefixesN3 +
nosePropIsDependentRel +
" ex:bob ex:a \"Bob\". \n" +
" ex:glasses65 ex:a \"glasses 65\" ." ;
Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
StmtIterator stmtIt = model.listStatements(
model.createResource("http://example.com/bob"),
model.createProperty("http://example.com/hasNose"),
(RDFNode)null);
List<Statement> deletes =
DependentResourceDeleteJena.getDependentResourceDeleteList(stmtIt.nextStatement(),model);
model.remove(deletes);
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
boolean same = expectedModel.isIsomorphicWith( model );
if( ! same ) printModels( expectedModel, model);
Assert.assertTrue( same );
}
@org.junit.Test
public void testStmtForceDeleteWithNestedBNodes() {
String n3 =
prefixesN3 +
nosePropIsDependentRel +
" ex:bob ex:a \"Bob\". \n" +
" ex:bob ex:hasNose [ \n" +
" ex:a \"this is a bnode\"; \n" +
" ex:c ex:glasses65 ; \n" +
" ex:c [ " +
" ex:a \"this is a nested bnode\" ] " +
"] . \n" +
" ex:glasses65 ex:a \"glasses 65\" ." ;
String expected =
prefixesN3 +
nosePropIsDependentRel +
" ex:bob ex:a \"Bob\". \n" +
" ex:glasses65 ex:a \"glasses 65\" ." ;
Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
StmtIterator stmtIt = model.listStatements(
model.createResource("http://example.com/bob"),
model.createProperty("http://example.com/hasNose"),
(RDFNode)null);
List<Statement> deletes =
DependentResourceDeleteJena.getDependentResourceDeleteList(stmtIt.nextStatement(),model);
model.remove(deletes);
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
boolean same = expectedModel.isIsomorphicWith( model );
if( ! same ) printModels( expectedModel, model);
Assert.assertTrue( same );
}
@org.junit.Test
public void testResNormalDelete() {
String n3 =
prefixesN3 +
nosePropIsDependentRel +
" ex:bob ex:hasNose ex:nose1 . " ;
String expected =
prefixesN3 +
nosePropIsDependentRel ;
Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
List<Statement> deletes = DependentResourceDeleteJena.getDependentResourceDeleteList(
model.createResource("http://example.com/nose1"),model);
Model resultModel = model.remove(deletes);
//all statements should be deleted
boolean same = resultModel.isIsomorphicWith( expectedModel );
if( ! same ) printModels( expectedModel, model);
Assert.assertTrue( same);
}
@org.junit.Test
public void testResSimpleForceDelete() {
String n3 =
prefixesN3 +
nosePropIsDependentRel +
" ex:bob ex:hasNose ex:nose1 . \n" +
" ex:nose1 ex:hasHair ex:hair23. \n" +
" ex:hair23 ex:hasHairCount \"23\". " ;
String expected =
prefixesN3 +
nosePropIsDependentRel +
" ex:hair23 ex:hasHairCount \"23\". " ;
Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
List<Statement> deletes = DependentResourceDeleteJena.getDependentResourceDeleteList(
model.createResource("http://example.com/nose1"),model);
Model resultModel = model.remove(deletes);
//all statements should be deleted
boolean same = resultModel.isIsomorphicWith( expectedModel );
if( ! same ) printModels( expectedModel, model);
Assert.assertTrue( same);
}
@org.junit.Test
public void testResNonForceDelete() {
String n3 =
prefixesN3 +
" ex:bob ex:hasNose ex:nose1 . \n" +
" ex:nose1 ex:hasHair ex:hair23. \n" +
" ex:hair23 ex:hasHairCount \"23\". " ;
String expected =
prefixesN3 +
" ex:hair23 ex:hasHairCount \"23\". " ;
Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
List<Statement> deletes = DependentResourceDeleteJena.getDependentResourceDeleteList(
model.createResource("http://example.com/nose1"),model);
Model resultModel = model.remove(deletes);
//all statements should be deleted
boolean same = resultModel.isIsomorphicWith( expectedModel );
if( ! same ) printModels( expectedModel, model);
Assert.assertTrue( same);
}
@org.junit.Test
public void testResNonForceDelete2() {
String n3 =
prefixesN3 +
nosePropIsDependentRel +
" ex:bob ex:hasNose ex:nose1 . \n" +
" ex:nose1 ex:hasHair ex:hair23. \n" +
" ex:hair23 ex:hasHairCount \"23\". " ;
String expected =
prefixesN3 +
nosePropIsDependentRel +
" ex:hair23 ex:hasHairCount \"23\". " ;
Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
List<Statement> deletes = DependentResourceDeleteJena.getDependentResourceDeleteList(
model.createResource("http://example.com/nose1"),model);
Model resultModel = model.remove(deletes);
//all statements should be deleted
boolean same = resultModel.isIsomorphicWith( expectedModel );
if( ! same ) printModels( expectedModel, model);
Assert.assertTrue( same);
}
@org.junit.Test
public void testResForceDeleteWithLiterals() {
String n3 =
prefixesN3 +
nosePropIsDependentRel +
" ex:hasHair " + isDependentRelation +
" ex:bob ex:a \"Bob\". \n" +
" ex:bob ex:hasNose ex:nose1 . \n" +
" ex:nose1 ex:a \"this is a literal\". \n" +
" ex:nose1 ex:b \"2343\" . \n" +
" ex:nose1 ex:hasHair ex:hair23. \n" +
" ex:hair23 ex:hasHairCount \"23\". " ;
String expected =
prefixesN3 +
nosePropIsDependentRel +
" ex:hasHair " + isDependentRelation +
" ex:bob ex:a \"Bob\". \n" ;
Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
List<Statement> deletes = DependentResourceDeleteJena.getDependentResourceDeleteList(
model.createResource("http://example.com/nose1"),model);
model.remove(deletes);
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
boolean same = expectedModel.isIsomorphicWith( model );
if( ! same ) printModels( expectedModel, model);
Assert.assertTrue( same );
}
@org.junit.Test
public void testResForceDeleteWithCycles() {
String n3 =
prefixesN3 +
nosePropIsDependentRel +
"ex:hasHair " + isDependentRelation +
" ex:bob ex:a \"Bob\". \n" +
" ex:bob ex:hasNose ex:nose1 . \n" +
" ex:nose1 ex:a \"this is a literal\". \n" +
" ex:nose1 ex:b \"2343\" . \n" +
" ex:nose1 ex:c ex:bob . \n" +
" ex:nose1 ex:hasHair ex:hair23. \n" +
" ex:hair23 ex:c ex:bob . \n" +
" ex:hair23 ex:hasHairCount \"23\". " ;
String expected =
prefixesN3 +
nosePropIsDependentRel +
"ex:hasHair " + isDependentRelation +
" ex:bob ex:a \"Bob\". \n" ;
Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
List<Statement> deletes = DependentResourceDeleteJena.getDependentResourceDeleteList(
model.createResource("http://example.com/nose1"),model);
model.remove(deletes);
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
boolean same = expectedModel.isIsomorphicWith( model );
if( ! same ) printModels( expectedModel, model);
Assert.assertTrue( same );
}
@org.junit.Test
public void testResForceDeleteWithCycles2() {
String n3 =
prefixesN3 +
nosePropIsDependentRel +
" ex:bob ex:a \"Bob\". \n" +
" ex:bob ex:hasNose ex:nose1 . \n" +
" ex:nose1 ex:a \"this is a literal\". \n" +
" ex:nose1 ex:b \"2343\" . \n" +
" ex:nose1 ex:c ex:nose1 . \n" +
" ex:nose1 ex:c ex:bob . \n" ;
String expected =
prefixesN3 +
nosePropIsDependentRel ;
Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
List<Statement> deletes = DependentResourceDeleteJena.getDependentResourceDeleteList(
model.createResource("http://example.com/bob"),model);
model.remove(deletes);
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
boolean same = expectedModel.isIsomorphicWith( model );
if( ! same ) printModels( expectedModel, model);
Assert.assertTrue( same );
}
@org.junit.Test
public void testResForceDeleteWithLinks() {
String n3 =
prefixesN3 +
nosePropIsDependentRel +
" ex:bob ex:a \"Bob\". \n" +
" ex:bob ex:hasNose ex:nose1 . \n" +
" ex:nose1 ex:c ex:glasses65 . \n" +
" ex:glasses65 ex:c ex:nose1 . \n" +
" ex:glasses65 ex:a \"glasses 65\" ." ;
String expected =
prefixesN3 +
nosePropIsDependentRel +
" ex:bob ex:a \"Bob\". \n" +
" ex:glasses65 ex:a \"glasses 65\" ." ;
Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
List<Statement> deletes = DependentResourceDeleteJena.getDependentResourceDeleteList(
model.createResource("http://example.com/nose1"),model);
model.remove(deletes);
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
boolean same = expectedModel.isIsomorphicWith( model );
if( ! same ) printModels( expectedModel, model);
Assert.assertTrue( same );
}
// @org.junit.Test
// public void testResForceDeleteWithBNodes() {
// String n3 =
// prefixesN3 +
// nosePropIsDependentRel +
// " ex:bob ex:a \"Bob\". \n" +
// " ex:bob ex:hasNose [ \n" +
// " ex:a \"this is a bnode\"; \n" +
// " ex:c ex:glasses65 ] . \n" +
// " ex:glasses65 ex:a \"glasses 65\" ." ;
//
// String expected =
// prefixesN3 +
// nosePropIsDependentRel +
// " ex:bob ex:a \"Bob\". \n" +
// " ex:glasses65 ex:a \"glasses 65\" ." ;
// Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
//
// StmtIterator stmtIt = model.listStatements(
// model.createResource("http://example.com/bob"),
// model.createProperty("http://example.com/hasNose"),
// (RDFNode)null);
//
// RDFNode bnode = stmtIt.nextStatement().getObject();
//
// List<Statement> deletes =
// DependentResourceDeleteJena.getDependentResourceDeleteList(bnode,model);
// model.remove(deletes);
//
// Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
// boolean same = expectedModel.isIsomorphicWith( model );
// if( ! same ) printModels( expectedModel, model);
// Assert.assertTrue( same );
// }
// @org.junit.Test
// public void testResForceDeleteWithNestedBNodes() {
// String n3 =
// prefixesN3 +
// nosePropIsDependentRel +
// " ex:bob ex:a \"Bob\". \n" +
// " ex:bob ex:hasNose [ \n" +
// " ex:a \"this is a bnode\"; \n" +
// " ex:c ex:glasses65 ; \n" +
// " ex:c [ " +
// " ex:a \"this is a nested bnode\" ] " +
// "] . \n" +
// " ex:glasses65 ex:a \"glasses 65\" ." ;
//
// String expected =
// prefixesN3 +
// nosePropIsDependentRel +
// " ex:bob ex:a \"Bob\". \n" +
// " ex:glasses65 ex:a \"glasses 65\" ." ;
//
// Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
//
// StmtIterator stmtIt = model.listStatements(
// model.createResource("http://example.com/bob"),
// model.createProperty("http://example.com/hasNose"),
// (RDFNode)null);
// RDFNode bnode = stmtIt.nextStatement().getObject();
//
// List<Statement> deletes =
// DependentResourceDeleteJena.getDependentResourceDeleteList(bnode,model);
// model.remove(deletes);
//
// Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
// boolean same = expectedModel.isIsomorphicWith( model );
// if( ! same ) printModels( expectedModel, model);
// Assert.assertTrue( same );
// }
@org.junit.Test
public void testDeleteForChange() {
String source =
prefixesN3 +
nosePropIsDependentRel +
"ex:hasHair " + isDependentRelation +
" ex:bob ex:a \"Bob\". \n" +
" ex:bob ex:hasNose ex:nose1 . \n" +
" ex:nose1 ex:a \"this is a literal\". \n" +
" ex:nose1 ex:b \"2343\" . \n" +
" ex:nose1 ex:hasHair ex:hair23. \n" +
" ex:hair23 ex:hasHairCount \"23\". " ;
String expected =
prefixesN3 +
nosePropIsDependentRel +
"ex:hasHair " + isDependentRelation +
" ex:bob ex:a \"Bob\". \n" ;
String retractions =
"@prefix ex: <http://example.com/> . \n" +
" ex:bob ex:hasNose ex:nose1 . ";
Model sourceModel = (ModelFactory.createDefaultModel()).read(new StringReader(source), "", "N3");
Model additionsModel = (ModelFactory.createDefaultModel()); //no additions
Model retractionsModel = (ModelFactory.createDefaultModel()).read(new StringReader(retractions), "", "N3");
Model deletes =
DependentResourceDeleteJena.getDependentResourceDeleteForChange(additionsModel, retractionsModel, sourceModel);
sourceModel.remove(retractionsModel);
sourceModel.remove(deletes);
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
boolean same = expectedModel.isIsomorphicWith( sourceModel );
if( ! same ) printModels( expectedModel, sourceModel);
Assert.assertTrue( same );
}
@org.junit.Test
public void testDeleteForChangeWithReplace() {
String source =
prefixesN3 +
nosePropIsDependentRel +
" ex:bob ex:a \"Bob\". \n" +
" ex:jim ex:a \"Jim\". \n" +
" ex:bob ex:hasNose ex:nose1 . \n" +
" ex:nose1 ex:a \"this is a literal\". \n" +
" ex:nose1 ex:b \"2343\" . \n" +
" ex:nose1 ex:hasHair ex:hair23. \n" +
" ex:hair23 ex:hasHairCount \"23\". " ;
String expected =
prefixesN3 +
nosePropIsDependentRel +
" ex:jim ex:a \"Jim\". \n" +
" ex:bob ex:a \"Bob\". \n" +
" ex:jim ex:hasNose ex:nose1 . \n" +
" ex:nose1 ex:a \"this is a literal\". \n" +
" ex:nose1 ex:b \"2343\" . \n" +
" ex:nose1 ex:hasHair ex:hair23. \n" +
" ex:hair23 ex:hasHairCount \"23\". " ;
String additions =
"@prefix ex: <http://example.com/> . \n" +
" ex:jim ex:hasNose ex:nose1 . ";
String retractions =
"@prefix ex: <http://example.com/> . \n" +
" ex:bob ex:hasNose ex:nose1 . ";
Model sourceModel = (ModelFactory.createDefaultModel()).read(new StringReader(source), "", "N3");
Model additionsModel = (ModelFactory.createDefaultModel()).read(new StringReader(additions), "", "N3");
Model retractionsModel = (ModelFactory.createDefaultModel()).read(new StringReader(retractions), "", "N3");
Model depDeletes =
DependentResourceDeleteJena.getDependentResourceDeleteForChange(additionsModel, retractionsModel, sourceModel);
sourceModel.remove(depDeletes);
sourceModel.remove(retractionsModel);
sourceModel.add(additionsModel);
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
boolean same = expectedModel.isIsomorphicWith( sourceModel );
if( ! same ) printModels( expectedModel, sourceModel);
Assert.assertTrue( same );
}
@org.junit.Test
public void testDeleteWithNonZeroInDegree() {
/*
This tests deleting a position context node from the organization side.
Currently the required behavior is that the position context node not be
deleted when the object property statement is deleted from the organization side.
*/
String source =
prefixesN3 +
" ex:personHasPosition " + isDependentRelation +
" ex:bob ex:a \"Bob\". \n" +
" ex:orgP ex:a \"orgP\". \n" +
" ex:bob ex:personHasPosition ex:position1 . \n" +
" ex:orgP ex:positionInOrganization ex:position1 . \n" +
" ex:position1 ex:a \"This is Position1\". \n" +
" ex:position1 ex:b \"2343\" . ";
String expected =
prefixesN3 +
" ex:personHasPosition " + isDependentRelation +
" ex:bob ex:a \"Bob\". \n" +
" ex:orgP ex:a \"orgP\". \n" +
" ex:bob ex:personHasPosition ex:position1 . \n" +
" ex:position1 ex:a \"This is Position1\". \n" +
" ex:position1 ex:hasOrgName \"org xyz\" . \n" +
" ex:position1 ex:b \"2343\" . ";
// prefixesN3 +
// " ex:bob ex:a \"Bob\". \n" +
// " ex:orgP ex:a \"orgP\". \n" +
// " ex:bob ex:hasPosition ex:position1 . \n" +
// " ex:position1 ex:a \"This is Position1\". \n" +
// " ex:position1 ex:hasOrgName \"org xyz\" . \n" +
// " ex:position1 ex:b \"2343\" . ";
String additions =
"@prefix ex: <http://example.com/> . \n" +
"@prefix xsd: <" + XSD.getURI() + "> . \n " +
" ex:position1 ex:hasOrgName \"org xyz\" . ";
String retractions =
"@prefix ex: <http://example.com/> . \n" +
"@prefix xsd: <" + XSD.getURI() + "> . \n " +
" ex:orgP ex:positionInOrganization ex:position1 . ";
Model sourceModel = (ModelFactory.createDefaultModel()).read(new StringReader(source), "", "N3");
Model additionsModel = (ModelFactory.createDefaultModel()).read(new StringReader(additions), "", "N3");
Model retractionsModel = (ModelFactory.createDefaultModel()).read(new StringReader(retractions), "", "N3");
Model depDeletes =
DependentResourceDeleteJena.getDependentResourceDeleteForChange(additionsModel, retractionsModel, sourceModel);
sourceModel.remove(depDeletes);
sourceModel.remove(retractionsModel);
sourceModel.add(additionsModel);
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
boolean same = expectedModel.isIsomorphicWith( sourceModel );
if( ! same ) printModels( expectedModel, sourceModel);
Assert.assertTrue( same );
}
@org.junit.Test
public void testDeleteWithNonZeroInDegree2() {
/*
This tests deleting a position context node from the organization side.
Currently the required behavior is that the position context node not be
deleted when the object property statement is deleted from the organization side.
*/
String source =
prefixesN3 +
" ex:personHasPosition " + isDependentRelation +
" ex:bob ex:a \"Bob\". \n" +
" ex:orgP ex:a \"orgP\". \n" +
" ex:bob ex:personHasPosition ex:position1 . \n" +
" ex:orgP ex:positionInOrganization ex:position1 . \n" +
" ex:position1 ex:a \"This is Position1\". \n" +
" ex:position1 ex:b \"2343\" . ";
String expected =
prefixesN3 +
" ex:personHasPosition " + isDependentRelation +
" ex:bob ex:a \"Bob\". \n" +
" ex:orgP ex:a \"orgP\". \n" +
" ex:bob ex:personHasPosition ex:position1 . \n" +
" ex:position1 ex:a \"This is Position1\". \n" +
" ex:position1 ex:b \"2343\" . ";
String retractions =
"@prefix ex: <http://example.com/> . \n" +
"@prefix xsd: <" + XSD.getURI() + "> . \n " +
" ex:orgP ex:positionInOrganization ex:position1 . ";
Model sourceModel = (ModelFactory.createDefaultModel()).read(new StringReader(source), "", "N3");
Model additionsModel = ModelFactory.createDefaultModel(); //no additions
Model retractionsModel = (ModelFactory.createDefaultModel()).read(new StringReader(retractions), "", "N3");
Model depDeletes =
DependentResourceDeleteJena.getDependentResourceDeleteForChange(additionsModel, retractionsModel, sourceModel);
sourceModel.remove(depDeletes);
sourceModel.remove(retractionsModel);
sourceModel.add(additionsModel);
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
boolean same = expectedModel.isIsomorphicWith( sourceModel );
if( ! same ) printModels( expectedModel, sourceModel);
Assert.assertTrue( same );
}
}

View file

@ -0,0 +1,488 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.dao.jena;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.StringReader;
import org.junit.Assert;
import org.junit.Test;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.ontology.OntProperty;
import com.hp.hpl.jena.ontology.Restriction;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;
import com.hp.hpl.jena.vocabulary.XSD;
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.IndividualImpl;
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;
import edu.cornell.mannlib.vitro.webapp.dao.InsertException;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
public class JenaBaseDaoTest {
String isDependentRelation =
" <"+VitroVocabulary.PROPERTY_STUBOBJECTPROPERTYANNOT+"> \"true\"^^xsd:boolean .\n" ;
String nosePropIsDependentRel =
"<"+VitroVocabulary.PROPERTY_STUBOBJECTPROPERTYANNOT+"> rdf:type owl:AnnotationProperty .\n" +
" ex:hasNose " + isDependentRelation;
String prefixesN3 =
"@prefix vitro: <" + VitroVocabulary.vitroURI + "> . \n" +
"@prefix xsd: <" + XSD.getURI() + "> . \n " +
"@prefix rdf: <" + RDF.getURI() + "> . \n"+
"@prefix rdfs: <" + RDFS.getURI() + "> . \n"+
"@prefix owl: <" + OWL.getURI() + "> . \n" +
"@prefix ex: <http://example.com/> . \n" ;
@Test
public void smartRemoveTestForIndivdiualDelete(){
String n3 = prefixesN3 +
"ex:prop1 rdf:type owl:ObjectProperty ." +
"ex:prop1 rdfs:label \"Prop 1 Dependent Relation\" ." +
"ex:prop1 " + isDependentRelation;
Model readInModel = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
OntModel ontModel = ModelFactory.createOntologyModel();
ontModel.add(readInModel);
WebappDaoFactoryJena wdfj = new WebappDaoFactoryJena( ontModel);
try {
ObjectProperty prop1 = wdfj.getObjectPropertyDao().getObjectPropertyByURI("http://example.com/prop1");
Assert.assertNotNull(prop1);
Individual ind = new IndividualImpl();
ind.setURI("http://example.com/bob");
ind.setName("Smith, Bob");
wdfj.getIndividualDao().insertNewIndividual(ind);
Individual indxyz = new IndividualImpl();
indxyz.setURI("http://example.com/depResXYZ");
indxyz.setName("depResXYZ");
wdfj.getIndividualDao().insertNewIndividual(indxyz);
Individual indAbc = new IndividualImpl();
indAbc.setURI("http://example.com/depResNested");
indAbc.setName("depResNested");
wdfj.getIndividualDao().insertNewIndividual(indAbc);
ObjectPropertyStatement ops = new ObjectPropertyStatementImpl();
ops.setSubjectURI("http://example.com/bob");
ops.setPropertyURI("http://example.com/prop1");
ops.setObjectURI("http://example.com/depResXYZ");
wdfj.getObjectPropertyStatementDao().insertNewObjectPropertyStatement(ops);
ops = new ObjectPropertyStatementImpl();
ops.setSubjectURI("http://example.com/depResXYZ");
ops.setPropertyURI("http://example.com/prop1");
ops.setObjectURI("http://example.com/depResNested");
wdfj.getObjectPropertyStatementDao().insertNewObjectPropertyStatement(ops);
wdfj.getIndividualDao().deleteIndividual("http://example.com/depResXYZ");
String expected =
"@prefix xsd: <http://www.w3.org/2001/XMLSchema#> . "+
"@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> ."+
"@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> ."+
"@prefix owl: <http://www.w3.org/2002/07/owl#> . "+
"<http://example.com/bob> a owl:Thing ; " +
" rdfs:label \"Smith, Bob\"@en-US . "+
"<http://example.com/prop1> " +
" a owl:ObjectProperty ; " +
" rdfs:label \"Prop 1 Dependent Relation\" ; " +
isDependentRelation ;
Model expectedModel = (ModelFactory.createOntologyModel()).read(new StringReader(expected), "", "N3");
assertEquivalentModels(expectedModel, ontModel);
} catch (InsertException e) {
Assert.fail(e.getMessage());
}
}
@Test
public void smartRemoveTestForObjPropStmtDelete(){
String n3 = prefixesN3 +
"ex:prop1 rdf:type owl:ObjectProperty ." +
"ex:prop1 rdfs:label \"Prop 1 Dependent Relation\" ." +
"ex:prop1 " + isDependentRelation;
Model readInModel = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
OntModel model = ModelFactory.createOntologyModel();
model.add(readInModel);
WebappDaoFactoryJena wdfj = new WebappDaoFactoryJena( model);
Individual ind = new IndividualImpl();
ind.setURI("http://example.com/bob");
ind.setName("Smith, Bob");
try {
wdfj.getIndividualDao().insertNewIndividual(ind);
} catch (InsertException e) {
Assert.fail("Could not create new Individual Smith, Bob");
}
Individual indxyz = new IndividualImpl();
indxyz.setURI("http://example.com/depResXYZ");
indxyz.setName("depResXYZ");
try {
wdfj.getIndividualDao().insertNewIndividual(indxyz);
} catch (InsertException e) {
Assert.fail("Could not create new Individual depResXYZ");
}
Individual indAbc = new IndividualImpl();
indAbc.setURI("http://example.com/depResNested");
indAbc.setName("depResNested");
try {
wdfj.getIndividualDao().insertNewIndividual(indAbc);
} catch (InsertException e) {
Assert.fail("Could not create new Individual depResNested");
}
ObjectPropertyStatement ops = new ObjectPropertyStatementImpl();
ops.setSubjectURI("http://example.com/bob");
ops.setPropertyURI("http://example.com/prop1");
ops.setObjectURI("http://example.com/depResXYZ");
wdfj.getObjectPropertyStatementDao().insertNewObjectPropertyStatement(ops);
ops = new ObjectPropertyStatementImpl();
ops.setSubjectURI("http://example.com/depResXYZ");
ops.setPropertyURI("http://example.com/prop1");
ops.setObjectURI("http://example.com/depResNested");
wdfj.getObjectPropertyStatementDao().insertNewObjectPropertyStatement(ops);
ops = new ObjectPropertyStatementImpl();
ops.setSubjectURI("http://example.com/bob");
ops.setPropertyURI("http://example.com/prop1");
ops.setObjectURI("http://example.com/depResXYZ");
wdfj.getObjectPropertyStatementDao().deleteObjectPropertyStatement(ops);
String expected =
"@prefix xsd: <http://www.w3.org/2001/XMLSchema#> . "+
"@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> ."+
"@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> ."+
"@prefix owl: <http://www.w3.org/2002/07/owl#> . "+
"<http://example.com/bob> a owl:Thing ; " +
" rdfs:label \"Smith, Bob\"@en-US . "+
"<http://example.com/prop1> " +
" a owl:ObjectProperty ; " +
" rdfs:label \"Prop 1 Dependent Relation\" ; " +
isDependentRelation ;
Model expectedModel = (ModelFactory.createOntologyModel()).read(new StringReader(expected), "", "N3");
assertEquivalentModels(expectedModel, model);
}
@Test
public void smartRemoveTestForObjPropDelete(){
String n3 = prefixesN3 +
"ex:prop1 rdf:type owl:ObjectProperty ." +
"ex:prop1 rdfs:label \"Prop 1 Dependent Relation\" ." +
"ex:prop1 " + isDependentRelation;
Model readInModel = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
OntModel ontModel = ModelFactory.createOntologyModel();
ontModel.add(readInModel);
WebappDaoFactoryJena wdfj = new WebappDaoFactoryJena( ontModel);
try {
ObjectProperty prop1 = wdfj.getObjectPropertyDao().getObjectPropertyByURI("http://example.com/prop1");
Assert.assertNotNull(prop1);
Individual ind = new IndividualImpl();
ind.setURI("http://example.com/bob");
ind.setName("Smith, Bob");
wdfj.getIndividualDao().insertNewIndividual(ind);
Individual indxyz = new IndividualImpl();
indxyz.setURI("http://example.com/depResXYZ");
indxyz.setName("depResXYZ");
wdfj.getIndividualDao().insertNewIndividual(indxyz);
Individual indAbc = new IndividualImpl();
indAbc.setURI("http://example.com/depResNested");
indAbc.setName("depResNested");
wdfj.getIndividualDao().insertNewIndividual(indAbc);
ObjectPropertyStatement ops = new ObjectPropertyStatementImpl();
ops.setSubjectURI("http://example.com/bob");
ops.setPropertyURI("http://example.com/prop1");
ops.setObjectURI("http://example.com/depResXYZ");
wdfj.getObjectPropertyStatementDao().insertNewObjectPropertyStatement(ops);
ops = new ObjectPropertyStatementImpl();
ops.setSubjectURI("http://example.com/depResXYZ");
ops.setPropertyURI("http://example.com/prop1");
ops.setObjectURI("http://example.com/depResNested");
wdfj.getObjectPropertyStatementDao().insertNewObjectPropertyStatement(ops);
wdfj.getObjectPropertyDao().deleteObjectProperty(prop1);
String expected =
"@prefix xsd: <http://www.w3.org/2001/XMLSchema#> . "+
"@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> ."+
"@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> ."+
"@prefix owl: <http://www.w3.org/2002/07/owl#> . "+
"<http://example.com/bob> a owl:Thing ; " +
" rdfs:label \"Smith, Bob\"@en-US . " ;
Model expectedModel = (ModelFactory.createOntologyModel()).read(new StringReader(expected), "", "N3");
assertEquivalentModels(expectedModel, ontModel);
} catch (InsertException e) {
Assert.fail(e.getMessage());
}
}
// @Test
// public void smartRemoveTestForObjPropDelete(){
//
// OntModel model = ModelFactory.createOntologyModel();
// WebappDaoFactoryJena wdfj = new WebappDaoFactoryJena( model );
//
// /* Need to have the DEPENDENT_RESOURCE class in the model */
// VClass cls = new VClass();
// //cls.setURI(VitroVocabulary.DEPENDENT_RESOURCE);
// try {
// wdfj.getVClassDao().insertNewVClass(cls);
// } catch (InsertException e1) {
// Assert.fail("could not create class for dependentResourc");
// }
//
// /* Need to have an Object Property */
// ObjectProperty op = new ObjectProperty();
// op.setURI("http://example.com/prop1");
// try {
// wdfj.getObjectPropertyDao().insertObjectProperty(op);
// } catch (InsertException e1) {
// Assert.fail("Could not create object property.");
// }
//
// Individual ind = new IndividualImpl();
// ind.setURI("http://example.com/bob");
// ind.setName("Smith, Bob");
// try {
// wdfj.getIndividualDao().insertNewIndividual(ind);
// } catch (InsertException e) {
// Assert.fail("Could not create new Individual Smith, Bob");
// }
//
// Individual indxyz = new IndividualImpl();
// indxyz.setURI("http://example.com/depResXYZ");
// indxyz.setName("depResXYZ");
// //indxyz.setVClassURI(VitroVocabulary.DEPENDENT_RESOURCE);
// try {
// wdfj.getIndividualDao().insertNewIndividual(indxyz);
// } catch (InsertException e) {
// Assert.fail("Could not create new Individual depResXYZ");
// }
//// StmtIterator it = model.listStatements(model.createResource("http://example.com/depResXYZ"),
//// RDF.type, model.createResource(VitroVocabulary.DEPENDENT_RESOURCE));
//// Assert.assertTrue("depResXYZ did not get rdf:type vitro:dependentResource" ,
//// it != null && it.nextStatement() != null);
//
// Individual indAbc = new IndividualImpl();
// indAbc.setURI("http://example.com/depResNested");
// indAbc.setName("depResNested");
//// indAbc.setVClassURI(VitroVocabulary.DEPENDENT_RESOURCE);
// try {
// wdfj.getIndividualDao().insertNewIndividual(indAbc);
// } catch (InsertException e) {
// Assert.fail("Could not create new Individual depResNested");
// }
//// it = model.listStatements(model.createResource("http://example.com/depResNested"),
//// RDF.type, model.createResource(VitroVocabulary.DEPENDENT_RESOURCE));
//// Assert.assertTrue("depResNested did not get rdf:type vitro:dependentResource" ,
//// it != null && it.nextStatement() != null);
//
//
// ObjectPropertyStatement ops = new ObjectPropertyStatementImpl();
// ops.setSubjectURI("http://example.com/bob");
// ops.setPropertyURI("http://example.com/prop1");
// ops.setObjectURI("http://example.com/depResXYZ");
// wdfj.getObjectPropertyStatementDao().insertNewObjectPropertyStatement(ops);
//
// ops = new ObjectPropertyStatementImpl();
// ops.setSubjectURI("http://example.com/depResXYZ");
// ops.setPropertyURI("http://example.com/prop1");
// ops.setObjectURI("http://example.com/depResNested");
// wdfj.getObjectPropertyStatementDao().insertNewObjectPropertyStatement(ops);
//
// String expected = "<rdf:RDF\n"+
// " xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n"+
// " xmlns:j.0=\"http://vitro.mannlib.cornell.edu/ns/vitro/0.7#\"\n"+
// " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"\n"+
// " xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"\n"+
// " xmlns:owl=\"http://www.w3.org/2002/07/owl#\"\n"+
// " xmlns:j.1=\"http://example.com/\" > \n"+
// " <rdf:Description rdf:about=\"http://example.com/bob\">\n"+
// " <rdfs:label xml:lang=\"en-US\">Smith, Bob</rdfs:label>\n"+
// " <rdf:type rdf:resource=\"http://www.w3.org/2002/07/owl#Thing\"/>\n"+
// " </rdf:Description>\n"+
// " <rdf:Description rdf:about=\"http://vitro.mannlib.cornell.edu/ns/vitro/0.7#DependentResource\">\n"+
// " <j.0:displayRankAnnot rdf:datatype=\"http://www.w3.org/2001/XMLSchema#int\">-1</j.0:displayRankAnnot>\n"+
// " <j.0:displayLimitAnnot rdf:datatype=\"http://www.w3.org/2001/XMLSchema#int\">-1</j.0:displayLimitAnnot>\n"+
// " <rdf:type rdf:resource=\"http://www.w3.org/2002/07/owl#Class\"/>\n"+
// " </rdf:Description>\n"+
// "</rdf:RDF>";
//
// wdfj.getObjectPropertyDao().deleteObjectProperty(op);
//
// Model expectedModel = (ModelFactory.createOntologyModel()).read(new StringReader(expected), "", "RDF/XML");
//
// //modtime times make it difficult to compare graphs
// wipeOutModTime(expectedModel);
// wipeOutModTime(model);
// Assert.assertTrue( model.isIsomorphicWith(expectedModel));
// }
@Test
/**
* Tests that any statements with a property as predicate are removed
* when the property itself is removed
*/
public void testABoxAssertionsRemovedWhenPropertyRemoved() throws InsertException {
OntModel preModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
OntModel postModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
WebappDaoFactoryJena preWadf = new WebappDaoFactoryJena(preModel);
// make some other stuff that won't be deleted
ObjectProperty objPropNotForDeletion = new ObjectProperty();
objPropNotForDeletion.setURI("http://dont.delete.me/objProp");
preWadf.getObjectPropertyDao().insertObjectProperty(objPropNotForDeletion);
DataProperty dataPropNotForDeletion = new DataProperty();
dataPropNotForDeletion.setURI("http://dont.delete.me/dataProp");
preWadf.getDataPropertyDao().insertDataProperty(dataPropNotForDeletion);
ObjectPropertyStatement objPropStmtNotForDeletion = new ObjectPropertyStatementImpl();
objPropStmtNotForDeletion.setSubjectURI("http://individual.example.org/a/");
objPropStmtNotForDeletion.setProperty(objPropNotForDeletion);
objPropStmtNotForDeletion.setObjectURI("http://individual.example.org/b/");
preWadf.getObjectPropertyStatementDao().insertNewObjectPropertyStatement(objPropStmtNotForDeletion);
DataPropertyStatement dataPropStmtNotForDeletion = new DataPropertyStatementImpl();
dataPropStmtNotForDeletion.setIndividualURI("http://individual.example.org/a/");
dataPropStmtNotForDeletion.setDatapropURI(dataPropNotForDeletion.getURI());
dataPropStmtNotForDeletion.setData("junk");
// copy the not-for-deletion data to the postModel
postModel.add(preModel);
// Make some properties and assertions that should be deleted.
// After deletion, the "preModel" should match the "postModel," which
// only contains the not-for-deletion statements.
ObjectProperty objProp = new ObjectProperty();
objProp.setURI("http://example.org/objProp");
preWadf.getObjectPropertyDao().insertObjectProperty(objProp);
DataProperty dataProp = new DataProperty();
dataProp.setURI("http://example.org/dataProp");
preWadf.getDataPropertyDao().insertDataProperty(dataProp);
ObjectPropertyStatement objPropStmtForDeletion = new ObjectPropertyStatementImpl();
objPropStmtForDeletion.setSubjectURI("http://example.org/sdfadsf/");
objPropStmtForDeletion.setProperty(objProp);
objPropStmtForDeletion.setObjectURI("http://example.org/asdfasdfasfa/");
preWadf.getObjectPropertyStatementDao().insertNewObjectPropertyStatement(objPropStmtForDeletion);
DataPropertyStatement dataPropStmtForDeletion = new DataPropertyStatementImpl();
dataPropStmtForDeletion.setIndividualURI("http://example.org/asdf123/");
dataPropStmtForDeletion.setDatapropURI(dataProp.getURI());
dataPropStmtForDeletion.setData("I will be deleted!");
preWadf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dataPropStmtForDeletion);
// delete the object property and the data property.
// The abox assertions should go with them.
preWadf.getObjectPropertyDao().deleteObjectProperty(objProp);
preWadf.getDataPropertyDao().deleteDataProperty(dataProp);
// the preModel and the postModel should now have the same statements
//Assert.assertTrue(preModel.isIsomorphicWith(postModel));
Assert.assertTrue(preModel.size() == postModel.size());
}
@Test
/**
* Test that removing classes or properties used in restrictions
* does not leave behind broken, syntactically-invalid restrictions.
* The restrictions should be deleted.
*/
public void testPreventInvalidRestrictionsOnDeletion() {
OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
WebappDaoFactoryJena wadf = new WebappDaoFactoryJena(m);
String ns = "http://example.org/ontology/";
String class1URI = ns + "Class1";
String class2URI = ns + "Class2";
String propURI = ns + "property";
OntClass class1 = m.createClass(class1URI);
OntClass class2 = m.createClass(class2URI);
OntProperty prop = m.createObjectProperty(propURI);
Restriction rest = m.createAllValuesFromRestriction(null, prop, class2);
class1.addSuperClass(rest);
ObjectProperty op = wadf.getObjectPropertyDao().getObjectPropertyByURI(propURI);
wadf.getObjectPropertyDao().deleteObjectProperty(op);
Assert.assertEquals(class1.listSuperClasses().toSet().size(), 0);
Assert.assertEquals(m.size(), 2); // just rdf:type owl:Class for Class1 and Class2
prop = m.createObjectProperty(propURI);
rest = m.createAllValuesFromRestriction(null, prop, class2);
class1.addSuperClass(rest);
VClass vclass = wadf.getVClassDao().getVClassByURI(class2URI);
wadf.getVClassDao().deleteVClass(vclass);
Assert.assertEquals(class1.listSuperClasses().toSet().size(), 0);
Assert.assertEquals(m.size(), 2); // just rdf:type for Class1 and Prop
}
/**
* Compare the contents of the expected model with the actual model (not counting modification times).
*/
private void assertEquivalentModels(Model expected, Model actual) {
// modtime times make it difficult to compare graphs
wipeOutModTime(expected);
wipeOutModTime(actual);
if (actual.isIsomorphicWith(expected)) {
return;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream p = new PrintStream(out, true);
p.println("Models do not match: expected <");
expected.write(out);
p.println("> but was <");
actual.write(out);
p.println(">");
Assert.fail(out.toString());
}
private void wipeOutModTime(Model model){
model.removeAll(null, model.createProperty(VitroVocabulary.MODTIME), null);
}
}

View file

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

View file

@ -0,0 +1,105 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.dao.jena;
import java.io.InputStream;
import java.lang.reflect.Field;
import org.apache.log4j.Level;
import org.junit.Assert;
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.Model;
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.controller.freemarker.UrlBuilder;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.menu.MainMenu;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.menu.MenuItem;
public class MenuDaoJenaTest extends AbstractTestClass {
OntModel displayModel;
@Before
public void setUp() throws Exception {
// Suppress error logging.
setLoggerLevel(RDFDefaultErrorHandler.class, Level.OFF);
Model model = ModelFactory.createDefaultModel();
InputStream in = MenuDaoJenaTest.class.getResourceAsStream("resources/menuForTest.n3");
model.read(in,"","N3");
displayModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM,model);
}
@Test
public void getMenuItemTest(){
SimpleOntModelSelector sos = new SimpleOntModelSelector( ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM));
sos.setDisplayModel(displayModel);
MenuDaoJena menuDaoJena = new MenuDaoJena(new WebappDaoFactoryJena(sos));
MainMenu menu = menuDaoJena.getMainMenu( "notImportant" );
try{
Class clz = UrlBuilder.class;
Field f = clz.getDeclaredField( "contextPath" );
f.setAccessible(true);
f.set(null, "bogusUrlContextPath");
}catch(Exception e){
Assert.fail(e.toString());
}
Assert.assertNotNull(menu);
Assert.assertNotNull( menu.getItems() );
Assert.assertEquals(5, menu.getItems().size());
//The nulls in getUrl() are from the UrlBuilder not being setup correctly.
//it should be fine.
MenuItem item = menu.getItems().get(0);
Assert.assertNotNull(item);
Assert.assertEquals("Home",item.getLinkText());
Assert.assertEquals("bogusUrlContextPath/home",item.getUrl());
item = menu.getItems().get(1);
Assert.assertNotNull(item);
Assert.assertEquals("People",item.getLinkText());
Assert.assertEquals("bogusUrlContextPath/people",item.getUrl());
item = menu.getItems().get(2);
Assert.assertNotNull(item);
Assert.assertEquals("Publications",item.getLinkText());
Assert.assertEquals("bogusUrlContextPath/publications",item.getUrl());
item = menu.getItems().get(3);
Assert.assertNotNull(item);
Assert.assertEquals("Events",item.getLinkText());
Assert.assertEquals("bogusUrlContextPath/events",item.getUrl());
item = menu.getItems().get(4);
Assert.assertNotNull(item);
Assert.assertEquals("Organizations",item.getLinkText());
Assert.assertEquals("bogusUrlContextPath/organizations",item.getUrl());
}
@Test
public void isActiveTest(){
SimpleOntModelSelector sos = new SimpleOntModelSelector( ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM));
sos.setDisplayModel(displayModel);
MenuDaoJena menuDaoJena = new MenuDaoJena(new WebappDaoFactoryJena(sos));
//First arg is the page the user is on. Second arg is the urlmapping of the menu item.
Assert.assertTrue( menuDaoJena.isActive("/", "/") );
Assert.assertTrue( menuDaoJena.isActive("/people", "/people") );
Assert.assertFalse( menuDaoJena.isActive("/people", "/") );
Assert.assertFalse( menuDaoJena.isActive("/", "/people") );
}
}

View file

@ -0,0 +1,230 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.dao.jena;
import org.apache.log4j.Level;
import org.junit.Assert;
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.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.impl.RDFDefaultErrorHandler;
import com.hp.hpl.jena.vocabulary.RDFS;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.dao.InsertException;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
public class ObjectPropertyDaoJenaTest extends AbstractTestClass {
@Test
public void testCollateBySubclass(){
/* Check that we can save collateBySubclass */
OntModel model = ModelFactory.createOntologyModel();
WebappDaoFactory wdf = new WebappDaoFactoryJena(model);
ObjectProperty op1 = new ObjectProperty();
String propURI = "http://example.com/testObjectProp" ;
op1.setURI(propURI);
Assert.assertFalse(op1.getCollateBySubclass());
try {
wdf.getObjectPropertyDao().insertObjectProperty(op1);
ObjectProperty op2 = wdf.getObjectPropertyDao().getObjectPropertyByURI(propURI);
Assert.assertNotNull(op2);
Assert.assertFalse(op2.getCollateBySubclass());
op2.setCollateBySubclass(true);
wdf.getObjectPropertyDao().updateObjectProperty(op2);
ObjectProperty op3 = wdf.getObjectPropertyDao().getObjectPropertyByURI(propURI);
Assert.assertNotNull(op3);
Assert.assertTrue(op3.getCollateBySubclass());
op3.setCollateBySubclass(false);
wdf.getObjectPropertyDao().updateObjectProperty(op3);
ObjectProperty op4 = wdf.getObjectPropertyDao().getObjectPropertyByURI(propURI);
Assert.assertNotNull(op4);
Assert.assertFalse(op4.getCollateBySubclass());
} catch (InsertException e) {
Assert.fail(e.getMessage());
}
}
@Test
public void testStubObjectProperty(){
/* Check that we can save collateBySubclass */
OntModel model = ModelFactory.createOntologyModel();
WebappDaoFactory wdf = new WebappDaoFactoryJena(model);
ObjectProperty op1 = new ObjectProperty();
String propURI = "http://example.com/testObjectProp" ;
op1.setURI(propURI);
Assert.assertFalse(op1.getStubObjectRelation());
try {
wdf.getObjectPropertyDao().insertObjectProperty(op1);
ObjectProperty op2 = wdf.getObjectPropertyDao().getObjectPropertyByURI(propURI);
Assert.assertNotNull(op2);
Assert.assertFalse(op2.getStubObjectRelation());
op2.setStubObjectRelation(true);
wdf.getObjectPropertyDao().updateObjectProperty(op2);
ObjectProperty op3 = wdf.getObjectPropertyDao().getObjectPropertyByURI(propURI);
Assert.assertNotNull(op3);
Assert.assertTrue(op3.getStubObjectRelation());
op3.setStubObjectRelation(false);
wdf.getObjectPropertyDao().updateObjectProperty(op3);
ObjectProperty op4 = wdf.getObjectPropertyDao().getObjectPropertyByURI(propURI);
Assert.assertNotNull(op4);
Assert.assertFalse(op4.getStubObjectRelation());
} catch (InsertException e) {
Assert.fail(e.getMessage());
}
}
@Test
// Test that the ObjectPropertyDaoJena::updateProperty method will only update the jena model for
// those properties in ObjectProperty that have a different value from what is already in the
// jena model for that property.
//
// Specifically, updateProperty method should not remove a statement from the model and
// then add the same statement back in. The reason for this is that in vitro the "immutable" properties
// are stored in a sub-model and the user-editable properties are stored in a super-model and
// all updates are performed against the super-model, so removing and then re-adding
// the same statement may result in a change of state (if the statement was in the sub-model
// it will migrate to the super-model) because of the way jena handles additions and
// deletions with respect to super and sub models. This migration of statements may cause
// undesirable behavior in the vitro application.
public void minimalUpdates(){
// 1. create two models and attach one as a sub-model of the other
// 2. populate the sub-model with one statement for each of the properties represented in ObjectProperty
// TODO still need to populate more of the properties, and set up some inverse and parent and inverse of
// parent relationships in the test data.
// 3. save the state of both the sub-model and the super-model
// 4. populate an ObjectProperty object with the data in the (combined) model and call the updateProperty
// (having made no changes to the ObjectProperty object)
// 5. verify that both the sub-model and the super-model are unchanged
String propertyURI = "http://example.com/testObjectProp";
OntModel superModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM); // this simulates the user-editable ontology in vivo
OntModel subModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM); // this simulates the core ontology in vivo
superModel.addSubModel(subModel);
String rdfsLabel = "this is the rdfs label";
String lang = "en-US";
// populate sub-model
com.hp.hpl.jena.ontology.ObjectProperty property1 = subModel.createObjectProperty(propertyURI);
property1.setLabel(rdfsLabel,lang);
property1.convertToTransitiveProperty();
property1.convertToSymmetricProperty();
property1.convertToFunctionalProperty();
property1.convertToInverseFunctionalProperty();
property1.setPropertyValue(RDFS.domain, subModel.createResource("http://thisIsTheDomainClassURI"));
property1.setPropertyValue(RDFS.range, subModel.createResource("http://thisIsTheRangeClassURI"));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.EXAMPLE_ANNOT), subModel.createTypedLiteral("this is the example"));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.DESCRIPTION_ANNOT), subModel.createTypedLiteral("this is the description"));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.PUBLIC_DESCRIPTION_ANNOT), subModel.createTypedLiteral("this is the public description"));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.DISPLAY_LIMIT), subModel.createTypedLiteral(6));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.PROPERTY_ENTITYSORTFIELD), subModel.createTypedLiteral("this is the entity sort field"));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.PROPERTY_ENTITYSORTDIRECTION), subModel.createTypedLiteral("this is the entity sort direction"));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.DISPLAY_RANK_ANNOT), subModel.createTypedLiteral(21));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.PROPERTY_OBJECTINDIVIDUALSORTPROPERTY), subModel.createResource("http://thisIsTheObjectIndividualSortProperty"));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.HIDDEN_FROM_DISPLAY_BELOW_ROLE_LEVEL_ANNOT), subModel.createResource("http://vitro.mannlib.cornell.edu/ns/vitro/role#curator"));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.PROHIBITED_FROM_UPDATE_BELOW_ROLE_LEVEL_ANNOT), subModel.createResource("http://vitro.mannlib.cornell.edu/ns/vitro/role#selfEditor"));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT), subModel.createResource("http://vitro.mannlib.cornell.edu/ns/vitro/role#editor"));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.PROPERTY_INPROPERTYGROUPANNOT), subModel.createResource("http://thisIsTheInPropertyGroupURI"));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.PROPERTY_CUSTOMENTRYFORMANNOT), subModel.createResource("http://thisIsTheCustomFormEntryURI"));
property1.setPropertyValue(subModel.createProperty(VitroVocabulary.PROPERTY_SELECTFROMEXISTINGANNOT), subModel.createTypedLiteral(true));
// Save copies of sub-model and super-model
// uncommment the next two lines to debug failures
//System.out.println("**Before updating data property:");
//printModels(superModel, subModel);
superModel.removeSubModel(subModel);
OntModel origSubModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
origSubModel.add(subModel);
OntModel origSuperModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
origSuperModel.add(superModel);
superModel.addSubModel(subModel);
// Populate the ObjectProperty with the data in the sub-model and then update the combined model
// (from the unchanged object).
WebappDaoFactoryJena wdfj = new WebappDaoFactoryJena(superModel);
ObjectPropertyDaoJena pdj = (ObjectPropertyDaoJena) wdfj.getObjectPropertyDao();
ObjectProperty objectProperty = pdj.getObjectPropertyByURI(propertyURI); // the Property will be populated
// with the information already in
// the jena model.
// check RDFS label here
pdj.updateObjectProperty(objectProperty); // we haven't changed any values here, so
// the models should be unchanged.
// Verify that the sub-model and super-model are both unchanged
// uncommment the next two lines to debug failures
//System.out.println("\n**After updating data property:");
//printModels(superModel,subModel);
superModel.removeSubModel(subModel);
//modtime affects the diff but we don't care about that difference
wipeOutModTime(origSubModel);
wipeOutModTime(origSuperModel);
wipeOutModTime(subModel);
wipeOutModTime(superModel);
Assert.assertTrue(subModel.isIsomorphicWith(origSubModel));
Assert.assertTrue(superModel.isIsomorphicWith(origSuperModel));
}
void printModels(OntModel superModel, OntModel subModel) {
// Detach the submodel for printing to get an accurate
// account of what is in each.
superModel.removeSubModel(subModel);
System.out.println("\nThe sub-model has " + subModel.size() + " statements:");
System.out.println("---------------------------------------------------");
subModel.writeAll(System.out,"N3",null);
System.out.println("\nThe super-model has " + superModel.size() + " statements:");
System.out.println("---------------------------------------------------");
superModel.write(System.out,"N3",null);
superModel.addSubModel(subModel);
}
void wipeOutModTime(Model model){
model.removeAll(null, model.createProperty(VitroVocabulary.MODTIME), null);
}
}

View file

@ -0,0 +1,34 @@
/* $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.*;
import org.junit.Test;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
public class ObjectPropertyStatementDaoJenaTest {
/**
* Test if jena lib can parse N3 that it generates.
* owl:sameAs has been a problem when it is represetned
* in N3 with the character =
*/
@Test
public void testN3WithSameAs() {
String n3WithSameAs = " <http://example.com/bob> = <http://example.com/robert> .";
try{
Model m = ModelFactory.createDefaultModel();
m.read(n3WithSameAs, null, "N3");
fail( "If this test fails it means that jena now correctly parses = when reading N3.");
}catch(Exception ex ){
}
}
}

View file

@ -0,0 +1,291 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.dao.jena;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.IndividualImpl;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.Ontology;
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao;
import edu.cornell.mannlib.vitro.webapp.dao.InsertException;
import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.OntologyDao;
import edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
/**
* Test that the Jena DAOs write different types of data to the appropriate models.
* @author bjl23
*
*/
public class OntModelSegementationTest {
private WebappDaoFactoryJena wadf;
@org.junit.Before
public void setUpWebappDaoFactoryJena() {
wadf = new WebappDaoFactoryJena(new SimpleOntModelSelector());
}
@Test
public void testUserAccountModel() {
UserAccountsDao uadao = wadf.getUserAccountsDao();
OntModelSelector oms = wadf.getOntModelSelector();
UserAccount user = new UserAccount();
user.setFirstName("Chuck");
user.setLastName("Roast");
user.setExternalAuthId("chuckroast");
uadao.insertUserAccount(user);
Assert.assertTrue(oms.getUserAccountsModel().size() > 0);
Assert.assertTrue(oms.getFullModel().size() == 0);
Assert.assertTrue(oms.getABoxModel().size() == 0);
Assert.assertTrue(oms.getTBoxModel().size() == 0);
Assert.assertTrue(oms.getApplicationMetadataModel().size() == 0);
user.setEmailAddress("todd@somewhere");
uadao.updateUserAccount(user);
Assert.assertTrue(oms.getUserAccountsModel().size() > 0);
Assert.assertTrue(oms.getFullModel().size() == 0);
Assert.assertTrue(oms.getABoxModel().size() == 0);
Assert.assertTrue(oms.getTBoxModel().size() == 0);
Assert.assertTrue(oms.getApplicationMetadataModel().size() == 0);
uadao.deleteUserAccount(user.getUri());
Assert.assertTrue(oms.getUserAccountsModel().size() == 0);
Assert.assertTrue(oms.getFullModel().size() == 0);
Assert.assertTrue(oms.getABoxModel().size() == 0);
Assert.assertTrue(oms.getTBoxModel().size() == 0);
Assert.assertTrue(oms.getApplicationMetadataModel().size() == 0);
}
/*
@Test
public void testApplicationMetadataModel() throws InsertException {
PortalDao pdao = wadf.getPortalDao();
TabDao tdao = wadf.getTabDao();
VClassGroupDao vcgdao = wadf.getVClassGroupDao();
PropertyGroupDao pgdao = wadf.getPropertyGroupDao();
OntModelSelector oms = wadf.getOntModelSelector();
this.assertAllModelsExceptAppMetadataAreEmpty(oms);
//insert a portal
Portal portal = new Portal();
portal.setPortalId(1);
portal.setAppName("test portal");
pdao.insertPortal(portal);
this.assertMetadataModelNonemptyAndAllOtherModelsAreEmpty(oms);
//insert a tab
Tab tab = new Tab();
tab.setTitle("test tab");
int tabId = tdao.insertTab(tab);
tab.setTabId(tabId);
this.assertMetadataModelNonemptyAndAllOtherModelsAreEmpty(oms);
//insert a classgroup
VClassGroup group = new VClassGroup();
group.setURI("http://example.org/classgroup");
group.setPublicName("test group");
vcgdao.insertNewVClassGroup(group);
this.assertMetadataModelNonemptyAndAllOtherModelsAreEmpty(oms);
//insert a property group
PropertyGroup pgroup = new PropertyGroup();
pgroup.setURI("http://example.org/propertygroup");
pgroup.setName("test property group");
pgdao.insertNewPropertyGroup(pgroup);
this.assertMetadataModelNonemptyAndAllOtherModelsAreEmpty(oms);
portal.setAppName("updated portal");
tab.setTitle("updated tab");
group.setPublicName("updated group");
pgroup.setName("updated property group");
pdao.updatePortal(portal);
this.assertMetadataModelNonemptyAndAllOtherModelsAreEmpty(oms);
tdao.updateTab(tab);
this.assertMetadataModelNonemptyAndAllOtherModelsAreEmpty(oms);
vcgdao.updateVClassGroup(group);
this.assertMetadataModelNonemptyAndAllOtherModelsAreEmpty(oms);
pgdao.updatePropertyGroup(pgroup);
this.assertMetadataModelNonemptyAndAllOtherModelsAreEmpty(oms);
tdao.deleteTab(tab);
vcgdao.deleteVClassGroup(group);
pgdao.deletePropertyGroup(pgroup);
this.assertAllModelsExceptAppMetadataAreEmpty(oms);
}
*/
@Test
public void testTBoxModel() throws InsertException {
OntModelSelector oms = wadf.getOntModelSelector();
VClassDao vcDao = wadf.getVClassDao();
ObjectPropertyDao opDao = wadf.getObjectPropertyDao();
DataPropertyDao dpDao = wadf.getDataPropertyDao();
OntologyDao oDao = wadf.getOntologyDao();
VClass vclass = new VClass();
vclass.setURI("http://example.org/vclass");
vcDao.insertNewVClass(vclass);
this.assertTBoxModelNonemptyAndAllOtherModelsAreEmpty(oms);
ObjectProperty op = new ObjectProperty();
op.setURI("http://example.org/objectProperty");
opDao.insertObjectProperty(op);
this.assertTBoxModelNonemptyAndAllOtherModelsAreEmpty(oms);
DataProperty dp = new DataProperty();
dp.setURI("http://example.org/dataProperty");
dpDao.insertDataProperty(dp);
this.assertTBoxModelNonemptyAndAllOtherModelsAreEmpty(oms);
Ontology o = new Ontology();
o.setURI("http://example.org/");
oDao.insertNewOntology(o);
this.assertTBoxModelNonemptyAndAllOtherModelsAreEmpty(oms);
vclass.setName("vclass");
op.setDomainPublic("objectProperty");
dp.setPublicName("dataProperty");
o.setName("ontology");
vcDao.updateVClass(vclass);
this.assertTBoxModelNonemptyAndAllOtherModelsAreEmpty(oms);
opDao.updateObjectProperty(op);
this.assertTBoxModelNonemptyAndAllOtherModelsAreEmpty(oms);
dpDao.updateDataProperty(dp);
this.assertTBoxModelNonemptyAndAllOtherModelsAreEmpty(oms);
oDao.updateOntology(o);
this.assertTBoxModelNonemptyAndAllOtherModelsAreEmpty(oms);
vcDao.deleteVClass(vclass);
opDao.deleteObjectProperty(op);
dpDao.deleteDataProperty(dp);
oDao.deleteOntology(o);
this.assertAllModelsExceptAppMetadataAreEmpty(oms);
}
@Test
public void testAboxModel() throws InsertException {
OntModelSelector oms = wadf.getOntModelSelector();
IndividualDao iDao = wadf.getIndividualDao();
Individual ind = new IndividualImpl("http://example.org/individual");
iDao.insertNewIndividual(ind);
this.assertABoxModelNonemptyAndAllOtherModelsAreEmpty(oms);
ind.setName("ind");
iDao.updateIndividual(ind);
this.assertABoxModelNonemptyAndAllOtherModelsAreEmpty(oms);
iDao.deleteIndividual(ind);
this.assertAllModelsExceptAppMetadataAreEmpty(oms);
}
private void assertAllModelsExceptAppMetadataAreEmpty(OntModelSelector oms) {
//Assert.assertTrue(oms.getApplicationMetadataModel().size() == 0);
Assert.assertTrue(oms.getFullModel().size() == 0);
Assert.assertTrue(oms.getABoxModel().size() == 0);
Assert.assertTrue(oms.getTBoxModel().size() == 0);
Assert.assertTrue(oms.getUserAccountsModel().size() == 0);
}
/*
private void assertMetadataModelNonemptyAndAllOtherModelsAreEmpty(OntModelSelector oms) {
Assert.assertTrue(oms.getApplicationMetadataModel().size() > 0);
Assert.assertTrue(oms.getFullModel().size() == oms.getApplicationMetadataModel().size());
Assert.assertTrue(oms.getABoxModel().size() == 0);
Assert.assertTrue(oms.getTBoxModel().size() == 0);
Assert.assertTrue(oms.getUserAccountsModel().size() == 0);
}
*/
private void assertTBoxModelNonemptyAndAllOtherModelsAreEmpty(OntModelSelector oms) {
Assert.assertTrue(oms.getTBoxModel().size() > 0);
Assert.assertTrue(oms.getFullModel().size() == oms.getTBoxModel().size());
Assert.assertTrue(oms.getABoxModel().size() == 0);
Assert.assertTrue(oms.getApplicationMetadataModel().size() == 0);
Assert.assertTrue(oms.getUserAccountsModel().size() == 0);
}
private void assertABoxModelNonemptyAndAllOtherModelsAreEmpty(OntModelSelector oms) {
Assert.assertTrue(oms.getABoxModel().size() > 0);
Assert.assertTrue(oms.getFullModel().size() == oms.getABoxModel().size());
Assert.assertTrue(oms.getTBoxModel().size() == 0);
Assert.assertTrue(oms.getApplicationMetadataModel().size() == 0);
Assert.assertTrue(oms.getUserAccountsModel().size() == 0);
}
@Ignore
@Test
public void testConcurrency() throws InsertException {
(new Thread(new ClassLister(wadf))).start();
(new Thread(new ClassLister(wadf))).start();
VClass v = null;
for (int i = 0; i < 50; i++) {
v = new VClass();
v.setURI("http://example.org/vclass" + i);
wadf.getVClassDao().insertNewVClass(v);
}
for (int i = 0; i < 500; i++) {
v.setName("blah " + i);
wadf.getVClassDao().updateVClass(v);
}
}
private class ClassLister implements Runnable {
private WebappDaoFactory wadf;
public ClassLister(WebappDaoFactory wadf) {
this.wadf = wadf;
}
public void run() {
//int vclassTotal = wadf.getVClassDao().getAllVclasses().size();
for (int i = 0; i < 1500; i++) {
wadf.getVClassDao().getAllVclasses().size();
// if (vclassTotal != wadf.getVClassDao().getAllVclasses().size()) {
// throw new RuntimeException("Inconsistent VClass list size");
// }
}
}
}
}

View file

@ -0,0 +1,206 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.dao.jena;
import java.io.StringReader;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
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.vocabulary.XSD;
import edu.cornell.mannlib.vitro.webapp.beans.PropertyInstance;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
public class PropertyInstanceDaoJenaTest {
String isDependentRelation =
" <"+VitroVocabulary.PROPERTY_STUBOBJECTPROPERTYANNOT+"> \"true\"^^xsd:boolean .\n" ;
String nosePropIsDependentRel =
"<"+VitroVocabulary.PROPERTY_STUBOBJECTPROPERTYANNOT+"> rdf:type owl:AnnotationProperty .\n" +
" ex:hasNose " + isDependentRelation;
String prefixesN3 =
"@prefix vitro: <" + VitroVocabulary.vitroURI + "> . \n" +
"@prefix xsd: <" + XSD.getURI() + "> . \n " +
"@prefix ex: <http://example.com/> . \n" +
"@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . \n"+
"@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . \n"+
"@prefix owl: <http://www.w3.org/2002/07/owl#> . \n";
void printModels(Model expected, Model result){
System.out.println("Expected:");
expected.write(System.out);
System.out.println("Result:");
result.write(System.out);
}
@org.junit.Test
public void testStmtNonForceDelete() {
String n3 =
prefixesN3 +
" ex:bob ex:hasNose ex:nose1 . \n" +
" ex:nose1 ex:hasHair ex:hair23. \n" +
" ex:hair23 ex:hasHairCount \"23\". " ;
String expected =
prefixesN3 +
" ex:nose1 ex:hasHair ex:hair23. \n" +
" ex:hair23 ex:hasHairCount \"23\". " ;
Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
OntModel ontModel = ModelFactory.createOntologyModel();
ontModel.add(model.listStatements());
WebappDaoFactory wdf = new WebappDaoFactoryJena(ontModel);
wdf.getPropertyInstanceDao().deleteObjectPropertyStatement("http://example.com/bob", "http://example.com/hasNose", "http://example.com/nose1");
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
wipeOutModTime(ontModel);
//Model resultModel = ModelFactory.createDefaultModel().add(ontModel.listStatements());
boolean same = expectedModel.isIsomorphicWith( ontModel.getBaseModel() );
if( ! same ) printModels( expectedModel, ontModel.getBaseModel());
Assert.assertTrue( same );
}
@org.junit.Test
public void testStmtSimpleForceDelete() {
String n3=
prefixesN3 +
nosePropIsDependentRel +
"ex:hasHair " + isDependentRelation +
" ex:bob ex:hasNose ex:nose1 . \n" +
" ex:nose1 ex:hasHair ex:hair23. \n" +
" ex:hair23 ex:hasHairCount \"23\". " ;
String expected =
prefixesN3 +
nosePropIsDependentRel +
"ex:hasHair " + isDependentRelation ;
Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
OntModel ontModel = ModelFactory.createOntologyModel();
ontModel.add(model.listStatements());
WebappDaoFactory wdf = new WebappDaoFactoryJena(ontModel);
wdf.getPropertyInstanceDao().deleteObjectPropertyStatement("http://example.com/bob", "http://example.com/hasNose", "http://example.com/nose1");
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
wipeOutModTime(ontModel);
//Model resultModel = ModelFactory.createDefaultModel().add(ontModel.listStatements());
boolean same = expectedModel.isIsomorphicWith( ontModel.getBaseModel() );
if( ! same ) printModels( expectedModel, ontModel.getBaseModel());
Assert.assertTrue( same );
}
@org.junit.Test
public void testStmtForceDeleteWithLiterals() {
String n3 =
prefixesN3 +
nosePropIsDependentRel +
"ex:hasHair " + isDependentRelation +
" ex:bob ex:a \"Bob\". \n" +
" ex:bob ex:hasNose ex:nose1 . \n" +
" ex:nose1 ex:a \"this is a literal\". \n" +
" ex:nose1 ex:b \"2343\" . \n" +
" ex:nose1 ex:hasHair ex:hair23. \n" +
" ex:hair23 ex:hasHairCount \"23\". " ;
String expected =
prefixesN3 +
nosePropIsDependentRel +
"ex:hasHair " + isDependentRelation +
" ex:bob ex:a \"Bob\". \n" ;
Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
OntModel ontModel = ModelFactory.createOntologyModel();
ontModel.add(model.listStatements());
WebappDaoFactory wdf = new WebappDaoFactoryJena(ontModel);
wdf.getPropertyInstanceDao().deleteObjectPropertyStatement("http://example.com/bob", "http://example.com/hasNose", "http://example.com/nose1");
Model expectedModel = (ModelFactory.createDefaultModel()).read(new StringReader(expected), "", "N3");
wipeOutModTime(ontModel);
//Model resultModel = ModelFactory.createDefaultModel().add(ontModel.listStatements());
boolean same = expectedModel.isIsomorphicWith( ontModel.getBaseModel() );
if( ! same ) printModels( expectedModel, ontModel.getBaseModel());
Assert.assertTrue( same );
}
void wipeOutModTime(Model model){
model.removeAll(null, model.createProperty(VitroVocabulary.MODTIME), null);
}
@org.junit.Test
public void testGetAllPossiblePropInstForIndividual() {
String n3 = prefixesN3 +
"ex:hasMold a owl:ObjectProperty . \n" +
"ex:hasSpore a owl:ObjectProperty . \n" +
"ex:hasFungus a owl:ObjectProperty . \n" +
"ex:redHerring a owl:ObjectProperty . \n" +
"ex:Person a owl:Class . \n" +
"ex:Agent a owl:Class . \n" +
"ex:Mold a owl:Class . \n" +
"ex:Spore a owl:Class . \n" +
"ex:Fungus a owl:Class . \n" +
"ex:Organism a owl:Class . \n" +
"ex:Mold rdfs:subClassOf ex:Organism . \n" +
"ex:Spore rdfs:subClassOf ex:Organism . \n" +
"ex:Fungus rdfs:subClassOf ex:Organism . \n" +
"ex:Person rdfs:subClassOf ex:Agent . \n" +
"ex:hasFungus rdfs:range ex:Fungus . \n" +
"ex:hasFungus rdfs:domain ex:Agent . \n" +
"ex:Agent rdfs:subClassOf [ a owl:Restriction ; \n" +
"owl:onProperty ex:hasMold ; \n" +
"owl:allValuesFrom ex:Organism ] . \n" +
"ex:Person rdfs:subClassOf [ a owl:Restriction ; \n" +
"owl:onProperty ex:hasMold ; \n" +
"owl:allValuesFrom ex:Mold ] . \n" +
"ex:Agent rdfs:subClassOf [ a owl:Restriction ; \n" +
"owl:onProperty ex:hasSpore ; \n" +
"owl:allValuesFrom ex:Organism ] . \n" +
"ex:Person rdfs:subClassOf [ a owl:Restriction ; \n" +
"owl:onProperty ex:hasSpore ; \n" +
"owl:someValuesFrom ex:Spore ] . \n" +
"ex:bob a ex:Person ; a ex:Agent . \n";
// The applicable properties for bob should be:
// 1. hasMold (values from Mold)
// 2. hasSpore (values from Organism)
// 3. hasFungus (values from Fungus)
OntModel ontModel = (ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM));
ontModel.read(new StringReader(n3), null, "N3");
WebappDaoFactory wadf = new WebappDaoFactoryJena(ontModel);
Assert.assertEquals(4, wadf.getObjectPropertyDao().getAllObjectProperties().size());
Assert.assertEquals(6, wadf.getVClassDao().getAllVclasses().size());
Assert.assertNotNull(wadf.getIndividualDao().getIndividualByURI("http://example.com/bob"));
Collection<PropertyInstance> pinsts = wadf.getPropertyInstanceDao()
.getAllPossiblePropInstForIndividual("http://example.com/bob");
Assert.assertEquals(3, pinsts.size());
Map<String, String> propToRange = new HashMap<String,String>();
for (PropertyInstance pi : pinsts) {
propToRange.put(pi.getPropertyURI(), pi.getRangeClassURI());
}
Assert.assertEquals("http://example.com/Mold", propToRange.get("http://example.com/hasMold"));
Assert.assertEquals("http://example.com/Organism", propToRange.get("http://example.com/hasSpore"));
Assert.assertEquals("http://example.com/Fungus", propToRange.get("http://example.com/hasFungus"));
}
}

View file

@ -0,0 +1,178 @@
/* $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.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Ignore;
import org.junit.Test;
import com.hp.hpl.jena.query.QuerySolutionMap;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
/**
* TODO
*/
public class QueryUtilsTest extends AbstractTestClass {
// ----------------------------------------------------------------------
// Test bindVariables
// ----------------------------------------------------------------------
private QuerySolutionMap bindings = new QuerySolutionMap();
@Test
public void bindResource() {
bindings.add("uri", ResourceFactory.createResource("http://my.uri"));
assertBoundQueryEquals("a resource ?uri", "a resource <http://my.uri>");
}
@Test
public void bindPlainLiteral() {
bindings.add("plain", ResourceFactory.createPlainLiteral("too easy"));
assertBoundQueryEquals("This is ?plain ?plain",
"This is \"too easy\" \"too easy\"");
}
@Test
public void bindTypedLiteral() {
bindings.add("typed", ResourceFactory.createTypedLiteral(100L));
assertBoundQueryEquals("take this ?typed number",
"take this \"100\"^^<http://www.w3.org/2001/XMLSchema#long> number");
}
@Test
public void bindLanguageLiteral() {
Literal l = ModelFactory.createDefaultModel().createLiteral("Spanish",
"es-ES");
bindings.add("lang", l);
assertBoundQueryEquals("speak my ?lang?", "speak my \"Spanish\"@es-ES?");
}
@Ignore
@Test
public void bindAnon() {
fail("bindAnon not implemented");
}
// ----------------------------------------------------------------------
private void assertBoundQueryEquals(String template, String expected) {
String actual = QueryUtils.bindVariables(template, bindings);
assertEquals("bounding results", expected, actual);
}
// ----------------------------------------------------------------------
// Test removeDuplicatesMapsFromList
// ----------------------------------------------------------------------
private List<Map<String, String>> theList = list(
map(pair("id", "1"), pair("color", "blue"), pair("size", "large")),
map(pair("id", "2"), pair("color", "red"), pair("size", "large"),
pair("parity", "odd")));
private List<Map<String, String>> filteredList;
@Test
public void noKeys() {
assertExpectedIDs(ids("1", "2"), keys());
}
@Test
public void emptyList() {
theList = new ArrayList<>();
assertExpectedIDs(ids(), keys("color"));
}
@Test
public void unrecognizedKey() {
assertExpectedIDs(ids("1", "2"), keys("bogus"));
}
@Test
public void unmatchedKey() {
assertExpectedIDs(ids("1", "2"), keys("parity"));
}
@Test
public void foundDuplicate() {
assertExpectedIDs(ids("1"), keys("size"));
}
@Test
public void noDuplicates() {
assertExpectedIDs(ids("1", "2"), keys("color"));
}
@Test
public void matchOneKeyOfMany() {
assertExpectedIDs(ids("1"), keys("color", "size"));
}
@Test
public void multipleDuplicatesOfASingleRecord() {
theList.add(map(pair("id", "3"), pair("size", "large")));
assertExpectedIDs(ids("1"), keys("color", "size"));
}
// ----------------------------------------------------------------------
private void assertExpectedIDs(String[] ids, String[] keys) {
filteredList = QueryUtils.removeDuplicatesMapsFromList(theList, keys);
assertEquals("ids", Arrays.asList(ids), idsInFilteredList());
}
private List<String> idsInFilteredList() {
List<String> ids = new ArrayList<>();
for (Map<String, String> map : filteredList) {
String id = map.get("id");
if (id == null) {
fail("ID was null");
} else {
ids.add(id);
}
}
return ids;
}
@SafeVarargs
private final List<Map<String, String>> list(Map<String, String>... maps) {
return new ArrayList<>(Arrays.asList(maps));
}
private Map<String, String> map(String[]... pairs) {
Map<String, String> map = new HashMap<>();
for (String[] pair : pairs) {
map.put(pair[0], pair[1]);
}
return map;
}
private String[] pair(String... s) {
return s;
}
private String[] keys(String... keys) {
return keys;
}
private String[] ids(String... ids) {
return ids;
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
}

View file

@ -0,0 +1,518 @@
/* $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 static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
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.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.RDFNode;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.beans.PermissionSet;
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount.Status;
/**
* TODO
*/
public class UserAccountsDaoJenaTest extends AbstractTestClass {
private static final Set<String> EMPTY = Collections.<String> emptySet();
/**
* Where the model statements are stored for this test.
*/
private static final String N3_DATA_FILENAME = "resources/UserAccountsDaoJenaTest.n3";
private static final String NS_MINE = "http://vivo.mydomain.edu/individual/";
private static final String URI_USER1 = NS_MINE + "user01";
private static final String URI_NO_SUCH_USER = NS_MINE + "bogusUser";
private static final String EMAIL_USER1 = "email@able.edu";
private static final String EMAIL_NO_SUCH_USER = NS_MINE
+ "bogus@email.com";
private static final String URI_ROLE1 = NS_MINE + "role1";
private static final String URI_ROLE2 = NS_MINE + "role2";
private static final String URI_ROLE3 = NS_MINE + "role3";
private static final String URI_PROFILE1 = NS_MINE + "profile1";
private static final String URI_PROFILE2 = NS_MINE + "profile2";
private OntModel ontModel;
private WebappDaoFactoryJena wadf;
private UserAccountsDaoJena dao;
private UserAccount user1;
private UserAccount userNew;
private UserAccount userA;
private UserAccount userB;
private UserAccount userC;
@Before
public void setup() throws IOException {
InputStream stream = UserAccountsDaoJenaTest.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();
wadf = new WebappDaoFactoryJena(ontModel);
dao = new UserAccountsDaoJena(wadf);
}
@Before
public void createUserAccountValues() {
user1 = userAccount(URI_USER1, "email@able.edu", "Zack", "Roberts",
"garbage", "", 0L, false, 5, 12345678L, Status.ACTIVE, "user1",
false, collection(URI_ROLE1), false, EMPTY);
userNew = userAccount("", "email@here", "Joe", "Blow", "XXXX", "YYYY",
0L, false, 1, 0L, Status.ACTIVE, "jblow", false, EMPTY, false,
EMPTY);
userA = userAccount("", "aahern@here", "Alf", "Ahern", "XXXX", "YYYY",
0L, false, 1, 0L, Status.ACTIVE, "aahern", false, EMPTY, false,
collection(URI_PROFILE1));
userB = userAccount("", "email@here", "Betty", "Boop", "XXXX", "YYYY",
0L, false, 1, 0L, Status.ACTIVE, "bboop", false, EMPTY, false,
collection(URI_PROFILE1, URI_PROFILE2));
userC = userAccount("", "ccallas@here", "Charlie", "Callas", "XXXX",
"YYYY", 0L, false, 1, 0L, Status.ACTIVE, "ccallas", false,
EMPTY, false, collection(URI_PROFILE2));
}
// ----------------------------------------------------------------------
// Tests for UserAccount methods.
// ----------------------------------------------------------------------
@Test
public void getUserAccountByUriSuccess() {
UserAccount u = dao.getUserAccountByUri(URI_USER1);
assertEqualAccounts(user1, u);
}
@Test
public void getUserAccountByUriNull() {
UserAccount u = dao.getUserAccountByUri(null);
assertNull("null result", u);
}
@Test
public void getUserAccountByUriNotFound() {
UserAccount u = dao.getUserAccountByUri("bogusUri");
assertNull("null result", u);
}
@Test
public void getUserAccountByUriWrongType() {
UserAccount u = dao.getUserAccountByUri(URI_ROLE1);
// System.out.println(u);
assertNull("null result", u);
}
@Test
public void getUserAccountByEmailSuccess() {
UserAccount u = dao.getUserAccountByEmail(EMAIL_USER1);
assertEquals("uri", URI_USER1, u.getUri());
}
@Test
public void getUserAccountByEmailNull() {
UserAccount u = dao.getUserAccountByEmail(null);
assertEquals("uri", null, u);
}
@Test
public void getUserAccountByEmailNotFound() {
UserAccount u = dao.getUserAccountByEmail(EMAIL_NO_SUCH_USER);
assertEquals("uri", null, u);
}
@Test
public void insertUserAccountSuccess() {
UserAccount raw = userAccount(userNew);
String uri = dao.insertUserAccount(raw);
UserAccount processed = dao.getUserAccountByUri(uri);
assertEqualAccounts(raw, processed);
}
@Test(expected = NullPointerException.class)
public void insertUserAccountNullUserAccount() {
dao.insertUserAccount(null);
}
@Test(expected = IllegalArgumentException.class)
public void insertUserAccountUriIsNotEmpty() {
UserAccount in = new UserAccount();
in.setUri(NS_MINE + "XXXXXX");
dao.insertUserAccount(in);
}
@Test
public void updateUserAccountSuccess() {
UserAccount orig = userAccount(URI_USER1, "updatedEmail@able.edu",
"Ezekiel", "Roberts", "differentHash", "oldHash", 1L, false,
43, 1020304050607080L, Status.ACTIVE, "updatedUser1", false,
collection(URI_ROLE1, URI_ROLE3), false, EMPTY);
dao.updateUserAccount(orig);
UserAccount updated = dao.getUserAccountByUri(URI_USER1);
assertEqualAccounts(orig, updated);
}
@Test(expected = NullPointerException.class)
public void updateUserAccountNullUserAccount() {
dao.updateUserAccount(null);
}
@Test(expected = IllegalArgumentException.class)
public void updateUserAccountDoesNotExist() {
UserAccount up = new UserAccount();
up.setUri(NS_MINE + "XXXXXX");
dao.updateUserAccount(up);
}
@Test
public void deleteUserAccountSuccess() {
dao.deleteUserAccount(URI_USER1);
StmtIterator stmts = ontModel.listStatements(
ontModel.getResource(URI_USER1), null, (RDFNode) null);
if (stmts.hasNext()) {
String message = "Expecting no statements to remain in the model, but found:\n";
while (stmts.hasNext()) {
message += " " + formatStatement(stmts.next()) + "\n";
}
fail(message);
}
}
@Test
public void deleteUserAccountNullUri() {
// no complaint, no action.
dao.deleteUserAccount(null);
}
@Test
public void deleteUserAccountDoesNotExist() {
// no complaint, no action.
dao.deleteUserAccount(URI_NO_SUCH_USER);
}
@Test
public void insertUserAccountWithProxies() {
userNew.setProxiedIndividualUris(collection(
NS_MINE + "userNewProxyOne", NS_MINE + "userNewProxyTwo"));
String userUri = dao.insertUserAccount(userNew);
UserAccount inserted = dao.getUserAccountByUri(userUri);
assertEqualAccounts(userNew, inserted);
}
@Test
public void updateUserAccountWithProxies() {
UserAccount beforeAccount = dao.getUserAccountByUri(URI_USER1);
user1.setProxiedIndividualUris(collection(NS_MINE + "newProxyForUser1"));
dao.updateUserAccount(user1);
UserAccount updated = dao.getUserAccountByUri(URI_USER1);
assertEqualAccounts(user1, updated);
}
// ----------------------------------------------------------------------
// Tests for proxy-related methods
// ----------------------------------------------------------------------
@Test
public void getProxyEditorsFirst() {
String profileOne = NS_MINE + "userNewProxyOne";
String profileTwo = NS_MINE + "userNewProxyTwo";
userNew.setProxiedIndividualUris(collection(profileOne, profileTwo));
String userUri = dao.insertUserAccount(userNew);
UserAccount user = dao.getUserAccountByUri(userUri);
assertExpectedAccountUris("proxy for profile one",
Collections.singleton(user),
dao.getUserAccountsWhoProxyForPage(profileOne));
}
@Test
public void getProxyEditorsSecond() {
String profileOne = NS_MINE + "userNewProxyOne";
String profileTwo = NS_MINE + "userNewProxyTwo";
userNew.setProxiedIndividualUris(collection(profileOne, profileTwo));
String userUri = dao.insertUserAccount(userNew);
UserAccount user = dao.getUserAccountByUri(userUri);
assertExpectedAccountUris("proxy for profile two",
Collections.singleton(user),
dao.getUserAccountsWhoProxyForPage(profileTwo));
}
@Test
public void getProxyEditorsBogus() {
String profileOne = NS_MINE + "userNewProxyOne";
String profileTwo = NS_MINE + "userNewProxyTwo";
String bogusProfile = NS_MINE + "bogus";
userNew.setProxiedIndividualUris(collection(profileOne, profileTwo));
dao.insertUserAccount(userNew);
assertExpectedAccountUris("proxy for bogus profile",
Collections.<UserAccount> emptySet(),
dao.getUserAccountsWhoProxyForPage(bogusProfile));
}
@Test
public void setProxyEditorsOnProfile() {
String uriA = dao.insertUserAccount(userA);
String uriB = dao.insertUserAccount(userB);
String uriC = dao.insertUserAccount(userC);
dao.setProxyAccountsOnProfile(URI_PROFILE1, collection(uriB, uriC));
assertExpectedProxies("userA", collection(),
dao.getUserAccountByUri(uriA).getProxiedIndividualUris());
assertExpectedProxies("userB", collection(URI_PROFILE1, URI_PROFILE2),
dao.getUserAccountByUri(uriB).getProxiedIndividualUris());
assertExpectedProxies("userC", collection(URI_PROFILE1, URI_PROFILE2),
dao.getUserAccountByUri(uriC).getProxiedIndividualUris());
}
// ----------------------------------------------------------------------
// Tests for PermissionSet methods
// ----------------------------------------------------------------------
@Test
public void getPermissionSetByUriSuccess() {
PermissionSet ps = dao.getPermissionSetByUri(URI_ROLE1);
assertEquals("uri", URI_ROLE1, ps.getUri());
assertEquals("label", "Role 1", ps.getLabel());
assertEquals("permissionUris",
Collections.singleton(NS_MINE + "permissionA"),
ps.getPermissionUris());
}
@Test
public void getPermissionSetByUriNull() {
PermissionSet ps = dao.getPermissionSetByUri(null);
assertNull("null result", ps);
}
@Test
public void getPermissionSetByUriNotFound() {
PermissionSet ps = dao.getPermissionSetByUri("bogusUri");
assertNull("null result", ps);
}
@Test
public void getPermissionSetByUriWrongType() {
PermissionSet ps = dao.getPermissionSetByUri(URI_USER1);
assertNull("null result", ps);
}
@Test
public void getAllPermissionSets() {
setLoggerLevel(JenaBaseDao.class, Level.DEBUG);
Set<PermissionSet> expected = new HashSet<PermissionSet>();
PermissionSet ps1 = new PermissionSet();
ps1.setUri(URI_ROLE1);
ps1.setLabel("Role 1");
ps1.setPermissionUris(Collections.singleton(NS_MINE + "permissionA"));
expected.add(ps1);
PermissionSet ps2 = new PermissionSet();
ps2.setUri(URI_ROLE2);
ps2.setLabel("Role 2");
ps2.setForNewUsers(true);
expected.add(ps2);
PermissionSet ps3 = new PermissionSet();
ps3.setUri(URI_ROLE3);
ps3.setLabel("Role 3");
ps3.setForPublic(true);
expected.add(ps3);
assertCorrectPermissionSets(expected, dao.getAllPermissionSets());
}
// ----------------------------------------------------------------------
// helper methods
// ----------------------------------------------------------------------
private Collection<String> collection(String... args) {
return Arrays.asList(args);
}
private UserAccount userAccount(String uri, String emailAddress,
String firstName, String lastName, String md5Password,
String oldPassword, long passwordLinkExpires,
boolean passwordChangeRequired, int loginCount, long lastLoginTime,
Status status, String externalAuthId, boolean externalAuthOnly,
Collection<String> permissionSetUris, boolean rootUser,
Collection<String> proxiedIndividualUris) {
UserAccount ua = new UserAccount();
ua.setUri(uri);
ua.setEmailAddress(emailAddress);
ua.setFirstName(firstName);
ua.setLastName(lastName);
ua.setMd5Password(md5Password);
ua.setOldPassword(oldPassword);
ua.setPasswordLinkExpires(passwordLinkExpires);
ua.setPasswordChangeRequired(passwordChangeRequired);
ua.setLoginCount(loginCount);
ua.setLastLoginTime(lastLoginTime);
ua.setStatus(status);
ua.setExternalAuthId(externalAuthId);
ua.setExternalAuthOnly(externalAuthOnly);
ua.setPermissionSetUris(permissionSetUris);
ua.setRootUser(rootUser);
ua.setProxiedIndividualUris(proxiedIndividualUris);
return ua;
}
private UserAccount userAccount(UserAccount in) {
UserAccount out = new UserAccount();
out.setUri(in.getUri());
out.setEmailAddress(in.getEmailAddress());
out.setFirstName(in.getFirstName());
out.setLastName(in.getLastName());
out.setMd5Password(in.getMd5Password());
out.setOldPassword(in.getOldPassword());
out.setPasswordLinkExpires(in.getPasswordLinkExpires());
out.setPasswordChangeRequired(in.isPasswordChangeRequired());
out.setLoginCount(in.getLoginCount());
out.setLastLoginTime(in.getLastLoginTime());
out.setStatus(in.getStatus());
out.setExternalAuthId(in.getExternalAuthId());
out.setExternalAuthOnly(in.isExternalAuthOnly());
out.setPermissionSetUris(in.getPermissionSetUris());
out.setRootUser(in.isRootUser());
out.setProxiedIndividualUris(in.getProxiedIndividualUris());
return out;
}
private void assertEqualAccounts(UserAccount e, UserAccount a) {
if (!e.getUri().equals("")) {
assertEquals("uri", e.getUri(), a.getUri());
}
assertEquals("email", e.getEmailAddress(), a.getEmailAddress());
assertEquals("first name", e.getFirstName(), a.getFirstName());
assertEquals("last name", e.getLastName(), a.getLastName());
assertEquals("password", e.getMd5Password(), a.getMd5Password());
assertEquals("old password", e.getOldPassword(), a.getOldPassword());
assertEquals("link expires", e.getPasswordLinkExpires(),
a.getPasswordLinkExpires());
assertEquals("password change", e.isPasswordChangeRequired(),
a.isPasswordChangeRequired());
assertEquals("login count", e.getLoginCount(), a.getLoginCount());
assertEquals("last login", e.getLastLoginTime(), a.getLastLoginTime());
assertEquals("status", e.getStatus(), a.getStatus());
assertEquals("external ID", e.getExternalAuthId(),
a.getExternalAuthId());
assertEquals("external only", e.isExternalAuthOnly(),
a.isExternalAuthOnly());
assertEquals("permission sets", e.getPermissionSetUris(),
a.getPermissionSetUris());
assertEquals("root user", e.isRootUser(), a.isRootUser());
assertEquals("proxied URIs", e.getProxiedIndividualUris(),
a.getProxiedIndividualUris());
}
private void assertCorrectPermissionSets(Set<PermissionSet> expected,
Collection<PermissionSet> actual) {
Set<Map<String, Object>> expectedMaps = new HashSet<Map<String, Object>>();
for (PermissionSet ps : expected) {
expectedMaps.add(buildMapFromPermissionSet(ps));
}
Set<Map<String, Object>> actualMaps = new HashSet<Map<String, Object>>();
for (PermissionSet ps : actual) {
actualMaps.add(buildMapFromPermissionSet(ps));
}
assertEquals("all permission sets", expectedMaps, actualMaps);
}
private Map<String, Object> buildMapFromPermissionSet(PermissionSet ps) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("uri", ps.getUri());
map.put("label", ps.getLabel());
map.put("permissions", ps.getPermissionUris());
map.put("forNewUsers", ps.isForNewUsers());
map.put("forPublic", ps.isForPublic());
return map;
}
private void assertExpectedAccountUris(String label,
Set<UserAccount> expectedUserAccounts,
Collection<UserAccount> actualUserAccounts) {
Set<String> expectedUris = new HashSet<String>();
for (UserAccount ua : expectedUserAccounts) {
expectedUris.add(ua.getUri());
}
Set<String> actualUris = new HashSet<String>();
for (UserAccount ua : actualUserAccounts) {
actualUris.add(ua.getUri());
}
assertEqualSets(label, expectedUris, actualUris);
}
private void assertExpectedProxies(String label,
Collection<String> expected, Set<String> actual) {
Set<String> expectedSet = new HashSet<String>(expected);
assertEqualSets(label, expectedSet, actual);
}
@SuppressWarnings("unused")
private void dumpModelStatements() {
StmtIterator stmts = ontModel.listStatements();
while (stmts.hasNext()) {
Statement stmt = stmts.next();
// System.out.println(formatStatement(stmt));
}
}
private String formatStatement(Statement stmt) {
return stmt.getSubject().getURI() + " ==> "
+ stmt.getPredicate().getURI() + " ==> "
+ stmt.getObject().toString();
}
}

View file

@ -0,0 +1,203 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.dao.jena;
import java.util.List;
import static org.junit.Assert.*;
import org.junit.Test;
import com.hp.hpl.jena.ontology.ObjectProperty;
import com.hp.hpl.jena.ontology.OntClass;
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.vocabulary.OWL;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
/**
*
*
*/
public class VClassDaoTest {
@Test
// Test that the VClassDaoJena::updateVClass method will only update the jena model for
// those properties in VClass that have a different value from what is already in the
// jena model for that property.
//
// Specifically, VClass should not remove a statement from the model and then add the
// same statement back in. The reason for this is that in vivo the "immutable" properties
// are stored in a sub-model and the user-editable properties are stored in a super-model and
// all updates are performed against the super-model, so removing and then re-adding
// the same statement may result in a change of state (if the statement was in the sub-model
// it will migrate to the super-model) because of the way jena handles additions and
// deletions with respect to super and sub models. This migration of statements may cause
// undesirable behavior in the vivo/vitro application.
public void modelIsolation(){
// 1. create two models and attach one as a sub-model of the other
// 2. populate the sub-model with one statement for each of the 14 properties represented in VClass
// 3. save the state of both the sub-model and the super-model
// 4. populate a VClass object with the data in the (combined) model and call the updateVClass method
// 5. verify that both the sub-model and the super-model are unchanged
String class1URI = "http://test.vivo/AcademicDegree";
OntModel superModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM); // this simulates the user-editable ontology in vivo
OntModel subModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM); // this simulates the core ontology in vivo
superModel.addSubModel(subModel);
String rdfsLabel = "this is the rdfs label";
String lang = "en-US";
// populate sub-model
OntClass class1 = subModel.createClass(class1URI);
class1.setLabel(rdfsLabel,lang); //rdfs:label
class1.setPropertyValue(subModel.createProperty(VitroVocabulary.IN_CLASSGROUP), subModel.createResource("http://thisIsTheClassGroupURI"));
class1.setPropertyValue(subModel.createProperty(VitroVocabulary.SHORTDEF), subModel.createTypedLiteral("this is the short definition"));
class1.setPropertyValue(subModel.createProperty(VitroVocabulary.EXAMPLE_ANNOT), subModel.createTypedLiteral("this is the example - why is this a string?"));
class1.setPropertyValue(subModel.createProperty(VitroVocabulary.DESCRIPTION_ANNOT), subModel.createTypedLiteral("this is the description"));
class1.setPropertyValue(subModel.createProperty(VitroVocabulary.DISPLAY_LIMIT), subModel.createTypedLiteral(-1));
class1.setPropertyValue(subModel.createProperty(VitroVocabulary.DISPLAY_RANK_ANNOT), subModel.createTypedLiteral(-11));
class1.setPropertyValue(subModel.createProperty(VitroVocabulary.SEARCH_BOOST_ANNOT), subModel.createTypedLiteral(2.4f));
class1.setPropertyValue(subModel.createProperty(VitroVocabulary.HIDDEN_FROM_DISPLAY_BELOW_ROLE_LEVEL_ANNOT), subModel.createResource("http://vitro.mannlib.cornell.edu/ns/vitro/role#curator"));
class1.setPropertyValue(subModel.createProperty(VitroVocabulary.PROHIBITED_FROM_UPDATE_BELOW_ROLE_LEVEL_ANNOT), subModel.createResource("http://vitro.mannlib.cornell.edu/ns/vitro/role#selfEditor"));
class1.setPropertyValue(subModel.createProperty(VitroVocabulary.HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT), subModel.createResource("http://vitro.mannlib.cornell.edu/ns/vitro/role#editor"));
class1.setPropertyValue(subModel.createProperty(VitroVocabulary.PROPERTY_CUSTOMENTRYFORMANNOT), subModel.createTypedLiteral("this is the custom entry form annotation"));
class1.setPropertyValue(subModel.createProperty(VitroVocabulary.PROPERTY_CUSTOMDISPLAYVIEWANNOT), subModel.createTypedLiteral("this is the custom display view annotation"));
class1.setPropertyValue(subModel.createProperty(VitroVocabulary.PROPERTY_CUSTOMSHORTVIEWANNOT), subModel.createTypedLiteral("this is the custom short view annotation"));
class1.setPropertyValue(subModel.createProperty(VitroVocabulary.PROPERTY_CUSTOMSEARCHVIEWANNOT), subModel.createTypedLiteral("this is the custom search view annotation"));
// Save copies of sub-model and super-model
// uncommment the next two lines to debug failures
//System.out.println("**Before updating VClass:");
//printModels(superModel, subModel);
superModel.removeSubModel(subModel);
OntModel origSubModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
origSubModel.add(subModel);
OntModel origSuperModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
origSuperModel.add(superModel);
superModel.addSubModel(subModel);
// Populate the VClass with the data in the sub-model and then update the combined model
WebappDaoFactoryJena wdfj = new WebappDaoFactoryJena(superModel);
VClassDaoJena vcdj = (VClassDaoJena) wdfj.getVClassDao();
VClass vClass = vcdj.getVClassByURI(class1URI); // the VClass will be populated with the
// information already in the jena model.
assertEquals(vClass.getName(), class1.getLabel(lang)); //
vcdj.updateVClass(vClass); // we haven't changed any values here, so
// the models should be unchanged.
// Verify that the sub-model and super-model are both unchanged
// uncommment the next two lines to debug failures
//System.out.println("\n**After updating VClass:");
//printModels(superModel,subModel);
superModel.removeSubModel(subModel);
//modtime affects the diff but we don't care about that difference
wipeOutModTime(origSubModel);
wipeOutModTime(origSuperModel);
wipeOutModTime(subModel);
wipeOutModTime(superModel);
assertTrue(subModel.isIsomorphicWith(origSubModel));
assertTrue(superModel.isIsomorphicWith(origSuperModel));
}
void printModels(OntModel superModel, OntModel subModel) {
// Detach the submodel for printing to get an accurate
// account of what is in each.
superModel.removeSubModel(subModel);
System.out.println("\nThe sub-model has " + subModel.size() + " statements:");
System.out.println("---------------------------------------------------");
subModel.writeAll(System.out,"N3",null);
System.out.println("\nThe super-model has " + superModel.size() + " statements:");
System.out.println("---------------------------------------------------");
superModel.write(System.out,"N3",null);
superModel.addSubModel(subModel);
}
void wipeOutModTime(Model model){
model.removeAll(null, model.createProperty(VitroVocabulary.MODTIME), null);
}
@Test
public void getVClassesForPropertyTest(){
String lang = "en-US";
String superClassURI = "http://example.com/SUPER_class";
String subClassAURI = "http://example.com/SUB_class_A";
String subClassBURI = "http://example.com/SUB_class_B";
String propURI = "http://example.com/PROP";
String propNoRangeURI = "http://example.com/PROP_NO_RANGE";
OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
//Define super class and sub classes
OntClass superClass = model.createClass( superClassURI );
superClass.addLabel("SUPER",lang);
superClass.setPropertyValue(model.createProperty(VitroVocabulary.IN_CLASSGROUP), model.createResource("http://thisIsTheClassGroupURI"));
superClass.addSuperClass( OWL.Thing );
OntClass subA = model.createClass(subClassAURI);
subA.addLabel("subA",lang);
subA.setPropertyValue(model.createProperty(VitroVocabulary.IN_CLASSGROUP), model.createResource("http://thisIsTheClassGroupURI"));
superClass.addSubClass(subA);
OntClass subB = model.createClass(subClassBURI);
subB.addLabel("subB",lang);
subB.setPropertyValue(model.createProperty(VitroVocabulary.IN_CLASSGROUP), model.createResource("http://thisIsTheClassGroupURI"));
superClass.addSubClass(subB);
//Define property using the super class
ObjectProperty prop = model.createObjectProperty( propURI );
prop.setLabel("PROP", lang);
prop.setRange( superClass );
ObjectProperty propNoRange = model.createObjectProperty( propNoRangeURI );
propNoRange.setLabel("PROP_NO_RANGE", lang);
WebappDaoFactoryJena wdfj = new WebappDaoFactoryJena(model);
List<VClass> classesForProp = wdfj.getVClassDao().getVClassesForProperty(propURI, true);
assertNotNull( classesForProp );
assertEquals(3, classesForProp.size());
List<VClass> classesForPropNoRange = wdfj.getVClassDao().getVClassesForProperty(propNoRangeURI, true);
assertNotNull( classesForPropNoRange );
assertEquals(0, classesForPropNoRange.size());
}
}

View file

@ -0,0 +1,102 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.dao.jena;
import java.io.StringReader;
import org.junit.Assert;
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.ResourceFactory;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.vocabulary.RDFS;
public class VClassGroupCacheTest {
@Before
public void setUp() throws Exception {
}
@Test
public void testIsVClassGroupNameChange() {
//protected static boolean isVClassGroupNameChange(Statement stmt, OntModel jenaOntModel) {
String rdf =
"core:Summer \n" +
" a owl:Class ; \n" +
" rdfs:label \"Spring and toast 3\"@en-US ; \n" +
" rdfs:subClassOf owl:Thing ; \n" +
" vitro:descriptionAnnot \n" +
" \"cgaa\"^^xsd:string ; \n" +
" vitro:displayLimitAnnot \n" +
" \"-1\"^^xsd:int ; \n" +
" vitro:displayRankAnnot \n" +
" \"-1\"^^xsd:int ; \n" +
" vitro:exampleAnnot \"serefs\"^^xsd:string ; \n" +
" vitro:hiddenFromDisplayBelowRoleLevelAnnot \n" +
" <http://vitro.mannlib.cornell.edu/ns/vitro/role#public> ; \n" +
" vitro:inClassGroup <http://vivoweb.org/ontology#vitroClassGroupequipment> ; \n" +
" vitro:prohibitedFromUpdateBelowRoleLevelAnnot \n" +
" <http://vitro.mannlib.cornell.edu/ns/vitro/role#public> ; \n" +
" vitro:shortDef \"sfsfe\"^^xsd:string ; \n" +
" owl:equivalentClass core:Summer . ";
OntModel om = ModelFactory.createOntologyModel();
om.read( new StringReader( prefixes + rdf) , null , "N3");
Statement stmt = ResourceFactory.createStatement(
ResourceFactory.createResource("http://vivoweb.org/ontology/core#Summer"),
RDFS.label,
ResourceFactory.createPlainLiteral("some old label"));
boolean isNameChange = VClassGroupCache.isClassNameChange(stmt, om);
Assert.assertTrue("Expected it to be a name change but it wasn't.", isNameChange);
stmt = ResourceFactory.createStatement(
ResourceFactory.createResource("http://vivoweb.org/ontology/core#bogus"),
ResourceFactory.createProperty("http://example.com/nonLabelProperty"),
ResourceFactory.createPlainLiteral("some old label"));
boolean notNameChange = ! VClassGroupCache.isClassNameChange(stmt, om);
Assert.assertTrue("Expected it to NOT be a name change but it was.", notNameChange);
stmt = ResourceFactory.createStatement(
ResourceFactory.createResource("http://vivoweb.org/ontology/core#bogus"),
RDFS.label,
ResourceFactory.createPlainLiteral("some old label"));
notNameChange = ! VClassGroupCache.isClassNameChange(stmt, om);
Assert.assertTrue("Expected it to NOT be a name change but it was.", notNameChange);
}
static final String prefixes =
"@prefix dc: <http://purl.org/dc/elements/1.1/> . \n" +
"@prefix pvs: <http://vivoweb.org/ontology/provenance-support#> . \n" +
"@prefix geo: <http://aims.fao.org/aos/geopolitical.owl#> . \n" +
"@prefix foaf: <http://xmlns.com/foaf/0.1/> . \n" +
"@prefix scires: <http://vivoweb.org/ontology/scientific-research#> . \n" +
"@prefix scripps: <http://vivo.scripps.edu/> . \n" +
"@prefix dcterms: <http://purl.org/dc/terms/> . \n" +
"@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . \n" +
"@prefix swrl: <http://www.w3.org/2003/11/swrl#> . \n" +
"@prefix vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> . \n" +
"@prefix event: <http://purl.org/NET/c4dm/event.owl#> . \n" +
"@prefix bibo: <http://purl.org/ontology/bibo/> . \n" +
"@prefix xsd: <http://www.w3.org/2001/XMLSchema#> . \n" +
"@prefix owl: <http://www.w3.org/2002/07/owl#> . \n" +
"@prefix swrlb: <http://www.w3.org/2003/11/swrlb#> . \n" +
"@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . \n" +
"@prefix core: <http://vivoweb.org/ontology/core#> . \n" +
"@prefix skos: <http://www.w3.org/2004/02/skos/core#> . \n" +
"@prefix vivo: <http://vivo.library.cornell.edu/ns/0.1#> . \n" +
"@prefix dcelem: <http://purl.org/dc/elements/1.1/> . \n" +
"@prefix ero: <http://purl.obolibrary.org/obo/> . \n" +
" \n" ;
}

View file

@ -0,0 +1,526 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.dao.jena;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.hp.hpl.jena.ontology.AllValuesFromRestriction;
import com.hp.hpl.jena.ontology.AnnotationProperty;
import com.hp.hpl.jena.ontology.CardinalityRestriction;
import com.hp.hpl.jena.ontology.ComplementClass;
import com.hp.hpl.jena.ontology.HasValueRestriction;
import com.hp.hpl.jena.ontology.IntersectionClass;
import com.hp.hpl.jena.ontology.MaxCardinalityRestriction;
import com.hp.hpl.jena.ontology.MinCardinalityRestriction;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.ontology.OntProperty;
import com.hp.hpl.jena.ontology.OntResource;
import com.hp.hpl.jena.ontology.Restriction;
import com.hp.hpl.jena.ontology.SomeValuesFromRestriction;
import com.hp.hpl.jena.ontology.UnionClass;
import com.hp.hpl.jena.rdf.model.Literal;
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 com.hp.hpl.jena.shared.Lock;
import com.hp.hpl.jena.util.iterator.ClosableIterator;
import com.hp.hpl.jena.vocabulary.RDFS;
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean;
import edu.cornell.mannlib.vitro.webapp.beans.Ontology;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.OntologyDao;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
/**
*
*
*
*/
public class VClassJenaTest {
@Test
// NIHVIVO-1157 introduced VClassJena.java, a lazy-loading version of VClass.java.
// Per instructions from Brian L., this test tests that for one randomly selected Class,
// the getter methods in VClassJena return the same values as would have been
// returned by the pre-NIHVIVO-1157 VClass (which would have been set by the
// (now deleted) vClassWebappFromOntClass inner class in VClassDaoJena).
//
// Note: I think this might be a better test (at least easier to read, and
// maybe more stable) if the values returned by the VClassJena getter methods
// are tested against hard-coded values (which could be set now based on the
// model code)
public void correctValues(){
// 1. create a model and populate it with the data for one class
// 2. retrieve the OntClass for the target class by URI
// 3. populate a VClass instance from the OntClass instance, as it would have been
// populated pre-NIHVIVO-1157 (with the deleted vClassWebappFromOntClass, copied here)
// 4. populate a VClassJena instance as is done with the current application code
// 5. verify that the getter methods on the VClassJena and VClass instances return the same values
String class1URI = "http://test.vivo/AcademicDegree";
OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
String rdfsLabel = "this is the rdfs label";
String lang = "en-US";
// populate sub-model
OntClass class1 = ontModel.createClass(class1URI);
class1.setLabel(rdfsLabel,lang); //rdfs:label
class1.setPropertyValue(ontModel.createProperty(VitroVocabulary.IN_CLASSGROUP), ontModel.createResource("http://thisIsTheClassGroupURI"));
class1.setPropertyValue(ontModel.createProperty(VitroVocabulary.SHORTDEF), ontModel.createTypedLiteral("this is the short definition"));
class1.setPropertyValue(ontModel.createProperty(VitroVocabulary.EXAMPLE_ANNOT), ontModel.createTypedLiteral("this is the example"));
class1.setPropertyValue(ontModel.createProperty(VitroVocabulary.DESCRIPTION_ANNOT), ontModel.createTypedLiteral("this is the description"));
class1.setPropertyValue(ontModel.createProperty(VitroVocabulary.DISPLAY_LIMIT), ontModel.createTypedLiteral(-1));
class1.setPropertyValue(ontModel.createProperty(VitroVocabulary.DISPLAY_RANK_ANNOT), ontModel.createTypedLiteral(-11));
class1.setPropertyValue(ontModel.createProperty(VitroVocabulary.SEARCH_BOOST_ANNOT), ontModel.createTypedLiteral(2.4f));
class1.setPropertyValue(ontModel.createProperty(VitroVocabulary.HIDDEN_FROM_DISPLAY_BELOW_ROLE_LEVEL_ANNOT), ontModel.createResource("http://vitro.mannlib.cornell.edu/ns/vitro/role#curator"));
class1.setPropertyValue(ontModel.createProperty(VitroVocabulary.PROHIBITED_FROM_UPDATE_BELOW_ROLE_LEVEL_ANNOT), ontModel.createResource("http://vitro.mannlib.cornell.edu/ns/vitro/role#selfEditor"));
class1.setPropertyValue(ontModel.createProperty(VitroVocabulary.HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT), ontModel.createResource("http://vitro.mannlib.cornell.edu/ns/vitro/role#editor"));
class1.setPropertyValue(ontModel.createProperty(VitroVocabulary.PROPERTY_CUSTOMENTRYFORMANNOT), ontModel.createTypedLiteral("this is the custom entry form annotation"));
class1.setPropertyValue(ontModel.createProperty(VitroVocabulary.PROPERTY_CUSTOMDISPLAYVIEWANNOT), ontModel.createTypedLiteral("this is the custom display view annotation"));
class1.setPropertyValue(ontModel.createProperty(VitroVocabulary.PROPERTY_CUSTOMSHORTVIEWANNOT), ontModel.createTypedLiteral("this is the custom short view annotation"));
class1.setPropertyValue(ontModel.createProperty(VitroVocabulary.PROPERTY_CUSTOMSEARCHVIEWANNOT), ontModel.createTypedLiteral("this is the custom search view annotation"));
WebappDaoFactoryJena wadf = new WebappDaoFactoryJena(ontModel);
// Populate a VClass instance...old style
VClass vClass = vClassWebappFromOntClass(class1,wadf);
// Populate a VClassJena instance...modern style
VClassJena vClassJena = new VClassJena(class1, wadf);
// Check that the getters from the VClass and the VClassJena return the same values
Assert.assertEquals(vClassJena.getName(), vClass.getName());
Assert.assertEquals(vClassJena.getLocalNameWithPrefix(), vClass.getLocalNameWithPrefix());
Assert.assertEquals(vClassJena.getPickListName(), vClass.getPickListName());
Assert.assertEquals(vClassJena.getExample(), vClass.getExample());
Assert.assertEquals(vClassJena.getDescription(), vClass.getDescription());
Assert.assertEquals(vClassJena.getShortDef(), vClass.getShortDef());
Assert.assertEquals(vClassJena.getDisplayRank(), vClass.getDisplayRank());
Assert.assertEquals(vClassJena.getGroupURI(), vClass.getGroupURI());
Assert.assertEquals(vClassJena.getCustomEntryForm(), vClass.getCustomEntryForm());
Assert.assertEquals(vClassJena.getCustomShortView(), vClass.getCustomShortView());
Assert.assertEquals(vClassJena.getCustomSearchView(), vClass.getCustomSearchView());
Assert.assertEquals(vClassJena.getSearchBoost(), vClass.getSearchBoost());
Assert.assertEquals(vClassJena.getHiddenFromDisplayBelowRoleLevel(), vClass.getHiddenFromDisplayBelowRoleLevel());
Assert.assertEquals(vClassJena.getProhibitedFromUpdateBelowRoleLevel(), vClass.getProhibitedFromUpdateBelowRoleLevel());
Assert.assertEquals(vClassJena.getHiddenFromPublishBelowRoleLevel(), vClass.getHiddenFromPublishBelowRoleLevel());
}
// To help in debugging the unit test
void printModels(OntModel ontModel) {
System.out.println("\nThe model has " + ontModel.size() + " statements:");
System.out.println("---------------------------------------------------");
ontModel.writeAll(System.out,"N3",null);
}
// The following class and methods are pre-NIHVIVO-1157 code for
// populating a VClass. Original comments included.
private OntModel _constModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);
protected AnnotationProperty LOCAL_SHORTDEF = _constModel.createAnnotationProperty(VitroVocabulary.SHORTDEF);
protected AnnotationProperty LOCAL_DESCRIPTION_ANNOT = _constModel.createAnnotationProperty(VitroVocabulary.DESCRIPTION_ANNOT);
protected AnnotationProperty LOCAL_DISPLAY_LIMIT = _constModel.createAnnotationProperty(VitroVocabulary.DISPLAY_LIMIT);
protected AnnotationProperty LOCAL_EXAMPLE_ANNOT = _constModel.createAnnotationProperty(VitroVocabulary.EXAMPLE_ANNOT);
protected AnnotationProperty LOCAL_DISPLAY_RANK_ANNOT = _constModel.createAnnotationProperty(VitroVocabulary.DISPLAY_RANK_ANNOT);
protected AnnotationProperty LOCAL_SEARCH_BOOST_ANNOT = _constModel.createAnnotationProperty(VitroVocabulary.SEARCH_BOOST_ANNOT);
protected AnnotationProperty LOCAL_PROPERTY_CUSTOMENTRYFORMANNOT = _constModel.createAnnotationProperty(VitroVocabulary.PROPERTY_CUSTOMENTRYFORMANNOT);
protected AnnotationProperty LOCAL_PROPERTY_CUSTOMDISPLAYVIEWANNOT = _constModel.createAnnotationProperty(VitroVocabulary.PROPERTY_CUSTOMDISPLAYVIEWANNOT);
protected AnnotationProperty LOCAL_PROPERTY_CUSTOMSHORTVIEWANNOT = _constModel.createAnnotationProperty(VitroVocabulary.PROPERTY_CUSTOMSHORTVIEWANNOT);
protected AnnotationProperty LOCAL_PROPERTY_CUSTOMSEARCHVIEWANNOT = _constModel.createAnnotationProperty(VitroVocabulary.PROPERTY_CUSTOMSEARCHVIEWANNOT);
protected AnnotationProperty LOCAL_HIDDEN_FROM_DISPLAY_BELOW_ROLE_LEVEL_ANNOT = _constModel.createAnnotationProperty(VitroVocabulary.HIDDEN_FROM_DISPLAY_BELOW_ROLE_LEVEL_ANNOT);
protected AnnotationProperty LOCAL_PROHIBITED_FROM_UPDATE_BELOW_ROLE_LEVEL_ANNOT = _constModel.createAnnotationProperty(VitroVocabulary.PROHIBITED_FROM_UPDATE_BELOW_ROLE_LEVEL_ANNOT);
protected AnnotationProperty LOCAL_HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT = _constModel.createAnnotationProperty(VitroVocabulary.HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT);
protected AnnotationProperty LOCAL_IN_CLASSGROUP = _constModel.createAnnotationProperty(VitroVocabulary.IN_CLASSGROUP);
private VClass vClassWebappFromOntClass(OntClass cls, WebappDaoFactoryJena wadf) {
VClass vcw = new VClass();
cls.getModel().enterCriticalSection(Lock.READ);
vcw.setName(getLabelForClass(cls,false,false,wadf));
vcw.setLocalNameWithPrefix(wadf.makeLocalNameWithPrefix(vcw));
vcw.setPickListName(getLabelForClass(cls,false,true,wadf));
try {
if (cls.isAnon()) {
vcw.setNamespace(VitroVocabulary.PSEUDO_BNODE_NS);
vcw.setLocalName(cls.getId().toString());
} else {
if (vcw.getName() == null)
vcw.setName("[null]");
vcw.setURI(cls.getURI());
vcw.setNamespace(cls.getNameSpace());
vcw.setLocalName(cls.getLocalName());
}
try {
Resource groupRes = (Resource) cls.getPropertyValue(LOCAL_IN_CLASSGROUP);
if (groupRes != null) {
vcw.setGroupURI(groupRes.getURI());
}
} catch (Exception e) {
System.out.println("error retrieving vitro:inClassGroup property value for "+cls.getURI());
}
vcw.setShortDef(getPropertyStringValue(cls,LOCAL_SHORTDEF));
vcw.setExample(getPropertyStringValue(cls,LOCAL_EXAMPLE_ANNOT));
vcw.setDescription(getPropertyStringValue(cls,LOCAL_DESCRIPTION_ANNOT));
vcw.setDisplayLimit(getPropertyNonNegativeIntValue(cls,LOCAL_DISPLAY_LIMIT));
vcw.setDisplayRank(getPropertyNonNegativeIntValue(cls,LOCAL_DISPLAY_RANK_ANNOT));
vcw.setCustomEntryForm(getPropertyStringValue(cls,LOCAL_PROPERTY_CUSTOMENTRYFORMANNOT));
vcw.setCustomDisplayView(getPropertyStringValue(cls,LOCAL_PROPERTY_CUSTOMDISPLAYVIEWANNOT));
vcw.setCustomShortView(getPropertyStringValue(cls,LOCAL_PROPERTY_CUSTOMSHORTVIEWANNOT));
vcw.setCustomSearchView(getPropertyStringValue(cls,LOCAL_PROPERTY_CUSTOMSEARCHVIEWANNOT));
vcw.setSearchBoost(getPropertyFloatValue(cls,LOCAL_SEARCH_BOOST_ANNOT));
//There might be multiple HIDDEN_FROM_EDIT_DISPLAY_ANNOT properties, only use the highest
StmtIterator it = cls.listProperties(LOCAL_HIDDEN_FROM_DISPLAY_BELOW_ROLE_LEVEL_ANNOT);
BaseResourceBean.RoleLevel hiddenRoleLevel = null;
while( it.hasNext() ){
Statement stmt = it.nextStatement();
RDFNode obj;
if( stmt != null && (obj = stmt.getObject()) != null && obj.isURIResource() ){
Resource res = (Resource)obj.as(Resource.class);
if( res != null && res.getURI() != null ){
BaseResourceBean.RoleLevel roleFromModel = BaseResourceBean.RoleLevel.getRoleByUri(res.getURI());
if( roleFromModel != null &&
(hiddenRoleLevel == null || roleFromModel.compareTo(hiddenRoleLevel) > 0 )){
hiddenRoleLevel = roleFromModel;
}
}
}
}
vcw.setHiddenFromDisplayBelowRoleLevel(hiddenRoleLevel);//this might get set to null
//There might be multiple PROHIBITED_FROM_UPDATE_DISPLAY_ANNOT properties, only use the highest
it = cls.listProperties(LOCAL_PROHIBITED_FROM_UPDATE_BELOW_ROLE_LEVEL_ANNOT);
BaseResourceBean.RoleLevel prohibitedRoleLevel = null;
while( it.hasNext() ){
Statement stmt = it.nextStatement();
RDFNode obj;
if( stmt != null && (obj = stmt.getObject()) != null && obj.isURIResource() ){
Resource res = (Resource)obj.as(Resource.class);
if( res != null && res.getURI() != null ){
BaseResourceBean.RoleLevel roleFromModel = BaseResourceBean.RoleLevel.getRoleByUri(res.getURI());
if( roleFromModel != null &&
(prohibitedRoleLevel == null || roleFromModel.compareTo(prohibitedRoleLevel) > 0 )){
prohibitedRoleLevel = roleFromModel;
}
}
}
}
vcw.setProhibitedFromUpdateBelowRoleLevel(prohibitedRoleLevel);//this might get set to null
//There might be multiple LOCAL_HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT properties, only use the highest
it = cls.listProperties(LOCAL_HIDDEN_FROM_PUBLISH_BELOW_ROLE_LEVEL_ANNOT);
BaseResourceBean.RoleLevel publishRoleLevel = null;
while( it.hasNext() ){
Statement stmt = it.nextStatement();
RDFNode obj;
if( stmt != null && (obj = stmt.getObject()) != null && obj.isURIResource() ){
Resource res = (Resource)obj.as(Resource.class);
if( res != null && res.getURI() != null ){
BaseResourceBean.RoleLevel roleFromModel = BaseResourceBean.RoleLevel.getRoleByUri(res.getURI());
if( roleFromModel != null &&
(publishRoleLevel == null || roleFromModel.compareTo(publishRoleLevel) > 0 )){
publishRoleLevel = roleFromModel;
}
}
}
}
vcw.setHiddenFromPublishBelowRoleLevel(publishRoleLevel);//this might get set to null
} finally {
cls.getModel().leaveCriticalSection();
}
return vcw;
}
public String getLabelForClass(OntClass cls,boolean withPrefix,boolean forPickList,WebappDaoFactoryJena wadf) {
cls.getModel().enterCriticalSection(Lock.READ);
try {
if (cls.isAnon()) {
if (cls.isRestriction()) {
Restriction rest = cls.asRestriction();
OntProperty onProperty = rest.getOnProperty();
String labelStr = "restriction on " + getLabelOrId(onProperty) + ": ";
if (rest.isAllValuesFromRestriction() || rest.isSomeValuesFromRestriction()) {
Resource fillerRes = null;
if (rest.isAllValuesFromRestriction()) {
AllValuesFromRestriction avfRest = rest.asAllValuesFromRestriction();
fillerRes = avfRest.getAllValuesFrom();
labelStr += "all values from ";
} else {
SomeValuesFromRestriction svfRest = rest.asSomeValuesFromRestriction();
fillerRes = svfRest.getSomeValuesFrom();
labelStr += "some values from ";
}
if (fillerRes.canAs(OntClass.class)) {
OntClass avf = (OntClass) fillerRes.as(OntClass.class);
labelStr += getLabelForClass(avf,withPrefix,forPickList,wadf);
} else {
try {
labelStr += getLabelOrId( (OntResource) fillerRes.as(OntResource.class));
} catch (Exception e) {
labelStr += "???";
}
}
} else if (rest.isHasValueRestriction()) {
HasValueRestriction hvRest = rest.asHasValueRestriction();
labelStr += "has value ";
RDFNode fillerNode = hvRest.getHasValue();
try {
if (fillerNode.isResource()) {
labelStr += getLabelOrId((OntResource)fillerNode.as(OntResource.class));
} else {
labelStr += ((Literal) fillerNode.as(Literal.class)).getLexicalForm();
}
} catch (Exception e) {
labelStr += "???";
}
} else if (rest.isMinCardinalityRestriction()) {
MinCardinalityRestriction mcRest = rest.asMinCardinalityRestriction();
labelStr += "minimum cardinality ";
labelStr += mcRest.getMinCardinality();
} else if (rest.isMaxCardinalityRestriction()) {
MaxCardinalityRestriction mcRest = rest.asMaxCardinalityRestriction();
labelStr += "maximum cardinality ";
labelStr += mcRest.getMaxCardinality();
} else if (rest.isCardinalityRestriction()) {
CardinalityRestriction cRest = rest.asCardinalityRestriction();
labelStr += "cardinality ";
labelStr += cRest.getCardinality();
}
return labelStr;
} else if (isBooleanClassExpression(cls)) {
String labelStr = "(";
if (cls.isComplementClass()) {
labelStr += "not ";
ComplementClass ccls = (ComplementClass) cls.as(ComplementClass.class);
labelStr += getLabelForClass(ccls.getOperand(),withPrefix,forPickList,wadf);
} else if (cls.isIntersectionClass()) {
IntersectionClass icls = (IntersectionClass) cls.as(IntersectionClass.class);
for (Iterator operandIt = icls.listOperands(); operandIt.hasNext();) {
OntClass operand = (OntClass) operandIt.next();
labelStr += getLabelForClass(operand,withPrefix,forPickList,wadf);
if (operandIt.hasNext()) {
labelStr += " and ";
}
}
} else if (cls.isUnionClass()) {
UnionClass icls = (UnionClass) cls.as(UnionClass.class);
for (Iterator operandIt = icls.listOperands(); operandIt.hasNext();) {
OntClass operand = (OntClass) operandIt.next();
labelStr += getLabelForClass(operand,withPrefix,forPickList,wadf);
if (operandIt.hasNext()) {
labelStr += " or ";
}
}
}
return labelStr+")";
} else {
// BJL23 2009-02-19
// I'm putting the link markup in because I need it,
// but obviously we need to factor this out into the display layer.
return "<a href=\"vclassEdit?uri="+URLEncoder.encode(getClassURIStr(cls),"UTF-8")+"\">[anonymous class]</a>";
}
} else {
if (withPrefix || forPickList) {
OntologyDao oDao=wadf.getOntologyDao();
Ontology o = (Ontology)oDao.getOntologyByURI(cls.getNameSpace());
if (o!=null) {
if (withPrefix) {
return(o.getPrefix()==null?(o.getName()==null?"unspec:"+getLabelOrId(cls):o.getName()+":"+getLabelOrId(cls)):o.getPrefix()+":"+getLabelOrId(cls));
} else {
return(getLabelOrId(cls)+(o.getPrefix()==null?(o.getName()==null?" (unspec)":" ("+o.getName()+")"):" ("+o.getPrefix()+")"));
}
} else {
return getLabelOrId(cls);
}
}
return getLabelOrId(cls);
}
} catch (Exception e) {
return "???";
} finally {
cls.getModel().leaveCriticalSection();
}
}
protected String getLabelOrId(OntResource r) {
String label = null;
r.getOntModel().enterCriticalSection(Lock.READ);
try {
label = getLabel(r);
if( label == null || label.length() == 0 )
label = getLocalNameOrId(r);
} finally {
r.getOntModel().leaveCriticalSection();
}
return label;
}
private final boolean ALSO_TRY_NO_LANG = true;
/**
* works through list of PREFERRED_LANGUAGES to find an appropriate
* label, or NULL if not found.
*/
protected String getLabel(OntResource r){
String label = null;
r.getOntModel().enterCriticalSection(Lock.READ);
try {
// try rdfs:label with preferred languages
label = tryPropertyForPreferredLanguages( r, RDFS.label, ALSO_TRY_NO_LANG );
// try vitro:label with preferred languages
if ( label == null ) {
label = tryPropertyForPreferredLanguages( r, r.getModel().getProperty(VitroVocabulary.label), ALSO_TRY_NO_LANG );
}
} finally {
r.getOntModel().leaveCriticalSection();
}
return label;
}
private String tryPropertyForPreferredLanguages( OntResource r, Property p, boolean alsoTryNoLang ) {
String label = null;
List<RDFNode> labels = (List<RDFNode>) r.listPropertyValues(p).toList();
String lang = "en-US";
label = getLabel2(lang,labels);
if ( label == null && alsoTryNoLang ) {
label = getLabel2("", labels);
}
return label;
}
private String getLabel2(String lang, List<RDFNode>labelList) {
Iterator<RDFNode> labelIt = labelList.iterator();
while (labelIt.hasNext()) {
RDFNode label = labelIt.next();
if (label.isLiteral()) {
Literal labelLit = ((Literal)label);
String labelLanguage = labelLit.getLanguage();
if ( (labelLanguage==null) && (lang==null) ) {
return labelLit.getLexicalForm();
}
if ( (lang != null) && (lang.equals(labelLanguage)) ) {
return labelLit.getLexicalForm();
}
}
}
return null;
}
/**
* Get the local name, bnode or URI of the resource.
*/
protected String getLocalNameOrId(OntResource r){
String label = null;
r.getOntModel().enterCriticalSection(Lock.READ);
try {
String localName = r.getLocalName();
if (localName != null) {
label = localName;
} else if (r.isAnon()) {
label = r.getId().toString();
} else {
label = r.getURI();
}
} finally {
r.getOntModel().leaveCriticalSection();
}
return label;
}
protected String getPropertyStringValue(OntResource res, Property dataprop) {
if (dataprop != null) {
try {
ClosableIterator stateIt = res.getModel().listStatements(res,dataprop,(Literal)null);
try {
if (stateIt.hasNext())
return ((Literal)((Statement)stateIt.next()).getObject()).getString();
else
return null;
} finally {
stateIt.close();
}
} catch (Exception e) {
return null;
}
} else {
return null;
}
}
protected int getPropertyNonNegativeIntValue(OntResource res, Property dataprop) {
if (dataprop != null) {
try {
return ((Literal)res.getPropertyValue(dataprop)).getInt();
} catch (Exception e) {
return -1;
}
} else {
return -1;
}
}
protected Float getPropertyFloatValue(OntResource res, Property prop){
if( prop != null ){
try{
return new Float( ((Literal)res.getPropertyValue(prop)).getFloat() );
}catch(Exception e){
return null;
}
}else
return null;
}
public synchronized boolean isBooleanClassExpression(OntClass cls) {
return (cls.isComplementClass() || cls.isIntersectionClass() || cls.isUnionClass());
}
protected String getClassURIStr(Resource cls) {
if (cls.isAnon()) {
return VitroVocabulary.PSEUDO_BNODE_NS+cls.getId().toString();
} else {
return cls.getURI();
}
}
}

View file

@ -0,0 +1,128 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.dao.vclassgroup;
import java.io.StringReader;
import org.junit.Assert;
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.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
public class ProhibitedFromSearchTest {
String SEARCH_CONFIG_URI = DisplayVocabulary.SEARCH_INDEX_URI;
String TEST_CLASS = "http://vivoweb.org/ontology/test/bogus#Class5";
String n3 =
"@prefix : <http://vitro.mannlib.cornell.edu/ns/vitroDisplay#> . \n" +
"@prefix vivo: <http://vivoweb.org/ontology/test/bogus#> . \n" +
"@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . \n"+
"<"+SEARCH_CONFIG_URI+"> rdf:type :ProhibitedFromSearch ;\n" +
" <" + DisplayVocabulary.EXCLUDE_CLASS.getURI() + "> vivo:Class2, vivo:Class3, vivo:Class4, <"+TEST_CLASS+"> .\n" ;
@Test
public void testBuildingProhibited(){
Model r = ModelFactory.createDefaultModel().read(new StringReader(n3), null, "N3");
OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
m.add( r.listStatements() );
Assert.assertTrue(m.size() > 4);
ProhibitedFromSearch pfs = new ProhibitedFromSearch( SEARCH_CONFIG_URI , m);
Assert.assertNotNull(pfs.prohibitedClasses);
Assert.assertTrue(pfs.prohibitedClasses.size() == 4);
Assert.assertTrue(pfs.isClassProhibitedFromSearch(TEST_CLASS));
Assert.assertTrue(!pfs.isClassProhibitedFromSearch("http://someOtherClass.com/test"));
}
@Test
public void testNotFound(){
Model r = ModelFactory.createDefaultModel().read(new StringReader(n3), null, "N3");
OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
m.add( r.listStatements() );
Assert.assertTrue(m.size() > 4);
ProhibitedFromSearch pfs = new ProhibitedFromSearch( "http://NotFound.com/inModel", m);
Assert.assertNotNull(pfs.prohibitedClasses);
Assert.assertTrue(pfs.prohibitedClasses.size() == 0);
Assert.assertTrue(!pfs.isClassProhibitedFromSearch(TEST_CLASS));
Assert.assertTrue(!pfs.isClassProhibitedFromSearch("http://someOtherClass.com/test"));
}
@Test
public void testListener(){
Model r = ModelFactory.createDefaultModel().read(new StringReader(n3), null, "N3");
OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
m.add( r.listStatements() );
Assert.assertTrue(m.size() > 4);
ProhibitedFromSearch pfs = new ProhibitedFromSearch( SEARCH_CONFIG_URI , m);
Assert.assertTrue(pfs.prohibitedClasses.size() == 4);
Resource bougsClass3 = ResourceFactory.createResource("http://example.com/bougsClass3");
Resource searchConfig = ResourceFactory.createResource(SEARCH_CONFIG_URI);
m.add(searchConfig, DisplayVocabulary.EXCLUDE_CLASS, bougsClass3);
Assert.assertEquals(5, pfs.prohibitedClasses.size());
m.remove(searchConfig, DisplayVocabulary.EXCLUDE_CLASS, bougsClass3);
Assert.assertEquals(4, pfs.prohibitedClasses.size());
Resource bougsClass4 = ResourceFactory.createResource("http://vivoweb.org/ontology/test/bogus#Class4");
m.remove(searchConfig, DisplayVocabulary.EXCLUDE_CLASS, bougsClass4);
Assert.assertEquals(3, pfs.prohibitedClasses.size());
}
@Test
public void testListenerAbnormal(){
Model r = ModelFactory.createDefaultModel().read(new StringReader(n3), null, "N3");
OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
m.add( r.listStatements() );
Assert.assertTrue(m.size() > 4);
ProhibitedFromSearch pfs = new ProhibitedFromSearch( SEARCH_CONFIG_URI , m);
Assert.assertTrue(pfs.prohibitedClasses.size() == 4);
int originalSize = pfs.prohibitedClasses.size();
Literal bogusLiteral = ResourceFactory.createPlainLiteral("some bogus literal");
Resource searchConfig = ResourceFactory.createResource(SEARCH_CONFIG_URI);
m.add(searchConfig, DisplayVocabulary.EXCLUDE_CLASS, bogusLiteral);
Assert.assertEquals(originalSize, pfs.prohibitedClasses.size());
m.remove(searchConfig, DisplayVocabulary.EXCLUDE_CLASS, bogusLiteral);
Assert.assertEquals(originalSize, pfs.prohibitedClasses.size());
Resource anonRes = ResourceFactory.createResource();
m.remove(searchConfig, DisplayVocabulary.EXCLUDE_CLASS, anonRes);
Assert.assertEquals(originalSize, pfs.prohibitedClasses.size());
}
@Test
public void testPrimaryIndex(){
String primaryIndexN3 =
"<http://vitro.mannlib.cornell.edu/ontologies/display/1.1#SearchIndex>" +
"<http://vitro.mannlib.cornell.edu/ontologies/display/1.1#excludeClass>" +
"<http://vivoweb.org/ontology/core#NonAcademic> . ";
Model r = ModelFactory.createDefaultModel().read(new StringReader(primaryIndexN3), null, "N3");
OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
m.add( r.listStatements() );
Assert.assertTrue(m.size() == 1);
ProhibitedFromSearch pfs = new ProhibitedFromSearch( DisplayVocabulary.SEARCH_INDEX_URI, m);
Assert.assertNotNull(pfs.prohibitedClasses);
Assert.assertEquals(1, pfs.prohibitedClasses.size() );
Assert.assertTrue(pfs.isClassProhibitedFromSearch("http://vivoweb.org/ontology/core#NonAcademic"));
Assert.assertTrue(!pfs.isClassProhibitedFromSearch("http://someOtherClass.com/test"));
}
}

View file

@ -0,0 +1,125 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.hp.hpl.jena.rdf.model.Literal;
public class EditLiteralTest {
@Test
public void testEqual(){
Assert.assertTrue( EditLiteral.equalLiterals(
new EditLiteral("dog", (String)null, (String)null ),
new EditLiteral("dog", (String)null, (String)null )
));
Assert.assertTrue( EditLiteral.equalLiterals(
new EditLiteral("dog", (String)"http://someUri", (String)null ),
new EditLiteral("dog", (String)"http://someUri", (String)null )
));
Assert.assertTrue( EditLiteral.equalLiterals(
new EditLiteral("dog", (String)null, (String)"SOMELANG" ),
new EditLiteral("dog", (String)null, (String)"SOMELANG" )
));
//datatype trumps lang
Assert.assertTrue( EditLiteral.equalLiterals(
new EditLiteral("dog", (String)"http://someUri", (String)"SOMELANG" ),
new EditLiteral("dog", (String)"http://someUri", (String)null )
));
Assert.assertTrue( EditLiteral.equalLiterals(
new EditLiteral("dog", (String)"http://someUri", (String)null ),
new EditLiteral("dog", (String)"http://someUri", (String)"OTHERLANG" )
));
Assert.assertTrue( EditLiteral.equalLiterals(
new EditLiteral("dog", (String)"http://someUri", (String)"SOMELANG" ),
new EditLiteral("dog", (String)"http://someUri", (String)"SOMELANG" )
));
Assert.assertTrue( EditLiteral.equalLiterals(
new EditLiteral("dog", (String)"http://someUri", (String)"SOMELANG" ),
new EditLiteral("dog", (String)"http://someUri", (String)"OTHERLANG" )
));
Assert.assertTrue( EditLiteral.equalLiterals(
new EditLiteral("dog", (String)null, (String)"SOMELANG" ),
new EditLiteral("dog", (String)null, (String)"SOMELANG" )
));
//NOT EQUAL CASES
Assert.assertFalse( EditLiteral.equalLiterals(
new EditLiteral("dog", (String)null, (String)null ),
new EditLiteral("catFood", (String)null, (String)null )
));
Assert.assertFalse( EditLiteral.equalLiterals(
new EditLiteral("dog", (String)"http://someUri", (String)null ),
new EditLiteral("dog", (String)"http://otherUri.com", (String)null )
));
Assert.assertFalse( EditLiteral.equalLiterals(
new EditLiteral("dog", (String)null, (String)"SOMELANG" ),
new EditLiteral("dog", (String)null, (String)"OTHERLANG" )
));
Assert.assertFalse( EditLiteral.equalLiterals(
new EditLiteral("dog", (String)"http://someUri", (String)"SOMELANG" ),
new EditLiteral("dog", (String)"http://otherUri.com", (String)"SOMELANG" )
));
Assert.assertFalse( EditLiteral.equalLiterals(
new EditLiteral("dog", (String)"http://someUri", (String)"SOMELANG" ),
new EditLiteral("dog", (String)"http://otherUri.com", (String)null )
));
Assert.assertFalse( EditLiteral.equalLiterals(
new EditLiteral("dog", (String)"http://someUri", (String)null ),
new EditLiteral("dog", (String)"http://otherUri.com", (String)"SOMELANG" )
));
Assert.assertFalse( EditLiteral.equalLiterals(
new EditLiteral("dog", (String)"http://someUri", (String)null ),
new EditLiteral("dog", (String)null, (String)null )
));
Assert.assertFalse( EditLiteral.equalLiterals(
new EditLiteral("dog", (String)null, (String)null ),
new EditLiteral("dog", (String)"http://someUri", (String)null )
));
Assert.assertFalse( EditLiteral.equalLiterals(
new EditLiteral("dog", (String)null, (String)"SOMELANG" ),
new EditLiteral("dog", (String)null, (String)null )
));
Assert.assertFalse( EditLiteral.equalLiterals(
new EditLiteral("dog", (String)null, (String)null ),
new EditLiteral("dog", (String)null, (String)"SOMELANG" )
));
Assert.assertFalse( EditLiteral.equalLiterals(
new EditLiteral("dog", (String)null, (String)null ),
new EditLiteral(null, (String)null, (String)null )
));
Assert.assertFalse( EditLiteral.equalLiterals(
new EditLiteral(null, (String)null, (String)null ),
new EditLiteral("dog", (String)null, (String)null )
));
Assert.assertFalse( EditLiteral.equalLiterals(
new EditLiteral("dog", (String)null, (String)"SOMELANG" ),
new EditLiteral("catFood", (String)null, (String)"SOMELANG" )
));
Assert.assertFalse( EditLiteral.equalLiterals(
new EditLiteral("dog", (String)"http://someUri", (String)null ),
new EditLiteral("catFood", (String)"http://someUri", (String)null )
));
}
@Test
public void testBug2(){
Literal a2 = new EditLiteral("<ul><li>Stephen G. Yusem is the senior partner of High, Swartz, Roberts &amp; Seidel in Norristown, Pennsylvania. <br /></li><li>He has been certified as a mediator for the United States District Court for the Eastern District of Pennsylvania since 1991. <br /></li><li>He is a Fellow of the College of Commercial Arbitrators, a member of the Chartered Institute of Arbitrators, a panelist on the CPR Roster of Distinguished Neutrals and a past director of the Commercial Section of the Association for Conflict Resolution. <br /></li><li>He co-chairs the Arbitration Committee of the Dispute Resolution Section of the American Bar Association and is a former member of the Arbitration Faculty of the American Arbitration Association. <br /></li><li>He is a past president of the Montgomery County (PA) Bar Association and was Founding President of the Montgomery County Bar Foundation. He co-teaches Dispute Resolution: Negotiation, Mediation and Arbitration in the fall semester.</li></ul>",
"http://www.w3.org/2001/XMLSchema#string","");
Literal b2 = new EditLiteral("<ul><li>Stephen G. Yusem is the senior partner of High, Swartz, Roberts &amp; Seidel in Norristown, Pennsylvania. <br /></li><li>He has been certified as a mediator for the United States District Court for the Eastern District of Pennsylvania since 1991. <br /></li></ul>",
"http://www.w3.org/2001/XMLSchema#string",null);
Assert.assertFalse( EditLiteral.equalLiterals( a2, b2 ) );
}
}

View file

@ -0,0 +1,52 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing;
import org.junit.Assert;
import org.apache.commons.io.output.NullOutputStream;
import org.junit.Test;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.vocabulary.RDFS;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.N3EditUtils;
public class EditN3UtilsTest {
@Test
public void testStripInvalidXMLChars() {
Model m = ModelFactory.createDefaultModel();
String containsInvalidXMLChars = "Blah \u0001blah \u0002blah\uDDDD";
String clean = "Blah blah blah";
// add a statement with the literal incompatible with XML to model m
m.add(m.createResource(), RDFS.label, containsInvalidXMLChars);
Assert.assertFalse(isSerializableAsXML(m));
String stripped = N3EditUtils.stripInvalidXMLChars(
containsInvalidXMLChars);
Assert.assertEquals(clean, stripped);
// clear the model of any statements
m.removeAll();
// add a statement with a literal that has been stripped of bad chars
m.add(m.createResource(), RDFS.label, stripped);
Assert.assertTrue(isSerializableAsXML(m));
}
private boolean isSerializableAsXML(Model m) {
try {
NullOutputStream nullStream = new NullOutputStream();
m.write(nullStream, "RDF/XML");
return true;
} catch (Exception e) {
return false;
}
}
}

View file

@ -0,0 +1,47 @@
/* $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.util.Collections;
import org.junit.Assert;
import org.junit.Test;
public class BasicValidationVTwoTest {
@SuppressWarnings("unchecked")
@Test
public void testHttpUrlValidate() {
BasicValidationVTwo bv = new BasicValidationVTwo(Collections.EMPTY_MAP);
String res;
res = bv.validate("httpUrl", "http://example.com/index");
Assert.assertEquals(res, BasicValidationVTwo.SUCCESS);
res = bv.validate("httpUrl", "http://example.com/index?bogus=skjd%20skljd&something=sdkf");
Assert.assertEquals(res, BasicValidationVTwo.SUCCESS);
res = bv.validate("httpUrl", "http://example.com/index#2.23?bogus=skjd%20skljd&something=sdkf");
Assert.assertEquals(res, BasicValidationVTwo.SUCCESS);
}
@SuppressWarnings("unchecked")
@Test
public void testEmptyValidate(){
BasicValidationVTwo bv = new BasicValidationVTwo(Collections.EMPTY_MAP);
Assert.assertEquals(
bv.validate("nonempty", null)
, BasicValidationVTwo.REQUIRED_FIELD_EMPTY_MSG);
Assert.assertEquals(
bv.validate("nonempty", "")
, BasicValidationVTwo.REQUIRED_FIELD_EMPTY_MSG);
Assert.assertEquals(
bv.validate("nonempty", "some value")
, BasicValidationVTwo.SUCCESS);
}
}

View file

@ -0,0 +1,36 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import stubs.javax.servlet.http.HttpServletRequestStub;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
public class EditConfigurationUtilsTest {
@Before
public void setUp() throws Exception {
}
@Test
public void testGetEditKey() {
HttpServletRequestStub req = new HttpServletRequestStub();
req.addParameter("datapropKey", "2343");
Integer hash = EditConfigurationUtils.getDataHash(new VitroRequest(req));
Assert.assertNotNull(hash);
Assert.assertEquals(new Integer(2343), hash);
req = new HttpServletRequestStub();
hash = EditConfigurationUtils.getDataHash(new VitroRequest(req));
Assert.assertNull( hash);
}
}

View file

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

View file

@ -0,0 +1,399 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
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 com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.dao.InsertException;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfigurationConstants;
public class ProcessRdfFormTest extends AbstractTestClass{
@Test
public void basicNewStatementTest() throws Exception{
/* A very basic new statement edit. */
EditConfigurationVTwo config = new EditConfigurationVTwo();
config.setEditKey("mockEditKey");
config.setN3Required(Arrays.asList("?test1 ?test2 ?test3 ." ));
config.setUrisOnform(Arrays.asList("test1", "test2", "test3"));
Map<String,String[]> values = new HashMap<String, String[]>();
values.put("test1", (new String[] {"http://test.com/uri1"}));
values.put("test2", (new String[] {"http://test.com/uri2"}));
values.put("test3", (new String[] {"http://test.com/uri3"}));
values.put("editKey", (new String[] {"mockEditKey"}));
MultiValueEditSubmission submission = new MultiValueEditSubmission(values, config);
ProcessRdfForm processor = new ProcessRdfForm(config,getMockNewURIMaker());
/* test just the N3 substitution part */
List<String>req = config.getN3Required();
List<String>opt = config.getN3Optional();
processor.subInValuesToN3( config , submission, req, opt, null , null);
assertNotNull(req);
assertTrue( req.size() > 0);
assertNotNull(req.get(0));
assertEquals("<http://test.com/uri1> <http://test.com/uri2> <http://test.com/uri3> .", req.get(0));
/* test the N3 and parse RDF parts */
AdditionsAndRetractions changes = processor.process( config, submission, null );
assertNotNull( changes );
assertNotNull( changes.getAdditions() );
assertNotNull( changes.getRetractions());
assertTrue( changes.getAdditions().size() == 1 );
assertTrue( changes.getRetractions().size() == 0 );
assertTrue( changes.getAdditions().contains(
ResourceFactory.createResource("http://test.com/uri1"),
ResourceFactory.createProperty("http://test.com/uri2"),
ResourceFactory.createResource("http://test.com/uri3")));
}
/* A very basic edit of an existing statement. */
@Test
public void basicEditStatement() throws Exception{
String testXURI = "http://test.com/uriX";
String testYURI = "http://test.com/uriY";
String testZURIOrginal = "http://test.com/uriZ";
String testZURIChanged = "http://test.com/uriZChanged";
/* set up model */
Model model = ModelFactory.createDefaultModel();
model.add(model.createResource(testXURI),
model.createProperty(testYURI),
model.createResource(testZURIOrginal));
/* set up EditConfiguration */
EditConfigurationVTwo config = new EditConfigurationVTwo();
config.setEditKey("mockEditKey");
config.setUrisOnform(Arrays.asList("testX", "testY", "testZ"));
config.setN3Required( Arrays.asList("?testX ?testY ?testZ ." ));
config.setVarNameForSubject("testX");
config.setSubjectUri(testXURI);
config.setPredicateUri(testYURI);
config.setVarNameForPredicate("testY");
config.setObject(testZURIOrginal);
config.setVarNameForObject("testZ");
config.prepareForObjPropUpdate(model);
/* set up Submission */
Map<String,String[]> values = new HashMap<String, String[]>();
values.put("testZ", (new String[] {testZURIChanged}));
values.put("editKey", (new String[] {"mockEditKey"}));
MultiValueEditSubmission submission = new MultiValueEditSubmission(values, config);
ProcessRdfForm processor = new ProcessRdfForm(config,getMockNewURIMaker());
AdditionsAndRetractions changes = processor.process( config, submission, null );
assertNotNull( changes );
assertNotNull( changes.getAdditions() );
assertNotNull( changes.getRetractions());
assertTrue( changes.getAdditions().size() == 1 );
assertTrue( changes.getRetractions().size() == 1 );
assertTrue( changes.getAdditions().contains(
ResourceFactory.createResource(testXURI),
ResourceFactory.createProperty(testYURI),
ResourceFactory.createResource(testZURIChanged)));
assertTrue( changes.getRetractions().contains(
ResourceFactory.createResource(testXURI),
ResourceFactory.createProperty(testYURI),
ResourceFactory.createResource(testZURIOrginal)));
}
@Test
public void substituteInSubPredObjURIsTest(){
String testXURI = "http://test.com/uriX";
String testYURI = "http://test.com/uriY";
String testZURI = "http://test.com/uriZ";
/* set up EditConfiguration */
EditConfigurationVTwo config = new EditConfigurationVTwo();
config.setVarNameForSubject("testX");
config.setSubjectUri(testXURI);
config.setPredicateUri(testYURI);
config.setVarNameForPredicate("testY");
config.setObject(testZURI);
config.setVarNameForObject("testZ");
List<String> a = Arrays.asList("a.0 ?testX ?testY ?testZ.", "a.1 ?testX ?testY ?testZ.");
List<String> b = Arrays.asList("b.0 ?testX ?testY ?testZ.", "b.1 ?testX ?testY ?testZ.");
ProcessRdfForm processor = new ProcessRdfForm(config,getMockNewURIMaker());
processor.substituteInSubPredObjURIs(config, a, b);
assertEquals("a.0 <" + testXURI + "> <" + testYURI + "> <" + testZURI + ">.", a.get(0));
assertEquals("a.1 <" + testXURI + "> <" + testYURI + "> <" + testZURI + ">.", a.get(1));
assertEquals("b.0 <" + testXURI + "> <" + testYURI + "> <" + testZURI + ">.", b.get(0));
assertEquals("b.1 <" + testXURI + "> <" + testYURI + "> <" + testZURI + ">.", b.get(1));
}
@Test
public void unicodeTest() throws Exception{
/* A test unicode characters with new statement edit. */
/* make configuration */
EditConfigurationVTwo config = new EditConfigurationVTwo();
config.setEditKey("mockEditKey");
config.setN3Required(Arrays.asList("?test1 ?test2 ?test3 ." ));
config.setUrisOnform(Arrays.asList("test1", "test2", "test3"));
String test1 = "http://test.com/uriWithUnicodeƺ",
test2 = "http://test.com/latin-1-ÙåàÞñöÿ",
test3 = "http://test.com/moreUnicode-ἎἘὤ" ;
/* make submission */
Map<String,String[]> values = new HashMap<String, String[]>();
values.put("test1", (new String[] {test1}));
values.put("test2", (new String[] {test2}));
values.put("test3", (new String[] {test3}));
values.put("editKey", (new String[] {"mockEditKey"}));
MultiValueEditSubmission submission = new MultiValueEditSubmission(values, config);
ProcessRdfForm processor = new ProcessRdfForm(config,getMockNewURIMaker());
/* test just the N3 substitution part */
List<String>req = config.getN3Required();
List<String>opt = config.getN3Optional();
processor.subInValuesToN3( config , submission, req, opt, null , null);
assertNotNull(req);
assertTrue( req.size() > 0);
assertNotNull(req.get(0));
assertEquals("<" +test1+ "> <" +test2+ "> <" +test3+ "> .", req.get(0));
/* test the N3 and parse RDF parts */
AdditionsAndRetractions changes = processor.process( config, submission, null );
assertNotNull( changes );
assertNotNull( changes.getAdditions() );
assertNotNull( changes.getRetractions());
assertTrue( changes.getAdditions().size() == 1 );
assertTrue( changes.getRetractions().size() == 0 );
assertTrue( changes.getAdditions().contains(
ResourceFactory.createResource(test1),
ResourceFactory.createProperty(test2),
ResourceFactory.createResource(test3)));
}
@Test
public void basicNewResourceTest() throws Exception{
/* A very basic new statement edit. */
EditConfigurationVTwo config = new EditConfigurationVTwo();
config.setEditKey("mockEditKey");
config.setN3Required(Arrays.asList("?newRes ?test2 ?test3 ." ));
config.setUrisOnform(Arrays.asList( "test2", "test3"));
config.addNewResource("newRes", null);
config.setEntityToReturnTo("?newRes");
Map<String,String[]> values = new HashMap<String, String[]>();
values.put("test2", (new String[] {"http://test.com/uri2"}));
values.put("test3", (new String[] {"http://test.com/uri3"}));
values.put("editKey", (new String[] {"mockEditKey"}));
MultiValueEditSubmission submission = new MultiValueEditSubmission(values, config);
ProcessRdfForm processor = new ProcessRdfForm(config,getMockNewURIMaker());
/* test just the N3 substitution part */
List<String>req = config.getN3Required();
List<String>opt = config.getN3Optional();
processor.subInValuesToN3( config , submission, req, opt, null , null);
assertNotNull(req);
assertTrue( req.size() > 0);
assertNotNull(req.get(0));
assertEquals("<"+NEWURI_STRING + "0> <http://test.com/uri2> <http://test.com/uri3> .", req.get(0));
assertEquals("<" + NEWURI_STRING + "0>", submission.getEntityToReturnTo());
/* test the N3 and parse RDF parts */
AdditionsAndRetractions changes = processor.process( config, submission, null );
assertNotNull( changes );
assertNotNull( changes.getAdditions() );
assertNotNull( changes.getRetractions());
assertTrue( changes.getAdditions().size() == 1 );
assertTrue( changes.getRetractions().size() == 0 );
assertTrue( changes.getAdditions().contains(
ResourceFactory.createResource(NEWURI_STRING + "0"),
ResourceFactory.createProperty("http://test.com/uri2"),
ResourceFactory.createResource("http://test.com/uri3")));
}
@Test
//Edit existing statement
public void forcedNewResourceTest() throws Exception{
/* A very basic new statement edit. */
EditConfigurationVTwo config = new EditConfigurationVTwo();
config.setEditKey("mockEditKey");
config.setN3Required(Arrays.asList("?newRes ?test2 ?test3 ." ));
config.setUrisOnform(Arrays.asList( "newRes", "test2", "test3"));
//set uris in scope to include an existing value for new resource
config.addUrisInScope("newRes", Arrays.asList("<http://test.com/uri1>"));
config.addNewResource("newRes", null);
config.setEntityToReturnTo("?newRes");
Map<String,String[]> values = new HashMap<String, String[]>();
//value from form should indicate that newRes should have new uri created
values.put("newRes", (new String[] {EditConfigurationConstants.NEW_URI_SENTINEL}));
values.put("test2", (new String[] {"http://test.com/uri2"}));
values.put("test3", (new String[] {"http://test.com/uri3"}));
values.put("editKey", (new String[] {"mockEditKey"}));
MultiValueEditSubmission submission = new MultiValueEditSubmission(values, config);
ProcessRdfForm processor = new ProcessRdfForm(config,getMockNewURIMaker());
/* test just the N3 substitution part */
List<String>req = config.getN3Required();
List<String>opt = config.getN3Optional();
processor.subInValuesToN3( config , submission, req, opt, null , null);
assertNotNull(req);
assertTrue( req.size() > 0);
assertNotNull(req.get(0));
assertEquals("<"+NEWURI_STRING + "0> <http://test.com/uri2> <http://test.com/uri3> .", req.get(0));
assertEquals("<" + NEWURI_STRING + "0>", submission.getEntityToReturnTo());
/* test the N3 and parse RDF parts */
AdditionsAndRetractions changes = processor.process( config, submission, null );
assertNotNull( changes );
assertNotNull( changes.getAdditions() );
assertNotNull( changes.getRetractions());
assertTrue( changes.getAdditions().size() == 1 );
//the old uri should be removed
assertTrue( changes.getRetractions().size() == 0 );
assertTrue( changes.getAdditions().contains(
ResourceFactory.createResource(NEWURI_STRING + "0"),
ResourceFactory.createProperty("http://test.com/uri2"),
ResourceFactory.createResource("http://test.com/uri3")));
}
/* An edit of an existing statement set where some statements need to be replaced while
* others must be retained. */
@Test
public void basicEditReplaceStatement() throws Exception{
String testXURI = "http://test.com/uriX";
String testYURI = "http://test.com/uriY";
String testZURIOrginal = "http://test.com/uriZ";
String testZURIChanged = "http://test.com/uriZChanged";
String zType = "http://test.com/TestType";
String rdfsLabel = "http://www.w3.org/2000/01/rdf-schema#label";
/* set up model */
Model model = ModelFactory.createDefaultModel();
//?x ?y ?zOriginal.
model.add(model.createResource(testXURI),
model.createProperty(testYURI),
model.createResource(testZURIOrginal));
//?zOriginal a TestType.
model.add(model.createResource(testZURIOrginal),
RDF.type,
model.createResource(zType));
//?zOriginal label "zLabel";
model.add(model.createResource(testZURIOrginal),
RDFS.label,
model.createLiteral("Z Original Label"));
/* set up EditConfiguration */
EditConfigurationVTwo config = new EditConfigurationVTwo();
config.setEditKey("mockEditKey");
config.setLiteralsOnForm(Arrays.asList("zLabel"));
config.setUrisOnform(Arrays.asList("testX", "testY", "testZ"));
config.setN3Required( Arrays.asList("?testX ?testY ?testZ ." ));
config.setN3Optional( Arrays.asList("?testZ a <" + zType + "> . \n" +
"?testZ <" + rdfsLabel + "> ?zLabel ." ));
//mimicking an existing value for the label
config.addLiteralInScope("zLabel", model.createLiteral("Z Original Label"));
config.setVarNameForSubject("testX");
config.setSubjectUri(testXURI);
config.setPredicateUri(testYURI);
config.setVarNameForPredicate("testY");
config.setObject(testZURIOrginal);
config.setVarNameForObject("testZ");
config.addField(new FieldVTwo().setName("zLabel"));
config.prepareForObjPropUpdate(model);
/* set up Submission */
Map<String,String[]> values = new HashMap<String, String[]>();
values.put("testZ", (new String[] {testZURIChanged}));
values.put("zLabel", (new String[] {"New Z Label"}));
values.put("editKey", (new String[] {"mockEditKey"}));
MultiValueEditSubmission submission = new MultiValueEditSubmission(values, config);
ProcessRdfForm processor = new ProcessRdfForm(config,getMockNewURIMaker());
AdditionsAndRetractions changes = processor.process( config, submission, null );
assertNotNull( changes );
assertNotNull( changes.getAdditions() );
assertNotNull( changes.getRetractions());
// assertTrue( changes.getAdditions().size() == 3 );
//only one statement should be retracted
// assertTrue( changes.getRetractions().size() == 1 );
assertTrue( changes.getAdditions().contains(
ResourceFactory.createResource(testXURI),
ResourceFactory.createProperty(testYURI),
ResourceFactory.createResource(testZURIChanged)));
assertTrue( changes.getRetractions().contains(
ResourceFactory.createResource(testXURI),
ResourceFactory.createProperty(testYURI),
ResourceFactory.createResource(testZURIOrginal)));
}
String NEWURI_STRING= "http://newURI/n";
public NewURIMaker getMockNewURIMaker(){
return new NewURIMaker() {
int count = 0;
@Override
public String getUnusedNewURI(String prefixURI) throws InsertException {
if( prefixURI != null )
return prefixURI + count;
else
return NEWURI_STRING + count;
}
};
}
}

View file

@ -0,0 +1,129 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmission;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
public class AntiXssValidationTest {
@Test
public void testLiteral( ){
//test all fields constructor
AntiXssValidation validator =new AntiXssValidation();
EditConfigurationVTwo eConf = new EditConfigurationVTwo();
eConf.setEditKey("fakeEditKey");
eConf.addField( new FieldVTwo().setName("X") );
eConf.setLiteralsOnForm( Arrays.asList("X") );
Map<String, String[]> params = new HashMap<String,String[]>();
String[] vals= { "some sort of string" };
params.put("X", vals);
MultiValueEditSubmission mvEditSub =
new MultiValueEditSubmission(params,eConf);
Map<String, String> res = validator.validate(eConf, mvEditSub);
Assert.assertEquals(null, res);
}
@Test
public void testAllURI( ){
//test all fields constructor
AntiXssValidation validator =new AntiXssValidation();
EditConfigurationVTwo eConf = new EditConfigurationVTwo();
eConf.setEditKey("fakeEditKey");
eConf.setUrisOnform( Arrays.asList("X","Y","Z"));
Map<String, String[]> params = new HashMap<String,String[]>();
String[] strings0 = {"no problem 0"};
params.put("X", strings0 );
String[] strings1 = {"no problem 1"};
params.put("Y", strings1 );
String[] strings2 = {"no problem 2"};
params.put("Z", strings2 );
MultiValueEditSubmission mvEditSub =
new MultiValueEditSubmission(params,eConf);
Map<String, String> res = validator.validate(eConf, mvEditSub);
Assert.assertNull( res );
}
protected Map<String, String> testURI( String ... strings){
AntiXssValidation validator =
new AntiXssValidation(Arrays.asList("X"));
EditConfigurationVTwo eConf = new EditConfigurationVTwo();
eConf.setEditKey("fakeEditKey");
eConf.setUrisOnform( Arrays.asList("X"));
Map<String, String[]> params = new HashMap<String,String[]>();
params.put("X", strings );
MultiValueEditSubmission mvEditSub =
new MultiValueEditSubmission(params,eConf);
return validator.validate(eConf, mvEditSub);
}
@Test
public void testURIValidation(){
Map<String, String> result = testURI("http://this.should.be.fine.com/xyz#lskd?junk=a&bkeck=%23");
Assert.assertNull(result);
}
@Test
public void testURIValidationWithScriptTagLevel1(){
Map<String, String> result = null;
result = testURI("http:<SCRIPT SRC=http://ha.ckers.org/xss.js></SCRIPT>//bad.news.com");
Assert.assertNotNull(result);
result = testURI("http:<IMG SRC=JaVaScRiPt:alert('XSS')>//bad.news.com");
Assert.assertNotNull(result);
result = testURI("http:<IMG SRC=javascript:alert('XSS')>//bad.news.com");
Assert.assertNotNull(result);
result = testURI("http:<IMG SRC=javascript:alert(&quot;XSS&quot;)>//bad.news.com");
Assert.assertNotNull(result);
result = testURI("http:<IMG SRC=\"jav\tascript:alert('XSS');\">//bad.news.com");
Assert.assertNotNull(result);
}
@Test
public void testURIValidationWithScriptTagLevel2(){
Map<String, String> result = null;
result = testURI("http:<IMG SRC=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97;&#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;>//bad.news.com");
Assert.assertNotNull(result);
result = testURI("http:<IMG SRC=&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041>//bad.news.com");
Assert.assertNotNull(result);
result = testURI("http:<IMG SRC=&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&#x3A&#x61&#x6C&#x65&#x72&#x74&#x28&#x27&#x58&#x53&#x53&#x27&#x29>//bad.news.com");
Assert.assertNotNull(result);
result = testURI("http:<<SCRIPT>alert(\"XSS\");//<</SCRIPT>//bad.news.com");
Assert.assertNotNull(result);
result = testURI("http:<IMG SRC=&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041>//bad.news.com");
Assert.assertNotNull(result);
result = testURI("http:<IMG SRC=&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041>//bad.news.com");
Assert.assertNotNull(result);
}
}

View file

@ -0,0 +1,221 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.vocabulary.XSD;
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.IndividualImpl;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.RdfLiteralHash;
public class RdfLiteralHashTest {
final String TEST_VALUE ="this is a test literal string";
final String TEST_DATA_PROP_URI ="http://this.is.a.test.uri.com/1999/02/blec-ns#test2332";
final String TEST_INDIVIDUAL_URI ="http://this.is.a.testUri.com/1999/02/bleck-ns#INDIVIDUAL787878";
final String TEST_DATA_TYPE_URI ="http://this.is.a.uri.com/TEST/DATA/TYPE#e8";
final String TEST_LANG = "ENG";
@Test
public void testEdBackground(){
String value = "[CELE97] Waldemar Celes and Jonathan Corson-Rikert. &quot;Act: An Easy-to-use and Dynamically Extensible 3D Graphics Library&quot; in Proceedings, Brazilian Symposium on Computer Graphics and Image Processing, Campos do Jordao, SP -Brazil, October, 1997.";
String propUri = "http://vivo.library.cornell.edu/ns/0.1#publications";
String subject = "http://vivo.library.cornell.edu/ns/0.1#individual22972";
String datatypeUri= null;
String language = null;
DataPropertyStatement stmt = new DataPropertyStatementImpl();
stmt.setIndividualURI(subject);
stmt.setData(value);
stmt.setDatapropURI(propUri);
stmt.setDatatypeURI(datatypeUri);
stmt.setLanguage(language);
int hash = RdfLiteralHash.makeRdfLiteralHash( stmt);
Assert.assertTrue(hash != 0);
Assert.assertEquals(1646037091 , hash);
}
@Test
public void testMakeRdfLiteralHash() {
DataPropertyStatement stmt = new DataPropertyStatementImpl();
stmt.setData(TEST_VALUE);
stmt.setDatapropURI(TEST_DATA_PROP_URI);
stmt.setIndividualURI(TEST_INDIVIDUAL_URI);
int hash = RdfLiteralHash.makeRdfLiteralHash(stmt);
Assert.assertTrue(hash != 0);
stmt = new DataPropertyStatementImpl();
stmt.setData(TEST_VALUE);
stmt.setDatapropURI(TEST_DATA_PROP_URI);
stmt.setIndividualURI(TEST_INDIVIDUAL_URI);
stmt.setDatatypeURI(TEST_DATA_TYPE_URI);
hash = RdfLiteralHash.makeRdfLiteralHash(stmt);
Assert.assertTrue(hash != 0);
stmt = new DataPropertyStatementImpl();
stmt.setData(TEST_VALUE);
stmt.setDatapropURI(TEST_DATA_PROP_URI);
stmt.setIndividualURI(TEST_INDIVIDUAL_URI);
stmt.setLanguage(TEST_LANG);
hash = RdfLiteralHash.makeRdfLiteralHash(stmt);
Assert.assertTrue(hash != 0);
}
@Test
public void testDoesStmtMatchHash() {
DataPropertyStatement stmtA = new DataPropertyStatementImpl();
DataPropertyStatement stmtB = new DataPropertyStatementImpl();
int expectedHash = 0;
stmtA.setData(TEST_VALUE);
stmtA.setDatapropURI(TEST_DATA_PROP_URI);
stmtA.setIndividualURI(TEST_INDIVIDUAL_URI);
expectedHash = RdfLiteralHash.makeRdfLiteralHash(stmtA);
stmtB.setData(TEST_VALUE);
stmtB.setDatapropURI(TEST_DATA_PROP_URI);
stmtB.setIndividualURI(TEST_INDIVIDUAL_URI);
Assert.assertTrue(expectedHash == RdfLiteralHash.makeRdfLiteralHash(stmtB) );
Assert.assertTrue( RdfLiteralHash.doesStmtMatchHash(stmtB, expectedHash));
stmtA = new DataPropertyStatementImpl();
stmtA.setData(TEST_VALUE);
stmtA.setDatapropURI(TEST_DATA_PROP_URI);
stmtA.setIndividualURI(TEST_INDIVIDUAL_URI);
stmtA.setDatatypeURI(TEST_DATA_TYPE_URI);
expectedHash = RdfLiteralHash.makeRdfLiteralHash(stmtA);
stmtB = new DataPropertyStatementImpl();
stmtB.setData(TEST_VALUE);
stmtB.setDatapropURI(TEST_DATA_PROP_URI);
stmtB.setIndividualURI(TEST_INDIVIDUAL_URI);
stmtB.setDatatypeURI(TEST_DATA_TYPE_URI);
Assert.assertTrue( expectedHash == RdfLiteralHash.makeRdfLiteralHash(stmtB) );
Assert.assertTrue( RdfLiteralHash.doesStmtMatchHash(stmtB, expectedHash));
stmtA = new DataPropertyStatementImpl();
stmtA.setData(TEST_VALUE);
stmtA.setDatapropURI(TEST_DATA_PROP_URI);
stmtA.setIndividualURI(TEST_INDIVIDUAL_URI);
stmtA.setLanguage(TEST_LANG);
expectedHash = RdfLiteralHash.makeRdfLiteralHash(stmtA);
stmtB = new DataPropertyStatementImpl();
stmtB.setData(TEST_VALUE);
stmtB.setDatapropURI(TEST_DATA_PROP_URI);
stmtB.setIndividualURI(TEST_INDIVIDUAL_URI);
stmtB.setLanguage(TEST_LANG);
Assert.assertTrue( expectedHash == RdfLiteralHash.makeRdfLiteralHash(stmtB) );
Assert.assertTrue( RdfLiteralHash.doesStmtMatchHash(stmtB, expectedHash));
Assert.assertTrue( ! RdfLiteralHash.doesStmtMatchHash(null, expectedHash) );
}
// @Test
// public void testGetDataPropertyStmtByHash() {
// DataPropertyStatement stmtA = new DataPropertyStatementImpl();
// IndividualImpl ind = new IndividualImpl();
// List<DataPropertyStatement> stmts = new ArrayList<DataPropertyStatement>();
//
// int expectedHash = 0;
//
// //test to see if the same subURI, predURI and Value can be distinguished by LANG/datatype
// stmtA.setData(TEST_VALUE);
// stmtA.setDatapropURI(TEST_DATA_PROP_URI);
// stmtA.setIndividualURI(TEST_INDIVIDUAL_URI);
// stmts.add(stmtA);
// int expectedHashForSimpleStmt = RdfLiteralHash.makeRdfLiteralHash(stmtA);
//
// stmtA = new DataPropertyStatementImpl();
// stmtA.setData(TEST_VALUE );
// stmtA.setDatapropURI(TEST_DATA_PROP_URI);
// stmtA.setIndividualURI(TEST_INDIVIDUAL_URI);
// stmtA.setDatatypeURI(TEST_DATA_TYPE_URI);
// int expectedHashForDatatypeStmt = RdfLiteralHash.makeRdfLiteralHash(stmtA);
// stmts.add(stmtA);
//
// stmtA = new DataPropertyStatementImpl();
// stmtA.setData(TEST_VALUE );
// stmtA.setDatapropURI(TEST_DATA_PROP_URI);
// stmtA.setIndividualURI(TEST_INDIVIDUAL_URI);
// stmtA.setLanguage(TEST_LANG);
// int expectedHashForLangStmt = RdfLiteralHash.makeRdfLiteralHash(stmtA);
// stmts.add(stmtA);
//
// ind.setDataPropertyStatements(stmts);
//
// DataPropertyStatement stmt = RdfLiteralHash.getDataPropertyStmtByHash(ind, expectedHashForLangStmt);
// Assert.assertNotNull(stmt);
// Assert.assertEquals(TEST_DATA_PROP_URI, stmt.getDatapropURI() );
// Assert.assertEquals(TEST_INDIVIDUAL_URI, stmt.getIndividualURI() );
// Assert.assertEquals(TEST_LANG, stmt.getLanguage() );
// Assert.assertEquals(TEST_VALUE, stmt.getData() );
// Assert.assertNull(stmt.getDatatypeURI());
//
// stmt = RdfLiteralHash.getDataPropertyStmtByHash(ind.getURI(), expectedHashForSimpleStmt);
// Assert.assertNotNull(stmt);
// Assert.assertEquals(TEST_DATA_PROP_URI, stmt.getDatapropURI() );
// Assert.assertEquals(TEST_INDIVIDUAL_URI, stmt.getIndividualURI() );
// Assert.assertEquals(TEST_VALUE, stmt.getData() );
// Assert.assertNull(stmt.getDatatypeURI());
// Assert.assertNull(stmt.getLanguage());
//
// stmt = RdfLiteralHash.getDataPropertyStmtByHash(ind, expectedHashForDatatypeStmt);
// Assert.assertNotNull(stmt);
// Assert.assertEquals(TEST_DATA_PROP_URI, stmt.getDatapropURI() );
// Assert.assertEquals(TEST_INDIVIDUAL_URI, stmt.getIndividualURI() );
// Assert.assertEquals(TEST_VALUE, stmt.getData() );
// Assert.assertEquals(TEST_DATA_TYPE_URI, stmt.getDatatypeURI() );
// Assert.assertNull(stmt.getLanguage());
//
//
// stmt = RdfLiteralHash.getDataPropertyStmtByHash(ind, 111111);
// Assert.assertNull(stmt);
//
// }
// @Test
// public void testGetRdfsLabelStatementByHash(){
//
// String n3 =
// "@prefix ex: <http://example.com/> . \n" +
// "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . \n"+
// "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n"+
// " ex:bob rdfs:label \"Smith, Bob\"^^<"+XSD.xstring.getURI()+"> ." ;
//
// Model model = (ModelFactory.createDefaultModel()).read(new StringReader(n3), "", "N3");
//
// Individual bob = new IndividualImpl();
// bob.setURI("http://example.com/bob");
//
// int hash = RdfLiteralHash.makeRdfsLabelLiteralHash(bob, "Smith, Bob", model);
// DataPropertyStatement stmt = RdfLiteralHash.getRdfsLabelStatementByHash(bob.getURI(), model, hash);
//
// String data = stmt.getData();
// String datatypeUri = stmt.getDatatypeURI();
// String predicateUri = stmt.getDatapropURI();
// String subjectUri = stmt.getIndividualURI();
//
// Assert.assertEquals("Smith, Bob", data);
// Assert.assertEquals(XSD.xstring.getURI(), datatypeUri);
// Assert.assertEquals(VitroVocabulary.LABEL, predicateUri);
// Assert.assertEquals("http://example.com/bob", subjectUri);
//
// }
}

View file

@ -0,0 +1,86 @@
/* $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;
/**
*/
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(FileServingHelper.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

@ -0,0 +1,225 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.filestorage.impl;
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

@ -0,0 +1,295 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.filestorage.impl;
import static edu.cornell.mannlib.vitro.webapp.filestorage.impl.FileStorageImpl.FILE_STORAGE_NAMESPACES_PROPERTIES;
import static edu.cornell.mannlib.vitro.webapp.filestorage.impl.FileStorageImpl.FILE_STORAGE_ROOT;
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;
import edu.cornell.mannlib.vitro.webapp.modules.fileStorage.FileAlreadyExistsException;
/**
* 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
// ----------------------------------------------------------------------
@SuppressWarnings("unused")
@Test(expected = IllegalArgumentException.class)
public void baseDirDoesntExist() throws IOException {
File baseDir = new File(tempDir, "doesntExist");
new FileStorageImpl(baseDir, EMPTY_NAMESPACES);
}
@SuppressWarnings("unused")
@Test(expected = IllegalStateException.class)
public void partialInitializationRoot() throws IOException {
File baseDir = new File(tempDir, "partialWithRoot");
baseDir.mkdir();
new File(baseDir, FILE_STORAGE_ROOT).mkdir();
new FileStorageImpl(baseDir, EMPTY_NAMESPACES);
}
@SuppressWarnings("unused")
@Test(expected = IllegalStateException.class)
public void partialInitializationNamespaces() throws IOException {
File baseDir = new File(tempDir, "partialWithNamespaces");
baseDir.mkdir();
new File(baseDir, 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(), 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

@ -0,0 +1,874 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.filters;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletResponse;
import org.junit.Assert;
import org.junit.Test;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import edu.cornell.mannlib.vitro.webapp.utils.NamespaceMapper;
public class URLRewritingHttpServletResponseTest {
/*
* Style A is for sites that are running at a URL like http://localhost:8080/vivo
* with no portals.
*/
protected void urlEncodingStyleA(String urlToEncode, String expectedUrlResult ){
URLRewritingHttpServletResponse urhsr = new URLRewritingHttpServletResponse(new stubs.javax.servlet.http.HttpServletResponseStub());
List<String>externalNamespaces = new ArrayList();
externalNamespaces.add("http://vivo.med.cornell.edu/individual/");
String actual = urhsr.encodeForVitro(urlToEncode, "UTF-8",
true, 1,
getMockNamespaceMapper(),
"http://vivo.cornell.edu/individual/",
externalNamespaces);
Assert.assertEquals(expectedUrlResult, actual);
}
/*
* Style A is for sites that are running behind apache httpd at a
* URL like http://caruso.mannlib.cornell.edu/ with no portals.
*/
protected void urlEncodingStyleB(String urlToEncode, String expectedUrlResult){
URLRewritingHttpServletResponse urhsr = new URLRewritingHttpServletResponse(new stubs.javax.servlet.http.HttpServletResponseStub());
List<String>externalNamespaces = new ArrayList();
externalNamespaces.add("http://vivo.med.cornell.edu/individual/");
String actual = urhsr.encodeForVitro(urlToEncode, "UTF-8",
true, 0,
getMockNamespaceMapper(),
"http://vivo.cornell.edu/individual/",
externalNamespaces);
Assert.assertEquals(expectedUrlResult, actual);
}
@Test
public void test40984(){ urlEncodingStyleA( "/vivo/js/jquery.js",
"/vivo/js/jquery.js"); }
@Test
public void test40988(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/getURLParam.js",
"/vivo/js/jquery_plugins/getURLParam.js"); }
@Test
public void test40994(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/colorAnimations.js",
"/vivo/js/jquery_plugins/colorAnimations.js"); }
@Test
public void test40995(){ urlEncodingStyleA(
"/vivo/js/propertyGroupSwitcher.js",
"/vivo/js/propertyGroupSwitcher.js"); }
@Test
public void test40996(){ urlEncodingStyleA( "/vivo/js/controls.js",
"/vivo/js/controls.js"); }
@Test
public void test40999(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/jquery.form.js",
"/vivo/js/jquery_plugins/jquery.form.js"); }
@Test
public void test41004(){ urlEncodingStyleA(
"/vivo/js/tiny_mce/tiny_mce.js", "/vivo/js/tiny_mce/tiny_mce.js"); }
@Test
public void test41133(){ urlEncodingStyleA(
"/vivo/entityEdit?uri=http%3a%2f%2fbogus.com%2findividual%2fn3671",
"/vivo/entityEdit?uri=http%3A%2F%2Fbogus.com%2Findividual%2Fn3671"); }
@Test
public void test41464(){ urlEncodingStyleA(
"/vivo/themes/vivo-basic/site_icons/visualization/ajax-loader.gif",
"/vivo/themes/vivo-basic/site_icons/visualization/ajax-loader.gif"); }
@Test
public void test41465(){ urlEncodingStyleA(
"/vivo/visualization?render_mode=dynamic&container=vis_container&vis=person_pub_count&vis_mode=short&uri=http%3a%2f%2fbogus.com%2findividual%2fn3671",
"/vivo/visualization?render_mode=dynamic&container=vis_container&vis=person_pub_count&vis_mode=short&uri=http%3A%2F%2Fbogus.com%2Findividual%2Fn3671");
}
@Test
public void test42110(){ urlEncodingStyleA(
"/vivo/js/imageUpload/imageUploadUtils.js",
"/vivo/js/imageUpload/imageUploadUtils.js"); }
@Test
public void test57982(){ urlEncodingStyleA(
"entityEdit?uri=http%3a%2f%2fxmlns.com%2ffoaf%2f0.1%2fAgent",
"entityEdit?uri=http%3A%2F%2Fxmlns.com%2Ffoaf%2F0.1%2FAgent");
}
@Test
public void test57983(){ urlEncodingStyleA(
"/vivo/vclassEdit?uri=http%3a%2f%2fxmlns.com%2ffoaf%2f0.1%2fAgent",
"/vivo/vclassEdit?uri=http%3A%2F%2Fxmlns.com%2Ffoaf%2F0.1%2FAgent"); }
@Test
public void test57986(){ urlEncodingStyleA(
"entityEdit?uri=http%3a%2f%2fxmlns.com%2ffoaf%2f0.1%2fPerson",
"entityEdit?uri=http%3A%2F%2Fxmlns.com%2Ffoaf%2F0.1%2FPerson");
}
@Test
public void test57987(){ urlEncodingStyleA(
"/vivo/vclassEdit?uri=http%3a%2f%2fxmlns.com%2ffoaf%2f0.1%2fPerson",
"/vivo/vclassEdit?uri=http%3A%2F%2Fxmlns.com%2Ffoaf%2F0.1%2FPerson");
}
@Test
public void test57988(){ urlEncodingStyleA(
"entityEdit?uri=http%3a%2f%2fwww.w3.org%2f2002%2f07%2fowl%23Thing",
"entityEdit?uri=http%3A%2F%2Fwww.w3.org%2F2002%2F07%2Fowl%23Thing");
}
@Test
public void test57989(){ urlEncodingStyleA(
"/vivo/vclassEdit?uri=http%3a%2f%2fwww.w3.org%2f2002%2f07%2fowl%23Thing",
"/vivo/vclassEdit?uri=http%3A%2F%2Fwww.w3.org%2F2002%2F07%2Fowl%23Thing");
}
@Test
public void test42083(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvivoweb.org%2fontology%2fcore%23Address",
"vclassEdit?uri=http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23Address");
}
@Test
public void test42084(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvivoweb.org%2fontology%2fcore%23DateTimeInterval",
"vclassEdit?uri=http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23DateTimeInterval");
}
@Test
public void test42085(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvivoweb.org%2fontology%2fcore%23URLLink",
"vclassEdit?uri=http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23URLLink");
}
@Test
public void test42086(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvivoweb.org%2fontology%2fcore%23AcademicDegree",
"vclassEdit?uri=http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23AcademicDegree");
}
@Test
public void test42087(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fpurl.org%2fontology%2fbibo%2fDocumentStatus",
"vclassEdit?uri=http%3A%2F%2Fpurl.org%2Fontology%2Fbibo%2FDocumentStatus");
}
@Test
public void test42088(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvivoweb.org%2fontology%2fcore%23DateTimeValuePrecision",
"vclassEdit?uri=http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23DateTimeValuePrecision");
}
@Test
public void test42089(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvivoweb.org%2fontology%2fcore%23DateTimeValue",
"vclassEdit?uri=http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23DateTimeValue");
}
@Test
public void test42090(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvivoweb.org%2fontology%2fcore%23Award",
"vclassEdit?uri=http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23Award");
}
@Test
public void test42091(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvivoweb.org%2fontology%2fcore%23Authorship",
"vclassEdit?uri=http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23Authorship");
}
@Test
public void test48256(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fxmlns.com%2ffoaf%2f0.1%2fPerson",
"vclassEdit?uri=http%3A%2F%2Fxmlns.com%2Ffoaf%2F0.1%2FPerson");
}
@Test
public void test11309(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvitro.mannlib.cornell.edu%2fns%2fbnode%23-43882498%3a12c1825c819%3a-7df6",
"vclassEdit?uri=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fns%2Fbnode%23-43882498%3A12c1825c819%3A-7df6");
}
@Test
public void test11310(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvitro.mannlib.cornell.edu%2fns%2fbnode%23-43882498%3a12c1825c819%3a-7e02",
"vclassEdit?uri=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fns%2Fbnode%23-43882498%3A12c1825c819%3A-7e02");
}
@Test
public void test11311(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvitro.mannlib.cornell.edu%2fns%2fbnode%23-43882498%3a12c1825c819%3a-7e09",
"vclassEdit?uri=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fns%2Fbnode%23-43882498%3A12c1825c819%3A-7e09");
}
@Test
public void test11312(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvitro.mannlib.cornell.edu%2fns%2fbnode%23-43882498%3a12c1825c819%3a-7df5",
"vclassEdit?uri=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fns%2Fbnode%23-43882498%3A12c1825c819%3A-7df5");
}
@Test
public void test11313(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvitro.mannlib.cornell.edu%2fns%2fbnode%23-43882498%3a12c1825c819%3a-7df4",
"vclassEdit?uri=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fns%2Fbnode%23-43882498%3A12c1825c819%3A-7df4");
}
@Test
public void test11314(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvitro.mannlib.cornell.edu%2fns%2fbnode%23-43882498%3a12c1825c819%3a-7df9",
"vclassEdit?uri=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fns%2Fbnode%23-43882498%3A12c1825c819%3A-7df9");
}
@Test
public void test11315(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvitro.mannlib.cornell.edu%2fns%2fbnode%23-43882498%3a12c1825c819%3a-7df8",
"vclassEdit?uri=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fns%2Fbnode%23-43882498%3A12c1825c819%3A-7df8");
}
@Test
public void test11317(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvitro.mannlib.cornell.edu%2fns%2fbnode%23-43882498%3a12c1825c819%3a-7df7",
"vclassEdit?uri=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fns%2Fbnode%23-43882498%3A12c1825c819%3A-7df7");
}
@Test
public void test11318(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fxmlns.com%2ffoaf%2f0.1%2fAgent",
"vclassEdit?uri=http%3A%2F%2Fxmlns.com%2Ffoaf%2F0.1%2FAgent");
}
@Test
public void test11319(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvivoweb.org%2fontology%2fcore%23Librarian",
"vclassEdit?uri=http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23Librarian");
}
@Test
public void test11320(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvivoweb.org%2fontology%2fcore%23Student",
"vclassEdit?uri=http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23Student");
}
@Test
public void test11321(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvivoweb.org%2fontology%2fcore%23NonAcademic",
"vclassEdit?uri=http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23NonAcademic");
}
@Test
public void test11322(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvivoweb.org%2fontology%2fcore%23NonFacultyAcademic",
"vclassEdit?uri=http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23NonFacultyAcademic");
}
@Test
public void test113222(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvivoweb.org%2fontology%2fcore%23FacultyMember",
"vclassEdit?uri=http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23FacultyMember");
}
@Test
public void test11323(){ urlEncodingStyleA(
"vclassEdit?uri=http%3a%2f%2fvivoweb.org%2fontology%2fcore%23EmeritusProfessor",
"vclassEdit?uri=http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23EmeritusProfessor");
}
@Test
public void test53543(){ urlEncodingStyleA(
"ingest?action=outputModel&modelName=http%3a%2f%2fvitro.mannlib.cornell.edu%2fdefault%2fvitro-kb-2",
"ingest?action=outputModel&modelName=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fdefault%2Fvitro-kb-2");
}
@Test
public void test53549(){ urlEncodingStyleA(
"ingest?action=outputModel&modelName=http%3a%2f%2fvitro.mannlib.cornell.edu%2fdefault%2fvitro-kb-inf",
"ingest?action=outputModel&modelName=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fdefault%2Fvitro-kb-inf");
}
@Test
public void test53555(){ urlEncodingStyleA(
"ingest?action=outputModel&modelName=http%3a%2f%2fvitro.mannlib.cornell.edu%2fdefault%2fvitro-kb-userAccounts",
"ingest?action=outputModel&modelName=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fdefault%2Fvitro-kb-userAccounts");
}
@Test
public void test53557(){ urlEncodingStyleA(
"ingest?action=outputModel&modelName=http%3a%2f%2fvitro.mannlib.cornell.edu%2fdefault%2fvitro-kb-displayMetadata",
"ingest?action=outputModel&modelName=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fdefault%2Fvitro-kb-displayMetadata");
}
@Test
public void test391499(){ urlEncodingStyleA(
"/vivo/edit/forms/css/customForm.css",
"/vivo/edit/forms/css/customForm.css"); }
@Test
public void test39149(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/thickbox/thickbox.css",
"/vivo/js/jquery_plugins/thickbox/thickbox.css"); }
@Test
public void test39153(){ urlEncodingStyleA(
"/vivo/edit/processRdfForm2.jsp", "/vivo/edit/processRdfForm2.jsp"); }
@Test
public void test39472(){ urlEncodingStyleA(
"/vivo/js/extensions/String.js", "/vivo/js/extensions/String.js"); }
@Test
public void test394730(){ urlEncodingStyleA( "/vivo/js/jquery.js",
"/vivo/js/jquery.js"); }
@Test
public void test39473(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/jquery.bgiframe.pack.js",
"/vivo/js/jquery_plugins/jquery.bgiframe.pack.js"); }
@Test
public void test39474(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/thickbox/thickbox-compressed.js",
"/vivo/js/jquery_plugins/thickbox/thickbox-compressed.js"); }
@Test
public void test39475(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/ui.datepicker.js",
"/vivo/js/jquery_plugins/ui.datepicker.js"); }
@Test
public void test14958(){ urlEncodingStyleA( "/vivo/js/jquery.js",
"/vivo/js/jquery.js"); }
@Test
public void test14968(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/getURLParam.js",
"/vivo/js/jquery_plugins/getURLParam.js"); }
@Test
public void test14972(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/colorAnimations.js",
"/vivo/js/jquery_plugins/colorAnimations.js"); }
@Test
public void test14979(){ urlEncodingStyleA(
"/vivo/js/propertyGroupSwitcher.js",
"/vivo/js/propertyGroupSwitcher.js"); }
@Test
public void test14980(){ urlEncodingStyleA( "/vivo/js/controls.js",
"/vivo/js/controls.js"); }
@Test
public void test14982(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/jquery.form.js",
"/vivo/js/jquery_plugins/jquery.form.js"); }
@Test
public void test14986(){ urlEncodingStyleA(
"/vivo/js/tiny_mce/tiny_mce.js", "/vivo/js/tiny_mce/tiny_mce.js"); }
@Test
public void test14999(){ urlEncodingStyleA(
"/vivo/entityEdit?uri=http%3a%2f%2fbogus.com%2findividual%2fn3671",
"/vivo/entityEdit?uri=http%3A%2F%2Fbogus.com%2Findividual%2Fn3671"); }
@Test
public void test15011(){ urlEncodingStyleA(
"/vivo/themes/vivo-basic/site_icons/visualization/ajax-loader.gif",
"/vivo/themes/vivo-basic/site_icons/visualization/ajax-loader.gif"); }
@Test
public void test15014(){ urlEncodingStyleA(
"/vivo/visualization?render_mode=dynamic&container=vis_container&vis=person_pub_count&vis_mode=short&uri=http%3a%2f%2fbogus.com%2findividual%2fn3671",
"/vivo/visualization?render_mode=dynamic&container=vis_container&vis=person_pub_count&vis_mode=short&uri=http%3A%2F%2Fbogus.com%2Findividual%2Fn3671");
}
@Test
public void test15143(){ urlEncodingStyleA(
"/vivo/js/imageUpload/imageUploadUtils.js",
"/vivo/js/imageUpload/imageUploadUtils.js"); }
@Test
public void test184670(){ urlEncodingStyleA(
"/vivo/js/jquery-ui/css/smoothness/jquery-ui-1.8.9.custom.css",
"/vivo/js/jquery-ui/css/smoothness/jquery-ui-1.8.9.custom.css"); }
@Test
public void test18467(){ urlEncodingStyleA(
"/vivo/edit/forms/css/customForm.css",
"/vivo/edit/forms/css/customForm.css"); }
@Test
public void test184680(){ urlEncodingStyleA(
"/vivo/edit/forms/css/customFormWithAutocomplete.css",
"/vivo/edit/forms/css/customFormWithAutocomplete.css"); }
@Test
public void test18468(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/thickbox/thickbox.css",
"/vivo/js/jquery_plugins/thickbox/thickbox.css"); }
@Test
public void test18472(){ urlEncodingStyleA(
"/vivo/edit/processRdfForm2.jsp", "/vivo/edit/processRdfForm2.jsp"); }
@Test
public void test18506(){ urlEncodingStyleA( "/vivo/individual?uri=",
"/vivo/individual?uri="); }
@Test
public void test18512(){ urlEncodingStyleA(
"/vivo/autocomplete?tokenize=true&stem=true",
"/vivo/autocomplete?tokenize=true&stem=true"); }
@Test
public void test18516(){ urlEncodingStyleA(
"/vivo/js/extensions/String.js", "/vivo/js/extensions/String.js"); }
@Test
public void test18543(){ urlEncodingStyleA( "/vivo/js/jquery.js",
"/vivo/js/jquery.js"); }
@Test
public void test185440(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/jquery.bgiframe.pack.js",
"/vivo/js/jquery_plugins/jquery.bgiframe.pack.js"); }
@Test
public void test18544(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/thickbox/thickbox-compressed.js",
"/vivo/js/jquery_plugins/thickbox/thickbox-compressed.js"); }
@Test
public void test18545(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/ui.datepicker.js",
"/vivo/js/jquery_plugins/ui.datepicker.js"); }
@Test
public void test18546(){ urlEncodingStyleA(
"/vivo/js/jquery-ui/js/jquery-ui-1.8.9.custom.min.js",
"/vivo/js/jquery-ui/js/jquery-ui-1.8.9.custom.min.js"); }
@Test
public void test185470(){ urlEncodingStyleA(
"/vivo/js/customFormUtils.js", "/vivo/js/customFormUtils.js"); }
@Test
public void test18547(){ urlEncodingStyleA(
"/vivo/edit/forms/js/customFormWithAutocomplete.js",
"/vivo/edit/forms/js/customFormWithAutocomplete.js"); }
@Test
public void test27127(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/thickbox/thickbox.css",
"/vivo/js/jquery_plugins/thickbox/thickbox.css"); }
@Test
public void test27130(){ urlEncodingStyleA(
"/vivo/edit/processDatapropRdfForm.jsp",
"/vivo/edit/processDatapropRdfForm.jsp"); }
@Test
public void test271590(){ urlEncodingStyleA(
"/vivo/js/extensions/String.js", "/vivo/js/extensions/String.js"); }
@Test
public void test27159(){ urlEncodingStyleA( "/vivo/js/jquery.js",
"/vivo/js/jquery.js"); }
@Test
public void test27160(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/jquery.bgiframe.pack.js",
"/vivo/js/jquery_plugins/jquery.bgiframe.pack.js"); }
@Test
public void test27161(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/thickbox/thickbox-compressed.js",
"/vivo/js/jquery_plugins/thickbox/thickbox-compressed.js"); }
@Test
public void test27166(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/ui.datepicker.js",
"/vivo/js/jquery_plugins/ui.datepicker.js"); }
@Test
public void test14842(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/thickbox/thickbox.css",
"/vivo/js/jquery_plugins/thickbox/thickbox.css"); }
@Test
public void test14846(){ urlEncodingStyleA(
"/vivo/edit/processDatapropRdfForm.jsp",
"/vivo/edit/processDatapropRdfForm.jsp"); }
@Test
public void test148510(){ urlEncodingStyleA(
"/vivo/js/extensions/String.js", "/vivo/js/extensions/String.js"); }
@Test
public void test14851(){ urlEncodingStyleA( "/vivo/js/jquery.js",
"/vivo/js/jquery.js"); }
@Test
public void test14852(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/jquery.bgiframe.pack.js",
"/vivo/js/jquery_plugins/jquery.bgiframe.pack.js"); }
@Test
public void test148530(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/thickbox/thickbox-compressed.js",
"/vivo/js/jquery_plugins/thickbox/thickbox-compressed.js"); }
@Test
public void test14853(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/ui.datepicker.js",
"/vivo/js/jquery_plugins/ui.datepicker.js"); }
@Test
public void test43748(){ urlEncodingStyleA(
"/vivo/js/jquery-ui/css/smoothness/jquery-ui-1.8.9.custom.css",
"/vivo/js/jquery-ui/css/smoothness/jquery-ui-1.8.9.custom.css"); }
@Test
public void test43749(){ urlEncodingStyleA(
"/vivo/edit/forms/css/customForm.css",
"/vivo/edit/forms/css/customForm.css"); }
@Test
public void test437500(){ urlEncodingStyleA(
"/vivo/edit/forms/css/customFormWithAutocomplete.css",
"/vivo/edit/forms/css/customFormWithAutocomplete.css"); }
@Test
public void test43750(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/thickbox/thickbox.css",
"/vivo/js/jquery_plugins/thickbox/thickbox.css"); }
@Test
public void test437540(){ urlEncodingStyleA(
"/vivo/edit/processRdfForm2.jsp", "/vivo/edit/processRdfForm2.jsp"); }
@Test
public void test43754(){ urlEncodingStyleA( "/vivo/individual?uri=",
"/vivo/individual?uri="); }
@Test
public void test43757(){ urlEncodingStyleA(
"/vivo/autocomplete?tokenize=true&stem=true",
"/vivo/autocomplete?tokenize=true&stem=true"); }
@Test
public void test43760(){ urlEncodingStyleA(
"/vivo/js/extensions/String.js", "/vivo/js/extensions/String.js"); }
@Test
public void test437610(){ urlEncodingStyleA( "/vivo/js/jquery.js",
"/vivo/js/jquery.js"); }
@Test
public void test43761(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/jquery.bgiframe.pack.js",
"/vivo/js/jquery_plugins/jquery.bgiframe.pack.js"); }
@Test
public void test43762(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/thickbox/thickbox-compressed.js",
"/vivo/js/jquery_plugins/thickbox/thickbox-compressed.js"); }
@Test
public void test437630(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/ui.datepicker.js",
"/vivo/js/jquery_plugins/ui.datepicker.js"); }
@Test
public void test43763(){ urlEncodingStyleA(
"/vivo/js/jquery-ui/js/jquery-ui-1.8.9.custom.min.js",
"/vivo/js/jquery-ui/js/jquery-ui-1.8.9.custom.min.js"); }
@Test
public void test437640(){ urlEncodingStyleA(
"/vivo/js/customFormUtils.js", "/vivo/js/customFormUtils.js"); }
@Test
public void test43764(){ urlEncodingStyleA(
"/vivo/edit/forms/js/customFormWithAutocomplete.js",
"/vivo/edit/forms/js/customFormWithAutocomplete.js"); }
@Test
public void test14550(){ urlEncodingStyleA(
"/vivo/js/jquery-ui/css/smoothness/jquery-ui-1.8.9.custom.css",
"/vivo/js/jquery-ui/css/smoothness/jquery-ui-1.8.9.custom.css"); }
@Test
public void test14551(){ urlEncodingStyleA(
"/vivo/edit/forms/css/customForm.css",
"/vivo/edit/forms/css/customForm.css"); }
@Test
public void test1455200(){ urlEncodingStyleA(
"/vivo/edit/forms/css/customFormWithAutocomplete.css",
"/vivo/edit/forms/css/customFormWithAutocomplete.css"); }
@Test
public void test14552(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/thickbox/thickbox.css",
"/vivo/js/jquery_plugins/thickbox/thickbox.css"); }
@Test
public void test14556(){ urlEncodingStyleA(
"/vivo/edit/processRdfForm2.jsp", "/vivo/edit/processRdfForm2.jsp"); }
@Test
public void test14557(){ urlEncodingStyleA( "/vivo/individual?uri=",
"/vivo/individual?uri="); }
@Test
public void test145610(){ urlEncodingStyleA(
"/vivo/autocomplete?tokenize=true&stem=true",
"/vivo/autocomplete?tokenize=true&stem=true"); }
@Test
public void test14561(){ urlEncodingStyleA( "/vivo/admin/sparqlquery",
"/vivo/admin/sparqlquery"); }
@Test
public void test14565(){ urlEncodingStyleA(
"/vivo/js/extensions/String.js", "/vivo/js/extensions/String.js"); }
@Test
public void test145650(){ urlEncodingStyleA( "/vivo/js/jquery.js",
"/vivo/js/jquery.js"); }
@Test
public void test145660(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/jquery.bgiframe.pack.js",
"/vivo/js/jquery_plugins/jquery.bgiframe.pack.js"); }
@Test
public void test14566(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/thickbox/thickbox-compressed.js",
"/vivo/js/jquery_plugins/thickbox/thickbox-compressed.js"); }
@Test
public void test14567(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/ui.datepicker.js",
"/vivo/js/jquery_plugins/ui.datepicker.js"); }
@Test
public void test145680(){ urlEncodingStyleA(
"/vivo/js/jquery-ui/js/jquery-ui-1.8.9.custom.min.js",
"/vivo/js/jquery-ui/js/jquery-ui-1.8.9.custom.min.js"); }
@Test
public void test14568(){ urlEncodingStyleA(
"/vivo/js/customFormUtils.js", "/vivo/js/customFormUtils.js"); }
@Test
public void test145690(){ urlEncodingStyleA(
"/vivo/js/browserUtils.js", "/vivo/js/browserUtils.js"); }
@Test
public void test14569(){ urlEncodingStyleA(
"/vivo/edit/forms/js/customFormWithAutocomplete.js",
"/vivo/edit/forms/js/customFormWithAutocomplete.js"); }
@Test
public void test29078(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/thickbox/thickbox.css",
"/vivo/js/jquery_plugins/thickbox/thickbox.css"); }
@Test
public void test29081(){ urlEncodingStyleA(
"/vivo/edit/processDatapropRdfForm.jsp",
"/vivo/edit/processDatapropRdfForm.jsp"); }
@Test
public void test29084(){ urlEncodingStyleA(
"/vivo/js/extensions/String.js", "/vivo/js/extensions/String.js"); }
@Test
public void test29085(){ urlEncodingStyleA( "/vivo/js/jquery.js",
"/vivo/js/jquery.js"); }
@Test
public void test290860(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/jquery.bgiframe.pack.js",
"/vivo/js/jquery_plugins/jquery.bgiframe.pack.js"); }
@Test
public void test29086(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/thickbox/thickbox-compressed.js",
"/vivo/js/jquery_plugins/thickbox/thickbox-compressed.js"); }
@Test
public void test29087(){ urlEncodingStyleA(
"/vivo/js/jquery_plugins/ui.datepicker.js",
"/vivo/js/jquery_plugins/ui.datepicker.js"); }
@Test
public void test35560(){ urlEncodingStyleB( "/js/jquery.js",
"/js/jquery.js"); }
@Test
public void test35562(){ urlEncodingStyleB(
"/js/jquery_plugins/getURLParam.js",
"/js/jquery_plugins/getURLParam.js"); }
@Test
public void test35564(){ urlEncodingStyleB(
"/js/jquery_plugins/colorAnimations.js",
"/js/jquery_plugins/colorAnimations.js"); }
@Test
public void test35568(){ urlEncodingStyleB(
"/js/propertyGroupSwitcher.js", "/js/propertyGroupSwitcher.js"); }
@Test
public void test35617(){ urlEncodingStyleB( "/js/controls.js",
"/js/controls.js"); }
@Test
public void test35618(){ urlEncodingStyleB(
"/js/jquery_plugins/jquery.form.js",
"/js/jquery_plugins/jquery.form.js"); }
@Test
public void test356180(){ urlEncodingStyleB(
"/js/tiny_mce/tiny_mce.js", "/js/tiny_mce/tiny_mce.js"); }
@Test
public void test37150(){ urlEncodingStyleB(
"/entityEdit?uri=http%3a%2f%2fbogus.com%2findividual%2fn3671",
"/entityEdit?uri=http%3A%2F%2Fbogus.com%2Findividual%2Fn3671"); }
@Test
public void test37402(){ urlEncodingStyleB(
"/themes/vivo-basic/site_icons/visualization/ajax-loader.gif",
"/themes/vivo-basic/site_icons/visualization/ajax-loader.gif"); }
@Test
public void test37403(){ urlEncodingStyleB(
"/visualization?render_mode=dynamic&container=vis_container&vis=person_pub_count&vis_mode=short&uri=http%3a%2f%2fbogus.com%2findividual%2fn3671",
"/visualization?render_mode=dynamic&container=vis_container&vis=person_pub_count&vis_mode=short&uri=http%3A%2F%2Fbogus.com%2Findividual%2Fn3671");
}
@Test
public void test38667(){ urlEncodingStyleB(
"/js/imageUpload/imageUploadUtils.js",
"/js/imageUpload/imageUploadUtils.js"); }
@Test
public void test47087(){ urlEncodingStyleB(
"entityEdit?uri=http%3a%2f%2fxmlns.com%2ffoaf%2f0.1%2fAgent",
"entityEdit?uri=http%3A%2F%2Fxmlns.com%2Ffoaf%2F0.1%2FAgent");
}
@Test
public void test47088(){ urlEncodingStyleB(
"/vclassEdit?uri=http%3a%2f%2fxmlns.com%2ffoaf%2f0.1%2fAgent",
"/vclassEdit?uri=http%3A%2F%2Fxmlns.com%2Ffoaf%2F0.1%2FAgent"); }
@Test
public void test470910(){ urlEncodingStyleB(
"entityEdit?uri=http%3a%2f%2fxmlns.com%2ffoaf%2f0.1%2fPerson",
"entityEdit?uri=http%3A%2F%2Fxmlns.com%2Ffoaf%2F0.1%2FPerson");
}
@Test
public void test47091(){ urlEncodingStyleB(
"/vclassEdit?uri=http%3a%2f%2fxmlns.com%2ffoaf%2f0.1%2fPerson",
"/vclassEdit?uri=http%3A%2F%2Fxmlns.com%2Ffoaf%2F0.1%2FPerson"); }
@Test
public void test470930(){ urlEncodingStyleB(
"entityEdit?uri=http%3a%2f%2fwww.w3.org%2f2002%2f07%2fowl%23Thing",
"entityEdit?uri=http%3A%2F%2Fwww.w3.org%2F2002%2F07%2Fowl%23Thing");
}
@Test
public void test47093(){ urlEncodingStyleB(
"/vclassEdit?uri=http%3a%2f%2fwww.w3.org%2f2002%2f07%2fowl%23Thing",
"/vclassEdit?uri=http%3A%2F%2Fwww.w3.org%2F2002%2F07%2Fowl%23Thing");
}
@Test
public void test04993(){ urlEncodingStyleB(
"vclassEdit?uri=http%3a%2f%2fvitro.mannlib.cornell.edu%2fns%2fbnode%23-20981c46%3a12c18866689%3a-7d2e",
"vclassEdit?uri=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fns%2Fbnode%23-20981c46%3A12c18866689%3A-7d2e");
}
@Test
public void test04994(){ urlEncodingStyleB(
"vclassEdit?uri=http%3a%2f%2fvitro.mannlib.cornell.edu%2fns%2fbnode%23-20981c46%3a12c18866689%3a-7dad",
"vclassEdit?uri=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fns%2Fbnode%23-20981c46%3A12c18866689%3A-7dad");
}
@Test
public void test04995(){ urlEncodingStyleB(
"vclassEdit?uri=http%3a%2f%2fvitro.mannlib.cornell.edu%2fns%2fbnode%23-20981c46%3a12c18866689%3a-7d31",
"vclassEdit?uri=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fns%2Fbnode%23-20981c46%3A12c18866689%3A-7d31");
}
@Test
public void test04996(){ urlEncodingStyleB(
"vclassEdit?uri=http%3a%2f%2fvitro.mannlib.cornell.edu%2fns%2fbnode%23-20981c46%3a12c18866689%3a-7db7",
"vclassEdit?uri=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fns%2Fbnode%23-20981c46%3A12c18866689%3A-7db7");
}
@Test
public void test04997(){ urlEncodingStyleB(
"vclassEdit?uri=http%3a%2f%2fvitro.mannlib.cornell.edu%2fns%2fbnode%23-20981c46%3a12c18866689%3a-7df2",
"vclassEdit?uri=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fns%2Fbnode%23-20981c46%3A12c18866689%3A-7df2");
}
@Test
public void test04999(){ urlEncodingStyleB(
"vclassEdit?uri=http%3a%2f%2fxmlns.com%2ffoaf%2f0.1%2fOrganization",
"vclassEdit?uri=http%3A%2F%2Fxmlns.com%2Ffoaf%2F0.1%2FOrganization");
}
@Test
public void test05000(){ urlEncodingStyleB(
"vclassEdit?uri=http%3a%2f%2fxmlns.com%2ffoaf%2f0.1%2fPerson",
"vclassEdit?uri=http%3A%2F%2Fxmlns.com%2Ffoaf%2F0.1%2FPerson");
}
@Test
public void test13898(){ urlEncodingStyleB(
"entityEdit?uri=http%3a%2f%2fvitro.mannlib.cornell.edu%2fns%2fvitro%2fpublic%23File",
"entityEdit?uri=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fns%2Fvitro%2Fpublic%23File");
}
@Test
public void test13899(){ urlEncodingStyleB(
"/vclassEdit?uri=http%3a%2f%2fvitro.mannlib.cornell.edu%2fns%2fvitro%2fpublic%23File",
"/vclassEdit?uri=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fns%2Fvitro%2Fpublic%23File");
}
@Test
public void test28454(){ urlEncodingStyleB(
"entityEdit?uri=http%3a%2f%2fwww.w3.org%2f2002%2f07%2fowl%23Thing",
"entityEdit?uri=http%3A%2F%2Fwww.w3.org%2F2002%2F07%2Fowl%23Thing");
}
@Test
public void test28458(){ urlEncodingStyleB(
"/vclassEdit?uri=http%3a%2f%2fwww.w3.org%2f2002%2f07%2fowl%23Thing",
"/vclassEdit?uri=http%3A%2F%2Fwww.w3.org%2F2002%2F07%2Fowl%23Thing");
}
@Test
public void test38687(){ urlEncodingStyleB(
"vclassEdit?uri=http%3a%2f%2fvitro.mannlib.cornell.edu%2fns%2fbnode%23-20981c46%3a12c18866689%3a-7d75",
"vclassEdit?uri=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fns%2Fbnode%23-20981c46%3A12c18866689%3A-7d75");
}
@Test
public void test38693(){ urlEncodingStyleB(
"vclassEdit?uri=http%3a%2f%2fvitro.mannlib.cornell.edu%2fns%2fbnode%23-20981c46%3a12c18866689%3a-7d76",
"vclassEdit?uri=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fns%2Fbnode%23-20981c46%3A12c18866689%3A-7d76");
}
@Test
public void test38694(){ urlEncodingStyleB(
"vclassEdit?uri=http%3a%2f%2fvivoweb.org%2fontology%2fcore%23AbstractInformation",
"vclassEdit?uri=http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23AbstractInformation");
}
@Test
public void test38695(){ urlEncodingStyleB(
"vclassEdit?uri=http%3a%2f%2fvitro.mannlib.cornell.edu%2fns%2fbnode%23-20981c46%3a12c18866689%3a-7d77",
"vclassEdit?uri=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fns%2Fbnode%23-20981c46%3A12c18866689%3A-7d77");
}
@Test
public void test38696(){ urlEncodingStyleB(
"vclassEdit?uri=http%3a%2f%2fpurl.org%2fontology%2fbibo%2fThesisDegree",
"vclassEdit?uri=http%3A%2F%2Fpurl.org%2Fontology%2Fbibo%2FThesisDegree");
}
@Test
public void test43123(){ urlEncodingStyleB(
"vclassEdit?uri=http%3a%2f%2fxmlns.com%2ffoaf%2f0.1%2fPerson",
"vclassEdit?uri=http%3A%2F%2Fxmlns.com%2Ffoaf%2F0.1%2FPerson");
}
@Test
public void test43124(){ urlEncodingStyleB(
"vclassEdit?uri=http%3a%2f%2fvivoweb.org%2fontology%2fcore%23Postdoc",
"vclassEdit?uri=http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23Postdoc");
}
@Test
public void test59983(){ urlEncodingStyleB(
"propertyEdit?uri=http%3a%2f%2fpurl.org%2fdc%2fterms%2fcontributor",
"propertyEdit?uri=http%3A%2F%2Fpurl.org%2Fdc%2Fterms%2Fcontributor");
}
@Test
public void test17004(){ urlEncodingStyleB(
"ingest?action=outputModel&modelName=http%3a%2f%2fvitro.mannlib.cornell.edu%2fdefault%2fvitro-kb-2",
"ingest?action=outputModel&modelName=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fdefault%2Fvitro-kb-2");
}
@Test
public void test17017(){ urlEncodingStyleB(
"ingest?action=outputModel&modelName=http%3a%2f%2fvitro.mannlib.cornell.edu%2fdefault%2fvitro-kb-inf",
"ingest?action=outputModel&modelName=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fdefault%2Fvitro-kb-inf");
}
@Test
public void test17021(){ urlEncodingStyleB(
"ingest?action=outputModel&modelName=http%3a%2f%2fvitro.mannlib.cornell.edu%2fdefault%2fvitro-kb-userAccounts",
"ingest?action=outputModel&modelName=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fdefault%2Fvitro-kb-userAccounts");
}
@Test
public void test17033(){ urlEncodingStyleB(
"ingest?action=outputModel&modelName=http%3a%2f%2fvitro.mannlib.cornell.edu%2fdefault%2fvitro-kb-displayMetadata",
"ingest?action=outputModel&modelName=http%3A%2F%2Fvitro.mannlib.cornell.edu%2Fdefault%2Fvitro-kb-displayMetadata");
}
public NamespaceMapper getMockNamespaceMapper(){
return new NamespaceMapper() {
@Override
public void removedStatements(Model arg0) {
// TODO Auto-generated method stub
}
@Override
public void removedStatements(StmtIterator arg0) {
// TODO Auto-generated method stub
}
@Override
public void removedStatements(List<Statement> arg0) {
// TODO Auto-generated method stub
}
@Override
public void removedStatements(Statement[] arg0) {
// TODO Auto-generated method stub
}
@Override
public void removedStatement(Statement arg0) {
// TODO Auto-generated method stub
}
@Override
public void notifyEvent(Model arg0, Object arg1) {
// TODO Auto-generated method stub
}
@Override
public void addedStatements(Model arg0) {
// TODO Auto-generated method stub
}
@Override
public void addedStatements(StmtIterator arg0) {
// TODO Auto-generated method stub
}
@Override
public void addedStatements(List<Statement> arg0) {
// TODO Auto-generated method stub
}
@Override
public void addedStatements(Statement[] arg0) {
// TODO Auto-generated method stub
}
@Override
public void addedStatement(Statement arg0) {
// TODO Auto-generated method stub
}
@Override
public List<String> getPrefixesForNamespace(String namespace) {
// TODO Auto-generated method stub
return null;
}
@Override
public String getPrefixForNamespace(String namespace) {
// TODO Auto-generated method stub
return null;
}
@Override
public String getNamespaceForPrefix(String prefix) {
// TODO Auto-generated method stub
return null;
}
};
}
}

View file

@ -0,0 +1,145 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.filters;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
public class VitroURLTest {
/**
* Test of beginsWithSlash method, of class VitroURL.
*/
@Test
public void testBeginsWithSlash()
{
String pathStr = "entity?home=1&uri=http://aims.fao.org/aos/geopolitical.owl#Afghanistan";
VitroURL instance = new VitroURL("", "UTF-8");
boolean expResult = false;
boolean result = instance.beginsWithSlash(pathStr);
assertEquals(expResult, result);
}
/**
* Test of endsInSlash method, of class VitroURL.
*/
@Test
public void testEndsInSlash()
{
String pathStr = "/entity?home=1&uri=http://aims.fao.org/aos/geopolitical.owl#Afghanistan";
VitroURL instance = new VitroURL("", "UTF-8");
boolean expResult = false;
boolean result = instance.endsInSlash(pathStr);
assertEquals(expResult, result);
}
/**
* Test of toString method, of class VitroURL.
* This test includes a Individual URI with a '=' and a '?'
* This test is from David Cliff via sourceforge.
*/
@Test
public void testToString()
{
String MelbUniStr = "/entity?home=1&uri=HTTPS://bida.themis.unimelb.edu.au/pls/apex/f?p=mrw2rdf:org:::::org_id:145";
VitroURL instance = new VitroURL(MelbUniStr, "UTF-8");
String expResult = "/entity?home=1&uri=HTTPS%3A%2F%2Fbida.themis.unimelb.edu.au%2Fpls%2Fapex%2Ff%3Fp%3Dmrw2rdf%3Aorg%3A%3A%3A%3A%3Aorg_id%3A145";
String result = instance.toString();
assertEquals(expResult, result);
String defaultTestStr = "/entity?home=1&uri=http://aims.fao.org/aos/geopolitical.owl#Afghanistan";
instance = new VitroURL(defaultTestStr, "UTF-8");
expResult = "/entity?home=1&uri=http%3A%2F%2Faims.fao.org%2Faos%2Fgeopolitical.owl%23Afghanistan";
result = instance.toString();
assertEquals(expResult, result);
}
/**
* This is a test similar to testToString()
* in that it has a = and a ? but it doesn't
* expect a double encoded URI.
*/
@Test
public void testWithEqualsSign(){
String MelbUniStr = "/entity?home=1&uri=HTTPS://bida.themis.unimelb.edu.au/pls/apex/f?p=mrw2rdf:org:::::org_id:145";
VitroURL instance = new VitroURL(MelbUniStr, "UTF-8");
String expResult ="/entity?home=1&uri=HTTPS%3A%2F%2Fbida.themis.unimelb.edu.au%2Fpls%2Fapex%2Ff%3Fp%3Dmrw2rdf%3Aorg%3A%3A%3A%3A%3Aorg_id%3A145";
assertEquals(expResult, instance.toString());
}
@Test
public void testParseQueryParams(){
//parseQueryParams
VitroURL instance = new VitroURL("stringNotImportant", "UTF-8");
List<String[]> result = instance.parseQueryParams("uri=HTTPS://bida.themis.unimelb.edu.au/pls/apex/f?p=mrw2rdf:org:::::org_id:145");
Assert.assertNotNull(result);
Assert.assertEquals(1, result.size());
Assert.assertNotNull(result.get(0));
Assert.assertEquals(2, result.get(0).length);
Assert.assertEquals("uri",result.get(0)[0]);
Assert.assertEquals("HTTPS://bida.themis.unimelb.edu.au/pls/apex/f?p=mrw2rdf:org:::::org_id:145",result.get(0)[1]);
}
@Test
public void testParseQueryParams2(){
//parseQueryParams
VitroURL instance = new VitroURL("stringNotImportant", "UTF-8");
List<String[]> result = instance.parseQueryParams("home=1&uri=HTTPS://bida.themis.unimelb.edu.au/pls/apex/f?p=mrw2rdf:org:::::org_id:145");
Assert.assertNotNull(result);
Assert.assertEquals(2, result.size());
Assert.assertNotNull(result.get(0));
Assert.assertEquals(2, result.get(0).length);
Assert.assertEquals("home",result.get(0)[0]);
Assert.assertEquals("1",result.get(0)[1]);
Assert.assertNotNull(result.get(1));
Assert.assertEquals(2, result.get(1).length);
Assert.assertEquals("uri",result.get(1)[0]);
Assert.assertEquals("HTTPS://bida.themis.unimelb.edu.au/pls/apex/f?p=mrw2rdf:org:::::org_id:145",result.get(1)[1]);
}
@Test
public void testParseQueryParams3(){
//parseQueryParams
VitroURL instance = new VitroURL("stringNotImportant", "UTF-8");
List<String[]> result = instance.parseQueryParams("home=1&uri=HTTPS://bida.edu.au/pls/apex/f?p=mrw2&additiona=234");
Assert.assertNotNull(result);
Assert.assertEquals(2, result.size());
Assert.assertNotNull(result.get(0));
Assert.assertEquals(2, result.get(0).length);
Assert.assertEquals("home",result.get(0)[0]);
Assert.assertEquals("1",result.get(0)[1]);
Assert.assertNotNull(result.get(1));
Assert.assertEquals(2, result.get(1).length);
Assert.assertEquals("uri",result.get(1)[0]);
Assert.assertEquals("HTTPS://bida.edu.au/pls/apex/f?p=mrw2&additiona=234",result.get(1)[1]);
}
@Test (expected=Error.class)
public void testParseQueryParams4(){
//parseQueryParams
VitroURL instance = new VitroURL("stringNotImportant", "UTF-8");
List<String[]> result = instance.parseQueryParams("home=1&shouldBeURI=HTTPS://bida.edu.au/pls/apex/f?p=mrw2&additiona=234");
Assert.assertNotNull(result);
Assert.assertEquals(2, result.size());
Assert.assertNotNull(result.get(0));
Assert.assertEquals(2, result.get(0).length);
Assert.assertEquals("home",result.get(0)[0]);
Assert.assertEquals("1",result.get(0)[1]);
Assert.assertNotNull(result.get(1));
Assert.assertEquals(2, result.get(1).length);
Assert.assertEquals("uri",result.get(1)[0]);
Assert.assertEquals("HTTPS://bida.edu.au/pls/apex/f?p=mrw2&additiona=234",result.get(1)[1]);
}
}

View file

@ -0,0 +1,360 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.freemarker.loader;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.SortedSet;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import edu.cornell.mannlib.vitro.webapp.freemarker.loader.FreemarkerTemplateLoader.PathPieces;
import edu.cornell.mannlib.vitro.webapp.freemarker.loader.FreemarkerTemplateLoader.PathPiecesFileVisitor;
/**
* TODO
*/
public class FreemarkerTemplateLoaderTest {
private PathPiecesFileVisitor visitor;
private String[] paths;
// ----------------------------------------------------------------------
// PathPieces tests
// ----------------------------------------------------------------------
@Test
public void ppLanguageRegionExtension() {
assertPathPieces("this_en_US.ftl", "this", "_en", "_US", ".ftl");
}
@Test
public void ppLanguageRegion() {
assertPathPieces("this_en_US", "this", "_en", "_US", "");
}
@Test
public void ppLanguageExtension() {
assertPathPieces("this_en.ftl", "this", "_en", "", ".ftl");
}
@Test
public void ppLanguage() {
assertPathPieces("this_en", "this", "_en", "", "");
}
@Test
public void ppDefaultExtension() {
assertPathPieces("this.ftl", "this", "", "", ".ftl");
}
@Test
public void ppDefault() {
assertPathPieces("this", "this", "", "", "");
}
@Test
public void ppExtraUnderscoreExtension() {
assertPathPieces("woo_hoo_en_US.ftl", "woo_hoo", "_en", "_US", ".ftl");
}
@Test
public void ppExtraUnderscore() {
assertPathPieces("woo_hoo_en_US", "woo_hoo", "_en", "_US", "");
}
// ----------------------------------------------------------------------
// Specific function tests
// ----------------------------------------------------------------------
@Test
public void baseAndExtensionMatch() {
paths("match-me.ftl");
assertMatches("match-me.ftl", 1, "match-me.ftl");
}
@Test
public void baseAndExtensionDontMatch() {
paths("match-me.ftl");
assertMatches("fail.ftl", 0, null);
assertMatches("match-me", 0, null);
assertMatches("match-me.FTL", 0, null);
}
@Test
public void matchRegardlessOfDepth() {
paths("short-path.ftl", "long/long-path.ftl");
assertMatches("long/short-path.ftl", 1, "short-path.ftl");
assertMatches("long-path.ftl", 1, "long/long-path.ftl");
}
@Test
public void preferShorterPath() {
paths("shorter-is-better", "long/shorter-is-better");
assertMatches("shorter-is-better", 2, "shorter-is-better");
}
@Test
public void preferShorterPathToExactPath() {
paths("shorter-is-better", "long/shorter-is-better");
assertMatches("long/shorter-is-better", 2, "shorter-is-better");
}
@Test
public void languageAndRegionMustMatchExactly() {
paths("this_es_MX.ftl", "this_es_ES.ftl", "this_es.ftl");
assertMatches("this_es_ES.ftl", 1, "this_es_ES.ftl");
}
@Test
public void languageAndRegionNoMatch() {
paths("this_es_MX.ftl", "this_es_ES.ftl", "this_es.ftl");
assertMatches("this_es_GO.ftl", 0, null);
}
@Test
public void languagePrefersExactMatch() {
paths("this_es_MX.ftl", "this_es.ftl", "this_es_ES.ftl");
assertMatches("this_es.ftl", 3, "this_es.ftl");
}
@Test
public void languageAcceptsApproximateMatch() {
paths("this_es_MX.ftl");
assertMatches("this_es.ftl", 1, "this_es_MX.ftl");
}
@Test
public void languagePrefersApproximateAlphabetical() {
paths("this_es_MX.ftl", "this_es_ES.ftl");
assertMatches("this_es.ftl", 2, "this_es_ES.ftl");
}
@Test
public void defaultPrefersExactMatch() {
paths("this_fr.ftl", "this.ftl", "this_fr_BE.ftl");
assertMatches("this.ftl", 3, "this.ftl");
}
@Test
public void defaultPrefersDefaultRegion() {
paths("this_fr_BE.ftl", "this_fr.ftl", "this_fr_CA.ftl");
assertMatches("this.ftl", 3, "this_fr.ftl");
}
@Test
public void defaultPrefersLanguageAlphabetical() {
paths("this_es.ftl", "this_fr.ftl");
assertMatches("this.ftl", 2, "this_es.ftl");
}
@Test
public void defaultPrefersRegionAlphabetical() {
paths("this_fr_BE.ftl", "this_fr_CA.ftl");
assertMatches("this.ftl", 2, "this_fr_BE.ftl");
}
// ----------------------------------------------------------------------
// Freemarker simulation tests
// ----------------------------------------------------------------------
public static final String[] FREEMARKER_TEST_PATHS = {
"long/this_fr_BE.ftl", "language_fr.ftl", "default.ftl",
"language-approx_en_US.ftl" };
@Test
public void freemarkerLangAndRegionExact() {
paths = FREEMARKER_TEST_PATHS;
assertFM("this_fr_BE.ftl", 1, "long/this_fr_BE.ftl");
}
@Test
public void freemarkerLangAndRegionMatchLang() {
paths = FREEMARKER_TEST_PATHS;
assertFM("language_fr_CA.ftl", 2, "language_fr.ftl");
}
@Test
public void freemarkerLangAndRegionMatchDefault() {
paths = FREEMARKER_TEST_PATHS;
assertFM("default_es_ES.ftl", 3, "default.ftl");
}
@Test
public void freemarkerLangAndRegionNoMatch() {
paths = FREEMARKER_TEST_PATHS;
assertFM("bogus_en_US.ftl", 3, null);
}
@Test
public void freemarkerLangExact() {
paths = FREEMARKER_TEST_PATHS;
assertFM("language_fr.ftl", 1, "language_fr.ftl");
}
@Test
public void freemarkerLangMatchLangAndRegion() {
paths = FREEMARKER_TEST_PATHS;
assertFM("language-approx_en.ftl", 1, "language-approx_en_US.ftl");
}
@Test
public void freemarkerLangMatchDefault() {
paths = FREEMARKER_TEST_PATHS;
assertFM("default_en.ftl", 2, "default.ftl");
}
@Test
public void freemarkerLangNoMatch() {
paths = FREEMARKER_TEST_PATHS;
assertFM("bogus_it.ftl", 2, null);
}
@Test
public void freemarkerDefaultExact() {
paths = FREEMARKER_TEST_PATHS;
assertFM("default.ftl", 1, "default.ftl");
}
@Test
public void freemarkerDefaultMatchLang() {
paths = FREEMARKER_TEST_PATHS;
assertFM("language.ftl", 1, "language_fr.ftl");
}
@Test
public void freemarkerDefaultMatchLangAndRegion() {
paths = FREEMARKER_TEST_PATHS;
assertFM("this.ftl", 1, "long/this_fr_BE.ftl");
}
@Test
public void freemarkerDefaultNoMatch() {
paths = FREEMARKER_TEST_PATHS;
assertFM("bogus.ftl", 1, null);
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
private void paths(String... p) {
this.paths = p;
}
private void assertPathPieces(String path, String base, String language,
String region, String extension) {
PathPieces pp = new PathPieces(path);
String[] expected = new String[] { base, language, region, extension };
String[] actual = new String[] { pp.base, pp.language, pp.region,
pp.extension };
assertEquals("pieces", Arrays.asList(expected), Arrays.asList(actual));
}
/**
* @param searchTerm
* template we are looking for
* @param expectedHowMany
* How many matches do we expect?
* @param expectedBestFit
* What should the best match turn out to be?
* @throws IOException
*/
private void assertMatches(String searchTerm, int expectedHowMany,
String expectedBestFitString) {
Path expectedBestFit = (expectedBestFitString == null) ? null : Paths
.get(expectedBestFitString);
SortedSet<PathPieces> matches = runTheVisitor(searchTerm);
int actualHowMany = matches.size();
Path actualBestFit = matches.isEmpty() ? null : matches.last().path;
if (expectedHowMany != actualHowMany) {
fail("How many results: expected " + expectedHowMany
+ ", but was " + actualHowMany + ": " + matches);
}
assertEquals("Best result", expectedBestFit, actualBestFit);
}
/**
* Try for exact match, then pare down if needed, just like Freemarker
* would.
*/
private void assertFM(String searchTerm, int expectedNumberOfTries,
String expectedBestString) {
Path expectedBestFit = expectedBestString == null ? null : Paths
.get(expectedBestString);
PathPieces stPp = new PathPieces(searchTerm);
int actualNumberOfTries = 0;
Path actualBestFit = null;
if (StringUtils.isNotBlank(stPp.region)) {
actualNumberOfTries++;
SortedSet<PathPieces> matches = runTheVisitor(stPp.base
+ stPp.language + stPp.region + stPp.extension);
if (!matches.isEmpty()) {
actualBestFit = matches.last().path;
}
}
if (actualBestFit == null && StringUtils.isNotBlank(stPp.language)) {
actualNumberOfTries++;
SortedSet<PathPieces> matches = runTheVisitor(stPp.base
+ stPp.language + stPp.extension);
if (!matches.isEmpty()) {
actualBestFit = matches.last().path;
}
}
if (actualBestFit == null) {
actualNumberOfTries++;
SortedSet<PathPieces> matches = runTheVisitor(stPp.base
+ stPp.extension);
if (!matches.isEmpty()) {
actualBestFit = matches.last().path;
}
}
assertEquals("How many tries", expectedNumberOfTries,
actualNumberOfTries);
assertEquals("best fit", expectedBestFit, actualBestFit);
}
private SortedSet<PathPieces> runTheVisitor(String searchTerm) {
try {
visitor = new PathPiecesFileVisitorStub(new PathPieces(searchTerm));
for (String p : this.paths) {
visitor.visitFile(Paths.get(p), null);
}
} catch (IOException e) {
fail("Failed: " + e);
}
return visitor.getMatches();
}
// ----------------------------------------------------------------------
// Helper classes
// ----------------------------------------------------------------------
/**
* We want to test the PathPiecesFileVisitor, but we can't have it checking
* to see whether the files actually exist.
*/
private static class PathPiecesFileVisitorStub extends
PathPiecesFileVisitor {
public PathPiecesFileVisitorStub(PathPieces searchTerm) {
super(searchTerm);
}
@Override
public boolean fileQualifies(Path path) {
return true;
}
}
}

View file

@ -0,0 +1,93 @@
package edu.cornell.mannlib.vitro.webapp.i18n;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
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.i18n.selection.SelectedLocale;
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
/**
* Test the I18N functionality.
*
* Start by checking the logic that finds approximate matches for
* language-specific property files.
*/
public class I18nTest extends AbstractTestClass {
private static final List<Locale> SELECTABLE_LOCALES = locales("es_MX",
"en_US");
ServletContextStub ctx;
@Before
public void setup() {
ctx = new ServletContextStub();
}
@Test
public void noMatchOnLanguageRegion() {
assertLocales("fr_CA", SELECTABLE_LOCALES, "fr_CA", "fr", "");
}
@Test
public void noMatchOnLanguage() {
assertLocales("fr", SELECTABLE_LOCALES, "fr", "");
}
@Test
public void noMatchOnRoot() {
assertLocales("", SELECTABLE_LOCALES, "");
}
@Test
public void matchOnLanguageRegion() {
assertLocales("es_ES", SELECTABLE_LOCALES, "es_ES", "es", "es_MX", "");
}
@Test
public void matchOnLanguage() {
assertLocales("es", SELECTABLE_LOCALES, "es", "es_MX", "");
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
private void assertLocales(String requested, List<Locale> selectable,
String... expected) {
SelectedLocale.setSelectableLocales(ctx, selectable);
List<Locale> expectedLocales = locales(expected);
I18n.ThemeBasedControl control = new I18n.ThemeBasedControl(ctx,
"bogusThemeDirectory");
List<Locale> actualLocales = control.getCandidateLocales(
"bogusBaseName", locale(requested));
assertEquals("Expected locales", expectedLocales, actualLocales);
}
private static List<Locale> locales(String... strings) {
List<Locale> locales = new ArrayList<>();
for (String s : strings) {
locales.add(locale(s));
}
return locales;
}
private static Locale locale(String s) {
String[] parts = s.split("_");
String language = (parts.length > 0) ? parts[0] : "";
String country = (parts.length > 1) ? parts[1] : "";
String variant = (parts.length > 2) ? parts[2] : "";
return new Locale(language, country, variant);
}
}

View file

@ -0,0 +1,314 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.i18n.selection;
import static edu.cornell.mannlib.vitro.webapp.i18n.selection.LocaleSelectionSetup.PROPERTY_FORCE_LOCALE;
import static edu.cornell.mannlib.vitro.webapp.i18n.selection.LocaleSelectionSetup.PROPERTY_SELECTABLE_LOCALES;
import static edu.cornell.mannlib.vitro.webapp.i18n.selection.SelectedLocale.ATTRIBUTE_NAME;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import javax.servlet.ServletContextEvent;
import org.apache.commons.lang.LocaleUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.log4j.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import stubs.edu.cornell.mannlib.vitro.webapp.config.ConfigurationPropertiesStub;
import stubs.edu.cornell.mannlib.vitro.webapp.startup.StartupStatusStub;
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.i18n.selection.SelectedLocale.ContextSelectedLocale;
/**
* TODO
*/
public class LocaleSelectionSetupTest extends AbstractTestClass {
// ----------------------------------------------------------------------
// Infrastructure
// ----------------------------------------------------------------------
private LocaleSelectionSetup lss;
private ServletContextStub ctx;
private ServletContextEvent sce;
private ConfigurationPropertiesStub props;
private StartupStatusStub ss;
private int[] expectedMessageCounts;
private Locale expectedForcedLocale;
private List<Locale> expectedSelectableLocales;
@Before
public void setup() {
// setLoggerLevel(LocaleSelectionSetup.class, Level.DEBUG);
// setLoggerLevel(StartupStatusStub.class, Level.DEBUG);
setLoggerLevel(ConfigurationProperties.class, Level.WARN);
ctx = new ServletContextStub();
sce = new ServletContextEvent(ctx);
props = new ConfigurationPropertiesStub();
props.setBean(ctx);
ss = new StartupStatusStub(ctx);
lss = new LocaleSelectionSetup();
}
@After
public void checkExpectations() {
if (expectedMessageCounts == null) {
fail("expecteMessages() was not called");
}
String message = compareMessageCount("info", ss.getInfoCount(),
expectedMessageCounts[0])
+ compareMessageCount("warning", ss.getWarningCount(),
expectedMessageCounts[1])
+ compareMessageCount("fatal", ss.getFatalCount(),
expectedMessageCounts[2])
+ checkForced()
+ checkSelectable();
if (!message.isEmpty()) {
fail(message);
}
}
private String compareMessageCount(String label, int actual, int expected) {
if (expected == actual) {
return "";
} else {
return "expecting " + expected + " " + label
+ " messages, but received " + actual + "; ";
}
}
private String checkForced() {
Locale actual = null;
Object o = ctx.getAttribute(ATTRIBUTE_NAME);
if (o instanceof ContextSelectedLocale) {
actual = ((ContextSelectedLocale) o).getForcedLocale();
}
Locale expected = expectedForcedLocale;
if (ObjectUtils.equals(expected, actual)) {
return "";
} else {
return "expected forced locale of " + expectedForcedLocale
+ ", but was " + actual + "; ";
}
}
private String checkSelectable() {
List<Locale> actual = Collections.emptyList();
Object o = ctx.getAttribute(ATTRIBUTE_NAME);
if (o instanceof ContextSelectedLocale) {
actual = ((ContextSelectedLocale) o).getSelectableLocales();
}
List<Locale> expected = expectedSelectableLocales;
if (expected == null) {
expected = Collections.emptyList();
}
if (ObjectUtils.equals(expected, actual)) {
return "";
} else {
return "expected selectable locales of " + expected + ", but was "
+ actual + "; ";
}
}
// ----------------------------------------------------------------------
// The tests
// ----------------------------------------------------------------------
// General functionality
@Test
public void neitherPropertyIsSpecified() {
lss.contextInitialized(sce);
expectMessages(1, 0, 0);
}
@Test
public void forceSuccessL() {
props.setProperty(PROPERTY_FORCE_LOCALE, "es");
lss.contextInitialized(sce);
expectForced("es");
expectMessages(1, 0, 0);
}
@Test
public void forceSuccessL_C() {
props.setProperty(PROPERTY_FORCE_LOCALE, "es_ES");
lss.contextInitialized(sce);
expectForced("es_ES");
expectMessages(1, 0, 0);
}
@Test
public void forceSuccessL_C_V() {
props.setProperty(PROPERTY_FORCE_LOCALE, "no_NO_NY");
lss.contextInitialized(sce);
expectForced("no_NO_NY");
expectMessages(1, 0, 0);
}
@Test
public void oneSelectable() {
props.setProperty(PROPERTY_SELECTABLE_LOCALES, "fr_FR");
lss.contextInitialized(sce);
expectSelectable("fr_FR");
expectMessages(1, 0, 0);
}
@Test
public void twoSelectables() {
props.setProperty(PROPERTY_SELECTABLE_LOCALES, "fr_FR, es_PE");
lss.contextInitialized(sce);
expectSelectable("fr_FR", "es_PE");
expectMessages(1, 0, 0);
}
@Test
public void bothPropertiesAreSpecified() {
props.setProperty(PROPERTY_FORCE_LOCALE, "es_ES");
props.setProperty(PROPERTY_SELECTABLE_LOCALES, "fr_FR");
lss.contextInitialized(sce);
expectForced("es_ES");
expectMessages(1, 1, 0);
}
// Locale string syntax (common to both force and selectable)
@Test
public void langaugeIsEmpty() {
props.setProperty(PROPERTY_FORCE_LOCALE, "_ES");
lss.contextInitialized(sce);
expectMessages(0, 1, 0);
}
@Test
public void languageWrongLength() {
props.setProperty(PROPERTY_FORCE_LOCALE, "e_ES");
lss.contextInitialized(sce);
expectMessages(0, 1, 0);
}
@Test
public void languageNotAlphabetic() {
props.setProperty(PROPERTY_FORCE_LOCALE, "e4_ES");
lss.contextInitialized(sce);
expectMessages(0, 1, 0);
}
@Test
public void languageNotLowerCase() {
props.setProperty(PROPERTY_FORCE_LOCALE, "eS_ES");
lss.contextInitialized(sce);
expectMessages(0, 1, 0);
}
@Test
public void countryIsEmpty() {
props.setProperty(PROPERTY_FORCE_LOCALE, "es_ _13");
lss.contextInitialized(sce);
expectMessages(0, 1, 0);
}
@Test
public void countryWrongLength() {
props.setProperty(PROPERTY_FORCE_LOCALE, "es_ESS");
lss.contextInitialized(sce);
expectMessages(0, 1, 0);
}
@Test
public void countryNotAlphabetic() {
props.setProperty(PROPERTY_FORCE_LOCALE, "es_E@");
lss.contextInitialized(sce);
expectMessages(0, 1, 0);
}
@Test
public void countryNotUpperCase() {
props.setProperty(PROPERTY_FORCE_LOCALE, "es_es");
lss.contextInitialized(sce);
expectMessages(0, 1, 0);
}
@Test
public void variantIsEmpty() {
props.setProperty(PROPERTY_FORCE_LOCALE, "es_ES_");
lss.contextInitialized(sce);
expectMessages(0, 1, 0);
}
@Test
public void funkyVariantIsAcceptable() {
props.setProperty(PROPERTY_FORCE_LOCALE, "es_ES_123_aa");
lss.contextInitialized(sce);
expectForced("es_ES_123_aa");
expectMessages(1, 1, 0);
}
@Test
public void localeNotRecognizedProducesWarning() {
props.setProperty(PROPERTY_FORCE_LOCALE, "es_FR");
lss.contextInitialized(sce);
expectForced("es_FR");
expectMessages(1, 1, 0);
}
// Syntax of selectable property
@Test
public void emptySelectableLocaleProducesWarning() {
props.setProperty(PROPERTY_SELECTABLE_LOCALES, "es_ES, , fr_FR");
lss.contextInitialized(sce);
expectSelectable("es_ES", "fr_FR");
expectMessages(1, 1, 0);
}
@Test
public void blanksAroundCommasAreIgnored() {
props.setProperty(PROPERTY_SELECTABLE_LOCALES, "es_ES,en_US \t , fr_FR");
lss.contextInitialized(sce);
expectSelectable("es_ES", "en_US", "fr_FR");
expectMessages(1, 0, 0);
}
// ----------------------------------------------------------------------
// helper methods
// ----------------------------------------------------------------------
private void expectMessages(int infoCount, int warningCount, int fatalCount) {
this.expectedMessageCounts = new int[] { infoCount, warningCount,
fatalCount };
}
private void expectForced(String localeString) {
this.expectedForcedLocale = stringToLocale(localeString);
}
private void expectSelectable(String... strings) {
List<Locale> list = new ArrayList<Locale>();
for (String string : strings) {
list.add(stringToLocale(string));
}
this.expectedSelectableLocales = list;
}
private Locale stringToLocale(String string) {
return LocaleUtils.toLocale(string);
}
}

View file

@ -0,0 +1,135 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.imageprocessor.jai;
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.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.imageprocessor.jai.JaiImageProcessor;
import edu.cornell.mannlib.vitro.webapp.modules.imageProcessor.ImageProcessor.CropRectangle;
import edu.cornell.mannlib.vitro.webapp.modules.imageProcessor.ImageProcessor.Dimensions;
/**
* 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 JaiImageProcessorTester extends Frame {
/** Big enough to hold the JPEG file, certainly. */
private final static int BUFFER_SIZE = 200 * 200 * 4;
private final static Dimensions THUMBNAIL_SIZE = new Dimensions(
THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
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 JaiImageProcessor thumbnailer = new JaiImageProcessor();
@SuppressWarnings("deprecation")
private JaiImageProcessorTester() {
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, THUMBNAIL_SIZE));
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;
}
@SuppressWarnings("unused")
public static void main(String[] args) {
Logger.getLogger(JaiImageProcessor.class).setLevel(Level.DEBUG);
new JaiImageProcessorTester();
}
private static class ImageCropData {
final String filename;
final CropRectangle crop;
ImageCropData(String filename, int x, int y, int size) {
this.filename = filename;
this.crop = new CropRectangle(x, y, size,
size);
}
}
private class CloseWindowListener extends WindowAdapter {
@Override
public void windowClosing(WindowEvent e) {
setVisible(false);
dispose();
System.exit(0);
}
}
}

View file

@ -0,0 +1,271 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.imageprocessor.jai;
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.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.imageprocessor.jai.JaiImageProcessorTester2.CropDataSet.CropData;
import edu.cornell.mannlib.vitro.webapp.imageprocessor.jai.JaiImageProcessor.NonNoisyImagingListener;
import edu.cornell.mannlib.vitro.webapp.modules.imageProcessor.ImageProcessor.CropRectangle;
import edu.cornell.mannlib.vitro.webapp.modules.imageProcessor.ImageProcessor.Dimensions;
/**
* 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 JaiImageProcessorTester2 extends Frame {
private static final Log log = LogFactory
.getLog(JaiImageProcessorTester2.class);
private static final int ROWS = 6;
private static final int COLUMNS = 9;
private static final int EDGE_THRESHOLD = 6000;
private static final Dimensions THUMBNAIL_SIZE = new Dimensions(200, 200);
/** Keep things quiet. */
static {
JAI.getDefaultInstance().setImagingListener(
new NonNoisyImagingListener());
}
private final String imagePath;
private final JaiImageProcessor thumbnailer;
public JaiImageProcessorTester2(String imagePath,
CropDataSet cropDataSet) {
this.imagePath = imagePath;
this.thumbnailer = new JaiImageProcessor();
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 javax.media.jai.widget.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, THUMBNAIL_SIZE);
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(JaiImageProcessor.class).setLevel(Level.DEBUG);
Logger.getLogger(JaiImageProcessorTester2.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 JaiImageProcessorTester2(
"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

@ -0,0 +1,224 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.modelaccess.adapters;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import stubs.com.hp.hpl.jena.rdf.model.ModelMaker.ModelMakerStub;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.ModelMaker;
import com.hp.hpl.jena.rdf.model.ModelReader;
import com.hp.hpl.jena.shared.AlreadyExistsException;
import com.hp.hpl.jena.shared.CannotCreateException;
import com.hp.hpl.jena.shared.DoesNotExistException;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
/**
* Test the functions of a ListCachingModelMaker. Does it properly register the
* presence of a model with no triples?
*/
public class ListCachingModelMakerTest extends AbstractTestClass {
private static final String URI_ONE = "http://model.one";
private static final String URI_TWO = "http://model.two";
private static final String URI_NONE = "http://model.does.not.exist";
private static final Model MODEL_ONE = createModel();
private static final Model MODEL_TWO = createModel();
private static final Model MODEL_DEFAULT = createModel();
private static final Model MODEL_FRESH = createModel();
private ModelMaker rigorous;
private ModelMaker relaxed;
private ModelMaker mm;
private ModelReader modelReader;
private static Model createModel() {
return ModelFactory.createDefaultModel();
}
@Before
public void setup() {
rigorous = ModelMakerStub.rigorous(MODEL_DEFAULT, MODEL_FRESH)
.put(URI_ONE, MODEL_ONE).put(URI_TWO, MODEL_TWO);
relaxed = ModelMakerStub.relaxed(MODEL_DEFAULT, MODEL_FRESH)
.put(URI_ONE, MODEL_ONE).put(URI_TWO, MODEL_TWO);
relaxed(); // call rigorous() to override, if desired.
}
// ----------------------------------------------------------------------
// The tests
// ----------------------------------------------------------------------
@SuppressWarnings("unused")
@Test(expected = NullPointerException.class)
public void nullInnerModel() {
new ListCachingModelMaker(null);
}
@Test
public void listModels() {
assertList(URI_ONE, URI_TWO);
}
@Test
public void hasModelExist() {
assertTrue(mm.hasModel(URI_ONE));
}
@Test
public void hasModelNonExist() {
assertFalse(mm.hasModel(URI_NONE));
}
@Test
public void createModelExist() {
assertEquals(MODEL_ONE, mm.createModel(URI_ONE));
assertList(URI_ONE, URI_TWO);
}
@Test
public void createModelNonExist() {
assertEquals(MODEL_FRESH, mm.createModel(URI_NONE));
assertList(URI_ONE, URI_TWO, URI_NONE);
}
@Test(expected = AlreadyExistsException.class)
public void createModelStrictExist() {
mm.createModel(URI_ONE, true);
}
@Test
public void createModelStrictNonExist() {
assertEquals(MODEL_FRESH, mm.createModel(URI_NONE, true));
assertList(URI_ONE, URI_TWO, URI_NONE);
}
@Test
public void openModelExist() {
assertEquals(MODEL_TWO, mm.openModel(URI_TWO));
assertList(URI_ONE, URI_TWO);
}
@Test(expected = DoesNotExistException.class)
public void openModelRigorousNonExist() {
rigorous();
mm.openModel(URI_NONE);
}
@Test
public void openModelRelaxedNonExist() {
assertEquals(MODEL_FRESH, mm.openModel(URI_NONE));
assertList(URI_ONE, URI_TWO, URI_NONE);
}
@Test
public void openModelIfPresentExist() {
assertEquals(MODEL_TWO, mm.openModelIfPresent(URI_TWO));
assertList(URI_ONE, URI_TWO);
}
@Test
public void openModelIfPresentNonExist() {
assertNull(mm.openModelIfPresent(URI_NONE));
assertList(URI_ONE, URI_TWO);
}
@Test
public void openModelStrictExist() {
assertEquals(MODEL_ONE, mm.openModel(URI_ONE, true));
assertList(URI_ONE, URI_TWO);
}
@Test
public void openModelNonStrictExist() {
assertEquals(MODEL_ONE, mm.openModel(URI_ONE, false));
assertList(URI_ONE, URI_TWO);
}
@Test
public void openModelNonStrictNonExist() {
assertEquals(MODEL_FRESH, mm.openModel(URI_NONE, false));
assertList(URI_ONE, URI_TWO, URI_NONE);
}
@Test
public void removeModelExist() {
mm.removeModel(URI_ONE);
assertList(URI_TWO);
}
@Test(expected = DoesNotExistException.class)
public void removeModelNonExist() {
mm.removeModel(URI_NONE);
}
@Test
public void getModelExist() {
assertEquals(MODEL_TWO, mm.getModel(URI_TWO));
assertList(URI_ONE, URI_TWO);
}
@Test
public void getModelRigorousNonExist() {
rigorous();
assertNull(mm.getModel(URI_NONE));
assertList(URI_ONE, URI_TWO);
}
@Test
public void getModelRelaxedNonExist() {
assertEquals(MODEL_FRESH, mm.getModel(URI_NONE));
assertList(URI_ONE, URI_TWO, URI_NONE);
}
@Test
public void getModelLoadIfAbsentExist() {
assertEquals(MODEL_TWO, mm.getModel(URI_TWO, modelReader));
assertList(URI_ONE, URI_TWO);
}
@Test(expected = CannotCreateException.class)
public void getModelLoadIfAbsentRigorousNonExist() {
rigorous();
mm.getModel(URI_NONE, modelReader);
}
@Test
public void getModelLoadIfAbsentRelaxedNonExist() {
assertEquals(MODEL_FRESH, mm.getModel(URI_NONE, modelReader));
assertList(URI_ONE, URI_TWO, URI_NONE);
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
private void relaxed() {
mm = new ListCachingModelMaker(relaxed);
}
private void rigorous() {
mm = new ListCachingModelMaker(rigorous);
}
private void assertList(String... expectedArray) {
Set<String> expected = new HashSet<>(Arrays.asList(expectedArray));
Set<String> actual = mm.listModels().toSet();
assertEquals(expected, actual);
}
}

View file

@ -0,0 +1,175 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.modelaccess.adapters;
import static org.junit.Assert.assertEquals;
import java.io.StringReader;
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.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import stubs.com.hp.hpl.jena.rdf.model.ModelMaker.ModelMakerStub;
import com.hp.hpl.jena.graph.Graph;
import com.hp.hpl.jena.graph.impl.CollectionGraph;
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.ResourceFactory;
import com.hp.hpl.jena.rdf.model.Statement;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
/**
* Checks the function of a MemoryMappingModelMaker, testing the difference in
* behavior between an mapped model and an unmapped model.
*/
public class MemoryMappingModelMakerTest extends AbstractTestClass {
private static final String URI_MAPPED = "http://memory.mapped.model";
private static final String URI_UNMAPPED = "http://unmapped.model";
private static final String MODEL_CONTENTS = "@prefix : <http://z#> . \n"
+ ":a :b :c .";
private GraphModelStructure unmapped;
private GraphModelStructure mapped;
private ModelMakerStub innerModelMaker;
private MemoryMappingModelMaker mmmm;
@Before
public void setup() {
unmapped = new GraphModelStructure(URI_UNMAPPED, MODEL_CONTENTS);
mapped = new GraphModelStructure(URI_MAPPED, MODEL_CONTENTS);
innerModelMaker = ModelMakerStub.rigorous(createModel(), createModel());
innerModelMaker.put(mapped.uri, mapped.model);
innerModelMaker.put(unmapped.uri, unmapped.model);
mmmm = new MemoryMappingModelMaker(innerModelMaker, mapped.uri);
unmapped.methodCalls.clear();
mapped.methodCalls.clear();
}
// ----------------------------------------------------------------------
// tests
// ----------------------------------------------------------------------
@Test
public void unmappedRead() {
assertModelContents(unmapped, "[http://z#a, http://z#b, http://z#c]");
assertMethodCalls(unmapped, "find");
}
@Test
public void mappedRead() {
assertModelContents(mapped, "[http://z#a, http://z#b, http://z#c]");
assertMethodCalls(mapped);
}
@Test
public void unmappedWrite() {
mmmm.openModel(URI_UNMAPPED).add(newStatement());
assertModelContents(unmapped, "[http://z#a, http://z#b, http://z#c]",
"[http://z#new, http://z#to, http://z#you]");
assertMethodCalls(unmapped, "add", "find");
}
@Test
public void mappedWrite() {
mmmm.openModel(URI_MAPPED).add(newStatement());
assertModelContents(mapped, "[http://z#a, http://z#b, http://z#c]",
"[http://z#new, http://z#to, http://z#you]");
assertMethodCalls(mapped, "add");
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
private static Model createModel() {
return ModelFactory.createDefaultModel();
}
private void assertModelContents(GraphModelStructure gms,
String... expected) {
Set<Statement> stmts = mmmm.openModel(gms.uri).listStatements().toSet();
assertStatements(stmts, expected);
}
private void assertStatements(Set<Statement> stmts, String... expected) {
Set<String> actual = new HashSet<>();
for (Statement stmt : stmts) {
actual.add(stmt.toString());
}
assertEquals(new HashSet<>(Arrays.asList(expected)), actual);
}
private void assertMethodCalls(GraphModelStructure gms, String... expected) {
assertEquals(Arrays.asList(expected), gms.methodCalls);
}
public Statement newStatement() {
Resource s = ResourceFactory.createResource("http://z#new");
Property p = ResourceFactory.createProperty("http://z#to");
Resource o = ResourceFactory.createResource("http://z#you");
return ResourceFactory.createStatement(s, p, o);
}
// ----------------------------------------------------------------------
// Helper classes
// ----------------------------------------------------------------------
private static class GraphModelStructure {
final String uri;
final Graph graph;
final List<String> methodCalls;
final RecordingInvocationHandler handler;
final Graph proxy;
final Model model;
public GraphModelStructure(String uri, String contents) {
this.uri = uri;
graph = new CollectionGraph();
methodCalls = new ArrayList<>();
handler = new RecordingInvocationHandler(graph, methodCalls);
proxy = wrapGraph();
model = ModelFactory.createModelForGraph(proxy);
model.read(new StringReader(contents), null, "TURTLE");
}
private Graph wrapGraph() {
ClassLoader classLoader = Model.class.getClassLoader();
Class<?>[] interfaces = new Class<?>[] { Graph.class };
return (Graph) Proxy.newProxyInstance(classLoader, interfaces,
handler);
}
}
private static class RecordingInvocationHandler implements
InvocationHandler {
private final Object inner;
private final List<String> methodCalls;
public RecordingInvocationHandler(Object inner, List<String> methodCalls) {
this.inner = inner;
this.methodCalls = methodCalls;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
methodCalls.add(method.getName());
return method.invoke(inner, args);
}
}
}

View file

@ -0,0 +1,223 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.modelaccess.adapters;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import stubs.com.hp.hpl.jena.rdf.model.ModelMaker.ModelMakerStub;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.ModelMaker;
import com.hp.hpl.jena.rdf.model.ModelReader;
import com.hp.hpl.jena.shared.AlreadyExistsException;
import com.hp.hpl.jena.shared.CannotCreateException;
import com.hp.hpl.jena.shared.DoesNotExistException;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
/**
* Test the functions of a ModelMakerWithPersistentEmptyModels. Does it properly register the
* presence of a model with no triples?
*/
public class ModelMakerWithPersistentEmptyModelsTest extends AbstractTestClass {
private static final String URI_ONE = "http://model.one";
private static final String URI_TWO = "http://model.two";
private static final String URI_NONE = "http://model.does.not.exist";
private static final Model MODEL_ONE = createModel();
private static final Model MODEL_TWO = createModel();
private static final Model MODEL_DEFAULT = createModel();
private static final Model MODEL_FRESH = createModel();
private ModelMaker rigorous;
private ModelMaker relaxed;
private ModelMaker mm;
private ModelReader modelReader;
private static Model createModel() {
return ModelFactory.createDefaultModel();
}
@Before
public void setup() {
rigorous = ModelMakerStub.rigorous(MODEL_DEFAULT, MODEL_FRESH)
.put(URI_ONE, MODEL_ONE).put(URI_TWO, MODEL_TWO);
relaxed = ModelMakerStub.relaxed(MODEL_DEFAULT, MODEL_FRESH)
.put(URI_ONE, MODEL_ONE).put(URI_TWO, MODEL_TWO);
relaxed(); // call rigorous() to override, if desired.
}
// ----------------------------------------------------------------------
// The tests
// ----------------------------------------------------------------------
@SuppressWarnings("unused")
@Test(expected = NullPointerException.class)
public void nullInnerModel() {
new ModelMakerWithPersistentEmptyModels(null);
}
@Test
public void listModels() {
assertList(URI_ONE, URI_TWO);
}
@Test
public void hasModelExist() {
assertTrue(mm.hasModel(URI_ONE));
}
@Test
public void hasModelNonExist() {
assertFalse(mm.hasModel(URI_NONE));
}
@Test
public void createModelExist() {
assertEquals(MODEL_ONE, mm.createModel(URI_ONE));
assertList(URI_ONE, URI_TWO);
}
@Test
public void createModelNonExist() {
assertEquals(MODEL_FRESH, mm.createModel(URI_NONE));
assertList(URI_ONE, URI_TWO, URI_NONE);
}
@Test(expected = AlreadyExistsException.class)
public void createModelStrictExist() {
mm.createModel(URI_ONE, true);
}
@Test
public void createModelStrictNonExist() {
assertEquals(MODEL_FRESH, mm.createModel(URI_NONE, true));
assertList(URI_ONE, URI_TWO, URI_NONE);
}
@Test
public void openModelExist() {
assertEquals(MODEL_TWO, mm.openModel(URI_TWO));
assertList(URI_ONE, URI_TWO);
}
@Test(expected = DoesNotExistException.class)
public void openModelRigorousNonExist() {
rigorous();
mm.openModel(URI_NONE);
}
@Test
public void openModelRelaxedNonExist() {
assertEquals(MODEL_FRESH, mm.openModel(URI_NONE));
assertList(URI_ONE, URI_TWO, URI_NONE);
}
@Test
public void openModelIfPresentExist() {
assertEquals(MODEL_TWO, mm.openModelIfPresent(URI_TWO));
assertList(URI_ONE, URI_TWO);
}
@Test
public void openModelIfPresentNonExist() {
assertNull(mm.openModelIfPresent(URI_NONE));
assertList(URI_ONE, URI_TWO);
}
@Test
public void openModelStrictExist() {
assertEquals(MODEL_ONE, mm.openModel(URI_ONE, true));
assertList(URI_ONE, URI_TWO);
}
@Test
public void openModelNonStrictExist() {
assertEquals(MODEL_ONE, mm.openModel(URI_ONE, false));
assertList(URI_ONE, URI_TWO);
}
@Test
public void openModelNonStrictNonExist() {
assertEquals(MODEL_FRESH, mm.openModel(URI_NONE, false));
assertList(URI_ONE, URI_TWO, URI_NONE);
}
@Test
public void removeModelExist() {
mm.removeModel(URI_ONE);
assertList(URI_TWO);
}
@Test(expected = DoesNotExistException.class)
public void removeModelNonExist() {
mm.removeModel(URI_NONE);
}
@Test
public void getModelExist() {
assertEquals(MODEL_TWO, mm.getModel(URI_TWO));
assertList(URI_ONE, URI_TWO);
}
@Test
public void getModelRigorousNonExist() {
rigorous();
assertNull(mm.getModel(URI_NONE));
assertList(URI_ONE, URI_TWO);
}
@Test
public void getModelRelaxedNonExist() {
assertEquals(MODEL_FRESH, mm.getModel(URI_NONE));
assertList(URI_ONE, URI_TWO, URI_NONE);
}
@Test
public void getModelLoadIfAbsentExist() {
assertEquals(MODEL_TWO, mm.getModel(URI_TWO, modelReader));
assertList(URI_ONE, URI_TWO);
}
@Test(expected = CannotCreateException.class)
public void getModelLoadIfAbsentRigorousNonExist() {
rigorous();
mm.getModel(URI_NONE, modelReader);
}
@Test
public void getModelLoadIfAbsentRelaxedNonExist() {
assertEquals(MODEL_FRESH, mm.getModel(URI_NONE, modelReader));
assertList(URI_ONE, URI_TWO, URI_NONE);
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
private void relaxed() {
mm = new ModelMakerWithPersistentEmptyModels(relaxed);
}
private void rigorous() {
mm = new ModelMakerWithPersistentEmptyModels(rigorous);
}
private void assertList(String... expectedArray) {
Set<String> expected = new HashSet<>(Arrays.asList(expectedArray));
Set<String> actual = mm.listModels().toSet();
assertEquals(expected, actual);
}
}

View file

@ -0,0 +1,722 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.rdfservice.adapters;
import static com.hp.hpl.jena.ontology.OntModelSpec.OWL_MEM;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import com.hp.hpl.jena.graph.BulkUpdateHandler;
import com.hp.hpl.jena.graph.impl.GraphWithPerform;
import com.hp.hpl.jena.graph.impl.SimpleBulkUpdateHandler;
import com.hp.hpl.jena.mem.GraphMem;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.listeners.StatementListener;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelChangedListener;
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.ResourceFactory;
import com.hp.hpl.jena.rdf.model.Statement;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.testing.RecordingProxy;
import edu.cornell.mannlib.vitro.testing.RecordingProxy.MethodCall;
import edu.cornell.mannlib.vitro.testing.RecordingProxy.MethodCallRecorder;
/**
* Test that the VitroModelFactory is doing what we want, with regard to bulk
* updates.
*
* With the switch to Jena 2.10, bulk update operations are deprecated, but
* still supported, to a large extent. A Graph still has a bulk updater which
* can be called for bulk operations (like adding multiple statements). However,
* the default Model won't call the bulk updater of its Graph, and neither will
* the default OntModel.
*
* VitroModelFactory creates Models and OntModels that do call the bulk updaters
* of their respective graphs.
*
* ---------------
*
* These tests show which methods are called on which objects (graph, model,
* listener) for both simple operations (add a statement) and bulk operations
* (add multiple statements).
*
* The tests of the default ModelFactory aren't necessary. They do add
* confidence to the testing mechanism, and provide a contrast with the
* VitroModelFactory.
*
* The tests of simple operations may or may not add value. Probably good to
* keep them.
*
* ----------------
*
* Who knows how we will deal with this in the next Jena upgrade, when
* presumably the bulk updaters will be removed completely.
*/
public class VitroModelFactoryTest extends AbstractTestClass {
private static final Statement SINGLE_STATEMENT = stmt(
resource("http://subject"), property("http://add"),
literal("object"));
private static final Statement[] MULTIPLE_STATEMENTS = {
stmt(resource("http://subject"), property("http://add"),
literal("first")),
stmt(resource("http://subject"), property("http://add"),
literal("second")) };
private static final String[] BORING_METHOD_NAMES = { "getPrefixMapping",
"getEventManager", "getBulkUpdateHandler", "find", "getGraph" };
// ----------------------------------------------------------------------
// createModelForGraph()
// ----------------------------------------------------------------------
/**
* A ModelGroup has a talkative graph, with a talkative bulkUpdater, wrapped
* by a model that has a talkative listener attached.
*
* But what kind of model?
*/
private static abstract class ModelGroup extends TestObjectGrouping {
final GraphWithPerform g;
final BulkUpdateHandler bu;
final ModelChangedListener l;
final Model m;
protected ModelGroup() {
MyGraphMem rawGraph = new MyGraphMem();
this.g = wrapGraph(rawGraph);
this.bu = makeBulkUpdater(this.g, rawGraph);
this.l = makeListener();
this.m = wrapModel(makeModel(this.g));
this.m.register(this.l);
reset(g);
reset(bu);
reset(l);
reset(m);
}
protected abstract Model makeModel(GraphWithPerform g);
}
/** A ModelGroup with a default-style model. */
private static class DefaultModelGroup extends ModelGroup {
@Override
protected Model makeModel(GraphWithPerform g) {
return ModelFactory.createModelForGraph(g);
}
}
/** A ModelGroup with a Vitro-style model. */
private static class VitroModelGroup extends ModelGroup {
@Override
protected Model makeModel(GraphWithPerform g) {
return VitroModelFactory.createModelForGraph(g);
}
}
private ModelGroup mg;
@Test
public void addOneToModel() {
mg = new DefaultModelGroup();
mg.m.add(SINGLE_STATEMENT);
new MethodCalls().add(mg.g, "add").add(mg.bu)
.add(mg.l, "addedStatement").test();
}
@Test
public void addOneToVitroModel() {
mg = new VitroModelGroup();
mg.m.add(SINGLE_STATEMENT);
new MethodCalls().add(mg.g, "add").add(mg.bu)
.add(mg.l, "addedStatement").test();
}
@Test
public void addMultipleToModel() {
mg = new DefaultModelGroup();
mg.m.add(MULTIPLE_STATEMENTS);
new MethodCalls().add(mg.g, "performAdd", "performAdd").add(mg.bu)
.add(mg.l, "addedStatements").test();
}
@Test
public void addMultipleToVitroModel() {
mg = new VitroModelGroup();
mg.m.add(MULTIPLE_STATEMENTS);
new MethodCalls().add(mg.g, "performAdd", "performAdd")
.add(mg.bu, "add").add(mg.l, "addedStatements").test();
}
// ----------------------------------------------------------------------
// createOntologyModel()
// ----------------------------------------------------------------------
private OntModelGroup omg;
/**
* An OntModelGroup is like a ModelGroup, but the model is wrapped in an
* OntModel that has its own talkative listener.
*
* But what kind of Model, and what kind of OntModel?
*/
private static abstract class OntModelGroup extends ModelGroup {
final ModelChangedListener ol;
final OntModel om;
protected OntModelGroup() {
this.ol = makeListener();
this.om = wrapOntModel(makeOntModel(this.m));
this.om.register(this.ol);
}
protected abstract OntModel makeOntModel(Model m);
}
/**
* An OntModelGroup with a default-style OntModel and a default-style Model.
*/
private static class DefaultOntModelGroup extends OntModelGroup {
@Override
protected OntModel makeOntModel(Model m) {
return ModelFactory.createOntologyModel(OWL_MEM, m);
}
@Override
protected Model makeModel(GraphWithPerform g) {
return ModelFactory.createModelForGraph(g);
}
}
/**
* An OntModelGroup with a Vitro-style OntModel and a Vitro-style Model.
*/
private static class VitroOntModelGroup extends OntModelGroup {
@Override
protected OntModel makeOntModel(Model m) {
return VitroModelFactory.createOntologyModel(m);
}
@Override
protected Model makeModel(GraphWithPerform g) {
return VitroModelFactory.createModelForGraph(g);
}
}
@Test
public void addOneToOntModel() {
omg = new DefaultOntModelGroup();
omg.om.add(SINGLE_STATEMENT);
new MethodCalls().add(omg.g, "add").add(omg.bu)
.add(omg.l, "addedStatement").add(omg.ol, "addedStatement")
.test();
}
@Test
public void addOneToVitroOntModel() {
omg = new VitroOntModelGroup();
omg.om.add(SINGLE_STATEMENT);
new MethodCalls().add(omg.g, "add").add(omg.bu)
.add(omg.l, "addedStatement").add(omg.ol, "addedStatement")
.test();
}
@Test
public void addMultipleToOntModel() {
omg = new DefaultOntModelGroup();
omg.om.add(MULTIPLE_STATEMENTS);
new MethodCalls().add(omg.g, "add", "add").add(omg.bu)
.add(omg.l, "addedStatement", "addedStatement")
.add(omg.ol, "addedStatements").test();
}
@Test
public void addMultipleToVitroOntModel() {
omg = new VitroOntModelGroup();
omg.om.add(MULTIPLE_STATEMENTS);
new MethodCalls().add(omg.g, "performAdd", "performAdd")
.add(omg.bu, "add").add(omg.l, "addedStatements")
.add(omg.ol, "addedStatements").test();
}
// ----------------------------------------------------------------------
// createUnion(Model, Model)
// ----------------------------------------------------------------------
/**
* A UnionModelGroup is two ModelGroups, joined into a union that has its
* own talkative listener.
*
* But what kind of ModelGroup, and what kind of union?
*/
private abstract static class UnionModelGroup extends TestObjectGrouping {
final ModelGroup base;
final ModelGroup plus;
final Model m;
final ModelChangedListener l;
protected UnionModelGroup() {
this.base = makeModelGroup();
this.plus = makeModelGroup();
this.m = wrapModel(makeUnion(this.base.m, this.plus.m));
this.l = makeListener();
this.m.register(this.l);
}
protected abstract ModelGroup makeModelGroup();
protected abstract Model makeUnion(Model baseModel, Model plusModel);
}
/**
* A UnionModelGroup with default-style Models and a default-style union.
*/
private static class DefaultUnionModelGroup extends UnionModelGroup {
@Override
protected ModelGroup makeModelGroup() {
return new DefaultModelGroup();
}
@Override
protected Model makeUnion(Model baseModel, Model plusModel) {
return ModelFactory.createUnion(baseModel, plusModel);
}
}
/**
* A UnionModelGroup with Vitro-style Models and a Vitro-style union.
*/
private static class VitroUnionModelGroup extends UnionModelGroup {
@Override
protected ModelGroup makeModelGroup() {
return new VitroModelGroup();
}
@Override
protected Model makeUnion(Model baseModel, Model plusModel) {
return VitroModelFactory.createUnion(baseModel, plusModel);
}
}
private UnionModelGroup umg;
@Test
public void addOneToUnion() {
umg = new DefaultUnionModelGroup();
umg.m.add(SINGLE_STATEMENT);
new MethodCalls().add(umg.base.g, "add").add(umg.base.bu)
.add(umg.base.l, "addedStatement").add(umg.plus.g)
.add(umg.plus.bu).add(umg.plus.l).add(umg.l, "addedStatement")
.test();
}
@Test
public void addOneToVitroUnion() {
umg = new VitroUnionModelGroup();
umg.m.add(SINGLE_STATEMENT);
new MethodCalls().add(umg.base.g, "add").add(umg.base.bu)
.add(umg.base.l, "addedStatement").add(umg.plus.g)
.add(umg.plus.bu).add(umg.plus.l).add(umg.l, "addedStatement")
.test();
}
@Test
public void addMultipleToUnion() {
umg = new DefaultUnionModelGroup();
umg.m.add(MULTIPLE_STATEMENTS);
new MethodCalls().add(umg.base.g, "add", "add").add(umg.base.bu)
.add(umg.base.l, "addedStatement", "addedStatement")
.add(umg.plus.g).add(umg.plus.bu).add(umg.plus.l)
.add(umg.l, "addedStatements").test();
}
@Test
public void addMultipleToVitroUnion() {
umg = new VitroUnionModelGroup();
umg.m.add(MULTIPLE_STATEMENTS);
new MethodCalls().add(umg.base.g, "performAdd", "performAdd")
.add(umg.base.bu, "add").add(umg.base.l, "addedStatements")
.add(umg.plus.g).add(umg.plus.bu).add(umg.plus.l)
.add(umg.l, "addedStatements").test();
}
// ----------------------------------------------------------------------
// createUnion(OntModel, OntModel)
// ----------------------------------------------------------------------
/**
* A UnionOntModelGroup is two OntModelGroups, joined into a union that has
* its own talkative listener.
*
* But what kind of OntModelGroup, and what kind of union?
*/
private abstract static class UnionOntModelGroup extends TestObjectGrouping {
final OntModelGroup base;
final OntModelGroup plus;
final OntModel om;
final ModelChangedListener l;
protected UnionOntModelGroup() {
this.base = makeOntModelGroup();
this.plus = makeOntModelGroup();
this.om = wrapOntModel(makeOntUnion(this.base.om, this.plus.om));
this.l = makeListener();
this.om.register(this.l);
}
protected abstract OntModelGroup makeOntModelGroup();
protected abstract OntModel makeOntUnion(OntModel baseModel,
OntModel plusModel);
}
/**
* A UnionOntModelGroup with default-style OntModels and a default-style
* union.
*/
private static class DefaultUnionOntModelGroup extends UnionOntModelGroup {
@Override
protected OntModelGroup makeOntModelGroup() {
return new DefaultOntModelGroup();
}
@Override
protected OntModel makeOntUnion(OntModel baseModel, OntModel plusModel) {
return ModelFactory.createOntologyModel(OWL_MEM,
ModelFactory.createUnion(baseModel, plusModel));
}
}
/**
* A UnionOntModelGroup with Vitro-style OntModels and a Vitro-style union.
*/
private static class VitroUnionOntModelGroup extends UnionOntModelGroup {
@Override
protected OntModelGroup makeOntModelGroup() {
return new VitroOntModelGroup();
}
@Override
protected OntModel makeOntUnion(OntModel baseModel, OntModel plusModel) {
return VitroModelFactory.createUnion(baseModel, plusModel);
}
}
private UnionOntModelGroup uomg;
@Test
public void addOneToOntUnion() {
uomg = new DefaultUnionOntModelGroup();
uomg.om.add(SINGLE_STATEMENT);
new MethodCalls().add(uomg.base.g, "add").add(uomg.base.bu)
.add(uomg.base.l, "addedStatement").add(uomg.plus.g)
.add(uomg.plus.bu).add(uomg.plus.l)
.add(uomg.l, "addedStatement").test();
}
@Test
public void addOneToVitroOntUnion() {
uomg = new VitroUnionOntModelGroup();
uomg.om.add(SINGLE_STATEMENT);
new MethodCalls().add(uomg.base.g, "add").add(uomg.base.bu)
.add(uomg.base.l, "addedStatement").add(uomg.plus.g)
.add(uomg.plus.bu).add(uomg.plus.l)
.add(uomg.l, "addedStatement").test();
}
@Test
public void addMultipleToOntUnion() {
uomg = new DefaultUnionOntModelGroup();
uomg.om.add(MULTIPLE_STATEMENTS);
new MethodCalls().add(uomg.base.g, "add", "add").add(uomg.base.bu)
.add(uomg.base.l, "addedStatement", "addedStatement")
.add(uomg.plus.g).add(uomg.plus.bu).add(uomg.plus.l)
.add(uomg.l, "addedStatements").test();
}
@Test
public void addMultipleToVitroOntUnion() {
uomg = new VitroUnionOntModelGroup();
uomg.om.add(MULTIPLE_STATEMENTS);
new MethodCalls().add(uomg.base.g, "performAdd", "performAdd")
.add(uomg.base.bu, "add").add(uomg.base.l, "addedStatements")
.add(uomg.plus.g).add(uomg.plus.bu).add(uomg.plus.l)
.add(uomg.l, "addedStatements").test();
}
// ----------------------------------------------------------------------
// OntModel of Union of Models
//
// This shouldn't hold any surprises, should it?
// ----------------------------------------------------------------------
/**
* A OntModelUnionModelGroup is a UnionModelGroup wrapped by an OntModel
* with a listener.
*
* But what kind of UnionModelGroup, and what kind of OntModel?
*/
private abstract static class OntModelUnionModelGroup extends
TestObjectGrouping {
final UnionModelGroup union;
final OntModel om;
final ModelChangedListener ol;
protected OntModelUnionModelGroup() {
this.union = makeUnionModelGroup();
this.om = wrapOntModel(makeOntModel(union.m));
this.ol = makeListener();
this.om.register(this.ol);
reset(om);
}
protected abstract UnionModelGroup makeUnionModelGroup();
protected abstract OntModel makeOntModel(Model m);
}
/**
* A OntModelUnionModelGroup with default-style UnionModelGroup and a
* default-style OntModel.
*/
private static class DefaultOntModelUnionModelGroup extends
OntModelUnionModelGroup {
@Override
protected UnionModelGroup makeUnionModelGroup() {
return new DefaultUnionModelGroup();
}
@Override
protected OntModel makeOntModel(Model m) {
return ModelFactory.createOntologyModel(OWL_MEM, m);
}
}
/**
* A OntModelUnionModelGroup with Vitro-style UnionModelGroup and a
* Vitro-style OntModel.
*/
private static class VitroOntModelUnionModelGroup extends
OntModelUnionModelGroup {
@Override
protected UnionModelGroup makeUnionModelGroup() {
return new VitroUnionModelGroup();
}
@Override
protected OntModel makeOntModel(Model m) {
return VitroModelFactory.createOntologyModel(m);
}
}
private OntModelUnionModelGroup omumg;
@Test
public void addOneToOntModeledUnionModel() {
omumg = new DefaultOntModelUnionModelGroup();
omumg.om.add(SINGLE_STATEMENT);
new MethodCalls().add(omumg.om, "add").add(omumg.ol, "addedStatement")
.add(omumg.union.base.g, "add").add(omumg.union.base.bu)
.add(omumg.union.base.m)
.add(omumg.union.base.l, "addedStatement")
.add(omumg.union.plus.g).add(omumg.union.plus.bu)
.add(omumg.union.plus.m).add(omumg.union.plus.l).test();
}
@Test
public void addOneToVitroOntModeledUnionModel() {
omumg = new VitroOntModelUnionModelGroup();
omumg.om.add(SINGLE_STATEMENT);
new MethodCalls().add(omumg.om, "add").add(omumg.ol, "addedStatement")
.add(omumg.union.base.g, "add").add(omumg.union.base.bu)
.add(omumg.union.base.m)
.add(omumg.union.base.l, "addedStatement")
.add(omumg.union.plus.g).add(omumg.union.plus.bu)
.add(omumg.union.plus.m).add(omumg.union.plus.l).test();
}
@Test
public void addMultipleToOntModeledUnionModel() {
omumg = new DefaultOntModelUnionModelGroup();
omumg.om.add(MULTIPLE_STATEMENTS);
new MethodCalls().add(omumg.om, "add").add(omumg.ol, "addedStatements")
.add(omumg.union.base.g, "add", "add").add(omumg.union.base.bu)
.add(omumg.union.base.m)
.add(omumg.union.base.l, "addedStatement", "addedStatement")
.add(omumg.union.plus.g).add(omumg.union.plus.bu)
.add(omumg.union.plus.m).add(omumg.union.plus.l).test();
}
@Test
public void addMultipleToVitroOntModeledUnionModel() {
omumg = new VitroOntModelUnionModelGroup();
omumg.om.add(MULTIPLE_STATEMENTS);
new MethodCalls().add(omumg.om, "add").add(omumg.ol, "addedStatements")
.add(omumg.union.base.g, "performAdd", "performAdd")
.add(omumg.union.base.bu, "add").add(omumg.union.base.m)
.add(omumg.union.base.l, "addedStatements")
.add(omumg.union.plus.g).add(omumg.union.plus.bu)
.add(omumg.union.plus.m).add(omumg.union.plus.l).test();
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
private static Statement stmt(Resource subject, Property predicate,
RDFNode object) {
return ResourceFactory.createStatement(subject, predicate, object);
}
private static Resource resource(String uri) {
return ResourceFactory.createResource(uri);
}
private static Property property(String uri) {
return ResourceFactory.createProperty(uri);
}
private static Literal literal(String value) {
return ResourceFactory.createPlainLiteral(value);
}
/** Just for debugging */
private void dumpMethodCalls(String message, Object proxy) {
System.out.println(message + " method calls:");
for (MethodCall call : ((MethodCallRecorder) proxy).getMethodCalls()) {
String formatted = " " + call.getName();
for (Object arg : call.getArgList()) {
formatted += " " + arg.getClass();
}
System.out.println(formatted);
}
}
// ----------------------------------------------------------------------
// Helper classes
// ----------------------------------------------------------------------
/**
* The latest Graph classes allow you to get their BulkUpdateHandler, but
* won't allow you to set it.
*/
private static class MyGraphMem extends GraphMem {
public void setBulkUpdateHandler(BulkUpdateHandler bulkHandler) {
this.bulkHandler = bulkHandler;
}
}
/**
* A collection of "CallNames", each of which holds a list of expected
* calls, a recording proxy from which we can get the actual calls, and a
* method to compare them.
*/
private static class MethodCalls {
private final List<CallNames> list = new ArrayList<>();
public MethodCalls add(Object proxy, String... names) {
list.add(new CallNames((MethodCallRecorder) proxy, names));
return this;
}
/**
* Create a string that represents all of the expected method calls.
* Create a string that represents all of the interesting actual calls.
* Compare the strings.
*/
private void test() {
try (StringWriter expectSw = new StringWriter();
PrintWriter expectWriter = new PrintWriter(expectSw, true);
StringWriter actualSw = new StringWriter();
PrintWriter actualWriter = new PrintWriter(actualSw, true);) {
for (CallNames calls : list) {
expectWriter.println(Arrays.asList(calls.names));
actualWriter.println(filterMethodNames(calls.proxy
.getMethodCallNames()));
}
assertEquals(expectSw.toString(), actualSw.toString());
} catch (IOException e) {
fail(e.toString());
}
}
private List<String> filterMethodNames(List<String> raw) {
List<String> filtered = new ArrayList<>(raw);
filtered.removeAll(Arrays.asList(BORING_METHOD_NAMES));
return filtered;
}
private static class CallNames {
private final MethodCallRecorder proxy;
private final String[] names;
public CallNames(MethodCallRecorder proxy, String[] names) {
this.proxy = proxy;
this.names = names;
}
}
}
/**
* Some utility methods for creating a group of test objects.
*/
private static abstract class TestObjectGrouping {
protected GraphWithPerform wrapGraph(MyGraphMem raw) {
return RecordingProxy.create(raw, GraphWithPerform.class);
}
protected BulkUpdateHandler makeBulkUpdater(GraphWithPerform g,
MyGraphMem raw) {
SimpleBulkUpdateHandler rawBu = new SimpleBulkUpdateHandler(g);
BulkUpdateHandler bu = RecordingProxy.create(rawBu,
BulkUpdateHandler.class);
raw.setBulkUpdateHandler(bu);
return bu;
}
protected static ModelChangedListener makeListener() {
return RecordingProxy.create(new StatementListener(),
ModelChangedListener.class);
}
protected Model wrapModel(Model m) {
return RecordingProxy.create(m, Model.class);
}
protected OntModel wrapOntModel(OntModel om) {
return RecordingProxy.create(om, OntModel.class);
}
protected <T> T reset(T proxy) {
((MethodCallRecorder) proxy).resetMethodCalls();
return proxy;
}
}
}

View file

@ -0,0 +1,309 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.rdfservice.filter;
import static org.junit.Assert.assertEquals;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
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 stubs.com.hp.hpl.jena.rdf.model.LiteralStub;
import com.hp.hpl.jena.rdf.model.Literal;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
/**
* This is the matching order we expect to see:
*
* <pre>
* exact match to preferred, by order.
* partial match to preferred, by order.
* vanilla or null (no language)
* no match
* </pre>
*/
public class LanguageFilteringRDFServiceTest extends AbstractTestClass {
private static final Log log = LogFactory
.getLog(LanguageFilteringRDFServiceTest.class);
private static final String COLLATOR_CLASSNAME = "edu.cornell.mannlib.vitro.webapp.rdfservice.filter.LanguageFilteringRDFService$RowIndexedLiteralSortByLang";
private static final String RIL_CLASSNAME = "edu.cornell.mannlib.vitro.webapp.rdfservice.filter.LanguageFilteringRDFService$RowIndexedLiteral";
private LanguageFilteringRDFService filteringRDFService;
private List<Object> listOfRowIndexedLiterals;
private int literalIndex;
private List<String> preferredLanguages;
private List<String> availableLanguages;
private List<String> expectedSortOrders;
@Before
public void setup() {
// setLoggerLevel(this.getClass(), Level.DEBUG);
// setLoggerLevel(LanguageFilteringRDFService.class, Level.DEBUG);
}
// ----------------------------------------------------------------------
// The tests
// ----------------------------------------------------------------------
@Test
public void singleMatch() {
preferredLanguages = list("en-US");
availableLanguages = list("en-US");
expectedSortOrders = list("en-US");
testArbitraryOrder();
}
@Test
public void singleNoMatch() {
preferredLanguages = list("en-US");
availableLanguages = list("es-MX");
expectedSortOrders = list("es-MX");
testArbitraryOrder();
}
@Test
public void doubleMatch() {
preferredLanguages = list("en-US", "es-MX");
availableLanguages = list("en-US", "es-MX");
expectedSortOrders = list("en-US", "es-MX");
testBothWays();
}
@Test
public void noMatches() {
preferredLanguages = list("es-MX");
availableLanguages = list("en-US", "fr-FR");
expectedSortOrders = list("en-US", "fr-FR");
testArbitraryOrder();
}
@Test
public void partialMatches() {
preferredLanguages = list("en", "es");
availableLanguages = list("en-US", "es-MX");
expectedSortOrders = list("en-US", "es-MX");
testBothWays();
}
@Test
public void matchIsBetterThanNoMatch() {
preferredLanguages = list("en-US", "es-MX");
availableLanguages = list("en-US", "fr-FR");
expectedSortOrders = list("en-US", "fr-FR");
testBothWays();
}
@Test
public void matchIsBetterThanPartialMatch() {
preferredLanguages = list("es-ES", "en-US");
availableLanguages = list("en-US", "es-MX");
expectedSortOrders = list("en-US", "es-MX");
testBothWays();
}
@Test
public void exactMatchIsBetterThanPartialMatch() {
preferredLanguages = list("es");
availableLanguages = list("es", "es-MX");
expectedSortOrders = list("es", "es-MX");
testBothWays();
}
@Test
public void matchIsBetterThanVanilla() {
preferredLanguages = list("en-US");
availableLanguages = list("en-US", "");
expectedSortOrders = list("en-US", "");
testBothWays();
}
@Test
public void partialMatchIsBetterThanVanilla() {
preferredLanguages = list("es-MX");
availableLanguages = list("es-ES", "");
expectedSortOrders = list("es-ES", "");
testBothWays();
}
@Test
public void vanillaIsBetterThanNoMatch() {
preferredLanguages = list("es-MX");
availableLanguages = list("en-US", "");
expectedSortOrders = list("", "en-US");
testBothWays();
}
@Test
public void omnibus() {
preferredLanguages = list("es-MX", "es", "en-UK", "es-PE", "fr");
availableLanguages = list("es-MX", "es", "fr", "es-ES", "fr-FR", "",
"de-DE");
expectedSortOrders = list("es-MX", "es", "fr", "es-ES", "fr-FR", "",
"de-DE");
testBothWays();
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
/**
* Sort the available languages as they are presented. Then reverse them and
* sort again.
*/
private void testBothWays() {
createLanguageFilter();
buildListOfLiterals();
sortListOfLiterals();
assertLanguageOrder("sort literals");
buildReversedListOfLiterals();
sortListOfLiterals();
assertLanguageOrder("sort reversed literals");
}
/**
* Sort the available languages, without caring what the eventual sorted
* order is. Really, this is just a test to see that no exceptions are
* thrown, and no languages are "lost in translation".
*/
private void testArbitraryOrder() {
createLanguageFilter();
buildListOfLiterals();
sortListOfLiterals();
assertLanguages("sort literals");
buildReversedListOfLiterals();
sortListOfLiterals();
assertLanguages("sort reversed literals");
}
private List<String> list(String... strings) {
return new ArrayList<String>(Arrays.asList(strings));
}
private void createLanguageFilter() {
filteringRDFService = new LanguageFilteringRDFService(null,
preferredLanguages);
}
private void buildListOfLiterals() {
List<Object> list = new ArrayList<Object>();
for (String language : availableLanguages) {
list.add(buildRowIndexedLiteral(language));
}
listOfRowIndexedLiterals = list;
}
private void buildReversedListOfLiterals() {
List<Object> list = new ArrayList<Object>();
for (String language : availableLanguages) {
list.add(0, buildRowIndexedLiteral(language));
}
listOfRowIndexedLiterals = list;
}
private void sortListOfLiterals() {
log.debug("before sorting: "
+ languagesFromLiterals(listOfRowIndexedLiterals));
Comparator<Object> comparator = buildRowIndexedLiteralSortByLang();
Collections.sort(listOfRowIndexedLiterals, comparator);
}
private void assertLanguageOrder(String message) {
List<String> expectedLanguages = expectedSortOrders;
log.debug("expected order: " + expectedLanguages);
List<String> actualLanguages = languagesFromLiterals(listOfRowIndexedLiterals);
log.debug("actual order: " + actualLanguages);
assertEquals(message, expectedLanguages, actualLanguages);
}
private void assertLanguages(String message) {
Set<String> expectedLanguages = new HashSet<String>(expectedSortOrders);
log.debug("expected languages: " + expectedLanguages);
Set<String> actualLanguages = new HashSet<String>(
languagesFromLiterals(listOfRowIndexedLiterals));
log.debug("actual languages: " + actualLanguages);
assertEquals(message, expectedLanguages, actualLanguages);
}
private List<String> languagesFromLiterals(List<Object> literals) {
List<String> actualLanguages = new ArrayList<String>();
for (Object ril : literals) {
actualLanguages.add(getLanguageFromRowIndexedLiteral(ril));
}
return actualLanguages;
}
// ----------------------------------------------------------------------
// Reflection methods to get around "private" declarations.
// ----------------------------------------------------------------------
private Object buildRowIndexedLiteral(String language) {
try {
Class<?> clazz = Class.forName(RIL_CLASSNAME);
Class<?>[] argTypes = { LanguageFilteringRDFService.class,
Literal.class, Integer.TYPE };
Constructor<?> constructor = clazz.getDeclaredConstructor(argTypes);
constructor.setAccessible(true);
Literal l = new LiteralStub(language);
int i = literalIndex++;
return constructor.newInstance(filteringRDFService, l, i);
} catch (Exception e) {
throw new RuntimeException(
"Could not create a row-indexed literal", e);
}
}
@SuppressWarnings("unchecked")
private Comparator<Object> buildRowIndexedLiteralSortByLang() {
try {
Class<?> clazz = Class.forName(COLLATOR_CLASSNAME);
Class<?>[] argTypes = { LanguageFilteringRDFService.class };
Constructor<?> constructor = clazz.getDeclaredConstructor(argTypes);
constructor.setAccessible(true);
return (Comparator<Object>) constructor
.newInstance(filteringRDFService);
} catch (Exception e) {
throw new RuntimeException("Could not create a collator", e);
}
}
private String getLanguageFromRowIndexedLiteral(Object ril) {
try {
Method m = ril.getClass().getDeclaredMethod("getLiteral");
m.setAccessible(true);
Literal l = (Literal) m.invoke(ril);
return l.getLanguage();
} catch (Exception e) {
throw new RuntimeException(
"Could not get the Literal from a RowIndexedLiteral", e);
}
}
}

View file

@ -0,0 +1,575 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.reasoner;
import org.apache.log4j.Level;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import stubs.edu.cornell.mannlib.vitro.webapp.modules.ApplicationStub;
import stubs.edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchEngineStub;
import stubs.javax.servlet.ServletContextStub;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.ontology.OntProperty;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.vocabulary.OWL;
import edu.cornell.mannlib.vitro.webapp.utils.threads.VitroBackgroundThread;
public class SimpleReasonerInversePropertyTest extends SimpleReasonerTBoxHelper {
long delay = 50;
@Before
public void suppressErrorOutput() {
suppressSyserr();
//Turn off log messages to console
setLoggerLevel(SimpleReasoner.class, Level.OFF);
setLoggerLevel(SimpleReasonerTBoxListener.class, Level.OFF);
setLoggerLevel(ABoxRecomputer.class, Level.OFF);
}
@Before public void setup() {
ApplicationStub.setup(new ServletContextStub(), new SearchEngineStub());
}
@Test
public void addABoxAssertion1Test(){
addABoxAssertion1(true);
}
@Test
public void addABoxAssertion1NoSameAsTest(){
addABoxAssertion1(false);
}
/*
* basic scenarios around adding abox data
*
* Create a Tbox with property P inverseOf property Q.
* Add a statement a P b, and verify that b Q a is inferred.
* Add a statement c Q d and verify that d Q c is inferred.
*/
public void addABoxAssertion1(boolean sameAs ) {
// set up the tbox
OntModel tBox = createTBoxModel();
OntProperty P = createObjectProperty(tBox, "http://test.vivo/P", "property P");
OntProperty Q = createObjectProperty(tBox, "http://test.vivo/Q", "property Q");
setInverse(P, Q);
// this is the model to receive abox inferences
Model inf = ModelFactory.createDefaultModel();
// create an abox and register the SimpleReasoner listener with it
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
SimpleReasoner sr = new SimpleReasoner(tBox,aBox,inf);
sr.setSameAsEnabled( sameAs );
aBox.register( sr );
// add assertions to the abox and verify inferences
Resource a = aBox.createResource("http://test.vivo/a");
Resource b = aBox.createResource("http://test.vivo/b");
Resource c = aBox.createResource("http://test.vivo/c");
Resource d = aBox.createResource("http://test.vivo/d");
aBox.add(a,P,b);
Assert.assertTrue(inf.contains(b,Q,a));
aBox.add(c,Q,d);
Assert.assertTrue(inf.contains(d,P,c));
// delete assertions and verify that inferences go away
aBox.remove(c,Q,d);
Assert.assertFalse(inf.contains(d,P,c));
aBox.remove(a,P,b);
Assert.assertFalse(inf.contains(b,Q,a));
}
@Test
public void addABoxAssertion2Test() {
addABoxAssertion2(true);
}
@Test
public void addABoxAssertion2NoSameAsTest() {
addABoxAssertion2(false);
}
/*
* don't infer statements already in the abox
* (never infer because it's in the abox already)
*/
public void addABoxAssertion2(boolean sameAs ) {
// set up the tbox
OntModel tBox = createTBoxModel();
OntProperty P = createObjectProperty(tBox, "http://test.vivo/P", "property P");
OntProperty Q = createObjectProperty(tBox, "http://test.vivo/Q", "property Q");
setInverse(P, Q);
// this is the model to receive abox inferences
Model inf = ModelFactory.createDefaultModel();
// create an ABox and add data (no inferencing happening yet)
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
// Individuals a, b, c and d
Resource a = aBox.createResource("http://test.vivo/a");
Resource b = aBox.createResource("http://test.vivo/b");
aBox.add(b,Q,a);
// register SimpleReasoner
aBox.register(new SimpleReasoner(tBox, aBox, inf));
Assert.assertFalse(inf.contains(b,Q,a));
// add data and verify inferences
aBox.add(a,P,b);
Assert.assertFalse(inf.contains(b,Q,a));
}
@Test
public void addABoxAssertion3Test() {
addABoxAssertion3(true);
}
@Test
public void addABoxAssertion3NoSameAsTest(){
addABoxAssertion3(false);
}
/*
* don't infer statements already in the abox
* (remove the inference when it is asserted)
*/
public void addABoxAssertion3(boolean sameAs) {
// set up the tbox
OntModel tBox = createTBoxModel();
OntProperty P = createObjectProperty(tBox, "http://test.vivo/P", "property P");
OntProperty Q = createObjectProperty(tBox, "http://test.vivo/Q", "property Q");
setInverse(P, Q);
// this is the model to receive abox inferences
Model inf = ModelFactory.createDefaultModel();
// create abox and register SimpleReasoner
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
SimpleReasoner sr = new SimpleReasoner(tBox, aBox, inf);
sr.setSameAsEnabled( sameAs );
aBox.register( sr );
// add statements to the abox and verify inferences
Resource a = aBox.createResource("http://test.vivo/a");
Resource b = aBox.createResource("http://test.vivo/b");
aBox.add(a,P,b);
Assert.assertTrue(inf.contains(b,Q,a));
aBox.add(b,Q,a); // this should cause the inference to be removed
Assert.assertFalse(inf.contains(b,Q,a));
}
@Test
public void addABoxAssertion4Test() {
addABoxAssertion4(true);
}
@Test
public void addABoxAssertion4NoSameAsTest() {
addABoxAssertion4(false);
}
/*
* adding abox data where the property has an inverse and
* and equivalent property.
*/
public void addABoxAssertion4( boolean sameAs ) {
// set up the tbox
OntModel tBox = createTBoxModel();
OntProperty P = createObjectProperty(tBox, "http://test.vivo/P", "property P");
OntProperty Q = createObjectProperty(tBox, "http://test.vivo/Q", "property Q");
OntProperty R = createObjectProperty(tBox, "http://test.vivo/R", "property R");
setInverse(P, Q);
setInverse(R, Q);
setEquivalent(R, P);
// this is the model to receive abox inferences
Model inf = ModelFactory.createDefaultModel();
// create an ABox and register the SimpleReasoner with it
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
SimpleReasoner sr = new SimpleReasoner(tBox, aBox, inf);
sr.setSameAsEnabled( sameAs );
aBox.register( sr );
// add abox statements and verify inferences
Resource a = aBox.createResource("http://test.vivo/a");
Resource b = aBox.createResource("http://test.vivo/b");
Resource c = aBox.createResource("http://test.vivo/c");
Resource d = aBox.createResource("http://test.vivo/d");
aBox.add(a,R,b);
Assert.assertTrue(inf.contains(b,Q,a));
aBox.add(c,Q,d);
Assert.assertTrue(inf.contains(d,P,c));
Assert.assertTrue(inf.contains(d,R,c));
}
@Test
public void removedABoxAssertion1Test(){
removedABoxAssertion1(true);
}
@Test
public void removedABoxAssertion1NoSameAsTest(){
removedABoxAssertion1(false);
}
/*
* basic scenarios around removing abox data
* don't remove an inference if it's still
* entailed by something else in the abox.
*/
public void removedABoxAssertion1(boolean sameAs) {
// set up the tbox
OntModel tBox = createTBoxModel();
OntProperty P = createObjectProperty(tBox, "http://test.vivo/P", "property P");
OntProperty Q = createObjectProperty(tBox, "http://test.vivo/Q", "property Q");
OntProperty T = createObjectProperty(tBox, "http://test.vivo/T", "property T");
setInverse(P, Q);
setInverse(P, T);
// this is the model to receive abox inferences
Model inf = ModelFactory.createDefaultModel();
// create an ABox and register the SimpleReasoner with it
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
SimpleReasoner sr = new SimpleReasoner(tBox, aBox, inf);
sr.setSameAsEnabled( sameAs );
aBox.register( sr );
// add statements to the abox and verify inferences
Resource a = aBox.createResource("http://test.vivo/a");
Resource b = aBox.createResource("http://test.vivo/b");
Resource c = aBox.createResource("http://test.vivo/c");
Resource d = aBox.createResource("http://test.vivo/d");
aBox.add(a,P,b);
Assert.assertTrue(inf.contains(b,Q,a));
// d P c is inferred from c Q d and also from c T d
aBox.add(c,Q,d);
aBox.add(c,T,d);
Assert.assertTrue(inf.contains(d,P,c));
aBox.remove(a,P,b);
Assert.assertFalse(inf.contains(b,Q,a));
aBox.remove(c,Q,d);
Assert.assertTrue(inf.contains(d,P,c)); // still inferred from c T d
}
@Test
public void removedABoxAssertion2Test(){
removedABoxAssertion2(true);
}
@Test
public void removedABoxAssertion2NoSameAsTest(){
removedABoxAssertion2(false);
}
/*
* removing abox data with equivalent and inverse properties
* don't remove inference if it's still inferred.
*/
public void removedABoxAssertion2(boolean sameAs) {
// set up the tbox
OntModel tBox = createTBoxModel();
OntProperty P = createObjectProperty(tBox, "http://test.vivo/P", "property P");
OntProperty Q = createObjectProperty(tBox, "http://test.vivo/Q", "property Q");
OntProperty T = createObjectProperty(tBox, "http://test.vivo/T", "property T");
setInverse(P, Q);
setInverse(T, Q);
setEquivalent(P, T);
// this is the model to receive abox inferences
Model inf = ModelFactory.createDefaultModel();
// create an abox and register the SimpleReasoner listener with it
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
SimpleReasoner sr = new SimpleReasoner(tBox, aBox, inf);
sr.setSameAsEnabled( sameAs );
aBox.register( sr );
// add abox data and verify inferences
Resource a = aBox.createResource("http://test.vivo/a");
Resource b = aBox.createResource("http://test.vivo/b");
// b Q a is inferred from a P b and also from a T b.
aBox.add(a,P,b);
aBox.add(a,T,b);
Assert.assertTrue(inf.contains(b,Q,a));
Assert.assertFalse(inf.contains(a,P,b));
Assert.assertFalse(inf.contains(a,T,b));
aBox.remove(a,P,b);
Assert.assertTrue(inf.contains(b,Q,a));
}
@Test
public void removedABoxAssertion3Test(){
removedABoxAssertion3(true);
}
@Test
public void removedABoxAssertion3NoSameAsTest(){
removedABoxAssertion3(false);
}
/*
* removing abox data with equivalent and inverse properties
*/
public void removedABoxAssertion3(boolean sameAs) {
// set up the tbox
OntModel tBox = createTBoxModel();
OntProperty P = createObjectProperty(tBox, "http://test.vivo/P", "property P");
OntProperty Q = createObjectProperty(tBox, "http://test.vivo/Q", "property Q");
setInverse(P, Q);
// this is the model to receive abox inferences
Model inf = ModelFactory.createDefaultModel();
// create the abox and add some data - no reasoning is happening yet
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
Resource a = aBox.createResource("http://test.vivo/a");
Resource b = aBox.createResource("http://test.vivo/b");
aBox.add(a,P,b);
// register the SimpleReasoner
SimpleReasoner sr = new SimpleReasoner(tBox, aBox, inf);
sr.setSameAsEnabled( sameAs );
aBox.register( sr );
// add abox statements and verify inferences
aBox.add(b,Q,a);
Assert.assertFalse(inf.contains(b,Q,a));
Assert.assertFalse(inf.contains(a,P,b)); // this could be inferred from b Q a, but
// it's already in the abox
aBox.remove(a,P,b);
Assert.assertTrue(inf.contains(a,P,b)); // now it gets added to inference model
// when it's removed from the abox
}
@Test
public void addTBoxInverseAssertion1Test() throws InterruptedException {
addTBoxInverseAssertion1(true);
}
@Test
public void addTBoxInverseAssertion1NoSameAsTest() throws InterruptedException {
addTBoxInverseAssertion1(false);
}
/*
* adding an inverseOf assertion to the tbox
*/
public void addTBoxInverseAssertion1(boolean sameAs) throws InterruptedException {
// set up the tbox
OntModel tBox = createTBoxModel();
OntProperty P = createObjectProperty(tBox, "http://test.vivo/P", "property P");
OntProperty Q = createObjectProperty(tBox, "http://test.vivo/Q", "property Q");
// this is the model to receive abox inferences
Model inf = ModelFactory.createDefaultModel();
// abox
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
// set up SimpleReasoner and register it with abox. register
// SimpleReasonerTBoxListener with the tbox.
SimpleReasoner simpleReasoner = new SimpleReasoner(tBox, aBox, inf );
simpleReasoner.setSameAsEnabled( sameAs );
aBox.register(simpleReasoner);
SimpleReasonerTBoxListener simpleReasonerTBoxListener = getTBoxListener(simpleReasoner);
tBox.register(simpleReasonerTBoxListener);
// add abox data
Resource a = aBox.createIndividual("http://test.vivo/a", OWL.Thing);
Resource b = aBox.createIndividual("http://test.vivo/b", OWL.Thing);
Resource c = aBox.createIndividual("http://test.vivo/c", OWL.Thing);
Resource d = aBox.createIndividual("http://test.vivo/d", OWL.Thing);
aBox.add(a,P,b);
aBox.add(c,P,d);
aBox.add(b,Q,a);
// Assert P and Q as inverses and wait for
// SimpleReasonerTBoxListener thread to end
setInverse(P, Q);
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
// Verify inferences
Assert.assertTrue(inf.contains(d,Q,c));
Assert.assertFalse(inf.contains(b,Q,a));
Assert.assertFalse(inf.contains(a,P,b));
simpleReasonerTBoxListener.setStopRequested();
}
@Test
public void removeTBoxInverseAssertion1Test() throws InterruptedException {
removeTBoxInverseAssertion1(true);
}
@Test
public void removeTBoxInverseAssertion1NoSameAsTest() throws InterruptedException {
removeTBoxInverseAssertion1(false);
}
/*
* removing an inverseOf assertion from the tbox
*/
public void removeTBoxInverseAssertion1(boolean sameAs) throws InterruptedException {
// set up the tbox
OntModel tBox = createTBoxModel();
OntProperty P = createObjectProperty(tBox, "http://test.vivo/P", "property P");
OntProperty Q = createObjectProperty(tBox, "http://test.vivo/Q", "property Q");
setInverse(P, Q);
// this is the model to receive abox inferences
Model inf = ModelFactory.createDefaultModel();
// abox
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
// set up SimpleReasoner and SimpleReasonerTBox listener,
// register them with abox and tbox
SimpleReasoner simpleReasoner = new SimpleReasoner(tBox, aBox, inf);
simpleReasoner.setSameAsEnabled( sameAs );
aBox.register(simpleReasoner);
SimpleReasonerTBoxListener simpleReasonerTBoxListener = getTBoxListener(simpleReasoner);
tBox.register(simpleReasonerTBoxListener);
// add statements to the abox and verify inference
Resource c = aBox.createIndividual("http://test.vivo/c", OWL.Thing);
Resource d = aBox.createIndividual("http://test.vivo/d", OWL.Thing);
aBox.add(c,P,d);
Assert.assertTrue(inf.contains(d,Q,c));
// Remove P and Q inverse relationship and wait for
// SimpleReasoner TBox thread to end.
removeInverse(P, Q);
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
// Verify inference has been removed
Assert.assertFalse(inf.contains(d,Q,c));
simpleReasonerTBoxListener.setStopRequested();
}
@Test
public void recomputeABox1Test() throws InterruptedException {
recomputeABox1(true);
}
@Test
public void recomputeABox1NoSameAsTest() throws InterruptedException {
recomputeABox1(false);
}
/*
* Basic scenario around recomputing the ABox inferences
*/
public void recomputeABox1(boolean sameAs) throws InterruptedException {
// set up the tbox
OntModel tBox = createTBoxModel();
OntProperty P = createObjectProperty(tBox, "http://test.vivo/P", "property P");
OntProperty Q = createObjectProperty(tBox, "http://test.vivo/Q", "property Q");
setInverse(P, Q);
OntProperty X = createObjectProperty(tBox, "http://test.vivo/X", "property X");
OntProperty Y = createObjectProperty(tBox, "http://test.vivo/Y", "property Y");
setInverse(X, Y);
// create abox and abox inf model and register simplereasoner
// with abox.
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
Model inf = ModelFactory.createDefaultModel();
SimpleReasoner simpleReasoner = new SimpleReasoner(tBox, aBox, inf);
simpleReasoner.setSameAsEnabled( sameAs );
aBox.register(simpleReasoner);
// abox statements
Resource a = aBox.createIndividual("http://test.vivo/a", OWL.Thing);
Resource b = aBox.createIndividual("http://test.vivo/b", OWL.Thing);
Resource c = aBox.createIndividual("http://test.vivo/c", OWL.Thing);
Resource d = aBox.createIndividual("http://test.vivo/d", OWL.Thing);
aBox.add(a,P,b);
aBox.add(c,X,d);
Assert.assertTrue(inf.contains(b,Q,a));
Assert.assertTrue(inf.contains(d,Y,c));
inf.remove(b,Q,a);
inf.remove(d,Y,c);
//recompute whole abox
simpleReasoner.recompute();
while (simpleReasoner.isRecomputing()) {
Thread.sleep(delay);
}
// Verify inferences
Assert.assertTrue(inf.contains(b,Q,a));
Assert.assertTrue(inf.contains(d,Y,c));
}
//==================================== Utility methods ====================
SimpleReasonerTBoxListener getTBoxListener(SimpleReasoner simpleReasoner) {
return new SimpleReasonerTBoxListener(simpleReasoner, new Exception().getStackTrace()[1].getMethodName());
}
// To help in debugging the unit test
void printModel(Model model, String modelName) {
System.out.println("\nThe " + modelName + " model has " + model.size() + " statements:");
System.out.println("---------------------------------------------------------------------");
model.write(System.out);
}
// To help in debugging the unit test
void printModel(OntModel ontModel, String modelName) {
System.out.println("\nThe " + modelName + " model has " + ontModel.size() + " statements:");
System.out.println("---------------------------------------------------------------------");
ontModel.writeAll(System.out,"N3",null);
}
}

View file

@ -0,0 +1,142 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.reasoner;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Level;
import org.junit.Assert;
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.ontology.OntProperty;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDFS;
public class SimpleReasonerPluginTest extends SimpleReasonerTBoxHelper {
long delay = 50;
private final static String DEFAULT_NS = "http://vivoweb.org/individual/";
private final static String DCTERMS_NS = "http://purl.org/dc/terms/";
private final static String VIVOCORE_NS = "http://vivoweb.org/ontology/core#";
private final static String creator_URI = DCTERMS_NS + "creator";
private final static String authorInAuthorship_URI = VIVOCORE_NS + "authorInAuthorship";
private final static String linkedAuthor_URI = VIVOCORE_NS + "linkedAuthor";
private final static String informationResourceInAuthorship_URI = VIVOCORE_NS + "informationResourceInAuthorship";
private final static String linkedInformationResource_URI = VIVOCORE_NS + "linkedInformationResource";
@Before
public void suppressErrorOutput() {
//suppressSyserr();
//Turn off log messages to console
setLoggerLevel(SimpleReasoner.class, Level.DEBUG);
setLoggerLevel(SimpleReasonerTBoxListener.class, Level.DEBUG);
}
/*
* testing samplePlugin - based on dcterms:creator plugin
*
*/
@Test
public void test1() {
OntModel tBox = createTBoxModel();
OntProperty authorInAuthorship = tBox.createObjectProperty(authorInAuthorship_URI);
OntProperty linkedAuthor = tBox.createObjectProperty(linkedAuthor_URI);
OntProperty informationResourceInAuthorship = tBox.createObjectProperty(informationResourceInAuthorship_URI);
OntProperty linkedInformationResource = tBox.createObjectProperty(linkedInformationResource_URI);
authorInAuthorship.addInverseOf(linkedAuthor);
informationResourceInAuthorship.addInverseOf(linkedInformationResource);
Literal title1 = tBox.createLiteral("My Findings");
Literal name1 = tBox.createLiteral("Priscilla Powers");
// this is the model to receive inferences
Model inf = ModelFactory.createDefaultModel();
// create an ABox and register the SimpleReasoner listener with it
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
SimpleReasoner simpleReasoner = new SimpleReasoner(tBox, aBox, inf);
aBox.register(simpleReasoner);
// register plugin with SimpleReasoner
List<ReasonerPlugin> pluginList = new ArrayList<ReasonerPlugin>();
String pluginClassName = "edu.cornell.mannlib.vitro.webapp.reasoner.plugin.SamplePlugin";
try {
ReasonerPlugin plugin = (ReasonerPlugin) Class.forName(pluginClassName).getConstructors()[0].newInstance();
plugin.setSimpleReasoner(simpleReasoner);
pluginList.add(plugin);
simpleReasoner.setPluginList(pluginList);
} catch (Exception e) {
System.out.println("Exception trying to instantiate plugin: " + e.getMessage());
e.printStackTrace();
return;
}
Property dctermsCreator = ResourceFactory.createProperty(creator_URI);
// add abox data for person, authorship and article.
// note, they aren't actually typed in this test tbox
Resource prissy = aBox.createResource(DEFAULT_NS + "prissy");
// assert same as
Resource authorship1 = aBox.createResource(DEFAULT_NS + "authorship1");
Resource article1 = aBox.createResource(DEFAULT_NS + "article1");
Resource article100 = aBox.createResource(DEFAULT_NS + "article100");
aBox.add(prissy,RDFS.label,name1);
aBox.add(prissy,authorInAuthorship,authorship1);
aBox.add(authorship1,linkedAuthor,prissy);
aBox.add(authorship1,linkedInformationResource,article1);
aBox.add(article1,RDFS.label,title1);
aBox.add(article1,informationResourceInAuthorship,authorship1);
aBox.add(article1, OWL.sameAs, article100);
Assert.assertTrue(inf.contains(article1,dctermsCreator,prissy));
Assert.assertTrue(inf.contains(article100,dctermsCreator,prissy));
aBox.remove(authorship1,linkedAuthor,prissy);
Assert.assertFalse(inf.contains(article1,dctermsCreator,prissy));
Assert.assertFalse(inf.contains(article100,dctermsCreator,prissy));
}
//==================================== Utility methods ====================
SimpleReasonerTBoxListener getTBoxListener(SimpleReasoner simpleReasoner) {
return new SimpleReasonerTBoxListener(simpleReasoner, new Exception().getStackTrace()[1].getMethodName());
}
// To help in debugging the unit test
void printModel(Model model, String modelName) {
System.out.println("\nThe " + modelName + " model has " + model.size() + " statements:");
System.out.println("---------------------------------------------------------------------");
model.write(System.out);
}
// To help in debugging the unit test
void printModel(OntModel ontModel, String modelName) {
System.out.println("\nThe " + modelName + " model has " + ontModel.size() + " statements:");
System.out.println("---------------------------------------------------------------------");
ontModel.writeAll(System.out,"N3",null);
}
}

View file

@ -0,0 +1,753 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.reasoner;
import org.apache.log4j.Level;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.hp.hpl.jena.ontology.AnnotationProperty;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.ontology.OntProperty;
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.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDF;
import edu.cornell.mannlib.vitro.webapp.utils.threads.VitroBackgroundThread;
public class SimpleReasonerSameAsTest extends SimpleReasonerTBoxHelper {
long delay = 50;
private static final String mostSpecificTypePropertyURI = "http://vitro.mannlib.cornell.edu/ns/vitro/0.7#mostSpecificType";
@Before
public void suppressErrorOutput() {
suppressSyserr();
//Turn off log messages to console
setLoggerLevel(SimpleReasoner.class, Level.OFF);
setLoggerLevel(SimpleReasonerTBoxListener.class, Level.OFF);
setLoggerLevel(ABoxRecomputer.class, Level.OFF);
}
/*
* basic scenario of adding an abox sameAs assertion
//*/
@Test
public void addSameAsABoxAssertion1() {
OntModel tBox = createTBoxModel();
OntProperty P = createObjectProperty(tBox, "http://test.vivo/P", "property P");
OntProperty Q = createObjectProperty(tBox, "http://test.vivo/Q", "property Q");
OntProperty S = createObjectProperty(tBox, "http://test.vivo/S", "property S");
OntProperty T = createObjectProperty(tBox, "http://test.vivo/T", "property T");
Literal literal1 = tBox.createLiteral("Literal value 1");
Literal literal2 = tBox.createLiteral("Literal value 2");
// this is the model to receive inferences
Model inf = ModelFactory.createDefaultModel();
// create an ABox and register the SimpleReasoner listener with it
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
aBox.register(new SimpleReasoner(tBox, aBox, inf));
// Individuals a, b, c and d
Resource a = aBox.createResource("http://test.vivo/a");
Resource b = aBox.createResource("http://test.vivo/b");
Resource c = aBox.createResource("http://test.vivo/c");
Resource d = aBox.createResource("http://test.vivo/d");
aBox.add(a,P,c);
aBox.add(a,S,literal1);
aBox.add(b,Q,d);
aBox.add(b,T,literal2);
aBox.add(a,OWL.sameAs,b);
Assert.assertTrue(inf.contains(b,OWL.sameAs,a));
Assert.assertTrue(inf.contains(b,P,c));
Assert.assertTrue(inf.contains(b,S,literal1));
Assert.assertTrue(inf.contains(a,Q,d));
Assert.assertTrue(inf.contains(a,T,literal2));
Assert.assertFalse(aBox.contains(b,OWL.sameAs,a));
Assert.assertFalse(aBox.contains(b,P,c));
Assert.assertFalse(aBox.contains(b,S,literal1));
Assert.assertFalse(aBox.contains(a,Q,d));
Assert.assertFalse(aBox.contains(a,T,literal2));
//run same test with sameAs = false
inf = ModelFactory.createDefaultModel();
aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
SimpleReasoner sres = new SimpleReasoner(tBox,aBox,inf);
sres.setSameAsEnabled( false );
aBox.register(sres);
a = aBox.createResource("http://test.vivo/a");
b = aBox.createResource("http://test.vivo/b");
c = aBox.createResource("http://test.vivo/c");
d = aBox.createResource("http://test.vivo/d");
aBox.add(a,P,c);
aBox.add(a,S,literal1);
aBox.add(b,Q,d);
aBox.add(b,T,literal2);
aBox.add(a,OWL.sameAs,b);
//these are now false since sameAs is off
Assert.assertFalse(inf.contains(b,OWL.sameAs,a));
Assert.assertFalse(inf.contains(b,P,c));
Assert.assertFalse(inf.contains(b,S,literal1));
Assert.assertFalse(inf.contains(a,Q,d));
Assert.assertFalse(inf.contains(a,T,literal2));
//these still shouldn't be in the abox
Assert.assertFalse(aBox.contains(b,OWL.sameAs,a));
Assert.assertFalse(aBox.contains(b,P,c));
Assert.assertFalse(aBox.contains(b,S,literal1));
Assert.assertFalse(aBox.contains(a,Q,d));
Assert.assertFalse(aBox.contains(a,T,literal2));
}
/*
* basic scenario of removing an abox sameAs assertion
*/
@Test
public void removeSameAsABoxAssertion1() {
OntModel tBox = createTBoxModel();
OntProperty P = createObjectProperty(tBox, "http://test.vivo/P", "property P");
OntProperty Q = createObjectProperty(tBox, "http://test.vivo/Q", "property Q");
OntProperty S = createObjectProperty(tBox, "http://test.vivo/S", "property S");
OntProperty T = createObjectProperty(tBox, "http://test.vivo/T", "property T");
Literal literal1 = tBox.createLiteral("Literal value 1");
Literal literal2 = tBox.createLiteral("Literal value 2");
// this is the model to receive inferences
Model inf = ModelFactory.createDefaultModel();
// create an ABox and register the SimpleReasoner listener with it
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
aBox.register(new SimpleReasoner(tBox, aBox, inf));
// Individuals a, b, c and d
Resource a = aBox.createResource("http://test.vivo/a");
Resource b = aBox.createResource("http://test.vivo/b");
Resource c = aBox.createResource("http://test.vivo/c");
Resource d = aBox.createResource("http://test.vivo/d");
aBox.add(a,P,c);
aBox.add(a,S,literal1);
aBox.add(b,Q,d);
aBox.add(b,T,literal2);
aBox.add(a,OWL.sameAs,b);
Assert.assertTrue(inf.contains(b,OWL.sameAs,a));
Assert.assertTrue(inf.contains(b,P,c));
Assert.assertTrue(inf.contains(b,S,literal1));
Assert.assertTrue(inf.contains(a,Q,d));
Assert.assertTrue(inf.contains(a,T,literal2));
aBox.remove(a,OWL.sameAs,b);
Assert.assertFalse(inf.contains(b,OWL.sameAs,a));
Assert.assertFalse(inf.contains(b,P,c));
Assert.assertFalse(inf.contains(b,S,literal1));
Assert.assertFalse(inf.contains(a,Q,d));
Assert.assertFalse(inf.contains(a,T,literal2));
}
/*
* adding abox assertion for individual in sameAs chain.
*/
@Test
public void addABoxAssertion1() {
OntModel tBox = createTBoxModel();
OntProperty P = createObjectProperty(tBox, "http://test.vivo/P", "property P");
OntProperty Q = createObjectProperty(tBox, "http://test.vivo/Q", "property Q");
OntProperty S = createObjectProperty(tBox, "http://test.vivo/S", "property S");
OntProperty T = createObjectProperty(tBox, "http://test.vivo/T", "property T");
Literal literal1 = tBox.createLiteral("Literal value 1");
Literal literal2 = tBox.createLiteral("Literal value 2");
// this is the model to receive inferences
Model inf = ModelFactory.createDefaultModel();
// create an ABox and register the SimpleReasoner listener with it
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
aBox.register(new SimpleReasoner(tBox, aBox, inf));
// Individuals a, b, c and d
Resource a = aBox.createResource("http://test.vivo/a");
Resource b = aBox.createResource("http://test.vivo/b");
Resource c = aBox.createResource("http://test.vivo/c");
Resource d = aBox.createResource("http://test.vivo/d");
Resource e = aBox.createResource("http://test.vivo/e");
Resource f = aBox.createResource("http://test.vivo/f");
aBox.add(a,OWL.sameAs,b);
aBox.add(b,OWL.sameAs,e);
aBox.add(e,OWL.sameAs,f);
Assert.assertTrue(inf.contains(b,OWL.sameAs,a));
Assert.assertTrue(inf.contains(e,OWL.sameAs,a));
Assert.assertTrue(inf.contains(e,OWL.sameAs,b));
Assert.assertTrue(inf.contains(a,OWL.sameAs,e));
Assert.assertTrue(inf.contains(f,OWL.sameAs,e));
Assert.assertTrue(inf.contains(f,OWL.sameAs,b));
Assert.assertTrue(inf.contains(f,OWL.sameAs,a));
Assert.assertTrue(inf.contains(b,OWL.sameAs,f));
Assert.assertTrue(inf.contains(a,OWL.sameAs,f));
aBox.add(a,P,c);
aBox.add(a,S,literal1);
aBox.add(b,Q,d);
aBox.add(b,T,literal2);
Assert.assertTrue(inf.contains(b,P,c));
Assert.assertTrue(inf.contains(b,S,literal1));
Assert.assertTrue(inf.contains(a,Q,d));
Assert.assertTrue(inf.contains(a,T,literal2));
Assert.assertTrue(inf.contains(e,P,c));
Assert.assertTrue(inf.contains(e,S,literal1));
Assert.assertTrue(inf.contains(e,Q,d));
Assert.assertTrue(inf.contains(e,T,literal2));
Assert.assertTrue(inf.contains(f,P,c));
Assert.assertTrue(inf.contains(f,S,literal1));
Assert.assertTrue(inf.contains(f,Q,d));
Assert.assertTrue(inf.contains(f,T,literal2));
aBox.remove(b,OWL.sameAs,e);
Assert.assertTrue(inf.contains(b,OWL.sameAs,a));
Assert.assertFalse(inf.contains(e,OWL.sameAs,a));
Assert.assertFalse(inf.contains(e,OWL.sameAs,b));
Assert.assertFalse(inf.contains(a,OWL.sameAs,e));
Assert.assertTrue(inf.contains(f,OWL.sameAs,e));
Assert.assertFalse(inf.contains(f,OWL.sameAs,b));
Assert.assertFalse(inf.contains(f,OWL.sameAs,a));
Assert.assertFalse(inf.contains(b,OWL.sameAs,f));
Assert.assertFalse(inf.contains(a,OWL.sameAs,f));
Assert.assertTrue(inf.contains(b,P,c));
Assert.assertTrue(inf.contains(b,S,literal1));
Assert.assertTrue(inf.contains(a,Q,d));
Assert.assertTrue(inf.contains(a,T,literal2));
Assert.assertFalse(inf.contains(e,P,c));
Assert.assertFalse(inf.contains(e,S,literal1));
Assert.assertFalse(inf.contains(e,Q,d));
Assert.assertFalse(inf.contains(e,T,literal2));
Assert.assertFalse(inf.contains(f,P,c));
Assert.assertFalse(inf.contains(f,S,literal1));
Assert.assertFalse(inf.contains(f,Q,d));
Assert.assertFalse(inf.contains(f,T,literal2));
}
/**
* test of enableSameAs( false )
*/
@Test
public void disabledSameAs() {
OntModel tBox = createTBoxModel();
OntProperty P = createObjectProperty(tBox, "http://test.vivo/P", "property P");
OntProperty Q = createObjectProperty(tBox, "http://test.vivo/Q", "property Q");
OntProperty S = createObjectProperty(tBox, "http://test.vivo/S", "property S");
OntProperty T = createObjectProperty(tBox, "http://test.vivo/T", "property T");
Literal literal1 = tBox.createLiteral("Literal value 1");
Literal literal2 = tBox.createLiteral("Literal value 2");
// this is the model to receive inferences
Model inf = ModelFactory.createDefaultModel();
// create an ABox and register the SimpleReasoner listener with it
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
aBox.register(new SimpleReasoner(tBox, aBox, inf));
// Individuals a, b, c and d
Resource a = aBox.createResource("http://test.vivo/a");
Resource b = aBox.createResource("http://test.vivo/b");
Resource c = aBox.createResource("http://test.vivo/c");
Resource d = aBox.createResource("http://test.vivo/d");
aBox.add(a,P,c);
aBox.add(a,S,literal1);
aBox.add(b,Q,d);
aBox.add(b,T,literal2);
aBox.add(a,OWL.sameAs,b);
Assert.assertTrue(inf.contains(b,OWL.sameAs,a));
Assert.assertTrue(inf.contains(b,P,c));
Assert.assertTrue(inf.contains(b,S,literal1));
Assert.assertTrue(inf.contains(a,Q,d));
Assert.assertTrue(inf.contains(a,T,literal2));
Assert.assertFalse(aBox.contains(b,OWL.sameAs,a));
Assert.assertFalse(aBox.contains(b,P,c));
Assert.assertFalse(aBox.contains(b,S,literal1));
Assert.assertFalse(aBox.contains(a,Q,d));
Assert.assertFalse(aBox.contains(a,T,literal2));
//run same test with sameAs = false
inf = ModelFactory.createDefaultModel();
aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
SimpleReasoner sres = new SimpleReasoner(tBox,aBox,inf);
sres.setSameAsEnabled( false );
aBox.register(sres);
a = aBox.createResource("http://test.vivo/a");
b = aBox.createResource("http://test.vivo/b");
c = aBox.createResource("http://test.vivo/c");
d = aBox.createResource("http://test.vivo/d");
aBox.add(a,P,c);
aBox.add(a,S,literal1);
aBox.add(b,Q,d);
aBox.add(b,T,literal2);
aBox.add(a,OWL.sameAs,b);
//these are now false since sameAs is off
Assert.assertFalse(inf.contains(b,OWL.sameAs,a));
Assert.assertFalse(inf.contains(b,P,c));
Assert.assertFalse(inf.contains(b,S,literal1));
Assert.assertFalse(inf.contains(a,Q,d));
Assert.assertFalse(inf.contains(a,T,literal2));
//these still shouldn't be in the abox
Assert.assertFalse(aBox.contains(b,OWL.sameAs,a));
Assert.assertFalse(aBox.contains(b,P,c));
Assert.assertFalse(aBox.contains(b,S,literal1));
Assert.assertFalse(aBox.contains(a,Q,d));
Assert.assertFalse(aBox.contains(a,T,literal2));
}
/*
* sameAs with datatype properties
*/
@Test
public void addABoxAssertion2() {
OntModel tBox = createTBoxModel();
OntProperty desc = tBox.createDatatypeProperty("http://test.vivo/desc");
desc.setLabel("property desc", "en-US");
Literal desc1 = tBox.createLiteral("individual 1");
Literal desc2 = tBox.createLiteral("individual 2");
// this is the model to receive inferences
Model inf = ModelFactory.createDefaultModel();
// create an ABox and register the SimpleReasoner listener with it
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
aBox.register(new SimpleReasoner(tBox, aBox, inf));
// Individuals a and b
Resource a = aBox.createResource("http://test.vivo/a");
Resource b = aBox.createResource("http://test.vivo/b");
aBox.add(a,desc,desc1);
aBox.add(b,desc,desc2);
aBox.add(a,OWL.sameAs,b);
Assert.assertTrue(inf.contains(a,desc,desc2));
Assert.assertTrue(inf.contains(b,desc,desc1));
Assert.assertTrue(inf.contains(b,OWL.sameAs,a));
}
/*
* basic scenario of removing an abox assertion for
* an individual is sameAs another.
*/
@Test
public void removeABoxAssertion1() {
OntModel tBox = createTBoxModel();
OntProperty P = createObjectProperty(tBox, "http://test.vivo/P", "property P");
OntProperty Q = createObjectProperty(tBox, "http://test.vivo/Q", "property Q");
OntProperty S = createObjectProperty(tBox, "http://test.vivo/S", "property S");
OntProperty T = createObjectProperty(tBox, "http://test.vivo/T", "property T");
Literal literal1 = tBox.createLiteral("Literal value 1");
Literal literal2 = tBox.createLiteral("Literal value 2");
// this is the model to receive inferences
Model inf = ModelFactory.createDefaultModel();
// create an ABox and register the SimpleReasoner listener with it
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
aBox.register(new SimpleReasoner(tBox, aBox, inf));
// Individuals a, b, c and d
Resource a = aBox.createResource("http://test.vivo/a");
Resource b = aBox.createResource("http://test.vivo/b");
Resource c = aBox.createResource("http://test.vivo/c");
Resource d = aBox.createResource("http://test.vivo/d");
aBox.add(a,P,c);
aBox.add(a,S,literal1);
aBox.add(b,Q,d);
aBox.add(b,T,literal2);
aBox.add(a,OWL.sameAs,b);
aBox.remove(a,P,c);
aBox.remove(a,S,literal1);
Assert.assertFalse(inf.contains(b,P,c));
Assert.assertFalse(inf.contains(b,S,literal1));
}
/*
* adding and removing an inverseOf assertion for individuals who
* are sameAs each other.
*/
@Test
public void tBoxInverseAssertion1() throws InterruptedException {
OntModel tBox = createTBoxModel();
OntProperty P = createObjectProperty(tBox, "http://test.vivo/P", "property P");
OntProperty Q = createObjectProperty(tBox, "http://test.vivo/Q", "property Q");
// Create ABox and Inference models and register
// the ABox reasoner listeners with the ABox and TBox
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
Model inf = ModelFactory.createDefaultModel();
SimpleReasoner simpleReasoner = new SimpleReasoner(tBox, aBox, inf);
aBox.register(simpleReasoner);
SimpleReasonerTBoxListener simpleReasonerTBoxListener = getTBoxListener(simpleReasoner);
tBox.register(simpleReasonerTBoxListener);
// Individuals a and b
Resource a = aBox.createResource("http://test.vivo/a");
Resource b = aBox.createResource("http://test.vivo/b");
// abox statements
aBox.add(a,P,b);
aBox.add(a, OWL.sameAs,b);
setInverse(Q, P);
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
Assert.assertTrue(inf.contains(b,Q,a));
Assert.assertTrue(inf.contains(b,OWL.sameAs,a));
Assert.assertTrue(inf.contains(b,P,b));
Assert.assertTrue(inf.contains(a,Q,a));
removeInverse(Q, P);
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
Assert.assertFalse(inf.contains(b,Q,a));
Assert.assertTrue(inf.contains(b,OWL.sameAs,a));
Assert.assertTrue(inf.contains(b,P,b));
Assert.assertFalse(inf.contains(a,Q,a));
simpleReasonerTBoxListener.setStopRequested();
}
/*
* adding and removing a type assertion for an individual who has
* a sameAs individual.
*/
//@Test
public void tBoxTypeAssertion1() {
// Create a Tbox with a simple class hierarchy. B is a subclass of A.
OntModel tBox = createTBoxModel();
OntClass classA = createClass(tBox, "http://test.vivo/A", "class A");
OntClass classB = createClass(tBox, "http://test.vivo/B", "class B");
addSubclass(classA, classB);
// this is the model to receive inferences
Model inf = ModelFactory.createDefaultModel();
// create an ABox and register the SimpleReasoner listener with it
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
aBox.register(new SimpleReasoner(tBox, aBox, inf));
Resource x = aBox.createResource("http://test.vivo/x");
Resource y = aBox.createResource("http://test.vivo/y");
Resource z = aBox.createResource("http://test.vivo/z");
aBox.add(x,OWL.sameAs,y);
aBox.add(y,OWL.sameAs,z);
aBox.add(x,RDF.type,classB);
Assert.assertTrue(inf.contains(y,RDF.type,classB));
Assert.assertTrue(inf.contains(y,RDF.type,classA));
Assert.assertTrue(inf.contains(z,RDF.type,classB));
Assert.assertTrue(inf.contains(z,RDF.type,classA));
aBox.remove(x,RDF.type,classB);
Assert.assertFalse(inf.contains(y,RDF.type,classB));
Assert.assertFalse(inf.contains(y,RDF.type,classA));
Assert.assertFalse(inf.contains(z,RDF.type,classB));
Assert.assertFalse(inf.contains(z,RDF.type,classA));
}
/*
* adding and removing subclass assertion when there is an
* individual member who has a sameAs individual.
*/
//@Test
public void tBoxSubclassAssertion1() throws InterruptedException {
// Create a Tbox with a simple class hierarchy. B is a subclass of A.
OntModel tBox = createTBoxModel();
OntClass classA = createClass(tBox, "http://test.vivo/A", "class A");
OntClass classB = createClass(tBox, "http://test.vivo/B", "class B");
OntClass classC = createClass(tBox, "http://test.vivo/C", "class C");
//create aBox and SimpleReasoner to listen to them
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
Model inf = ModelFactory.createDefaultModel();
SimpleReasoner simpleReasoner = new SimpleReasoner(tBox, aBox, inf);
aBox.register(simpleReasoner);
SimpleReasonerTBoxListener simpleReasonerTBoxListener = getTBoxListener(simpleReasoner);
tBox.register(simpleReasonerTBoxListener);
// set up ABox
Resource a = aBox.createResource("http://test.vivo/a");
Resource b = aBox.createResource("http://test.vivo/b");
Resource c = aBox.createResource("http://test.vivo/c");
aBox.add(a, RDF.type, classC);
aBox.add(a, OWL.sameAs, b);
aBox.add(c, OWL.sameAs, a);
// update TBox
addSubclass(classA, classB);
// wait for SimpleReasonerTBoxListener thread to end
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
addSubclass(classB, classC);
// wait for SimpleReasonerTBoxListener thread to end
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
// Verify inferences
Assert.assertFalse(inf.contains(a, RDF.type, classC));
Assert.assertTrue(inf.contains(a, RDF.type, classB));
Assert.assertTrue(inf.contains(a, RDF.type, classA));
Assert.assertTrue(inf.contains(b, RDF.type, classC));
Assert.assertTrue(inf.contains(b, RDF.type, classB));
Assert.assertTrue(inf.contains(b, RDF.type, classA));
Assert.assertTrue(inf.contains(c, RDF.type, classC));
Assert.assertTrue(inf.contains(c, RDF.type, classB));
Assert.assertTrue(inf.contains(c, RDF.type, classA));
// update TBox
removeSubclass(classA, classB);
// wait for SimpleReasonerTBoxListener thread to end
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
// Verify inferences
Assert.assertFalse(inf.contains(a, RDF.type, classC));
Assert.assertTrue(inf.contains(a, RDF.type, classB));
Assert.assertFalse(inf.contains(a, RDF.type, classA));
Assert.assertTrue(inf.contains(b, RDF.type, classC));
Assert.assertTrue(inf.contains(b, RDF.type, classB));
Assert.assertFalse(inf.contains(b, RDF.type, classA));
Assert.assertTrue(inf.contains(c, RDF.type, classC));
Assert.assertTrue(inf.contains(c, RDF.type, classB));
Assert.assertFalse(inf.contains(c, RDF.type, classA));
// update TBox
removeSubclass(classB, classC);
// wait for SimpleReasonerTBoxListener thread to end
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
// Verify inferences
Assert.assertFalse(inf.contains(a, RDF.type, classC));
Assert.assertFalse(inf.contains(a, RDF.type, classB));
Assert.assertFalse(inf.contains(a, RDF.type, classA));
Assert.assertTrue(inf.contains(b, RDF.type, classC));
Assert.assertFalse(inf.contains(b, RDF.type, classB));
Assert.assertFalse(inf.contains(b, RDF.type, classA));
Assert.assertTrue(inf.contains(c, RDF.type, classC));
Assert.assertFalse(inf.contains(c, RDF.type, classB));
Assert.assertFalse(inf.contains(c, RDF.type, classA));
simpleReasonerTBoxListener.setStopRequested();
}
/*
* test that mostSpecificType inferences propagate to sameAs
* individuals
*/
//@Test
public void mostSpecificTypeTest1() {
// Create a Tbox with a simple class hierarchy. B is a subclass of A.
OntModel tBox = createTBoxModel();
OntClass classA = createClass(tBox, "http://test.vivo/A", "class A");
OntClass classC = createClass(tBox, "http://test.vivo/B", "class C");
OntClass classD = createClass(tBox, "http://test.vivo/B", "class D");
OntClass classE = createClass(tBox, "http://test.vivo/B", "class E");
addSubclass(classA, classC);
addSubclass(classC, classD);
addSubclass(classC, classE);
// SimpleReasonerTBoxListener is not being used.
AnnotationProperty mostSpecificType = tBox.createAnnotationProperty(mostSpecificTypePropertyURI);
// this will receive the abox inferences
Model inf = ModelFactory.createDefaultModel();
// abox
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
// set up SimpleReasoner and register it with abox
SimpleReasoner simpleReasoner = new SimpleReasoner(tBox, aBox, inf);
aBox.register(simpleReasoner);
// add & remove ABox type statements and verify inferences
Resource a = aBox.createResource("http://test.vivo/a");
Resource b = aBox.createResource("http://test.vivo/b");
Resource c = aBox.createResource("http://test.vivo/c");
Resource d = aBox.createResource("http://test.vivo/d");
aBox.add(a, OWL.sameAs, b);
aBox.add(c, OWL.sameAs, b);
aBox.add(d, OWL.sameAs, a);
aBox.add(a, RDF.type, classD);
aBox.add(d, RDF.type, classC);
Assert.assertFalse(inf.contains(a,RDF.type,classD));
Assert.assertTrue(inf.contains(a,RDF.type,classC));
Assert.assertTrue(inf.contains(b,RDF.type, classD));
Assert.assertTrue(inf.contains(b,RDF.type, classC));
Assert.assertTrue(inf.contains(c,RDF.type, classD));
Assert.assertTrue(inf.contains(c,RDF.type, classC));
Assert.assertTrue(inf.contains(d,RDF.type, classD));
Assert.assertFalse(inf.contains(d,RDF.type, classC));
Assert.assertTrue(inf.contains(a, mostSpecificType, ResourceFactory.createResource(classD.getURI())));
Assert.assertTrue(inf.contains(b, mostSpecificType, ResourceFactory.createResource(classD.getURI())));
Assert.assertTrue(inf.contains(c, mostSpecificType, ResourceFactory.createResource(classD.getURI())));
Assert.assertTrue(inf.contains(d, mostSpecificType, ResourceFactory.createResource(classD.getURI())));
Assert.assertFalse(inf.contains(a, mostSpecificType, ResourceFactory.createResource(classC.getURI())));
Assert.assertFalse(inf.contains(b, mostSpecificType, ResourceFactory.createResource(classC.getURI())));
Assert.assertFalse(inf.contains(c, mostSpecificType, ResourceFactory.createResource(classC.getURI())));
Assert.assertFalse(inf.contains(d, mostSpecificType, ResourceFactory.createResource(classC.getURI())));
aBox.remove(a, RDF.type, classD);
Assert.assertFalse(inf.contains(a,RDF.type,classD));
Assert.assertTrue(inf.contains(a,RDF.type,classC));
Assert.assertFalse(inf.contains(b,RDF.type, classD));
Assert.assertTrue(inf.contains(b,RDF.type, classC));
Assert.assertFalse(inf.contains(c,RDF.type, classD));
Assert.assertTrue(inf.contains(c,RDF.type, classC));
Assert.assertFalse(inf.contains(d,RDF.type, classD));
Assert.assertFalse(inf.contains(d,RDF.type, classC));
Assert.assertTrue(inf.contains(a, mostSpecificType, ResourceFactory.createResource(classC.getURI())));
Assert.assertTrue(inf.contains(b, mostSpecificType, ResourceFactory.createResource(classC.getURI())));
Assert.assertTrue(inf.contains(c, mostSpecificType, ResourceFactory.createResource(classC.getURI())));
Assert.assertTrue(inf.contains(d, mostSpecificType, ResourceFactory.createResource(classC.getURI())));
Assert.assertFalse(inf.contains(a, mostSpecificType, ResourceFactory.createResource(classD.getURI())));
Assert.assertFalse(inf.contains(b, mostSpecificType, ResourceFactory.createResource(classD.getURI())));
Assert.assertFalse(inf.contains(c, mostSpecificType, ResourceFactory.createResource(classD.getURI())));
Assert.assertFalse(inf.contains(d, mostSpecificType, ResourceFactory.createResource(classD.getURI())));
}
/*
* Basic scenario around recomputing the ABox inferences
*/
@Test
public void recomputeABox1() throws InterruptedException {
OntModel tBox = createTBoxModel();
OntProperty P = createObjectProperty(tBox, "http://test.vivo/P", "property P");
OntProperty Q = createObjectProperty(tBox, "http://test.vivo/Q", "property Q");
OntProperty S = createObjectProperty(tBox, "http://test.vivo/S", "property S");
OntProperty T = createObjectProperty(tBox, "http://test.vivo/T", "property T");
Literal literal1 = tBox.createLiteral("Literal value 1");
Literal literal2 = tBox.createLiteral("Literal value 2");
// this is the model to receive inferences
Model inf = ModelFactory.createDefaultModel();
// create an ABox and register the SimpleReasoner listener with it
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
SimpleReasoner simpleReasoner = new SimpleReasoner(tBox, aBox, inf);
aBox.register(simpleReasoner);
// Individuals a, b, c and d
Resource a = aBox.createIndividual("http://test.vivo/a", OWL.Thing);
Resource b = aBox.createIndividual("http://test.vivo/b", OWL.Thing);
Resource c = aBox.createIndividual("http://test.vivo/c", OWL.Thing);
Resource d = aBox.createIndividual("http://test.vivo/d", OWL.Thing);
aBox.add(a,P,c);
aBox.add(a,S,literal1);
aBox.add(b,Q,d);
aBox.add(b,T,literal2);
aBox.add(a,OWL.sameAs,b);
Assert.assertTrue(inf.contains(b,OWL.sameAs,a));
Assert.assertTrue(inf.contains(b,P,c));
Assert.assertTrue(inf.contains(b,S,literal1));
Assert.assertTrue(inf.contains(a,Q,d));
Assert.assertTrue(inf.contains(a,T,literal2));
inf.remove(b,OWL.sameAs,a);
inf.remove(b,P,c);
inf.remove(b,S,literal1);
inf.remove(a,Q,d);
inf.remove(a,T,literal2);
simpleReasoner.recompute();
while (simpleReasoner.isRecomputing()) {
Thread.sleep(delay);
}
// Verify inferences
Assert.assertTrue(inf.contains(b,OWL.sameAs,a));
Assert.assertTrue(inf.contains(b,P,c));
Assert.assertTrue(inf.contains(b,S,literal1));
Assert.assertTrue(inf.contains(a,Q,d));
Assert.assertTrue(inf.contains(a,T,literal2));
}
//==================================== Utility methods ====================
SimpleReasonerTBoxListener getTBoxListener(SimpleReasoner simpleReasoner) {
return new SimpleReasonerTBoxListener(simpleReasoner, new Exception().getStackTrace()[1].getMethodName());
}
// To help in debugging the unit test
void printModel(Model model, String modelName) {
System.out.println("\nThe " + modelName + " model has " + model.size() + " statements:");
System.out.println("---------------------------------------------------------------------");
model.write(System.out);
}
// To help in debugging the unit test
void printModel(OntModel ontModel, String modelName) {
System.out.println("\nThe " + modelName + " model has " + ontModel.size() + " statements:");
System.out.println("---------------------------------------------------------------------");
ontModel.writeAll(System.out,"N3",null);
}
}

View file

@ -0,0 +1,232 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.reasoner;
import java.util.HashSet;
import java.util.Set;
import com.hp.hpl.jena.ontology.ObjectProperty;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.ontology.OntProperty;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
/**
* We're using a simple OntModel as the TBox in the SimpleReasoner tests, so we
* don't get tied to a particular TBox reasoner (like Pellet).
*
* But the SimpleReasoner expects certain elementary reasoning, so these methods
* impose that reasoning on the model.
*
* On the model: Thing is a class.
*
* On classes: Every class is equivalent to itself, a subclass of itself, and a
* subclass of Thing. Every class is a subclass of all its ancestors and a
* superclass of all its descendants. Every class has the same superclasses and
* subclasses as do all of its equivalent classes.
*
* On object properties: Every object property is equivalent to itself and a
* subproperty of itself. Every object property has the same inverses as do all
* of its equivalent properties.
*
* ----------------------
*
* It's a little silly to implement this as a parent class of the unit tests. It
* would have been nicer to find a way that is more object-oriented but still
* explicit in what "reasoning" is performed. This will do for now.
*/
public class SimpleReasonerTBoxHelper extends AbstractTestClass {
private static String URI_THING = "http://www.w3.org/2002/07/owl#Thing";
// ----------------------------------------------------------------------
// The model
// ----------------------------------------------------------------------
protected OntModel createTBoxModel() {
OntModel tBox = ModelFactory
.createOntologyModel(OntModelSpec.OWL_DL_MEM);
createClass(tBox, URI_THING, "OWL Thing");
return tBox;
}
// ----------------------------------------------------------------------
// Classes
// ----------------------------------------------------------------------
protected OntClass createClass(OntModel tBox, String uri, String label) {
OntClass s = tBox.createClass(uri);
s.setLabel(label, "en-US");
s.addEquivalentClass(s);
s.addSubClass(s);
thing(tBox).addSubClass(s);
return s;
}
private OntClass thing(OntModel tBox) {
return tBox.getOntClass(URI_THING);
}
/**
* Make sure that you establish subclass relationships before setting
* equivalent classes.
*/
protected void setEquivalent(OntClass c1, OntClass c2) {
setEquivalentClasses(equivalences(c1), equivalences(c2));
setEquivalentClasses(equivalences(c2), equivalences(c1));
c1.addEquivalentClass(c2);
c2.addEquivalentClass(c1);
copySubClasses(c1, c2);
copySubClasses(c2, c1);
copySuperClasses(c1, c2);
copySuperClasses(c2, c1);
}
private void setEquivalentClasses(Set<OntClass> equivalences1,
Set<OntClass> equivalences2) {
for (OntClass c1 : equivalences1) {
for (OntClass c2 : equivalences2) {
c1.addEquivalentClass(c2);
}
}
}
private void copySubClasses(OntClass c1, OntClass c2) {
for (OntClass sub : c1.listSubClasses().toList()) {
c2.addSubClass(sub);
}
}
private void copySuperClasses(OntClass c1, OntClass c2) {
for (OntClass sup : c1.listSuperClasses().toList()) {
c2.addSuperClass(sup);
}
}
private Set<OntClass> equivalences(OntClass c1) {
return new HashSet<OntClass>(c1.listEquivalentClasses().toList());
}
protected void addSubclass(OntClass parent, OntClass child) {
addSubclass(equivalences(parent), equivalences(child));
}
private void addSubclass(Set<OntClass> equivalentParents,
Set<OntClass> equivalentChildren) {
for (OntClass parent : equivalentParents) {
for (OntClass child : equivalentChildren) {
parent.addSubClass(child);
for (OntClass ancestor : parent.listSuperClasses().toList()) {
ancestor.addSubClass(child);
}
for (OntClass descendant : child.listSubClasses().toList()) {
parent.addSubClass(descendant);
}
}
}
}
protected void removeSubclass(OntClass parent, OntClass child) {
removeSubclass(equivalences(parent), equivalences(child));
}
/**
* This has the potential for problems if we set this up:
*
* <pre>
* A -> B -> C
*
* explicit add A -> C
*
* remove A -> B
* </pre>
*
* But why would we do that?
*/
private void removeSubclass(Set<OntClass> equivalentParents,
Set<OntClass> equivalentChildren) {
for (OntClass parent : equivalentParents) {
for (OntClass child : equivalentChildren) {
parent.removeSubClass(child);
for (OntClass ancestor : parent.listSuperClasses().toList()) {
ancestor.removeSubClass(child);
}
for (OntClass descendant : child.listSubClasses().toList()) {
parent.removeSubClass(descendant);
}
}
}
}
// ----------------------------------------------------------------------
// Object properties
// ----------------------------------------------------------------------
protected ObjectProperty createObjectProperty(OntModel tBox, String uri,
String label) {
ObjectProperty p = tBox.createObjectProperty(uri);
p.setLabel(label, "en-US");
p.addEquivalentProperty(p);
p.addSubProperty(p);
return p;
}
protected void setEquivalent(OntProperty p1, OntProperty p2) {
setEquivalentProperty(equivalences(p1), equivalences(p2));
setEquivalentProperty(equivalences(p2), equivalences(p1));
copyInverses(p1, p2);
copyInverses(p2, p1);
}
private void setEquivalentProperty(Set<OntProperty> equivalences1,
Set<OntProperty> equivalences2) {
for (OntProperty p1 : equivalences1) {
for (OntProperty p2 : equivalences2) {
p1.addEquivalentProperty(p2);
}
}
}
private void copyInverses(OntProperty p1, OntProperty p2) {
for (OntProperty inv : p1.listInverse().toList()) {
p2.addInverseOf(inv);
}
}
protected void setInverse(OntProperty p1, OntProperty p2) {
setInverse(equivalences(p1), equivalences(p2));
setInverse(equivalences(p2), equivalences(p1));
}
private void setInverse(Set<OntProperty> equivalences1,
Set<OntProperty> equivalences2) {
for (OntProperty p1 : equivalences1) {
for (OntProperty p2 : equivalences2) {
p1.addInverseOf(p2);
}
}
}
protected void removeInverse(OntProperty p1, OntProperty p2) {
removeInverse(equivalences(p1), equivalences(p2));
removeInverse(equivalences(p2), equivalences(p1));
}
private void removeInverse(Set<OntProperty> equivalences1,
Set<OntProperty> equivalences2) {
for (OntProperty p1 : equivalences1) {
for (OntProperty p2 : equivalences2) {
p1.removeInverseProperty(p2);
}
}
}
private Set<OntProperty> equivalences(OntProperty p) {
return new HashSet<OntProperty>(p.listEquivalentProperties().toSet());
}
}

View file

@ -0,0 +1,874 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.reasoner;
import org.apache.log4j.Level;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import com.hp.hpl.jena.ontology.AnnotationProperty;
import com.hp.hpl.jena.ontology.OntClass;
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.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDF;
import edu.cornell.mannlib.vitro.webapp.utils.threads.VitroBackgroundThread;
public class SimpleReasonerTest extends SimpleReasonerTBoxHelper {
private static final String mostSpecificTypePropertyURI = "http://vitro.mannlib.cornell.edu/ns/vitro/0.7#mostSpecificType";
long delay = 50;
@Before
public void suppressErrorOutput() {
suppressSyserr();
//Turn off log messages to console
setLoggerLevel(SimpleReasoner.class, Level.OFF);
setLoggerLevel(SimpleReasonerTBoxListener.class, Level.OFF);
}
@Test
public void addABoxTypeAssertion1Test(){
addABoxTypeAssertion1(true);
}
@Test
public void addABoxTypeAssertion1NoSameAsTest(){
addABoxTypeAssertion1(false);
}
/*
* Test that when an individual is asserted to be of a type,
* its asserted type is not added to the inference graph
*/
public void addABoxTypeAssertion1( boolean sameAsEnabled ){
// Create a Tbox with a simple class hierarchy. B is a subclass of A.
OntModel tBox = createTBoxModel();
OntClass classA = createClass(tBox, "http://test.vivo/A", "class A");
OntClass classB = createClass(tBox, "http://test.vivo/B", "class B");
classA.addSubClass(classB);
// this is the model to receive inferences
Model inf = ModelFactory.createDefaultModel();
// create an ABox and register the SimpleReasoner listener with it
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
SimpleReasoner simpleReasoner = new SimpleReasoner(tBox, aBox, inf);
simpleReasoner.setSameAsEnabled( sameAsEnabled );
aBox.register(simpleReasoner);
// Individual x
Resource ind_x = aBox.createResource("http://test.vivo/x");
// add a statement to the ABox that individual x is of type (i.e. is an instance of) B.
Statement xisb = ResourceFactory.createStatement(ind_x, RDF.type, classB);
aBox.add(xisb);
// Verify that "x is of type B" was not inferred
Assert.assertFalse(inf.contains(xisb));
}
@Test
public void addABoxTypeAssertion2Test(){
addABoxTypeAssertion2(true);
}
@Test
public void addABoxTypeAssertion2NoSameAs(){
addABoxTypeAssertion2(false);
}
/*
* Test that when an individual is asserted have a type,
* that inferences are materialized that it has the types
* of its superclasses
*/
public void addABoxTypeAssertion2(boolean enableSameAs){
// Create a Tbox with a simple class hierarchy. D and E are subclasses
// of C. B and C are subclasses of A.
OntModel tBox = createTBoxModel();
OntClass classA = createClass(tBox, "http://test.vivo/A", "class A");
OntClass classB = createClass(tBox, "http://test.vivo/B", "class B");
OntClass classC = createClass(tBox, "http://test.vivo/C", "class C");
OntClass classD = createClass(tBox, "http://test.vivo/D", "class D");
OntClass classE = createClass(tBox, "http://test.vivo/E", "class E");
addSubclass(classA, classB);
addSubclass(classA, classC);
addSubclass(classC, classD);
addSubclass(classC, classE);
// this is the model to receive inferences
Model inf = ModelFactory.createDefaultModel();
// create an Abox and register the SimpleReasoner listener with it
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
SimpleReasoner sr = new SimpleReasoner(tBox, aBox, inf);
sr.setSameAsEnabled( enableSameAs );
aBox.register( sr );
// add a statement to the ABox that individual x is of type E.
Resource ind_x = aBox.createResource("http://test.vivo/x");
aBox.add(ind_x, RDF.type, classE);
// Verify that "x is of type C" was inferred
Statement xisc = ResourceFactory.createStatement(ind_x, RDF.type, classC);
Assert.assertTrue(inf.contains(xisc));
// Verify that "x is of type A" was inferred
Statement xisa = ResourceFactory.createStatement(ind_x, RDF.type, classA);
Assert.assertTrue(inf.contains(xisa));
}
@Test
public void addABoxTypeAssertion3Test() throws InterruptedException{
addABoxTypeAssertion3(true);
}
@Test
public void addABoxTypeAssertion3NoSameAs() throws InterruptedException{
addABoxTypeAssertion3(false);
}
/*
* Test inference based on class equivalence
*/
public void addABoxTypeAssertion3(boolean enableSameAs) throws InterruptedException {
// Add classes A, B and C to the TBox
// A is equivalent to B
// C is a subclass of A
OntModel tBox = createTBoxModel();
OntClass classA = createClass(tBox, "http://test.vivo/A", "class A");
OntClass classB = createClass(tBox, "http://test.vivo/B", "class B");
OntClass classC = createClass(tBox, "http://test.vivo/C", "class C");
addSubclass(classA, classC);
setEquivalent(classA, classB);
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
Model inf = ModelFactory.createDefaultModel();
SimpleReasoner sr = new SimpleReasoner(tBox, aBox, inf);
sr.setSameAsEnabled( enableSameAs );
SimpleReasoner simpleReasoner = sr ;
aBox.register(simpleReasoner);
SimpleReasonerTBoxListener simpleReasonerTBoxListener = getTBoxListener(simpleReasoner);
tBox.register(simpleReasonerTBoxListener);
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
// Add a statement that individual x is of type C to the ABox
Resource ind_x = aBox.createResource("http://test.vivo/x");
aBox.add(ind_x, RDF.type, classC);
// Verify that "x is of type A" was inferred
Statement xisa = ResourceFactory.createStatement(ind_x, RDF.type, classA);
Assert.assertTrue(inf.contains(xisa));
// Verify that "x is of type B" was inferred
Statement xisb = ResourceFactory.createStatement(ind_x, RDF.type, classB);
Assert.assertTrue(inf.contains(xisb));
simpleReasonerTBoxListener.setStopRequested();;
}
@Test
public void addABoxTypeAssertion4Test()throws InterruptedException{
addABoxTypeAssertion4(true);
}
@Test
public void addABoxTypeAssertion4NoSameAs()throws InterruptedException{
addABoxTypeAssertion4(false);
}
/*
* Test inference based on class equivalence
*/
public void addABoxTypeAssertion4(boolean enableSameAs) throws InterruptedException {
// Add classes A and B to the TBox
// A is equivalent to B
OntModel tBox = createTBoxModel();
OntClass classA = createClass(tBox, "http://test.vivo/A", "class A");
OntClass classB = createClass(tBox, "http://test.vivo/B", "class B");
setEquivalent(classA, classB);
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
Model inf = ModelFactory.createDefaultModel();
SimpleReasoner sr = new SimpleReasoner(tBox, aBox, inf);
sr.setSameAsEnabled( enableSameAs );
SimpleReasoner simpleReasoner = sr ;
aBox.register(simpleReasoner);
SimpleReasonerTBoxListener simpleReasonerTBoxListener = getTBoxListener(simpleReasoner);
tBox.register(simpleReasonerTBoxListener);
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
// Add a statement that individual x is of type B to the ABox
Resource ind_x = aBox.createResource("http://test.vivo/x");
aBox.add(ind_x, RDF.type, classB);
// Verify that "x is of type A" was inferred
Statement xisa = ResourceFactory.createStatement(ind_x, RDF.type, classA);
Assert.assertTrue(inf.contains(xisa));
simpleReasonerTBoxListener.setStopRequested();
}
@Test
public void addABoxTypeAssertion5Test()throws InterruptedException{
addABoxTypeAssertion5(true);
}
@Test
public void addABoxTypeAssertion5NoSameAs()throws InterruptedException{
addABoxTypeAssertion5(false);
}
/*
* Test inference based on class equivalence
*/
public void addABoxTypeAssertion5(boolean enableSameAs) throws InterruptedException {
// Add classes classes A and B to the TBox
// A is equivalent to B
OntModel tBox = createTBoxModel();
OntClass classA = createClass(tBox, "http://test.vivo/A", "class A");
OntClass classB = createClass(tBox, "http://test.vivo/B", "class B");
setEquivalent(classA, classB);
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
Model inf = ModelFactory.createDefaultModel();
SimpleReasoner sr = new SimpleReasoner(tBox, aBox, inf);
sr.setSameAsEnabled( enableSameAs );
SimpleReasoner simpleReasoner = sr ;
aBox.register(simpleReasoner);
SimpleReasonerTBoxListener simpleReasonerTBoxListener = getTBoxListener(simpleReasoner);
tBox.register(simpleReasonerTBoxListener);
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
// Add a statement that individual x is of type B to the ABox
Resource ind_x = aBox.createResource("http://test.vivo/x");
aBox.add(ind_x, RDF.type, classB);
// Verify that "x is of type A" was inferred
Statement xisa = ResourceFactory.createStatement(ind_x, RDF.type, classA);
Assert.assertTrue(inf.contains(xisa));
// Remove the statement that x is of type B from the ABox
aBox.remove(ind_x, RDF.type, classB);
// Verify that "x is of type A" was removed from the inference graph
Assert.assertFalse(inf.contains(xisa));
simpleReasonerTBoxListener.setStopRequested();
}
@Test
public void removeABoxTypeAssertion1Test() {
removeABoxTypeAssertion1(true);
}
@Test
public void removeABoxTypeAssertion1NoSameAs() {
removeABoxTypeAssertion1(false);
}
/*
* Test that when it is retracted that an individual is of a type,
* that the inferences that it is of the type of all superclasses
* of the retracted type are retracted from the inference graph.
* However, any assertions that are otherwise entailed (by the
* TBox, ABox and inference graph minus the retracted type statement)
* should not be retracted.
*/
public void removeABoxTypeAssertion1(boolean enableSameAs){
// Create a Tbox with a simple class hierarchy. C is a subclass of B
// and B is a subclass of A.
OntModel tBox = createTBoxModel();
OntClass classA = createClass(tBox, "http://test.vivo/A", "class A");
OntClass classB = createClass(tBox, "http://test.vivo/B", "class B");
OntClass classC = createClass(tBox, "http://test.vivo/C", "class C");
addSubclass(classB, classC);
addSubclass(classA, classB);
// this is the model to receive inferences
Model inf = ModelFactory.createDefaultModel();
// create an Abox and register the SimpleReasoner listener with it
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
SimpleReasoner sr = new SimpleReasoner(tBox, aBox, inf);
sr.setSameAsEnabled( enableSameAs );
aBox.register( sr );
// add a statement to the ABox that individual x is of type C.
Resource ind_x = aBox.createResource("http://test.vivo/x");
aBox.add(ind_x, RDF.type, classC);
// add a statement to the ABox that individual x is of type B.
aBox.add(ind_x, RDF.type, classB);
// remove the statement that individual x is of type C
aBox.remove(ind_x, RDF.type, classC);
// Verify that the inference graph contains the statement that x is of type A.
Statement xisa = ResourceFactory.createStatement(ind_x, RDF.type, classA);
Assert.assertTrue(inf.contains(xisa));
// Hopefully the assertion that x is b got removed from
// the inference graph
Statement xisb = ResourceFactory.createStatement(ind_x, RDF.type, classB);
Assert.assertFalse(inf.contains(xisb));
}
@Test
public void addTBoxSubClassAssertion1Test()throws InterruptedException{
addTBoxSubClassAssertion1(true);
}
@Test
public void addTBoxSubClassAssertion1NoSameAs()throws InterruptedException{
addTBoxSubClassAssertion1(false);
}
/*
* Test the addition of a subClassOf statement to
* the TBox. The instance data that is the basis
* for the inference is in the ABox. The existing
* instance of the newly declared subclass should
* be inferred to have the type of the superclass.
* There are also a few checks that the instance
* is not inferred to have the types of some other
* random classes.
*
* Since the addition of an owl:equivalentClass
* statement is implemented as two calls to the
* method that handles the addition of an
* rdfs:subClassOf statement, this test serves
* as a test of equivalentClass statements also.
*/
public void addTBoxSubClassAssertion1(boolean enableSameAs) throws InterruptedException {
// Create the TBox and add classes A, B, C and D
OntModel tBox = createTBoxModel();
OntClass classA = createClass(tBox, "http://test.vivo/A", "class A");
OntClass classB = createClass(tBox, "http://test.vivo/B", "class B");
OntClass classC = createClass(tBox, "http://test.vivo/C", "class C");
OntClass classD = createClass(tBox, "http://test.vivo/D", "class D");
// Create ABox and Inference models and register
// the ABox reasoner listeners with the ABox and TBox
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
Model inf = ModelFactory.createDefaultModel();
SimpleReasoner sr = new SimpleReasoner(tBox, aBox, inf);
sr.setSameAsEnabled( enableSameAs );
SimpleReasoner simpleReasoner = sr ;
aBox.register(simpleReasoner);
SimpleReasonerTBoxListener simpleReasonerTBoxListener = getTBoxListener(simpleReasoner);
tBox.register(simpleReasonerTBoxListener);
// Add a statement that individual x is of type C to the ABox
Resource ind_x = aBox.createResource("http://test.vivo/x");
aBox.add(ind_x, RDF.type, classC);
// Add a statement that C is a subclass of A to the TBox
addSubclass(classA, classC);
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
// Verify that "x is of type A" was inferred
Statement xisa = ResourceFactory.createStatement(ind_x, RDF.type, classA);
Assert.assertTrue(inf.contains(xisa));
// Verify that "x is of type B" was not inferred
Statement xisb = ResourceFactory.createStatement(ind_x, RDF.type, classB);
Assert.assertFalse(inf.contains(xisb));
// Verify that "x is of type D" was not inferred
Statement xisd = ResourceFactory.createStatement(ind_x, RDF.type, classD);
Assert.assertFalse(inf.contains(xisd));
simpleReasonerTBoxListener.setStopRequested();
}
@Test
public void addTBoxSubClassAssertion2Test()throws InterruptedException{
addTBoxSubClassAssertion2(true);
}
@Test
public void addTBoxSubClassAssertion2NoSameAs()throws InterruptedException{
addTBoxSubClassAssertion2(false);
}
/*
* Test the addition of a subClassOf statement to
* the TBox. The instance data that is the basis
* for the inference is in the ABox graph and the
* inference graph. The existing instance of the
* subclass of the newly added subclass should
* be inferred to have the type of the superclass
* of the newly added subclass.
*
* Since the addition of an owl:equivalentClass
* statement is implemented as two calls to the
* method that handles the addition of an
* rdfs:subClassOf statement, this test serves
* as some test of equivalentClass statements also.
*
*/
public void addTBoxSubClassAssertion2(boolean enableSameAs) throws InterruptedException {
// Create the TBox and add classes A, B, C and D.
// D is a subclass of C.
OntModel tBox = createTBoxModel();
OntClass classA = createClass(tBox, "http://test.vivo/A", "class A");
OntClass classB = createClass(tBox, "http://test.vivo/B", "class B");
OntClass classC = createClass(tBox, "http://test.vivo/C", "class C");
OntClass classD = createClass(tBox, "http://test.vivo/D", "class D");
addSubclass(classC, classD);
// Create ABox and Inference models and register
// the ABox reasoner listeners with the ABox and TBox
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
Model inf = ModelFactory.createDefaultModel();
SimpleReasoner sr = new SimpleReasoner(tBox, aBox, inf);
sr.setSameAsEnabled( enableSameAs );
SimpleReasoner simpleReasoner = sr ;
aBox.register(simpleReasoner);
SimpleReasonerTBoxListener simpleReasonerTBoxListener = getTBoxListener(simpleReasoner);
tBox.register(simpleReasonerTBoxListener);
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
// Add a statement that individual x is of type D to the ABox
Resource ind_x = aBox.createResource("http://test.vivo/x");
aBox.add(ind_x, RDF.type, classD);
// Add a statement that C is a subclass of A to the TBox
addSubclass(classA, classC);
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
// Verify that "x is of type A" was inferred
Statement xisa = ResourceFactory.createStatement(ind_x, RDF.type, classA);
Assert.assertTrue(inf.contains(xisa));
simpleReasonerTBoxListener.setStopRequested();
}
@Test
public void removeTBoxSubClassAssertion1Test()throws InterruptedException{
removeTBoxSubClassAssertion1(true);
}
@Test
public void removeTBoxSubClassAssertion1NoSameAs()throws InterruptedException{
removeTBoxSubClassAssertion1(false);
}
/*
* Test the removal of a subClassOf statement from
* the TBox. The instance data that is the basis
* for the inference is in the ABox graph and the
* inference graph.
*
*/
public void removeTBoxSubClassAssertion1(boolean enableSameAs) throws InterruptedException {
// Create the TBox and add classes A, B, C, D, E, F, G and H.
// B, C and D are subclasses of A.
// E is a subclass of B.
// F and G are subclasses of C.
// H is a subclass of D.
OntModel tBox = createTBoxModel();
OntClass classA = createClass(tBox, "http://test.vivo/A", "class A");
OntClass classB = createClass(tBox, "http://test.vivo/B", "class B");
OntClass classC = createClass(tBox, "http://test.vivo/C", "class C");
OntClass classD = createClass(tBox, "http://test.vivo/D", "class D");
OntClass classE = createClass(tBox, "http://test.vivo/E", "class E");
OntClass classF = createClass(tBox, "http://test.vivo/F", "class F");
OntClass classG = createClass(tBox, "http://test.vivo/G", "class G");
OntClass classH = createClass(tBox, "http://test.vivo/H", "class H");
addSubclass(classA, classB);
addSubclass(classA, classC);
addSubclass(classA, classD);
addSubclass(classB, classE);
addSubclass(classC, classF);
addSubclass(classC, classG);
addSubclass(classD, classH);
// Create ABox and Inference models and register
// the ABox reasoner listeners with the ABox and TBox
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
Model inf = ModelFactory.createDefaultModel();
SimpleReasoner sr = new SimpleReasoner(tBox, aBox, inf);
sr.setSameAsEnabled( enableSameAs );
SimpleReasoner simpleReasoner = sr ;
aBox.register(simpleReasoner);
SimpleReasonerTBoxListener simpleReasonerTBoxListener = getTBoxListener(simpleReasoner);
tBox.register(simpleReasonerTBoxListener);
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
// Add a statement that individual x is of type E to the ABox
Resource ind_x = aBox.createResource("http://test.vivo/x");
aBox.add(ind_x, RDF.type, classE);
// Remove the statement that B is a subclass of A from the TBox
removeSubclass(classA, classB);
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
// Verify that "x is of type A" is not in the inference graph
Statement xisa = ResourceFactory.createStatement(ind_x, RDF.type, classA);
Assert.assertFalse(inf.contains(xisa));
// Verify that "x is of type B" is in the inference graph
Statement xisb = ResourceFactory.createStatement(ind_x, RDF.type, classB);
Assert.assertTrue(inf.contains(xisb));
// Add statements that individual y is of types F and H to the ABox
Resource ind_y = aBox.createResource("http://test.vivo/y");
aBox.add(ind_y, RDF.type, classF);
aBox.add(ind_y, RDF.type, classH);
// Remove the statement that C is a subclass of A from the TBox
classA.removeSubClass(classC);
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
// Verify that "y is of type A" is in the inference graph
Statement yisa = ResourceFactory.createStatement(ind_y, RDF.type, classA);
Assert.assertTrue(inf.contains(yisa));
simpleReasonerTBoxListener.setStopRequested();
}
@Ignore(" needs TBoxReasoner infrastructure which is not in this suite.")
@Test
public void bcdTest()throws InterruptedException{
bcd(true);
}
@Ignore(" needs TBoxReasoner infrastructure which is not in this suite.")
@Test
public void bcdNoSameAsTest()throws InterruptedException{
bcd(false);
}
/*
* Test the removal of a subClassOf statement from
* the TBox. The instance data that is the basis
* for the inference is in the ABox graph and the
* inference graph.
*
*/
// this test would need TBoxReasoner infrastructure, which we're not
// testing in this suite. The reason it doesn't work as it is because
// the SimpleReasonerTBoxListener is not listening to the tBox inference
// model as the TBoxReasoner is updating it. I could simulate it by adding to the
// tBox assertions what we can count on the TBoxReasoner to infer.
public void bcd(boolean enableSameAs) throws InterruptedException {
OntModel tBox = createTBoxModel();
// Create ABox and Inference models and register
// the ABox reasoner listeners with the ABox and TBox
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
Model inf = ModelFactory.createDefaultModel();
SimpleReasoner simpleReasoner = new SimpleReasoner(tBox, aBox, inf);
simpleReasoner.setSameAsEnabled( enableSameAs );
aBox.register(simpleReasoner);
SimpleReasonerTBoxListener simpleReasonerTBoxListener = getTBoxListener(simpleReasoner);
tBox.register(simpleReasonerTBoxListener);
// Add classes LivingThing, Flora, Brassica to the TBox
// Brassica is a subClass of Flora and Flora is a subclass of Brassica
OntClass LivingThing = createClass(tBox, "http://test.vivo/LivingThing", "Living Thing");
OntClass Flora = createClass(tBox, "http://test.vivo/Flora", "Flora");
OntClass Brassica = createClass(tBox, "http://test.vivo/Brassica", "Brassica");
addSubclass(LivingThing, Flora);
addSubclass(Flora, Brassica);
tBox.rebind();
tBox.prepare();
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
// Add a statement that individual kale is of type Brassica to the ABox
Resource kale = aBox.createResource("http://test.vivo/kale");
aBox.add(kale, RDF.type, Brassica);
// Remove the statement that Brassica is a subclass of Flora from the TBox
Flora.removeSubClass(Brassica);
tBox.rebind();
tBox.prepare();
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
// Verify that "kale is of type Flora" is not in the inference graph
Statement kaleIsFlora = ResourceFactory.createStatement(kale, RDF.type, Flora);
Assert.assertFalse(inf.contains(kaleIsFlora));
// Verify that "kale is of type LivingThing" is not in the inference graph
Statement kaleIsLivingThing = ResourceFactory.createStatement(kale, RDF.type, LivingThing);
Assert.assertFalse(inf.contains(kaleIsLivingThing));
simpleReasonerTBoxListener.setStopRequested();
}
@Test
public void mstTest1Test()throws InterruptedException{
mstTest1(true);
}
@Test
public void mstTest1NoSameAs()throws InterruptedException{
mstTest1(false);
}
/*
* Test computation of mostSpecificType annotations in response
* to an added/removed ABox type assertion.
*/
public void mstTest1(boolean enableSameAs) throws InterruptedException {
// Set up the Tbox with a class hierarchy. C is a subclass of A
// and Y. D and E are subclasses of C. B is a subclass of D.
OntModel tBox = createTBoxModel();
OntClass classA = createClass(tBox, "http://test.vivo/A", "class A");
OntClass classB = createClass(tBox, "http://test.vivo/B", "class B");
OntClass classC = createClass(tBox, "http://test.vivo/C", "class C");
OntClass classD = createClass(tBox, "http://test.vivo/D", "class D");
OntClass classE = createClass(tBox, "http://test.vivo/E", "class E");
OntClass classY = createClass(tBox, "http://test.vivo/Y", "class Y");
addSubclass(classA, classC);
addSubclass(classY, classC);
addSubclass(classC, classD);
addSubclass(classC, classE);
addSubclass(classD, classB);
// Create ABox and Inference models and register
// the ABox reasoner listeners with the ABox and TBox
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
Model inf = ModelFactory.createDefaultModel();
SimpleReasoner sr = new SimpleReasoner(tBox, aBox, inf);
sr.setSameAsEnabled( enableSameAs );
SimpleReasoner simpleReasoner = sr ;
aBox.register(simpleReasoner);
SimpleReasonerTBoxListener simpleReasonerTBoxListener = getTBoxListener(simpleReasoner);
tBox.register(simpleReasonerTBoxListener);
AnnotationProperty mostSpecificType = tBox.createAnnotationProperty(mostSpecificTypePropertyURI);
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
// Add the statement individual x is of type Y to the ABox
Resource ind_x = aBox.createResource("http://test.vivo/x");
aBox.add(ind_x, RDF.type, classD);
// Verify ind_x mostSpecificType annotation for D
Assert.assertTrue(inf.contains(ind_x, mostSpecificType, ResourceFactory.createResource(classD.getURI())));
// Verify ind_x doesn't have a mostSpecificType annotation for
// A, Y, C, E or B.
Assert.assertFalse(aBox.contains(ind_x, mostSpecificType, ResourceFactory.createResource(classA.getURI())));
Assert.assertFalse(aBox.contains(ind_x, mostSpecificType, ResourceFactory.createResource(classY.getURI())));
Assert.assertFalse(aBox.contains(ind_x, mostSpecificType, ResourceFactory.createResource(classC.getURI())));
Assert.assertFalse(aBox.contains(ind_x, mostSpecificType, ResourceFactory.createResource(classE.getURI())));
Assert.assertFalse(aBox.contains(ind_x, mostSpecificType, ResourceFactory.createResource(classB.getURI())));
aBox.remove(ind_x, RDF.type, classD); // retract assertion that x is of type D.
// Verify that D is not longer the most specific type
Assert.assertFalse(inf.contains(ind_x, mostSpecificType, ResourceFactory.createResource(classD.getURI())));
simpleReasonerTBoxListener.setStopRequested();
}
@Test
public void mstTest2Test()throws InterruptedException{
mstTest2(true);
}
@Test
public void mstTest2NoSameAs()throws InterruptedException{
mstTest2(false);
}
/*
* Test computation of mostSpecificType annotations in response
* to an added ABox type assertion.
*/
public void mstTest2(boolean enableSameAs) throws InterruptedException {
// Set up the Tbox with a class hierarchy. A, B, and C are all equivalent.
// This implies that they are all subclasses of each other.
OntModel tBox = createTBoxModel();
OntClass classA = createClass(tBox, "http://test.vivo/A", "class A");
OntClass classB = createClass(tBox, "http://test.vivo/B", "class B");
OntClass classC = createClass(tBox, "http://test.vivo/C", "class C");
setEquivalent(classA, classB);
setEquivalent(classB, classC);
// Create ABox and Inference models and register
// the ABox reasoner listeners with the ABox and TBox
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
Model inf = ModelFactory.createDefaultModel();
SimpleReasoner sr = new SimpleReasoner(tBox, aBox, inf);
sr.setSameAsEnabled( enableSameAs );
SimpleReasoner simpleReasoner = sr ;
aBox.register(simpleReasoner);
SimpleReasonerTBoxListener simpleReasonerTBoxListener = getTBoxListener(simpleReasoner);
tBox.register(simpleReasonerTBoxListener);
AnnotationProperty mostSpecificType = tBox.createAnnotationProperty(mostSpecificTypePropertyURI);
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
// Add the statement individual x is of type B to the ABox
Resource ind_x = aBox.createResource("http://test.vivo/x");
aBox.add(ind_x, RDF.type, classB);
// Verify ind_x mostSpecificType annotation for A, B and C
Assert.assertTrue(inf.contains(ind_x, mostSpecificType, ResourceFactory.createResource(classA.getURI())));
Assert.assertTrue(inf.contains(ind_x, mostSpecificType, ResourceFactory.createResource(classB.getURI())));
Assert.assertTrue(inf.contains(ind_x, mostSpecificType, ResourceFactory.createResource(classC.getURI())));
simpleReasonerTBoxListener.setStopRequested();
}
@Test
public void mstTest3Test()throws InterruptedException{
mstTest3(true);
}
@Test
public void mstTest3NoSameAs()throws InterruptedException{
mstTest3(false);
}
/*
* Test computation of mostSpecificType annotations in response
* to an added/removed TBox assertions.
*/
public void mstTest3(boolean enableSameAs) throws InterruptedException {
// Set up the Tbox with classes A, B, C, D, E, F and G
OntModel tBox = createTBoxModel();
OntClass classA = createClass(tBox, "http://test.vivo/A", "class A");
OntClass classB = createClass(tBox, "http://test.vivo/B", "class B");
OntClass classC = createClass(tBox, "http://test.vivo/C", "class C");
OntClass classD = createClass(tBox, "http://test.vivo/D", "class D");
OntClass classE = createClass(tBox, "http://test.vivo/E", "class E");
OntClass classF = createClass(tBox, "http://test.vivo/F", "class F");
OntClass classG = createClass(tBox, "http://test.vivo/G", "class G");
// Create ABox and Inference models and register
// the ABox reasoner listeners with the ABox and TBox
OntModel aBox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
Model inf = ModelFactory.createDefaultModel();
SimpleReasoner sr = new SimpleReasoner(tBox, aBox, inf);
sr.setSameAsEnabled( enableSameAs );
SimpleReasoner simpleReasoner = sr ;
aBox.register(simpleReasoner);
SimpleReasonerTBoxListener simpleReasonerTBoxListener = getTBoxListener(simpleReasoner);
tBox.register(simpleReasonerTBoxListener);
OntClass OWL_THING = tBox.createClass(OWL.Thing.getURI());
AnnotationProperty mostSpecificType = tBox.createAnnotationProperty(mostSpecificTypePropertyURI);
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
// add individuals x, y and z to the aBox
Resource ind_x = aBox.createResource("http://test.vivo/x");
Resource ind_y = aBox.createResource("http://test.vivo/y");
aBox.add(ind_x, RDF.type, OWL_THING);
aBox.add(ind_y, RDF.type, classD);
Assert.assertTrue(inf.contains(ind_x, mostSpecificType, ResourceFactory.createResource(OWL.Thing.getURI())));
Assert.assertTrue(inf.contains(ind_y, mostSpecificType, ResourceFactory.createResource(classD.getURI())));
aBox.add(ind_x, RDF.type, classC);
aBox.add(ind_y, RDF.type, classF);
Assert.assertFalse(inf.contains(ind_x, mostSpecificType, ResourceFactory.createResource(OWL.Thing.getURI())));
Assert.assertTrue(inf.contains(ind_x, mostSpecificType, ResourceFactory.createResource(classC.getURI())));
Assert.assertTrue(inf.contains(ind_y, mostSpecificType, ResourceFactory.createResource(classD.getURI())));
Assert.assertTrue(inf.contains(ind_y, mostSpecificType, ResourceFactory.createResource(classF.getURI())));
// Set up a class hierarchy.
addSubclass(classA, classB);
addSubclass(classA, classC);
addSubclass(classA, classD);
addSubclass(classC, classE);
addSubclass(classD, classF);
addSubclass(classD, classG);
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
Assert.assertFalse(inf.contains(ind_y, mostSpecificType, ResourceFactory.createResource(classD.getURI())));
Assert.assertTrue(inf.contains(ind_y, mostSpecificType, ResourceFactory.createResource(classF.getURI())));
// If F is removed as a subclass of D, then D should once again be a most specific type
// for y.
removeSubclass(classD, classF);
while (!VitroBackgroundThread.getLivingThreads().isEmpty()) {
Thread.sleep(delay);
}
Assert.assertTrue(inf.contains(ind_y, mostSpecificType, ResourceFactory.createResource(classD.getURI())));
simpleReasonerTBoxListener.setStopRequested();
}
SimpleReasonerTBoxListener getTBoxListener(SimpleReasoner simpleReasoner) {
return new SimpleReasonerTBoxListener(simpleReasoner, new Exception().getStackTrace()[1].getMethodName());
}
// To help in debugging the unit test
void printModel(Model model, String modelName) {
System.out.println("\nThe " + modelName + " model has " + model.size() + " statements:");
System.out.println("---------------------------------------------------------------------");
model.write(System.out);
}
// To help in debugging the unit test
void printModel(OntModel ontModel, String modelName) {
System.out.println("\nThe " + modelName + " model has " + ontModel.size() + " statements:");
System.out.println("---------------------------------------------------------------------");
ontModel.writeAll(System.out,"N3",null);
}
}

View file

@ -0,0 +1,18 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.reasoner.plugin;
import edu.cornell.mannlib.vitro.webapp.reasoner.ReasonerPlugin;
public class SamplePlugin extends SimpleBridgingRule implements ReasonerPlugin {
private final static String DCTERMS = "http://purl.org/dc/terms/";
private final static String VIVOCORE = "http://vivoweb.org/ontology/core#";
public SamplePlugin() {
super(VIVOCORE + "informationResourceInAuthorship",
VIVOCORE + "linkedAuthor",
DCTERMS + "creator");
}
}

View file

@ -0,0 +1,68 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
/**
*
*/
package edu.cornell.mannlib.vitro.webapp.search.controller;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import stubs.edu.cornell.mannlib.vitro.webapp.i18n.I18nStub;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder.ParamMap;
import edu.cornell.mannlib.vitro.webapp.search.controller.PagedSearchController.PagingLink;
public class PagedSearchControllerTest {
@Before
public void useI18nStubBundles() {
I18nStub.setup();
}
@Test
public void testGetPagingLinks() {
ParamMap pm = new ParamMap();
int hitsPerPage = 25;
int totalHits = 500;
int currentStartIndex = 0;
List<PagingLink> pageLinks = PagedSearchController.getPagingLinks(currentStartIndex, hitsPerPage, totalHits, "baseURL", pm, null);
Assert.assertNotNull(pageLinks);
Assert.assertEquals(500 / 25, pageLinks.size());
//test for no page links on a very short result
hitsPerPage = 25;
totalHits = 10;
currentStartIndex = 0;
pageLinks = PagedSearchController.getPagingLinks(currentStartIndex, hitsPerPage, totalHits, "baseURL", pm, null);
Assert.assertNotNull(pageLinks);
Assert.assertEquals(0, pageLinks.size());
}
@Test
public void testGetPagingLinksForLargeResults() {
ParamMap pm = new ParamMap();
int hitsPerPage = 25;
int totalHits = 349909;
int currentStartIndex = 0;
List<PagingLink> pageLinks = PagedSearchController.getPagingLinks(currentStartIndex, hitsPerPage, totalHits, "baseURL", pm, null);
Assert.assertNotNull(pageLinks);
Assert.assertEquals( PagedSearchController.DEFAULT_MAX_HIT_COUNT / hitsPerPage, pageLinks.size());
//test for large sets of results with high start index
hitsPerPage = 25;
totalHits = PagedSearchController.DEFAULT_MAX_HIT_COUNT + 20329;
currentStartIndex = PagedSearchController.DEFAULT_MAX_HIT_COUNT + 5432;
pageLinks = PagedSearchController.getPagingLinks(currentStartIndex, hitsPerPage, totalHits, "baseURL", pm, null);
Assert.assertNotNull(pageLinks);
Assert.assertEquals(
(currentStartIndex / hitsPerPage) + //all the pages that are before the current page
(PagedSearchController.DEFAULT_MAX_HIT_COUNT / hitsPerPage) + //some pages after the current apge
1, //for the more... page
pageLinks.size());
}
}

View file

@ -0,0 +1,89 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.search.controller;
import java.io.Reader;
import java.io.StringReader;
import java.util.Iterator;
import org.junit.Assert;
import org.junit.Test;
/**
* Accepts requests to update a set of URIs in the search index.
*/
public class UpdateUrisInIndexTest {
@Test(expected = NullPointerException.class)
public void nullString() {
scan(null, 0);
}
@Test
public void emptyString() {
scan("", 0);
}
@Test
public void nothingButDelimiters() {
scan(" , ", 0);
scan("\n", 0);
scan("\n\n\n", 0);
scan("\n, \t\r ,\n\n", 0);
}
@Test
public void oneTokenNoDelimiters() {
scan("http://bogus.com/n234", 1);
}
@Test
public void oneTokenAssortedDelimiters() {
scan("http://bogus.com/n234\n", 1);
scan("\nhttp://bogus.com/n234", 1);
scan("\nhttp://bogus.com/n234\n", 1);
}
@Test
public void twoTokensAssortedDelimiters() {
scan("http://bogus.com/n234\nhttp://bogus.com/n442", 2);
scan("http://bogus.com/n234, http://bogus.com/n442", 2);
scan("http://bogus.com/n234,\nhttp://bogus.com/n442\n", 2);
}
@Test
public void nonBreakingSpace() {
scan("non\u00A0breaking\u00A0space", 1);
}
@Test
public void omnibus() {
scan(" a , b,c d\t,\re", 5);
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
public void scan(String input, int expectedUris) {
Reader reader = (input == null) ? null : new StringReader(input);
Iterator<String> it = new UpdateUrisInIndex().createScanner(reader);
int count = 0;
while (it.hasNext()) {
String uri = it.next();
if (uri == null) {
Assert.fail("Scanner should not return null strings \n "
+ "Null string for uri #" + count + " for input '"
+ input + "'");
} else if (uri.isEmpty()) {
Assert.fail("Scanner should not return empty strings \n "
+ "Empty string for uri #" + count + " for input '"
+ input + "'");
}
count++;
}
Assert.assertEquals("Incorrect number of URIs from input '" + input
+ "'", expectedUris, count);
}
}

View file

@ -0,0 +1,56 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.searchengine.base;
import static org.junit.Assert.*;
import java.util.Collection;
import java.util.Map;
import org.junit.Test;
import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchInputField;
/**
* TODO
*/
public class BaseSearchInputDocumentTest {
/**
* The copy constructor should make a deep copy, down to (but not including)
* the field values. The component parts should be equal, but not the same.
*/
@Test
public void copyConstructor() {
BaseSearchInputDocument doc = new BaseSearchInputDocument();
doc.setDocumentBoost(42.6F);
SearchInputField field1 = new BaseSearchInputField("testField");
field1.addValues("value1", "value2");
field1.setBoost(1.1F);
doc.addField(field1);
SearchInputField field2 = new BaseSearchInputField("anotherField");
field2.setBoost(-16F);
doc.addField(field2);
BaseSearchInputDocument other = new BaseSearchInputDocument(doc);
assertEquals(doc, other);
assertEquals(doc.getDocumentBoost(), other.getDocumentBoost(), 0.01F);
Map<String, SearchInputField> docMap = doc.getFieldMap();
Map<String, SearchInputField> otherMap = other.getFieldMap();
assertEquals(docMap, otherMap);
assertNotSame(docMap, otherMap);
for (String fieldName : docMap.keySet()) {
SearchInputField docField = doc.getField(fieldName);
SearchInputField otherField = other.getField(fieldName);
assertEquals(docField, otherField);
assertNotSame(docField, otherField);
Collection<Object> docFieldValues = docField.getValues();
Collection<Object> otherFieldValues = otherField.getValues();
assertEquals(docFieldValues, otherFieldValues);
}
}
}

View file

@ -0,0 +1,77 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.searchindex.documentBuilding;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess.WhichService.CONTENT;
import java.io.InputStream;
import org.apache.log4j.Level;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import stubs.edu.cornell.mannlib.vitro.webapp.modelaccess.ContextModelAccessStub;
import stubs.edu.cornell.mannlib.vitro.webapp.modules.ApplicationStub;
import stubs.edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchEngineStub;
import stubs.javax.servlet.ServletContextStub;
import com.hp.hpl.jena.rdf.model.Model;
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.application.ApplicationUtils;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.IndividualImpl;
import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchInputDocument;
import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchInputField;
import edu.cornell.mannlib.vitro.webapp.rdfservice.impl.jena.model.RDFServiceModel;
import edu.cornell.mannlib.vitro.webapp.search.VitroSearchTermNames;
public class ThumbnailImageURLTest extends AbstractTestClass{
ContextModelAccessStub contextModels;
String personsURI = "http://vivo.cornell.edu/individual/individual8803";
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
setLoggerLevel(RDFDefaultErrorHandler.class, Level.OFF);
ApplicationStub.setup(new ServletContextStub(), new SearchEngineStub());
Model model = ModelFactory.createDefaultModel();
InputStream in = ThumbnailImageURLTest.class.getResourceAsStream("testPerson.n3");
model.read(in,"","N3");
contextModels = new ContextModelAccessStub();
contextModels.setRDFService(CONTENT, new RDFServiceModel( model ));
}
/**
* Test to see if ThumbnailImageURL gets the date it is suppose to gete
* from a set of RDF.
*/
@Test
public void testThumbnailFieldCreatedInSearchDoc() {
SearchInputDocument doc = ApplicationUtils.instance().getSearchEngine().createInputDocument();
ThumbnailImageURL testMe = new ThumbnailImageURL();
testMe.setContextModels(contextModels);
Individual ind = new IndividualImpl();
ind.setURI(personsURI);
//make sure that the person is in the RDF
testMe.modifyDocument(ind, doc);
//make sure that a search document field got created for the thumbnail image
SearchInputField thumbnailField = doc.getField( VitroSearchTermNames.THUMBNAIL_URL );
Assert.assertNotNull(thumbnailField);
Assert.assertNotNull( thumbnailField.getValues() );
Assert.assertEquals(1, thumbnailField.getValues().size());
Assert.assertEquals("http://vivo.cornell.edu/individual/n54945", thumbnailField.getFirstValue());
}
}

View file

@ -0,0 +1,86 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.searchindex.exclusions;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import edu.cornell.mannlib.vitro.webapp.beans.IndividualImpl;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
public class ExcludeBasedOnTypeTest {
@Test
public void testCheckForExclusion() {
ExcludeBasedOnType ebot = new ExcludeBasedOnType();
ebot.addTypeToExclude("http://xmlns.com/foaf/0.1/Person");
IndividualImpl ind = new IndividualImpl();
ind.setURI("http://example.com/n2343");
VClass personClass = new VClass("http://xmlns.com/foaf/0.1/Person");
ind.setVClasses(Collections.singletonList(personClass), false);
String excludeResult = ebot.checkForExclusion(ind);
assertNotNull( excludeResult );
}
@Test
public void testCheckForExclusion2() {
ExcludeBasedOnType ebot = new ExcludeBasedOnType();
ebot.addTypeToExclude("http://example.com/KillerRobot");
IndividualImpl ind = new IndividualImpl();
ind.setURI("http://example.com/n2343");
List<VClass> vClassList = new ArrayList<VClass>();
vClassList.add( new VClass("http://xmlns.com/foaf/0.1/Agent"));
vClassList.add( new VClass("http://example.com/Robot"));
vClassList.add( new VClass("http://example.com/KillerRobot"));
vClassList.add( new VClass("http://example.com/Droid"));
ind.setVClasses(vClassList, false);
String excludeResult = ebot.checkForExclusion(ind);
assertNotNull( excludeResult );
}
@Test
public void testCheckForNonExclusion() {
ExcludeBasedOnType ebot = new ExcludeBasedOnType();
ebot.addTypeToExclude("http://xmlns.com/foaf/0.1/Person");
IndividualImpl ind = new IndividualImpl();
ind.setURI("http://example.com/n2343");
VClass personClass = new VClass("http://xmlns.com/foaf/0.1/Robot");
ind.setVClasses(Collections.singletonList(personClass), false);
String excludeResult = ebot.checkForExclusion(ind);
assertNull( excludeResult );
}
@Test
public void testCheckForNonExclusion2() {
ExcludeBasedOnType ebot = new ExcludeBasedOnType();
ebot.addTypeToExclude("http://xmlns.com/foaf/0.1/Person");
IndividualImpl ind = new IndividualImpl();
ind.setURI("http://example.com/n2343");
List<VClass> vClassList = new ArrayList<VClass>();
vClassList.add( new VClass("http://xmlns.com/foaf/0.1/Agent"));
vClassList.add( new VClass("http://example.com/Robot"));
vClassList.add( new VClass("http://example.com/KillerRobot"));
vClassList.add( new VClass("http://example.com/Droid"));
ind.setVClasses(vClassList, false);
String excludeResult = ebot.checkForExclusion(ind);
assertNull( excludeResult );
}
}

View file

@ -0,0 +1,152 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.searchindex.indexing;
import java.io.StringReader;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import stubs.edu.cornell.mannlib.vitro.webapp.modelaccess.ContextModelAccessStub;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames;
/**
* @author bdc34
*
*/
public class AdditionalURIsForClassGroupChangesTest {
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
}
/**
* Test method for {@link edu.cornell.mannlib.vitro.webapp.search.indexing.AdditionalURIsForClassGroupChanges#findAdditionalURIsToIndex(com.hp.hpl.jena.rdf.model.Statement)}.
*/
@Test
public void testFindAdditionalURIsToIndex() {
OntModel model = ModelFactory.createOntologyModel();
model.read( new StringReader(n3ForPresentationClass), null, "N3");
ContextModelAccessStub models = new ContextModelAccessStub();
models.setOntModel(ModelNames.TBOX_ASSERTIONS, model);
AdditionalURIsForClassGroupChanges uriFinder = new AdditionalURIsForClassGroupChanges( );
uriFinder.setContextModels(models);
List<String> uris = uriFinder.findAdditionalURIsToIndex(
ResourceFactory.createStatement(
ResourceFactory.createResource("http://vivoweb.org/ontology/core#Presentation"),
ResourceFactory.createProperty(VitroVocabulary.IN_CLASSGROUP),
ResourceFactory.createResource("http://example.com/someClassGroup")));
Assert.assertNotNull(uris);
Assert.assertTrue("uris list is empty", uris.size() > 0 );
Assert.assertTrue(uris.contains("http://vivo.scripps.edu/individual/n400"));
Assert.assertTrue(uris.contains("http://vivo.scripps.edu/individual/n12400"));
Assert.assertTrue(uris.contains("http://vivo.scripps.edu/individual/n210"));
Assert.assertTrue(uris.contains("http://vivo.scripps.edu/individual/n264"));
Assert.assertTrue(uris.contains("http://vivo.scripps.edu/individual/n25031"));
Assert.assertTrue(uris.contains("http://vivo.scripps.edu/individual/n2486"));
Assert.assertTrue("uris list should not contain n9999",!uris.contains("http://vivo.scripps.edu/individual/n9999"));
Assert.assertTrue("uris list should not contain n9998",!uris.contains("http://vivo.scripps.edu/individual/n9998"));
// Assert.assertTrue("uris didn't not contain test:onions", uris.contains(testNS+"onions"));
// Assert.assertTrue("uris didn't not contain test:cheese", uris.contains(testNS+"cheese"));
// Assert.assertTrue("uris didn't not contain test:icecream", uris.contains(testNS+"icecream"));
//
// Assert.assertTrue("uris contained test:Person", !uris.contains(testNS+"Person"));
// Assert.assertTrue("uris contained owl:Thing", !uris.contains( OWL.Thing.getURI() ));
}
String n3ForPresentationClass =
"@prefix dc: <http://purl.org/dc/elements/1.1/> . \n" +
"@prefix pvs: <http://vivoweb.org/ontology/provenance-support#> . \n" +
"@prefix geo: <http://aims.fao.org/aos/geopolitical.owl#> . \n" +
"@prefix foaf: <http://xmlns.com/foaf/0.1/> . \n" +
"@prefix scires: <http://vivoweb.org/ontology/scientific-research#> . \n" +
"@prefix scripps: <http://vivo.scripps.edu/> . \n" +
"@prefix dcterms: <http://purl.org/dc/terms/> . \n" +
"@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . \n" +
"@prefix swrl: <http://www.w3.org/2003/11/swrl#> . \n" +
"@prefix vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> . \n" +
"@prefix event: <http://purl.org/NET/c4dm/event.owl#> . \n" +
"@prefix bibo: <http://purl.org/ontology/bibo/> . \n" +
"@prefix xsd: <http://www.w3.org/2001/XMLSchema#> . \n" +
"@prefix owl: <http://www.w3.org/2002/07/owl#> . \n" +
"@prefix swrlb: <http://www.w3.org/2003/11/swrlb#> . \n" +
"@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . \n" +
"@prefix core: <http://vivoweb.org/ontology/core#> . \n" +
"@prefix skos: <http://www.w3.org/2004/02/skos/core#> . \n" +
"@prefix vivo: <http://vivo.library.cornell.edu/ns/0.1#> . \n" +
"@prefix dcelem: <http://purl.org/dc/elements/1.1/> . \n" +
"@prefix ero: <http://purl.obolibrary.org/obo/> . \n" +
" \n" +
"core:Presentation \n" +
" a owl:Class ; \n" +
" rdfs:label \"Presentation\"@en-US ; \n" +
" rdfs:subClassOf event:Event , owl:Thing ; \n" +
" vitro:displayLimitAnnot \n" +
" \"-1\"^^xsd:int ; \n" +
" vitro:displayRankAnnot \n" +
" \"-1\"^^xsd:int ; \n" +
" vitro:hiddenFromDisplayBelowRoleLevelAnnot \n" +
" <http://vitro.mannlib.cornell.edu/ns/vitro/role#public> ; \n" +
" vitro:inClassGroup <http://vivoweb.org/ontology#vitroClassGroupevents> ; \n" +
" vitro:prohibitedFromUpdateBelowRoleLevelAnnot \n" +
" <http://vitro.mannlib.cornell.edu/ns/vitro/role#public> ; \n" +
" vitro:shortDef \"Encompasses talk, speech, lecture, slide lecture, conference presentation\"^^xsd:string ; \n" +
" owl:equivalentClass core:Presentation . \n" +
" \n" +
" \n" +
"core:Presentation \n" +
" owl:equivalentClass core:Presentation . \n" +
" \n" +
"<http://vivo.scripps.edu/individual/n400> \n" +
" a core:Presentation . \n" +
" \n" +
"<http://vivo.scripps.edu/individual/n12400> \n" +
" a core:Presentation . \n" +
" \n" +
"<http://vivo.scripps.edu/individual/n210> \n" +
" a core:Presentation . \n" +
" \n" +
"<http://vivo.scripps.edu/individual/n264> \n" +
" a core:Presentation ; \n" +
" vitro:mostSpecificType \n" +
" core:Presentation . \n" +
" \n" +
"<http://vivo.scripps.edu/individual/n25031> \n" +
" a core:Presentation ; \n" +
" vitro:mostSpecificType \n" +
" core:Presentation . \n" +
" \n" +
"<http://vivo.scripps.edu/individual/n2486> \n" +
" a core:Presentation ; \n" +
" vitro:mostSpecificType \n" +
" core:Presentation . \n" +
" \n " +
"<http://vivo.scripps.edu/individual/n9998> \n" +
" a core:BogusClass . \n" +
"<http://vivo.scripps.edu/individual/n9999> \n" +
" a core:BogusClass . \n" +
" \n" +
"core:InvitedTalk \n" +
" rdfs:subClassOf core:Presentation . \n" +
" \n" ;
}

View file

@ -0,0 +1,175 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.searchindex.indexing;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess.WhichService.CONTENT;
import java.io.StringReader;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import stubs.edu.cornell.mannlib.vitro.webapp.modelaccess.ContextModelAccessStub;
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 com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDFS;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
import edu.cornell.mannlib.vitro.webapp.rdfservice.impl.jena.model.RDFServiceModel;
public class AdditionalURIsForObjectPropertiesTest {
Model model;
RDFService rdfService;
AdditionalURIsForObjectProperties aufop;
String testNS = "http://example.com/test#";
String n3 = "" +
"@prefix owl: <http://www.w3.org/2002/07/owl#> .\n" +
"@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . \n" +
"@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . \n" +
"@prefix test: <"+ testNS + "> . \n" +
"\n" +
"test:bob rdfs:label \"Mr Bob\" . \n" +
"test:bob test:hatsize \"8 1/2 inches\" . \n" +
"test:bob test:likes test:icecream . \n" +
"test:bob test:likes test:onions . \n" +
"test:bob test:likes test:cheese . \n" +
"test:bob a test:Person . \n" +
"test:bob a owl:Thing . \n" +
"test:bob test:likes [ rdfs:label \"this is a blank node\" ] . ";
@Before
public void setUp() throws Exception {
model = ModelFactory.createDefaultModel();
model.read(new StringReader(n3 ), null , "N3");
rdfService = new RDFServiceModel(model);
ContextModelAccessStub models = new ContextModelAccessStub();
models.setRDFService(CONTENT, rdfService);
aufop = new AdditionalURIsForObjectProperties();
aufop.setContextModels(models);
}
@Test
public void testChangeOfRdfsLabel() {
List<String> uris = aufop.findAdditionalURIsToIndex(
ResourceFactory.createStatement(
ResourceFactory.createResource(testNS + "bob"),
RDFS.label,
ResourceFactory.createPlainLiteral("Some new label for bob")));
Assert.assertNotNull(uris);
Assert.assertTrue("uris was empty", uris.size() > 0 );
Assert.assertTrue("uris didn't not contain test:onions", uris.contains(testNS+"onions"));
Assert.assertTrue("uris didn't not contain test:cheese", uris.contains(testNS+"cheese"));
Assert.assertTrue("uris didn't not contain test:icecream", uris.contains(testNS+"icecream"));
Assert.assertTrue("uris contained test:Person", !uris.contains(testNS+"Person"));
Assert.assertTrue("uris contained owl:Thing", !uris.contains( OWL.Thing.getURI() ));
Assert.assertEquals(3, uris.size());
}
@Test
public void testChangeOfObjPropStmt() {
List<String> uris = aufop.findAdditionalURIsToIndex(
ResourceFactory.createStatement(
ResourceFactory.createResource(testNS + "bob"),
ResourceFactory.createProperty(testNS+"likes"),
ResourceFactory.createResource(testNS+"cheese")));
Assert.assertNotNull(uris);
Assert.assertTrue("uris was empty", uris.size() > 0 );
Assert.assertTrue("uris didn't not contain test:cheese", uris.contains(testNS+"cheese"));
Assert.assertTrue("uris contained test:Person", !uris.contains(testNS+"Person"));
Assert.assertTrue("uris contained owl:Thing", !uris.contains( OWL.Thing.getURI() ));
Assert.assertTrue("uris contained test:onions", !uris.contains(testNS+"onions"));
Assert.assertTrue("uris contained test:icecream", !uris.contains(testNS+"icecream"));
Assert.assertEquals(1, uris.size());
}
@Test
public void testOfDataPropChange() {
List<String> uris = aufop.findAdditionalURIsToIndex(
ResourceFactory.createStatement(
ResourceFactory.createResource(testNS + "bob"),
ResourceFactory.createProperty(testNS+"hatsize"),
ResourceFactory.createPlainLiteral("Some new hat size for bob")));
Assert.assertNotNull(uris);
Assert.assertTrue("uris was not empty", uris.size() == 0 );
}
// For NIHVIVO-2902
@Test
public void testNIHVIVO_2902 (){
//Update search index for research area when a statement is
//removed between a person and the research area.
Model model = ModelFactory.createDefaultModel();
model.read(new StringReader( n3ForNIHVIVO_2902 ), null , "N3");
ContextModelAccessStub models = new ContextModelAccessStub();
models.setRDFService(CONTENT, new RDFServiceModel(model));
aufop.setContextModels(models);
List<String> uris = aufop.findAdditionalURIsToIndex(
ResourceFactory.createStatement(
ResourceFactory.createResource("http://caruso-laptop.mannlib.cornell.edu:8090/vivo/individual/n2241"),
ResourceFactory.createProperty("http://vivoweb.org/ontology/core#hasResearchArea"),
ResourceFactory.createResource("http://caruso-laptop.mannlib.cornell.edu:8090/vivo/individual/n7416")));
Assert.assertNotNull(uris);
Assert.assertTrue("uris was empty", uris.size() > 0 );
Assert.assertTrue("NIHVIVO-2902 regression, research area is not getting reindexed", uris.contains("http://caruso-laptop.mannlib.cornell.edu:8090/vivo/individual/n7416"));
}
// For NIHVIVO-2902
String n3ForNIHVIVO_2902 =
"@prefix dc: <http://purl.org/dc/elements/1.1/> . \n" +
"@prefix pvs: <http://vivoweb.org/ontology/provenance-support#> . \n" +
"@prefix geo: <http://aims.fao.org/aos/geopolitical.owl#> . \n" +
"@prefix foaf: <http://xmlns.com/foaf/0.1/> . \n" +
"@prefix scires: <http://vivoweb.org/ontology/scientific-research#> . \n" +
"@prefix scripps: <http://vivo.scripps.edu/> . \n" +
"@prefix dcterms: <http://purl.org/dc/terms/> . \n" +
"@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . \n" +
"@prefix swrl: <http://www.w3.org/2003/11/swrl#> . \n" +
"@prefix vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#>. \n" +
"@prefix event: <http://purl.org/NET/c4dm/event.owl#> . \n" +
"@prefix bibo: <http://purl.org/ontology/bibo/> . \n" +
"@prefix xsd: <http://www.w3.org/2001/XMLSchema#> . \n" +
"@prefix owl: <http://www.w3.org/2002/07/owl#> . \n" +
"@prefix swrlb: <http://www.w3.org/2003/11/swrlb#> . \n" +
"@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . \n" +
"@prefix core: <http://vivoweb.org/ontology/core#> . \n" +
"@prefix skos: <http://www.w3.org/2004/02/skos/core#> . \n" +
"@prefix vivo: <http://vivo.library.cornell.edu/ns/0.1#> . \n" +
"@prefix dcelem: <http://purl.org/dc/elements/1.1/> . \n" +
"@prefix ero: <http://purl.obolibrary.org/obo/> . \n" +
" \n" +
"<http://caruso-laptop.mannlib.cornell.edu:8090/vivo/individual/n2241> \n" +
" a core:FacultyMember , foaf:Person , owl:Thing , foaf:Agent ; \n" +
" rdfs:label \"Faculty, Jane\" ; \n" +
" vitro:modTime \"2011-07-15T15:08:35\"^^xsd:dateTime ; \n" +
" vitro:mostSpecificType \n" +
" core:FacultyMember ; \n" +
" core:hasResearchArea \n" +
" <http://caruso-laptop.mannlib.cornell.edu:8090/vivo/individual/n7416> ; \n" +
" core:mailingAddress <http://caruso-laptop.mannlib.cornell.edu:8090/vivo/individual/n5993> ; \n" +
" foaf:firstName \"Jane\"^^xsd:string ; \n" +
" foaf:lastName \"Faculty\"^^xsd:string . ";
}

View file

@ -0,0 +1,47 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.searchindex.indexing;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.rdf.model.Statement;
/**
* @author bdc34
*
*/
public class AdditionalURIsForTypeStatementsTest {
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
}
/**
* Test method for {@link edu.cornell.mannlib.vitro.webapp.search.indexing.AdditionalURIsForTypeStatements#findAdditionalURIsToIndex(com.hp.hpl.jena.rdf.model.Statement)}.
*/
@Test
public void testFindAdditionalURIsToIndex() {
AdditionalURIsForTypeStatements aufts = new AdditionalURIsForTypeStatements();
String subject = "http://caruso-laptop.mannlib.cornell.edu:8090/vivo/individual/n3270";
Statement typeChangeStatement = ResourceFactory.createStatement(
ResourceFactory.createResource(subject),
ResourceFactory.createProperty("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
ResourceFactory.createResource( "http://caruso-laptop.mannlib.cornell.edu:8090/vivo/ontology/localOnt#LocalInternalClass"));
List<String> uris = aufts.findAdditionalURIsToIndex( typeChangeStatement );
Assert.assertNotNull(uris);
Assert.assertTrue("Did not contain subject of type change statement", uris.contains(subject));
}
}

View file

@ -0,0 +1,156 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.searchindex.indexing;
import static com.hp.hpl.jena.rdf.model.ResourceFactory.createPlainLiteral;
import static com.hp.hpl.jena.rdf.model.ResourceFactory.createProperty;
import static com.hp.hpl.jena.rdf.model.ResourceFactory.createResource;
import static com.hp.hpl.jena.rdf.model.ResourceFactory.createStatement;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess.WhichService.CONTENT;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Before;
import org.junit.Test;
import stubs.edu.cornell.mannlib.vitro.webapp.modelaccess.ContextModelAccessStub;
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.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
import edu.cornell.mannlib.vitro.webapp.rdfservice.impl.jena.model.RDFServiceModel;
/**
* TODO
*
* If the statement qualifies, execute the queries and return the accumulated
* results.
*
* A statement qualifies if the predicate matches any of the restrictions, or if
* there are no restrictions.
*
* If a query contains a ?subject or ?object variable, it will be bound to the
* URI of the subject or object of the statement, respectively. If the subject
* or object has no URI for the query, then the query will be ignored.
*
* All of the result fields of all result rows of all of the queries will be
* returned.
*
* A label may be supplied to the instance, for use in logging. If no label is
* supplied, one will be generated.
*/
public class SelectQueryUriFinderTest extends AbstractTestClass {
private static final Log log = LogFactory
.getLog(SelectQueryUriFinderTest.class);
private static final String BOB_URI = "http://ns#Bob";
private static final String BETTY_URI = "http://ns#Betty";
private static final String DICK_URI = "http://ns#Dick";
private static final String JANE_URI = "http://ns#Jane";
private static final String FRIEND_URI = "http://ns#Friend";
private static final String SEES_URI = "http://ns#Sees";
private static final String OTHER_URI = "http://ns#Other";
private static final Resource BOB = createResource(BOB_URI);
private static final Resource BETTY = createResource(BETTY_URI);
private static final Resource DICK = createResource(DICK_URI);
private static final Resource JANE = createResource(JANE_URI);
private static final Property FRIEND = createProperty(FRIEND_URI);
private static final Property SEES = createProperty(SEES_URI);
private static final String QUERY1 = "SELECT ?friend WHERE {?subject <"
+ FRIEND_URI + "> ?friend}";
private static final String QUERY2 = "SELECT ?partner WHERE {?object <"
+ FRIEND_URI + "> ?partner}";
private Model m;
private RDFService rdfService;
private SelectQueryUriFinder finder;
private List<String> foundUris;
@Before
public void populateModel() {
m = ModelFactory.createDefaultModel();
m.add(createStatement(BOB, FRIEND, BETTY));
m.add(createStatement(DICK, FRIEND, JANE));
rdfService = new RDFServiceModel(m);
ContextModelAccessStub models = new ContextModelAccessStub();
models.setRDFService(CONTENT, rdfService);
finder = new SelectQueryUriFinder();
finder.setContextModels(models);
finder.addQuery(QUERY1);
finder.addQuery(QUERY2);
}
@Test
public void fullSuccess_bothResults() {
setPredicateRestrictions();
exerciseUriFinder(BOB, SEES, DICK);
assertExpectedUris(BETTY_URI, JANE_URI);
}
@Test
public void acceptableRestriction_bothResults() {
setPredicateRestrictions(SEES_URI);
exerciseUriFinder(BOB, SEES, DICK);
assertExpectedUris(BETTY_URI, JANE_URI);
}
@Test
public void excludingRestriction_noResults() {
setPredicateRestrictions(OTHER_URI);
exerciseUriFinder(BOB, SEES, DICK);
assertExpectedUris();
}
@Test
public void blankSubject_justObjectResult() {
setPredicateRestrictions();
exerciseUriFinder(createResource(), SEES, DICK);
assertExpectedUris(JANE_URI);
}
@Test
public void literalObject_justSubjectResult() {
setPredicateRestrictions();
exerciseUriFinder(BOB, SEES, createPlainLiteral("Bogus"));
assertExpectedUris(BETTY_URI);
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
private void setPredicateRestrictions(String... uris) {
for (String uri : uris) {
finder.addPredicateRestriction(uri);
}
}
private void exerciseUriFinder(Resource subject, Property predicate,
RDFNode object) {
foundUris = finder.findAdditionalURIsToIndex(createStatement(subject,
predicate, object));
}
private void assertExpectedUris(String... expectedArray) {
Set<String> expected = new HashSet<>(Arrays.asList(expectedArray));
Set<String> actual = new HashSet<>(foundUris);
assertEquals("found URIs", expected, actual);
}
}

View file

@ -0,0 +1,22 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.servlet.setup;
import java.io.StringReader;
import org.junit.Assert;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
public class UpdateKnowledgeBaseTest extends AbstractTestClass {
@org.junit.Test
public void testMigrateDisplayModel14() {
return;
}
}

View file

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

View file

@ -0,0 +1,69 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.test;
import java.io.IOException;
import java.io.InputStream;
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;
/**
* this is a class to load owl files for testing.
* @author bdc34
*
*/
public class JenaOntologyLoader {
public OntModel ontModel = null;
/**
* This should load the system with classes, data properties and
* object properties that the vitro systems needs.
*
* @return
* @throws Exception
*/
OntModel loadSystemAndUsers() throws Exception{
Model model = ModelFactory.createDefaultModel();
for( String ont : systemOnts){
InputStream in = this.getClass().getResourceAsStream(ont);
model.read(in,null);
in.close();
}
ontModel = ModelFactory.createOntologyModel(ONT_MODEL_SPEC,model);
ontModel.prepare();
return ontModel;
}
/**
* Loads a owl file into the ontModel. Looks for files on classpath.
* example: loadSpecialVivoModel("/testontologies/smallVivo-20070809.owl")
*
* @param junk
* @return
* @throws IOException
*/
OntModel loadSpecialVivoModel(String junk) throws IOException{
InputStream in = this.getClass().getResourceAsStream(junk);
Model model = ModelFactory.createDefaultModel();
model.read(in,null);
in.close();
ontModel.add(model);
ontModel.prepare();
return ontModel;
}
static String systemOnts[] ={
"/testontologies/vitro1.owl",
"/testontologies/vivo-users.owl" };
static String testOnt[] ={
"/testontologies/smallVivo-20070809.owl" };
static OntModelSpec ONT_MODEL_SPEC = OntModelSpec.OWL_DL_MEM; // no additional entailment reasoning
}

View file

@ -0,0 +1,30 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.utils;
import org.apache.log4j.Level;
import org.junit.Before;
import org.junit.Test;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
/**
* User: jc55
* Date: August 22, 2008
* Time: 4:37 PM
*/
public class MakeTidyTest extends AbstractTestClass {
@Before
public void suppressLogging() {
setLoggerLevel(MakeTidy.class, Level.WARN);
}
@Test
public void testTidy(){
String inputStr = "<p garbage here/><ul><li>list element one</li><li>list element two</li></ul></p";
String expected = "<ul><li>list element one</li><li>list element two</li></ul>";
MakeTidy tidy = new MakeTidy();
assertEquivalentXmlDocs(expected, tidy.process(inputStr));
}
}

View file

@ -0,0 +1,92 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.utils;
import static org.junit.Assert.*;
import static edu.cornell.mannlib.vitro.webapp.utils.SparqlQueryRunner.*;
import org.junit.Test;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
/**
* For now, just test the methods that manipulate the query string.
*/
public class SparqlQueryRunnerTest extends AbstractTestClass {
@Test
public void bindValuesNameNotFound() {
String raw = "No such name here";
String expected = raw;
assertEquals(expected, bindValues(raw, uriValue("bogus", "BOGUS")));
}
@Test
public void bindOneUri() {
String raw = "Replace both ?this and ?this also.";
String expected = "Replace both <URI> and <URI> also.";
assertEquals(expected, bindValues(raw, uriValue("this", "URI")));
}
@Test
public void bindTwoUris() {
String raw = "Replace both ?this and ?that also.";
String expected = "Replace both <URI> and <ANOTHER> also.";
assertEquals(
expected,
bindValues(raw, uriValue("this", "URI"),
uriValue("that", "ANOTHER")));
}
@Test
public void honorWordBoundary() {
String raw = "Replace ?this but not ?thistle.";
String expected = "Replace <URI> but not ?thistle.";
assertEquals(expected, bindValues(raw, uriValue("this", "URI")));
}
@Test
public void honorStringLimit() {
String raw = "?this";
String expected = "<URI>";
assertEquals(expected, bindValues(raw, uriValue("this", "URI")));
}
private static final String REAL_WORLD_RAW = "" //
+ "PREFIX : <http://vitro.mannlib.cornell.edu/ns/vitro/ApplicationConfiguration#> \n" //
+ "\n" //
+ "SELECT DISTINCT ?context ?config \n" //
+ "WHERE { \n" //
+ " ?context a :ConfigContext ; \n" //
+ " :configContextFor ?baseUri ; \n" //
+ " :qualifiedByDomain ?domainUri ; \n" //
+ " :qualifiedBy ?rangeUri ; \n" //
+ " :hasConfiguration ?config . \n" //
+ "} \n"; //
private static final String REAL_WORLD_EXPECTED = "" //
+ "PREFIX : <http://vitro.mannlib.cornell.edu/ns/vitro/ApplicationConfiguration#> \n" //
+ "\n" //
+ "SELECT DISTINCT ?context ?config \n" //
+ "WHERE { \n" //
+ " ?context a :ConfigContext ; \n" //
+ " :configContextFor <http://vivoweb.org/ontology/core#relates> ; \n" //
+ " :qualifiedByDomain <http://vivoweb.org/ontology/core#Contract> ; \n" //
+ " :qualifiedBy <http://vivoweb.org/ontology/core#ResearcherRole> ; \n" //
+ " :hasConfiguration ?config . \n" //
+ "} \n"; //
@Test
public void realWorldExample() {
assertEquals(
REAL_WORLD_EXPECTED,
bindValues(
REAL_WORLD_RAW,
uriValue("baseUri",
"http://vivoweb.org/ontology/core#relates"),
uriValue("domainUri",
"http://vivoweb.org/ontology/core#Contract"),
uriValue("rangeUri",
"http://vivoweb.org/ontology/core#ResearcherRole")));
}
}

View file

@ -0,0 +1,72 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.utils.dataGetter;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Level;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import stubs.javax.servlet.http.HttpServletRequestStub;
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.impl.RDFDefaultErrorHandler;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
public class DataGetterUtilsTest extends AbstractTestClass{
OntModel displayModel;
VitroRequest vreq;
String testDataGetterURI_1 = "http://vitro.mannlib.cornell.edu/ontologies/display/1.1#query1data";
String pageURI_1 = "http://vitro.mannlib.cornell.edu/ontologies/display/1.1#SPARQLPage";
String pageX = "http://vitro.mannlib.cornell.edu/ontologies/display/1.1#pageX";
String dataGetterX = "http://vitro.mannlib.cornell.edu/ontologies/display/1.1#pageDataGetterX";
@Before
public void setUp() throws Exception {
// Suppress error logging.
setLoggerLevel(RDFDefaultErrorHandler.class, Level.OFF);
Model model = ModelFactory.createDefaultModel();
InputStream in = DataGetterUtilsTest.class.getResourceAsStream("resources/dataGetterTest.n3");
model.read(in,"","N3");
displayModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM,model);
vreq = new VitroRequest(new HttpServletRequestStub());
}
@Test
public void testGetJClassForDataGetterURI() throws IllegalAccessException {
String fullJavaClassName = DataGetterUtils.getJClassForDataGetterURI(displayModel, testDataGetterURI_1);
Assert.assertNotNull(fullJavaClassName);
Assert.assertTrue("java class name should not be empty", ! StringUtils.isEmpty(fullJavaClassName));
Assert.assertEquals(SparqlQueryDataGetter.class.getName(), fullJavaClassName);
}
@Test
public void testDataGetterForURI() throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, ClassNotFoundException, InvocationTargetException, NoSuchMethodException {
DataGetter dg = DataGetterUtils.dataGetterForURI(vreq, displayModel, testDataGetterURI_1);
Assert.assertNotNull(dg);
}
@Test
public void testGetDataGettersForPage() throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, ClassNotFoundException, InvocationTargetException, NoSuchMethodException {
List<DataGetter> dgList =
DataGetterUtils.getDataGettersForPage(vreq, displayModel, pageURI_1);
Assert.assertNotNull(dgList);
Assert.assertTrue("List of DataGetters was empty, it should not be.", dgList.size() > 0);
}
}

View file

@ -0,0 +1,87 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.utils.dataGetter;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Level;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import stubs.javax.servlet.http.HttpServletRequestStub;
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.ResourceFactory;
import com.hp.hpl.jena.rdf.model.impl.RDFDefaultErrorHandler;
import com.hp.hpl.jena.vocabulary.RDF;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.jena.SimpleOntModelSelector;
import edu.cornell.mannlib.vitro.webapp.dao.jena.WebappDaoFactoryJena;
public class SparqlQueryDataGetterTest extends AbstractTestClass{
OntModel displayModel;
String testDataGetterURI_1 = "http://vitro.mannlib.cornell.edu/ontologies/display/1.1#query1data";
WebappDaoFactory wdf;
VitroRequest vreq;
@Before
public void setUp() throws Exception {
// Suppress error logging.
setLoggerLevel(RDFDefaultErrorHandler.class, Level.OFF);
OntModel model = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM);
InputStream in = SparqlQueryDataGetterTest.class.getResourceAsStream("resources/dataGetterTest.n3");
model.read(in,"","N3");
displayModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM,model);
SimpleOntModelSelector sos = new SimpleOntModelSelector( ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM));
sos.setDisplayModel(displayModel);
wdf = new WebappDaoFactoryJena(sos);
vreq = new VitroRequest(new HttpServletRequestStub());
}
@Test
public void testBasicGetData() throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, ClassNotFoundException, InvocationTargetException, NoSuchMethodException {
DataGetter dg = DataGetterUtils.dataGetterForURI(vreq, displayModel, testDataGetterURI_1);
Assert.assertNotNull(dg);
Assert.assertTrue(
"DataGetter should be of type " + SparqlQueryDataGetter.class.getName(),
dg instanceof SparqlQueryDataGetter);
SparqlQueryDataGetter sdg = (SparqlQueryDataGetter)dg;
Model dataModel = ModelFactory.createDefaultModel();
String bobURI = "http://example.com/p/bob";
dataModel.add(ResourceFactory.createResource(bobURI), RDF.type, ResourceFactory.createResource("http://xmlns.com/foaf/0.1/Person"));
Map<String, String> params = Collections.emptyMap();
Map<String,Object> mapOut = sdg.doQueryOnModel(sdg.queryText, dataModel);
Assert.assertNotNull(mapOut);
Assert.assertTrue("should contain key people" , mapOut.containsKey("people"));
Object obj = mapOut.get("people");
Assert.assertTrue("people should be a List, it is " + obj.getClass().getName(), obj instanceof List);
List people = (List)obj;
Assert.assertEquals(1, people.size());
Map<String,String> first = (Map<String, String>) people.get(0);
Assert.assertEquals(bobURI, first.get("uri"));
}
}

View file

@ -0,0 +1,261 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.utils.http;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.utils.http.ContentTypeUtil.AcceptableType;
import edu.cornell.mannlib.vitro.webapp.utils.http.ContentTypeUtil.MatchCriteria;
/**
* TODO
*/
public class ContentTypeUtilTest extends AbstractTestClass {
// ----------------------------------------------------------------------
// MatchCriteria tests
// ----------------------------------------------------------------------
@Test
public void mcEmptyName() {
checkMatchCriteriaConstructor("MC empty name", "", "*", "*");
}
@Test
public void mcNullName() {
checkMatchCriteriaConstructor("MC null name", null, "*", "*");
}
@Test
public void mcTypeOnly() {
checkMatchCriteriaConstructor("MC type only", "image", "image", "*");
}
@Test
public void mcTypeAndSubtype() {
checkMatchCriteriaConstructor("MC type and subtype", "image/png",
"image", "png");
}
@Test
public void mcTypeAndEmptySubtype() {
checkMatchCriteriaConstructor("MC type and empty subtype", "image/",
"image", "*");
}
@Test
public void mcWildcardType() {
checkMatchCriteriaConstructor("MC wild card type", "*", "*", "*");
}
@Test
public void mcWildcardSubtype() {
checkMatchCriteriaConstructor("MC wild card subtype", "image/*",
"image", "*");
}
@Test
public void mcMatchWildcardType() {
checkMatchQuality("MC match wild card type 1", "*", "text", 1);
checkMatchQuality("MC match wild card type 2", "text", "*", 1);
checkMatchQuality("MC match wild card type 3", "*", "text/plain", 1);
checkMatchQuality("MC match wild card type 4", "text/*", "*", 1);
}
@Test
public void mcTypesDontMatch() {
checkMatchQuality("MC types don't match 1", "this", "that", 0);
checkMatchQuality("MC types don't match 2", "this/match", "that/match",
0);
}
@Test
public void mcMatchWildcardSubtype() {
checkMatchQuality("MC match wild card subtype 1", "text", "text/xml", 2);
checkMatchQuality("MC match wild card subtype 2", "image/jpeg",
"image/*", 2);
}
@Test
public void mcSubtypesDontMatch() {
checkMatchQuality("MC match subtypes don't match", "text/xml",
"text/plain", 0);
}
@Test
public void mcFullMatch() {
checkMatchQuality("MC full match", "text/plain", "text/plain", 3);
}
// ----------------------------------------------------------------------
// AcceptableType tests
// ----------------------------------------------------------------------
@Test
public void atNullQ() throws AcceptHeaderParsingException {
checkAcceptableTypeConstructor("AT null Q", null, 1.0F);
}
@Test
public void atEmptyQ() throws AcceptHeaderParsingException {
checkAcceptableTypeConstructor("AT empty Q", "", 1.0F);
}
@Test
public void atBlankQ() throws AcceptHeaderParsingException {
checkAcceptableTypeConstructor("AT blank Q", " \t", 1.0F);
}
@Test(expected = AcceptHeaderParsingException.class)
public void atInvalidQ() throws AcceptHeaderParsingException {
checkAcceptableTypeConstructor("AT invalid Q", "99XX", 0.0F);
}
@Test(expected = AcceptHeaderParsingException.class)
public void atQTooHigh() throws AcceptHeaderParsingException {
checkAcceptableTypeConstructor("AT Q too high", "1.1", 0.0F);
}
@Test(expected = AcceptHeaderParsingException.class)
public void atQTooLow() throws AcceptHeaderParsingException {
checkAcceptableTypeConstructor("AT Q too low", "0", 0.0F);
}
@Test
public void atGoodQ() throws AcceptHeaderParsingException {
checkAcceptableTypeConstructor("AT good Q", "0.4", 0.4F);
}
@Test
public void atWildcardMatchWorks() throws AcceptHeaderParsingException {
checkMatchQuality("AT wild card match", "*", 0.5F, "text/plain", 2.5F);
}
@Test
public void atPartialMatchIsBetter() throws AcceptHeaderParsingException {
checkMatchQuality("AT partial match", "text", 0.5F, "text/plain", 3.5F);
}
@Test
public void atFullMatchIsBest() throws AcceptHeaderParsingException {
checkMatchQuality("AT full match", "text/plain", 0.5F, "text/plain",
4.5F);
}
@Test
public void atNoMatchTotallyBites() throws AcceptHeaderParsingException {
checkMatchQuality("AT full match", "text/xml", 0.5F, "text/plain", 0.0F);
}
// ----------------------------------------------------------------------
// Best content type tests
// ----------------------------------------------------------------------
@Test
public void ctNullHeaderMatchesAnything() throws Exception {
findBestMatch("CT null header matches anything", null,
available("anything"), "anything");
}
@Test
public void ctEmptyHeaderMatchesAnything() throws Exception {
findBestMatch("CT empty header matches anything", "",
available("anything"), "anything");
}
@Test
public void ctBlankHeaderMatchesAnything() throws Exception {
findBestMatch("CT blank header matches anything", " \t ",
available("anything"), "anything");
}
@Test(expected = NotAcceptableException.class)
public void ctNullCollectionMatchesNothing() throws Exception {
findBestMatch("CT null collection matches nothing", "*/*", null,
"nothing");
}
@Test(expected = NotAcceptableException.class)
public void ctEmptyCollectionMatchesNothing() throws Exception {
findBestMatch("CT empty collection matches nothing", "*/*",
available(), "nothing");
}
@Test
public void ctWildcardIsOK() throws Exception {
findBestMatch("CT wild card is OK",
"text/*;q=0.3, text/html;q=0.1, */*;q=0.5",
available("image/png"), "image/png");
}
@Test
public void ctPartialMatchIsBetter() throws Exception {
findBestMatch("CT partial match is better",
"text/*;q=0.3, text/html;q=0.1, */*;q=0.5",
available("image/png", "text/xml"), "text/xml");
}
@Test
public void ctFullMatchIsBest() throws Exception {
findBestMatch("CT full match is best",
"text/*;q=0.3, text/html;q=0.1, */*;q=0.5",
available("image/png", "text/xml", "text/html"), "text/html");
}
@Test(expected = NotAcceptableException.class)
public void ctNoMatchTotalBites() throws Exception {
findBestMatch("CT no match totally bites",
"text/*;q=0.3, text/html;q=0.1", available("no/match"),
"nothing");
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
private void checkMatchCriteriaConstructor(String message, String name,
String expectedType, String expectedSubtype) {
MatchCriteria mc = new MatchCriteria(name);
assertEquals(message + " - type", expectedType, mc.getType());
assertEquals(message + " - subtype", expectedSubtype, mc.getSubtype());
}
private void checkMatchQuality(String message, String name1, String name2,
int expected) {
MatchCriteria mc1 = new MatchCriteria(name1);
MatchCriteria mc2 = new MatchCriteria(name2);
int actual = mc1.matchQuality(mc2);
assertEquals(message, expected, actual);
}
private void checkAcceptableTypeConstructor(String message, String qString,
float expected) throws AcceptHeaderParsingException {
AcceptableType at = new AcceptableType("irrelevant", qString);
assertEquals(message, expected, at.getQ(), 0.0001F);
}
private void checkMatchQuality(String message, String name1, float qValue,
String name2, float expected) throws AcceptHeaderParsingException {
AcceptableType at = new AcceptableType(name1, Float.toString(qValue));
MatchCriteria mc = new MatchCriteria(name2);
float actual = at.fitQuality(mc);
assertEquals(message, expected, actual, 0.0001F);
}
private List<String> available(String... names) {
return Arrays.asList(names);
}
private void findBestMatch(String message, String acceptHeader,
List<String> availableTypeNames, String expected)
throws AcceptHeaderParsingException, NotAcceptableException {
String actual = ContentTypeUtil.bestContentType(acceptHeader,
availableTypeNames);
assertEquals(message, expected, actual);
}
}

View file

@ -0,0 +1,129 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.utils.ingest;
import java.io.StringWriter;
import org.junit.Assert;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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 com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import edu.cornell.mannlib.vitro.webapp.dao.jena.RDFServiceGraph;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
import edu.cornell.mannlib.vitro.webapp.rdfservice.impl.jena.model.RDFServiceModel;
import edu.cornell.mannlib.vitro.webapp.utils.jena.JenaIngestUtils;
public class JenaIngestUtilsTest {
private final Log log = LogFactory.getLog(JenaIngestUtilsTest.class);
protected JenaIngestUtils utils = new JenaIngestUtils();
protected Model makeModel() {
Model base = ModelFactory.createDefaultModel();
RDFService rdfService = new RDFServiceModel(base);
return RDFServiceGraph.createRDFServiceModel(
new RDFServiceGraph(rdfService));
}
@Test
public void testSmush() {
Model model = makeModel();
model.read(JenaIngestUtilsTest.class.getResourceAsStream(
"smush.start.n3"), null, "N3");
JenaIngestUtils utils = new JenaIngestUtils();
Model actualResult = utils.smushResources(
model, model.getProperty("http://example.com/ns/duckCode"));
boolean matchesPossibleResult = false;
for(int i = 1; i < 7; i++) {
Model possibleResult = ModelFactory.createDefaultModel();
possibleResult.read(JenaIngestUtilsTest.class.getResourceAsStream(
"smush.end." + i + ".n3"), null, "N3");
if(actualResult.isIsomorphicWith(possibleResult)) {
matchesPossibleResult = true;
break;
}
}
if (!matchesPossibleResult) {
StringWriter s = new StringWriter();
actualResult.write(s, "N3");
Assert.fail("Smushed model does not match one of the possible results:\n" +
s.toString());
}
}
@Test
public void testRenameBNodes() {
Model initialState = ModelFactory.createDefaultModel();
initialState.read(JenaIngestUtilsTest.class.getResourceAsStream(
"renameBlank.n3"), null, "N3");
Model renamedState = utils.renameBNodes(
initialState, "http://example.org/node/n");
Assert.assertEquals("Post-rename model is not the same size as the " +
"initial model", initialState.size(), renamedState.size());
StmtIterator sit = renamedState.listStatements();
boolean lingeringBNodes = false;
while(sit.hasNext()) {
Statement stmt = sit.nextStatement();
if(stmt.getSubject().isAnon() || stmt.getObject().isAnon()) {
lingeringBNodes = true;
}
}
if(lingeringBNodes) {
StringWriter s = new StringWriter();
renamedState.write(s, "N3");
Assert.fail("Renamed model still contains blank nodes \n" +
s.toString());
}
}
@Test
public void testGenerateTBox() {
Model abox = ModelFactory.createDefaultModel();
abox.read(JenaIngestUtilsTest.class.getResourceAsStream(
"abox.n3"), null, "N3");
Model tbox = ModelFactory.createDefaultModel();
tbox.read(JenaIngestUtilsTest.class.getResourceAsStream(
"tbox.n3"), null, "N3");
Model generatedTBox = utils.generateTBox(abox);
//log.warn(tbox.toString());
Assert.assertTrue("Generated TBox does not match expected result",
tbox.isIsomorphicWith(generatedTBox));
}
@Test
public void testDoMerge() {
OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, makeModel());
OntModel tbox = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, makeModel());
model.read(JenaIngestUtilsTest.class.getResourceAsStream(
"merge.n3"), null, "N3");
tbox.read(JenaIngestUtilsTest.class.getResourceAsStream("tbox.n3"), null, "N3");
Model expectedMergeMultipleLabels = model.read(
JenaIngestUtilsTest.class.getResourceAsStream(
"mergeResultMultipleLabels.n3"), null, "N3");
utils.doMerge("http://example.com/ns/n1", "http://example.com/ns/n1", model, tbox, false);
Assert.assertTrue("Merged model with multiple labels does not match " +
"expected result", expectedMergeMultipleLabels.isIsomorphicWith(model));
model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, makeModel());
model.read(JenaIngestUtilsTest.class.getResourceAsStream(
"merge.n3"), null, "N3");
Model expectedMergeSingleLabel = model.read(
JenaIngestUtilsTest.class.getResourceAsStream(
"mergeResultSingleLabel.n3"), null, "N3");
utils.doMerge("http://example.com/ns/n1", "http://example.com/ns/n1", model, tbox, true);
Assert.assertTrue("Merged model with multiple labels does not match " +
"expected result", expectedMergeSingleLabel.isIsomorphicWith(model));
}
}

View file

@ -0,0 +1,41 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.utils.jena;
import org.junit.Assert;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import org.junit.Test;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDF;
public class JenaIngestUtilsTest extends AbstractTestClass {
@Test
public void testRenameBNodes() {
JenaIngestUtils jiu = new JenaIngestUtils();
Model blankModel = ModelFactory.createDefaultModel();
for (int i = 0; i < 20; i++) {
blankModel.add(blankModel.createResource(), RDF.type, OWL.Thing);
}
Assert.assertTrue(blankModel.size() == 20);
Model named = jiu.renameBNodes(blankModel, "http://example.org/resource");
Assert.assertTrue(named.size() == blankModel.size());
Assert.assertTrue(named.size() == 20);
StmtIterator stmtIt = named.listStatements();
while (stmtIt.hasNext()) {
Statement stmt = stmtIt.nextStatement();
Assert.assertEquals("http://example.org/", stmt.getSubject().getNameSpace());
}
}
}

View file

@ -0,0 +1,80 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.utils.searchengine;
import static org.junit.Assert.*;
import org.junit.Test;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
public class AutoCompleteWordsTest extends AbstractTestClass {
private static final String WORD_DELIMITER = "[, ]+";
private static final String FIELD_NAME_COMPLETE = "complete";
private static final String FIELD_NAME_PARTIAL = "partial";
@Test
public void nullSearchTerm() {
assertQueryString(null, "");
}
@Test
public void emptySearchTerm() {
assertQueryString("", "");
}
@Test
public void blankSearchTerm() {
assertQueryString(" ", "");
}
@Test
public void searchTermContainsOnlyCommas() {
assertQueryString(",,", "");
}
@Test
public void oneWord() {
assertQueryString("first", "partial:\"first\"");
}
@Test
public void twoWords() {
assertQueryString("first, second",
"complete:\"first\" AND partial:\"second\"");
}
@Test
public void threeWords() {
assertQueryString("first, second, third",
"complete:\"first\" AND complete:\"second\" AND partial:\"third\"");
}
@Test
public void oneWordAndComma() {
assertQueryString("first,", "complete:\"first\"");
}
@Test
public void oneWordAndCommaAndSpace() {
assertQueryString("first, ", "complete:\"first\"");
}
@Test
public void emptyCompleteWord() {
assertQueryString(", second", "partial:\"second\"");
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
private void assertQueryString(String searchTerm, String expected) {
AutoCompleteWords acw = new AutoCompleteWords(searchTerm,
WORD_DELIMITER);
String actual = acw.assembleQuery(FIELD_NAME_COMPLETE,
FIELD_NAME_PARTIAL);
assertEquals(expected, actual);
}
}

View file

@ -0,0 +1,63 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.web;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import edu.cornell.mannlib.vitro.webapp.controller.individual.IndividualController;
public class ContentTypeTest {
@Test
public void typeAndQTest1(){
Map<String,Float> map = ContentType.getTypesAndQ(
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,application/rdf+xml;q=0.93,text/rdf+n3;q=0.5");
Assert.assertEquals(1.0f, map.get("text/html"), 0.01f);
Assert.assertEquals(1.0f, map.get("application/xhtml+xml"), 0.01f);
Assert.assertEquals(0.9f, map.get("application/xml"), 0.01f);
Assert.assertEquals(0.93f,map.get("application/rdf+xml"), 0.01f);
Assert.assertEquals(0.5f, map.get("text/rdf+n3"), 0.01f);
Assert.assertEquals(0.8f,map.get("*/*"), 0.01f);
}
@Test
public void typeAndQTest2(){
Map<String,Float> map = ContentType.getTypesAndQ(
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
Assert.assertEquals(1.0f, map.get("text/html"), 0.01f);
Assert.assertEquals(1.0f, map.get("application/xhtml+xml"), 0.01f);
Assert.assertEquals(0.9f, map.get("application/xml"), 0.01f);
Assert.assertEquals(0.8f,map.get("*/*"), 0.01f);
}
@Test
public void testWeightedBestContentTypeForTabulator(){
//accept header from tabulator
Map<String,Float> clientAccepts = ContentType.getTypesAndQ(
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,application/rdf+xml;q=0.93,text/rdf+n3;q=0.5");
Map<String,Float> serverTypes = IndividualController.ACCEPTED_CONTENT_TYPES;
Assert.assertEquals("application/rdf+xml", ContentType.getBestContentType(clientAccepts, serverTypes));
}
/**
* Modified this, added q-factor to text/html, because otherwise the result is indeterminate, and the
* test fails in Java 8.
*/
@Test
public void testWeightedBestContentTypeForFirefox(){
//accept header from normal firefox
Map<String,Float> clientAccepts = ContentType.getTypesAndQ(
"text/html;q=0.95,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
Map<String,Float> serverTypes = IndividualController.ACCEPTED_CONTENT_TYPES;
Assert.assertEquals("application/xhtml+xml", ContentType.getBestContentType(clientAccepts, serverTypes));
}
}

View file

@ -0,0 +1,22 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.web.templatemodels;
import org.junit.Test;
public class BaseTemplateModelTest {
private static String value;
@Test
public void testCleanURIofNull(){
BaseTemplateModel btm = new BaseTemplateModel(){};
//should not throw NPE
value = btm.cleanURIForDisplay( null );
//should not throw NPE
value = btm.cleanTextForDisplay( null );
}
}

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