]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
d84bbacb756173577bc4b6d98b325f6fd1c68712
[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.organization;
25
26 import java.util.List;
27
28 import javax.ws.rs.Consumes;
29 import javax.ws.rs.DELETE;
30 import javax.ws.rs.GET;
31 import javax.ws.rs.POST;
32 import javax.ws.rs.PUT;
33 import javax.ws.rs.Path;
34 import javax.ws.rs.PathParam;
35 import javax.ws.rs.Produces;
36 import javax.ws.rs.QueryParam;
37 import javax.ws.rs.WebApplicationException;
38 import javax.ws.rs.core.Context;
39 import javax.ws.rs.core.MultivaluedMap;
40 import javax.ws.rs.core.Response;
41 import javax.ws.rs.core.UriBuilder;
42 import javax.ws.rs.core.UriInfo;
43
44 import org.collectionspace.services.OrgAuthorityJAXBSchema;
45 import org.collectionspace.services.OrganizationJAXBSchema;
46 import org.collectionspace.services.common.AbstractMultiPartCollectionSpaceResourceImpl;
47 import org.collectionspace.services.common.ClientType;
48 import org.collectionspace.services.common.ServiceMain;
49 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
50 import org.collectionspace.services.common.authorityref.AuthorityRefList;
51 //import org.collectionspace.services.common.context.MultipartServiceContext;
52 //import org.collectionspace.services.common.context.MultipartServiceContextFactory;
53 import org.collectionspace.services.common.context.MultipartServiceContextImpl;
54 //import org.collectionspace.services.common.context.MultipartServiceContextFactory;
55 import org.collectionspace.services.common.context.ServiceBindingUtils;
56 import org.collectionspace.services.common.context.ServiceContext;
57 import org.collectionspace.services.common.document.BadRequestException;
58 import org.collectionspace.services.common.document.DocumentFilter;
59 import org.collectionspace.services.common.document.DocumentHandler;
60 import org.collectionspace.services.common.document.DocumentNotFoundException;
61 import org.collectionspace.services.common.document.DocumentWrapper;
62 import org.collectionspace.services.common.query.IQueryManager;
63 import org.collectionspace.services.common.repository.RepositoryClient;
64 import org.collectionspace.services.contact.ContactResource;
65 import org.collectionspace.services.contact.ContactsCommon;
66 import org.collectionspace.services.contact.ContactsCommonList;
67 import org.collectionspace.services.contact.ContactJAXBSchema;
68 import org.collectionspace.services.contact.nuxeo.ContactDocumentModelHandler;
69 import org.collectionspace.services.common.security.UnauthorizedException;
70 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils;
71 import org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl;
72 import org.collectionspace.services.organization.nuxeo.OrganizationDocumentModelHandler;
73 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
74 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
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 OrgAuthorityResource.
82  */
83 @Path("/orgauthorities")
84 @Consumes("multipart/mixed")
85 @Produces("multipart/mixed")
86 public class OrgAuthorityResource extends
87                 AbstractMultiPartCollectionSpaceResourceImpl {
88
89     /** The Constant orgAuthorityServiceName. */
90     private final static String orgAuthorityServiceName = "orgauthorities";
91     
92     /** The Constant organizationServiceName. */
93     private final static String organizationServiceName = "organizations";
94     
95     /** The logger. */
96     final Logger logger = LoggerFactory.getLogger(OrgAuthorityResource.class);
97     //FIXME retrieve client type from configuration
98     /** The Constant CLIENT_TYPE. */
99     final static ClientType CLIENT_TYPE = ServiceMain.getInstance().getClientType();
100     
101     /** The contact resource. */
102     private ContactResource contactResource = new ContactResource();
103
104     /**
105      * Instantiates a new org authority resource.
106      */
107     public OrgAuthorityResource() {
108         // do nothing
109     }
110
111     /* (non-Javadoc)
112      * @see org.collectionspace.services.common.AbstractCollectionSpaceResourceImpl#getVersionString()
113      */
114     @Override
115     protected String getVersionString() {
116         /** The last change revision. */
117         final String lastChangeRevision = "$LastChangedRevision$";
118         return lastChangeRevision;
119     }
120     
121     /* (non-Javadoc)
122      * @see org.collectionspace.services.common.AbstractCollectionSpaceResourceImpl#getServiceName()
123      */
124     @Override
125     public String getServiceName() {
126         return orgAuthorityServiceName;
127     }
128     
129     /* (non-Javadoc)
130      * @see org.collectionspace.services.common.CollectionSpaceResource#getCommonPartClass()
131      */
132     @Override
133     public Class<OrgauthoritiesCommon> getCommonPartClass() {
134         return OrgauthoritiesCommon.class;
135     }    
136
137     /**
138      * Gets the item service name.
139      * 
140      * @return the item service name
141      */
142     public String getItemServiceName() {
143         return organizationServiceName;
144     }
145
146     /**
147      * Gets the contact service name.
148      * 
149      * @return the contact service name
150      */
151     public String getContactServiceName() {
152         return contactResource.getServiceName();
153     }
154
155     /*
156     public RemoteServiceContext createItemServiceContext(MultipartInput input) throws Exception {
157     RemoteServiceContext ctx = new RemoteServiceContextImpl(getItemServiceName());
158     ctx.setInput(input);
159     return ctx;
160     }
161      */
162     /* (non-Javadoc)
163      * @see org.collectionspace.services.common.AbstractCollectionSpaceResourceImpl#createDocumentHandler(org.collectionspace.services.common.context.ServiceContext)
164      */
165 //    @Override
166 //    public DocumentHandler createDocumentHandler(ServiceContext ctx) throws Exception {
167 //        DocumentHandler docHandler =ctx.getDocumentHandler();
168 //        if (ctx.getInput() != null) {
169 //            Object obj = ((MultipartServiceContext) ctx).getInputPart(ctx.getCommonPartLabel(), OrgauthoritiesCommon.class);
170 //            if (obj != null) {
171 //                docHandler.setCommonPart((OrgauthoritiesCommon) obj);
172 //            }
173 //        }
174 //        return docHandler;
175 //    }
176
177     /**
178      * Creates the item document handler.
179      * 
180      * @param ctx the ctx
181      * @param inAuthority the in authority
182      * 
183      * @return the document handler
184      * 
185      * @throws Exception the exception
186      */
187     private DocumentHandler createItemDocumentHandler(
188                 ServiceContext<MultipartInput, MultipartOutput> ctx,
189             String inAuthority) throws Exception {      
190         OrganizationDocumentModelHandler docHandler = (OrganizationDocumentModelHandler)createDocumentHandler(
191                         ctx,
192                         ctx.getCommonPartLabel(getItemServiceName()),
193                         OrganizationsCommon.class);             
194         docHandler.setInAuthority(inAuthority);
195         
196         
197 //        ((OrganizationDocumentModelHandler) docHandler).setInAuthority(inAuthority);
198 //        if (ctx.getInput() != null) {
199 //            Object obj = ((MultipartServiceContext) ctx).getInputPart(ctx.getCommonPartLabel(getItemServiceName()),
200 //                    OrganizationsCommon.class);
201 //            if (obj != null) {
202 //                docHandler.setCommonPart((OrganizationsCommon) obj);
203 //            }
204 //        }
205
206         return docHandler;
207     }
208
209     /**
210      * Creates the contact document handler.
211      * 
212      * @param ctx the ctx
213      * @param inAuthority the in authority
214      * @param inItem the in item
215      * 
216      * @return the document handler
217      * 
218      * @throws Exception the exception
219      */
220     private DocumentHandler createContactDocumentHandler(
221                 ServiceContext<MultipartInput, MultipartOutput> ctx, String inAuthority,
222             String inItem) throws Exception {
223         
224         ContactDocumentModelHandler docHandler = (ContactDocumentModelHandler)createDocumentHandler(
225                         ctx,
226                         ctx.getCommonPartLabel(getContactServiceName()),
227                         ContactsCommon.class);          
228         docHandler.setInAuthority(inAuthority);
229         docHandler.setInItem(inItem);
230         
231 //        DocumentHandler docHandler = ctx.getDocumentHandler();
232 //        // Set the inAuthority and inItem values, which specify the
233 //        // parent authority (e.g. PersonAuthority, OrgAuthority) and the item
234 //        // (e.g. Person, Organization) with which the Contact is associated.
235 //        ((ContactDocumentModelHandler) docHandler).setInAuthority(inAuthority);
236 //        ((ContactDocumentModelHandler) docHandler).setInItem(inItem);
237 //        if (ctx.getInput() != null) {
238 //            Object obj = ((MultipartServiceContext) ctx)
239 //                .getInputPart(ctx.getCommonPartLabel(getContactServiceName()),
240 //                ContactsCommon.class);
241 //            if (obj != null) {
242 //                docHandler.setCommonPart((ContactsCommon) obj);
243 //            }
244 //        }
245         return docHandler;
246     }
247
248     /**
249      * Creates the org authority.
250      * 
251      * @param input the input
252      * 
253      * @return the response
254      */
255     @POST
256     public Response createOrgAuthority(MultipartInput input) {
257         try {
258                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(input);
259             DocumentHandler handler = createDocumentHandler(ctx);
260             String csid = getRepositoryClient(ctx).create(ctx, handler);
261             //orgAuthorityObject.setCsid(csid);
262             UriBuilder path = UriBuilder.fromResource(OrgAuthorityResource.class);
263             path.path("" + csid);
264             Response response = Response.created(path.build()).build();
265             return response;
266         } catch (BadRequestException bre) {
267             Response response = Response.status(
268                     Response.Status.BAD_REQUEST).entity("Create failed reason " + bre.getErrorReason()).type("text/plain").build();
269             throw new WebApplicationException(response);
270         } catch (UnauthorizedException ue) {
271             Response response = Response.status(
272                     Response.Status.UNAUTHORIZED).entity("Create failed reason " + ue.getErrorReason()).type("text/plain").build();
273             throw new WebApplicationException(response);
274         } catch (Exception e) {
275             if (logger.isDebugEnabled()) {
276                 logger.debug("Caught exception in createOrgAuthority", e);
277             }
278             Response response = Response.status(
279                     Response.Status.INTERNAL_SERVER_ERROR).entity("Create failed").type("text/plain").build();
280             throw new WebApplicationException(response);
281         }
282     }
283
284     /**
285      * Gets the org authority by name.
286      * 
287      * @param specifier the specifier
288      * 
289      * @return the org authority by name
290      */
291     @GET
292     @Path("urn:cspace:name({specifier})")
293     public MultipartOutput getOrgAuthorityByName(@PathParam("specifier") String specifier) {
294         String idValue = null;
295         if (specifier == null) {
296             logger.error("getOrgAuthority: missing name!");
297             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
298                     "get failed on OrgAuthority (missing specifier)").type(
299                     "text/plain").build();
300             throw new WebApplicationException(response);
301         }
302         String whereClause =
303                 OrgAuthorityJAXBSchema.ORGAUTHORITIES_COMMON+
304                 ":"+OrgAuthorityJAXBSchema.DISPLAY_NAME+
305                 "='"+specifier+"'";
306         // We only get a single doc - if there are multiple,
307         // it is an error in use.
308
309         if (logger.isDebugEnabled()) {
310             logger.debug("getOrgAuthority with name=" + specifier);
311         } 
312         MultipartOutput result = null;
313         try {
314                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext();
315             DocumentHandler handler = createDocumentHandler(ctx);
316             DocumentFilter myFilter = new DocumentFilter(whereClause, 0, 1);
317             handler.setDocumentFilter(myFilter);
318             getRepositoryClient(ctx).get(ctx, handler);
319             result = (MultipartOutput) ctx.getOutput();
320         } catch (UnauthorizedException ue) {
321             Response response = Response.status(
322                     Response.Status.UNAUTHORIZED).entity("Get failed reason " + ue.getErrorReason()).type("text/plain").build();
323             throw new WebApplicationException(response);
324         } catch (DocumentNotFoundException dnfe) {
325             if (logger.isDebugEnabled()) {
326                 logger.debug("getOrgAuthority", dnfe);
327             }
328             Response response = Response.status(Response.Status.NOT_FOUND).entity(
329                     "Get failed on OrgAuthority spec=" + specifier).type(
330                     "text/plain").build();
331             throw new WebApplicationException(response);
332         } catch (Exception e) {
333             if (logger.isDebugEnabled()) {
334                 logger.debug("getOrgAuthority", e);
335             }
336             Response response = Response.status(
337                     Response.Status.INTERNAL_SERVER_ERROR).entity("Get failed").type("text/plain").build();
338             throw new WebApplicationException(response);
339         }
340         if (result == null) {
341             Response response = Response.status(Response.Status.NOT_FOUND).entity(
342                     "Get failed, the requested OrgAuthority spec:" + specifier + ": was not found.").type(
343                     "text/plain").build();
344             throw new WebApplicationException(response);
345         }
346         return result;
347     }
348
349     /**
350      * Gets the entities referencing this Organization instance. The service type
351      * can be passed as a query param "type", and must match a configured type
352      * for the service bindings. If not set, the type defaults to
353      * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
354      * @param parentcsid 
355      * 
356      * @param csid the parent csid
357      * @param itemcsid the person csid
358      * @param ui the ui
359      * 
360      * @return the info for the referencing objects
361      */
362     @GET
363     @Path("{csid}/items/{itemcsid}/refObjs")
364     @Produces("application/xml")
365     public AuthorityRefDocList getReferencingObjects(
366                 @PathParam("csid") String parentcsid,
367                 @PathParam("itemcsid") String itemcsid,
368                 @Context UriInfo ui) {
369         AuthorityRefDocList authRefDocList = null;
370         if (logger.isDebugEnabled()) {
371                 logger.debug("getReferencingObjects with parentcsid=" 
372                                 + parentcsid + " and itemcsid=" + itemcsid);
373         }
374         if (parentcsid == null || "".equals(parentcsid)
375                         || itemcsid == null || "".equals(itemcsid)) {
376                 logger.error("getPerson: missing parentcsid or itemcsid!");
377                 Response response = Response.status(Response.Status.BAD_REQUEST).entity(
378                                 "get failed on Person with parentcsid=" 
379                                 + parentcsid + " and itemcsid=" + itemcsid).type(
380                                 "text/plain").build();
381                 throw new WebApplicationException(response);
382         }
383         try {
384                 // Note that we have to create the service context for the Items, not the main service
385                 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
386                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getItemServiceName(), queryParams);
387                 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
388                 RepositoryClient repoClient = getRepositoryClient(ctx); 
389                 DocumentFilter myFilter = handler.getDocumentFilter();
390                 String serviceType = ServiceBindingUtils.SERVICE_TYPE_PROCEDURE;
391                 List<String> list = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
392                 if (list != null) {
393                         serviceType = list.get(0);
394                 }
395                 DocumentWrapper<DocumentModel> docWrapper = repoClient.getDoc(ctx, itemcsid);
396                 DocumentModel docModel = docWrapper.getWrappedObject();
397                 String refName = (String)docModel.getPropertyValue(OrganizationJAXBSchema.REF_NAME);
398
399                 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(ctx,
400                                 repoClient, 
401                                 serviceType,
402                                 refName,
403                                 myFilter.getPageSize(), myFilter.getStartPage(), true );
404         } catch (UnauthorizedException ue) {
405                 Response response = Response.status(
406                                 Response.Status.UNAUTHORIZED).entity("Get failed reason " + ue.getErrorReason()).type("text/plain").build();
407                 throw new WebApplicationException(response);
408         } catch (DocumentNotFoundException dnfe) {
409                 if (logger.isDebugEnabled()) {
410                         logger.debug("getReferencingObjects", dnfe);
411                 }
412                 Response response = Response.status(Response.Status.NOT_FOUND).entity(
413                                 "GetReferencingObjects failed with parentcsid=" 
414                                 + parentcsid + " and itemcsid=" + itemcsid).type(
415                                 "text/plain").build();
416                 throw new WebApplicationException(response);
417         } catch (Exception e) { // Includes DocumentException
418                 if (logger.isDebugEnabled()) {
419                         logger.debug("GetReferencingObjects", e);
420                 }
421                 Response response = Response.status(
422                                 Response.Status.INTERNAL_SERVER_ERROR).entity("Get failed").type("text/plain").build();
423                 throw new WebApplicationException(response);
424         }
425         if (authRefDocList == null) {
426                 Response response = Response.status(Response.Status.NOT_FOUND).entity(
427                                 "Get failed, the requested Person CSID:" + itemcsid + ": was not found.").type(
428                                 "text/plain").build();
429                 throw new WebApplicationException(response);
430         }
431         return authRefDocList;
432     }
433
434     
435     /**
436      * Gets the org authority.
437      * 
438      * @param csid the csid
439      * 
440      * @return the org authority
441      */
442     @GET
443     @Path("{csid}")
444     public MultipartOutput getOrgAuthority(@PathParam("csid") String csid) {
445         String idValue = null;
446         if (csid == null) {
447             logger.error("getOrgAuthority: missing csid!");
448             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
449                     "get failed on OrgAuthority csid=" + csid).type(
450                     "text/plain").build();
451             throw new WebApplicationException(response);
452         }
453         if (logger.isDebugEnabled()) {
454             logger.debug("getOrgAuthority with path(id)=" + csid);
455         }
456         MultipartOutput result = null;
457         try {
458                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext();
459             DocumentHandler handler = createDocumentHandler(ctx);
460             getRepositoryClient(ctx).get(ctx, csid, handler);
461             result = (MultipartOutput) ctx.getOutput();
462         } catch (UnauthorizedException ue) {
463             Response response = Response.status(
464                     Response.Status.UNAUTHORIZED).entity("Get failed reason " + ue.getErrorReason()).type("text/plain").build();
465             throw new WebApplicationException(response);
466         } catch (DocumentNotFoundException dnfe) {
467             if (logger.isDebugEnabled()) {
468                 logger.debug("getOrgAuthority", dnfe);
469             }
470             Response response = Response.status(Response.Status.NOT_FOUND).entity(
471                     "Get failed on OrgAuthority csid=" + csid).type(
472                     "text/plain").build();
473             throw new WebApplicationException(response);
474         } catch (Exception e) {
475             if (logger.isDebugEnabled()) {
476                 logger.debug("getOrgAuthority", e);
477             }
478             Response response = Response.status(
479                     Response.Status.INTERNAL_SERVER_ERROR).entity("Get failed").type("text/plain").build();
480             throw new WebApplicationException(response);
481         }
482         if (result == null) {
483             Response response = Response.status(Response.Status.NOT_FOUND).entity(
484                     "Get failed, the requested OrgAuthority CSID:" + csid + ": was not found.").type(
485                     "text/plain").build();
486             throw new WebApplicationException(response);
487         }
488         return result;
489     }
490
491     /**
492      * Gets the org authority list.
493      * 
494      * @param ui the ui
495      * 
496      * @return the org authority list
497      */
498     @GET
499     @Produces("application/xml")
500     public OrgauthoritiesCommonList getOrgAuthorityList(@Context UriInfo ui) {
501         OrgauthoritiesCommonList orgAuthorityObjectList = new OrgauthoritiesCommonList();
502         try {
503             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
504                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(queryParams);
505             DocumentHandler handler = createDocumentHandler(ctx);
506             DocumentFilter myFilter = handler.getDocumentFilter();
507             String nameQ = queryParams.getFirst("refName");
508             if (nameQ != null) {
509                 myFilter.setWhereClause("orgauthorities_common:refName='" + nameQ + "'");
510             }
511             getRepositoryClient(ctx).getFiltered(ctx, handler);
512             orgAuthorityObjectList = (OrgauthoritiesCommonList) handler.getCommonPartList();
513         } catch (UnauthorizedException ue) {
514             Response response = Response.status(
515                     Response.Status.UNAUTHORIZED).entity("Index failed reason " + ue.getErrorReason()).type("text/plain").build();
516             throw new WebApplicationException(response);
517         } catch (Exception e) {
518             if (logger.isDebugEnabled()) {
519                 logger.debug("Caught exception in getOrgAuthorityList", e);
520             }
521             Response response = Response.status(
522                     Response.Status.INTERNAL_SERVER_ERROR).entity("Index failed").type("text/plain").build();
523             throw new WebApplicationException(response);
524         }
525         return orgAuthorityObjectList;
526     }
527
528     /**
529      * Update org authority.
530      * 
531      * @param csid the csid
532      * @param theUpdate the the update
533      * 
534      * @return the multipart output
535      */
536     @PUT
537     @Path("{csid}")
538     public MultipartOutput updateOrgAuthority(
539             @PathParam("csid") String csid,
540             MultipartInput theUpdate) {
541         if (logger.isDebugEnabled()) {
542             logger.debug("updateOrgAuthority with csid=" + csid);
543         }
544         if (csid == null || "".equals(csid)) {
545             logger.error("updateOrgAuthority: missing csid!");
546             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
547                     "update failed on OrgAuthority csid=" + csid).type(
548                     "text/plain").build();
549             throw new WebApplicationException(response);
550         }
551         MultipartOutput result = null;
552         try {
553                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(theUpdate);
554             DocumentHandler handler = createDocumentHandler(ctx);
555             getRepositoryClient(ctx).update(ctx, csid, handler);
556             result = (MultipartOutput) ctx.getOutput();
557         } catch (BadRequestException bre) {
558             Response response = Response.status(
559                     Response.Status.BAD_REQUEST).entity("Create failed reason " + bre.getErrorReason()).type("text/plain").build();
560             throw new WebApplicationException(response);
561         } catch (UnauthorizedException ue) {
562             Response response = Response.status(
563                     Response.Status.UNAUTHORIZED).entity("Update failed reason " + ue.getErrorReason()).type("text/plain").build();
564             throw new WebApplicationException(response);
565         } catch (DocumentNotFoundException dnfe) {
566             if (logger.isDebugEnabled()) {
567                 logger.debug("caught exception in updateOrgAuthority", dnfe);
568             }
569             Response response = Response.status(Response.Status.NOT_FOUND).entity(
570                     "Update failed on OrgAuthority csid=" + csid).type(
571                     "text/plain").build();
572             throw new WebApplicationException(response);
573         } catch (Exception e) {
574             Response response = Response.status(
575                     Response.Status.INTERNAL_SERVER_ERROR).entity("Update failed").type("text/plain").build();
576             throw new WebApplicationException(response);
577         }
578         return result;
579     }
580
581     /**
582      * Delete org authority.
583      * 
584      * @param csid the csid
585      * 
586      * @return the response
587      */
588     @DELETE
589     @Path("{csid}")
590     public Response deleteOrgAuthority(@PathParam("csid") String csid) {
591
592         if (logger.isDebugEnabled()) {
593             logger.debug("deleteOrgAuthority with csid=" + csid);
594         }
595         if (csid == null || "".equals(csid)) {
596             logger.error("deleteOrgAuthority: missing csid!");
597             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
598                     "delete failed on OrgAuthority csid=" + csid).type(
599                     "text/plain").build();
600             throw new WebApplicationException(response);
601         }
602         try {
603                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext();
604             getRepositoryClient(ctx).delete(ctx, csid);
605             return Response.status(HttpResponseCodes.SC_OK).build();
606         } catch (UnauthorizedException ue) {
607             Response response = Response.status(
608                     Response.Status.UNAUTHORIZED).entity("Delete failed reason " + ue.getErrorReason()).type("text/plain").build();
609             throw new WebApplicationException(response);
610         } catch (DocumentNotFoundException dnfe) {
611             if (logger.isDebugEnabled()) {
612                 logger.debug("caught exception in deleteOrgAuthority", dnfe);
613             }
614             Response response = Response.status(Response.Status.NOT_FOUND).entity(
615                     "Delete failed on OrgAuthority csid=" + csid).type(
616                     "text/plain").build();
617             throw new WebApplicationException(response);
618         } catch (Exception e) {
619             Response response = Response.status(
620                     Response.Status.INTERNAL_SERVER_ERROR).entity("Delete failed").type("text/plain").build();
621             throw new WebApplicationException(response);
622         }
623
624     }
625
626     /*************************************************************************
627      * Organization parts - this is a sub-resource of OrgAuthority
628      *************************************************************************/
629     @POST
630     @Path("{csid}/items")
631     public Response createOrganization(@PathParam("csid") String parentcsid, MultipartInput input) {
632         try {
633                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getItemServiceName(),
634                                 input);
635             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
636             String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
637             UriBuilder path = UriBuilder.fromResource(OrgAuthorityResource.class);
638             path.path(parentcsid + "/items/" + itemcsid);
639             Response response = Response.created(path.build()).build();
640             return response;
641         } catch (BadRequestException bre) {
642             Response response = Response.status(
643                     Response.Status.BAD_REQUEST).entity("Create failed reason " + bre.getErrorReason()).type("text/plain").build();
644             throw new WebApplicationException(response);
645         } catch (UnauthorizedException ue) {
646             Response response = Response.status(
647                     Response.Status.UNAUTHORIZED).entity("Create failed reason " + ue.getErrorReason()).type("text/plain").build();
648             throw new WebApplicationException(response);
649         } catch (Exception e) {
650             if (logger.isDebugEnabled()) {
651                 logger.debug("Caught exception in createOrganization", e);
652             }
653             Response response = Response.status(
654                     Response.Status.INTERNAL_SERVER_ERROR).entity("Create failed").type("text/plain").build();
655             throw new WebApplicationException(response);
656         }
657     }
658
659     /**
660      * Gets the organization.
661      * 
662      * @param csid The organization authority (parent) CSID.
663      * @param itemcsid The organization item CSID.
664      * 
665      * @return the organization.
666      */
667     @GET
668     @Path("{csid}/items/{itemcsid}")
669     public MultipartOutput getOrganization(
670             @PathParam("csid") String parentcsid,
671             @PathParam("itemcsid") String itemcsid) {
672         if (logger.isDebugEnabled()) {
673             logger.debug("getOrganization with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
674         }
675         if (parentcsid == null || "".equals(parentcsid)) {
676             logger.error("getOrganization: missing csid!");
677             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
678                     "get failed on Organization csid=" + parentcsid).type(
679                     "text/plain").build();
680             throw new WebApplicationException(response);
681         }
682         if (itemcsid == null || "".equals(itemcsid)) {
683             logger.error("getOrganization: missing itemcsid!");
684             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
685                     "get failed on Organization itemcsid=" + itemcsid).type(
686                     "text/plain").build();
687             throw new WebApplicationException(response);
688         }
689         MultipartOutput result = null;
690         try {
691             // Note that we have to create the service context for the Items, not the main service
692                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getItemServiceName());
693             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
694             getRepositoryClient(ctx).get(ctx, itemcsid, handler);
695             // TODO should we assert that the item is in the passed orgAuthority?
696             result = (MultipartOutput) ctx.getOutput();
697         } catch (UnauthorizedException ue) {
698             Response response = Response.status(
699                     Response.Status.UNAUTHORIZED).entity("Get failed reason " + ue.getErrorReason()).type("text/plain").build();
700             throw new WebApplicationException(response);
701         } catch (DocumentNotFoundException dnfe) {
702             if (logger.isDebugEnabled()) {
703                 logger.debug("getOrganization", dnfe);
704             }
705             Response response = Response.status(Response.Status.NOT_FOUND).entity(
706                     "Get failed on Organization csid=" + itemcsid).type(
707                     "text/plain").build();
708             throw new WebApplicationException(response);
709         } catch (Exception e) {
710             if (logger.isDebugEnabled()) {
711                 logger.debug("getOrganization", e);
712             }
713             Response response = Response.status(
714                     Response.Status.INTERNAL_SERVER_ERROR).entity("Get failed").type("text/plain").build();
715             throw new WebApplicationException(response);
716         }
717         if (result == null) {
718             Response response = Response.status(Response.Status.NOT_FOUND).entity(
719                     "Get failed, the requested Organization CSID:" + itemcsid + ": was not found.").type(
720                     "text/plain").build();
721             throw new WebApplicationException(response);
722         }
723         return result;
724     }
725
726     /**
727      * Gets the authority refs for an Organization item.
728      *
729      * @param csid The organization authority (parent) CSID.
730      * @param itemcsid The organization item CSID.
731      *
732      * @return the authority refs for the Organization item.
733      */
734     @GET
735     @Path("{csid}/items/{itemcsid}/authorityrefs")
736     @Produces("application/xml")
737     public AuthorityRefList getOrganizationAuthorityRefs(
738                 @PathParam("csid") String parentcsid,
739                 @PathParam("itemcsid") String itemcsid,
740                 @Context UriInfo ui) {
741         AuthorityRefList authRefList = null;
742         try {
743             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
744             ServiceContext<MultipartInput, MultipartOutput> ctx =
745                 createServiceContext(getItemServiceName(), queryParams);
746             RemoteDocumentModelHandlerImpl handler =
747                 (RemoteDocumentModelHandlerImpl) createItemDocumentHandler(ctx, parentcsid);
748             DocumentWrapper<DocumentModel> docWrapper =
749                getRepositoryClient(ctx).getDoc(ctx, itemcsid);
750             List<String> authRefFields =
751                 ((MultipartServiceContextImpl)ctx).getCommonPartPropertyValues(
752                 ServiceBindingUtils.AUTH_REF_PROP, ServiceBindingUtils.QUALIFIED_PROP_NAMES);
753             authRefList = handler.getAuthorityRefs(docWrapper, authRefFields);
754         } catch (UnauthorizedException ue) {
755             Response response = Response.status(
756                     Response.Status.UNAUTHORIZED).entity("Failed to retrieve authority references: reason " + ue.getErrorReason()).type("text/plain").build();
757             throw new WebApplicationException(response);
758         } catch (Exception e) {
759             if (logger.isDebugEnabled()) {
760                 logger.debug("Caught exception in getAuthorityRefs", e);
761             }
762             Response response = Response.status(
763                     Response.Status.INTERNAL_SERVER_ERROR).entity("Failed to retrieve authority references").type("text/plain").build();
764             throw new WebApplicationException(response);
765         }
766         return authRefList;
767     }
768
769     /**
770      * Gets the organization list.
771      * 
772      * @param parentcsid the parentcsid
773      * @param partialTerm the partial term
774      * @param ui the ui
775      * 
776      * @return the organization list
777      */
778     @GET
779     @Path("{csid}/items")
780     @Produces("application/xml")
781     public OrganizationsCommonList getOrganizationList(
782             @PathParam("csid") String parentcsid,
783             @QueryParam (IQueryManager.SEARCH_TYPE_PARTIALTERM) String partialTerm,
784             @Context UriInfo ui) {
785         OrganizationsCommonList organizationObjectList = new OrganizationsCommonList();
786         try {
787             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
788             // Note that docType defaults to the ServiceName, so we're fine with that.
789                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getItemServiceName(),
790                                 queryParams);
791             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
792             DocumentFilter myFilter = handler.getDocumentFilter(); //new DocumentFilter();
793             myFilter.setWhereClause(OrganizationJAXBSchema.ORGANIZATIONS_COMMON +
794                         ":" + OrganizationJAXBSchema.IN_AUTHORITY + "=" +
795                         "'" + parentcsid + "'");
796             
797             // AND organizations_common:displayName LIKE '%partialTerm%'
798             if (partialTerm != null && !partialTerm.isEmpty()) {
799                 String ptClause = "AND " + OrganizationJAXBSchema.ORGANIZATIONS_COMMON +
800                         ":" + OrganizationJAXBSchema.DISPLAY_NAME +
801                         " LIKE " + "'%" + partialTerm + "%'";
802                 myFilter.appendWhereClause(ptClause);
803             }            
804             getRepositoryClient(ctx).getFiltered(ctx, handler);
805             organizationObjectList = (OrganizationsCommonList) handler.getCommonPartList();
806         } catch (UnauthorizedException ue) {
807             Response response = Response.status(
808                     Response.Status.UNAUTHORIZED).entity("Index failed reason " + ue.getErrorReason()).type("text/plain").build();
809             throw new WebApplicationException(response);
810         } catch (Exception e) {
811             if (logger.isDebugEnabled()) {
812                 logger.debug("Caught exception in getOrganizationList", e);
813             }
814             Response response = Response.status(
815                     Response.Status.INTERNAL_SERVER_ERROR).entity("Index failed").type("text/plain").build();
816             throw new WebApplicationException(response);
817         }
818         return organizationObjectList;
819     }
820
821     /**
822      * Gets the organization list by auth name.
823      * 
824      * @param parentSpecifier the parent specifier
825      * @param partialTerm the partial term
826      * @param ui the ui
827      * 
828      * @return the organization list by auth name
829      */
830     @GET
831     @Path("urn:cspace:name({specifier})/items")
832     @Produces("application/xml")
833     public OrganizationsCommonList getOrganizationListByAuthName(
834                 @PathParam("specifier") String parentSpecifier,
835             @QueryParam (IQueryManager.SEARCH_TYPE_PARTIALTERM) String partialTerm,            
836             @Context UriInfo ui) {
837         OrganizationsCommonList personObjectList = new OrganizationsCommonList();
838         try {
839             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
840             String whereClause =
841                 OrgAuthorityJAXBSchema.ORGAUTHORITIES_COMMON+
842                 ":" + OrgAuthorityJAXBSchema.DISPLAY_NAME+
843                 "='" + parentSpecifier+"'";
844             // Need to get an Authority by name
845             ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(queryParams);
846             String parentcsid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause);
847
848             ctx = createServiceContext(getItemServiceName(), queryParams);
849             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
850             DocumentFilter myFilter = handler.getDocumentFilter();// new DocumentFilter();
851
852             // Add the where clause "organizations_common:inAuthority='" + parentcsid + "'"
853             myFilter.setWhereClause(OrganizationJAXBSchema.ORGANIZATIONS_COMMON + ":" +
854                         OrganizationJAXBSchema.IN_AUTHORITY + "='" + parentcsid + "'");
855             
856             // AND organizations_common:displayName LIKE '%partialTerm%'
857             if (partialTerm != null && !partialTerm.isEmpty()) {
858                 String ptClause = "AND " +
859                 OrganizationJAXBSchema.ORGANIZATIONS_COMMON + ":" +
860                 OrganizationJAXBSchema.DISPLAY_NAME +
861                         " LIKE " +
862                         "'%" + partialTerm + "%'";
863                 myFilter.appendWhereClause(ptClause);
864             }            
865             getRepositoryClient(ctx).getFiltered(ctx, handler);
866             personObjectList = (OrganizationsCommonList) handler.getCommonPartList();
867         } catch (UnauthorizedException ue) {
868             Response response = Response.status(
869                     Response.Status.UNAUTHORIZED).entity("Index failed reason " + ue.getErrorReason()).type("text/plain").build();
870             throw new WebApplicationException(response);
871         } catch (Exception e) {
872             if (logger.isDebugEnabled()) {
873                 logger.debug("Caught exception in getOrganizationListByAuthName", e);
874             }
875             Response response = Response.status(
876                     Response.Status.INTERNAL_SERVER_ERROR).entity("Index failed").type("text/plain").build();
877             throw new WebApplicationException(response);
878         }
879         return personObjectList;
880     }
881
882     /**
883      * Update organization.
884      * 
885      * @param parentcsid the parentcsid
886      * @param itemcsid the itemcsid
887      * @param theUpdate the the update
888      * 
889      * @return the multipart output
890      */
891     @PUT
892     @Path("{csid}/items/{itemcsid}")
893     public MultipartOutput updateOrganization(
894             @PathParam("csid") String parentcsid,
895             @PathParam("itemcsid") String itemcsid,
896             MultipartInput theUpdate) {
897         if (logger.isDebugEnabled()) {
898             logger.debug("updateOrganization with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
899         }
900         if (parentcsid == null || "".equals(parentcsid)) {
901             logger.error("updateOrganization: missing csid!");
902             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
903                     "update failed on Organization parentcsid=" + parentcsid).type(
904                     "text/plain").build();
905             throw new WebApplicationException(response);
906         }
907         if (itemcsid == null || "".equals(itemcsid)) {
908             logger.error("updateOrganization: missing itemcsid!");
909             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
910                     "update failed on Organization=" + itemcsid).type(
911                     "text/plain").build();
912             throw new WebApplicationException(response);
913         }
914         MultipartOutput result = null;
915         try {
916             // Note that we have to create the service context for the Items, not the main service
917                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getItemServiceName(),
918                                 theUpdate);
919             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
920             getRepositoryClient(ctx).update(ctx, itemcsid, handler);
921             result = (MultipartOutput) ctx.getOutput();
922         } catch (BadRequestException bre) {
923             Response response = Response.status(
924                     Response.Status.BAD_REQUEST).entity("Create failed reason " + bre.getErrorReason()).type("text/plain").build();
925             throw new WebApplicationException(response);
926         } catch (UnauthorizedException ue) {
927             Response response = Response.status(
928                     Response.Status.UNAUTHORIZED).entity("Update failed reason " + ue.getErrorReason()).type("text/plain").build();
929             throw new WebApplicationException(response);
930         } catch (DocumentNotFoundException dnfe) {
931             if (logger.isDebugEnabled()) {
932                 logger.debug("caught exception in updateOrganization", dnfe);
933             }
934             Response response = Response.status(Response.Status.NOT_FOUND).entity(
935                     "Update failed on Organization csid=" + itemcsid).type(
936                     "text/plain").build();
937             throw new WebApplicationException(response);
938         } catch (Exception e) {
939             Response response = Response.status(
940                     Response.Status.INTERNAL_SERVER_ERROR).entity("Update failed").type("text/plain").build();
941             throw new WebApplicationException(response);
942         }
943         return result;
944     }
945
946     /**
947      * Delete organization.
948      * 
949      * @param parentcsid the parentcsid
950      * @param itemcsid the itemcsid
951      * 
952      * @return the response
953      */
954     @DELETE
955     @Path("{csid}/items/{itemcsid}")
956     public Response deleteOrganization(
957             @PathParam("csid") String parentcsid,
958             @PathParam("itemcsid") String itemcsid) {
959         if (logger.isDebugEnabled()) {
960             logger.debug("deleteOrganization with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
961         }
962         if (parentcsid == null || "".equals(parentcsid)) {
963             logger.error("deleteOrganization: missing csid!");
964             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
965                     "delete failed on Organization parentcsid=" + parentcsid).type(
966                     "text/plain").build();
967             throw new WebApplicationException(response);
968         }
969         if (itemcsid == null || "".equals(itemcsid)) {
970             logger.error("deleteOrganization: missing itemcsid!");
971             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
972                     "delete failed on Organization=" + itemcsid).type(
973                     "text/plain").build();
974             throw new WebApplicationException(response);
975         }
976         try {
977             // Note that we have to create the service context for the Items, not the main service
978                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getItemServiceName());
979             getRepositoryClient(ctx).delete(ctx, itemcsid);
980             return Response.status(HttpResponseCodes.SC_OK).build();
981         } catch (UnauthorizedException ue) {
982             Response response = Response.status(
983                     Response.Status.UNAUTHORIZED).entity("Delete failed reason " + ue.getErrorReason()).type("text/plain").build();
984             throw new WebApplicationException(response);
985         } catch (DocumentNotFoundException dnfe) {
986             if (logger.isDebugEnabled()) {
987                 logger.debug("caught exception in deleteOrganization", dnfe);
988             }
989             Response response = Response.status(Response.Status.NOT_FOUND).entity(
990                     "Delete failed on Organization itemcsid=" + itemcsid).type(
991                     "text/plain").build();
992             throw new WebApplicationException(response);
993         } catch (Exception e) {
994             Response response = Response.status(
995                     Response.Status.INTERNAL_SERVER_ERROR).entity("Delete failed").type("text/plain").build();
996             throw new WebApplicationException(response);
997         }
998
999     }
1000
1001     /*************************************************************************
1002      * Contact parts - this is a sub-resource of Organization (or "item")
1003      *************************************************************************/
1004     @POST
1005     @Path("{parentcsid}/items/{itemcsid}/contacts")
1006     public Response createContact(
1007             @PathParam("parentcsid") String parentcsid,
1008             @PathParam("itemcsid") String itemcsid,
1009             MultipartInput input) {
1010         try {
1011             // Note that we have to create the service context and document
1012             // handler for the Contact service, not the main service.
1013                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getContactServiceName(), input);
1014             DocumentHandler handler = createContactDocumentHandler(ctx, parentcsid, itemcsid);
1015             String csid = getRepositoryClient(ctx).create(ctx, handler);
1016             UriBuilder path = UriBuilder.fromResource(OrgAuthorityResource.class);
1017             path.path("" + parentcsid + "/items/" + itemcsid + "/contacts/" + csid);
1018             Response response = Response.created(path.build()).build();
1019             return response;
1020         } catch (BadRequestException bre) {
1021             Response response = Response.status(
1022                     Response.Status.BAD_REQUEST).entity("Create failed reason " + bre.getErrorReason()).type("text/plain").build();
1023             throw new WebApplicationException(response);
1024         } catch (UnauthorizedException ue) {
1025             Response response = Response.status(
1026                     Response.Status.UNAUTHORIZED).entity("Create failed reason " + ue.getErrorReason()).type("text/plain").build();
1027             throw new WebApplicationException(response);
1028         } catch (Exception e) {
1029             if (logger.isDebugEnabled()) {
1030                 logger.debug("Caught exception in createContact", e);
1031             }
1032             Response response = Response.status(
1033                 Response.Status.INTERNAL_SERVER_ERROR)
1034                 .entity("Attempt to create Contact failed.")
1035                 .type("text/plain").build();
1036             throw new WebApplicationException(response);
1037         }
1038
1039     }
1040
1041     /**
1042      * Gets the contact list.
1043      * 
1044      * @param parentcsid the parentcsid
1045      * @param itemcsid the itemcsid
1046      * @param ui the ui
1047      * 
1048      * @return the contact list
1049      */
1050     @GET
1051     @Produces({"application/xml"})
1052     @Path("{parentcsid}/items/{itemcsid}/contacts/")
1053     public ContactsCommonList getContactList(
1054             @PathParam("parentcsid") String parentcsid,
1055             @PathParam("itemcsid") String itemcsid,
1056             @Context UriInfo ui) {
1057         ContactsCommonList contactObjectList = new ContactsCommonList();
1058         try {
1059             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
1060                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getContactServiceName(),
1061                                 queryParams);
1062             DocumentHandler handler = createContactDocumentHandler(ctx, parentcsid, itemcsid);
1063             DocumentFilter myFilter = handler.getDocumentFilter(); //new DocumentFilter();
1064             myFilter.setWhereClause(ContactJAXBSchema.CONTACTS_COMMON + ":" +
1065                 ContactJAXBSchema.IN_AUTHORITY +
1066                 "='" + parentcsid + "'" +
1067                 " AND " +
1068                 ContactJAXBSchema.CONTACTS_COMMON + ":" +
1069                 ContactJAXBSchema.IN_ITEM +
1070                 "='" + itemcsid + "'" +
1071                 " AND ecm:isProxy = 0");
1072             getRepositoryClient(ctx).getFiltered(ctx, handler);
1073             contactObjectList = (ContactsCommonList) handler.getCommonPartList();
1074         } catch (UnauthorizedException ue) {
1075             Response response = Response.status(
1076                     Response.Status.UNAUTHORIZED).entity("Index failed reason " + ue.getErrorReason()).type("text/plain").build();
1077             throw new WebApplicationException(response);
1078         } catch (Exception e) {
1079             if (logger.isDebugEnabled()) {
1080                 logger.debug("Caught exception in getContactsList", e);
1081             }
1082             Response response = Response.status(
1083                     Response.Status.INTERNAL_SERVER_ERROR).entity("Index failed").type("text/plain").build();
1084             throw new WebApplicationException(response);
1085         }
1086         return contactObjectList;
1087     }
1088
1089     /**
1090      * Gets the contact.
1091      * 
1092      * @param parentcsid the parentcsid
1093      * @param itemcsid the itemcsid
1094      * @param csid the csid
1095      * 
1096      * @return the contact
1097      */
1098     @GET
1099     @Path("{parentcsid}/items/{itemcsid}/contacts/{csid}")
1100     public MultipartOutput getContact(
1101             @PathParam("parentcsid") String parentcsid,
1102             @PathParam("itemcsid") String itemcsid,
1103             @PathParam("csid") String csid) {
1104         MultipartOutput result = null;
1105        if (logger.isDebugEnabled()) {
1106             logger.debug("getContact with parentCsid=" + parentcsid +
1107             " itemcsid=" + itemcsid + " csid=" + csid);
1108         }
1109         try {
1110             // Note that we have to create the service context and document
1111             // handler for the Contact service, not the main service.
1112                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getContactServiceName());
1113             DocumentHandler handler = createContactDocumentHandler(ctx, parentcsid, itemcsid);
1114             getRepositoryClient(ctx).get(ctx, csid, handler);
1115             result = (MultipartOutput) ctx.getOutput();
1116         } catch (UnauthorizedException ue) {
1117             Response response = Response.status(
1118                     Response.Status.UNAUTHORIZED).entity("Get failed reason " + ue.getErrorReason()).type("text/plain").build();
1119             throw new WebApplicationException(response);
1120         } catch (DocumentNotFoundException dnfe) {
1121             if (logger.isDebugEnabled()) {
1122                 logger.debug("getContact", dnfe);
1123             }
1124             Response response = Response.status(Response.Status.NOT_FOUND)
1125                 .entity("Get failed, the requested Contact CSID:" + csid + ": was not found.")
1126                 .type("text/plain").build();
1127             throw new WebApplicationException(response);
1128         } catch (Exception e) {
1129             if (logger.isDebugEnabled()) {
1130                 logger.debug("getContact", e);
1131             }
1132             Response response = Response.status(Response.Status.INTERNAL_SERVER_ERROR)
1133                 .entity("Get contact failed")
1134                 .type("text/plain").build();
1135             throw new WebApplicationException(response);
1136         }
1137         if (result == null) {
1138             Response response = Response.status(Response.Status.NOT_FOUND)
1139                 .entity("Get failed, the requested Contact CSID:" + csid + ": was not found.")
1140                 .type("text/plain").build();
1141             throw new WebApplicationException(response);
1142         }
1143         return result;
1144
1145     }
1146
1147     /**
1148      * Update contact.
1149      * 
1150      * @param parentcsid the parentcsid
1151      * @param itemcsid the itemcsid
1152      * @param csid the csid
1153      * @param theUpdate the the update
1154      * 
1155      * @return the multipart output
1156      */
1157     @PUT
1158     @Path("{parentcsid}/items/{itemcsid}/contacts/{csid}")
1159     public MultipartOutput updateContact(
1160             @PathParam("parentcsid") String parentcsid,
1161             @PathParam("itemcsid") String itemcsid,
1162             @PathParam("csid") String csid,
1163             MultipartInput theUpdate) {
1164        if (logger.isDebugEnabled()) {
1165             logger.debug("updateContact with parentcsid=" + parentcsid +
1166             " itemcsid=" + itemcsid + " csid=" + csid);
1167         }
1168        if (parentcsid == null || parentcsid.trim().isEmpty()) {
1169             logger.error("updateContact: missing csid!");
1170             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
1171                     "update failed on Contact parentcsid=" + parentcsid).type(
1172                     "text/plain").build();
1173             throw new WebApplicationException(response);
1174         }
1175         if (itemcsid == null || itemcsid.trim().isEmpty()) {
1176             logger.error("updateContact: missing itemcsid!");
1177             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
1178                     "update failed on Contact=" + itemcsid).type(
1179                     "text/plain").build();
1180             throw new WebApplicationException(response);
1181         }
1182         if (csid == null || csid.trim().isEmpty()) {
1183             logger.error("updateContact: missing csid!");
1184             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
1185                     "update failed on Contact=" + csid).type(
1186                     "text/plain").build();
1187             throw new WebApplicationException(response);
1188         }
1189         MultipartOutput result = null;
1190         try {
1191             // Note that we have to create the service context and document
1192             // handler for the Contact service, not the main service.
1193                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getContactServiceName(), theUpdate);
1194             DocumentHandler handler = createContactDocumentHandler(ctx, parentcsid, itemcsid);
1195             getRepositoryClient(ctx).update(ctx, csid, handler);
1196             result = (MultipartOutput) ctx.getOutput();
1197         } catch (BadRequestException bre) {
1198             Response response = Response.status(
1199                     Response.Status.BAD_REQUEST).entity("Create failed reason " + bre.getErrorReason()).type("text/plain").build();
1200             throw new WebApplicationException(response);
1201         } catch (UnauthorizedException ue) {
1202             Response response = Response.status(
1203                     Response.Status.UNAUTHORIZED).entity("Update failed reason " + ue.getErrorReason()).type("text/plain").build();
1204             throw new WebApplicationException(response);
1205         } catch (DocumentNotFoundException dnfe) {
1206             if (logger.isDebugEnabled()) {
1207                 logger.debug("caught exception in updateContact", dnfe);
1208             }
1209             Response response = Response.status(Response.Status.NOT_FOUND).entity(
1210                     "Update failed on Contact csid=" + itemcsid).type(
1211                     "text/plain").build();
1212             throw new WebApplicationException(response);
1213         } catch (Exception e) {
1214             Response response = Response.status(
1215                     Response.Status.INTERNAL_SERVER_ERROR).entity("Update failed").type("text/plain").build();
1216             throw new WebApplicationException(response);
1217         }
1218         return result;
1219     }
1220
1221     /**
1222      * Delete contact.
1223      * 
1224      * @param parentcsid the parentcsid
1225      * @param itemcsid the itemcsid
1226      * @param csid the csid
1227      * 
1228      * @return the response
1229      */
1230     @DELETE
1231     @Path("{parentcsid}/items/{itemcsid}/contacts/{csid}")
1232     public Response deleteContact(
1233             @PathParam("parentcsid") String parentcsid,
1234             @PathParam("itemcsid") String itemcsid,
1235             @PathParam("csid") String csid) {
1236         if (logger.isDebugEnabled()) {
1237             logger.debug("deleteContact with parentCsid=" + parentcsid +
1238             " itemcsid=" + itemcsid + " csid=" + csid);
1239         }
1240         if (parentcsid == null || parentcsid.trim().isEmpty()) {
1241             logger.error("deleteContact: missing parentcsid!");
1242             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
1243                     "delete contact failed on parentcsid=" + parentcsid).type(
1244                     "text/plain").build();
1245             throw new WebApplicationException(response);
1246         }
1247         if (itemcsid == null || itemcsid.trim().isEmpty()) {
1248             logger.error("deleteContact: missing itemcsid!");
1249             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
1250                     "delete contact failed on itemcsid=" + itemcsid).type(
1251                     "text/plain").build();
1252             throw new WebApplicationException(response);
1253         }
1254         if (csid == null || csid.trim().isEmpty()) {
1255             logger.error("deleteContact: missing csid!");
1256             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
1257                     "delete contact failed on csid=" + csid).type(
1258                     "text/plain").build();
1259             throw new WebApplicationException(response);
1260         }
1261         try {
1262             // Note that we have to create the service context for the
1263             // Contact service, not the main service.
1264                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getContactServiceName());
1265             getRepositoryClient(ctx).delete(ctx, csid);
1266             return Response.status(HttpResponseCodes.SC_OK).build();
1267          } catch (UnauthorizedException ue) {
1268             Response response = Response.status(
1269                     Response.Status.UNAUTHORIZED).entity("Delete failed reason " + ue.getErrorReason()).type("text/plain").build();
1270             throw new WebApplicationException(response);
1271          } catch (DocumentNotFoundException dnfe) {
1272             if (logger.isDebugEnabled()) {
1273                 logger.debug("Caught exception in deleteContact", dnfe);
1274             }
1275             Response response = Response.status(Response.Status.NOT_FOUND)
1276                 .entity("Delete failed, the requested Contact CSID:" + csid + ": was not found.")
1277                 .type("text/plain").build();
1278             throw new WebApplicationException(response);
1279        } catch (Exception e) {
1280             Response response = Response.status(
1281                     Response.Status.INTERNAL_SERVER_ERROR).entity("Delete failed").type("text/plain").build();
1282             throw new WebApplicationException(response);
1283         }
1284     }
1285
1286 }