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