Sprint i18n with main (#209)

* Layer uqam updates onto master (minus trailing whitespace)

* Update RDFServiceFactorySingle.java

* Sprint i18n whitespace (#143)

* Removed extraneous whitespace
   - modified:   api/src/main/java/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/BaseEditElementVTwo.java

* move RootUserPolicy.java from VIVO to Vitro repo.

* Remove blank line

* Fixed indentations

* Update whitespace for: TemplateProcessingHelper.java

* Update whitespace for: RDFServiceModel.java

* Removed extraneous whitespaces.

* Tagging UQAM Comments with following tags

-Add-Feature
-Optimization
-Linguistic-Management
-Bug-Correction

* Resolve compilation failures in Vitro tests

* Remove whitespace changes from SelectListGeneratorVTwo.java

* Add null check on field values of RDF Form (#158)

Resolves: https://jira.lyrasis.org/browse/VIVO-1800

Co-authored-by: Andrew Woods <awoods@duraspace.org>

* Fix incorrect tool-tip in language selection dropdown (#156)

Resolves: https://jira.lyrasis.org/browse/VIVO-1783

Co-authored-by: Andrew Woods <awoods@duraspace.org>

* Sprint i18n/lang filtering model (#159)

* Add language-aware graph filtering instead of layering on additional RDFService

Resolves: https://jira.lyrasis.org/browse/VIVO-1771

* Remove hardcoded link label (#161)

Resolves: https://jira.lyrasis.org/browse/VIVO-1779

* Enable filtering of non-enabled i18n language files from being loaded into triple store (#160)

Define name of available language listing file (found in Vitro-languages)
Update RDFFilesLoader method interfaces to include ServletContext

Part of resolution to: https://jira.lyrasis.org/browse/VIVO-1836

Co-authored-by: Andrew Woods <awoods@duraspace.org>

* Add i18n version of Edit page title (#157)

Related to: https://jira.lyrasis.org/browse/VIVO-1779

Co-authored-by: Andrew Woods <awoods@duraspace.org>

* Changing ontology extensions for n3 & assigning a base IRI to each (#163)

ontology

Co-authored-by: michelheon <heon@videotorn.ca>
Co-authored-by: Andrew Woods <awoods@duraspace.org>

https://jira.lyrasis.org/browse/VIVO-1862

* Update sprint-i18n with master branch (#166)

* Make data property richtext editor option selectable from UI

* [VIVO-1755] - Better error handling when reasoner disabled (#137)

* Better error handling when reasoner disabled

* Change reasoner error log message to debug

* Extend reasoner status error handling

* Improve reasoner error log message and extend to JenaAdminActions

* Bump up log level for admin action to 'warn' and edit admin panel error message

* Change Model writer lang from "N3-PP" to "N3" (#149)

Resolves: https://jira.lyrasis.org/browse/VIVO-1761

Co-authored-by: Andrew Woods <awoods@duraspace.org>

* [VIVO-1851] - Add 'remove' option to named graph management page (#162)

* Add 'remove' option to named graph management page

Resolves: https://jira.lyrasis.org/browse/VIVO-1851

* [VIVO-1872] - Add download option to SPARQL Query page (#164)

* Add download option to SPARQL Query page

* Set SPARQL query results content type even if downloading

* Address pull request comments

Co-authored-by: gneissone <mbgross@wustl.edu>
Co-authored-by: Ralph O'Flinn <roflinn@users.noreply.github.com>
Co-authored-by: Andrew Woods <awoods@duraspace.org>

* [VIVO-1839] - Use language name for selector instead of flags (#165)

* Use language name for selector instead of flags
* Add country name to language selector
* Increase min-width of language dropdown
* Update data tree comment in languageSelector.ftl
* Min-width for language dropdown
* Language dropdown css adjustment
* Capitalize locale label
* Indent on languageSelector.ftl

Resolves: https://jira.lyrasis.org/browse/VIVO-1839

* Adds internationalization to the admin/sparql-query page (#167)

* Adds internationalization to the admin/sparql-query page

Partial resolution of: https://jira.lyrasis.org/browse/VIVO-1873

* Add i18n for 'save query result'

Related to: https://jira.lyrasis.org/browse/VIVO-1873

* code review

Co-authored-by: Andrew Woods <awoods@duraspace.org>

* removed redundat files which are now available via Vitro- and VIVO-languages

* Making UQAM-optimization aware of https://

* Add parent reference to installer/pom.xml (#174)

Resolves: https://jira.lyrasis.org/browse/VIVO-1903

Co-authored-by: Andrew Woods <awoods@duraspace.org>

* Revert non-function RDF changes (#177)

Related to: https://jira.lyrasis.org/browse/VIVO-1905

Co-authored-by: Andrew Woods <awoods@duraspace.org>

* Ensure 'other' in Individual->Teaching->advisees->type is translated

Partial resolution to: https://jira.lyrasis.org/browse/VIVO-1881

* Re-add logic from commit 7420957

* [VIVO-1812] use i18n translation for validation messages (#179)

* replace constants with i18n text in BasicValidationVTwo
* use constants for i18n template key

Partial resolution of: https://jira.lyrasis.org/browse/VIVO-1812

* added js_string at i18n strings to handle quotes properly, ticket vivo-1842 (#180)

Partial resolution for: https://jira.lyrasis.org/browse/VIVO-1842

* [VIVO-1870] simplify and concat translation for browse by vclass (#182)

* simplify and concat translation for browse by vclass

Partial resolution of: https://jira.lyrasis.org/browse/VIVO-1870

* [VIVO-1900] i18n: added empty check for getCountry, fixing bug with spanish label (es) (#181)

* added empty check for getCountry, fixing bug with spanish label (es), ticket vivo-1900

Partial resolution to: https://jira.lyrasis.org/browse/VIVO-1900

* [VIVO 1870] update i18n key to JavaScript mapping (#183)

* update menupage-script i18n key to JavaScript mapping

Follow-on to resolution of: https://jira.lyrasis.org/browse/VIVO-1870

* [VIVO-1837] get i18n bundle from WebappDaoFactoryConfig preferred locales (#178)

* apply i18n text to VClassDaoJena.getLabelForClass
* expose i18n bundle through webapp dao factory interface
* use whole messages for i18n
* if request available use request bundle else use context bundle
* clear cache when context theme directory changes
* make getOverridingLocale from context private
* select locale based on preferred locale from webapp dao factory
* use first preferred local even when no selectable locales available on context
* build default preferred locales from default preferred languages

Resolves: https://jira.lyrasis.org/browse/VIVO-1837

* Ensure that "available langs" include base langs (#185)

Resolves: https://jira.lyrasis.org/browse/VIVO-1922

Co-authored-by: Andrew Woods <awoods@duraspace.org>

* Ensure I18nStub is initialized before pertinent tests (#186)

Resolves: https://jira.lyrasis.org/browse/VIVO-1923

Co-authored-by: Andrew Woods <awoods@duraspace.org>

* add additional null checks to ensure context is ready for theme change (#187)

* [VIVO-1915] i18n - Adding a label with language tag through the "new" manageLabelsForindividualAddForm.ftl does not take the setting for language tag (#184)

* Fixed bug when addng a label with language tag through managLabelsForindividualAddForm, re ticket VIVO-1915

* removed the language select for managing multi language labels, ticket vivo-1915

* readded the fix for language selection because of the fr-CA version of the manageLabelsForIndividualftl, ticket vivo-1915

* removed earlier fix, removed comments, modified ManageLabelGenrator, ticket vivo-1915

Partial resolution to: https://jira.lyrasis.org/browse/VIVO-1915

* - replaced hard coded "or"s with i18n().or

* [VIVO-1925] i18n: Editing labels results in new label (#188)

* fixed bug: Editing language labels results in new label, ticket vivo-1925

Resolves: https://jira.lyrasis.org/browse/VIVO-1925

* Enable lang selection without need for 'available-langs.properties' (#169)

* Enable lang selection without need for 'available-langs.properties'
Co-authored-by: Andrew Woods <awoods@duraspace.org>

* Reduce number of times QuerySolutions are looped in LanguageFilteringRDFService (#194)

- No functional change in this update

Resolves: https://jira.lyrasis.org/browse/VIVO-1931

Co-authored-by: Andrew Woods <awoods@duraspace.org>

* Prevent 'ProcessRdfForm.parseN3ToRDF' from using null linguisticContext (#197)

Resolves: https://jira.lyrasis.org/browse/VIVO-1944

Co-authored-by: Andrew Woods <awoods@duraspace.org>

* [Vivo 1918] i18n: Reload firsttime files on start-up if changed (#195)

Co-authored-by: Andrew Woods <awoods@lyrasis.org>

* [VIVO-1936] i18n: updated the language comment in runtime.properties

* ftl function to capitalize group name affording override

* Further i18n for BasicValidationVTwo.java

* Fixed DeletePropertyController.java - getting localname of property properly (#200)

* Fixed DeletePropertyController.java - getting localname of property properly

Resolves: https://jira.lyrasis.org/browse/VIVO-1816

* Removed hardcoded time units by properties calls in dateTimeWithPrecision.ftl

* Use i18n values for date time form (#204)

Resolves: https://jira.lyrasis.org/browse/VIVO-1953

* VIVO-1929: patch authorizing create individual form (#206)

* patch authorizing create individual form

Resolves: https://jira.lyrasis.org/browse/VIVO-1929

* Issue/vivo 1947 (#205)

* Make data property richtext editor option selectable from UI
* Better error handling when reasoner disabled
* Change reasoner error log message to debug
* Extend reasoner status error handling
* Improve reasoner error log message and extend to JenaAdminActions
* Bump up log level for admin action to 'warn' and edit admin panel error message
* Change Model writer lang from "N3-PP" to "N3" (#149)
* Prevent ontology editor and N3 editing from deleting property values in languages other than the one associated with the editing request. [https://jira.lyrasis.org/browse/VIVO-1947]

Resolves: https://jira.lyrasis.org/browse/VIVO-1947

Co-authored-by: gneissone <mbgross@wustl.edu>
Co-authored-by: Ralph O'Flinn <roflinn@users.noreply.github.com>
Co-authored-by: Andrew Woods <awoods@lyrasis.org>
Co-authored-by: Andrew Woods <awoods@duraspace.org>

* Remove comments

Co-authored-by: Andrew Woods <awoods@duraspace.org>
Co-authored-by: Nicolas D <46490666+nicalico@users.noreply.github.com>
Co-authored-by: VIVO UQAM <62542918+UQAM-VIVO@users.noreply.github.com>
Co-authored-by: Matthias Luehr <luehr@hs-mittweida.de>
Co-authored-by: michelheonuqam <heon.michel@uqam.ca>
Co-authored-by: Brian Lowe <brianjlowe@gmail.com>
Co-authored-by: j-dornbusch <joachim.dornbusch@ehess.fr>
Co-authored-by: Michel Heon <heon@videotron.ca>
Co-authored-by: gneissone <mbgross@wustl.edu>
Co-authored-by: Ralph O'Flinn <roflinn@users.noreply.github.com>
Co-authored-by: dofeldsc <dofeldsc@uos.de>
Co-authored-by: root <root@vivo-development.hs-mittweida.de>
Co-authored-by: gneissone <mbgross@unavco.org>
Co-authored-by: William Welling <wwelling@library.tamu.edu>
Co-authored-by: Kampe <Benjamin.Kampe@tib.eu>
Co-authored-by: Gross, Benjamin <benjamin.gross@clarivate.com>
Co-authored-by: matthiasluehr <60263380+matthiasluehr@users.noreply.github.com>
Co-authored-by: nicolasdickner <dickner.nicolas@uqam.ca>
This commit is contained in:
Andrew Woods 2021-02-10 12:04:01 -05:00 committed by GitHub
parent 28188e9719
commit eb949919b5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
175 changed files with 2748 additions and 2207 deletions

View file

@ -37,7 +37,14 @@ public class RootUserPolicy implements PolicyIface {
private static final Log log = LogFactory.getLog(RootUserPolicy.class); private static final Log log = LogFactory.getLog(RootUserPolicy.class);
private static final String PROPERTY_ROOT_USER_EMAIL = "rootUser.emailAddress"; 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 = "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. * This is the entire policy. If you are a root user, you are authorized.
@ -150,10 +157,12 @@ public class RootUserPolicy implements PolicyIface {
ua.setEmailAddress(configuredRootUser); ua.setEmailAddress(configuredRootUser);
ua.setFirstName("root"); ua.setFirstName("root");
ua.setLastName("user"); ua.setLastName("user");
// UQAM Add-Feature using getRootPasswordFromConfig()
ua.setArgon2Password(Authenticator.applyArgon2iEncoding( ua.setArgon2Password(Authenticator.applyArgon2iEncoding(
ROOT_USER_INITIAL_PASSWORD)); getRootPasswordFromConfig()));
ua.setMd5Password(""); ua.setMd5Password("");
ua.setPasswordChangeRequired(true); // UQAM Add-Feature using getRootPasswdChangeRequiredFromConfig()
ua.setPasswordChangeRequired(getRootPasswdChangeRequiredFromConfig().booleanValue());
ua.setStatus(Status.ACTIVE); ua.setStatus(Status.ACTIVE);
ua.setRootUser(true); ua.setRootUser(true);
@ -191,7 +200,31 @@ public class RootUserPolicy implements PolicyIface {
ss.warning(this, "For security, " ss.warning(this, "For security, "
+ "it is best to delete unneeded root user accounts."); + "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 @Override
public void contextDestroyed(ServletContextEvent sce) { public void contextDestroyed(ServletContextEvent sce) {
// Nothing to destroy // Nothing to destroy

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -3,6 +3,8 @@
package edu.cornell.mannlib.vitro.webapp.controller.freemarker; package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -42,6 +44,8 @@ public class BrowseController extends FreemarkerHttpServlet {
List<VClassGroup> groups = null; List<VClassGroup> groups = null;
VClassGroupsForRequest vcgc = VClassGroupCache.getVClassGroups(vreq); VClassGroupsForRequest vcgc = VClassGroupCache.getVClassGroups(vreq);
groups =vcgc.getGroups(); groups =vcgc.getGroups();
Collections.sort(groups, publicNameComparator);
// sortGroupListByPublicName(groups);
List<VClassGroupTemplateModel> vcgroups = new ArrayList<VClassGroupTemplateModel>(groups.size()); List<VClassGroupTemplateModel> vcgroups = new ArrayList<VClassGroupTemplateModel>(groups.size());
for (VClassGroup group : groups) { for (VClassGroup group : groups) {
vcgroups.add(new VClassGroupTemplateModel(group)); vcgroups.add(new VClassGroupTemplateModel(group));
@ -50,4 +54,35 @@ public class BrowseController extends FreemarkerHttpServlet {
return new TemplateResponseValues(templateName, body); 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

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

View file

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

View file

@ -4,6 +4,7 @@ package edu.cornell.mannlib.vitro.webapp.controller.json;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ArrayNode;
@ -15,6 +16,7 @@ import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.beans.Individual; import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao; 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;
import edu.cornell.mannlib.vitro.webapp.services.shortview.ShortViewService.ShortViewContext; import edu.cornell.mannlib.vitro.webapp.services.shortview.ShortViewService.ShortViewContext;
import edu.cornell.mannlib.vitro.webapp.services.shortview.ShortViewServiceSetup; import edu.cornell.mannlib.vitro.webapp.services.shortview.ShortViewServiceSetup;
@ -73,7 +75,11 @@ public class GetRandomSearchIndividualsByVClass extends GetSearchIndividualsByVC
modelMap.put("individual", modelMap.put("individual",
IndividualTemplateModelBuilder.build(individual, vreq)); IndividualTemplateModelBuilder.build(individual, vreq));
modelMap.put("vclass", vclassName); 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); ShortViewService svs = ShortViewServiceSetup.getService(ctx);
return svs.renderShortView(individual, ShortViewContext.BROWSE, return svs.renderShortView(individual, ShortViewContext.BROWSE,
modelMap, vreq); modelMap, vreq);

View file

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

View file

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

View file

@ -26,47 +26,34 @@ public class FauxPropertyDaoFiltering extends BaseFiltering implements FauxPrope
@Override @Override
public List<FauxProperty> getFauxPropertiesForBaseUri(String uri) { public List<FauxProperty> getFauxPropertiesForBaseUri(String uri) {
// TODO Auto-generated method stub return innerFauxPropertyDao.getFauxPropertiesForBaseUri(uri);
throw new RuntimeException(
"FauxPropertyDao.getFauxPropertiesForBaseUri() not implemented.");
} }
@Override @Override
public FauxProperty getFauxPropertyFromContextUri(String contextUri) { public FauxProperty getFauxPropertyFromContextUri(String contextUri) {
// TODO Auto-generated method stub return innerFauxPropertyDao.getFauxPropertyFromContextUri(contextUri);
throw new RuntimeException(
"FauxPropertyDaoFiltering.getFauxPropertyFromConfigContextUri() not implemented.");
} }
@Override @Override
public FauxProperty getFauxPropertyByUris(String domainUri, String baseUri, public FauxProperty getFauxPropertyByUris(String domainUri, String baseUri,
String rangeUri) { String rangeUri) {
// TODO Auto-generated method stub return innerFauxPropertyDao.getFauxPropertyByUris(domainUri, baseUri,
throw new RuntimeException( rangeUri);
"FauxPropertyDaoFiltering.getFauxPropertyByUris() not implemented.");
} }
@Override @Override
public void updateFauxProperty(FauxProperty fp) { public void updateFauxProperty(FauxProperty fp) {
// TODO Auto-generated method stub innerFauxPropertyDao.updateFauxProperty(fp);
throw new RuntimeException("FauxPropertyDaoFiltering.updateFauxProperty() not implemented.");
} }
@Override @Override
public void deleteFauxProperty(FauxProperty fp) { public void deleteFauxProperty(FauxProperty fp) {
// TODO Auto-generated method stub innerFauxPropertyDao.deleteFauxProperty(fp);
throw new RuntimeException("FauxPropertyDao.deleteFauxProperty() not implemented.");
} }
@Override @Override
public void insertFauxProperty(FauxProperty fp) { public void insertFauxProperty(FauxProperty fp) {
// TODO Auto-generated method stub innerFauxPropertyDao.insertFauxProperty(fp);
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; import edu.cornell.mannlib.vitro.webapp.edit.EditLiteral;
class IndividualDaoFiltering extends BaseFiltering implements IndividualDao{ public class IndividualDaoFiltering extends BaseFiltering implements IndividualDao{
IndividualDao innerIndividualDao; IndividualDao innerIndividualDao;
VitroFilters filters; 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.ObjectPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.filtering.filters.VitroFilters; import edu.cornell.mannlib.vitro.webapp.dao.filtering.filters.VitroFilters;
class ObjectPropertyDaoFiltering extends BaseFiltering implements ObjectPropertyDao{ public class ObjectPropertyDaoFiltering extends BaseFiltering implements ObjectPropertyDao{
final ObjectPropertyDao innerObjectPropertyDao; final ObjectPropertyDao innerObjectPropertyDao;
final VitroFilters filters; 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.ObjectPropertyStatementDao;
import edu.cornell.mannlib.vitro.webapp.dao.filtering.filters.VitroFilters; import edu.cornell.mannlib.vitro.webapp.dao.filtering.filters.VitroFilters;
class ObjectPropertyStatementDaoFiltering extends BaseFiltering implements ObjectPropertyStatementDao{ public class ObjectPropertyStatementDaoFiltering extends BaseFiltering implements ObjectPropertyStatementDao{
final ObjectPropertyStatementDao innerObjectPropertyStatementDao; final ObjectPropertyStatementDao innerObjectPropertyStatementDao;
final VitroFilters filters; final VitroFilters filters;

View file

@ -24,6 +24,7 @@ import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassGroupDao; import edu.cornell.mannlib.vitro.webapp.dao.VClassGroupDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.filtering.filters.VitroFilters; 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. * This wraps a WebappDaoFactory and applies filtering.
@ -276,4 +277,9 @@ public class WebappDaoFactoryFiltering implements WebappDaoFactory {
public void close() { public void close() {
innerWebappDaoFactory.close(); innerWebappDaoFactory.close();
} }
@Override
public I18nBundle getI18nBundle() {
return innerWebappDaoFactory.getI18nBundle();
}
} }

View file

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

View file

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

View file

@ -230,10 +230,9 @@ public class FauxPropertyDaoJena extends JenaBaseDao implements FauxPropertyDao
OBJECT_PROPERTY_DISPLAY_CONFIG); OBJECT_PROPERTY_DISPLAY_CONFIG);
addPropertyResourceURINotEmpty(config, PROPERTY_GROUP, addPropertyResourceURINotEmpty(config, PROPERTY_GROUP,
fp.getGroupURI()); fp.getGroupURI());
addPropertyStringValue(config, DISPLAY_NAME, fp.getDisplayName(), updatePlainLiteralValue(config, DISPLAY_NAME, fp.getDisplayName());
displayModel); updatePlainLiteralValue(config, PUBLIC_DESCRIPTION_ANNOT,
addPropertyStringValue(config, PUBLIC_DESCRIPTION_ANNOT, fp.getPublicDescription());
fp.getPublicDescription(), displayModel);
addPropertyIntValue(config, DISPLAY_RANK_ANNOT, addPropertyIntValue(config, DISPLAY_RANK_ANNOT,
fp.getDisplayTier(), displayModel); fp.getDisplayTier(), displayModel);
addPropertyIntValue(config, DISPLAY_LIMIT, fp.getDisplayLimit(), addPropertyIntValue(config, DISPLAY_LIMIT, fp.getDisplayLimit(),
@ -328,10 +327,10 @@ public class FauxPropertyDaoJena extends JenaBaseDao implements FauxPropertyDao
.getConfigUri()); .getConfigUri());
updatePropertyResourceURIValue(config, PROPERTY_GROUP, updatePropertyResourceURIValue(config, PROPERTY_GROUP,
fp.getGroupURI()); fp.getGroupURI());
updatePropertyStringValue(config, DISPLAY_NAME, updatePlainLiteralValue(config, DISPLAY_NAME,
fp.getDisplayName(), displayModel); fp.getDisplayName());
updatePropertyStringValue(config, PUBLIC_DESCRIPTION_ANNOT, updatePlainLiteralValue(config, PUBLIC_DESCRIPTION_ANNOT,
fp.getPublicDescription(), displayModel); fp.getPublicDescription());
updatePropertyIntValue(config, DISPLAY_RANK_ANNOT, updatePropertyIntValue(config, DISPLAY_RANK_ANNOT,
fp.getDisplayTier(), displayModel); fp.getDisplayTier(), displayModel);
updatePropertyIntValue(config, DISPLAY_LIMIT, fp.getDisplayLimit(), 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.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.Date; import java.util.Date;
import java.util.HashSet; import java.util.HashSet;
@ -14,14 +14,14 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; 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.datatypes.xsd.XSDDatatype;
import org.apache.jena.graph.Node; import org.apache.jena.graph.Node;
import org.apache.jena.graph.NodeFactory; 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.DatatypeProperty;
import org.apache.jena.ontology.ObjectProperty; import org.apache.jena.ontology.ObjectProperty;
import org.apache.jena.ontology.OntClass; import org.apache.jena.ontology.OntClass;
@ -39,6 +39,7 @@ import org.apache.jena.rdf.model.NodeIterator;
import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource; 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.Statement;
import org.apache.jena.rdf.model.StmtIterator; import org.apache.jena.rdf.model.StmtIterator;
import org.apache.jena.shared.Lock; import org.apache.jena.shared.Lock;
@ -754,21 +755,110 @@ public class JenaBaseDao extends JenaBaseDaoCon {
} }
/** /**
* convenience method for updating the RDFS label * 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.
*/ */
protected void updateRDFSLabel(OntResource ontRes, String label) { protected void updateRDFSLabel(OntResource ontRes, String lexicalForm) {
updatePlainLiteralValue(ontRes, RDFS.label, lexicalForm);
if (label != null && label.length() > 0) {
String existingValue = ontRes.getLabel(getDefaultLanguage());
if (existingValue == null || !existingValue.equals(label)) {
ontRes.setLabel(label, getDefaultLanguage());
} }
/**
* 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);
}
/**
* 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());
}
/**
* 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.");
}
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 { } else {
ontRes.removeAll(RDFS.label); // New literal already exists in the model.
// Do not add it again.
addNew = false;
} }
} }
}
}
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) { private Literal getLabel(String lang, List<RDFNode>labelList) {
for (RDFNode label : labelList) { for (RDFNode label : labelList) {
@ -780,6 +870,13 @@ public class JenaBaseDao extends JenaBaseDaoCon {
} }
if ((lang != null) && (lang.equals(labelLanguage))) { if ((lang != null) && (lang.equals(labelLanguage))) {
return labelLit; 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,6 +72,7 @@ public class MenuDaoJena extends JenaBaseDao implements MenuDao {
return getMenu( getOntModelSelector().getDisplayModel(), url ); return getMenu( getOntModelSelector().getDisplayModel(), url );
} }
@Override
public MainMenu getMainMenu( ServletRequest req, String url ) { public MainMenu getMainMenu( ServletRequest req, String url ) {
OntModel displayModel = LanguageFilteringUtils.wrapOntModelInALanguageFilter(getOntModelSelector().getDisplayModel(), req ); OntModel displayModel = LanguageFilteringUtils.wrapOntModelInALanguageFilter(getOntModelSelector().getDisplayModel(), req );
return getMenu(displayModel, url) ; return getMenu(displayModel, url) ;

View file

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

View file

@ -290,6 +290,11 @@ public class RDFServiceGraph implements GraphWithPerform {
literalBuff.append("\""); literalBuff.append("\"");
pyString(literalBuff, node.getLiteralLexicalForm()); pyString(literalBuff, node.getLiteralLexicalForm());
literalBuff.append("\""); 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())) { if (!StringUtils.isEmpty(node.getLiteralLanguage())) {
literalBuff.append("@").append(node.getLiteralLanguage()); literalBuff.append("@").append(node.getLiteralLanguage());
} else if (node.getLiteralDatatypeURI() != null) { } else if (node.getLiteralDatatypeURI() != null) {

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -28,6 +28,7 @@ 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.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.freemarker.config.FreemarkerConfiguration; 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;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess.LanguageOption;
import freemarker.template.Configuration; import freemarker.template.Configuration;
public class EditConfigurationUtils { public class EditConfigurationUtils {
@ -61,18 +62,24 @@ public class EditConfigurationUtils {
return vreq.getParameter("rangeUri"); return vreq.getParameter("rangeUri");
} }
public static String getTypeOfNew(VitroRequest vreq) {
return vreq.getParameter("typeOfNew");
}
public static VClass getRangeVClass(VitroRequest vreq) { 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( WebappDaoFactory ctxDaoFact = ModelAccess.on(
vreq.getSession().getServletContext()).getWebappDaoFactory(); vreq.getSession().getServletContext()).getWebappDaoFactory();
return ctxDaoFact.getVClassDao().getVClassByURI(getRangeUri(vreq)); return ctxDaoFact.getVClassDao().getVClassByURI(getRangeUri(vreq));
} }
//get individual 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) { public static Individual getSubjectIndividual(VitroRequest vreq) {
Individual subject = null; Individual subject = null;
String subjectUri = getSubjectUri(vreq); String subjectUri = getSubjectUri(vreq);
@ -122,12 +129,24 @@ public class EditConfigurationUtils {
public static ObjectProperty getObjectPropertyForPredicate(VitroRequest vreq, public static ObjectProperty getObjectPropertyForPredicate(VitroRequest vreq,
String predicateUri, String domainUri, String rangeUri) { String predicateUri, String domainUri, String rangeUri) {
WebappDaoFactory wdf = vreq.getWebappDaoFactory(); // WebappDaoFactory wdf = vreq.getWebappDaoFactory();
// UQAM-Linguistic-Management Use linguistic context
WebappDaoFactory wdf = ModelAccess.on(vreq).getWebappDaoFactory(LanguageOption.LANGUAGE_AWARE);
ObjectProperty objectProp = wdf.getObjectPropertyDao().getObjectPropertyByURIs( ObjectProperty objectProp = wdf.getObjectPropertyDao().getObjectPropertyByURIs(
predicateUri, domainUri, rangeUri); predicateUri, domainUri, rangeUri);
return objectProp; 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) { public static DataProperty getDataPropertyForPredicate(VitroRequest vreq, String predicateUri) {
WebappDaoFactory wdf = vreq.getWebappDaoFactory(); WebappDaoFactory wdf = vreq.getWebappDaoFactory();
//TODO: Check reason for employing unfiltered webapp dao factory and note if using a different version //TODO: Check reason for employing unfiltered webapp dao factory and note if using a different version
@ -205,6 +224,7 @@ public class EditConfigurationUtils {
return (op != null && dp == null); return (op != null && dp == null);
} }
private static boolean isVitroLabel(String predicateUri) { private static boolean isVitroLabel(String predicateUri) {
return predicateUri.equals(VitroVocabulary.LABEL); return predicateUri.equals(VitroVocabulary.LABEL);
} }

View file

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

View file

@ -10,23 +10,23 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle; import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; 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.Literal;
import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory; import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.XSD; 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.EditLiteral;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.i18n.I18n;
public class MultiValueEditSubmission { public class MultiValueEditSubmission {
@ -34,21 +34,31 @@ public class MultiValueEditSubmission {
private Map<String,List<Literal>> literalsFromForm ; private Map<String,List<Literal>> literalsFromForm ;
private Map<String,List<String>> urisFromForm ; private Map<String,List<String>> urisFromForm ;
private Map<String,String> validationErrors; private Map<String,String> validationErrors;
private BasicValidationVTwo basicValidation; private BasicValidationVTwo basicValidation;
private Map<String, List<FileItem>> filesFromForm;
private static Model literalCreationModel; private static Model literalCreationModel;
private String entityToReturnTo; private String entityToReturnTo;
private VitroRequest _vreq;
private static final String TIME_URI = XSD.time.getURI();
static{ static{
literalCreationModel = ModelFactory.createDefaultModel(); literalCreationModel = ModelFactory.createDefaultModel();
} }
/*
public MultiValueEditSubmission(Map<String,String[]> queryParameters, EditConfigurationVTwo editConfig){ * 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();
if( editConfig == null ) if( editConfig == null )
throw new Error("EditSubmission needs an EditConfiguration"); throw new Error("EditSubmission needs an EditConfiguration");
this.editKey = editConfig.getEditKey(); this.editKey = editConfig.getEditKey();
@ -92,11 +102,12 @@ public class MultiValueEditSubmission {
processEditElementFields(editConfig,queryParameters); processEditElementFields(editConfig,queryParameters);
//Incorporating basic validation //Incorporating basic validation
//Validate URIS //Validate URIS
this.basicValidation = new BasicValidationVTwo(editConfig, this); this.basicValidation = new BasicValidationVTwo(editConfig, I18n.bundle(vreq));
Map<String,String> errors = basicValidation.validateUris( urisFromForm ); Map<String,String> errors = basicValidation.validateUris( urisFromForm );
//Validate literals and add errors to the list of existing errors //Validate literals and add errors to the list of existing errors
errors.putAll(basicValidation.validateLiterals( literalsFromForm )); errors.putAll(basicValidation.validateLiterals( literalsFromForm ));
if( errors != null ) { // UQAM Add empty contition
if( errors != null && !errors.isEmpty()) {
validationErrors.putAll( errors); validationErrors.putAll( errors);
} }
@ -141,9 +152,8 @@ public class MultiValueEditSubmission {
} }
} }
} }
/* maybe this could be static */ /* maybe this could be static */
public Literal createLiteral(String value, String datatypeUri, String lang) { public Literal createLiteral_ORIG(String value, String datatypeUri, String lang) {
if( datatypeUri != null ){ if( datatypeUri != null ){
if( "http://www.w3.org/2001/XMLSchema:anyURI".equals(datatypeUri) ){ if( "http://www.w3.org/2001/XMLSchema:anyURI".equals(datatypeUri) ){
try { try {
@ -159,12 +169,27 @@ public class MultiValueEditSubmission {
return ResourceFactory.createPlainLiteral(value); return ResourceFactory.createPlainLiteral(value);
} }
private static final String DATE_TIME_URI = XSD.dateTime.getURI(); /* maybe this could be static */
private static final String DATE_URI = XSD.date.getURI(); public Literal createLiteral(String value, String datatypeUri, String lang) {
private static final String TIME_URI = XSD.time.getURI(); if( datatypeUri != null && !datatypeUri.isEmpty() ){
// UQAM Original code contained tow-dots ':' in place of '#'
private static DateTimeFormatter dformater = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:00"); // if( "http://www.w3.org/2001/XMLSchema:anyURI".equals(datatypeUri) ){
private static DateTimeFormatter dateFormater = DateTimeFormat.forPattern("yyyy-MM-dd"); 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);
}
public Map<String,String> getValidationErrors(){ public Map<String,String> getValidationErrors(){
return validationErrors; return validationErrors;
@ -264,12 +289,46 @@ public class MultiValueEditSubmission {
for(String value:valueList) { for(String value:valueList) {
value = N3EditUtils.stripInvalidXMLChars(value); value = N3EditUtils.stripInvalidXMLChars(value);
//Add to array of literals corresponding to this variable //Add to array of literals corresponding to this variable
/* UQAM OLD
if (!StringUtils.isEmpty(value)) { if (!StringUtils.isEmpty(value)) {
literalsArray.add(createLiteral( literalsArray.add(createLiteral(
value, value,
field.getRangeDatatypeUri(), field.getRangeDatatypeUri(),
field.getRangeLang())); 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); literalsFromForm.put(var, literalsArray);

View file

@ -9,15 +9,24 @@ import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.ontology.OntModel; import org.apache.jena.ontology.OntModel;
import org.apache.jena.rdf.model.Literal; import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory; 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.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.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.InsertException; import edu.cornell.mannlib.vitro.webapp.dao.InsertException;
@ -41,6 +50,7 @@ public class ProcessRdfForm {
private EditN3GeneratorVTwo populator; private EditN3GeneratorVTwo populator;
private Map<String,String> urisForNewResources = null; private Map<String,String> urisForNewResources = null;
// private VitroRequest _vreq;
/** /**
* Construct the ProcessRdfForm object. * Construct the ProcessRdfForm object.
*/ */
@ -76,9 +86,9 @@ public class ProcessRdfForm {
AdditionsAndRetractions changes; AdditionsAndRetractions changes;
if( configuration.isUpdate() ){ if( configuration.isUpdate() ){
changes = editExistingStatements(configuration, submission); changes = editExistingStatements(configuration, submission, vreq); //UQAM vreq for getting linguistic context
} else { } else {
changes = createNewStatements(configuration, submission ); changes = createNewStatements(configuration, submission, vreq ); //UQAM vreq for getting linguistic context
} }
changes = getMinimalChanges(changes); changes = getMinimalChanges(changes);
@ -99,12 +109,15 @@ public class ProcessRdfForm {
* any optional N3 is to originally configure the * any optional N3 is to originally configure the
* configuration.setN3Optional() to be empty. * configuration.setN3Optional() to be empty.
* *
* UQAM add vreq for linguistic context managing
*
* @throws Exception May throw an exception if the required N3 * @throws Exception May throw an exception if the required N3
* does not parse. * does not parse.
*
*/ */
private AdditionsAndRetractions createNewStatements( private AdditionsAndRetractions createNewStatements(
EditConfigurationVTwo configuration, EditConfigurationVTwo configuration,
MultiValueEditSubmission submission) throws Exception { MultiValueEditSubmission submission, VitroRequest vreq) throws Exception {
log.debug("in createNewStatements()" ); log.debug("in createNewStatements()" );
//getN3Required and getN3Optional will return copies of the //getN3Required and getN3Optional will return copies of the
@ -113,10 +126,10 @@ public class ProcessRdfForm {
List<String> optionalN3 = configuration.getN3Optional(); List<String> optionalN3 = configuration.getN3Optional();
/* substitute in the form values and existing values */ /* substitute in the form values and existing values */
subInValuesToN3( configuration, submission, requiredN3, optionalN3, null , null); subInValuesToN3( configuration, submission, requiredN3, optionalN3, null , null, vreq);
/* parse N3 to RDF Models, No retractions since all of the statements are new. */ /* parse N3 to RDF Models, No retractions since all of the statements are new. */
return parseN3ToChange(requiredN3, optionalN3, null, null); return parseN3ToChange(requiredN3, optionalN3, null, null, vreq, null);
} }
/* for a list of N3 strings, substitute in the subject, predicate and object URIs /* for a list of N3 strings, substitute in the subject, predicate and object URIs
@ -140,10 +153,12 @@ public class ProcessRdfForm {
* retractions are mutually diff'ed before statements are added to or * retractions are mutually diff'ed before statements are added to or
* removed from the model. The explicit change check can cause problems in * removed from the model. The explicit change check can cause problems in
* more complex setups, like the automatic form building in DataStaR. * more complex setups, like the automatic form building in DataStaR.
* @param vreq For getting linguistic context
*/ */
protected AdditionsAndRetractions editExistingStatements( protected AdditionsAndRetractions editExistingStatements(
EditConfigurationVTwo editConfig, EditConfigurationVTwo editConfig,
MultiValueEditSubmission submission) throws Exception { MultiValueEditSubmission submission, VitroRequest vreq) throws Exception {
log.debug("editing an existing resource: " + editConfig.getObject() ); log.debug("editing an existing resource: " + editConfig.getObject() );
@ -156,18 +171,18 @@ public class ProcessRdfForm {
subInValuesToN3(editConfig, submission, subInValuesToN3(editConfig, submission,
N3RequiredAssert, N3OptionalAssert, N3RequiredAssert, N3OptionalAssert,
N3RequiredRetract, N3OptionalRetract); N3RequiredRetract, N3OptionalRetract, vreq);
return parseN3ToChange( return parseN3ToChange(
N3RequiredAssert,N3OptionalAssert, N3RequiredAssert,N3OptionalAssert,
N3RequiredRetract, N3OptionalRetract); N3RequiredRetract, N3OptionalRetract, vreq, editConfig);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
protected void subInValuesToN3( protected void subInValuesToN3(
EditConfigurationVTwo editConfig, MultiValueEditSubmission submission, EditConfigurationVTwo editConfig, MultiValueEditSubmission submission,
List<String> requiredAsserts, List<String> optionalAsserts, List<String> requiredAsserts, List<String> optionalAsserts,
List<String> requiredRetracts, List<String> optionalRetracts ) throws InsertException{ List<String> requiredRetracts, List<String> optionalRetracts, VitroRequest vreq ) throws InsertException{
//need to substitute into the return to URL becase it may need new resource URIs //need to substitute into the return to URL becase it may need new resource URIs
List<String> URLToReturnTo = Arrays.asList(submission.getEntityToReturnTo()); List<String> URLToReturnTo = Arrays.asList(submission.getEntityToReturnTo());
@ -184,7 +199,41 @@ public class ProcessRdfForm {
//Retractions does NOT get values from form. //Retractions does NOT get values from form.
/* ******** Form submission Literals *********** */ /* ******** Form submission Literals *********** */
substituteInMultiLiterals( submission.getLiteralsFromForm(), requiredAsserts, optionalAsserts, URLToReturnTo); /*
* 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);
logSubstitue( "Added form Literals", requiredAsserts, optionalAsserts, requiredRetracts, optionalRetracts); logSubstitue( "Added form Literals", requiredAsserts, optionalAsserts, requiredRetracts, optionalRetracts);
//Retractions does NOT get values from form. //Retractions does NOT get values from form.
@ -254,20 +303,106 @@ public class ProcessRdfForm {
protected AdditionsAndRetractions parseN3ToChange( protected AdditionsAndRetractions parseN3ToChange(
List<String> requiredAdds, List<String> optionalAdds, List<String> requiredAdds, List<String> optionalAdds,
List<String> requiredDels, List<String> optionalDels) throws Exception{ List<String> requiredDels, List<String> optionalDels, VitroRequest vreq, EditConfigurationVTwo editConfig) throws Exception{
List<Model> adds = parseN3ToRDF(requiredAdds, REQUIRED); List<Model> adds = parseN3ToRDF(requiredAdds, REQUIRED);
adds.addAll( parseN3ToRDF(optionalAdds, OPTIONAL)); adds.addAll( parseN3ToRDF(optionalAdds, OPTIONAL));
List<Model> retracts = new ArrayList<Model>(); List<Model> retracts = new ArrayList<Model>();
if( requiredDels != null && optionalDels != null ){ if( requiredDels != null && optionalDels != null ){
retracts.addAll( parseN3ToRDF(requiredDels, REQUIRED) ); String lingCxt=null;
retracts.addAll( parseN3ToRDF(optionalDels, OPTIONAL) ); //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) );
} }
return new AdditionsAndRetractions(adds,retracts); 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. * Parse the n3Strings to a List of RDF Model objects.
* *

View file

@ -7,6 +7,7 @@ import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import edu.cornell.mannlib.vitro.webapp.i18n.I18nBundle;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -40,7 +41,8 @@ public class ChildVClassesOptions implements FieldOptions {
public Map<String, String> getOptions( public Map<String, String> getOptions(
EditConfigurationVTwo editConfig, EditConfigurationVTwo editConfig,
String fieldName, String fieldName,
WebappDaoFactory wDaoFact) throws Exception{ WebappDaoFactory wDaoFact,
I18nBundle i18n) throws Exception{
// now create an empty HashMap to populate and return // now create an empty HashMap to populate and return
HashMap <String,String> optionsMap = new LinkedHashMap<String,String>(); 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$ */ /* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields;
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
@ -15,6 +15,7 @@ import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao; import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.i18n.I18nBundle;
public class ChildVClassesWithParent implements FieldOptions { public class ChildVClassesWithParent implements FieldOptions {
@ -37,20 +38,24 @@ public class ChildVClassesWithParent implements FieldOptions {
return this; return this;
} }
@Override /*
* 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
*/
public Map<String, String> getOptions( public Map<String, String> getOptions(
EditConfigurationVTwo editConfig, EditConfigurationVTwo editConfig,
String fieldName, String fieldName,
WebappDaoFactory wDaoFact) throws Exception { WebappDaoFactory wDaoFact,
I18nBundle i18n) throws Exception {
HashMap <String,String> optionsMap = new LinkedHashMap<String,String>(); 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 // first test to see whether there's a default "leave blank" value specified with the literal options
if ( ! StringUtils.isEmpty( defaultOptionLabel ) ){ if ( ! StringUtils.isEmpty( defaultOptionLabel ) ){
optionsMap.put(LEFT_BLANK, defaultOptionLabel); optionsMap.put(LEFT_BLANK, defaultOptionLabel);
} }
String other_i18n = i18n.text("other");
optionsMap.put(classUri, "Other"); // first character in capital
optionsMap.put(classUri, other_i18n.substring(0, 1).toUpperCase() + other_i18n.substring(1));
VClassDao vclassDao = wDaoFact.getVClassDao(); VClassDao vclassDao = wDaoFact.getVClassDao();
List<String> subClassList = vclassDao.getAllSubClassURIs(classUri); List<String> subClassList = vclassDao.getAllSubClassURIs(classUri);
if (subClassList != null && subClassList.size() > 0) { if (subClassList != null && subClassList.size() > 0) {

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -11,6 +11,8 @@ import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; 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.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -25,7 +27,8 @@ public class SelectListGeneratorVTwo {
public static Map<String,String> getOptions( public static Map<String,String> getOptions(
EditConfigurationVTwo editConfig, EditConfigurationVTwo editConfig,
String fieldName, String fieldName,
WebappDaoFactory wDaoFact){ WebappDaoFactory wDaoFact,
I18nBundle i18n){
if( editConfig == null ){ if( editConfig == null ){
@ -48,7 +51,45 @@ public class SelectListGeneratorVTwo {
} }
try { try {
return field.getFieldOptions().getOptions(editConfig,fieldName,wDaoFact); 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));
} catch (Exception e) { } catch (Exception e) {
log.error("Error runing getFieldOptionis()",e); log.error("Error runing getFieldOptionis()",e);
return Collections.emptyMap(); return Collections.emptyMap();

View file

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

View file

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

View file

@ -224,6 +224,20 @@ public class ManageLabelsForIndividualGenerator extends BaseEditConfigurationGen
config.addFormSpecificData("displayRemoveLink", (numberExistingLabels > 1)); 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 //How do we edit? Will need to see
config.addFormSpecificData("deleteWebpageUrl", "/edit/primitiveDelete"); config.addFormSpecificData("deleteWebpageUrl", "/edit/primitiveDelete");

View file

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

View file

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

View file

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

@ -11,6 +11,7 @@ import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.jena.ontology.OntModel; import org.apache.jena.ontology.OntModel;
@ -70,6 +71,10 @@ public class EditRequestDispatchController extends FreemarkerHttpServlet {
@Override @Override
protected AuthorizationRequest requiredActions(VitroRequest vreq) { protected AuthorizationRequest requiredActions(VitroRequest vreq) {
// If request is for new individual, return simple do back end editing action permission
if (StringUtils.isNotEmpty(EditConfigurationUtils.getTypeOfNew(vreq))) {
return SimplePermission.DO_BACK_END_EDITING.ACTION;
}
// Check if this statement can be edited here and return unauthorized if not // Check if this statement can be edited here and return unauthorized if not
String subjectUri = EditConfigurationUtils.getSubjectUri(vreq); String subjectUri = EditConfigurationUtils.getSubjectUri(vreq);
String predicateUri = EditConfigurationUtils.getPredicateUri(vreq); String predicateUri = EditConfigurationUtils.getPredicateUri(vreq);
@ -148,7 +153,7 @@ public class EditRequestDispatchController extends FreemarkerHttpServlet {
templateData.put("editConfiguration", etm); templateData.put("editConfiguration", etm);
templateData.put("editSubmission", submissionTemplateModel); templateData.put("editSubmission", submissionTemplateModel);
//Corresponding to original note for consistency with selenium tests and 1.1.1 //Corresponding to original note for consistency with selenium tests and 1.1.1
templateData.put("title", "Edit"); templateData.put("title", etm.getPageTitle());
templateData.put("submitUrl", getSubmissionUrl(vreq)); templateData.put("submitUrl", getSubmissionUrl(vreq));
templateData.put("cancelUrl", etm.getCancelUrl()); templateData.put("cancelUrl", etm.getCancelUrl());
templateData.put("editKey", editConfig.getEditKey()); templateData.put("editKey", editConfig.getEditKey());

View file

@ -76,7 +76,9 @@ public class PostEditCleanupController extends FreemarkerHttpServlet{
if( entityToReturnTo == null ){ if( entityToReturnTo == null ){
// this will not work if there entityToReturnTo has a new resource URI, // 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 // in that case entityToReturnTo should not have been passed to this method as null
MultiValueEditSubmission submission = new MultiValueEditSubmission(vreq.getParameterMap(), editConfig); // UQAM-Linguistic-Management
// MultiValueEditSubmission submission = new MultiValueEditSubmission(vreq.getParameterMap(), editConfig);
MultiValueEditSubmission submission = new MultiValueEditSubmission(vreq, editConfig);
entityToReturnTo = N3EditUtils.processEntityToReturnTo(editConfig, submission, vreq); entityToReturnTo = N3EditUtils.processEntityToReturnTo(editConfig, submission, vreq);
} }

View file

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

View file

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

View file

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

View file

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

View file

@ -8,6 +8,7 @@ import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.MissingResourceException; import java.util.MissingResourceException;
import java.util.Objects;
import java.util.ResourceBundle; import java.util.ResourceBundle;
import java.util.SortedSet; import java.util.SortedSet;
import java.util.TreeSet; import java.util.TreeSet;
@ -20,7 +21,9 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; 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.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.DeveloperSettings;
import edu.cornell.mannlib.vitro.webapp.utils.developer.Key; import edu.cornell.mannlib.vitro.webapp.utils.developer.Key;
@ -49,12 +52,27 @@ public class I18n {
* This is where the work gets done. Not declared final, so it can be * This is where the work gets done. Not declared final, so it can be
* modified in unit tests. * modified in unit tests.
*/ */
private static I18n instance = new I18n(); private static I18n instance;
private final ServletContext ctx;
protected I18n(ServletContext ctx) {
this.ctx = ctx;
}
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
// Static methods // 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. * A convenience method to get a bundle and format the text.
*/ */
@ -72,19 +90,26 @@ public class I18n {
} }
/** /**
* Get a I18nBundle by this name. * Get a request I18nBundle by this name.
*/ */
public static I18nBundle bundle(String bundleName, HttpServletRequest req) { public static I18nBundle bundle(String bundleName, HttpServletRequest req) {
return instance.getBundle(bundleName, req); return instance.getBundle(bundleName, req);
} }
/** /**
* Get the default I18nBundle. * Get the default request I18nBundle.
*/ */
public static I18nBundle bundle(HttpServletRequest req) { public static I18nBundle bundle(HttpServletRequest req) {
return instance.getBundle(DEFAULT_BUNDLE_NAME, 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 // The instance
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
@ -106,25 +131,59 @@ public class I18n {
* Declared 'protected' so it can be overridden in unit tests. * Declared 'protected' so it can be overridden in unit tests.
*/ */
protected I18nBundle getBundle(String bundleName, HttpServletRequest req) { protected I18nBundle getBundle(String bundleName, HttpServletRequest req) {
log.debug("Getting bundle '" + bundleName + "'"); log.debug("Getting request bundle '" + bundleName + "'");
I18nLogger i18nLogger = new I18nLogger();
try {
checkDevelopmentMode(req); checkDevelopmentMode(req);
checkForChangeInThemeDirectory(req); checkForChangeInThemeDirectory(req);
String dir = themeDirectory.get(); Locale locale = req.getLocale();
ServletContext ctx = req.getSession().getServletContext();
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();
ResourceBundle.Control control = new ThemeBasedControl(ctx, dir); ResourceBundle.Control control = new ThemeBasedControl(ctx, dir);
ResourceBundle rb = ResourceBundle.getBundle(bundleName, ResourceBundle rb = ResourceBundle.getBundle(bundleName,
req.getLocale(), control); locale, control);
return new I18nBundle(bundleName, rb, i18nLogger); return new I18nBundle(bundleName, rb, i18nLogger);
} catch (MissingResourceException e) { } catch (MissingResourceException e) {
log.warn("Didn't find text bundle '" + bundleName + "'"); log.warn("Didn't find text bundle '" + bundleName + "'");
return I18nBundle.emptyBundle(bundleName, i18nLogger); return I18nBundle.emptyBundle(bundleName, i18nLogger);
} catch (Exception e) { } catch (Exception e) {
log.error("Failed to create text bundle '" + bundleName + "'", e); log.error("Failed to create text bundle '" + bundleName + "'", e);
return I18nBundle.emptyBundle(bundleName, i18nLogger); return I18nBundle.emptyBundle(bundleName, i18nLogger);
} }
} }
@ -139,6 +198,16 @@ 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 * If the theme directory has changed from before, clear the cache of all
* ResourceBundles. * ResourceBundles.
@ -153,6 +222,30 @@ 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. */ /** Only clear the cache one time per request. */
private void clearCacheOnRequest(HttpServletRequest req) { private void clearCacheOnRequest(HttpServletRequest req) {
if (req.getAttribute(ATTRIBUTE_CACHE_CLEARED) != null) { if (req.getAttribute(ATTRIBUTE_CACHE_CLEARED) != null) {

View file

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

View file

@ -14,6 +14,7 @@ import org.apache.commons.lang3.LocaleUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties; import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties;
import edu.cornell.mannlib.vitro.webapp.i18n.I18n;
import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus; import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus;
/** /**
@ -48,6 +49,10 @@ public class LocaleSelectionSetup implements ServletContextListener {
ss = StartupStatus.getBean(ctx); ss = StartupStatus.getBean(ctx);
props = ConfigurationProperties.getBean(sce); 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(); readProperties();
if (isForcing() && hasSelectables()) { if (isForcing() && hasSelectables()) {

View file

@ -1,58 +0,0 @@
/* $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,6 +6,8 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -61,13 +63,10 @@ public abstract class SelectedLocale {
ServletContext ctx = session.getServletContext(); ServletContext ctx = session.getServletContext();
Object ctxInfo = ctx.getAttribute(ATTRIBUTE_NAME); Object ctxInfo = ctx.getAttribute(ATTRIBUTE_NAME);
if (ctxInfo instanceof ContextSelectedLocale) {
Locale forcedLocale = ((ContextSelectedLocale) ctxInfo) Optional<Locale> forcedLocale = getForcedLocale(ctxInfo);
.getForcedLocale(); if (forcedLocale.isPresent()) {
if (forcedLocale != null) { return forcedLocale.get();
log.debug("Found forced locale in the context: " + forcedLocale);
return forcedLocale;
}
} }
Object sessionInfo = session.getAttribute(ATTRIBUTE_NAME); Object sessionInfo = session.getAttribute(ATTRIBUTE_NAME);
@ -95,6 +94,49 @@ public abstract class SelectedLocale {
return null; return null;
} }
/**
* 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;
}
return null;
}
/** /**
* Get the current Locale to use, which is the first of these to be found: * Get the current Locale to use, which is the first of these to be found:
* <ul> * <ul>
@ -121,6 +163,42 @@ public abstract class SelectedLocale {
return Locale.getDefault(); 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 * 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. * easily build the selection panel in the GUI. Clears any forced locale.

View file

@ -13,20 +13,27 @@ public class ModelNames {
public static final String ABOX_ASSERTIONS = "http://vitro.mannlib.cornell.edu/default/vitro-kb-2"; 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_INFERENCES = "http://vitro.mannlib.cornell.edu/default/vitro-kb-inf";
public static final String ABOX_UNION = "vitro:aboxOntModel"; 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_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_INFERENCES = "http://vitro.mannlib.cornell.edu/default/inferred-tbox";
public static final String TBOX_UNION = "vitro:tboxOntModel"; 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_ASSERTIONS = "vitro:baseOntModel";
public static final String FULL_INFERENCES = "vitro:inferenceOntModel"; public static final String FULL_INFERENCES = "vitro:inferenceOntModel";
public static final String FULL_UNION = "vitro:jenaOntModel"; 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 = "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 = "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 = "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 = "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 = "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 * A map of the URIS, keyed by their short names, intended only for display
@ -39,17 +46,24 @@ public class ModelNames {
map.put("ABOX_ASSERTIONS", ABOX_ASSERTIONS); map.put("ABOX_ASSERTIONS", ABOX_ASSERTIONS);
map.put("ABOX_INFERENCES", ABOX_INFERENCES); map.put("ABOX_INFERENCES", ABOX_INFERENCES);
map.put("ABOX_UNION", ABOX_UNION); 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_ASSERTIONS", TBOX_ASSERTIONS);
map.put("TBOX_INFERENCES", TBOX_INFERENCES); map.put("TBOX_INFERENCES", TBOX_INFERENCES);
map.put("TBOX_UNION", TBOX_UNION); 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_ASSERTIONS", FULL_ASSERTIONS);
map.put("FULL_INFERENCES", FULL_INFERENCES); map.put("FULL_INFERENCES", FULL_INFERENCES);
map.put("FULL_UNION", FULL_UNION); map.put("FULL_UNION", FULL_UNION);
map.put("APPLICATION_METADATA", APPLICATION_METADATA); 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", USER_ACCOUNTS);
map.put("USER_ACCOUNTS_FIRSTTIME_BACKUP", USER_ACCOUNTS_FIRSTTIME_BACKUP);
map.put("DISPLAY", DISPLAY); map.put("DISPLAY", DISPLAY);
map.put("DISPLAY_FIRSTTIME_BACKUP", DISPLAY_FIRSTTIME_BACKUP);
map.put("DISPLAY_TBOX", DISPLAY_TBOX); 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", DISPLAY_DISPLAY);
map.put("DISPLAY_DISPLAY_FIRSTTIME_BACKUP", DISPLAY_DISPLAY_FIRSTTIME_BACKUP);
return Collections.unmodifiableMap(map); return Collections.unmodifiableMap(map);
} }

View file

@ -202,7 +202,7 @@ public class RequestModelAccessImpl implements RequestModelAccess {
@Override @Override
public OntModel getOntModel(String name, LanguageOption... options) { public OntModel getOntModel(String name, LanguageOption... options) {
return getOntModel(new OntModelKey(name, options)); return addLanguageAwareness(getOntModel(new OntModelKey(name, options)));
} }
private OntModel getOntModel(OntModelKey key) { private OntModel getOntModel(OntModelKey key) {

View file

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

View file

@ -10,6 +10,8 @@ import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelChangedListener; import org.apache.jena.rdf.model.ModelChangedListener;
import org.apache.jena.rdf.model.RDFNode; 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 * Interface for API to write, read, and update Vitro's RDF store, with support
* to allow listening, logging and auditing. * to allow listening, logging and auditing.
@ -263,4 +265,10 @@ public interface RDFService {
* multiple invocations do not cause an error. * multiple invocations do not cause an error.
*/ */
public void close(); 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

@ -0,0 +1,136 @@
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) { protected AbstractModelDecorator(Model m) {
if (m == null) { if (m == null) {
throw new NullPointerException("m may not be null."); throw new IllegalArgumentException("m may not be null.");
} }
this.inner = m; this.inner = m;
} }

View file

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

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

View file

@ -0,0 +1,104 @@
package edu.cornell.mannlib.vitro.webapp.rdfservice.filter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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;
/**
* A filter of literal statements from Models according to language preferences.
*/
public class LanguageFilterModel {
private static final Log log = LogFactory.getLog(LanguageFilterModel.class);
/**
*
* @param m the model to filter. May not be null.
* @param langs list of strings of type 'en-US'. May not be null.
* @return model with language-inappropriate literal statements filtered out.
*/
public Model filterModel(Model m, List<String> langs) {
log.debug("filterModel");
List<Statement> retractions = new ArrayList<Statement>();
StmtIterator stmtIt = m.listStatements();
while (stmtIt.hasNext()) {
Statement stmt = stmtIt.nextStatement();
if (stmt.getObject().isLiteral()) {
List<Statement> candidatesForRemoval = m.listStatements(
stmt.getSubject(), stmt.getPredicate(), (RDFNode) null).toList();
if (candidatesForRemoval.size() == 1) {
continue;
}
candidatesForRemoval.sort(new StatementSortByLang(langs));
log.debug("sorted statements: " + showSortedStatements(candidatesForRemoval));
Iterator<Statement> candIt = candidatesForRemoval.iterator();
String langRegister = null;
boolean chuckRemaining = false;
while(candIt.hasNext()) {
Statement s = candIt.next();
if (!s.getObject().isLiteral()) {
continue;
} else if (chuckRemaining) {
retractions.add(s);
}
String lang = s.getObject().asLiteral().getLanguage();
if (langRegister == null) {
langRegister = lang;
} else if (!langRegister.equals(lang)) {
chuckRemaining = true;
retractions.add(s);
}
}
}
}
m.remove(retractions);
return m;
}
private String showSortedStatements(List<Statement> candidatesForRemoval) {
List<String> langStrings = new ArrayList<String>();
for (Statement stmt: candidatesForRemoval) {
if (stmt == null) {
langStrings.add("null stmt");
} else {
RDFNode node = stmt.getObject();
if (!node.isLiteral()) {
langStrings.add("not literal");
} else {
langStrings.add(node.asLiteral().getLanguage());
}
}
}
return langStrings.toString();
}
private class StatementSortByLang extends LangSort implements Comparator<Statement> {
public StatementSortByLang(List<String> langs) {
super(langs);
}
public int compare(Statement s1, Statement s2) {
if (s1 == null || s2 == null) {
return 0;
} else if (!s1.getObject().isLiteral() || !s2.getObject().isLiteral()) {
return 0;
}
String s1lang = s1.getObject().asLiteral().getLanguage();
String s2lang = s2.getObject().asLiteral().getLanguage();
return compareLangs(s1lang, s2lang);
}
}
}

View file

@ -0,0 +1,59 @@
package edu.cornell.mannlib.vitro.webapp.rdfservice.filter;
import java.util.List;
import org.apache.jena.graph.Graph;
import org.apache.jena.graph.Node;
import org.apache.jena.graph.Triple;
import org.apache.jena.mem.GraphMem;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.util.iterator.ExtendedIterator;
import edu.cornell.mannlib.vitro.webapp.rdfservice.adapters.AbstractGraphDecorator;
/**
* A graph decorator that filters find() results according to a list of
* preferred language strings
*/
public class LanguageFilteringGraph extends AbstractGraphDecorator
implements Graph {
private List<String> langs;
private LanguageFilterModel filterModel = new LanguageFilterModel();
/**
* Return a graph wrapped in a decorator that will filter find() results
* according to the supplied list of acceptable languages
* @param g the graph to wrap with language awareness. May not be null.
* @param preferredLanguages a list of preferred language strings. May not
* be null.
*/
protected LanguageFilteringGraph(Graph g, List<String> preferredLanguages) {
super(g);
this.langs = preferredLanguages;
}
@Override
public ExtendedIterator<Triple> find(Triple arg0) {
return filter(super.find(arg0));
}
@Override
public ExtendedIterator<Triple> find(Node arg0, Node arg1, Node arg2) {
return filter(super.find(arg0, arg1, arg2));
}
private ExtendedIterator<Triple> filter(ExtendedIterator<Triple> triples) {
Graph tmp = new GraphMem();
while(triples.hasNext()) {
Triple t = triples.next();
tmp.add(t);
}
Model filteredModel = filterModel.filterModel(
ModelFactory.createModelForGraph(tmp), langs);
return filteredModel.getGraph().find();
}
}

View file

@ -7,14 +7,14 @@ import java.io.ByteArrayOutputStream;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.jena.query.QuerySolution; import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet; import org.apache.jena.query.ResultSet;
import org.apache.jena.query.ResultSetFactory; import org.apache.jena.query.ResultSetFactory;
@ -22,11 +22,9 @@ import org.apache.jena.query.ResultSetFormatter;
import org.apache.jena.rdf.model.Literal; import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelChangedListener; import org.apache.jena.rdf.model.ModelChangedListener;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.RDFNode; 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.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeListener; import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeListener;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeSet; import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeSet;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService; import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
@ -39,25 +37,11 @@ public class LanguageFilteringRDFService implements RDFService {
private static final Log log = LogFactory.getLog(LanguageFilteringRDFService.class); private static final Log log = LogFactory.getLog(LanguageFilteringRDFService.class);
private RDFService s; private RDFService s;
private List<String> langs; private List<String> langs;
private LanguageFilterModel filterModel = new LanguageFilterModel();
public LanguageFilteringRDFService(RDFService service, List<String> langs) { public LanguageFilteringRDFService(RDFService service, List<String> langs) {
this.s = service; this.s = service;
this.langs = normalizeLangs(langs); this.langs = new AcceptableLanguages(langs);
}
private List<String> normalizeLangs(List<String> langs) {
log.debug("Preferred languages:" + langs);
List<String> normalizedLangs = new ArrayList<String>(langs);
for (String lang : langs) {
String baseLang = lang.split("-")[0];
if (!normalizedLangs.contains(baseLang)) {
normalizedLangs.add(baseLang);
}
}
log.debug("Normalized languages:" + normalizedLangs);
return normalizedLangs;
} }
@Override @Override
@ -83,23 +67,17 @@ public class LanguageFilteringRDFService implements RDFService {
public InputStream sparqlConstructQuery(String query, public InputStream sparqlConstructQuery(String query,
ModelSerializationFormat resultFormat) ModelSerializationFormat resultFormat)
throws RDFServiceException { throws RDFServiceException {
Model m = RDFServiceUtils.parseModel(s.sparqlConstructQuery(query, resultFormat), resultFormat); Model m = RDFServiceUtils.parseModel(s.sparqlConstructQuery(
InputStream in = outputModel(filterModel(m), resultFormat); query, resultFormat), resultFormat);
InputStream in = outputModel(filterModel.filterModel(
m, langs), resultFormat);
return in; return in;
} }
@Override @Override
public void sparqlConstructQuery(String query, Model model) public void sparqlConstructQuery(String query, Model model)
throws RDFServiceException { throws RDFServiceException {
if (model.isEmpty()) {
s.sparqlConstructQuery(query, model); s.sparqlConstructQuery(query, model);
filterModel(model);
} else {
Model constructedModel = ModelFactory.createDefaultModel();
s.sparqlConstructQuery(query, constructedModel);
filterModel(constructedModel);
model.add(constructedModel);
}
} }
@Override @Override
@ -107,7 +85,7 @@ public class LanguageFilteringRDFService implements RDFService {
ModelSerializationFormat resultFormat) ModelSerializationFormat resultFormat)
throws RDFServiceException { throws RDFServiceException {
Model m = RDFServiceUtils.parseModel(s.sparqlDescribeQuery(query, resultFormat), resultFormat); Model m = RDFServiceUtils.parseModel(s.sparqlDescribeQuery(query, resultFormat), resultFormat);
return outputModel(filterModel(m), resultFormat); return outputModel(filterModel.filterModel(m, langs), resultFormat);
} }
private InputStream outputModel(Model m, ModelSerializationFormat resultFormat) { private InputStream outputModel(Model m, ModelSerializationFormat resultFormat) {
@ -116,62 +94,6 @@ public class LanguageFilteringRDFService implements RDFService {
return new ByteArrayInputStream(out.toByteArray()); return new ByteArrayInputStream(out.toByteArray());
} }
private Model filterModel(Model m) {
log.debug("filterModel");
List<Statement> retractions = new ArrayList<Statement>();
StmtIterator stmtIt = m.listStatements();
while (stmtIt.hasNext()) {
Statement stmt = stmtIt.nextStatement();
if (stmt.getObject().isLiteral()) {
List<Statement> candidatesForRemoval = m.listStatements(
stmt.getSubject(), stmt.getPredicate(), (RDFNode) null).toList();
if (candidatesForRemoval.size() == 1) {
continue;
}
candidatesForRemoval.sort(new StatementSortByLang());
log.debug("sorted statements: " + showSortedStatements(candidatesForRemoval));
Iterator<Statement> candIt = candidatesForRemoval.iterator();
String langRegister = null;
boolean chuckRemaining = false;
while(candIt.hasNext()) {
Statement s = candIt.next();
if (!s.getObject().isLiteral()) {
continue;
} else if (chuckRemaining) {
retractions.add(s);
}
String lang = s.getObject().asLiteral().getLanguage();
if (langRegister == null) {
langRegister = lang;
} else if (!langRegister.equals(lang)) {
chuckRemaining = true;
retractions.add(s);
}
}
}
}
m.remove(retractions);
return m;
}
private String showSortedStatements(List<Statement> candidatesForRemoval) {
List<String> langStrings = new ArrayList<String>();
for (Statement stmt: candidatesForRemoval) {
if (stmt == null) {
langStrings.add("null stmt");
} else {
RDFNode node = stmt.getObject();
if (!node.isLiteral()) {
langStrings.add("not literal");
} else {
langStrings.add(node.asLiteral().getLanguage());
}
}
}
return langStrings.toString();
}
@Override @Override
public InputStream sparqlSelectQuery(String query, public InputStream sparqlSelectQuery(String query,
ResultFormat resultFormat) throws RDFServiceException { ResultFormat resultFormat) throws RDFServiceException {
@ -180,7 +102,16 @@ public class LanguageFilteringRDFService implements RDFService {
s.sparqlSelectQuery(query, RDFService.ResultFormat.JSON)); s.sparqlSelectQuery(query, RDFService.ResultFormat.JSON));
List<QuerySolution> solnList = getSolutionList(resultSet); List<QuerySolution> solnList = getSolutionList(resultSet);
List<String> vars = resultSet.getResultVars(); List<String> vars = resultSet.getResultVars();
// This block loops all of the Query variables;
// for each QuerySolution, creates a map of the values of the other variables than the current
// 'variable' --> a list of RowIndexedLiterals.
// In this way, all of the QuerySolutions with equal values of their other variables are grouped.
// This map is used subsequently to filter Literals based on lang
for (String var : vars) { for (String var : vars) {
Map<List<RDFNode>, List<RowIndexedLiteral>> nonVarToRowIndexedLiterals = new HashMap<>();
// First pass of solnList to populate map
for (int i = 0; i < solnList.size(); i++) { for (int i = 0; i < solnList.size(); i++) {
QuerySolution s = solnList.get(i); QuerySolution s = solnList.get(i);
if (s == null) { if (s == null) {
@ -190,23 +121,32 @@ public class LanguageFilteringRDFService implements RDFService {
if (node == null || !node.isLiteral()) { if (node == null || !node.isLiteral()) {
continue; continue;
} }
List<RowIndexedLiteral> candidatesForRemoval =
new ArrayList<RowIndexedLiteral>(); // Create entry representing values other than current 'var' for this QuerySolution
candidatesForRemoval.add(new RowIndexedLiteral(node.asLiteral(), i)); List<RDFNode> nonVarList = new ArrayList(vars.size() - 1);
for (int j = i + 1; j < solnList.size(); j++) { for (String v : vars) {
QuerySolution t = solnList.get(j); if (!v.equals(var)) {
if (t == null) { nonVarList.add(s.get(v));
continue;
}
if (matchesExceptForVar(s, t, var, vars)) {
candidatesForRemoval.add(
new RowIndexedLiteral(t.getLiteral(var), j));
} }
} }
List<RowIndexedLiteral> rowIndexedLiterals = nonVarToRowIndexedLiterals.get(nonVarList);
if (rowIndexedLiterals == null) {
rowIndexedLiterals = new ArrayList();
}
rowIndexedLiterals.add(new RowIndexedLiteral(node.asLiteral(), i));
// Add RowIndexedLiterals to the map
nonVarToRowIndexedLiterals.put(nonVarList, rowIndexedLiterals);
}
// Second pass of solnList (via the map) to evaluate candidatesForRemoval
for (List<RDFNode> key : nonVarToRowIndexedLiterals.keySet()) {
List<RowIndexedLiteral> candidatesForRemoval = nonVarToRowIndexedLiterals.get(key);
if (candidatesForRemoval.size() == 1) { if (candidatesForRemoval.size() == 1) {
continue; continue;
} }
candidatesForRemoval.sort(new RowIndexedLiteralSortByLang()); candidatesForRemoval.sort(new RowIndexedLiteralSortByLang(langs));
log.debug("sorted RowIndexedLiterals: " + showSortedRILs(candidatesForRemoval)); log.debug("sorted RowIndexedLiterals: " + showSortedRILs(candidatesForRemoval));
Iterator<RowIndexedLiteral> candIt = candidatesForRemoval.iterator(); Iterator<RowIndexedLiteral> candIt = candidatesForRemoval.iterator();
String langRegister = null; String langRegister = null;
@ -254,10 +194,9 @@ public class LanguageFilteringRDFService implements RDFService {
@Override @Override
public void sparqlSelectQuery(String query, ResultSetConsumer consumer) throws RDFServiceException { public void sparqlSelectQuery(String query, ResultSetConsumer consumer) throws RDFServiceException {
log.debug("sparqlSelectQuery: " + query.replaceAll("\\s+", " ")); log.debug("sparqlSelectQuery: " + query.replaceAll("\\s+", " "));
s.sparqlSelectQuery(query, new ResultSetConsumer.Chaining(consumer) { s.sparqlSelectQuery(query, new ResultSetConsumer.Chaining(consumer) {
List<String> vars; List<String> vars;
List<QuerySolution> solnList = new ArrayList<QuerySolution>(); List<QuerySolution> solnList = new ArrayList<>();
@Override @Override
protected void processQuerySolution(QuerySolution qs) { protected void processQuerySolution(QuerySolution qs) {
@ -273,7 +212,15 @@ public class LanguageFilteringRDFService implements RDFService {
protected void endProcessing() { protected void endProcessing() {
chainStartProcessing(); chainStartProcessing();
// This block loops all of the Query variables;
// for each QuerySolution, creates a map of the values of the other variables than the current
// 'variable' --> a list of RowIndexedLiterals.
// In this way, all of the QuerySolutions with equal values of their other variables are grouped.
// This map is used subsequently to filter Literals based on lang
for (String var : vars) { for (String var : vars) {
Map<List<RDFNode>, List<RowIndexedLiteral>> nonVarToRowIndexedLiterals = new HashMap<>();
// First pass of solnList to populate map
for (int i = 0; i < solnList.size(); i++) { for (int i = 0; i < solnList.size(); i++) {
QuerySolution s = solnList.get(i); QuerySolution s = solnList.get(i);
if (s == null) { if (s == null) {
@ -283,23 +230,32 @@ public class LanguageFilteringRDFService implements RDFService {
if (node == null || !node.isLiteral()) { if (node == null || !node.isLiteral()) {
continue; continue;
} }
List<RowIndexedLiteral> candidatesForRemoval =
new ArrayList<RowIndexedLiteral>(); // Create entry representing values other than current 'var' for this QuerySolution
candidatesForRemoval.add(new RowIndexedLiteral(node.asLiteral(), i)); List<RDFNode> nonVarList = new ArrayList(vars.size() - 1);
for (int j = i + 1; j < solnList.size(); j++) { for (String v : vars) {
QuerySolution t = solnList.get(j); if (!v.equals(var)) {
if (t == null) { nonVarList.add(s.get(v));
continue;
}
if (matchesExceptForVar(s, t, var, vars)) {
candidatesForRemoval.add(
new RowIndexedLiteral(t.getLiteral(var), j));
} }
} }
List<RowIndexedLiteral> rowIndexedLiterals = nonVarToRowIndexedLiterals.get(nonVarList);
if (rowIndexedLiterals == null) {
rowIndexedLiterals = new ArrayList();
}
rowIndexedLiterals.add(new RowIndexedLiteral(node.asLiteral(), i));
// Add RowIndexedLiterals to the map
nonVarToRowIndexedLiterals.put(nonVarList, rowIndexedLiterals);
}
// Second pass of solnList (via the map) to evaluate candidatesForRemoval
for (List<RDFNode> key : nonVarToRowIndexedLiterals.keySet()) {
List<RowIndexedLiteral> candidatesForRemoval = nonVarToRowIndexedLiterals.get(key);
if (candidatesForRemoval.size() == 1) { if (candidatesForRemoval.size() == 1) {
continue; continue;
} }
candidatesForRemoval.sort(new RowIndexedLiteralSortByLang()); candidatesForRemoval.sort(new RowIndexedLiteralSortByLang(langs));
log.debug("sorted RowIndexedLiterals: " + showSortedRILs(candidatesForRemoval)); log.debug("sorted RowIndexedLiterals: " + showSortedRILs(candidatesForRemoval));
Iterator<RowIndexedLiteral> candIt = candidatesForRemoval.iterator(); Iterator<RowIndexedLiteral> candIt = candidatesForRemoval.iterator();
String langRegister = null; String langRegister = null;
@ -357,34 +313,6 @@ public class LanguageFilteringRDFService implements RDFService {
} }
private boolean matchesExceptForVar(QuerySolution a, QuerySolution b,
String varName, List<String> varList) {
if (varName == null) {
throw new RuntimeException("expected non-null variable nane");
}
for (String var : varList) {
RDFNode nodea = a.get(var);
RDFNode nodeb = b.get(var);
if (var.equals(varName)) {
if (nodea == null || !nodea.isLiteral() || nodeb == null || !nodeb.isLiteral()) {
return false;
}
} else {
if (nodea == null && nodeb == null) {
continue;
} else if (nodea == null && nodeb != null) {
return false;
} else if (nodeb == null && nodea != null) {
return false;
}
if (!a.get(var).equals(b.get(var))) {
return false;
}
}
}
return true;
}
private List<QuerySolution> getSolutionList(ResultSet resultSet) { private List<QuerySolution> getSolutionList(ResultSet resultSet) {
List<QuerySolution> solnList = new ArrayList<QuerySolution>(); List<QuerySolution> solnList = new ArrayList<QuerySolution>();
while (resultSet.hasNext()) { while (resultSet.hasNext()) {
@ -489,52 +417,12 @@ public class LanguageFilteringRDFService implements RDFService {
s.close(); s.close();
} }
private class LangSort {
// any inexact match is worse than any exact match
private int inexactMatchPenalty = langs.size();
// no language is worse than any inexact match (if the preferred list does not include "").
private int noLanguage = 2 * inexactMatchPenalty;
// no match is worse than no language.
private int noMatch = noLanguage + 1;
protected int compareLangs(String t1lang, String t2lang) {
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;
}
}
private class RowIndexedLiteralSortByLang extends LangSort implements Comparator<RowIndexedLiteral> { private class RowIndexedLiteralSortByLang extends LangSort implements Comparator<RowIndexedLiteral> {
public RowIndexedLiteralSortByLang(List<String> langs) {
super(langs);
}
public int compare(RowIndexedLiteral rilit1, RowIndexedLiteral rilit2) { public int compare(RowIndexedLiteral rilit1, RowIndexedLiteral rilit2) {
if (rilit1 == null || rilit2 == null) { if (rilit1 == null || rilit2 == null) {
return 0; return 0;
@ -547,20 +435,19 @@ public class LanguageFilteringRDFService implements RDFService {
} }
} }
private class StatementSortByLang extends LangSort implements Comparator<Statement> { /*
* UQAM-Linguistic-Management Useful among other things to transport the linguistic context in the service
* (non-Javadoc)
* @see edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService#setVitroRequest(edu.cornell.mannlib.vitro.webapp.controller.VitroRequest)
*/
private VitroRequest vitroRequest;
public int compare(Statement s1, Statement s2) { public void setVitroRequest(VitroRequest vitroRequest) {
if (s1 == null || s2 == null) { this.vitroRequest = vitroRequest;
return 0;
} else if (!s1.getObject().isLiteral() || !s2.getObject().isLiteral()) {
return 0;
} }
String s1lang = s1.getObject().asLiteral().getLanguage(); public VitroRequest getVitroRequest() {
String s2lang = s2.getObject().asLiteral().getLanguage(); return vitroRequest;
return compareLangs(s1lang, s2lang);
}
} }
} }

View file

@ -4,26 +4,62 @@ package edu.cornell.mannlib.vitro.webapp.rdfservice.filter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Set;
import javax.servlet.ServletRequest; import javax.servlet.ServletRequest;
import org.apache.commons.lang3.LocaleUtils;
import org.apache.jena.ontology.OntModel; import org.apache.jena.ontology.OntModel;
import org.apache.jena.ontology.OntModelSpec; import org.apache.jena.ontology.OntModelSpec;
import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.ModelFactory;
import edu.cornell.mannlib.vitro.webapp.dao.jena.RDFServiceGraph;
import edu.cornell.mannlib.vitro.webapp.rdfservice.impl.jena.model.RDFServiceModel;
/** /**
* Some methods that will come in handy when dealing with Language Filtering * Some methods that will come in handy when dealing with Language Filtering
*/ */
public class LanguageFilteringUtils { public class LanguageFilteringUtils {
private static final String UNDERSCORE = "_";
private static final String HYPHEN = "-";
private static final String DEFAULT_LANG_STRING = "en";
/**
* Take a Locale object, such as we might get from a
* request, and convert to a language string used in RDF.
*
* While converting, change all underscores (as in Locale names) to hyphens
* (as in RDF language specifiers).
*/
public static String localeToLanguage(Locale locale) {
return locale.toString().replace(UNDERSCORE, HYPHEN);
}
/**
* Take a language string and convert to a Locale.
*
* While converting, change all hyphens (as in RDF language specifiers) to
* underscores (as in Locale names). Ensure language string is lowercase
* and country abbreviation is uppercase.
*/
public static Locale languageToLocale(String langStr) {
String[] langParts = langStr.split(HYPHEN);
if (langParts.length > 2) {
langStr = String.join(UNDERSCORE, langParts[0].toLowerCase(),
langParts[1].toUpperCase(), langParts[2]);
} else if (langParts.length > 1) {
langStr = String.join(UNDERSCORE, langParts[0].toLowerCase(),
langParts[1].toUpperCase());
} else {
langStr = langParts[0].toLowerCase();
}
return LocaleUtils.toLocale(langStr);
}
/** /**
* Take an Enumeration of Locale objects, such as we might get from a * Take an Enumeration of Locale objects, such as we might get from a
* request, and convert to a List of langauage strings, such as are needed * request, and convert to a List of language strings, such as are needed
* by the LanguageFilteringRDFService. * by the LanguageFilteringRDFService.
* *
* While converting, change all underscores (as in Locale names) to hyphens * While converting, change all underscores (as in Locale names) to hyphens
@ -33,27 +69,43 @@ public class LanguageFilteringUtils {
List<String> langs = new ArrayList<>(); List<String> langs = new ArrayList<>();
while (locales.hasMoreElements()) { while (locales.hasMoreElements()) {
Locale locale = (Locale) locales.nextElement(); Locale locale = (Locale) locales.nextElement();
langs.add(locale.toString().replace("_", "-")); langs.add(locale.toString().replace(UNDERSCORE, HYPHEN));
} }
if (langs.isEmpty()) { if (langs.isEmpty()) {
langs.add("en"); langs.add(DEFAULT_LANG_STRING);
} }
return langs;
return langs;
} }
/** /**
* Add a Language Filtering layer to an OntModel by treating it as an RDFService. * Take a List of language strings and convert to a List of Locale.
*
* While converting, change all hyphens (as in RDF language specifiers) to
* under scores (as in Locale names). Ensure language string is lowercase
* and country abbreviation is uppercase.
*/
public static List<Locale> languagesToLocales(List<String> langs) {
Set<Locale> locales = new HashSet<>();
langs.forEach(langStr -> {
locales.add(languageToLocale(langStr));
});
if (locales.isEmpty()) {
locales.add(LocaleUtils.toLocale(DEFAULT_LANG_STRING));
}
return new ArrayList<>(locales);
}
/**
* Add a Language Filtering layer to an OntModel
*/ */
public static OntModel wrapOntModelInALanguageFilter(OntModel rawModel, public static OntModel wrapOntModelInALanguageFilter(OntModel rawModel,
ServletRequest req) { ServletRequest req) {
/** This is some nasty layering. Could we do this more easily? */ List<String> languages = new AcceptableLanguages(localesToLanguages(req.getLocales()));
List<String> languages = localesToLanguages(req.getLocales());
return ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, return ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM,
RDFServiceGraph.createRDFServiceModel( ModelFactory.createModelForGraph(new LanguageFilteringGraph(
new RDFServiceGraph( rawModel.getGraph(), languages)));
new LanguageFilteringRDFService(
new RDFServiceModel(rawModel), languages))));
} }
private LanguageFilteringUtils() { private LanguageFilteringUtils() {

View file

@ -9,6 +9,7 @@ import java.util.List;
import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelChangedListener; import org.apache.jena.rdf.model.ModelChangedListener;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeListener; import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeListener;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeSet; import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeSet;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService; import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
@ -218,7 +219,20 @@ public class RDFServiceFactorySingle implements RDFServiceFactory {
return ToString.simpleName(this) + "[" + ToString.hashHex(this) return ToString.simpleName(this) + "[" + ToString.hashHex(this)
+ ", inner=" + s + "]"; + ", inner=" + s + "]";
} }
/*
* UQAM-Linguistic-Management Useful among other things to transport the linguistic context in the service
* (non-Javadoc)
* @see edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService#setVitroRequest(edu.cornell.mannlib.vitro.webapp.controller.VitroRequest)
*/
private VitroRequest vitroRequest;
public void setVitroRequest(VitroRequest vitroRequest) {
this.vitroRequest = vitroRequest;
}
public VitroRequest getVitroRequest() {
return vitroRequest;
}
} }
} }

View file

@ -32,6 +32,7 @@ import org.apache.jena.riot.out.NodeFormatter;
import org.apache.jena.riot.out.NodeFormatterTTL; import org.apache.jena.riot.out.NodeFormatterTTL;
import org.apache.jena.vocabulary.RDF; import org.apache.jena.vocabulary.RDF;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeListener; import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeListener;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeSet; import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeSet;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ModelChange; import edu.cornell.mannlib.vitro.webapp.rdfservice.ModelChange;
@ -141,8 +142,8 @@ public abstract class RDFServiceImpl implements RDFService {
} }
protected void notifyListeners(ModelChange modelChange) throws IOException { protected void notifyListeners(ModelChange modelChange) throws IOException {
for (ChangeListener listener : registeredListeners) {
modelChange.getSerializedModel().reset(); modelChange.getSerializedModel().reset();
for (ChangeListener listener : registeredListeners) {
listener.notifyModelChange(modelChange); listener.notifyModelChange(modelChange);
} }
log.debug(registeredJenaListeners.size() + " registered Jena listeners"); log.debug(registeredJenaListeners.size() + " registered Jena listeners");
@ -259,6 +260,7 @@ public abstract class RDFServiceImpl implements RDFService {
} else if (node.getLiteralDatatypeURI() != null) { } else if (node.getLiteralDatatypeURI() != null) {
literalBuff.append("^^<").append(node.getLiteralDatatypeURI()).append(">"); literalBuff.append("^^<").append(node.getLiteralDatatypeURI()).append(">");
} }
return literalBuff.toString(); return literalBuff.toString();
} else { } else {
return varName; return varName;
@ -453,4 +455,19 @@ public abstract class RDFServiceImpl implements RDFService {
} }
} }
} }
/*
* UQAM Useful among other things to transport the linguistic context in the service
* (non-Javadoc)
* @see edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService#setVitroRequest(edu.cornell.mannlib.vitro.webapp.controller.VitroRequest)
*/
private VitroRequest vitroRequest;
public void setVitroRequest(VitroRequest vitroRequest) {
this.vitroRequest = vitroRequest;
}
public VitroRequest getVitroRequest() {
return vitroRequest;
}
} }

View file

@ -42,6 +42,7 @@ import org.apache.jena.sdb.SDB;
import org.apache.jena.shared.Lock; import org.apache.jena.shared.Lock;
import org.apache.jena.sparql.core.Quad; import org.apache.jena.sparql.core.Quad;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.jena.DatasetWrapper; import edu.cornell.mannlib.vitro.webapp.dao.jena.DatasetWrapper;
import edu.cornell.mannlib.vitro.webapp.dao.jena.RDFServiceDataset; import edu.cornell.mannlib.vitro.webapp.dao.jena.RDFServiceDataset;
import edu.cornell.mannlib.vitro.webapp.dao.jena.SparqlGraph; import edu.cornell.mannlib.vitro.webapp.dao.jena.SparqlGraph;
@ -704,4 +705,19 @@ public abstract class RDFServiceJena extends RDFServiceImpl implements RDFServic
protected QueryExecution createQueryExecution(String queryString, Query q, Dataset d) { protected QueryExecution createQueryExecution(String queryString, Query q, Dataset d) {
return QueryExecutionFactory.create(q, d); return QueryExecutionFactory.create(q, d);
} }
/*
* UQAM-Linguistic-Management Useful among other things to transport the linguistic context in the service
* (non-Javadoc)
* @see edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService#setVitroRequest(edu.cornell.mannlib.vitro.webapp.controller.VitroRequest)
*/
private VitroRequest vitroRequest;
public void setVitroRequest(VitroRequest vitroRequest) {
this.vitroRequest = vitroRequest;
}
public VitroRequest getVitroRequest() {
return vitroRequest;
}
} }

View file

@ -13,6 +13,7 @@ import org.apache.jena.query.Dataset;
import org.apache.jena.query.DatasetFactory; import org.apache.jena.query.DatasetFactory;
import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.Model;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.jena.DatasetWrapper; import edu.cornell.mannlib.vitro.webapp.dao.jena.DatasetWrapper;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeSet; import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeSet;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ModelChange; import edu.cornell.mannlib.vitro.webapp.rdfservice.ModelChange;
@ -119,4 +120,18 @@ public class RDFServiceModel extends RDFServiceJena implements RDFService {
return true; return true;
} }
/*
* UQAM-Linguistic-Management Useful among other things to transport the linguistic context in the service
* (non-Javadoc)
* @see edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService#setVitroRequest(edu.cornell.mannlib.vitro.webapp.controller.VitroRequest)
*/
private VitroRequest vitroRequest;
public void setVitroRequest(VitroRequest vitroRequest) {
this.vitroRequest = vitroRequest;
}
public VitroRequest getVitroRequest() {
return vitroRequest;
}
} }

View file

@ -9,6 +9,7 @@ import java.util.List;
import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelChangedListener; import org.apache.jena.rdf.model.ModelChangedListener;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeListener; import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeListener;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeSet; import edu.cornell.mannlib.vitro.webapp.rdfservice.ChangeSet;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService; import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
@ -207,4 +208,19 @@ public class LoggingRDFService implements RDFService {
public String toString() { public String toString() {
return "LoggingRDFService[inner=" + innerService + "]"; return "LoggingRDFService[inner=" + innerService + "]";
} }
/*
* UQAM-Linguistic-Management Useful among other things to transport the linguistic context in the service
* (non-Javadoc)
* @see edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService#setVitroRequest(edu.cornell.mannlib.vitro.webapp.controller.VitroRequest)
*/
private VitroRequest vitroRequest;
public void setVitroRequest(VitroRequest vitroRequest) {
this.vitroRequest = vitroRequest;
}
public VitroRequest getVitroRequest() {
return vitroRequest;
}
} }

View file

@ -10,7 +10,6 @@ import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;

View file

@ -445,14 +445,26 @@ public class FakeApplicationOntologyService {
* "display model". The query finds a preferred title for the individual. * "display model". The query finds a preferred title for the individual.
*/ */
private static class FakeVivoPeopleDataGetter extends SparqlQueryDataGetter { private static class FakeVivoPeopleDataGetter extends SparqlQueryDataGetter {
private static String QUERY_STRING = "" // private static String QUERY_STRING = ""
// + "PREFIX obo: <http://purl.obolibrary.org/obo/> \n"
// + "PREFIX vcard: <http://www.w3.org/2006/vcard/ns#> \n"
// + "SELECT ?pt \n" + "WHERE { \n"
// + " ?uri obo:ARG_2000028 ?vIndividual . \n"
// + " ?vIndividual vcard:hasTitle ?vTitle . \n"
// + " ?vTitle vcard:title ?pt . \n" + "} LIMIT 1";
/*
* UQAM-Optimization New query including Linguistic context
*/
private static String QUERY_STRING_LANG = ""
+ "PREFIX obo: <http://purl.obolibrary.org/obo/> \n" + "PREFIX obo: <http://purl.obolibrary.org/obo/> \n"
+ "PREFIX vcard: <http://www.w3.org/2006/vcard/ns#> \n" + "PREFIX vcard: <http://www.w3.org/2006/vcard/ns#> \n"
+ "SELECT ?pt \n" + "WHERE { \n" + "SELECT ?pt \n" + "WHERE { \n"
+ " ?uri obo:ARG_2000028 ?vIndividual . \n" + " ?uri obo:ARG_2000028 ?vIndividual . \n"
+ " ?vIndividual vcard:hasTitle ?vTitle . \n" + " ?vIndividual vcard:hasTitle ?vTitle . \n"
+ " ?vTitle vcard:title ?pt . \n" + "} LIMIT 1"; + " ?vTitle vcard:title ?pt . \n"
+ " FILTER (lang(?pt) = '?langCtx' ) \n"
+ " } LIMIT 1";
private static final String FAKE_VIVO_PEOPLE_DATA_GETTER_URI = "http://FakeVivoPeopleDataGetter"; private static final String FAKE_VIVO_PEOPLE_DATA_GETTER_URI = "http://FakeVivoPeopleDataGetter";
private static OntModel fakeDisplayModel = initializeFakeDisplayModel(); private static OntModel fakeDisplayModel = initializeFakeDisplayModel();
@ -467,7 +479,7 @@ public class FakeApplicationOntologyService {
Property saveToVarProperty = m Property saveToVarProperty = m
.getProperty(DisplayVocabulary.SAVE_TO_VAR); .getProperty(DisplayVocabulary.SAVE_TO_VAR);
m.add(dataGetter, queryProperty, QUERY_STRING); m.add(dataGetter, queryProperty, QUERY_STRING_LANG); //UQAM-Optimization Using query with linguistic context
m.add(dataGetter, saveToVarProperty, "extra"); m.add(dataGetter, saveToVarProperty, "extra");
return m; return m;
} }
@ -475,18 +487,24 @@ public class FakeApplicationOntologyService {
private String individualUri; private String individualUri;
private VitroRequest vreq; private VitroRequest vreq;
private ServletContext ctx; private ServletContext ctx;
private String langCtx = "en-US";
public FakeVivoPeopleDataGetter(VitroRequest vreq, String individualUri) { public FakeVivoPeopleDataGetter(VitroRequest vreq, String individualUri) {
super(vreq, fakeDisplayModel, "http://FakeVivoPeopleDataGetter"); super(vreq, initializeFakeDisplayModel(), "http://FakeVivoPeopleDataGetter");
this.individualUri = individualUri; this.individualUri = individualUri;
this.vreq = vreq; this.vreq = vreq;
this.ctx = vreq.getSession().getServletContext(); this.ctx = vreq.getSession().getServletContext();
this.langCtx = vreq.getLocale().getLanguage(); // UQAM-Optimization add the linguistic context
if (!vreq.getLocale().getCountry().isEmpty()) {
this.langCtx += "-" + vreq.getLocale().getCountry();
}
} }
@Override @Override
public Map<String, Object> getData(Map<String, Object> pageData) { public Map<String, Object> getData(Map<String, Object> pageData) {
Map<String, Object> parms = new HashMap<>(); Map<String, Object> parms = new HashMap<>();
parms.put("uri", individualUri); parms.put("uri", individualUri);
parms.put("langCtx", langCtx); //UQAM-Optimization add the linguistic context
return super.getData(parms); return super.getData(parms);
} }

View file

@ -12,15 +12,30 @@ import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener; import javax.servlet.ServletContextListener;
import org.apache.jena.ontology.OntModel; import org.apache.jena.ontology.OntModel;
import org.apache.jena.rdf.model.Model;
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.Statement;
import org.apache.jena.rdf.model.StmtIterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess; import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus; import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus;
import edu.cornell.mannlib.vitro.webapp.rdfservice.adapters.VitroModelFactory;
/** /**
* Set up the models that use the CONFIGURATION RDFService. They are all mapped * Set up the models that use the CONFIGURATION RDFService. They are all mapped
* to memory-based models. * to memory-based models.
*/ */
public class ConfigurationModelsSetup implements ServletContextListener { public class ConfigurationModelsSetup implements ServletContextListener {
private static final Log log = LogFactory.getLog(ConfigurationModelsSetup.class);
@Override @Override
public void contextInitialized(ServletContextEvent sce) { public void contextInitialized(ServletContextEvent sce) {
ServletContext ctx = sce.getServletContext(); ServletContext ctx = sce.getServletContext();
@ -31,33 +46,223 @@ public class ConfigurationModelsSetup implements ServletContextListener {
setupModel(ctx, DISPLAY_TBOX, "displayTbox"); setupModel(ctx, DISPLAY_TBOX, "displayTbox");
setupModel(ctx, DISPLAY_DISPLAY, "displayDisplay"); setupModel(ctx, DISPLAY_DISPLAY, "displayDisplay");
setupModel(ctx, USER_ACCOUNTS, "auth"); setupModel(ctx, USER_ACCOUNTS, "auth");
ss.info(this, ss.info(this, "Set up the display models and the user accounts model.");
"Set up the display models and the user accounts model.");
} catch (Exception e) { } catch (Exception e) {
ss.fatal(this, e.getMessage(), e.getCause()); ss.fatal(this, e.getMessage(), e.getCause());
} }
} }
private void setupModel(ServletContext ctx, String modelUri, private void setupModel(ServletContext ctx, String modelUri, String modelPath) {
String modelPath) {
try { try {
OntModel ontModel = ModelAccess.on(ctx).getOntModel(modelUri); OntModel ontModel = ModelAccess.on(ctx).getOntModel(modelUri);
if (ontModel.isEmpty()) {
loadFirstTimeFiles(ctx, modelPath, ontModel); loadFirstTimeFiles(ctx, modelPath, ontModel);
// backup firsttime files
OntModel baseModelFirsttime = ModelAccess.on(ctx).getOntModel(modelUri + "FirsttimeBackup");
baseModelFirsttime.add(ontModel);
} else {
// Check if the firsttime files have changed since the firsttime startup,
// if so, then apply the changes but not overwrite the whole user model
applyFirstTimeChanges(ctx, modelPath, modelUri, ontModel);
}
loadEveryTimeFiles(ctx, modelPath, ontModel); loadEveryTimeFiles(ctx, modelPath, ontModel);
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("Failed to create the '" + modelPath throw new RuntimeException("Failed to create the '" + modelPath + "' model (" + modelUri + ").", e);
+ "' model (" + modelUri + ").", e);
} }
} }
private void loadFirstTimeFiles(ServletContext ctx, String modelPath, private void loadFirstTimeFiles(ServletContext ctx, String modelPath, OntModel baseModel) {
OntModel baseModel) { RDFFilesLoader.loadFirstTimeFiles(ctx, modelPath, baseModel, baseModel.isEmpty());
RDFFilesLoader.loadFirstTimeFiles(modelPath, baseModel, baseModel.isEmpty());
} }
private void loadEveryTimeFiles(ServletContext ctx, String modelPath, private void loadEveryTimeFiles(ServletContext ctx, String modelPath, OntModel memoryModel) {
OntModel memoryModel) { RDFFilesLoader.loadEveryTimeFiles(ctx, modelPath, memoryModel);
RDFFilesLoader.loadEveryTimeFiles(modelPath, memoryModel); }
/*
* Check if the firsttime files have changed since the firsttime startup, if so,
* then apply the changes but not overwrite the whole user model
*/
private void applyFirstTimeChanges(ServletContext ctx, String modelPath, String modelUri, OntModel userModel) {
log.info("Reload firsttime files on start-up if changed: '" + modelPath +"', URI: '" + modelUri + "'");
boolean updatedFiles = false;
// get configuration models from the firsttime start up (backup state)
OntModel baseModelFirsttimeBackup = ModelAccess.on(ctx).getOntModel(modelUri + "FirsttimeBackup");
// compare firsttime files with configuration models
log.debug("compare firsttime files with configuration models (backup from first start) for " + modelPath);
OntModel baseModelFirsttime = VitroModelFactory.createOntologyModel();
RDFFilesLoader.loadFirstTimeFiles(ctx, modelPath, baseModelFirsttime, true);
if (baseModelFirsttime.isIsomorphicWith(baseModelFirsttimeBackup)) {
log.debug("They are the same, so do nothing: '" + modelPath + "'");
} else {
log.debug("They differ:" + modelPath + ", compare values in configuration models with user's triplestore");
updatedFiles = applyChanges(baseModelFirsttimeBackup, baseModelFirsttime, userModel, modelPath);
if (updatedFiles)
log.info("The model was updated, " + modelPath);
}
}
/*
* This method is designed to compare configuration models (baseModel) with firsttime files (newModel):
* if they are the same, stop
* else, if they differ, compare values in configuration models (baseModel) with user's triplestore
* if they are the same, update user's triplestore with value in new firsttime files
* else, if they differ, leave user's triplestore statement alone
* finally, overwrite the configuration models with content of the updated firstime files
*
* @param baseModel The backup firsttime model (from the first startup)
* @param newModel The current state of the firsttime files in the directory
* @param userModel The current state of the user model
* @param modelIdString Just an string for the output for better debugging
* (display, displayTbox, displayDisplay, auth)
*/
private boolean applyChanges(Model baseModel, Model newModel, Model userModel, String modelIdString) {
boolean updatedFiles = false;
StringWriter out = new StringWriter();
StringWriter out2 = new StringWriter();
Model difOldNew = baseModel.difference(newModel);
Model difNewOld = newModel.difference(baseModel);
// remove special cases for display, problem with blank nodes
if (modelIdString.equals("display")) {
removeBlankTriples(difOldNew);
removeBlankTriples(difNewOld);
}
if (difOldNew.isEmpty() && difNewOld.isEmpty()) {
// if there is no difference, nothing needs to be done
log.debug("For the " + modelIdString + " model, there is no difference in both directions. So do nothing.");
} else {
// if there is a difference, we need to remove the triples in difOldNew and
// add the triples in difNewOld to the back up firsttime model
if (!difOldNew.isEmpty()) {
difOldNew.write(out, "TTL");
log.debug("Difference for " + modelIdString + " (old -> new), these triples should be removed: " + out);
// Check if the UI-changes Overlap with the changes made in the fristtime-files
checkUiChangesOverlapWithFileChanges(baseModel, userModel, difOldNew);
// before we remove the triples, we need to compare values in back up firsttime with user's triplestore
// if the triples which should be removed are still in user´s triplestore, remove them
if (userModel.containsAny(difOldNew)) {
log.debug("Some of these triples are in the user triples store, so they will be removed now");
userModel.remove(difOldNew);
updatedFiles = true;
}
// remove the triples from the backup firsttime model for the next check
baseModel.remove(difOldNew);
}
if (!difNewOld.isEmpty()) {
difNewOld.write(out2, "TTL");
log.debug("Difference for " + modelIdString + " (new -> old), these triples should be added: " + out2);
// Check if the UI-changes Overlap with the changes made in the fristtime-files
checkUiChangesOverlapWithFileChanges(baseModel, userModel, difNewOld);
// before we add the triples, we need to compare values in back up firsttime with user's triplestore
// if the triples which should be added are not already in user´s triplestore, add them
if (!userModel.containsAll(difNewOld)) {
log.debug("Some of these triples are not in the user triples store, so they will be added now");
// but only the triples that are no already there
Model tmp = difNewOld.difference(userModel);
userModel.add(tmp);
updatedFiles = true;
}
// add the triples from the back up firsttime model for the next check
baseModel.add(difNewOld);
}
}
return updatedFiles;
}
/**
* Check if the UI-changes Overlap with the changes made in the fristtime-files, if they overlap these changes are not applied to the user-model (UI)
*
* @param baseModel firsttime backup model
* @param userModel current state in the system (user/UI-model)
* @param changesModel the changes between firsttime-files and firttime-backup
*/
private void checkUiChangesOverlapWithFileChanges(Model baseModel, Model userModel, Model changesModel) {
log.debug("Beginn check if subtractions from Backup-firsttime model to current state of firsttime-files were changed in user-model (via UI)");
Model changesUserModel = userModel.difference(baseModel);
List<Statement> changedInUIandFileStatements = new ArrayList<Statement>();
if(!changesUserModel.isEmpty())
{
removeBlankTriples(changesUserModel);
StringWriter out3 = new StringWriter();
changesUserModel.write(out3, "TTL");
log.debug("There were changes in the user-model via UI which have also changed in the firsttime files, the following triples will not be updated");
// iterate all statements and check if the ones which should be removed were not changed via the UI
StmtIterator iter = changesUserModel.listStatements();
while (iter.hasNext()) {
Statement stmt = iter.nextStatement(); // get next statement
Resource subject = stmt.getSubject(); // get the subject
Property predicate = stmt.getPredicate(); // get the predicate
RDFNode object = stmt.getObject(); // get the object
StmtIterator iter2 = changesModel.listStatements();
while (iter2.hasNext()) {
Statement stmt2 = iter2.nextStatement(); // get next statement
Resource subject2 = stmt2.getSubject(); // get the subject
Property predicate2 = stmt2.getPredicate(); // get the predicate
RDFNode object2 = stmt2.getObject(); // get the object
// if subject and predicate are equal but the object differs and the language tag is the same, do not update these triples
// this case indicates an change in the UI, which should not be overwriten from the firsttime files
if(subject.equals(subject2) && predicate.equals(predicate2) && !object.equals(object2) ) {
// if object is an literal, check the language tag
if (object.isLiteral() && object2.isLiteral()) {
// if the langauge tag is the same, remove this triple from the update list
if(object.asLiteral().getLanguage().equals(object2.asLiteral().getLanguage())) {
log.debug("This two triples changed UI and files: \n UI: " + stmt + " \n file: " +stmt2);
changedInUIandFileStatements.add(stmt2);
}
} else {
log.debug("This two triples changed UI and files: \n UI: " + stmt + " \n file: " +stmt2);
changedInUIandFileStatements.add(stmt2);
}
}
}
}
// remove triples which were changed in the user model (UI) from the list
changesModel.remove(changedInUIandFileStatements);
} else {
log.debug("There were no changes in the user-model via UI compared to the backup-firsttime-model");
}
}
/**
* Remove all triples where subject or object is blank (Anon)
*/
private void removeBlankTriples(Model model) {
StmtIterator iter = model.listStatements();
List<Statement> removeStatement = new ArrayList<Statement>();
while (iter.hasNext()) {
Statement stmt = iter.nextStatement(); // get next statement
Resource subject = stmt.getSubject(); // get the subject
RDFNode object = stmt.getObject(); // get the object
if(subject.isAnon() || object.isAnon())
{
removeStatement.add(stmt);
}
}
model.remove(removeStatement);
} }
@Override @Override

View file

@ -5,9 +5,13 @@ package edu.cornell.mannlib.vitro.webapp.servlet.setup;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.ABOX_ASSERTIONS; import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.ABOX_ASSERTIONS;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.APPLICATION_METADATA; import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.APPLICATION_METADATA;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.TBOX_ASSERTIONS; import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.TBOX_ASSERTIONS;
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 java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.io.StringWriter;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextEvent;
@ -17,12 +21,16 @@ import org.apache.commons.logging.LogFactory;
import org.apache.jena.ontology.OntModel; import org.apache.jena.ontology.OntModel;
import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.ResIterator; import org.apache.jena.rdf.model.ResIterator;
import org.apache.jena.rdf.model.Resource; import org.apache.jena.rdf.model.Resource;
import org.apache.jena.shared.Lock; import org.apache.jena.shared.Lock;
import org.apache.jena.util.ResourceUtils; import org.apache.jena.util.ResourceUtils;
import org.apache.jena.util.iterator.ClosableIterator; import org.apache.jena.util.iterator.ClosableIterator;
import org.apache.jena.vocabulary.RDF; import org.apache.jena.vocabulary.RDF;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.rdf.model.StmtIterator;
import org.apache.jena.rdf.model.RDFNode;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ContextModelAccess; import edu.cornell.mannlib.vitro.webapp.modelaccess.ContextModelAccess;
@ -61,21 +69,38 @@ public class ContentModelSetup extends JenaDataSourceSetupBase
if (applicationMetadataModel.isEmpty()) { if (applicationMetadataModel.isEmpty()) {
firstTimeStartup = true; firstTimeStartup = true;
initializeApplicationMetadata(ctx, applicationMetadataModel); initializeApplicationMetadata(ctx, applicationMetadataModel);
// backup copy from firsttime files
OntModel applicationMetadataModelFirsttime = models.getOntModel(APPLICATION_METADATA_FIRSTTIME_BACKUP);
applicationMetadataModelFirsttime.add(applicationMetadataModel);
} else { } else {
// check if some of the firsttime files have changed since the first start up and
// if they changed, apply these changes to the user models
applyFirstTimeChanges(ctx);
checkForNamespaceMismatch( applicationMetadataModel, ctx ); checkForNamespaceMismatch( applicationMetadataModel, ctx );
} }
OntModel baseABoxModel = models.getOntModel(ABOX_ASSERTIONS); OntModel baseABoxModel = models.getOntModel(ABOX_ASSERTIONS);
if (firstTimeStartup) { if (firstTimeStartup) {
RDFFilesLoader.loadFirstTimeFiles("abox", baseABoxModel, true); RDFFilesLoader.loadFirstTimeFiles(ctx, "abox", baseABoxModel, true);
// backup copy from firsttime files
OntModel baseABoxModelFirsttime = models.getOntModel(ABOX_ASSERTIONS_FIRSTTIME_BACKUP);
baseABoxModelFirsttime.add(baseABoxModel);
} }
RDFFilesLoader.loadEveryTimeFiles("abox", baseABoxModel); RDFFilesLoader.loadEveryTimeFiles(ctx, "abox", baseABoxModel);
OntModel baseTBoxModel = models.getOntModel(TBOX_ASSERTIONS); OntModel baseTBoxModel = models.getOntModel(TBOX_ASSERTIONS);
if (firstTimeStartup) { if (firstTimeStartup) {
RDFFilesLoader.loadFirstTimeFiles("tbox", baseTBoxModel, true); RDFFilesLoader.loadFirstTimeFiles(ctx, "tbox", baseTBoxModel, true);
// backup copy from firsttime files
OntModel baseTBoxModelFirsttime = models.getOntModel(TBOX_ASSERTIONS_FIRSTTIME_BACKUP);
baseTBoxModelFirsttime.add(baseTBoxModel);
} }
RDFFilesLoader.loadEveryTimeFiles("tbox", baseTBoxModel); RDFFilesLoader.loadEveryTimeFiles(ctx, "tbox", baseTBoxModel);
} }
private long secondsSince(long startTime) { private long secondsSince(long startTime) {
@ -94,7 +119,7 @@ public class ContentModelSetup extends JenaDataSourceSetupBase
private void initializeApplicationMetadata(ServletContext ctx, private void initializeApplicationMetadata(ServletContext ctx,
Model applicationMetadataModel) { Model applicationMetadataModel) {
OntModel temporaryAMModel = VitroModelFactory.createOntologyModel(); OntModel temporaryAMModel = VitroModelFactory.createOntologyModel();
RDFFilesLoader.loadFirstTimeFiles("applicationMetadata", temporaryAMModel, true); RDFFilesLoader.loadFirstTimeFiles(ctx, "applicationMetadata", temporaryAMModel, true);
setPortalUriOnFirstTime(temporaryAMModel, ctx); setPortalUriOnFirstTime(temporaryAMModel, ctx);
applicationMetadataModel.add(temporaryAMModel); applicationMetadataModel.add(temporaryAMModel);
} }
@ -191,6 +216,188 @@ public class ContentModelSetup extends JenaDataSourceSetupBase
} }
} }
/*
* Check if the firsttime files have changed since the firsttime startup for all ContentModels,
* if so, then apply the changes but not overwrite the whole user model
*/
private void applyFirstTimeChanges(ServletContext ctx) {
applyFirstTimeChanges(ctx, "applicationMetadata", APPLICATION_METADATA_FIRSTTIME_BACKUP, APPLICATION_METADATA);
applyFirstTimeChanges(ctx, "abox", ABOX_ASSERTIONS_FIRSTTIME_BACKUP, ABOX_ASSERTIONS);
applyFirstTimeChanges(ctx, "tbox", TBOX_ASSERTIONS_FIRSTTIME_BACKUP, TBOX_ASSERTIONS);
}
/*
* Check if the firsttime files have changed since the firsttime startup for one ContentModel,
* if so, then apply the changes but not overwrite the whole user model
*/
private void applyFirstTimeChanges(ServletContext ctx, String modelPath, String firsttimeBackupModelUri, String userModelUri) {
log.info("Reload firsttime files on start-up if changed: '" + modelPath +"', URI: '" +userModelUri+ "'");
ContextModelAccess models = ModelAccess.on(ctx);
OntModel firsttimeBackupModel = models.getOntModel(firsttimeBackupModelUri);
// compare firsttime files with configuration models
log.debug("compare firsttime files with configuration models (backup from first start) for " + modelPath);
OntModel firsttimeFilesModel = VitroModelFactory.createOntologyModel();
RDFFilesLoader.loadFirstTimeFiles(ctx, modelPath, firsttimeFilesModel, true);
// special initialization for application metadata model
if (firsttimeBackupModelUri.equals(APPLICATION_METADATA_FIRSTTIME_BACKUP)) {
setPortalUriOnFirstTime(firsttimeFilesModel, ctx);
}
if ( firsttimeBackupModel.isIsomorphicWith(firsttimeFilesModel) ) {
log.debug("They are the same, so do nothing: '" + modelPath + "'");
} else {
log.debug("They differ: '" + modelPath + "', compare values in configuration models with user's triplestore");
OntModel userModel = models.getOntModel(userModelUri);
// double check the statements (blank notes, etc.) and apply the changes
boolean updatedFiles = applyChanges(firsttimeBackupModel, firsttimeFilesModel, userModel, modelPath);
if (updatedFiles) log.info("The model was updated, " + modelPath);
}
}
/*
* This method is designed to compare configuration models (baseModel) with firsttime files (newModel):
* if they are the same, stopFirstTime
* else, if they differ, compare values in configuration models (baseModel) with user's triplestore
* if they are the same, update user's triplestore with value in new firsttime files
* else, if they differ, leave user's triplestore statement alone
* finally, overwrite the configuration models with content of the updated firstime files
*
* @param baseModel The backup firsttime model (from the first startup)
* @param newModel The current state of the firsttime files in the directory
* @param userModel The current state of the user model
* @param modelIdString Just an string for the output for better debugging (tbox, abox, applicationMetadata)
*/
private boolean applyChanges(Model baseModel, Model newModel, Model userModel, String modelIdString) {
boolean updatedFiles = false;
StringWriter out = new StringWriter();
StringWriter out2 = new StringWriter();
Model difOldNew = baseModel.difference(newModel);
Model difNewOld = newModel.difference(baseModel);
// special case for "rootTab" triple, do not need an update (is it still used in general? if not remove this case)
if(modelIdString.equals("applicationMetadata")) {
Property p = userModel.createProperty("http://vitro.mannlib.cornell.edu/ns/vitro/0.7#", "rootTab");
difOldNew.removeAll(null, p, null);
difNewOld.removeAll(null, p, null);
}
if (difOldNew.isEmpty() && difNewOld.isEmpty()) {
// if there is no difference, nothing needs to be done
log.debug("For the " + modelIdString + " model, there is no difference in both directions. So do nothing.");
} else {
// if there is a difference, we need to remove the triples in difOldNew and
// add the triples in difNewOld to the back up firsttime model
if (!difOldNew.isEmpty()) {
difOldNew.write(out, "TTL");
log.debug("Difference for " + modelIdString + " (old -> new), these triples should be removed: " + out);
// Check if the UI-changes Overlap with the changes made in the fristtime-files
checkUiChangesOverlapWithFileChanges(baseModel, userModel, difOldNew);
// before we remove the triples, we need to compare values in back up firsttime with user's triplestore
// if the triples which should be removed are still in user´s triplestore, remove them
if (userModel.containsAny(difOldNew)) {
log.debug("Some of these triples are in the user triples store, so they will be removed now");
userModel.remove(difOldNew);
updatedFiles = true;
}
// remove the triples from the back up firsttime model for the next check
baseModel.remove(difOldNew);
}
if (!difNewOld.isEmpty()) {
difNewOld.write(out2, "TTL");
log.debug("Difference for " + modelIdString + " (new -> old), these triples should be added: " + out2);
// Check if the UI-changes Overlap with the changes made in the fristtime-files
checkUiChangesOverlapWithFileChanges(baseModel, userModel, difNewOld);
// before we add the triples, we need to compare values in back up firsttime with user's triplestore
// if the triples which should be added are not already in user´s triplestore, add them
if (!userModel.containsAll(difNewOld)) {
log.debug("Some of these triples are not in the user triples store, so they will be added now");
// but only the triples that are no already there
Model tmp = difNewOld.difference(userModel);
userModel.add(tmp);
updatedFiles = true;
}
// add the triples from the back up firsttime model for the next check
baseModel.add(difNewOld);
}
}
return updatedFiles;
}
/**
* Check if the UI-changes Overlap with the changes made in the fristtime-files, if they overlap these changes are not applied to the user-model (UI)
*
* @param baseModel firsttime backup model
* @param userModel current state in the system (user/UI-model)
* @param changesModel the changes between firsttime-files and firttime-backup
*/
private void checkUiChangesOverlapWithFileChanges(Model baseModel, Model userModel, Model changesModel) {
log.debug("Beginn check if subtractions from Backup-firsttime model to current state of firsttime-files were changed in user-model (via UI)");
Model changesUserModel = userModel.difference(baseModel);
List<Statement> changedInUIandFileStatements = new ArrayList<Statement>();
if(!changesUserModel.isEmpty())
{
StringWriter out3 = new StringWriter();
changesUserModel.write(out3, "TTL");
log.debug("There were changes in the user-model via UI which have also changed in the firsttime files, the following triples will not be updated");
// iterate all statements and check if the ones which should be removed were not changed via the UI
StmtIterator iter = changesUserModel.listStatements();
while (iter.hasNext()) {
Statement stmt = iter.nextStatement(); // get next statement
Resource subject = stmt.getSubject(); // get the subject
Property predicate = stmt.getPredicate(); // get the predicate
RDFNode object = stmt.getObject(); // get the object
StmtIterator iter2 = changesModel.listStatements();
while (iter2.hasNext()) {
Statement stmt2 = iter2.nextStatement(); // get next statement
Resource subject2 = stmt2.getSubject(); // get the subject
Property predicate2 = stmt2.getPredicate(); // get the predicate
RDFNode object2 = stmt2.getObject(); // get the object
// if subject and predicate are equal but the object differs and the language tag is the same, do not update these triples
// this case indicates an change in the UI, which should not be overwriten from the firsttime files
if(subject.equals(subject2) && predicate.equals(predicate2) && !object.equals(object2) ) {
// if object is an literal, check the language tag
if (object.isLiteral() && object2.isLiteral()) {
// if the langauge tag is the same, remove this triple from the update list
if(object.asLiteral().getLanguage().equals(object2.asLiteral().getLanguage())) {
log.debug("This two triples changed UI and files: \n UI: " + stmt + " \n file: " +stmt2);
changedInUIandFileStatements.add(stmt2);
}
} else {
log.debug("This two triples changed UI and files: \n UI: " + stmt + " \n file: " +stmt2);
changedInUIandFileStatements.add(stmt2);
}
}
}
}
// remove triples which were changed in the user model (UI) from the list
changesModel.remove(changedInUIandFileStatements);
} else {
log.debug("There were no changes in the user-model via UI compared to the backup-firsttime-model");
}
}
/* ===================================================================== */ /* ===================================================================== */
@Override @Override

View file

@ -3,6 +3,7 @@
package edu.cornell.mannlib.vitro.webapp.servlet.setup; package edu.cornell.mannlib.vitro.webapp.servlet.setup;
import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess.WhichService.CONTENT; import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess.WhichService.CONTENT;
import static edu.cornell.mannlib.vitro.webapp.servlet.setup.RDFFilesLoader.getEnabledLocales;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
@ -46,6 +47,7 @@ public class FileGraphSetup implements ServletContextListener {
private static final Log log = LogFactory.getLog(FileGraphSetup.class); private static final Log log = LogFactory.getLog(FileGraphSetup.class);
private static final String RDF = "rdf"; private static final String RDF = "rdf";
private static final String I18N = "i18n";
private static final String ABOX = "abox"; private static final String ABOX = "abox";
private static final String TBOX = "tbox"; private static final String TBOX = "tbox";
private static final String FILEGRAPH = "filegraph"; private static final String FILEGRAPH = "filegraph";
@ -76,6 +78,12 @@ public class FileGraphSetup implements ServletContextListener {
// ABox files // ABox files
Set<Path> paths = getFilegraphPaths(ctx, RDF, ABOX, FILEGRAPH); Set<Path> paths = getFilegraphPaths(ctx, RDF, ABOX, FILEGRAPH);
// Load ABox files from enabled languages
Set<String> enabledLocales = getEnabledLocales(ctx);
for (String locale : enabledLocales) {
paths.addAll(getFilegraphPaths(ctx, RDF, I18N, locale, ABOX, FILEGRAPH));
}
cleanupDB(dataset, pathsToURIs(paths, ABOX), ABOX); cleanupDB(dataset, pathsToURIs(paths, ABOX), ABOX);
// Just update the ABox filegraphs in the DB; don't attach them to a base model. // Just update the ABox filegraphs in the DB; don't attach them to a base model.
@ -84,6 +92,11 @@ public class FileGraphSetup implements ServletContextListener {
// TBox files // TBox files
paths = getFilegraphPaths(ctx, RDF, TBOX, FILEGRAPH); paths = getFilegraphPaths(ctx, RDF, TBOX, FILEGRAPH);
// Load TBox files from enabled languages
for (String locale : enabledLocales) {
paths.addAll(getFilegraphPaths(ctx, RDF, I18N, locale, TBOX, FILEGRAPH));
}
cleanupDB(dataset, pathsToURIs(paths, TBOX),TBOX); cleanupDB(dataset, pathsToURIs(paths, TBOX),TBOX);
OntModel tboxBaseModel = ModelAccess.on(ctx).getOntModel(ModelNames.TBOX_ASSERTIONS); OntModel tboxBaseModel = ModelAccess.on(ctx).getOntModel(ModelNames.TBOX_ASSERTIONS);

View file

@ -2,7 +2,6 @@
package edu.cornell.mannlib.vitro.webapp.servlet.setup; package edu.cornell.mannlib.vitro.webapp.servlet.setup;
import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -10,9 +9,13 @@ import java.nio.file.DirectoryStream;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set; import java.util.Set;
import java.util.TreeSet; import java.util.TreeSet;
import edu.cornell.mannlib.vitro.webapp.i18n.selection.SelectedLocale;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -23,6 +26,8 @@ import org.apache.jena.rdf.model.ModelFactory;
import edu.cornell.mannlib.vitro.webapp.application.ApplicationUtils; import edu.cornell.mannlib.vitro.webapp.application.ApplicationUtils;
import javax.servlet.ServletContext;
/** /**
* Help to load RDF files on first time and on every startup. * Help to load RDF files on first time and on every startup.
*/ */
@ -31,11 +36,12 @@ public class RDFFilesLoader {
private static final String DEFAULT_RDF_FORMAT = "RDF/XML"; private static final String DEFAULT_RDF_FORMAT = "RDF/XML";
private static final String RDF = "rdf"; private static final String RDF = "rdf";
private static final String I18N = "i18n";
private static final String FIRST_TIME = "firsttime"; private static final String FIRST_TIME = "firsttime";
private static final String EVERY_TIME = "everytime"; private static final String EVERY_TIME = "everytime";
/** /**
* Path filter that ignores sub-directories, hidden files, and markdown * Path filter that ignores sub-directories, hidden files and markdown
* files. * files.
*/ */
private static final DirectoryStream.Filter<Path> RDF_FILE_FILTER = new DirectoryStream.Filter<Path>() { private static final DirectoryStream.Filter<Path> RDF_FILE_FILTER = new DirectoryStream.Filter<Path>() {
@ -64,11 +70,20 @@ public class RDFFilesLoader {
* *
* The files from the directory are added to the model. * The files from the directory are added to the model.
*/ */
public static void loadFirstTimeFiles(String modelPath, Model model, public static void loadFirstTimeFiles(ServletContext ctx, String modelPath, Model model,
boolean firstTime) { boolean firstTime) {
if (firstTime) { if (firstTime) {
String home = locateHomeDirectory(); String home = locateHomeDirectory();
// Load common files
Set<Path> paths = getPaths(home, RDF, modelPath, FIRST_TIME); Set<Path> paths = getPaths(home, RDF, modelPath, FIRST_TIME);
// Load enabled languages
Set<String> enabledLocales = getEnabledLocales(ctx);
for (String locale : enabledLocales) {
paths.addAll(getPaths(home, RDF, I18N, locale, modelPath, FIRST_TIME));
}
for (Path p : paths) { for (Path p : paths) {
log.info("Loading " + relativePath(p, home)); log.info("Loading " + relativePath(p, home));
readOntologyFileIntoModel(p, model); readOntologyFileIntoModel(p, model);
@ -87,11 +102,20 @@ public class RDFFilesLoader {
* *
* The files from the directory become a sub-model of the model. * The files from the directory become a sub-model of the model.
*/ */
public static void loadEveryTimeFiles(String modelPath, OntModel model) { public static void loadEveryTimeFiles(ServletContext ctx, String modelPath, OntModel model) {
OntModel everytimeModel = ModelFactory OntModel everytimeModel = ModelFactory
.createOntologyModel(OntModelSpec.OWL_MEM); .createOntologyModel(OntModelSpec.OWL_MEM);
String home = locateHomeDirectory(); String home = locateHomeDirectory();
// Load common files
Set<Path> paths = getPaths(home, RDF, modelPath, EVERY_TIME); Set<Path> paths = getPaths(home, RDF, modelPath, EVERY_TIME);
// Load enabled languages
Set<String> enabledLocales = getEnabledLocales(ctx);
for (String locale : enabledLocales) {
paths.addAll(getPaths(home, RDF, I18N, locale, modelPath, EVERY_TIME));
}
for (Path p : paths) { for (Path p : paths) {
log.info("Loading " + relativePath(p, home)); log.info("Loading " + relativePath(p, home));
readOntologyFileIntoModel(p, everytimeModel); readOntologyFileIntoModel(p, everytimeModel);
@ -99,6 +123,23 @@ public class RDFFilesLoader {
model.addSubModel(everytimeModel); model.addSubModel(everytimeModel);
} }
public static Set<String> getEnabledLocales(ServletContext ctx) {
Set<String> enabledLocales = new HashSet<>();
// Which locales are enabled in runtime.properties?
List<Locale> locales = SelectedLocale.getSelectableLocales(ctx);
for (Locale locale : locales) {
enabledLocales.add(locale.toLanguageTag().replace('-', '_'));
}
// If no languages were enabled in runtime.properties, add 'en_US' as the default
if (enabledLocales.isEmpty()) {
enabledLocales.add("en_US");
}
return enabledLocales;
}
private static Path relativePath(Path p, String home) { private static Path relativePath(Path p, String home) {
try { try {
return Paths.get(home).relativize(p); return Paths.get(home).relativize(p);
@ -107,36 +148,9 @@ public class RDFFilesLoader {
} }
} }
/**
* Create a model from all the RDF files in the specified directory.
*/
public static OntModel getModelFromDir(File dir) {
OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
if (dir == null) {
log.warn("Must pass a File to getModelFromDir()");
return model;
}
if (!dir.isDirectory()) {
log.warn("Directory must be a File object for a directory");
return model;
}
if (!dir.canRead()) {
log.warn("getModelFromDir(): Directory "
+ " must be readable, check permissions on "
+ dir.getAbsolutePath());
return model;
}
Set<Path> paths = getPaths(dir.getPath());
for (Path p : paths) {
readOntologyFileIntoModel(p, model);
}
return model;
}
/** /**
* Find the paths to RDF files in this directory. Sub-directories, hidden * Find the paths to RDF files in this directory. Sub-directories, hidden
* files, and markdown files are ignored. * files, markdown, and non-enabled language files are ignored.
*/ */
private static Set<Path> getPaths(String parentDir, String... strings) { private static Set<Path> getPaths(String parentDir, String... strings) {
Path dir = Paths.get(parentDir, strings); Path dir = Paths.get(parentDir, strings);

View file

@ -6,7 +6,6 @@ import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.APPLICATIO
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;

View file

@ -534,8 +534,12 @@ public class UpdateKnowledgeBase {
try { try {
if (f.getName().endsWith(".md")) { if (f.getName().endsWith(".md")) {
// Markdown files are documentation - skip. // Markdown files are documentation - skip.
} else if (f.getName().endsWith(".n3")) { // UQAM-Optimization accept lower and upper case in fn extension
} else if (f.getName().toLowerCase().endsWith(".n3")) {
om.read(fis, null, "N3"); om.read(fis, null, "N3");
// UQAM-Optimization Accept Turtle (Must for us)
} else if (f.getName().toLowerCase().endsWith(".ttl")) {
om.read(fis, null, "TURTLE");
} else { } else {
om.read(fis, null, "RDF/XML"); om.read(fis, null, "RDF/XML");
} }

View file

@ -98,9 +98,11 @@ public class BasicShortTermCombinedTripleSource implements
@Override @Override
public WebappDaoFactoryConfig getWebappDaoFactoryConfig() { public WebappDaoFactoryConfig getWebappDaoFactoryConfig() {
List<String> langs = getPreferredLanguages(); List<String> langs = getPreferredLanguages();
List<Locale> locales = Collections.list(getPreferredLocales());
WebappDaoFactoryConfig config = new WebappDaoFactoryConfig(); WebappDaoFactoryConfig config = new WebappDaoFactoryConfig();
config.setDefaultNamespace(props.getProperty("Vitro.defaultNamespace")); config.setDefaultNamespace(props.getProperty("Vitro.defaultNamespace"));
config.setPreferredLanguages(langs); config.setPreferredLanguages(langs);
config.setPreferredLocales(locales);
config.setUnderlyingStoreReasoned(isStoreReasoned()); config.setUnderlyingStoreReasoned(isStoreReasoned());
config.setCustomListViewConfigFileMap(getCustomListViewConfigFileMap()); config.setCustomListViewConfigFileMap(getCustomListViewConfigFileMap());
return config; return config;
@ -111,7 +113,6 @@ public class BasicShortTermCombinedTripleSource implements
return LanguageFilteringUtils.localesToLanguages(getPreferredLocales()); return LanguageFilteringUtils.localesToLanguages(getPreferredLocales());
} }
@SuppressWarnings("unchecked")
private Enumeration<Locale> getPreferredLocales() { private Enumeration<Locale> getPreferredLocales() {
return req.getLocales(); return req.getLocales();
} }

View file

@ -165,7 +165,16 @@ public class SparqlQueryDataGetter extends DataGetterBase implements DataGetter{
private String bindParameters(String text, Map<String, String> merged) { private String bindParameters(String text, Map<String, String> merged) {
String bound = text; String bound = text;
for (String key : merged.keySet()) { for (String key : merged.keySet()) {
bound = bound.replaceAll("([?$]" + key + ")([^a-zA-Z0-9_\\-])", "<" + merged.get(key) + ">$2"); String value = merged.get(key);
if (value.startsWith("http://") || value.startsWith("https://")) {
/*
* UQAM-Optimization if the "value" looks like an URI then wrap the value with the characters '<' '>'
*
*/
bound = bound.replaceAll("([?$]" + key + ")([^a-zA-Z0-9_\\-])", "<" + value + ">$2");
} else {
bound = bound.replaceAll("([?$]" + key + ")([^a-zA-Z0-9_\\-])", value + "$2");
}
} }
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("parameters: " + merged); log.debug("parameters: " + merged);

View file

@ -21,6 +21,10 @@ import org.apache.commons.logging.LogFactory;
* check their current status. * check their current status.
*/ */
public class VitroBackgroundThread extends Thread { public class VitroBackgroundThread extends Thread {
// UQAM-Bug-Correction add start
public synchronized void start() {
super.start();
}
private static final Log log = LogFactory.getLog(VitroBackgroundThread.class); private static final Log log = LogFactory.getLog(VitroBackgroundThread.class);
private static final ConcurrentLinkedQueue<WeakReference<VitroBackgroundThread>> allThreads = new ConcurrentLinkedQueue<WeakReference<VitroBackgroundThread>>(); private static final ConcurrentLinkedQueue<WeakReference<VitroBackgroundThread>> allThreads = new ConcurrentLinkedQueue<WeakReference<VitroBackgroundThread>>();

View file

@ -20,8 +20,6 @@ import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource; import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamResult;
import edu.cornell.mannlib.vitro.webapp.beans.ApplicationBean;
import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document; import org.w3c.dom.Document;

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