2 * This document is a part of the source code and related artifacts
\r
3 * for CollectionSpace, an open source collections management system
\r
4 * for museums and related institutions:
\r
6 * http://www.collectionspace.org
\r
7 * http://wiki.collectionspace.org
\r
9 * Copyright (c)) 2009 Regents of the University of California
\r
11 * Licensed under the Educational Community License (ECL), Version 2.0.
\r
12 * You may not use this file except in compliance with this License.
\r
14 * You may obtain a copy of the ECL 2.0 License at
\r
15 * https://source.collectionspace.org/collection-space/LICENSE.txt
\r
17 * Unless required by applicable law or agreed to in writing, software
\r
18 * distributed under the License is distributed on an "AS IS" BASIS,
\r
19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
20 * See the License for the specific language governing permissions and
\r
21 * limitations under the License.
\r
24 package org.collectionspace.services.organization.client.sample;
\r
26 import java.util.ArrayList;
\r
27 import java.util.Arrays;
\r
28 import java.util.HashMap;
\r
29 import java.util.List;
\r
30 import java.util.Map;
\r
32 import javax.ws.rs.core.MediaType;
\r
33 import javax.ws.rs.core.MultivaluedMap;
\r
34 import javax.ws.rs.core.Response;
\r
36 import org.apache.log4j.BasicConfigurator;
\r
37 import org.collectionspace.services.OrganizationJAXBSchema;
\r
38 import org.collectionspace.services.client.OrgAuthorityClient;
\r
39 import org.collectionspace.services.client.OrgAuthorityClientUtils;
\r
40 import org.collectionspace.services.client.test.ServiceRequestType;
\r
41 import org.collectionspace.services.organization.OrgauthoritiesCommon;
\r
42 import org.collectionspace.services.organization.OrgauthoritiesCommonList;
\r
43 import org.collectionspace.services.organization.OrganizationsCommon;
\r
44 import org.collectionspace.services.organization.OrganizationsCommonList;
\r
45 import org.jboss.resteasy.client.ClientResponse;
\r
46 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
\r
47 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
\r
48 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
\r
49 import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
\r
50 import org.slf4j.Logger;
\r
51 import org.slf4j.LoggerFactory;
\r
54 * OrgAuthority Sample, carries out tests against a
\r
55 * deployed and running OrgAuthority Service.
\r
57 * $LastChangedRevision: 1055 $
\r
58 * $LastChangedDate: 2009-12-09 12:25:15 -0800 (Wed, 09 Dec 2009) $
\r
60 public class Sample {
\r
61 private static final Logger logger =
\r
62 LoggerFactory.getLogger(Sample.class);
\r
64 // Instance variables specific to this test.
\r
65 private OrgAuthorityClient client = new OrgAuthorityClient();
\r
66 final String SERVICE_PATH_COMPONENT = "organizations";
\r
67 final String ITEM_SERVICE_PATH_COMPONENT = "items";
\r
70 // ---------------------------------------------------------------
\r
72 // ---------------------------------------------------------------
\r
73 protected String createOrgAuthRefName(String orgAuthorityName) {
\r
74 return "urn:cspace:org.collectionspace.demo:orgauthority:name("
\r
75 +orgAuthorityName+")";
\r
78 protected String createOrganizationRefName(
\r
79 String orgAuthRefName, String orgName) {
\r
80 return orgAuthRefName+":organization:name("+orgName+")";
\r
85 public void createOrgAuthority(String orgAuthName, List<Map<String,String>> orgInfos ) {
\r
87 // Expected status code: 201 Created
\r
88 int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
\r
89 // Type of service request being tested
\r
90 ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
\r
92 logger.info("Import: Create orgAuthority: \"" + orgAuthName +"\"");
\r
93 String baseOrgAuthRefName = createOrgAuthRefName(orgAuthName);
\r
94 String fullOrgAuthRefName = baseOrgAuthRefName+"'"+orgAuthName+"'";
\r
95 MultipartOutput multipart =
\r
96 OrgAuthorityClientUtils.createOrgAuthorityInstance(
\r
97 orgAuthName, fullOrgAuthRefName,
\r
98 client.getCommonPartName());
\r
99 ClientResponse<Response> res = client.create(multipart);
\r
101 int statusCode = res.getStatus();
\r
103 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
\r
104 throw new RuntimeException("Could not create enumeration: \""+orgAuthName
\r
105 +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
\r
107 if(statusCode != EXPECTED_STATUS_CODE) {
\r
108 throw new RuntimeException("Unexpected Status when creating enumeration: \""
\r
109 +orgAuthName +"\", Status:"+ statusCode);
\r
112 // Store the ID returned from this create operation
\r
113 // for additional tests below.
\r
114 String newOrgAuthId = extractId(res);
\r
115 logger.info("Import: Created orgAuthority: \"" + orgAuthName +"\" ID:"
\r
118 // Add items to the orgAuthority
\r
119 for(Map<String,String> orgInfo : orgInfos){
\r
120 createItemInOrgAuth(newOrgAuthId, baseOrgAuthRefName, orgInfo);
\r
125 private String createItemInOrgAuth(String vcsid,
\r
126 String orgAuthorityRefName, Map<String,String> orgInfo) {
\r
127 // Expected status code: 201 Created
\r
128 int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
\r
129 // Type of service request being tested
\r
130 ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
\r
131 String shortName = orgInfo.get(OrganizationJAXBSchema.SHORT_NAME);
\r
132 String refName = createOrganizationRefName(
\r
133 orgAuthorityRefName, shortName)+"'"+shortName+"'";
\r
136 logger.info("Import: Create Item: \""+shortName+
\r
137 "\" in orgAuthority: \"" + orgAuthorityRefName +"\"");
\r
138 MultipartOutput multipart =
\r
139 OrgAuthorityClientUtils.createOrganizationInstance( vcsid,
\r
140 refName, orgInfo, client.getItemCommonPartName() );
\r
142 ClientResponse<Response> res = client.createItem(vcsid, multipart);
\r
144 int statusCode = res.getStatus();
\r
146 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
\r
147 throw new RuntimeException("Could not create Item: \""+shortName
\r
148 +"\" in orgAuthority: \"" + orgAuthorityRefName
\r
149 +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
\r
151 if(statusCode != EXPECTED_STATUS_CODE) {
\r
152 throw new RuntimeException("Unexpected Status when creating Item: \""+shortName
\r
153 +"\" in orgAuthority: \"" + orgAuthorityRefName +
\r
154 "\", Status:"+ statusCode);
\r
157 return extractId(res);
\r
161 // ---------------------------------------------------------------
\r
163 // ---------------------------------------------------------------
\r
165 private OrgauthoritiesCommonList readOrgAuthorities() {
\r
167 // Expected status code: 200 OK
\r
168 int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
\r
169 // Type of service request being tested
\r
170 ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ;
\r
172 // Submit the request to the service and store the response.
\r
173 ClientResponse<OrgauthoritiesCommonList> res = client.readList();
\r
174 OrgauthoritiesCommonList list = res.getEntity();
\r
176 int statusCode = res.getStatus();
\r
177 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
\r
178 throw new RuntimeException("Could not read list of orgAuthorities: "
\r
179 + invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
\r
181 if(statusCode != EXPECTED_STATUS_CODE) {
\r
182 throw new RuntimeException("Unexpected Status when reading " +
\r
183 "list of orgAuthorities, Status:"+ statusCode);
\r
189 private List<String> readOrgAuthorityIds(OrgauthoritiesCommonList list) {
\r
191 List<String> ids = new ArrayList<String>();
\r
192 List<OrgauthoritiesCommonList.OrgauthorityListItem> orgAuthorities =
\r
193 list.getOrgauthorityListItem();
\r
194 for (OrgauthoritiesCommonList.OrgauthorityListItem orgAuthority : orgAuthorities) {
\r
195 ids.add(orgAuthority.getCsid());
\r
200 private OrgauthoritiesCommon readOrgAuthority(String orgAuthId) {
\r
202 // Expected status code: 200 OK
\r
203 int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
\r
204 // Type of service request being tested
\r
205 ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ;
\r
207 // Submit the request to the service and store the response.
\r
208 OrgauthoritiesCommon orgAuthority = null;
\r
210 ClientResponse<MultipartInput> res = client.read(orgAuthId);
\r
211 int statusCode = res.getStatus();
\r
212 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
\r
213 throw new RuntimeException("Could not read orgAuthority"
\r
214 + invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
\r
216 if(statusCode != EXPECTED_STATUS_CODE) {
\r
217 throw new RuntimeException("Unexpected Status when reading " +
\r
218 "orgAuthority, Status:"+ statusCode);
\r
220 MultipartInput input = (MultipartInput) res.getEntity();
\r
221 orgAuthority = (OrgauthoritiesCommon) extractPart(input,
\r
222 client.getCommonPartName(), OrgauthoritiesCommon.class);
\r
223 } catch (Exception e) {
\r
224 throw new RuntimeException("Could not read orgAuthority: ", e);
\r
227 return orgAuthority;
\r
230 private OrganizationsCommonList readItemsInOrgAuth(String orgAuthId) {
\r
232 // Expected status code: 200 OK
\r
233 int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
\r
234 // Type of service request being tested
\r
235 ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ;
\r
237 // Submit the request to the service and store the response.
\r
238 ClientResponse<OrganizationsCommonList> res =
\r
239 client.readItemList(orgAuthId);
\r
240 OrganizationsCommonList list = res.getEntity();
\r
242 int statusCode = res.getStatus();
\r
244 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
\r
245 throw new RuntimeException("Could not read items in orgAuthority: "
\r
246 + invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
\r
248 if(statusCode != EXPECTED_STATUS_CODE) {
\r
249 throw new RuntimeException("Unexpected Status when reading " +
\r
250 "items in orgAuthority, Status:"+ statusCode);
\r
256 private List<String> readOrganizationIds(OrganizationsCommonList list) {
\r
258 List<String> ids = new ArrayList<String>();
\r
259 List<OrganizationsCommonList.OrganizationListItem> items =
\r
260 list.getOrganizationListItem();
\r
261 for (OrganizationsCommonList.OrganizationListItem item : items) {
\r
262 ids.add(item.getCsid());
\r
267 // ---------------------------------------------------------------
\r
269 // ---------------------------------------------------------------
\r
271 private void deleteOrgAuthority(String vcsid) {
\r
272 // Expected status code: 200 OK
\r
273 int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
\r
274 // Type of service request being tested
\r
275 ServiceRequestType REQUEST_TYPE = ServiceRequestType.DELETE;
\r
277 ClientResponse<Response> res = client.delete(vcsid);
\r
278 int statusCode = res.getStatus();
\r
280 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
\r
281 throw new RuntimeException("Could not delete orgAuthority: "
\r
282 + invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
\r
284 if(statusCode != EXPECTED_STATUS_CODE) {
\r
285 throw new RuntimeException("Unexpected Status when deleting " +
\r
286 "orgAuthority, Status:"+ statusCode);
\r
290 private void deleteAllOrgAuthorities() {
\r
291 List<String> ids = readOrgAuthorityIds(readOrgAuthorities());
\r
292 for (String id : ids) {
\r
293 deleteOrgAuthority(id);
\r
297 private void deleteOrganization(String vcsid, String itemcsid) {
\r
298 // Expected status code: 200 OK
\r
299 int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
\r
300 // Type of service request being tested
\r
301 ServiceRequestType REQUEST_TYPE = ServiceRequestType.DELETE;
\r
303 ClientResponse<Response> res = client.deleteItem(vcsid, itemcsid);
\r
304 int statusCode = res.getStatus();
\r
306 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
\r
307 throw new RuntimeException("Could not delete orgAuthority item: "
\r
308 + invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
\r
310 if(statusCode != EXPECTED_STATUS_CODE) {
\r
311 throw new RuntimeException("Unexpected Status when deleting " +
\r
312 "orgAuthority item, Status:"+ statusCode);
\r
316 private void deleteAllItemsForOrgAuth(String orgAuthId) {
\r
317 List<String> itemIds = readOrganizationIds(readItemsInOrgAuth(orgAuthId));
\r
318 for (String itemId : itemIds) {
\r
319 deleteOrganization(orgAuthId, itemId);
\r
323 // ---------------------------------------------------------------
\r
324 // Utility methods used by tests above
\r
325 // ---------------------------------------------------------------
\r
328 // Retrieve individual fields of orgAuthority records.
\r
330 private String displayAllOrgAuthorities(OrgauthoritiesCommonList list) {
\r
331 StringBuffer sb = new StringBuffer();
\r
332 List<OrgauthoritiesCommonList.OrgauthorityListItem> orgAuthorities =
\r
333 list.getOrgauthorityListItem();
\r
335 for (OrgauthoritiesCommonList.OrgauthorityListItem orgAuthority : orgAuthorities) {
\r
336 sb.append("orgAuthority [" + i + "]" + "\n");
\r
337 sb.append(displayOrgAuthorityDetails(orgAuthority));
\r
340 return sb.toString();
\r
343 private String displayOrgAuthorityDetails(
\r
344 OrgauthoritiesCommonList.OrgauthorityListItem orgAuthority) {
\r
345 StringBuffer sb = new StringBuffer();
\r
346 sb.append("displayName=" + orgAuthority.getDisplayName() + "\n");
\r
347 sb.append("vocabType=" + orgAuthority.getVocabType() + "\n");
\r
348 // sb.append("csid=" + orgAuthority.getCsid() + "\n");
\r
349 sb.append("URI=" + orgAuthority.getUri() + "\n");
\r
350 return sb.toString();
\r
353 // Retrieve individual fields of organization records.
\r
355 private String displayAllOrganizations(OrganizationsCommonList list) {
\r
356 StringBuffer sb = new StringBuffer();
\r
357 List<OrganizationsCommonList.OrganizationListItem> items =
\r
358 list.getOrganizationListItem();
\r
360 for (OrganizationsCommonList.OrganizationListItem item : items) {
\r
361 sb.append("organization [" + i + "]" + "\n");
\r
362 sb.append(displayOrganizationDetails(item));
\r
365 return sb.toString();
\r
368 private String displayOrganizationDetails(
\r
369 OrganizationsCommonList.OrganizationListItem item) {
\r
370 StringBuffer sb = new StringBuffer();
\r
371 sb.append("csid=" + item.getCsid() + "\n");
\r
372 sb.append("displayName=" + item.getDisplayName() + "\n");
\r
373 // sb.append("URI=" + item.getUri() + "\n");
\r
374 return sb.toString();
\r
377 private Object extractPart(MultipartInput input, String label,
\r
378 Class clazz) throws Exception {
\r
380 for(InputPart part : input.getParts()){
\r
381 String partLabel = part.getHeaders().getFirst("label");
\r
382 if(label.equalsIgnoreCase(partLabel)){
\r
383 String partStr = part.getBodyAsString();
\r
384 if(logger.isDebugEnabled()){
\r
385 logger.debug("extracted part str=\n" + partStr);
\r
387 obj = part.getBody(clazz, null);
\r
388 if(logger.isDebugEnabled()){
\r
389 logger.debug("extracted part obj=\n", obj, clazz);
\r
398 * Returns an error message indicating that the status code returned by a
\r
399 * specific call to a service does not fall within a set of valid status
\r
400 * codes for that service.
\r
402 * @param serviceRequestType A type of service request (e.g. CREATE, DELETE).
\r
404 * @param statusCode The invalid status code that was returned in the response,
\r
405 * from submitting that type of request to the service.
\r
407 * @return An error message.
\r
409 protected String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
\r
410 return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
\r
411 requestType.validStatusCodesAsString();
\r
414 protected String extractId(ClientResponse<Response> res) {
\r
415 MultivaluedMap<String, Object> mvm = res.getMetadata();
\r
416 String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
\r
417 if(logger.isDebugEnabled()){
\r
418 logger.info("extractId:uri=" + uri);
\r
420 String[] segments = uri.split("/");
\r
421 String id = segments[segments.length - 1];
\r
422 if(logger.isDebugEnabled()){
\r
423 logger.debug("id=" + id);
\r
428 protected String createRefName(String displayName) {
\r
429 return displayName.replaceAll("\\W", "");
\r
432 public static void main(String[] args) {
\r
434 // Configure logging.
\r
435 BasicConfigurator.configure();
\r
437 logger.info("OrgAuthority Sample starting...");
\r
439 Sample sample = new Sample();
\r
440 OrgauthoritiesCommonList orgAuthorities;
\r
441 List<String> orgAuthIds;
\r
442 String details = "";
\r
444 // Optionally delete all orgAuthorities and organizations.
\r
446 boolean ENABLE_DELETE_ALL = false;
\r
447 if (ENABLE_DELETE_ALL) {
\r
449 logger.info("Deleting all organizations and orgAuthorities ...");
\r
451 // For each orgAuthority ...
\r
452 orgAuthorities = sample.readOrgAuthorities();
\r
453 orgAuthIds = sample.readOrgAuthorityIds(orgAuthorities);
\r
454 for (String orgAuthId : orgAuthIds) {
\r
455 logger.info("Deleting all organizations for orgAuthority ...");
\r
456 sample.deleteAllItemsForOrgAuth(orgAuthId);
\r
457 logger.info("Deleting orgAuthority ...");
\r
458 sample.deleteOrgAuthority(orgAuthId);
\r
461 logger.info("Reading orgAuthorities after deletion ...");
\r
462 orgAuthorities = sample.readOrgAuthorities();
\r
463 details = sample.displayAllOrgAuthorities(orgAuthorities);
\r
464 logger.info(details);
\r
466 logger.info("Reading items in each orgAuthority after deletion ...");
\r
467 orgAuthIds = sample.readOrgAuthorityIds(orgAuthorities);
\r
468 for (String orgAuthId : orgAuthIds) {
\r
469 OrganizationsCommonList items = sample.readItemsInOrgAuth(orgAuthId);
\r
470 details = sample.displayAllOrganizations(items);
\r
471 logger.info(details);
\r
476 // Create new authorities, each populated with organizations.
\r
477 Map<String, String> mmiOrgMap = new HashMap<String,String>();
\r
478 mmiOrgMap.put(OrganizationJAXBSchema.SHORT_NAME, "MMI");
\r
479 mmiOrgMap.put(OrganizationJAXBSchema.LONG_NAME, "Museum of the Moving Image");
\r
480 mmiOrgMap.put(OrganizationJAXBSchema.CONTACT_NAME, "Megan Forbes");
\r
481 mmiOrgMap.put(OrganizationJAXBSchema.FOUNDING_DATE, "1984");
\r
482 mmiOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "Astoria, NY");
\r
483 Map<String, String> pahmaOrgMap = new HashMap<String,String>();
\r
484 pahmaOrgMap.put(OrganizationJAXBSchema.SHORT_NAME, "PAHMA");
\r
485 pahmaOrgMap.put(OrganizationJAXBSchema.LONG_NAME, "Phoebe A. Hearst Museum of Anthropology");
\r
486 pahmaOrgMap.put(OrganizationJAXBSchema.NAME_ADDITIONS, "University of California, Berkeley");
\r
487 pahmaOrgMap.put(OrganizationJAXBSchema.CONTACT_NAME, "Michael Black");
\r
488 pahmaOrgMap.put(OrganizationJAXBSchema.FOUNDING_DATE, "1901");
\r
489 pahmaOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "Berkeley, CA");
\r
490 Map<String, String> savoyOrgMap = new HashMap<String,String>();
\r
491 savoyOrgMap.put(OrganizationJAXBSchema.SHORT_NAME, "Savoy Theatre");
\r
492 savoyOrgMap.put(OrganizationJAXBSchema.FOUNDING_DATE, "1900");
\r
493 savoyOrgMap.put(OrganizationJAXBSchema.DISSOLUTION_DATE, "1952");
\r
494 savoyOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "New York, NY");
\r
495 List<Map<String, String>> orgMaps =
\r
496 Arrays.asList(mmiOrgMap, pahmaOrgMap, savoyOrgMap );
\r
498 sample.createOrgAuthority("Sample Org Authority", orgMaps);
\r
500 logger.info("OrgAuthority Sample complete.");
\r
502 logger.info("Reading orgAuthorities and items ...");
\r
503 // Get a list of orgAuthorities.
\r
504 orgAuthorities = sample.readOrgAuthorities();
\r
505 // For each orgAuthority ...
\r
506 for (OrgauthoritiesCommonList.OrgauthorityListItem
\r
507 orgAuthority : orgAuthorities.getOrgauthorityListItem()) {
\r
508 // Get its display name.
\r
509 logger.info(orgAuthority.getDisplayName());
\r
510 // Get a list of the organizations in this orgAuthority.
\r
511 OrganizationsCommonList items =
\r
512 sample.readItemsInOrgAuth(orgAuthority.getCsid());
\r
513 // For each organization ...
\r
514 for (OrganizationsCommonList.OrganizationListItem
\r
515 item : items.getOrganizationListItem()) {
\r
516 // Get its display name.
\r
517 logger.info(" " + item.getDisplayName());
\r
521 // Sample alternate methods of reading all orgAuthorities and
\r
522 // organizations separately.
\r
523 boolean RUN_ADDITIONAL_SAMPLES = false;
\r
524 if (RUN_ADDITIONAL_SAMPLES) {
\r
526 logger.info("Reading all orgAuthorities ...");
\r
527 details = sample.displayAllOrgAuthorities(orgAuthorities);
\r
528 logger.info(details);
\r
530 logger.info("Reading all organizations ...");
\r
531 orgAuthIds = sample.readOrgAuthorityIds(orgAuthorities);
\r
532 for (String orgAuthId : orgAuthIds) {
\r
533 OrganizationsCommonList items = sample.readItemsInOrgAuth(orgAuthId);
\r
534 details = sample.displayAllOrganizations(items);
\r
535 logger.info(details);
\r