]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
88fe963c1b19e42b04353321e094923275a6647e
[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  * https://source.collectionspace.org/collection-space/LICENSE.txt
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  */
23
24 package org.collectionspace.services.collectionobject.client.sample;
25
26 import java.io.StringWriter;
27 import java.util.ArrayList;
28 import java.util.List;
29
30 import javax.ws.rs.core.MediaType;
31 import javax.ws.rs.core.MultivaluedMap;
32 import javax.ws.rs.core.Response;
33 import javax.xml.bind.JAXBContext;
34 import javax.xml.bind.Marshaller;
35
36 import org.collectionspace.services.client.CollectionObjectClient;
37 import org.collectionspace.services.client.PayloadInputPart;
38 import org.collectionspace.services.client.PayloadOutputPart;
39 import org.collectionspace.services.client.PoxPayloadIn;
40 import org.collectionspace.services.client.PoxPayloadOut;
41 import org.collectionspace.services.collectionobject.CollectionobjectsCommon;
42 import org.collectionspace.services.collectionobject.CollectionobjectsCommonList;
43 import org.collectionspace.services.collectionobject.ResponsibleDepartmentList;
44 import org.collectionspace.services.collectionobject.domain.naturalhistory.CollectionobjectsNaturalhistory;
45
46 import org.jboss.resteasy.client.ClientResponse;
47
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  * Sample, sample client code for creating and accessing 
53  * CollectionObject records.
54  *
55  * $LastChangedRevision: $
56  * $LastChangedDate: $
57  */
58 public class Sample {
59
60     private static final Logger logger =
61         LoggerFactory.getLogger(Sample.class);
62
63     // Instance variables specific to this test.
64     private CollectionObjectClient client = new CollectionObjectClient();
65     final String SERVICE_PATH_COMPONENT = "collectionobjects";
66
67
68     // ---------------------------------------------------------------
69     // Create
70     // ---------------------------------------------------------------
71
72     public String createCollectionObject() {
73
74        // Create a CollectionObject record to submit to the service.
75        PoxPayloadOut multipart = createCollectionObjectInstance();
76
77        // Submit a 'create' request to the service, sending the new
78        // CollectionObject record to be created, and store the response.
79        ClientResponse<Response> res = client.create(multipart);
80
81        // Get the status code from the response and check it against
82        // the expected status code.
83        if (res.getStatus() != Response.Status.CREATED.getStatusCode()) {
84            logger.error("Error creating new CollectionObject. Status code = " +
85                res.getStatus());
86            return "";
87        } else {
88            logger.info("CollectionObject created successfully.");
89        }
90
91        // Return the new record number for the newly-created record.
92        return extractId(res);
93
94    }
95
96     // ---------------------------------------------------------------
97     // Read
98     // ---------------------------------------------------------------
99
100     public PoxPayloadIn readCollectionObject(String resourceId) throws Exception {
101
102         if (resourceId == null || resourceId.trim().isEmpty()) {
103             throw new IllegalArgumentException(
104                 "Resource ID must not be null or empty.");
105         }
106
107         // Submit the read ("get") request to the service and store the response.
108         // The resourceId is a unique identifier for the CollectionObject
109         // record we're reading.
110         ClientResponse<String> res = client.read(resourceId);
111
112         // Get the status code from the response and check it against
113         // the expected status code.
114         if (res.getStatus() != Response.Status.OK.getStatusCode()) {
115             logger.error("Error reading CollectionObject with" +
116                "resource ID " + resourceId + ". Status code = " +
117                res.getStatus());
118             return null;
119         }
120
121         // Get the entity body of the response from the service.
122         PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
123
124         return input;
125
126    }
127
128    private CollectionobjectsCommonList readCollectionObjectList()
129        throws Exception {
130
131         // Submit the read list request to the service and store the response.
132         ClientResponse<CollectionobjectsCommonList> res = client.readList();
133
134         // Get the status code from the response and check it against
135         // the expected status code.
136         if (res.getStatus() != Response.Status.OK.getStatusCode()) {
137             logger.error("Error reading list of CollectionObjects. Status code = " +
138                res.getStatus());
139             return null;
140         }
141
142         CollectionobjectsCommonList list = res.getEntity();
143         return list;
144
145
146    }
147
148    // ---------------------------------------------------------------
149    // Delete
150    // ---------------------------------------------------------------
151
152    private void deleteCollectionObject(String resourceId) {
153
154         if (resourceId == null || resourceId.trim().isEmpty()) {
155             throw new IllegalArgumentException(
156                 "Resource ID must not be null or empty.");
157         }
158         
159         ClientResponse res = client.delete(resourceId);
160
161         // Get the status code from the response and check it against
162         // the expected status code.
163         if (res.getStatus() != Response.Status.OK.getStatusCode()) {
164             logger.error("Error deleting CollectionObject with" +
165                "resource ID " + resourceId + ". Status code = " +
166                res.getStatus());
167             return;
168         }
169
170    }
171
172    private void deleteAllCollectionObjects() throws Exception {
173
174         int recordsDeleted = 0;
175         for (String resourceId : getAllResourceIds()) {
176
177             ClientResponse res = client.delete(resourceId);
178
179             // Get the status code from the response and check it against
180             // the expected status code.
181             if (res.getStatus() != Response.Status.OK.getStatusCode()) {
182             logger.error("Error deleting CollectionObject with" +
183                "resource ID " + resourceId + ". Status code = " +
184                res.getStatus());
185             } else {
186                 recordsDeleted++;
187             }
188         }
189
190         if (logger.isInfoEnabled()) {
191             logger.info("Deleted " + recordsDeleted + " CollectionObject record(s).");
192         }
193
194    }
195
196    // ---------------------------------------------------------------
197    // Utility methods
198    // ---------------------------------------------------------------
199
200    private PoxPayloadOut createCollectionObjectInstance() {
201
202        // Create the Common part of a CollectionObject and add data to its fields.
203
204        CollectionobjectsCommon collectionObject = new CollectionobjectsCommon();
205        collectionObject.setObjectNumber("some object number here");
206        collectionObject.getObjectNameList().getObjectNameGroup().get(0).setObjectName("some object name here");
207
208
209        ResponsibleDepartmentList deptList = new ResponsibleDepartmentList();
210        List<String> depts = deptList.getResponsibleDepartment();
211        // @TODO Use properly formatted refNames for representative departments
212        // in this example test record. The following are mere placeholders.
213        depts.add("urn:org.collectionspace.services.department:Registrar");
214        depts.add("urn:org.walkerart.department:Fine Art");
215        collectionObject.setAge(""); // Test using an empty String.
216        collectionObject.getBriefDescriptions().getBriefDescription().add("Papier mache bird mask with horns, " +
217                       "painted red with black and yellow spots. " +
218                       "Puerto Rico. ca. 8&quot; high, 6&quot; wide, projects 10&quot; (with horns).");
219        PoxPayloadOut multipart = new PoxPayloadOut(CollectionObjectClient.SERVICE_PAYLOAD_NAME);
220        PayloadOutputPart commonPart = multipart.addPart(collectionObject,
221                MediaType.APPLICATION_XML_TYPE);
222        commonPart.setLabel(getCommonPartName());
223
224        if (logger.isInfoEnabled()) {
225            logger.info("CollectionObject Common part to be created:");
226            logger.info(objectAsXmlString(collectionObject,
227                CollectionobjectsCommon.class));
228        }
229
230        // Create a "domain" part of a CollectionObject and add data to its fields.
231        // This part might come from a community or consortia in a particular domain.
232        // There could potentially be multiple "domain" parts in a CollectionObject record.
233
234        // This example adds data to fields for a hypothetical Natural History domain,
235        // as in the case of the test fields below ...
236
237        CollectionobjectsNaturalhistory conh = new CollectionobjectsNaturalhistory();
238        conh.setNhString("test-string");
239        conh.setNhInt(999);
240        conh.setNhLong(9999);
241
242        PayloadOutputPart nhPart = multipart.addPart(conh, MediaType.APPLICATION_XML_TYPE);
243        nhPart.setLabel(getNHPartName());
244
245        if (logger.isInfoEnabled()) {
246            logger.info("CollectionObject Natural History part to be created:");
247            logger.info(objectAsXmlString(conh,
248                CollectionobjectsNaturalhistory.class));
249        }
250
251        // Return the multipart entity body that will be submitted in the
252        // 'create' request, above.
253        return multipart;
254    }
255
256         static Object extractPart(PoxPayloadIn input, String label, Class clazz) {
257                 Object obj = null;
258
259                 PayloadInputPart payloadInputPart = input.getPart(label);
260                 if (payloadInputPart != null) {
261                         obj = payloadInputPart.getBody();
262                 }
263
264                 return obj;
265         }
266
267     public void displayCollectionObject(PoxPayloadIn input)
268         throws Exception {
269
270         if (input == null) {
271             throw new IllegalArgumentException(
272                 "Could not display null CollectionObject record.");
273         }
274
275         // Extract each part of the record, and convert it from
276         // its XML representation to its associated Java object.
277
278         // Read the Common part of the record.
279         CollectionobjectsCommon collectionObject =
280                 (CollectionobjectsCommon) extractPart(input,
281                 client.getCommonPartName(), CollectionobjectsCommon.class);
282
283        if (logger.isInfoEnabled()) {
284            logger.info("CollectionObject Common part read:");
285            logger.info(objectAsXmlString(collectionObject,
286                CollectionobjectsCommon.class));
287        }
288
289        // Read the Natural History part of the record.
290        CollectionobjectsNaturalhistory conh =
291            (CollectionobjectsNaturalhistory) extractPart(input,
292                getNHPartName(), CollectionobjectsNaturalhistory.class);
293
294         if (logger.isInfoEnabled()) {
295            logger.info("CollectionObject Natural History part read:");
296            logger.info(objectAsXmlString(conh,
297                CollectionobjectsNaturalhistory.class));
298        }
299
300     }
301
302
303     private String getCommonPartName() {
304        return client.getCommonPartName();
305     }
306
307     private String getNHPartName() {
308        return "collectionobjects_naturalhistory";
309     }
310
311     private List<String> getAllResourceIds() throws Exception {
312         
313         CollectionobjectsCommonList list = readCollectionObjectList();
314         List<String> resourceIds = new ArrayList();
315         List<CollectionobjectsCommonList.CollectionObjectListItem> items =
316                 list.getCollectionObjectListItem();
317
318         for (CollectionobjectsCommonList.CollectionObjectListItem item : items) {
319             resourceIds.add(item.getCsid());
320         }
321
322         return resourceIds;
323     }
324
325     private String extractId(ClientResponse<Response> res) {
326         MultivaluedMap<String, Object> mvm = res.getMetadata();
327         String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
328         if(logger.isInfoEnabled()){
329                 logger.info("extractId:uri=" + uri);
330         }
331         String[] segments = uri.split("/");
332         String id = segments[segments.length - 1];
333         if(logger.isInfoEnabled()){
334                 logger.info("id=" + id);
335         }
336         return id;
337     }
338
339     private String objectAsXmlString(Object o, Class clazz) {
340         StringWriter sw = new StringWriter();
341         try{
342             JAXBContext jc = JAXBContext.newInstance(clazz);
343             Marshaller m = jc.createMarshaller();
344             m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
345                     Boolean.TRUE);
346             m.marshal(o, sw);
347         }catch(Exception e){
348             e.printStackTrace();
349         }
350         return sw.toString();
351     }
352     
353     public static void main(String[] args) throws Exception {
354
355         Sample sample = new Sample();
356
357         // Optionally first delete all existing collection object records.
358         boolean ENABLE_DELETE_ALL = false;
359         if (ENABLE_DELETE_ALL) {
360             logger.info("Deleting all CollectionObject records ...");
361             sample.deleteAllCollectionObjects();
362         }
363
364         logger.info("Creating a new CollectionObject record ...");
365         String newRecordId = sample.createCollectionObject();
366         
367         if (newRecordId == null || newRecordId.trim().isEmpty()) {
368             logger.error("Could not create new record.");
369             return;
370         }
371
372         logger.info("Reading the new CollectionObject record ...");
373         PoxPayloadIn corecord = sample.readCollectionObject(newRecordId);
374         sample.displayCollectionObject(corecord);
375
376         logger.info("Deleting the new CollectionObject record ...");
377         sample.deleteCollectionObject(newRecordId);
378                 
379     }
380
381 }