]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
ed28be1f3604cfab3eb9cc8c2abccb3cfeddd508
[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 java.util.List;
27 import java.util.Map;
28
29 import javax.ws.rs.Consumes;
30 import javax.ws.rs.DELETE;
31 import javax.ws.rs.GET;
32 import javax.ws.rs.POST;
33 import javax.ws.rs.PUT;
34 import javax.ws.rs.Path;
35 import javax.ws.rs.PathParam;
36 import javax.ws.rs.Produces;
37 import javax.ws.rs.core.Context;
38 import javax.ws.rs.core.MultivaluedMap;
39 import javax.ws.rs.core.Request;
40 import javax.ws.rs.core.Response;
41 import javax.ws.rs.core.UriBuilder;
42 import javax.ws.rs.core.UriInfo;
43
44 import org.collectionspace.services.client.IClientQueryParams;
45 import org.collectionspace.services.client.IQueryManager;
46 import org.collectionspace.services.client.PoxPayloadIn;
47 import org.collectionspace.services.client.PoxPayloadOut;
48 import org.collectionspace.services.client.workflow.WorkflowClient;
49 import org.collectionspace.services.common.CSWebApplicationException;
50 import org.collectionspace.services.common.NuxeoBasedResource;
51 import org.collectionspace.services.common.ResourceMap;
52 import org.collectionspace.services.common.ServiceMain;
53 import org.collectionspace.services.common.ServiceMessages;
54 import org.collectionspace.services.common.StoredValuesUriTemplate;
55 import org.collectionspace.services.common.UriTemplateFactory;
56 import org.collectionspace.services.common.UriTemplateRegistry;
57 import org.collectionspace.services.common.UriTemplateRegistryKey;
58 import org.collectionspace.services.common.api.RefName;
59 import org.collectionspace.services.common.api.Tools;
60 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
61 import org.collectionspace.services.common.authorityref.AuthorityRefList;
62 import org.collectionspace.services.common.context.JaxRsContext;
63 import org.collectionspace.services.common.context.MultipartServiceContext;
64 import org.collectionspace.services.common.context.RemoteServiceContext;
65 import org.collectionspace.services.common.context.ServiceBindingUtils;
66 import org.collectionspace.services.common.context.ServiceContext;
67 import org.collectionspace.services.common.document.DocumentException;
68 import org.collectionspace.services.common.document.DocumentFilter;
69 import org.collectionspace.services.common.document.DocumentHandler;
70 import org.collectionspace.services.common.document.DocumentNotFoundException;
71 import org.collectionspace.services.common.document.DocumentWrapper;
72 import org.collectionspace.services.common.document.Hierarchy;
73 import org.collectionspace.services.common.query.QueryManager;
74 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityDocumentModelHandler;
75 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityItemDocumentModelHandler;
76 import org.collectionspace.services.common.workflow.service.nuxeo.WorkflowDocumentModelHandler;
77 import org.collectionspace.services.config.ClientType;
78 import org.collectionspace.services.jaxb.AbstractCommonList;
79 import org.collectionspace.services.lifecycle.TransitionDef;
80 import org.collectionspace.services.nuxeo.client.java.DocumentModelHandler;
81 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
82 import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl;
83 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
84 import org.collectionspace.services.workflow.WorkflowCommon;
85 import org.jboss.resteasy.util.HttpResponseCodes;
86 import org.nuxeo.ecm.core.api.DocumentModel;
87 import org.nuxeo.ecm.core.api.DocumentModelList;
88 import org.slf4j.Logger;
89 import org.slf4j.LoggerFactory;
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 NuxeoBasedResource {
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     public 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 CSWebApplicationException {
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 CSWebApplicationException(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<?, AbstractCommonList, DocumentModel, DocumentModelList> 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.Authority.buildAuthority(ctx.getTenantName(),
262                 ctx.getServiceName(), 
263                 null,   // Only use shortId form!!!
264                 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,
275                         String op, UriInfo uriInfo) throws Exception {
276                 CsidAndShortIdentifier tempResult = lookupParentCSIDAndShortIdentifer(
277                                 parentspecifier, method, op, uriInfo);
278                 return tempResult.CSID;
279         }
280
281     private CsidAndShortIdentifier lookupParentCSIDAndShortIdentifer(
282                 String parentspecifier,
283                 String method,
284                 String op,
285                 UriInfo uriInfo)
286             throws Exception {
287         CsidAndShortIdentifier result = new CsidAndShortIdentifier();
288         Specifier parentSpec = getSpecifier(parentspecifier, method, op);
289         // Note that we have to create the service context for the Items, not the main service
290         String parentcsid;
291         String parentShortIdentifier;
292         if (parentSpec.form == SpecifierForm.CSID) {
293             parentShortIdentifier = null;
294             parentcsid = parentSpec.value;
295             // Uncomment when app layer is ready to integrate
296             // Uncommented since refNames are currently only generated if not present - ADR CSPACE-3178
297             parentShortIdentifier = FETCH_SHORT_ID;
298         } else {
299             parentShortIdentifier = parentSpec.value;
300             String whereClause = buildWhereForAuthByName(parentSpec.value);
301             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getServiceName(), uriInfo);
302             parentcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause); //FIXME: REM - If the parent has been soft-deleted, should we be looking for the item?
303         }
304         result.CSID = parentcsid;
305         result.shortIdentifier = parentShortIdentifier;
306         return result;
307     }
308
309     public String lookupItemCSID(String itemspecifier, String parentcsid, String method, String op, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx)
310             throws DocumentException {
311         String itemcsid;
312         Specifier itemSpec = getSpecifier(itemspecifier, method, op);
313         if (itemSpec.form == SpecifierForm.CSID) {
314             itemcsid = itemSpec.value;
315         } else {
316             String itemWhereClause = buildWhereForAuthItemByName(itemSpec.value, parentcsid);
317             itemcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, itemWhereClause); //FIXME: REM - Should we be looking for the 'wf_deleted' query param and filtering on it?
318         }
319         return itemcsid;
320     }
321
322     /*
323      * Generally, callers will first call RefName.AuthorityItem.parse with a refName, and then 
324      * use the returned item.inAuthority.resource and a resourceMap to get a service-specific
325      * Resource. They then call this method on that resource.
326      */
327     @Override
328         public DocumentModel getDocModelForAuthorityItem(CoreSessionInterface repoSession, RefName.AuthorityItem item) 
329                         throws Exception, DocumentNotFoundException {
330         if(item == null) {
331                 return null;
332         }
333         String whereClause = buildWhereForAuthByName(item.getParentShortIdentifier());
334         // Ensure we have the right context.
335         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(item.inAuthority.resource);
336         
337         // HACK - this really must be moved to the doc handler, not here. No Nuxeo specific stuff here!
338         RepositoryJavaClientImpl client = (RepositoryJavaClientImpl)getRepositoryClient(ctx);
339         String parentcsid = client.findDocCSID(repoSession, ctx, whereClause);
340
341         String itemWhereClause = buildWhereForAuthItemByName(item.getShortIdentifier(), parentcsid);
342         ctx = createServiceContext(getItemServiceName());
343         DocumentWrapper<DocumentModel> docWrapper = client.findDoc(repoSession, ctx, itemWhereClause);
344         DocumentModel docModel = docWrapper.getWrappedObject();
345         return docModel;
346     }
347
348
349     @POST                                                                                                       //FIXME: REM - 5/1/2012 - We can probably remove this method.
350     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.
351         try {
352             PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
353             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
354             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
355             String csid = getRepositoryClient(ctx).create(ctx, handler);
356             UriBuilder path = UriBuilder.fromResource(resourceClass);
357             path.path("" + csid);
358             Response response = Response.created(path.build()).build();
359             return response;
360         } catch (Exception e) {
361             throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
362         }
363     }
364
365     protected String buildWhereForAuthByName(String name) {
366         return authorityCommonSchemaName
367                 + ":" + AuthorityJAXBSchema.SHORT_IDENTIFIER
368                 + "='" + name + "'";
369     }
370
371     protected String buildWhereForAuthItemByName(String name, String parentcsid) {
372         return authorityItemCommonSchemaName
373                 + ":" + AuthorityItemJAXBSchema.SHORT_IDENTIFIER
374                 + "='" + name + "' AND "
375                 + authorityItemCommonSchemaName + ":"
376                 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
377                 + "'" + parentcsid + "'";
378     }
379
380     /**
381      * Gets the authority.
382      * 
383      * @param specifier either a CSID or one of the urn forms
384      * 
385      * @return the authority
386      */
387     @GET
388     @Path("{csid}")
389     @Override
390     public byte[] get(
391             @Context Request request,
392             @Context UriInfo ui,
393             @PathParam("csid") String specifier) {
394         PoxPayloadOut result = null;
395         try {
396             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
397             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
398
399             Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
400             if (spec.form == SpecifierForm.CSID) {
401                 if (logger.isDebugEnabled()) {
402                     logger.debug("getAuthority with csid=" + spec.value);
403                 }
404                 getRepositoryClient(ctx).get(ctx, spec.value, handler);
405             } else {
406                 String whereClause = buildWhereForAuthByName(spec.value);
407                 DocumentFilter myFilter = new DocumentFilter(whereClause, 0, 1);
408                 handler.setDocumentFilter(myFilter);
409                 getRepositoryClient(ctx).get(ctx, handler);
410             }
411             result = ctx.getOutput();
412
413         } catch (Exception e) {
414             throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
415         }
416
417         if (result == null) {
418             Response response = Response.status(Response.Status.NOT_FOUND).entity(
419                     "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type(
420                     "text/plain").build();
421             throw new CSWebApplicationException(response);
422         }
423
424         return result.getBytes();
425     }
426
427     /**
428      * Finds and populates the authority list.
429      * 
430      * @param ui the ui
431      * 
432      * @return the authority list
433      */
434     @GET
435     @Produces("application/xml")
436     public AbstractCommonList getAuthorityList(@Context UriInfo uriInfo) { //FIXME - REM 5/3/2012 - This is not reachable from the JAX-RS dispatcher.  Instead the equivalent method in ResourceBase is getting called.
437         AbstractCommonList result = null;
438         
439         try {
440             MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
441             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(uriInfo);
442             
443             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
444             DocumentFilter myFilter = handler.getDocumentFilter();
445             // Need to make the default sort order for authority items
446             // be on the displayName field
447             String sortBy = queryParams.getFirst(IClientQueryParams.ORDER_BY_PARAM);
448             if (sortBy == null || sortBy.isEmpty()) {
449                 String qualifiedDisplayNameField = authorityCommonSchemaName + ":"
450                         + AuthorityItemJAXBSchema.DISPLAY_NAME;
451                 myFilter.setOrderByClause(qualifiedDisplayNameField);
452             }
453             String nameQ = queryParams.getFirst("refName");
454             if (nameQ != null) {
455                 myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'");
456             }
457             getRepositoryClient(ctx).getFiltered(ctx, handler);
458             result = handler.getCommonPartList();
459         } catch (Exception e) {
460             throw bigReThrow(e, ServiceMessages.GET_FAILED);
461         }
462         
463         return result;
464     }
465     
466     /**
467      * Update authority.
468      *
469      * @param specifier the csid or id
470      *
471      * @return the multipart output
472      */
473     @PUT
474     @Path("{csid}")
475     public byte[] updateAuthority(
476             @PathParam("csid") String specifier,
477             String xmlPayload) {
478         PoxPayloadOut result = null;
479         try {
480             PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
481             Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
482             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
483             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
484             String csid;
485             if (spec.form == SpecifierForm.CSID) {
486                 csid = spec.value;
487             } else {
488                 String whereClause = buildWhereForAuthByName(spec.value);
489                 csid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause);
490             }
491             getRepositoryClient(ctx).update(ctx, csid, handler);
492             result = ctx.getOutput();
493         } catch (Exception e) {
494             throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
495         }
496         return result.getBytes();
497     }
498
499     /**
500      * Delete authority.
501      * 
502      * @param csid the csid
503      * 
504      * @return the response
505      */
506     @DELETE
507     @Path("{csid}")
508     public Response deleteAuthority(@PathParam("csid") String csid) {
509         if (logger.isDebugEnabled()) {
510             logger.debug("deleteAuthority with csid=" + csid);
511         }
512         try {
513             ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid");
514             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
515             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
516             getRepositoryClient(ctx).delete(ctx, csid, handler);
517             return Response.status(HttpResponseCodes.SC_OK).build();
518         } catch (Exception e) {
519             throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid);
520         }
521     }
522
523     /*************************************************************************
524      * Create an AuthorityItem - this is a sub-resource of Authority
525      * @param specifier either a CSID or one of the urn forms
526      * @return Authority item response
527      *************************************************************************/
528     @POST
529     @Path("{csid}/items")
530     public Response createAuthorityItem(
531                 @Context ResourceMap resourceMap,
532                 @Context UriInfo uriInfo, 
533                 @PathParam("csid") String parentspecifier,
534                 String xmlPayload) {
535         Response result = null;
536         
537         try {
538             PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
539             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), input, resourceMap, uriInfo);
540
541             // Note: must have the parentShortId, to do the create.
542             CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(parentspecifier, "createAuthorityItem", "CREATE_ITEM", null);
543             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = 
544                 createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
545             String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
546             UriBuilder path = UriBuilder.fromResource(resourceClass);
547             path.path(parent.CSID + "/items/" + itemcsid);
548             result = Response.created(path.build()).build();
549         } catch (Exception e) {
550             throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
551         }
552         
553         return result;
554     }
555
556     @GET
557     @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
558     public byte[] getItemWorkflow(
559             @PathParam("csid") String csid,
560             @PathParam("itemcsid") String itemcsid) {
561         PoxPayloadOut result = null;
562
563         try {
564             ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
565             String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
566
567             MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
568             WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
569             ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
570             getRepositoryClient(ctx).get(ctx, itemcsid, handler);
571             result = ctx.getOutput();
572         } catch (Exception e) {
573             throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
574         }
575         return result.getBytes();
576     }
577
578     //FIXME: This method is almost identical to the method org.collectionspace.services.common.updateWorkflowWithTransition() so
579     // they should be consolidated -be DRY (don't repeat yourself).
580     @PUT
581     @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH + "/{transition}")
582     public byte[] updateItemWorkflowWithTransition(
583             @PathParam("csid") String csid,
584             @PathParam("itemcsid") String itemcsid,
585             @PathParam("transition") String transition) {
586         PoxPayloadOut result = null;
587         
588         try {
589                 //
590                 // Create an empty workflow_commons input part and set it into a new "workflow" sub-resource context
591                 PoxPayloadIn input = new PoxPayloadIn(WorkflowClient.SERVICE_PAYLOAD_NAME, new WorkflowCommon(), 
592                                 WorkflowClient.SERVICE_COMMONPART_NAME);
593             MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, input);
594
595             // Create a service context and document handler for the parent resource.
596             ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
597             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> parentDocHandler = this.createDocumentHandler(parentCtx);
598             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
599
600             // When looking for the document, we need to use the parent's workspace name -not the "workflow" workspace name
601             String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
602             ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
603             
604                 // Get the type of transition we're being asked to make and store it as a context parameter -used by the workflow document handler
605             TransitionDef transitionDef = getTransitionDef(parentCtx, transition);
606             ctx.setProperty(WorkflowClient.TRANSITION_ID, transitionDef);
607             
608             WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
609             getRepositoryClient(ctx).update(ctx, itemcsid, handler);
610             result = ctx.getOutput();
611         } catch (Exception e) {
612             throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
613         }
614         
615         return result.getBytes();
616     }
617
618     /**
619      * Gets the authority item.
620      * 
621      * @param parentspecifier either a CSID or one of the urn forms
622      * @param itemspecifier either a CSID or one of the urn forms
623      * 
624      * @return the authority item
625      */
626     @GET
627     @Path("{csid}/items/{itemcsid}")
628     public byte[] getAuthorityItem(
629             @Context Request request,
630             @Context UriInfo uriInfo,
631                 @Context ResourceMap resourceMap,            
632             @PathParam("csid") String parentspecifier,
633             @PathParam("itemcsid") String itemspecifier) {
634         PoxPayloadOut result = null;
635         try {
636             String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", uriInfo);
637
638             RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = 
639                 (RemoteServiceContext<PoxPayloadIn, PoxPayloadOut>) createServiceContext(getItemServiceName(), resourceMap, uriInfo);
640             
641             JaxRsContext jaxRsContext = new JaxRsContext(request, uriInfo); // REM - Why are we setting this?  Who is using the getter?
642             ctx.setJaxRsContext(jaxRsContext);
643
644             // We omit the parentShortId, only needed when doing a create...
645             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createItemDocumentHandler(ctx, parentcsid, null);
646
647             Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
648             if (itemSpec.form == SpecifierForm.CSID) {
649                 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
650             } else {
651                 String itemWhereClause =
652                         buildWhereForAuthItemByName(itemSpec.value, parentcsid);
653                 DocumentFilter myFilter = new DocumentFilter(itemWhereClause, 0, 1);
654                 handler.setDocumentFilter(myFilter);
655                 getRepositoryClient(ctx).get(ctx, handler);
656             }
657             // TODO should we assert that the item is in the passed vocab?
658             result = ctx.getOutput();
659         } catch (Exception e) {
660             throw bigReThrow(e, ServiceMessages.GET_FAILED);
661         }
662         
663         if (result == null) {
664             Response response = Response.status(Response.Status.NOT_FOUND).entity(
665                     "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
666                     "text/plain").build();
667             throw new CSWebApplicationException(response);
668         }
669         
670         return result.getBytes();
671     }
672
673     /*
674      * Most of the authority child classes will/should use this implementation.  However, the Vocabulary service's item schema is
675      * different enough that it will have to override this method in it's resource class.
676      */
677     @Override
678         protected String getOrderByField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
679                 String result = null;
680
681                 result = NuxeoUtils.getPrimaryElPathPropertyName(
682                                 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
683                                 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
684
685                 return result;
686         }
687         
688     @Override
689         protected String getPartialTermMatchField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
690                 String result = null;
691                 
692                 result = NuxeoUtils.getMultiElPathPropertyName(
693                                 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
694                                 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
695
696                 return result;
697         }
698     
699     /**
700      * Gets the authorityItem list for the specified authority
701      * If partialPerm is specified, keywords will be ignored.
702      * 
703      * @param specifier either a CSID or one of the urn forms
704      * @param partialTerm if non-null, matches partial terms
705      * @param keywords if non-null, matches terms in the keyword index for items
706      * @param ui passed to include additional parameters, like pagination controls
707      * 
708      * @return the authorityItem list
709      */
710     @GET
711     @Path("{csid}/items")
712     @Produces("application/xml")
713     public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
714             @Context UriInfo uriInfo) {
715         AbstractCommonList result = null;
716         
717         try {
718             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
719             MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
720             
721             String orderBy = queryParams.getFirst(IClientQueryParams.ORDER_BY_PARAM);
722             String termStatus = queryParams.getFirst(SEARCH_TYPE_TERMSTATUS);
723             String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
724             String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
725             String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
726
727             // For the wildcard case, parentcsid is null, but docHandler will deal with this.
728             // We omit the parentShortId, only needed when doing a create...
729             String parentcsid = PARENT_WILDCARD.equals(specifier) ? null :
730                                 lookupParentCSID(specifier, "getAuthorityItemList", "LIST", uriInfo);
731             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler =
732                 createItemDocumentHandler(ctx, parentcsid, null);
733             
734             DocumentFilter myFilter = handler.getDocumentFilter();
735             // If we are not wildcarding the parent, add a restriction
736             if (parentcsid != null) {
737                     myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
738                             + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
739                             + "'" + parentcsid + "'",
740                             IQueryManager.SEARCH_QUALIFIER_AND);
741             }
742
743             if (Tools.notBlank(termStatus)) {
744                 // Start with the qualified termStatus field
745                 String qualifiedTermStatusField = authorityItemCommonSchemaName + ":"
746                         + AuthorityItemJAXBSchema.TERM_STATUS;
747                 String[] filterTerms = termStatus.trim().split("\\|");
748                 String tsClause = QueryManager.createWhereClauseToFilterFromStringList(qualifiedTermStatusField, filterTerms, IQueryManager.FILTER_EXCLUDE);
749                 myFilter.appendWhereClause(tsClause, IQueryManager.SEARCH_QUALIFIER_AND);
750             }
751
752             result = search(ctx, handler, uriInfo, orderBy, keywords, advancedSearch, partialTerm);            
753         } catch (Exception e) {
754             throw bigReThrow(e, ServiceMessages.LIST_FAILED);
755         }
756         
757         return result;
758     }
759
760     /**
761      * @return the name of the property used to specify references for items in this type of
762      * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
763      * Some types (like Vocabulary) use a separate property.
764      */
765     protected String getRefPropName() {
766         return ServiceBindingUtils.AUTH_REF_PROP;
767     }
768     
769     /**
770      * Gets the entities referencing this Authority item instance. The service type
771      * can be passed as a query param "type", and must match a configured type
772      * for the service bindings. If not set, the type defaults to
773      * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
774      *
775      * @param parentspecifier either a CSID or one of the urn forms
776      * @param itemspecifier either a CSID or one of the urn forms
777      * @param ui the ui
778      * 
779      * @return the info for the referencing objects
780      */
781     @GET
782     @Path("{csid}/items/{itemcsid}/refObjs")
783     @Produces("application/xml")
784     public AuthorityRefDocList getReferencingObjects(
785             @PathParam("csid") String parentspecifier,
786             @PathParam("itemcsid") String itemspecifier,
787             @Context UriTemplateRegistry uriTemplateRegistry,
788             @Context UriInfo uriInfo) {
789         AuthorityRefDocList authRefDocList = null;
790         try {
791             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
792             MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
793
794             String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", uriInfo);
795             String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
796
797             List<String> serviceTypes = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
798             if(serviceTypes == null || serviceTypes.isEmpty()) {
799                 serviceTypes = ServiceBindingUtils.getCommonServiceTypes(true); //CSPACE-5359: Should now include objects, procedures, and authorities
800             }
801             
802             // Note that we have to create the service context for the Items, not the main service
803             // We omit the parentShortId, only needed when doing a create...
804             AuthorityItemDocumentModelHandler<?> handler = (AuthorityItemDocumentModelHandler<?>)
805                                                                                                 createItemDocumentHandler(ctx, parentcsid, null);
806
807             authRefDocList = handler.getReferencingObjects(ctx, uriTemplateRegistry, serviceTypes, getRefPropName(), itemcsid);
808         } catch (Exception e) {
809             throw bigReThrow(e, ServiceMessages.GET_FAILED);
810         }
811         if (authRefDocList == null) {
812             Response response = Response.status(Response.Status.NOT_FOUND).entity(
813                     "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
814                     "text/plain").build();
815             throw new CSWebApplicationException(response);
816         }
817         return authRefDocList;
818     }
819
820     /**
821      * Gets the authority terms used in the indicated Authority item.
822      *
823      * @param parentspecifier either a CSID or one of the urn forms
824      * @param itemspecifier either a CSID or one of the urn forms
825      * @param ui passed to include additional parameters, like pagination controls
826      *
827      * @return the authority refs for the Authority item.
828      */
829     @GET
830     @Path("{csid}/items/{itemcsid}/authorityrefs")
831     @Produces("application/xml")
832     public AuthorityRefList getAuthorityItemAuthorityRefs(
833             @PathParam("csid") String parentspecifier,
834             @PathParam("itemcsid") String itemspecifier,
835             @Context UriInfo uriInfo) {
836         AuthorityRefList authRefList = null;
837         try {
838             // Note that we have to create the service context for the Items, not the main service
839             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
840             MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
841             String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", uriInfo);
842             // We omit the parentShortId, only needed when doing a create...
843             DocumentModelHandler<?, AbstractCommonList> handler =
844                     (DocumentModelHandler<?, AbstractCommonList>)createItemDocumentHandler(ctx, parentcsid, null /*no parent short ID*/);
845
846             String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
847
848             List<RefNameServiceUtils.AuthRefConfigInfo> authRefsInfo = RefNameServiceUtils.getConfiguredAuthorityRefs(ctx);
849             authRefList = handler.getAuthorityRefs(itemcsid, authRefsInfo);
850         } catch (Exception e) {
851             throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
852         }
853         return authRefList;
854     }
855
856     /**
857      * Update authorityItem.
858      * 
859      * @param parentspecifier either a CSID or one of the urn forms
860      * @param itemspecifier either a CSID or one of the urn forms
861      *
862      * @return the multipart output
863      */
864     @PUT
865     @Path("{csid}/items/{itemcsid}")
866     public byte[] updateAuthorityItem(
867                 @Context ResourceMap resourceMap, 
868             @Context UriInfo uriInfo,
869             @PathParam("csid") String parentspecifier,
870             @PathParam("itemcsid") String itemspecifier,
871             String xmlPayload) {
872         PoxPayloadOut result = null;
873         try {
874             PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
875             // Note that we have to create the service context for the Items, not the main service
876             // 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
877             CsidAndShortIdentifier csidAndShortId = lookupParentCSIDAndShortIdentifer(parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
878             String parentcsid = csidAndShortId.CSID;
879             String parentShortId = csidAndShortId.shortIdentifier;
880
881             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate, resourceMap, uriInfo);
882             String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx);
883
884             // We omit the parentShortId, only needed when doing a create...
885             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createItemDocumentHandler(ctx, parentcsid, parentShortId);
886             getRepositoryClient(ctx).update(ctx, itemcsid, handler);
887             result = ctx.getOutput();
888
889         } catch (Exception e) {
890             throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
891         }
892         return result.getBytes();
893     }
894
895     /**
896      * Delete authorityItem.
897      * 
898      * @param parentcsid the parentcsid
899      * @param itemcsid the itemcsid
900      * 
901      * @return the response
902      */
903     @DELETE
904     @Path("{csid}/items/{itemcsid}")
905     public Response deleteAuthorityItem(
906             @PathParam("csid") String parentcsid,
907             @PathParam("itemcsid") String itemcsid) {
908         //try{
909         if (logger.isDebugEnabled()) {
910             logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
911         }
912         try {
913             ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
914             ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
915             //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
916             // }catch (Throwable t){
917             //    System.out.println("ERROR in setting up DELETE: "+t);
918             // }
919             // try {
920             // Note that we have to create the service context for the Items, not the main service
921             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName());
922             DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
923             getRepositoryClient(ctx).delete(ctx, itemcsid, handler);
924             return Response.status(HttpResponseCodes.SC_OK).build();
925         } catch (Exception e) {
926             throw bigReThrow(e, ServiceMessages.DELETE_FAILED + "  itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
927         }
928     }
929     public final static String hierarchy = "hierarchy";
930
931     @GET
932     @Path("{csid}/items/{itemcsid}/" + hierarchy)
933     @Produces("application/xml")
934     public String getHierarchy(@PathParam("csid") String csid,
935             @PathParam("itemcsid") String itemcsid,
936             @Context UriInfo ui) throws Exception {
937         try {
938             // 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...?
939             String calledUri = ui.getPath();
940             String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
941             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), ui);
942             ctx.setUriInfo(ui);
943             String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
944             if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
945                 return Hierarchy.surface(ctx, itemcsid, uri);
946             } else {
947                 return Hierarchy.dive(ctx, itemcsid, uri);
948             }
949         } catch (Exception e) {
950             throw bigReThrow(e, "Error showing hierarchy", itemcsid);
951         }
952     }
953     
954     protected String getItemDocType(String tenantId) {
955         return getDocType(tenantId, getItemServiceName());
956     }
957         
958     /**
959      * Returns a UriRegistry entry: a map of tenant-qualified URI templates
960      * for the current resource, for all tenants
961      * 
962      * @return a map of URI templates for the current resource, for all tenants
963      */
964     @Override
965     public Map<UriTemplateRegistryKey,StoredValuesUriTemplate> getUriRegistryEntries() {
966         Map<UriTemplateRegistryKey,StoredValuesUriTemplate> uriRegistryEntriesMap =
967                 super.getUriRegistryEntries();
968         List<String> tenantIds = getTenantBindingsReader().getTenantIds();
969         for (String tenantId : tenantIds) {
970                 uriRegistryEntriesMap.putAll(getUriRegistryEntries(tenantId, getItemDocType(tenantId), UriTemplateFactory.ITEM));
971         }
972         return uriRegistryEntriesMap;
973     }
974   
975 }