]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
56af0dd392d51ff3c7f229625cc28adfacc8fae3
[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(repoClient, 
400                                 ctx.getTenantId(), serviceType, refName,
401                                 myFilter.getPageSize(), myFilter.getStartPage(), true );
402         } catch (UnauthorizedException ue) {
403                 Response response = Response.status(
404                                 Response.Status.UNAUTHORIZED).entity("Get failed reason " + ue.getErrorReason()).type("text/plain").build();
405                 throw new WebApplicationException(response);
406         } catch (DocumentNotFoundException dnfe) {
407                 if (logger.isDebugEnabled()) {
408                         logger.debug("getReferencingObjects", dnfe);
409                 }
410                 Response response = Response.status(Response.Status.NOT_FOUND).entity(
411                                 "GetReferencingObjects failed with parentcsid=" 
412                                 + parentcsid + " and itemcsid=" + itemcsid).type(
413                                 "text/plain").build();
414                 throw new WebApplicationException(response);
415         } catch (Exception e) { // Includes DocumentException
416                 if (logger.isDebugEnabled()) {
417                         logger.debug("GetReferencingObjects", e);
418                 }
419                 Response response = Response.status(
420                                 Response.Status.INTERNAL_SERVER_ERROR).entity("Get failed").type("text/plain").build();
421                 throw new WebApplicationException(response);
422         }
423         if (authRefDocList == null) {
424                 Response response = Response.status(Response.Status.NOT_FOUND).entity(
425                                 "Get failed, the requested Person CSID:" + itemcsid + ": was not found.").type(
426                                 "text/plain").build();
427                 throw new WebApplicationException(response);
428         }
429         return authRefDocList;
430     }
431
432     
433     /**
434      * Gets the org authority.
435      * 
436      * @param csid the csid
437      * 
438      * @return the org authority
439      */
440     @GET
441     @Path("{csid}")
442     public MultipartOutput getOrgAuthority(@PathParam("csid") String csid) {
443         String idValue = null;
444         if (csid == null) {
445             logger.error("getOrgAuthority: missing csid!");
446             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
447                     "get failed on OrgAuthority csid=" + csid).type(
448                     "text/plain").build();
449             throw new WebApplicationException(response);
450         }
451         if (logger.isDebugEnabled()) {
452             logger.debug("getOrgAuthority with path(id)=" + csid);
453         }
454         MultipartOutput result = null;
455         try {
456                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext();
457             DocumentHandler handler = createDocumentHandler(ctx);
458             getRepositoryClient(ctx).get(ctx, csid, handler);
459             result = (MultipartOutput) ctx.getOutput();
460         } catch (UnauthorizedException ue) {
461             Response response = Response.status(
462                     Response.Status.UNAUTHORIZED).entity("Get failed reason " + ue.getErrorReason()).type("text/plain").build();
463             throw new WebApplicationException(response);
464         } catch (DocumentNotFoundException dnfe) {
465             if (logger.isDebugEnabled()) {
466                 logger.debug("getOrgAuthority", dnfe);
467             }
468             Response response = Response.status(Response.Status.NOT_FOUND).entity(
469                     "Get failed on OrgAuthority csid=" + csid).type(
470                     "text/plain").build();
471             throw new WebApplicationException(response);
472         } catch (Exception e) {
473             if (logger.isDebugEnabled()) {
474                 logger.debug("getOrgAuthority", e);
475             }
476             Response response = Response.status(
477                     Response.Status.INTERNAL_SERVER_ERROR).entity("Get failed").type("text/plain").build();
478             throw new WebApplicationException(response);
479         }
480         if (result == null) {
481             Response response = Response.status(Response.Status.NOT_FOUND).entity(
482                     "Get failed, the requested OrgAuthority CSID:" + csid + ": was not found.").type(
483                     "text/plain").build();
484             throw new WebApplicationException(response);
485         }
486         return result;
487     }
488
489     /**
490      * Gets the org authority list.
491      * 
492      * @param ui the ui
493      * 
494      * @return the org authority list
495      */
496     @GET
497     @Produces("application/xml")
498     public OrgauthoritiesCommonList getOrgAuthorityList(@Context UriInfo ui) {
499         OrgauthoritiesCommonList orgAuthorityObjectList = new OrgauthoritiesCommonList();
500         try {
501             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
502                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(queryParams);
503             DocumentHandler handler = createDocumentHandler(ctx);
504             DocumentFilter myFilter = handler.getDocumentFilter();
505             String nameQ = queryParams.getFirst("refName");
506             if (nameQ != null) {
507                 myFilter.setWhereClause("orgauthorities_common:refName='" + nameQ + "'");
508             }
509             getRepositoryClient(ctx).getFiltered(ctx, handler);
510             orgAuthorityObjectList = (OrgauthoritiesCommonList) handler.getCommonPartList();
511         } catch (UnauthorizedException ue) {
512             Response response = Response.status(
513                     Response.Status.UNAUTHORIZED).entity("Index failed reason " + ue.getErrorReason()).type("text/plain").build();
514             throw new WebApplicationException(response);
515         } catch (Exception e) {
516             if (logger.isDebugEnabled()) {
517                 logger.debug("Caught exception in getOrgAuthorityList", e);
518             }
519             Response response = Response.status(
520                     Response.Status.INTERNAL_SERVER_ERROR).entity("Index failed").type("text/plain").build();
521             throw new WebApplicationException(response);
522         }
523         return orgAuthorityObjectList;
524     }
525
526     /**
527      * Update org authority.
528      * 
529      * @param csid the csid
530      * @param theUpdate the the update
531      * 
532      * @return the multipart output
533      */
534     @PUT
535     @Path("{csid}")
536     public MultipartOutput updateOrgAuthority(
537             @PathParam("csid") String csid,
538             MultipartInput theUpdate) {
539         if (logger.isDebugEnabled()) {
540             logger.debug("updateOrgAuthority with csid=" + csid);
541         }
542         if (csid == null || "".equals(csid)) {
543             logger.error("updateOrgAuthority: missing csid!");
544             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
545                     "update failed on OrgAuthority csid=" + csid).type(
546                     "text/plain").build();
547             throw new WebApplicationException(response);
548         }
549         MultipartOutput result = null;
550         try {
551                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(theUpdate);
552             DocumentHandler handler = createDocumentHandler(ctx);
553             getRepositoryClient(ctx).update(ctx, csid, handler);
554             result = (MultipartOutput) ctx.getOutput();
555         } catch (BadRequestException bre) {
556             Response response = Response.status(
557                     Response.Status.BAD_REQUEST).entity("Create failed reason " + bre.getErrorReason()).type("text/plain").build();
558             throw new WebApplicationException(response);
559         } catch (UnauthorizedException ue) {
560             Response response = Response.status(
561                     Response.Status.UNAUTHORIZED).entity("Update failed reason " + ue.getErrorReason()).type("text/plain").build();
562             throw new WebApplicationException(response);
563         } catch (DocumentNotFoundException dnfe) {
564             if (logger.isDebugEnabled()) {
565                 logger.debug("caught exception in updateOrgAuthority", dnfe);
566             }
567             Response response = Response.status(Response.Status.NOT_FOUND).entity(
568                     "Update failed on OrgAuthority csid=" + csid).type(
569                     "text/plain").build();
570             throw new WebApplicationException(response);
571         } catch (Exception e) {
572             Response response = Response.status(
573                     Response.Status.INTERNAL_SERVER_ERROR).entity("Update failed").type("text/plain").build();
574             throw new WebApplicationException(response);
575         }
576         return result;
577     }
578
579     /**
580      * Delete org authority.
581      * 
582      * @param csid the csid
583      * 
584      * @return the response
585      */
586     @DELETE
587     @Path("{csid}")
588     public Response deleteOrgAuthority(@PathParam("csid") String csid) {
589
590         if (logger.isDebugEnabled()) {
591             logger.debug("deleteOrgAuthority with csid=" + csid);
592         }
593         if (csid == null || "".equals(csid)) {
594             logger.error("deleteOrgAuthority: missing csid!");
595             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
596                     "delete failed on OrgAuthority csid=" + csid).type(
597                     "text/plain").build();
598             throw new WebApplicationException(response);
599         }
600         try {
601                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext();
602             getRepositoryClient(ctx).delete(ctx, csid);
603             return Response.status(HttpResponseCodes.SC_OK).build();
604         } catch (UnauthorizedException ue) {
605             Response response = Response.status(
606                     Response.Status.UNAUTHORIZED).entity("Delete failed reason " + ue.getErrorReason()).type("text/plain").build();
607             throw new WebApplicationException(response);
608         } catch (DocumentNotFoundException dnfe) {
609             if (logger.isDebugEnabled()) {
610                 logger.debug("caught exception in deleteOrgAuthority", dnfe);
611             }
612             Response response = Response.status(Response.Status.NOT_FOUND).entity(
613                     "Delete failed on OrgAuthority csid=" + csid).type(
614                     "text/plain").build();
615             throw new WebApplicationException(response);
616         } catch (Exception e) {
617             Response response = Response.status(
618                     Response.Status.INTERNAL_SERVER_ERROR).entity("Delete failed").type("text/plain").build();
619             throw new WebApplicationException(response);
620         }
621
622     }
623
624     /*************************************************************************
625      * Organization parts - this is a sub-resource of OrgAuthority
626      *************************************************************************/
627     @POST
628     @Path("{csid}/items")
629     public Response createOrganization(@PathParam("csid") String parentcsid, MultipartInput input) {
630         try {
631                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getItemServiceName(),
632                                 input);
633             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
634             String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
635             UriBuilder path = UriBuilder.fromResource(OrgAuthorityResource.class);
636             path.path(parentcsid + "/items/" + itemcsid);
637             Response response = Response.created(path.build()).build();
638             return response;
639         } catch (BadRequestException bre) {
640             Response response = Response.status(
641                     Response.Status.BAD_REQUEST).entity("Create failed reason " + bre.getErrorReason()).type("text/plain").build();
642             throw new WebApplicationException(response);
643         } catch (UnauthorizedException ue) {
644             Response response = Response.status(
645                     Response.Status.UNAUTHORIZED).entity("Create failed reason " + ue.getErrorReason()).type("text/plain").build();
646             throw new WebApplicationException(response);
647         } catch (Exception e) {
648             if (logger.isDebugEnabled()) {
649                 logger.debug("Caught exception in createOrganization", e);
650             }
651             Response response = Response.status(
652                     Response.Status.INTERNAL_SERVER_ERROR).entity("Create failed").type("text/plain").build();
653             throw new WebApplicationException(response);
654         }
655     }
656
657     /**
658      * Gets the organization.
659      * 
660      * @param csid The organization authority (parent) CSID.
661      * @param itemcsid The organization item CSID.
662      * 
663      * @return the organization.
664      */
665     @GET
666     @Path("{csid}/items/{itemcsid}")
667     public MultipartOutput getOrganization(
668             @PathParam("csid") String parentcsid,
669             @PathParam("itemcsid") String itemcsid) {
670         if (logger.isDebugEnabled()) {
671             logger.debug("getOrganization with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
672         }
673         if (parentcsid == null || "".equals(parentcsid)) {
674             logger.error("getOrganization: missing csid!");
675             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
676                     "get failed on Organization csid=" + parentcsid).type(
677                     "text/plain").build();
678             throw new WebApplicationException(response);
679         }
680         if (itemcsid == null || "".equals(itemcsid)) {
681             logger.error("getOrganization: missing itemcsid!");
682             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
683                     "get failed on Organization itemcsid=" + itemcsid).type(
684                     "text/plain").build();
685             throw new WebApplicationException(response);
686         }
687         MultipartOutput result = null;
688         try {
689             // Note that we have to create the service context for the Items, not the main service
690                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getItemServiceName());
691             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
692             getRepositoryClient(ctx).get(ctx, itemcsid, handler);
693             // TODO should we assert that the item is in the passed orgAuthority?
694             result = (MultipartOutput) ctx.getOutput();
695         } catch (UnauthorizedException ue) {
696             Response response = Response.status(
697                     Response.Status.UNAUTHORIZED).entity("Get failed reason " + ue.getErrorReason()).type("text/plain").build();
698             throw new WebApplicationException(response);
699         } catch (DocumentNotFoundException dnfe) {
700             if (logger.isDebugEnabled()) {
701                 logger.debug("getOrganization", dnfe);
702             }
703             Response response = Response.status(Response.Status.NOT_FOUND).entity(
704                     "Get failed on Organization csid=" + itemcsid).type(
705                     "text/plain").build();
706             throw new WebApplicationException(response);
707         } catch (Exception e) {
708             if (logger.isDebugEnabled()) {
709                 logger.debug("getOrganization", e);
710             }
711             Response response = Response.status(
712                     Response.Status.INTERNAL_SERVER_ERROR).entity("Get failed").type("text/plain").build();
713             throw new WebApplicationException(response);
714         }
715         if (result == null) {
716             Response response = Response.status(Response.Status.NOT_FOUND).entity(
717                     "Get failed, the requested Organization CSID:" + itemcsid + ": was not found.").type(
718                     "text/plain").build();
719             throw new WebApplicationException(response);
720         }
721         return result;
722     }
723
724     /**
725      * Gets the authority refs for an Organization item.
726      *
727      * @param csid The organization authority (parent) CSID.
728      * @param itemcsid The organization item CSID.
729      *
730      * @return the authority refs for the Organization item.
731      */
732     @GET
733     @Path("{csid}/items/{itemcsid}/authorityrefs")
734     @Produces("application/xml")
735     public AuthorityRefList getOrganizationAuthorityRefs(
736                 @PathParam("csid") String parentcsid,
737                 @PathParam("itemcsid") String itemcsid,
738                 @Context UriInfo ui) {
739         AuthorityRefList authRefList = null;
740         try {
741             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
742             ServiceContext<MultipartInput, MultipartOutput> ctx =
743                 createServiceContext(getItemServiceName(), queryParams);
744             RemoteDocumentModelHandlerImpl handler =
745                 (RemoteDocumentModelHandlerImpl) createItemDocumentHandler(ctx, parentcsid);
746             DocumentWrapper<DocumentModel> docWrapper =
747                getRepositoryClient(ctx).getDoc(ctx, itemcsid);
748             List<String> authRefFields =
749                 ((MultipartServiceContextImpl)ctx).getCommonPartPropertyValues(
750                 ServiceBindingUtils.AUTH_REF_PROP, ServiceBindingUtils.QUALIFIED_PROP_NAMES);
751             authRefList = handler.getAuthorityRefs(docWrapper, authRefFields);
752         } catch (UnauthorizedException ue) {
753             Response response = Response.status(
754                     Response.Status.UNAUTHORIZED).entity("Failed to retrieve authority references: reason " + ue.getErrorReason()).type("text/plain").build();
755             throw new WebApplicationException(response);
756         } catch (Exception e) {
757             if (logger.isDebugEnabled()) {
758                 logger.debug("Caught exception in getAuthorityRefs", e);
759             }
760             Response response = Response.status(
761                     Response.Status.INTERNAL_SERVER_ERROR).entity("Failed to retrieve authority references").type("text/plain").build();
762             throw new WebApplicationException(response);
763         }
764         return authRefList;
765     }
766
767     /**
768      * Gets the organization list.
769      * 
770      * @param parentcsid the parentcsid
771      * @param partialTerm the partial term
772      * @param ui the ui
773      * 
774      * @return the organization list
775      */
776     @GET
777     @Path("{csid}/items")
778     @Produces("application/xml")
779     public OrganizationsCommonList getOrganizationList(
780             @PathParam("csid") String parentcsid,
781             @QueryParam (IQueryManager.SEARCH_TYPE_PARTIALTERM) String partialTerm,
782             @Context UriInfo ui) {
783         OrganizationsCommonList organizationObjectList = new OrganizationsCommonList();
784         try {
785             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
786             // Note that docType defaults to the ServiceName, so we're fine with that.
787                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getItemServiceName(),
788                                 queryParams);
789             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
790             DocumentFilter myFilter = handler.getDocumentFilter(); //new DocumentFilter();
791             myFilter.setWhereClause(OrganizationJAXBSchema.ORGANIZATIONS_COMMON +
792                         ":" + OrganizationJAXBSchema.IN_AUTHORITY + "=" +
793                         "'" + parentcsid + "'");
794             
795             // AND organizations_common:displayName LIKE '%partialTerm%'
796             if (partialTerm != null && !partialTerm.isEmpty()) {
797                 String ptClause = "AND " + OrganizationJAXBSchema.ORGANIZATIONS_COMMON +
798                         ":" + OrganizationJAXBSchema.DISPLAY_NAME +
799                         " LIKE " + "'%" + partialTerm + "%'";
800                 myFilter.appendWhereClause(ptClause);
801             }            
802             getRepositoryClient(ctx).getFiltered(ctx, handler);
803             organizationObjectList = (OrganizationsCommonList) handler.getCommonPartList();
804         } catch (UnauthorizedException ue) {
805             Response response = Response.status(
806                     Response.Status.UNAUTHORIZED).entity("Index failed reason " + ue.getErrorReason()).type("text/plain").build();
807             throw new WebApplicationException(response);
808         } catch (Exception e) {
809             if (logger.isDebugEnabled()) {
810                 logger.debug("Caught exception in getOrganizationList", e);
811             }
812             Response response = Response.status(
813                     Response.Status.INTERNAL_SERVER_ERROR).entity("Index failed").type("text/plain").build();
814             throw new WebApplicationException(response);
815         }
816         return organizationObjectList;
817     }
818
819     /**
820      * Gets the organization list by auth name.
821      * 
822      * @param parentSpecifier the parent specifier
823      * @param partialTerm the partial term
824      * @param ui the ui
825      * 
826      * @return the organization list by auth name
827      */
828     @GET
829     @Path("urn:cspace:name({specifier})/items")
830     @Produces("application/xml")
831     public OrganizationsCommonList getOrganizationListByAuthName(
832                 @PathParam("specifier") String parentSpecifier,
833             @QueryParam (IQueryManager.SEARCH_TYPE_PARTIALTERM) String partialTerm,            
834             @Context UriInfo ui) {
835         OrganizationsCommonList personObjectList = new OrganizationsCommonList();
836         try {
837             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
838             String whereClause =
839                 OrgAuthorityJAXBSchema.ORGAUTHORITIES_COMMON+
840                 ":" + OrgAuthorityJAXBSchema.DISPLAY_NAME+
841                 "='" + parentSpecifier+"'";
842             // Need to get an Authority by name
843             ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(queryParams);
844             String parentcsid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause);
845
846             ctx = createServiceContext(getItemServiceName(), queryParams);
847             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
848             DocumentFilter myFilter = handler.getDocumentFilter();// new DocumentFilter();
849
850             // Add the where clause "organizations_common:inAuthority='" + parentcsid + "'"
851             myFilter.setWhereClause(OrganizationJAXBSchema.ORGANIZATIONS_COMMON + ":" +
852                         OrganizationJAXBSchema.IN_AUTHORITY + "='" + parentcsid + "'");
853             
854             // AND organizations_common:displayName LIKE '%partialTerm%'
855             if (partialTerm != null && !partialTerm.isEmpty()) {
856                 String ptClause = "AND " +
857                 OrganizationJAXBSchema.ORGANIZATIONS_COMMON + ":" +
858                 OrganizationJAXBSchema.DISPLAY_NAME +
859                         " LIKE " +
860                         "'%" + partialTerm + "%'";
861                 myFilter.appendWhereClause(ptClause);
862             }            
863             getRepositoryClient(ctx).getFiltered(ctx, handler);
864             personObjectList = (OrganizationsCommonList) handler.getCommonPartList();
865         } catch (UnauthorizedException ue) {
866             Response response = Response.status(
867                     Response.Status.UNAUTHORIZED).entity("Index failed reason " + ue.getErrorReason()).type("text/plain").build();
868             throw new WebApplicationException(response);
869         } catch (Exception e) {
870             if (logger.isDebugEnabled()) {
871                 logger.debug("Caught exception in getOrganizationListByAuthName", e);
872             }
873             Response response = Response.status(
874                     Response.Status.INTERNAL_SERVER_ERROR).entity("Index failed").type("text/plain").build();
875             throw new WebApplicationException(response);
876         }
877         return personObjectList;
878     }
879
880     /**
881      * Update organization.
882      * 
883      * @param parentcsid the parentcsid
884      * @param itemcsid the itemcsid
885      * @param theUpdate the the update
886      * 
887      * @return the multipart output
888      */
889     @PUT
890     @Path("{csid}/items/{itemcsid}")
891     public MultipartOutput updateOrganization(
892             @PathParam("csid") String parentcsid,
893             @PathParam("itemcsid") String itemcsid,
894             MultipartInput theUpdate) {
895         if (logger.isDebugEnabled()) {
896             logger.debug("updateOrganization with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
897         }
898         if (parentcsid == null || "".equals(parentcsid)) {
899             logger.error("updateOrganization: missing csid!");
900             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
901                     "update failed on Organization parentcsid=" + parentcsid).type(
902                     "text/plain").build();
903             throw new WebApplicationException(response);
904         }
905         if (itemcsid == null || "".equals(itemcsid)) {
906             logger.error("updateOrganization: missing itemcsid!");
907             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
908                     "update failed on Organization=" + itemcsid).type(
909                     "text/plain").build();
910             throw new WebApplicationException(response);
911         }
912         MultipartOutput result = null;
913         try {
914             // Note that we have to create the service context for the Items, not the main service
915                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getItemServiceName(),
916                                 theUpdate);
917             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
918             getRepositoryClient(ctx).update(ctx, itemcsid, handler);
919             result = (MultipartOutput) ctx.getOutput();
920         } catch (BadRequestException bre) {
921             Response response = Response.status(
922                     Response.Status.BAD_REQUEST).entity("Create failed reason " + bre.getErrorReason()).type("text/plain").build();
923             throw new WebApplicationException(response);
924         } catch (UnauthorizedException ue) {
925             Response response = Response.status(
926                     Response.Status.UNAUTHORIZED).entity("Update failed reason " + ue.getErrorReason()).type("text/plain").build();
927             throw new WebApplicationException(response);
928         } catch (DocumentNotFoundException dnfe) {
929             if (logger.isDebugEnabled()) {
930                 logger.debug("caught exception in updateOrganization", dnfe);
931             }
932             Response response = Response.status(Response.Status.NOT_FOUND).entity(
933                     "Update failed on Organization csid=" + itemcsid).type(
934                     "text/plain").build();
935             throw new WebApplicationException(response);
936         } catch (Exception e) {
937             Response response = Response.status(
938                     Response.Status.INTERNAL_SERVER_ERROR).entity("Update failed").type("text/plain").build();
939             throw new WebApplicationException(response);
940         }
941         return result;
942     }
943
944     /**
945      * Delete organization.
946      * 
947      * @param parentcsid the parentcsid
948      * @param itemcsid the itemcsid
949      * 
950      * @return the response
951      */
952     @DELETE
953     @Path("{csid}/items/{itemcsid}")
954     public Response deleteOrganization(
955             @PathParam("csid") String parentcsid,
956             @PathParam("itemcsid") String itemcsid) {
957         if (logger.isDebugEnabled()) {
958             logger.debug("deleteOrganization with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
959         }
960         if (parentcsid == null || "".equals(parentcsid)) {
961             logger.error("deleteOrganization: missing csid!");
962             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
963                     "delete failed on Organization parentcsid=" + parentcsid).type(
964                     "text/plain").build();
965             throw new WebApplicationException(response);
966         }
967         if (itemcsid == null || "".equals(itemcsid)) {
968             logger.error("deleteOrganization: missing itemcsid!");
969             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
970                     "delete failed on Organization=" + itemcsid).type(
971                     "text/plain").build();
972             throw new WebApplicationException(response);
973         }
974         try {
975             // Note that we have to create the service context for the Items, not the main service
976                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getItemServiceName());
977             getRepositoryClient(ctx).delete(ctx, itemcsid);
978             return Response.status(HttpResponseCodes.SC_OK).build();
979         } catch (UnauthorizedException ue) {
980             Response response = Response.status(
981                     Response.Status.UNAUTHORIZED).entity("Delete failed reason " + ue.getErrorReason()).type("text/plain").build();
982             throw new WebApplicationException(response);
983         } catch (DocumentNotFoundException dnfe) {
984             if (logger.isDebugEnabled()) {
985                 logger.debug("caught exception in deleteOrganization", dnfe);
986             }
987             Response response = Response.status(Response.Status.NOT_FOUND).entity(
988                     "Delete failed on Organization itemcsid=" + itemcsid).type(
989                     "text/plain").build();
990             throw new WebApplicationException(response);
991         } catch (Exception e) {
992             Response response = Response.status(
993                     Response.Status.INTERNAL_SERVER_ERROR).entity("Delete failed").type("text/plain").build();
994             throw new WebApplicationException(response);
995         }
996
997     }
998
999     /*************************************************************************
1000      * Contact parts - this is a sub-resource of Organization (or "item")
1001      *************************************************************************/
1002     @POST
1003     @Path("{parentcsid}/items/{itemcsid}/contacts")
1004     public Response createContact(
1005             @PathParam("parentcsid") String parentcsid,
1006             @PathParam("itemcsid") String itemcsid,
1007             MultipartInput input) {
1008         try {
1009             // Note that we have to create the service context and document
1010             // handler for the Contact service, not the main service.
1011                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getContactServiceName(), input);
1012             DocumentHandler handler = createContactDocumentHandler(ctx, parentcsid, itemcsid);
1013             String csid = getRepositoryClient(ctx).create(ctx, handler);
1014             UriBuilder path = UriBuilder.fromResource(OrgAuthorityResource.class);
1015             path.path("" + parentcsid + "/items/" + itemcsid + "/contacts/" + csid);
1016             Response response = Response.created(path.build()).build();
1017             return response;
1018         } catch (BadRequestException bre) {
1019             Response response = Response.status(
1020                     Response.Status.BAD_REQUEST).entity("Create failed reason " + bre.getErrorReason()).type("text/plain").build();
1021             throw new WebApplicationException(response);
1022         } catch (UnauthorizedException ue) {
1023             Response response = Response.status(
1024                     Response.Status.UNAUTHORIZED).entity("Create failed reason " + ue.getErrorReason()).type("text/plain").build();
1025             throw new WebApplicationException(response);
1026         } catch (Exception e) {
1027             if (logger.isDebugEnabled()) {
1028                 logger.debug("Caught exception in createContact", e);
1029             }
1030             Response response = Response.status(
1031                 Response.Status.INTERNAL_SERVER_ERROR)
1032                 .entity("Attempt to create Contact failed.")
1033                 .type("text/plain").build();
1034             throw new WebApplicationException(response);
1035         }
1036
1037     }
1038
1039     /**
1040      * Gets the contact list.
1041      * 
1042      * @param parentcsid the parentcsid
1043      * @param itemcsid the itemcsid
1044      * @param ui the ui
1045      * 
1046      * @return the contact list
1047      */
1048     @GET
1049     @Produces({"application/xml"})
1050     @Path("{parentcsid}/items/{itemcsid}/contacts/")
1051     public ContactsCommonList getContactList(
1052             @PathParam("parentcsid") String parentcsid,
1053             @PathParam("itemcsid") String itemcsid,
1054             @Context UriInfo ui) {
1055         ContactsCommonList contactObjectList = new ContactsCommonList();
1056         try {
1057             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
1058                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getContactServiceName(),
1059                                 queryParams);
1060             DocumentHandler handler = createContactDocumentHandler(ctx, parentcsid, itemcsid);
1061             DocumentFilter myFilter = handler.getDocumentFilter(); //new DocumentFilter();
1062             myFilter.setWhereClause(ContactJAXBSchema.CONTACTS_COMMON + ":" +
1063                 ContactJAXBSchema.IN_AUTHORITY +
1064                 "='" + parentcsid + "'" +
1065                 " AND " +
1066                 ContactJAXBSchema.CONTACTS_COMMON + ":" +
1067                 ContactJAXBSchema.IN_ITEM +
1068                 "='" + itemcsid + "'" +
1069                 " AND ecm:isProxy = 0");
1070             getRepositoryClient(ctx).getFiltered(ctx, handler);
1071             contactObjectList = (ContactsCommonList) handler.getCommonPartList();
1072         } catch (UnauthorizedException ue) {
1073             Response response = Response.status(
1074                     Response.Status.UNAUTHORIZED).entity("Index failed reason " + ue.getErrorReason()).type("text/plain").build();
1075             throw new WebApplicationException(response);
1076         } catch (Exception e) {
1077             if (logger.isDebugEnabled()) {
1078                 logger.debug("Caught exception in getContactsList", e);
1079             }
1080             Response response = Response.status(
1081                     Response.Status.INTERNAL_SERVER_ERROR).entity("Index failed").type("text/plain").build();
1082             throw new WebApplicationException(response);
1083         }
1084         return contactObjectList;
1085     }
1086
1087     /**
1088      * Gets the contact.
1089      * 
1090      * @param parentcsid the parentcsid
1091      * @param itemcsid the itemcsid
1092      * @param csid the csid
1093      * 
1094      * @return the contact
1095      */
1096     @GET
1097     @Path("{parentcsid}/items/{itemcsid}/contacts/{csid}")
1098     public MultipartOutput getContact(
1099             @PathParam("parentcsid") String parentcsid,
1100             @PathParam("itemcsid") String itemcsid,
1101             @PathParam("csid") String csid) {
1102         MultipartOutput result = null;
1103        if (logger.isDebugEnabled()) {
1104             logger.debug("getContact with parentCsid=" + parentcsid +
1105             " itemcsid=" + itemcsid + " csid=" + csid);
1106         }
1107         try {
1108             // Note that we have to create the service context and document
1109             // handler for the Contact service, not the main service.
1110                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getContactServiceName());
1111             DocumentHandler handler = createContactDocumentHandler(ctx, parentcsid, itemcsid);
1112             getRepositoryClient(ctx).get(ctx, csid, handler);
1113             result = (MultipartOutput) ctx.getOutput();
1114         } catch (UnauthorizedException ue) {
1115             Response response = Response.status(
1116                     Response.Status.UNAUTHORIZED).entity("Get failed reason " + ue.getErrorReason()).type("text/plain").build();
1117             throw new WebApplicationException(response);
1118         } catch (DocumentNotFoundException dnfe) {
1119             if (logger.isDebugEnabled()) {
1120                 logger.debug("getContact", dnfe);
1121             }
1122             Response response = Response.status(Response.Status.NOT_FOUND)
1123                 .entity("Get failed, the requested Contact CSID:" + csid + ": was not found.")
1124                 .type("text/plain").build();
1125             throw new WebApplicationException(response);
1126         } catch (Exception e) {
1127             if (logger.isDebugEnabled()) {
1128                 logger.debug("getContact", e);
1129             }
1130             Response response = Response.status(Response.Status.INTERNAL_SERVER_ERROR)
1131                 .entity("Get contact failed")
1132                 .type("text/plain").build();
1133             throw new WebApplicationException(response);
1134         }
1135         if (result == null) {
1136             Response response = Response.status(Response.Status.NOT_FOUND)
1137                 .entity("Get failed, the requested Contact CSID:" + csid + ": was not found.")
1138                 .type("text/plain").build();
1139             throw new WebApplicationException(response);
1140         }
1141         return result;
1142
1143     }
1144
1145     /**
1146      * Update contact.
1147      * 
1148      * @param parentcsid the parentcsid
1149      * @param itemcsid the itemcsid
1150      * @param csid the csid
1151      * @param theUpdate the the update
1152      * 
1153      * @return the multipart output
1154      */
1155     @PUT
1156     @Path("{parentcsid}/items/{itemcsid}/contacts/{csid}")
1157     public MultipartOutput updateContact(
1158             @PathParam("parentcsid") String parentcsid,
1159             @PathParam("itemcsid") String itemcsid,
1160             @PathParam("csid") String csid,
1161             MultipartInput theUpdate) {
1162        if (logger.isDebugEnabled()) {
1163             logger.debug("updateContact with parentcsid=" + parentcsid +
1164             " itemcsid=" + itemcsid + " csid=" + csid);
1165         }
1166        if (parentcsid == null || parentcsid.trim().isEmpty()) {
1167             logger.error("updateContact: missing csid!");
1168             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
1169                     "update failed on Contact parentcsid=" + parentcsid).type(
1170                     "text/plain").build();
1171             throw new WebApplicationException(response);
1172         }
1173         if (itemcsid == null || itemcsid.trim().isEmpty()) {
1174             logger.error("updateContact: missing itemcsid!");
1175             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
1176                     "update failed on Contact=" + itemcsid).type(
1177                     "text/plain").build();
1178             throw new WebApplicationException(response);
1179         }
1180         if (csid == null || csid.trim().isEmpty()) {
1181             logger.error("updateContact: missing csid!");
1182             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
1183                     "update failed on Contact=" + csid).type(
1184                     "text/plain").build();
1185             throw new WebApplicationException(response);
1186         }
1187         MultipartOutput result = null;
1188         try {
1189             // Note that we have to create the service context and document
1190             // handler for the Contact service, not the main service.
1191                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getContactServiceName(), theUpdate);
1192             DocumentHandler handler = createContactDocumentHandler(ctx, parentcsid, itemcsid);
1193             getRepositoryClient(ctx).update(ctx, csid, handler);
1194             result = (MultipartOutput) ctx.getOutput();
1195         } catch (BadRequestException bre) {
1196             Response response = Response.status(
1197                     Response.Status.BAD_REQUEST).entity("Create failed reason " + bre.getErrorReason()).type("text/plain").build();
1198             throw new WebApplicationException(response);
1199         } catch (UnauthorizedException ue) {
1200             Response response = Response.status(
1201                     Response.Status.UNAUTHORIZED).entity("Update failed reason " + ue.getErrorReason()).type("text/plain").build();
1202             throw new WebApplicationException(response);
1203         } catch (DocumentNotFoundException dnfe) {
1204             if (logger.isDebugEnabled()) {
1205                 logger.debug("caught exception in updateContact", dnfe);
1206             }
1207             Response response = Response.status(Response.Status.NOT_FOUND).entity(
1208                     "Update failed on Contact csid=" + itemcsid).type(
1209                     "text/plain").build();
1210             throw new WebApplicationException(response);
1211         } catch (Exception e) {
1212             Response response = Response.status(
1213                     Response.Status.INTERNAL_SERVER_ERROR).entity("Update failed").type("text/plain").build();
1214             throw new WebApplicationException(response);
1215         }
1216         return result;
1217     }
1218
1219     /**
1220      * Delete contact.
1221      * 
1222      * @param parentcsid the parentcsid
1223      * @param itemcsid the itemcsid
1224      * @param csid the csid
1225      * 
1226      * @return the response
1227      */
1228     @DELETE
1229     @Path("{parentcsid}/items/{itemcsid}/contacts/{csid}")
1230     public Response deleteContact(
1231             @PathParam("parentcsid") String parentcsid,
1232             @PathParam("itemcsid") String itemcsid,
1233             @PathParam("csid") String csid) {
1234         if (logger.isDebugEnabled()) {
1235             logger.debug("deleteContact with parentCsid=" + parentcsid +
1236             " itemcsid=" + itemcsid + " csid=" + csid);
1237         }
1238         if (parentcsid == null || parentcsid.trim().isEmpty()) {
1239             logger.error("deleteContact: missing parentcsid!");
1240             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
1241                     "delete contact failed on parentcsid=" + parentcsid).type(
1242                     "text/plain").build();
1243             throw new WebApplicationException(response);
1244         }
1245         if (itemcsid == null || itemcsid.trim().isEmpty()) {
1246             logger.error("deleteContact: missing itemcsid!");
1247             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
1248                     "delete contact failed on itemcsid=" + itemcsid).type(
1249                     "text/plain").build();
1250             throw new WebApplicationException(response);
1251         }
1252         if (csid == null || csid.trim().isEmpty()) {
1253             logger.error("deleteContact: missing csid!");
1254             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
1255                     "delete contact failed on csid=" + csid).type(
1256                     "text/plain").build();
1257             throw new WebApplicationException(response);
1258         }
1259         try {
1260             // Note that we have to create the service context for the
1261             // Contact service, not the main service.
1262                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getContactServiceName());
1263             getRepositoryClient(ctx).delete(ctx, csid);
1264             return Response.status(HttpResponseCodes.SC_OK).build();
1265          } catch (UnauthorizedException ue) {
1266             Response response = Response.status(
1267                     Response.Status.UNAUTHORIZED).entity("Delete failed reason " + ue.getErrorReason()).type("text/plain").build();
1268             throw new WebApplicationException(response);
1269          } catch (DocumentNotFoundException dnfe) {
1270             if (logger.isDebugEnabled()) {
1271                 logger.debug("Caught exception in deleteContact", dnfe);
1272             }
1273             Response response = Response.status(Response.Status.NOT_FOUND)
1274                 .entity("Delete failed, the requested Contact CSID:" + csid + ": was not found.")
1275                 .type("text/plain").build();
1276             throw new WebApplicationException(response);
1277        } catch (Exception e) {
1278             Response response = Response.status(
1279                     Response.Status.INTERNAL_SERVER_ERROR).entity("Delete failed").type("text/plain").build();
1280             throw new WebApplicationException(response);
1281         }
1282     }
1283
1284 }