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