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