]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
7337b6243ce201ee7feb455cebe09d13105fcf37
[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 Regents of the University of California
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.acquisition;
25
26 import java.util.List;
27
28 import javax.ws.rs.Consumes;
29 import javax.ws.rs.GET;
30 import javax.ws.rs.Path;
31 import javax.ws.rs.Produces;
32 import javax.ws.rs.DELETE;
33 import javax.ws.rs.POST;
34 import javax.ws.rs.PUT;
35 import javax.ws.rs.PathParam;
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.client.PoxPayloadIn;
45 import org.collectionspace.services.client.PoxPayloadOut;
46 import org.collectionspace.services.client.AcquisitionClient;
47 import org.collectionspace.services.nuxeo.client.java.DocumentModelHandler;
48
49 import org.collectionspace.services.common.AbstractMultiPartCollectionSpaceResourceImpl;
50 import org.collectionspace.services.common.authorityref.AuthorityRefList;
51 import org.collectionspace.services.common.ServiceMessages;
52 import org.collectionspace.services.common.context.MultipartServiceContextImpl;
53 import org.collectionspace.services.common.context.ServiceBindingUtils;
54 import org.collectionspace.services.common.context.ServiceContext;
55 import org.collectionspace.services.common.document.DocumentFilter;
56 import org.collectionspace.services.common.document.DocumentNotFoundException;
57 import org.collectionspace.services.common.document.DocumentHandler;
58 import org.collectionspace.services.common.document.DocumentWrapper;
59 import org.collectionspace.services.common.query.IQueryManager;
60 import org.collectionspace.services.common.query.QueryManager;
61 import org.collectionspace.services.common.security.UnauthorizedException;
62 import org.collectionspace.services.nuxeo.client.java.DocumentModelHandler;
63 import org.collectionspace.services.jaxb.AbstractCommonList;
64 import org.collectionspace.services.nuxeo.client.java.CommonList;
65
66 import org.jboss.resteasy.util.HttpResponseCodes;
67 import org.nuxeo.ecm.core.api.DocumentModel;
68
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71
72 /**
73  * AcquisitionResource.java
74  *
75  * Handles requests to the Acquisition service, orchestrates the retrieval
76  * of relevant resources, and returns responses to the client.
77  */
78 @Path(AcquisitionClient.SERVICE_PATH)
79 @Produces({"application/xml"})
80 @Consumes({"application/xml"})
81 public class AcquisitionResource
82         extends AbstractMultiPartCollectionSpaceResourceImpl {
83
84     /** The logger. */
85     final Logger logger = LoggerFactory.getLogger(AcquisitionResource.class);
86
87     /* (non-Javadoc)
88      * @see org.collectionspace.services.common.AbstractCollectionSpaceResourceImpl#getVersionString()
89      */
90     @Override
91     protected String getVersionString() {
92         /** The last change revision. */
93         final String lastChangeRevision = "$LastChangedRevision$";
94         return lastChangeRevision;
95     }
96
97     /* (non-Javadoc)
98      * @see org.collectionspace.services.common.AbstractCollectionSpaceResourceImpl#getServiceName()
99      */
100     @Override
101     public String getServiceName() {
102         return AcquisitionClient.SERVICE_NAME;
103     }
104
105     @Override
106     public Class<AcquisitionsCommon> getCommonPartClass() {
107         return AcquisitionsCommon.class;
108     }
109
110     /* (non-Javadoc) //FIXME: REM - Please remove dead code.
111      * @see org.collectionspace.services.common.AbstractCollectionSpaceResourceImpl#createDocumentHandler(org.collectionspace.services.common.context.ServiceContext)
112      */
113 //    @Override
114 //    public DocumentHandler createDocumentHandler(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) throws Exception {
115 //        DocumentHandler docHandler = ctx.getDocumentHandler();
116 //        if (ctx.getInput() != null) {
117 //            Object obj = ((MultipartServiceContext) ctx).getInputPart(ctx.getCommonPartLabel(), AcquisitionsCommon.class);
118 //            if (obj != null) {
119 //                docHandler.setCommonPart((AcquisitionsCommon) obj);
120 //            }
121 //        }
122 //        return docHandler;
123 //    }
124     /**
125      * Instantiates a new acquisition resource.
126      */
127     public AcquisitionResource() {
128         // Empty constructor.  Note that all JAX-RS resource classes are singletons.
129     }
130
131     /**
132      * Creates the acquisition.
133      * 
134      * @param input the input
135      * 
136      * @return the response
137      */
138     @POST
139     public Response createAcquisition(String xmlPayload) {
140         try {
141                 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
142             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
143             DocumentHandler handler = createDocumentHandler(ctx);
144             String csid = getRepositoryClient(ctx).create(ctx, handler);
145             UriBuilder path = UriBuilder.fromResource(AcquisitionResource.class);
146             path.path("" + csid);
147             Response response = Response.created(path.build()).build();
148             return response;
149         } catch (UnauthorizedException ue) {
150             Response response = Response.status(
151                     Response.Status.UNAUTHORIZED).entity(
152                     ServiceMessages.CREATE_FAILED + ue.getErrorReason()).type("text/plain").build();
153             throw new WebApplicationException(response);
154         } catch (Exception e) {
155             if (logger.isDebugEnabled()) {
156                 logger.debug("Caught exception in createAcquisition", e);
157             }
158             Response response = Response.status(
159                     Response.Status.INTERNAL_SERVER_ERROR).entity(
160                     ServiceMessages.CREATE_FAILED + e.getMessage()).type("text/plain").build();
161             throw new WebApplicationException(response);
162         }
163     }
164
165     /**
166      * Gets the acquisition.
167      * 
168      * @param csid the csid
169      * 
170      * @return the acquisition
171      */
172     @GET
173     @Path("{csid}")
174     public byte[] getAcquisition(
175             @PathParam("csid") String csid) {
176         if (logger.isDebugEnabled()) {
177             logger.debug("getAcquisition with csid=" + csid);
178         }
179         if (csid == null || "".equals(csid)) {
180             logger.error("getAcquisition:" + ServiceMessages.MISSING_CSID);
181             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
182                     ServiceMessages.READ_FAILED + ServiceMessages.MISSING_CSID).type("text/plain").build();
183             throw new WebApplicationException(response);
184         }
185         PoxPayloadOut result = null;
186         try {
187             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
188             DocumentHandler handler = createDocumentHandler(ctx);
189             getRepositoryClient(ctx).get(ctx, csid, handler);
190             result = ctx.getOutput();
191         } catch (UnauthorizedException ue) {
192             Response response = Response.status(
193                     Response.Status.UNAUTHORIZED).entity(
194                     ServiceMessages.READ_FAILED + ue.getErrorReason()).type("text/plain").build();
195             throw new WebApplicationException(response);
196         } catch (DocumentNotFoundException dnfe) {
197             if (logger.isDebugEnabled()) {
198                 logger.debug("getAcquisition", dnfe);
199             }
200             Response response = Response.status(Response.Status.NOT_FOUND).entity(
201                     ServiceMessages.READ_FAILED + ServiceMessages.resourceNotFoundMsg(csid)).type("text/plain").build();
202             throw new WebApplicationException(response);
203         } catch (Exception e) {
204             if (logger.isDebugEnabled()) {
205                 logger.debug("getAcquisition", e);
206             }
207             Response response = Response.status(
208                     Response.Status.INTERNAL_SERVER_ERROR).entity(
209                     ServiceMessages.READ_FAILED + e.getMessage()).type("text/plain").build();
210             throw new WebApplicationException(response);
211         }
212
213         if (result == null) {
214             Response response = Response.status(Response.Status.NOT_FOUND).entity(
215                     ServiceMessages.READ_FAILED + ServiceMessages.resourceNotFoundMsg(csid)).type("text/plain").build();
216             throw new WebApplicationException(response);
217         }
218         return result.getBytes();
219     }
220
221     /**
222      * Gets the acquisition list.
223      * 
224      * @param ui the ui
225      * @param keywords the keywords
226      * 
227      * @return the acquisition list
228      */
229     @GET
230     @Produces("application/xml")
231     public CommonList getAcquisitionList(@Context UriInfo ui,
232             @QueryParam(IQueryManager.SEARCH_TYPE_KEYWORDS_KW) String keywords) {
233         CommonList result = null;
234         MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
235         if (keywords != null) {
236             result = searchAcquisitions(queryParams, keywords);
237         } else {
238             result = getAcquisitionsList(queryParams);
239         }
240
241         return result;
242     }
243
244     /**
245      * Gets the acquisitions list.
246      * 
247      * @return the acquisitions list
248      */
249     private CommonList getAcquisitionsList(MultivaluedMap<String, String> queryParams) {
250         CommonList commonList;
251         try {
252             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(queryParams);
253             DocumentHandler handler = createDocumentHandler(ctx);
254             getRepositoryClient(ctx).getFiltered(ctx, handler);
255             commonList = (CommonList) handler.getCommonPartList();
256         } catch (UnauthorizedException ue) {
257             Response response = Response.status(
258                     Response.Status.UNAUTHORIZED).entity(
259                     ServiceMessages.LIST_FAILED + ue.getErrorReason()).type("text/plain").build();
260             throw new WebApplicationException(response);
261         } catch (Exception e) {
262             if (logger.isDebugEnabled()) {
263                 logger.debug("Caught exception in getAcquisitionList", e);
264             }
265             Response response = Response.status(
266                     Response.Status.INTERNAL_SERVER_ERROR).entity(
267                     ServiceMessages.LIST_FAILED + e.getMessage()).type("text/plain").build();
268             throw new WebApplicationException(response);
269         }
270         return commonList;
271     }
272
273     /**
274      * Update acquisition.
275      * 
276      * @param csid the csid
277      * @param theUpdate the the update
278      * 
279      * @return the multipart output
280      */
281     @PUT
282     @Path("{csid}")
283     public byte[] updateAcquisition(
284             @PathParam("csid") String csid,
285             String xmlPayload) {
286         if (logger.isDebugEnabled()) {
287             logger.debug("updateAcquisition with csid=" + csid);
288         }
289         if (csid == null || "".equals(csid)) {
290             logger.error("updateAcquisition: missing csid!");
291             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
292                     ServiceMessages.UPDATE_FAILED + ServiceMessages.MISSING_CSID).type("text/plain").build();
293             throw new WebApplicationException(response);
294         }
295         PoxPayloadOut result = null;
296         try {
297                 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
298             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
299             DocumentHandler handler = createDocumentHandler(ctx);
300             getRepositoryClient(ctx).update(ctx, csid, handler);
301             result = ctx.getOutput();
302         } catch (UnauthorizedException ue) {
303             Response response = Response.status(
304                     Response.Status.UNAUTHORIZED).entity(
305                     ServiceMessages.UPDATE_FAILED + ue.getErrorReason()).type("text/plain").build();
306             throw new WebApplicationException(response);
307         } catch (DocumentNotFoundException dnfe) {
308             if (logger.isDebugEnabled()) {
309                 logger.debug("caught exception in updateAcquisition", dnfe);
310             }
311             Response response = Response.status(Response.Status.NOT_FOUND).entity(
312                     ServiceMessages.UPDATE_FAILED + ServiceMessages.resourceNotFoundMsg(csid)).type("text/plain").build();
313             throw new WebApplicationException(response);
314         } catch (Exception e) {
315             Response response = Response.status(
316                     Response.Status.INTERNAL_SERVER_ERROR).entity(
317                     ServiceMessages.UPDATE_FAILED + e.getMessage()).type("text/plain").build();
318             throw new WebApplicationException(response);
319         }
320         return result.getBytes();
321     }
322
323     /**
324      * Delete acquisition.
325      * 
326      * @param csid the csid
327      * 
328      * @return the response
329      */
330     @DELETE
331     @Path("{csid}")
332     public Response deleteAcquisition(@PathParam("csid") String csid) {
333
334         if (logger.isDebugEnabled()) {
335             logger.debug("deleteAcquisition with csid=" + csid);
336         }
337         if (csid == null || "".equals(csid)) {
338             logger.error("deleteAcquisition: missing csid!");
339             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
340                     ServiceMessages.DELETE_FAILED + ServiceMessages.MISSING_CSID).type("text/plain").build();
341             throw new WebApplicationException(response);
342         }
343         try {
344             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
345             getRepositoryClient(ctx).delete(ctx, csid);
346             return Response.status(HttpResponseCodes.SC_OK).build();
347         } catch (UnauthorizedException ue) {
348             Response response = Response.status(
349                     Response.Status.UNAUTHORIZED).entity(
350                     ServiceMessages.DELETE_FAILED + ue.getErrorReason()).type("text/plain").build();
351             throw new WebApplicationException(response);
352         } catch (DocumentNotFoundException dnfe) {
353             if (logger.isDebugEnabled()) {
354                 logger.debug("caught exception in deleteAcquisition", dnfe);
355             }
356             Response response = Response.status(Response.Status.NOT_FOUND).entity(
357                     ServiceMessages.DELETE_FAILED + ServiceMessages.resourceNotFoundMsg(csid)).type("text/plain").build();
358             throw new WebApplicationException(response);
359         } catch (Exception e) {
360             Response response = Response.status(
361                     Response.Status.INTERNAL_SERVER_ERROR).entity(
362                     ServiceMessages.DELETE_FAILED + e.getMessage()).type("text/plain").build();
363             throw new WebApplicationException(response);
364         }
365     }
366
367     /**
368      * Keywords search acquisitions.
369      * 
370      * @param ui the ui
371      * @param keywords the keywords
372      * 
373      * @return the acquisitions common list
374      */
375     @GET
376     @Path("/search")
377     @Produces("application/xml")
378     @Deprecated
379     public CommonList keywordsSearchAcquisitions(@Context UriInfo ui,
380             @QueryParam(IQueryManager.SEARCH_TYPE_KEYWORDS) String keywords) {
381         MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
382         return searchAcquisitions(queryParams, keywords);
383     }
384
385     /**
386      * Search acquisitions.
387      * 
388      * @param keywords the keywords
389      * 
390      * @return the acquisitions common list
391      */
392     private CommonList searchAcquisitions(
393             MultivaluedMap<String, String> queryParams, String keywords) {
394         CommonList commonList;
395         try {
396             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(queryParams);
397             DocumentHandler handler = createDocumentHandler(ctx);
398
399             // perform a keyword search
400             if (keywords != null && !keywords.isEmpty()) {
401                 String whereClause = QueryManager.createWhereClauseFromKeywords(keywords);
402                 DocumentFilter documentFilter = handler.getDocumentFilter();
403                 documentFilter.setWhereClause(whereClause);
404                 if (logger.isDebugEnabled()) {
405                     logger.debug("The WHERE clause is: " + documentFilter.getWhereClause());
406                 }
407             }
408             getRepositoryClient(ctx).getFiltered(ctx, handler);
409             commonList = (CommonList) handler.getCommonPartList();
410         } catch (UnauthorizedException ue) {
411             Response response = Response.status(
412                     Response.Status.UNAUTHORIZED).entity(
413                     ServiceMessages.SEARCH_FAILED + ue.getErrorReason()).type("text/plain").build();
414             throw new WebApplicationException(response);
415         } catch (Exception e) {
416             if (logger.isDebugEnabled()) {
417                 logger.debug("Caught exception in search for Acquisitions", e);
418             }
419             Response response = Response.status(
420                     Response.Status.INTERNAL_SERVER_ERROR).entity(
421                     ServiceMessages.SEARCH_FAILED + e.getMessage()).type("text/plain").build();
422             throw new WebApplicationException(response);
423         }
424         return commonList;
425     }
426
427     /**
428      * Gets the authority refs.
429      * 
430      * @param csid the csid
431      * @param ui the ui
432      * 
433      * @return the authority refs
434      */
435     @GET
436     @Path("{csid}/authorityrefs")
437     public AuthorityRefList getAuthorityRefs(
438             @PathParam("csid") String csid,
439             @Context UriInfo ui) {
440         AuthorityRefList authRefList = null;
441         try {
442             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
443             DocumentWrapper<DocumentModel> docWrapper =
444                     getRepositoryClient(ctx).getDoc(ctx, csid);
445             DocumentModelHandler<PoxPayloadIn, PoxPayloadOut> handler = (DocumentModelHandler<PoxPayloadIn, PoxPayloadOut>) createDocumentHandler(ctx);
446             List<String> authRefFields =
447                     ((MultipartServiceContextImpl) ctx).getCommonPartPropertyValues(
448                     ServiceBindingUtils.AUTH_REF_PROP, ServiceBindingUtils.QUALIFIED_PROP_NAMES);
449             authRefList = handler.getAuthorityRefs(docWrapper, authRefFields);
450         } catch (UnauthorizedException ue) {
451             Response response = Response.status(
452                     Response.Status.UNAUTHORIZED).entity(
453                     ServiceMessages.AUTH_REFS_FAILED + ue.getErrorReason()).type("text/plain").build();
454             throw new WebApplicationException(response);
455         } catch (Exception e) {
456             if (logger.isDebugEnabled()) {
457                 logger.debug("Caught exception in getAuthorityRefs", e);
458             }
459             Response response = Response.status(
460                     Response.Status.INTERNAL_SERVER_ERROR).entity(
461                     ServiceMessages.AUTH_REFS_FAILED + e.getMessage()).type("text/plain").build();
462             throw new WebApplicationException(response);
463         }
464         return authRefList;
465     }
466 }