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