]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
60547b7880c738ed8bbfc032d0b3fbaab6ebe2ff
[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
598     /*************************************************************************
599      * Create an AuthorityItem - this is a sub-resource of Authority
600      * @param specifier either a CSID or one of the urn forms
601      * @return Authority item response
602      *************************************************************************/
603     @POST
604     @Path("{csid}/items")
605     public Response createAuthorityItem(
606                 @Context ResourceMap resourceMap,
607                 @Context UriInfo uriInfo, 
608                 @PathParam("csid") String parentspecifier,
609                 String xmlPayload) {
610         Response result = null;
611         
612         try {
613             PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
614             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), input, resourceMap, uriInfo);
615
616             // Note: must have the parentShortId, to do the create.
617             CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(null, parentspecifier, "createAuthorityItem", "CREATE_ITEM", null);
618             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = 
619                 createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
620             String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
621             UriBuilder path = UriBuilder.fromResource(resourceClass);
622             path.path(parent.CSID + "/items/" + itemcsid);
623             result = Response.created(path.build()).build();
624         } catch (Exception e) {
625             throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
626         }
627         
628         return result;
629     }
630
631     @GET
632     @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
633     public byte[] getItemWorkflow(
634             @PathParam("csid") String csid,
635             @PathParam("itemcsid") String itemcsid) {
636         PoxPayloadOut result = null;
637
638         try {
639             ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
640             String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
641
642             MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
643             WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
644             ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
645             getRepositoryClient(ctx).get(ctx, itemcsid, handler);
646             result = ctx.getOutput();
647         } catch (Exception e) {
648             throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
649         }
650         return result.getBytes();
651     }
652
653     //FIXME: This method is almost identical to the method org.collectionspace.services.common.updateWorkflowWithTransition() so
654     // they should be consolidated -be DRY (don't repeat yourself).
655     @PUT
656     @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH + "/{transition}")
657     public byte[] updateItemWorkflowWithTransition(
658             @PathParam("csid") String csid,
659             @PathParam("itemcsid") String itemcsid,
660             @PathParam("transition") String transition) {
661         PoxPayloadOut result = null;
662         
663         try {
664                 //
665                 // Create an empty workflow_commons input part and set it into a new "workflow" sub-resource context
666                 PoxPayloadIn input = new PoxPayloadIn(WorkflowClient.SERVICE_PAYLOAD_NAME, new WorkflowCommon(), 
667                                 WorkflowClient.SERVICE_COMMONPART_NAME);
668             MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, input);
669
670             // Create a service context and document handler for the parent resource.
671             ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
672             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> parentDocHandler = this.createDocumentHandler(parentCtx);
673             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
674
675             // When looking for the document, we need to use the parent's workspace name -not the "workflow" workspace name
676             String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
677             ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
678             
679                 // Get the type of transition we're being asked to make and store it as a context parameter -used by the workflow document handler
680             TransitionDef transitionDef = getTransitionDef(parentCtx, transition);
681             ctx.setProperty(WorkflowClient.TRANSITION_ID, transitionDef);
682             
683             WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
684             getRepositoryClient(ctx).update(ctx, itemcsid, handler);
685             result = ctx.getOutput();
686         } catch (Exception e) {
687             throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
688         }
689         
690         return result.getBytes();
691     }
692
693     /**
694      * Gets the authority item.
695      * 
696      * @param parentspecifier either a CSID or one of the urn forms
697      * @param itemspecifier either a CSID or one of the urn forms
698      * 
699      * @return the authority item
700      */
701     @GET
702     @Path("{csid}/items/{itemcsid}")
703     public byte[] getAuthorityItem(
704             @Context Request request,
705             @Context UriInfo uriInfo,
706                 @Context ResourceMap resourceMap,            
707             @PathParam("csid") String parentspecifier,
708             @PathParam("itemcsid") String itemspecifier) {
709         PoxPayloadOut result = null;
710         try {
711             String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", uriInfo);
712
713             RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = 
714                 (RemoteServiceContext<PoxPayloadIn, PoxPayloadOut>) createServiceContext(getItemServiceName(), resourceMap, uriInfo);
715             
716             JaxRsContext jaxRsContext = new JaxRsContext(request, uriInfo); // Needed for getting account permissions part of the payload
717             ctx.setJaxRsContext(jaxRsContext);
718
719             // We omit the parentShortId, only needed when doing a create...
720             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createItemDocumentHandler(ctx, parentcsid, null);
721
722             Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
723             if (itemSpec.form == SpecifierForm.CSID) {
724                 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
725             } else {
726                 String itemWhereClause =
727                                 RefNameServiceUtils.buildWhereForAuthItemByName(authorityItemCommonSchemaName, itemSpec.value, parentcsid);
728                 DocumentFilter myFilter = new NuxeoDocumentFilter(itemWhereClause, 0, 1); // start at page 0 and get 1 item
729                 handler.setDocumentFilter(myFilter);
730                 getRepositoryClient(ctx).get(ctx, handler);
731             }
732             // TODO should we assert that the item is in the passed vocab?
733             result = ctx.getOutput();
734         } catch (Exception e) {
735             throw bigReThrow(e, ServiceMessages.GET_FAILED);
736         }
737         
738         if (result == null) {
739             Response response = Response.status(Response.Status.NOT_FOUND).entity(
740                     "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
741                     "text/plain").build();
742             throw new CSWebApplicationException(response);
743         }
744         
745         return result.getBytes();
746     }
747
748     /*
749      * Most of the authority child classes will/should use this implementation.  However, the Vocabulary service's item schema is
750      * different enough that it will have to override this method in it's resource class.
751      */
752     @Override
753         protected String getOrderByField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
754                 String result = null;
755
756                 result = NuxeoUtils.getPrimaryElPathPropertyName(
757                                 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
758                                 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
759
760                 return result;
761         }
762         
763     @Override
764         protected String getPartialTermMatchField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
765                 String result = null;
766                 
767                 result = NuxeoUtils.getMultiElPathPropertyName(
768                                 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
769                                 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
770
771                 return result;
772         }
773     
774     /**
775      * Gets the authorityItem list for the specified authority
776      * If partialPerm is specified, keywords will be ignored.
777      * 
778      * @param specifier either a CSID or one of the urn forms
779      * @param partialTerm if non-null, matches partial terms
780      * @param keywords if non-null, matches terms in the keyword index for items
781      * @param ui passed to include additional parameters, like pagination controls
782      * 
783      * @return the authorityItem list
784      */
785     @GET
786     @Path("{csid}/items")
787     @Produces("application/xml")
788     public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
789             @Context UriInfo uriInfo) {
790         AbstractCommonList result = null;
791         
792         try {
793             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
794             MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
795             
796             String orderBy = queryParams.getFirst(IClientQueryParams.ORDER_BY_PARAM);
797             String termStatus = queryParams.getFirst(SEARCH_TYPE_TERMSTATUS);
798             String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
799             String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
800             String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
801
802             // For the wildcard case, parentcsid is null, but docHandler will deal with this.
803             // We omit the parentShortId, only needed when doing a create...
804             String parentcsid = PARENT_WILDCARD.equals(specifier) ? null :
805                                 lookupParentCSID(specifier, "getAuthorityItemList", "LIST", uriInfo);
806             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler =
807                 createItemDocumentHandler(ctx, parentcsid, null);
808             
809             DocumentFilter myFilter = handler.getDocumentFilter();
810             // If we are not wildcarding the parent, add a restriction
811             if (parentcsid != null) {
812                     myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
813                             + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
814                             + "'" + parentcsid + "'",
815                             IQueryManager.SEARCH_QUALIFIER_AND);
816             }
817
818             if (Tools.notBlank(termStatus)) {
819                 // Start with the qualified termStatus field
820                 String qualifiedTermStatusField = authorityItemCommonSchemaName + ":"
821                         + AuthorityItemJAXBSchema.TERM_STATUS;
822                 String[] filterTerms = termStatus.trim().split("\\|");
823                 String tsClause = QueryManager.createWhereClauseToFilterFromStringList(qualifiedTermStatusField, filterTerms, IQueryManager.FILTER_EXCLUDE);
824                 myFilter.appendWhereClause(tsClause, IQueryManager.SEARCH_QUALIFIER_AND);
825             }
826
827             result = search(ctx, handler, uriInfo, orderBy, keywords, advancedSearch, partialTerm);            
828         } catch (Exception e) {
829             throw bigReThrow(e, ServiceMessages.LIST_FAILED);
830         }
831         
832         return result;
833     }
834
835     /**
836      * @return the name of the property used to specify references for items in this type of
837      * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
838      * Some types (like Vocabulary) use a separate property.
839      */
840     protected String getRefPropName() {
841         return ServiceBindingUtils.AUTH_REF_PROP;
842     }
843     
844     /**
845      * Gets the entities referencing this Authority item instance. The service type
846      * can be passed as a query param "type", and must match a configured type
847      * for the service bindings. If not set, the type defaults to
848      * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
849      *
850      * @param parentspecifier either a CSID or one of the urn forms
851      * @param itemspecifier either a CSID or one of the urn forms
852      * @param ui the ui
853      * 
854      * @return the info for the referencing objects
855      */
856     @GET
857     @Path("{csid}/items/{itemcsid}/refObjs")
858     @Produces("application/xml")
859     public AuthorityRefDocList getReferencingObjects(
860             @PathParam("csid") String parentspecifier,
861             @PathParam("itemcsid") String itemspecifier,
862             @Context UriTemplateRegistry uriTemplateRegistry,
863             @Context UriInfo uriInfo) {
864         AuthorityRefDocList authRefDocList = null;
865         try {
866             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
867             MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
868
869             String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", uriInfo);
870             String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
871
872             List<String> serviceTypes = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
873             if(serviceTypes == null || serviceTypes.isEmpty()) {
874                 serviceTypes = ServiceBindingUtils.getCommonServiceTypes(true); //CSPACE-5359: Should now include objects, procedures, and authorities
875             }
876             
877             // Note that we have to create the service context for the Items, not the main service
878             // We omit the parentShortId, only needed when doing a create...
879             AuthorityItemDocumentModelHandler<?> handler = (AuthorityItemDocumentModelHandler<?>)
880                                                                                                 createItemDocumentHandler(ctx, parentcsid, null);
881
882             authRefDocList = handler.getReferencingObjects(ctx, uriTemplateRegistry, serviceTypes, getRefPropName(), itemcsid);
883         } catch (Exception e) {
884             throw bigReThrow(e, ServiceMessages.GET_FAILED);
885         }
886         if (authRefDocList == null) {
887             Response response = Response.status(Response.Status.NOT_FOUND).entity(
888                     "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
889                     "text/plain").build();
890             throw new CSWebApplicationException(response);
891         }
892         return authRefDocList;
893     }
894
895     /**
896      * Gets the authority terms used in the indicated Authority item.
897      *
898      * @param parentspecifier either a CSID or one of the urn forms
899      * @param itemspecifier either a CSID or one of the urn forms
900      * @param ui passed to include additional parameters, like pagination controls
901      *
902      * @return the authority refs for the Authority item.
903      */
904     @GET
905     @Path("{csid}/items/{itemcsid}/authorityrefs")
906     @Produces("application/xml")
907     public AuthorityRefList getAuthorityItemAuthorityRefs(
908             @PathParam("csid") String parentspecifier,
909             @PathParam("itemcsid") String itemspecifier,
910             @Context UriInfo uriInfo) {
911         AuthorityRefList authRefList = null;
912         try {
913             // Note that we have to create the service context for the Items, not the main service
914             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
915             MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
916             String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", uriInfo);
917             // We omit the parentShortId, only needed when doing a create...
918             DocumentModelHandler<?, AbstractCommonList> handler =
919                     (DocumentModelHandler<?, AbstractCommonList>)createItemDocumentHandler(ctx, parentcsid, null /*no parent short ID*/);
920
921             String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
922
923             List<RefNameServiceUtils.AuthRefConfigInfo> authRefsInfo = RefNameServiceUtils.getConfiguredAuthorityRefs(ctx);
924             authRefList = handler.getAuthorityRefs(itemcsid, authRefsInfo);
925         } catch (Exception e) {
926             throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
927         }
928         return authRefList;
929     }
930
931     /**
932      * Synchronizes the authority and its terms with a Shared Authority Server (SAS).
933      * 
934      * @param specifier either CSIDs and/or one of the urn forms
935      * 
936      * @return the authority item if it was synchronized with SAS
937      */
938     @GET
939     @Path("{csid}/items/{itemcsid}/sync")
940     public byte[] synchronizeItem(
941                 @Context ResourceMap resourceMap,
942             @Context Request request,
943             @Context UriInfo uriInfo,
944             @PathParam("csid") String parentIdentifier,
945             @PathParam("itemcsid") String itemIdentifier
946             ) {
947         byte[] result;
948         boolean neededSync = false;
949         PoxPayloadOut payloadOut = null;
950         AuthorityItemSpecifier specifier;
951         CsidAndShortIdentifier parent;
952         
953         try {
954             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), null, resourceMap, uriInfo);
955             parent = lookupParentCSIDAndShortIdentifer(null, parentIdentifier, "syncAuthorityItem(parent)", "SYNC_ITEM", null);
956             AuthorityItemDocumentModelHandler handler = (AuthorityItemDocumentModelHandler)createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
957             Specifier parentSpecifier = getSpecifier(parent.CSID, "getAuthority", "GET");
958             Specifier itemSpecifier = getSpecifier(itemIdentifier, "getAuthorityItem", "GET");
959             specifier = new AuthorityItemSpecifier(parentSpecifier, itemSpecifier);
960             neededSync = getRepositoryClient(ctx).synchronize(ctx, specifier, handler);
961             payloadOut = ctx.getOutput();
962         } catch (Exception e) {
963             throw bigReThrow(e, ServiceMessages.SYNC_FAILED, itemIdentifier);
964         }
965
966         //
967         // If a sync was needed and was successful, return a copy of the updated resource.  Acts like an UPDATE.
968         //
969         if (neededSync == true) {
970                 result = payloadOut.getBytes();
971         } else {
972                 result = String.format("Authority item resource '%s' was already in sync with shared authority server.",
973                                 itemIdentifier).getBytes();
974                 Response response = Response.status(Response.Status.NOT_MODIFIED).entity(result).type("text/plain").build();
975             throw new CSWebApplicationException(response);
976         }
977         
978         return result;
979     }
980     
981     /**
982      * Update authorityItem.
983      * 
984      * @param parentspecifier either a CSID or one of the urn forms
985      * @param itemspecifier either a CSID or one of the urn forms
986      *
987      * @return the multipart output
988      */
989     @PUT
990     @Path("{csid}/items/{itemcsid}")
991     public byte[] updateAuthorityItem(
992                 @Context ResourceMap resourceMap, 
993             @Context UriInfo uriInfo,
994             @PathParam("csid") String parentSpecifier,
995             @PathParam("itemcsid") String itemSpecifier,
996             String xmlPayload) {
997         PoxPayloadOut result = null;
998         
999         try {
1000             PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
1001             result = updateAuthorityItem(null, resourceMap, uriInfo, parentSpecifier, itemSpecifier, theUpdate, true); // passing TRUE so parent authority rev num increases
1002         } catch (Exception e) {
1003             throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
1004         }
1005         
1006         return result.getBytes();
1007     }
1008     
1009     public PoxPayloadOut updateAuthorityItem(
1010                 ServiceContext itemServiceCtx, // Ok to be null
1011                 ResourceMap resourceMap, 
1012             UriInfo uriInfo,
1013             String parentspecifier,
1014             String itemspecifier,
1015             PoxPayloadIn theUpdate,
1016             boolean shouldUpdateParentRev) throws Exception {
1017         PoxPayloadOut result = null;
1018         
1019         CsidAndShortIdentifier csidAndShortId = lookupParentCSIDAndShortIdentifer(itemServiceCtx, parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
1020         String parentcsid = csidAndShortId.CSID;
1021         String parentShortId = csidAndShortId.shortIdentifier;
1022         //
1023         // If the itemServiceCtx context is not null, use it.  Otherwise, create a new context
1024         //
1025         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = itemServiceCtx;
1026         if (ctx == null) {
1027                 ctx = createServiceContext(getItemServiceName(), theUpdate, resourceMap, uriInfo);
1028         }
1029         String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx); //use itemServiceCtx if it is not null
1030
1031         // We omit the parentShortId, only needed when doing a create...
1032         AuthorityItemDocumentModelHandler handler = (AuthorityItemDocumentModelHandler)createItemDocumentHandler(ctx, parentcsid, parentShortId);
1033         handler.setShouldUpdateParentRevNumber(shouldUpdateParentRev);
1034         getRepositoryClient(ctx).update(ctx, itemcsid, handler);
1035         result = ctx.getOutput();
1036
1037         return result;
1038     }
1039
1040     /**
1041      * Delete authorityItem.
1042      * 
1043      * @param parentcsid the parentcsid
1044      * @param itemcsid the itemcsid
1045      * 
1046      * @return the response
1047      */
1048     @DELETE
1049     @Path("{csid}/items/{itemcsid}")
1050     public Response deleteAuthorityItem(
1051             @PathParam("csid") String parentcsid,
1052             @PathParam("itemcsid") String itemcsid) {
1053         //try{
1054         if (logger.isDebugEnabled()) {
1055             logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
1056         }
1057         try {
1058             ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
1059             ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
1060             //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
1061             // }catch (Throwable t){
1062             //    System.out.println("ERROR in setting up DELETE: "+t);
1063             // }
1064             // try {
1065             // Note that we have to create the service context for the Items, not the main service
1066             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName());
1067             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
1068             getRepositoryClient(ctx).delete(ctx, itemcsid, handler);
1069             return Response.status(HttpResponseCodes.SC_OK).build();
1070         } catch (Exception e) {
1071             throw bigReThrow(e, ServiceMessages.DELETE_FAILED + "  itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
1072         }
1073     }
1074     public final static String hierarchy = "hierarchy";
1075
1076     @GET
1077     @Path("{csid}/items/{itemcsid}/" + hierarchy)
1078     @Produces("application/xml")
1079     public String getHierarchy(@PathParam("csid") String csid,
1080             @PathParam("itemcsid") String itemcsid,
1081             @Context UriInfo ui) throws Exception {
1082         try {
1083             // 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...?
1084             String calledUri = ui.getPath();
1085             String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
1086             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), ui);
1087             ctx.setUriInfo(ui);
1088             String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
1089             if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
1090                 return Hierarchy.surface(ctx, itemcsid, uri);
1091             } else {
1092                 return Hierarchy.dive(ctx, itemcsid, uri);
1093             }
1094         } catch (Exception e) {
1095             throw bigReThrow(e, "Error showing hierarchy", itemcsid);
1096         }
1097     }
1098     
1099     protected String getItemDocType(String tenantId) {
1100         return getDocType(tenantId, getItemServiceName());
1101     }
1102         
1103     /**
1104      * Returns a UriRegistry entry: a map of tenant-qualified URI templates
1105      * for the current resource, for all tenants
1106      * 
1107      * @return a map of URI templates for the current resource, for all tenants
1108      */
1109     @Override
1110     public Map<UriTemplateRegistryKey,StoredValuesUriTemplate> getUriRegistryEntries() {
1111         Map<UriTemplateRegistryKey,StoredValuesUriTemplate> uriRegistryEntriesMap =
1112                 super.getUriRegistryEntries();
1113         List<String> tenantIds = getTenantBindingsReader().getTenantIds();
1114         for (String tenantId : tenantIds) {
1115                 uriRegistryEntriesMap.putAll(getUriRegistryEntries(tenantId, getItemDocType(tenantId), UriTemplateFactory.ITEM));
1116         }
1117         return uriRegistryEntriesMap;
1118     }
1119   
1120 }