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