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