]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
bab68fcd9ec5ee7d262b22bf71762a61d7335cdc
[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;
25
26 import java.util.List;
27 import java.util.Map;
28
29 import javax.ws.rs.Consumes;
30 import javax.ws.rs.DELETE;
31 import javax.ws.rs.GET;
32 import javax.ws.rs.POST;
33 import javax.ws.rs.PUT;
34 import javax.ws.rs.Path;
35 import javax.ws.rs.PathParam;
36 import javax.ws.rs.Produces;
37 import javax.ws.rs.core.Context;
38 import javax.ws.rs.core.MultivaluedMap;
39 import javax.ws.rs.core.Request;
40 import javax.ws.rs.core.Response;
41 import javax.ws.rs.core.UriBuilder;
42 import javax.ws.rs.core.UriInfo;
43
44 import org.collectionspace.services.client.IClientQueryParams;
45 import org.collectionspace.services.client.IQueryManager;
46 import org.collectionspace.services.client.PoxPayloadIn;
47 import org.collectionspace.services.client.PoxPayloadOut;
48 import org.collectionspace.services.client.workflow.WorkflowClient;
49 import org.collectionspace.services.common.CSWebApplicationException;
50 import org.collectionspace.services.common.NuxeoBasedResource;
51 import org.collectionspace.services.common.ResourceMap;
52 import org.collectionspace.services.common.ServiceMain;
53 import org.collectionspace.services.common.ServiceMessages;
54 import org.collectionspace.services.common.StoredValuesUriTemplate;
55 import org.collectionspace.services.common.UriTemplateFactory;
56 import org.collectionspace.services.common.UriTemplateRegistry;
57 import org.collectionspace.services.common.UriTemplateRegistryKey;
58 import org.collectionspace.services.common.api.RefName;
59 import org.collectionspace.services.common.api.Tools;
60 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
61 import org.collectionspace.services.common.authorityref.AuthorityRefList;
62 import org.collectionspace.services.common.context.JaxRsContext;
63 import org.collectionspace.services.common.context.MultipartServiceContext;
64 import org.collectionspace.services.common.context.RemoteServiceContext;
65 import org.collectionspace.services.common.context.ServiceBindingUtils;
66 import org.collectionspace.services.common.context.ServiceContext;
67 import org.collectionspace.services.common.document.DocumentException;
68 import org.collectionspace.services.common.document.DocumentFilter;
69 import org.collectionspace.services.common.document.DocumentHandler;
70 import org.collectionspace.services.common.document.DocumentNotFoundException;
71 import org.collectionspace.services.common.document.DocumentWrapper;
72 import org.collectionspace.services.common.document.Hierarchy;
73 import org.collectionspace.services.common.query.QueryManager;
74 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityDocumentModelHandler;
75 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityItemDocumentModelHandler;
76 import org.collectionspace.services.common.workflow.service.nuxeo.WorkflowDocumentModelHandler;
77 import org.collectionspace.services.config.ClientType;
78 import org.collectionspace.services.jaxb.AbstractCommonList;
79 import org.collectionspace.services.lifecycle.TransitionDef;
80 import org.collectionspace.services.nuxeo.client.java.DocumentModelHandler;
81 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
82 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentFilter;
83 import org.collectionspace.services.nuxeo.client.java.RepositoryClientImpl;
84 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
85 import org.collectionspace.services.workflow.WorkflowCommon;
86 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthorityItemSpecifier;
87 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.SpecifierForm;
88 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.Specifier;
89 import org.jboss.resteasy.util.HttpResponseCodes;
90 import org.nuxeo.ecm.core.api.DocumentModel;
91 import org.nuxeo.ecm.core.api.DocumentModelList;
92 import org.slf4j.Logger;
93 import org.slf4j.LoggerFactory;
94
95 /**
96  * The Class AuthorityResource.
97  */
98 /**
99  * @author pschmitz
100  *
101  * @param <AuthCommon>
102  * @param <AuthItemHandler>
103  */
104 /**
105  * @author pschmitz
106  *
107  * @param <AuthCommon>
108  * @param <AuthItemHandler>
109  */
110 @Consumes("application/xml")
111 @Produces("application/xml")
112 public abstract class AuthorityResource<AuthCommon, AuthItemHandler>
113         extends NuxeoBasedResource {
114         
115         final static String SEARCH_TYPE_TERMSTATUS = "ts";
116
117     protected Class<AuthCommon> authCommonClass;
118     protected Class<?> resourceClass;
119     protected String authorityCommonSchemaName;
120     protected String authorityItemCommonSchemaName;
121     final static ClientType CLIENT_TYPE = ServiceMain.getInstance().getClientType(); //FIXME: REM - 3 Why is this field needed?  I see no references to it.
122     final static String URN_PREFIX = "urn:cspace:";
123     final static int URN_PREFIX_LEN = URN_PREFIX.length();
124     final static String URN_PREFIX_NAME = "name(";
125     final static int URN_NAME_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_NAME.length();
126     final static String URN_PREFIX_ID = "id(";
127     final static int URN_ID_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_ID.length();
128     final static String FETCH_SHORT_ID = "_fetch_";
129     public final static String PARENT_WILDCARD = "_ALL_";
130         
131     final Logger logger = LoggerFactory.getLogger(AuthorityResource.class);
132
133     protected Specifier getSpecifier(String specifierIn, String method, String op) throws CSWebApplicationException {
134         if (logger.isDebugEnabled()) {
135             logger.debug("getSpecifier called by: " + method + " with specifier: " + specifierIn);
136         }
137         if (specifierIn != null) {
138             if (!specifierIn.startsWith(URN_PREFIX)) {
139                 // We'll assume it is a CSID and complain if it does not match
140                 return new Specifier(SpecifierForm.CSID, specifierIn);
141             } else {
142                 if (specifierIn.startsWith(URN_PREFIX_NAME, URN_PREFIX_LEN)) {
143                     int closeParen = specifierIn.indexOf(')', URN_NAME_PREFIX_LEN);
144                     if (closeParen >= 0) {
145                         return new Specifier(SpecifierForm.URN_NAME,
146                                 specifierIn.substring(URN_NAME_PREFIX_LEN, closeParen));
147                     }
148                 } else if (specifierIn.startsWith(URN_PREFIX_ID, URN_PREFIX_LEN)) {
149                     int closeParen = specifierIn.indexOf(')', URN_ID_PREFIX_LEN);
150                     if (closeParen >= 0) {
151                         return new Specifier(SpecifierForm.CSID,
152                                 specifierIn.substring(URN_ID_PREFIX_LEN, closeParen));
153                     }
154                 }
155             }
156         }
157         logger.error(method + ": bad or missing specifier!");
158         Response response = Response.status(Response.Status.BAD_REQUEST).entity(
159                 op + " failed on bad or missing Authority specifier").type(
160                 "text/plain").build();
161         throw new CSWebApplicationException(response);
162     }
163
164     /**
165      * Instantiates a new Authority resource.
166      */
167     public AuthorityResource(Class<AuthCommon> authCommonClass, Class<?> resourceClass,
168             String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
169         this.authCommonClass = authCommonClass;
170         this.resourceClass = resourceClass;
171         this.authorityCommonSchemaName = authorityCommonSchemaName;
172         this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
173     }
174
175     public abstract String getItemServiceName();
176     
177     public abstract String getItemTermInfoGroupXPathBase();
178
179     @Override
180     protected String getVersionString() {
181         return "$LastChangedRevision: 2617 $";
182     }
183
184     @Override
185     public Class<AuthCommon> getCommonPartClass() {
186         return authCommonClass;
187     }
188
189     /**
190      * Creates the item document handler.
191      * 
192      * @param ctx the ctx
193      * @param inAuthority the in vocabulary
194      * 
195      * @return the document handler
196      * 
197      * @throws Exception the exception
198      */
199     protected DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> createItemDocumentHandler(
200             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
201             String inAuthority, String parentShortIdentifier)
202             throws Exception {
203         String authorityRefNameBase;
204         AuthorityItemDocumentModelHandler<?> docHandler;
205
206         if (parentShortIdentifier == null) {
207             authorityRefNameBase = null;
208         } else {
209             ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx =
210                     createServiceContext(getServiceName());
211             if (parentShortIdentifier.equals(FETCH_SHORT_ID)) {
212                 // Get from parent document
213                 parentShortIdentifier = getAuthShortIdentifier(parentCtx, inAuthority);
214             }
215             authorityRefNameBase = buildAuthorityRefNameBase(parentCtx, parentShortIdentifier);
216         }
217
218         docHandler = (AuthorityItemDocumentModelHandler<?>) createDocumentHandler(ctx,
219                 ctx.getCommonPartLabel(getItemServiceName()),
220                 authCommonClass);
221         // FIXME - Richard and Aron think the following three lines should
222         // be in the constructor for the AuthorityItemDocumentModelHandler
223         // because all three are required fields.
224         docHandler.setInAuthority(inAuthority);
225         docHandler.setAuthorityRefNameBase(authorityRefNameBase);
226         docHandler.setItemTermInfoGroupXPathBase(getItemTermInfoGroupXPathBase());
227         return docHandler;
228     }
229
230     public String getAuthShortIdentifier(
231             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String authCSID)
232             throws DocumentNotFoundException, DocumentException {
233         String shortIdentifier = null;
234         try {
235             AuthorityDocumentModelHandler<?> handler =
236                     (AuthorityDocumentModelHandler<?>) createDocumentHandler(ctx);
237             shortIdentifier = handler.getShortIdentifier(authCSID, authorityCommonSchemaName);
238         } catch (Exception e) {
239             if (logger.isDebugEnabled()) {
240                 logger.debug("Caught exception ", e);
241             }
242             throw new DocumentException(e);
243         }
244         return shortIdentifier;
245     }
246
247     protected String buildAuthorityRefNameBase(
248             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String shortIdentifier) {
249         RefName.Authority authority = RefName.Authority.buildAuthority(ctx.getTenantName(),
250                 ctx.getServiceName(), 
251                 null,   // Only use shortId form!!!
252                 shortIdentifier, null);
253         return authority.toString();
254     }
255
256     public static class CsidAndShortIdentifier {
257         String CSID;
258         String shortIdentifier;
259     }
260
261         protected String lookupParentCSID(String parentspecifier, String method,
262                         String op, UriInfo uriInfo) throws Exception {
263                 CsidAndShortIdentifier tempResult = lookupParentCSIDAndShortIdentifer(null,
264                                 parentspecifier, method, op, uriInfo);
265                 return tempResult.CSID;
266         }
267
268     private CsidAndShortIdentifier lookupParentCSIDAndShortIdentifer(
269                 ServiceContext itemServiceCtx,
270                 String parentSpecifier,
271                 String method,
272                 String op,
273                 UriInfo uriInfo)
274             throws Exception {
275         CsidAndShortIdentifier result = new CsidAndShortIdentifier();
276         Specifier parentSpec = getSpecifier(parentSpecifier, method, op);
277         // Note that we have to create the service context for the Items, not the main service
278         String parentcsid;
279         String parentShortIdentifier;
280         if (parentSpec.form == SpecifierForm.CSID) {
281             parentShortIdentifier = null;
282             parentcsid = parentSpec.value;
283             // Uncomment when app layer is ready to integrate
284             // Uncommented since refNames are currently only generated if not present - ADR CSPACE-3178
285             parentShortIdentifier = FETCH_SHORT_ID;
286         } else {
287             parentShortIdentifier = parentSpec.value;
288             String whereClause = RefNameServiceUtils.buildWhereForAuthByName(authorityCommonSchemaName, parentSpec.value);
289             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getServiceName(), uriInfo);
290             CoreSessionInterface repoSession = null;
291             if (itemServiceCtx != null) {
292                  repoSession = (CoreSessionInterface) itemServiceCtx.getCurrentRepositorySession();  // We want to use the thread's current repo session
293             }
294             parentcsid = getRepositoryClient(ctx).findDocCSID(repoSession, ctx, whereClause); //FIXME: REM - If the parent has been soft-deleted, should we be looking for the item?
295         }
296         
297         result.CSID = parentcsid;
298         result.shortIdentifier = parentShortIdentifier;
299         return result;
300     }
301
302     public String lookupItemCSID(String itemspecifier, String parentcsid, String method, String op, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx)
303             throws DocumentException {
304         String itemcsid;
305         Specifier itemSpec = getSpecifier(itemspecifier, method, op);
306         if (itemSpec.form == SpecifierForm.CSID) {
307             itemcsid = itemSpec.value;
308         } else {
309             String itemWhereClause = RefNameServiceUtils.buildWhereForAuthItemByName(authorityItemCommonSchemaName, itemSpec.value, parentcsid);
310             itemcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, itemWhereClause); //FIXME: REM - Should we be looking for the 'wf_deleted' query param and filtering on it?
311         }
312         return itemcsid;
313     }
314
315     /*
316      * Generally, callers will first call RefName.AuthorityItem.parse with a refName, and then 
317      * use the returned item.inAuthority.resource and a resourceMap to get a service-specific
318      * Resource. They then call this method on that resource.
319      */
320     @Override
321         public DocumentModel getDocModelForAuthorityItem(CoreSessionInterface repoSession, RefName.AuthorityItem item) 
322                         throws Exception, DocumentNotFoundException {
323         if(item == null) {
324                 return null;
325         }
326         String whereClause = RefNameServiceUtils.buildWhereForAuthByName(authorityCommonSchemaName, item.getParentShortIdentifier());
327         // Ensure we have the right context.
328         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(item.inAuthority.resource);
329         
330         // HACK - this really must be moved to the doc handler, not here. No Nuxeo specific stuff here!
331         RepositoryClientImpl client = (RepositoryClientImpl)getRepositoryClient(ctx);
332         String parentcsid = client.findDocCSID(repoSession, ctx, whereClause);
333
334         String itemWhereClause = RefNameServiceUtils.buildWhereForAuthItemByName(authorityItemCommonSchemaName, item.getShortIdentifier(), parentcsid);
335         ctx = createServiceContext(getItemServiceName());
336         DocumentWrapper<DocumentModel> docWrapper = client.findDoc(repoSession, ctx, itemWhereClause);
337         DocumentModel docModel = docWrapper.getWrappedObject();
338         return docModel;
339     }
340
341
342     @POST
343     public Response createAuthority(String xmlPayload) {
344         //
345         // Requests to create new authorities come in on new threads. Unfortunately, we need to synchronize those threads on this block because, as of 8/27/2015, we can't seem to get Nuxeo
346         // transaction code to deal with a database level UNIQUE constraint violations on the 'shortidentifier' column of the vocabularies_common table.
347         // Therefore, to prevent having multiple authorities with the same shortid, we need to synchronize
348         // the code that creates new authorities.  The authority document model handler will first check for authorities with the same short id before
349         // trying to create a new authority.
350         //
351         synchronized(AuthorityResource.class) {
352                 try {
353                     PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
354                     ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
355                     DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
356                     String csid = getRepositoryClient(ctx).create(ctx, handler);
357                     UriBuilder path = UriBuilder.fromResource(resourceClass);
358                     path.path("" + csid);
359                     Response response = Response.created(path.build()).build();
360                     return response;
361                 } catch (Exception e) {
362                     throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
363                 }
364         }
365     }
366
367
368     /**
369      * Synchronizes the authority and its terms with a Shared Authority Server.
370      * 
371      * @param specifier either a CSID or one of the urn forms
372      * 
373      * @return the authority
374      */
375     @GET
376     @Path("{csid}/sync")
377     public byte[] synchronize(
378             @Context Request request,
379             @Context UriInfo ui,
380             @PathParam("csid") String csid) {
381         byte[] result;
382         boolean neededSync = false;
383         PoxPayloadOut payloadOut = null;
384         Specifier specifier;
385         
386         try {
387             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
388             AuthorityDocumentModelHandler handler = (AuthorityDocumentModelHandler)createDocumentHandler(ctx);
389             specifier = getSpecifier(csid, "getAuthority", "GET");
390             neededSync = getRepositoryClient(ctx).synchronize(ctx, specifier, handler);
391             payloadOut = ctx.getOutput();
392         } catch (Exception e) {
393             throw bigReThrow(e, ServiceMessages.SYNC_FAILED, csid);
394         }
395
396         //
397         // If a sync was needed and was successful, return a copy of the updated resource.  Acts like an UPDATE.
398         //
399         if (neededSync == true) {
400                 result = payloadOut.getBytes();
401         } else {
402                 result = String.format("Authority resource '%s' was already in sync with shared authority server.",
403                                 specifier.value).getBytes();
404                 Response response = Response.status(Response.Status.NOT_MODIFIED).entity(result).type("text/plain").build();
405             throw new CSWebApplicationException(response);
406         }
407         
408         return result;
409     }
410     
411     /**
412      * Gets the authority.
413      * 
414      * @param specifier either a CSID or one of the urn forms
415      * 
416      * @return the authority
417      */
418     @GET
419     @Path("{csid}")
420     @Override
421     public byte[] get(
422             @Context Request request,
423             @Context UriInfo ui,
424             @PathParam("csid") String specifier) {
425         PoxPayloadOut result = null;
426         try {
427             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
428             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
429
430             Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
431             if (spec.form == SpecifierForm.CSID) {
432                 if (logger.isDebugEnabled()) {
433                     logger.debug("getAuthority with csid=" + spec.value);
434                 }
435                 getRepositoryClient(ctx).get(ctx, spec.value, handler);
436             } else {
437                 String whereClause = RefNameServiceUtils.buildWhereForAuthByName(authorityCommonSchemaName, spec.value);
438                 DocumentFilter myFilter = new NuxeoDocumentFilter(whereClause, 0, 1);
439                 handler.setDocumentFilter(myFilter);
440                 getRepositoryClient(ctx).get(ctx, handler);
441             }
442             result = ctx.getOutput();
443
444         } catch (Exception e) {
445             throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
446         }
447
448         if (result == null) {
449             Response response = Response.status(Response.Status.NOT_FOUND).entity(
450                     "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type(
451                     "text/plain").build();
452             throw new CSWebApplicationException(response);
453         }
454
455         return result.getBytes();
456     }
457
458     /**
459      * Finds and populates the authority list.
460      * 
461      * @param ui the ui
462      * 
463      * @return the authority list
464      */
465     @GET
466     @Produces("application/xml")
467     public AbstractCommonList getAuthorityList(@Context UriInfo uriInfo) { //FIXME - REM 5/3/2012 - This is not reachable from the JAX-RS dispatcher.  Instead the equivalent method in ResourceBase is getting called.
468         AbstractCommonList result = null;
469         
470         try {
471             MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
472             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(uriInfo);
473             
474             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
475             DocumentFilter myFilter = handler.getDocumentFilter();
476             // Need to make the default sort order for authority items
477             // be on the displayName field
478             String sortBy = queryParams.getFirst(IClientQueryParams.ORDER_BY_PARAM);
479             if (sortBy == null || sortBy.isEmpty()) {
480                 String qualifiedDisplayNameField = authorityCommonSchemaName + ":"
481                         + AuthorityItemJAXBSchema.DISPLAY_NAME;
482                 myFilter.setOrderByClause(qualifiedDisplayNameField);
483             }
484             String nameQ = queryParams.getFirst("refName");
485             if (nameQ != null) {
486                 myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'");
487             }
488             getRepositoryClient(ctx).getFiltered(ctx, handler);
489             result = handler.getCommonPartList();
490         } catch (Exception e) {
491             throw bigReThrow(e, ServiceMessages.GET_FAILED);
492         }
493         
494         return result;
495     }
496     
497     /**
498      * Update authority.
499      *
500      * @param specifier the csid or id
501      *
502      * @return the multipart output
503      */
504     @PUT
505     @Path("{csid}")
506     public byte[] updateAuthority(
507             @PathParam("csid") String specifier,
508             String xmlPayload) {
509         PoxPayloadOut result = null;
510         try {
511             PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
512             Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
513             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
514             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
515             String csid;
516             if (spec.form == SpecifierForm.CSID) {
517                 csid = spec.value;
518             } else {
519                 String whereClause = RefNameServiceUtils.buildWhereForAuthByName(authorityCommonSchemaName, spec.value);
520                 csid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause);
521             }
522             getRepositoryClient(ctx).update(ctx, csid, handler);
523             result = ctx.getOutput();
524         } catch (Exception e) {
525             throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
526         }
527         return result.getBytes();
528     }
529
530     /**
531      * Delete authority.
532      * 
533      * @param csid the csid
534      * 
535      * @return the response
536      */
537     @Deprecated
538 //    @DELETE
539     @Path("{csid}")
540     public Response old_deleteAuthority(@PathParam("csid") String csid) {
541         if (logger.isDebugEnabled()) {
542             logger.debug("deleteAuthority with csid=" + csid);
543         }
544         try {
545             ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid");
546             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
547             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
548             getRepositoryClient(ctx).delete(ctx, csid, handler);
549             return Response.status(HttpResponseCodes.SC_OK).build();
550         } catch (Exception e) {
551             throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid);
552         }
553     }
554     
555     /**
556      * Delete authority
557      * 
558      * @param csid the csid or a URN specifier form -e.g., urn:cspace:name(OurMuseumPersonAuthority)
559      * 
560      * @return the response
561      */
562     @DELETE
563     @Path("{csid}")
564     public Response deleteAuthority(
565             @Context Request request,
566             @Context UriInfo ui,
567             @PathParam("csid") String specifier) {
568         if (logger.isDebugEnabled()) {
569             logger.debug("deleteAuthority with specifier=" + specifier);
570         }
571         
572         try {
573             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
574             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
575
576             Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
577             if (spec.form == SpecifierForm.CSID) {
578                 if (logger.isDebugEnabled()) {
579                     logger.debug("deleteAuthority with csid=" + spec.value);
580                 }
581                 ensureCSID(spec.value, ServiceMessages.DELETE_FAILED, "Authority.csid");
582                 getRepositoryClient(ctx).delete(ctx, spec.value, handler);
583             } else {
584                 if (logger.isDebugEnabled()) {
585                     logger.debug("deleteAuthority with specifier=" + spec.value);
586                 }               
587                 String whereClause = RefNameServiceUtils.buildWhereForAuthByName(authorityCommonSchemaName, spec.value);
588                 getRepositoryClient(ctx).deleteWithWhereClause(ctx, whereClause, handler);
589             }
590             
591             return Response.status(HttpResponseCodes.SC_OK).build();
592         } catch (Exception e) {
593             throw bigReThrow(e, ServiceMessages.DELETE_FAILED, specifier);
594         }
595     }
596     
597     protected Response createAuthorityItem(ServiceContext ctx, String parentspecifier) throws Exception {
598         Response result = null;
599         
600         // Note: must have the parentShortId, to do the create.
601         CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(null, parentspecifier, "createAuthorityItem", "CREATE_ITEM", null);
602         DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = 
603                 createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
604         String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
605         UriBuilder path = UriBuilder.fromResource(resourceClass);
606         path.path(parent.CSID + "/items/" + itemcsid);
607         result = Response.created(path.build()).build();
608
609         return result;
610     }
611
612     /**
613      * Called with an existing context.
614      * @param parentCtx
615      * @param parentspecifier
616      * @param input
617      * @return
618      * @throws Exception
619      */
620     public Response createAuthorityItemWithParentContext(ServiceContext parentCtx,
621                 String parentspecifier,
622                 PoxPayloadIn input) throws Exception {
623         Response result = null;
624         
625         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), input,
626                         parentCtx.getResourceMap(), parentCtx.getUriInfo());
627         if (parentCtx.getCurrentRepositorySession() != null) {
628                 ctx.setCurrentRepositorySession(parentCtx.getCurrentRepositorySession());
629         }
630         result = this.createAuthorityItem(ctx, parentspecifier);
631
632         return result;
633     }
634         
635     /*************************************************************************
636      * Create an AuthorityItem - this is a sub-resource of Authority
637      * @param specifier either a CSID or one of the urn forms
638      * @return Authority item response
639      *************************************************************************/
640     @POST
641     @Path("{csid}/items")
642     public Response createAuthorityItem(
643                 @Context ResourceMap resourceMap,
644                 @Context UriInfo uriInfo, 
645                 @PathParam("csid") String parentspecifier,
646                 String xmlPayload) {
647         Response result = null;
648         
649         try {
650             PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
651             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), input, resourceMap, uriInfo);
652             result = this.createAuthorityItem(ctx, parentspecifier);
653         } catch (Exception e) {
654             throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
655         }
656         
657         return result;
658     }
659
660     @GET
661     @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
662     public byte[] getItemWorkflow(
663             @PathParam("csid") String csid,
664             @PathParam("itemcsid") String itemcsid) {
665         PoxPayloadOut result = null;
666
667         try {
668             ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
669             String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
670
671             MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
672             WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
673             ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
674             getRepositoryClient(ctx).get(ctx, itemcsid, handler);
675             result = ctx.getOutput();
676         } catch (Exception e) {
677             throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
678         }
679         return result.getBytes();
680     }
681
682     //FIXME: This method is almost identical to the method org.collectionspace.services.common.updateWorkflowWithTransition() so
683     // they should be consolidated -be DRY (don't repeat yourself).
684     @PUT
685     @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH + "/{transition}")
686     public byte[] updateItemWorkflowWithTransition(
687             @PathParam("csid") String csid,
688             @PathParam("itemcsid") String itemcsid,
689             @PathParam("transition") String transition) {
690         PoxPayloadOut result = null;
691         
692         try {
693                 //
694                 // Create an empty workflow_commons input part and set it into a new "workflow" sub-resource context
695                 PoxPayloadIn input = new PoxPayloadIn(WorkflowClient.SERVICE_PAYLOAD_NAME, new WorkflowCommon(), 
696                                 WorkflowClient.SERVICE_COMMONPART_NAME);
697             MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, input);
698
699             // Create a service context and document handler for the parent resource.
700             ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
701             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> parentDocHandler = this.createDocumentHandler(parentCtx);
702             ctx.setProperty(WorkflowClient.PARENT_DOCHANDLER, parentDocHandler); //added as a context param for the workflow document handler -it will call the parent's dochandler "prepareForWorkflowTranstion" method
703
704             // When looking for the document, we need to use the parent's workspace name -not the "workflow" workspace name
705             String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
706             ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
707             
708                 // Get the type of transition we're being asked to make and store it as a context parameter -used by the workflow document handler
709             TransitionDef transitionDef = getTransitionDef(parentCtx, transition);
710             ctx.setProperty(WorkflowClient.TRANSITION_ID, transitionDef);
711             
712             WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
713             getRepositoryClient(ctx).update(ctx, itemcsid, handler);
714             result = ctx.getOutput();
715         } catch (Exception e) {
716             throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
717         }
718         
719         return result.getBytes();
720     }
721     
722     private PoxPayloadOut getAuthorityItem(
723                 ServiceContext ctx,
724             String parentIdentifier,
725             String itemIdentifier) throws Exception {
726         PoxPayloadOut result = null;
727         
728         String parentcsid = lookupParentCSID(parentIdentifier, "getAuthorityItem(parent)", "GET_ITEM", null);
729         // We omit the parentShortId, only needed when doing a create...
730         DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createItemDocumentHandler(ctx, parentcsid, null);
731
732         Specifier itemSpec = getSpecifier(itemIdentifier, "getAuthorityItem(item)", "GET_ITEM");
733         if (itemSpec.form == SpecifierForm.CSID) {
734             getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
735         } else {
736             String itemWhereClause =
737                         RefNameServiceUtils.buildWhereForAuthItemByName(authorityItemCommonSchemaName, itemSpec.value, parentcsid);
738             DocumentFilter myFilter = new NuxeoDocumentFilter(itemWhereClause, 0, 1); // start at page 0 and get 1 item
739             handler.setDocumentFilter(myFilter);
740             getRepositoryClient(ctx).get(ctx, handler);
741         }
742         // TODO should we assert that the item is in the passed vocab?
743         result = (PoxPayloadOut) ctx.getOutput();
744
745         return result;
746     }
747
748     public PoxPayloadOut getAuthorityItemWithParentContext(
749                 ServiceContext parentCtx,
750             String parentIdentifier,
751             String itemIdentifier) throws Exception {
752         PoxPayloadOut result = null;
753         
754         ServiceContext ctx = createServiceContext(getItemServiceName(), parentCtx.getResourceMap(), parentCtx.getUriInfo());
755         if (parentCtx.getCurrentRepositorySession() != null) {
756                 ctx.setCurrentRepositorySession(parentCtx.getCurrentRepositorySession()); // Reuse the current repo session if one exists
757         }
758         result = getAuthorityItem(ctx, parentIdentifier, itemIdentifier);
759         
760         return result;
761     }
762     
763     /**
764      * Gets the authority item.
765      * 
766      * @param parentspecifier either a CSID or one of the urn forms
767      * @param itemspecifier either a CSID or one of the urn forms
768      * 
769      * @return the authority item
770      */
771     @GET
772     @Path("{csid}/items/{itemcsid}")
773     public byte[] getAuthorityItem(
774             @Context Request request,
775             @Context UriInfo uriInfo,
776                 @Context ResourceMap resourceMap,            
777             @PathParam("csid") String parentIdentifier,
778             @PathParam("itemcsid") String itemIdentifier) {
779         PoxPayloadOut result = null;
780         try {
781             RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = 
782                         (RemoteServiceContext<PoxPayloadIn, PoxPayloadOut>) createServiceContext(getItemServiceName(), resourceMap, uriInfo);
783
784             JaxRsContext jaxRsContext = new JaxRsContext(request, uriInfo); // Needed for getting account permissions part of the resource
785             ctx.setJaxRsContext(jaxRsContext);
786             
787             result = getAuthorityItem(ctx, parentIdentifier, itemIdentifier);
788         } catch (DocumentNotFoundException dnf) {
789             throw bigReThrow(dnf, ServiceMessages.resourceNotFoundMsg(itemIdentifier));
790         } catch (Exception e) {
791             throw bigReThrow(e, ServiceMessages.GET_FAILED);
792         }
793                 
794         return result.getBytes();
795     }
796
797     /*
798      * Most of the authority child classes will/should use this implementation.  However, the Vocabulary service's item schema is
799      * different enough that it will have to override this method in it's resource class.
800      */
801     @Override
802         protected String getOrderByField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
803                 String result = null;
804
805                 result = NuxeoUtils.getPrimaryElPathPropertyName(
806                                 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
807                                 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
808
809                 return result;
810         }
811         
812     @Override
813         protected String getPartialTermMatchField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
814                 String result = null;
815                 
816                 result = NuxeoUtils.getMultiElPathPropertyName(
817                                 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
818                                 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
819
820                 return result;
821         }
822     
823     /**
824      * Gets the authorityItem list for the specified authority
825      * If partialPerm is specified, keywords will be ignored.
826      * 
827      * @param specifier either a CSID or one of the urn forms
828      * @param partialTerm if non-null, matches partial terms
829      * @param keywords if non-null, matches terms in the keyword index for items
830      * @param ui passed to include additional parameters, like pagination controls
831      * 
832      * @return the authorityItem list
833      */
834     @GET
835     @Path("{csid}/items")
836     @Produces("application/xml")
837     public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
838             @Context UriInfo uriInfo) {
839         AbstractCommonList result = null;
840         
841         try {
842             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
843             MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
844             
845             String orderBy = queryParams.getFirst(IClientQueryParams.ORDER_BY_PARAM);
846             String termStatus = queryParams.getFirst(SEARCH_TYPE_TERMSTATUS);
847             String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
848             String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
849             String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
850
851             // For the wildcard case, parentcsid is null, but docHandler will deal with this.
852             // We omit the parentShortId, only needed when doing a create...
853             String parentcsid = PARENT_WILDCARD.equals(specifier) ? null :
854                                 lookupParentCSID(specifier, "getAuthorityItemList", "LIST", uriInfo);
855             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler =
856                 createItemDocumentHandler(ctx, parentcsid, null);
857             
858             DocumentFilter myFilter = handler.getDocumentFilter();
859             // If we are not wildcarding the parent, add a restriction
860             if (parentcsid != null) {
861                     myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
862                             + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
863                             + "'" + parentcsid + "'",
864                             IQueryManager.SEARCH_QUALIFIER_AND);
865             }
866
867             if (Tools.notBlank(termStatus)) {
868                 // Start with the qualified termStatus field
869                 String qualifiedTermStatusField = authorityItemCommonSchemaName + ":"
870                         + AuthorityItemJAXBSchema.TERM_STATUS;
871                 String[] filterTerms = termStatus.trim().split("\\|");
872                 String tsClause = QueryManager.createWhereClauseToFilterFromStringList(qualifiedTermStatusField, filterTerms, IQueryManager.FILTER_EXCLUDE);
873                 myFilter.appendWhereClause(tsClause, IQueryManager.SEARCH_QUALIFIER_AND);
874             }
875
876             result = search(ctx, handler, uriInfo, orderBy, keywords, advancedSearch, partialTerm);            
877         } catch (Exception e) {
878             throw bigReThrow(e, ServiceMessages.LIST_FAILED);
879         }
880         
881         return result;
882     }
883
884     /**
885      * @return the name of the property used to specify references for items in this type of
886      * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
887      * Some types (like Vocabulary) use a separate property.
888      */
889     protected String getRefPropName() {
890         return ServiceBindingUtils.AUTH_REF_PROP;
891     }
892     
893     /**
894      * Gets the entities referencing this Authority item instance. The service type
895      * can be passed as a query param "type", and must match a configured type
896      * for the service bindings. If not set, the type defaults to
897      * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
898      *
899      * @param parentspecifier either a CSID or one of the urn forms
900      * @param itemspecifier either a CSID or one of the urn forms
901      * @param ui the ui
902      * 
903      * @return the info for the referencing objects
904      */
905     @GET
906     @Path("{csid}/items/{itemcsid}/refObjs")
907     @Produces("application/xml")
908     public AuthorityRefDocList getReferencingObjects(
909             @PathParam("csid") String parentspecifier,
910             @PathParam("itemcsid") String itemspecifier,
911             @Context UriTemplateRegistry uriTemplateRegistry,
912             @Context UriInfo uriInfo) {
913         AuthorityRefDocList authRefDocList = null;
914         try {
915             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
916             MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
917
918             String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", uriInfo);
919             String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
920
921             List<String> serviceTypes = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
922             if(serviceTypes == null || serviceTypes.isEmpty()) {
923                 serviceTypes = ServiceBindingUtils.getCommonServiceTypes(true); //CSPACE-5359: Should now include objects, procedures, and authorities
924             }
925             
926             // Note that we have to create the service context for the Items, not the main service
927             // We omit the parentShortId, only needed when doing a create...
928             AuthorityItemDocumentModelHandler<?> handler = (AuthorityItemDocumentModelHandler<?>)
929                                                                                                 createItemDocumentHandler(ctx, parentcsid, null);
930
931             authRefDocList = handler.getReferencingObjects(ctx, uriTemplateRegistry, serviceTypes, getRefPropName(), itemcsid);
932         } catch (Exception e) {
933             throw bigReThrow(e, ServiceMessages.GET_FAILED);
934         }
935         if (authRefDocList == null) {
936             Response response = Response.status(Response.Status.NOT_FOUND).entity(
937                     "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
938                     "text/plain").build();
939             throw new CSWebApplicationException(response);
940         }
941         return authRefDocList;
942     }
943
944     /**
945      * Gets the authority terms used in the indicated Authority item.
946      *
947      * @param parentspecifier either a CSID or one of the urn forms
948      * @param itemspecifier either a CSID or one of the urn forms
949      * @param ui passed to include additional parameters, like pagination controls
950      *
951      * @return the authority refs for the Authority item.
952      */
953     @GET
954     @Path("{csid}/items/{itemcsid}/authorityrefs")
955     @Produces("application/xml")
956     public AuthorityRefList getAuthorityItemAuthorityRefs(
957             @PathParam("csid") String parentspecifier,
958             @PathParam("itemcsid") String itemspecifier,
959             @Context UriInfo uriInfo) {
960         AuthorityRefList authRefList = null;
961         try {
962             // Note that we have to create the service context for the Items, not the main service
963             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
964             MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
965             String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", uriInfo);
966             // We omit the parentShortId, only needed when doing a create...
967             DocumentModelHandler<?, AbstractCommonList> handler =
968                     (DocumentModelHandler<?, AbstractCommonList>)createItemDocumentHandler(ctx, parentcsid, null /*no parent short ID*/);
969
970             String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
971
972             List<RefNameServiceUtils.AuthRefConfigInfo> authRefsInfo = RefNameServiceUtils.getConfiguredAuthorityRefs(ctx);
973             authRefList = handler.getAuthorityRefs(itemcsid, authRefsInfo);
974         } catch (Exception e) {
975             throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
976         }
977         return authRefList;
978     }
979     
980     /**
981      * Synchronizes a local authority item with a share authority server (SAS) item.
982      * @param ctx
983      * @param parentIdentifier
984      * @param itemIdentifier
985      * @return
986      * @throws Exception
987      */
988     protected PoxPayloadOut synchronizeItem(
989                 ServiceContext ctx,
990             String parentIdentifier,
991             String itemIdentifier) throws Exception {
992         PoxPayloadOut result = null;
993         AuthorityItemSpecifier specifier;
994         CsidAndShortIdentifier parent;
995         boolean neededSync = false;
996
997         parent = lookupParentCSIDAndShortIdentifer(null, parentIdentifier, "syncAuthorityItem(parent)", "SYNC_ITEM", null);
998         AuthorityItemDocumentModelHandler handler = (AuthorityItemDocumentModelHandler)createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
999         Specifier parentSpecifier = getSpecifier(parent.CSID, "getAuthority", "GET");
1000         Specifier itemSpecifier = getSpecifier(itemIdentifier, "getAuthorityItem", "GET");
1001         specifier = new AuthorityItemSpecifier(parentSpecifier, itemSpecifier);
1002         //
1003         neededSync = getRepositoryClient(ctx).synchronize(ctx, specifier, handler);
1004         if (neededSync == true) {
1005                 result = (PoxPayloadOut) ctx.getOutput();
1006         }
1007         
1008         return result;
1009     }
1010
1011     /**
1012      * Using the parent and item ID, sync the local item with the SAS (shared authority server)
1013      * Used by the AuthorityItemDocumentModelHandler when synchronizing a list of remote authority items with a
1014      * local authority.  The parent context was created for the authority (parent) because the sync started there.
1015      * @param parentCtx
1016      * @param parentIdentifier
1017      * @param itemIdentifier
1018      * @return
1019      * @throws Exception
1020      */
1021     public PoxPayloadOut synchronizeItemWithParentContext(
1022                 ServiceContext parentCtx,
1023             String parentIdentifier,
1024             String itemIdentifier
1025             ) throws Exception {
1026         PoxPayloadOut result = null;
1027         
1028         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(),
1029                         parentCtx.getResourceMap(),
1030                         parentCtx.getUriInfo());
1031         if (parentCtx.getCurrentRepositorySession() != null) {
1032                 ctx.setCurrentRepositorySession(parentCtx.getCurrentRepositorySession());
1033         }
1034         result = synchronizeItem(ctx, parentIdentifier, itemIdentifier);
1035         
1036         return result;
1037     }
1038     
1039     /**
1040      * Synchronizes an authority item and with a Shared Authority Server (SAS) item.
1041      * 
1042      * @param specifier either CSIDs and/or one of the urn forms
1043      * 
1044      * @return the authority item if it was synchronized with SAS
1045      */
1046     @GET
1047     @Path("{csid}/items/{itemcsid}/sync")
1048     public byte[] synchronizeItem(
1049                 @Context ResourceMap resourceMap,
1050             @Context UriInfo uriInfo,
1051             @PathParam("csid") String parentIdentifier,
1052             @PathParam("itemcsid") String itemIdentifier) {
1053         byte[] result;
1054         boolean neededSync = false;
1055         PoxPayloadOut payloadOut = null;
1056         
1057         try {
1058             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), null, resourceMap, uriInfo);
1059             payloadOut = this.synchronizeItem(ctx, parentIdentifier, itemIdentifier);
1060             if (payloadOut != null) {
1061                 neededSync = true;
1062             }
1063         } catch (Exception e) {
1064             throw bigReThrow(e, ServiceMessages.SYNC_FAILED, itemIdentifier);
1065         }
1066
1067         //
1068         // If a sync was needed and was successful, return a copy of the updated resource.  Acts like an UPDATE.
1069         //
1070         if (neededSync == true) {
1071                 result = payloadOut.getBytes();
1072         } else {
1073                 result = String.format("Authority item resource '%s' was already in sync with shared authority server.",
1074                                 itemIdentifier).getBytes();
1075                 Response response = Response.status(Response.Status.NOT_MODIFIED).entity(result).type("text/plain").build();
1076             throw new CSWebApplicationException(response);
1077         }
1078         
1079         return result;
1080     }
1081     
1082     /**
1083      * Update authorityItem.
1084      * 
1085      * @param parentspecifier either a CSID or one of the urn forms
1086      * @param itemspecifier either a CSID or one of the urn forms
1087      *
1088      * @return the multipart output
1089      */
1090     @PUT
1091     @Path("{csid}/items/{itemcsid}")
1092     public byte[] updateAuthorityItem(
1093                 @Context ResourceMap resourceMap, 
1094             @Context UriInfo uriInfo,
1095             @PathParam("csid") String parentSpecifier,
1096             @PathParam("itemcsid") String itemSpecifier,
1097             String xmlPayload) {
1098         PoxPayloadOut result = null;
1099         
1100         try {
1101             PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
1102             result = updateAuthorityItem(null, resourceMap, uriInfo, parentSpecifier, itemSpecifier, theUpdate, true); // passing TRUE so parent authority rev num increases
1103         } catch (Exception e) {
1104             throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
1105         }
1106         
1107         return result.getBytes();
1108     }
1109     
1110     public PoxPayloadOut updateAuthorityItem(
1111                 ServiceContext itemServiceCtx, // Ok to be null
1112                 ResourceMap resourceMap, 
1113             UriInfo uriInfo,
1114             String parentspecifier,
1115             String itemspecifier,
1116             PoxPayloadIn theUpdate,
1117             boolean shouldUpdateParentRev) throws Exception {
1118         PoxPayloadOut result = null;
1119         
1120         CsidAndShortIdentifier csidAndShortId = lookupParentCSIDAndShortIdentifer(itemServiceCtx, parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
1121         String parentcsid = csidAndShortId.CSID;
1122         String parentShortId = csidAndShortId.shortIdentifier;
1123         //
1124         // If the itemServiceCtx context is not null, use it.  Otherwise, create a new context
1125         //
1126         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = itemServiceCtx;
1127         if (ctx == null) {
1128                 ctx = createServiceContext(getItemServiceName(), theUpdate, resourceMap, uriInfo);
1129         }
1130         String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx); //use itemServiceCtx if it is not null
1131
1132         // We omit the parentShortId, only needed when doing a create...
1133         AuthorityItemDocumentModelHandler handler = (AuthorityItemDocumentModelHandler)createItemDocumentHandler(ctx, parentcsid, parentShortId);
1134         handler.setShouldUpdateParentRevNumber(shouldUpdateParentRev);
1135         getRepositoryClient(ctx).update(ctx, itemcsid, handler);
1136         result = ctx.getOutput();
1137
1138         return result;
1139     }
1140
1141     /**
1142      * Delete authorityItem.
1143      * 
1144      * @param parentcsid the parentcsid
1145      * @param itemcsid the itemcsid
1146      * 
1147      * @return the response
1148      */
1149     @DELETE
1150     @Path("{csid}/items/{itemcsid}")
1151     public Response deleteAuthorityItem(
1152             @PathParam("csid") String parentcsid,
1153             @PathParam("itemcsid") String itemcsid) {
1154         //try{
1155         if (logger.isDebugEnabled()) {
1156             logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
1157         }
1158         try {
1159             ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
1160             ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
1161             //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
1162             // }catch (Throwable t){
1163             //    System.out.println("ERROR in setting up DELETE: "+t);
1164             // }
1165             // try {
1166             // Note that we have to create the service context for the Items, not the main service
1167             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName());
1168             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
1169             getRepositoryClient(ctx).delete(ctx, itemcsid, handler);
1170             return Response.status(HttpResponseCodes.SC_OK).build();
1171         } catch (Exception e) {
1172             throw bigReThrow(e, ServiceMessages.DELETE_FAILED + "  itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
1173         }
1174     }
1175     public final static String hierarchy = "hierarchy";
1176
1177     @GET
1178     @Path("{csid}/items/{itemcsid}/" + hierarchy)
1179     @Produces("application/xml")
1180     public String getHierarchy(@PathParam("csid") String csid,
1181             @PathParam("itemcsid") String itemcsid,
1182             @Context UriInfo ui) throws Exception {
1183         try {
1184             // All items in dive can look at their child uri's to get uri.  So we calculate the very first one.  We could also do a GET and look at the common part uri field, but why...?
1185             String calledUri = ui.getPath();
1186             String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
1187             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), ui);
1188             ctx.setUriInfo(ui);
1189             String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
1190             if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
1191                 return Hierarchy.surface(ctx, itemcsid, uri);
1192             } else {
1193                 return Hierarchy.dive(ctx, itemcsid, uri);
1194             }
1195         } catch (Exception e) {
1196             throw bigReThrow(e, "Error showing hierarchy", itemcsid);
1197         }
1198     }
1199     
1200     protected String getItemDocType(String tenantId) {
1201         return getDocType(tenantId, getItemServiceName());
1202     }
1203         
1204     /**
1205      * Returns a UriRegistry entry: a map of tenant-qualified URI templates
1206      * for the current resource, for all tenants
1207      * 
1208      * @return a map of URI templates for the current resource, for all tenants
1209      */
1210     @Override
1211     public Map<UriTemplateRegistryKey,StoredValuesUriTemplate> getUriRegistryEntries() {
1212         Map<UriTemplateRegistryKey,StoredValuesUriTemplate> uriRegistryEntriesMap =
1213                 super.getUriRegistryEntries();
1214         List<String> tenantIds = getTenantBindingsReader().getTenantIds();
1215         for (String tenantId : tenantIds) {
1216                 uriRegistryEntriesMap.putAll(getUriRegistryEntries(tenantId, getItemDocType(tenantId), UriTemplateFactory.ITEM));
1217         }
1218         return uriRegistryEntriesMap;
1219     }
1220   
1221 }