2 * PersonAuthorityClientUtils.java
4 * {Purpose of This Class}
6 * {Other Notes Relating to This Class (Optional)}
9 * $LastChangedRevision: $
12 * This document is a part of the source code and related artifacts
13 * for CollectionSpace, an open source collections management system
14 * for museums and related institutions:
16 * http://www.collectionspace.org
17 * http://wiki.collectionspace.org
19 * Copyright © 2009 {Contributing Institution}
21 * Licensed under the Educational Community License (ECL), Version 2.0.
22 * You may not use this file except in compliance with this License.
24 * You may obtain a copy of the ECL 2.0 License at
25 * https://source.collectionspace.org/collection-space/LICENSE.txt
27 package org.collectionspace.services.client;
31 import javax.ws.rs.core.MediaType;
32 import javax.ws.rs.core.MultivaluedMap;
33 import javax.ws.rs.core.Response;
35 import org.collectionspace.services.PersonJAXBSchema;
36 import org.collectionspace.services.client.test.ServiceRequestType;
37 import org.collectionspace.services.common.api.Tools;
38 import org.collectionspace.services.person.GroupList;
39 import org.collectionspace.services.person.NationalityList;
40 import org.collectionspace.services.person.OccupationList;
41 import org.collectionspace.services.person.PersonTermGroup;
42 import org.collectionspace.services.person.PersonTermGroupList;
43 import org.collectionspace.services.person.PersonsCommon;
44 import org.collectionspace.services.person.PersonauthoritiesCommon;
45 import org.collectionspace.services.person.SchoolOrStyleList;
46 import org.collectionspace.services.person.StructuredDateGroup;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
51 * The Class PersonAuthorityClientUtils.
53 public class PersonAuthorityClientUtils {
55 /** The Constant logger. */
56 private static final Logger logger =
57 LoggerFactory.getLogger(PersonAuthorityClientUtils.class);
58 private static final ServiceRequestType READ_REQ = ServiceRequestType.READ;
59 static private final Random random = new Random(System.currentTimeMillis());
62 * @param csid the id of the PersonAuthority
63 * @param client if null, creates a new client
67 public static String getAuthorityRefName(String csid, PersonClient client) throws Exception{
69 client = new PersonClient();
71 Response res = client.read(csid);
73 int statusCode = res.getStatus();
74 if(!READ_REQ.isValidStatusCode(statusCode)
75 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
76 throw new RuntimeException("Invalid status code returned: "+statusCode);
78 //FIXME: remove the following try catch once Aron fixes signatures
80 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
81 PersonauthoritiesCommon personAuthority =
82 (PersonauthoritiesCommon) CollectionSpaceClientUtils.extractPart(input,
83 client.getCommonPartName(), PersonauthoritiesCommon.class);
84 if(personAuthority == null) {
85 throw new RuntimeException("Null personAuthority returned from service.");
87 return personAuthority.getRefName();
88 } catch (Exception e) {
89 throw new RuntimeException(e);
97 * @param csid the id of the PersonAuthority
98 * @param client if null, creates a new client
102 public static String getPersonRefName(String inAuthority, String csid, PersonClient client) throws Exception{
103 if ( client == null) {
104 client = new PersonClient();
106 Response res = client.readItem(inAuthority, csid);
108 int statusCode = res.getStatus();
109 if(!READ_REQ.isValidStatusCode(statusCode)
110 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
111 throw new RuntimeException("Invalid status code returned: "+statusCode);
113 //FIXME: remove the following try catch once Aron fixes signatures
115 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
116 PersonsCommon person =
117 (PersonsCommon) CollectionSpaceClientUtils.extractPart(input,
118 client.getItemCommonPartName(), PersonsCommon.class);
119 if (person == null) {
120 throw new RuntimeException("Null person returned from service.");
122 return person.getRefName();
123 } catch (Exception e) {
124 throw new RuntimeException(e);
132 * Creates the person authority instance.
134 * @param displayName the display name
135 * @param shortIdentifier the short Id
136 * @param headerLabel the header label
137 * @return the multipart output
139 public static PoxPayloadOut createPersonAuthorityInstance(String displayName, String shortIdentifier, String headerLabel ) {
140 PersonauthoritiesCommon personAuthority = new PersonauthoritiesCommon();
141 personAuthority.setDisplayName(displayName);
142 personAuthority.setShortIdentifier(shortIdentifier);
143 //String refName = createPersonAuthRefName(shortIdentifier, displayName);
144 //personAuthority.setRefName(refName);
145 personAuthority.setVocabType("PersonAuthority");
146 PoxPayloadOut multipart = new PoxPayloadOut(PersonClient.SERVICE_PAYLOAD_NAME);
147 PayloadOutputPart commonPart = multipart.addPart(personAuthority, MediaType.APPLICATION_XML_TYPE);
148 commonPart.setLabel(headerLabel);
150 if (logger.isDebugEnabled()) {
151 logger.debug("To be created, personAuthority common: ",
152 personAuthority, PersonauthoritiesCommon.class);
159 * Create a very simple Person term -just a short ID and display name.
161 public static PoxPayloadOut createPersonInstance(String shortIdentifier, String displayName,
162 String headerLabel) {
163 List<PersonTermGroup> terms = getTermGroupInstance(shortIdentifier, displayName);
165 Map<String, String> personInfo = new HashMap<String, String>();
166 personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortIdentifier);
168 return createPersonInstance(null, null, personInfo, terms, null, headerLabel);
172 * Creates a person instance.
174 * @param inAuthority the owning authority
175 * @param personAuthRefName the owning Authority ref name
176 * @param personInfo the person info
177 * @param headerLabel the header label
178 * @return the multipart output
180 public static PoxPayloadOut createPersonInstance(
182 String personAuthRefName,
183 Map<String, String> personInfo,
184 List<PersonTermGroup> terms,
185 String headerLabel) {
186 if (terms == null || terms.isEmpty()) {
187 terms = getTermGroupInstance(getGeneratedIdentifier());
189 final Map<String, List<String>> EMPTY_PERSON_REPEATABLES_INFO = new HashMap<String, List<String>>();
190 return createPersonInstance(inAuthority, null /*personAuthRefName*/,
191 personInfo, terms, EMPTY_PERSON_REPEATABLES_INFO, headerLabel);
195 * Creates a person instance.
197 * @param inAuthority the owning authority
198 * @param personAuthRefName the owning Authority ref name
199 * @param personInfo the person info
200 * @param terms a list of Person terms
201 * @param personRepeatablesInfo names and values of repeatable scalar fields in the Person record
202 * @param headerLabel the header label
203 * @return the multipart output
205 public static PoxPayloadOut createPersonInstance(
207 String personAuthRefName,
208 Map<String, String> personInfo,
209 List<PersonTermGroup> terms,
210 Map<String, List<String>> personRepeatablesInfo,
211 String headerLabel) {
213 PersonsCommon person = new PersonsCommon();
214 person.setInAuthority(inAuthority);
215 String shortId = personInfo.get(PersonJAXBSchema.SHORT_IDENTIFIER);
216 if (shortId == null || shortId.isEmpty()) {
217 throw new IllegalArgumentException("shortIdentifier cannot be null or empty");
219 person.setShortIdentifier(shortId);
221 if (personInfo != null) {
224 if ((value = personInfo.get(PersonJAXBSchema.BIRTH_DATE)) != null) {
225 StructuredDateGroup birthDate = new StructuredDateGroup();
226 birthDate.setDateDisplayDate(value);
227 person.setBirthDateGroup(birthDate);
229 if ((value = personInfo.get(PersonJAXBSchema.DEATH_DATE)) != null) {
230 StructuredDateGroup deathDate = new StructuredDateGroup();
231 deathDate.setDateDisplayDate(value);
232 person.setDeathDateGroup(deathDate);
234 if ((value = personInfo.get(PersonJAXBSchema.BIRTH_PLACE)) != null)
235 person.setBirthPlace(value);
236 if ((value = personInfo.get(PersonJAXBSchema.DEATH_PLACE)) != null)
237 person.setDeathPlace(value);
238 if ((value = personInfo.get(PersonJAXBSchema.GENDER)) != null)
239 person.setGender(value);
240 if ((value = personInfo.get(PersonJAXBSchema.BIO_NOTE)) != null)
241 person.setBioNote(value);
242 if ((value = personInfo.get(PersonJAXBSchema.NAME_NOTE)) != null)
243 person.setNameNote(value);
246 // Set values in the Term Information Group
247 PersonTermGroupList termList = new PersonTermGroupList();
248 if (terms == null || terms.isEmpty()) {
249 terms = getTermGroupInstance(getGeneratedIdentifier());
251 termList.getPersonTermGroup().addAll(terms);
252 person.setPersonTermGroupList(termList);
254 if (personRepeatablesInfo != null) {
255 List<String> values = null;
257 if ((values = (List<String>) personRepeatablesInfo.get(PersonJAXBSchema.GROUPS)) != null) {
258 GroupList groupsList = new GroupList();
259 List<String> groups = groupsList.getGroup();
260 groups.addAll(values);
261 person.setGroups(groupsList);
263 if ((values = (List<String>) personRepeatablesInfo.get(PersonJAXBSchema.NATIONALITIES)) != null) {
264 NationalityList nationalitiesList = new NationalityList();
265 List<String> nationalities = nationalitiesList.getNationality();
266 nationalities.addAll(values);
267 person.setNationalities(nationalitiesList);
270 if ((values = (List<String>) personRepeatablesInfo.get(PersonJAXBSchema.OCCUPATIONS)) != null) {
271 OccupationList occupationsList = new OccupationList();
272 List<String> occupations = occupationsList.getOccupation();
273 occupations.addAll(values);
274 person.setOccupations(occupationsList);
276 if ((values = (List<String>) personRepeatablesInfo.get(PersonJAXBSchema.SCHOOLS_OR_STYLES)) != null) {
277 SchoolOrStyleList schoolOrStyleList = new SchoolOrStyleList();
278 List<String> schoolsOrStyles = schoolOrStyleList.getSchoolOrStyle();
279 schoolsOrStyles.addAll(values);
280 person.setSchoolsOrStyles(schoolOrStyleList);
284 PoxPayloadOut multipart = new PoxPayloadOut(PersonClient.SERVICE_ITEM_PAYLOAD_NAME);
285 PayloadOutputPart commonPart = multipart.addPart(person, MediaType.APPLICATION_XML_TYPE);
286 commonPart.setLabel(headerLabel);
288 if (logger.isDebugEnabled()) {
289 logger.debug("to be created, person common ", person, PersonsCommon.class);
296 * Creates the item in authority.
298 * @param vcsid the vcsid
299 * @param personAuthorityRefName the person authority ref name
300 * @param personMap the person map. PersonJAXBSchema.SHORT_IDENTIFIER is REQUIRED.
301 * @param client the client
304 public static String createItemInAuthority(String vcsid,
305 String personAuthorityRefName, Map<String,String> personMap,
306 List<PersonTermGroup> terms, Map<String, List<String>> personRepeatablesMap,
307 PersonClient client ) {
308 // Expected status code: 201 Created
309 int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
310 // Type of service request being tested
311 ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
313 String displayName = "";
314 if (terms !=null && terms.size() > 0) {
315 displayName = terms.get(0).getTermDisplayName();
318 if(logger.isDebugEnabled()){
319 logger.debug("Creating item with display name: \"" + displayName
320 +"\" in personAuthority: \"" + vcsid +"\"");
322 PoxPayloadOut multipart =
323 createPersonInstance(vcsid, null /*personAuthorityRefName*/,
324 personMap, terms, personRepeatablesMap, client.getItemCommonPartName());
326 String result = null;
327 Response res = client.createItem(vcsid, multipart);
329 int statusCode = res.getStatus();
331 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
332 throw new RuntimeException("Could not create Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)
333 +"\" in personAuthority: \"" + vcsid //personAuthorityRefName
334 +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
336 if(statusCode != EXPECTED_STATUS_CODE) {
337 throw new RuntimeException("Unexpected Status when creating Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)
338 +"\" in personAuthority: \"" + vcsid /*personAuthorityRefName*/ +"\", Status:"+ statusCode);
341 result = extractId(res);
350 * Creates the personAuthority ref name.
352 * @param shortId the personAuthority shortIdentifier
353 * @param displaySuffix displayName to be appended, if non-null
357 public static String createPersonAuthRefName(String shortId, String displaySuffix) {
358 String refName = "urn:cspace:org.collectionspace.demo:personauthority:name("
360 if(displaySuffix!=null&&!displaySuffix.isEmpty())
361 refName += "'"+displaySuffix+"'";
367 * Creates the person ref name.
369 * @param personAuthRefName the person auth ref name
370 * @param shortId the person shortIdentifier
371 * @param displaySuffix displayName to be appended, if non-null
375 public static String createPersonRefName(
376 String personAuthRefName, String shortId, String displaySuffix) {
377 String refName = personAuthRefName+":person:name("+shortId+")";
378 if(displaySuffix!=null&&!displaySuffix.isEmpty())
379 refName += "'"+displaySuffix+"'";
390 public static String extractId(Response res) {
391 MultivaluedMap<String, Object> mvm = res.getMetadata();
392 // FIXME: This may throw an NPE if the Location: header isn't present
393 String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
394 if(logger.isDebugEnabled()){
395 logger.debug("extractId:uri=" + uri);
397 String[] segments = uri.split("/");
398 String id = segments[segments.length - 1];
399 if(logger.isDebugEnabled()){
400 logger.debug("id=" + id);
406 * Returns an error message indicating that the status code returned by a
407 * specific call to a service does not fall within a set of valid status
408 * codes for that service.
410 * @param serviceRequestType A type of service request (e.g. CREATE, DELETE).
412 * @param statusCode The invalid status code that was returned in the response,
413 * from submitting that type of request to the service.
415 * @return An error message.
417 public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
418 return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
419 requestType.validStatusCodesAsString();
425 * Produces a default displayName from the basic name and dates fields.
426 * @see PersonDocumentModelHandler.prepareDefaultDisplayName() which
427 * duplicates this logic, until we define a service-general utils package
428 * that is neither client nor service specific.
434 * @return display name
436 public static String prepareDefaultDisplayName(
437 String foreName, String middleName, String surName,
438 String birthDate, String deathDate) {
439 StringBuilder newStr = new StringBuilder();
440 final String sep = " ";
441 final String dateSep = "-";
442 List<String> nameStrings =
443 Arrays.asList(foreName, middleName, surName);
444 boolean firstAdded = false;
445 for(String partStr : nameStrings ){
446 if(null != partStr ) {
450 newStr.append(partStr);
454 // Now we add the dates. In theory could have dates with no name, but that is their problem.
455 boolean foundBirth = false;
456 if(null != birthDate) {
460 newStr.append(birthDate);
461 newStr.append(dateSep); // Put this in whether there is a death date or not
464 if(null != deathDate) {
469 newStr.append(dateSep);
471 newStr.append(deathDate);
473 return newStr.toString();
476 private static List<PersonTermGroup> getTermGroupInstance(String shortIdentifier) {
477 return getTermGroupInstance(shortIdentifier, shortIdentifier);
480 public static List<PersonTermGroup> getTermGroupInstance(String shortIdentifier, String displayName) {
481 if (Tools.isBlank(shortIdentifier)) {
482 shortIdentifier = getGeneratedIdentifier();
484 if (Tools.isBlank(shortIdentifier)) {
485 displayName = shortIdentifier;
488 List<PersonTermGroup> terms = new ArrayList<PersonTermGroup>();
489 PersonTermGroup term = new PersonTermGroup();
490 term.setTermDisplayName(displayName);
491 term.setTermName(shortIdentifier);
496 private static String getGeneratedIdentifier() {
497 return "id" + createIdentifier();
500 private static String createIdentifier() {
501 long identifier = System.currentTimeMillis() + random.nextInt();
502 return Long.toString(identifier);