]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
37060f9bc906191b7105b5701856295ebdc4252c
[tmp/jakarta-migration.git] /
1 /**
2  *  This document is a part of the source code and related artifacts
3  *  for CollectionSpace, an open source collections management system
4  *  for museums and related institutions:
5
6  *  http://www.collectionspace.org
7  *  http://wiki.collectionspace.org
8
9  *  Copyright 2009 University of California at Berkeley
10
11  *  Licensed under the Educational Community License (ECL), Version 2.0.
12  *  You may not use this file except in compliance with this License.
13
14  *  You may obtain a copy of the ECL 2.0 License at
15
16  *  https://source.collectionspace.org/collection-space/LICENSE.txt
17
18  *  Unless required by applicable law or agreed to in writing, software
19  *  distributed under the License is distributed on an "AS IS" BASIS,
20  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21  *  See the License for the specific language governing permissions and
22  *  limitations under the License.
23  */
24 package org.collectionspace.services.common.vocabulary.nuxeo;
25
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.Map;
29
30 import javax.ws.rs.core.Response;
31
32 import org.collectionspace.services.client.AbstractCommonListUtils;
33 import org.collectionspace.services.client.AuthorityClient;
34 import org.collectionspace.services.client.CollectionSpaceClient;
35 import org.collectionspace.services.client.PayloadInputPart;
36 import org.collectionspace.services.client.VocabularyClient;
37 import org.collectionspace.services.client.PoxPayloadIn;
38 import org.collectionspace.services.client.PoxPayloadOut;
39 import org.collectionspace.services.client.workflow.WorkflowClient;
40 import org.collectionspace.services.common.ResourceMap;
41 import org.collectionspace.services.common.XmlTools;
42 import org.collectionspace.services.common.api.RefName;
43 import org.collectionspace.services.common.api.RefName.Authority;
44 import org.collectionspace.services.common.api.RefNameUtils;
45 import org.collectionspace.services.common.api.RefNameUtils.AuthorityInfo;
46 import org.collectionspace.services.common.api.RefNameUtils.AuthorityTermInfo;
47 import org.collectionspace.services.common.api.Tools;
48 import org.collectionspace.services.common.context.ServiceContext;
49 import org.collectionspace.services.common.document.DocumentException;
50 import org.collectionspace.services.common.document.DocumentHandler;
51 import org.collectionspace.services.common.document.DocumentNotFoundException;
52 import org.collectionspace.services.common.document.DocumentReferenceException;
53 import org.collectionspace.services.common.document.DocumentWrapper;
54 import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema;
55 import org.collectionspace.services.common.vocabulary.AuthorityJAXBSchema;
56 import org.collectionspace.services.common.vocabulary.AuthorityResource;
57 import org.collectionspace.services.common.vocabulary.AuthorityServiceUtils;
58 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthorityItemSpecifier;
59 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.Specifier;
60 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.SpecifierForm;
61 import org.collectionspace.services.config.service.ObjectPartType;
62 import org.collectionspace.services.jaxb.AbstractCommonList;
63 import org.collectionspace.services.jaxb.AbstractCommonList.ListItem;
64 import org.collectionspace.services.lifecycle.TransitionDef;
65 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentModelHandler;
66 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
67 import org.collectionspace.services.nuxeo.client.java.RepositoryClientImpl;
68 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
69 import org.dom4j.Document;
70 import org.dom4j.Element;
71 import org.nuxeo.ecm.core.api.ClientException;
72 import org.nuxeo.ecm.core.api.DocumentModel;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
75
76 /**
77  * AuthorityDocumentModelHandler
78  *
79  * $LastChangedRevision: $
80  * $LastChangedDate: $
81  */
82 public abstract class AuthorityDocumentModelHandler<AuthCommon>
83         extends NuxeoDocumentModelHandler<AuthCommon> {
84     
85         private final Logger logger = LoggerFactory.getLogger(AuthorityDocumentModelHandler.class);     
86     
87         protected String authorityCommonSchemaName;
88     protected String authorityItemCommonSchemaName;
89     protected boolean shouldUpdateRevNumber = true; // default to updating the revision number
90
91     public AuthorityDocumentModelHandler(String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
92         this.authorityCommonSchemaName = authorityCommonSchemaName;
93         this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
94     }
95     
96     public void setShouldUpdateRevNumber(boolean flag) {
97         this.shouldUpdateRevNumber = flag;
98     }
99     
100     public boolean getShouldUpdateRevNumber() {
101         return this.shouldUpdateRevNumber;
102     }
103     
104     /**
105      * The entity type expected from the JAX-RS Response object
106      */
107     public Class<String> getEntityResponseType() {
108         return String.class;
109     }
110     
111     @Override
112     public void prepareSync() throws Exception {
113         this.setShouldUpdateRevNumber(AuthorityServiceUtils.DONT_UPDATE_REV);  // Never update rev nums on sync operations
114     }
115
116     protected PayloadInputPart extractPart(Response res, String partLabel)
117             throws Exception {
118             PoxPayloadIn input = new PoxPayloadIn((String)res.readEntity(getEntityResponseType()));
119             PayloadInputPart payloadInputPart = input.getPart(partLabel);
120             if (payloadInputPart == null) {
121                 logger.error("Part " + partLabel + " was unexpectedly null.");
122             }
123             return payloadInputPart;
124     }
125     
126     @Override
127     public boolean handleSync(DocumentWrapper<Object> wrapDoc) throws Exception {
128         boolean result = false;
129         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
130         Specifier specifier = (Specifier) wrapDoc.getWrappedObject();
131         //
132         // Get the rev number of the authority so we can compare with rev number of shared authority
133         //
134         DocumentModel docModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), authorityCommonSchemaName, specifier);
135         Long localRev = (Long) NuxeoUtils.getProperyValue(docModel, AuthorityJAXBSchema.REV);
136         String shortId = (String) NuxeoUtils.getProperyValue(docModel, AuthorityJAXBSchema.SHORT_IDENTIFIER);
137         //
138         // Using the short ID of the local authority, create a URN specifier to retrieve the SAS authority
139         //
140         Specifier sasSpecifier = new Specifier(SpecifierForm.URN_NAME, shortId);
141         PoxPayloadIn sasPayloadIn = AuthorityServiceUtils.requestPayloadIn(ctx, sasSpecifier, getEntityResponseType());
142         //
143         // If the authority on the SAS is newer, synch all the items and then the authority record as well
144         //
145         //
146         Long sasRev = getRevision(sasPayloadIn);
147         if (sasRev > localRev) {
148                 //
149                 // First, sync all the authority items
150                 //
151                 syncAllItems(ctx, sasSpecifier);
152                 //
153                 // Next, sync the authority resource/record itself
154                 //
155                 AuthorityResource authorityResource = (AuthorityResource) ctx.getResource();
156                 ctx.setProperty(AuthorityServiceUtils.SHOULD_UPDATE_REV_PROPERTY, AuthorityServiceUtils.DONT_UPDATE_REV); // Don't update the rev number, use the rev number for the SAS instance instead
157                 PoxPayloadOut payloadOut = authorityResource.update(ctx, ctx.getResourceMap(), ctx.getUriInfo(), docModel.getName(), 
158                                 sasPayloadIn);
159                 if (payloadOut != null) {
160                         ctx.setOutput(payloadOut);
161                         result = true;
162                 }
163         }
164         
165         return result;
166     }
167     
168     /*
169      * Get the list of authority items from the remote shared authority server (SAS) and try
170      * to synchronize them with the local items.  If items exist on the remote but not the local, we'll create them.
171      */
172     protected int syncAllItems(ServiceContext ctx, Specifier sasAuthoritySpecifier) throws Exception {
173         int result = -1;
174         int created = 0;
175         int synched = 0;
176         int alreadySynched = 0;
177         int deprecated = 0;
178         int totalItemsProcessed = 0;
179         ArrayList<String> itemsInRemoteAuthority = new ArrayList<String>();
180         //
181         // Iterate over the list of items/terms in the remote authority
182         //
183         PoxPayloadIn sasPayloadInItemList = requestPayloadInItemList(ctx, sasAuthoritySpecifier);
184         List<Element> itemList = getItemList(sasPayloadInItemList);
185         if (itemList != null) {
186                 for (Element e:itemList) {
187                         String remoteRefName = XmlTools.getElementValue(e, "refName");
188                         itemsInRemoteAuthority.add(remoteRefName);
189                         long status = syncRemoteItemWithLocalItem(ctx, remoteRefName);
190                         if (status == 1) {
191                                 created++;
192                         } else if (status == 0) {
193                                 synched++;
194                         } else {
195                                 alreadySynched++;
196                         }
197                         totalItemsProcessed++;
198                 }
199         }
200         //
201         // Now see if we need to deprecate or delete items that have been hard-deleted from the SAS but still exist
202         // locally.  Subtract (remove) the list of remote items from the list of local items to determine which
203         // of the remote items have been hard deleted.
204         //
205         ArrayList<String> itemsInLocalAuthority = getItemsInLocalAuthority(ctx, sasAuthoritySpecifier);
206         if (itemsInLocalAuthority.removeAll(itemsInRemoteAuthority) == true) {
207                 ArrayList<String> remainingItems = itemsInLocalAuthority; // now a subset of local items
208                 //
209                 // We now need to either hard-deleted or deprecate the remaining authorities
210                 //
211                 long processed = deleteOrDeprecateItems(ctx, remainingItems);
212                 if (processed != remainingItems.size()) {
213                         throw new Exception("Encountered unexpected exception trying to delete or deprecated authority items during synchronization.");
214                 }
215         }
216
217         
218         logger.info(String.format("Total number of items processed during sync: %d", totalItemsProcessed));
219         logger.info(String.format("Number of items synchronized: %d", synched));
220         logger.info(String.format("Number of items created during sync: %d", created));
221         logger.info(String.format("Number not needing synchronization: %d", alreadySynched));
222
223         return result;
224     }
225
226     /**
227      * 
228      * @param ctx
229      * @param refNameList
230      * @return
231      * @throws Exception
232      */
233     private long deleteOrDeprecateItems(ServiceContext ctx, ArrayList<String> refNameList) throws Exception {
234         long result = 0;
235         
236         ArrayList<String> failureList = new ArrayList<String>();
237         for (String refName:refNameList) {
238                 AuthorityTermInfo itemInfo = RefNameUtils.parseAuthorityTermInfo(refName);
239                 AuthorityResource authorityResource = (AuthorityResource) ctx.getResource();
240                 try {
241                         authorityResource.deleteAuthorityItem(ctx, itemInfo.inAuthority.csid, itemInfo.csid);
242                         result++;
243                 } catch (DocumentReferenceException de) {
244                         logger.info(String.format("Authority item '%s' has existing references and cannot be removed during sync.",
245                                         refName), de);
246                         boolean marked = AuthorityServiceUtils.markAuthorityItemAsDeprecated(ctx, authorityItemCommonSchemaName,
247                                         itemInfo.csid);
248                         if (marked == true) {
249                                 result++;
250                         }
251                 } catch (Exception e) {
252                         logger.warn(String.format("Unable to delete authority item '%s'", refName), e);
253                         throw e;
254                 }
255         }
256
257         if (logger.isWarnEnabled() == true) {
258                 if (result != refNameList.size()) {
259                         logger.warn(String.format("Unable to delete or deprecate some authority items during synchronization with SAS.  Deleted or deprecated %d of %d.  See the services log file for details.",
260                                         result, refNameList.size()));
261                 }
262         }
263         
264         return result;
265     }
266     
267     /**
268      * Gets the list of SAS related items in the local authority.  We exlude items with the "proposed" flags because
269      * we want a list with only SAS created items.
270      * 
271      * We need to add pagination support to this call!!!
272      * 
273      * @param ctx
274      * @param specifier
275      * @return
276      * @throws Exception
277      */
278     private ArrayList<String> getItemsInLocalAuthority(ServiceContext ctx, Specifier specifier) throws Exception {
279         ArrayList<String> result = new ArrayList<String>();
280         
281         ResourceMap resourceMap = ctx.getResourceMap();
282         String resourceName = ctx.getClient().getServiceName();
283         AuthorityResource authorityResource = (AuthorityResource) resourceMap.get(resourceName);
284         AbstractCommonList acl = authorityResource.getAuthorityItemList(ctx, specifier.value, ctx.getUriInfo());
285         List<ListItem> listItemList = acl.getListItem();
286         for (ListItem listItem:listItemList) {
287                 Boolean proposed = getBooleanValue(listItem, AuthorityItemJAXBSchema.PROPOSED);
288                 if (proposed == false) { // exclude "proposed" (i.e., local-only items)
289                         result.add(AbstractCommonListUtils.ListItemGetElementValue(listItem, AuthorityItemJAXBSchema.REF_NAME));
290                 }
291         }
292         
293         return result;
294     }
295     
296     private Boolean getBooleanValue(ListItem listItem, String name) {
297         Boolean result = null;
298         
299                 String value = AbstractCommonListUtils.ListItemGetElementValue(listItem, name);
300                 if (value != null) {
301                         result = Boolean.valueOf(value);
302                 }
303                 
304                 return result;
305     }
306     
307     private String getStringValue(ListItem listItem, String name) {
308         return AbstractCommonListUtils.ListItemGetElementValue(listItem, AuthorityItemJAXBSchema.REF_NAME);
309     }
310     
311     /**
312      * This is a sync method.
313      * @param ctx
314      * @param parentIdentifier - Must be in short-id-refname form -i.e., urn:cspace:name(shortid)
315      * @param itemIdentifier   - Must be in short-id-refname form -i.e., urn:cspace:name(shortid)
316      * @throws Exception 
317      */
318     protected void createLocalItem(ServiceContext ctx, String parentIdentifier, String itemIdentifier) throws Exception {
319         //
320         // Create a URN short ID specifier for the getting a copy of the remote authority item
321         //
322         Specifier authoritySpecifier = Specifier.getSpecifier(parentIdentifier);
323         Specifier itemSpecifier = Specifier.getSpecifier(itemIdentifier);
324         AuthorityItemSpecifier sasAuthorityItemSpecifier = new AuthorityItemSpecifier(authoritySpecifier, itemSpecifier);
325         //
326         // Get the remote payload
327         //
328         PoxPayloadIn sasPayloadIn = AuthorityServiceUtils.requestPayloadIn(sasAuthorityItemSpecifier, 
329                         ctx.getServiceName(), getEntityResponseType());
330         //
331         // Using the payload from the remote server, create a local copy of the item
332         //
333         AuthorityResource authorityResource = (AuthorityResource) ctx.getResource();
334         Response response = authorityResource.createAuthorityItemWithParentContext(ctx, authoritySpecifier.getURNValue(),
335                         sasPayloadIn, AuthorityServiceUtils.DONT_UPDATE_REV, AuthorityServiceUtils.NOT_PROPOSED);
336         //
337         // Check the response for successful POST result
338         //
339         if (response.getStatus() != Response.Status.CREATED.getStatusCode()) {
340                 throw new DocumentException(String.format("Could not create new authority item '%s' during synchronization of the '%s' authority.",
341                                 itemIdentifier, parentIdentifier));
342         }
343         //
344         // Since we're creating an item that was sourced from the SAS, we need to lock it.
345         //
346         authorityResource.updateItemWorkflowWithTransition(ctx, parentIdentifier, itemIdentifier, 
347                         WorkflowClient.WORKFLOWTRANSITION_LOCK, AuthorityServiceUtils.DONT_UPDATE_REV);
348         }
349     
350     /**
351      * Try to synchronize a remote item (using its refName) with a local item.  If the local doesn't yet
352      * exist, we'll create it.
353      * Result values:
354      *  -1 = sync not needed; i.e., already in sync
355      *   0 = sync succeeded
356      *   1 = local item was missing so we created it
357      * @param ctx
358      * @param refName
359      * @return
360      * @throws Exception
361      */
362     protected long syncRemoteItemWithLocalItem(ServiceContext ctx, String itemRefName) throws Exception {
363         long result = -1;
364         //
365         // Using the item refname (with no local CSID), create specifiers that we'll use to find the local versions
366         //
367         AuthorityTermInfo authorityTermInfo = RefNameUtils.parseAuthorityTermInfo(itemRefName);
368         String parentIdentifier = Specifier.createShortIdURNValue(authorityTermInfo.inAuthority.name);
369         String itemIdentifier = Specifier.createShortIdURNValue(authorityTermInfo.name);
370         //
371         // We'll use the Authority JAX-RS resource to peform sync operations (creates and updates)
372         //
373         AuthorityResource authorityResource = (AuthorityResource) ctx.getResource();            
374         PoxPayloadOut localItemPayloadOut;
375         try {
376                 localItemPayloadOut = authorityResource.getAuthorityItemWithExistingContext(ctx, parentIdentifier, itemIdentifier);
377         } catch (DocumentNotFoundException dnf) {
378                 //
379                 // Document not found, means we need to create an item/term that exists only on the SAS
380                 //
381                 logger.info(String.format("Remote item with refname='%s' doesn't exist locally, so we'll create it.", itemRefName));
382                 createLocalItem(ctx, parentIdentifier, itemIdentifier);
383                 return 1; // exit with status of 1 means we created a new authority item
384         }
385         //
386         // If we get here, we know the item exists both locally and remotely, so we need to synchronize them.
387         //
388         //
389         try {
390                 PoxPayloadOut theUpdate = authorityResource.synchronizeItemWithExistingContext(ctx, parentIdentifier, itemIdentifier);
391                 if (theUpdate != null) {
392                         result = 0; // means we needed to sync this item with SAS
393                         logger.debug(String.format("Sync'd authority item parent='%s' id='%s with SAS.  Updated payload is: \n%s",
394                                         parentIdentifier, itemIdentifier, theUpdate.getXmlPayload()));
395                 }
396         } catch (DocumentReferenceException de) { // Exception for items that still have records/resource referencing them.
397                 result = -1;
398                 logger.error(String.format("Could not sync authority item = '%s' because it has existing records referencing it.",
399                                 itemIdentifier));
400         }
401         
402         return result; // -1 = no sync needed/possible, 0 = sync'd, 1 = created new item
403     }
404         
405     private PoxPayloadIn requestPayloadInItemList(ServiceContext ctx, Specifier specifier) throws Exception {
406         PoxPayloadIn result = null;
407         
408         AuthorityClient client = (AuthorityClient) ctx.getClient();
409         Response res = client.readItemList(specifier.getURNValue(),
410                         null,   // partial term string
411                         null    // keyword string
412                         );
413         try {
414                 int statusCode = res.getStatus();
415         
416                 // Check the status code of the response: does it match
417                 // the expected response(s)?
418                 if (logger.isDebugEnabled()) {
419                     logger.debug(client.getClass().getCanonicalName() + ": status = " + statusCode);
420                 }
421                 
422             result = new PoxPayloadIn((String)res.readEntity(getEntityResponseType())); // Get the entire response!             
423         } finally {
424                 res.close();
425         }
426         
427         return result;
428     }
429     
430
431     /*
432      * Non standard injection of CSID into common part, since caller may access through
433      * shortId, and not know the CSID.
434      * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#extractPart(org.nuxeo.ecm.core.api.DocumentModel, java.lang.String, org.collectionspace.services.common.service.ObjectPartType)
435      */
436     @Override
437     protected Map<String, Object> extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
438             throws Exception {
439         Map<String, Object> unQObjectProperties = super.extractPart(docModel, schema, partMeta);
440
441         // Add the CSID to the common part
442         if (partMeta.getLabel().equalsIgnoreCase(authorityCommonSchemaName)) {
443             String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
444             unQObjectProperties.put("csid", csid);
445         }
446
447         return unQObjectProperties;
448     }
449     
450     public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
451         super.fillAllParts(wrapDoc, action);
452         //
453         // Update the record's revision number on both CREATE and UPDATE actions, but not on SYNC
454         //
455         if (this.getShouldUpdateRevNumber() == true) { // We won't update rev numbers on synchronization with SAS
456                 updateRevNumbers(wrapDoc);
457         }
458     }
459     
460     protected void updateRevNumbers(DocumentWrapper<DocumentModel> wrapDoc) {
461         DocumentModel documentModel = wrapDoc.getWrappedObject();
462         Long rev = (Long)documentModel.getProperty(authorityCommonSchemaName, AuthorityJAXBSchema.REV);
463         if (rev == null) {
464                 rev = (long)0;
465         } else {
466                 rev++;
467         }
468         documentModel.setProperty(authorityCommonSchemaName, AuthorityJAXBSchema.REV, rev);
469     }
470     
471     /*
472      * We consider workflow state changes as changes that should bump the revision number
473      * (non-Javadoc)
474      * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#handleWorkflowTransition(org.collectionspace.services.common.document.DocumentWrapper, org.collectionspace.services.lifecycle.TransitionDef)
475      */
476     @Override
477     public void handleWorkflowTransition(ServiceContext ctx, DocumentWrapper<DocumentModel> wrapDoc, TransitionDef transitionDef) throws Exception {
478         // Update the revision number
479         updateRevNumbers(wrapDoc);
480     }
481     
482     @Override
483     public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
484         super.handleCreate(wrapDoc);
485         // CSPACE-3178:
486         // Uncomment once debugged and App layer is read to integrate
487         // Experimenting with this uncommented now ...
488         handleDisplayNameAsShortIdentifier(wrapDoc.getWrappedObject(), authorityCommonSchemaName);
489         updateRefnameForAuthority(wrapDoc, authorityCommonSchemaName);//CSPACE-3178
490     }
491     
492     protected String buildWhereForShortId(String name) {
493         return authorityCommonSchemaName
494                 + ":" + AuthorityJAXBSchema.SHORT_IDENTIFIER
495                 + "='" + name + "'";
496     }
497     
498     private boolean isUnique(DocumentModel docModel, String schemaName) throws DocumentException {
499         return true;
500     }
501     
502     private boolean temp_isUnique(DocumentModel docModel, String schemaName) throws DocumentException {
503         boolean result = true;
504         
505         ServiceContext ctx = this.getServiceContext();
506         String shortIdentifier = (String) docModel.getProperty(schemaName, AuthorityJAXBSchema.SHORT_IDENTIFIER);
507         String nxqlWhereClause = buildWhereForShortId(shortIdentifier);
508         try {
509                         DocumentWrapper<DocumentModel> searchResultWrapper = getRepositoryClient(ctx).findDoc(ctx, nxqlWhereClause);
510                         if (searchResultWrapper != null) {
511                                 result = false;
512                                 if (logger.isInfoEnabled() == true) {
513                                         DocumentModel searchResult = searchResultWrapper.getWrappedObject();
514                                         String debugMsg = String.format("Could not create a new authority with a short identifier of '%s', because one already exists with the same short identifer: CSID = '%s'",
515                                                         shortIdentifier, searchResult.getName());
516                                         logger.trace(debugMsg);
517                                 }
518                         }
519                 } catch (DocumentNotFoundException e) {
520                         // Not a problem, just means we couldn't find another authority with that short ID
521                 }
522         
523         return result;
524     }
525
526     /**
527      * If no short identifier was provided in the input payload,
528      * generate a short identifier from the display name. Either way though,
529      * the short identifier needs to be unique.
530      */
531     private void handleDisplayNameAsShortIdentifier(DocumentModel docModel, String schemaName) throws Exception {
532         String shortIdentifier = (String) docModel.getProperty(schemaName, AuthorityJAXBSchema.SHORT_IDENTIFIER);
533         String displayName = (String) docModel.getProperty(schemaName, AuthorityJAXBSchema.DISPLAY_NAME);
534         String shortDisplayName = "";
535         String generateShortIdentifier = null;
536         if (Tools.isEmpty(shortIdentifier)) {
537                 generateShortIdentifier = AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(displayName, shortDisplayName);
538             docModel.setProperty(schemaName, AuthorityJAXBSchema.SHORT_IDENTIFIER, shortIdentifier);
539         }
540         
541         if (isUnique(docModel, schemaName) == false) {
542                 String shortId = generateShortIdentifier == null ? shortIdentifier : generateShortIdentifier;
543                 String errMsgVerb = generateShortIdentifier == null ? "supplied" : "generated";
544                 String errMsg = String.format("The %s short identifier '%s' was not unique, so the new authority could not be created.",
545                                 errMsgVerb, shortId);
546                 throw new DocumentException(errMsg);
547         }
548     }
549  
550     /**
551      * Generate a refName for the authority from the short identifier
552      * and display name.
553      * 
554      * All refNames for authorities are generated.  If a client supplies
555      * a refName, it will be overwritten during create (per this method) 
556      * or discarded during update (per filterReadOnlyPropertiesForPart).
557      * 
558      * @see #filterReadOnlyPropertiesForPart(Map<String, Object>, org.collectionspace.services.common.service.ObjectPartType)
559      * 
560      */
561     protected void updateRefnameForAuthority(DocumentWrapper<DocumentModel> wrapDoc, String schemaName) throws Exception {
562         DocumentModel docModel = wrapDoc.getWrappedObject();
563         RefName.Authority authority = (Authority) getRefName(getServiceContext(), docModel);
564         String refName = authority.toString();
565         docModel.setProperty(schemaName, AuthorityJAXBSchema.REF_NAME, refName);
566     }
567     
568     @Override
569     public RefName.RefNameInterface getRefName(ServiceContext ctx,
570                 DocumentModel docModel) {
571         RefName.RefNameInterface refname = null;
572
573         try {
574                 String shortIdentifier = (String) docModel.getProperty(authorityCommonSchemaName, AuthorityJAXBSchema.SHORT_IDENTIFIER);
575                 String displayName = (String) docModel.getProperty(authorityCommonSchemaName, AuthorityJAXBSchema.DISPLAY_NAME);
576                 RefName.Authority authority = RefName.Authority.buildAuthority(ctx.getTenantName(),
577                         ctx.getServiceName(),
578                         null,   // Only use shortId form!!!
579                         shortIdentifier,
580                         displayName);
581                 refname = authority;
582         } catch (Exception e) {
583                 logger.error(e.getMessage(), e);
584         }
585         
586         return refname;
587     }
588     
589     @Override
590     protected String getRefnameDisplayName(DocumentWrapper<DocumentModel> docWrapper) {
591         String result = null;
592         
593         DocumentModel docModel = docWrapper.getWrappedObject();
594         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
595         RefName.Authority refname = (RefName.Authority)getRefName(ctx, docModel);
596         result = refname.getDisplayName();
597         
598         return result;
599     }    
600     
601     public String getShortIdentifier(ServiceContext ctx, String authCSID, String schemaName) throws Exception {
602         String shortIdentifier = null;
603         CoreSessionInterface repoSession = null;
604         boolean releaseSession = false;
605
606         RepositoryClientImpl nuxeoRepoClient = (RepositoryClientImpl)this.getRepositoryClient(ctx);
607         try {
608                 repoSession = nuxeoRepoClient.getRepositorySession(ctx);
609             DocumentWrapper<DocumentModel> wrapDoc = nuxeoRepoClient.getDocFromCsid(ctx, repoSession, authCSID);
610             DocumentModel docModel = wrapDoc.getWrappedObject();
611             if (docModel == null) {
612                 throw new DocumentNotFoundException(String.format("Could not find authority resource with CSID='%s'.", authCSID));
613             }
614             shortIdentifier = (String) docModel.getProperty(schemaName, AuthorityJAXBSchema.SHORT_IDENTIFIER);
615         } catch (ClientException ce) {
616             throw new RuntimeException("AuthorityDocHandler Internal Error: cannot get shortId!", ce);
617         } finally {
618                 if (repoSession != null) {
619                         nuxeoRepoClient.releaseRepositorySession(ctx, repoSession);
620                 }
621         }
622         
623         return shortIdentifier;
624     }
625
626     /**
627      * Filters out selected values supplied in an update request.
628      * 
629      * @param objectProps the properties filtered out from the update payload
630      * @param partMeta metadata for the object to fill
631      */
632     @Override
633     public void filterReadOnlyPropertiesForPart(
634             Map<String, Object> objectProps, ObjectPartType partMeta) {
635         super.filterReadOnlyPropertiesForPart(objectProps, partMeta);
636         String commonPartLabel = getServiceContext().getCommonPartLabel();
637         if (partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) {
638             objectProps.remove(AuthorityJAXBSchema.CSID);
639             objectProps.remove(AuthorityJAXBSchema.SHORT_IDENTIFIER);
640             objectProps.remove(AuthorityJAXBSchema.REF_NAME);
641         }
642     }    
643 }