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