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