Merge remote-tracking branch 'origin' into develop

This commit is contained in:
Brian Caruso 2013-03-05 17:15:58 -05:00
commit 08f583e280
110 changed files with 5057 additions and 1583 deletions

View file

@ -0,0 +1,308 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServlet;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.NameFileFilter;
import org.apache.commons.io.filefilter.NotFileFilter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
/**
* Check to see that web.xml doesn't include any constructs that are permitted
* by Tomcat but prohibited by the Servlet 2.4 Specification.
*
* These are things that might not be noticed when testing Vitro on Tomcat, but
* might show up as problems on other containers like GlassFish or WebLogic.
* <ul>
* <li>
* The contents of <dispatcher/> elements must be upper-case. Tomcat permits
* lower-case, but the specification does not.</li>
* <li>
* All <servlet-class/> tags must point to existing classes. Tomcat does not try
* to load a servlet until it is necessary to service a request, but WebLogic
* loads them on startup. Either method is permitted by the specification.</li>
* </ul>
*
* As long as we're here, let's check some things that would cause Vitro to fail
* in any servlet container.
* <ul>
* <li>
* All <listener-class/> tags must point to existing classes.</li>
* <li>
* All <filter-class/> tags must point to existing classes.</li>
* <li>
* All <taglib-location/> tags must point to existing files.</li>
* </ul>
*/
@RunWith(value = Parameterized.class)
public class WebXmlTest extends AbstractTestClass {
private static final Log log = LogFactory.getLog(WebXmlTest.class);
@Parameters
public static Collection<Object[]> findWebXmlFiles() {
IOFileFilter fileFilter = new NameFileFilter("web.xml");
IOFileFilter dirFilter = new NotFileFilter(new NameFileFilter(".build"));
Collection<File> files = FileUtils.listFiles(new File("."), fileFilter,
dirFilter);
if (files.isEmpty()) {
System.out.println("WARNING: could not find web.xml");
} else {
if (files.size() > 1) {
System.out
.println("WARNING: testing more than one web.xml file: "
+ files);
}
}
Collection<Object[]> parameters = new ArrayList<Object[]>();
for (File file : files) {
parameters.add(new Object[] { file });
}
return parameters;
}
private static DocumentBuilder docBuilder = createDocBuilder();
private static XPath xpath = createXPath();
private static DocumentBuilder createDocBuilder() {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
factory.setNamespaceAware(true); // never forget this!
return factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
}
private static XPath createXPath() {
XPath xp = XPathFactory.newInstance().newXPath();
xp.setNamespaceContext(new StupidNamespaceContext());
return xp;
}
private File webXmlFile;
private Document webXmlDoc;
private List<String> messages = new ArrayList<String>();
public WebXmlTest(File file) {
this.webXmlFile = file;
}
@Before
public void parseWebXml() throws SAXException, IOException {
if (webXmlDoc == null) {
webXmlDoc = docBuilder.parse(webXmlFile);
}
}
@Test
public void checkAll() throws IOException {
checkDispatcherValues();
checkServletClasses();
checkListenerClasses();
checkFilterClasses();
checkTaglibLocations();
if (!messages.isEmpty()) {
for (String message : messages) {
System.out.println(message);
}
fail("Found these problems with '" + webXmlFile.getCanonicalPath()
+ "'\n " + StringUtils.join(messages, "\n "));
}
}
private void checkDispatcherValues() {
List<String> okValues = Arrays.asList(new String[] { "FORWARD",
"REQUEST", "INCLUDE", "ERROR" });
for (Node n : findNodes("//j2ee:dispatcher")) {
String text = n.getTextContent();
if (!okValues.contains(text)) {
messages.add("<dispatcher>" + text
+ "</dispatcher> is not valid. Acceptable values are "
+ okValues);
}
}
}
private void checkServletClasses() {
for (Node n : findNodes("//j2ee:servlet-class")) {
String text = n.getTextContent();
String problem = confirmClassNameIsValid(text, HttpServlet.class);
if (problem != null) {
messages.add("<servlet-class>" + text
+ "</servlet-class> is not valid: " + problem);
}
}
}
private void checkListenerClasses() {
for (Node n : findNodes("//j2ee:listener-class")) {
String text = n.getTextContent();
String problem = confirmClassNameIsValid(text,
ServletContextListener.class);
if (problem != null) {
messages.add("<listener-class>" + text
+ "</listener-class> is not valid: " + problem);
}
}
}
private void checkFilterClasses() {
for (Node n : findNodes("//j2ee:filter-class")) {
String text = n.getTextContent();
String problem = confirmClassNameIsValid(text, Filter.class);
if (problem != null) {
messages.add("<filter-class>" + text
+ "</filter-class> is not valid: " + problem);
}
}
}
private void checkTaglibLocations() {
// TODO Don't know how to do this one. Where do we look for the taglibs?
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
/**
* Search for an Xpath, returning a handy list.
*/
private List<Node> findNodes(String pattern) {
try {
XPathExpression xpe = xpath.compile(pattern);
NodeList nodes = (NodeList) xpe.evaluate(
webXmlDoc.getDocumentElement(), XPathConstants.NODESET);
List<Node> list = new ArrayList<Node>();
for (int i = 0; i < nodes.getLength(); i++) {
list.add(nodes.item(i));
}
return list;
} catch (XPathExpressionException e) {
throw new RuntimeException(e);
}
}
/**
* Check that the supplied className can be instantiated with a
* zero-argument constructor, and assigned to a variable of the target
* class.
*/
private String confirmClassNameIsValid(String className,
Class<?> targetClass) {
try {
Class<?> specifiedClass = Class.forName(className);
Object o = specifiedClass.newInstance();
if (!targetClass.isInstance(o)) {
return specifiedClass.getSimpleName()
+ " is not a subclass of "
+ targetClass.getSimpleName() + ".";
}
} catch (ClassNotFoundException e) {
return "The class does not exist.";
} catch (InstantiationException e) {
return "The class does not have a public constructor "
+ "that takes zero arguments.";
} catch (IllegalAccessException e) {
return "The class does not have a public constructor "
+ "that takes zero arguments.";
}
return null;
}
/**
* Dump the first 20 nodes of an XML context, excluding comments and blank
* text nodes.
*/
@SuppressWarnings("unused")
private int dumpXml(Node xmlNode, int... parms) {
int remaining = (parms.length == 0) ? 20 : parms[0];
int level = (parms.length < 2) ? 1 : parms[1];
Node n = xmlNode;
if (Node.COMMENT_NODE == n.getNodeType()) {
return 0;
}
if (Node.TEXT_NODE == n.getNodeType()) {
if (StringUtils.isBlank(n.getTextContent())) {
return 0;
}
}
int used = 1;
System.out.println(StringUtils.repeat("-->", level) + n);
NodeList nl = n.getChildNodes();
for (int i = 0; (i < nl.getLength() && remaining > used); i++) {
used += dumpXml(nl.item(i), remaining - used, level + 1);
}
return used;
}
// ----------------------------------------------------------------------
// Helper classes
// ----------------------------------------------------------------------
private static class StupidNamespaceContext implements NamespaceContext {
@Override
public String getNamespaceURI(String prefix) {
if ("j2ee".equals(prefix)) {
return "http://java.sun.com/xml/ns/j2ee";
} else {
throw new UnsupportedOperationException();
}
}
@Override
public String getPrefix(String namespaceURI) {
throw new UnsupportedOperationException();
}
@Override
public Iterator<?> getPrefixes(String namespaceURI) {
throw new UnsupportedOperationException();
}
}
}

View file

@ -52,15 +52,6 @@ public class IndividualRequestAnalyzerTest extends AbstractTestClass {
private static final String URL_BYTESTREAM_ALIAS = URL_HOME_PAGE + "/file/"
+ ID_FILE_BYTESTREAM + "/" + BYTESTREAM_FILENAME;
/**
* Info about an individual that appears in a different namespace.
*/
private static final String SOME_PREFIX = "somePrefix";
private static final String SOME_NAMESPACE = "http://some.namespace/";
private static final String ID_INDIVIDUAL_FOREIGN = "foreignId";
private static final String URI_INDIVIDUAL_FOREIGN = SOME_NAMESPACE
+ ID_INDIVIDUAL_FOREIGN;
private IndividualRequestAnalyzer analyzer;
private IndividualRequestAnalysisContextStub analysisContext;
private HttpServletRequestStub req;
@ -69,7 +60,6 @@ public class IndividualRequestAnalyzerTest extends AbstractTestClass {
private IndividualStub testIndividual;
private IndividualStub bytestreamIndividual;
private IndividualStub foreignIndividual;
@Before
public void setup() {
@ -83,10 +73,6 @@ public class IndividualRequestAnalyzerTest extends AbstractTestClass {
bytestreamIndividual = new IndividualStub(URI_FILE_BYTESTREAM);
analysisContext.addIndividual(bytestreamIndividual);
analysisContext.setAliasUrl(URI_FILE_BYTESTREAM, URL_BYTESTREAM_ALIAS);
foreignIndividual = new IndividualStub(URI_INDIVIDUAL_FOREIGN);
analysisContext.addIndividual(foreignIndividual);
analysisContext.setNamespacePrefix(SOME_PREFIX, SOME_NAMESPACE);
}
// ----------------------------------------------------------------------
@ -132,16 +118,6 @@ public class IndividualRequestAnalyzerTest extends AbstractTestClass {
assertDefaultRequestInfo("find by display path", URI_INDIVIDUAL_TEST);
}
/** /individual/nsPrefix/localname */
@Test
public void findByPrefixAndLocalname() {
req.setRequestUrl(url(DEFAULT_NAMESPACE + SOME_PREFIX + "/"
+ ID_INDIVIDUAL_FOREIGN));
analyzeIt();
assertDefaultRequestInfo("find by prefix and localname",
URI_INDIVIDUAL_FOREIGN);
}
/** /individual/a/b/c fails. */
@Test
public void unrecognizedPath() {

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,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,179 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.com.hp.hpl.jena.rdf.model;
import com.hp.hpl.jena.datatypes.RDFDatatype;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.RDFVisitor;
import com.hp.hpl.jena.rdf.model.Resource;
/**
* Only implemented what I needed so far. The rest is left as an exercise for
* the student.
*/
public class LiteralStub implements Literal {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
final String language;
public LiteralStub(String language) {
this.language = language;
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public boolean isLiteral() {
return true;
}
@Override
public boolean isAnon() {
return false;
}
@Override
public boolean isResource() {
return false;
}
@Override
public boolean isURIResource() {
return false;
}
@Override
public Literal asLiteral() {
return this;
}
@Override
public Resource asResource() {
throw new ClassCastException();
}
@Override
public String getLanguage() {
return language;
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public <T extends RDFNode> T as(Class<T> view) {
throw new RuntimeException("LiteralStub.as() not implemented.");
}
@Override
public <T extends RDFNode> boolean canAs(Class<T> arg0) {
throw new RuntimeException("LiteralStub.canAs() not implemented.");
}
@Override
public Model getModel() {
throw new RuntimeException("LiteralStub.getModel() not implemented.");
}
@Override
public Object visitWith(RDFVisitor arg0) {
throw new RuntimeException("LiteralStub.visitWith() not implemented.");
}
@Override
public Node asNode() {
throw new RuntimeException("LiteralStub.asNode() not implemented.");
}
@Override
public boolean getBoolean() {
throw new RuntimeException("LiteralStub.getBoolean() not implemented.");
}
@Override
public byte getByte() {
throw new RuntimeException("LiteralStub.getByte() not implemented.");
}
@Override
public char getChar() {
throw new RuntimeException("LiteralStub.getChar() not implemented.");
}
@Override
public RDFDatatype getDatatype() {
throw new RuntimeException("LiteralStub.getDatatype() not implemented.");
}
@Override
public String getDatatypeURI() {
throw new RuntimeException(
"LiteralStub.getDatatypeURI() not implemented.");
}
@Override
public double getDouble() {
throw new RuntimeException("LiteralStub.getDouble() not implemented.");
}
@Override
public float getFloat() {
throw new RuntimeException("LiteralStub.getFloat() not implemented.");
}
@Override
public int getInt() {
throw new RuntimeException("LiteralStub.getInt() not implemented.");
}
@Override
public String getLexicalForm() {
throw new RuntimeException(
"LiteralStub.getLexicalForm() not implemented.");
}
@Override
public long getLong() {
throw new RuntimeException("LiteralStub.getLong() not implemented.");
}
@Override
public short getShort() {
throw new RuntimeException("LiteralStub.getShort() not implemented.");
}
@Override
public String getString() {
throw new RuntimeException("LiteralStub.getString() not implemented.");
}
@Override
public Object getValue() {
throw new RuntimeException("LiteralStub.getValue() not implemented.");
}
@Override
public Literal inModel(Model arg0) {
throw new RuntimeException("LiteralStub.inModel() not implemented.");
}
@Override
public boolean isWellFormedXML() {
throw new RuntimeException(
"LiteralStub.isWellFormedXML() not implemented.");
}
@Override
public boolean sameValueAs(Literal arg0) {
throw new RuntimeException("LiteralStub.sameValueAs() not implemented.");
}
}

View file

@ -21,7 +21,6 @@ public class IndividualRequestAnalysisContextStub implements
private final String defaultNamespace;
private final Map<String, Individual> individualsByUri = new HashMap<String, Individual>();
private final Map<String, Individual> profilePages = new HashMap<String, Individual>();
private final Map<String, String> namespacesByPrefix = new HashMap<String, String>();
private final Map<String, String> aliasUrlsByIndividual = new HashMap<String, String>();
public IndividualRequestAnalysisContextStub(String defaultNamespace) {
@ -36,10 +35,6 @@ public class IndividualRequestAnalysisContextStub implements
profilePages.put(netId, individual);
}
public void setNamespacePrefix(String prefix, String namespace) {
namespacesByPrefix.put(prefix, namespace);
}
public void setAliasUrl(String individualUri, String aliasUrl) {
aliasUrlsByIndividual.put(individualUri, aliasUrl);
}
@ -53,15 +48,6 @@ public class IndividualRequestAnalysisContextStub implements
return defaultNamespace;
}
@Override
public String getNamespaceForPrefix(String prefix) {
if (prefix == null) {
return "";
}
String namespace = namespacesByPrefix.get(prefix);
return (namespace == null) ? "" : namespace;
}
@Override
public Individual getIndividualByURI(String individualUri) {
if (individualUri == null) {

View file

@ -0,0 +1,140 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.edu.cornell.mannlib.vitro.webapp.startup;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus;
/**
* Keep track of how many messages come in.
*/
public class StartupStatusStub extends StartupStatus {
private static final Log log = LogFactory.getLog(StartupStatusStub.class);
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private int infoCount = 0;
private int warningCount = 0;
private int fatalCount = 0;
public StartupStatusStub(ServletContext ctx) {
ctx.setAttribute(ATTRIBUTE_NAME, this);
}
public int getInfoCount() {
return infoCount;
}
public int getWarningCount() {
return warningCount;
}
public int getFatalCount() {
return fatalCount;
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public void info(ServletContextListener listener, String message) {
log.debug("INFO: " + message);
infoCount++;
}
@Override
public void info(ServletContextListener listener, String message,
Throwable cause) {
log.debug("INFO: " + message + " " + cause);
infoCount++;
}
@Override
public void warning(ServletContextListener listener, String message) {
log.debug("WARNING: " + message);
warningCount++;
}
@Override
public void warning(ServletContextListener listener, String message,
Throwable cause) {
log.debug("WARNING: " + message + " " + cause);
warningCount++;
}
@Override
public void fatal(ServletContextListener listener, String message) {
log.debug("FATAL: " + message);
fatalCount++;
}
@Override
public void fatal(ServletContextListener listener, String message,
Throwable cause) {
log.debug("FATAL: " + message + " " + cause);
fatalCount++;
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public void listenerNotExecuted(ServletContextListener listener) {
throw new RuntimeException(
"StartupStatusStub.listenerNotExecuted() not implemented.");
}
@Override
public void listenerExecuted(ServletContextListener listener) {
throw new RuntimeException(
"StartupStatusStub.listenerExecuted() not implemented.");
}
@Override
public boolean allClear() {
throw new RuntimeException(
"StartupStatusStub.allClear() not implemented.");
}
@Override
public boolean isStartupAborted() {
throw new RuntimeException(
"StartupStatusStub.isStartupAborted() not implemented.");
}
@Override
public List<StatusItem> getStatusItems() {
throw new RuntimeException(
"StartupStatusStub.getStatusItems() not implemented.");
}
@Override
public List<StatusItem> getErrorItems() {
throw new RuntimeException(
"StartupStatusStub.getErrorItems() not implemented.");
}
@Override
public List<StatusItem> getWarningItems() {
throw new RuntimeException(
"StartupStatusStub.getWarningItems() not implemented.");
}
@Override
public List<StatusItem> getItemsForListener(ServletContextListener listener) {
throw new RuntimeException(
"StartupStatusStub.getItemsForListener() not implemented.");
}
}

View file

@ -1,123 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package stubs.edu.cornell.mannlib.vitro.webapp.utils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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;
/**
* A minimal implementation of the NamespaceMapper.
*
* I have only implemented the methods that I needed. Feel free to implement
* others.
*/
public class NamespaceMapperStub implements NamespaceMapper {
// ----------------------------------------------------------------------
// Stub infrastructure
// ----------------------------------------------------------------------
private final Map<String, String> prefixMap = new HashMap<String, String>();
public void setPrefixForNamespace(String prefix, String namespace) {
prefixMap.put(prefix, namespace);
}
// ----------------------------------------------------------------------
// Stub methods
// ----------------------------------------------------------------------
@Override
public String getNamespaceForPrefix(String prefix) {
return prefixMap.get(prefix);
}
// ----------------------------------------------------------------------
// Un-implemented methods
// ----------------------------------------------------------------------
@Override
public void addedStatement(Statement arg0) {
throw new RuntimeException(
"NamespaceMapperStub.addedStatement() not implemented.");
}
@Override
public void addedStatements(Statement[] arg0) {
throw new RuntimeException(
"NamespaceMapperStub.addedStatements() not implemented.");
}
@Override
public void addedStatements(List<Statement> arg0) {
throw new RuntimeException(
"NamespaceMapperStub.addedStatements() not implemented.");
}
@Override
public void addedStatements(StmtIterator arg0) {
throw new RuntimeException(
"NamespaceMapperStub.addedStatements() not implemented.");
}
@Override
public void addedStatements(Model arg0) {
throw new RuntimeException(
"NamespaceMapperStub.addedStatements() not implemented.");
}
@Override
public void notifyEvent(Model arg0, Object arg1) {
throw new RuntimeException(
"NamespaceMapperStub.notifyEvent() not implemented.");
}
@Override
public void removedStatement(Statement arg0) {
throw new RuntimeException(
"NamespaceMapperStub.removedStatement() not implemented.");
}
@Override
public void removedStatements(Statement[] arg0) {
throw new RuntimeException(
"NamespaceMapperStub.removedStatements() not implemented.");
}
@Override
public void removedStatements(List<Statement> arg0) {
throw new RuntimeException(
"NamespaceMapperStub.removedStatements() not implemented.");
}
@Override
public void removedStatements(StmtIterator arg0) {
throw new RuntimeException(
"NamespaceMapperStub.removedStatements() not implemented.");
}
@Override
public void removedStatements(Model arg0) {
throw new RuntimeException(
"NamespaceMapperStub.removedStatements() not implemented.");
}
@Override
public String getPrefixForNamespace(String namespace) {
throw new RuntimeException(
"NamespaceMapperStub.getPrefixForNamespace() not implemented.");
}
@Override
public List<String> getPrefixesForNamespace(String namespace) {
throw new RuntimeException(
"NamespaceMapperStub.getPrefixesForNamespace() not implemented.");
}
}