]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
94d2e32e9a2b995f60da0996abd6e2d5b7ef4ea1
[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             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
554
555                         Specifier parentSpec = getSpecifier(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM");
556                         Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
557                         // Note that we have to create the service context for the Items, not the main service
558                         RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
559                         String parentcsid;
560                         if(parentSpec.form==SpecifierForm.CSID) {
561                                 parentcsid = parentSpec.value;
562                         } else {
563                                 String whereClause = buildWhereForAuthByName(parentSpec.value);
564                                 ctx = (RemoteServiceContext)createServiceContext(getServiceName(), queryParams);
565                                 parentcsid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause); //FIXME: REM - If the parent has been soft-deleted, should we be looking for the item?
566                         }
567                         ctx = (RemoteServiceContext)createServiceContext(getItemServiceName(), queryParams);
568                         ctx.setJaxRsContext(jaxRsContext);
569                         DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
570                         if(itemSpec.form==SpecifierForm.CSID) {
571                                 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
572                         } else {
573                                 String itemWhereClause = 
574                                         buildWhereForAuthItemByName(itemSpec.value, parentcsid);
575                     DocumentFilter myFilter = new DocumentFilter(itemWhereClause, 0, 1);
576                     handler.setDocumentFilter(myFilter);
577                     getRepositoryClient(ctx).get(ctx, handler);
578                         }
579                         // TODO should we assert that the item is in the passed vocab?
580                         result = ctx.getOutput();
581                 } catch (UnauthorizedException ue) {
582                         Response response = Response.status(
583                                         Response.Status.UNAUTHORIZED).entity("Get failed reason " + ue.getErrorReason()).type("text/plain").build();
584                         throw new WebApplicationException(response);
585                 } catch (DocumentNotFoundException dnfe) {
586                         if (logger.isDebugEnabled()) {
587                                 logger.debug("getAuthorityItem", dnfe);
588                         }
589                         Response response = Response.status(Response.Status.NOT_FOUND).entity(
590                                         "Get failed on AuthorityItem specifier=" + itemspecifier).type(
591                                         "text/plain").build();
592                         throw new WebApplicationException(response);
593                 } catch (Exception e) {
594                         if (logger.isDebugEnabled()) {
595                                 logger.debug("getAuthorityItem", e);
596                         }
597                         Response response = Response.status(
598                                         Response.Status.INTERNAL_SERVER_ERROR).entity("Get failed").type("text/plain").build();
599                         throw new WebApplicationException(response);
600                 }
601                 if (result == null) {
602                         Response response = Response.status(Response.Status.NOT_FOUND).entity(
603                                         "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
604                                         "text/plain").build();
605                         throw new WebApplicationException(response);
606                 }
607                 return result.getBytes();
608         }
609
610
611         /**
612          * Gets the authorityItem list for the specified authority
613          * If partialPerm is specified, keywords will be ignored.
614          * 
615          * @param specifier either a CSID or one of the urn forms
616          * @param partialTerm if non-null, matches partial terms
617          * @param keywords if non-null, matches terms in the keyword index for items
618          * @param ui passed to include additional parameters, like pagination controls
619          * 
620          * @return the authorityItem list
621          */
622         @GET
623         @Path("{csid}/items")
624         @Produces("application/xml")
625         public AuthItemCommonList getAuthorityItemList(
626                         @PathParam("csid") String specifier,
627                         @QueryParam(IQueryManager.SEARCH_TYPE_PARTIALTERM) String partialTerm,
628                         @QueryParam(IQueryManager.SEARCH_TYPE_KEYWORDS_KW) String keywords,
629                         @Context UriInfo ui) {
630                 try {
631                         Specifier spec = getSpecifier(specifier, "getAuthorityItemList", "LIST");
632                         MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
633                         // Note that docType defaults to the ServiceName, so we're fine with that.
634                         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
635                         String parentcsid;
636                         if(spec.form==SpecifierForm.CSID) {
637                                 parentcsid = spec.value;
638                         } else {
639                                 String whereClause = buildWhereForAuthByName(spec.value);
640                                 ctx = createServiceContext(getServiceName(), queryParams);
641                                 parentcsid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause);
642                         }
643                         ctx = createServiceContext(getItemServiceName(), queryParams);
644                         DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
645                         DocumentFilter myFilter = handler.getDocumentFilter();
646                         myFilter.appendWhereClause(authorityItemCommonSchemaName + ":" +
647                                         AuthorityItemJAXBSchema.IN_AUTHORITY + "=" + 
648                                         "'" + parentcsid + "'",
649                                         IQueryManager.SEARCH_QUALIFIER_AND);
650
651                         // AND vocabularyitems_common:displayName LIKE '%partialTerm%'
652                         if (partialTerm != null && !partialTerm.isEmpty()) {
653                                 String ptClause = QueryManager.createWhereClauseForPartialMatch(
654                                 authorityItemCommonSchemaName + ":"
655                                 + AuthorityItemJAXBSchema.DISPLAY_NAME, partialTerm );
656                                 myFilter.appendWhereClause(ptClause, IQueryManager.SEARCH_QUALIFIER_AND);
657                         } else if (keywords != null) {
658                                 String kwdClause = QueryManager.createWhereClauseFromKeywords(keywords);
659                                 myFilter.appendWhereClause(kwdClause, IQueryManager.SEARCH_QUALIFIER_AND);
660                         }
661                         if (logger.isDebugEnabled()) {
662                                 logger.debug("getAuthorityItemList filtered WHERE clause: "
663                                                 + myFilter.getWhereClause());
664                         }
665                         getRepositoryClient(ctx).getFiltered(ctx, handler);
666                         return (AuthItemCommonList) handler.getCommonPartList();
667                 } catch (UnauthorizedException ue) {
668                         Response response = Response.status(
669                                         Response.Status.UNAUTHORIZED).entity("Index failed reason " + ue.getErrorReason()).type("text/plain").build();
670                         throw new WebApplicationException(response);
671                 } catch (Exception e) {
672                         if (logger.isDebugEnabled()) {
673                                 logger.debug("Caught exception in getAuthorityItemList", e);
674                         }
675                         Response response = Response.status(
676                                         Response.Status.INTERNAL_SERVER_ERROR).entity("Index failed").type("text/plain").build();
677                         throw new WebApplicationException(response);
678                 }
679         }
680
681     /**
682      * Gets the entities referencing this Authority item instance. The service type
683      * can be passed as a query param "type", and must match a configured type
684      * for the service bindings. If not set, the type defaults to
685      * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
686      *
687          * @param parentspecifier either a CSID or one of the urn forms
688          * @param itemspecifier either a CSID or one of the urn forms
689      * @param ui the ui
690      * 
691      * @return the info for the referencing objects
692      */
693     @GET
694     @Path("{csid}/items/{itemcsid}/refObjs")
695     @Produces("application/xml")
696     public AuthorityRefDocList getReferencingObjects(
697                         @PathParam("csid") String parentspecifier,
698                         @PathParam("itemcsid") String itemspecifier,
699                 @Context UriInfo ui) {
700         AuthorityRefDocList authRefDocList = null;
701         try {
702                 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
703                         Specifier parentSpec = getSpecifier(parentspecifier, 
704                                         "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS");
705                         Specifier itemSpec = getSpecifier(itemspecifier, 
706                                         "getReferencingObjects(item)", "GET_ITEM_REF_OBJS");
707                         // Note that we have to create the service context for the Items, not the main service
708             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
709                         String parentcsid;
710                         if(parentSpec.form==SpecifierForm.CSID) {
711                                 parentcsid = parentSpec.value;
712                         } else {
713                                 String whereClause = buildWhereForAuthByName(parentSpec.value);
714                     ctx = createServiceContext(getServiceName(), queryParams);
715                                 parentcsid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause); //FIXME: REM - If the parent is soft-deleted should we still try to find the item?
716                         }
717                 ctx = createServiceContext(getItemServiceName(), queryParams);
718             String itemcsid;
719                         if(itemSpec.form==SpecifierForm.CSID) {
720                                 itemcsid = itemSpec.value;
721                         } else {
722                                 String itemWhereClause = 
723                                         buildWhereForAuthItemByName(itemSpec.value, parentcsid);
724                                 itemcsid = getRepositoryClient(ctx).findDocCSID(ctx, itemWhereClause); //FIXME: REM - Should we be looking for the 'wf_deleted' query param and filtering on it?
725                         }
726                 // Note that we have to create the service context for the Items, not the main service
727                 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
728                 RepositoryClient repoClient = getRepositoryClient(ctx); 
729                 DocumentFilter myFilter = handler.getDocumentFilter();
730                 String serviceType = ServiceBindingUtils.SERVICE_TYPE_PROCEDURE;
731                 List<String> list = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
732                 if (list != null) {
733                         serviceType = list.get(0);
734                 }
735                 DocumentWrapper<DocumentModel> docWrapper = repoClient.getDoc(ctx, itemcsid);
736                 DocumentModel docModel = docWrapper.getWrappedObject();
737                 String refName = (String)docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
738
739                 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(ctx,
740                                 repoClient, 
741                                 serviceType,
742                                 refName,
743                                 myFilter.getPageSize(), myFilter.getStartPage(), true /*computeTotal*/ );
744         } catch (UnauthorizedException ue) {
745                 Response response = Response.status(
746                                 Response.Status.UNAUTHORIZED).entity("Get failed reason " + ue.getErrorReason()).type("text/plain").build();
747                 throw new WebApplicationException(response);
748         } catch (DocumentNotFoundException dnfe) {
749                 if (logger.isDebugEnabled()) {
750                         logger.debug("getReferencingObjects", dnfe);
751                 }
752                 Response response = Response.status(Response.Status.NOT_FOUND).entity(
753                                 "GetReferencingObjects failed with parentspecifier=" 
754                                 + parentspecifier + " and itemspecifier=" + itemspecifier).type(
755                                 "text/plain").build();
756                 throw new WebApplicationException(response);
757         } catch (Exception e) { // Includes DocumentException
758                 if (logger.isDebugEnabled()) {
759                         logger.debug("GetReferencingObjects", e);
760                 }
761                 Response response = Response.status(
762                                 Response.Status.INTERNAL_SERVER_ERROR).entity("Get failed").type("text/plain").build();
763                 throw new WebApplicationException(response);
764         }
765         if (authRefDocList == null) {
766                 Response response = Response.status(Response.Status.NOT_FOUND).entity(
767                                 "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
768                                 "text/plain").build();
769                 throw new WebApplicationException(response);
770         }
771         return authRefDocList;
772     }
773
774     /**
775      * Gets the authority terms used in the indicated Authority item.
776      *
777          * @param parentspecifier either a CSID or one of the urn forms
778          * @param itemspecifier either a CSID or one of the urn forms
779          * @param ui passed to include additional parameters, like pagination controls
780      *
781      * @return the authority refs for the Authority item.
782      */
783     @GET
784     @Path("{csid}/items/{itemcsid}/authorityrefs")
785     @Produces("application/xml")
786     public AuthorityRefList getAuthorityItemAuthorityRefs(
787                 @PathParam("csid") String parentspecifier,
788                 @PathParam("itemcsid") String itemspecifier,
789                 @Context UriInfo ui) {
790         AuthorityRefList authRefList = null;
791         try {
792                         Specifier parentSpec = getSpecifier(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS");
793                         Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS");
794                         // Note that we have to create the service context for the Items, not the main service
795             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
796             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
797                         String parentcsid;
798                         if(parentSpec.form==SpecifierForm.CSID) {
799                                 parentcsid = parentSpec.value;
800                         } else {
801                                 String whereClause = buildWhereForAuthByName(parentSpec.value);
802                     ctx = createServiceContext(getServiceName());
803                                 parentcsid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause);
804                         }
805             ctx = createServiceContext(getItemServiceName(), queryParams);
806             RemoteDocumentModelHandlerImpl handler =
807                 (RemoteDocumentModelHandlerImpl) createItemDocumentHandler(ctx, parentcsid);
808             String itemcsid;
809                         if(itemSpec.form==SpecifierForm.CSID) {
810                                 itemcsid = itemSpec.value;
811                         } else {
812                                 String itemWhereClause = 
813                                         buildWhereForAuthItemByName(itemSpec.value, parentcsid);
814                                 itemcsid = getRepositoryClient(ctx).findDocCSID(ctx, itemWhereClause);
815                         }
816             DocumentWrapper<DocumentModel> docWrapper =
817                getRepositoryClient(ctx).getDoc(ctx, itemcsid);
818             List<String> authRefFields =
819                 ((MultipartServiceContextImpl)ctx).getCommonPartPropertyValues(
820                 ServiceBindingUtils.AUTH_REF_PROP, ServiceBindingUtils.QUALIFIED_PROP_NAMES);
821             authRefList = handler.getAuthorityRefs(docWrapper, authRefFields);
822         } catch (UnauthorizedException ue) {
823             Response response = Response.status(
824                     Response.Status.UNAUTHORIZED).entity("Failed to retrieve authority references: reason " + ue.getErrorReason()).type("text/plain").build();
825             throw new WebApplicationException(response);
826         } catch (Exception e) {
827             if (logger.isDebugEnabled()) {
828                 logger.debug("Caught exception in getAuthorityRefs", e);
829             }
830             Response response = Response.status(
831                     Response.Status.INTERNAL_SERVER_ERROR).entity("Failed to retrieve authority references").type("text/plain").build();
832             throw new WebApplicationException(response);
833         }
834         return authRefList;
835     }
836
837         /**
838          * Update authorityItem.
839          * 
840          * @param parentspecifier either a CSID or one of the urn forms
841          * @param itemspecifier either a CSID or one of the urn forms
842          * @param theUpdate the the update
843          * 
844          * @return the multipart output
845          */
846         @PUT
847         @Path("{csid}/items/{itemcsid}")
848         public byte[] updateAuthorityItem(
849                         @PathParam("csid") String parentspecifier,
850                         @PathParam("itemcsid") String itemspecifier,
851                         String xmlPayload) {
852                 PoxPayloadOut result = null;
853                 try {
854                         PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
855                         Specifier parentSpec = getSpecifier(parentspecifier, 
856                                         "updateAuthorityItem(parent)", "UPDATE_ITEM");
857                         Specifier itemSpec = getSpecifier(itemspecifier, 
858                                         "updateAuthorityItem(item)", "UPDATE_ITEM");
859                         // Note that we have to create the service context for the Items, not the main service
860             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
861                         String parentcsid;
862                         if(parentSpec.form==SpecifierForm.CSID) {
863                                 parentcsid = parentSpec.value;
864                         } else {
865                                 String whereClause = buildWhereForAuthByName(parentSpec.value);
866                     ctx = createServiceContext(getServiceName());
867                                 parentcsid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause);
868                         }
869                         ctx = createServiceContext(getItemServiceName(), theUpdate);
870             String itemcsid;
871                         if(itemSpec.form==SpecifierForm.CSID) {
872                                 itemcsid = itemSpec.value;
873                         } else {
874                                 String itemWhereClause = 
875                                         buildWhereForAuthItemByName(itemSpec.value, parentcsid);
876                                 itemcsid = getRepositoryClient(ctx).findDocCSID(ctx, itemWhereClause);
877                         }
878                         // Note that we have to create the service context for the Items, not the main service
879                         DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
880                         getRepositoryClient(ctx).update(ctx, itemcsid, handler);
881                         result = ctx.getOutput();
882                 } catch (BadRequestException bre) {
883                         Response response = Response.status(
884                                         Response.Status.BAD_REQUEST).entity("Create failed reason " + bre.getErrorReason()).type("text/plain").build();
885                         throw new WebApplicationException(response);
886                 } catch (UnauthorizedException ue) {
887                         Response response = Response.status(
888                                         Response.Status.UNAUTHORIZED).entity("Update failed reason " + ue.getErrorReason()).type("text/plain").build();
889                         throw new WebApplicationException(response);
890                 } catch (DocumentNotFoundException dnfe) {
891                         if (logger.isDebugEnabled()) {
892                                 logger.debug("caught DNF exception in updateAuthorityItem", dnfe);
893                         }
894                         Response response = Response.status(Response.Status.NOT_FOUND).entity(
895                                         "Update failed on AuthorityItem csid=" + itemspecifier).type(
896                                         "text/plain").build();
897                         throw new WebApplicationException(response);
898                 } catch (Exception e) {
899                         Response response = Response.status(
900                                         Response.Status.INTERNAL_SERVER_ERROR).entity("Update failed").type("text/plain").build();
901                         throw new WebApplicationException(response);
902                 }
903                 return result.getBytes();
904         }
905
906         /**
907          * Delete authorityItem.
908          * 
909          * @param parentcsid the parentcsid
910          * @param itemcsid the itemcsid
911          * 
912          * @return the response
913          */
914         @DELETE
915         @Path("{csid}/items/{itemcsid}")
916         public Response deleteAuthorityItem(
917                         @PathParam("csid") String parentcsid,
918                         @PathParam("itemcsid") String itemcsid) {
919                 if (logger.isDebugEnabled()) {
920                         logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
921                 }
922                 if (parentcsid == null || "".equals(parentcsid)) {
923                         logger.error("deleteVocabularyItem: missing csid!");
924                         Response response = Response.status(Response.Status.BAD_REQUEST).entity(
925                                         "delete failed on AuthorityItem parentcsid=" + parentcsid).type(
926                                         "text/plain").build();
927                         throw new WebApplicationException(response);
928                 }
929                 if (itemcsid == null || "".equals(itemcsid)) {
930                         logger.error("deleteVocabularyItem: missing itemcsid!");
931                         Response response = Response.status(Response.Status.BAD_REQUEST).entity(
932                                         "delete failed on AuthorityItem=" + itemcsid).type(
933                                         "text/plain").build();
934                         throw new WebApplicationException(response);
935                 }
936                 try {
937                         // Note that we have to create the service context for the Items, not the main service
938                         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName());
939                         getRepositoryClient(ctx).delete(ctx, itemcsid);
940                         return Response.status(HttpResponseCodes.SC_OK).build();
941                 } catch (UnauthorizedException ue) {
942                         Response response = Response.status(
943                                         Response.Status.UNAUTHORIZED).entity("Delete failed reason " + ue.getErrorReason()).type("text/plain").build();
944                         throw new WebApplicationException(response);
945                 } catch (DocumentNotFoundException dnfe) {
946                         if (logger.isDebugEnabled()) {
947                                 logger.debug("caught exception in deleteAuthorityItem", dnfe);
948                         }
949                         Response response = Response.status(Response.Status.NOT_FOUND).entity(
950                                         "Delete failed on AuthorityItem itemcsid=" + itemcsid).type(
951                                         "text/plain").build();
952                         throw new WebApplicationException(response);
953                 } catch (Exception e) {
954                         Response response = Response.status(
955                                         Response.Status.INTERNAL_SERVER_ERROR).entity("Delete failed").type("text/plain").build();
956                         throw new WebApplicationException(response);
957                 }
958         }
959     
960 }