]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
897604a456ea0046cf1747cd3d3f16f71093856f
[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 (c)) 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.vocabulary.client.sample;
25
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.HashMap;
29 import java.util.List;
30
31 import javax.ws.rs.core.MediaType;
32 import javax.ws.rs.core.MultivaluedMap;
33 import javax.ws.rs.core.Response;
34
35 import org.apache.log4j.BasicConfigurator;
36 //import org.collectionspace.services.VocabularyItemJAXBSchema; 
37 import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema;
38
39 import org.collectionspace.services.client.PayloadInputPart;
40 import org.collectionspace.services.client.PoxPayloadIn;
41 import org.collectionspace.services.client.PoxPayloadOut;
42 import org.collectionspace.services.client.VocabularyClient;
43 import org.collectionspace.services.client.VocabularyClientUtils;
44 import org.collectionspace.services.client.test.ServiceRequestType;
45 import org.collectionspace.services.vocabulary.VocabulariesCommon;
46 import org.collectionspace.services.vocabulary.VocabulariesCommonList;
47 import org.collectionspace.services.vocabulary.VocabularyitemsCommon;
48 import org.collectionspace.services.vocabulary.VocabularyitemsCommonList;
49 import org.jboss.resteasy.client.ClientResponse;
50 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
51 import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 /**
56  * VocabularyServiceTest, carries out tests against a
57  * deployed and running Vocabulary Service.
58  *
59  * $LastChangedRevision$
60  * $LastChangedDate$
61  */
62 public class Sample {
63     private static final Logger logger =
64         LoggerFactory.getLogger(Sample.class);
65
66     // Instance variables specific to this test.
67     private VocabularyClient client = new VocabularyClient();
68     final String SERVICE_PATH_COMPONENT = "vocabularies";
69     final String ITEM_SERVICE_PATH_COMPONENT = "items";
70
71
72     // ---------------------------------------------------------------
73     // Create
74     // ---------------------------------------------------------------
75
76     public void createEnumeration(String vocabName, List<String> enumValues ) {
77
78         // Expected status code: 201 Created
79         int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
80         // Type of service request being tested
81         ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
82
83         if(logger.isDebugEnabled()){
84                 logger.debug("Import: Create vocabulary: \"" + vocabName +"\"");
85         }
86
87         String displaySuffix = "displayName-" + System.currentTimeMillis(); //TODO: Laramie20100728 temp fix, made-up displaySuffix.
88         String baseVocabRefName = VocabularyClientUtils.createVocabularyRefName(vocabName, displaySuffix);   //TODO: Laramie20100728 temp fix  was vocabName, false
89         String fullVocabRefName = VocabularyClientUtils.createVocabularyRefName(vocabName, displaySuffix);   //TODO: Laramie20100728 temp fix  was vocabName, true
90         PoxPayloadOut multipart = VocabularyClientUtils.createEnumerationInstance(
91                         vocabName, fullVocabRefName, client.getCommonPartName());
92         ClientResponse<Response> res = client.create(multipart);
93
94         int statusCode = res.getStatus();
95
96         if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
97                 throw new RuntimeException("Could not create enumeration: \""+vocabName
98                                 +"\" "+ VocabularyClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
99         }
100         if(statusCode != EXPECTED_STATUS_CODE) {
101                 throw new RuntimeException("Unexpected Status when creating enumeration: \""
102                                 +vocabName +"\", Status:"+ statusCode);
103         }
104
105         // Store the ID returned from this create operation
106         // for additional tests below.
107         String newVocabId = VocabularyClientUtils.extractId(res);
108         if(logger.isDebugEnabled()){
109                 logger.debug("Import: Created vocabulary: \"" + vocabName +"\" ID:"
110                                 +newVocabId );
111         }
112         for(String itemName : enumValues){
113             HashMap<String, String> itemInfo = new HashMap<String, String>();
114             itemInfo.put(AuthorityItemJAXBSchema.DISPLAY_NAME, itemName);
115                 VocabularyClientUtils.createItemInVocabulary(newVocabId, 
116                                 baseVocabRefName, itemInfo, client);
117         }
118     }
119     
120    // ---------------------------------------------------------------
121    // Read
122    // ---------------------------------------------------------------
123
124    private VocabulariesCommonList readVocabularies() {
125
126         // Expected status code: 200 OK
127         int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
128         // Type of service request being tested
129         ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ;
130
131         // Submit the request to the service and store the response.
132         ClientResponse<VocabulariesCommonList> res = client.readList();
133         VocabulariesCommonList list = res.getEntity();
134
135         int statusCode = res.getStatus();
136         if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
137                 throw new RuntimeException("Could not read list of vocabularies: "
138                 + VocabularyClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
139         }
140         if(statusCode != EXPECTED_STATUS_CODE) {
141                 throw new RuntimeException("Unexpected Status when reading " +
142                 "list of vocabularies, Status:"+ statusCode);
143         }
144
145         return list;
146    }
147
148     private List<String> readVocabularyIds(VocabulariesCommonList list) {
149
150         List<String> ids = new ArrayList<String>();
151         List<VocabulariesCommonList.VocabularyListItem> vocabularies =
152             list.getVocabularyListItem();
153         for (VocabulariesCommonList.VocabularyListItem vocabulary : vocabularies) {
154             ids.add(vocabulary.getCsid());
155         }
156         return ids;
157    }
158     
159    private VocabulariesCommon readVocabulary(String vocabId) {
160
161         // Expected status code: 200 OK
162         int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
163         // Type of service request being tested
164         ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ;
165
166         // Submit the request to the service and store the response.
167         VocabulariesCommon vocabulary = null;
168         try {
169             ClientResponse<String> res = client.read(vocabId);
170             int statusCode = res.getStatus();
171             if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
172                 throw new RuntimeException("Could not read vocabulary"
173                     + VocabularyClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
174             }
175             if(statusCode != EXPECTED_STATUS_CODE) {
176                 throw new RuntimeException("Unexpected Status when reading " +
177                     "vocabulary, Status:"+ statusCode);
178             }
179             PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
180             vocabulary = (VocabulariesCommon) extractPart(input,
181                     client.getCommonPartName(), VocabulariesCommon.class);
182         } catch (Exception e) {
183             throw new RuntimeException("Could not read vocabulary: ", e);
184         }
185
186         return vocabulary;
187     }
188
189     private VocabularyitemsCommonList readItemsInVocab(String vocabId) {
190
191         // Expected status code: 200 OK
192         int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
193         // Type of service request being tested
194         ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ;
195
196         // Submit the request to the service and store the response.
197                           //  readItemList(String inAuthority, String partialTerm, String keywords)
198         ClientResponse<VocabularyitemsCommonList> res =  client.readItemList(vocabId, "", ""); //TODO: figure out these params.  I just put in empty string to make it recompile after refactoring.  Laramie20100728
199         VocabularyitemsCommonList list = res.getEntity();
200
201         int statusCode = res.getStatus();
202
203         if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
204                 throw new RuntimeException("Could not read items in vocabulary: "
205                 + VocabularyClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
206         }
207         if(statusCode != EXPECTED_STATUS_CODE) {
208                 throw new RuntimeException("Unexpected Status when reading " +
209                 "items in vocabulary, Status:"+ statusCode);
210         }
211
212         return list;
213     }
214
215     private List<String> readVocabularyItemIds(VocabularyitemsCommonList list) {
216
217         List<String> ids = new ArrayList<String>();
218         List<VocabularyitemsCommonList.VocabularyitemListItem> items =
219             list.getVocabularyitemListItem();
220         for (VocabularyitemsCommonList.VocabularyitemListItem item : items) {
221             ids.add(item.getCsid());
222         }
223         return ids;
224    }
225
226     // ---------------------------------------------------------------
227     // Delete
228     // ---------------------------------------------------------------
229
230     private void deleteVocabulary(String vcsid) {
231          // Expected status code: 200 OK
232         int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
233         // Type of service request being tested
234         ServiceRequestType REQUEST_TYPE = ServiceRequestType.DELETE;
235
236         ClientResponse<Response> res = client.delete(vcsid);
237         int statusCode = res.getStatus();
238
239         if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
240                 throw new RuntimeException("Could not delete vocabulary: "
241                 + VocabularyClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
242         }
243         if(statusCode != EXPECTED_STATUS_CODE) {
244                 throw new RuntimeException("Unexpected Status when deleting " +
245                 "vocabulary, Status:"+ statusCode);
246         }
247     }
248
249     private void deleteAllVocabularies() {
250         List<String> ids = readVocabularyIds(readVocabularies());
251         for (String id : ids) {
252             deleteVocabulary(id);
253         }
254     }
255
256         private void deleteVocabularyItem(String vcsid, String itemcsid) {
257          // Expected status code: 200 OK
258         int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
259         // Type of service request being tested
260         ServiceRequestType REQUEST_TYPE = ServiceRequestType.DELETE;
261
262         ClientResponse<Response> res = client.deleteItem(vcsid, itemcsid);
263         int statusCode = res.getStatus();
264
265         if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
266                 throw new RuntimeException("Could not delete vocabulary item: "
267                 + VocabularyClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
268         }
269         if(statusCode != EXPECTED_STATUS_CODE) {
270                 throw new RuntimeException("Unexpected Status when deleting " +
271                 "vocabulary item, Status:"+ statusCode);
272         }
273     }
274
275     private void deleteAllItemsForVocab(String vocabId) {
276         List<String> itemIds = readVocabularyItemIds(readItemsInVocab(vocabId));
277         for (String itemId : itemIds) {
278             deleteVocabularyItem(vocabId, itemId);
279         }
280     }
281
282     // ---------------------------------------------------------------
283     // Utility methods used by tests above
284     // ---------------------------------------------------------------
285
286     // Retrieve individual fields of vocabulary records.
287
288     private String displayAllVocabularies(VocabulariesCommonList list) {
289         StringBuffer sb = new StringBuffer();
290             List<VocabulariesCommonList.VocabularyListItem> vocabularies =
291                     list.getVocabularyListItem();
292             int i = 0;
293         for (VocabulariesCommonList.VocabularyListItem vocabulary : vocabularies) {
294             sb.append("vocabulary [" + i + "]" + "\n");
295             sb.append(displayVocabularyDetails(vocabulary));
296             i++;
297         }
298         return sb.toString();
299     }
300
301     private String displayVocabularyDetails(
302         VocabulariesCommonList.VocabularyListItem vocabulary) {
303             StringBuffer sb = new StringBuffer();
304             sb.append("displayName=" + vocabulary.getDisplayName() + "\n");
305             sb.append("vocabType=" + vocabulary.getVocabType() + "\n");
306             // sb.append("csid=" + vocabulary.getCsid() + "\n");
307             sb.append("URI=" + vocabulary.getUri() + "\n");
308         return sb.toString();
309     }
310
311     // Retrieve individual fields of vocabulary item records.
312
313     private String displayAllVocabularyItems(VocabularyitemsCommonList list) {
314         StringBuffer sb = new StringBuffer();
315         List<VocabularyitemsCommonList.VocabularyitemListItem> items =
316                 list.getVocabularyitemListItem();
317         int i = 0;
318         for (VocabularyitemsCommonList.VocabularyitemListItem item : items) {
319             sb.append("vocabulary item [" + i + "]" + "\n");
320             sb.append(displayVocabularyItemDetails(item));
321             i++;
322         }
323         return sb.toString();
324     }
325
326     private String displayVocabularyItemDetails(
327         VocabularyitemsCommonList.VocabularyitemListItem item) {
328             StringBuffer sb = new StringBuffer();
329             sb.append("csid=" + item.getCsid() + "\n");
330             sb.append("displayName=" + item.getDisplayName() + "\n");
331             // sb.append("URI=" + item.getUri() + "\n");
332         return sb.toString();
333     }
334
335     // TODO this should be moved to a common utils class
336     private Object extractPart(PoxPayloadIn input, String label,
337         Class clazz) throws Exception {
338         Object obj = null;
339         obj = input.getPart(label);
340         /*
341         for(PayloadInputPart part : input.getParts()){
342             String partLabel = part.getHeaders().getFirst("label");
343             if(label.equalsIgnoreCase(partLabel)){
344                 String partStr = part.getBodyAsString();
345                 if(logger.isDebugEnabled()){
346                     logger.debug("extracted part str=\n" + partStr);
347                 }
348                 obj = part.getBody(clazz, null);
349                 if(logger.isDebugEnabled()){
350                     logger.debug("extracted part obj=\n", obj, clazz);
351                 }
352                 break;
353             }
354         }
355         */
356         return obj;
357     }
358
359         public static void main(String[] args) {
360
361         // Configure logging.
362                 BasicConfigurator.configure();
363
364         logger.info("VocabularyBaseImport starting...");
365
366                 Sample vbi = new Sample();
367         VocabulariesCommonList vocabularies;
368         List<String> vocabIds;
369         String details = "";
370
371         // Optionally delete all vocabularies and vocabulary items.
372
373         boolean ENABLE_DELETE_ALL = false;
374         if (ENABLE_DELETE_ALL) {
375
376             logger.info("Deleting all vocabulary items and vocabularies ...");
377
378             // For each vocabulary ...
379             vocabularies = vbi.readVocabularies();
380             vocabIds = vbi.readVocabularyIds(vocabularies);
381             for (String vocabId : vocabIds) {
382                 logger.info("Deleting all vocabulary items for vocabulary ...");
383                 vbi.deleteAllItemsForVocab(vocabId);
384                 logger.info("Deleting vocabulary ...");
385                 vbi.deleteVocabulary(vocabId);
386             }
387
388             logger.info("Reading vocabularies after deletion ...");
389             vocabularies = vbi.readVocabularies();
390             details = vbi.displayAllVocabularies(vocabularies);
391             logger.info(details);
392
393             logger.info("Reading items in each vocabulary after deletion ...");
394             vocabIds = vbi.readVocabularyIds(vocabularies);
395             for (String vocabId : vocabIds) {
396                 VocabularyitemsCommonList items = vbi.readItemsInVocab(vocabId);
397                 details = vbi.displayAllVocabularyItems(items);
398                 logger.info(details);
399             }
400
401         }
402
403         // Create new vocabularies, each populated with vocabulary items.
404
405                 final String acquisitionMethodsVocabName = "Acquisition Methods";
406                 final String entryMethodsVocabName = "Entry Methods";
407                 final String entryReasonsVocabName = "Entry Reasons";
408                 final String responsibleDeptsVocabName = "Responsible Departments";
409
410                 List<String> acquisitionMethodsEnumValues = 
411                         Arrays.asList("Gift","Purchase","Exchange","Transfer","Treasure");
412                 List<String> entryMethodsEnumValues = 
413                         Arrays.asList("In person","Post","Found on doorstep");
414                 List<String> entryReasonsEnumValues = 
415                         Arrays.asList("Enquiry","Commission","Loan");
416                 List<String> respDeptNamesEnumValues = 
417                         Arrays.asList("Antiquities","Architecture and Design","Decorative Arts",
418                                                                         "Ethnography","Herpetology","Media and Performance Art",
419                                                                         "Paintings and Sculpture","Paleobotany","Photographs",
420                                                                         "Prints and Drawings");
421         
422                 vbi.createEnumeration(acquisitionMethodsVocabName, acquisitionMethodsEnumValues);
423                 vbi.createEnumeration(entryMethodsVocabName, entryMethodsEnumValues);
424                 vbi.createEnumeration(entryReasonsVocabName, entryReasonsEnumValues);
425                 vbi.createEnumeration(responsibleDeptsVocabName, respDeptNamesEnumValues);
426
427                 logger.info("VocabularyBaseImport complete.");
428
429         logger.info("Reading vocabularies and items ...");
430         // Get a list of vocabularies.
431         vocabularies = vbi.readVocabularies();
432         // For each vocabulary ...
433         for (VocabulariesCommonList.VocabularyListItem
434             vocabulary : vocabularies.getVocabularyListItem()) {
435             // Get its display name.
436             logger.info(vocabulary.getDisplayName());
437             // Get a list of the vocabulary items in this vocabulary.
438             VocabularyitemsCommonList items =
439                 vbi.readItemsInVocab(vocabulary.getCsid());
440             // For each vocabulary item ...
441             for (VocabularyitemsCommonList.VocabularyitemListItem
442                 item : items.getVocabularyitemListItem()) {
443                 // Get its display name.
444                 logger.info(" " + item.getDisplayName());
445             }
446         }
447
448         // Sample alternate methods of reading all vocabularies and
449         // vocabulary items separately.
450         boolean RUN_ADDITIONAL_SAMPLES = false;
451         if (RUN_ADDITIONAL_SAMPLES) {
452
453             logger.info("Reading all vocabularies ...");
454             details = vbi.displayAllVocabularies(vocabularies);
455             logger.info(details);
456
457             logger.info("Reading all vocabulary items ...");
458             vocabIds = vbi.readVocabularyIds(vocabularies);
459             for (String vocabId : vocabIds) {
460                 VocabularyitemsCommonList items = vbi.readItemsInVocab(vocabId);
461                 details = vbi.displayAllVocabularyItems(items);
462                 logger.info(details);
463             }
464
465         }
466
467         }
468
469 }