2 * QueryManagerNuxeoImpl.java
\r
4 * {Purpose of This Class}
\r
6 * {Other Notes Relating to This Class (Optional)}
\r
9 * $LastChangedRevision: $
\r
10 * $LastChangedDate: $
\r
12 * This document is a part of the source code and related artifacts
\r
13 * for CollectionSpace, an open source collections management system
\r
14 * for museums and related institutions:
\r
16 * http://www.collectionspace.org
\r
17 * http://wiki.collectionspace.org
\r
19 * Copyright © 2009 {Contributing Institution}
\r
21 * Licensed under the Educational Community License (ECL), Version 2.0.
\r
22 * You may not use this file except in compliance with this License.
\r
24 * You may obtain a copy of the ECL 2.0 License at
\r
25 * https://source.collectionspace.org/collection-space/LICENSE.txt
\r
27 package org.collectionspace.services.common.query.nuxeo;
\r
29 import org.slf4j.Logger;
\r
30 import org.slf4j.LoggerFactory;
\r
32 import java.util.regex.Matcher;
\r
33 import java.util.regex.Pattern;
\r
35 import org.nuxeo.ecm.core.api.DocumentModel;
\r
36 import org.nuxeo.ecm.core.api.DocumentModelList;
\r
37 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
\r
38 //import org.nuxeo.ecm.core.client.NuxeoClient;
\r
40 import org.collectionspace.services.jaxb.InvocableJAXBSchema;
\r
41 //import org.collectionspace.services.nuxeo.client.java.NuxeoConnector;
\r
42 //import org.collectionspace.services.nuxeo.client.java.NxConnect;
\r
43 import org.collectionspace.services.nuxeo.client.java.NuxeoClientEmbedded;
\r
44 import org.collectionspace.services.nuxeo.client.java.NuxeoConnectorEmbedded;
\r
46 import org.collectionspace.services.client.IQueryManager;
\r
47 import org.collectionspace.services.common.invocable.Invocable;
\r
48 import org.collectionspace.services.common.invocable.InvocableUtils;
\r
49 import org.collectionspace.services.common.storage.DatabaseProductType;
\r
50 import org.collectionspace.services.common.storage.JDBCTools;
\r
52 public class QueryManagerNuxeoImpl implements IQueryManager {
\r
54 private static String ECM_FULLTEXT_LIKE = "ecm:fulltext"
\r
55 + SEARCH_TERM_SEPARATOR + IQueryManager.SEARCH_LIKE;
\r
56 private static String SEARCH_LIKE_FORM = null;
\r
58 private final Logger logger = LoggerFactory
\r
59 .getLogger(QueryManagerNuxeoImpl.class);
\r
61 // Consider that letters, letter-markers, numbers, '_' and apostrophe are
\r
63 private static Pattern nonWordChars = Pattern
\r
64 .compile("[^\\p{L}\\p{M}\\p{N}_']");
\r
65 private static Pattern kwdTokenizer = Pattern.compile("(?:(['\"])(.*?)(?<!\\\\)(?>\\\\\\\\)*\\1|([^ ]+))");
\r
66 private static Pattern unescapedDblQuotes = Pattern.compile("(?<!\\\\)\"");
\r
67 private static Pattern unescapedSingleQuote = Pattern.compile("(?<!\\\\)'");
\r
68 private static Pattern kwdSearchProblemChars = Pattern.compile("[\\:\\(\\)\\*\\%]");
\r
69 private static Pattern kwdSearchHyphen = Pattern.compile(" - ");
\r
71 private static String getLikeForm() {
\r
72 if (SEARCH_LIKE_FORM == null) {
\r
74 DatabaseProductType type = JDBCTools.getDatabaseProductType();
\r
75 if (type == DatabaseProductType.MYSQL) {
\r
76 SEARCH_LIKE_FORM = IQueryManager.SEARCH_LIKE;
\r
77 } else if (type == DatabaseProductType.POSTGRESQL) {
\r
78 SEARCH_LIKE_FORM = IQueryManager.SEARCH_ILIKE;
\r
80 } catch (Exception e) {
\r
81 SEARCH_LIKE_FORM = IQueryManager.SEARCH_LIKE;
\r
84 return SEARCH_LIKE_FORM;
\r
87 // TODO: This is currently just an example fixed query. This should
\r
89 // removed or replaced with a more generic method.
\r
94 * org.collectionspace.services.common.query.IQueryManager#execQuery(java
\r
99 public void execQuery(String queryString) {
\r
100 NuxeoClientEmbedded client = null;
\r
102 client = NuxeoConnectorEmbedded.getInstance().getClient();
\r
103 RepositoryInstance repoSession = client.openRepository();
\r
105 DocumentModelList docModelList = repoSession
\r
106 .query("SELECT * FROM Relation WHERE relations_common:subjectCsid='updated-Subject-1'");
\r
107 // DocumentModelList docModelList =
\r
108 // repoSession.query("SELECT * FROM Relation");
\r
109 // DocumentModelList docModelList =
\r
110 // repoSession.query("SELECT * FROM CollectionObject WHERE collectionobject:objectNumber='objectNumber-1251305545865'");
\r
111 for (DocumentModel docModel : docModelList) {
\r
113 .println("--------------------------------------------");
\r
114 System.out.println(docModel.getPathAsString());
\r
115 System.out.println(docModel.getName());
\r
116 System.out.println(docModel.getPropertyValue("dc:title"));
\r
117 // System.out.println("subjectCsid=" +
\r
118 // docModel.getProperty("relations_common",
\r
119 // "subjectCsid").toString());
\r
122 } catch (Exception e) {
\r
123 // TODO Auto-generated catch block
\r
124 e.printStackTrace();
\r
129 public String createWhereClauseFromAdvancedSearch(String advancedSearch) {
\r
130 String result = null;
\r
132 // Process search term. FIXME: REM - Do we need to perform and string filtering here?
\r
134 if (advancedSearch != null && !advancedSearch.isEmpty()) {
\r
135 StringBuffer advancedSearchWhereClause = new StringBuffer(
\r
137 result = advancedSearchWhereClause.toString();
\r
146 * @see org.collectionspace.services.common.query.IQueryManager#
\r
147 * createWhereClauseFromKeywords(java.lang.String)
\r
149 // TODO handle keywords containing escaped punctuation chars, then we need
\r
151 // search by matching on the fulltext.simpletext field.
\r
152 // TODO handle keywords containing unescaped double quotes by matching the
\r
154 // against the fulltext.simpletext field.
\r
155 // Both these require using JDBC, since we cannot get to the fulltext table
\r
158 public String createWhereClauseFromKeywords(String keywords) {
\r
159 String result = null;
\r
160 StringBuffer fullTextWhereClause = new StringBuffer();
\r
161 // Split on unescaped double quotes to handle phrases
\r
162 Matcher regexMatcher = kwdTokenizer.matcher(keywords.trim());
\r
163 boolean addNOT = false;
\r
164 boolean newWordSet = true;
\r
165 while (regexMatcher.find()) {
\r
166 String phrase = regexMatcher.group();
\r
167 // Not needed - already trimmed by split:
\r
168 // String trimmed = phrase.trim();
\r
169 // Ignore empty strings from match, or goofy input
\r
170 if (phrase.isEmpty())
\r
172 // Note we let OR through as is
\r
173 if("AND".equalsIgnoreCase(phrase)) {
\r
174 continue; // AND is default
\r
175 } else if("NOT".equalsIgnoreCase(phrase)) {
\r
179 // Next comment block of questionable value...
\r
181 // ignore the special chars except single quote here - can't hurt
\r
182 // TODO this should become a special function that strips things the
\r
183 // fulltext will ignore, including non-word chars and too-short
\r
185 // and escaping single quotes. Can return a boolean for anything
\r
187 // which triggers the back-up search. We can think about whether
\r
189 // short words not in a quoted phrase should trigger the backup.
\r
190 String escapedAndTrimmed = unescapedSingleQuote.matcher(phrase).replaceAll("\\\\'");
\r
191 // If there are non-word chars in the phrase, we need to match the
\r
192 // phrase exactly against the fulltext table for this object
\r
193 // if(nonWordChars.matcher(trimmed).matches()) {
\r
195 // Replace problem chars with spaces. Patches CSPACE-4147,
\r
197 escapedAndTrimmed = kwdSearchProblemChars.matcher(escapedAndTrimmed).replaceAll(" ").trim();
\r
198 escapedAndTrimmed = kwdSearchHyphen.matcher(escapedAndTrimmed).replaceAll(" ").trim();
\r
199 if(escapedAndTrimmed.isEmpty()) {
\r
200 if (logger.isDebugEnabled() == true) {
\r
201 logger.debug("Phrase reduced to empty after replacements: " + phrase);
\r
206 if (fullTextWhereClause.length()==0) {
\r
207 fullTextWhereClause.append(SEARCH_GROUP_OPEN);
\r
210 fullTextWhereClause.append(ECM_FULLTEXT_LIKE + "'");
\r
211 newWordSet = false;
\r
213 fullTextWhereClause.append(SEARCH_TERM_SEPARATOR);
\r
216 fullTextWhereClause.append("-"); // Negate the next term
\r
219 fullTextWhereClause.append(escapedAndTrimmed);
\r
221 if (logger.isTraceEnabled() == true) {
\r
222 logger.trace("Current built whereClause is: "
\r
223 + fullTextWhereClause.toString());
\r
226 if (fullTextWhereClause.length()==0) {
\r
227 if (logger.isDebugEnabled() == true) {
\r
228 logger.debug("No usable keywords specified in string:[" + keywords + "]");
\r
231 fullTextWhereClause.append("'" + SEARCH_GROUP_CLOSE);
\r
234 result = fullTextWhereClause.toString();
\r
235 if (logger.isDebugEnabled()) {
\r
236 logger.debug("Final built WHERE clause is: " + result);
\r
245 * @see org.collectionspace.services.common.query.IQueryManager#
\r
246 * createWhereClauseFromKeywords(java.lang.String)
\r
248 // TODO handle keywords containing escaped punctuation chars, then we need
\r
250 // search by matching on the fulltext.simpletext field.
\r
251 // TODO handle keywords containing unescaped double quotes by matching the
\r
253 // against the fulltext.simpletext field.
\r
254 // Both these require using JDBC, since we cannot get to the fulltext table
\r
257 public String createWhereClauseForPartialMatch(String field,
\r
258 String partialTerm) {
\r
259 String trimmed = (partialTerm == null) ? "" : partialTerm.trim();
\r
260 if (trimmed.isEmpty()) {
\r
261 throw new RuntimeException("No partialTerm specified.");
\r
263 if (field == null || field.isEmpty()) {
\r
264 throw new RuntimeException("No match field specified.");
\r
266 String ptClause = field + getLikeForm() + "'%"
\r
267 + unescapedSingleQuote.matcher(trimmed).replaceAll("\\\\'")
\r
273 * Creates a filtering where clause from docType, for invocables.
\r
278 * @return the string
\r
281 public String createWhereClauseForInvocableByDocType(String schema,
\r
283 String trimmed = (docType == null) ? "" : docType.trim();
\r
284 if (trimmed.isEmpty()) {
\r
285 throw new RuntimeException("No docType specified.");
\r
287 if (schema == null || schema.isEmpty()) {
\r
288 throw new RuntimeException("No match schema specified.");
\r
290 String wClause = schema + ":" + InvocableJAXBSchema.FOR_DOC_TYPES
\r
291 + " = '" + trimmed + "'";
\r
296 * Creates a filtering where clause from invocation mode, for invocables.
\r
301 * @return the string
\r
304 public String createWhereClauseForInvocableByMode(String schema, String mode) {
\r
305 String trimmed = (mode == null) ? "" : mode.trim();
\r
306 if (trimmed.isEmpty()) {
\r
307 throw new RuntimeException("No docType specified.");
\r
309 if (schema == null || schema.isEmpty()) {
\r
310 throw new RuntimeException("No match schema specified.");
\r
312 String wClause = InvocableUtils.getPropertyNameForInvocationMode(
\r
313 schema, trimmed) + " != 0";
\r
319 * @return true if there were any chars filtered, that will require a backup
\r
320 * qualifying search on the actual text.
\r
322 private boolean filterForFullText(String input) {
\r
323 boolean fFilteredChars = false;
\r
325 return fFilteredChars;
\r
329 * Creates a query to filter a qualified (string) field according to a list of string values.
\r
330 * @param qualifiedField The schema-qualified field to filter on
\r
331 * @param filterTerms the list of one or more strings to filter on
\r
332 * @param fExclude If true, will require qualifiedField NOT match the filters strings.
\r
333 * If false, will require qualifiedField does match one of the filters strings.
\r
334 * @return queryString
\r
337 public String createWhereClauseToFilterFromStringList(String qualifiedField, String[] filterTerms, boolean fExclude) {
\r
338 // Start with the qualified termStatus field
\r
339 StringBuilder filterClause = new StringBuilder(qualifiedField);
\r
340 if(filterTerms.length == 1) {
\r
341 filterClause.append(fExclude?" <> '":" = '");
\r
342 filterClause.append(filterTerms[0]);
\r
343 filterClause.append('\'');
\r
345 filterClause.append(fExclude?" NOT IN (":" IN (");
\r
346 for(int i=0; i<filterTerms.length; i++) {
\r
348 filterClause.append(',');
\r
350 filterClause.append('\'');
\r
351 filterClause.append(filterTerms[i]);
\r
352 filterClause.append('\'');
\r
354 filterClause.append(')');
\r
356 return filterClause.toString();
\r