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