]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
ed39f501a118cb91a56f783f0f6c0f4bd5bf6f6e
[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  *  $LastChangedRevision$
25  */
26 package org.collectionspace.services.collectionobject;
27
28 import java.util.ArrayList;
29 import java.util.List;
30
31 import javax.ws.rs.Consumes;
32 import javax.ws.rs.DELETE;
33 import javax.ws.rs.GET;
34 import javax.ws.rs.POST;
35 import javax.ws.rs.PUT;
36 import javax.ws.rs.Path;
37 import javax.ws.rs.PathParam;
38 import javax.ws.rs.Produces;
39 import javax.ws.rs.QueryParam;
40 import javax.ws.rs.WebApplicationException;
41 import javax.ws.rs.core.Context;
42 import javax.ws.rs.core.Response;
43 import javax.ws.rs.core.UriBuilder;
44 import javax.ws.rs.core.UriInfo;
45 import javax.ws.rs.core.MultivaluedMap;
46
47 import org.collectionspace.services.common.imaging.nuxeo.NuxeoImageUtils;
48 import org.collectionspace.services.common.AbstractMultiPartCollectionSpaceResourceImpl;
49 import org.collectionspace.services.common.authorityref.AuthorityRefList;
50 import org.collectionspace.services.common.context.ServiceContextFactory;
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.DocumentFilter;
58 import org.collectionspace.services.common.document.DocumentHandler;
59 import org.collectionspace.services.common.document.DocumentNotFoundException;
60 import org.collectionspace.services.common.document.DocumentWrapper;
61 import org.collectionspace.services.common.query.IQueryManager;
62 import org.collectionspace.services.common.query.QueryManager;
63 import org.collectionspace.services.common.security.UnauthorizedException;
64 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils;
65 import org.collectionspace.services.intake.IntakeResource;
66 import org.collectionspace.services.intake.IntakesCommonList;
67 //import org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl;
68 import org.collectionspace.services.nuxeo.client.java.DocumentModelHandler;
69 import org.collectionspace.services.relation.NewRelationResource;
70 import org.collectionspace.services.relation.RelationsCommonList;
71 import org.collectionspace.services.relation.RelationshipType;
72 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
73 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
74 import org.jboss.resteasy.util.HttpResponseCodes;
75 import org.nuxeo.ecm.core.api.DocumentModel;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
78
79
80 /**
81  * The Class CollectionObjectResource.
82  */
83 @Path("/collectionobjects")
84 @Consumes("multipart/mixed")
85 @Produces("multipart/mixed")
86 public class CollectionObjectResource
87         extends AbstractMultiPartCollectionSpaceResourceImpl {
88
89     /** The Constant serviceName. */
90     static final public String serviceName = "collectionobjects";
91     
92     /** The logger. */
93     final Logger logger = LoggerFactory.getLogger(CollectionObjectResource.class);
94
95     /* (non-Javadoc)
96      * @see org.collectionspace.services.common.AbstractCollectionSpaceResourceImpl#getVersionString()
97      */
98     @Override
99     public String getVersionString() {
100         /** The last change revision. */
101         final String lastChangeRevision = "$LastChangedRevision$";
102         return lastChangeRevision;
103     }
104
105     /* (non-Javadoc)
106      * @see org.collectionspace.services.common.AbstractCollectionSpaceResourceImpl#getServiceName()
107      */
108     @Override
109     public String getServiceName() {
110         return serviceName;
111     }
112     
113     /* (non-Javadoc)
114      * @see org.collectionspace.services.common.CollectionSpaceResource#getCommonPartClass()
115      */
116     @Override
117     public Class<CollectionobjectsCommon> getCommonPartClass() {
118         return CollectionobjectsCommon.class;
119     }
120     
121     /* (non-Javadoc)
122      * @see org.collectionspace.services.common.AbstractCollectionSpaceResourceImpl#createDocumentHandler(org.collectionspace.services.common.context.ServiceContext)
123      */
124 //    @Override
125 //    public DocumentHandler createDocumentHandler(ServiceContext<MultipartInput, MultipartOutput> ctx) throws Exception {
126 //        DocumentHandler docHandler = ctx.getDocumentHandler();
127 //        if (ctx.getInput() != null) {
128 //            Object obj = ((MultipartServiceContext) ctx).getInputPart(ctx.getCommonPartLabel(),
129 //                    CollectionobjectsCommon.class);
130 //            if (obj != null) {
131 //                docHandler.setCommonPart((CollectionobjectsCommon) obj);
132 //            }
133 //        }
134 //        return docHandler;
135 //    }
136
137     /**
138      * Creates the collection object.
139      * 
140      * @param input the input
141      * 
142      * @return the response
143      */
144     @POST
145     public Response createCollectionObject(MultipartInput input) {
146         try {
147             ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(input); //
148             DocumentHandler handler = createDocumentHandler(ctx);
149             String csid = getRepositoryClient(ctx).create(ctx, handler);
150             UriBuilder path = UriBuilder.fromResource(CollectionObjectResource.class);
151             path.path("" + csid);
152             Response response = Response.created(path.build()).build();
153             return response;
154         } catch (BadRequestException bre) {
155             Response response = Response.status(
156                     Response.Status.BAD_REQUEST).entity("Create failed reason " + bre.getErrorReason()).type("text/plain").build();
157             throw new WebApplicationException(response);
158         } catch (UnauthorizedException ue) {
159             Response response = Response.status(
160                     Response.Status.UNAUTHORIZED).entity("Create failed reason " + ue.getErrorReason()).type("text/plain").build();
161             throw new WebApplicationException(response);
162         } catch (Exception e) {
163             if (logger.isDebugEnabled()) {
164                 logger.debug("Caught exception in createCollectionObject", e);
165             }
166             Response response = Response.status(
167                     Response.Status.INTERNAL_SERVER_ERROR).entity("Create failed").type("text/plain").build();
168             throw new WebApplicationException(response);
169         }
170     }
171
172     /**
173      * Gets the collection object.
174      * 
175      * @param csid the csid
176      * 
177      * @return the collection object
178      */
179     @GET
180     @Path("{csid}")
181     public MultipartOutput getCollectionObject(
182             @PathParam("csid") String csid) {
183         if (logger.isDebugEnabled()) {
184             logger.debug("getCollectionObject with csid=" + csid);
185         }
186         if (csid == null || "".equals(csid)) {
187             logger.error("getCollectionObject: missing csid!");
188             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
189                     "get failed on CollectionObject csid=" + csid).type(
190                     "text/plain").build();
191             throw new WebApplicationException(response);
192         }
193         MultipartOutput result = null;
194         try {
195             ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext();
196             DocumentHandler handler = createDocumentHandler(ctx);
197             getRepositoryClient(ctx).get(ctx, csid, handler);
198             result = (MultipartOutput) ctx.getOutput();
199         } catch (UnauthorizedException ue) {
200             Response response = Response.status(
201                     Response.Status.UNAUTHORIZED).entity("Get failed reason " + ue.getErrorReason()).type("text/plain").build();
202             throw new WebApplicationException(response);
203         } catch (DocumentNotFoundException dnfe) {
204             if (logger.isDebugEnabled()) {
205                 logger.debug("getCollectionObject", dnfe);
206             }
207             Response response = Response.status(Response.Status.NOT_FOUND).entity(
208                     "Get failed on CollectionObject csid=" + csid).type(
209                     "text/plain").build();
210             throw new WebApplicationException(response);
211         } catch (Exception e) {
212             if (logger.isDebugEnabled()) {
213                 logger.debug("getCollectionObject", e);
214             }
215             Response response = Response.status(
216                     Response.Status.INTERNAL_SERVER_ERROR).entity("Get failed").type("text/plain").build();
217             throw new WebApplicationException(response);
218         }
219
220         if (result == null) {
221             Response response = Response.status(Response.Status.NOT_FOUND).entity(
222                     "Get failed, the requested CollectionObject CSID:" + csid + ": was not found.").type(
223                     "text/plain").build();
224             throw new WebApplicationException(response);
225         }
226         return result;
227     }
228     
229     /**
230      * Gets the collection object list.
231      * 
232      * @param ui the ui
233      * @param keywords the keywords
234      * 
235      * @return the collection object list
236      */
237     @GET
238     @Produces("application/xml")
239     public CollectionobjectsCommonList getCollectionObjectList(@Context UriInfo ui,
240                 @QueryParam(IQueryManager.SEARCH_TYPE_KEYWORDS_KW) String keywords) {
241         CollectionobjectsCommonList result = null;
242         MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
243         if (keywords != null) {
244                 result = searchCollectionObjects(queryParams, keywords);
245         } else {
246                 result = getCollectionObjectList(queryParams);
247         }
248         
249         return result;
250     }
251     
252     /**
253      * Gets the collection object list.
254      */
255     private CollectionobjectsCommonList getCollectionObjectList(MultivaluedMap<String, String> queryParams) {
256         CollectionobjectsCommonList collectionObjectList;
257         try {
258             ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(queryParams);
259             DocumentHandler handler = createDocumentHandler(ctx);
260             getRepositoryClient(ctx).getFiltered(ctx, handler);
261             collectionObjectList = (CollectionobjectsCommonList) handler.getCommonPartList();
262         } catch (UnauthorizedException ue) {
263             Response response = Response.status(
264                     Response.Status.UNAUTHORIZED).entity("Index failed reason " + ue.getErrorReason()).type("text/plain").build();
265             throw new WebApplicationException(response);
266         } catch (Exception e) {
267             if (logger.isDebugEnabled()) {
268                 logger.debug("Caught exception in getCollectionObjectList", e);
269             }
270             Response response = Response.status(
271                     Response.Status.INTERNAL_SERVER_ERROR).entity("Index failed").type("text/plain").build();
272             throw new WebApplicationException(response);
273         }
274         return collectionObjectList;
275     }
276
277     /**
278      * Update collection object.
279      * 
280      * @param csid the csid
281      * @param theUpdate the the update
282      * 
283      * @return the multipart output
284      */
285     @PUT
286     @Path("{csid}")
287     public MultipartOutput updateCollectionObject(
288             @PathParam("csid") String csid,
289             MultipartInput theUpdate) {
290         if (logger.isDebugEnabled()) {
291             logger.debug("updateCollectionObject with csid=" + csid);
292         }
293         if (csid == null || "".equals(csid)) {
294             logger.error("updateCollectionObject: missing csid!");
295             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
296                     "update failed on CollectionObject csid=" + csid).type(
297                     "text/plain").build();
298             throw new WebApplicationException(response);
299         }
300         MultipartOutput result = null;
301         try {
302             ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(theUpdate);
303             DocumentHandler handler = createDocumentHandler(ctx);
304             getRepositoryClient(ctx).update(ctx, csid, handler);
305             result = (MultipartOutput) ctx.getOutput();
306         } catch (BadRequestException bre) {
307             Response response = Response.status(
308                     Response.Status.BAD_REQUEST).entity("Update failed reason " + bre.getErrorReason()).type("text/plain").build();
309             throw new WebApplicationException(response);
310         } catch (UnauthorizedException ue) {
311             Response response = Response.status(
312                     Response.Status.UNAUTHORIZED).entity("Update failed reason " + ue.getErrorReason()).type("text/plain").build();
313             throw new WebApplicationException(response);
314         } catch (DocumentNotFoundException dnfe) {
315             if (logger.isDebugEnabled()) {
316                 logger.debug("caugth exception in updateCollectionObject", dnfe);
317             }
318             Response response = Response.status(Response.Status.NOT_FOUND).entity(
319                     "Update failed on CollectionObject csid=" + csid).type(
320                     "text/plain").build();
321             throw new WebApplicationException(response);
322         } catch (Exception e) {
323             Response response = Response.status(
324                     Response.Status.INTERNAL_SERVER_ERROR).entity("Update failed").type("text/plain").build();
325             throw new WebApplicationException(response);
326         }
327         return result;
328     }
329
330     /**
331      * Delete collection object.
332      * 
333      * @param csid the csid
334      * 
335      * @return the response
336      */
337     @DELETE
338     @Path("{csid}")
339     public Response deleteCollectionObject(@PathParam("csid") String csid) {
340
341         if (logger.isDebugEnabled()) {
342             logger.debug("deleteCollectionObject with csid=" + csid);
343         }
344         if (csid == null || "".equals(csid)) {
345             logger.error("deleteCollectionObject: missing csid!");
346             Response response = Response.status(Response.Status.BAD_REQUEST).entity(
347                     "delete failed on CollectionObject csid=" + csid).type(
348                     "text/plain").build();
349             throw new WebApplicationException(response);
350         }
351         try {
352             ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext();
353             getRepositoryClient(ctx).delete(ctx, csid);
354             return Response.status(HttpResponseCodes.SC_OK).build();
355         } catch (UnauthorizedException ue) {
356             Response response = Response.status(
357                     Response.Status.UNAUTHORIZED).entity("Delete failed reason " + ue.getErrorReason()).type("text/plain").build();
358             throw new WebApplicationException(response);
359         } catch (DocumentNotFoundException dnfe) {
360             if (logger.isDebugEnabled()) {
361                 logger.debug("caught exception in deleteCollectionObject", dnfe);
362             }
363             Response response = Response.status(Response.Status.NOT_FOUND).entity(
364                     "Delete failed on CollectionObject csid=" + csid).type(
365                     "text/plain").build();
366             throw new WebApplicationException(response);
367         } catch (Exception e) {
368             Response response = Response.status(
369                     Response.Status.INTERNAL_SERVER_ERROR).entity("Delete failed").type("text/plain").build();
370             throw new WebApplicationException(response);
371         }
372
373     }
374
375     /**
376      * Gets the intakes common list.
377      * 
378      * @param ui the ui
379      * @param csid the csid
380      * 
381      * @return the intakes common list
382      */
383     @GET
384     @Path("{csid}/intakes")
385     @Produces("application/xml")
386     public IntakesCommonList getIntakesCommonList(@Context UriInfo ui,
387                 @PathParam("csid") String csid) {
388         IntakesCommonList result = null;        
389         MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
390         
391         try {
392                 //
393                 // Find all the intake-related relation records.
394                 //
395                 String subjectCsid = csid;
396                 String predicate = RelationshipType.COLLECTIONOBJECT_INTAKE.value();
397                 String objectCsid = null;
398                 NewRelationResource relationResource = new NewRelationResource();
399                 RelationsCommonList relationsCommonList = relationResource.getRelationList(queryParams,
400                                 subjectCsid, predicate, objectCsid);
401                 
402                 //
403                 // Create an array of Intake csid's
404                 //
405                 List<RelationsCommonList.RelationListItem> relationsListItems = relationsCommonList.getRelationListItem();
406                 List<String> intakeCsidList = new ArrayList<String>();
407             for (RelationsCommonList.RelationListItem relationsListItem : relationsListItems) {
408                 intakeCsidList.add(relationsListItem.getObjectCsid());
409                 }
410             
411             //
412             // Get a response list for the Intake records from the Intake resource
413             //
414                 IntakeResource intakeResource = new IntakeResource();
415                 result = intakeResource.getIntakeList(intakeCsidList);
416         } catch (Exception e) {
417             if (logger.isDebugEnabled()) {
418                 logger.debug("Caught exception in getIntakeList", e);
419             }
420             Response response = Response.status(
421                     Response.Status.INTERNAL_SERVER_ERROR).entity("Index failed").type("text/plain").build();
422             throw new WebApplicationException(response);
423         }
424         
425         return result;
426     }
427
428     /**
429      * Gets the authority refs.
430      * 
431      * @param csid the csid
432      * @param ui the ui
433      * 
434      * @return the authority refs
435      */
436     @GET
437     @Path("{csid}/authorityrefs")
438     @Produces("application/xml")
439     public AuthorityRefList getAuthorityRefs(
440                 @PathParam("csid") String csid, 
441                 @Context UriInfo ui) {
442         AuthorityRefList authRefList = null;
443         try {
444                 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
445             ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(queryParams);
446             DocumentWrapper<DocumentModel> docWrapper = 
447                 getRepositoryClient(ctx).getDoc(ctx, csid);
448             DocumentModelHandler<MultipartInput, MultipartOutput> docHandler = 
449                 (DocumentModelHandler<MultipartInput, MultipartOutput>)createDocumentHandler(ctx);
450             List<String> authRefFields = 
451                 ((MultipartServiceContextImpl)ctx).getCommonPartPropertyValues(
452                                 ServiceBindingUtils.AUTH_REF_PROP, ServiceBindingUtils.QUALIFIED_PROP_NAMES);
453             authRefList = docHandler.getAuthorityRefs(docWrapper, authRefFields);
454         } catch (UnauthorizedException ue) {
455             Response response = Response.status(
456                     Response.Status.UNAUTHORIZED).entity("Index failed reason " + ue.getErrorReason()).type("text/plain").build();
457             throw new WebApplicationException(response);
458         } catch (Exception e) {
459             if (logger.isDebugEnabled()) {
460                 logger.debug("Caught exception in getAuthorityRefs", e);
461             }
462             Response response = Response.status(
463                     Response.Status.INTERNAL_SERVER_ERROR).entity("Index failed").type("text/plain").build();
464             throw new WebApplicationException(response);
465         }
466         return authRefList;
467     }
468     
469     /**
470      * Roundtrip.
471      * 
472      * This is an intentionally empty method used for getting a rough time estimate
473      * of the overhead required for a client->server request/response cycle.
474      * 
475      * @return the response
476      */
477     @GET
478     @Path("/roundtrip")
479     @Produces("application/xml")
480     public Response roundtrip() {
481         Response result = null;
482         
483                 if (logger.isDebugEnabled()) {
484                         logger.debug("------------------------------------------------------------------------------");
485                         logger.debug("Client to server roundtrip called.");
486                         logger.debug("------------------------------------------------------------------------------");
487                         logger.debug("");
488                 }
489                 result = Response.status(HttpResponseCodes.SC_OK).build();
490                 
491                 return result;
492     }
493     
494     @GET
495     @Path("/picture")
496     @Produces("application/xml")
497     public Response createPictureDocument() {
498         Response result = null;
499         
500                 if (logger.isDebugEnabled()) {
501                         logger.debug("------------------------------------------------------------------------------");
502                         logger.debug("Prototype to create a Picture document in Nuxeo");
503                         logger.debug("------------------------------------------------------------------------------");
504                         logger.debug("");
505                 }
506                 
507                 NuxeoImageUtils.createPicture();
508                 result = Response.status(HttpResponseCodes.SC_OK).build();
509                 
510                 return result;
511     }    
512
513     /**
514      * This method is deprecated.  Use kwSearchCollectionObjects() method instead.
515      * Keywords search collection objects.
516      * @param ui 
517      * 
518      * @param keywords the keywords
519      * 
520      * @return the collectionobjects common list
521      */
522     @GET
523     @Path("/search")
524     @Produces("application/xml")
525     public CollectionobjectsCommonList keywordsSearchCollectionObjects(@Context UriInfo ui,
526             @QueryParam(IQueryManager.SEARCH_TYPE_KEYWORDS) String keywords) {
527         MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
528         return searchCollectionObjects(queryParams, keywords);
529     }    
530     
531     /**
532      * Search collection objects.
533      * 
534      * @param keywords the keywords
535      * 
536      * @return the collectionobjects common list
537      */
538     private CollectionobjectsCommonList searchCollectionObjects(
539                 MultivaluedMap<String, String> queryParams,
540                 String keywords) {
541         CollectionobjectsCommonList collectionObjectList;
542         try {
543             ServiceContext<MultipartInput, MultipartOutput> ctx = createServiceContext(queryParams);
544             DocumentHandler handler = createDocumentHandler(ctx);
545
546             // perform a keyword search
547             if (keywords != null && !keywords.isEmpty()) {
548                 String whereClause = QueryManager.createWhereClauseFromKeywords(keywords);
549                 DocumentFilter documentFilter = handler.getDocumentFilter();
550                 documentFilter.setWhereClause(whereClause);
551                 if (logger.isDebugEnabled()) {
552                     logger.debug("The WHERE clause is: " + documentFilter.getWhereClause());
553                 }
554             }
555             getRepositoryClient(ctx).getFiltered(ctx, handler);
556             collectionObjectList = (CollectionobjectsCommonList) handler.getCommonPartList();
557         } catch (UnauthorizedException ue) {
558             Response response = Response.status(
559                     Response.Status.UNAUTHORIZED).entity("Index failed reason " + ue.getErrorReason()).type("text/plain").build();
560             throw new WebApplicationException(response);
561         } catch (Exception e) {
562             if (logger.isDebugEnabled()) {
563                 logger.debug("Caught exception in getCollectionObjectList", e);
564             }
565             Response response = Response.status(
566                     Response.Status.INTERNAL_SERVER_ERROR).entity("Index failed").type("text/plain").build();
567             throw new WebApplicationException(response);
568         }
569         return collectionObjectList;
570     }
571         
572 }