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