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