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