]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
a5fce2fe39c0bdd83da77812d7455c84654a35a7
[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(@PathParam("csid") String specifier) {
263                 PoxPayloadOut result = null;
264                 try {
265                         Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
266                         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
267                         DocumentHandler handler = createDocumentHandler(ctx);
268                         if(spec.form == SpecifierForm.CSID) {
269                                 if (logger.isDebugEnabled()) {
270                                         logger.debug("getAuthority with csid=" + spec.value);
271                                 }
272                                 getRepositoryClient(ctx).get(ctx, spec.value, handler);
273                         } else {
274                                 String whereClause = buildWhereForAuthByName(spec.value);
275                                 DocumentFilter myFilter = new DocumentFilter(whereClause, 0, 1);
276                                 handler.setDocumentFilter(myFilter);
277                                 getRepositoryClient(ctx).get(ctx, handler);
278                         }
279                         result = ctx.getOutput();
280                 } catch (UnauthorizedException ue) {
281                         Response response = Response.status(
282                                         Response.Status.UNAUTHORIZED).entity("Get failed reason " + ue.getErrorReason()).type("text/plain").build();
283                         throw new WebApplicationException(response);
284                 } catch (DocumentNotFoundException dnfe) {
285                         if (logger.isDebugEnabled()) {
286                                 logger.debug("getAuthority", dnfe);
287                         }
288                         Response response = Response.status(Response.Status.NOT_FOUND).entity(
289                                         "Get failed on Authority specifier=" + specifier).type(
290                                         "text/plain").build();
291                         throw new WebApplicationException(response);
292                 } catch (Exception e) {
293                         if (logger.isDebugEnabled()) {
294                                 logger.debug("getAuthority", e);
295                         }
296                         Response response = Response.status(
297                                         Response.Status.INTERNAL_SERVER_ERROR).entity("Get failed").type("text/plain").build();
298                         throw new WebApplicationException(response);
299                 }
300
301                 if (result == null) {
302                         Response response = Response.status(Response.Status.NOT_FOUND).entity(
303                                         "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type(
304                                         "text/plain").build();
305                         throw new WebApplicationException(response);
306                 }
307
308                 return result.getBytes();
309         }
310
311         /**
312          * Finds and populates the authority list.
313          * 
314          * @param ui the ui
315          * 
316          * @return the authority list
317          */
318     @GET
319     @Produces("application/xml")
320     public AuthCommonList getAuthorityList(@Context UriInfo ui) {
321                 try {
322                         MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
323                         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(queryParams);
324                         DocumentHandler handler = createDocumentHandler(ctx);
325                         DocumentFilter myFilter = handler.getDocumentFilter();
326                         String nameQ = queryParams.getFirst("refName");
327                         if (nameQ != null) {
328                                 myFilter.setWhereClause(authorityCommonSchemaName+":refName='" + nameQ + "'");
329                         }
330                         getRepositoryClient(ctx).getFiltered(ctx, handler);
331                         return (AuthCommonList) handler.getCommonPartList();
332                 } catch (UnauthorizedException ue) {
333                         Response response = Response.status(
334                                         Response.Status.UNAUTHORIZED).entity("Index failed reason " + ue.getErrorReason()).type("text/plain").build();
335                         throw new WebApplicationException(response);
336                 } catch (Exception e) {
337                         if (logger.isDebugEnabled()) {
338                                 logger.debug("Caught exception in getAuthorityList", e);
339                         }
340                         Response response = Response.status(
341                                         Response.Status.INTERNAL_SERVER_ERROR).entity("Index failed").type("text/plain").build();
342                         throw new WebApplicationException(response);
343                 }
344         }
345
346         /**
347          * Update authority.
348          * 
349          * @param specifier the csid or id
350          * @param theUpdate the the update
351          * 
352          * @return the multipart output
353          */
354         @PUT
355         @Path("{csid}")
356         public byte[] updateAuthority(
357                         @PathParam("csid") String specifier,
358                         String xmlPayload) {
359                 PoxPayloadOut result = null;
360                 try {
361                         PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
362                         Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
363                         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
364                         DocumentHandler handler = createDocumentHandler(ctx);
365                         String csid;
366                         if(spec.form==SpecifierForm.CSID) {
367                                 csid = spec.value;
368                         } else {
369                                 String whereClause = buildWhereForAuthByName(spec.value);
370                                 csid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause);
371                         }
372                         getRepositoryClient(ctx).update(ctx, csid, handler);
373                         result = ctx.getOutput();
374                 } catch (UnauthorizedException ue) {
375                         Response response = Response.status(
376                                         Response.Status.UNAUTHORIZED).entity("Update failed reason " + ue.getErrorReason()).type("text/plain").build();
377                         throw new WebApplicationException(response);
378                 } catch (DocumentNotFoundException dnfe) {
379                         if (logger.isDebugEnabled()) {
380                                 logger.debug("caught exception in updateAuthority", dnfe);
381                         }
382                         Response response = Response.status(Response.Status.NOT_FOUND).entity(
383                                         "Update failed on Authority specifier=" + specifier).type(
384                                         "text/plain").build();
385                         throw new WebApplicationException(response);
386                 } catch (Exception e) {
387                         Response response = Response.status(
388                                         Response.Status.INTERNAL_SERVER_ERROR).entity("Update failed").type("text/plain").build();
389                         throw new WebApplicationException(response);
390                 }
391                 return result.getBytes();
392         }
393
394         /**
395          * Delete authority.
396          * 
397          * @param csid the csid
398          * 
399          * @return the response
400          */
401         @DELETE
402         @Path("{csid}")
403         public Response deleteAuthority(@PathParam("csid") String csid) {
404
405                 if (logger.isDebugEnabled()) {
406                         logger.debug("deleteAuthority with csid=" + csid);
407                 }
408                 if (csid == null || "".equals(csid)) {
409                         logger.error("deleteAuthority: missing csid!");
410                         Response response = Response.status(Response.Status.BAD_REQUEST).entity(
411                                         "delete failed on Authority csid=" + csid).type(
412                                         "text/plain").build();
413                         throw new WebApplicationException(response);
414                 }
415                 try {
416                         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
417                         getRepositoryClient(ctx).delete(ctx, csid);
418                         return Response.status(HttpResponseCodes.SC_OK).build();
419                 } catch (UnauthorizedException ue) {
420                         Response response = Response.status(
421                                         Response.Status.UNAUTHORIZED).entity("Delete failed reason " + ue.getErrorReason()).type("text/plain").build();
422                         throw new WebApplicationException(response);
423                 } catch (DocumentNotFoundException dnfe) {
424                         if (logger.isDebugEnabled()) {
425                                 logger.debug("caught exception in deleteAuthority", dnfe);
426                         }
427                         Response response = Response.status(Response.Status.NOT_FOUND).entity(
428                                         "Delete failed on Authority csid=" + csid).type(
429                                         "text/plain").build();
430                         throw new WebApplicationException(response);
431                 } catch (Exception e) {
432                         Response response = Response.status(
433                                         Response.Status.INTERNAL_SERVER_ERROR).entity("Delete failed").type("text/plain").build();
434                         throw new WebApplicationException(response);
435                 }
436
437         }
438
439         /*************************************************************************
440          * Create an AuthorityItem - this is a sub-resource of Authority
441          * @param specifier either a CSID or one of the urn forms
442          * @param input the payload 
443          * @return Authority item response
444          *************************************************************************/
445         @POST
446         @Path("{csid}/items")
447         public Response createAuthorityItem(@PathParam("csid") String specifier, String xmlPayload) {
448                 try {
449                         PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
450                         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
451                         Specifier spec = getSpecifier(specifier, "createAuthorityItem", "CREATE_ITEM");
452                         String parentcsid;
453                         if(spec.form==SpecifierForm.CSID) {
454                                 parentcsid = spec.value;
455                         } else {
456                                 String whereClause = buildWhereForAuthByName(spec.value);
457                     ctx = createServiceContext(getServiceName());
458                                 parentcsid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause);
459                         }
460                         ctx = createServiceContext(getItemServiceName(), input);
461                         DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
462                         String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
463                         UriBuilder path = UriBuilder.fromResource(resourceClass);
464                         path.path(parentcsid + "/items/" + itemcsid);
465                         Response response = Response.created(path.build()).build();
466                         return response;
467                 } catch (BadRequestException bre) {
468                         Response response = Response.status(
469                                         Response.Status.BAD_REQUEST).entity("Create failed reason " + bre.getErrorReason()).type("text/plain").build();
470                         throw new WebApplicationException(response);
471                 } catch (UnauthorizedException ue) {
472                         Response response = Response.status(
473                                         Response.Status.UNAUTHORIZED).entity("Create failed reason " + ue.getErrorReason()).type("text/plain").build();
474                         throw new WebApplicationException(response);
475                 } catch (Exception e) {
476                         if (logger.isDebugEnabled()) {
477                                 logger.debug("Caught exception in createAuthorityItem", e);
478                         }
479                         Response response = Response.status(
480                                         Response.Status.INTERNAL_SERVER_ERROR).entity("Create failed").type("text/plain").build();
481                         throw new WebApplicationException(response);
482                 }
483         }
484
485     @GET
486     @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
487     public byte[] getItemWorkflow(
488             @PathParam("csid") String csid,
489             @PathParam("itemcsid") String itemcsid) {
490         PoxPayloadOut result = null;
491
492         try {           
493             ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
494             String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
495                 
496                 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
497                 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
498                 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
499             getRepositoryClient(ctx).get(ctx, itemcsid, handler);
500             result = ctx.getOutput();
501         } catch (Exception e) {
502             throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
503         }
504                 
505         return result.getBytes();
506     }
507     
508     @PUT
509     @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
510     public byte[] updateWorkflow(
511             @PathParam("csid") String csid,
512             @PathParam("itemcsid") String itemcsid,
513                 String xmlPayload) {
514         PoxPayloadOut result = null;
515         try {
516                 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
517                 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
518                 
519                 PoxPayloadIn workflowUpdate = new PoxPayloadIn(xmlPayload);
520                 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, workflowUpdate);
521                 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
522                 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
523                 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
524                 result = ctx.getOutput();
525         } catch (Exception e) {
526             throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
527         }
528         return result.getBytes();
529     }    
530     
531         
532         /**
533          * Gets the authority item.
534          * 
535          * @param parentspecifier either a CSID or one of the urn forms
536          * @param itemspecifier either a CSID or one of the urn forms
537          * 
538          * @return the authority item
539          */
540         @GET
541         @Path("{csid}/items/{itemcsid}")
542         public byte[] getAuthorityItem(
543                 @Context Request request,
544             @Context UriInfo ui,
545                         @PathParam("csid") String parentspecifier,
546                         @PathParam("itemcsid") String itemspecifier) {
547                 PoxPayloadOut result = null;
548                 try {
549                 JaxRsContext jaxRsContext = new JaxRsContext(request, ui);
550
551                         Specifier parentSpec = getSpecifier(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM");
552                         Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
553                         // Note that we have to create the service context for the Items, not the main service
554                         RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
555                         String parentcsid;
556                         if(parentSpec.form==SpecifierForm.CSID) {
557                                 parentcsid = parentSpec.value;
558                         } else {
559                                 String whereClause = buildWhereForAuthByName(parentSpec.value);
560                                 ctx = (RemoteServiceContext)createServiceContext(getServiceName());
561                                 parentcsid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause);
562                         }
563                         ctx = (RemoteServiceContext)createServiceContext(getItemServiceName());
564                         ctx.setJaxRsContext(jaxRsContext);
565                         DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
566                         if(itemSpec.form==SpecifierForm.CSID) {
567                                 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
568                         } else {
569                                 String itemWhereClause = 
570                                         buildWhereForAuthItemByName(itemSpec.value, parentcsid);
571                     DocumentFilter myFilter = new DocumentFilter(itemWhereClause, 0, 1);
572                     handler.setDocumentFilter(myFilter);
573                     getRepositoryClient(ctx).get(ctx, handler);
574                         }
575                         // TODO should we assert that the item is in the passed vocab?
576                         result = ctx.getOutput();
577                 } catch (UnauthorizedException ue) {
578                         Response response = Response.status(
579                                         Response.Status.UNAUTHORIZED).entity("Get failed reason " + ue.getErrorReason()).type("text/plain").build();
580                         throw new WebApplicationException(response);
581                 } catch (DocumentNotFoundException dnfe) {
582                         if (logger.isDebugEnabled()) {
583                                 logger.debug("getAuthorityItem", dnfe);
584                         }
585                         Response response = Response.status(Response.Status.NOT_FOUND).entity(
586                                         "Get failed on AuthorityItem specifier=" + itemspecifier).type(
587                                         "text/plain").build();
588                         throw new WebApplicationException(response);
589                 } catch (Exception e) {
590                         if (logger.isDebugEnabled()) {
591                                 logger.debug("getAuthorityItem", e);
592                         }
593                         Response response = Response.status(
594                                         Response.Status.INTERNAL_SERVER_ERROR).entity("Get failed").type("text/plain").build();
595                         throw new WebApplicationException(response);
596                 }
597                 if (result == null) {
598                         Response response = Response.status(Response.Status.NOT_FOUND).entity(
599                                         "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
600                                         "text/plain").build();
601                         throw new WebApplicationException(response);
602                 }
603                 return result.getBytes();
604         }
605
606
607         /**
608          * Gets the authorityItem list for the specified authority
609          * If partialPerm is specified, keywords will be ignored.
610          * 
611          * @param specifier either a CSID or one of the urn forms
612          * @param partialTerm if non-null, matches partial terms
613          * @param keywords if non-null, matches terms in the keyword index for items
614          * @param ui passed to include additional parameters, like pagination controls
615          * 
616          * @return the authorityItem list
617          */
618         @GET
619         @Path("{csid}/items")
620         @Produces("application/xml")
621         public AuthItemCommonList getAuthorityItemList(
622                         @PathParam("csid") String specifier,
623                         @QueryParam(IQueryManager.SEARCH_TYPE_PARTIALTERM) String partialTerm,
624                         @QueryParam(IQueryManager.SEARCH_TYPE_KEYWORDS_KW) String keywords,
625                         @Context UriInfo ui) {
626                 try {
627                         Specifier spec = getSpecifier(specifier, "getAuthorityItemList", "LIST");
628                         MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
629                         // Note that docType defaults to the ServiceName, so we're fine with that.
630                         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
631                         String parentcsid;
632                         if(spec.form==SpecifierForm.CSID) {
633                                 parentcsid = spec.value;
634                         } else {
635                                 String whereClause = buildWhereForAuthByName(spec.value);
636                                 ctx = createServiceContext(getServiceName());
637                                 parentcsid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause);
638                         }
639                         ctx = createServiceContext(getItemServiceName(), queryParams);
640                         DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
641                         DocumentFilter myFilter = handler.getDocumentFilter();
642                         myFilter.setWhereClause(
643                                         authorityItemCommonSchemaName + ":"
644                                         + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
645                                         + "'" + parentcsid + "'");
646
647                         // AND vocabularyitems_common:displayName LIKE '%partialTerm%'
648                         if (partialTerm != null && !partialTerm.isEmpty()) {
649                                 String ptClause = QueryManager.createWhereClauseForPartialMatch(
650                                 authorityItemCommonSchemaName + ":"
651                                 + AuthorityItemJAXBSchema.DISPLAY_NAME, partialTerm );
652                                 myFilter.appendWhereClause(ptClause, IQueryManager.SEARCH_QUALIFIER_AND);
653                         } else if (keywords != null) {
654                                 String kwdClause = QueryManager.createWhereClauseFromKeywords(keywords);
655                                 myFilter.appendWhereClause(kwdClause, IQueryManager.SEARCH_QUALIFIER_AND);
656                         }
657                         if (logger.isDebugEnabled()) {
658                                 logger.debug("getAuthorityItemList filtered WHERE clause: "
659                                                 + myFilter.getWhereClause());
660                         }
661                         getRepositoryClient(ctx).getFiltered(ctx, handler);
662                         return (AuthItemCommonList) handler.getCommonPartList();
663                 } catch (UnauthorizedException ue) {
664                         Response response = Response.status(
665                                         Response.Status.UNAUTHORIZED).entity("Index failed reason " + ue.getErrorReason()).type("text/plain").build();
666                         throw new WebApplicationException(response);
667                 } catch (Exception e) {
668                         if (logger.isDebugEnabled()) {
669                                 logger.debug("Caught exception in getAuthorityItemList", e);
670                         }
671                         Response response = Response.status(
672                                         Response.Status.INTERNAL_SERVER_ERROR).entity("Index failed").type("text/plain").build();
673                         throw new WebApplicationException(response);
674                 }
675         }
676
677     /**
678      * Gets the entities referencing this Authority item instance. The service type
679      * can be passed as a query param "type", and must match a configured type
680      * for the service bindings. If not set, the type defaults to
681      * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
682      *
683          * @param parentspecifier either a CSID or one of the urn forms
684          * @param itemspecifier either a CSID or one of the urn forms
685      * @param ui the ui
686      * 
687      * @return the info for the referencing objects
688      */
689     @GET
690     @Path("{csid}/items/{itemcsid}/refObjs")
691     @Produces("application/xml")
692     public AuthorityRefDocList getReferencingObjects(
693                         @PathParam("csid") String parentspecifier,
694                         @PathParam("itemcsid") String itemspecifier,
695                 @Context UriInfo ui) {
696         AuthorityRefDocList authRefDocList = null;
697         try {
698                 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
699                         Specifier parentSpec = getSpecifier(parentspecifier, 
700                                         "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS");
701                         Specifier itemSpec = getSpecifier(itemspecifier, 
702                                         "getReferencingObjects(item)", "GET_ITEM_REF_OBJS");
703                         // Note that we have to create the service context for the Items, not the main service
704             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
705                         String parentcsid;
706                         if(parentSpec.form==SpecifierForm.CSID) {
707                                 parentcsid = parentSpec.value;
708                         } else {
709                                 String whereClause = buildWhereForAuthByName(parentSpec.value);
710                     ctx = createServiceContext(getServiceName());
711                                 parentcsid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause);
712                         }
713                 ctx = createServiceContext(getItemServiceName(), queryParams);
714             String itemcsid;
715                         if(itemSpec.form==SpecifierForm.CSID) {
716                                 itemcsid = itemSpec.value;
717                         } else {
718                                 String itemWhereClause = 
719                                         buildWhereForAuthItemByName(itemSpec.value, parentcsid);
720                                 itemcsid = getRepositoryClient(ctx).findDocCSID(ctx, itemWhereClause);
721                         }
722                 // Note that we have to create the service context for the Items, not the main service
723                 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
724                 RepositoryClient repoClient = getRepositoryClient(ctx); 
725                 DocumentFilter myFilter = handler.getDocumentFilter();
726                 String serviceType = ServiceBindingUtils.SERVICE_TYPE_PROCEDURE;
727                 List<String> list = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
728                 if (list != null) {
729                         serviceType = list.get(0);
730                 }
731                 DocumentWrapper<DocumentModel> docWrapper = repoClient.getDoc(ctx, itemcsid);
732                 DocumentModel docModel = docWrapper.getWrappedObject();
733                 String refName = (String)docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
734
735                 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(ctx,
736                                 repoClient, 
737                                 serviceType,
738                                 refName,
739                                 myFilter.getPageSize(), myFilter.getStartPage(), true /*computeTotal*/ );
740         } catch (UnauthorizedException ue) {
741                 Response response = Response.status(
742                                 Response.Status.UNAUTHORIZED).entity("Get failed reason " + ue.getErrorReason()).type("text/plain").build();
743                 throw new WebApplicationException(response);
744         } catch (DocumentNotFoundException dnfe) {
745                 if (logger.isDebugEnabled()) {
746                         logger.debug("getReferencingObjects", dnfe);
747                 }
748                 Response response = Response.status(Response.Status.NOT_FOUND).entity(
749                                 "GetReferencingObjects failed with parentspecifier=" 
750                                 + parentspecifier + " and itemspecifier=" + itemspecifier).type(
751                                 "text/plain").build();
752                 throw new WebApplicationException(response);
753         } catch (Exception e) { // Includes DocumentException
754                 if (logger.isDebugEnabled()) {
755                         logger.debug("GetReferencingObjects", e);
756                 }
757                 Response response = Response.status(
758                                 Response.Status.INTERNAL_SERVER_ERROR).entity("Get failed").type("text/plain").build();
759                 throw new WebApplicationException(response);
760         }
761         if (authRefDocList == null) {
762                 Response response = Response.status(Response.Status.NOT_FOUND).entity(
763                                 "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
764                                 "text/plain").build();
765                 throw new WebApplicationException(response);
766         }
767         return authRefDocList;
768     }
769
770     /**
771      * Gets the authority terms used in the indicated Authority item.
772      *
773          * @param parentspecifier either a CSID or one of the urn forms
774          * @param itemspecifier either a CSID or one of the urn forms
775          * @param ui passed to include additional parameters, like pagination controls
776      *
777      * @return the authority refs for the Authority item.
778      */
779     @GET
780     @Path("{csid}/items/{itemcsid}/authorityrefs")
781     @Produces("application/xml")
782     public AuthorityRefList getAuthorityItemAuthorityRefs(
783                 @PathParam("csid") String parentspecifier,
784                 @PathParam("itemcsid") String itemspecifier,
785                 @Context UriInfo ui) {
786         AuthorityRefList authRefList = null;
787         try {
788                         Specifier parentSpec = getSpecifier(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS");
789                         Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS");
790                         // Note that we have to create the service context for the Items, not the main service
791             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
792             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
793                         String parentcsid;
794                         if(parentSpec.form==SpecifierForm.CSID) {
795                                 parentcsid = parentSpec.value;
796                         } else {
797                                 String whereClause = buildWhereForAuthByName(parentSpec.value);
798                     ctx = createServiceContext(getServiceName());
799                                 parentcsid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause);
800                         }
801             ctx = createServiceContext(getItemServiceName(), queryParams);
802             RemoteDocumentModelHandlerImpl handler =
803                 (RemoteDocumentModelHandlerImpl) createItemDocumentHandler(ctx, parentcsid);
804             String itemcsid;
805                         if(itemSpec.form==SpecifierForm.CSID) {
806                                 itemcsid = itemSpec.value;
807                         } else {
808                                 String itemWhereClause = 
809                                         buildWhereForAuthItemByName(itemSpec.value, parentcsid);
810                                 itemcsid = getRepositoryClient(ctx).findDocCSID(ctx, itemWhereClause);
811                         }
812             DocumentWrapper<DocumentModel> docWrapper =
813                getRepositoryClient(ctx).getDoc(ctx, itemcsid);
814             List<String> authRefFields =
815                 ((MultipartServiceContextImpl)ctx).getCommonPartPropertyValues(
816                 ServiceBindingUtils.AUTH_REF_PROP, ServiceBindingUtils.QUALIFIED_PROP_NAMES);
817             authRefList = handler.getAuthorityRefs(docWrapper, authRefFields);
818         } catch (UnauthorizedException ue) {
819             Response response = Response.status(
820                     Response.Status.UNAUTHORIZED).entity("Failed to retrieve authority references: reason " + ue.getErrorReason()).type("text/plain").build();
821             throw new WebApplicationException(response);
822         } catch (Exception e) {
823             if (logger.isDebugEnabled()) {
824                 logger.debug("Caught exception in getAuthorityRefs", e);
825             }
826             Response response = Response.status(
827                     Response.Status.INTERNAL_SERVER_ERROR).entity("Failed to retrieve authority references").type("text/plain").build();
828             throw new WebApplicationException(response);
829         }
830         return authRefList;
831     }
832
833         /**
834          * Update authorityItem.
835          * 
836          * @param parentspecifier either a CSID or one of the urn forms
837          * @param itemspecifier either a CSID or one of the urn forms
838          * @param theUpdate the the update
839          * 
840          * @return the multipart output
841          */
842         @PUT
843         @Path("{csid}/items/{itemcsid}")
844         public byte[] updateAuthorityItem(
845                         @PathParam("csid") String parentspecifier,
846                         @PathParam("itemcsid") String itemspecifier,
847                         String xmlPayload) {
848                 PoxPayloadOut result = null;
849                 try {
850                         PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
851                         Specifier parentSpec = getSpecifier(parentspecifier, 
852                                         "updateAuthorityItem(parent)", "UPDATE_ITEM");
853                         Specifier itemSpec = getSpecifier(itemspecifier, 
854                                         "updateAuthorityItem(item)", "UPDATE_ITEM");
855                         // Note that we have to create the service context for the Items, not the main service
856             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
857                         String parentcsid;
858                         if(parentSpec.form==SpecifierForm.CSID) {
859                                 parentcsid = parentSpec.value;
860                         } else {
861                                 String whereClause = buildWhereForAuthByName(parentSpec.value);
862                     ctx = createServiceContext(getServiceName());
863                                 parentcsid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause);
864                         }
865                         ctx = createServiceContext(getItemServiceName(), theUpdate);
866             String itemcsid;
867                         if(itemSpec.form==SpecifierForm.CSID) {
868                                 itemcsid = itemSpec.value;
869                         } else {
870                                 String itemWhereClause = 
871                                         buildWhereForAuthItemByName(itemSpec.value, parentcsid);
872                                 itemcsid = getRepositoryClient(ctx).findDocCSID(ctx, itemWhereClause);
873                         }
874                         // Note that we have to create the service context for the Items, not the main service
875                         DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
876                         getRepositoryClient(ctx).update(ctx, itemcsid, handler);
877                         result = ctx.getOutput();
878                 } catch (BadRequestException bre) {
879                         Response response = Response.status(
880                                         Response.Status.BAD_REQUEST).entity("Create failed reason " + bre.getErrorReason()).type("text/plain").build();
881                         throw new WebApplicationException(response);
882                 } catch (UnauthorizedException ue) {
883                         Response response = Response.status(
884                                         Response.Status.UNAUTHORIZED).entity("Update failed reason " + ue.getErrorReason()).type("text/plain").build();
885                         throw new WebApplicationException(response);
886                 } catch (DocumentNotFoundException dnfe) {
887                         if (logger.isDebugEnabled()) {
888                                 logger.debug("caught DNF exception in updateAuthorityItem", dnfe);
889                         }
890                         Response response = Response.status(Response.Status.NOT_FOUND).entity(
891                                         "Update failed on AuthorityItem csid=" + itemspecifier).type(
892                                         "text/plain").build();
893                         throw new WebApplicationException(response);
894                 } catch (Exception e) {
895                         Response response = Response.status(
896                                         Response.Status.INTERNAL_SERVER_ERROR).entity("Update failed").type("text/plain").build();
897                         throw new WebApplicationException(response);
898                 }
899                 return result.getBytes();
900         }
901
902         /**
903          * Delete authorityItem.
904          * 
905          * @param parentcsid the parentcsid
906          * @param itemcsid the itemcsid
907          * 
908          * @return the response
909          */
910         @DELETE
911         @Path("{csid}/items/{itemcsid}")
912         public Response deleteAuthorityItem(
913                         @PathParam("csid") String parentcsid,
914                         @PathParam("itemcsid") String itemcsid) {
915                 if (logger.isDebugEnabled()) {
916                         logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
917                 }
918                 if (parentcsid == null || "".equals(parentcsid)) {
919                         logger.error("deleteVocabularyItem: missing csid!");
920                         Response response = Response.status(Response.Status.BAD_REQUEST).entity(
921                                         "delete failed on AuthorityItem parentcsid=" + parentcsid).type(
922                                         "text/plain").build();
923                         throw new WebApplicationException(response);
924                 }
925                 if (itemcsid == null || "".equals(itemcsid)) {
926                         logger.error("deleteVocabularyItem: missing itemcsid!");
927                         Response response = Response.status(Response.Status.BAD_REQUEST).entity(
928                                         "delete failed on AuthorityItem=" + itemcsid).type(
929                                         "text/plain").build();
930                         throw new WebApplicationException(response);
931                 }
932                 try {
933                         // Note that we have to create the service context for the Items, not the main service
934                         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName());
935                         getRepositoryClient(ctx).delete(ctx, itemcsid);
936                         return Response.status(HttpResponseCodes.SC_OK).build();
937                 } catch (UnauthorizedException ue) {
938                         Response response = Response.status(
939                                         Response.Status.UNAUTHORIZED).entity("Delete failed reason " + ue.getErrorReason()).type("text/plain").build();
940                         throw new WebApplicationException(response);
941                 } catch (DocumentNotFoundException dnfe) {
942                         if (logger.isDebugEnabled()) {
943                                 logger.debug("caught exception in deleteAuthorityItem", dnfe);
944                         }
945                         Response response = Response.status(Response.Status.NOT_FOUND).entity(
946                                         "Delete failed on AuthorityItem itemcsid=" + itemcsid).type(
947                                         "text/plain").build();
948                         throw new WebApplicationException(response);
949                 } catch (Exception e) {
950                         Response response = Response.status(
951                                         Response.Status.INTERNAL_SERVER_ERROR).entity("Delete failed").type("text/plain").build();
952                         throw new WebApplicationException(response);
953                 }
954         }
955     
956 }