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
6 * http://www.collectionspace.org http://wiki.collectionspace.org
\r
8 * Copyright 2009 University of California at Berkeley
\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
13 * You may obtain a copy of the ECL 2.0 License at
\r
15 * https://source.collectionspace.org/collection-space/LICENSE.txt
\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
23 package org.collectionspace.services.common.vocabulary;
\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
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
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.config.URIUtils;
\r
55 import org.collectionspace.services.common.context.ServiceBindingUtils;
\r
56 import org.collectionspace.services.common.document.DocumentException;
\r
57 import org.collectionspace.services.common.document.DocumentFilter;
\r
58 import org.collectionspace.services.common.document.DocumentNotFoundException;
\r
59 import org.collectionspace.services.common.document.DocumentUtils;
\r
60 import org.collectionspace.services.common.document.DocumentWrapper;
\r
61 import org.collectionspace.services.common.query.QueryManager;
\r
62 import org.collectionspace.services.common.repository.RepositoryClient;
\r
63 // import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema;
\r
64 import org.collectionspace.services.nuxeo.client.java.DocHandlerBase;
\r
65 import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl;
\r
66 import org.collectionspace.services.common.security.SecurityUtils;
\r
67 import org.collectionspace.services.config.service.ServiceBindingType;
\r
68 import org.collectionspace.services.jaxb.AbstractCommonList;
\r
69 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
\r
71 import com.sun.xml.bind.v2.runtime.unmarshaller.XsiNilLoader.Array;
\r
74 * RefNameServiceUtils is a collection of services utilities related to refName
\r
77 * $LastChangedRevision: $ $LastChangedDate: $
\r
79 public class RefNameServiceUtils {
\r
81 public static class AuthRefConfigInfo {
\r
83 public String getQualifiedDisplayName() {
\r
84 return (Tools.isBlank(schema))
\r
85 ? displayName : DocumentUtils.appendSchemaName(schema, displayName);
\r
88 public String getDisplayName() {
\r
92 public void setDisplayName(String displayName) {
\r
93 this.displayName = displayName;
\r
98 public String getSchema() {
\r
102 public void setSchema(String schema) {
\r
103 this.schema = schema;
\r
106 public String getFullPath() {
\r
110 public void setFullPath(String fullPath) {
\r
111 this.fullPath = fullPath;
\r
114 protected String[] pathEls;
\r
116 public AuthRefConfigInfo(AuthRefConfigInfo arci) {
\r
117 this.displayName = arci.displayName;
\r
118 this.schema = arci.schema;
\r
119 this.fullPath = arci.fullPath;
\r
120 this.pathEls = arci.pathEls;
\r
121 // Skip the pathElse check, since we are creatign from another (presumably valid) arci.
\r
124 public AuthRefConfigInfo(String displayName, String schema, String fullPath, String[] pathEls) {
\r
125 this.displayName = displayName;
\r
126 this.schema = schema;
\r
127 this.fullPath = fullPath;
\r
128 this.pathEls = pathEls;
\r
132 // Split a config value string like "intakes_common:collector", or
\r
133 // "collectionobjects_common:contentPeoples|contentPeople"
\r
134 // "collectionobjects_common:assocEventGroupList/*/assocEventPlace"
\r
135 // If has a pipe ('|') second part is a displayLabel, and first is path
\r
136 // Otherwise, entry is a path, and can use the last pathElement as displayName
\r
137 // Should be schema qualified.
\r
138 public AuthRefConfigInfo(String configString) {
\r
139 String[] pair = configString.split("\\|", 2);
\r
141 String displayName, fullPath;
\r
142 if (pair.length == 1) {
\r
143 // no label specifier, so we'll defer getting label
\r
144 fullPath = pair[0];
\r
145 pathEls = pair[0].split("/");
\r
146 displayName = pathEls[pathEls.length - 1];
\r
148 fullPath = pair[0];
\r
149 pathEls = pair[0].split("/");
\r
150 displayName = pair[1];
\r
152 String[] schemaSplit = pathEls[0].split(":", 2);
\r
154 if (schemaSplit.length == 1) { // schema not specified
\r
157 schema = schemaSplit[0];
\r
158 if (pair.length == 1 && pathEls.length == 1) { // simplest case of field in top level schema, no labelll
\r
159 displayName = schemaSplit[1]; // Have to fix up displayName to have no schema
\r
162 this.displayName = displayName;
\r
163 this.schema = schema;
\r
164 this.fullPath = fullPath;
\r
165 this.pathEls = pathEls;
\r
169 protected void checkPathEls() {
\r
170 int len = pathEls.length;
\r
172 throw new InternalError("Bad values in authRef info - caller screwed up:" + fullPath);
\r
174 // Handle case of them putting a leading slash on the path
\r
175 if (len > 1 && pathEls[0].endsWith(":")) {
\r
177 String[] newArray = new String[len];
\r
178 newArray[0] = pathEls[0] + pathEls[1];
\r
180 System.arraycopy(pathEls, 2, newArray, 1, len - 1);
\r
182 pathEls = newArray;
\r
187 public static class AuthRefInfo extends AuthRefConfigInfo {
\r
189 public Property getProperty() {
\r
193 public void setProperty(Property property) {
\r
194 this.property = property;
\r
198 public AuthRefInfo(String displayName, String schema, String fullPath, String[] pathEls, Property prop) {
\r
199 super(displayName, schema, fullPath, pathEls);
\r
200 this.property = prop;
\r
203 public AuthRefInfo(AuthRefConfigInfo arci, Property prop) {
\r
205 this.property = prop;
\r
208 private static final Logger logger = LoggerFactory.getLogger(RefNameServiceUtils.class);
\r
209 private static ArrayList<String> refNameServiceTypes = null;
\r
211 public static List<AuthRefConfigInfo> getConfiguredAuthorityRefs(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
\r
212 List<String> authRefFields =
\r
213 ((AbstractServiceContextImpl) ctx).getAllPartsPropertyValues(
\r
214 ServiceBindingUtils.AUTH_REF_PROP, ServiceBindingUtils.QUALIFIED_PROP_NAMES);
\r
215 ArrayList<AuthRefConfigInfo> authRefsInfo = new ArrayList<AuthRefConfigInfo>(authRefFields.size());
\r
216 for (String spec : authRefFields) {
\r
217 AuthRefConfigInfo arci = new AuthRefConfigInfo(spec);
\r
218 authRefsInfo.add(arci);
\r
220 return authRefsInfo;
\r
223 public static AuthorityRefDocList getAuthorityRefDocs(
\r
224 RepositoryInstance repoSession,
\r
225 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
\r
226 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient,
\r
227 List<String> serviceTypes,
\r
229 String refPropName,
\r
230 DocumentFilter filter, boolean computeTotal)
\r
231 throws DocumentException, DocumentNotFoundException {
\r
232 AuthorityRefDocList wrapperList = new AuthorityRefDocList();
\r
233 AbstractCommonList commonList = (AbstractCommonList) wrapperList;
\r
234 int pageNum = filter.getStartPage();
\r
235 int pageSize = filter.getPageSize();
\r
237 List<AuthorityRefDocList.AuthorityRefDocItem> list =
\r
238 wrapperList.getAuthorityRefDocItem();
\r
240 Map<String, ServiceBindingType> queriedServiceBindings = new HashMap<String, ServiceBindingType>();
\r
241 Map<String, List<AuthRefConfigInfo>> authRefFieldsByService = new HashMap<String, List<AuthRefConfigInfo>>();
\r
243 RepositoryJavaClientImpl nuxeoRepoClient = (RepositoryJavaClientImpl) repoClient;
\r
245 // Ignore any provided page size and number query parameters in
\r
246 // the following call, as they pertain to the list of authority
\r
247 // references to be returned, not to the list of documents to be
\r
248 // scanned for those references.
\r
249 DocumentModelList docList = findAuthorityRefDocs(ctx, repoClient, repoSession,
\r
250 serviceTypes, refName, refPropName, queriedServiceBindings, authRefFieldsByService,
\r
251 filter.getWhereClause(), null, 0 /* pageSize */, 0 /* pageNum */, computeTotal);
\r
253 if (docList == null) { // found no authRef fields - nothing to process
\r
254 return wrapperList;
\r
257 // set the fieldsReturned list. Even though this is a fixed schema, app layer treats
\r
258 // this like other abstract common lists
\r
260 * <xs:element name="docType" type="xs:string" minOccurs="1" />
\r
261 * <xs:element name="docId" type="xs:string" minOccurs="1" />
\r
262 * <xs:element name="docNumber" type="xs:string" minOccurs="0" />
\r
263 * <xs:element name="docName" type="xs:string" minOccurs="0" />
\r
264 * <xs:element name="sourceField" type="xs:string" minOccurs="1" />
\r
265 * <xs:element name="uri" type="xs:anyURI" minOccurs="1" />
\r
266 * <xs:element name="updatedAt" type="xs:string" minOccurs="1" />
\r
267 * <xs:element name="workflowState" type="xs:string" minOccurs="1"
\r
270 String fieldList = "docType|docId|docNumber|docName|sourceField|uri|updatedAt|workflowState";
\r
271 commonList.setFieldsReturned(fieldList);
\r
273 // As a side-effect, the method called below modifies the value of
\r
274 // the 'list' variable, which holds the list of references to
\r
275 // an authority item.
\r
277 // There can be more than one reference to a particular authority
\r
278 // item within any individual document scanned, so the number of
\r
279 // authority references may potentially exceed the total number
\r
280 // of documents scanned.
\r
281 int nRefsFound = processRefObjsDocList(docList, refName, queriedServiceBindings, authRefFieldsByService, // the actual list size needs to be updated to the size of "list"
\r
284 commonList.setPageSize(pageSize);
\r
286 // Values returned in the pagination block above the list items
\r
287 // need to reflect the number of references to authority items
\r
288 // returned, rather than the number of documents originally scanned
\r
289 // to find such references.
\r
290 commonList.setPageNum(pageNum);
\r
291 commonList.setTotalItems(list.size());
\r
293 // Slice the list to return only the specified page of items
\r
294 // in the list results.
\r
296 // FIXME: There may well be a pattern-based way to do this
\r
297 // in our framework, and if we can eliminate much of the
\r
298 // non-DRY code below, that would be desirable.
\r
300 int startIndex = 0;
\r
303 // Return all results if pageSize is 0.
\r
304 if (pageSize == 0) {
\r
306 endIndex = list.size();
\r
308 startIndex = pageNum * pageSize;
\r
311 // Return an empty list when the start of the requested page is
\r
312 // beyond the last item in the list.
\r
313 if (startIndex > list.size()) {
\r
314 wrapperList.getAuthorityRefDocItem().clear();
\r
315 commonList.setItemsInPage(wrapperList.getAuthorityRefDocItem().size());
\r
316 return wrapperList;
\r
319 // Otherwise, return a list of items from the start of the specified
\r
320 // page through the last item on that page, or otherwise through the
\r
321 // last item in the entire list, if that occurs earlier than the end
\r
322 // of the specified page.
\r
323 if (endIndex == 0) {
\r
324 int pageEndIndex = ((startIndex + pageSize));
\r
325 endIndex = (pageEndIndex > list.size()) ? list.size() : pageEndIndex;
\r
328 // Slice the list to return only the specified page of results.
\r
329 // Note: the second argument to List.subList(), endIndex, is
\r
330 // exclusive of the item at its index position, reflecting the
\r
331 // zero-index nature of the list.
\r
332 List<AuthorityRefDocList.AuthorityRefDocItem> currentPageList =
\r
333 new ArrayList<AuthorityRefDocList.AuthorityRefDocItem>(list.subList(startIndex, endIndex));
\r
334 wrapperList.getAuthorityRefDocItem().clear();
\r
335 wrapperList.getAuthorityRefDocItem().addAll(currentPageList);
\r
336 commonList.setItemsInPage(currentPageList.size());
\r
338 if (logger.isDebugEnabled() && (nRefsFound < docList.size())) {
\r
339 logger.debug("Internal curiosity: got fewer matches of refs than # docs matched..."); // We found a ref to ourself and have excluded it.
\r
341 } catch (Exception e) {
\r
342 logger.error("Could not retrieve a list of documents referring to the specified authority item", e);
\r
343 wrapperList = null;
\r
346 return wrapperList;
\r
349 private static ArrayList<String> getRefNameServiceTypes() {
\r
350 if (refNameServiceTypes == null) {
\r
351 refNameServiceTypes = new ArrayList<String>();
\r
352 refNameServiceTypes.add(ServiceBindingUtils.SERVICE_TYPE_AUTHORITY);
\r
353 refNameServiceTypes.add(ServiceBindingUtils.SERVICE_TYPE_OBJECT);
\r
354 refNameServiceTypes.add(ServiceBindingUtils.SERVICE_TYPE_PROCEDURE);
\r
356 return refNameServiceTypes;
\r
358 // Seems like a good value - no real data to set this well.
\r
359 // Note: can set this value lower; e.g. to 3 during debugging; - ADR 2012-07-10
\r
360 private static final int N_OBJS_TO_UPDATE_PER_LOOP = 100;
\r
362 public static int updateAuthorityRefDocs(
\r
363 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
\r
364 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient,
\r
365 RepositoryInstance repoSession,
\r
368 String refPropName) throws Exception {
\r
369 Map<String, ServiceBindingType> queriedServiceBindings = new HashMap<String, ServiceBindingType>();
\r
370 Map<String, List<AuthRefConfigInfo>> authRefFieldsByService = new HashMap<String, List<AuthRefConfigInfo>>();
\r
372 int docsScanned = 0;
\r
373 int nRefsFound = 0;
\r
374 int currentPage = 0;
\r
375 int docsInCurrentPage = 0;
\r
376 final String WHERE_CLAUSE_ADDITIONS_VALUE = null;
\r
377 final String ORDER_BY_VALUE = "collectionspace_core:createdAt";
\r
379 if (!(repoClient instanceof RepositoryJavaClientImpl)) {
\r
380 throw new InternalError("updateAuthorityRefDocs() called with unknown repoClient type!");
\r
382 try { // REM - How can we deal with transaction and timeout issues here.
\r
383 final int pageSize = N_OBJS_TO_UPDATE_PER_LOOP;
\r
384 DocumentModelList docList;
\r
385 boolean morePages = true;
\r
386 while (morePages) {
\r
388 docList = findAuthorityRefDocs(ctx, repoClient, repoSession,
\r
389 getRefNameServiceTypes(), oldRefName, refPropName,
\r
390 queriedServiceBindings, authRefFieldsByService, WHERE_CLAUSE_ADDITIONS_VALUE, ORDER_BY_VALUE, pageSize, currentPage, false);
\r
392 if (docList == null) {
\r
393 logger.debug("updateAuthorityRefDocs: no documents could be found that referenced the old refName");
\r
396 docsInCurrentPage = docList.size();
\r
397 logger.debug("updateAuthorityRefDocs: current page=" + currentPage + " documents included in page=" + docsInCurrentPage);
\r
398 if (docsInCurrentPage == 0) {
\r
399 logger.debug("updateAuthorityRefDocs: no more documents requiring refName updates could be found");
\r
402 if (docsInCurrentPage < pageSize) {
\r
403 logger.debug("updateAuthorityRefDocs: assuming no more documents requiring refName updates will be found, as docsInCurrentPage < pageSize");
\r
407 int nRefsFoundThisPage = processRefObjsDocList(docList, oldRefName, queriedServiceBindings, authRefFieldsByService,
\r
409 if (nRefsFoundThisPage > 0) {
\r
410 ((RepositoryJavaClientImpl) repoClient).saveDocListWithoutHandlerProcessing(ctx, repoSession, docList, true);
\r
411 nRefsFound += nRefsFoundThisPage;
\r
414 // FIXME: Per REM, set a limit of num objects - something like
\r
415 // 1000K objects - and also add a log Warning after some threshold
\r
416 docsScanned += docsInCurrentPage;
\r
422 } catch (Exception e) {
\r
423 logger.error("Internal error updating the AuthorityRefDocs: " + e.getLocalizedMessage());
\r
424 logger.debug(Tools.errorToString(e, true));
\r
427 logger.debug("updateAuthorityRefDocs replaced a total of " + nRefsFound + " authority references, within as many as " + docsScanned + " scanned document(s)");
\r
431 private static DocumentModelList findAuthorityRefDocs(
\r
432 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
\r
433 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient,
\r
434 RepositoryInstance repoSession, List<String> serviceTypes,
\r
436 String refPropName,
\r
437 Map<String, ServiceBindingType> queriedServiceBindings,
\r
438 Map<String, List<AuthRefConfigInfo>> authRefFieldsByService,
\r
439 String whereClauseAdditions,
\r
440 String orderByClause,
\r
443 boolean computeTotal) throws DocumentException, DocumentNotFoundException {
\r
445 // Get the service bindings for this tenant
\r
446 TenantBindingConfigReaderImpl tReader =
\r
447 ServiceMain.getInstance().getTenantBindingConfigReader();
\r
448 // We need to get all the procedures, authorities, and objects.
\r
449 List<ServiceBindingType> servicebindings = tReader.getServiceBindingsByType(ctx.getTenantId(), serviceTypes);
\r
450 if (servicebindings == null || servicebindings.isEmpty()) {
\r
451 logger.error("RefNameServiceUtils.getAuthorityRefDocs: No services bindings found, cannot proceed!");
\r
454 // Filter the list for current user rights
\r
455 servicebindings = SecurityUtils.getReadableServiceBindingsForCurrentUser(servicebindings);
\r
457 ArrayList<String> docTypes = new ArrayList<String>();
\r
459 String query = computeWhereClauseForAuthorityRefDocs(refName, refPropName, docTypes, servicebindings,
\r
460 queriedServiceBindings, authRefFieldsByService);
\r
461 if (query == null) { // found no authRef fields - nothing to query
\r
464 // Additional qualifications, like workflow state
\r
465 if (Tools.notBlank(whereClauseAdditions)) {
\r
466 query += " AND " + whereClauseAdditions;
\r
468 // Now we have to issue the search
\r
469 RepositoryJavaClientImpl nuxeoRepoClient = (RepositoryJavaClientImpl) repoClient;
\r
470 DocumentWrapper<DocumentModelList> docListWrapper = nuxeoRepoClient.findDocs(ctx, repoSession,
\r
471 docTypes, query, orderByClause, pageSize, pageNum, computeTotal);
\r
472 // Now we gather the info for each document into the list and return
\r
473 DocumentModelList docList = docListWrapper.getWrappedObject();
\r
476 private static final boolean READY_FOR_COMPLEX_QUERY = true;
\r
478 private static String computeWhereClauseForAuthorityRefDocs(
\r
480 String refPropName,
\r
481 ArrayList<String> docTypes,
\r
482 List<ServiceBindingType> servicebindings,
\r
483 Map<String, ServiceBindingType> queriedServiceBindings,
\r
484 Map<String, List<AuthRefConfigInfo>> authRefFieldsByService) {
\r
486 boolean fFirst = true;
\r
487 List<String> authRefFieldPaths;
\r
488 for (ServiceBindingType sb : servicebindings) {
\r
489 // Gets the property names for each part, qualified with the part label (which
\r
490 // is also the table name, the way that the repository works).
\r
491 authRefFieldPaths =
\r
492 ServiceBindingUtils.getAllPartsPropertyValues(sb,
\r
493 refPropName, ServiceBindingUtils.QUALIFIED_PROP_NAMES);
\r
494 if (authRefFieldPaths.isEmpty()) {
\r
497 ArrayList<AuthRefConfigInfo> authRefsInfo = new ArrayList<AuthRefConfigInfo>();
\r
498 for (String spec : authRefFieldPaths) {
\r
499 AuthRefConfigInfo arci = new AuthRefConfigInfo(spec);
\r
500 authRefsInfo.add(arci);
\r
503 String docType = sb.getObject().getName();
\r
504 queriedServiceBindings.put(docType, sb);
\r
505 authRefFieldsByService.put(docType, authRefsInfo);
\r
506 docTypes.add(docType);
\r
509 if (fFirst) { // found no authRef fields - nothing to query
\r
512 // We used to build a complete matches query, but that was too complex.
\r
513 // Just build a keyword query based upon some key pieces - the urn syntax elements and the shortID
\r
514 // Note that this will also match the Item itself, but that will get filtered out when
\r
515 // we compute actual matches.
\r
516 AuthorityTermInfo authTermInfo = RefNameUtils.parseAuthorityTermInfo(refName);
\r
518 String keywords = RefNameUtils.URN_PREFIX
\r
519 + " AND " + (authTermInfo.inAuthority.name != null
\r
520 ? authTermInfo.inAuthority.name : authTermInfo.inAuthority.csid)
\r
521 + " AND " + (authTermInfo.name != null
\r
522 ? authTermInfo.name : authTermInfo.csid);
\r
524 String whereClauseStr = QueryManager.createWhereClauseFromKeywords(keywords);
\r
526 if (logger.isTraceEnabled()) {
\r
527 logger.trace("The 'where' clause to find refObjs is: ", whereClauseStr);
\r
530 return whereClauseStr;
\r
534 * Runs through the list of found docs, processing them. If list is
\r
535 * non-null, then processing means gather the info for items. If list is
\r
536 * null, and newRefName is non-null, then processing means replacing and
\r
537 * updating. If processing/updating, this must be called in teh context of
\r
538 * an open session, and caller must release Session after calling this.
\r
541 private static int processRefObjsDocList(
\r
542 DocumentModelList docList,
\r
544 Map<String, ServiceBindingType> queriedServiceBindings,
\r
545 Map<String, List<AuthRefConfigInfo>> authRefFieldsByService,
\r
546 List<AuthorityRefDocList.AuthorityRefDocItem> list,
\r
547 String newAuthorityRefName) {
\r
548 Iterator<DocumentModel> iter = docList.iterator();
\r
549 int nRefsFoundTotal = 0;
\r
550 while (iter.hasNext()) {
\r
551 DocumentModel docModel = iter.next();
\r
552 AuthorityRefDocList.AuthorityRefDocItem ilistItem;
\r
554 String docType = docModel.getDocumentType().getName();
\r
555 docType = ServiceBindingUtils.getUnqualifiedTenantDocType(docType);
\r
556 ServiceBindingType sb = queriedServiceBindings.get(docType);
\r
558 throw new RuntimeException(
\r
559 "getAuthorityRefDocs: No Service Binding for docType: " + docType);
\r
562 if (list == null) { // no list - should be update refName case.
\r
563 if (newAuthorityRefName == null) {
\r
564 throw new InternalError("processRefObjsDocList() called with neither an itemList nor a new RefName!");
\r
567 } else { // Have a list - refObjs case
\r
568 if (newAuthorityRefName != null) {
\r
569 throw new InternalError("processRefObjsDocList() called with both an itemList and a new RefName!");
\r
571 ilistItem = new AuthorityRefDocList.AuthorityRefDocItem();
\r
572 String csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
\r
573 ilistItem.setDocId(csid);
\r
575 // FIXME: Hack for CSPACE-5406; this instead should use the (forthcoming)
\r
576 // URL pattern-to-Doctype registry described in CSPACE-5471 - ADR 2012-07-18
\r
577 if (sb.getType().equalsIgnoreCase(URIUtils.AUTHORITY_SERVICE_CATEGORY)) {
\r
578 String authoritySvcName = URIUtils.getAuthoritySvcName(docType);
\r
579 String inAuthorityCsid;
\r
581 inAuthorityCsid = (String) docModel.getPropertyValue("inAuthority"); // AuthorityItemJAXBSchema.IN_AUTHORITY
\r
582 uri = URIUtils.getAuthorityItemUri(authoritySvcName, inAuthorityCsid, csid);
\r
583 } catch (Exception e) {
\r
584 logger.warn("Could not extract inAuthority property from authority item record: " + e.getMessage());
\r
587 uri = URIUtils.getUri(sb.getName(), csid);;
\r
589 ilistItem.setUri(uri);
\r
591 ilistItem.setWorkflowState(docModel.getCurrentLifeCycleState());
\r
592 ilistItem.setUpdatedAt(DocHandlerBase.getUpdatedAtAsString(docModel));
\r
593 } catch (Exception e) {
\r
594 logger.error("Error getting core values for doc [" + csid + "]: " + e.getLocalizedMessage());
\r
596 // The id and URI are the same on all doctypes
\r
597 ilistItem.setDocType(docType);
\r
598 ilistItem.setDocNumber(
\r
599 ServiceBindingUtils.getMappedFieldInDoc(sb, ServiceBindingUtils.OBJ_NUMBER_PROP, docModel));
\r
600 ilistItem.setDocName(
\r
601 ServiceBindingUtils.getMappedFieldInDoc(sb, ServiceBindingUtils.OBJ_NAME_PROP, docModel));
\r
603 // Now, we have to loop over the authRefFieldsByService to figure
\r
604 // out which field(s) matched this.
\r
605 List<AuthRefConfigInfo> matchingAuthRefFields = authRefFieldsByService.get(docType);
\r
606 if (matchingAuthRefFields == null || matchingAuthRefFields.isEmpty()) {
\r
607 throw new RuntimeException(
\r
608 "getAuthorityRefDocs: internal logic error: can't fetch authRefFields for DocType.");
\r
610 //String authRefAncestorField = "";
\r
611 //String authRefDescendantField = "";
\r
612 //String sourceField = "";
\r
613 int nRefsFoundInDoc = 0;
\r
615 ArrayList<RefNameServiceUtils.AuthRefInfo> foundProps = new ArrayList<RefNameServiceUtils.AuthRefInfo>();
\r
617 findAuthRefPropertiesInDoc(docModel, matchingAuthRefFields, refName, foundProps);
\r
618 for (RefNameServiceUtils.AuthRefInfo ari : foundProps) {
\r
619 if (ilistItem != null) {
\r
620 if (nRefsFoundInDoc == 0) { // First one?
\r
621 ilistItem.setSourceField(ari.getQualifiedDisplayName());
\r
622 } else { // duplicates from one object
\r
623 ilistItem = cloneAuthRefDocItem(ilistItem, ari.getQualifiedDisplayName());
\r
625 list.add(ilistItem);
\r
626 } else { // update refName case
\r
627 Property propToUpdate = ari.getProperty();
\r
628 propToUpdate.setValue(newAuthorityRefName);
\r
632 } catch (ClientException ce) {
\r
633 throw new RuntimeException(
\r
634 "getAuthorityRefDocs: Problem fetching values from repo: " + ce.getLocalizedMessage());
\r
636 if (nRefsFoundInDoc == 0) {
\r
638 "getAuthorityRefDocs: Result: "
\r
639 + docType + " [" + NuxeoUtils.getCsid(docModel)
\r
640 + "] does not reference ["
\r
643 nRefsFoundTotal += nRefsFoundInDoc;
\r
645 return nRefsFoundTotal;
\r
648 private static AuthorityRefDocList.AuthorityRefDocItem cloneAuthRefDocItem(
\r
649 AuthorityRefDocList.AuthorityRefDocItem ilistItem, String sourceField) {
\r
650 AuthorityRefDocList.AuthorityRefDocItem newlistItem = new AuthorityRefDocList.AuthorityRefDocItem();
\r
651 newlistItem.setDocId(ilistItem.getDocId());
\r
652 newlistItem.setDocName(ilistItem.getDocName());
\r
653 newlistItem.setDocNumber(ilistItem.getDocNumber());
\r
654 newlistItem.setDocType(ilistItem.getDocType());
\r
655 newlistItem.setUri(ilistItem.getUri());
\r
656 newlistItem.setSourceField(sourceField);
\r
657 return newlistItem;
\r
660 public static List<AuthRefInfo> findAuthRefPropertiesInDoc(
\r
661 DocumentModel docModel,
\r
662 List<AuthRefConfigInfo> authRefFieldInfo,
\r
663 String refNameToMatch,
\r
664 List<AuthRefInfo> foundProps) {
\r
665 // Assume that authRefFieldInfo is keyed by the field name (possibly mapped for UI)
\r
666 // and the values are elPaths to the field, where intervening group structures in
\r
667 // lists of complex structures are replaced with "*". Thus, valid paths include
\r
668 // the following (note that the ServiceBindingUtils prepend schema names to configured values):
\r
669 // "schemaname:fieldname"
\r
670 // "schemaname:scalarlistname"
\r
671 // "schemaname:complexfieldname/fieldname"
\r
672 // "schemaname:complexlistname/*/fieldname"
\r
673 // "schemaname:complexlistname/*/scalarlistname"
\r
674 // "schemaname:complexlistname/*/complexfieldname/fieldname"
\r
675 // "schemaname:complexlistname/*/complexlistname/*/fieldname"
\r
677 for (AuthRefConfigInfo arci : authRefFieldInfo) {
\r
679 // Get first property and work down as needed.
\r
680 Property prop = docModel.getProperty(arci.pathEls[0]);
\r
681 findAuthRefPropertiesInProperty(foundProps, prop, arci, 0, refNameToMatch);
\r
682 } catch (Exception e) {
\r
683 logger.error("Problem fetching property: " + arci.pathEls[0]);
\r
689 public static List<AuthRefInfo> findAuthRefPropertiesInProperty(
\r
690 List<AuthRefInfo> foundProps,
\r
692 AuthRefConfigInfo arci,
\r
693 int pathStartIndex, // Supports recursion and we work down the path
\r
694 String refNameToMatch) {
\r
695 if (pathStartIndex >= arci.pathEls.length) {
\r
696 throw new ArrayIndexOutOfBoundsException("Index = " + pathStartIndex + " for path: "
\r
697 + arci.pathEls.toString());
\r
699 AuthRefInfo ari = null;
\r
700 if (prop == null) {
\r
704 if (prop instanceof StringProperty) { // scalar string
\r
705 addARIifMatches(refNameToMatch, arci, prop, foundProps);
\r
706 } else if (prop instanceof List) {
\r
707 List<Property> propList = (List<Property>) prop;
\r
708 // run through list. Must either be list of Strings, or Complex
\r
709 for (Property listItemProp : propList) {
\r
710 if (listItemProp instanceof StringProperty) {
\r
711 if (arci.pathEls.length - pathStartIndex != 1) {
\r
712 logger.error("Configuration for authRefs does not match schema structure: "
\r
713 + arci.pathEls.toString());
\r
716 addARIifMatches(refNameToMatch, arci, listItemProp, foundProps);
\r
718 } else if (listItemProp.isComplex()) {
\r
719 // Just recurse to handle this. Note that since this is a list of complex,
\r
720 // which should look like listName/*/... we add 2 to the path start index
\r
721 findAuthRefPropertiesInProperty(foundProps, listItemProp, arci,
\r
722 pathStartIndex + 2, refNameToMatch);
\r
724 logger.error("Configuration for authRefs does not match schema structure: "
\r
725 + arci.pathEls.toString());
\r
729 } else if (prop.isComplex()) {
\r
730 String localPropName = arci.pathEls[pathStartIndex];
\r
732 Property localProp = prop.get(localPropName);
\r
733 // Now just recurse, pushing down the path 1 step
\r
734 findAuthRefPropertiesInProperty(foundProps, localProp, arci,
\r
735 pathStartIndex, refNameToMatch);
\r
736 } catch (PropertyNotFoundException pnfe) {
\r
737 logger.error("Could not find property: [" + localPropName + "] in path: "
\r
738 + arci.getFullPath());
\r
739 // Fall through - ari will be null and we will continue...
\r
742 logger.error("Configuration for authRefs does not match schema structure: "
\r
743 + arci.pathEls.toString());
\r
747 foundProps.add(ari); //FIXME: REM - This is dead code. 'ari' is never touched after being initalized to null. Why?
\r
753 private static void addARIifMatches(
\r
754 String refNameToMatch,
\r
755 AuthRefConfigInfo arci,
\r
757 List<AuthRefInfo> foundProps) {
\r
758 // Need to either match a passed refName
\r
759 // OR have no refName to match but be non-empty
\r
761 String value = (String) prop.getValue();
\r
762 if (((refNameToMatch != null) && refNameToMatch.equals(value))
\r
763 || ((refNameToMatch == null) && Tools.notBlank(value))) {
\r
765 logger.debug("Found a match on property: " + prop.getPath() + " with value: [" + value + "]");
\r
766 AuthRefInfo ari = new AuthRefInfo(arci, prop);
\r
767 foundProps.add(ari);
\r
769 } catch (PropertyException pe) {
\r
770 logger.debug("PropertyException on: " + prop.getPath() + pe.getLocalizedMessage());
\r
775 * Identifies whether the refName was found in the supplied field. If passed
\r
776 * a new RefName, will set that into fields in which the old one was found.
\r
778 * Only works for: * Scalar fields * Repeatable scalar fields (aka
\r
779 * multi-valued fields)
\r
781 * Does not work for: * Structured fields (complexTypes) * Repeatable
\r
782 * structured fields (repeatable complexTypes) private static int
\r
783 * refNameFoundInField(String oldRefName, Property fieldValue, String
\r
784 * newRefName) { int nFound = 0; if (fieldValue instanceof List) {
\r
785 * List<Property> fieldValueList = (List) fieldValue; for (Property
\r
786 * listItemValue : fieldValueList) { try { if ((listItemValue instanceof
\r
787 * StringProperty) &&
\r
788 * oldRefName.equalsIgnoreCase((String)listItemValue.getValue())) {
\r
789 * nFound++; if(newRefName!=null) { fieldValue.setValue(newRefName); } else
\r
790 * { // We cannot quit after the first, if we are replacing values. // If we
\r
791 * are just looking (not replacing), finding one is enough. break; } } }
\r
792 * catch( PropertyException pe ) {} } } else { try { if ((fieldValue
\r
793 * instanceof StringProperty) &&
\r
794 * oldRefName.equalsIgnoreCase((String)fieldValue.getValue())) { nFound++;
\r
795 * if(newRefName!=null) { fieldValue.setValue(newRefName); } } } catch(
\r
796 * PropertyException pe ) {} } return nFound; }
\r