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