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:
6 * http://www.collectionspace.org
7 * http://wiki.collectionspace.org
9 * Copyright (c)) 2009 Regents of the University of California
11 * Licensed under the Educational Community License (ECL), Version 2.0.
12 * You may not use this file except in compliance with this License.
14 * You may obtain a copy of the ECL 2.0 License at
15 * https://source.collectionspace.org/collection-space/LICENSE.txt
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.
24 package org.collectionspace.services.person.client.sample;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.HashMap;
29 import java.util.List;
32 import javax.ws.rs.core.MediaType;
33 import javax.ws.rs.core.MultivaluedMap;
34 import javax.ws.rs.core.Response;
36 import org.apache.log4j.BasicConfigurator;
37 import org.collectionspace.services.PersonJAXBSchema;
38 import org.collectionspace.services.client.PersonAuthorityClient;
39 import org.collectionspace.services.client.PersonAuthorityClientUtils;
40 import org.collectionspace.services.client.PoxPayloadIn;
41 import org.collectionspace.services.client.PoxPayloadOut;
42 import org.collectionspace.services.client.test.ServiceRequestType;
43 import org.collectionspace.services.person.PersonauthoritiesCommon;
44 import org.collectionspace.services.person.PersonauthoritiesCommonList;
45 import org.collectionspace.services.person.PersonsCommon;
46 import org.collectionspace.services.person.PersonsCommonList;
47 import org.jboss.resteasy.client.ClientResponse;
48 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
49 import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
54 * PersonAuthority Sample, carries out tests against a
55 * deployed and running PersonAuthority Service.
57 * $LastChangedRevision: 1055 $
58 * $LastChangedDate: 2009-12-09 12:25:15 -0800 (Wed, 09 Dec 2009) $
61 private static final Logger logger =
62 LoggerFactory.getLogger(Sample.class);
64 // Instance variables specific to this test.
65 private PersonAuthorityClient client = new PersonAuthorityClient();
66 final String SERVICE_PATH_COMPONENT = "persons";
67 final String ITEM_SERVICE_PATH_COMPONENT = "items";
70 // ---------------------------------------------------------------
72 // ---------------------------------------------------------------
74 public void createPersonAuthority(String personAuthorityName,
75 List<Map<String, String>> personMaps ) {
77 // Expected status code: 201 Created
78 int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
79 // Type of service request being tested
80 ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
82 logger.info("Import: Create personAuthority: \"" + personAuthorityName +"\"");
85 String displaySuffix = "displayName-" + System.currentTimeMillis(); //TODO: Laramie20100728 temp fix, made-up displaySuffix.
86 String basePersonRefName = PersonAuthorityClientUtils.createPersonAuthRefName(personAuthorityName, displaySuffix);//TODO: Laramie20100728 temp fix was personAuthorityName, false
87 String fullPersonRefName = PersonAuthorityClientUtils.createPersonAuthRefName(personAuthorityName, displaySuffix); //TODO: Laramie20100728 temp fix was personAuthorityName, true
88 PoxPayloadOut multipart =
89 PersonAuthorityClientUtils.createPersonAuthorityInstance(
90 personAuthorityName, fullPersonRefName, client.getCommonPartName() );
91 ClientResponse<Response> res = client.create(multipart);
93 int statusCode = res.getStatus();
95 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
96 throw new RuntimeException("Could not create enumeration: \""+personAuthorityName
97 +"\" "+ PersonAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
99 if(statusCode != EXPECTED_STATUS_CODE) {
100 throw new RuntimeException("Unexpected Status when creating enumeration: \""
101 +personAuthorityName +"\", Status:"+ statusCode);
104 // Store the ID returned from this create operation
105 // for additional tests below.
106 String newPersonAuthId = PersonAuthorityClientUtils.extractId(res);
107 logger.info("Import: Created personAuthority: \"" + personAuthorityName +"\" ID:"
110 // Add items to the personAuthority
111 for(Map<String,String> personMap : personMaps){
112 createItemInAuthority(newPersonAuthId, basePersonRefName, personMap);
117 private String createItemInAuthority(String vcsid,
118 String personAuthorityRefName, Map<String,String> personMap) {
119 // Expected status code: 201 Created
120 int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
121 // Type of service request being tested
122 ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
123 String foreName = personMap.get(PersonJAXBSchema.FORE_NAME);
124 String middleName = personMap.get(PersonJAXBSchema.MIDDLE_NAME);
125 String surName = personMap.get(PersonJAXBSchema.SUR_NAME);
126 String birthDate = personMap.get(PersonJAXBSchema.BIRTH_DATE);
127 String deathDate = personMap.get(PersonJAXBSchema.DEATH_DATE);
128 StringBuilder builtName = new StringBuilder();
130 builtName.append(foreName);
132 builtName.append(middleName);
134 builtName.append(surName);
136 builtName.append(birthDate);
137 builtName.append("-");
139 builtName.append(deathDate);
141 String displaySuffix = "displayName-" + System.currentTimeMillis(); //TODO: Laramie20100728 temp fix, made-up displaySuffix.
143 String refName = PersonAuthorityClientUtils.createPersonRefName(personAuthorityRefName, builtName.toString(), displaySuffix); //TODO was ...,true);
144 logger.info("Import: Create Item: \""+refName+"\" in personAuthority: \"" + personAuthorityRefName +"\"");
146 if(logger.isDebugEnabled()){
147 logger.debug("Import: Create Item: \""+builtName.toString()
148 +"\" in personAuthorityulary: \"" + personAuthorityRefName +"\"");
150 PoxPayloadOut multipart = createPersonInstance( vcsid, refName,
152 ClientResponse<Response> res = client.createItem(vcsid, multipart);
154 int statusCode = res.getStatus();
156 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
157 throw new RuntimeException("Could not create Item: \""+refName
158 +"\" in personAuthority: \"" + personAuthorityRefName
159 +"\" "+ PersonAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
161 if(statusCode != EXPECTED_STATUS_CODE) {
162 throw new RuntimeException("Unexpected Status when creating Item: \""+refName
163 +"\" in personAuthority: \"" + personAuthorityRefName +"\", Status:"+ statusCode);
166 return PersonAuthorityClientUtils.extractId(res);
170 // ---------------------------------------------------------------
172 // ---------------------------------------------------------------
174 private PersonauthoritiesCommonList readPersonAuthorities() {
176 // Expected status code: 200 OK
177 int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
178 // Type of service request being tested
179 ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ;
181 // Submit the request to the service and store the response.
182 ClientResponse<PersonauthoritiesCommonList> res = client.readList();
183 PersonauthoritiesCommonList list = res.getEntity();
185 int statusCode = res.getStatus();
186 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
187 throw new RuntimeException("Could not read list of personAuthorities: "
188 + PersonAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
190 if(statusCode != EXPECTED_STATUS_CODE) {
191 throw new RuntimeException("Unexpected Status when reading " +
192 "list of personAuthorities, Status:"+ statusCode);
198 private List<String> readPersonAuthorityIds(PersonauthoritiesCommonList list) {
200 List<String> ids = new ArrayList<String>();
201 List<PersonauthoritiesCommonList.PersonauthorityListItem> personAuthorities =
202 list.getPersonauthorityListItem();
203 for (PersonauthoritiesCommonList.PersonauthorityListItem personAuthority : personAuthorities) {
204 ids.add(personAuthority.getCsid());
209 private PersonauthoritiesCommon readPersonAuthority(String personAuthId) {
211 // Expected status code: 200 OK
212 int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
213 // Type of service request being tested
214 ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ;
216 // Submit the request to the service and store the response.
217 PersonauthoritiesCommon personAuthority = null;
219 ClientResponse<String> res = client.read(personAuthId);
220 int statusCode = res.getStatus();
221 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
222 throw new RuntimeException("Could not read personAuthority"
223 + PersonAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
225 if(statusCode != EXPECTED_STATUS_CODE) {
226 throw new RuntimeException("Unexpected Status when reading " +
227 "personAuthority, Status:"+ statusCode);
229 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
230 personAuthority = (PersonauthoritiesCommon) extractPart(input,
231 client.getCommonPartName(), PersonauthoritiesCommon.class);
232 } catch (Exception e) {
233 throw new RuntimeException("Could not read personAuthority: ", e);
236 return personAuthority;
239 private PersonsCommonList readItemsInPersonAuth(String personAuthId) {
241 // Expected status code: 200 OK
242 int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
243 // Type of service request being tested
244 ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ;
246 // Submit the request to the service and store the response.
247 ClientResponse<PersonsCommonList> res = client.readItemList(personAuthId, "", ""); //TODO: Laramie201007289 added empty strings to satisfy api
248 PersonsCommonList list = res.getEntity();
250 int statusCode = res.getStatus();
252 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
253 throw new RuntimeException("Could not read items in personAuthority: "
254 + PersonAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
256 if(statusCode != EXPECTED_STATUS_CODE) {
257 throw new RuntimeException("Unexpected Status when reading " +
258 "items in personAuthority, Status:"+ statusCode);
264 private List<String> readPersonIds(PersonsCommonList list) {
266 List<String> ids = new ArrayList<String>();
267 List<PersonsCommonList.PersonListItem> items =
268 list.getPersonListItem();
269 for (PersonsCommonList.PersonListItem item : items) {
270 ids.add(item.getCsid());
275 // ---------------------------------------------------------------
277 // ---------------------------------------------------------------
279 private void deletePersonAuthority(String vcsid) {
280 // Expected status code: 200 OK
281 int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
282 // Type of service request being tested
283 ServiceRequestType REQUEST_TYPE = ServiceRequestType.DELETE;
285 ClientResponse<Response> res = client.delete(vcsid);
286 int statusCode = res.getStatus();
288 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
289 throw new RuntimeException("Could not delete personAuthority: "
290 + PersonAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
292 if(statusCode != EXPECTED_STATUS_CODE) {
293 throw new RuntimeException("Unexpected Status when deleting " +
294 "personAuthority, Status:"+ statusCode);
298 private void deleteAllPersonAuthorities() {
299 List<String> ids = readPersonAuthorityIds(readPersonAuthorities());
300 for (String id : ids) {
301 deletePersonAuthority(id);
305 private void deletePerson(String vcsid, String itemcsid) {
306 // Expected status code: 200 OK
307 int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode();
308 // Type of service request being tested
309 ServiceRequestType REQUEST_TYPE = ServiceRequestType.DELETE;
311 ClientResponse<Response> res = client.deleteItem(vcsid, itemcsid);
312 int statusCode = res.getStatus();
314 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
315 throw new RuntimeException("Could not delete personAuthority item: "
316 + PersonAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
318 if(statusCode != EXPECTED_STATUS_CODE) {
319 throw new RuntimeException("Unexpected Status when deleting " +
320 "personAuthority item, Status:"+ statusCode);
324 private void deleteAllItemsForPersonAuth(String personAuthId) {
325 List<String> itemIds = readPersonIds(readItemsInPersonAuth(personAuthId));
326 for (String itemId : itemIds) {
327 deletePerson(personAuthId, itemId);
331 // ---------------------------------------------------------------
332 // Utility methods used by tests above
333 // ---------------------------------------------------------------
336 private PoxPayloadOut createPersonAuthorityInstance(
337 String displayName, String refName ) {
338 PersonauthoritiesCommon personAuthority = new PersonauthoritiesCommon();
339 personAuthority.setDisplayName(displayName);
340 personAuthority.setRefName(refName);
341 personAuthority.setVocabType("PersonAuthority");
342 PoxPayloadOut multipart = new PoxPayloadOut();
343 OutputPart commonPart = multipart.addPart(personAuthority, MediaType.APPLICATION_XML_TYPE);
344 commonPart.getHeaders().add("label", client.getCommonPartName());
346 if(logger.isDebugEnabled()){
347 logger.debug("to be created, personAuthority common ",
348 personAuthority, PersonauthoritiesCommon.class);
355 private PoxPayloadOut createPersonInstance(String inAuthority,
356 String refName, Map<String, String> personInfo ) {
357 PersonsCommon person = new PersonsCommon();
358 person.setInAuthority(inAuthority);
359 person.setRefName(refName);
361 if((value = (String)personInfo.get(PersonJAXBSchema.FORE_NAME))!=null)
362 person.setForeName(value);
363 if((value = (String)personInfo.get(PersonJAXBSchema.MIDDLE_NAME))!=null)
364 person.setMiddleName(value);
365 if((value = (String)personInfo.get(PersonJAXBSchema.SUR_NAME))!=null)
366 person.setSurName(value);
367 if((value = (String)personInfo.get(PersonJAXBSchema.INITIALS))!=null)
368 person.setInitials(value);
369 if((value = (String)personInfo.get(PersonJAXBSchema.SALUTATIONS))!=null)
370 person.setSalutation(value);
371 if((value = (String)personInfo.get(PersonJAXBSchema.TITLE))!=null)
372 person.setTitle(value);
373 if((value = (String)personInfo.get(PersonJAXBSchema.NAME_ADDITIONS))!=null)
374 person.setNameAdditions(value);
375 if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_DATE))!=null) {
376 StructuredDateGroup birthDate = new StructuredDateGroup();
377 birthDate.setDateDisplayDate(value);
378 person.setBirthDateGroup(birthDate);
380 if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_DATE))!=null) {
381 StructuredDateGroup deathDate = new StructuredDateGroup();
382 deathDate.setDateDisplayDate(value);
383 person.setDeathDateGroup(deathDate);
385 if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_PLACE))!=null)
386 person.setBirthPlace(value);
387 if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_PLACE))!=null)
388 person.setDeathPlace(value);
390 /* TODO: Laramie20100728 removed missing member calls
391 if((value = (String)personInfo.get(PersonJAXBSchema.GROUP))!=null)
392 person.setGroup(value);
393 if((value = (String)personInfo.get(PersonJAXBSchema.NATIONALITY))!=null)
394 person.setNationality(value);
395 if((value = (String)personInfo.get(PersonJAXBSchema.OCCUPATION))!=null)
396 person.setOccupation(value);
397 if((value = (String)personInfo.get(PersonJAXBSchema.SCHOOL_OR_STYLE))!=null)
398 person.setSchoolOrStyle(value);
401 if((value = (String)personInfo.get(PersonJAXBSchema.GENDER))!=null)
402 person.setGender(value);
403 if((value = (String)personInfo.get(PersonJAXBSchema.BIO_NOTE))!=null)
404 person.setBioNote(value);
405 if((value = (String)personInfo.get(PersonJAXBSchema.NAME_NOTE))!=null)
406 person.setNameNote(value);
407 PoxPayloadOut multipart = new PoxPayloadOut();
408 OutputPart commonPart = multipart.addPart(person,
409 MediaType.APPLICATION_XML_TYPE);
410 commonPart.getHeaders().add("label", client.getItemCommonPartName());
412 if(logger.isDebugEnabled()){
413 logger.debug("to be created, person common"+person);
419 // Retrieve individual fields of personAuthority records.
421 private String displayAllPersonAuthorities(PersonauthoritiesCommonList list) {
422 StringBuffer sb = new StringBuffer();
423 List<PersonauthoritiesCommonList.PersonauthorityListItem> personAuthorities =
424 list.getPersonauthorityListItem();
426 for (PersonauthoritiesCommonList.PersonauthorityListItem personAuthority : personAuthorities) {
427 sb.append("personAuthority [" + i + "]" + "\n");
428 sb.append(displayPersonAuthorityDetails(personAuthority));
431 return sb.toString();
434 private String displayPersonAuthorityDetails(
435 PersonauthoritiesCommonList.PersonauthorityListItem personAuthority) {
436 StringBuffer sb = new StringBuffer();
437 sb.append("displayName=" + personAuthority.getDisplayName() + "\n");
438 sb.append("vocabType=" + personAuthority.getVocabType() + "\n");
439 // sb.append("csid=" + personAuthority.getCsid() + "\n");
440 sb.append("URI=" + personAuthority.getUri() + "\n");
441 return sb.toString();
444 // Retrieve individual fields of person records.
446 private String displayAllPersons(PersonsCommonList list) {
447 StringBuffer sb = new StringBuffer();
448 List<PersonsCommonList.PersonListItem> items =
449 list.getPersonListItem();
451 for (PersonsCommonList.PersonListItem item : items) {
452 sb.append("person [" + i + "]" + "\n");
453 sb.append(displayPersonDetails(item));
456 return sb.toString();
459 private String displayPersonDetails(
460 PersonsCommonList.PersonListItem item) {
461 StringBuffer sb = new StringBuffer();
462 sb.append("csid=" + item.getCsid() + "\n");
463 sb.append("displayName=" + item.getDisplayName() + "\n");
464 // sb.append("URI=" + item.getUri() + "\n");
465 return sb.toString();
468 private Object extractPart(PoxPayloadIn input, String label,
469 Class clazz) throws Exception {
471 for(InputPart part : input.getParts()){
472 String partLabel = part.getHeaders().getFirst("label");
473 if(label.equalsIgnoreCase(partLabel)){
474 String partStr = part.getBodyAsString();
475 if(logger.isDebugEnabled()){
476 logger.debug("extracted part str=\n" + partStr);
478 obj = part.getBody(clazz, null);
479 if(logger.isDebugEnabled()){
480 logger.debug("extracted part obj=\n", obj, clazz);
488 public static void main(String[] args) {
490 // Configure logging.
491 BasicConfigurator.configure();
493 logger.info("PersonAuthority Sample starting...");
495 Sample sample = new Sample();
496 PersonauthoritiesCommonList personAuthorities;
497 List<String> personAuthIds;
500 // Optionally delete all personAuthorities and persons.
502 boolean ENABLE_DELETE_ALL = false;
503 if (ENABLE_DELETE_ALL) {
505 logger.info("Deleting all persons and personAuthorities ...");
507 // For each personAuthority ...
508 personAuthorities = sample.readPersonAuthorities();
509 personAuthIds = sample.readPersonAuthorityIds(personAuthorities);
510 for (String personAuthId : personAuthIds) {
511 logger.info("Deleting all persons for personAuthority ...");
512 sample.deleteAllItemsForPersonAuth(personAuthId);
513 logger.info("Deleting personAuthority ...");
514 sample.deletePersonAuthority(personAuthId);
517 logger.info("Reading personAuthorities after deletion ...");
518 personAuthorities = sample.readPersonAuthorities();
519 details = sample.displayAllPersonAuthorities(personAuthorities);
520 logger.info(details);
522 logger.info("Reading items in each personAuthority after deletion ...");
523 personAuthIds = sample.readPersonAuthorityIds(personAuthorities);
524 for (String personAuthId : personAuthIds) {
525 PersonsCommonList items = sample.readItemsInPersonAuth(personAuthId);
526 details = sample.displayAllPersons(items);
527 logger.info(details);
532 // Create new authorities, each populated with persons.
534 Map<String, String> johnWayneMap = new HashMap<String,String>();
535 johnWayneMap.put(PersonJAXBSchema.FORE_NAME, "John");
536 johnWayneMap.put(PersonJAXBSchema.SUR_NAME, "Wayne");
537 johnWayneMap.put(PersonJAXBSchema.GENDER, "male");
538 Map<String, String> patrickSchmitzMap = new HashMap<String,String>();
539 patrickSchmitzMap.put(PersonJAXBSchema.FORE_NAME, "Patrick");
540 patrickSchmitzMap.put(PersonJAXBSchema.SUR_NAME, "Schmitz");
541 patrickSchmitzMap.put(PersonJAXBSchema.GENDER, "male");
542 Map<String, String> janeDoeMap = new HashMap<String,String>();
543 janeDoeMap.put(PersonJAXBSchema.FORE_NAME, "Jane");
544 janeDoeMap.put(PersonJAXBSchema.SUR_NAME, "Doe");
545 janeDoeMap.put(PersonJAXBSchema.GENDER, "female");
546 List<Map<String, String>> personsMaps =
547 Arrays.asList(johnWayneMap, patrickSchmitzMap, janeDoeMap );
549 sample.createPersonAuthority("Sample Person Auth", personsMaps);
551 logger.info("PersonAuthority Sample complete.");
553 logger.info("Reading personAuthorities and items ...");
554 // Get a list of personAuthorities.
555 personAuthorities = sample.readPersonAuthorities();
556 // For each personAuthority ...
557 for (PersonauthoritiesCommonList.PersonauthorityListItem
558 personAuthority : personAuthorities.getPersonauthorityListItem()) {
559 // Get its display name.
560 logger.info(personAuthority.getDisplayName());
561 // Get a list of the persons in this personAuthority.
562 PersonsCommonList items =
563 sample.readItemsInPersonAuth(personAuthority.getCsid());
564 // For each person ...
565 for (PersonsCommonList.PersonListItem
566 item : items.getPersonListItem()) {
567 // Get its short name.
568 logger.info(" " + item.getDisplayName());
572 // Sample alternate methods of reading all personAuthorities and
573 // persons separately.
574 boolean RUN_ADDITIONAL_SAMPLES = false;
575 if (RUN_ADDITIONAL_SAMPLES) {
577 logger.info("Reading all personAuthorities ...");
578 details = sample.displayAllPersonAuthorities(personAuthorities);
579 logger.info(details);
581 logger.info("Reading all persons ...");
582 personAuthIds = sample.readPersonAuthorityIds(personAuthorities);
583 for (String personAuthId : personAuthIds) {
584 PersonsCommonList items = sample.readItemsInPersonAuth(personAuthId);
585 details = sample.displayAllPersons(items);
586 logger.info(details);