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