Compare commits

..

41 commits

Author SHA1 Message Date
234a849a19 Moved shortview config to VIVO branch 2021-06-28 20:02:53 +02:00
75557ca4aa Moved template change to VIVO branch 2021-06-28 14:41:22 +02:00
45f303c1ae Reverted changes to Vitro templates. Move files to VIVO branch. 2021-06-28 14:27:03 +02:00
f16eef642a Use unique key in account activation link and reset password link (#234)
* Use unique key for email activation and password reset

* Renamed old variable from hash to key

* Check for null before setting email key for backward compatibility. Removed comment about old behaviour.

* Send password_change_invalid_key message instead of password_change_not_pending on key mismatch.
2021-06-12 18:56:16 +02:00
Brian Lowe
0df4231b41 Move event listening to RDFServiceGraph level to avoid adding a new redundant listener each time a model is made for an existing RDFServiceGraph. Resolve https://jira.lyrasis.org/browse/VIVO-1976 2021-04-12 13:05:52 +02:00
Brian Lowe
48297bba56 Allow site admins to edit pages in page management. Resolve https://jira.lyrasis.org/browse/VIVO-1973 2021-04-09 15:34:15 +02:00
32f817e73a Autoselect hits per page from query. 2021-04-07 18:04:34 +02:00
Svetlana Rastegina
a9a89d220b Added classes for titles. 2021-03-31 14:21:04 +02:00
1dbbe6ed4c Renamed works to sources 2021-03-30 15:41:59 +02:00
4ab94d59af Fix compilation creation 2021-03-26 14:11:30 +01:00
c2429a6768 Allow table tags in TinyMCE 2021-03-25 12:40:40 +01:00
Svetlana Rastegina
64cd06fbbb Removed collapsible buttons paddings. 2021-03-22 23:08:22 +01:00
Svetlana Rastegina
0bdfe65d42 Removed margin top in search results. 2021-03-22 19:43:53 +01:00
8e3a98cc56 Collapse all results on virtual article display 2021-03-22 19:20:00 +01:00
e2d37bbb75 Moved create new compilation button inside container 2021-03-22 13:29:42 +01:00
caa1bc8412 Hide literature and bibliography by default 2021-03-22 13:17:12 +01:00
63f15a90ef Fixed delete individual url params 2021-03-01 21:56:42 +01:00
cb35b5f647 Open try block before creating query 2021-03-01 12:32:21 +01:00
2f8fa040db Allow admins delete individuals 2021-02-25 23:17:32 +01:00
75841b9fb2 Do not create compilation with no excerpts 2021-02-25 21:48:19 +01:00
1590d58830 Process query builder rules in custom search controller 2021-02-24 01:17:53 +01:00
a6fa88bd1f Cleaned custom search controller 2021-02-23 20:39:55 +01:00
d6eb01de9c Fix naming mistake in describe query 2021-02-18 18:53:07 +01:00
af9820b7f3 Added template model, freemarker macro and pass checks in EditRequestDispatchController for individual deletion 2021-02-18 18:33:52 +01:00
William Welling
2e0b3f0f05 VIVO-1929: patch authorizing create individual form (#206)
* patch authorizing create individual form

Resolves: https://jira.lyrasis.org/browse/VIVO-1929
2021-02-17 15:25:39 +01:00
4fdbb71fee Added code for deleting individuals 2021-02-17 14:15:10 +01:00
2a56ec8c30 fix 2021-01-30 17:43:36 +01:00
566ca88d6f Added scripts to fill out new compilation form from search results 2021-01-27 18:54:39 +01:00
9d48755893 Removed unused code 2020-09-21 15:21:44 +02:00
f6fbe83c90 Show query form in search error page 2020-09-03 17:23:08 +02:00
3e5e60e788 Added combined search form. 2020-09-03 15:37:54 +02:00
084801bf5e Reorder search results messages 2020-09-02 16:10:05 +02:00
df8c386663 Added query builder to search results 2020-08-25 10:48:29 +02:00
98398a58b6 Switch to custom search service 2020-08-18 15:07:34 +02:00
37579c5581 Changed ontology 2020-08-13 19:36:12 +02:00
ee16a2863d Configured used html tags 2020-08-03 16:53:44 +02:00
38e8d326a6 Fix compile error 2020-08-03 16:16:23 +02:00
d2a3a73d3c Antisamy policy fixes 2020-08-03 16:16:02 +02:00
06e1e104df Added search queries 2020-07-14 14:14:00 +02:00
f36881f24c Short view for virtual articles 2020-07-08 13:33:32 +02:00
d5a9a9bca6 Virtual articles search template 2020-07-08 13:19:23 +02:00
231 changed files with 2630 additions and 11261 deletions

View file

@ -1,34 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. Windows, Linux]
- Browser [e.g. chrome, safari]
- Tomcat version [e.g. 8, 9]
- VIVO version [e.g. 1.11.0, 1.12.0]
- Apache Solr or ElasticSearch version
**Additional context**
Add any other context about the problem here.

View file

@ -1,20 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

View file

@ -1,28 +0,0 @@
name: Build
on: [ push, pull_request, workflow_dispatch ]
jobs:
build:
runs-on: ubuntu-latest
env:
MAVEN_OPTS: -Xmx1024M
steps:
- uses: actions/checkout@v2
- name: Maven Cache
uses: actions/cache@v2
with:
path: ~/.m2/repository
key: ${{ runner.os }}-cache-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: ${{ runner.os }}-cache-m2-
- name: Setup Java
uses: actions/setup-java@v1
with:
java-version: 11
- name: Maven Build
run: mvn clean install

22
.travis.yml Normal file
View file

@ -0,0 +1,22 @@
language: java
dist: trusty
sudo: false
jdk:
- openjdk8
- oraclejdk8
env:
# Give Maven 1GB of memory to work with
- MAVEN_OPTS=-Xmx1024M
cache:
directories:
- .autoconf
- $HOME/.m2
install:
- "echo 'Skipping install stage, dependencies will be downloaded during build and test stages.'"
script:
- "mvn clean package -Dmaven.test.skip=false"

View file

@ -1,6 +1,6 @@
# What is Vitro?
[![Build](https://github.com/vivo-project/Vitro/workflows/Build/badge.svg)](https://github.com/vivo-project/Vitro/actions?query=workflow%3ABuild)
[![Build Status](https://travis-ci.org/vivo-project/Vitro.png?branch=develop)](https://travis-ci.org/vivo-project/Vitro)
Vitro is a general-purpose web-based ontology and instance editor with customizable public browsing.

View file

@ -7,13 +7,13 @@
<groupId>org.vivoweb</groupId>
<artifactId>vitro-api</artifactId>
<version>1.12.1-SNAPSHOT</version>
<version>1.11.2-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.vivoweb</groupId>
<artifactId>vitro-project</artifactId>
<version>1.12.1-SNAPSHOT</version>
<version>1.11.2-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
@ -66,7 +66,7 @@
<dependency>
<groupId>org.vivoweb</groupId>
<artifactId>vitro-dependencies</artifactId>
<version>1.12.1-SNAPSHOT</version>
<version>1.11.2-SNAPSHOT</version>
<type>pom</type>
</dependency>
<dependency>
@ -85,7 +85,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>

View file

@ -62,7 +62,6 @@ public class ApplicationSetup implements ServletContextListener {
private void locateApplicationConfigFile() {
Path path = this.vitroHomeDir.getPath().resolve(APPLICATION_SETUP_PATH);
if (!Files.exists(path)) {
throw new IllegalStateException("'" + path + "' does not exist.");
}

View file

@ -37,14 +37,7 @@ public class RootUserPolicy implements PolicyIface {
private static final Log log = LogFactory.getLog(RootUserPolicy.class);
private static final String PROPERTY_ROOT_USER_EMAIL = "rootUser.emailAddress";
/*
* UQAM Add-Feature For parameterization of rootUser
*/
private static final String PROPERTY_ROOT_USER_PASSWORD = "rootUser.password";
private static final String PROPERTY_ROOT_USER_PASSWORD_CHANGE_REQUIRED = "rootUser.passwordChangeRequired";
private static final String ROOT_USER_INITIAL_PASSWORD = "rootPassword";
private static final String ROOT_USER_INITIAL_PASSWORD_CHANGE_REQUIRED = "true";
/**
* This is the entire policy. If you are a root user, you are authorized.
@ -157,12 +150,10 @@ public class RootUserPolicy implements PolicyIface {
ua.setEmailAddress(configuredRootUser);
ua.setFirstName("root");
ua.setLastName("user");
// UQAM Add-Feature using getRootPasswordFromConfig()
ua.setArgon2Password(Authenticator.applyArgon2iEncoding(
getRootPasswordFromConfig()));
ROOT_USER_INITIAL_PASSWORD));
ua.setMd5Password("");
// UQAM Add-Feature using getRootPasswdChangeRequiredFromConfig()
ua.setPasswordChangeRequired(getRootPasswdChangeRequiredFromConfig().booleanValue());
ua.setPasswordChangeRequired(true);
ua.setStatus(Status.ACTIVE);
ua.setRootUser(true);
@ -200,31 +191,7 @@ public class RootUserPolicy implements PolicyIface {
ss.warning(this, "For security, "
+ "it is best to delete unneeded root user accounts.");
}
/*
* UQAM Add-Feature
* Add for getting rootUser.password property value from runtime.properties
*/
private String getRootPasswordFromConfig() {
String passwd = ConfigurationProperties.getBean(ctx).getProperty(
PROPERTY_ROOT_USER_PASSWORD);
if (passwd == null) {
passwd = ROOT_USER_INITIAL_PASSWORD;
}
return passwd;
}
/*
* UQAM Add-Feature
* Add for getting rootUser.passwordChangeRequired property value from runtime.properties
*/
private Boolean getRootPasswdChangeRequiredFromConfig() {
String passwdCR = ConfigurationProperties.getBean(ctx).getProperty(
PROPERTY_ROOT_USER_PASSWORD_CHANGE_REQUIRED);
if (passwdCR == null) {
passwdCR = ROOT_USER_INITIAL_PASSWORD_CHANGE_REQUIRED;
}
return new Boolean(passwdCR);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// Nothing to destroy

View file

@ -20,7 +20,6 @@ public class ApplicationBean {
public final static int VIVO_SEARCHBOX_SIZE = 20;
private final static String DEFAULT_APPLICATION_NAME = "Vitro";
private final static String DEFAULT_APPLICATION_AVAILABLE_LANGS_FILE = "available-langs";
private final static String DEFAULT_ROOT_LOGOTYPE_IMAGE = "";
private final static int DEFAULT_ROOT_LOGOTYPE_WIDTH = 0;
private final static int DEFAULT_ROOT_LOGOTYPE_HEIGHT = 0;
@ -34,7 +33,6 @@ public class ApplicationBean {
private boolean initialized = false;
private String sessionIdStr = null;
private String applicationName = DEFAULT_APPLICATION_NAME;
private String availableLangsFile = DEFAULT_APPLICATION_AVAILABLE_LANGS_FILE;
private String rootLogotypeImage = DEFAULT_ROOT_LOGOTYPE_IMAGE;
private int rootLogotypeWidth = DEFAULT_ROOT_LOGOTYPE_WIDTH;
@ -54,7 +52,6 @@ public class ApplicationBean {
output += " initialized from DB: [" + initialized + "]\n";
output += " session id: [" + sessionIdStr + "]\n";
output += " application name: [" + applicationName + "]\n";
output += " available langs file: [" + availableLangsFile + "]\n";
output += " root logotype image: [" + rootLogotypeImage + "]\n";
output += " root logotype width: [" + rootLogotypeWidth + "]\n";
output += " root logotype height: [" + rootLogotypeHeight + "]\n";
@ -180,10 +177,6 @@ public class ApplicationBean {
return "";
}
public String getAvailableLangsFile() {
return availableLangsFile;
}
/**
* Directory to find the images. Subdirectories include css, jsp and site_icons.
* Example: "themes/enhanced/"

View file

@ -109,7 +109,7 @@ public abstract class ConfigurationProperties {
throw new NullPointerException("bean may not be null.");
}
context.setAttribute(ATTRIBUTE_NAME, bean);
log.debug(bean);
log.info(bean);
}
/** Package access, so unit tests can call it. */

View file

@ -118,6 +118,7 @@ public class ConfigurationPropertiesSetup implements ServletContextListener {
}
}
private File locateRuntimePropertiesFile(File vitroHomeDir,
File vitroHomeDirConfig, StartupStatus ss) {

View file

@ -17,8 +17,6 @@ import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import edu.cornell.mannlib.vitro.webapp.i18n.I18n;
import edu.cornell.mannlib.vitro.webapp.i18n.I18nBundle;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -77,8 +75,8 @@ public class SparqlQueryController extends FreemarkerHttpServlet {
private static final String[] SAMPLE_QUERY = { //
"", //
"#", //
"i18n:sparql_query_description_0", //
"i18n:sparql_query_description_1", //
"# This example query gets 20 geographic locations", //
"# and (if available) their labels", //
"#", //
"SELECT ?geoLocation ?label", //
"WHERE", //
@ -195,11 +193,9 @@ public class SparqlQueryController extends FreemarkerHttpServlet {
@Override
protected ResponseValues processRequest(VitroRequest vreq) throws Exception {
I18nBundle i18n = I18n.bundle(vreq);
Map<String, Object> bodyMap = new HashMap<>();
bodyMap.put("sampleQuery", buildSampleQuery(i18n, buildPrefixList(vreq)));
bodyMap.put("title", i18n.text("sparql_query_title"));
bodyMap.put("sampleQuery", buildSampleQuery(buildPrefixList(vreq)));
bodyMap.put("title", "SPARQL Query");
bodyMap.put("submitUrl", UrlBuilder.getUrl("admin/sparqlquery"));
return new TemplateResponseValues(TEMPLATE_NAME, bodyMap);
}
@ -226,7 +222,7 @@ public class SparqlQueryController extends FreemarkerHttpServlet {
return prefixList;
}
private String buildSampleQuery(I18nBundle i18n, List<Prefix> prefixList) {
private String buildSampleQuery(List<Prefix> prefixList) {
StringWriter sw = new StringWriter();
PrintWriter writer = new PrintWriter(sw);
@ -234,10 +230,6 @@ public class SparqlQueryController extends FreemarkerHttpServlet {
writer.println(p);
}
for (String line : SAMPLE_QUERY) {
if (line.startsWith("i18n:")) {
// Get i18n translation
line = i18n.text(line.substring("i18n:".length()));
}
writer.println(line);
}

View file

@ -108,9 +108,7 @@ public class LoginRedirector {
throws IOException {
try {
DisplayMessage.setMessage(request, assembleWelcomeMessage());
String redirectUrl = getRedirectionUriForLoggedInUser();
log.debug("Sending redirect to path: " + redirectUrl);
response.sendRedirect(redirectUrl);
response.sendRedirect(getRedirectionUriForLoggedInUser());
} catch (IOException e) {
log.debug("Problem with re-direction", e);
response.sendRedirect(getApplicationHomePageUrl());
@ -177,13 +175,21 @@ public class LoginRedirector {
}
}
/**
* The application home page can be overridden by an attribute in the
* ServletContext. Further, it can either be an absolute URL, or it can be
* relative to the application. Weird.
*/
private String getApplicationHomePageUrl() {
String contextPath = request.getContextPath();
if (contextPath.equals("")) {
return "/";
String contextRedirect = (String) session.getServletContext()
.getAttribute("postLoginRequest");
if (contextRedirect != null) {
if (contextRedirect.indexOf(":") == -1) {
return request.getContextPath() + contextRedirect;
} else {
return contextRedirect;
}
else {
return contextPath;
}
return request.getContextPath();
}
}

View file

@ -43,7 +43,7 @@ public class Classes2ClassesRetryController extends BaseEditController {
action = epo.getAction();
}
VClassDao vcDao = ModelAccess.on(request).getWebappDaoFactory().getVClassDao();
VClassDao vcDao = ModelAccess.on(getServletContext()).getWebappDaoFactory().getVClassDao();
epo.setDataAccessObject(vcDao);
Classes2Classes objectForEditing = new Classes2Classes();

View file

@ -51,7 +51,8 @@ public class ClassgroupRetryController extends BaseEditController {
action = epo.getAction();
}
VClassGroupDao cgDao = ModelAccess.on(request).getWebappDaoFactory().getVClassGroupDao();
VClassGroupDao cgDao = ModelAccess.on(
getServletContext()).getWebappDaoFactory().getVClassGroupDao();
epo.setDataAccessObject(cgDao);

View file

@ -50,12 +50,11 @@ public class DatapropRetryController extends BaseEditController {
//create an EditProcessObject for this and put it in the session
EditProcessObject epo = super.createEpo(request);
epo.setImplementationClass(DataProperty.class);
epo.setBeanClass(DataProperty.class);
VitroRequest vreq = new VitroRequest(request);
WebappDaoFactory wadf = ModelAccess.on(vreq).getWebappDaoFactory();
WebappDaoFactory wadf = ModelAccess.on(getServletContext()).getWebappDaoFactory();
DatatypeDao dDao = wadf.getDatatypeDao();
DataPropertyDao dpDao = wadf.getDataPropertyDao();

View file

@ -106,7 +106,7 @@ public class FauxPropertyRetryController extends BaseEditController {
this.epo = epo;
this.fpDao = ModelAccess.on(req).getWebappDaoFactory()
this.fpDao = ModelAccess.on(ctx).getWebappDaoFactory()
.getFauxPropertyDao();
}
@ -114,8 +114,6 @@ public class FauxPropertyRetryController extends BaseEditController {
void populate() {
epo.setDataAccessObject(fpDao);
epo.setAction(determineAction());
epo.setImplementationClass(FauxProperty.class);
epo.setBeanClass(FauxProperty.class);
if (epo.getUseRecycledBean()) {
beanForEditing = (FauxProperty) epo.getNewBean();

View file

@ -71,7 +71,7 @@ public class NamespacePrefixOperationController extends BaseEditController {
if (request.getParameter("_cancel") == null) {
OntModel ontModel = ModelAccess.on(req).getOntModel();
OntModel ontModel = ModelAccess.on(getServletContext()).getOntModel();
String namespaceStr = request.getParameter("namespace");
String prefixStr = request.getParameter("prefix");

View file

@ -51,7 +51,7 @@ public class PropertyGroupRetryController extends BaseEditController {
}
PropertyGroupDao pgDao = ModelAccess.on(
req).getWebappDaoFactory().getPropertyGroupDao();
getServletContext()).getWebappDaoFactory().getPropertyGroupDao();
epo.setDataAccessObject(pgDao);

View file

@ -53,7 +53,6 @@ public class PropertyRetryController extends BaseEditController {
/*for testing*/
ObjectProperty testMask = new ObjectProperty();
epo.setImplementationClass(ObjectProperty.class);
epo.setBeanClass(ObjectProperty.class);
epo.setBeanMask(testMask);
@ -65,7 +64,7 @@ public class PropertyRetryController extends BaseEditController {
action = epo.getAction();
}
ObjectPropertyDao propDao = ModelAccess.on(req).getWebappDaoFactory().getObjectPropertyDao();
ObjectPropertyDao propDao = ModelAccess.on(getServletContext()).getWebappDaoFactory().getObjectPropertyDao();
epo.setDataAccessObject(propDao);
OntologyDao ontDao = request.getUnfilteredWebappDaoFactory().getOntologyDao();

View file

@ -48,7 +48,7 @@ public class RestrictionOperationController extends BaseEditController {
String defaultLandingPage = getDefaultLandingPage(request);
try {
OntModel ontModel = ModelAccess.on(req)
OntModel ontModel = ModelAccess.on(getServletContext())
.getOntModel(TBOX_ASSERTIONS);
HashMap epoHash = null;

View file

@ -48,7 +48,7 @@ public class VclassEditController extends BaseEditController {
EditProcessObject epo = super.createEpo(request, FORCE_NEW);
request.setAttribute("epoKey", epo.getKey());
VClassDao vcwDao = ModelAccess.on(req).getWebappDaoFactory(ASSERTIONS_ONLY).getVClassDao();
VClassDao vcwDao = ModelAccess.on(getServletContext()).getWebappDaoFactory(ASSERTIONS_ONLY).getVClassDao();
VClass vcl = (VClass)vcwDao.getVClassByURI(request.getParameter("uri"));
if (vcl == null) {
@ -152,8 +152,8 @@ public class VclassEditController extends BaseEditController {
request.setAttribute("formSelect",formSelect);
// if supported, we want to show only the asserted superclasses and subclasses.
VClassDao vcDao = ModelAccess.on(req).getWebappDaoFactory(ASSERTIONS_ONLY).getVClassDao();
VClassDao displayVcDao = ModelAccess.on(req).getWebappDaoFactory().getVClassDao();
VClassDao vcDao = ModelAccess.on(getServletContext()).getWebappDaoFactory(ASSERTIONS_ONLY).getVClassDao();
VClassDao displayVcDao = ModelAccess.on(getServletContext()).getWebappDaoFactory().getVClassDao();
List<VClass> superVClasses = getVClassesForURIList(
vcDao.getSuperClassURIs(vcl.getURI(),false), displayVcDao);

View file

@ -66,10 +66,11 @@ public class VclassRetryController extends BaseEditController {
action = epo.getAction();
}
WebappDaoFactory wadf = ModelAccess.on(req).getWebappDaoFactory();
WebappDaoFactory wadf = ModelAccess.on(getServletContext()).getWebappDaoFactory();
VClassDao vcwDao = wadf.getVClassDao();
epo.setDataAccessObject(vcwDao);
VClassGroupDao cgDao = wadf.getVClassGroupDao();
OntologyDao oDao = wadf.getOntologyDao();
VClass vclassForEditing = null;

View file

@ -37,7 +37,7 @@ public class NamespacesListingController extends BaseEditController {
VitroRequest vrequest = new VitroRequest(request);
OntModel ontModel = ModelAccess.on(vrequest).getOntModel();
OntModel ontModel = ModelAccess.on(getServletContext()).getOntModel();
ArrayList results = new ArrayList();
request.setAttribute("results",results);

View file

@ -54,7 +54,7 @@ public class RestrictionsListingController extends BaseEditController {
epo = super.createEpo(request);
OntModel ontModel = ModelAccess.on(vrequest).getOntModel();
OntModel ontModel = ModelAccess.on(getServletContext()).getOntModel();
ObjectPropertyDao opDao = vrequest.getUnfilteredWebappDaoFactory().getObjectPropertyDao();
VClassDao vcDao = vrequest.getUnfilteredWebappDaoFactory().getVClassDao();

View file

@ -3,8 +3,6 @@
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -44,8 +42,6 @@ public class BrowseController extends FreemarkerHttpServlet {
List<VClassGroup> groups = null;
VClassGroupsForRequest vcgc = VClassGroupCache.getVClassGroups(vreq);
groups =vcgc.getGroups();
Collections.sort(groups, publicNameComparator);
// sortGroupListByPublicName(groups);
List<VClassGroupTemplateModel> vcgroups = new ArrayList<VClassGroupTemplateModel>(groups.size());
for (VClassGroup group : groups) {
vcgroups.add(new VClassGroupTemplateModel(group));
@ -54,35 +50,4 @@ public class BrowseController extends FreemarkerHttpServlet {
return new TemplateResponseValues(templateName, body);
}
public Comparator<VClassGroup> publicNameComparator = new Comparator<VClassGroup>() {
public int compare(VClassGroup s1, VClassGroup s2) {
String groupName1 = s1.getPublicName().toUpperCase();
String groupName2 = s2.getPublicName().toUpperCase();
//ascending order
return groupName1.compareTo(groupName2);
//descending order
//return groupName2.compareTo(groupName1);
}};
//
// public void sortGroupListByPublicName(List<VClassGroup> groupList) {
// groupList.sort(new Comparator<VClassGroup>() {
// public int compare(VClassGroup first, VClassGroup second) {
// if (first != null) {
// if (second != null) {
// return (first.getDisplayRank() - second.getDisplayRank());
// } else {
// log.error("error--2nd VClassGroup is null in VClassGroupDao.getGroupList().compare()");
// }
// } else {
// log.error("error--1st VClassGroup is null in VClassGroupDao.getGroupList().compare()");
// }
// return 0;
// }
// });
// }
}

View file

@ -44,11 +44,12 @@ public class DeleteIndividualController extends FreemarkerHttpServlet{
private static final boolean BEGIN = true;
private static final boolean END = !BEGIN;
private static String TYPE_QUERY = ""
private static String TYPE_QUERY_START = ""
+ "PREFIX vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#>"
+ "SELECT ?type "
+ "WHERE"
+ "{ ?individualURI vitro:mostSpecificType ?type ."
+ "{ <";
private static String TYPE_QUERY_END = "> vitro:mostSpecificType ?type ."
+ "}";
private static String queryForDeleteQuery =
"PREFIX display: <" + DisplayVocabulary.DISPLAY_NS +"> \n" +
@ -73,7 +74,7 @@ public class DeleteIndividualController extends FreemarkerHttpServlet{
String delteQueryText = getDeleteQueryForType(type, displayModel);
byte[] toRemove = getIndividualsToDelete(individualUri, delteQueryText, vreq);
if (toRemove.length > 0) {
deleteIndividuals(toRemove, vreq);
deleteIndividuals(toRemove,vreq);
}
String redirectUrl = getRedirectUrl(vreq);
@ -90,14 +91,14 @@ public class DeleteIndividualController extends FreemarkerHttpServlet{
private TemplateResponseValues prepareErrorMessage(String errorMessage) {
HashMap<String, Object> map = new HashMap<String, Object>();
HashMap<String,Object> map = new HashMap<String,Object>();
map.put("errorMessage", errorMessage);
return new TemplateResponseValues("error-message.ftl", map);
}
private String handleErrors(VitroRequest vreq) {
String uri = vreq.getParameter("individualUri");
if (uri == null) {
if ( uri == null) {
return "Individual uri is null. No object to delete.";
}
if (uri.contains(">")) {
@ -106,26 +107,26 @@ public class DeleteIndividualController extends FreemarkerHttpServlet{
return "";
}
private static String getDeleteQueryForType(String typeURI, Model displayModel) {
private static String getDeleteQueryForType(String typeURI,Model displayModel) {
String deleteQueryText = DEFAULT_DELETE_QUERY_TEXT;
Query queryForTypeSpecificDeleteQuery = QueryFactory.create(queryForDeleteQuery);
QuerySolutionMap initialBindings = new QuerySolutionMap();
initialBindings.add("associatedURI", ResourceFactory.createResource(typeURI));
initialBindings.add("associatedURI", ResourceFactory.createResource( typeURI ));
displayModel.enterCriticalSection(Lock.READ);
try {
QueryExecution qexec = QueryExecutionFactory.create(queryForTypeSpecificDeleteQuery, displayModel, initialBindings);
try {
try{
QueryExecution qexec = QueryExecutionFactory.create(queryForTypeSpecificDeleteQuery,displayModel,initialBindings );
try{
ResultSet results = qexec.execSelect();
while (results.hasNext()) {
QuerySolution solution = results.nextSolution();
deleteQueryText = solution.get("deleteQueryText").toString();
}
} finally {
qexec.close();
}
} finally {
displayModel.leaveCriticalSection();
}
}finally{ qexec.close(); }
}finally{ displayModel.leaveCriticalSection(); }
if (!deleteQueryText.equals(DEFAULT_DELETE_QUERY_TEXT)) {
log.debug("For " + typeURI + " found delete query \n" + deleteQueryText);
@ -138,12 +139,7 @@ public class DeleteIndividualController extends FreemarkerHttpServlet{
private String getObjectMostSpecificType(String individualURI, VitroRequest vreq) {
String type = "";
try {
Query typeQuery = QueryFactory.create(TYPE_QUERY);
QuerySolutionMap bindings = new QuerySolutionMap();
bindings.add("individualURI", ResourceFactory.createResource(individualURI));
Model ontModel = vreq.getJenaOntModel();
QueryExecution qexec = QueryExecutionFactory.create(typeQuery, ontModel, bindings);
ResultSet results = qexec.execSelect();
ResultSet results = QueryUtils.getLanguageNeutralQueryResults(makeTypeQuery(individualURI), vreq);
while (results.hasNext()) {
QuerySolution solution = results.nextSolution();
type = solution.get("type").toString();
@ -156,16 +152,16 @@ public class DeleteIndividualController extends FreemarkerHttpServlet{
return type;
}
private byte[] getIndividualsToDelete(String targetIndividual, String deleteQuery, VitroRequest vreq) {
private byte[] getIndividualsToDelete(String targetIndividual, String deleteQuery,VitroRequest vreq) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
Query queryForTypeSpecificDeleteQuery = QueryFactory.create(deleteQuery);
QuerySolutionMap bindings = new QuerySolutionMap();
bindings.add("individualURI", ResourceFactory.createResource(targetIndividual));
QuerySolutionMap initialBindings = new QuerySolutionMap();
initialBindings.add("individualURI", ResourceFactory.createResource( targetIndividual ));
Model ontModel = vreq.getJenaOntModel();
QueryExecution qexec = QueryExecutionFactory.create(queryForTypeSpecificDeleteQuery, ontModel, bindings);
QueryExecution qexec = QueryExecutionFactory.create(queryForTypeSpecificDeleteQuery,ontModel,initialBindings );
Model results = qexec.execDescribe();
results.write(out, "N3");
results.write(out,"N3");
} catch (Exception e) {
log.error("Query raised an error \n" + deleteQuery);
@ -174,6 +170,10 @@ public class DeleteIndividualController extends FreemarkerHttpServlet{
return out.toByteArray();
}
private String makeTypeQuery(String objectURI) {
return TYPE_QUERY_START + objectURI + TYPE_QUERY_END;
}
private void deleteIndividuals(byte[] toRemove, VitroRequest vreq) {
String removingString = new String(toRemove, StandardCharsets.UTF_8);
RDFService rdfService = vreq.getRDFService();
@ -193,7 +193,8 @@ public class DeleteIndividualController extends FreemarkerHttpServlet{
cs.addPreChangeEvent(new BulkUpdateEvent(null, BEGIN));
cs.addPostChangeEvent(new BulkUpdateEvent(null, END));
return cs;
}
}

View file

@ -10,9 +10,6 @@ import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.ResourceFactory;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.AuthorizationRequest;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
@ -28,8 +25,6 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUti
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.N3EditUtils;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.web.URLEncoder;
/*
* Custom deletion controller to which deletion requests from default property form are sent. May be replaced
* later with additional features in process rdf form controller or alternative location.
@ -69,8 +64,8 @@ public class DeletePropertyController extends FreemarkerHttpServlet {
// TODO Auto-generated method stub
String subjectUri = EditConfigurationUtils.getSubjectUri(vreq);
String predicateUri = EditConfigurationUtils.getPredicateUri(vreq);
Property prop = ResourceFactory.createProperty(predicateUri);
String localName = prop.getLocalName();
int hashIndex = predicateUri.lastIndexOf("#");
String localName = predicateUri.substring(hashIndex + 1);
String redirectUrl = "/entity?uri=" + URLEncoder.encode(subjectUri);
return redirectUrl + "#" + URLEncoder.encode(localName);
}

View file

@ -8,7 +8,6 @@ import static javax.mail.Message.RecipientType.TO;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
@ -18,6 +17,7 @@ import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import edu.cornell.mannlib.vitro.webapp.dao.jena.MenuDaoJena;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -93,8 +93,6 @@ public class FreemarkerHttpServlet extends VitroHttpServlet {
throws IOException, ServletException {
super.doGet(request,response);
//UQAM-Optimization set for UTF-8
response.setCharacterEncoding("UTF-8");
VitroRequest vreq = new VitroRequest(request);
ResponseValues responseValues = null;
@ -105,8 +103,8 @@ public class FreemarkerHttpServlet extends VitroHttpServlet {
if (!isAuthorizedToDisplayPage(request, response, requiredActions(vreq))) {
return;
}
responseValues = processRequest(vreq);
responseValues = processRequest(vreq);
doResponse(vreq, response, responseValues);
} catch (Throwable e) {
@ -278,15 +276,8 @@ public class FreemarkerHttpServlet extends VitroHttpServlet {
// is specified in the main page template.
bodyString = "";
}
templateDataModel.put("body", bodyString);
String lang = vreq.getLocale().getLanguage();
if (!vreq.getLocale().getCountry().isEmpty()) {
lang += "-" + vreq.getLocale().getCountry();
}
templateDataModel.put("country", lang);
// Tell the template and any directives it uses that we're processing a page template.
templateDataModel.put("templateType", PAGE_TEMPLATE_TYPE);
@ -471,7 +462,7 @@ public class FreemarkerHttpServlet extends VitroHttpServlet {
protected MainMenu getDisplayModelMenu(VitroRequest vreq){
String url = vreq.getRequestURI().substring(vreq.getContextPath().length());
return vreq.getWebappDaoFactory().getMenuDao().getMainMenu(url);
return vreq.getWebappDaoFactory().getMenuDao().getMainMenu(vreq, url);
}
// NIHVIVO-3307: we need this here instead of FreemarkerConfiguration.java so that updates to

View file

@ -37,7 +37,7 @@ public class UrlBuilder {
LOGIN("/login"),
LOGOUT("/logout"),
OBJECT_PROPERTY_EDIT("/propertyEdit"),
EXTENDED_SEARCH("/extendedsearch"),
CUSTOMSEARCH("/customsearch"),
SEARCH("/search"),
SITE_ADMIN("/siteAdmin"),
TERMS_OF_USE("/termsOfUse"),

View file

@ -11,29 +11,28 @@ import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.LocaleUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdf.model.Literal;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerHttpServlet;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ExceptionResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
import edu.cornell.mannlib.vitro.webapp.dao.jena.QueryUtils;
import edu.cornell.mannlib.vitro.webapp.i18n.selection.SelectedLocale;
import edu.cornell.mannlib.vitro.webapp.rdfservice.filter.LanguageFilteringUtils;
/*Servlet to view all labels in various languages for individual*/
@ -48,13 +47,12 @@ public class ViewLabelsServlet extends FreemarkerHttpServlet{
String subjectUri = vreq.getParameter("subjectUri");
body.put("subjectUri", subjectUri);
try {
//the labels already added by the user
ArrayList<Literal> existingLabels = this.getExistingLabels(subjectUri, vreq);
//Get all language codes/labels used in the list of existing labels
List<HashMap<String, String>> locales = this.getLocales(vreq, existingLabels);
//Get all language codes/labels in the system, and this list is sorted by language name
List<HashMap<String, String>> locales = this.getLocales(vreq);
//Get code to label hashmap - we use this to get the language name for the language code returned in the rdf literal
HashMap<String, String> localeCodeToNameMap = this.getFullCodeToLanguageNameMap(locales);
//the labels already added by the user
ArrayList<Literal> existingLabels = this.getExistingLabels(subjectUri, vreq);
//existing labels keyed by language name and each of the list of labels is sorted by language name
HashMap<String, List<LabelInformation>> existingLabelsByLanguageName = this.getLabelsSortedByLanguageName(existingLabels, localeCodeToNameMap, vreq, subjectUri);
//Get available locales for the drop down for adding a new label, also sorted by language name
@ -139,26 +137,20 @@ public class ViewLabelsServlet extends FreemarkerHttpServlet{
doGet(request, response);
}
//get locales present in list of literals
public List<HashMap<String, String>> getLocales(VitroRequest vreq,
List<Literal> existingLiterals) {
Set<Locale> locales = new HashSet<Locale>();
for(Literal literal : existingLiterals) {
String language = literal.getLanguage();
if(!StringUtils.isEmpty(language)) {
locales.add(LanguageFilteringUtils.languageToLocale(language));
}
}
if (locales.isEmpty()) {
//get locales
public List<HashMap<String, String>> getLocales(VitroRequest vreq) {
List<Locale> selectables = SelectedLocale.getSelectableLocales(vreq);
if (selectables.isEmpty()) {
return Collections.emptyList();
}
List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
Locale currentLocale = SelectedLocale.getCurrentLocale(vreq);
for (Locale locale : locales) {
for (Locale locale : selectables) {
try {
list.add(buildLocaleMap(locale, currentLocale));
} catch (FileNotFoundException e) {
log.warn("Can't show locale '" + locale + "': " + e);
log.warn("Can't show the Locale selector for '" + locale
+ "': " + e);
}
}
@ -196,8 +188,8 @@ public class ViewLabelsServlet extends FreemarkerHttpServlet{
ArrayList<Literal> labels = new ArrayList<Literal>();
try {
// Show only labels with current language filtering
ResultSet results = QueryUtils.getQueryResults(queryStr, vreq);
//We want to get the labels for all the languages, not just the display language
ResultSet results = QueryUtils.getLanguageNeutralQueryResults(queryStr, vreq);
while (results.hasNext()) {
QuerySolution soln = results.nextSolution();
Literal nodeLiteral = soln.get("label").asLiteral();

View file

@ -6,13 +6,14 @@ import java.io.IOException;
import java.sql.SQLException;
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.apache.jena.rdf.model.RDFNode;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.IndividualTemplateModelBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
@ -35,7 +36,6 @@ import edu.cornell.mannlib.vitro.webapp.i18n.selection.SelectedLocale;
import edu.cornell.mannlib.vitro.webapp.utils.dataGetter.ExecuteDataRetrieval;
import edu.cornell.mannlib.vitro.webapp.web.beanswrappers.ReadOnlyBeansWrapper;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.IndividualTemplateModel;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.IndividualTemplateModelBuilder;
import edu.ucsf.vitro.opensocial.OpenSocialManager;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.TemplateModel;
@ -123,10 +123,8 @@ class IndividualResponseBuilder {
* into the data model: no real data can be modified.
*/
// body.put("individual", wrap(itm, BeansWrapper.EXPOSE_SAFE));
LabelAndLanguageCount labelAndLanguageCount = getLabelAndLanguageCount(
itm.getUri(), vreq);
body.put("labelCount", labelAndLanguageCount.getLabelCount());
body.put("languageCount", labelAndLanguageCount.getLanguageCount());
body.put("labelCount", getLabelCount(itm.getUri(), vreq));
body.put("languageCount", getLanguagesRepresentedCount(itm.getUri(), vreq));
//We also need to know the number of available locales
body.put("localesCount", SelectedLocale.getSelectableLocales(vreq).size());
body.put("profileType", getProfileType(itm.getUri(), vreq));
@ -284,103 +282,61 @@ class IndividualResponseBuilder {
return map;
}
private static String LABEL_QUERY = ""
private static String LABEL_COUNT_QUERY = ""
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n"
+ "SELECT ?label WHERE { \n"
+ "SELECT ( str(COUNT(?label)) AS ?labelCount ) WHERE { \n"
+ " ?subject rdfs:label ?label \n"
+ " FILTER isLiteral(?label) \n"
+ "}" ;
// Queries that were previously used for counts via RDFService that didn't
// filter results by language. With language filtering, aggregate
// functions like COUNT() cannot be used.
private static String DISTINCT_LANGUAGE_QUERY = ""
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n"
+ "SELECT ( str(COUNT(DISTINCT lang(?label))) AS ?languageCount ) WHERE { \n"
+ " ?subject rdfs:label ?label \n"
+ " FILTER isLiteral(?label) \n"
+ "}" ;
// private static String LABEL_COUNT_QUERY = ""
// + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n"
// + "SELECT ( str(COUNT(?label)) AS ?labelCount ) WHERE { \n"
// + " ?subject rdfs:label ?label \n"
// + " FILTER isLiteral(?label) \n"
// + "}" ;
// private static String DISTINCT_LANGUAGE_QUERY = ""
// + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n"
// + "SELECT ( str(COUNT(DISTINCT lang(?label))) AS ?languageCount ) WHERE { \n"
// + " ?subject rdfs:label ?label \n"
// + " FILTER isLiteral(?label) \n"
// + "}" ;
private static LabelAndLanguageCount getLabelAndLanguageCount(
String subjectUri, VitroRequest vreq) {
// 1.12.0 Now filtering to only the labels for the current locale so as
// to be consistent with other editing forms. Because the language
// filter can only act on a result set containing actual literals,
// we can't do the counting with a COUNT() in the query itself. So
// we will now use the LABEL_QUERY instead of LABEL_COUNT_QUERY and
// count the rows and the number of distinct languages represented.
Set<String> distinctLanguages = new HashSet<String>();
String queryStr = QueryUtils.subUriForQueryVar(LABEL_QUERY, "subject", subjectUri);
private static Integer getLabelCount(String subjectUri, VitroRequest vreq) {
String queryStr = QueryUtils.subUriForQueryVar(LABEL_COUNT_QUERY, "subject", subjectUri);
log.debug("queryStr = " + queryStr);
int labelCount = 0;
int theCount = 0;
try {
ResultSet results = QueryUtils.getQueryResults(queryStr, vreq);
while(results.hasNext()) {
QuerySolution qsoln = results.next();
labelCount++;
String lang = qsoln.getLiteral("label").getLanguage();
if(lang == null) {
lang = "";
//ResultSet results = QueryUtils.getQueryResults(queryStr, vreq);
//Get query results across all languages in order for template to show manage labels link correctly
ResultSet results = QueryUtils.getLanguageNeutralQueryResults(queryStr, vreq);
if (results.hasNext()) {
QuerySolution soln = results.nextSolution();
RDFNode labelCount = soln.get("labelCount");
if (labelCount != null && labelCount.isLiteral()) {
theCount = labelCount.asLiteral().getInt();
}
distinctLanguages.add(lang);
}
} catch (Exception e) {
log.error(e, e);
}
return new LabelAndLanguageCount(labelCount, distinctLanguages.size());
}
private static class LabelAndLanguageCount {
private Integer labelCount;
private Integer languageCount;
public LabelAndLanguageCount(Integer labelCount, Integer languageCount) {
this.labelCount = labelCount;
this.languageCount = languageCount;
}
public Integer getLabelCount() {
return this.labelCount;
}
public Integer getLanguageCount() {
return this.languageCount;
}
return theCount;
}
//what is the number of languages represented across the labels
// This version not compatible with language-filtering RDF services
// private static Integer getLanguagesRepresentedCount(String subjectUri, VitroRequest vreq) {
// String queryStr = QueryUtils.subUriForQueryVar(DISTINCT_LANGUAGE_QUERY, "subject", subjectUri);
// log.debug("queryStr = " + queryStr);
// int theCount = 0;
// try {
//
// ResultSet results = QueryUtils.getLanguageNeutralQueryResults(queryStr, vreq);
// if (results.hasNext()) {
// QuerySolution soln = results.nextSolution();
// RDFNode languageCount = soln.get("languageCount");
// if (languageCount != null && languageCount.isLiteral()) {
// theCount = languageCount.asLiteral().getInt();
// log.info("Language count is " + theCount);
// }
// }
// } catch (Exception e) {
// log.error(e, e);
// }
// log.info("Returning language count " + theCount);
// return theCount;
// }
private static Integer getLanguagesRepresentedCount(String subjectUri, VitroRequest vreq) {
String queryStr = QueryUtils.subUriForQueryVar(DISTINCT_LANGUAGE_QUERY, "subject", subjectUri);
log.debug("queryStr = " + queryStr);
int theCount = 0;
try {
ResultSet results = QueryUtils.getLanguageNeutralQueryResults(queryStr, vreq);
if (results.hasNext()) {
QuerySolution soln = results.nextSolution();
RDFNode languageCount = soln.get("languageCount");
if (languageCount != null && languageCount.isLiteral()) {
theCount = languageCount.asLiteral().getInt();
}
}
} catch (Exception e) {
log.error(e, e);
}
return theCount;
}
private static String PROFILE_TYPE_QUERY = ""
+ "PREFIX display: <http://vitro.mannlib.cornell.edu/ontologies/display/1.1#> \n"

View file

@ -4,7 +4,6 @@ package edu.cornell.mannlib.vitro.webapp.controller.json;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import com.fasterxml.jackson.databind.node.ArrayNode;
@ -16,7 +15,6 @@ import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao;
import edu.cornell.mannlib.vitro.webapp.i18n.selection.SelectedLocale;
import edu.cornell.mannlib.vitro.webapp.services.shortview.ShortViewService;
import edu.cornell.mannlib.vitro.webapp.services.shortview.ShortViewService.ShortViewContext;
import edu.cornell.mannlib.vitro.webapp.services.shortview.ShortViewServiceSetup;
@ -75,11 +73,7 @@ public class GetRandomSearchIndividualsByVClass extends GetSearchIndividualsByVC
modelMap.put("individual",
IndividualTemplateModelBuilder.build(individual, vreq));
modelMap.put("vclass", vclassName);
String langCtx = vreq.getLocale().getLanguage(); //UQAM-Linguistic-Management build the linguistic context
if (!vreq.getLocale().getCountry().isEmpty()) {
langCtx += "-" + vreq.getLocale().getCountry();
}
modelMap.put("langCtx", langCtx); // UQAM-Linguistic-Management add the linguistic context to map
ShortViewService svs = ShortViewServiceSetup.getService(ctx);
return svs.renderShortView(individual, ShortViewContext.BROWSE,
modelMap, vreq);

View file

@ -5,8 +5,6 @@ package edu.cornell.mannlib.vitro.webapp.dao;
import java.util.List;
import java.util.Set;
import edu.cornell.mannlib.vitro.webapp.i18n.I18nBundle;
public interface WebappDaoFactory {
/**
@ -134,6 +132,4 @@ public interface WebappDaoFactory {
public MenuDao getMenuDao();
public I18nBundle getI18nBundle();
}

View file

@ -5,17 +5,14 @@ package edu.cornell.mannlib.vitro.webapp.dao;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import edu.cornell.mannlib.vitro.webapp.dao.PropertyDao.FullPropertyKey;
import edu.cornell.mannlib.vitro.webapp.rdfservice.filter.LanguageFilteringUtils;
public class WebappDaoFactoryConfig {
private List<String> preferredLanguages;
private List<Locale> preferredLocales;
private String defaultNamespace;
private Set<String> nonUserNamespaces;
private boolean isUnderlyingStoreReasoned = false;
@ -23,7 +20,6 @@ public class WebappDaoFactoryConfig {
public WebappDaoFactoryConfig() {
preferredLanguages = Arrays.asList("en-US", "en", "EN");
preferredLocales = LanguageFilteringUtils.languagesToLocales(preferredLanguages);
defaultNamespace = "http://vitro.mannlib.cornell.edu/ns/default#";
nonUserNamespaces = new HashSet<String>();
nonUserNamespaces.add(VitroVocabulary.vitroURI);
@ -37,14 +33,6 @@ public class WebappDaoFactoryConfig {
this.preferredLanguages = pl;
}
public List<Locale> getPreferredLocales() {
return this.preferredLocales;
}
public void setPreferredLocales(List<Locale> pl) {
this.preferredLocales = pl;
}
public String getDefaultNamespace() {
return defaultNamespace;
}

View file

@ -17,7 +17,7 @@ import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.InsertException;
import edu.cornell.mannlib.vitro.webapp.dao.filtering.filters.VitroFilters;
public class DataPropertyDaoFiltering extends BaseFiltering implements DataPropertyDao{
class DataPropertyDaoFiltering extends BaseFiltering implements DataPropertyDao{
final DataPropertyDao innerDataPropertyDao;
final VitroFilters filters;

View file

@ -18,7 +18,7 @@ import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyStatementDao;
import edu.cornell.mannlib.vitro.webapp.dao.filtering.filters.VitroFilters;
public class DataPropertyStatementDaoFiltering extends BaseFiltering implements DataPropertyStatementDao{
class DataPropertyStatementDaoFiltering extends BaseFiltering implements DataPropertyStatementDao{
final DataPropertyStatementDao innerDataPropertyStatementDao;
final VitroFilters filters;

View file

@ -26,34 +26,47 @@ public class FauxPropertyDaoFiltering extends BaseFiltering implements FauxPrope
@Override
public List<FauxProperty> getFauxPropertiesForBaseUri(String uri) {
return innerFauxPropertyDao.getFauxPropertiesForBaseUri(uri);
// TODO Auto-generated method stub
throw new RuntimeException(
"FauxPropertyDao.getFauxPropertiesForBaseUri() not implemented.");
}
@Override
public FauxProperty getFauxPropertyFromContextUri(String contextUri) {
return innerFauxPropertyDao.getFauxPropertyFromContextUri(contextUri);
// TODO Auto-generated method stub
throw new RuntimeException(
"FauxPropertyDaoFiltering.getFauxPropertyFromConfigContextUri() not implemented.");
}
@Override
public FauxProperty getFauxPropertyByUris(String domainUri, String baseUri,
String rangeUri) {
return innerFauxPropertyDao.getFauxPropertyByUris(domainUri, baseUri,
rangeUri);
// TODO Auto-generated method stub
throw new RuntimeException(
"FauxPropertyDaoFiltering.getFauxPropertyByUris() not implemented.");
}
@Override
public void updateFauxProperty(FauxProperty fp) {
innerFauxPropertyDao.updateFauxProperty(fp);
// TODO Auto-generated method stub
throw new RuntimeException("FauxPropertyDaoFiltering.updateFauxProperty() not implemented.");
}
@Override
public void deleteFauxProperty(FauxProperty fp) {
innerFauxPropertyDao.deleteFauxProperty(fp);
// TODO Auto-generated method stub
throw new RuntimeException("FauxPropertyDao.deleteFauxProperty() not implemented.");
}
@Override
public void insertFauxProperty(FauxProperty fp) {
innerFauxPropertyDao.insertFauxProperty(fp);
// TODO Auto-generated method stub
throw new RuntimeException("FauxPropertyDao.insertFauxProperty() not implemented.");
}
}

View file

@ -20,7 +20,7 @@ import edu.cornell.mannlib.vitro.webapp.dao.filtering.filters.VitroFilters;
import edu.cornell.mannlib.vitro.webapp.edit.EditLiteral;
public class IndividualDaoFiltering extends BaseFiltering implements IndividualDao{
class IndividualDaoFiltering extends BaseFiltering implements IndividualDao{
IndividualDao innerIndividualDao;
VitroFilters filters;

View file

@ -17,7 +17,7 @@ import edu.cornell.mannlib.vitro.webapp.dao.InsertException;
import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.filtering.filters.VitroFilters;
public class ObjectPropertyDaoFiltering extends BaseFiltering implements ObjectPropertyDao{
class ObjectPropertyDaoFiltering extends BaseFiltering implements ObjectPropertyDao{
final ObjectPropertyDao innerObjectPropertyDao;
final VitroFilters filters;

View file

@ -16,7 +16,7 @@ import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatementImpl;
import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyStatementDao;
import edu.cornell.mannlib.vitro.webapp.dao.filtering.filters.VitroFilters;
public class ObjectPropertyStatementDaoFiltering extends BaseFiltering implements ObjectPropertyStatementDao{
class ObjectPropertyStatementDaoFiltering extends BaseFiltering implements ObjectPropertyStatementDao{
final ObjectPropertyStatementDao innerObjectPropertyStatementDao;
final VitroFilters filters;

View file

@ -24,7 +24,6 @@ import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassGroupDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.filtering.filters.VitroFilters;
import edu.cornell.mannlib.vitro.webapp.i18n.I18nBundle;
/**
* This wraps a WebappDaoFactory and applies filtering.
@ -68,7 +67,7 @@ public class WebappDaoFactoryFiltering implements WebappDaoFactory {
transient private PropertyGroupDao filteringPropertyGroupDao=null;
transient private PropertyInstanceDao filteringPropertyInstanceDao=null;
public WebappDaoFactoryFiltering(WebappDaoFactory innerDao, VitroFilters filters){
public WebappDaoFactoryFiltering( WebappDaoFactory innerDao, VitroFilters filters){
if( innerDao == null )
throw new Error("innerWebappDaoFactory must be non-null");
this.filters = filters;
@ -277,9 +276,4 @@ public class WebappDaoFactoryFiltering implements WebappDaoFactory {
public void close() {
innerWebappDaoFactory.close();
}
@Override
public I18nBundle getI18nBundle() {
return innerWebappDaoFactory.getI18nBundle();
}
}

View file

@ -83,21 +83,22 @@ public class ApplicationDaoJena extends JenaBaseDao implements ApplicationDao {
}
ontModel.enterCriticalSection(Lock.WRITE);
try {
updateRDFSLabel(appInd, application.getApplicationName());
updatePlainLiteralValue(
appInd, APPLICATION_ABOUTTEXT, application.getAboutText());
updatePlainLiteralValue(
appInd.setLabel(application.getApplicationName(), null);
updatePropertyStringValue(
appInd, APPLICATION_ABOUTTEXT, application.getAboutText(),
ontModel);
updatePropertyStringValue(
appInd, APPLICATION_ACKNOWLEGETEXT,
application.getAcknowledgeText());
application.getAcknowledgeText(), ontModel);
updatePropertyStringValue(
appInd, APPLICATION_CONTACTMAIL,
application.getContactMail(), ontModel);
updatePropertyStringValue(
appInd, APPLICATION_CORRECTIONMAIL,
application.getCorrectionMail(), ontModel);
updatePlainLiteralValue(
updatePropertyStringValue(
appInd, APPLICATION_COPYRIGHTANCHOR,
application.getCopyrightAnchor());
application.getCopyrightAnchor(), ontModel);
updatePropertyStringValue(
appInd, APPLICATION_COPYRIGHTURL,
application.getCopyrightURL(), ontModel);

View file

@ -516,9 +516,9 @@ public class DataPropertyDaoJena extends PropertyDaoJena implements
if (dtp.getFunctional()) {
ontModel.add(jDataprop,RDF.type,OWL.FunctionalProperty);
}
updatePlainLiteralValue(jDataprop, EXAMPLE, dtp.getExample());
updatePlainLiteralValue(jDataprop, DESCRIPTION_ANNOT, dtp.getDescription());
updatePlainLiteralValue(jDataprop, PUBLIC_DESCRIPTION_ANNOT, dtp.getPublicDescription());
addPropertyStringValue(jDataprop, EXAMPLE, dtp.getExample(), ontModel);
addPropertyStringValue(jDataprop, DESCRIPTION_ANNOT, dtp.getDescription(), ontModel);
addPropertyStringValue(jDataprop, PUBLIC_DESCRIPTION_ANNOT, dtp.getPublicDescription(), ontModel);
addPropertyStringValue(jDataprop, EDITING, dtp.getEditing(), ontModel);
addPropertyNonNegativeIntValue(jDataprop, DISPLAY_RANK_ANNOT, dtp.getDisplayTier(), ontModel);
addPropertyNonNegativeIntValue(jDataprop, DISPLAY_LIMIT, dtp.getDisplayLimit(), ontModel);
@ -587,9 +587,9 @@ public class DataPropertyDaoJena extends PropertyDaoJena implements
}
}
updatePlainLiteralValue(jDataprop, EXAMPLE, dtp.getExample());
updatePlainLiteralValue(jDataprop, DESCRIPTION_ANNOT, dtp.getDescription());
updatePlainLiteralValue(jDataprop, PUBLIC_DESCRIPTION_ANNOT, dtp.getPublicDescription());
updatePropertyStringValue(jDataprop, EXAMPLE, dtp.getExample(), ontModel);
updatePropertyStringValue(jDataprop, DESCRIPTION_ANNOT, dtp.getDescription(), ontModel);
updatePropertyStringValue(jDataprop, PUBLIC_DESCRIPTION_ANNOT, dtp.getPublicDescription(), ontModel);
updatePropertyStringValue(jDataprop, EDITING, dtp.getEditing(), ontModel);
updatePropertyNonNegativeIntValue(jDataprop, DISPLAY_RANK_ANNOT, dtp.getDisplayTier(), ontModel);
updatePropertyNonNegativeIntValue(jDataprop, DISPLAY_LIMIT, dtp.getDisplayLimit(), ontModel);

View file

@ -230,9 +230,10 @@ public class FauxPropertyDaoJena extends JenaBaseDao implements FauxPropertyDao
OBJECT_PROPERTY_DISPLAY_CONFIG);
addPropertyResourceURINotEmpty(config, PROPERTY_GROUP,
fp.getGroupURI());
updatePlainLiteralValue(config, DISPLAY_NAME, fp.getDisplayName());
updatePlainLiteralValue(config, PUBLIC_DESCRIPTION_ANNOT,
fp.getPublicDescription());
addPropertyStringValue(config, DISPLAY_NAME, fp.getDisplayName(),
displayModel);
addPropertyStringValue(config, PUBLIC_DESCRIPTION_ANNOT,
fp.getPublicDescription(), displayModel);
addPropertyIntValue(config, DISPLAY_RANK_ANNOT,
fp.getDisplayTier(), displayModel);
addPropertyIntValue(config, DISPLAY_LIMIT, fp.getDisplayLimit(),
@ -327,10 +328,10 @@ public class FauxPropertyDaoJena extends JenaBaseDao implements FauxPropertyDao
.getConfigUri());
updatePropertyResourceURIValue(config, PROPERTY_GROUP,
fp.getGroupURI());
updatePlainLiteralValue(config, DISPLAY_NAME,
fp.getDisplayName());
updatePlainLiteralValue(config, PUBLIC_DESCRIPTION_ANNOT,
fp.getPublicDescription());
updatePropertyStringValue(config, DISPLAY_NAME,
fp.getDisplayName(), displayModel);
updatePropertyStringValue(config, PUBLIC_DESCRIPTION_ANNOT,
fp.getPublicDescription(), displayModel);
updatePropertyIntValue(config, DISPLAY_RANK_ANNOT,
fp.getDisplayTier(), displayModel);
updatePropertyIntValue(config, DISPLAY_LIMIT, fp.getDisplayLimit(),

View file

@ -5,8 +5,8 @@ package edu.cornell.mannlib.vitro.webapp.dao.jena;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
@ -14,14 +14,14 @@ import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.iri.IRI;
import org.apache.jena.iri.IRIFactory;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.graph.Node;
import org.apache.jena.graph.NodeFactory;
import org.apache.jena.iri.IRI;
import org.apache.jena.iri.IRIFactory;
import org.apache.jena.ontology.DatatypeProperty;
import org.apache.jena.ontology.ObjectProperty;
import org.apache.jena.ontology.OntClass;
@ -39,7 +39,6 @@ import org.apache.jena.rdf.model.NodeIterator;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.rdf.model.StmtIterator;
import org.apache.jena.shared.Lock;
@ -755,110 +754,21 @@ public class JenaBaseDao extends JenaBaseDaoCon {
}
/**
* Add to an OntResource an rdfs:label value with lexical form and default
* language tag. Remove any other existing values in default language.
* If lexicalForm parameter is null, remove all plain literal values of
* Property in default language.
* @param ontRes may not be null
* @param lexicalForm may be null. If null, existing values will be deleted
* but none will be added.
* convenience method for updating the RDFS label
*/
protected void updateRDFSLabel(OntResource ontRes, String lexicalForm) {
updatePlainLiteralValue(ontRes, RDFS.label, lexicalForm);
}
protected void updateRDFSLabel(OntResource ontRes, String label) {
/**
* Add to an OntResource an rdfs:label value with lexical form and optional
* language tag. Remove any other existing plain literal values that match
* specified language or lack language tags if no language is supplied.
* If lexicalForm parameter is null, remove all plain literal labels in
* specified language, or all existing language-less labels
* if no language is specified.
* @param ontRes may not be null
* @param lexicalForm may be null. If null, existing values will be deleted
* but none will be added.
* @param lang may be null. If null, method acts on language-less plain
* literal labels and ignores those with language tags.
*/
protected void updateRDFSLabel(OntResource ontRes, String lexicalForm, String lang) {
updatePlainLiteralValue(ontRes, RDFS.label, lexicalForm, lang);
}
if (label != null && label.length() > 0) {
/**
* Add to an OntResource a Property value with lexical form and default
* language tag. Remove any other existing values in default language.
* If lexicalForm parameter is null, remove all plain literal values of
* Property in default language.
* @param ontRes may not be null
* @param lexicalForm may be null. If null, existing values will be deleted
* but none will be added.
*/
protected void updatePlainLiteralValue(OntResource ontRes, Property property,
String lexicalForm) {
updatePlainLiteralValue(ontRes, property, lexicalForm, getDefaultLanguage());
}
String existingValue = ontRes.getLabel(getDefaultLanguage());
/**
* Add to an OntResource a Property value with lexical form and optional
* language tag. Remove any other existing plain literal values that match
* specified language or lack language tags if no language is supplied.
* If lexicalForm parameter is null, remove all plain literal values of
* Property in specified language, or all existing language-less literals
* if no language is specified.
* @param ontRes may not be null
* @param lexicalForm may be null. If null, existing values will be deleted
* but none will be added.
* @param lang may be null. If null, method acts on language-less
* plain literal values and ignores those with language tags.
*/
protected void updatePlainLiteralValue(OntResource ontRes, Property property,
String lexicalForm, String lang) {
if(ontRes == null) {
throw new IllegalArgumentException("ontRes may not be null.");
if (existingValue == null || !existingValue.equals(label)) {
ontRes.setLabel(label, getDefaultLanguage());
}
boolean addNew = true;
List<Statement> toRemove = new ArrayList<Statement>();
StmtIterator existingStmts = ontRes.listProperties(property);
while(existingStmts.hasNext()) {
Statement stmt = existingStmts.next();
if(stmt.getObject().isLiteral()) {
Literal lit = stmt.getObject().asLiteral();
if( (lang == null && isLanguageLessPlainLiteral(lit))
|| (lang != null && lang.equals(lit.getLanguage())) ) {
if(!lit.getLexicalForm().equals(lexicalForm)) {
toRemove.add(stmt);
} else {
// New literal already exists in the model.
// Do not add it again.
addNew = false;
ontRes.removeAll(RDFS.label);
}
}
}
}
if(!toRemove.isEmpty()) {
ontRes.getModel().remove(toRemove);
}
if (addNew && (lexicalForm != null)) {
if(!StringUtils.isEmpty(lang)) {
ontRes.addProperty(property, ResourceFactory.createLangLiteral(
lexicalForm, lang));
} else {
ontRes.addProperty(property, ResourceFactory.createPlainLiteral(
lexicalForm));
}
}
}
private boolean isLanguageLessPlainLiteral(Literal lit) {
// In RDF 1.1 all the language-less literals get datatype xsd:string.
// The null datatype check is here just in case this gets run on an older
// version of Jena. rdf:PlainLiteral is also a datatype, but doesn't
// (yet) seem to be used by Jena.
return StringUtils.isEmpty(lit.getLanguage())
&& ((lit.getDatatype() == null)
|| XSDDatatype.XSDstring.equals(lit.getDatatype()) ||
(RDF.getURI() + "PlainLiteral").equals(lit.getDatatypeURI()));
}
private Literal getLabel(String lang, List<RDFNode>labelList) {
for (RDFNode label : labelList) {
@ -870,13 +780,6 @@ public class JenaBaseDao extends JenaBaseDaoCon {
}
if ((lang != null) && (lang.equals(labelLanguage))) {
return labelLit;
} else
/*
* UQAM-Linguistic-Management
* Check for country-part of lang (ex: 'en' for default consideration of labelLanguage in english but not encoded by 'en-US' most case of labels in vivo.owl)
*/
if ((lang != null) && (Arrays.asList(lang.split("-")).get(0).equals(labelLanguage))) {
return labelLit;
}
}
}

View file

@ -72,7 +72,6 @@ public class MenuDaoJena extends JenaBaseDao implements MenuDao {
return getMenu( getOntModelSelector().getDisplayModel(), url );
}
@Override
public MainMenu getMainMenu( ServletRequest req, String url ) {
OntModel displayModel = LanguageFilteringUtils.wrapOntModelInALanguageFilter(getOntModelSelector().getDisplayModel(), req );
return getMenu(displayModel, url) ;

View file

@ -714,14 +714,14 @@ public class ObjectPropertyDaoJena extends PropertyDaoJena implements ObjectProp
}
}
updatePlainLiteralValue(p, EXAMPLE_ANNOT, prop.getExample());
updatePlainLiteralValue(p, DESCRIPTION_ANNOT, prop.getDescription());
updatePlainLiteralValue(p, PUBLIC_DESCRIPTION_ANNOT, prop.getPublicDescription());
updatePropertyStringValue(p,EXAMPLE_ANNOT,prop.getExample(),getOntModel());
updatePropertyStringValue(p,DESCRIPTION_ANNOT,prop.getDescription(),getOntModel());
updatePropertyStringValue(p,PUBLIC_DESCRIPTION_ANNOT,prop.getPublicDescription(),getOntModel());
updatePropertyNonNegativeIntegerValue(p,DISPLAY_LIMIT,prop.getDomainDisplayLimitInteger(),getOntModel());
updatePropertyStringValue(p,PROPERTY_ENTITYSORTDIRECTION,prop.getDomainEntitySortDirection(),getOntModel());
if (inv != null) {
updatePlainLiteralValue(inv, EXAMPLE_ANNOT, prop.getExample());
updatePlainLiteralValue(inv, DESCRIPTION_ANNOT, prop.getDescription());
updatePropertyStringValue(inv,EXAMPLE_ANNOT,prop.getExample(),getOntModel());
updatePropertyStringValue(inv,DESCRIPTION_ANNOT,prop.getDescription(),getOntModel());
updatePropertyNonNegativeIntegerValue(inv,DISPLAY_LIMIT,prop.getRangeDisplayLimitInteger(),getOntModel());
updatePropertyStringValue(inv,PROPERTY_ENTITYSORTDIRECTION,prop.getRangeEntitySortDirection(),getOntModel());
}

View file

@ -289,15 +289,10 @@ public class RDFServiceGraph implements GraphWithPerform {
literalBuff.append("\"");
pyString(literalBuff, node.getLiteralLexicalForm());
literalBuff.append("\"");
/*
* UQAM-Bug-Correction
* reversing the condition tests.
* It is important to prioritize the language typology test in order to exploit the linguistic context in testing the type of data
*/
if (!StringUtils.isEmpty(node.getLiteralLanguage())) {
literalBuff.append("@").append(node.getLiteralLanguage());
} else if (node.getLiteralDatatypeURI() != null) {
if (node.getLiteralDatatypeURI() != null) {
literalBuff.append("^^<").append(node.getLiteralDatatypeURI()).append(">");
} else if (!StringUtils.isEmpty(node.getLiteralLanguage())) {
literalBuff.append("@").append(node.getLiteralLanguage());
}
return literalBuff.toString();
} else {

View file

@ -232,10 +232,10 @@ public class SparqlGraph implements GraphWithPerform {
literalBuff.append("\"");
pyString(literalBuff, node.getLiteralLexicalForm());
literalBuff.append("\"");
if (!StringUtils.isEmpty(node.getLiteralLanguage())) {
literalBuff.append("@").append(node.getLiteralLanguage());
} else if (node.getLiteralDatatypeURI() != null) {
if (node.getLiteralDatatypeURI() != null) {
literalBuff.append("^^<").append(node.getLiteralDatatypeURI()).append(">");
} else if (!StringUtils.isEmpty(node.getLiteralLanguage())) {
literalBuff.append("@").append(node.getLiteralLanguage());
}
return literalBuff.toString();
} else {

View file

@ -2,8 +2,6 @@
package edu.cornell.mannlib.vitro.webapp.dao.jena;
import static java.lang.String.format;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
@ -62,18 +60,15 @@ import edu.cornell.mannlib.vitro.webapp.dao.OntologyDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.jena.event.EditEvent;
import edu.cornell.mannlib.vitro.webapp.i18n.I18nBundle;
import edu.cornell.mannlib.vitro.webapp.web.URLEncoder;
public class VClassDaoJena extends JenaBaseDao implements VClassDao {
protected static final Log log = LogFactory.getLog(VClassDaoJena.class);
private final I18nBundle i18n;
private boolean isUnderlyingStoreReasoned = false;
public VClassDaoJena(WebappDaoFactoryJena wadf, boolean isUnderlyingStoreReasoned) {
super(wadf);
this.i18n = wadf.getI18nBundle();
this.isUnderlyingStoreReasoned = isUnderlyingStoreReasoned;
}
@ -96,19 +91,17 @@ public class VClassDaoJena extends JenaBaseDao implements VClassDao {
Restriction rest = cls.asRestriction();
OntProperty onProperty = rest.getOnProperty();
StringBuilder labelStr = new StringBuilder();
labelStr.append(format("%s ", i18n.text("restriction_on")))
.append(getLabelOrId(onProperty))
.append(": ");
labelStr.append("restriction on ").append(getLabelOrId(onProperty)).append(": ");
if (rest.isAllValuesFromRestriction() || rest.isSomeValuesFromRestriction()) {
Resource fillerRes = null;
if (rest.isAllValuesFromRestriction()) {
AllValuesFromRestriction avfRest = rest.asAllValuesFromRestriction();
fillerRes = avfRest.getAllValuesFrom();
labelStr.append(format("%s ", i18n.text("all_values_from")));
labelStr.append("all values from ");
} else {
SomeValuesFromRestriction svfRest = rest.asSomeValuesFromRestriction();
fillerRes = svfRest.getSomeValuesFrom();
labelStr.append(format("%s ", i18n.text("some_values_from")));
labelStr.append("some values from ");
}
if (fillerRes.canAs(OntClass.class)) {
OntClass avf = fillerRes.as(OntClass.class);
@ -122,7 +115,7 @@ public class VClassDaoJena extends JenaBaseDao implements VClassDao {
}
} else if (rest.isHasValueRestriction()) {
HasValueRestriction hvRest = rest.asHasValueRestriction();
labelStr.append(format("%s ", i18n.text("has_value")));
labelStr.append("has value ");
RDFNode fillerNode = hvRest.getHasValue();
try {
if (fillerNode.isResource()) {
@ -135,22 +128,22 @@ public class VClassDaoJena extends JenaBaseDao implements VClassDao {
}
} else if (rest.isMinCardinalityRestriction()) {
MinCardinalityRestriction mcRest = rest.asMinCardinalityRestriction();
labelStr.append(format("%s ", i18n.text("minimum_cardinality")));
labelStr.append("minimum cardinality ");
labelStr.append(mcRest.getMinCardinality());
} else if (rest.isMaxCardinalityRestriction()) {
MaxCardinalityRestriction mcRest = rest.asMaxCardinalityRestriction();
labelStr.append(format("%s ", i18n.text("maximum_cardinality")));
labelStr.append("maximum cardinality ");
labelStr.append(mcRest.getMaxCardinality());
} else if (rest.isCardinalityRestriction()) {
CardinalityRestriction cRest = rest.asCardinalityRestriction();
labelStr.append(format("%s ", i18n.text("cardinality")));
labelStr.append("cardinality ");
labelStr.append(cRest.getCardinality());
}
return labelStr.toString();
} else if (isBooleanClassExpression(cls)) {
StringBuilder labelStr = new StringBuilder("(");
if (cls.isComplementClass()) {
labelStr.append(format("%s ", i18n.text("not")));
labelStr.append("not ");
ComplementClass ccls = cls.as(ComplementClass.class);
labelStr.append(getLabelForClass(ccls.getOperand(), withPrefix, forPickList));
} else if (cls.isIntersectionClass()) {
@ -160,7 +153,7 @@ public class VClassDaoJena extends JenaBaseDao implements VClassDao {
OntClass operand = operandIt.next();
labelStr.append(getLabelForClass(operand, withPrefix, forPickList));
if (operandIt.hasNext()) {
labelStr.append(format(" %s ", i18n.text("and")));
labelStr.append(" and ");
}
}
} else if (cls.isUnionClass()) {
@ -170,7 +163,7 @@ public class VClassDaoJena extends JenaBaseDao implements VClassDao {
OntClass operand = operandIt.next();
labelStr.append(getLabelForClass(operand, withPrefix, forPickList));
if (operandIt.hasNext()) {
labelStr.append(format(" %s ", i18n.text("or")));
labelStr.append(" or ");
}
}
}
@ -959,9 +952,9 @@ public class VClassDaoJena extends JenaBaseDao implements VClassDao {
} catch (Exception e) {
log.error("error linking class "+cls.getURI()+" to class group");
}
updatePlainLiteralValue(ontCls, SHORTDEF, cls.getShortDef());
updatePlainLiteralValue(ontCls, EXAMPLE_ANNOT, cls.getExample());
updatePlainLiteralValue(ontCls, DESCRIPTION_ANNOT, cls.getDescription());
addPropertyStringValue(ontCls,SHORTDEF,cls.getShortDef(),ontModel);
addPropertyStringValue(ontCls,EXAMPLE_ANNOT,cls.getExample(),ontModel);
addPropertyStringValue(ontCls,DESCRIPTION_ANNOT,cls.getDescription(),ontModel);
addPropertyIntValue(ontCls,DISPLAY_LIMIT,cls.getDisplayLimit(),ontModel);
addPropertyIntValue(ontCls,DISPLAY_RANK_ANNOT,cls.getDisplayRank(),ontModel);
@ -1018,9 +1011,9 @@ public class VClassDaoJena extends JenaBaseDao implements VClassDao {
if (ontCls != null) {
updateRDFSLabel(ontCls, cls.getName());
updatePropertyResourceURIValue(ontCls,IN_CLASSGROUP,cls.getGroupURI(),ontModel);
updatePlainLiteralValue(ontCls, SHORTDEF, cls.getShortDef());
updatePlainLiteralValue(ontCls, EXAMPLE_ANNOT, cls.getExample());
updatePlainLiteralValue(ontCls, DESCRIPTION_ANNOT, cls.getDescription());
updatePropertyStringValue(ontCls,SHORTDEF,cls.getShortDef(),ontModel);
updatePropertyStringValue(ontCls,EXAMPLE_ANNOT,cls.getExample(),ontModel);
updatePropertyStringValue(ontCls,DESCRIPTION_ANNOT,cls.getDescription(),ontModel);
updatePropertyNonNegativeIntValue(ontCls,DISPLAY_LIMIT,cls.getDisplayLimit(),ontModel);
updatePropertyNonNegativeIntValue(ontCls,DISPLAY_RANK_ANNOT,cls.getDisplayRank(),ontModel);
updatePropertyFloatValue(ontCls, SEARCH_BOOST_ANNOT, cls.getSearchBoost(), ontModel);

View file

@ -276,7 +276,7 @@ public class VClassGroupDaoJena extends JenaBaseDao implements VClassGroupDao {
try {
Individual groupInd = ontModel.getIndividual(vcg.getURI());
try {
updateRDFSLabel(groupInd, vcg.getPublicName(), getDefaultLanguage());
groupInd.setLabel(vcg.getPublicName(), getDefaultLanguage());
} catch (Exception e) {
log.error("error updating name for "+groupInd.getURI());
}

View file

@ -50,8 +50,6 @@ import edu.cornell.mannlib.vitro.webapp.dao.VClassGroupDao;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactoryConfig;
import edu.cornell.mannlib.vitro.webapp.i18n.I18n;
import edu.cornell.mannlib.vitro.webapp.i18n.I18nBundle;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
import edu.cornell.mannlib.vitro.webapp.rdfservice.impl.jena.model.RDFServiceModel;
@ -613,10 +611,5 @@ public class WebappDaoFactoryJena implements WebappDaoFactory {
}
}
@Override
public I18nBundle getI18nBundle() {
// return context based bundle for preferred locales
return I18n.bundle(config.getPreferredLocales());
}
}

View file

@ -132,11 +132,6 @@ public class EditLiteral implements Literal {
throw new UnsupportedOperationException();
}
@Override
public boolean isStmtResource() {
throw new UnsupportedOperationException();
}
public Literal inModel(Model model) {
throw new UnsupportedOperationException();
}

View file

@ -4,6 +4,7 @@ package edu.cornell.mannlib.vitro.webapp.edit.listener.impl;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.logging.Log;

View file

@ -24,25 +24,15 @@ import edu.cornell.mannlib.vitro.webapp.beans.Datatype;
import edu.cornell.mannlib.vitro.webapp.dao.jena.DatatypeDaoJena;
import edu.cornell.mannlib.vitro.webapp.dao.jena.WebappDaoFactoryJena;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.i18n.I18nBundle;
public class BasicValidationVTwo {
public final static String REQUIRED_FIELD_EMPTY_MSG = "required_field_empty_msg";
public final static String DATA_NOT_PAST_MSG = "data_not_past_msg";
public final static String INVALID_DATE_FORM_MSG = "invalid_date_form_msg";
public final static String FILE_MUST_BE_ENTERED_MSG = "file_must_be_entered_msg";
public final static String INVALID_URL_MSG = "invalid_url_msg";
private I18nBundle i18n;
Map<String, List<String>> varsToValidations;
EditConfigurationVTwo editConfig;
public BasicValidationVTwo(EditConfigurationVTwo editConfig, I18nBundle i18n){
public BasicValidationVTwo(EditConfigurationVTwo editConfig, MultiValueEditSubmission editSub){
this.editConfig = editConfig;
this.i18n = i18n;
Map<String,List<String>> validatorsForFields = new HashMap<String,List<String>>();
for(String fieldName: editConfig.getFields().keySet()){
FieldVTwo field = editConfig.getField(fieldName);
@ -52,9 +42,8 @@ public class BasicValidationVTwo {
checkValidations();
}
public BasicValidationVTwo(Map<String, List<String>> varsToValidations, I18nBundle i18n){
public BasicValidationVTwo(Map<String, List<String>> varsToValidations){
this.varsToValidations = varsToValidations;
this.i18n = i18n;
checkValidations();
}
@ -105,7 +94,7 @@ public class BasicValidationVTwo {
//If no literals and this field was required, this is an error message
//and can return
if((literals == null || literals.size() == 0) && isRequiredField) {
errors.put(name, i18n.text(REQUIRED_FIELD_EMPTY_MSG));
errors.put(name, REQUIRED_FIELD_EMPTY_MSG);
break;
}
//Loop through literals if literals exist
@ -124,7 +113,7 @@ public class BasicValidationVTwo {
// incorrectly generate errors.
if (isEmpty(value)) {
if (isRequiredField) {
errors.put(name, i18n.text(REQUIRED_FIELD_EMPTY_MSG));
errors.put(name, REQUIRED_FIELD_EMPTY_MSG);
}
break;
}
@ -165,11 +154,11 @@ public class BasicValidationVTwo {
private String validate(String validationType, List<FileItem> fileItems) {
if( "nonempty".equalsIgnoreCase(validationType)){
if( fileItems == null || fileItems.size() == 0 ){
return i18n.text(FILE_MUST_BE_ENTERED_MSG);
return "a file must be entered for this field.";
}else{
FileItem fileItem = fileItems.get(0);
if( fileItem == null || fileItem.getName() == null || fileItem.getName().length() < 1 || fileItem.getSize() < 0){
return i18n.text(FILE_MUST_BE_ENTERED_MSG);
return "a file must be entered for this field.";
}
}
}
@ -185,14 +174,14 @@ public class BasicValidationVTwo {
// This case may be needed for validation of other field types.
if( "nonempty".equalsIgnoreCase(validationType)){
if( isEmpty(value) )
return i18n.text(REQUIRED_FIELD_EMPTY_MSG);
return REQUIRED_FIELD_EMPTY_MSG;
}
// Format validation
else if("isDate".equalsIgnoreCase(validationType)){
if( isDate( value))
return SUCCESS;
else
return i18n.text(INVALID_DATE_FORM_MSG);
return "must be in valid date format mm/dd/yyyy.";
}
else if( validationType.indexOf("datatype:") == 0 ) {
String datatypeURI = validationType.substring(9);
@ -205,7 +194,7 @@ public class BasicValidationVTwo {
} else if ("httpUrl".equalsIgnoreCase(validationType)){
//check if it has http or https, we could do more but for now this is all.
if(! value.startsWith("http://") && ! value.startsWith("https://") ){
return i18n.text(INVALID_URL_MSG);
return "This URL must start with http:// or https://";
}else{
return SUCCESS;
}
@ -227,7 +216,7 @@ public class BasicValidationVTwo {
dayParamStr = value.substring(monthDash + 1, value.length());
inputC.set(Integer.parseInt(yearParamStr), Integer.parseInt(monthParamStr) - 1, Integer.parseInt(dayParamStr));
if(inputC.before(c)) {
return i18n.text(DATA_NOT_PAST_MSG);
return this.DATE_NOT_PAST_MSG;
//Returning null makes the error message "field is empty" display instead
//return null;
} else {
@ -289,9 +278,14 @@ public class BasicValidationVTwo {
return (value == null || value.trim().length() == 0);
}
private static Pattern urlRX = Pattern.compile("(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)/{0,2}[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?");
/** we use null to indicate success */
public final static String SUCCESS = null;
public final static String REQUIRED_FIELD_EMPTY_MSG = "This field must not be empty.";
public final static String DATE_NOT_PAST_MSG = "Please enter a future target date for publication (past dates are invalid).";
//public final static String MIN_FIELDS_NOT_POPULATED = "Please enter values for at least ";
//public final static String FORM_ERROR_FIELD_ID = "formannotationerrors";
/** regex for strings like "12/31/2004" */

View file

@ -28,7 +28,6 @@ import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.freemarker.config.FreemarkerConfiguration;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess.LanguageOption;
import freemarker.template.Configuration;
public class EditConfigurationUtils {
@ -67,19 +66,17 @@ public class EditConfigurationUtils {
}
public static VClass getRangeVClass(VitroRequest vreq) {
// This needs a WebappDaoFactory with no filtering/RDFService
// funny business because it needs to be able to retrieve anonymous union
// classes by their "pseudo-bnode URIs".
// Someday we'll need to figure out a different way of doing this.
WebappDaoFactory ctxDaoFact = ModelAccess.on(
vreq.getSession().getServletContext()).getWebappDaoFactory();
return ctxDaoFact.getVClassDao().getVClassByURI(getRangeUri(vreq));
}
public static VClass getLangAwardRangeVClass(VitroRequest vreq) {
// UQAM-Linguistic-Management
WebappDaoFactory vreqDaoFact = ModelAccess.on(vreq).getWebappDaoFactory(
LanguageOption.LANGUAGE_AWARE);
return vreqDaoFact.getVClassDao().getVClassByURI(getRangeUri(vreq));
}
//get individual
public static Individual getSubjectIndividual(VitroRequest vreq) {
Individual subject = null;
String subjectUri = getSubjectUri(vreq);
@ -129,24 +126,12 @@ public class EditConfigurationUtils {
public static ObjectProperty getObjectPropertyForPredicate(VitroRequest vreq,
String predicateUri, String domainUri, String rangeUri) {
// WebappDaoFactory wdf = vreq.getWebappDaoFactory();
// UQAM-Linguistic-Management Use linguistic context
WebappDaoFactory wdf = ModelAccess.on(vreq).getWebappDaoFactory(LanguageOption.LANGUAGE_AWARE);
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
ObjectProperty objectProp = wdf.getObjectPropertyDao().getObjectPropertyByURIs(
predicateUri, domainUri, rangeUri);
return objectProp;
}
// UQAM Use linguistic context
public static ObjectProperty getObjectPropertyForPredicateLangAware(VitroRequest vreq,
String predicateUri, String domainUri, String rangeUri) {
// WebappDaoFactory wdf = vreq.getWebappDaoFactory();
// UQAM Use linguistic context
WebappDaoFactory wdf = ModelAccess.on(vreq).getWebappDaoFactory(LanguageOption.LANGUAGE_AWARE);
ObjectProperty objectProp = wdf.getObjectPropertyDao().getObjectPropertyByURIs(
predicateUri, domainUri, rangeUri);
return objectProp;
}
public static DataProperty getDataPropertyForPredicate(VitroRequest vreq, String predicateUri) {
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
//TODO: Check reason for employing unfiltered webapp dao factory and note if using a different version
@ -224,7 +209,6 @@ public class EditConfigurationUtils {
return (op != null && dp == null);
}
private static boolean isVitroLabel(String predicateUri) {
return predicateUri.equals(VitroVocabulary.LABEL);
}

View file

@ -366,8 +366,6 @@ public class EditN3GeneratorVTwo {
{
sbuff.append("@") ;
sbuff.append(lang) ;
// added by UQAM to exit at this point without adding datatype
return sbuff.toString() ;
}
// Format the datatype

View file

@ -10,23 +10,23 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.XSD;
import org.apache.jena.vocabulary.RDF;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.edit.EditLiteral;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.i18n.I18n;
public class MultiValueEditSubmission {
@ -34,31 +34,21 @@ public class MultiValueEditSubmission {
private Map<String,List<Literal>> literalsFromForm ;
private Map<String,List<String>> urisFromForm ;
private Map<String,String> validationErrors;
private BasicValidationVTwo basicValidation;
private Map<String, List<FileItem>> filesFromForm;
private static Model literalCreationModel;
private String entityToReturnTo;
private VitroRequest _vreq;
private static final String TIME_URI = XSD.time.getURI();
static{
literalCreationModel = ModelFactory.createDefaultModel();
}
/*
* UQAM
* replace
* public MultiValueEditSubmission(Map<String,String[]> queryParameters, EditConfigurationVTwo editConfig)
* by this new signature
* This affect PostEditCleanupController and ProcessRdfFormController classes.
* This replacement is justified by the fact that we need a linguistic context in this class.
*/
public MultiValueEditSubmission(VitroRequest vreq, EditConfigurationVTwo editConfig){
// UQAM add this both lines
_vreq = vreq;
Map<String,String[]> queryParameters = vreq.getParameterMap();
public MultiValueEditSubmission(Map<String,String[]> queryParameters, EditConfigurationVTwo editConfig){
if( editConfig == null )
throw new Error("EditSubmission needs an EditConfiguration");
this.editKey = editConfig.getEditKey();
@ -102,12 +92,11 @@ public class MultiValueEditSubmission {
processEditElementFields(editConfig,queryParameters);
//Incorporating basic validation
//Validate URIS
this.basicValidation = new BasicValidationVTwo(editConfig, I18n.bundle(vreq));
this.basicValidation = new BasicValidationVTwo(editConfig, this);
Map<String,String> errors = basicValidation.validateUris( urisFromForm );
//Validate literals and add errors to the list of existing errors
errors.putAll(basicValidation.validateLiterals( literalsFromForm ));
// UQAM Add empty contition
if( errors != null && !errors.isEmpty()) {
if( errors != null ) {
validationErrors.putAll( errors);
}
@ -152,8 +141,9 @@ public class MultiValueEditSubmission {
}
}
}
/* maybe this could be static */
public Literal createLiteral_ORIG(String value, String datatypeUri, String lang) {
public Literal createLiteral(String value, String datatypeUri, String lang) {
if( datatypeUri != null ){
if( "http://www.w3.org/2001/XMLSchema:anyURI".equals(datatypeUri) ){
try {
@ -169,27 +159,12 @@ public class MultiValueEditSubmission {
return ResourceFactory.createPlainLiteral(value);
}
/* maybe this could be static */
public Literal createLiteral(String value, String datatypeUri, String lang) {
if( datatypeUri != null && !datatypeUri.isEmpty() ){
// UQAM Original code contained tow-dots ':' in place of '#'
// if( "http://www.w3.org/2001/XMLSchema:anyURI".equals(datatypeUri) ){
if( XSD.anyURI.getURI().equals(datatypeUri) ){
// try {
// return literalCreationModel.createTypedLiteral( URLEncoder.encode(value, "UTF8"), datatypeUri);
return literalCreationModel.createTypedLiteral( value, datatypeUri);
// } catch (UnsupportedEncodingException e) {
// log.error(e, e);
// }
} else if ( XSD.xstring.getURI().equals(datatypeUri) || RDF.dtLangString.getURI().equals(datatypeUri) ){
if( lang != null && lang.length() > 0 ) return ResourceFactory.createLangLiteral(value, lang);
}
return literalCreationModel.createTypedLiteral(value, datatypeUri);
// UQAM take into account the linguistic context
} else if( lang != null && lang.length() > 0 )
return ResourceFactory.createLangLiteral(value, lang);
return ResourceFactory.createPlainLiteral(value);
}
private static final String DATE_TIME_URI = XSD.dateTime.getURI();
private static final String DATE_URI = XSD.date.getURI();
private static final String TIME_URI = XSD.time.getURI();
private static DateTimeFormatter dformater = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:00");
private static DateTimeFormatter dateFormater = DateTimeFormat.forPattern("yyyy-MM-dd");
public Map<String,String> getValidationErrors(){
return validationErrors;
@ -289,46 +264,12 @@ public class MultiValueEditSubmission {
for(String value:valueList) {
value = N3EditUtils.stripInvalidXMLChars(value);
//Add to array of literals corresponding to this variable
/* UQAM OLD
if (!StringUtils.isEmpty(value)) {
literalsArray.add(createLiteral(
value,
field.getRangeDatatypeUri(),
field.getRangeLang()));
}
*/
/*
* UQAM Replaced by this to take the linguistic context into consideration.
*/
if (!StringUtils.isEmpty(value)) {
String rangeLang = field.getRangeLang(); //UQAM Default value
try {
if (_vreq != null ) {
// only if the request comes from the rdfsLabelGenerator the language should be used
Boolean getLabelLanguage = false;
if (!StringUtils.isBlank(editConfig.formUrl) && editConfig.formUrl.contains("RDFSLabelGenerator")) {
getLabelLanguage = true;
}
// if the language is set in the given Literal, this language-tag should be used and remain the same
// for example when you edit an label with an langauge-tag (no matter which language is selected globally)
if (!StringUtils.isBlank(editConfig.getLiteralsInScope().get("label").get(0).getLanguage()) && getLabelLanguage)
{
rangeLang = editConfig.getLiteralsInScope().get("label").get(0).getLanguage();
} else { // if the literal has no langauge-tag, use the language which is globally selected
rangeLang = _vreq.getLocale().getLanguage();
if (!_vreq.getLocale().getCountry().isEmpty()) {
rangeLang += "-" + _vreq.getLocale().getCountry();
}
}
}
} catch (Exception e) {
}
literalsArray.add(createLiteral(
value,
field.getRangeDatatypeUri(),
rangeLang));
}
}
literalsFromForm.put(var, literalsArray);

View file

@ -9,24 +9,15 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.shared.Lock;
import org.apache.jena.vocabulary.RDF;
import org.apache.jena.vocabulary.XSD;
import org.apache.commons.lang3.StringUtils;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.InsertException;
@ -50,7 +41,6 @@ public class ProcessRdfForm {
private EditN3GeneratorVTwo populator;
private Map<String,String> urisForNewResources = null;
// private VitroRequest _vreq;
/**
* Construct the ProcessRdfForm object.
*/
@ -86,9 +76,9 @@ public class ProcessRdfForm {
AdditionsAndRetractions changes;
if( configuration.isUpdate() ){
changes = editExistingStatements(configuration, submission, vreq); //UQAM vreq for getting linguistic context
changes = editExistingStatements(configuration, submission);
} else {
changes = createNewStatements(configuration, submission, vreq ); //UQAM vreq for getting linguistic context
changes = createNewStatements(configuration, submission );
}
changes = getMinimalChanges(changes);
@ -109,15 +99,12 @@ public class ProcessRdfForm {
* any optional N3 is to originally configure the
* configuration.setN3Optional() to be empty.
*
* UQAM add vreq for linguistic context managing
*
* @throws Exception May throw an exception if the required N3
* does not parse.
*
*/
private AdditionsAndRetractions createNewStatements(
EditConfigurationVTwo configuration,
MultiValueEditSubmission submission, VitroRequest vreq) throws Exception {
MultiValueEditSubmission submission) throws Exception {
log.debug("in createNewStatements()" );
//getN3Required and getN3Optional will return copies of the
@ -126,10 +113,10 @@ public class ProcessRdfForm {
List<String> optionalN3 = configuration.getN3Optional();
/* substitute in the form values and existing values */
subInValuesToN3( configuration, submission, requiredN3, optionalN3, null , null, vreq);
subInValuesToN3( configuration, submission, requiredN3, optionalN3, null , null);
/* parse N3 to RDF Models, No retractions since all of the statements are new. */
return parseN3ToChange(requiredN3, optionalN3, null, null, vreq, null);
return parseN3ToChange(requiredN3, optionalN3, null, null);
}
/* for a list of N3 strings, substitute in the subject, predicate and object URIs
@ -153,12 +140,10 @@ public class ProcessRdfForm {
* retractions are mutually diff'ed before statements are added to or
* removed from the model. The explicit change check can cause problems in
* more complex setups, like the automatic form building in DataStaR.
* @param vreq For getting linguistic context
*/
protected AdditionsAndRetractions editExistingStatements(
EditConfigurationVTwo editConfig,
MultiValueEditSubmission submission, VitroRequest vreq) throws Exception {
MultiValueEditSubmission submission) throws Exception {
log.debug("editing an existing resource: " + editConfig.getObject() );
@ -171,18 +156,18 @@ public class ProcessRdfForm {
subInValuesToN3(editConfig, submission,
N3RequiredAssert, N3OptionalAssert,
N3RequiredRetract, N3OptionalRetract, vreq);
N3RequiredRetract, N3OptionalRetract);
return parseN3ToChange(
N3RequiredAssert,N3OptionalAssert,
N3RequiredRetract, N3OptionalRetract, vreq, editConfig);
N3RequiredRetract, N3OptionalRetract);
}
@SuppressWarnings("unchecked")
protected void subInValuesToN3(
EditConfigurationVTwo editConfig, MultiValueEditSubmission submission,
List<String> requiredAsserts, List<String> optionalAsserts,
List<String> requiredRetracts, List<String> optionalRetracts, VitroRequest vreq ) throws InsertException{
List<String> requiredRetracts, List<String> optionalRetracts ) throws InsertException{
//need to substitute into the return to URL becase it may need new resource URIs
List<String> URLToReturnTo = Arrays.asList(submission.getEntityToReturnTo());
@ -199,41 +184,7 @@ public class ProcessRdfForm {
//Retractions does NOT get values from form.
/* ******** Form submission Literals *********** */
/*
* UQAM Set all literals in the linguistic context
*/
Map<String, List<Literal>> literalsFromForm = submission.getLiteralsFromForm();
Set<String> keys = literalsFromForm.keySet();
for (String aKey : keys) {
List<Literal> literalFromForm = literalsFromForm.get(aKey);
List<Literal> newLiteralFromForm = new ArrayList<>();
for (Literal aLiteral : literalFromForm) {
if (aLiteral != null) {
String aLiteratDT = aLiteral.getDatatype().getURI();
Literal newLiteral = null;
String aText = aLiteral.getLexicalForm();
/*
* do it only if aLiteral are xstring datatype
*/
if (RDF.dtLangString.getURI().equals(aLiteratDT) && !aLiteral.getLanguage().isEmpty()) {
newLiteral = aLiteral;
}
else if (XSD.xstring.getURI().equals(aLiteratDT) || RDF.dtLangString.getURI().equals(aLiteratDT)) {
String lang = vreq.getLocale().getLanguage();
if (!vreq.getLocale().getCountry().isEmpty()) {
lang += "-" + vreq.getLocale().getCountry();
}
newLiteral = ResourceFactory.createLangLiteral(aText, lang);
} else {
newLiteral = ResourceFactory.createTypedLiteral(aText, aLiteral.getDatatype());
}
newLiteralFromForm.add(newLiteral);
}
}
literalsFromForm.replace(aKey, newLiteralFromForm);
}
substituteInMultiLiterals( literalsFromForm, requiredAsserts, optionalAsserts, URLToReturnTo);
substituteInMultiLiterals( submission.getLiteralsFromForm(), requiredAsserts, optionalAsserts, URLToReturnTo);
logSubstitue( "Added form Literals", requiredAsserts, optionalAsserts, requiredRetracts, optionalRetracts);
//Retractions does NOT get values from form.
@ -303,106 +254,20 @@ public class ProcessRdfForm {
protected AdditionsAndRetractions parseN3ToChange(
List<String> requiredAdds, List<String> optionalAdds,
List<String> requiredDels, List<String> optionalDels, VitroRequest vreq, EditConfigurationVTwo editConfig) throws Exception{
List<String> requiredDels, List<String> optionalDels) throws Exception{
List<Model> adds = parseN3ToRDF(requiredAdds, REQUIRED);
adds.addAll( parseN3ToRDF(optionalAdds, OPTIONAL));
List<Model> retracts = new ArrayList<Model>();
if( requiredDels != null && optionalDels != null ){
String lingCxt=null;
//UQAM Taking into account the linguistic context in retract
try {
// only if the request comes from the rdfsLabelGenerator the language should be used
Boolean getLabelLanguage = false;
if (!StringUtils.isBlank(editConfig.formUrl) && editConfig.formUrl.contains("RDFSLabelGenerator")) {
getLabelLanguage = true;
}
// if the language is set in the given Literal, this language-tag should be used and remain the same
// for example when you edit an label with an langauge-tag (no matter which language is selected globally)
if (editConfig != null && !StringUtils.isBlank(editConfig.getLiteralsInScope().get("label").get(0).getLanguage()) && getLabelLanguage) {
lingCxt = editConfig.getLiteralsInScope().get("label").get(0).getLanguage();
} else { // if the literal has no langauge-tag, use the language which is globally selected
lingCxt = vreq.getLocale().getLanguage();
if (!vreq.getLocale().getCountry().isEmpty()) {
lingCxt += "-" + vreq.getLocale().getCountry();
}
}
} catch (Exception e) {
}
retracts.addAll( parseN3ToRDF(requiredDels, REQUIRED, lingCxt) );
retracts.addAll( parseN3ToRDF(optionalDels, OPTIONAL, lingCxt) );
retracts.addAll( parseN3ToRDF(requiredDels, REQUIRED) );
retracts.addAll( parseN3ToRDF(optionalDels, OPTIONAL) );
}
return new AdditionsAndRetractions(adds,retracts);
}
/**
* Parse the n3Strings to a List of RDF Model objects.
*
* @param n3Strings N3 Strings to parse
* @param parseType if OPTIONAL, then don't throw exceptions on errors
* @param linguisticContext For Literals, Making parse only if the literal linguisticContext are same than linguisticContext parameter //UQAM
* If REQUIRED, then throw exceptions on errors.
* @throws Exception
*/
protected static List<Model> parseN3ToRDF(
List<String> n3Strings, N3ParseType parseType, String linguisticContext ) throws Exception {
// Use non-linguistic version of this method if no linguisticContext is provided
if (linguisticContext == null) {
return parseN3ToRDF(n3Strings, parseType);
}
List<String> errorMessages = new ArrayList<String>();
List<Model> rdfModels = new ArrayList<Model>();
for(String n3 : n3Strings){
try{
Model model = ModelFactory.createDefaultModel();
StringReader reader = new StringReader(n3);
model.read(reader, "", "N3");
List<Statement> stmts = model.listStatements().toList();
for (Iterator iterator = stmts.iterator(); iterator.hasNext();) {
Statement stmt = (Statement) iterator.next();
Resource subj = stmt.getSubject();
Property pred = stmt.getPredicate();
RDFNode obj = stmt.getObject();
if (obj.isLiteral()) {
Literal lit = obj.asLiteral();
String lang = lit.getLanguage();
if (! linguisticContext.equals(lang)) {
//UQAM Remove if linguisticContext != lang of the Literal
model.remove(subj, pred, obj);
}
}
}
rdfModels.add( model );
}catch(Throwable t){
errorMessages.add(t.getMessage() + "\nN3: \n" + n3 + "\n");
}
}
StringBuilder errors = new StringBuilder();
for( String errorMsg : errorMessages){
errors.append(errorMsg).append('\n');
}
if( !errorMessages.isEmpty() ){
if( REQUIRED.equals(parseType) ){
throw new Exception("Errors processing required N3. The EditConfiguration should " +
"be setup so that if a submission passes validation, there will not be errors " +
"in the required N3.\n" + errors );
}else if( OPTIONAL.equals(parseType) ){
log.debug("Some Optional N3 did not parse, if a optional N3 does not parse it " +
"will be ignored. This allows optional parts of a form submission to " +
"remain unfilled out and then the optional N3 does not get values subsituted in from" +
"the form submission values. It may also be the case that there are unintentional " +
"syntax errors the optional N3." );
log.debug(errors.toString());
}
}
return rdfModels;
}
/**
* Parse the n3Strings to a List of RDF Model objects.
*

View file

@ -7,7 +7,6 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.i18n.I18nBundle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -41,8 +40,7 @@ public class ChildVClassesOptions implements FieldOptions {
public Map<String, String> getOptions(
EditConfigurationVTwo editConfig,
String fieldName,
WebappDaoFactory wDaoFact,
I18nBundle i18n) throws Exception{
WebappDaoFactory wDaoFact) throws Exception{
// now create an empty HashMap to populate and return
HashMap <String,String> optionsMap = new LinkedHashMap<String,String>();

View file

@ -1,6 +1,6 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
@ -15,7 +15,6 @@ import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.i18n.I18nBundle;
public class ChildVClassesWithParent implements FieldOptions {
@ -38,24 +37,20 @@ public class ChildVClassesWithParent implements FieldOptions {
return this;
}
/*
* UQAM-Linguistic-Management
* This method is polymorphism of getOptions(EditConfigurationVTwo editConfig,String fieldName, WebappDaoFactory wDaoFact)
* for the internationalization of word "other" in the scroling list of personHasAdvisorRelationship.ftl
*/
@Override
public Map<String, String> getOptions(
EditConfigurationVTwo editConfig,
String fieldName,
WebappDaoFactory wDaoFact,
I18nBundle i18n) throws Exception {
WebappDaoFactory wDaoFact) throws Exception {
HashMap <String,String> optionsMap = new LinkedHashMap<String,String>();
// first test to see whether there's a default "leave blank" value specified with the literal options
if ( ! StringUtils.isEmpty( defaultOptionLabel ) ){
optionsMap.put(LEFT_BLANK, defaultOptionLabel);
}
String other_i18n = i18n.text("other");
// first character in capital
optionsMap.put(classUri, other_i18n.substring(0, 1).toUpperCase() + other_i18n.substring(1));
optionsMap.put(classUri, "Other");
VClassDao vclassDao = wDaoFact.getVClassDao();
List<String> subClassList = vclassDao.getAllSubClassURIs(classUri);
if (subClassList != null && subClassList.size() > 0) {

View file

@ -10,7 +10,6 @@ import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.i18n.I18nBundle;
public class ConstantFieldOptions implements FieldOptions {
@ -55,8 +54,7 @@ public class ConstantFieldOptions implements FieldOptions {
public Map<String, String> getOptions(
EditConfigurationVTwo editConfig,
String fieldName,
WebappDaoFactory wDaoFact,
I18nBundle i18n) throws Exception {
WebappDaoFactory wDaoFact) throws Exception {
// originally not auto-sorted but sorted now, and empty values not removed or replaced
HashMap <String,String> optionsMap = new LinkedHashMap<String,String>();

View file

@ -6,7 +6,6 @@ import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.i18n.I18nBundle;
/**
* Represents an object that can return a list of options
@ -29,8 +28,7 @@ public interface FieldOptions {
public Map<String,String> getOptions(
EditConfigurationVTwo editConfig,
String fieldName,
WebappDaoFactory wDaoFact,
I18nBundle i18n) throws Exception;
WebappDaoFactory wDaoFact) throws Exception;
/*
* Certain field options may have custom sorting requirements. If no sorting requirements exist,

View file

@ -6,7 +6,6 @@ import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.i18n.I18nBundle;
public class IndividualsViaClassGroupOptions implements FieldOptions {
@ -28,8 +27,7 @@ public class IndividualsViaClassGroupOptions implements FieldOptions {
public Map<String, String> getOptions(
EditConfigurationVTwo editConfig,
String fieldName,
WebappDaoFactory wDaoFact,
I18nBundle i18n) throws Exception {
WebappDaoFactory wDaoFact) throws Exception {
throw new Error("not implemented");
}

View file

@ -11,7 +11,6 @@ import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import edu.cornell.mannlib.vitro.webapp.i18n.I18nBundle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -78,8 +77,7 @@ public class IndividualsViaObjectPropetyOptions implements FieldOptions {
public Map<String, String> getOptions(
EditConfigurationVTwo editConfig,
String fieldName,
WebappDaoFactory wDaoFact,
I18nBundle i18n) {
WebappDaoFactory wDaoFact) {
HashMap<String, String> optionsMap = new LinkedHashMap<String, String>();
int optionsCount = 0;

View file

@ -8,7 +8,6 @@ import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.i18n.I18nBundle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -91,8 +90,7 @@ public class IndividualsViaSearchQueryOptions extends IndividualsViaVClassOption
public Map<String, String> getOptions(
EditConfigurationVTwo editConfig,
String fieldName,
WebappDaoFactory wDaoFact,
I18nBundle i18n) throws Exception {
WebappDaoFactory wDaoFact) throws Exception {
Map<String, Individual> individualMap = new HashMap<String, Individual>();

View file

@ -8,7 +8,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.i18n.I18nBundle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -49,8 +48,7 @@ public class IndividualsViaVClassOptions implements FieldOptions {
public Map<String, String> getOptions(
EditConfigurationVTwo editConfig,
String fieldName,
WebappDaoFactory wDaoFact,
I18nBundle i18n) throws Exception {
WebappDaoFactory wDaoFact) throws Exception {
Map<String, Individual> individualMap = new HashMap<String, Individual>();

View file

@ -9,7 +9,6 @@ import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.i18n.I18nBundle;
public class RdfTypeOptions implements FieldOptions {
@ -30,8 +29,7 @@ public class RdfTypeOptions implements FieldOptions {
public Map<String, String> getOptions(
EditConfigurationVTwo editConfig,
String fieldName,
WebappDaoFactory wdf,
I18nBundle i18n) {
WebappDaoFactory wdf) {
Map<String,String> uriToLabel = new HashMap<String,String>();
for (String uri : typeURIs) {

View file

@ -11,8 +11,6 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.i18n.I18n;
import edu.cornell.mannlib.vitro.webapp.i18n.I18nBundle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -27,8 +25,7 @@ public class SelectListGeneratorVTwo {
public static Map<String,String> getOptions(
EditConfigurationVTwo editConfig,
String fieldName,
WebappDaoFactory wDaoFact,
I18nBundle i18n){
WebappDaoFactory wDaoFact){
if( editConfig == null ){
@ -51,45 +48,7 @@ public class SelectListGeneratorVTwo {
}
try {
return field.getFieldOptions().getOptions(editConfig,fieldName,wDaoFact,i18n);
} catch (Exception e) {
log.error("Error runing getFieldOptionis()",e);
return Collections.emptyMap();
}
}
// UQAM Overcharge method for linguistic contexte processisng
// AWoods: This method appears to never be invoked.
public static Map<String,String> getOptions(
EditConfigurationVTwo editConfig,
String fieldName,
VitroRequest vreq){
if( editConfig == null ){
log.error( "fieldToSelectItemList() must be called with a non-null EditConfigurationVTwo ");
return Collections.emptyMap();
}
if( fieldName == null ){
log.error( "fieldToSelectItemList() must be called with a non-null fieldName");
return Collections.emptyMap();
}
FieldVTwo field = editConfig.getField(fieldName);
if (field==null) {
log.error("no field \""+fieldName+"\" found from editConfig.");
return Collections.emptyMap();
}
if( field.getFieldOptions() == null ){
return Collections.emptyMap();
}
try {
//UQAM need vreq instead of WebappDaoFactory
Map<String, String> parentClass = Collections.emptyMap();
FieldOptions fieldOptions = field.getFieldOptions();
return fieldOptions.getOptions(editConfig,fieldName,vreq.getWebappDaoFactory(), I18n.bundle(vreq));
return field.getFieldOptions().getOptions(editConfig,fieldName,wDaoFact);
} catch (Exception e) {
log.error("Error runing getFieldOptionis()",e);
return Collections.emptyMap();

View file

@ -16,7 +16,6 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTw
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.IdModelSelector;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.StandardModelSelector;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess.LanguageOption;
public abstract class BaseEditConfigurationGenerator implements EditConfigurationGenerator {
@ -64,7 +63,6 @@ public abstract class BaseEditConfigurationGenerator implements EditConfiguratio
setupModelSelectorsFromVitroRequest(vreq, editConfig);
OntModel queryModel = ModelAccess.on(vreq).getOntModel();
OntModel languageNeutralModel = vreq.getLanguageNeutralUnionFullModel();
if( editConfig.getSubjectUri() == null)
editConfig.setSubjectUri( EditConfigurationUtils.getSubjectUri(vreq));
@ -80,10 +78,7 @@ public abstract class BaseEditConfigurationGenerator implements EditConfiguratio
editConfig.prepareForObjPropUpdate(queryModel);
} else if( dataKey != null ) { // edit of a data prop statement
//do nothing since the data prop form generator must take care of it
// Use language-neutral model to ensure that a data property statement
// is found for any literal hash, even if the UI locale is changed.
editConfig.prepareForDataPropUpdate(languageNeutralModel,
vreq.getWebappDaoFactory().getDataPropertyDao());
editConfig.prepareForDataPropUpdate(queryModel, vreq.getWebappDaoFactory().getDataPropertyDao());
} else{
//this might be a create new or a form
editConfig.prepareForNonUpdate(queryModel);

View file

@ -350,7 +350,7 @@ public class DefaultAddMissingIndividualFormGenerator implements EditConfigurati
private void prepareForUpdate(VitroRequest vreq, HttpSession session, EditConfigurationVTwo editConfiguration) {
//Here, retrieve model from
OntModel model = ModelAccess.on(vreq).getOntModel();
OntModel model = ModelAccess.on(session.getServletContext()).getOntModel();
//if object property
if(EditConfigurationUtils.isObjectProperty(EditConfigurationUtils.getPredicateUri(vreq), vreq)){
Individual objectIndividual = EditConfigurationUtils.getObjectIndividual(vreq);

View file

@ -2,8 +2,6 @@
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess.LANGUAGE_NEUTRAL;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess.POLICY_NEUTRAL;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.DISPLAY;
import java.util.ArrayList;
@ -37,8 +35,6 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsVi
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation;
import edu.cornell.mannlib.vitro.webapp.i18n.I18n;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess.LanguageOption;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess.PolicyOption;
import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchEngine;
import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchEngineException;
import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchQuery;
@ -129,10 +125,7 @@ public class DefaultObjectPropertyFormGenerator implements EditConfigurationGene
// Someday we'll need to figure out a different way of doing this.
//WebappDaoFactory ctxDaoFact = ModelAccess.on(
// vreq.getSession().getServletContext()).getWebappDaoFactory();
// WebappDaoFactory ctxDaoFact = vreq.getLanguageNeutralWebappDaoFactory();
//UQAM Linguistic-Management Manage linguistic context
WebappDaoFactory ctxDaoFact = ModelAccess.on(vreq).getWebappDaoFactory(LanguageOption.LANGUAGE_AWARE, PolicyOption.POLICY_NEUTRAL);
WebappDaoFactory ctxDaoFact = vreq.getLanguageNeutralWebappDaoFactory();
List<VClass> types = new ArrayList<VClass>();
Individual subject = EditConfigurationUtils.getSubjectIndividual(vreq);
@ -467,7 +460,7 @@ public class DefaultObjectPropertyFormGenerator implements EditConfigurationGene
private void prepareForUpdate(VitroRequest vreq, HttpSession session, EditConfigurationVTwo editConfiguration) {
//Here, retrieve model from
OntModel model = ModelAccess.on(vreq).getOntModel();
OntModel model = ModelAccess.on(session.getServletContext()).getOntModel();
//if object property
if(EditConfigurationUtils.isObjectProperty(EditConfigurationUtils.getPredicateUri(vreq), vreq)){
Individual objectIndividual = EditConfigurationUtils.getObjectIndividual(vreq);

View file

@ -15,7 +15,6 @@ import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpSession;
@ -42,7 +41,6 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.FoafNameToRdfsLabelPreprocessor;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.ManageLabelsForIndividualPreprocessor;
import edu.cornell.mannlib.vitro.webapp.i18n.selection.SelectedLocale;
import edu.cornell.mannlib.vitro.webapp.rdfservice.filter.LanguageFilteringUtils;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.DataPropertyStatementTemplateModel;
/**
@ -204,12 +202,12 @@ public class ManageLabelsForIndividualGenerator extends BaseEditConfigurationGen
private void addFormSpecificData(EditConfigurationVTwo config,
VitroRequest vreq) {
//the labels already added by the user
ArrayList<Literal> existingLabels = this.getExistingLabels(config.getSubjectUri(), vreq);
//Get language codes/labels for languages present in the existing labels
List<HashMap<String, String>> locales = this.getLocales(vreq, existingLabels);
//Get all language codes/labels in the system, and this list is sorted by language name
List<HashMap<String, String>> locales = this.getLocales(vreq);
//Get code to label hashmap - we use this to get the language name for the language code returned in the rdf literal
HashMap<String, String> localeCodeToNameMap = this.getFullCodeToLanguageNameMap(locales);
//the labels already added by the user
ArrayList<Literal> existingLabels = this.getExistingLabels(config.getSubjectUri(), vreq);
int numberExistingLabels = existingLabels.size();
//existing labels keyed by language name and each of the list of labels is sorted by language name
HashMap<String, List<LabelInformation>> existingLabelsByLanguageName = this.getLabelsSortedByLanguageName(existingLabels, localeCodeToNameMap, config, vreq);
@ -226,20 +224,6 @@ public class ManageLabelsForIndividualGenerator extends BaseEditConfigurationGen
config.addFormSpecificData("displayRemoveLink", (numberExistingLabels > 1));
// get current selected locale
String rangeLang = vreq.getLocale().getLanguage();
if (!vreq.getLocale().getCountry().isEmpty()) {
rangeLang += "-" + vreq.getLocale().getCountry();
}
// check if locale already has an entry (label)
boolean localeEntryExisting = true;
for (HashMap<String, String> tmp : availableLocalesForAdd) {
if (tmp.get("code").equals(rangeLang)) localeEntryExisting = false;
}
config.addFormSpecificData("localeEntryExisting", localeEntryExisting);
config.addFormSpecificData("currentSelectedLocale", rangeLang);
//How do we edit? Will need to see
config.addFormSpecificData("deleteWebpageUrl", "/edit/primitiveDelete");
@ -375,9 +359,8 @@ public class ManageLabelsForIndividualGenerator extends BaseEditConfigurationGen
ArrayList<Literal> labels = new ArrayList<Literal>();
try {
// Get results filtered to current locale so as to be consistent
// with other editing forms.
ResultSet results = QueryUtils.getQueryResults(queryStr, vreq);
//We want to get the labels for all the languages, not just the display language
ResultSet results = QueryUtils.getLanguageNeutralQueryResults(queryStr, vreq);
while (results.hasNext()) {
QuerySolution soln = results.nextSolution();
Literal nodeLiteral = soln.get("label").asLiteral();
@ -404,32 +387,30 @@ public class ManageLabelsForIndividualGenerator extends BaseEditConfigurationGen
return template;
}
//get locales present in list of literals
public List<HashMap<String, String>> getLocales(VitroRequest vreq,
List<Literal> existingLiterals) {
Set<Locale> locales = new HashSet<Locale>();
for(Literal literal : existingLiterals) {
String language = literal.getLanguage();
if(!StringUtils.isEmpty(language)) {
locales.add(LanguageFilteringUtils.languageToLocale(language));
}
}
if (locales.isEmpty()) {
//get locales
public List<HashMap<String, String>> getLocales(VitroRequest vreq) {
List<Locale> selectables = SelectedLocale.getSelectableLocales(vreq);
if (selectables.isEmpty()) {
return Collections.emptyList();
}
List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
Locale currentLocale = SelectedLocale.getCurrentLocale(vreq);
for (Locale locale : locales) {
for (Locale locale : selectables) {
try {
list.add(buildLocaleMap(locale, currentLocale));
} catch (FileNotFoundException e) {
log.warn("Can't show locale '" + locale + "': " + e);
log.warn("Can't show the Locale selector for '" + locale
+ "': " + e);
}
}
return list;
}
public HashMap<String, String> getFullCodeToLanguageNameMap(List<HashMap<String, String>> localesList) {
HashMap<String, String> codeToLanguageMap = new HashMap<String, String>();
for(Map<String, String> locale: localesList) {

View file

@ -233,7 +233,7 @@ public class NewIndividualFormGenerator implements EditConfigurationGenerator {
private void prepareForUpdate(VitroRequest vreq, HttpSession session, EditConfigurationVTwo editConfiguration) {
//Here, retrieve model from
OntModel model = ModelAccess.on(vreq).getOntModel();
OntModel model = ModelAccess.on(session.getServletContext()).getOntModel();
//This form is always doing a non-update
editConfiguration.prepareForNonUpdate( model );

View file

@ -298,7 +298,7 @@ public class RDFSLabelGenerator implements EditConfigurationGenerator {
private void prepareForUpdate(VitroRequest vreq, HttpSession session, EditConfigurationVTwo editConfiguration) {
//Here, retrieve model from
OntModel model = ModelAccess.on(vreq).getOntModel();
OntModel model = ModelAccess.on(session.getServletContext()).getOntModel();
if( editConfiguration.isDataPropertyUpdate() ){
editConfiguration.prepareForDataPropUpdate(model, vreq.getWebappDaoFactory().getDataPropertyDao());
}

View file

@ -1,92 +0,0 @@
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.rdf.model.StmtIterator;
import edu.cornell.mannlib.vitro.webapp.rdfservice.filter.LanguageFilteringUtils;
/**
* A model change preprocessor that discards triples with language tags
* in the retractionsModel that do not match the specified language, unless
* the additionsModel also contains a new value for the same subject and
* predicate in that language, or no values in any language are added for the
* same subject and predicate (such as when an entire resource is deleted) .
*/
public class LimitRemovalsToLanguage implements ModelChangePreprocessor {
private static final Log log = LogFactory.getLog(LimitRemovalsToLanguage.class);
private String language;
/**
* @param locale the Java locale object representing the language
* to which edits should be limited. May not be null.
*/
public LimitRemovalsToLanguage(Locale locale) {
if(locale == null) {
throw new IllegalArgumentException("Locale may not be null.");
}
this.language = LanguageFilteringUtils.localeToLanguage(locale);
}
/**
* @param language string representing the RDF language tag to which
* edits should be limited. May not be null.
*/
public LimitRemovalsToLanguage(String language) {
if(language == null) {
throw new IllegalArgumentException("Language may not be null.");
}
this.language = language;
}
@Override
public void preprocess(Model retractionsModel, Model additionsModel,
HttpServletRequest request) {
log.debug("limiting changes to " + language);
List<Statement> eliminatedRetractions = new ArrayList<Statement>();
StmtIterator sit = retractionsModel.listStatements();
while(sit.hasNext()) {
Statement stmt = sit.next();
if(stmt.getObject().isLiteral()) {
Literal lit = stmt.getObject().asLiteral();
if(!StringUtils.isEmpty(lit.getLanguage())
&& !lit.getLanguage().equals(language)) {
boolean eliminateRetraction = true;
StmtIterator replacements = additionsModel
.listStatements(stmt.getSubject(),
stmt.getPredicate(), (RDFNode) null);
if(!replacements.hasNext()) {
eliminateRetraction = false;
} else {
while(replacements.hasNext()) {
Statement replacement = replacements.next();
if(replacement.getObject().isLiteral()
&& lit.getLanguage().equals(replacement
.getObject().asLiteral()
.getLanguage())) {
eliminateRetraction = false;
}
}
}
if(eliminateRetraction) {
eliminatedRetractions.add(stmt);
}
}
}
}
retractionsModel.remove(eliminatedRetractions);
}
}

View file

@ -169,7 +169,7 @@ public class EditRequestDispatchController extends FreemarkerHttpServlet {
templateData.put("editConfiguration", etm);
templateData.put("editSubmission", submissionTemplateModel);
//Corresponding to original note for consistency with selenium tests and 1.1.1
templateData.put("title", etm.getPageTitle());
templateData.put("title", "Edit");
templateData.put("submitUrl", getSubmissionUrl(vreq));
templateData.put("cancelUrl", etm.getCancelUrl());
templateData.put("editKey", editConfig.getEditKey());

View file

@ -74,11 +74,9 @@ public class PostEditCleanupController extends FreemarkerHttpServlet{
//The submission for getting the entity to return to is not retrieved from the session but needs
//to be created - as it is in processRdfForm3.jsp
if( entityToReturnTo == null ){
// this will not work if there entityToReturnTo has a new resource URI,
// in that case entityToReturnTo should not have been passed to this method as null
// UQAM-Linguistic-Management
// MultiValueEditSubmission submission = new MultiValueEditSubmission(vreq.getParameterMap(), editConfig);
MultiValueEditSubmission submission = new MultiValueEditSubmission(vreq, editConfig);
//this will not work if there entityToReturnTo has a new resource URI,
//in that case entityToReturnTo should not have been passed to this method as null
MultiValueEditSubmission submission = new MultiValueEditSubmission(vreq.getParameterMap(), editConfig);
entityToReturnTo = N3EditUtils.processEntityToReturnTo(editConfig, submission, vreq);
}

View file

@ -8,11 +8,10 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.annotation.WebServlet;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.Property;
@ -38,7 +37,8 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmis
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.N3EditUtils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.ProcessRdfForm;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.RdfLiteralHash;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.LimitRemovalsToLanguage;
import javax.servlet.annotation.WebServlet;
/**
* This servlet will convert a request to an EditSubmission,
@ -66,9 +66,7 @@ public class ProcessRdfFormController extends FreemarkerHttpServlet{
return handleMissingConfiguration(vreq);
//get the EditSubmission
// MultiValueEditSubmission submission = new MultiValueEditSubmission(vreq.getParameterMap(), configuration);
// Modified by UQAM-Linguistic-Management
MultiValueEditSubmission submission = new MultiValueEditSubmission(vreq, configuration);
MultiValueEditSubmission submission = new MultiValueEditSubmission(vreq.getParameterMap(), configuration);
EditSubmissionUtils.putEditSubmissionInSession(vreq.getSession(), submission);
//if errors, return error response
@ -103,9 +101,6 @@ public class ProcessRdfFormController extends FreemarkerHttpServlet{
if( configuration.isUseDependentResourceDelete() )
changes = ProcessRdfForm.addDependentDeletes(changes, queryModel);
// prevent form from removing literals in languages other than the one
// associated with the current request
configuration.addModelChangePreprocessor(new LimitRemovalsToLanguage(vreq.getLocale()));
N3EditUtils.preprocessModels(changes, configuration, vreq);
ProcessRdfForm.applyChangesToWriteModel(changes, queryModel, writeModel, N3EditUtils.getEditorUri(vreq) );

View file

@ -35,7 +35,6 @@ import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess.WhichService;
import edu.cornell.mannlib.vitro.webapp.modelaccess.impl.RequestModelAccessImpl;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
import edu.cornell.mannlib.vitro.webapp.rdfservice.filter.LanguageFilteringUtils;
import edu.cornell.mannlib.vitro.webapp.rdfservice.impl.RDFServiceUtils;
/**
@ -89,10 +88,8 @@ public class ModelSwitcher {
// If they asked for the display model, give it to them.
if (isParameterPresent(vreq, SWITCH_TO_DISPLAY_MODEL)) {
OntModel mainOntModel = LanguageFilteringUtils.wrapOntModelInALanguageFilter(
ModelAccess.on(vreq).getOntModel(DISPLAY), vreq);
OntModel tboxOntModel = LanguageFilteringUtils.wrapOntModelInALanguageFilter(
ModelAccess.on(vreq).getOntModel(DISPLAY_TBOX), vreq);
OntModel mainOntModel = ModelAccess.on(_context).getOntModel(DISPLAY);
OntModel tboxOntModel = ModelAccess.on(_context).getOntModel(DISPLAY_TBOX);
setSpecialWriteModel(vreq, mainOntModel);
vreq.setAttribute(VitroRequest.ID_FOR_ABOX_MODEL, VitroModelSource.ModelName.DISPLAY.toString());

View file

@ -63,7 +63,6 @@ public class PageRoutingFilter implements Filter{
// get URL without hostname or servlet context
HttpServletResponse response = (HttpServletResponse) arg1;
HttpServletRequest req = (HttpServletRequest) arg0;
String path = req.getRequestURI().substring(req.getContextPath().length());
// check for first part of path

View file

@ -6,7 +6,6 @@ import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;

View file

@ -304,7 +304,7 @@ public class FreemarkerConfigurationImpl extends Configuration {
urls.put("home", UrlBuilder.getHomeUrl());
urls.put("about", UrlBuilder.getUrl(Route.ABOUT));
urls.put("search", UrlBuilder.getUrl(Route.SEARCH));
urls.put("extendedsearch", UrlBuilder.getUrl(Route.EXTENDED_SEARCH));
urls.put("customsearch", UrlBuilder.getUrl(Route.CUSTOMSEARCH));
urls.put("termsOfUse", UrlBuilder.getUrl(Route.TERMS_OF_USE));
urls.put("login", UrlBuilder.getLoginUrl());
urls.put("logout", UrlBuilder.getLogoutUrl());

View file

@ -8,7 +8,6 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.SortedSet;
import java.util.TreeSet;
@ -21,9 +20,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.i18n.selection.SelectedLocale;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.utils.developer.DeveloperSettings;
import edu.cornell.mannlib.vitro.webapp.utils.developer.Key;
@ -52,27 +49,12 @@ public class I18n {
* This is where the work gets done. Not declared final, so it can be
* modified in unit tests.
*/
private static I18n instance;
private final ServletContext ctx;
protected I18n(ServletContext ctx) {
this.ctx = ctx;
}
private static I18n instance = new I18n();
// ----------------------------------------------------------------------
// Static methods
// ----------------------------------------------------------------------
/**
* This setup method must be called before I18n static methods can be used.
* It is currently called from LocaleSelectionSetup.contextInitialized, which
* should ensure it is called when the context is initialized.
*/
public static void setup(ServletContext ctx) {
I18n.instance = new I18n(ctx);
}
/**
* A convenience method to get a bundle and format the text.
*/
@ -90,26 +72,19 @@ public class I18n {
}
/**
* Get a request I18nBundle by this name.
* Get a I18nBundle by this name.
*/
public static I18nBundle bundle(String bundleName, HttpServletRequest req) {
return instance.getBundle(bundleName, req);
}
/**
* Get the default request I18nBundle.
* Get the default I18nBundle.
*/
public static I18nBundle bundle(HttpServletRequest req) {
return instance.getBundle(DEFAULT_BUNDLE_NAME, req);
}
/**
* Get the default context I18nBundle for preferred locales.
*/
public static I18nBundle bundle(List<Locale> preferredLocales) {
return instance.getBundle(DEFAULT_BUNDLE_NAME, preferredLocales);
}
// ----------------------------------------------------------------------
// The instance
// ----------------------------------------------------------------------
@ -131,59 +106,25 @@ public class I18n {
* Declared 'protected' so it can be overridden in unit tests.
*/
protected I18nBundle getBundle(String bundleName, HttpServletRequest req) {
log.debug("Getting request bundle '" + bundleName + "'");
log.debug("Getting bundle '" + bundleName + "'");
I18nLogger i18nLogger = new I18nLogger();
try {
checkDevelopmentMode(req);
checkForChangeInThemeDirectory(req);
Locale locale = req.getLocale();
return getBundle(bundleName, locale);
}
/**
* Get an I18nBundle by this name. The context provides the selectable
* Locale, the application directory, the theme directory and the
* development mode flag. Choosing matching locale from context by
* provided preferred locales.
*
* If the context indicates that the system is in development mode, then the
* cache is cleared on each request.
*
* If the theme directory has changed, the cache is cleared.
*
* Declared 'protected' so it can be overridden in unit tests.
*/
protected I18nBundle getBundle(String bundleName, List<Locale> preferredLocales) {
log.debug("Getting context bundle '" + bundleName + "'");
checkDevelopmentMode();
checkForChangeInThemeDirectory(ctx);
Locale locale = SelectedLocale.getPreferredLocale(ctx, preferredLocales);
return getBundle(bundleName, locale);
}
/**
* Get an I18nBundle by this name, context, and locale.
*/
private I18nBundle getBundle(String bundleName, Locale locale) {
I18nLogger i18nLogger = new I18nLogger();
try {
String dir = themeDirectory.get();
ServletContext ctx = req.getSession().getServletContext();
ResourceBundle.Control control = new ThemeBasedControl(ctx, dir);
ResourceBundle rb = ResourceBundle.getBundle(bundleName,
locale, control);
req.getLocale(), control);
return new I18nBundle(bundleName, rb, i18nLogger);
} catch (MissingResourceException e) {
log.warn("Didn't find text bundle '" + bundleName + "'");
return I18nBundle.emptyBundle(bundleName, i18nLogger);
} catch (Exception e) {
log.error("Failed to create text bundle '" + bundleName + "'", e);
return I18nBundle.emptyBundle(bundleName, i18nLogger);
}
}
@ -198,16 +139,6 @@ public class I18n {
}
}
/**
* If we are in development mode, clear the cache.
*/
private void checkDevelopmentMode() {
if (DeveloperSettings.getInstance().getBoolean(Key.I18N_DEFEAT_CACHE)) {
log.debug("In development mode - clearing the cache.");
ResourceBundle.clearCache();
}
}
/**
* If the theme directory has changed from before, clear the cache of all
* ResourceBundles.
@ -222,30 +153,6 @@ public class I18n {
}
}
/**
* If we have a complete model access and the theme directory has changed
* from before, clear the cache of all ResourceBundles.
*/
private void checkForChangeInThemeDirectory(ServletContext ctx) {
WebappDaoFactory wdf = ModelAccess.on(ctx)
.getWebappDaoFactory();
// Only applicable if context has a complete model access
if (Objects.nonNull(wdf)
&& Objects.nonNull(wdf.getApplicationDao())
&& Objects.nonNull(wdf.getApplicationDao().getApplicationBean())) {
String currentDir = wdf
.getApplicationDao()
.getApplicationBean()
.getThemeDir();
String previousDir = themeDirectory.getAndSet(currentDir);
if (!currentDir.equals(previousDir)) {
log.debug("Theme directory changed from '" + previousDir + "' to '"
+ currentDir + "' - clearing the cache.");
ResourceBundle.clearCache();
}
}
}
/** Only clear the cache one time per request. */
private void clearCacheOnRequest(HttpServletRequest req) {
if (req.getAttribute(ATTRIBUTE_CACHE_CLEARED) != null) {

View file

@ -10,9 +10,6 @@ import java.util.ResourceBundle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.utils.developer.DeveloperSettings;
import edu.cornell.mannlib.vitro.webapp.utils.developer.Key;
/**
* A wrapper for a ResourceBundle that will not throw an exception, no matter
* what string you request.
@ -23,9 +20,7 @@ import edu.cornell.mannlib.vitro.webapp.utils.developer.Key;
*/
public class I18nBundle {
private static final Log log = LogFactory.getLog(I18nBundle.class);
private static final String startSep = "\u25a4";
private static final String endSep = "\u25a5";
public static final String intSep = "\u25a6";
private static final String MESSAGE_BUNDLE_NOT_FOUND = "Text bundle ''{0}'' not found.";
private static final String MESSAGE_KEY_NOT_FOUND = "Text bundle ''{0}'' has no text for ''{1}''";
@ -81,26 +76,12 @@ public class I18nBundle {
log.warn(message);
textString = "ERROR: " + message;
}
String message = formatString(textString, parameters);
String result = formatString(textString, parameters);
if (i18nLogger != null) {
i18nLogger.log(bundleName, key, parameters, textString, message);
i18nLogger.log(bundleName, key, parameters, textString, result);
}
if (isNeedExportInfo()) {
String separatedArgs = "";
for (int i = 0; i < parameters.length; i++) {
separatedArgs += parameters[i] + intSep;
}
return startSep + key + intSep + textString + intSep + separatedArgs + message + endSep;
} else {
return message;
}
}
private static boolean isNeedExportInfo() {
return DeveloperSettings.getInstance().getBoolean(Key.I18N_ONLINE_TRANSLATION);
return result;
}
private static String formatString(String textString, Object... parameters) {

View file

@ -8,9 +8,6 @@ import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.i18n.I18nBundle;
import edu.cornell.mannlib.vitro.webapp.utils.developer.DeveloperSettings;
import edu.cornell.mannlib.vitro.webapp.utils.developer.Key;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
@ -68,11 +65,7 @@ public class I18nStringTemplateModel implements TemplateMethodModelEx,
.get(i));
}
try {
if(isOnlineTranslationsEnabled()) {
return getOnlineTranslationsFormattedMessage(textString, unwrappedArgs);
} else {
return MessageFormat.format(textString, unwrappedArgs);
}
} catch (Exception e) {
String message = "Can't format '" + key + "' from bundle '"
+ bundleName + "', wrong argument types: " + args
@ -83,39 +76,4 @@ public class I18nStringTemplateModel implements TemplateMethodModelEx,
}
}
/**
* Splits preProcessed string, formats message with arguments, lists arguments before message
* and combines preProcessed string back to be used with online translations.
* Substitutes arguments in message which is a part of preProcessed string
* @param preProcessed String "startSep + key + intSep + textString + intSep + message + endSep"
* @param arguments that should be listed before message and substituted in the message itself
* @return
*/
private String getOnlineTranslationsFormattedMessage(String preProcessed, Object[] args) {
String[] parts = preProcessed.split(I18nBundle.intSep);
final int messageIndex = parts.length -1;
String message = MessageFormat.format(parts[messageIndex], args);
String[] arguments = convertToArrayOfStrings(args);
parts[messageIndex] = "";
String result = String.join(I18nBundle.intSep, parts) +
String.join(I18nBundle.intSep, arguments) +
I18nBundle.intSep + message ;
return result;
}
private String[] convertToArrayOfStrings(Object[] args) {
String[] result = new String[args.length];
for (int i = 0; i < result.length; i++)
if (args[i] != null) {
result[i] = args[i].toString();
} else {
result[i] = "";
}
return result;
}
private static boolean isOnlineTranslationsEnabled() {
return DeveloperSettings.getInstance().getBoolean(Key.I18N_ONLINE_TRANSLATION);
}
}

View file

@ -89,8 +89,8 @@ public class LocaleSelectionDataGetter implements DataGetter {
Locale currentLocale) throws FileNotFoundException {
Map<String, Object> map = new HashMap<>();
map.put("code", locale.toString());
map.put("label", locale.getDisplayLanguage(locale));
map.put("country", locale.getDisplayCountry(locale));
map.put("label", locale.getDisplayName(currentLocale));
map.put("imageUrl", LocaleSelectorUtilities.getImageUrl(vreq, locale));
map.put("selected", currentLocale.equals(locale));
return map;
}

View file

@ -14,7 +14,6 @@ import org.apache.commons.lang3.LocaleUtils;
import org.apache.commons.lang3.StringUtils;
import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties;
import edu.cornell.mannlib.vitro.webapp.i18n.I18n;
import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus;
/**
@ -49,10 +48,6 @@ public class LocaleSelectionSetup implements ServletContextListener {
ss = StartupStatus.getBean(ctx);
props = ConfigurationProperties.getBean(sce);
// Instantiate I18n instance to afford access to ServletContext
// when requesting a bundle with or without a VitroRequest
I18n.setup(ctx);
readProperties();
if (isForcing() && hasSelectables()) {

View file

@ -0,0 +1,58 @@
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.i18n.selection;
import java.io.FileNotFoundException;
import java.util.Locale;
import java.util.Set;
import javax.servlet.ServletContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
/**
* Some static methods for the GUI aspects of selecting a Locale.
*/
public class LocaleSelectorUtilities {
private static final Log log = LogFactory
.getLog(LocaleSelectorUtilities.class);
/**
* Look in the current theme directory to find a selection image for this
* Locale.
*
* Images are expected at a resource path like
* /[themeDir]/i18n/images/select_locale_[locale_code].*
*
* For example, /themes/wilma/i18n/images/select_locale_en.png
* /themes/wilma/i18n/images/select_locale_en.JPEG
* /themes/wilma/i18n/images/select_locale_en.gif
*
* To create a proper URL, prepend the context path.
*/
public static String getImageUrl(VitroRequest vreq, Locale locale)
throws FileNotFoundException {
String filename = "select_locale_" + locale + ".";
String themeDir = vreq.getAppBean().getThemeDir();
String imageDirPath = "/" + themeDir + "i18n/images/";
ServletContext ctx = vreq.getSession().getServletContext();
@SuppressWarnings("unchecked")
Set<String> resourcePaths = ctx.getResourcePaths(imageDirPath);
if (resourcePaths != null) {
for (String resourcePath : resourcePaths) {
if (resourcePath.contains(filename)) {
String fullPath = vreq.getContextPath() + resourcePath;
log.debug("Found image for " + locale + " at '" + fullPath
+ "'");
return fullPath;
}
}
}
throw new FileNotFoundException("Can't find an image for " + locale);
}
}

View file

@ -6,8 +6,6 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
@ -63,10 +61,13 @@ public abstract class SelectedLocale {
ServletContext ctx = session.getServletContext();
Object ctxInfo = ctx.getAttribute(ATTRIBUTE_NAME);
Optional<Locale> forcedLocale = getForcedLocale(ctxInfo);
if (forcedLocale.isPresent()) {
return forcedLocale.get();
if (ctxInfo instanceof ContextSelectedLocale) {
Locale forcedLocale = ((ContextSelectedLocale) ctxInfo)
.getForcedLocale();
if (forcedLocale != null) {
log.debug("Found forced locale in the context: " + forcedLocale);
return forcedLocale;
}
}
Object sessionInfo = session.getAttribute(ATTRIBUTE_NAME);
@ -91,62 +92,7 @@ public abstract class SelectedLocale {
}
}
Locale fallbackLocale = getFallbackLocale();
log.debug("Using fallback locale as default: " + fallbackLocale);
return fallbackLocale;
}
/**
* Get the overriding Locale to use, which is the first of these to be found:
* <ul>
* <li>The forced Locale in the servlet context</li>
* <li>The first selectable locale matching a preferred locale</li>
* <li>The first of the preferred locale</li>
* <li>null</li>
* </ul>
*/
public static Locale getOverridingLocale(ServletContext ctx, List<Locale> preferredLocales) {
Object ctxInfo = ctx.getAttribute(ATTRIBUTE_NAME);
Optional<Locale> forcedLocale = getForcedLocale(ctxInfo);
if (forcedLocale.isPresent()) {
return forcedLocale.get();
}
if (ctxInfo instanceof ContextSelectedLocale) {
List<Locale> selectableLocales = ((ContextSelectedLocale) ctxInfo)
.getSelectableLocales();
if (Objects.nonNull(selectableLocales) && Objects.nonNull(preferredLocales)) {
for (Locale preferredLocal : preferredLocales) {
for (Locale selectableLocale : selectableLocales) {
if (selectableLocale.equals(preferredLocal)) {
log.debug("Using first matching selectable locale from context: "
+ selectableLocale);
return selectableLocale;
}
}
}
}
}
if (Objects.nonNull(preferredLocales) && !preferredLocales.isEmpty()) {
Locale preferredLocal = preferredLocales.get(0);
log.debug("Using first preferred locale as default: "
+ preferredLocal);
return preferredLocal;
}
Locale fallbackLocale = getFallbackLocale();
log.debug("Using fallback locale as default: " + fallbackLocale);
return fallbackLocale;
}
/**
* @return a default locale to use if no other criteria for selecting a
* different one exist.
*/
public static Locale getFallbackLocale() {
return new Locale("en", "US");
return null;
}
/**
@ -175,42 +121,6 @@ public abstract class SelectedLocale {
return Locale.getDefault();
}
/**
* Get the preferred Locale to use, which is the first of these to be found:
* <ul>
* <li>The forced Locale in the servlet context</li>
* <li>The first selectable locale matching a preferred locale</li>
* <li>The first of the preferred locale</li>
* <li>The default Locale for the JVM</li>
* </ul>
*/
public static Locale getPreferredLocale(ServletContext ctx, List<Locale> preferredLocales) {
Locale overridingLocale = getOverridingLocale(ctx, preferredLocales);
if (overridingLocale != null) {
return overridingLocale;
}
log.debug("Using default locale: " + Locale.getDefault());
return Locale.getDefault();
}
/**
* Check for forced locale on the context.
*/
private static Optional<Locale> getForcedLocale(Object ctxInfo) {
if (ctxInfo instanceof ContextSelectedLocale) {
Locale forcedLocale = ((ContextSelectedLocale) ctxInfo)
.getForcedLocale();
if (forcedLocale != null) {
log.debug("Found forced locale in the context: " + forcedLocale);
return Optional.of(forcedLocale);
}
}
return Optional.empty();
}
/**
* Store a list of selectable Locales in the servlet context, so we can
* easily build the selection panel in the GUI. Clears any forced locale.

View file

@ -13,27 +13,20 @@ public class ModelNames {
public static final String ABOX_ASSERTIONS = "http://vitro.mannlib.cornell.edu/default/vitro-kb-2";
public static final String ABOX_INFERENCES = "http://vitro.mannlib.cornell.edu/default/vitro-kb-inf";
public static final String ABOX_UNION = "vitro:aboxOntModel";
public static final String ABOX_ASSERTIONS_FIRSTTIME_BACKUP = ABOX_ASSERTIONS + "FirsttimeBackup";
public static final String TBOX_ASSERTIONS = "http://vitro.mannlib.cornell.edu/default/asserted-tbox";
public static final String TBOX_INFERENCES = "http://vitro.mannlib.cornell.edu/default/inferred-tbox";
public static final String TBOX_UNION = "vitro:tboxOntModel";
public static final String TBOX_ASSERTIONS_FIRSTTIME_BACKUP = TBOX_ASSERTIONS + "FirsttimeBackup";
public static final String FULL_ASSERTIONS = "vitro:baseOntModel";
public static final String FULL_INFERENCES = "vitro:inferenceOntModel";
public static final String FULL_UNION = "vitro:jenaOntModel";
public static final String APPLICATION_METADATA = "http://vitro.mannlib.cornell.edu/default/vitro-kb-applicationMetadata";
public static final String APPLICATION_METADATA_FIRSTTIME_BACKUP = APPLICATION_METADATA + "FirsttimeBackup";
public static final String USER_ACCOUNTS = "http://vitro.mannlib.cornell.edu/default/vitro-kb-userAccounts";
public static final String USER_ACCOUNTS_FIRSTTIME_BACKUP = USER_ACCOUNTS + "FirsttimeBackup";
public static final String DISPLAY = "http://vitro.mannlib.cornell.edu/default/vitro-kb-displayMetadata";
public static final String DISPLAY_FIRSTTIME_BACKUP = DISPLAY + "FirsttimeBackup";
public static final String DISPLAY_TBOX = "http://vitro.mannlib.cornell.edu/default/vitro-kb-displayMetadataTBOX";
public static final String DISPLAY_TBOX_FIRSTTIME_BACKUP = DISPLAY_TBOX + "FirsttimeBackup";
public static final String DISPLAY_DISPLAY = "http://vitro.mannlib.cornell.edu/default/vitro-kb-displayMetadata-displayModel";
public static final String DISPLAY_DISPLAY_FIRSTTIME_BACKUP = DISPLAY_DISPLAY + "FirsttimeBackup";
/**
* A map of the URIS, keyed by their short names, intended only for display
@ -46,24 +39,17 @@ public class ModelNames {
map.put("ABOX_ASSERTIONS", ABOX_ASSERTIONS);
map.put("ABOX_INFERENCES", ABOX_INFERENCES);
map.put("ABOX_UNION", ABOX_UNION);
map.put("ABOX_ASSERTIONS_FIRSTTIME_BACKUP", ABOX_ASSERTIONS_FIRSTTIME_BACKUP);
map.put("TBOX_ASSERTIONS", TBOX_ASSERTIONS);
map.put("TBOX_INFERENCES", TBOX_INFERENCES);
map.put("TBOX_UNION", TBOX_UNION);
map.put("TBOX_ASSERTIONS_FIRSTTIME_BACKUP", TBOX_ASSERTIONS_FIRSTTIME_BACKUP);
map.put("FULL_ASSERTIONS", FULL_ASSERTIONS);
map.put("FULL_INFERENCES", FULL_INFERENCES);
map.put("FULL_UNION", FULL_UNION);
map.put("APPLICATION_METADATA", APPLICATION_METADATA);
map.put("APPLICATION_METADATA_FIRSTTIME_BACKUP", APPLICATION_METADATA_FIRSTTIME_BACKUP);
map.put("USER_ACCOUNTS", USER_ACCOUNTS);
map.put("USER_ACCOUNTS_FIRSTTIME_BACKUP", USER_ACCOUNTS_FIRSTTIME_BACKUP);
map.put("DISPLAY", DISPLAY);
map.put("DISPLAY_FIRSTTIME_BACKUP", DISPLAY_FIRSTTIME_BACKUP);
map.put("DISPLAY_TBOX", DISPLAY_TBOX);
map.put("DISPLAY_TBOX_FIRSTTIME_BACKUP", DISPLAY_TBOX_FIRSTTIME_BACKUP);
map.put("DISPLAY_DISPLAY", DISPLAY_DISPLAY);
map.put("DISPLAY_DISPLAY_FIRSTTIME_BACKUP", DISPLAY_DISPLAY_FIRSTTIME_BACKUP);
return Collections.unmodifiableMap(map);
}

View file

@ -6,14 +6,6 @@ import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.DISPLAY;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.DISPLAY_DISPLAY;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.DISPLAY_TBOX;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.USER_ACCOUNTS;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.ABOX_ASSERTIONS_FIRSTTIME_BACKUP;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.TBOX_ASSERTIONS_FIRSTTIME_BACKUP;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.APPLICATION_METADATA_FIRSTTIME_BACKUP;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.USER_ACCOUNTS_FIRSTTIME_BACKUP;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.DISPLAY_FIRSTTIME_BACKUP;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.DISPLAY_TBOX_FIRSTTIME_BACKUP;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.DISPLAY_DISPLAY_FIRSTTIME_BACKUP;
import org.apache.jena.rdf.model.ModelMaker;
@ -26,10 +18,7 @@ public abstract class ConfigurationTripleSource implements TripleSource {
* add memory-mapping.
*/
protected static final String[] CONFIGURATION_MODELS = { DISPLAY,
DISPLAY_TBOX, DISPLAY_DISPLAY, USER_ACCOUNTS, ABOX_ASSERTIONS_FIRSTTIME_BACKUP,
TBOX_ASSERTIONS_FIRSTTIME_BACKUP, APPLICATION_METADATA_FIRSTTIME_BACKUP,
USER_ACCOUNTS_FIRSTTIME_BACKUP, DISPLAY_FIRSTTIME_BACKUP,
DISPLAY_TBOX_FIRSTTIME_BACKUP, DISPLAY_DISPLAY_FIRSTTIME_BACKUP };
DISPLAY_TBOX, DISPLAY_DISPLAY, USER_ACCOUNTS };
/**
* These decorators are added to a Configuration ModelMaker, regardless of

View file

@ -10,8 +10,6 @@ import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelChangedListener;
import org.apache.jena.rdf.model.RDFNode;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
/**
* Interface for API to write, read, and update Vitro's RDF store, with support
* to allow listening, logging and auditing.
@ -265,10 +263,4 @@ public interface RDFService {
* multiple invocations do not cause an error.
*/
public void close();
/**
* UQAM-Bug-Correction Useful among other things to transport the linguistic context in the service
* @param vitroRequest
*/
public void setVitroRequest(VitroRequest vitroRequest);
public VitroRequest getVitroRequest();
}

View file

@ -1,136 +0,0 @@
package edu.cornell.mannlib.vitro.webapp.rdfservice.adapters;
import org.apache.jena.graph.Capabilities;
import org.apache.jena.graph.Graph;
import org.apache.jena.graph.GraphEventManager;
import org.apache.jena.graph.GraphStatisticsHandler;
import org.apache.jena.graph.Node;
import org.apache.jena.graph.TransactionHandler;
import org.apache.jena.graph.Triple;
import org.apache.jena.shared.AddDeniedException;
import org.apache.jena.shared.DeleteDeniedException;
import org.apache.jena.shared.PrefixMapping;
import org.apache.jena.util.iterator.ExtendedIterator;
import edu.cornell.mannlib.vitro.webapp.utils.logging.ToString;
/**
* The base class for a delegating graph decorator.
*
* As implemented, all methods simply delegate to the inner graph. Subclasses
* should override selected methods to provide functionality.
*/
public abstract class AbstractGraphDecorator implements
Graph {
private final Graph inner;
protected AbstractGraphDecorator(Graph g) {
if (g == null) {
throw new IllegalArgumentException("g may not be null.");
}
this.inner = g;
}
@Override
public String toString() {
return ToString.simpleName(this) + "[" + ToString.hashHex(this)
+ ", inner=" + ToString.graphToString(inner) + "]";
}
@Override
public void add(Triple arg0) throws AddDeniedException {
inner.add(arg0);
}
@Override
public void clear() {
inner.clear();
}
@Override
public void close() {
inner.close();
}
@Override
public boolean contains(Triple arg0) {
return inner.contains(arg0);
}
@Override
public boolean contains(Node arg0, Node arg1, Node arg2) {
return inner.contains(arg0, arg1, arg2);
}
@Override
public void delete(Triple arg0) throws DeleteDeniedException {
inner.delete(arg0);
}
@Override
public boolean dependsOn(Graph arg0) {
return inner.dependsOn(arg0);
}
@Override
public ExtendedIterator<Triple> find(Triple arg0) {
return inner.find(arg0);
}
@Override
public ExtendedIterator<Triple> find(Node arg0, Node arg1, Node arg2) {
return inner.find(arg0, arg1, arg2);
}
@Override
public Capabilities getCapabilities() {
return inner.getCapabilities();
}
@Override
public GraphEventManager getEventManager() {
return inner.getEventManager();
}
@Override
public PrefixMapping getPrefixMapping() {
return inner.getPrefixMapping();
}
@Override
public GraphStatisticsHandler getStatisticsHandler() {
return inner.getStatisticsHandler();
}
@Override
public TransactionHandler getTransactionHandler() {
return inner.getTransactionHandler();
}
@Override
public boolean isClosed() {
return inner.isClosed();
}
@Override
public boolean isEmpty() {
return inner.isEmpty();
}
@Override
public boolean isIsomorphicWith(Graph arg0) {
return inner.isIsomorphicWith(arg0);
}
@Override
public void remove(Node arg0, Node arg1, Node arg2) {
inner.remove(arg0, arg1, arg2);
}
@Override
public int size() {
return inner.size();
}
}

View file

@ -54,7 +54,7 @@ public abstract class AbstractModelDecorator implements Model {
protected AbstractModelDecorator(Model m) {
if (m == null) {
throw new IllegalArgumentException("m may not be null.");
throw new NullPointerException("m may not be null.");
}
this.inner = m;
}
@ -325,11 +325,6 @@ public abstract class AbstractModelDecorator implements Model {
return inner.lock();
}
@Override
public boolean hasNoMappings() {
return inner.hasNoMappings();
}
@Override
public boolean samePrefixMappingAs(PrefixMapping other) {
return inner.samePrefixMappingAs(other);
@ -689,11 +684,6 @@ public abstract class AbstractModelDecorator implements Model {
return inner.createResource(uri);
}
@Override
public Resource createResource(Statement statement) {
return inner.createResource(statement);
}
@Override
public Property createProperty(String nameSpace, String localName) {
return inner.createProperty(nameSpace, localName);

View file

@ -364,11 +364,6 @@ public abstract class AbstractOntModelDecorator implements OntModel {
return inner.lock();
}
@Override
public boolean hasNoMappings() {
return inner.hasNoMappings();
}
@Override
public boolean samePrefixMappingAs(PrefixMapping other) {
return inner.samePrefixMappingAs(other);
@ -734,11 +729,6 @@ public abstract class AbstractOntModelDecorator implements OntModel {
return inner.createResource(uri);
}
@Override
public Resource createResource(Statement statement) {
return inner.createResource(statement);
}
@Override
public Property createProperty(String nameSpace, String localName) {
return inner.createProperty(nameSpace, localName);

View file

@ -1,36 +0,0 @@
package edu.cornell.mannlib.vitro.webapp.rdfservice.filter;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* A normalized list of languages/locales acceptable in results
* returned by language-filtering RDFServices, graphs, models, etc.
*/
public class AcceptableLanguages extends ArrayList<String>{
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(AcceptableLanguages.class);
/**
* Construct a normalized list of acceptable language strings
* from a set of raw language strings. For any values of form 'aa-BB',
* the base language ('aa') will be also added to the list.
* @param rawLanguageStrs may not be null
*/
public AcceptableLanguages(List<String> rawLanguageStrs) {
log.debug("Raw language strings:" + rawLanguageStrs);
for (String lang : rawLanguageStrs) {
this.add(lang);
String baseLang = lang.split("-")[0];
if (!lang.equals(baseLang) && !this.contains(baseLang)) {
this.add(baseLang);
}
}
log.debug("Normalized language strings:" + this);
}
}

View file

@ -9,7 +9,6 @@ import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.sparql.engine.binding.Binding;
import org.apache.jena.sparql.engine.binding.BindingUtils;
public class FilteredResultSet implements ResultSet {
@ -54,7 +53,7 @@ public class FilteredResultSet implements ResultSet {
@Override
public Binding nextBinding() {
return BindingUtils.asBinding(nextSolution());
throw new UnsupportedOperationException("Can we ignore this?");
}
@Override

View file

@ -1,78 +0,0 @@
package edu.cornell.mannlib.vitro.webapp.rdfservice.filter;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* A class for sorting language strings by acceptability according to a
* supplied list of language preferences.
* Refactored from LanguageFilteringRDFService for reuse by classes performing
* similar functions.
*/
public class LangSort {
private static final Log log = LogFactory.getLog(LangSort.class);
protected List<String> langs;
private int inexactMatchPenalty;
private int noLanguage;
private int noMatch;
/**
* Construct a language string sorter with a supplied list of preferred
* language strings
* @param preferredLanguageStrings list of preferred languages of form
* 'en-US', 'es', 'fr-CA'. May not be null.
*/
public LangSort(List<String> preferredLanguageStrings) {
this.langs = preferredLanguageStrings;
this.inexactMatchPenalty = langs.size();
// no language is worse than any inexact match (if the preferred list does not include "").
this.noLanguage = 2 * inexactMatchPenalty;
// no match is worse than no language.
this.noMatch = noLanguage + 1;
}
protected int compareLangs(String t1lang, String t2lang) {
int index1 = languageIndex(t1lang);
int index2 = languageIndex(t2lang);
if(index1 == index2) {
return t1lang.compareTo(t2lang);
} else {
return languageIndex(t1lang) - languageIndex(t2lang);
}
}
/**
* Return index of exact match, or index of partial match, or
* language-free, or no match.
*/
private int languageIndex(String lang) {
if (lang == null) {
lang = "";
}
int index = langs.indexOf(lang);
if (index >= 0) {
log.debug("languageIndex for '" + lang + "' is " + index);
return index;
}
if (lang.length() > 2) {
index = langs.indexOf(lang.substring(0, 2));
if (index >= 0) {
log.debug("languageIndex for '" + lang + "' is " + index + inexactMatchPenalty);
return index + inexactMatchPenalty;
}
}
if (lang.isEmpty()) {
log.debug("languageIndex for '" + lang + "' is " + noLanguage);
return noLanguage;
}
return noMatch;
}
}

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