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