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