]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
58c5788e1dac3488e35753b2902ce98c5629095a
[tmp/jakarta-migration.git] /
1 /**\r
2  * This document is a part of the source code and related artifacts for\r
3  * CollectionSpace, an open source collections management system for museums and\r
4  * related institutions:\r
5  *\r
6  * http://www.collectionspace.org http://wiki.collectionspace.org\r
7  *\r
8  * Copyright 2009 University of California at Berkeley\r
9  *\r
10  * Licensed under the Educational Community License (ECL), Version 2.0. You may\r
11  * not use this file except in compliance with this License.\r
12  *\r
13  * You may obtain a copy of the ECL 2.0 License at\r
14  *\r
15  * https://source.collectionspace.org/collection-space/LICENSE.txt\r
16  *\r
17  * Unless required by applicable law or agreed to in writing, software\r
18  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\r
19  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r
20  * License for the specific language governing permissions and limitations under\r
21  * the License.\r
22  */\r
23 package org.collectionspace.services.common.vocabulary;\r
24 \r
25 import java.util.ArrayList;\r
26 import java.util.HashMap;\r
27 import java.util.Iterator;\r
28 import java.util.List;\r
29 import java.util.Map;\r
30 \r
31 import org.nuxeo.ecm.core.api.ClientException;\r
32 import org.nuxeo.ecm.core.api.DocumentModel;\r
33 import org.nuxeo.ecm.core.api.DocumentModelList;\r
34 import org.nuxeo.ecm.core.api.model.Property;\r
35 import org.nuxeo.ecm.core.api.model.PropertyException;\r
36 import org.nuxeo.ecm.core.api.model.PropertyNotFoundException;\r
37 import org.nuxeo.ecm.core.api.model.impl.primitives.StringProperty;\r
38 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;\r
39 import org.slf4j.Logger;\r
40 import org.slf4j.LoggerFactory;\r
41 \r
42 import org.collectionspace.services.client.CollectionSpaceClient;\r
43 import org.collectionspace.services.client.IRelationsManager;\r
44 import org.collectionspace.services.client.PoxPayloadIn;\r
45 import org.collectionspace.services.client.PoxPayloadOut;\r
46 import org.collectionspace.services.common.ServiceMain;\r
47 import org.collectionspace.services.common.StoredValuesUriTemplate;\r
48 import org.collectionspace.services.common.UriTemplateFactory;\r
49 import org.collectionspace.services.common.UriTemplateRegistry;\r
50 import org.collectionspace.services.common.UriTemplateRegistryKey;\r
51 import org.collectionspace.services.common.context.ServiceContext;\r
52 import org.collectionspace.services.common.context.AbstractServiceContextImpl;\r
53 import org.collectionspace.services.common.api.RefNameUtils;\r
54 import org.collectionspace.services.common.api.Tools;\r
55 import org.collectionspace.services.common.api.RefNameUtils.AuthorityTermInfo;\r
56 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;\r
57 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;\r
58 import org.collectionspace.services.common.context.ServiceBindingUtils;\r
59 import org.collectionspace.services.common.document.DocumentException;\r
60 import org.collectionspace.services.common.document.DocumentFilter;\r
61 import org.collectionspace.services.common.document.DocumentNotFoundException;\r
62 import org.collectionspace.services.common.document.DocumentUtils;\r
63 import org.collectionspace.services.common.document.DocumentWrapper;\r
64 import org.collectionspace.services.common.query.QueryManager;\r
65 import org.collectionspace.services.common.relation.RelationUtils;\r
66 import org.collectionspace.services.common.repository.RepositoryClient;\r
67 import org.collectionspace.services.nuxeo.client.java.DocHandlerBase;\r
68 import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl;\r
69 import org.collectionspace.services.common.security.SecurityUtils;\r
70 import org.collectionspace.services.config.service.ServiceBindingType;\r
71 import org.collectionspace.services.jaxb.AbstractCommonList;\r
72 import org.collectionspace.services.nuxeo.util.NuxeoUtils;\r
73 \r
74 /**\r
75  * RefNameServiceUtils is a collection of services utilities related to refName\r
76  * usage.\r
77  *\r
78  * $LastChangedRevision: $ $LastChangedDate: $\r
79  */\r
80 public class RefNameServiceUtils {\r
81 \r
82     public static class AuthRefConfigInfo {\r
83 \r
84         public String getQualifiedDisplayName() {\r
85             return (Tools.isBlank(schema))\r
86                     ? displayName : DocumentUtils.appendSchemaName(schema, displayName);\r
87         }\r
88 \r
89         public String getDisplayName() {\r
90             return displayName;\r
91         }\r
92 \r
93         public void setDisplayName(String displayName) {\r
94             this.displayName = displayName;\r
95         }\r
96         String displayName;\r
97         String schema;\r
98 \r
99         public String getSchema() {\r
100             return schema;\r
101         }\r
102 \r
103         public void setSchema(String schema) {\r
104             this.schema = schema;\r
105         }\r
106 \r
107         public String getFullPath() {\r
108             return fullPath;\r
109         }\r
110 \r
111         public void setFullPath(String fullPath) {\r
112             this.fullPath = fullPath;\r
113         }\r
114         String fullPath;\r
115         protected String[] pathEls;\r
116 \r
117         public AuthRefConfigInfo(AuthRefConfigInfo arci) {\r
118             this.displayName = arci.displayName;\r
119             this.schema = arci.schema;\r
120             this.fullPath = arci.fullPath;\r
121             this.pathEls = arci.pathEls;\r
122             // Skip the pathElse check, since we are creatign from another (presumably valid) arci.\r
123         }\r
124 \r
125         public AuthRefConfigInfo(String displayName, String schema, String fullPath, String[] pathEls) {\r
126             this.displayName = displayName;\r
127             this.schema = schema;\r
128             this.fullPath = fullPath;\r
129             this.pathEls = pathEls;\r
130             checkPathEls();\r
131         }\r
132 \r
133         // Split a config value string like "intakes_common:collector", or\r
134         // "collectionobjects_common:contentPeoples|contentPeople"\r
135         // "collectionobjects_common:assocEventGroupList/*/assocEventPlace"\r
136         // If has a pipe ('|') second part is a displayLabel, and first is path\r
137         // Otherwise, entry is a path, and can use the last pathElement as displayName\r
138         // Should be schema qualified.\r
139         public AuthRefConfigInfo(String configString) {\r
140             String[] pair = configString.split("\\|", 2);\r
141             String[] pathEls;\r
142             String displayName, fullPath;\r
143             if (pair.length == 1) {\r
144                 // no label specifier, so we'll defer getting label\r
145                 fullPath = pair[0];\r
146                 pathEls = pair[0].split("/");\r
147                 displayName = pathEls[pathEls.length - 1];\r
148             } else {\r
149                 fullPath = pair[0];\r
150                 pathEls = pair[0].split("/");\r
151                 displayName = pair[1];\r
152             }\r
153             String[] schemaSplit = pathEls[0].split(":", 2);\r
154             String schema;\r
155             if (schemaSplit.length == 1) {    // schema not specified\r
156                 schema = null;\r
157             } else {\r
158                 schema = schemaSplit[0];\r
159                 if (pair.length == 1 && pathEls.length == 1) {    // simplest case of field in top level schema, no labelll\r
160                     displayName = schemaSplit[1];    // Have to fix up displayName to have no schema\r
161                 }\r
162             }\r
163             this.displayName = displayName;\r
164             this.schema = schema;\r
165             this.fullPath = fullPath;\r
166             this.pathEls = pathEls;\r
167             checkPathEls();\r
168         }\r
169 \r
170         protected void checkPathEls() {\r
171             int len = pathEls.length;\r
172             if (len < 1) {\r
173                 throw new InternalError("Bad values in authRef info - caller screwed up:" + fullPath);\r
174             }\r
175             // Handle case of them putting a leading slash on the path\r
176             if (len > 1 && pathEls[0].endsWith(":")) {\r
177                 len--;\r
178                 String[] newArray = new String[len];\r
179                 newArray[0] = pathEls[0] + pathEls[1];\r
180                 if (len >= 2) {\r
181                     System.arraycopy(pathEls, 2, newArray, 1, len - 1);\r
182                 }\r
183                 pathEls = newArray;\r
184             }\r
185         }\r
186     }\r
187 \r
188     public static class AuthRefInfo extends AuthRefConfigInfo {\r
189 \r
190         public Property getProperty() {\r
191             return property;\r
192         }\r
193 \r
194         public void setProperty(Property property) {\r
195             this.property = property;\r
196         }\r
197         Property property;\r
198 \r
199         public AuthRefInfo(String displayName, String schema, String fullPath, String[] pathEls, Property prop) {\r
200             super(displayName, schema, fullPath, pathEls);\r
201             this.property = prop;\r
202         }\r
203 \r
204         public AuthRefInfo(AuthRefConfigInfo arci, Property prop) {\r
205             super(arci);\r
206             this.property = prop;\r
207         }\r
208     }\r
209     \r
210     private static final Logger logger = LoggerFactory.getLogger(RefNameServiceUtils.class);\r
211     private static ArrayList<String> refNameServiceTypes = null;\r
212 \r
213     public static void updateRefNamesInRelations(\r
214             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,\r
215             RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient,\r
216             RepositoryInstance repoSession,\r
217             String oldRefName,\r
218             String newRefName) {\r
219         //\r
220         // First, look for and update all the places where the refName is the "subject" of the relationship\r
221         //\r
222         RelationUtils.updateRefNamesInRelations(ctx, repoClient, repoSession, IRelationsManager.SUBJECT_REFNAME, oldRefName, newRefName);\r
223         \r
224         //\r
225         // Next, look for and update all the places where the refName is the "object" of the relationship\r
226         //\r
227         RelationUtils.updateRefNamesInRelations(ctx, repoClient, repoSession, IRelationsManager.OBJECT_REFNAME, oldRefName, newRefName);\r
228     }\r
229     \r
230     public static List<AuthRefConfigInfo> getConfiguredAuthorityRefs(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {\r
231         List<String> authRefFields =\r
232                 ((AbstractServiceContextImpl) ctx).getAllPartsPropertyValues(\r
233                 ServiceBindingUtils.AUTH_REF_PROP, ServiceBindingUtils.QUALIFIED_PROP_NAMES);\r
234         ArrayList<AuthRefConfigInfo> authRefsInfo = new ArrayList<AuthRefConfigInfo>(authRefFields.size());\r
235         for (String spec : authRefFields) {\r
236             AuthRefConfigInfo arci = new AuthRefConfigInfo(spec);\r
237             authRefsInfo.add(arci);\r
238         }\r
239         return authRefsInfo;\r
240     }\r
241 \r
242     public static AuthorityRefDocList getAuthorityRefDocs(\r
243             RepositoryInstance repoSession,\r
244             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,\r
245             UriTemplateRegistry uriTemplateRegistry,\r
246             RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient,\r
247             List<String> serviceTypes,\r
248             String refName,\r
249             String refPropName, // authRef or termRef, authorities or vocab terms.\r
250             DocumentFilter filter, boolean computeTotal)\r
251             throws DocumentException, DocumentNotFoundException {\r
252         AuthorityRefDocList wrapperList = new AuthorityRefDocList();\r
253         AbstractCommonList commonList = (AbstractCommonList) wrapperList;\r
254         int pageNum = filter.getStartPage();\r
255         int pageSize = filter.getPageSize();\r
256         \r
257         List<AuthorityRefDocList.AuthorityRefDocItem> list =\r
258                 wrapperList.getAuthorityRefDocItem();\r
259 \r
260         Map<String, ServiceBindingType> queriedServiceBindings = new HashMap<String, ServiceBindingType>();\r
261         Map<String, List<AuthRefConfigInfo>> authRefFieldsByService = new HashMap<String, List<AuthRefConfigInfo>>();\r
262 \r
263         RepositoryJavaClientImpl nuxeoRepoClient = (RepositoryJavaClientImpl) repoClient;\r
264         try {\r
265             // Ignore any provided page size and number query parameters in\r
266             // the following call, as they pertain to the list of authority\r
267             // references to be returned, not to the list of documents to be\r
268             // scanned for those references.\r
269             DocumentModelList docList = findAuthorityRefDocs(ctx, repoClient, repoSession,\r
270                     serviceTypes, refName, refPropName, queriedServiceBindings, authRefFieldsByService,\r
271                     filter.getWhereClause(), null, 0 /* pageSize */, 0 /* pageNum */, computeTotal);\r
272 \r
273             if (docList == null) { // found no authRef fields - nothing to process\r
274                 return wrapperList;\r
275             }\r
276 \r
277             // set the fieldsReturned list. Even though this is a fixed schema, app layer treats\r
278             // this like other abstract common lists\r
279             /*\r
280              * <xs:element name="docType" type="xs:string" minOccurs="1" />\r
281              * <xs:element name="docId" type="xs:string" minOccurs="1" />\r
282              * <xs:element name="docNumber" type="xs:string" minOccurs="0" />\r
283              * <xs:element name="docName" type="xs:string" minOccurs="0" />\r
284              * <xs:element name="sourceField" type="xs:string" minOccurs="1" />\r
285              * <xs:element name="uri" type="xs:anyURI" minOccurs="1" />\r
286              * <xs:element name="updatedAt" type="xs:string" minOccurs="1" />\r
287              * <xs:element name="workflowState" type="xs:string" minOccurs="1"\r
288              * />\r
289              */\r
290             String fieldList = "docType|docId|docNumber|docName|sourceField|uri|updatedAt|workflowState";\r
291             commonList.setFieldsReturned(fieldList);\r
292 \r
293             // As a side-effect, the method called below modifies the value of\r
294             // the 'list' variable, which holds the list of references to\r
295             // an authority item.\r
296             //\r
297             // There can be more than one reference to a particular authority\r
298             // item within any individual document scanned, so the number of\r
299             // authority references may potentially exceed the total number\r
300             // of documents scanned.\r
301 \r
302             // Strip off displayName and only match the base, so we get references to all \r
303             // the NPTs as well as the PT.\r
304                 String strippedRefName = RefNameUtils.stripAuthorityTermDisplayName(refName);\r
305             int nRefsFound = processRefObjsDocList(docList, ctx.getTenantId(), strippedRefName, true, queriedServiceBindings, authRefFieldsByService, // the actual list size needs to be updated to the size of "list"\r
306                     list, null);\r
307 \r
308             commonList.setPageSize(pageSize);\r
309             \r
310             // Values returned in the pagination block above the list items\r
311             // need to reflect the number of references to authority items\r
312             // returned, rather than the number of documents originally scanned\r
313             // to find such references.\r
314             commonList.setPageNum(pageNum);\r
315             commonList.setTotalItems(list.size());\r
316 \r
317             // Slice the list to return only the specified page of items\r
318             // in the list results.\r
319             //\r
320             // FIXME: There may well be a pattern-based way to do this\r
321             // in our framework, and if we can eliminate much of the\r
322             // non-DRY code below, that would be desirable.\r
323             \r
324             int startIndex = 0;\r
325             int endIndex = 0;\r
326             \r
327             // Return all results if pageSize is 0.\r
328             if (pageSize == 0) {\r
329                 startIndex = 0;\r
330                 endIndex = list.size();\r
331             } else {\r
332                startIndex = pageNum * pageSize;\r
333             }\r
334             \r
335             // Return an empty list when the start of the requested page is\r
336             // beyond the last item in the list.\r
337             if (startIndex > list.size()) {\r
338                 wrapperList.getAuthorityRefDocItem().clear();\r
339                 commonList.setItemsInPage(wrapperList.getAuthorityRefDocItem().size());\r
340                 return wrapperList;\r
341             }\r
342 \r
343             // Otherwise, return a list of items from the start of the specified\r
344             // page through the last item on that page, or otherwise through the\r
345             // last item in the entire list, if that occurs earlier than the end\r
346             // of the specified page.\r
347             if (endIndex == 0) {\r
348                 int pageEndIndex = ((startIndex + pageSize));\r
349                 endIndex = (pageEndIndex > list.size()) ? list.size() : pageEndIndex;\r
350             }\r
351             \r
352             // Slice the list to return only the specified page of results.\r
353             // Note: the second argument to List.subList(), endIndex, is\r
354             // exclusive of the item at its index position, reflecting the\r
355             // zero-index nature of the list.\r
356             List<AuthorityRefDocList.AuthorityRefDocItem> currentPageList =\r
357                     new ArrayList<AuthorityRefDocList.AuthorityRefDocItem>(list.subList(startIndex, endIndex));\r
358             wrapperList.getAuthorityRefDocItem().clear();\r
359             wrapperList.getAuthorityRefDocItem().addAll(currentPageList);\r
360             commonList.setItemsInPage(currentPageList.size());\r
361             \r
362             if (logger.isDebugEnabled() && (nRefsFound < docList.size())) {\r
363                 logger.debug("Internal curiosity: got fewer matches of refs than # docs matched..."); // We found a ref to ourself and have excluded it.\r
364             }\r
365         } catch (Exception e) {\r
366             logger.error("Could not retrieve a list of documents referring to the specified authority item", e);\r
367             wrapperList = null;\r
368         }\r
369 \r
370         return wrapperList;\r
371     }\r
372 \r
373     private static ArrayList<String> getRefNameServiceTypes() {\r
374         if (refNameServiceTypes == null) {\r
375             refNameServiceTypes = new ArrayList<String>();\r
376             refNameServiceTypes.add(ServiceBindingUtils.SERVICE_TYPE_AUTHORITY);\r
377             refNameServiceTypes.add(ServiceBindingUtils.SERVICE_TYPE_OBJECT);\r
378             refNameServiceTypes.add(ServiceBindingUtils.SERVICE_TYPE_PROCEDURE);\r
379         }\r
380         return refNameServiceTypes;\r
381     }\r
382     \r
383     // Seems like a good value - no real data to set this well.\r
384     // Note: can set this value lower during debugging; e.g. to 3 - ADR 2012-07-10\r
385     private static final int N_OBJS_TO_UPDATE_PER_LOOP = 100;\r
386 \r
387     public static int updateAuthorityRefDocs(\r
388             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,\r
389             RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient,\r
390             RepositoryInstance repoSession,\r
391             String oldRefName,\r
392             String newRefName,\r
393             String refPropName) throws Exception {\r
394         Map<String, ServiceBindingType> queriedServiceBindings = new HashMap<String, ServiceBindingType>();\r
395         Map<String, List<AuthRefConfigInfo>> authRefFieldsByService = new HashMap<String, List<AuthRefConfigInfo>>();\r
396 \r
397         int docsScanned = 0;\r
398         int nRefsFound = 0;\r
399         int currentPage = 0;\r
400         int docsInCurrentPage = 0;\r
401         final String WHERE_CLAUSE_ADDITIONS_VALUE = null;\r
402         final String ORDER_BY_VALUE = CollectionSpaceClient.CORE_CREATED_AT; // "collectionspace_core:createdAt";\r
403 \r
404         if (repoClient instanceof RepositoryJavaClientImpl == false) {\r
405             throw new InternalError("updateAuthorityRefDocs() called with unknown repoClient type!");\r
406         }\r
407         \r
408         try { // REM - How can we deal with transaction and timeout issues here?\r
409             final int pageSize = N_OBJS_TO_UPDATE_PER_LOOP;\r
410             DocumentModelList docList;\r
411             boolean morePages = true;\r
412             while (morePages) {\r
413 \r
414                 docList = findAuthorityRefDocs(ctx, repoClient, repoSession,\r
415                         getRefNameServiceTypes(), oldRefName, refPropName,\r
416                         queriedServiceBindings, authRefFieldsByService, WHERE_CLAUSE_ADDITIONS_VALUE, ORDER_BY_VALUE, pageSize, currentPage, false);\r
417 \r
418                 if (docList == null) {\r
419                     logger.debug("updateAuthorityRefDocs: no documents could be found that referenced the old refName");\r
420                     break;\r
421                 }\r
422                 docsInCurrentPage = docList.size();\r
423                 logger.debug("updateAuthorityRefDocs: current page=" + currentPage + " documents included in page=" + docsInCurrentPage);\r
424                 if (docsInCurrentPage == 0) {\r
425                     logger.debug("updateAuthorityRefDocs: no more documents requiring refName updates could be found");\r
426                     break;\r
427                 }\r
428                 if (docsInCurrentPage < pageSize) {\r
429                     logger.debug("updateAuthorityRefDocs: assuming no more documents requiring refName updates will be found, as docsInCurrentPage < pageSize");\r
430                     morePages = false;\r
431                 }\r
432 \r
433                 // Only match complete refNames - unless and until we decide how to resolve changes\r
434                 // to NPTs we will defer that and only change PTs or refNames as passed in.\r
435                 int nRefsFoundThisPage = processRefObjsDocList(docList, ctx.getTenantId(), oldRefName, false, queriedServiceBindings, authRefFieldsByService, // Perform the refName updates on the list of document models\r
436                         null, newRefName);\r
437                 if (nRefsFoundThisPage > 0) {\r
438                     ((RepositoryJavaClientImpl) repoClient).saveDocListWithoutHandlerProcessing(ctx, repoSession, docList, true); // Flush the document model list out to Nuxeo storage\r
439                     nRefsFound += nRefsFoundThisPage;\r
440                 }\r
441 \r
442                 // FIXME: Per REM, set a limit of num objects - something like\r
443                 // 1000K objects - and also add a log Warning after some threshold\r
444                 docsScanned += docsInCurrentPage;\r
445                 if (morePages) {\r
446                     currentPage++;\r
447                 }\r
448 \r
449             }\r
450         } catch (Exception e) {\r
451             logger.error("Internal error updating the AuthorityRefDocs: " + e.getLocalizedMessage());\r
452             logger.debug(Tools.errorToString(e, true));\r
453             throw e;\r
454         }\r
455         logger.debug("updateAuthorityRefDocs replaced a total of " + nRefsFound + " authority references, within as many as " + docsScanned + " scanned document(s)");\r
456         return nRefsFound;\r
457     }\r
458 \r
459     private static DocumentModelList findAuthorityRefDocs(\r
460             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,\r
461             RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient,\r
462             RepositoryInstance repoSession, List<String> serviceTypes,\r
463             String refName,\r
464             String refPropName,\r
465             Map<String, ServiceBindingType> queriedServiceBindings,\r
466             Map<String, List<AuthRefConfigInfo>> authRefFieldsByService,\r
467             String whereClauseAdditions,\r
468             String orderByClause,\r
469             int pageSize,\r
470             int pageNum,\r
471             boolean computeTotal) throws DocumentException, DocumentNotFoundException {\r
472 \r
473         // Get the service bindings for this tenant\r
474         TenantBindingConfigReaderImpl tReader =\r
475                 ServiceMain.getInstance().getTenantBindingConfigReader();\r
476         // We need to get all the procedures, authorities, and objects.\r
477         List<ServiceBindingType> servicebindings = tReader.getServiceBindingsByType(ctx.getTenantId(), serviceTypes);\r
478         if (servicebindings == null || servicebindings.isEmpty()) {\r
479             logger.error("RefNameServiceUtils.getAuthorityRefDocs: No services bindings found, cannot proceed!");\r
480             return null;\r
481         }\r
482         // Filter the list for current user rights\r
483         servicebindings = SecurityUtils.getReadableServiceBindingsForCurrentUser(servicebindings);\r
484 \r
485         ArrayList<String> docTypes = new ArrayList<String>();\r
486 \r
487         String query = computeWhereClauseForAuthorityRefDocs(refName, refPropName, docTypes, servicebindings, // REM - Side effect that docTypes array gets set.  Any others?\r
488                 queriedServiceBindings, authRefFieldsByService);\r
489         if (query == null) { // found no authRef fields - nothing to query\r
490             return null;\r
491         }\r
492         // Additional qualifications, like workflow state\r
493         if (Tools.notBlank(whereClauseAdditions)) {\r
494             query += " AND " + whereClauseAdditions;\r
495         }\r
496         // Now we have to issue the search\r
497         RepositoryJavaClientImpl nuxeoRepoClient = (RepositoryJavaClientImpl) repoClient;\r
498         DocumentWrapper<DocumentModelList> docListWrapper = nuxeoRepoClient.findDocs(ctx, repoSession,\r
499                 docTypes, query, orderByClause, pageSize, pageNum, computeTotal);\r
500         // Now we gather the info for each document into the list and return\r
501         DocumentModelList docList = docListWrapper.getWrappedObject();\r
502         return docList;\r
503     }\r
504     private static final boolean READY_FOR_COMPLEX_QUERY = true;\r
505 \r
506     private static String computeWhereClauseForAuthorityRefDocs(\r
507             String refName,\r
508             String refPropName,\r
509             ArrayList<String> docTypes,\r
510             List<ServiceBindingType> servicebindings,\r
511             Map<String, ServiceBindingType> queriedServiceBindings,\r
512             Map<String, List<AuthRefConfigInfo>> authRefFieldsByService) {\r
513 \r
514         boolean fFirst = true;\r
515         List<String> authRefFieldPaths;\r
516         for (ServiceBindingType sb : servicebindings) {\r
517             // Gets the property names for each part, qualified with the part label (which\r
518             // is also the table name, the way that the repository works).\r
519             authRefFieldPaths =\r
520                     ServiceBindingUtils.getAllPartsPropertyValues(sb,\r
521                     refPropName, ServiceBindingUtils.QUALIFIED_PROP_NAMES);\r
522             if (authRefFieldPaths.isEmpty()) {\r
523                 continue;\r
524             }\r
525             ArrayList<AuthRefConfigInfo> authRefsInfo = new ArrayList<AuthRefConfigInfo>();\r
526             for (String spec : authRefFieldPaths) {\r
527                 AuthRefConfigInfo arci = new AuthRefConfigInfo(spec);\r
528                 authRefsInfo.add(arci);\r
529             }\r
530 \r
531             String docType = sb.getObject().getName();\r
532             queriedServiceBindings.put(docType, sb);\r
533             authRefFieldsByService.put(docType, authRefsInfo);\r
534             docTypes.add(docType);\r
535             fFirst = false;\r
536         }\r
537         if (fFirst) { // found no authRef fields - nothing to query\r
538             return null;\r
539         }\r
540         // We used to build a complete matches query, but that was too complex.\r
541         // Just build a keyword query based upon some key pieces - the urn syntax elements and the shortID\r
542         // Note that this will also match the Item itself, but that will get filtered out when\r
543         // we compute actual matches.\r
544         AuthorityTermInfo authTermInfo = RefNameUtils.parseAuthorityTermInfo(refName);\r
545 \r
546         String keywords = RefNameUtils.URN_PREFIX\r
547                 + " AND " + (authTermInfo.inAuthority.name != null\r
548                 ? authTermInfo.inAuthority.name : authTermInfo.inAuthority.csid)\r
549                 + " AND " + (authTermInfo.name != null\r
550                 ? authTermInfo.name : authTermInfo.csid);\r
551 \r
552         String whereClauseStr = QueryManager.createWhereClauseFromKeywords(keywords);\r
553 \r
554         if (logger.isTraceEnabled()) {\r
555             logger.trace("The 'where' clause to find refObjs is: ", whereClauseStr);\r
556         }\r
557 \r
558         return whereClauseStr;\r
559     }\r
560 \r
561     /*\r
562      * Runs through the list of found docs, processing them. If list is\r
563      * non-null, then processing means gather the info for items. If list is\r
564      * null, and newRefName is non-null, then processing means replacing and\r
565      * updating. If processing/updating, this must be called in the context of\r
566      * an open session, and caller must release Session after calling this.\r
567      *\r
568      */\r
569     private static int processRefObjsDocList(\r
570             DocumentModelList docList,\r
571             String tenantId,\r
572             String refName,\r
573             boolean matchBaseOnly,\r
574             Map<String, ServiceBindingType> queriedServiceBindings,\r
575             Map<String, List<AuthRefConfigInfo>> authRefFieldsByService,\r
576             List<AuthorityRefDocList.AuthorityRefDocItem> list,\r
577             String newAuthorityRefName) {\r
578         Iterator<DocumentModel> iter = docList.iterator();\r
579         int nRefsFoundTotal = 0;\r
580         while (iter.hasNext()) {\r
581             DocumentModel docModel = iter.next();\r
582             AuthorityRefDocList.AuthorityRefDocItem ilistItem;\r
583 \r
584             String docType = docModel.getDocumentType().getName(); // REM - This will be a tentant qualified document type\r
585             docType = ServiceBindingUtils.getUnqualifiedTenantDocType(docType);\r
586             ServiceBindingType sb = queriedServiceBindings.get(docType);\r
587             if (sb == null) {\r
588                 throw new RuntimeException(\r
589                         "getAuthorityRefDocs: No Service Binding for docType: " + docType);\r
590             }\r
591 \r
592             if (list == null) { // no list - should be update refName case.\r
593                 if (newAuthorityRefName == null) {\r
594                     throw new InternalError("processRefObjsDocList() called with neither an itemList nor a new RefName!");\r
595                 }\r
596                 ilistItem = null;\r
597             } else {    // Have a list - refObjs case\r
598                 if (newAuthorityRefName != null) {\r
599                     throw new InternalError("processRefObjsDocList() called with both an itemList and a new RefName!");\r
600                 }\r
601                 ilistItem = new AuthorityRefDocList.AuthorityRefDocItem();\r
602                 String csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());\r
603                 ilistItem.setDocId(csid);\r
604                 String uri = "";\r
605                 UriTemplateRegistry registry = ServiceMain.getInstance().getUriTemplateRegistry();\r
606                 UriTemplateRegistryKey key = new UriTemplateRegistryKey(tenantId, docType);\r
607                 StoredValuesUriTemplate template = registry.get(key);\r
608                 if (template != null) {\r
609                     Map<String, String> additionalValues = new HashMap<String, String>();\r
610                     if (template.getUriTemplateType() == UriTemplateFactory.RESOURCE) {\r
611                         additionalValues.put(UriTemplateFactory.IDENTIFIER_VAR, csid);\r
612                         uri = template.buildUri(additionalValues);\r
613                     } else if (template.getUriTemplateType() == UriTemplateFactory.ITEM) {\r
614                         try {\r
615                             String inAuthorityCsid = (String) docModel.getPropertyValue("inAuthority"); // AuthorityItemJAXBSchema.IN_AUTHORITY\r
616                             additionalValues.put(UriTemplateFactory.IDENTIFIER_VAR, inAuthorityCsid);\r
617                             additionalValues.put(UriTemplateFactory.ITEM_IDENTIFIER_VAR, csid);\r
618                             uri = template.buildUri(additionalValues);\r
619                         } catch (Exception e) {\r
620                             logger.warn("Could not extract inAuthority property from authority item record: " + e.getMessage());\r
621                         }\r
622                     } else if (template.getUriTemplateType() == UriTemplateFactory.CONTACT) {\r
623                         // FIXME: Generating contact sub-resource URIs requires additional work,\r
624                         // as a follow-on to CSPACE-5271 - ADR 2012-08-16\r
625                         // Sets the default (empty string) value for uri, for now\r
626                     } else {\r
627                         logger.warn("Unrecognized URI template type = " + template.getUriTemplateType());\r
628                         // Sets the default (empty string) value for uri\r
629                     }\r
630                 } else { // (if template == null)\r
631                     logger.warn("Could not retrieve URI template from registry via tenant ID "\r
632                             + tenantId + " and docType " + docType);\r
633                     // Sets the default (empty string) value for uri\r
634                 }\r
635                 ilistItem.setUri(uri);\r
636                 try {\r
637                     ilistItem.setWorkflowState(docModel.getCurrentLifeCycleState());\r
638                     ilistItem.setUpdatedAt(DocHandlerBase.getUpdatedAtAsString(docModel));\r
639                 } catch (Exception e) {\r
640                     logger.error("Error getting core values for doc [" + csid + "]: " + e.getLocalizedMessage());\r
641                 }\r
642                 ilistItem.setDocType(docType);\r
643                 ilistItem.setDocNumber(\r
644                         ServiceBindingUtils.getMappedFieldInDoc(sb, ServiceBindingUtils.OBJ_NUMBER_PROP, docModel));\r
645                 ilistItem.setDocName(\r
646                         ServiceBindingUtils.getMappedFieldInDoc(sb, ServiceBindingUtils.OBJ_NAME_PROP, docModel));\r
647             }\r
648             // Now, we have to loop over the authRefFieldsByService to figure\r
649             // out which field(s) matched this.\r
650             List<AuthRefConfigInfo> matchingAuthRefFields = authRefFieldsByService.get(docType);\r
651             if (matchingAuthRefFields == null || matchingAuthRefFields.isEmpty()) {\r
652                 throw new RuntimeException(\r
653                         "getAuthorityRefDocs: internal logic error: can't fetch authRefFields for DocType.");\r
654             }\r
655             //String authRefAncestorField = "";\r
656             //String authRefDescendantField = "";\r
657             //String sourceField = "";\r
658             int nRefsFoundInDoc = 0;\r
659 \r
660             ArrayList<RefNameServiceUtils.AuthRefInfo> foundProps = new ArrayList<RefNameServiceUtils.AuthRefInfo>();\r
661             try {\r
662                 findAuthRefPropertiesInDoc(docModel, matchingAuthRefFields, refName, matchBaseOnly, foundProps); // REM - side effect that foundProps is set\r
663                 for (RefNameServiceUtils.AuthRefInfo ari : foundProps) {\r
664                     if (ilistItem != null) {\r
665                         if (nRefsFoundInDoc == 0) {    // First one?\r
666                             ilistItem.setSourceField(ari.getQualifiedDisplayName());\r
667                         } else {    // duplicates from one object\r
668                             ilistItem = cloneAuthRefDocItem(ilistItem, ari.getQualifiedDisplayName());\r
669                         }\r
670                         list.add(ilistItem);\r
671                     } else {    // update refName case\r
672                         Property propToUpdate = ari.getProperty();\r
673                         propToUpdate.setValue(newAuthorityRefName);\r
674                     }\r
675                     nRefsFoundInDoc++;\r
676                 }\r
677             } catch (ClientException ce) {\r
678                 throw new RuntimeException(\r
679                         "getAuthorityRefDocs: Problem fetching values from repo: " + ce.getLocalizedMessage());\r
680             }\r
681             if (nRefsFoundInDoc == 0) {\r
682                 logger.warn(\r
683                         "getAuthorityRefDocs: Result: "\r
684                         + docType + " [" + NuxeoUtils.getCsid(docModel)\r
685                         + "] does not reference ["\r
686                         + refName + "]");\r
687             }\r
688             nRefsFoundTotal += nRefsFoundInDoc;\r
689         }\r
690         return nRefsFoundTotal;\r
691     }\r
692 \r
693     private static AuthorityRefDocList.AuthorityRefDocItem cloneAuthRefDocItem(\r
694             AuthorityRefDocList.AuthorityRefDocItem ilistItem, String sourceField) {\r
695         AuthorityRefDocList.AuthorityRefDocItem newlistItem = new AuthorityRefDocList.AuthorityRefDocItem();\r
696         newlistItem.setDocId(ilistItem.getDocId());\r
697         newlistItem.setDocName(ilistItem.getDocName());\r
698         newlistItem.setDocNumber(ilistItem.getDocNumber());\r
699         newlistItem.setDocType(ilistItem.getDocType());\r
700         newlistItem.setUri(ilistItem.getUri());\r
701         newlistItem.setSourceField(sourceField);\r
702         return newlistItem;\r
703     }\r
704 \r
705     public static List<AuthRefInfo> findAuthRefPropertiesInDoc(\r
706             DocumentModel docModel,\r
707             List<AuthRefConfigInfo> authRefFieldInfo,\r
708             String refNameToMatch,\r
709             List<AuthRefInfo> foundProps) {\r
710         return findAuthRefPropertiesInDoc(docModel, authRefFieldInfo, \r
711                                                                         refNameToMatch, false, foundProps);\r
712     }\r
713     \r
714     public static List<AuthRefInfo> findAuthRefPropertiesInDoc(\r
715             DocumentModel docModel,\r
716             List<AuthRefConfigInfo> authRefFieldInfo,\r
717             String refNameToMatch,\r
718             boolean matchBaseOnly,\r
719             List<AuthRefInfo> foundProps) {\r
720         // Assume that authRefFieldInfo is keyed by the field name (possibly mapped for UI)\r
721         // and the values are elPaths to the field, where intervening group structures in\r
722         // lists of complex structures are replaced with "*". Thus, valid paths include\r
723         // the following (note that the ServiceBindingUtils prepend schema names to configured values):\r
724         // "schemaname:fieldname"\r
725         // "schemaname:scalarlistname"\r
726         // "schemaname:complexfieldname/fieldname"\r
727         // "schemaname:complexlistname/*/fieldname"\r
728         // "schemaname:complexlistname/*/scalarlistname"\r
729         // "schemaname:complexlistname/*/complexfieldname/fieldname"\r
730         // "schemaname:complexlistname/*/complexlistname/*/fieldname"\r
731         // etc.\r
732         for (AuthRefConfigInfo arci : authRefFieldInfo) {\r
733             try {\r
734                 // Get first property and work down as needed.\r
735                 Property prop = docModel.getProperty(arci.pathEls[0]);\r
736                 findAuthRefPropertiesInProperty(foundProps, prop, arci, 0, refNameToMatch, matchBaseOnly);\r
737             } catch (Exception e) {\r
738                 logger.error("Problem fetching property: " + arci.pathEls[0]);\r
739             }\r
740         }\r
741         return foundProps;\r
742     }\r
743 \r
744     private static List<AuthRefInfo> findAuthRefPropertiesInProperty(\r
745             List<AuthRefInfo> foundProps,\r
746             Property prop,\r
747             AuthRefConfigInfo arci,\r
748             int pathStartIndex, // Supports recursion and we work down the path\r
749             String refNameToMatch,\r
750             boolean matchBaseOnly ) {\r
751         if (pathStartIndex >= arci.pathEls.length) {\r
752             throw new ArrayIndexOutOfBoundsException("Index = " + pathStartIndex + " for path: "\r
753                     + arci.pathEls.toString());\r
754         }\r
755         AuthRefInfo ari = null;\r
756         if (prop == null) {\r
757             return foundProps;\r
758         }\r
759 \r
760         if (prop instanceof StringProperty) {    // scalar string\r
761             addARIifMatches(refNameToMatch, matchBaseOnly, arci, prop, foundProps);\r
762         } else if (prop instanceof List) {\r
763             List<Property> propList = (List<Property>) prop;\r
764             // run through list. Must either be list of Strings, or Complex\r
765             for (Property listItemProp : propList) {\r
766                 if (listItemProp instanceof StringProperty) {\r
767                     if (arci.pathEls.length - pathStartIndex != 1) {\r
768                         logger.error("Configuration for authRefs does not match schema structure: "\r
769                                 + arci.pathEls.toString());\r
770                         break;\r
771                     } else {\r
772                         addARIifMatches(refNameToMatch, matchBaseOnly, arci, listItemProp, foundProps);\r
773                     }\r
774                 } else if (listItemProp.isComplex()) {\r
775                     // Just recurse to handle this. Note that since this is a list of complex, \r
776                     // which should look like listName/*/... we add 2 to the path start index \r
777                     findAuthRefPropertiesInProperty(foundProps, listItemProp, arci,\r
778                             pathStartIndex + 2, refNameToMatch, matchBaseOnly);\r
779                 } else {\r
780                     logger.error("Configuration for authRefs does not match schema structure: "\r
781                             + arci.pathEls.toString());\r
782                     break;\r
783                 }\r
784             }\r
785         } else if (prop.isComplex()) {\r
786             String localPropName = arci.pathEls[pathStartIndex];\r
787             try {\r
788                 Property localProp = prop.get(localPropName);\r
789                 // Now just recurse, pushing down the path 1 step\r
790                 findAuthRefPropertiesInProperty(foundProps, localProp, arci,\r
791                         pathStartIndex, refNameToMatch, matchBaseOnly);\r
792             } catch (PropertyNotFoundException pnfe) {\r
793                 logger.error("Could not find property: [" + localPropName + "] in path: "\r
794                         + arci.getFullPath());\r
795                 // Fall through - ari will be null and we will continue...\r
796             }\r
797         } else {\r
798             logger.error("Configuration for authRefs does not match schema structure: "\r
799                     + arci.pathEls.toString());\r
800         }\r
801 \r
802         if (ari != null) {\r
803             foundProps.add(ari); //FIXME: REM - This is dead code.  'ari' is never touched after being initalized to null.  Why?\r
804         }\r
805 \r
806         return foundProps;\r
807     }\r
808 \r
809     private static void addARIifMatches(\r
810             String refNameToMatch,\r
811             boolean matchBaseOnly,\r
812             AuthRefConfigInfo arci,\r
813             Property prop,\r
814             List<AuthRefInfo> foundProps) {\r
815         // Need to either match a passed refName \r
816         // OR have no refName to match but be non-empty\r
817         try {\r
818             String value = (String) prop.getValue();\r
819             if (((refNameToMatch != null) && \r
820                                 (matchBaseOnly?\r
821                                         (value!=null && value.startsWith(refNameToMatch))\r
822                                         :refNameToMatch.equals(value)))\r
823                     || ((refNameToMatch == null) && Tools.notBlank(value))) {\r
824                 // Found a match\r
825                 logger.debug("Found a match on property: " + prop.getPath() + " with value: [" + value + "]");\r
826                 AuthRefInfo ari = new AuthRefInfo(arci, prop);\r
827                 foundProps.add(ari);\r
828             }\r
829         } catch (PropertyException pe) {\r
830             logger.debug("PropertyException on: " + prop.getPath() + pe.getLocalizedMessage());\r
831         }\r
832     }\r
833 \r
834     /*\r
835      * Identifies whether the refName was found in the supplied field. If passed\r
836      * a new RefName, will set that into fields in which the old one was found.\r
837      *\r
838      * Only works for: * Scalar fields * Repeatable scalar fields (aka\r
839      * multi-valued fields)\r
840      *\r
841      * Does not work for: * Structured fields (complexTypes) * Repeatable\r
842      * structured fields (repeatable complexTypes) private static int\r
843      * refNameFoundInField(String oldRefName, Property fieldValue, String\r
844      * newRefName) { int nFound = 0; if (fieldValue instanceof List) {\r
845      * List<Property> fieldValueList = (List) fieldValue; for (Property\r
846      * listItemValue : fieldValueList) { try { if ((listItemValue instanceof\r
847      * StringProperty) &&\r
848      * oldRefName.equalsIgnoreCase((String)listItemValue.getValue())) {\r
849      * nFound++; if(newRefName!=null) { fieldValue.setValue(newRefName); } else\r
850      * { // We cannot quit after the first, if we are replacing values. // If we\r
851      * are just looking (not replacing), finding one is enough. break; } } }\r
852      * catch( PropertyException pe ) {} } } else { try { if ((fieldValue\r
853      * instanceof StringProperty) &&\r
854      * oldRefName.equalsIgnoreCase((String)fieldValue.getValue())) { nFound++;\r
855      * if(newRefName!=null) { fieldValue.setValue(newRefName); } } } catch(\r
856      * PropertyException pe ) {} } return nFound; }\r
857      */\r
858 }\r