]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
8ea47ae13db7e32c1c644a126f994dc645266b47
[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                 myFilter.setOrderByClause(qualifiedDisplayNameField);
431             }
432             String nameQ = queryParams.getFirst("refName");
433             if (nameQ != null) {
434                 myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'");
435             }
436             getRepositoryClient(ctx).getFiltered(ctx, handler);
437             return (AbstractCommonList) handler.getCommonPartList();
438         } catch (Exception e) {
439             throw bigReThrow(e, ServiceMessages.GET_FAILED);
440         }
441     }
442
443     /**
444      * Update authority.
445      *
446      * @param specifier the csid or id
447      *
448      * @return the multipart output
449      */
450     @PUT
451     @Path("{csid}")
452     public byte[] updateAuthority(
453             @PathParam("csid") String specifier,
454             String xmlPayload) {
455         PoxPayloadOut result = null;
456         try {
457             PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
458             Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
459             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
460             DocumentHandler handler = createDocumentHandler(ctx);
461             String csid;
462             if (spec.form == SpecifierForm.CSID) {
463                 csid = spec.value;
464             } else {
465                 String whereClause = buildWhereForAuthByName(spec.value);
466                 csid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause);
467             }
468             getRepositoryClient(ctx).update(ctx, csid, handler);
469             result = ctx.getOutput();
470         } catch (Exception e) {
471             throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
472         }
473         return result.getBytes();
474     }
475
476     /**
477      * Delete authority.
478      * 
479      * @param csid the csid
480      * 
481      * @return the response
482      */
483     @DELETE
484     @Path("{csid}")
485     public Response deleteAuthority(@PathParam("csid") String csid) {
486         if (logger.isDebugEnabled()) {
487             logger.debug("deleteAuthority with csid=" + csid);
488         }
489         try {
490             ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid");
491             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
492             DocumentHandler handler = createDocumentHandler(ctx);
493             getRepositoryClient(ctx).delete(ctx, csid, handler);
494             return Response.status(HttpResponseCodes.SC_OK).build();
495         } catch (Exception e) {
496             throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid);
497         }
498     }
499
500     /*************************************************************************
501      * Create an AuthorityItem - this is a sub-resource of Authority
502      * @param specifier either a CSID or one of the urn forms
503      * @return Authority item response
504      *************************************************************************/
505     @POST
506     @Path("{csid}/items")
507     public Response createAuthorityItem(@Context ResourceMap resourceMap, @Context UriInfo ui, 
508                 @PathParam("csid") String specifier, String xmlPayload) {
509         try {
510             PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
511             ServiceContext ctx = createServiceContext(getItemServiceName(), input);
512             ctx.setResourceMap(resourceMap);
513             ctx.setUriInfo(ui);    //Laramie
514
515             // Note: must have the parentShortId, to do the create.
516             CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(specifier, "createAuthorityItem", "CREATE_ITEM", null);
517             DocumentHandler handler = createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
518             String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
519             UriBuilder path = UriBuilder.fromResource(resourceClass);
520             path.path(parent.CSID + "/items/" + itemcsid);
521             Response response = Response.created(path.build()).build();
522             return response;
523         } catch (Exception e) {
524             throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
525         }
526     }
527
528     @GET
529     @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
530     public byte[] getItemWorkflow(
531             @PathParam("csid") String csid,
532             @PathParam("itemcsid") String itemcsid) {
533         PoxPayloadOut result = null;
534
535         try {
536             ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
537             String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
538
539             MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
540             WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
541             ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
542             getRepositoryClient(ctx).get(ctx, itemcsid, handler);
543             result = ctx.getOutput();
544         } catch (Exception e) {
545             throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
546         }
547         return result.getBytes();
548     }
549
550     //FIXME: This method is almost identical to the method org.collectionspace.services.common.updateWorkflowWithTransition() so
551     // they should be consolidated -be DRY (don't repeat yourself).
552     @PUT
553     @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH + "/{transition}")
554     public byte[] updateItemWorkflowWithTransition(
555             @PathParam("csid") String csid,
556             @PathParam("itemcsid") String itemcsid,
557             @PathParam("transition") String transition) {
558         PoxPayloadOut result = null;
559         
560         try {
561                 //
562                 // Create an empty workflow_commons input part and set it into a new "workflow" sub-resource context
563                 PoxPayloadIn input = new PoxPayloadIn(WorkflowClient.SERVICE_PAYLOAD_NAME, new WorkflowCommon(), 
564                                 WorkflowClient.SERVICE_COMMONPART_NAME);
565             MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, input);
566
567             // Create a service context and document handler for the parent resource.
568             ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
569             DocumentHandler parentDocHandler = this.createDocumentHandler(parentCtx);
570             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
571
572             // When looking for the document, we need to use the parent's workspace name -not the "workflow" workspace name
573             String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
574             ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
575             
576                 // Get the type of transition we're being asked to make and store it as a context parameter -used by the workflow document handler
577             TransitionDef transitionDef = getTransitionDef(parentCtx, transition);
578             ctx.setProperty(WorkflowClient.TRANSITION_ID, transitionDef);
579             
580             WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
581             getRepositoryClient(ctx).update(ctx, itemcsid, handler);
582             result = ctx.getOutput();
583         } catch (Exception e) {
584             throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
585         }
586         
587         return result.getBytes();
588     }
589
590     /**
591      * Gets the authority item.
592      * 
593      * @param parentspecifier either a CSID or one of the urn forms
594      * @param itemspecifier either a CSID or one of the urn forms
595      * 
596      * @return the authority item
597      */
598     @GET
599     @Path("{csid}/items/{itemcsid}")
600     public byte[] getAuthorityItem(
601             @Context Request request,
602             @Context UriInfo ui,
603             @PathParam("csid") String parentspecifier,
604             @PathParam("itemcsid") String itemspecifier) {
605         PoxPayloadOut result = null;
606         try {
607             JaxRsContext jaxRsContext = new JaxRsContext(request, ui);
608             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
609             String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", queryParams);
610
611             RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
612             ctx = (RemoteServiceContext) createServiceContext(getItemServiceName(), queryParams);
613             ctx.setJaxRsContext(jaxRsContext);
614
615             ctx.setUriInfo(ui); //ARG!   must pass this or subsequent calls will not have a ui.
616
617             // We omit the parentShortId, only needed when doing a create...
618             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
619
620             Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
621             if (itemSpec.form == SpecifierForm.CSID) {
622                 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
623             } else {
624                 String itemWhereClause =
625                         buildWhereForAuthItemByName(itemSpec.value, parentcsid);
626                 DocumentFilter myFilter = new DocumentFilter(itemWhereClause, 0, 1);
627                 handler.setDocumentFilter(myFilter);
628                 getRepositoryClient(ctx).get(ctx, handler);
629             }
630             // TODO should we assert that the item is in the passed vocab?
631             result = ctx.getOutput();
632         } catch (Exception e) {
633             throw bigReThrow(e, ServiceMessages.GET_FAILED);
634         }
635         if (result == null) {
636             Response response = Response.status(Response.Status.NOT_FOUND).entity(
637                     "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
638                     "text/plain").build();
639             throw new WebApplicationException(response);
640         }
641         return result.getBytes();
642     }
643
644     /**
645      * Gets the authorityItem list for the specified authority
646      * If partialPerm is specified, keywords will be ignored.
647      * 
648      * @param specifier either a CSID or one of the urn forms
649      * @param partialTerm if non-null, matches partial terms
650      * @param keywords if non-null, matches terms in the keyword index for items
651      * @param ui passed to include additional parameters, like pagination controls
652      * 
653      * @return the authorityItem list
654      */
655     @GET
656     @Path("{csid}/items")
657     @Produces("application/xml")
658     public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
659             @Context UriInfo ui) {
660         try {
661             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
662             String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
663             String termStatus = queryParams.getFirst(SEARCH_TYPE_TERMSTATUS);
664             String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
665             String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
666
667             String qualifiedDisplayNameField = authorityItemCommonSchemaName + ":"
668                     + AuthorityItemJAXBSchema.DISPLAY_NAME;
669
670             // Note that docType defaults to the ServiceName, so we're fine with that.
671             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
672
673             String parentcsid = PARENT_WILDCARD.equals(specifier)?null:
674                                                 lookupParentCSID(specifier, "getAuthorityItemList", "LIST", queryParams);
675
676             ctx = createServiceContext(getItemServiceName(), queryParams);
677
678             // For the wildcard case, parentcsid is null, but docHandler will deal with this.
679             // We omit the parentShortId, only needed when doing a create...
680             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
681             
682             DocumentFilter myFilter = handler.getDocumentFilter();
683             // Need to make the default sort order for authority items
684             // be on the displayName field
685             String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
686             if (sortBy == null || sortBy.isEmpty()) {
687                 myFilter.setOrderByClause(qualifiedDisplayNameField);
688             }
689
690             // If we are not wildcarding the parent, add a restriction
691             if(parentcsid!=null) {
692                     myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
693                             + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
694                             + "'" + parentcsid + "'",
695                             IQueryManager.SEARCH_QUALIFIER_AND);
696             }
697
698             if (Tools.notBlank(termStatus)) {
699                 // Start with the qualified termStatus field
700                 String qualifiedTermStatusField = authorityItemCommonSchemaName + ":"
701                         + AuthorityItemJAXBSchema.TERM_STATUS;
702                 String[] filterTerms = termStatus.trim().split("\\|");
703                 String tsClause = QueryManager.createWhereClauseToFilterFromStringList(qualifiedTermStatusField, filterTerms, IQueryManager.FILTER_EXCLUDE);
704                 myFilter.appendWhereClause(tsClause, IQueryManager.SEARCH_QUALIFIER_AND);
705             }
706                 
707             // AND vocabularyitems_common:displayName LIKE '%partialTerm%'
708             // NOTE: Partial terms searches are mutually exclusive to keyword and advanced-search, but
709             // the PT query param trumps the KW and AS query params.
710             if (partialTerm != null && !partialTerm.isEmpty()) {
711                 String ptClause = QueryManager.createWhereClauseForPartialMatch(
712                         qualifiedDisplayNameField, partialTerm);
713                 myFilter.appendWhereClause(ptClause, IQueryManager.SEARCH_QUALIFIER_AND);
714             } else if (keywords != null || advancedSearch != null) {
715 //                              String kwdClause = QueryManager.createWhereClauseFromKeywords(keywords);
716 //                              myFilter.appendWhereClause(kwdClause, IQueryManager.SEARCH_QUALIFIER_AND);
717                 return search(ctx, handler, queryParams, keywords, advancedSearch);
718             }
719             if (logger.isDebugEnabled()) {
720                 logger.debug("getAuthorityItemList filtered WHERE clause: "
721                         + myFilter.getWhereClause());
722             }
723             getRepositoryClient(ctx).getFiltered(ctx, handler);
724             return (AbstractCommonList) handler.getCommonPartList();
725         } catch (Exception e) {
726             throw bigReThrow(e, ServiceMessages.LIST_FAILED);
727         }
728     }
729
730     /**
731      * @return the name of the property used to specify references for items in this type of
732      * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
733      * Some types (like Vocabulary) use a separate property.
734      */
735     protected String getRefPropName() {
736         return ServiceBindingUtils.AUTH_REF_PROP;
737     }
738     
739     /**
740      * Gets the entities referencing this Authority item instance. The service type
741      * can be passed as a query param "type", and must match a configured type
742      * for the service bindings. If not set, the type defaults to
743      * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
744      *
745      * @param parentspecifier either a CSID or one of the urn forms
746      * @param itemspecifier either a CSID or one of the urn forms
747      * @param ui the ui
748      * 
749      * @return the info for the referencing objects
750      */
751     @GET
752     @Path("{csid}/items/{itemcsid}/refObjs")
753     @Produces("application/xml")
754     public AuthorityRefDocList getReferencingObjects(
755             @PathParam("csid") String parentspecifier,
756             @PathParam("itemcsid") String itemspecifier,
757             @Context UriInfo ui) {
758         AuthorityRefDocList authRefDocList = null;
759         try {
760             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
761
762             String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", queryParams);
763
764             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), queryParams);
765             String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
766
767             List<String> serviceTypes = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
768             if(serviceTypes == null || serviceTypes.isEmpty()) {
769                 // Temporary workaround for CSPACE-4983
770                 // serviceTypes = ServiceBindingUtils.getCommonServiceTypes();
771                 serviceTypes = ServiceBindingUtils.getCommonProcedureServiceTypes();
772             }
773             
774             // Note that we have to create the service context for the Items, not the main service
775             // We omit the parentShortId, only needed when doing a create...
776             AuthorityItemDocumentModelHandler<?> handler = (AuthorityItemDocumentModelHandler<?>)
777                                                                                                 createItemDocumentHandler(ctx, parentcsid, null);
778
779             authRefDocList = handler.getReferencingObjects(ctx, serviceTypes, getRefPropName(), itemcsid);
780         } catch (Exception e) {
781             throw bigReThrow(e, ServiceMessages.GET_FAILED);
782         }
783         if (authRefDocList == null) {
784             Response response = Response.status(Response.Status.NOT_FOUND).entity(
785                     "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
786                     "text/plain").build();
787             throw new WebApplicationException(response);
788         }
789         return authRefDocList;
790     }
791
792     /**
793      * Gets the authority terms used in the indicated Authority item.
794      *
795      * @param parentspecifier either a CSID or one of the urn forms
796      * @param itemspecifier either a CSID or one of the urn forms
797      * @param ui passed to include additional parameters, like pagination controls
798      *
799      * @return the authority refs for the Authority item.
800      */
801     @GET
802     @Path("{csid}/items/{itemcsid}/authorityrefs")
803     @Produces("application/xml")
804     public AuthorityRefList getAuthorityItemAuthorityRefs(
805             @PathParam("csid") String parentspecifier,
806             @PathParam("itemcsid") String itemspecifier,
807             @Context UriInfo ui) {
808         AuthorityRefList authRefList = null;
809         try {
810             // Note that we have to create the service context for the Items, not the main service
811             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
812             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
813
814             String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", queryParams);
815
816             ctx = createServiceContext(getItemServiceName(), queryParams);
817             // We omit the parentShortId, only needed when doing a create...
818             DocumentModelHandler handler =
819                     (DocumentModelHandler)createItemDocumentHandler(ctx, parentcsid, null);
820
821             String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
822
823             List<RefNameServiceUtils.AuthRefConfigInfo> authRefsInfo = RefNameServiceUtils.getConfiguredAuthorityRefs(ctx);
824             authRefList = handler.getAuthorityRefs(itemcsid, authRefsInfo);
825         } catch (Exception e) {
826             throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
827         }
828         return authRefList;
829     }
830
831     /**
832      * Update authorityItem.
833      * 
834      * @param parentspecifier either a CSID or one of the urn forms
835      * @param itemspecifier either a CSID or one of the urn forms
836      *
837      * @return the multipart output
838      */
839     @PUT
840     @Path("{csid}/items/{itemcsid}")
841     public byte[] updateAuthorityItem(
842                 @Context ResourceMap resourceMap, 
843             @Context UriInfo ui,
844             @PathParam("csid") String parentspecifier,
845             @PathParam("itemcsid") String itemspecifier,
846             String xmlPayload) {
847         PoxPayloadOut result = null;
848         try {
849             PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
850             // Note that we have to create the service context for the Items, not the main service
851             //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
852             String parentcsid = lookupParentCSID(parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
853
854             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate);
855             ctx.setResourceMap(resourceMap);
856             String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx);
857
858             // We omit the parentShortId, only needed when doing a create...
859             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
860             ctx.setUriInfo(ui);
861             getRepositoryClient(ctx).update(ctx, itemcsid, handler);
862             result = ctx.getOutput();
863
864         } catch (Exception e) {
865             throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
866         }
867         return result.getBytes();
868     }
869
870     /**
871      * Delete authorityItem.
872      * 
873      * @param parentcsid the parentcsid
874      * @param itemcsid the itemcsid
875      * 
876      * @return the response
877      */
878     @DELETE
879     @Path("{csid}/items/{itemcsid}")
880     public Response deleteAuthorityItem(
881             @PathParam("csid") String parentcsid,
882             @PathParam("itemcsid") String itemcsid) {
883         //try{
884         if (logger.isDebugEnabled()) {
885             logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
886         }
887         try {
888             ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
889             ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
890             //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
891             // }catch (Throwable t){
892             //    System.out.println("ERROR in setting up DELETE: "+t);
893             // }
894             // try {
895             // Note that we have to create the service context for the Items, not the main service
896             ServiceContext ctx = createServiceContext(getItemServiceName());
897             DocumentHandler handler = createDocumentHandler(ctx);
898             getRepositoryClient(ctx).delete(ctx, itemcsid, handler);
899             return Response.status(HttpResponseCodes.SC_OK).build();
900         } catch (Exception e) {
901             throw bigReThrow(e, ServiceMessages.DELETE_FAILED + "  itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
902         }
903     }
904     public final static String hierarchy = "hierarchy";
905
906     @GET
907     @Path("{csid}/items/{itemcsid}/" + hierarchy)
908     @Produces("application/xml")
909     public String getHierarchy(@PathParam("csid") String csid,
910             @PathParam("itemcsid") String itemcsid,
911             @Context UriInfo ui) throws Exception {
912         try {
913             // 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...?
914             String calledUri = ui.getPath();
915             String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
916             ServiceContext ctx = createServiceContext(getItemServiceName());
917             ctx.setUriInfo(ui);
918             String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
919             if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
920                 return Hierarchy.surface(ctx, itemcsid, uri);
921             } else {
922                 return Hierarchy.dive(ctx, itemcsid, uri);
923             }
924         } catch (Exception e) {
925             throw bigReThrow(e, "Error showing hierarchy", itemcsid);
926         }
927     }
928 }