]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
d5ecc330512465ad7f39ba9e3b6dd4ad2c322019
[tmp/jakarta-migration.git] /
1 /**     \r
2  * QueryManagerNuxeoImpl.java\r
3  *\r
4  * {Purpose of This Class}\r
5  *\r
6  * {Other Notes Relating to This Class (Optional)}\r
7  *\r
8  * $LastChangedBy: $\r
9  * $LastChangedRevision: $\r
10  * $LastChangedDate: $\r
11  *\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
15  *\r
16  * http://www.collectionspace.org\r
17  * http://wiki.collectionspace.org\r
18  *\r
19  * Copyright © 2009 {Contributing Institution}\r
20  *\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
23  *\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
26  */\r
27 package org.collectionspace.services.common.query.nuxeo;\r
28 \r
29 import org.slf4j.Logger;\r
30 import org.slf4j.LoggerFactory;\r
31 \r
32 import java.util.regex.Matcher;\r
33 import java.util.regex.Pattern;\r
34 \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
39 \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
45 \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
51 \r
52 public class QueryManagerNuxeoImpl implements IQueryManager {\r
53 \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
57 \r
58         private final Logger logger = LoggerFactory\r
59                         .getLogger(QueryManagerNuxeoImpl.class);\r
60 \r
61         // Consider that letters, letter-markers, numbers, '_' and apostrophe are\r
62         // words\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         // HACK to work around Nuxeo regression that tokenizes on '.'. \r
70         private static Pattern kwdSearchProblemChars = Pattern.compile("[\\:\\(\\)\\*\\%\\.]");\r
71         private static Pattern kwdSearchHyphen = Pattern.compile(" - ");\r
72 \r
73         private static String getLikeForm() {\r
74                 if (SEARCH_LIKE_FORM == null) {\r
75                         try {\r
76                                 DatabaseProductType type = JDBCTools.getDatabaseProductType();\r
77                                 if (type == DatabaseProductType.MYSQL) {\r
78                                         SEARCH_LIKE_FORM = IQueryManager.SEARCH_LIKE;\r
79                                 } else if (type == DatabaseProductType.POSTGRESQL) {\r
80                                         SEARCH_LIKE_FORM = IQueryManager.SEARCH_ILIKE;\r
81                                 }\r
82                         } catch (Exception e) {\r
83                                 SEARCH_LIKE_FORM = IQueryManager.SEARCH_LIKE;\r
84                         }\r
85                 }\r
86                 return SEARCH_LIKE_FORM;\r
87         }\r
88 \r
89         // TODO: This is currently just an example fixed query. This should\r
90         // eventually be\r
91         // removed or replaced with a more generic method.\r
92         /*\r
93          * (non-Javadoc)\r
94          * \r
95          * @see\r
96          * org.collectionspace.services.common.query.IQueryManager#execQuery(java\r
97          * .lang.String)\r
98          */\r
99         @Override\r
100         @Deprecated\r
101         public void execQuery(String queryString) {\r
102                 NuxeoClientEmbedded client = null;\r
103                 try {\r
104                         client = NuxeoConnectorEmbedded.getInstance().getClient();\r
105                         RepositoryInstance repoSession = client.openRepository();\r
106 \r
107                         DocumentModelList docModelList = repoSession\r
108                                         .query("SELECT * FROM Relation WHERE relations_common:subjectCsid='updated-Subject-1'");\r
109                         // DocumentModelList docModelList =\r
110                         // repoSession.query("SELECT * FROM Relation");\r
111                         // DocumentModelList docModelList =\r
112                         // repoSession.query("SELECT * FROM CollectionObject WHERE collectionobject:objectNumber='objectNumber-1251305545865'");\r
113                         for (DocumentModel docModel : docModelList) {\r
114                                 System.out\r
115                                                 .println("--------------------------------------------");\r
116                                 System.out.println(docModel.getPathAsString());\r
117                                 System.out.println(docModel.getName());\r
118                                 System.out.println(docModel.getPropertyValue("dc:title"));\r
119                                 // System.out.println("subjectCsid=" +\r
120                                 // docModel.getProperty("relations_common",\r
121                                 // "subjectCsid").toString());\r
122                         }\r
123 \r
124                 } catch (Exception e) {\r
125                         // TODO Auto-generated catch block\r
126                         e.printStackTrace();\r
127                 }\r
128         }\r
129 \r
130         @Override\r
131         public String createWhereClauseFromAdvancedSearch(String advancedSearch) {\r
132                 String result = null;\r
133                 //\r
134                 // Process search term.  FIXME: REM - Do we need to perform and string filtering here?\r
135                 //\r
136                 if (advancedSearch != null && !advancedSearch.isEmpty()) {\r
137                         StringBuffer advancedSearchWhereClause = new StringBuffer(\r
138                                         advancedSearch);\r
139                         result = advancedSearchWhereClause.toString();\r
140                 }\r
141                 \r
142                 return result;\r
143         }\r
144 \r
145         /*\r
146          * (non-Javadoc)\r
147          * \r
148          * @see org.collectionspace.services.common.query.IQueryManager#\r
149          * createWhereClauseFromKeywords(java.lang.String)\r
150          */\r
151         // TODO handle keywords containing escaped punctuation chars, then we need\r
152         // to qualify the\r
153         // search by matching on the fulltext.simpletext field.\r
154         // TODO handle keywords containing unescaped double quotes by matching the\r
155         // phrase\r
156         // against the fulltext.simpletext field.\r
157         // Both these require using JDBC, since we cannot get to the fulltext table\r
158         // in NXQL\r
159         @Override\r
160         public String createWhereClauseFromKeywords(String keywords) {\r
161                 String result = null;\r
162                 StringBuffer fullTextWhereClause = new StringBuffer();\r
163                 // Split on unescaped double quotes to handle phrases\r
164                 Matcher regexMatcher = kwdTokenizer.matcher(keywords.trim());\r
165                 boolean addNOT = false;\r
166                 boolean newWordSet = true;\r
167                 while (regexMatcher.find()) {\r
168                         String phrase = regexMatcher.group();\r
169                         // Not needed - already trimmed by split: \r
170                         // String trimmed = phrase.trim();\r
171                         // Ignore empty strings from match, or goofy input\r
172                         if (phrase.isEmpty())\r
173                                 continue;\r
174                         // Note we let OR through as is\r
175                         if("AND".equalsIgnoreCase(phrase)) {\r
176                                 continue;       // AND is default\r
177                         } else if("NOT".equalsIgnoreCase(phrase)) {\r
178                                 addNOT = true;\r
179                                 continue;\r
180                         }\r
181                         // Next comment block of questionable value...\r
182                         \r
183                         // ignore the special chars except single quote here - can't hurt\r
184                         // TODO this should become a special function that strips things the\r
185                         // fulltext will ignore, including non-word chars and too-short\r
186                         // words,\r
187                         // and escaping single quotes. Can return a boolean for anything\r
188                         // stripped,\r
189                         // which triggers the back-up search. We can think about whether\r
190                         // stripping\r
191                         // short words not in a quoted phrase should trigger the backup.\r
192                         String escapedAndTrimmed = unescapedSingleQuote.matcher(phrase).replaceAll("\\\\'");\r
193                         // If there are non-word chars in the phrase, we need to match the\r
194                         // phrase exactly against the fulltext table for this object\r
195                         // if(nonWordChars.matcher(trimmed).matches()) {\r
196                         // }\r
197                         // Replace problem chars with spaces. Patches CSPACE-4147,\r
198                         // CSPACE-4106\r
199                         escapedAndTrimmed = kwdSearchProblemChars.matcher(escapedAndTrimmed).replaceAll(" ").trim();\r
200                         escapedAndTrimmed = kwdSearchHyphen.matcher(escapedAndTrimmed).replaceAll(" ").trim();\r
201                         if(escapedAndTrimmed.isEmpty()) {\r
202                                 if (logger.isDebugEnabled() == true) {\r
203                                         logger.debug("Phrase reduced to empty after replacements: " + phrase);\r
204                                 }\r
205                                 continue;\r
206                         }\r
207 \r
208                         if (fullTextWhereClause.length()==0) {\r
209                                 fullTextWhereClause.append(SEARCH_GROUP_OPEN);\r
210                         }\r
211                         if (newWordSet) {\r
212                                 fullTextWhereClause.append(ECM_FULLTEXT_LIKE + "'");\r
213                                 newWordSet = false;\r
214                         } else {\r
215                                 fullTextWhereClause.append(SEARCH_TERM_SEPARATOR);\r
216                         }\r
217                         if(addNOT) {\r
218                                 fullTextWhereClause.append("-");        // Negate the next term\r
219                                 addNOT = false;\r
220                         }\r
221                         fullTextWhereClause.append(escapedAndTrimmed);\r
222                         \r
223                         if (logger.isTraceEnabled() == true) {\r
224                                 logger.trace("Current built whereClause is: "\r
225                                                 + fullTextWhereClause.toString());\r
226                         }\r
227                 }\r
228                 if (fullTextWhereClause.length()==0) {\r
229                         if (logger.isDebugEnabled() == true) {\r
230                                 logger.debug("No usable keywords specified in string:[" + keywords + "]");\r
231                         }\r
232                 } else {\r
233                         fullTextWhereClause.append("'" + SEARCH_GROUP_CLOSE);\r
234                 }\r
235 \r
236                 result = fullTextWhereClause.toString();\r
237                 if (logger.isDebugEnabled()) {\r
238                         logger.debug("Final built WHERE clause is: " + result);\r
239                 }\r
240 \r
241                 return result;\r
242         }\r
243 \r
244         /*\r
245          * (non-Javadoc)\r
246          * \r
247          * @see org.collectionspace.services.common.query.IQueryManager#\r
248          * createWhereClauseFromKeywords(java.lang.String)\r
249          */\r
250         // TODO handle keywords containing escaped punctuation chars, then we need\r
251         // to qualify the\r
252         // search by matching on the fulltext.simpletext field.\r
253         // TODO handle keywords containing unescaped double quotes by matching the\r
254         // phrase\r
255         // against the fulltext.simpletext field.\r
256         // Both these require using JDBC, since we cannot get to the fulltext table\r
257         // in NXQL\r
258         @Override\r
259         public String createWhereClauseForPartialMatch(String field,\r
260                         String partialTerm) {\r
261                 String trimmed = (partialTerm == null) ? "" : partialTerm.trim();\r
262                 if (trimmed.isEmpty()) {\r
263                         throw new RuntimeException("No partialTerm specified.");\r
264                 }\r
265                 if (field == null || field.isEmpty()) {\r
266                         throw new RuntimeException("No match field specified.");\r
267                 }\r
268                 String ptClause = field + getLikeForm() + "'%"\r
269                                 + unescapedSingleQuote.matcher(trimmed).replaceAll("\\\\'")\r
270                                 + "%'";\r
271                 return ptClause;\r
272         }\r
273 \r
274         /**\r
275          * Creates a filtering where clause from docType, for invocables.\r
276          * \r
277          * @param docType\r
278          *            the docType\r
279          * \r
280          * @return the string\r
281          */\r
282         @Override\r
283         public String createWhereClauseForInvocableByDocType(String schema,\r
284                         String docType) {\r
285                 String trimmed = (docType == null) ? "" : docType.trim();\r
286                 if (trimmed.isEmpty()) {\r
287                         throw new RuntimeException("No docType specified.");\r
288                 }\r
289                 if (schema == null || schema.isEmpty()) {\r
290                         throw new RuntimeException("No match schema specified.");\r
291                 }\r
292                 String wClause = schema + ":" + InvocableJAXBSchema.FOR_DOC_TYPES\r
293                                 + " = '" + trimmed + "'";\r
294                 return wClause;\r
295         }\r
296 \r
297         /**\r
298          * Creates a filtering where clause from invocation mode, for invocables.\r
299          * \r
300          * @param mode\r
301          *            the mode\r
302          * \r
303          * @return the string\r
304          */\r
305         @Override\r
306         public String createWhereClauseForInvocableByMode(String schema, String mode) {\r
307                 String trimmed = (mode == null) ? "" : mode.trim();\r
308                 if (trimmed.isEmpty()) {\r
309                         throw new RuntimeException("No docType specified.");\r
310                 }\r
311                 if (schema == null || schema.isEmpty()) {\r
312                         throw new RuntimeException("No match schema specified.");\r
313                 }\r
314                 String wClause = InvocableUtils.getPropertyNameForInvocationMode(\r
315                                 schema, trimmed) + " != 0";\r
316                 return wClause;\r
317         }\r
318 \r
319         /**\r
320          * @param input\r
321          * @return true if there were any chars filtered, that will require a backup\r
322          *         qualifying search on the actual text.\r
323          */\r
324         private boolean filterForFullText(String input) {\r
325                 boolean fFilteredChars = false;\r
326 \r
327                 return fFilteredChars;\r
328         }\r
329         \r
330         /**\r
331          * Creates a query to filter a qualified (string) field according to a list of string values. \r
332          * @param qualifiedField The schema-qualified field to filter on\r
333          * @param filterTerms the list of one or more strings to filter on\r
334          * @param fExclude If true, will require qualifiedField NOT match the filters strings.\r
335          *                                      If false, will require qualifiedField does match one of the filters strings.\r
336          * @return queryString\r
337          */\r
338         @Override\r
339         public String createWhereClauseToFilterFromStringList(String qualifiedField, String[] filterTerms, boolean fExclude) {\r
340         // Start with the qualified termStatus field\r
341         StringBuilder filterClause = new StringBuilder(qualifiedField);\r
342         if(filterTerms.length == 1) {\r
343                 filterClause.append(fExclude?" <> '":" = '");\r
344                 filterClause.append(filterTerms[0]);\r
345                 filterClause.append('\'');  \r
346         } else {\r
347                 filterClause.append(fExclude?" NOT IN (":" IN (");\r
348                 for(int i=0; i<filterTerms.length; i++) {\r
349                         if(i>0) {\r
350                                 filterClause.append(',');\r
351                         }\r
352                         filterClause.append('\'');  \r
353                         filterClause.append(filterTerms[i]);\r
354                         filterClause.append('\'');  \r
355                 }\r
356                 filterClause.append(')');  \r
357         }\r
358         return filterClause.toString();\r
359         }\r
360 \r
361 }\r