]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
05695cb7b4c4604bd50fdd37a272238c64146c36
[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(@PathParam("csid") String specifier,
584                         @Context UriInfo ui) {
585                 try {
586                         MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
587                 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
588                 String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
589                 String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
590                         
591             // Note that docType defaults to the ServiceName, so we're fine with that.
592             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
593
594             String parentcsid = lookupParentCSID(specifier, "getAuthorityItemList", "LIST", queryParams);
595
596                         ctx = createServiceContext(getItemServiceName(), queryParams);
597                         // We omit the parentShortId, only needed when doing a create...
598                         DocumentHandler handler = createItemDocumentHandler(ctx, 
599                                                                                 parentcsid, null);
600                         DocumentFilter myFilter = handler.getDocumentFilter();
601                         myFilter.appendWhereClause(authorityItemCommonSchemaName + ":" +
602                                         AuthorityItemJAXBSchema.IN_AUTHORITY + "=" + 
603                                         "'" + parentcsid + "'",
604                                         IQueryManager.SEARCH_QUALIFIER_AND);
605
606                         // AND vocabularyitems_common:displayName LIKE '%partialTerm%'
607                         // NOTE: Partial terms searches are mutually exclusive to keyword and advanced-search, but
608                         // the PT query param trumps the KW and AS query params.
609                         if (partialTerm != null && !partialTerm.isEmpty()) {
610                                 String ptClause = QueryManager.createWhereClauseForPartialMatch(
611                                 authorityItemCommonSchemaName + ":"
612                                 + AuthorityItemJAXBSchema.DISPLAY_NAME, partialTerm );
613                                 myFilter.appendWhereClause(ptClause, IQueryManager.SEARCH_QUALIFIER_AND);
614                         } else if (keywords != null || advancedSearch != null) {
615 //                              String kwdClause = QueryManager.createWhereClauseFromKeywords(keywords);
616 //                              myFilter.appendWhereClause(kwdClause, IQueryManager.SEARCH_QUALIFIER_AND);
617                                 return search(ctx, handler, queryParams, keywords, advancedSearch);
618                         }
619                         if (logger.isDebugEnabled()) {
620                                 logger.debug("getAuthorityItemList filtered WHERE clause: "
621                                                 + myFilter.getWhereClause());
622                         }
623                         getRepositoryClient(ctx).getFiltered(ctx, handler);
624                         return (AbstractCommonList) handler.getCommonPartList();
625                 } catch (Exception e) {
626                         throw bigReThrow(e, ServiceMessages.LIST_FAILED);
627                 }
628         }
629
630     /**
631      * Gets the entities referencing this Authority item instance. The service type
632      * can be passed as a query param "type", and must match a configured type
633      * for the service bindings. If not set, the type defaults to
634      * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
635      *
636          * @param parentspecifier either a CSID or one of the urn forms
637          * @param itemspecifier either a CSID or one of the urn forms
638      * @param ui the ui
639      * 
640      * @return the info for the referencing objects
641      */
642     @GET
643     @Path("{csid}/items/{itemcsid}/refObjs")
644     @Produces("application/xml")
645     public AuthorityRefDocList getReferencingObjects(
646                         @PathParam("csid") String parentspecifier,
647                         @PathParam("itemcsid") String itemspecifier,
648                 @Context UriInfo ui) {
649         AuthorityRefDocList authRefDocList = null;
650         try {
651                 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
652
653             String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", queryParams);
654
655             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), queryParams);
656             String itemcsid = lookupItemCSID(itemspecifier, parentcsid,  "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
657
658             // Note that we have to create the service context for the Items, not the main service
659                         // We omit the parentShortId, only needed when doing a create...
660                 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
661                 RepositoryClient repoClient = getRepositoryClient(ctx); 
662                 DocumentFilter myFilter = handler.getDocumentFilter();
663                 String serviceType = ServiceBindingUtils.SERVICE_TYPE_PROCEDURE;
664                 List<String> list = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
665                 if (list != null) {
666                         serviceType = list.get(0);
667                 }
668                 DocumentWrapper<DocumentModel> docWrapper = repoClient.getDoc(ctx, itemcsid);
669                 DocumentModel docModel = docWrapper.getWrappedObject();
670                 String refName = (String)docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
671
672                 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(ctx,
673                                 repoClient, 
674                                 serviceType,
675                                 refName,
676                                 myFilter.getPageSize(), myFilter.getStartPage(), true /*computeTotal*/ );
677         } catch (Exception e) {
678                         throw bigReThrow(e, ServiceMessages.GET_FAILED);
679                 }
680         if (authRefDocList == null) {
681                 Response response = Response.status(Response.Status.NOT_FOUND).entity(
682                                 "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
683                                 "text/plain").build();
684                 throw new WebApplicationException(response);
685         }
686         return authRefDocList;
687     }
688
689     /**
690      * Gets the authority terms used in the indicated Authority item.
691      *
692          * @param parentspecifier either a CSID or one of the urn forms
693          * @param itemspecifier either a CSID or one of the urn forms
694          * @param ui passed to include additional parameters, like pagination controls
695      *
696      * @return the authority refs for the Authority item.
697      */
698     @GET
699     @Path("{csid}/items/{itemcsid}/authorityrefs")
700     @Produces("application/xml")
701     public AuthorityRefList getAuthorityItemAuthorityRefs(
702                 @PathParam("csid") String parentspecifier,
703                 @PathParam("itemcsid") String itemspecifier,
704                 @Context UriInfo ui) {
705         AuthorityRefList authRefList = null;
706         try {
707                         // Note that we have to create the service context for the Items, not the main service
708             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
709             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
710
711             String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", queryParams);
712
713             ctx = createServiceContext(getItemServiceName(), queryParams);
714             // We omit the parentShortId, only needed when doing a create...
715             RemoteDocumentModelHandlerImpl handler =
716                 (RemoteDocumentModelHandlerImpl) createItemDocumentHandler(ctx, parentcsid, null);
717
718             String itemcsid = lookupItemCSID(itemspecifier, parentcsid,  "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
719
720             DocumentWrapper<DocumentModel> docWrapper = getRepositoryClient(ctx).getDoc(ctx, itemcsid);
721             List<String> authRefFields =
722                 ((MultipartServiceContextImpl)ctx).getCommonPartPropertyValues(
723                 ServiceBindingUtils.AUTH_REF_PROP, ServiceBindingUtils.QUALIFIED_PROP_NAMES);
724             authRefList = handler.getAuthorityRefs(docWrapper, authRefFields);
725         } catch (Exception e) {
726                         throw bigReThrow(e, ServiceMessages.GET_FAILED  + " parentspecifier: "+parentspecifier + " itemspecifier:" +itemspecifier);
727                 }return authRefList;
728     }
729
730         /**
731          * Update authorityItem.
732          * 
733          * @param parentspecifier either a CSID or one of the urn forms
734          * @param itemspecifier either a CSID or one of the urn forms
735          *
736          * @return the multipart output
737          */
738         @PUT
739         @Path("{csid}/items/{itemcsid}")
740         public byte[] updateAuthorityItem(
741             @Context UriInfo ui,
742                         @PathParam("csid") String parentspecifier,
743                         @PathParam("itemcsid") String itemspecifier,
744                         String xmlPayload) {
745                 PoxPayloadOut result = null;
746                 try {
747                         PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
748             // Note that we have to create the service context for the Items, not the main service
749             //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
750             String parentcsid = lookupParentCSID(parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
751
752             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate);
753             String itemcsid = lookupItemCSID(itemspecifier, parentcsid,   "updateAuthorityItem(item)", "UPDATE_ITEM", ctx);
754
755                         // We omit the parentShortId, only needed when doing a create...
756                         DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
757             ctx.setUriInfo(ui);
758                         getRepositoryClient(ctx).update(ctx, itemcsid, handler);
759                         result = ctx.getOutput();
760
761                 } catch (Exception e) {
762             throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
763                 }
764                 return result.getBytes();
765         }
766
767         /**
768          * Delete authorityItem.
769          * 
770          * @param parentcsid the parentcsid
771          * @param itemcsid the itemcsid
772          * 
773          * @return the response
774          */
775         @DELETE
776         @Path("{csid}/items/{itemcsid}")
777         public Response deleteAuthorityItem(
778                         @PathParam("csid") String parentcsid,
779                         @PathParam("itemcsid") String itemcsid) {
780                 //try{
781         if (logger.isDebugEnabled()) {
782             logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
783         }
784         try {
785                     ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
786             ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
787         //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
788         // }catch (Throwable t){
789         //    System.out.println("ERROR in setting up DELETE: "+t);
790         // }
791         // try {
792                         // Note that we have to create the service context for the Items, not the main service
793                         ServiceContext ctx = createServiceContext(getItemServiceName());
794                         getRepositoryClient(ctx).delete(ctx, itemcsid);
795                         return Response.status(HttpResponseCodes.SC_OK).build();
796         } catch (Exception e) {
797                         throw bigReThrow(e, ServiceMessages.DELETE_FAILED + "  itemcsid: " + itemcsid+ " parentcsid:" + parentcsid);
798                 }
799         }
800
801     public final static String hierarchy = "hierarchy";
802     @GET
803     @Path("{csid}/items/{itemcsid}/"+hierarchy)
804     @Produces("application/xml")
805     public String getHierarchy(@PathParam("csid") String csid,
806                                            @PathParam("itemcsid") String itemcsid,
807                                            @Context UriInfo ui) throws Exception {
808         try {
809             // 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...?
810             String calledUri = ui.getPath();
811             String uri = "/"+calledUri.substring(0, (calledUri.length()-("/"+hierarchy).length()));
812             ServiceContext ctx = createServiceContext(getItemServiceName());
813             ctx.setUriInfo(ui);
814             String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
815             if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)){
816                 return Hierarchy.surface(ctx, itemcsid, uri);
817             } else {
818                 return Hierarchy.dive(ctx, itemcsid, uri);
819             }
820         } catch (Exception e){
821             throw bigReThrow(e, "Error showing hierarchy", itemcsid);
822         }
823     }
824
825
826     
827 }