]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
1c86715beb33cd8bed41d710abed5922973c3c3e
[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.Collection;\r
27 import java.util.HashMap;\r
28 import java.util.Iterator;\r
29 import java.util.List;\r
30 import java.util.Map;\r
31 \r
32 import org.nuxeo.ecm.core.api.ClientException;\r
33 import org.nuxeo.ecm.core.api.DocumentModel;\r
34 import org.nuxeo.ecm.core.api.DocumentModelList;\r
35 import org.nuxeo.ecm.core.api.model.Property;\r
36 import org.nuxeo.ecm.core.api.model.PropertyException;\r
37 import org.nuxeo.ecm.core.api.model.PropertyNotFoundException;\r
38 import org.nuxeo.ecm.core.api.model.impl.primitives.StringProperty;\r
39 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;\r
40 import org.slf4j.Logger;\r
41 import org.slf4j.LoggerFactory;\r
42 \r
43 import org.collectionspace.services.client.PoxPayloadIn;\r
44 import org.collectionspace.services.client.PoxPayloadOut;\r
45 import org.collectionspace.services.common.ServiceMain;\r
46 import org.collectionspace.services.common.context.ServiceContext;\r
47 import org.collectionspace.services.common.context.AbstractServiceContextImpl;\r
48 import org.collectionspace.services.common.api.RefNameUtils;\r
49 import org.collectionspace.services.common.api.Tools;\r
50 import org.collectionspace.services.common.api.RefNameUtils.AuthorityTermInfo;\r
51 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;\r
52 import org.collectionspace.services.common.authorityref.AuthorityRefList;\r
53 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;\r
54 import org.collectionspace.services.common.context.ServiceBindingUtils;\r
55 import org.collectionspace.services.common.document.DocumentException;\r
56 import org.collectionspace.services.common.document.DocumentFilter;\r
57 import org.collectionspace.services.common.document.DocumentNotFoundException;\r
58 import org.collectionspace.services.common.document.DocumentUtils;\r
59 import org.collectionspace.services.common.document.DocumentWrapper;\r
60 import org.collectionspace.services.common.query.QueryManager;\r
61 import org.collectionspace.services.common.repository.RepositoryClient;\r
62 import org.collectionspace.services.nuxeo.client.java.DocHandlerBase;\r
63 import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl;\r
64 import org.collectionspace.services.common.security.SecurityUtils;\r
65 import org.collectionspace.services.config.service.ServiceBindingType;\r
66 import org.collectionspace.services.jaxb.AbstractCommonList;\r
67 import org.collectionspace.services.nuxeo.util.NuxeoUtils;\r
68 \r
69 import com.sun.xml.bind.v2.runtime.unmarshaller.XsiNilLoader.Array;\r
70 \r
71 /**\r
72  * RefNameServiceUtils is a collection of services utilities related to refName\r
73  * usage.\r
74  *\r
75  * $LastChangedRevision: $ $LastChangedDate: $\r
76  */\r
77 public class RefNameServiceUtils {\r
78 \r
79     public static class AuthRefConfigInfo {\r
80 \r
81         public String getQualifiedDisplayName() {\r
82             return (Tools.isBlank(schema))\r
83                     ? displayName : DocumentUtils.appendSchemaName(schema, displayName);\r
84         }\r
85 \r
86         public String getDisplayName() {\r
87             return displayName;\r
88         }\r
89 \r
90         public void setDisplayName(String displayName) {\r
91             this.displayName = displayName;\r
92         }\r
93         String displayName;\r
94         String schema;\r
95 \r
96         public String getSchema() {\r
97             return schema;\r
98         }\r
99 \r
100         public void setSchema(String schema) {\r
101             this.schema = schema;\r
102         }\r
103 \r
104         public String getFullPath() {\r
105             return fullPath;\r
106         }\r
107 \r
108         public void setFullPath(String fullPath) {\r
109             this.fullPath = fullPath;\r
110         }\r
111         String fullPath;\r
112         protected String[] pathEls;\r
113 \r
114         public AuthRefConfigInfo(AuthRefConfigInfo arci) {\r
115             this.displayName = arci.displayName;\r
116             this.schema = arci.schema;\r
117             this.fullPath = arci.fullPath;\r
118             this.pathEls = arci.pathEls;\r
119             // Skip the pathElse check, since we are creatign from another (presumably valid) arci.\r
120         }\r
121 \r
122         public AuthRefConfigInfo(String displayName, String schema, String fullPath, String[] pathEls) {\r
123             this.displayName = displayName;\r
124             this.schema = schema;\r
125             this.fullPath = fullPath;\r
126             this.pathEls = pathEls;\r
127             checkPathEls();\r
128         }\r
129 \r
130         // Split a config value string like "intakes_common:collector", or\r
131         // "collectionobjects_common:contentPeoples|contentPeople"\r
132         // "collectionobjects_common:assocEventGroupList/*/assocEventPlace"\r
133         // If has a pipe ('|') second part is a displayLabel, and first is path\r
134         // Otherwise, entry is a path, and can use the last pathElement as displayName\r
135         // Should be schema qualified.\r
136         public AuthRefConfigInfo(String configString) {\r
137             String[] pair = configString.split("\\|", 2);\r
138             String[] pathEls;\r
139             String displayName, fullPath;\r
140             if (pair.length == 1) {\r
141                 // no label specifier, so we'll defer getting label\r
142                 fullPath = pair[0];\r
143                 pathEls = pair[0].split("/");\r
144                 displayName = pathEls[pathEls.length - 1];\r
145             } else {\r
146                 fullPath = pair[0];\r
147                 pathEls = pair[0].split("/");\r
148                 displayName = pair[1];\r
149             }\r
150             String[] schemaSplit = pathEls[0].split(":", 2);\r
151             String schema;\r
152             if (schemaSplit.length == 1) {    // schema not specified\r
153                 schema = null;\r
154             } else {\r
155                 schema = schemaSplit[0];\r
156                 if (pair.length == 1 && pathEls.length == 1) {    // simplest case of field in top level schema, no labelll\r
157                     displayName = schemaSplit[1];    // Have to fix up displayName to have no schema\r
158                 }\r
159             }\r
160             this.displayName = displayName;\r
161             this.schema = schema;\r
162             this.fullPath = fullPath;\r
163             this.pathEls = pathEls;\r
164             checkPathEls();\r
165         }\r
166 \r
167         protected void checkPathEls() {\r
168             int len = pathEls.length;\r
169             if (len < 1) {\r
170                 throw new InternalError("Bad values in authRef info - caller screwed up:" + fullPath);\r
171             }\r
172             // Handle case of them putting a leading slash on the path\r
173             if (len > 1 && pathEls[0].endsWith(":")) {\r
174                 len--;\r
175                 String[] newArray = new String[len];\r
176                 newArray[0] = pathEls[0] + pathEls[1];\r
177                 if (len >= 2) {\r
178                     System.arraycopy(pathEls, 2, newArray, 1, len - 1);\r
179                 }\r
180                 pathEls = newArray;\r
181             }\r
182         }\r
183     }\r
184 \r
185     public static class AuthRefInfo extends AuthRefConfigInfo {\r
186 \r
187         public Property getProperty() {\r
188             return property;\r
189         }\r
190 \r
191         public void setProperty(Property property) {\r
192             this.property = property;\r
193         }\r
194         Property property;\r
195 \r
196         public AuthRefInfo(String displayName, String schema, String fullPath, String[] pathEls, Property prop) {\r
197             super(displayName, schema, fullPath, pathEls);\r
198             this.property = prop;\r
199         }\r
200 \r
201         public AuthRefInfo(AuthRefConfigInfo arci, Property prop) {\r
202             super(arci);\r
203             this.property = prop;\r
204         }\r
205     }\r
206     private static final Logger logger = LoggerFactory.getLogger(RefNameServiceUtils.class);\r
207     private static ArrayList<String> refNameServiceTypes = null;\r
208 \r
209     public static List<AuthRefConfigInfo> getConfiguredAuthorityRefs(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {\r
210         List<String> authRefFields =\r
211                 ((AbstractServiceContextImpl) ctx).getAllPartsPropertyValues(\r
212                 ServiceBindingUtils.AUTH_REF_PROP, ServiceBindingUtils.QUALIFIED_PROP_NAMES);\r
213         ArrayList<AuthRefConfigInfo> authRefsInfo = new ArrayList<AuthRefConfigInfo>(authRefFields.size());\r
214         for (String spec : authRefFields) {\r
215             AuthRefConfigInfo arci = new AuthRefConfigInfo(spec);\r
216             authRefsInfo.add(arci);\r
217         }\r
218         return authRefsInfo;\r
219     }\r
220 \r
221     public static AuthorityRefDocList getAuthorityRefDocs(\r
222             RepositoryInstance repoSession,\r
223             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,\r
224             RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient,\r
225             List<String> serviceTypes,\r
226             String refName,\r
227             String refPropName,\r
228             DocumentFilter filter, boolean computeTotal)\r
229             throws DocumentException, DocumentNotFoundException {\r
230         AuthorityRefDocList wrapperList = new AuthorityRefDocList();\r
231         AbstractCommonList commonList = (AbstractCommonList) wrapperList;\r
232         int pageNum = filter.getStartPage();\r
233         int pageSize = filter.getPageSize();\r
234         commonList.setPageNum(pageNum);\r
235         commonList.setPageSize(pageSize);\r
236         List<AuthorityRefDocList.AuthorityRefDocItem> list =\r
237                 wrapperList.getAuthorityRefDocItem();\r
238 \r
239         Map<String, ServiceBindingType> queriedServiceBindings = new HashMap<String, ServiceBindingType>();\r
240         Map<String, List<AuthRefConfigInfo>> authRefFieldsByService = new HashMap<String, List<AuthRefConfigInfo>>();\r
241 \r
242         RepositoryJavaClientImpl nuxeoRepoClient = (RepositoryJavaClientImpl) repoClient;\r
243         try {\r
244             DocumentModelList docList = findAuthorityRefDocs(ctx, repoClient, repoSession,\r
245                     serviceTypes, refName, refPropName, queriedServiceBindings, authRefFieldsByService,\r
246                     filter.getWhereClause(), null, pageSize, pageNum, computeTotal);\r
247 \r
248             if (docList == null) { // found no authRef fields - nothing to process\r
249                 return wrapperList;\r
250             }\r
251             // Set num of items in list. this is useful to our testing framework.\r
252             commonList.setItemsInPage(docList.size());\r
253             // set the total result size\r
254             commonList.setTotalItems(docList.totalSize());\r
255             // set the fieldsReturned list. Even though this is a fixed schema, app layer treats\r
256             // this like other abstract common lists\r
257             /*\r
258              * <xs:element name="docType" type="xs:string" minOccurs="1" />\r
259              * <xs:element name="docId" type="xs:string" minOccurs="1" />\r
260              * <xs:element name="docNumber" type="xs:string" minOccurs="0" />\r
261              * <xs:element name="docName" type="xs:string" minOccurs="0" />\r
262              * <xs:element name="sourceField" type="xs:string" minOccurs="1" />\r
263              * <xs:element name="uri" type="xs:anyURI" minOccurs="1" />\r
264              * <xs:element name="updatedAt" type="xs:string" minOccurs="1" />\r
265              * <xs:element name="workflowState" type="xs:string" minOccurs="1"\r
266              * />\r
267              */\r
268             String fieldList = "docType|docId|docNumber|docName|sourceField|uri|updatedAt|workflowState";\r
269             commonList.setFieldsReturned(fieldList);\r
270 \r
271             int nRefsFound = processRefObjsDocList(docList, refName, queriedServiceBindings, authRefFieldsByService, // the actual list size needs to be updated to the size of "list"\r
272                     list, null);\r
273             if (logger.isDebugEnabled() && (nRefsFound < docList.size())) {\r
274                 logger.debug("Internal curiosity: got fewer matches of refs than # docs matched..."); // We found a ref to ourself and have excluded it.\r
275             }\r
276         } catch (Exception e) {\r
277             logger.error("Could not retrieve the Nuxeo repository", e);\r
278             wrapperList = null;\r
279         }\r
280 \r
281         return wrapperList;\r
282     }\r
283 \r
284     private static ArrayList<String> getRefNameServiceTypes() {\r
285         if (refNameServiceTypes == null) {\r
286             refNameServiceTypes = new ArrayList<String>();\r
287             refNameServiceTypes.add(ServiceBindingUtils.SERVICE_TYPE_AUTHORITY);\r
288             refNameServiceTypes.add(ServiceBindingUtils.SERVICE_TYPE_OBJECT);\r
289             refNameServiceTypes.add(ServiceBindingUtils.SERVICE_TYPE_PROCEDURE);\r
290         }\r
291         return refNameServiceTypes;\r
292     }\r
293     // Seems like a good value - no real data to set this well.\r
294     // Note: can set this value lower; e.g. to 3 during debugging; - ADR 2012-07-10\r
295     private static final int N_OBJS_TO_UPDATE_PER_LOOP = 100;\r
296 \r
297     public static int updateAuthorityRefDocs(\r
298             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,\r
299             RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient,\r
300             RepositoryInstance repoSession,\r
301             String oldRefName,\r
302             String newRefName,\r
303             String refPropName) throws Exception {\r
304         Map<String, ServiceBindingType> queriedServiceBindings = new HashMap<String, ServiceBindingType>();\r
305         Map<String, List<AuthRefConfigInfo>> authRefFieldsByService = new HashMap<String, List<AuthRefConfigInfo>>();\r
306 \r
307         int docsScanned = 0;\r
308         int nRefsFound = 0;\r
309         int currentPage = 0;\r
310         int docsInCurrentPage = 0;\r
311         final String WHERE_CLAUSE_ADDITIONS_VALUE = null;\r
312         final String ORDER_BY_VALUE = "collectionspace_core:createdAt";\r
313 \r
314         if (!(repoClient instanceof RepositoryJavaClientImpl)) {\r
315             throw new InternalError("updateAuthorityRefDocs() called with unknown repoClient type!");\r
316         }\r
317         try { // REM - How can we deal with transaction and timeout issues here.\r
318             final int pageSize = N_OBJS_TO_UPDATE_PER_LOOP;\r
319             DocumentModelList docList;\r
320             boolean morePages = true;\r
321             while (morePages) {\r
322                 \r
323                 docList = findAuthorityRefDocs(ctx, repoClient, repoSession,\r
324                         getRefNameServiceTypes(), oldRefName, refPropName,\r
325                         queriedServiceBindings, authRefFieldsByService, WHERE_CLAUSE_ADDITIONS_VALUE, ORDER_BY_VALUE, pageSize, currentPage, false);\r
326                 \r
327                 if (docList == null) {\r
328                     logger.debug("updateAuthorityRefDocs: no documents could be found that referenced the old refName");\r
329                     break;\r
330                 }\r
331                 docsInCurrentPage = docList.size();\r
332                 logger.debug("updateAuthorityRefDocs: current page=" + currentPage + " documents included in page=" + docsInCurrentPage);\r
333                 if (docsInCurrentPage == 0) {\r
334                     logger.debug("updateAuthorityRefDocs: no more documents requiring refName updates could be found");\r
335                     break;\r
336                 }\r
337                 if (docsInCurrentPage < pageSize) {\r
338                     logger.debug("updateAuthorityRefDocs: assuming no more documents requiring refName updates will be found, as docsInCurrentPage < pageSize");\r
339                     morePages = false;\r
340                 }\r
341 \r
342                 int nRefsFoundThisPage = processRefObjsDocList(docList, oldRefName, queriedServiceBindings, authRefFieldsByService,\r
343                         null, newRefName);\r
344                 if (nRefsFoundThisPage > 0) {\r
345                     ((RepositoryJavaClientImpl) repoClient).saveDocListWithoutHandlerProcessing(ctx, repoSession, docList, true);\r
346                     nRefsFound += nRefsFoundThisPage;\r
347                 }\r
348                 \r
349                 // FIXME: Per REM, set a limit of num objects - something like\r
350                 // 1000K objects - and also add a log Warning after some threshold\r
351                 docsScanned += docsInCurrentPage;\r
352                 if (morePages) {\r
353                     currentPage++;\r
354                 }\r
355 \r
356             }\r
357         } catch (Exception e) {\r
358             logger.error("Internal error updating the AuthorityRefDocs: " + e.getLocalizedMessage());\r
359             logger.debug(Tools.errorToString(e, true));\r
360             throw e;\r
361         }\r
362         logger.debug("updateAuthorityRefDocs replaced a total of " + nRefsFound + " authority references, within as many as " + docsScanned + " scanned document(s)");\r
363         return nRefsFound;\r
364     }\r
365 \r
366     private static DocumentModelList findAuthorityRefDocs(\r
367             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,\r
368             RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient,\r
369             RepositoryInstance repoSession, List<String> serviceTypes,\r
370             String refName,\r
371             String refPropName,\r
372             Map<String, ServiceBindingType> queriedServiceBindings,\r
373             Map<String, List<AuthRefConfigInfo>> authRefFieldsByService,\r
374             String whereClauseAdditions,\r
375             String orderByClause,\r
376             int pageSize,\r
377             int pageNum,\r
378             boolean computeTotal) throws DocumentException, DocumentNotFoundException {\r
379 \r
380         // Get the service bindings for this tenant\r
381         TenantBindingConfigReaderImpl tReader =\r
382                 ServiceMain.getInstance().getTenantBindingConfigReader();\r
383         // We need to get all the procedures, authorities, and objects.\r
384         List<ServiceBindingType> servicebindings = tReader.getServiceBindingsByType(ctx.getTenantId(), serviceTypes);\r
385         if (servicebindings == null || servicebindings.isEmpty()) {\r
386             logger.error("RefNameServiceUtils.getAuthorityRefDocs: No services bindings found, cannot proceed!");\r
387             return null;\r
388         }\r
389         // Filter the list for current user rights\r
390         servicebindings = SecurityUtils.getReadableServiceBindingsForCurrentUser(servicebindings);\r
391 \r
392         ArrayList<String> docTypes = new ArrayList<String>();\r
393 \r
394         String query = computeWhereClauseForAuthorityRefDocs(refName, refPropName, docTypes, servicebindings,\r
395                 queriedServiceBindings, authRefFieldsByService);\r
396         if (query == null) { // found no authRef fields - nothing to query\r
397             return null;\r
398         }\r
399         // Additional qualifications, like workflow state\r
400         if (Tools.notBlank(whereClauseAdditions)) {\r
401             query += " AND " + whereClauseAdditions;\r
402         }        \r
403         // Now we have to issue the search\r
404         RepositoryJavaClientImpl nuxeoRepoClient = (RepositoryJavaClientImpl) repoClient;\r
405         DocumentWrapper<DocumentModelList> docListWrapper = nuxeoRepoClient.findDocs(ctx, repoSession,\r
406                 docTypes, query, orderByClause, pageSize, pageNum, computeTotal);\r
407         // Now we gather the info for each document into the list and return\r
408         DocumentModelList docList = docListWrapper.getWrappedObject();\r
409         return docList;\r
410     }\r
411     private static final boolean READY_FOR_COMPLEX_QUERY = true;\r
412 \r
413     private static String computeWhereClauseForAuthorityRefDocs(\r
414             String refName,\r
415             String refPropName,\r
416             ArrayList<String> docTypes,\r
417             List<ServiceBindingType> servicebindings,\r
418             Map<String, ServiceBindingType> queriedServiceBindings,\r
419             Map<String, List<AuthRefConfigInfo>> authRefFieldsByService) {\r
420 \r
421         boolean fFirst = true;\r
422         List<String> authRefFieldPaths;\r
423         for (ServiceBindingType sb : servicebindings) {\r
424             // Gets the property names for each part, qualified with the part label (which\r
425             // is also the table name, the way that the repository works).\r
426             authRefFieldPaths =\r
427                     ServiceBindingUtils.getAllPartsPropertyValues(sb,\r
428                     refPropName, ServiceBindingUtils.QUALIFIED_PROP_NAMES);\r
429             if (authRefFieldPaths.isEmpty()) {\r
430                 continue;\r
431             }\r
432             ArrayList<AuthRefConfigInfo> authRefsInfo = new ArrayList<AuthRefConfigInfo>();\r
433             for (String spec : authRefFieldPaths) {\r
434                 AuthRefConfigInfo arci = new AuthRefConfigInfo(spec);\r
435                 authRefsInfo.add(arci);\r
436             }\r
437 \r
438             String docType = sb.getObject().getName();\r
439             queriedServiceBindings.put(docType, sb);\r
440             authRefFieldsByService.put(docType, authRefsInfo);\r
441             docTypes.add(docType);\r
442             fFirst = false;\r
443         }\r
444         if (fFirst) { // found no authRef fields - nothing to query\r
445             return null;\r
446         }\r
447         // We used to build a complete matches query, but that was too complex.\r
448         // Just build a keyword query based upon some key pieces - the urn syntax elements and the shortID\r
449         // Note that this will also match the Item itself, but that will get filtered out when\r
450         // we compute actual matches.\r
451         AuthorityTermInfo authTermInfo = RefNameUtils.parseAuthorityTermInfo(refName);\r
452 \r
453         String keywords = RefNameUtils.URN_PREFIX\r
454                 + " AND " + (authTermInfo.inAuthority.name != null\r
455                 ? authTermInfo.inAuthority.name : authTermInfo.inAuthority.csid)\r
456                 + " AND " + (authTermInfo.name != null\r
457                 ? authTermInfo.name : authTermInfo.csid);\r
458 \r
459         String whereClauseStr = QueryManager.createWhereClauseFromKeywords(keywords);\r
460 \r
461         if (logger.isTraceEnabled()) {\r
462             logger.trace("The 'where' clause to find refObjs is: ", whereClauseStr);\r
463         }\r
464 \r
465         return whereClauseStr;\r
466     }\r
467 \r
468     /*\r
469      * Runs through the list of found docs, processing them. If list is\r
470      * non-null, then processing means gather the info for items. If list is\r
471      * null, and newRefName is non-null, then processing means replacing and\r
472      * updating. If processing/updating, this must be called in teh context of\r
473      * an open session, and caller must release Session after calling this.\r
474      *\r
475      */\r
476     private static int processRefObjsDocList(\r
477             DocumentModelList docList,\r
478             String refName,\r
479             Map<String, ServiceBindingType> queriedServiceBindings,\r
480             Map<String, List<AuthRefConfigInfo>> authRefFieldsByService,\r
481             List<AuthorityRefDocList.AuthorityRefDocItem> list,\r
482             String newAuthorityRefName) {\r
483         Iterator<DocumentModel> iter = docList.iterator();\r
484         int nRefsFoundTotal = 0;\r
485         while (iter.hasNext()) {\r
486             DocumentModel docModel = iter.next();\r
487             AuthorityRefDocList.AuthorityRefDocItem ilistItem;\r
488 \r
489             String docType = docModel.getDocumentType().getName();\r
490             docType = ServiceBindingUtils.getUnqualifiedTenantDocType(docType);\r
491             ServiceBindingType sb = queriedServiceBindings.get(docType);\r
492             if (sb == null) {\r
493                 throw new RuntimeException(\r
494                         "getAuthorityRefDocs: No Service Binding for docType: " + docType);\r
495             }\r
496             String serviceContextPath = "/" + sb.getName().toLowerCase() + "/";\r
497 \r
498             if (list == null) { // no list - should be update refName case.\r
499                 if (newAuthorityRefName == null) {\r
500                     throw new InternalError("processRefObjsDocList() called with neither an itemList nor a new RefName!");\r
501                 }\r
502                 ilistItem = null;\r
503             } else {    // Have a list - refObjs case\r
504                 if (newAuthorityRefName != null) {\r
505                     throw new InternalError("processRefObjsDocList() called with both an itemList and a new RefName!");\r
506                 }\r
507                 ilistItem = new AuthorityRefDocList.AuthorityRefDocItem();\r
508                 String csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());\r
509                 ilistItem.setDocId(csid);\r
510                 ilistItem.setUri(serviceContextPath + csid);\r
511                 try {\r
512                     ilistItem.setWorkflowState(docModel.getCurrentLifeCycleState());\r
513                     ilistItem.setUpdatedAt(DocHandlerBase.getUpdatedAtAsString(docModel));\r
514                 } catch (Exception e) {\r
515                     logger.error("Error getting core values for doc [" + csid + "]: " + e.getLocalizedMessage());\r
516                 }\r
517                 // The id and URI are the same on all doctypes\r
518                 ilistItem.setDocType(docType);\r
519                 ilistItem.setDocNumber(\r
520                         ServiceBindingUtils.getMappedFieldInDoc(sb, ServiceBindingUtils.OBJ_NUMBER_PROP, docModel));\r
521                 ilistItem.setDocName(\r
522                         ServiceBindingUtils.getMappedFieldInDoc(sb, ServiceBindingUtils.OBJ_NAME_PROP, docModel));\r
523             }\r
524             // Now, we have to loop over the authRefFieldsByService to figure\r
525             // out which field(s) matched this.\r
526             List<AuthRefConfigInfo> matchingAuthRefFields = authRefFieldsByService.get(docType);\r
527             if (matchingAuthRefFields == null || matchingAuthRefFields.isEmpty()) {\r
528                 throw new RuntimeException(\r
529                         "getAuthorityRefDocs: internal logic error: can't fetch authRefFields for DocType.");\r
530             }\r
531             //String authRefAncestorField = "";\r
532             //String authRefDescendantField = "";\r
533             //String sourceField = "";\r
534             int nRefsFoundInDoc = 0;\r
535 \r
536             ArrayList<RefNameServiceUtils.AuthRefInfo> foundProps = new ArrayList<RefNameServiceUtils.AuthRefInfo>();\r
537             try {\r
538                 findAuthRefPropertiesInDoc(docModel, matchingAuthRefFields, refName, foundProps);\r
539                 for (RefNameServiceUtils.AuthRefInfo ari : foundProps) {\r
540                     if (ilistItem != null) {\r
541                         if (nRefsFoundInDoc == 0) {    // First one?\r
542                             ilistItem.setSourceField(ari.getQualifiedDisplayName());\r
543                         } else {    // duplicates from one object\r
544                             ilistItem = cloneAuthRefDocItem(ilistItem, ari.getQualifiedDisplayName());\r
545                         }\r
546                         list.add(ilistItem);\r
547                     } else {    // update refName case\r
548                         Property propToUpdate = ari.getProperty();\r
549                         propToUpdate.setValue(newAuthorityRefName);\r
550                     }\r
551                     nRefsFoundInDoc++;\r
552                 }\r
553             } catch (ClientException ce) {\r
554                 throw new RuntimeException(\r
555                         "getAuthorityRefDocs: Problem fetching values from repo: " + ce.getLocalizedMessage());\r
556             }\r
557             if (nRefsFoundInDoc == 0) {\r
558                 logger.warn(\r
559                         "getAuthorityRefDocs: Result: "\r
560                         + docType + " [" + NuxeoUtils.getCsid(docModel)\r
561                         + "] does not reference ["\r
562                         + refName + "]");\r
563             }\r
564             nRefsFoundTotal += nRefsFoundInDoc;\r
565         }\r
566         return nRefsFoundTotal;\r
567     }\r
568 \r
569     private static AuthorityRefDocList.AuthorityRefDocItem cloneAuthRefDocItem(\r
570             AuthorityRefDocList.AuthorityRefDocItem ilistItem, String sourceField) {\r
571         AuthorityRefDocList.AuthorityRefDocItem newlistItem = new AuthorityRefDocList.AuthorityRefDocItem();\r
572         newlistItem.setDocId(ilistItem.getDocId());\r
573         newlistItem.setDocName(ilistItem.getDocName());\r
574         newlistItem.setDocNumber(ilistItem.getDocNumber());\r
575         newlistItem.setDocType(ilistItem.getDocType());\r
576         newlistItem.setUri(ilistItem.getUri());\r
577         newlistItem.setSourceField(sourceField);\r
578         return newlistItem;\r
579     }\r
580 \r
581     public static List<AuthRefInfo> findAuthRefPropertiesInDoc(\r
582             DocumentModel docModel,\r
583             List<AuthRefConfigInfo> authRefFieldInfo,\r
584             String refNameToMatch,\r
585             List<AuthRefInfo> foundProps) {\r
586         // Assume that authRefFieldInfo is keyed by the field name (possibly mapped for UI)\r
587         // and the values are elPaths to the field, where intervening group structures in\r
588         // lists of complex structures are replaced with "*". Thus, valid paths include\r
589         // the following (note that the ServiceBindingUtils prepend schema names to configured values):\r
590         // "schemaname:fieldname"\r
591         // "schemaname:scalarlistname"\r
592         // "schemaname:complexfieldname/fieldname"\r
593         // "schemaname:complexlistname/*/fieldname"\r
594         // "schemaname:complexlistname/*/scalarlistname"\r
595         // "schemaname:complexlistname/*/complexfieldname/fieldname"\r
596         // "schemaname:complexlistname/*/complexlistname/*/fieldname"\r
597         // etc.\r
598         for (AuthRefConfigInfo arci : authRefFieldInfo) {\r
599             try {\r
600                 // Get first property and work down as needed.\r
601                 Property prop = docModel.getProperty(arci.pathEls[0]);\r
602                 findAuthRefPropertiesInProperty(foundProps, prop, arci, 0, refNameToMatch);\r
603             } catch (Exception e) {\r
604                 logger.error("Problem fetching property: " + arci.pathEls[0]);\r
605             }\r
606         }\r
607         return foundProps;\r
608     }\r
609 \r
610     public static List<AuthRefInfo> findAuthRefPropertiesInProperty(\r
611             List<AuthRefInfo> foundProps,\r
612             Property prop,\r
613             AuthRefConfigInfo arci,\r
614             int pathStartIndex, // Supports recursion and we work down the path\r
615             String refNameToMatch) {\r
616         if (pathStartIndex >= arci.pathEls.length) {\r
617             throw new ArrayIndexOutOfBoundsException("Index = " + pathStartIndex + " for path: "\r
618                     + arci.pathEls.toString());\r
619         }\r
620         AuthRefInfo ari = null;\r
621         if (prop == null) {\r
622             return foundProps;\r
623         }\r
624 \r
625         if (prop instanceof StringProperty) {    // scalar string\r
626             addARIifMatches(refNameToMatch, arci, prop, foundProps);\r
627         } else if (prop instanceof List) {\r
628             List<Property> propList = (List<Property>) prop;\r
629             // run through list. Must either be list of Strings, or Complex\r
630             for (Property listItemProp : propList) {\r
631                 if (listItemProp instanceof StringProperty) {\r
632                     if (arci.pathEls.length - pathStartIndex != 1) {\r
633                         logger.error("Configuration for authRefs does not match schema structure: "\r
634                                 + arci.pathEls.toString());\r
635                         break;\r
636                     } else {\r
637                         addARIifMatches(refNameToMatch, arci, listItemProp, foundProps);\r
638                     }\r
639                 } else if (listItemProp.isComplex()) {\r
640                     // Just recurse to handle this. Note that since this is a list of complex, \r
641                     // which should look like listName/*/... we add 2 to the path start index \r
642                     findAuthRefPropertiesInProperty(foundProps, listItemProp, arci,\r
643                             pathStartIndex + 2, refNameToMatch);\r
644                 } else {\r
645                     logger.error("Configuration for authRefs does not match schema structure: "\r
646                             + arci.pathEls.toString());\r
647                     break;\r
648                 }\r
649             }\r
650         } else if (prop.isComplex()) {\r
651             String localPropName = arci.pathEls[pathStartIndex];\r
652             try {\r
653                 Property localProp = prop.get(localPropName);\r
654                 // Now just recurse, pushing down the path 1 step\r
655                 findAuthRefPropertiesInProperty(foundProps, localProp, arci,\r
656                         pathStartIndex, refNameToMatch);\r
657             } catch (PropertyNotFoundException pnfe) {\r
658                 logger.error("Could not find property: [" + localPropName + "] in path: "\r
659                         + arci.getFullPath());\r
660                 // Fall through - ari will be null and we will continue...\r
661             }\r
662         } else {\r
663             logger.error("Configuration for authRefs does not match schema structure: "\r
664                     + arci.pathEls.toString());\r
665         }\r
666 \r
667         if (ari != null) {\r
668             foundProps.add(ari); //FIXME: REM - This is dead code.  'ari' is never touched after being initalized to null.  Why?\r
669         }\r
670 \r
671         return foundProps;\r
672     }\r
673 \r
674     private static void addARIifMatches(\r
675             String refNameToMatch,\r
676             AuthRefConfigInfo arci,\r
677             Property prop,\r
678             List<AuthRefInfo> foundProps) {\r
679         // Need to either match a passed refName \r
680         // OR have no refName to match but be non-empty\r
681         try {\r
682             String value = (String) prop.getValue();\r
683             if (((refNameToMatch != null) && refNameToMatch.equals(value))\r
684                     || ((refNameToMatch == null) && Tools.notBlank(value))) {\r
685                 // Found a match\r
686                 logger.debug("Found a match on property: " + prop.getPath() + " with value: [" + value + "]");\r
687                 AuthRefInfo ari = new AuthRefInfo(arci, prop);\r
688                 foundProps.add(ari);\r
689             }\r
690         } catch (PropertyException pe) {\r
691             logger.debug("PropertyException on: " + prop.getPath() + pe.getLocalizedMessage());\r
692         }\r
693     }\r
694 \r
695     /*\r
696      * Identifies whether the refName was found in the supplied field. If passed\r
697      * a new RefName, will set that into fields in which the old one was found.\r
698      *\r
699      * Only works for: * Scalar fields * Repeatable scalar fields (aka\r
700      * multi-valued fields)\r
701      *\r
702      * Does not work for: * Structured fields (complexTypes) * Repeatable\r
703      * structured fields (repeatable complexTypes) private static int\r
704      * refNameFoundInField(String oldRefName, Property fieldValue, String\r
705      * newRefName) { int nFound = 0; if (fieldValue instanceof List) {\r
706      * List<Property> fieldValueList = (List) fieldValue; for (Property\r
707      * listItemValue : fieldValueList) { try { if ((listItemValue instanceof\r
708      * StringProperty) &&\r
709      * oldRefName.equalsIgnoreCase((String)listItemValue.getValue())) {\r
710      * nFound++; if(newRefName!=null) { fieldValue.setValue(newRefName); } else\r
711      * { // We cannot quit after the first, if we are replacing values. // If we\r
712      * are just looking (not replacing), finding one is enough. break; } } }\r
713      * catch( PropertyException pe ) {} } } else { try { if ((fieldValue\r
714      * instanceof StringProperty) &&\r
715      * oldRefName.equalsIgnoreCase((String)fieldValue.getValue())) { nFound++;\r
716      * if(newRefName!=null) { fieldValue.setValue(newRefName); } } } catch(\r
717      * PropertyException pe ) {} } return nFound; }\r
718      */\r
719 }\r