]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
470476f2511e4f0e53ad6e199a5cf0634d649c9b
[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         private static Pattern kwdSearchHyphen = Pattern.compile(" - ");\r
70 \r
71         private static String getLikeForm() {\r
72                 if (SEARCH_LIKE_FORM == null) {\r
73                         try {\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
79                                 }\r
80                         } catch (Exception e) {\r
81                                 SEARCH_LIKE_FORM = IQueryManager.SEARCH_LIKE;\r
82                         }\r
83                 }\r
84                 return SEARCH_LIKE_FORM;\r
85         }\r
86 \r
87         // TODO: This is currently just an example fixed query. This should\r
88         // eventually be\r
89         // removed or replaced with a more generic method.\r
90         /*\r
91          * (non-Javadoc)\r
92          * \r
93          * @see\r
94          * org.collectionspace.services.common.query.IQueryManager#execQuery(java\r
95          * .lang.String)\r
96          */\r
97         @Override\r
98         @Deprecated\r
99         public void execQuery(String queryString) {\r
100                 NuxeoClientEmbedded client = null;\r
101                 try {\r
102                         client = NuxeoConnectorEmbedded.getInstance().getClient();\r
103                         RepositoryInstance repoSession = client.openRepository();\r
104 \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
112                                 System.out\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
120                         }\r
121 \r
122                 } catch (Exception e) {\r
123                         // TODO Auto-generated catch block\r
124                         e.printStackTrace();\r
125                 }\r
126         }\r
127 \r
128         @Override\r
129         public String createWhereClauseFromAdvancedSearch(String advancedSearch) {\r
130                 String result = null;\r
131                 //\r
132                 // Process search term.  FIXME: REM - Do we need to perform and string filtering here?\r
133                 //\r
134                 if (advancedSearch != null && !advancedSearch.isEmpty()) {\r
135                         StringBuffer advancedSearchWhereClause = new StringBuffer(\r
136                                         advancedSearch);\r
137                         result = advancedSearchWhereClause.toString();\r
138                 }\r
139                 \r
140                 return result;\r
141         }\r
142 \r
143         /*\r
144          * (non-Javadoc)\r
145          * \r
146          * @see org.collectionspace.services.common.query.IQueryManager#\r
147          * createWhereClauseFromKeywords(java.lang.String)\r
148          */\r
149         // TODO handle keywords containing escaped punctuation chars, then we need\r
150         // to qualify the\r
151         // search by matching on the fulltext.simpletext field.\r
152         // TODO handle keywords containing unescaped double quotes by matching the\r
153         // phrase\r
154         // against the fulltext.simpletext field.\r
155         // Both these require using JDBC, since we cannot get to the fulltext table\r
156         // in NXQL\r
157         @Override\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
171                                 continue;\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
176                                 addNOT = true;\r
177                                 continue;\r
178                         }\r
179                         // Next comment block of questionable value...\r
180                         \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
184                         // words,\r
185                         // and escaping single quotes. Can return a boolean for anything\r
186                         // stripped,\r
187                         // which triggers the back-up search. We can think about whether\r
188                         // stripping\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
194                         // }\r
195                         // Replace problem chars with spaces. Patches CSPACE-4147,\r
196                         // CSPACE-4106\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
202                                 }\r
203                                 continue;\r
204                         }\r
205 \r
206                         if (fullTextWhereClause.length()==0) {\r
207                                 fullTextWhereClause.append(SEARCH_GROUP_OPEN);\r
208                         }\r
209                         if (newWordSet) {\r
210                                 fullTextWhereClause.append(ECM_FULLTEXT_LIKE + "'");\r
211                                 newWordSet = false;\r
212                         } else {\r
213                                 fullTextWhereClause.append(SEARCH_TERM_SEPARATOR);\r
214                         }\r
215                         if(addNOT) {\r
216                                 fullTextWhereClause.append("-");        // Negate the next term\r
217                                 addNOT = false;\r
218                         }\r
219                         fullTextWhereClause.append(escapedAndTrimmed);\r
220                         \r
221                         if (logger.isTraceEnabled() == true) {\r
222                                 logger.trace("Current built whereClause is: "\r
223                                                 + fullTextWhereClause.toString());\r
224                         }\r
225                 }\r
226                 if (fullTextWhereClause.length()==0) {\r
227                         if (logger.isDebugEnabled() == true) {\r
228                                 logger.debug("No usable keywords specified in string:[" + keywords + "]");\r
229                         }\r
230                 } else {\r
231                         fullTextWhereClause.append("'" + SEARCH_GROUP_CLOSE);\r
232                 }\r
233 \r
234                 result = fullTextWhereClause.toString();\r
235                 if (logger.isDebugEnabled()) {\r
236                         logger.debug("Final built WHERE clause is: " + result);\r
237                 }\r
238 \r
239                 return result;\r
240         }\r
241 \r
242         /*\r
243          * (non-Javadoc)\r
244          * \r
245          * @see org.collectionspace.services.common.query.IQueryManager#\r
246          * createWhereClauseFromKeywords(java.lang.String)\r
247          */\r
248         // TODO handle keywords containing escaped punctuation chars, then we need\r
249         // to qualify the\r
250         // search by matching on the fulltext.simpletext field.\r
251         // TODO handle keywords containing unescaped double quotes by matching the\r
252         // phrase\r
253         // against the fulltext.simpletext field.\r
254         // Both these require using JDBC, since we cannot get to the fulltext table\r
255         // in NXQL\r
256         @Override\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
262                 }\r
263                 if (field == null || field.isEmpty()) {\r
264                         throw new RuntimeException("No match field specified.");\r
265                 }\r
266                 String ptClause = field + getLikeForm() + "'%"\r
267                                 + unescapedSingleQuote.matcher(trimmed).replaceAll("\\\\'")\r
268                                 + "%'";\r
269                 return ptClause;\r
270         }\r
271 \r
272         /**\r
273          * Creates a filtering where clause from docType, for invocables.\r
274          * \r
275          * @param docType\r
276          *            the docType\r
277          * \r
278          * @return the string\r
279          */\r
280         @Override\r
281         public String createWhereClauseForInvocableByDocType(String schema,\r
282                         String docType) {\r
283                 String trimmed = (docType == null) ? "" : docType.trim();\r
284                 if (trimmed.isEmpty()) {\r
285                         throw new RuntimeException("No docType specified.");\r
286                 }\r
287                 if (schema == null || schema.isEmpty()) {\r
288                         throw new RuntimeException("No match schema specified.");\r
289                 }\r
290                 String wClause = schema + ":" + InvocableJAXBSchema.FOR_DOC_TYPES\r
291                                 + " = '" + trimmed + "'";\r
292                 return wClause;\r
293         }\r
294 \r
295         /**\r
296          * Creates a filtering where clause from invocation mode, for invocables.\r
297          * \r
298          * @param mode\r
299          *            the mode\r
300          * \r
301          * @return the string\r
302          */\r
303         @Override\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
308                 }\r
309                 if (schema == null || schema.isEmpty()) {\r
310                         throw new RuntimeException("No match schema specified.");\r
311                 }\r
312                 String wClause = InvocableUtils.getPropertyNameForInvocationMode(\r
313                                 schema, trimmed) + " != 0";\r
314                 return wClause;\r
315         }\r
316 \r
317         /**\r
318          * @param input\r
319          * @return true if there were any chars filtered, that will require a backup\r
320          *         qualifying search on the actual text.\r
321          */\r
322         private boolean filterForFullText(String input) {\r
323                 boolean fFilteredChars = false;\r
324 \r
325                 return fFilteredChars;\r
326         }\r
327         \r
328         /**\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
335          */\r
336         @Override\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
344         } else {\r
345                 filterClause.append(fExclude?" NOT IN (":" IN (");\r
346                 for(int i=0; i<filterTerms.length; i++) {\r
347                         if(i>0) {\r
348                                 filterClause.append(',');\r
349                         }\r
350                         filterClause.append('\'');  \r
351                         filterClause.append(filterTerms[i]);\r
352                         filterClause.append('\'');  \r
353                 }\r
354                 filterClause.append(')');  \r
355         }\r
356         return filterClause.toString();\r
357         }\r
358 \r
359 }\r