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