]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
5e52df1d923cb2ecd46c2c90bfb40a70f916fbd1
[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.organization.client.sample;
25
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31
32 import javax.ws.rs.core.MediaType;
33 import javax.ws.rs.core.MultivaluedMap;
34 import javax.ws.rs.core.Response;
35
36 import org.apache.log4j.BasicConfigurator;
37 import org.collectionspace.services.OrganizationJAXBSchema;
38 import org.collectionspace.services.client.OrgAuthorityClient;
39 import org.collectionspace.services.client.OrgAuthorityClientUtils;
40 import org.collectionspace.services.client.PayloadInputPart;
41 import org.collectionspace.services.client.PoxPayloadIn;
42 import org.collectionspace.services.client.PoxPayloadOut;
43 import org.collectionspace.services.client.test.ServiceRequestType;
44 import org.collectionspace.services.organization.OrgauthoritiesCommon;
45 import org.collectionspace.services.organization.OrgauthoritiesCommonList;
46 import org.collectionspace.services.organization.OrganizationsCommon;
47 import org.collectionspace.services.organization.OrganizationsCommonList;
48 import org.jboss.resteasy.client.ClientResponse;
49 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
50 import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 /**
55  * OrgAuthority Sample, carries out tests against a
56  * deployed and running OrgAuthority Service.
57  *
58  * $LastChangedRevision: 1055 $
59  * $LastChangedDate: 2009-12-09 12:25:15 -0800 (Wed, 09 Dec 2009) $
60  */
61 public class Sample {
62     private static final Logger logger =
63         LoggerFactory.getLogger(Sample.class);
64
65     // Instance variables specific to this test.
66     private OrgAuthorityClient client = new OrgAuthorityClient();
67     final String SERVICE_PATH_COMPONENT = "organizations";
68     final String ITEM_SERVICE_PATH_COMPONENT = "items";
69
70
71     // ---------------------------------------------------------------
72     // Create
73     // ---------------------------------------------------------------
74     protected String createOrgAuthRefName(String orgAuthorityName) {
75         return "urn:cspace:org.collectionspace.demo:orgauthority:name("
76                         +orgAuthorityName+")";
77     }
78
79     protected String createOrganizationRefName(
80                                                 String orgAuthRefName, String orgName) {
81         return orgAuthRefName+":organization:name("+orgName+")";
82     }
83
84     
85
86     public void createOrgAuthority(String orgAuthName, List<Map<String,String>> orgInfos ) {
87
88         // Expected status code: 201 Created
89         int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
90         // Type of service request being tested
91         ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
92
93         logger.info("Import: Create orgAuthority: \"" + orgAuthName +"\"");
94         String baseOrgAuthRefName = createOrgAuthRefName(orgAuthName);
95         String fullOrgAuthRefName = baseOrgAuthRefName+"'"+orgAuthName+"'";
96         PoxPayloadOut multipart = 
97                 OrgAuthorityClientUtils.createOrgAuthorityInstance(
98                                 orgAuthName, fullOrgAuthRefName, 
99                                 client.getCommonPartName());
100         ClientResponse<Response> res = client.create(multipart);
101
102         int statusCode = res.getStatus();
103
104         if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
105                 throw new RuntimeException("Could not create enumeration: \""+orgAuthName
106                                 +"\" "+ OrgAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
107         }
108         if(statusCode != EXPECTED_STATUS_CODE) {
109                 throw new RuntimeException("Unexpected Status when creating enumeration: \""
110                                 +orgAuthName +"\", Status:"+ statusCode);
111         }
112
113         // Store the ID returned from this create operation
114         // for additional tests below.
115         String newOrgAuthId = OrgAuthorityClientUtils.extractId(res);
116         logger.info("Import: Created orgAuthority: \"" + orgAuthName +"\" ID:"
117                                 +newOrgAuthId );
118         
119         // Add items to the orgAuthority
120         for(Map<String,String> orgInfo : orgInfos){
121                 createItemInOrgAuth(newOrgAuthId, baseOrgAuthRefName, orgInfo);
122         }
123         
124     }
125     
126     private String createItemInOrgAuth(String vcsid, 
127                 String orgAuthorityRefName, Map<String,String> orgInfo) {
128         // Expected status code: 201 Created
129         int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
130         // Type of service request being tested
131         ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
132         String shortName = orgInfo.get(OrganizationJAXBSchema.SHORT_NAME);
133         String refName = createOrganizationRefName(
134                                                 orgAuthorityRefName, shortName)+"'"+shortName+"'";
135
136
137         logger.info("Import: Create Item: \""+shortName+
138                         "\" in orgAuthority: \"" + orgAuthorityRefName +"\"");
139         PoxPayloadOut multipart = 
140                 OrgAuthorityClientUtils.createOrganizationInstance(refName, orgInfo, client.getItemCommonPartName() );
141
142         ClientResponse<Response> res = client.createItem(vcsid, multipart);
143
144         int statusCode = res.getStatus();
145
146         if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
147                 throw new RuntimeException("Could not create Item: \""+shortName
148                                 +"\" in orgAuthority: \"" + orgAuthorityRefName
149                                 +"\" "+ OrgAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
150         }
151         if(statusCode != EXPECTED_STATUS_CODE) {
152                 throw new RuntimeException("Unexpected Status when creating Item: \""+shortName
153                                 +"\" in orgAuthority: \"" + orgAuthorityRefName +
154                                 "\", Status:"+ statusCode);
155         }
156
157         return OrgAuthorityClientUtils.extractId(res);
158     }
159
160
161    // ---------------------------------------------------------------
162    // Read
163    // ---------------------------------------------------------------
164
165    private OrgauthoritiesCommonList readOrgAuthorities() {
166
167         // Expected status code: 200 OK
168         int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
169         // Type of service request being tested
170         ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ;
171
172         // Submit the request to the service and store the response.
173         ClientResponse<OrgauthoritiesCommonList> res = client.readList();
174         OrgauthoritiesCommonList list = res.getEntity();
175
176         int statusCode = res.getStatus();
177         if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
178                 throw new RuntimeException("Could not read list of orgAuthorities: "
179                 + OrgAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
180         }
181         if(statusCode != EXPECTED_STATUS_CODE) {
182                 throw new RuntimeException("Unexpected Status when reading " +
183                 "list of orgAuthorities, Status:"+ statusCode);
184         }
185
186         return list;
187    }
188
189     private List<String> readOrgAuthorityIds(OrgauthoritiesCommonList list) {
190
191         List<String> ids = new ArrayList<String>();
192         List<OrgauthoritiesCommonList.OrgauthorityListItem> orgAuthorities =
193             list.getOrgauthorityListItem();
194         for (OrgauthoritiesCommonList.OrgauthorityListItem orgAuthority : orgAuthorities) {
195             ids.add(orgAuthority.getCsid());
196         }
197         return ids;
198    }
199     
200    private OrgauthoritiesCommon readOrgAuthority(String orgAuthId) {
201
202         // Expected status code: 200 OK
203         int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
204         // Type of service request being tested
205         ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ;
206
207         // Submit the request to the service and store the response.
208         OrgauthoritiesCommon orgAuthority = null;
209         try {
210             ClientResponse<String> res = client.read(orgAuthId);
211             int statusCode = res.getStatus();
212             if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
213                 throw new RuntimeException("Could not read orgAuthority"
214                     + OrgAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
215             }
216             if(statusCode != EXPECTED_STATUS_CODE) {
217                 throw new RuntimeException("Unexpected Status when reading " +
218                     "orgAuthority, Status:"+ statusCode);
219             }
220             PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
221             PayloadInputPart orgAuthorityPart = input.getPart(client.getCommonPartName());
222             orgAuthority = (OrgauthoritiesCommon) orgAuthorityPart.getBody();
223         } catch (Exception e) {
224             throw new RuntimeException("Could not read orgAuthority: ", e);
225         }
226
227         return orgAuthority;
228     }
229
230     private OrganizationsCommonList readItemsInOrgAuth(String orgAuthId) {
231
232         // Expected status code: 200 OK
233         int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
234         // Type of service request being tested
235         ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ;
236
237         // Submit the request to the service and store the response.
238
239         //was: ClientResponse<OrganizationsCommonList> res = client.readItemList(orgAuthId);
240         //new API: readItemList(String inAuthority, String partialTerm, String keywords)
241         ClientResponse<OrganizationsCommonList> res = client.readItemList(orgAuthId, "", "");//TODO:   .New call, most certainly wrong.  Just trying to get this to compile. Laramie20100728
242
243         OrganizationsCommonList list = res.getEntity();
244
245         int statusCode = res.getStatus();
246
247         if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
248                 throw new RuntimeException("Could not read items in orgAuthority: "
249                 + OrgAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
250         }
251         if(statusCode != EXPECTED_STATUS_CODE) {
252                 throw new RuntimeException("Unexpected Status when reading " +
253                 "items in orgAuthority, Status:"+ statusCode);
254         }
255
256         return list;
257     }
258
259     private List<String> readOrganizationIds(OrganizationsCommonList list) {
260
261         List<String> ids = new ArrayList<String>();
262         List<OrganizationsCommonList.OrganizationListItem> items =
263             list.getOrganizationListItem();
264         for (OrganizationsCommonList.OrganizationListItem item : items) {
265             ids.add(item.getCsid());
266         }
267         return ids;
268    }
269
270     // ---------------------------------------------------------------
271     // Delete
272     // ---------------------------------------------------------------
273
274     private void deleteOrgAuthority(String vcsid) {
275          // Expected status code: 200 OK
276         int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
277         // Type of service request being tested
278         ServiceRequestType REQUEST_TYPE = ServiceRequestType.DELETE;
279
280         ClientResponse<Response> res = client.delete(vcsid);
281         int statusCode = res.getStatus();
282
283         if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
284                 throw new RuntimeException("Could not delete orgAuthority: "
285                 + OrgAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
286         }
287         if(statusCode != EXPECTED_STATUS_CODE) {
288                 throw new RuntimeException("Unexpected Status when deleting " +
289                 "orgAuthority, Status:"+ statusCode);
290         }
291     }
292
293     private void deleteAllOrgAuthorities() {
294         List<String> ids = readOrgAuthorityIds(readOrgAuthorities());
295         for (String id : ids) {
296             deleteOrgAuthority(id);
297         }
298     }
299
300         private void deleteOrganization(String vcsid, String itemcsid) {
301          // Expected status code: 200 OK
302         int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
303         // Type of service request being tested
304         ServiceRequestType REQUEST_TYPE = ServiceRequestType.DELETE;
305
306         ClientResponse<Response> res = client.deleteItem(vcsid, itemcsid);
307         int statusCode = res.getStatus();
308
309         if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
310                 throw new RuntimeException("Could not delete orgAuthority item: "
311                 + OrgAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
312         }
313         if(statusCode != EXPECTED_STATUS_CODE) {
314                 throw new RuntimeException("Unexpected Status when deleting " +
315                 "orgAuthority item, Status:"+ statusCode);
316         }
317     }
318
319     private void deleteAllItemsForOrgAuth(String orgAuthId) {
320         List<String> itemIds = readOrganizationIds(readItemsInOrgAuth(orgAuthId));
321         for (String itemId : itemIds) {
322             deleteOrganization(orgAuthId, itemId);
323         }
324     }
325
326     // ---------------------------------------------------------------
327     // Utility methods used by tests above
328     // ---------------------------------------------------------------
329
330
331     // Retrieve individual fields of orgAuthority records.
332
333     private String displayAllOrgAuthorities(OrgauthoritiesCommonList list) {
334         StringBuffer sb = new StringBuffer();
335             List<OrgauthoritiesCommonList.OrgauthorityListItem> orgAuthorities =
336                     list.getOrgauthorityListItem();
337             int i = 0;
338         for (OrgauthoritiesCommonList.OrgauthorityListItem orgAuthority : orgAuthorities) {
339             sb.append("orgAuthority [" + i + "]" + "\n");
340             sb.append(displayOrgAuthorityDetails(orgAuthority));
341             i++;
342         }
343         return sb.toString();
344     }
345
346     private String displayOrgAuthorityDetails(
347         OrgauthoritiesCommonList.OrgauthorityListItem orgAuthority) {
348             StringBuffer sb = new StringBuffer();
349             sb.append("displayName=" + orgAuthority.getDisplayName() + "\n");
350             sb.append("vocabType=" + orgAuthority.getVocabType() + "\n");
351             // sb.append("csid=" + orgAuthority.getCsid() + "\n");
352             sb.append("URI=" + orgAuthority.getUri() + "\n");
353         return sb.toString();
354     }
355
356     // Retrieve individual fields of organization records.
357
358     private String displayAllOrganizations(OrganizationsCommonList list) {
359         StringBuffer sb = new StringBuffer();
360         List<OrganizationsCommonList.OrganizationListItem> items =
361                 list.getOrganizationListItem();
362         int i = 0;
363         for (OrganizationsCommonList.OrganizationListItem item : items) {
364             sb.append("organization [" + i + "]" + "\n");
365             sb.append(displayOrganizationDetails(item));
366             i++;
367         }
368         return sb.toString();
369     }
370
371     private String displayOrganizationDetails(
372         OrganizationsCommonList.OrganizationListItem item) {
373             StringBuffer sb = new StringBuffer();
374             sb.append("csid=" + item.getCsid() + "\n");
375             sb.append("displayName=" + item.getDisplayName() + "\n");
376             // sb.append("URI=" + item.getUri() + "\n");
377         return sb.toString();
378     }
379
380 //    private Object extractPart(PoxPayloadIn input, String label,
381 //        Class clazz) throws Exception {
382 //        Object obj = null;
383 //        for(PayloadInputPart part : input.getParts()){
384 //            String partLabel = part.getHeaders().getFirst("label");
385 //            if(label.equalsIgnoreCase(partLabel)){
386 //                String partStr = part.getBodyAsString();
387 //                if(logger.isDebugEnabled()){
388 //                    logger.debug("extracted part str=\n" + partStr);
389 //                }
390 //                obj = part.getBody(clazz, null);
391 //                if(logger.isDebugEnabled()){
392 //                    logger.debug("extracted part obj=\n", obj, clazz);
393 //                }
394 //                break;
395 //            }
396 //        }
397 //        return obj;
398 //    }
399
400         public static void main(String[] args) {
401
402         // Configure logging.
403                 BasicConfigurator.configure();
404
405         logger.info("OrgAuthority Sample starting...");
406
407                 Sample sample = new Sample();
408         OrgauthoritiesCommonList orgAuthorities;
409         List<String> orgAuthIds;
410         String details = "";
411
412         // Optionally delete all orgAuthorities and organizations.
413
414         boolean ENABLE_DELETE_ALL = false;
415         if (ENABLE_DELETE_ALL) {
416
417             logger.info("Deleting all organizations and orgAuthorities ...");
418
419             // For each orgAuthority ...
420             orgAuthorities = sample.readOrgAuthorities();
421             orgAuthIds = sample.readOrgAuthorityIds(orgAuthorities);
422             for (String orgAuthId : orgAuthIds) {
423                 logger.info("Deleting all organizations for orgAuthority ...");
424                 sample.deleteAllItemsForOrgAuth(orgAuthId);
425                 logger.info("Deleting orgAuthority ...");
426                 sample.deleteOrgAuthority(orgAuthId);
427             }
428
429             logger.info("Reading orgAuthorities after deletion ...");
430             orgAuthorities = sample.readOrgAuthorities();
431             details = sample.displayAllOrgAuthorities(orgAuthorities);
432             logger.info(details);
433
434             logger.info("Reading items in each orgAuthority after deletion ...");
435             orgAuthIds = sample.readOrgAuthorityIds(orgAuthorities);
436             for (String orgAuthId : orgAuthIds) {
437                 OrganizationsCommonList items = sample.readItemsInOrgAuth(orgAuthId);
438                 details = sample.displayAllOrganizations(items);
439                 logger.info(details);
440             }
441
442         }
443
444         // Create new authorities, each populated with organizations.
445         Map<String, String> mmiOrgMap = new HashMap<String,String>();
446         mmiOrgMap.put(OrganizationJAXBSchema.SHORT_NAME, "MMI");
447         mmiOrgMap.put(OrganizationJAXBSchema.LONG_NAME, "Museum of the Moving Image");
448         //mmiOrgMap.put(OrganizationJAXBSchema.CONTACT_NAME, "Megan Forbes");
449         mmiOrgMap.put(OrganizationJAXBSchema.FOUNDING_DATE, "1984");
450         mmiOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "Astoria, NY");
451         Map<String, String> pahmaOrgMap = new HashMap<String,String>();
452         pahmaOrgMap.put(OrganizationJAXBSchema.SHORT_NAME, "PAHMA");
453         pahmaOrgMap.put(OrganizationJAXBSchema.LONG_NAME, "Phoebe A. Hearst Museum of Anthropology");
454         pahmaOrgMap.put(OrganizationJAXBSchema.NAME_ADDITIONS, "University of California, Berkeley");
455         //pahmaOrgMap.put(OrganizationJAXBSchema.CONTACT_NAME, "Michael Black");
456         pahmaOrgMap.put(OrganizationJAXBSchema.FOUNDING_DATE, "1901");
457         pahmaOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "Berkeley, CA");
458         Map<String, String> savoyOrgMap = new HashMap<String,String>();
459         savoyOrgMap.put(OrganizationJAXBSchema.SHORT_NAME, "Savoy Theatre");
460         savoyOrgMap.put(OrganizationJAXBSchema.FOUNDING_DATE, "1900");
461         savoyOrgMap.put(OrganizationJAXBSchema.DISSOLUTION_DATE, "1952");
462         savoyOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "New York, NY");
463         List<Map<String, String>> orgMaps = 
464                 Arrays.asList(mmiOrgMap, pahmaOrgMap, savoyOrgMap );
465         
466                 sample.createOrgAuthority("Sample Org Authority", orgMaps);
467
468                 logger.info("OrgAuthority Sample complete.");
469
470         logger.info("Reading orgAuthorities and items ...");
471         // Get a list of orgAuthorities.
472         orgAuthorities = sample.readOrgAuthorities();
473         // For each orgAuthority ...
474         for (OrgauthoritiesCommonList.OrgauthorityListItem
475             orgAuthority : orgAuthorities.getOrgauthorityListItem()) {
476             // Get its display name.
477             logger.info(orgAuthority.getDisplayName());
478             // Get a list of the organizations in this orgAuthority.
479             OrganizationsCommonList items =
480                 sample.readItemsInOrgAuth(orgAuthority.getCsid());
481             // For each organization ...
482             for (OrganizationsCommonList.OrganizationListItem
483                 item : items.getOrganizationListItem()) {
484                 // Get its display name.
485                 logger.info(" " + item.getDisplayName());
486             }
487         }
488
489         // Sample alternate methods of reading all orgAuthorities and
490         // organizations separately.
491         boolean RUN_ADDITIONAL_SAMPLES = false;
492         if (RUN_ADDITIONAL_SAMPLES) {
493
494             logger.info("Reading all orgAuthorities ...");
495             details = sample.displayAllOrgAuthorities(orgAuthorities);
496             logger.info(details);
497
498             logger.info("Reading all organizations ...");
499             orgAuthIds = sample.readOrgAuthorityIds(orgAuthorities);
500             for (String orgAuthId : orgAuthIds) {
501                 OrganizationsCommonList items = sample.readItemsInOrgAuth(orgAuthId);
502                 details = sample.displayAllOrganizations(items);
503                 logger.info(details);
504             }
505
506         }
507
508         }
509
510 }