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