]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
e71af43d77ebbee43876e7ce61f688657a00019c
[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.location;
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.LocationAuthorityJAXBSchema;
45 import org.collectionspace.services.LocationJAXBSchema;
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.location.nuxeo.LocationDocumentModelHandler;
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 LocationAuthorityResource.
83  */
84 @Path("/locationauthorities")
85 @Consumes("multipart/mixed")
86 @Produces("multipart/mixed")
87 public class LocationAuthorityResource extends
88                 AbstractMultiPartCollectionSpaceResourceImpl {
89
90     /** The Constant locationAuthorityServiceName. */
91     private final static String locationAuthorityServiceName = "locationauthorities";
92     
93     /** The Constant locationServiceName. */
94     private final static String locationServiceName = "locations";
95     
96     /** The logger. */
97     final Logger logger = LoggerFactory.getLogger(LocationAuthorityResource.class);
98     //FIXME retrieve client type from configuration
99     /** The Constant CLIENT_TYPE. */
100     final static ClientType CLIENT_TYPE = ServiceMain.getInstance().getClientType();
101     
102     /**
103      * Instantiates a new location authority resource.
104      */
105     public LocationAuthorityResource() {
106         // do nothing
107     }
108
109     /* (non-Javadoc)
110      * @see org.collectionspace.services.common.AbstractCollectionSpaceResourceImpl#getVersionString()
111      */
112     @Override
113     protected String getVersionString() {
114         /** The last change revision. */
115         final String lastChangeRevision = "$LastChangedRevision: 1850 $";
116         return lastChangeRevision;
117     }
118     
119     /* (non-Javadoc)
120      * @see org.collectionspace.services.common.AbstractCollectionSpaceResourceImpl#getServiceName()
121      */
122     @Override
123     public String getServiceName() {
124         return locationAuthorityServiceName;
125     }
126
127     @Override
128     public Class<LocationauthoritiesCommon> getCommonPartClass() {
129         return LocationauthoritiesCommon.class;
130     }
131     
132     /**
133      * Gets the item service name.
134      * 
135      * @return the item service name
136      */
137     public String getItemServiceName() {
138         return locationServiceName;
139     }
140
141     /**
142  * Creates the item document handler.
143  * 
144  * @param ctx the ctx
145  * @param inAuthority the in authority
146  * 
147  * @return the document handler
148  * 
149  * @throws Exception the exception
150  */
151     private DocumentHandler createItemDocumentHandler(ServiceContext<MultipartInput, MultipartOutput> ctx,
152             String inAuthority) throws Exception {    
153         LocationDocumentModelHandler docHandler = (LocationDocumentModelHandler)createDocumentHandler(ctx,
154                         ctx.getCommonPartLabel(getItemServiceName()),
155                         LocationsCommon.class);         
156         docHandler.setInAuthority(inAuthority);
157         
158         return docHandler;
159     }
160
161     /**
162      * Creates the location authority.
163      * 
164      * @param input the input
165      * 
166      * @return the response
167      */
168     @POST
169     public Response createLocationAuthority(MultipartInput input) {
170         try {
171                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(input);
172             DocumentHandler handler = createDocumentHandler(ctx);
173             String csid = getRepositoryClient(ctx).create(ctx, handler);
174             //locationAuthorityObject.setCsid(csid);
175             UriBuilder path = UriBuilder.fromResource(LocationAuthorityResource.class);
176             path.path("" + csid);
177             Response response = Response.created(path.build()).build();
178             return response;
179         } catch (BadRequestException bre) {
180             Response response = Response.status(
181                     Response.Status.BAD_REQUEST).entity("Create failed reason " + bre.getErrorReason()).type("text/plain").build();
182             throw new WebApplicationException(response);
183         } catch (UnauthorizedException ue) {
184             Response response = Response.status(
185                     Response.Status.UNAUTHORIZED).entity("Create failed reason " + ue.getErrorReason()).type("text/plain").build();
186             throw new WebApplicationException(response);
187         } catch (Exception e) {
188             if (logger.isDebugEnabled()) {
189                 logger.debug("Caught exception in createLocationAuthority", e);
190             }
191             Response response = Response.status(
192                     Response.Status.INTERNAL_SERVER_ERROR).entity("Create failed").type("text/plain").build();
193             throw new WebApplicationException(response);
194         }
195     }
196
197     /**
198      * Gets the location authority by name.
199      * 
200      * @param specifier the specifier
201      * 
202      * @return the location authority by name
203      */
204     @GET
205     @Path("urn:cspace:name({specifier})")
206     public MultipartOutput getLocationAuthorityByName(@PathParam("specifier") String specifier) {
207         if (specifier == null) {
208             logger.error("getLocationAuthority: missing name!");
209             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
210                     "get failed on LocationAuthority (missing specifier)").type(
211                     "text/plain").build();
212             throw new WebApplicationException(response);
213         }
214         String whereClause =
215                 LocationAuthorityJAXBSchema.LOCATIONAUTHORITIES_COMMON+
216                 ":"+LocationAuthorityJAXBSchema.DISPLAY_NAME+
217                 "='"+specifier+"'";
218         // We only get a single doc - if there are multiple,
219         // it is an error in use.
220
221         if (logger.isDebugEnabled()) {
222             logger.debug("getLocationAuthority with name=" + specifier);
223         } 
224         MultipartOutput result = null;
225         try {
226                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext();
227             DocumentHandler handler = createDocumentHandler(ctx);
228             DocumentFilter myFilter = new DocumentFilter(whereClause, 0, 1);
229             handler.setDocumentFilter(myFilter);
230             getRepositoryClient(ctx).get(ctx, handler);
231             result = (MultipartOutput) ctx.getOutput();
232         } catch (UnauthorizedException ue) {
233             Response response = Response.status(
234                     Response.Status.UNAUTHORIZED).entity("Get failed reason " + ue.getErrorReason()).type("text/plain").build();
235             throw new WebApplicationException(response);
236         } catch (DocumentNotFoundException dnfe) {
237             if (logger.isDebugEnabled()) {
238                 logger.debug("getLocationAuthority", dnfe);
239             }
240             Response response = Response.status(Response.Status.NOT_FOUND).entity(
241                     "Get failed on LocationAuthority spec=" + specifier).type(
242                     "text/plain").build();
243             throw new WebApplicationException(response);
244         } catch (Exception e) {
245             if (logger.isDebugEnabled()) {
246                 logger.debug("getLocationAuthority", e);
247             }
248             Response response = Response.status(
249                     Response.Status.INTERNAL_SERVER_ERROR).entity("Get failed").type("text/plain").build();
250             throw new WebApplicationException(response);
251         }
252         if (result == null) {
253             Response response = Response.status(Response.Status.NOT_FOUND).entity(
254                     "Get failed, the requested LocationAuthority spec:" + specifier + ": was not found.").type(
255                     "text/plain").build();
256             throw new WebApplicationException(response);
257         }
258         return result;
259     }
260
261     /**
262      * Gets the entities referencing this Location instance. The service type
263      * can be passed as a query param "type", and must match a configured type
264      * for the service bindings. If not set, the type defaults to
265      * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
266      * 
267      * @param csid the parent csid
268      * @param itemcsid the location csid
269      * @param ui the ui
270      * 
271      * @return the info for the referencing objects
272      */
273     @GET
274     @Path("{csid}/items/{itemcsid}/refObjs")
275     @Produces("application/xml")
276     public AuthorityRefDocList getReferencingObjects(
277             @PathParam("csid") String parentcsid,
278             @PathParam("itemcsid") String itemcsid,
279                 @Context UriInfo ui) {
280         AuthorityRefDocList authRefDocList = null;
281         if (logger.isDebugEnabled()) {
282             logger.debug("getReferencingObjects with parentcsid=" 
283                         + parentcsid + " and itemcsid=" + itemcsid);
284         }
285         if (parentcsid == null || "".equals(parentcsid)
286                 || itemcsid == null || "".equals(itemcsid)) {
287             logger.error("getLocation: missing parentcsid or itemcsid!");
288             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
289                     "get failed on Location with parentcsid=" 
290                         + parentcsid + " and itemcsid=" + itemcsid).type(
291                     "text/plain").build();
292             throw new WebApplicationException(response);
293         }
294     try {
295         // Note that we have to create the service context for the Items, not the main service
296         ServiceContext ctx = MultipartServiceContextFactory.get().createServiceContext(getItemServiceName());
297         DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
298         RepositoryClient repoClient = getRepositoryClient(ctx); 
299         DocumentFilter myFilter = handler.createDocumentFilter();
300         MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
301         myFilter.setPagination(queryParams);
302         String serviceType = ServiceBindingUtils.SERVICE_TYPE_PROCEDURE;
303         List<String> list = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
304         if (list != null) {
305                 serviceType = list.get(0);
306         }
307         DocumentWrapper<DocumentModel> docWrapper = repoClient.getDoc(ctx, itemcsid);
308         DocumentModel docModel = docWrapper.getWrappedObject();
309         String refName = (String)docModel.getPropertyValue(LocationJAXBSchema.REF_NAME);
310
311         authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(ctx, repoClient, 
312                         serviceType, refName,
313                         myFilter.getPageSize(), myFilter.getStartPage(), true );
314     } catch (UnauthorizedException ue) {
315         Response response = Response.status(
316                 Response.Status.UNAUTHORIZED).entity("Get failed reason " + ue.getErrorReason()).type("text/plain").build();
317         throw new WebApplicationException(response);
318     } catch (DocumentNotFoundException dnfe) {
319         if (logger.isDebugEnabled()) {
320             logger.debug("getReferencingObjects", dnfe);
321         }
322         Response response = Response.status(Response.Status.NOT_FOUND).entity(
323                 "GetReferencingObjects failed with parentcsid=" 
324                         + parentcsid + " and itemcsid=" + itemcsid).type(
325                 "text/plain").build();
326         throw new WebApplicationException(response);
327     } catch (Exception e) {     // Includes DocumentException
328         if (logger.isDebugEnabled()) {
329             logger.debug("GetReferencingObjects", e);
330         }
331         Response response = Response.status(
332                 Response.Status.INTERNAL_SERVER_ERROR).entity("Get failed").type("text/plain").build();
333         throw new WebApplicationException(response);
334     }
335     if (authRefDocList == null) {
336         Response response = Response.status(Response.Status.NOT_FOUND).entity(
337                 "Get failed, the requested Location CSID:" + itemcsid + ": was not found.").type(
338                 "text/plain").build();
339         throw new WebApplicationException(response);
340     }
341     return authRefDocList;
342     }
343
344     @GET
345     @Path("{csid}")
346     public MultipartOutput getLocationAuthority(@PathParam("csid") String csid) {
347         if (csid == null) {
348             logger.error("getLocationAuthority: missing csid!");
349             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
350                     "get failed on LocationAuthority csid=" + csid).type(
351                     "text/plain").build();
352             throw new WebApplicationException(response);
353         }
354         if (logger.isDebugEnabled()) {
355             logger.debug("getLocationAuthority with path(id)=" + csid);
356         } 
357         MultipartOutput result = null;
358         try {
359                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext();
360             DocumentHandler handler = createDocumentHandler(ctx);
361             getRepositoryClient(ctx).get(ctx, csid, handler);
362             result = (MultipartOutput) ctx.getOutput();
363         } catch (UnauthorizedException ue) {
364             Response response = Response.status(
365                     Response.Status.UNAUTHORIZED).entity("Get failed reason " + ue.getErrorReason()).type("text/plain").build();
366             throw new WebApplicationException(response);
367         } catch (DocumentNotFoundException dnfe) {
368             if (logger.isDebugEnabled()) {
369                 logger.debug("getLocationAuthority", dnfe);
370             }
371             Response response = Response.status(Response.Status.NOT_FOUND).entity(
372                     "Get failed on LocationAuthority csid=" + csid).type(
373                     "text/plain").build();
374             throw new WebApplicationException(response);
375         } catch (Exception e) {
376             if (logger.isDebugEnabled()) {
377                 logger.debug("getLocationAuthority", e);
378             }
379             Response response = Response.status(
380                     Response.Status.INTERNAL_SERVER_ERROR).entity("Get failed").type("text/plain").build();
381             throw new WebApplicationException(response);
382         }
383         if (result == null) {
384             Response response = Response.status(Response.Status.NOT_FOUND).entity(
385                     "Get failed, the requested LocationAuthority CSID:" + csid + ": was not found.").type(
386                     "text/plain").build();
387             throw new WebApplicationException(response);
388         }
389         return result;
390     }
391
392     /**
393      * Gets the location authority list.
394      * 
395      * @param ui the ui
396      * 
397      * @return the location authority list
398      */
399     @GET
400     @Produces("application/xml")
401     public LocationauthoritiesCommonList getLocationAuthorityList(@Context UriInfo ui) {
402         LocationauthoritiesCommonList locationAuthorityObjectList = new LocationauthoritiesCommonList();
403         try {
404                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext();
405             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
406             DocumentHandler handler = createDocumentHandler(ctx);
407             DocumentFilter myFilter = handler.createDocumentFilter(); //new DocumentFilter();
408             myFilter.setPagination(queryParams); //FIXME
409             String nameQ = queryParams.getFirst("refName");
410             if (nameQ != null) {
411                 myFilter.setWhereClause("locationauthorities_common:refName='" + nameQ + "'");
412             }
413             handler.setDocumentFilter(myFilter);
414             getRepositoryClient(ctx).getFiltered(ctx, handler);
415             locationAuthorityObjectList = (LocationauthoritiesCommonList) handler.getCommonPartList();
416         } catch (UnauthorizedException ue) {
417             Response response = Response.status(
418                     Response.Status.UNAUTHORIZED).entity("Index failed reason " + ue.getErrorReason()).type("text/plain").build();
419             throw new WebApplicationException(response);
420         } catch (Exception e) {
421             if (logger.isDebugEnabled()) {
422                 logger.debug("Caught exception in getLocationAuthorityList", e);
423             }
424             Response response = Response.status(
425                     Response.Status.INTERNAL_SERVER_ERROR).entity("Index failed").type("text/plain").build();
426             throw new WebApplicationException(response);
427         }
428         return locationAuthorityObjectList;
429     }
430
431     /**
432      * Update location authority.
433      * 
434      * @param csid the csid
435      * @param theUpdate the the update
436      * 
437      * @return the multipart output
438      */
439     @PUT
440     @Path("{csid}")
441     public MultipartOutput updateLocationAuthority(
442             @PathParam("csid") String csid,
443             MultipartInput theUpdate) {
444         if (logger.isDebugEnabled()) {
445             logger.debug("updateLocationAuthority with csid=" + csid);
446         }
447         if (csid == null || "".equals(csid)) {
448             logger.error("updateLocationAuthority: missing csid!");
449             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
450                     "update failed on LocationAuthority csid=" + csid).type(
451                     "text/plain").build();
452             throw new WebApplicationException(response);
453         }
454         MultipartOutput result = null;
455         try {
456                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(theUpdate);
457             DocumentHandler handler = createDocumentHandler(ctx);
458             getRepositoryClient(ctx).update(ctx, csid, handler);
459             result = (MultipartOutput) ctx.getOutput();
460         } catch (BadRequestException bre) {
461             Response response = Response.status(
462                     Response.Status.BAD_REQUEST).entity("Create failed reason " + bre.getErrorReason()).type("text/plain").build();
463             throw new WebApplicationException(response);
464         } catch (UnauthorizedException ue) {
465             Response response = Response.status(
466                     Response.Status.UNAUTHORIZED).entity("Update failed reason " + ue.getErrorReason()).type("text/plain").build();
467             throw new WebApplicationException(response);
468         } catch (DocumentNotFoundException dnfe) {
469             if (logger.isDebugEnabled()) {
470                 logger.debug("caugth exception in updateLocationAuthority", dnfe);
471             }
472             Response response = Response.status(Response.Status.NOT_FOUND).entity(
473                     "Update failed on LocationAuthority csid=" + csid).type(
474                     "text/plain").build();
475             throw new WebApplicationException(response);
476         } catch (Exception e) {
477             Response response = Response.status(
478                     Response.Status.INTERNAL_SERVER_ERROR).entity("Update failed").type("text/plain").build();
479             throw new WebApplicationException(response);
480         }
481         return result;
482     }
483
484     /**
485      * Delete location authority.
486      * 
487      * @param csid the csid
488      * 
489      * @return the response
490      */
491     @DELETE
492     @Path("{csid}")
493     public Response deleteLocationAuthority(@PathParam("csid") String csid) {
494
495         if (logger.isDebugEnabled()) {
496             logger.debug("deleteLocationAuthority with csid=" + csid);
497         }
498         if (csid == null || "".equals(csid)) {
499             logger.error("deleteLocationAuthority: missing csid!");
500             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
501                     "delete failed on LocationAuthority csid=" + csid).type(
502                     "text/plain").build();
503             throw new WebApplicationException(response);
504         }
505         try {
506                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext();
507             getRepositoryClient(ctx).delete(ctx, csid);
508             return Response.status(HttpResponseCodes.SC_OK).build();
509         } catch (UnauthorizedException ue) {
510             Response response = Response.status(
511                     Response.Status.UNAUTHORIZED).entity("Delete failed reason " + ue.getErrorReason()).type("text/plain").build();
512             throw new WebApplicationException(response);
513         } catch (DocumentNotFoundException dnfe) {
514             if (logger.isDebugEnabled()) {
515                 logger.debug("caught exception in deleteLocationAuthority", dnfe);
516             }
517             Response response = Response.status(Response.Status.NOT_FOUND).entity(
518                     "Delete failed on LocationAuthority csid=" + csid).type(
519                     "text/plain").build();
520             throw new WebApplicationException(response);
521         } catch (Exception e) {
522             Response response = Response.status(
523                     Response.Status.INTERNAL_SERVER_ERROR).entity("Delete failed").type("text/plain").build();
524             throw new WebApplicationException(response);
525         }
526
527     }
528
529     /*************************************************************************
530      * Location parts - this is a sub-resource of LocationAuthority
531      *************************************************************************/
532     @POST
533     @Path("{csid}/items")
534     public Response createLocation(@PathParam("csid") String parentcsid, MultipartInput input) {
535         try {
536                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getItemServiceName(), input);
537             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
538             String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
539             UriBuilder path = UriBuilder.fromResource(LocationAuthorityResource.class);
540             path.path(parentcsid + "/items/" + itemcsid);
541             Response response = Response.created(path.build()).build();
542             return response;
543         } catch (BadRequestException bre) {
544             Response response = Response.status(
545                     Response.Status.BAD_REQUEST).entity("Create failed reason " + bre.getErrorReason()).type("text/plain").build();
546             throw new WebApplicationException(response);
547         } catch (UnauthorizedException ue) {
548             Response response = Response.status(
549                     Response.Status.UNAUTHORIZED).entity("Create failed reason " + ue.getErrorReason()).type("text/plain").build();
550             throw new WebApplicationException(response);
551         } catch (Exception e) {
552             if (logger.isDebugEnabled()) {
553                 logger.debug("Caught exception in createLocation", e);
554             }
555             Response response = Response.status(
556                     Response.Status.INTERNAL_SERVER_ERROR).entity("Create failed").type("text/plain").build();
557             throw new WebApplicationException(response);
558         }
559     }
560
561     /**
562      * Gets the location.
563      * 
564      * @param parentcsid the parentcsid
565      * @param itemcsid the itemcsid
566      * 
567      * @return the location
568      */
569     @GET
570     @Path("{csid}/items/{itemcsid}")
571     public MultipartOutput getLocation(
572             @PathParam("csid") String parentcsid,
573             @PathParam("itemcsid") String itemcsid) {
574         if (logger.isDebugEnabled()) {
575             logger.debug("getLocation with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
576         }
577         if (parentcsid == null || "".equals(parentcsid)
578             || itemcsid == null || "".equals(itemcsid)) {
579             logger.error("getLocation: missing parentcsid or itemcsid!");
580             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
581                     "get failed on Location with parentcsid=" 
582                         + parentcsid + " and itemcsid=" + itemcsid).type(
583                     "text/plain").build();
584             throw new WebApplicationException(response);
585         }
586         MultipartOutput result = null;
587         try {
588             // Note that we have to create the service context for the Items, not the main service
589                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getItemServiceName());
590             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
591             getRepositoryClient(ctx).get(ctx, itemcsid, handler);
592             // TODO should we assert that the item is in the passed locationAuthority?
593             result = (MultipartOutput) ctx.getOutput();
594         } catch (UnauthorizedException ue) {
595             Response response = Response.status(
596                     Response.Status.UNAUTHORIZED).entity("Get failed reason " + ue.getErrorReason()).type("text/plain").build();
597             throw new WebApplicationException(response);
598         } catch (DocumentNotFoundException dnfe) {
599             if (logger.isDebugEnabled()) {
600                 logger.debug("getLocation", dnfe);
601             }
602             Response response = Response.status(Response.Status.NOT_FOUND).entity(
603                     "Get failed on Location csid=" + itemcsid).type(
604                     "text/plain").build();
605             throw new WebApplicationException(response);
606         } catch (Exception e) {
607             if (logger.isDebugEnabled()) {
608                 logger.debug("getLocation", e);
609             }
610             Response response = Response.status(
611                     Response.Status.INTERNAL_SERVER_ERROR).entity("Get failed").type("text/plain").build();
612             throw new WebApplicationException(response);
613         }
614         if (result == null) {
615             Response response = Response.status(Response.Status.NOT_FOUND).entity(
616                     "Get failed, the requested Location CSID:" + itemcsid + ": was not found.").type(
617                     "text/plain").build();
618             throw new WebApplicationException(response);
619         }
620         return result;
621     }
622
623     /**
624      * Gets the location list.
625      * 
626      * @param parentcsid the parentcsid
627      * @param partialTerm the partial term
628      * @param ui the ui
629      * 
630      * @return the location list
631      */
632     @GET
633     @Path("{csid}/items")
634     @Produces("application/xml")
635     public LocationsCommonList getLocationList(
636             @PathParam("csid") String parentcsid,
637             @QueryParam (IQueryManager.SEARCH_TYPE_PARTIALTERM) String partialTerm,            
638             @Context UriInfo ui) {
639         LocationsCommonList locationObjectList = new LocationsCommonList();
640         try {
641             // Note that docType defaults to the ServiceName, so we're fine with that.
642             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
643                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getItemServiceName(),
644                                 queryParams);
645             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
646             DocumentFilter myFilter = handler.getDocumentFilter();
647
648             // Add the where clause "locations_common:inAuthority='" + parentcsid + "'"
649             myFilter.setWhereClause(LocationJAXBSchema.LOCATIONS_COMMON + ":" +
650                         LocationJAXBSchema.IN_AUTHORITY + "='" + parentcsid + "'");
651             
652             // AND locations_common:displayName LIKE '%partialTerm%'
653             if (partialTerm != null && !partialTerm.isEmpty()) {
654                 String ptClause = 
655                 LocationJAXBSchema.LOCATIONS_COMMON + ":" +
656                         LocationJAXBSchema.DISPLAY_NAME +
657                         " LIKE " +
658                         "'%" + partialTerm + "%'";
659                 myFilter.appendWhereClause(ptClause, IQueryManager.SEARCH_QUALIFIER_AND);
660             }
661             getRepositoryClient(ctx).getFiltered(ctx, handler);
662             locationObjectList = (LocationsCommonList) handler.getCommonPartList();
663         } catch (UnauthorizedException ue) {
664             Response response = Response.status(
665                     Response.Status.UNAUTHORIZED).entity("Index failed reason " + ue.getErrorReason()).type("text/plain").build();
666             throw new WebApplicationException(response);
667         } catch (Exception e) {
668             if (logger.isDebugEnabled()) {
669                 logger.debug("Caught exception in getLocationList", e);
670             }
671             Response response = Response.status(
672                     Response.Status.INTERNAL_SERVER_ERROR).entity("Index failed").type("text/plain").build();
673             throw new WebApplicationException(response);
674         }
675         return locationObjectList;
676     }
677     
678
679     /**
680      * Gets the location list by auth name.
681      * 
682      * @param parentSpecifier the parent specifier
683      * @param partialTerm the partial term
684      * @param ui the ui
685      * 
686      * @return the location list by auth name
687      */
688     @GET
689     @Path("urn:cspace:name({specifier})/items")
690     @Produces("application/xml")
691     public LocationsCommonList getLocationListByAuthName(
692                 @PathParam("specifier") String parentSpecifier,
693             @QueryParam (IQueryManager.SEARCH_TYPE_PARTIALTERM) String partialTerm,            
694             @Context UriInfo ui) {
695         LocationsCommonList locationObjectList = new LocationsCommonList();
696         try {
697             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
698             String whereClause =
699                 LocationAuthorityJAXBSchema.LOCATIONAUTHORITIES_COMMON+
700                 ":"+LocationAuthorityJAXBSchema.DISPLAY_NAME+
701                 "='"+parentSpecifier+"'";
702             // Need to get an Authority by name
703             ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(queryParams);
704             String parentcsid = 
705                 getRepositoryClient(ctx).findDocCSID(ctx, whereClause);
706
707             ctx = createServiceContext(getItemServiceName(), queryParams);
708             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
709             DocumentFilter myFilter = handler.createDocumentFilter(); //new DocumentFilter();
710             myFilter.setPagination(queryParams); //FIXME
711
712             // Add the where clause "locations_common:inAuthority='" + parentcsid + "'"
713             myFilter.setWhereClause(LocationJAXBSchema.LOCATIONS_COMMON + ":" +
714                         LocationJAXBSchema.IN_AUTHORITY + "='" + parentcsid + "'");
715             
716             // AND locations_common:displayName LIKE '%partialTerm%'
717             if (partialTerm != null && !partialTerm.isEmpty()) {
718                 String ptClause = // "AND " +
719                 LocationJAXBSchema.LOCATIONS_COMMON + ":" +
720                         LocationJAXBSchema.DISPLAY_NAME +
721                         " LIKE " +
722                         "'%" + partialTerm + "%'";
723                 myFilter.appendWhereClause(ptClause, "AND");
724             }
725             
726             handler.setDocumentFilter(myFilter);
727             getRepositoryClient(ctx).getFiltered(ctx, handler);
728             locationObjectList = (LocationsCommonList) handler.getCommonPartList();
729         } catch (UnauthorizedException ue) {
730             Response response = Response.status(
731                     Response.Status.UNAUTHORIZED).entity("Index failed reason " + ue.getErrorReason()).type("text/plain").build();
732             throw new WebApplicationException(response);
733         } catch (Exception e) {
734             if (logger.isDebugEnabled()) {
735                 logger.debug("Caught exception in getLocationList", e);
736             }
737             Response response = Response.status(
738                     Response.Status.INTERNAL_SERVER_ERROR).entity("Index failed").type("text/plain").build();
739             throw new WebApplicationException(response);
740         }
741         return locationObjectList;
742     }
743
744     /**
745      * Update location.
746      * 
747      * @param parentcsid the parentcsid
748      * @param itemcsid the itemcsid
749      * @param theUpdate the the update
750      * 
751      * @return the multipart output
752      */
753     @PUT
754     @Path("{csid}/items/{itemcsid}")
755     public MultipartOutput updateLocation(
756             @PathParam("csid") String parentcsid,
757             @PathParam("itemcsid") String itemcsid,
758             MultipartInput theUpdate) {
759         if (logger.isDebugEnabled()) {
760             logger.debug("updateLocation with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
761         }
762         if (parentcsid == null || "".equals(parentcsid)) {
763             logger.error("updateLocation: missing csid!");
764             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
765                     "update failed on Location parentcsid=" + parentcsid).type(
766                     "text/plain").build();
767             throw new WebApplicationException(response);
768         }
769         if (itemcsid == null || "".equals(itemcsid)) {
770             logger.error("updateLocation: missing itemcsid!");
771             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
772                     "update failed on Location=" + itemcsid).type(
773                     "text/plain").build();
774             throw new WebApplicationException(response);
775         }
776         MultipartOutput result = null;
777         try {
778             // Note that we have to create the service context for the Items, not the main service
779                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getItemServiceName(),
780                                 theUpdate);
781             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid);
782             getRepositoryClient(ctx).update(ctx, itemcsid, handler);
783             result = (MultipartOutput) ctx.getOutput();
784         } catch (BadRequestException bre) {
785             Response response = Response.status(
786                     Response.Status.BAD_REQUEST).entity("Create failed reason " + bre.getErrorReason()).type("text/plain").build();
787             throw new WebApplicationException(response);
788         } catch (UnauthorizedException ue) {
789             Response response = Response.status(
790                     Response.Status.UNAUTHORIZED).entity("Update failed reason " + ue.getErrorReason()).type("text/plain").build();
791             throw new WebApplicationException(response);
792         } catch (DocumentNotFoundException dnfe) {
793             if (logger.isDebugEnabled()) {
794                 logger.debug("caught exception in updateLocation", dnfe);
795             }
796             Response response = Response.status(Response.Status.NOT_FOUND).entity(
797                     "Update failed on Location csid=" + itemcsid).type(
798                     "text/plain").build();
799             throw new WebApplicationException(response);
800         } catch (Exception e) {
801             Response response = Response.status(
802                     Response.Status.INTERNAL_SERVER_ERROR).entity("Update failed").type("text/plain").build();
803             throw new WebApplicationException(response);
804         }
805         return result;
806     }
807
808     /**
809      * Delete location.
810      * 
811      * @param parentcsid the parentcsid
812      * @param itemcsid the itemcsid
813      * 
814      * @return the response
815      */
816     @DELETE
817     @Path("{csid}/items/{itemcsid}")
818     public Response deleteLocation(
819             @PathParam("csid") String parentcsid,
820             @PathParam("itemcsid") String itemcsid) {
821         if (logger.isDebugEnabled()) {
822             logger.debug("deleteLocation with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
823         }
824         if (parentcsid == null || "".equals(parentcsid)) {
825             logger.error("deleteLocation: missing csid!");
826             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
827                     "delete failed on Location parentcsid=" + parentcsid).type(
828                     "text/plain").build();
829             throw new WebApplicationException(response);
830         }
831         if (itemcsid == null || "".equals(itemcsid)) {
832             logger.error("deleteLocation: missing itemcsid!");
833             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
834                     "delete failed on Location=" + itemcsid).type(
835                     "text/plain").build();
836             throw new WebApplicationException(response);
837         }
838         try {
839             // Note that we have to create the service context for the Items, not the main service
840                 ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(getItemServiceName());
841             getRepositoryClient(ctx).delete(ctx, itemcsid);
842             return Response.status(HttpResponseCodes.SC_OK).build();
843         } catch (UnauthorizedException ue) {
844             Response response = Response.status(
845                     Response.Status.UNAUTHORIZED).entity("Delete failed reason " + ue.getErrorReason()).type("text/plain").build();
846             throw new WebApplicationException(response);
847         } catch (DocumentNotFoundException dnfe) {
848             if (logger.isDebugEnabled()) {
849                 logger.debug("caught exception in deleteLocation", dnfe);
850             }
851             Response response = Response.status(Response.Status.NOT_FOUND).entity(
852                     "Delete failed on Location itemcsid=" + itemcsid).type(
853                     "text/plain").build();
854             throw new WebApplicationException(response);
855         } catch (Exception e) {
856             Response response = Response.status(
857                     Response.Status.INTERNAL_SERVER_ERROR).entity("Delete failed").type("text/plain").build();
858             throw new WebApplicationException(response);
859         }
860
861     }
862
863 }