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