]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
563792c0e522fc7b360e50e1947eb01dd68afb07
[tmp/jakarta-migration.git] /
1 /**
2  * This document is a part of the source code and related artifacts for
3  * CollectionSpace, an open source collections management system for museums and
4  * related institutions:
5  *
6  * http://www.collectionspace.org http://wiki.collectionspace.org
7  *
8  * Copyright 2009 University of California at Berkeley
9  *
10  * Licensed under the Educational Community License (ECL), Version 2.0. You may
11  * not use this file except in compliance with this License.
12  *
13  * You may obtain a copy of the ECL 2.0 License at
14  *
15  * https://source.collectionspace.org/collection-space/LICENSE.txt
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
19  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
20  * License for the specific language governing permissions and limitations under
21  * the License.
22  */
23 package org.collectionspace.services.common.vocabulary;
24
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.Map;
30
31 import javax.ws.rs.core.Response;
32
33 import org.nuxeo.ecm.core.api.ClientException;
34 import org.nuxeo.ecm.core.api.DocumentModel;
35 import org.nuxeo.ecm.core.api.DocumentModelList;
36 import org.nuxeo.ecm.core.api.model.Property;
37 import org.nuxeo.ecm.core.api.model.PropertyException;
38 import org.nuxeo.ecm.core.api.model.PropertyNotFoundException;
39 import org.nuxeo.ecm.core.api.model.impl.primitives.StringProperty;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.collectionspace.services.client.CollectionSpaceClient;
43 import org.collectionspace.services.client.IQueryManager;
44 import org.collectionspace.services.client.IRelationsManager;
45 import org.collectionspace.services.client.PoxPayloadIn;
46 import org.collectionspace.services.client.PoxPayloadOut;
47 import org.collectionspace.services.common.CSWebApplicationException;
48 import org.collectionspace.services.common.ServiceMain;
49 import org.collectionspace.services.common.StoredValuesUriTemplate;
50 import org.collectionspace.services.common.UriTemplateFactory;
51 import org.collectionspace.services.common.UriTemplateRegistry;
52 import org.collectionspace.services.common.UriTemplateRegistryKey;
53 import org.collectionspace.services.common.context.ServiceContext;
54 import org.collectionspace.services.common.context.AbstractServiceContextImpl;
55 import org.collectionspace.services.common.api.RefNameUtils;
56 import org.collectionspace.services.common.api.Tools;
57 import org.collectionspace.services.common.api.RefNameUtils.AuthorityTermInfo;
58 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
59 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
60 import org.collectionspace.services.common.context.ServiceBindingUtils;
61 import org.collectionspace.services.common.document.DocumentException;
62 import org.collectionspace.services.common.document.DocumentFilter;
63 import org.collectionspace.services.common.document.DocumentNotFoundException;
64 import org.collectionspace.services.common.document.DocumentUtils;
65 import org.collectionspace.services.common.document.DocumentWrapper;
66 import org.collectionspace.services.common.query.QueryManager;
67 import org.collectionspace.services.common.relation.RelationUtils;
68 import org.collectionspace.services.common.repository.RepositoryClient;
69 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
70 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentModelHandler;
71 import org.collectionspace.services.nuxeo.client.java.NuxeoRepositoryClientImpl;
72 import org.collectionspace.services.common.security.SecurityUtils;
73 import org.collectionspace.services.config.service.ServiceBindingType;
74 import org.collectionspace.services.jaxb.AbstractCommonList;
75 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
76
77 /**
78  * RefNameServiceUtils is a collection of services utilities related to refName
79  * usage.
80  *
81  * $LastChangedRevision: $ $LastChangedDate: $
82  */
83 public class RefNameServiceUtils {
84
85     public static enum SpecifierForm {
86         CSID, URN_NAME // Either a CSID or a short ID
87     };
88
89     public static class Specifier {
90         //
91         // URN statics for things like urn:cspace:name(grover)
92         //
93         final static String URN_PREFIX = "urn:cspace:";
94         final static int URN_PREFIX_LEN = URN_PREFIX.length();
95         final static String URN_PREFIX_NAME = "name(";
96         final static int URN_NAME_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_NAME.length();
97         final static String URN_PREFIX_ID = "id(";
98         final static int URN_ID_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_ID.length();
99         
100         public SpecifierForm form;
101         public String value;
102
103         public Specifier(SpecifierForm form, String value) {
104             this.form = form;
105             this.value = value;
106         }
107         
108         /*
109          *  identifier can be a CSID form like a8ad38ec-1d7d-4bf2-bd31 or a URN form like urn:cspace:name(shortid) or urn:cspace:id(a8ad38ec-1d7d-4bf2-bd31)
110          *
111          */
112         public static Specifier getSpecifier(String identifier) throws CSWebApplicationException {
113                 return getSpecifier(identifier, "NO-OP", "NO-OP");
114         }
115
116         /*
117          *  identifier can be a CSID form like a8ad38ec-1d7d-4bf2-bd31 or a URN form like urn:cspace:name(shortid) or urn:cspace:id(a8ad38ec-1d7d-4bf2-bd31)
118          *
119          */
120         public static Specifier getSpecifier(String identifier, String method, String op) throws CSWebApplicationException {
121                 Specifier result = null;
122
123                 if (identifier != null) {
124                 if (!identifier.startsWith(URN_PREFIX)) {
125                     // We'll assume it is a CSID and complain if it does not match
126                     result = new Specifier(SpecifierForm.CSID, identifier);
127                 } else {
128                     if (identifier.startsWith(URN_PREFIX_NAME, URN_PREFIX_LEN)) {
129                         int closeParen = identifier.indexOf(')', URN_NAME_PREFIX_LEN);
130                         if (closeParen >= 0) {
131                             result = new Specifier(SpecifierForm.URN_NAME,
132                                     identifier.substring(URN_NAME_PREFIX_LEN, closeParen));
133                         }
134                     } else if (identifier.startsWith(URN_PREFIX_ID, URN_PREFIX_LEN)) {
135                         int closeParen = identifier.indexOf(')', URN_ID_PREFIX_LEN);
136                         if (closeParen >= 0) {
137                             result = new Specifier(SpecifierForm.CSID,
138                                     identifier.substring(URN_ID_PREFIX_LEN, closeParen));
139                         }
140                     } else {
141                         logger.error(method + ": bad or missing specifier!");
142                         Response response = Response.status(Response.Status.BAD_REQUEST).entity(
143                                 op + " failed on bad or missing Authority specifier").type(
144                                 "text/plain").build();
145                         throw new CSWebApplicationException(response);
146                     }
147                 }
148             }
149             
150             return result;
151         }
152         
153         /**
154          * Creates a refName in the name / shortIdentifier form.
155          *
156          * @param shortId a shortIdentifier for an authority or one of its terms
157          * @return a refName for that authority or term, in the name / shortIdentifier form.
158          *         If the provided shortIdentifier is null or empty, returns
159          *         the empty string.
160          */
161         public static String createShortIdURNValue(String shortId) {
162                 String result = null;
163                 
164             if (shortId != null || !shortId.trim().isEmpty()) {
165                 result = String.format("urn:cspace:name(%s)", shortId);
166             }
167             
168             return result;
169         }        
170         
171         /**
172          * Returns a URN string identifier -e.g., urn:cspace:name(patrick) or urn:cspace:id(579d18a6-b464-4b11-ba3a)
173          * 
174          * @return
175          * @throws Exception
176          */
177         public String getURNValue() throws Exception {
178                 String result = null;
179                 
180                 if (form == SpecifierForm.CSID) {
181                         result = String.format("urn:cspace:id(%s)", value);
182                 } else if (form == SpecifierForm.URN_NAME) {
183                         result = String.format("urn:cspace:name(%s)", value);
184                 } else {
185                         throw new Exception(String.format("Unknown specifier form '%s'.", form));
186                 }
187                 
188                 return result;
189         }
190     }
191     
192     public static class AuthorityItemSpecifier {
193         private Specifier parentSpecifier;
194         private Specifier itemSpecifier;
195         
196         public AuthorityItemSpecifier(Specifier parentSpecifier, Specifier itemSpecifier) {
197                 this.parentSpecifier = parentSpecifier;
198                 this.itemSpecifier = itemSpecifier;
199         }
200         
201         public AuthorityItemSpecifier(SpecifierForm form, String parentCsidOrShortId, String itemCsidOrShortId) {
202                 this.parentSpecifier = new Specifier(form, parentCsidOrShortId);
203                 this.itemSpecifier = new Specifier(form, itemCsidOrShortId);
204         }       
205         
206         public Specifier getParentSpecifier() {
207                 return this.parentSpecifier;
208         }
209         
210         public Specifier getItemSpecifier() {
211                 return this.itemSpecifier;
212         }
213         
214         @Override
215         public String toString() {
216                 String result = "%s/items/%s";
217                 
218                 try {
219                                 result = String.format(result, this.parentSpecifier.getURNValue(), this.itemSpecifier.getURNValue());
220                         } catch (Exception e) {
221                                 result = "Unknown error trying to get string representation of Specifier.";
222                                 logger.error(result, e);
223                         }
224                 
225                 return result;
226         }
227     }
228
229     public static class AuthRefConfigInfo {
230
231         public String getQualifiedDisplayName() {
232             return (Tools.isBlank(schema))
233                     ? displayName : DocumentUtils.appendSchemaName(schema, displayName);
234         }
235
236         public String getDisplayName() {
237             return displayName;
238         }
239
240         public void setDisplayName(String displayName) {
241             this.displayName = displayName;
242         }
243         String displayName;
244         String schema;
245
246         public String getSchema() {
247             return schema;
248         }
249
250         public void setSchema(String schema) {
251             this.schema = schema;
252         }
253
254         public String getFullPath() {
255             return fullPath;
256         }
257
258         public void setFullPath(String fullPath) {
259             this.fullPath = fullPath;
260         }
261         String fullPath;
262         protected String[] pathEls;
263
264         public AuthRefConfigInfo(AuthRefConfigInfo arci) {
265             this.displayName = arci.displayName;
266             this.schema = arci.schema;
267             this.fullPath = arci.fullPath;
268             this.pathEls = arci.pathEls;
269             // Skip the pathElse check, since we are creatign from another (presumably valid) arci.
270         }
271
272         public AuthRefConfigInfo(String displayName, String schema, String fullPath, String[] pathEls) {
273             this.displayName = displayName;
274             this.schema = schema;
275             this.fullPath = fullPath;
276             this.pathEls = pathEls;
277             checkPathEls();
278         }
279
280         // Split a config value string like "intakes_common:collector", or
281         // "collectionobjects_common:contentPeoples|contentPeople"
282         // "collectionobjects_common:assocEventGroupList/*/assocEventPlace"
283         // If has a pipe ('|') second part is a displayLabel, and first is path
284         // Otherwise, entry is a path, and can use the last pathElement as displayName
285         // Should be schema qualified.
286         public AuthRefConfigInfo(String configString) {
287             String[] pair = configString.split("\\|", 2);
288             String[] pathEls;
289             String displayName, fullPath;
290             if (pair.length == 1) {
291                 // no label specifier, so we'll defer getting label
292                 fullPath = pair[0];
293                 pathEls = pair[0].split("/");
294                 displayName = pathEls[pathEls.length - 1];
295             } else {
296                 fullPath = pair[0];
297                 pathEls = pair[0].split("/");
298                 displayName = pair[1];
299             }
300             String[] schemaSplit = pathEls[0].split(":", 2);
301             String schema;
302             if (schemaSplit.length == 1) {    // schema not specified
303                 schema = null;
304             } else {
305                 schema = schemaSplit[0];
306                 if (pair.length == 1 && pathEls.length == 1) {    // simplest case of field in top level schema, no labelll
307                     displayName = schemaSplit[1];    // Have to fix up displayName to have no schema
308                 }
309             }
310             this.displayName = displayName;
311             this.schema = schema;
312             this.fullPath = fullPath;
313             this.pathEls = pathEls;
314             checkPathEls();
315         }
316
317         protected void checkPathEls() {
318             int len = pathEls.length;
319             if (len < 1) {
320                 throw new InternalError("Bad values in authRef info - caller screwed up:" + fullPath);
321             }
322             // Handle case of them putting a leading slash on the path
323             if (len > 1 && pathEls[0].endsWith(":")) {
324                 len--;
325                 String[] newArray = new String[len];
326                 newArray[0] = pathEls[0] + pathEls[1];
327                 if (len >= 2) {
328                     System.arraycopy(pathEls, 2, newArray, 1, len - 1);
329                 }
330                 pathEls = newArray;
331             }
332         }
333     }
334
335     public static class AuthRefInfo extends AuthRefConfigInfo {
336
337         public Property getProperty() {
338             return property;
339         }
340
341         public void setProperty(Property property) {
342             this.property = property;
343         }
344         Property property;
345
346         public AuthRefInfo(String displayName, String schema, String fullPath, String[] pathEls, Property prop) {
347             super(displayName, schema, fullPath, pathEls);
348             this.property = prop;
349         }
350
351         public AuthRefInfo(AuthRefConfigInfo arci, Property prop) {
352             super(arci);
353             this.property = prop;
354         }
355     }
356     
357     private static final Logger logger = LoggerFactory.getLogger(RefNameServiceUtils.class);
358     private static ArrayList<String> refNameServiceTypes = null;
359
360     public static void updateRefNamesInRelations(
361             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
362             RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient,
363             CoreSessionInterface repoSession,
364             String oldRefName,
365             String newRefName) throws Exception {
366         //
367         // First, look for and update all the places where the refName is the "subject" of the relationship
368         //
369         RelationUtils.updateRefNamesInRelations(ctx, repoClient, repoSession, IRelationsManager.SUBJECT_REFNAME, oldRefName, newRefName);
370         
371         //
372         // Next, look for and update all the places where the refName is the "object" of the relationship
373         //
374         RelationUtils.updateRefNamesInRelations(ctx, repoClient, repoSession, IRelationsManager.OBJECT_REFNAME, oldRefName, newRefName);
375     }
376     
377         public static List<AuthRefConfigInfo> getConfiguredAuthorityRefs(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
378                 List<String> authRefFields = ((AbstractServiceContextImpl) ctx).getAllPartsPropertyValues(
379                                 ServiceBindingUtils.AUTH_REF_PROP, ServiceBindingUtils.QUALIFIED_PROP_NAMES);
380                 ArrayList<AuthRefConfigInfo> authRefsInfo = new ArrayList<AuthRefConfigInfo>(authRefFields.size());
381                 for (String spec : authRefFields) {
382                         AuthRefConfigInfo arci = new AuthRefConfigInfo(spec);
383                         authRefsInfo.add(arci);
384                 }
385                 return authRefsInfo;
386         }
387
388     public static AuthorityRefDocList getAuthorityRefDocs(
389                 CoreSessionInterface repoSession,
390             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
391             RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient,
392             List<String> serviceTypes,
393             String refName,
394             String refPropName, // authRef or termRef, authorities or vocab terms.
395             DocumentFilter filter, boolean computeTotal)
396             throws DocumentException, DocumentNotFoundException {
397         AuthorityRefDocList wrapperList = new AuthorityRefDocList();
398         AbstractCommonList commonList = (AbstractCommonList) wrapperList;
399         int pageNum = filter.getStartPage();
400         int pageSize = filter.getPageSize();
401         
402         List<AuthorityRefDocList.AuthorityRefDocItem> list =
403                 wrapperList.getAuthorityRefDocItem();
404
405         Map<String, ServiceBindingType> queriedServiceBindings = new HashMap<String, ServiceBindingType>();
406         Map<String, List<AuthRefConfigInfo>> authRefFieldsByService = new HashMap<String, List<AuthRefConfigInfo>>();
407
408         NuxeoRepositoryClientImpl nuxeoRepoClient = (NuxeoRepositoryClientImpl) repoClient;
409         try {
410             // Ignore any provided page size and number query parameters in
411             // the following call, as they pertain to the list of authority
412             // references to be returned, not to the list of documents to be
413             // scanned for those references.
414             
415             // Get a list of possibly referencing documents. This list is
416             // lazily loaded, page by page. Ideally, only one page will
417             // need to be loaded to fill one page of results. Some number
418             // of possibly referencing documents will be false positives,
419             // so use a page size of double the requested page size to
420             // account for those.
421             DocumentModelList docList = findAllAuthorityRefDocs(ctx, repoClient, repoSession,
422                     serviceTypes, refName, refPropName, queriedServiceBindings, authRefFieldsByService,
423                     filter.getWhereClause(), null, 2*pageSize, computeTotal);
424
425             if (docList == null) { // found no authRef fields - nothing to process
426                 return wrapperList;
427             }
428
429             String fieldList = "docType|docId|docNumber|docName|sourceField|uri|refName|updatedAt|workflowState";  // FIXME: Should not be hard-coded string
430             commonList.setFieldsReturned(fieldList);
431
432             // As a side-effect, the method called below modifies the value of
433             // the 'list' variable, which holds the list of references to
434             // an authority item.
435             //
436             // There can be more than one reference to a particular authority
437             // item within any individual document scanned, so the number of
438             // authority references may potentially exceed the total number
439             // of documents scanned.
440
441             // Strip off displayName and only match the base, so we get references to all 
442             // the NPTs as well as the PT.
443                 String strippedRefName = RefNameUtils.stripAuthorityTermDisplayName(refName);
444                 
445                 // *** Need to pass in pagination info here. 
446             int nRefsFound = processRefObjsDocListForList(docList, ctx.getTenantId(), strippedRefName, 
447                         queriedServiceBindings, authRefFieldsByService, // the actual list size needs to be updated to the size of "list"
448                     list, pageSize, pageNum);
449                 
450             commonList.setPageSize(pageSize);
451             
452             // Values returned in the pagination block above the list items
453             // need to reflect the number of references to authority items
454             // returned, rather than the number of documents originally scanned
455             // to find such references.
456             // This will be an estimate only...
457             commonList.setPageNum(pageNum);
458                 commonList.setTotalItems(nRefsFound);   // Accurate if total was scanned, otherwise, just an estimate
459             commonList.setItemsInPage(list.size());
460             
461             if (logger.isDebugEnabled() && (nRefsFound < docList.size())) {
462                 logger.debug("Internal curiosity: got fewer matches of refs than # docs matched..."); // We found a ref to ourself and have excluded it.
463             }
464         } catch (Exception e) {
465             logger.error("Could not retrieve a list of documents referring to the specified authority item", e);
466             wrapperList = null;
467         }
468
469         return wrapperList;
470     }
471
472     private static ArrayList<String> getRefNameServiceTypes() {
473         if (refNameServiceTypes == null) {
474             refNameServiceTypes = new ArrayList<String>();
475             refNameServiceTypes.add(ServiceBindingUtils.SERVICE_TYPE_AUTHORITY);
476             refNameServiceTypes.add(ServiceBindingUtils.SERVICE_TYPE_OBJECT);
477             refNameServiceTypes.add(ServiceBindingUtils.SERVICE_TYPE_PROCEDURE);
478         }
479         return refNameServiceTypes;
480     }
481     
482     // Seems like a good value - no real data to set this well.
483     // Note: can set this value lower during debugging; e.g. to 3 - ADR 2012-07-10
484     private static final int N_OBJS_TO_UPDATE_PER_LOOP = 100;
485
486     public static int updateAuthorityRefDocs(
487             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
488             RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient,
489             CoreSessionInterface repoSession,
490             String oldRefName,
491             String newRefName,
492             String refPropName) throws Exception {
493         Map<String, ServiceBindingType> queriedServiceBindings = new HashMap<String, ServiceBindingType>();
494         Map<String, List<AuthRefConfigInfo>> authRefFieldsByService = new HashMap<String, List<AuthRefConfigInfo>>();
495
496         int docsScanned = 0;
497         int nRefsFound = 0;
498         int currentPage = 0;
499         int docsInCurrentPage = 0;
500         final String WHERE_CLAUSE_ADDITIONS_VALUE = null;
501         final String ORDER_BY_VALUE = CollectionSpaceClient.CORE_CREATED_AT  // "collectionspace_core:createdAt";
502                                           + ", " + IQueryManager.NUXEO_UUID; // CSPACE-6333: Add secondary sort on uuid, in case records have the same createdAt timestamp.
503
504         if (repoClient instanceof NuxeoRepositoryClientImpl == false) {
505             throw new InternalError("updateAuthorityRefDocs() called with unknown repoClient type!");
506         }
507         
508         try { // REM - How can we deal with transaction and timeout issues here?
509             final int pageSize = N_OBJS_TO_UPDATE_PER_LOOP;
510             DocumentModelList docList;
511             boolean morePages = true;
512             while (morePages) {
513
514                 docList = findAuthorityRefDocs(ctx, repoClient, repoSession,
515                         getRefNameServiceTypes(), oldRefName, refPropName,
516                         queriedServiceBindings, authRefFieldsByService, WHERE_CLAUSE_ADDITIONS_VALUE, ORDER_BY_VALUE, pageSize, currentPage, false);
517
518                 if (docList == null) {
519                     logger.debug("updateAuthorityRefDocs: no documents could be found that referenced the old refName");
520                     break;
521                 }
522                 docsInCurrentPage = docList.size();
523                 logger.debug("updateAuthorityRefDocs: current page=" + currentPage + " documents included in page=" + docsInCurrentPage);
524                 if (docsInCurrentPage == 0) {
525                     logger.debug("updateAuthorityRefDocs: no more documents requiring refName updates could be found");
526                     break;
527                 }
528                 if (docsInCurrentPage < pageSize) {
529                     logger.debug("updateAuthorityRefDocs: assuming no more documents requiring refName updates will be found, as docsInCurrentPage < pageSize");
530                     morePages = false;
531                 }
532
533                 // Only match complete refNames - unless and until we decide how to resolve changes
534                 // to NPTs we will defer that and only change PTs or refNames as passed in.
535                 int nRefsFoundThisPage = processRefObjsDocListForUpdate(ctx, docList, ctx.getTenantId(), oldRefName, 
536                                 queriedServiceBindings, authRefFieldsByService, // Perform the refName updates on the list of document models
537                         newRefName);
538                 if (nRefsFoundThisPage > 0) {
539                     ((NuxeoRepositoryClientImpl) repoClient).saveDocListWithoutHandlerProcessing(ctx, repoSession, docList, true); // Flush the document model list out to Nuxeo storage
540                     nRefsFound += nRefsFoundThisPage;
541                 }
542
543                 // FIXME: Per REM, set a limit of num objects - something like
544                 // 1000K objects - and also add a log Warning after some threshold
545                 docsScanned += docsInCurrentPage;
546                 if (morePages) {
547                     currentPage++;
548                 }
549
550             }
551         } catch (Exception e) {
552             logger.error("Internal error updating the AuthorityRefDocs: " + e.getLocalizedMessage());
553             logger.debug(Tools.errorToString(e, true));
554             throw e;
555         }
556         logger.debug("updateAuthorityRefDocs replaced a total of " + nRefsFound + " authority references, within as many as " + docsScanned + " scanned document(s)");
557         return nRefsFound;
558     }
559
560     private static DocumentModelList findAllAuthorityRefDocs(
561             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
562             RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient,
563             CoreSessionInterface repoSession, List<String> serviceTypes,
564             String refName,
565             String refPropName,
566             Map<String, ServiceBindingType> queriedServiceBindings,
567             Map<String, List<AuthRefConfigInfo>> authRefFieldsByService,
568             String whereClauseAdditions,
569             String orderByClause,
570             int pageSize,
571             boolean computeTotal) throws DocumentException, DocumentNotFoundException {
572                 
573         return new LazyAuthorityRefDocList(ctx, repoClient, repoSession,
574                         serviceTypes, refName, refPropName, queriedServiceBindings, authRefFieldsByService,
575                         whereClauseAdditions, orderByClause, pageSize, computeTotal);
576     }
577     
578     protected static DocumentModelList findAuthorityRefDocs(
579             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
580             RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient,
581             CoreSessionInterface repoSession, List<String> serviceTypes,
582             String refName,
583             String refPropName,
584             Map<String, ServiceBindingType> queriedServiceBindings,
585             Map<String, List<AuthRefConfigInfo>> authRefFieldsByService,
586             String whereClauseAdditions,
587             String orderByClause,
588             int pageSize,
589             int pageNum,
590             boolean computeTotal) throws DocumentException, DocumentNotFoundException {
591
592         // Get the service bindings for this tenant
593         TenantBindingConfigReaderImpl tReader =
594                 ServiceMain.getInstance().getTenantBindingConfigReader();
595         // We need to get all the procedures, authorities, and objects.
596         List<ServiceBindingType> servicebindings = tReader.getServiceBindingsByType(ctx.getTenantId(), serviceTypes);
597         if (servicebindings == null || servicebindings.isEmpty()) {
598             logger.error("RefNameServiceUtils.getAuthorityRefDocs: No services bindings found, cannot proceed!");
599             return null;
600         }
601         // Filter the list for current user rights
602         servicebindings = SecurityUtils.getReadableServiceBindingsForCurrentUser(servicebindings);
603
604         ArrayList<String> docTypes = new ArrayList<String>();
605
606         String query = computeWhereClauseForAuthorityRefDocs(refName, refPropName, docTypes, servicebindings, // REM - Side effect that docTypes, authRefFieldsByService, and queriedServiceBindings get set/change.  Any others?
607                 queriedServiceBindings, authRefFieldsByService);
608         if (query == null) { // found no authRef fields - nothing to query
609             return null;
610         }
611         // Additional qualifications, like workflow state
612         if (Tools.notBlank(whereClauseAdditions)) {
613             query += " AND " + whereClauseAdditions;
614         }
615         // Now we have to issue the search
616         NuxeoRepositoryClientImpl nuxeoRepoClient = (NuxeoRepositoryClientImpl) repoClient;
617         DocumentWrapper<DocumentModelList> docListWrapper = nuxeoRepoClient.findDocs(ctx, repoSession,
618                 docTypes, query, orderByClause, pageSize, pageNum, computeTotal);
619         // Now we gather the info for each document into the list and return
620         DocumentModelList docList = docListWrapper.getWrappedObject();
621         return docList;
622     }
623     private static final boolean READY_FOR_COMPLEX_QUERY = true;
624
625     private static String computeWhereClauseForAuthorityRefDocs(
626             String refName,
627             String refPropName,
628             ArrayList<String> docTypes,
629             List<ServiceBindingType> servicebindings,
630             Map<String, ServiceBindingType> queriedServiceBindings,
631             Map<String, List<AuthRefConfigInfo>> authRefFieldsByService) {
632
633         boolean fFirst = true;
634         List<String> authRefFieldPaths;
635         for (ServiceBindingType sb : servicebindings) {
636             // Gets the property names for each part, qualified with the part label (which
637             // is also the table name, the way that the repository works).
638             authRefFieldPaths =
639                     ServiceBindingUtils.getAllPartsPropertyValues(sb,
640                     refPropName, ServiceBindingUtils.QUALIFIED_PROP_NAMES);
641             if (authRefFieldPaths.isEmpty()) {
642                 continue;
643             }
644             ArrayList<AuthRefConfigInfo> authRefsInfo = new ArrayList<AuthRefConfigInfo>();
645             for (String spec : authRefFieldPaths) {
646                 AuthRefConfigInfo arci = new AuthRefConfigInfo(spec);
647                 authRefsInfo.add(arci);
648             }
649
650             String docType = sb.getObject().getName();
651             queriedServiceBindings.put(docType, sb);
652             authRefFieldsByService.put(docType, authRefsInfo);
653             docTypes.add(docType);
654             fFirst = false;
655         }
656         if (fFirst) { // found no authRef fields - nothing to query
657             return null;
658         }
659         // We used to build a complete matches query, but that was too complex.
660         // Just build a keyword query based upon some key pieces - the urn syntax elements and the shortID
661         // Note that this will also match the Item itself, but that will get filtered out when
662         // we compute actual matches.
663         AuthorityTermInfo authTermInfo = RefNameUtils.parseAuthorityTermInfo(refName);
664
665         String keywords = RefNameUtils.URN_PREFIX
666                 + " AND " + (authTermInfo.inAuthority.name != null
667                 ? authTermInfo.inAuthority.name : authTermInfo.inAuthority.csid)
668                 + " AND " + (authTermInfo.name != null
669                 ? authTermInfo.name : authTermInfo.csid); // REM - This seems likely to cause trouble?  We should consider searching for the full refname -excluding the display name suffix?
670
671         String whereClauseStr = QueryManager.createWhereClauseFromKeywords(keywords);
672
673         if (logger.isTraceEnabled()) {
674             logger.trace("The 'where' clause to find refObjs is: ", whereClauseStr);
675         }
676
677         return whereClauseStr;
678     }
679     
680     // TODO there are multiple copies of this that should be put somewhere common.
681         protected static String getRefname(DocumentModel docModel) throws ClientException {
682                 String result = (String)docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
683                                 CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME);
684                 return result;
685         }
686
687     private static int processRefObjsDocListForUpdate(
688                 ServiceContext ctx,
689             DocumentModelList docList,
690             String tenantId,
691             String refName,
692             Map<String, ServiceBindingType> queriedServiceBindings,
693             Map<String, List<AuthRefConfigInfo>> authRefFieldsByService,
694             String newAuthorityRefName) {
695         boolean matchBaseOnly = false;
696         
697         if (ctx.shouldForceUpdateRefnameReferences() == true) {
698                 refName = RefNameUtils.stripAuthorityTermDisplayName(refName);
699                 matchBaseOnly = true;
700         }
701         
702         return processRefObjsDocList(docList, tenantId, refName, matchBaseOnly, queriedServiceBindings,
703                         authRefFieldsByService, null, 0, 0, newAuthorityRefName);
704     }
705                         
706     private static int processRefObjsDocListForList(
707             DocumentModelList docList,
708             String tenantId,
709             String refName,
710             Map<String, ServiceBindingType> queriedServiceBindings,
711             Map<String, List<AuthRefConfigInfo>> authRefFieldsByService,
712             List<AuthorityRefDocList.AuthorityRefDocItem> list, 
713             int pageSize, int pageNum) {
714         return processRefObjsDocList(docList, tenantId, refName, true, queriedServiceBindings,
715                         authRefFieldsByService, list, pageSize, pageNum, null);
716     }
717                         
718
719         /*
720      * Runs through the list of found docs, processing them. If list is
721      * non-null, then processing means gather the info for items. If list is
722      * null, and newRefName is non-null, then processing means replacing and
723      * updating. If processing/updating, this must be called in the context of
724      * an open session, and caller must release Session after calling this.
725      *
726      */
727     private static int processRefObjsDocList(
728             DocumentModelList docList,
729             String tenantId,
730             String refName,
731             boolean matchBaseOnly,
732             Map<String, ServiceBindingType> queriedServiceBindings,
733             Map<String, List<AuthRefConfigInfo>> authRefFieldsByService,
734             List<AuthorityRefDocList.AuthorityRefDocItem> list,
735             int pageSize, int pageNum,  // Only used when constructing a list.
736             String newAuthorityRefName) {
737         UriTemplateRegistry registry = ServiceMain.getInstance().getUriTemplateRegistry();
738         Iterator<DocumentModel> iter = docList.iterator();
739         int nRefsFoundTotal = 0;
740         boolean foundSelf = false;
741
742         // When paginating results, we have to guess at the total. First guess is the number of docs returned
743         // by the query. However, this returns some false positives, so may be high. 
744         // In addition, we can match multiple fields per doc, so this may be low. Fun, eh?
745         int nDocsReturnedInQuery = (int)docList.totalSize();
746         int nDocsProcessed = 0;
747         int firstItemInPage = pageNum*pageSize;
748         while (iter.hasNext()) {
749             DocumentModel docModel = iter.next();
750             AuthorityRefDocList.AuthorityRefDocItem ilistItem;
751
752             String docType = docModel.getDocumentType().getName(); // REM - This will be a tentant qualified document type
753             docType = ServiceBindingUtils.getUnqualifiedTenantDocType(docType);
754             ServiceBindingType sb = queriedServiceBindings.get(docType);
755             if (sb == null) {
756                 throw new RuntimeException(
757                         "getAuthorityRefDocs: No Service Binding for docType: " + docType);
758             }
759
760             if (list == null) { // no list - should be update refName case.
761                 if (newAuthorityRefName == null) {
762                     throw new InternalError("processRefObjsDocList() called with neither an itemList nor a new RefName!");
763                 }
764                 ilistItem = null;
765                 pageSize = 0;
766                 firstItemInPage = 0;    // Do not paginate if updating, rather than building list
767             } else {    // Have a list - refObjs case
768                 if (newAuthorityRefName != null) {
769                     throw new InternalError("processRefObjsDocList() called with both an itemList and a new RefName!");
770                 }
771                 if(firstItemInPage > 100) {
772                         logger.warn("Processing a large offset (size:{}, num:{}) for refObjs - will be expensive!!!",
773                                                 pageSize, pageNum);
774                 }
775                 // Note that we have to go through check all the fields to determine the actual page start
776                 ilistItem = new AuthorityRefDocList.AuthorityRefDocItem();
777                 String csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
778                 try {
779                         String itemRefName = getRefname(docModel);
780                         ilistItem.setRefName(itemRefName);
781                 } catch (ClientException ce) {
782                     throw new RuntimeException(
783                             "processRefObjsDocList: Problem fetching refName from item Object: " 
784                                         + ce.getLocalizedMessage());
785                 }
786                 ilistItem.setDocId(csid);
787                 String uri = "";
788                 UriTemplateRegistryKey key = new UriTemplateRegistryKey(tenantId, docType);
789                 StoredValuesUriTemplate template = registry.get(key);
790                 if (template != null) {
791                     Map<String, String> additionalValues = new HashMap<String, String>();
792                     if (template.getUriTemplateType() == UriTemplateFactory.RESOURCE) {
793                         additionalValues.put(UriTemplateFactory.IDENTIFIER_VAR, csid);
794                         uri = template.buildUri(additionalValues);
795                     } else if (template.getUriTemplateType() == UriTemplateFactory.ITEM) {
796                         try {
797                             String inAuthorityCsid = (String) NuxeoUtils.getProperyValue(docModel, "inAuthority"); //docModel.getPropertyValue("inAuthority"); // AuthorityItemJAXBSchema.IN_AUTHORITY
798                             additionalValues.put(UriTemplateFactory.IDENTIFIER_VAR, inAuthorityCsid);
799                             additionalValues.put(UriTemplateFactory.ITEM_IDENTIFIER_VAR, csid);
800                             uri = template.buildUri(additionalValues);
801                         } catch (Exception e) {
802                             logger.warn("Could not extract inAuthority property from authority item record: " + e.getMessage());
803                         }
804                     } else if (template.getUriTemplateType() == UriTemplateFactory.CONTACT) {
805                         // FIXME: Generating contact sub-resource URIs requires additional work,
806                         // as a follow-on to CSPACE-5271 - ADR 2012-08-16
807                         // Sets the default (empty string) value for uri, for now
808                     } else {
809                         logger.warn("Unrecognized URI template type = " + template.getUriTemplateType());
810                         // Sets the default (empty string) value for uri
811                     }
812                 } else { // (if template == null)
813                     logger.warn("Could not retrieve URI template from registry via tenant ID "
814                             + tenantId + " and docType " + docType);
815                     // Sets the default (empty string) value for uri
816                 }
817                 ilistItem.setUri(uri);
818                 try {
819                     ilistItem.setWorkflowState(docModel.getCurrentLifeCycleState());
820                     ilistItem.setUpdatedAt(NuxeoDocumentModelHandler.getUpdatedAtAsString(docModel));
821                 } catch (Exception e) {
822                     logger.error("Error getting core values for doc [" + csid + "]: " + e.getLocalizedMessage());
823                 }
824                 ilistItem.setDocType(docType);
825                 ilistItem.setDocNumber(
826                         ServiceBindingUtils.getMappedFieldInDoc(sb, ServiceBindingUtils.OBJ_NUMBER_PROP, docModel));
827                 ilistItem.setDocName(
828                         ServiceBindingUtils.getMappedFieldInDoc(sb, ServiceBindingUtils.OBJ_NAME_PROP, docModel));
829             }
830             // Now, we have to loop over the authRefFieldsByService to figure out
831             // out which field(s) matched this.
832             List<AuthRefConfigInfo> matchingAuthRefFields = authRefFieldsByService.get(docType);
833             if (matchingAuthRefFields == null || matchingAuthRefFields.isEmpty()) {
834                 throw new RuntimeException(
835                         "getAuthorityRefDocs: internal logic error: can't fetch authRefFields for DocType.");
836             }
837             //String authRefAncestorField = "";
838             //String authRefDescendantField = "";
839             //String sourceField = "";
840
841             ArrayList<RefNameServiceUtils.AuthRefInfo> foundProps = new ArrayList<RefNameServiceUtils.AuthRefInfo>();
842             try {
843                 findAuthRefPropertiesInDoc(docModel, matchingAuthRefFields, refName, matchBaseOnly, foundProps); // REM - side effect that foundProps is set
844                 if(!foundProps.isEmpty()) {
845                     int nRefsFoundInDoc = 0;
846                         for (RefNameServiceUtils.AuthRefInfo ari : foundProps) {
847                                 if (ilistItem != null) {
848                                         // So this is a true positive, and not a false one. We have to consider pagination now.
849                                         if(nRefsFoundTotal >= firstItemInPage) {        // skipped enough already
850                                                 if (nRefsFoundInDoc == 0) {    // First one?
851                                                         ilistItem.setSourceField(ari.getQualifiedDisplayName());
852                                                 } else {    // duplicates from one object
853                                                         ilistItem = cloneAuthRefDocItem(ilistItem, ari.getQualifiedDisplayName());
854                                                 }
855                                                 list.add(ilistItem);
856                                         nRefsFoundInDoc++;      // Only increment if processed, or clone logic above will fail
857                                         }
858                                 } else {    // update refName case
859                                         Property propToUpdate = ari.getProperty();
860                                         propToUpdate.setValue(newAuthorityRefName);
861                                 }
862                                 nRefsFoundTotal++;              // Whether we processed or not, we found - essential to pagination logic
863                         }
864                 } else if(ilistItem != null) {
865                         String docRefName = ilistItem.getRefName();
866                     if (matchBaseOnly?
867                                         (docRefName!=null && docRefName.startsWith(refName))
868                                         :refName.equals(docRefName)) {
869                                 // We found the self for an item
870                                 foundSelf = true;
871                                 logger.debug("getAuthorityRefDocs: Result: "
872                                                                 + docType + " [" + NuxeoUtils.getCsid(docModel)
873                                                                 + "] appears to be self for: ["
874                                                                 + refName + "]");
875                         } else {
876                                 logger.debug("getAuthorityRefDocs: Result: "
877                                                                 + docType + " [" + NuxeoUtils.getCsid(docModel)
878                                                                 + "] does not reference ["
879                                                                 + refName + "]");
880                         }
881                 }
882             } catch (ClientException ce) {
883                 throw new RuntimeException(
884                                 "getAuthorityRefDocs: Problem fetching values from repo: " + ce.getLocalizedMessage());
885             }
886             nDocsProcessed++;
887             // Done processing that doc. Are we done with the whole page?
888             // Note pageSize <=0 means do them all
889             if((pageSize > 0) && ((nRefsFoundTotal-firstItemInPage)>=pageSize)) {
890                 // Quitting early, so we need to estimate the total. Assume one per doc
891                 // for the rest of the docs we matched in the query
892                 int unprocessedDocs = nDocsReturnedInQuery - nDocsProcessed;
893                 if(unprocessedDocs>0) {
894                         // We generally match ourselves in the keyword search. If we already saw ourselves
895                         // then do not try to correct for this. Otherwise, decrement the total.
896                         // Yes, this is fairly goofy, but the whole estimation mechanism is goofy. 
897                         if(!foundSelf)
898                                 unprocessedDocs--;
899                         nRefsFoundTotal += unprocessedDocs;
900                 }
901                 break;
902             }
903         } // close while(iterator)
904         return nRefsFoundTotal;
905     }
906
907     /**
908      * Clone an AuthorityRefDocItem which is a JAX-B generated class.  Be sure we're copying every field defined in the XSD (XML Schema) that is
909      * found here services\jaxb\src\main\resources\authorityrefdocs.xsd
910      * @param ilistItem
911      * @param sourceField
912      * @return
913      */
914     private static AuthorityRefDocList.AuthorityRefDocItem cloneAuthRefDocItem(
915             AuthorityRefDocList.AuthorityRefDocItem ilistItem, String sourceField) {
916         AuthorityRefDocList.AuthorityRefDocItem newlistItem = new AuthorityRefDocList.AuthorityRefDocItem();
917         newlistItem.setDocId(ilistItem.getDocId());
918         newlistItem.setDocName(ilistItem.getDocName());
919         newlistItem.setDocNumber(ilistItem.getDocNumber());
920         newlistItem.setDocType(ilistItem.getDocType());
921         newlistItem.setUri(ilistItem.getUri());
922         newlistItem.setSourceField(sourceField);
923         newlistItem.setRefName(ilistItem.getRefName());
924         newlistItem.setUpdatedAt(ilistItem.getUpdatedAt());
925         newlistItem.setWorkflowState(ilistItem.getWorkflowState());
926         return newlistItem;
927     }
928
929     public static List<AuthRefInfo> findAuthRefPropertiesInDoc(
930             DocumentModel docModel,
931             List<AuthRefConfigInfo> authRefFieldInfoList,
932             String refNameToMatch,
933             List<AuthRefInfo> foundProps) {
934         return findAuthRefPropertiesInDoc(docModel, authRefFieldInfoList, 
935                                                                         refNameToMatch, false, foundProps);
936     }
937     
938     public static List<AuthRefInfo> findAuthRefPropertiesInDoc(
939             DocumentModel docModel,
940             List<AuthRefConfigInfo> authRefFieldInfoList,
941             String refNameToMatch,
942             boolean matchBaseOnly,
943             List<AuthRefInfo> authRefInfoList) {
944         // Assume that authRefFieldInfo is keyed by the field name (possibly mapped for UI)
945         // and the values are elPaths to the field, where intervening group structures in
946         // lists of complex structures are replaced with "*". Thus, valid paths include
947         // the following (note that the ServiceBindingUtils prepend schema names to configured values):
948         // "schemaname:fieldname"
949         // "schemaname:scalarlistname"
950         // "schemaname:complexfieldname/fieldname"
951         // "schemaname:complexlistname/*/fieldname"
952         // "schemaname:complexlistname/*/scalarlistname"
953         // "schemaname:complexlistname/*/complexfieldname/fieldname"
954         // "schemaname:complexlistname/*/complexlistname/*/fieldname"
955         // etc.
956         for (AuthRefConfigInfo arci : authRefFieldInfoList) {
957             try {
958                 // Get first property and work down as needed.
959                 Property prop = docModel.getProperty(arci.pathEls[0]);
960                 findAuthRefPropertiesInProperty(authRefInfoList, prop, arci, 0, refNameToMatch, matchBaseOnly);
961             } catch (Exception e) {
962                 logger.error("Problem fetching property: " + arci.pathEls[0]);
963             }
964         }
965         return authRefInfoList;
966     }
967
968     private static List<AuthRefInfo> findAuthRefPropertiesInProperty(
969             List<AuthRefInfo> authRefInfoList,
970             Property prop,
971             AuthRefConfigInfo arci,
972             int pathStartIndex, // Supports recursion and we work down the path
973             String refNameToMatch,
974             boolean matchBaseOnly ) {
975         if (pathStartIndex >= arci.pathEls.length) {
976             throw new ArrayIndexOutOfBoundsException("Index = " + pathStartIndex + " for path: "
977                     + arci.pathEls.toString());
978         }
979         AuthRefInfo ari = null;
980         if (prop == null) {
981             return authRefInfoList;
982         }
983
984         if (prop instanceof StringProperty) {    // scalar string
985             addARIifMatches(refNameToMatch, matchBaseOnly, arci, prop, authRefInfoList); // REM - Side effect that foundProps gets changed/updated
986         } else if (prop instanceof List) {
987             List<Property> propList = (List<Property>) prop;
988             // run through list. Must either be list of Strings, or Complex
989             for (Property listItemProp : propList) {
990                 if (listItemProp instanceof StringProperty) {
991                     if (arci.pathEls.length - pathStartIndex != 1) {
992                         logger.error("Configuration for authRefs does not match schema structure: "
993                                 + arci.pathEls.toString());
994                         break;
995                     } else {
996                         addARIifMatches(refNameToMatch, matchBaseOnly, arci, listItemProp, authRefInfoList);
997                     }
998                 } else if (listItemProp.isComplex()) {
999                     // Just recurse to handle this. Note that since this is a list of complex, 
1000                     // which should look like listName/*/... we add 2 to the path start index 
1001                     findAuthRefPropertiesInProperty(authRefInfoList, listItemProp, arci,
1002                             pathStartIndex + 2, refNameToMatch, matchBaseOnly);
1003                 } else {
1004                     logger.error("Configuration for authRefs does not match schema structure: "
1005                             + arci.pathEls.toString());
1006                     break;
1007                 }
1008             }
1009         } else if (prop.isComplex()) {
1010             String localPropName = arci.pathEls[pathStartIndex];
1011             try {
1012                 Property localProp = prop.get(localPropName);
1013                 // Now just recurse, pushing down the path 1 step
1014                 findAuthRefPropertiesInProperty(authRefInfoList, localProp, arci,
1015                         pathStartIndex, refNameToMatch, matchBaseOnly);
1016             } catch (PropertyNotFoundException pnfe) {
1017                 logger.error("Could not find property: [" + localPropName + "] in path: "
1018                         + arci.getFullPath());
1019                 // Fall through - ari will be null and we will continue...
1020             }
1021         } else {
1022             logger.error("Configuration for authRefs does not match schema structure: "
1023                     + arci.pathEls.toString());
1024         }
1025
1026         if (ari != null) {
1027             authRefInfoList.add(ari); //FIXME: REM - This is dead code.  'ari' is never touched after being initalized to null.  Why?
1028         }
1029
1030         return authRefInfoList;
1031     }
1032
1033     private static void addARIifMatches(
1034             String refNameToMatch,
1035             boolean matchBaseOnly,
1036             AuthRefConfigInfo arci,
1037             Property prop,
1038             List<AuthRefInfo> authRefInfoList) {
1039         // Need to either match a passed refName 
1040         // OR have no refName to match but be non-empty
1041         try {
1042             String value = (String) prop.getValue();
1043             if (((refNameToMatch != null) && 
1044                                 (matchBaseOnly?
1045                                         (value!=null && value.startsWith(refNameToMatch))
1046                                         :refNameToMatch.equals(value)))
1047                     || ((refNameToMatch == null) && Tools.notBlank(value))) {
1048                 // Found a match
1049                 logger.debug("Found a match on property: " + prop.getPath() + " with value: [" + value + "]");
1050                 AuthRefInfo ari = new AuthRefInfo(arci, prop);
1051                 authRefInfoList.add(ari);
1052             }
1053         } catch (PropertyException pe) {
1054             logger.debug("PropertyException on: " + prop.getPath() + pe.getLocalizedMessage());
1055         }
1056     }
1057     
1058     public static String buildWhereForAuthByName(String authorityCommonSchemaName, String name) {
1059         return authorityCommonSchemaName
1060                 + ":" + AuthorityJAXBSchema.SHORT_IDENTIFIER
1061                 + "='" + name + "'";
1062     }
1063
1064     /**
1065      * Build an NXQL query for finding an item by its short ID
1066      * 
1067      * @param authorityItemCommonSchemaName
1068      * @param shortId
1069      * @param parentcsid
1070      * @return
1071      */
1072     public static String buildWhereForAuthItemByName(String authorityItemCommonSchemaName, String shortId, String parentcsid) {
1073         String result = null;
1074         
1075         result = String.format("%s:%s='%s'", authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER, shortId);
1076         //
1077         // Technically, we don't need the parent CSID since the short ID is unique so it can be null
1078         //
1079         if (parentcsid != null) {
1080                 result = String.format("%s AND %s:%s='%s'",
1081                                 result, authorityItemCommonSchemaName, AuthorityItemJAXBSchema.IN_AUTHORITY, parentcsid);
1082         }
1083         
1084         return result;
1085     }    
1086
1087     /*
1088      * Identifies whether the refName was found in the supplied field. If passed
1089      * a new RefName, will set that into fields in which the old one was found.
1090      *
1091      * Only works for: * Scalar fields * Repeatable scalar fields (aka
1092      * multi-valued fields)
1093      *
1094      * Does not work for: * Structured fields (complexTypes) * Repeatable
1095      * structured fields (repeatable complexTypes) private static int
1096      * refNameFoundInField(String oldRefName, Property fieldValue, String
1097      * newRefName) { int nFound = 0; if (fieldValue instanceof List) {
1098      * List<Property> fieldValueList = (List) fieldValue; for (Property
1099      * listItemValue : fieldValueList) { try { if ((listItemValue instanceof
1100      * StringProperty) &&
1101      * oldRefName.equalsIgnoreCase((String)listItemValue.getValue())) {
1102      * nFound++; if(newRefName!=null) { fieldValue.setValue(newRefName); } else
1103      * { // We cannot quit after the first, if we are replacing values. // If we
1104      * are just looking (not replacing), finding one is enough. break; } } }
1105      * catch( PropertyException pe ) {} } } else { try { if ((fieldValue
1106      * instanceof StringProperty) &&
1107      * oldRefName.equalsIgnoreCase((String)fieldValue.getValue())) { nFound++;
1108      * if(newRefName!=null) { fieldValue.setValue(newRefName); } } } catch(
1109      * PropertyException pe ) {} } return nFound; }
1110      */
1111 }