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.HashMap;
\r
27 import java.util.Iterator;
\r
28 import java.util.List;
\r
29 import java.util.Map;
\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
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
75 * RefNameServiceUtils is a collection of services utilities related to refName
\r
78 * $LastChangedRevision: $ $LastChangedDate: $
\r
80 public class RefNameServiceUtils {
\r
82 public static class AuthRefConfigInfo {
\r
84 public String getQualifiedDisplayName() {
\r
85 return (Tools.isBlank(schema))
\r
86 ? displayName : DocumentUtils.appendSchemaName(schema, displayName);
\r
89 public String getDisplayName() {
\r
93 public void setDisplayName(String displayName) {
\r
94 this.displayName = displayName;
\r
99 public String getSchema() {
\r
103 public void setSchema(String schema) {
\r
104 this.schema = schema;
\r
107 public String getFullPath() {
\r
111 public void setFullPath(String fullPath) {
\r
112 this.fullPath = fullPath;
\r
115 protected String[] pathEls;
\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
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
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
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
149 fullPath = pair[0];
\r
150 pathEls = pair[0].split("/");
\r
151 displayName = pair[1];
\r
153 String[] schemaSplit = pathEls[0].split(":", 2);
\r
155 if (schemaSplit.length == 1) { // schema not specified
\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
163 this.displayName = displayName;
\r
164 this.schema = schema;
\r
165 this.fullPath = fullPath;
\r
166 this.pathEls = pathEls;
\r
170 protected void checkPathEls() {
\r
171 int len = pathEls.length;
\r
173 throw new InternalError("Bad values in authRef info - caller screwed up:" + fullPath);
\r
175 // Handle case of them putting a leading slash on the path
\r
176 if (len > 1 && pathEls[0].endsWith(":")) {
\r
178 String[] newArray = new String[len];
\r
179 newArray[0] = pathEls[0] + pathEls[1];
\r
181 System.arraycopy(pathEls, 2, newArray, 1, len - 1);
\r
183 pathEls = newArray;
\r
188 public static class AuthRefInfo extends AuthRefConfigInfo {
\r
190 public Property getProperty() {
\r
194 public void setProperty(Property property) {
\r
195 this.property = property;
\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
204 public AuthRefInfo(AuthRefConfigInfo arci, Property prop) {
\r
206 this.property = prop;
\r
210 private static final Logger logger = LoggerFactory.getLogger(RefNameServiceUtils.class);
\r
211 private static ArrayList<String> refNameServiceTypes = null;
\r
213 public static void updateRefNamesInRelations(
\r
214 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
\r
215 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient,
\r
216 RepositoryInstance repoSession,
\r
218 String newRefName) {
\r
220 // First, look for and update all the places where the refName is the "subject" of the relationship
\r
222 RelationUtils.updateRefNamesInRelations(ctx, repoClient, repoSession, IRelationsManager.SUBJECT_REFNAME, oldRefName, newRefName);
\r
225 // Next, look for and update all the places where the refName is the "object" of the relationship
\r
227 RelationUtils.updateRefNamesInRelations(ctx, repoClient, repoSession, IRelationsManager.OBJECT_REFNAME, oldRefName, newRefName);
\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
239 return authRefsInfo;
\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
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
257 List<AuthorityRefDocList.AuthorityRefDocItem> list =
\r
258 wrapperList.getAuthorityRefDocItem();
\r
260 Map<String, ServiceBindingType> queriedServiceBindings = new HashMap<String, ServiceBindingType>();
\r
261 Map<String, List<AuthRefConfigInfo>> authRefFieldsByService = new HashMap<String, List<AuthRefConfigInfo>>();
\r
263 RepositoryJavaClientImpl nuxeoRepoClient = (RepositoryJavaClientImpl) repoClient;
\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
273 if (docList == null) { // found no authRef fields - nothing to process
\r
274 return wrapperList;
\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
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
290 String fieldList = "docType|docId|docNumber|docName|sourceField|uri|updatedAt|workflowState";
\r
291 commonList.setFieldsReturned(fieldList);
\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
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
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
308 commonList.setPageSize(pageSize);
\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
317 // Slice the list to return only the specified page of items
\r
318 // in the list results.
\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
324 int startIndex = 0;
\r
327 // Return all results if pageSize is 0.
\r
328 if (pageSize == 0) {
\r
330 endIndex = list.size();
\r
332 startIndex = pageNum * pageSize;
\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
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
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
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
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
370 return wrapperList;
\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
380 return refNameServiceTypes;
\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
387 public static int updateAuthorityRefDocs(
\r
388 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
\r
389 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient,
\r
390 RepositoryInstance repoSession,
\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
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
404 if (repoClient instanceof RepositoryJavaClientImpl == false) {
\r
405 throw new InternalError("updateAuthorityRefDocs() called with unknown repoClient type!");
\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
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
418 if (docList == null) {
\r
419 logger.debug("updateAuthorityRefDocs: no documents could be found that referenced the old refName");
\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
428 if (docsInCurrentPage < pageSize) {
\r
429 logger.debug("updateAuthorityRefDocs: assuming no more documents requiring refName updates will be found, as docsInCurrentPage < pageSize");
\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
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
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
450 } catch (Exception e) {
\r
451 logger.error("Internal error updating the AuthorityRefDocs: " + e.getLocalizedMessage());
\r
452 logger.debug(Tools.errorToString(e, true));
\r
455 logger.debug("updateAuthorityRefDocs replaced a total of " + nRefsFound + " authority references, within as many as " + docsScanned + " scanned document(s)");
\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
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
471 boolean computeTotal) throws DocumentException, DocumentNotFoundException {
\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
482 // Filter the list for current user rights
\r
483 servicebindings = SecurityUtils.getReadableServiceBindingsForCurrentUser(servicebindings);
\r
485 ArrayList<String> docTypes = new ArrayList<String>();
\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
492 // Additional qualifications, like workflow state
\r
493 if (Tools.notBlank(whereClauseAdditions)) {
\r
494 query += " AND " + whereClauseAdditions;
\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
504 private static final boolean READY_FOR_COMPLEX_QUERY = true;
\r
506 private static String computeWhereClauseForAuthorityRefDocs(
\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
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
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
531 String docType = sb.getObject().getName();
\r
532 queriedServiceBindings.put(docType, sb);
\r
533 authRefFieldsByService.put(docType, authRefsInfo);
\r
534 docTypes.add(docType);
\r
537 if (fFirst) { // found no authRef fields - nothing to query
\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
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
552 String whereClauseStr = QueryManager.createWhereClauseFromKeywords(keywords);
\r
554 if (logger.isTraceEnabled()) {
\r
555 logger.trace("The 'where' clause to find refObjs is: ", whereClauseStr);
\r
558 return whereClauseStr;
\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
569 private static int processRefObjsDocList(
\r
570 DocumentModelList docList,
\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
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
588 throw new RuntimeException(
\r
589 "getAuthorityRefDocs: No Service Binding for docType: " + docType);
\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
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
601 ilistItem = new AuthorityRefDocList.AuthorityRefDocItem();
\r
602 String csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
\r
603 ilistItem.setDocId(csid);
\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
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
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
627 logger.warn("Unrecognized URI template type = " + template.getUriTemplateType());
\r
628 // Sets the default (empty string) value for uri
\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
635 ilistItem.setUri(uri);
\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
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
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
655 //String authRefAncestorField = "";
\r
656 //String authRefDescendantField = "";
\r
657 //String sourceField = "";
\r
658 int nRefsFoundInDoc = 0;
\r
660 ArrayList<RefNameServiceUtils.AuthRefInfo> foundProps = new ArrayList<RefNameServiceUtils.AuthRefInfo>();
\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
670 list.add(ilistItem);
\r
671 } else { // update refName case
\r
672 Property propToUpdate = ari.getProperty();
\r
673 propToUpdate.setValue(newAuthorityRefName);
\r
677 } catch (ClientException ce) {
\r
678 throw new RuntimeException(
\r
679 "getAuthorityRefDocs: Problem fetching values from repo: " + ce.getLocalizedMessage());
\r
681 if (nRefsFoundInDoc == 0) {
\r
683 "getAuthorityRefDocs: Result: "
\r
684 + docType + " [" + NuxeoUtils.getCsid(docModel)
\r
685 + "] does not reference ["
\r
688 nRefsFoundTotal += nRefsFoundInDoc;
\r
690 return nRefsFoundTotal;
\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
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
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
732 for (AuthRefConfigInfo arci : authRefFieldInfo) {
\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
744 private static List<AuthRefInfo> findAuthRefPropertiesInProperty(
\r
745 List<AuthRefInfo> foundProps,
\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
755 AuthRefInfo ari = null;
\r
756 if (prop == null) {
\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
772 addARIifMatches(refNameToMatch, matchBaseOnly, arci, listItemProp, foundProps);
\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
780 logger.error("Configuration for authRefs does not match schema structure: "
\r
781 + arci.pathEls.toString());
\r
785 } else if (prop.isComplex()) {
\r
786 String localPropName = arci.pathEls[pathStartIndex];
\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
798 logger.error("Configuration for authRefs does not match schema structure: "
\r
799 + arci.pathEls.toString());
\r
803 foundProps.add(ari); //FIXME: REM - This is dead code. 'ari' is never touched after being initalized to null. Why?
\r
809 private static void addARIifMatches(
\r
810 String refNameToMatch,
\r
811 boolean matchBaseOnly,
\r
812 AuthRefConfigInfo arci,
\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
818 String value = (String) prop.getValue();
\r
819 if (((refNameToMatch != null) &&
\r
821 (value!=null && value.startsWith(refNameToMatch))
\r
822 :refNameToMatch.equals(value)))
\r
823 || ((refNameToMatch == null) && Tools.notBlank(value))) {
\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
829 } catch (PropertyException pe) {
\r
830 logger.debug("PropertyException on: " + prop.getPath() + pe.getLocalizedMessage());
\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
838 * Only works for: * Scalar fields * Repeatable scalar fields (aka
\r
839 * multi-valued fields)
\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