]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
0b3c219e072e031523e27085574dcabb9eadb493
[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             // Need to make the default sort order for authority items
383             // be on the displayName field
384             String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
385             if (sortBy == null || sortBy.isEmpty()) {
386                 String qualifiedDisplayNameField = authorityCommonSchemaName + ":"
387                         + AuthorityItemJAXBSchema.DISPLAY_NAME;
388                 myFilter.setOrderByClause(qualifiedDisplayNameField);
389             }
390             String nameQ = queryParams.getFirst("refName");
391             if (nameQ != null) {
392                 myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'");
393             }
394             getRepositoryClient(ctx).getFiltered(ctx, handler);
395             return (AbstractCommonList) handler.getCommonPartList();
396         } catch (Exception e) {
397             throw bigReThrow(e, ServiceMessages.GET_FAILED);
398         }
399     }
400
401     /**
402      * Update authority.
403      *
404      * @param specifier the csid or id
405      *
406      * @return the multipart output
407      */
408     @PUT
409     @Path("{csid}")
410     public byte[] updateAuthority(
411             @PathParam("csid") String specifier,
412             String xmlPayload) {
413         PoxPayloadOut result = null;
414         try {
415             PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
416             Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
417             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
418             DocumentHandler handler = createDocumentHandler(ctx);
419             String csid;
420             if (spec.form == SpecifierForm.CSID) {
421                 csid = spec.value;
422             } else {
423                 String whereClause = buildWhereForAuthByName(spec.value);
424                 csid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause);
425             }
426             getRepositoryClient(ctx).update(ctx, csid, handler);
427             result = ctx.getOutput();
428         } catch (Exception e) {
429             throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
430         }
431         return result.getBytes();
432     }
433
434     /**
435      * Delete authority.
436      * 
437      * @param csid the csid
438      * 
439      * @return the response
440      */
441     @DELETE
442     @Path("{csid}")
443     public Response deleteAuthority(@PathParam("csid") String csid) {
444         if (logger.isDebugEnabled()) {
445             logger.debug("deleteAuthority with csid=" + csid);
446         }
447         try {
448             ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid");
449             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
450             getRepositoryClient(ctx).delete(ctx, csid);
451             return Response.status(HttpResponseCodes.SC_OK).build();
452         } catch (Exception e) {
453             throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid);
454         }
455     }
456
457     /*************************************************************************
458      * Create an AuthorityItem - this is a sub-resource of Authority
459      * @param specifier either a CSID or one of the urn forms
460      * @return Authority item response
461      *************************************************************************/
462     @POST
463     @Path("{csid}/items")
464     public Response createAuthorityItem(@Context UriInfo ui, @PathParam("csid") String specifier, String xmlPayload) {
465         try {
466             PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
467             ServiceContext ctx = createServiceContext(getItemServiceName(), input);
468             ctx.setUriInfo(ui);    //Laramie
469
470             // Note: must have the parentShortId, to do the create.
471             CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(specifier, "createAuthorityItem", "CREATE_ITEM", null);
472             DocumentHandler handler = createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
473             String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
474             UriBuilder path = UriBuilder.fromResource(resourceClass);
475             path.path(parent.CSID + "/items/" + itemcsid);
476             Response response = Response.created(path.build()).build();
477             return response;
478         } catch (Exception e) {
479             throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
480         }
481     }
482
483     @GET
484     @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
485     public byte[] getItemWorkflow(
486             @PathParam("csid") String csid,
487             @PathParam("itemcsid") String itemcsid) {
488         PoxPayloadOut result = null;
489
490         try {
491             ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
492             String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
493
494             MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
495             WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
496             ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
497             getRepositoryClient(ctx).get(ctx, itemcsid, handler);
498             result = ctx.getOutput();
499         } catch (Exception e) {
500             throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
501         }
502         return result.getBytes();
503     }
504
505     @PUT
506     @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
507     public byte[] updateWorkflow(
508             @PathParam("csid") String csid,
509             @PathParam("itemcsid") String itemcsid,
510             String xmlPayload) {
511         PoxPayloadOut result = null;
512         try {
513             ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
514             String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
515
516             PoxPayloadIn workflowUpdate = new PoxPayloadIn(xmlPayload);
517             MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, workflowUpdate);
518             WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
519             ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
520             getRepositoryClient(ctx).update(ctx, itemcsid, handler);
521             result = ctx.getOutput();
522         } catch (Exception e) {
523             throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
524         }
525         return result.getBytes();
526     }
527
528     /**
529      * Gets the authority item.
530      * 
531      * @param parentspecifier either a CSID or one of the urn forms
532      * @param itemspecifier either a CSID or one of the urn forms
533      * 
534      * @return the authority item
535      */
536     @GET
537     @Path("{csid}/items/{itemcsid}")
538     public byte[] getAuthorityItem(
539             @Context Request request,
540             @Context UriInfo ui,
541             @PathParam("csid") String parentspecifier,
542             @PathParam("itemcsid") String itemspecifier) {
543         PoxPayloadOut result = null;
544         try {
545             JaxRsContext jaxRsContext = new JaxRsContext(request, ui);
546             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
547             String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", queryParams);
548
549             RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
550             ctx = (RemoteServiceContext) createServiceContext(getItemServiceName(), queryParams);
551             ctx.setJaxRsContext(jaxRsContext);
552
553             ctx.setUriInfo(ui); //ARG!   must pass this or subsequent calls will not have a ui.
554
555             // We omit the parentShortId, only needed when doing a create...
556             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
557
558             Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
559             if (itemSpec.form == SpecifierForm.CSID) {
560                 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
561             } else {
562                 String itemWhereClause =
563                         buildWhereForAuthItemByName(itemSpec.value, parentcsid);
564                 DocumentFilter myFilter = new DocumentFilter(itemWhereClause, 0, 1);
565                 handler.setDocumentFilter(myFilter);
566                 getRepositoryClient(ctx).get(ctx, handler);
567             }
568             // TODO should we assert that the item is in the passed vocab?
569             result = ctx.getOutput();
570         } catch (Exception e) {
571             throw bigReThrow(e, ServiceMessages.GET_FAILED);
572         }
573         if (result == null) {
574             Response response = Response.status(Response.Status.NOT_FOUND).entity(
575                     "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
576                     "text/plain").build();
577             throw new WebApplicationException(response);
578         }
579         return result.getBytes();
580     }
581
582     /**
583      * Gets the authorityItem list for the specified authority
584      * If partialPerm is specified, keywords will be ignored.
585      * 
586      * @param specifier either a CSID or one of the urn forms
587      * @param partialTerm if non-null, matches partial terms
588      * @param keywords if non-null, matches terms in the keyword index for items
589      * @param ui passed to include additional parameters, like pagination controls
590      * 
591      * @return the authorityItem list
592      */
593     @GET
594     @Path("{csid}/items")
595     @Produces("application/xml")
596     public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
597             @Context UriInfo ui) {
598         try {
599             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
600             String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
601             String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
602             String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
603
604             String qualifiedDisplayNameField = authorityItemCommonSchemaName + ":"
605                     + AuthorityItemJAXBSchema.DISPLAY_NAME;
606
607             // Note that docType defaults to the ServiceName, so we're fine with that.
608             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
609
610             String parentcsid = lookupParentCSID(specifier, "getAuthorityItemList", "LIST", queryParams);
611
612             ctx = createServiceContext(getItemServiceName(), queryParams);
613             // We omit the parentShortId, only needed when doing a create...
614             DocumentHandler handler = createItemDocumentHandler(ctx,
615                     parentcsid, null);
616             DocumentFilter myFilter = handler.getDocumentFilter();
617             // Need to make the default sort order for authority items
618             // be on the displayName field
619             String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
620             if (sortBy == null || sortBy.isEmpty()) {
621                 myFilter.setOrderByClause(qualifiedDisplayNameField);
622             }
623
624             myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
625                     + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
626                     + "'" + parentcsid + "'",
627                     IQueryManager.SEARCH_QUALIFIER_AND);
628
629             // AND vocabularyitems_common:displayName LIKE '%partialTerm%'
630             // NOTE: Partial terms searches are mutually exclusive to keyword and advanced-search, but
631             // the PT query param trumps the KW and AS query params.
632             if (partialTerm != null && !partialTerm.isEmpty()) {
633                 String ptClause = QueryManager.createWhereClauseForPartialMatch(
634                         qualifiedDisplayNameField, partialTerm);
635                 myFilter.appendWhereClause(ptClause, IQueryManager.SEARCH_QUALIFIER_AND);
636             } else if (keywords != null || advancedSearch != null) {
637 //                              String kwdClause = QueryManager.createWhereClauseFromKeywords(keywords);
638 //                              myFilter.appendWhereClause(kwdClause, IQueryManager.SEARCH_QUALIFIER_AND);
639                 return search(ctx, handler, queryParams, keywords, advancedSearch);
640             }
641             if (logger.isDebugEnabled()) {
642                 logger.debug("getAuthorityItemList filtered WHERE clause: "
643                         + myFilter.getWhereClause());
644             }
645             getRepositoryClient(ctx).getFiltered(ctx, handler);
646             return (AbstractCommonList) handler.getCommonPartList();
647         } catch (Exception e) {
648             throw bigReThrow(e, ServiceMessages.LIST_FAILED);
649         }
650     }
651
652     /**
653      * Gets the entities referencing this Authority item instance. The service type
654      * can be passed as a query param "type", and must match a configured type
655      * for the service bindings. If not set, the type defaults to
656      * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
657      *
658      * @param parentspecifier either a CSID or one of the urn forms
659      * @param itemspecifier either a CSID or one of the urn forms
660      * @param ui the ui
661      * 
662      * @return the info for the referencing objects
663      */
664     @GET
665     @Path("{csid}/items/{itemcsid}/refObjs")
666     @Produces("application/xml")
667     public AuthorityRefDocList getReferencingObjects(
668             @PathParam("csid") String parentspecifier,
669             @PathParam("itemcsid") String itemspecifier,
670             @Context UriInfo ui) {
671         AuthorityRefDocList authRefDocList = null;
672         try {
673             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
674
675             String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", queryParams);
676
677             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), queryParams);
678             String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
679
680             // Note that we have to create the service context for the Items, not the main service
681             // We omit the parentShortId, only needed when doing a create...
682             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
683             RepositoryClient repoClient = getRepositoryClient(ctx);
684             DocumentFilter myFilter = handler.getDocumentFilter();
685             String serviceType = ServiceBindingUtils.SERVICE_TYPE_PROCEDURE;
686             List<String> list = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
687             if (list != null) {
688                 serviceType = list.get(0);
689             }
690             DocumentWrapper<DocumentModel> docWrapper = repoClient.getDoc(ctx, itemcsid);
691             DocumentModel docModel = docWrapper.getWrappedObject();
692             String refName = (String) docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
693
694             authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(ctx,
695                     repoClient,
696                     serviceType,
697                     refName,
698                     myFilter.getPageSize(), myFilter.getStartPage(), true /*computeTotal*/);
699         } catch (Exception e) {
700             throw bigReThrow(e, ServiceMessages.GET_FAILED);
701         }
702         if (authRefDocList == null) {
703             Response response = Response.status(Response.Status.NOT_FOUND).entity(
704                     "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
705                     "text/plain").build();
706             throw new WebApplicationException(response);
707         }
708         return authRefDocList;
709     }
710
711     /**
712      * Gets the authority terms used in the indicated Authority item.
713      *
714      * @param parentspecifier either a CSID or one of the urn forms
715      * @param itemspecifier either a CSID or one of the urn forms
716      * @param ui passed to include additional parameters, like pagination controls
717      *
718      * @return the authority refs for the Authority item.
719      */
720     @GET
721     @Path("{csid}/items/{itemcsid}/authorityrefs")
722     @Produces("application/xml")
723     public AuthorityRefList getAuthorityItemAuthorityRefs(
724             @PathParam("csid") String parentspecifier,
725             @PathParam("itemcsid") String itemspecifier,
726             @Context UriInfo ui) {
727         AuthorityRefList authRefList = null;
728         try {
729             // Note that we have to create the service context for the Items, not the main service
730             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
731             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
732
733             String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", queryParams);
734
735             ctx = createServiceContext(getItemServiceName(), queryParams);
736             // We omit the parentShortId, only needed when doing a create...
737             RemoteDocumentModelHandlerImpl handler =
738                     (RemoteDocumentModelHandlerImpl) createItemDocumentHandler(ctx, parentcsid, null);
739
740             String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
741
742             DocumentWrapper<DocumentModel> docWrapper = getRepositoryClient(ctx).getDoc(ctx, itemcsid);
743             List<String> authRefFields =
744                     ((MultipartServiceContextImpl) ctx).getCommonPartPropertyValues(
745                     ServiceBindingUtils.AUTH_REF_PROP, ServiceBindingUtils.QUALIFIED_PROP_NAMES);
746             authRefList = handler.getAuthorityRefs(docWrapper, authRefFields);
747         } catch (Exception e) {
748             throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
749         }
750         return authRefList;
751     }
752
753     /**
754      * Update authorityItem.
755      * 
756      * @param parentspecifier either a CSID or one of the urn forms
757      * @param itemspecifier either a CSID or one of the urn forms
758      *
759      * @return the multipart output
760      */
761     @PUT
762     @Path("{csid}/items/{itemcsid}")
763     public byte[] updateAuthorityItem(
764             @Context UriInfo ui,
765             @PathParam("csid") String parentspecifier,
766             @PathParam("itemcsid") String itemspecifier,
767             String xmlPayload) {
768         PoxPayloadOut result = null;
769         try {
770             PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
771             // Note that we have to create the service context for the Items, not the main service
772             //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
773             String parentcsid = lookupParentCSID(parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
774
775             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate);
776             String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx);
777
778             // We omit the parentShortId, only needed when doing a create...
779             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
780             ctx.setUriInfo(ui);
781             getRepositoryClient(ctx).update(ctx, itemcsid, handler);
782             result = ctx.getOutput();
783
784         } catch (Exception e) {
785             throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
786         }
787         return result.getBytes();
788     }
789
790     /**
791      * Delete authorityItem.
792      * 
793      * @param parentcsid the parentcsid
794      * @param itemcsid the itemcsid
795      * 
796      * @return the response
797      */
798     @DELETE
799     @Path("{csid}/items/{itemcsid}")
800     public Response deleteAuthorityItem(
801             @PathParam("csid") String parentcsid,
802             @PathParam("itemcsid") String itemcsid) {
803         //try{
804         if (logger.isDebugEnabled()) {
805             logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
806         }
807         try {
808             ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
809             ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
810             //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
811             // }catch (Throwable t){
812             //    System.out.println("ERROR in setting up DELETE: "+t);
813             // }
814             // try {
815             // Note that we have to create the service context for the Items, not the main service
816             ServiceContext ctx = createServiceContext(getItemServiceName());
817             getRepositoryClient(ctx).delete(ctx, itemcsid);
818             return Response.status(HttpResponseCodes.SC_OK).build();
819         } catch (Exception e) {
820             throw bigReThrow(e, ServiceMessages.DELETE_FAILED + "  itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
821         }
822     }
823     public final static String hierarchy = "hierarchy";
824
825     @GET
826     @Path("{csid}/items/{itemcsid}/" + hierarchy)
827     @Produces("application/xml")
828     public String getHierarchy(@PathParam("csid") String csid,
829             @PathParam("itemcsid") String itemcsid,
830             @Context UriInfo ui) throws Exception {
831         try {
832             // 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...?
833             String calledUri = ui.getPath();
834             String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
835             ServiceContext ctx = createServiceContext(getItemServiceName());
836             ctx.setUriInfo(ui);
837             String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
838             if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
839                 return Hierarchy.surface(ctx, itemcsid, uri);
840             } else {
841                 return Hierarchy.dive(ctx, itemcsid, uri);
842             }
843         } catch (Exception e) {
844             throw bigReThrow(e, "Error showing hierarchy", itemcsid);
845         }
846     }
847 }