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