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