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
66 public static String getAuthorityRefName(String csid, PersonAuthorityClient client){
68 client = new PersonAuthorityClient();
70 Response res = client.read(csid);
72 int statusCode = res.getStatus();
73 if(!READ_REQ.isValidStatusCode(statusCode)
74 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
75 throw new RuntimeException("Invalid status code returned: "+statusCode);
77 //FIXME: remove the following try catch once Aron fixes signatures
79 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
80 PersonauthoritiesCommon personAuthority =
81 (PersonauthoritiesCommon) CollectionSpaceClientUtils.extractPart(input,
82 client.getCommonPartName(), PersonauthoritiesCommon.class);
83 if(personAuthority == null) {
84 throw new RuntimeException("Null personAuthority returned from service.");
86 return personAuthority.getRefName();
87 } catch (Exception e) {
88 throw new RuntimeException(e);
96 * @param csid the id of the PersonAuthority
97 * @param client if null, creates a new client
100 public static String getPersonRefName(String inAuthority, String csid, PersonAuthorityClient client){
101 if ( client == null) {
102 client = new PersonAuthorityClient();
104 Response res = client.readItem(inAuthority, csid);
106 int statusCode = res.getStatus();
107 if(!READ_REQ.isValidStatusCode(statusCode)
108 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
109 throw new RuntimeException("Invalid status code returned: "+statusCode);
111 //FIXME: remove the following try catch once Aron fixes signatures
113 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
114 PersonsCommon person =
115 (PersonsCommon) CollectionSpaceClientUtils.extractPart(input,
116 client.getItemCommonPartName(), PersonsCommon.class);
117 if (person == null) {
118 throw new RuntimeException("Null person returned from service.");
120 return person.getRefName();
121 } catch (Exception e) {
122 throw new RuntimeException(e);
130 * Creates the person authority instance.
132 * @param displayName the display name
133 * @param shortIdentifier the short Id
134 * @param headerLabel the header label
135 * @return the multipart output
137 public static PoxPayloadOut createPersonAuthorityInstance(
138 String displayName, String shortIdentifier, String headerLabel ) {
139 PersonauthoritiesCommon personAuthority = new PersonauthoritiesCommon();
140 personAuthority.setDisplayName(displayName);
141 personAuthority.setShortIdentifier(shortIdentifier);
142 //String refName = createPersonAuthRefName(shortIdentifier, displayName);
143 //personAuthority.setRefName(refName);
144 personAuthority.setVocabType("PersonAuthority");
145 PoxPayloadOut multipart = new PoxPayloadOut(PersonAuthorityClient.SERVICE_PAYLOAD_NAME);
146 PayloadOutputPart commonPart = multipart.addPart(personAuthority, MediaType.APPLICATION_XML_TYPE);
147 commonPart.setLabel(headerLabel);
149 if(logger.isDebugEnabled()){
150 logger.debug("to be created, personAuthority common ",
151 personAuthority, PersonauthoritiesCommon.class);
158 * Creates a person instance.
160 * @param inAuthority the owning authority
161 * @param personAuthRefName the owning Authority ref name
162 * @param personInfo the person info
163 * @param headerLabel the header label
164 * @return the multipart output
166 public static PoxPayloadOut createPersonInstance(String inAuthority,
167 String personAuthRefName,
168 Map<String, String> personInfo,
169 List<PersonTermGroup> terms,
171 if (terms == null || terms.isEmpty()) {
172 terms = getTermGroupInstance(getGeneratedIdentifier());
174 final Map<String, List<String>> EMPTY_PERSON_REPEATABLES_INFO =
175 new HashMap<String, List<String>>();
176 return createPersonInstance(inAuthority, null /*personAuthRefName*/,
177 personInfo, terms, EMPTY_PERSON_REPEATABLES_INFO, headerLabel);
181 * Creates a person instance.
183 * @param inAuthority the owning authority
184 * @param personAuthRefName the owning Authority ref name
185 * @param personInfo the person info
186 * @param terms a list of Person terms
187 * @param personRepeatablesInfo names and values of repeatable scalar fields in the Person record
188 * @param headerLabel the header label
189 * @return the multipart output
191 public static PoxPayloadOut createPersonInstance(String inAuthority,
192 String personAuthRefName, Map<String, String> personInfo,
193 List<PersonTermGroup> terms,
194 Map<String, List<String>> personRepeatablesInfo, String headerLabel){
195 PersonsCommon person = new PersonsCommon();
196 person.setInAuthority(inAuthority);
197 String shortId = personInfo.get(PersonJAXBSchema.SHORT_IDENTIFIER);
198 if (shortId == null || shortId.isEmpty()) {
199 throw new IllegalArgumentException("shortIdentifier cannot be null or empty");
201 person.setShortIdentifier(shortId);
204 List<String> values = null;
206 if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_DATE))!=null) {
207 StructuredDateGroup birthDate = new StructuredDateGroup();
208 birthDate.setDateDisplayDate(value);
209 person.setBirthDateGroup(birthDate);
211 if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_DATE))!=null) {
212 StructuredDateGroup deathDate = new StructuredDateGroup();
213 deathDate.setDateDisplayDate(value);
214 person.setDeathDateGroup(deathDate);
216 if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_PLACE))!=null)
217 person.setBirthPlace(value);
218 if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_PLACE))!=null)
219 person.setDeathPlace(value);
220 if((value = (String)personInfo.get(PersonJAXBSchema.GENDER))!=null)
221 person.setGender(value);
222 if((value = (String)personInfo.get(PersonJAXBSchema.BIO_NOTE))!=null)
223 person.setBioNote(value);
224 if((value = (String)personInfo.get(PersonJAXBSchema.NAME_NOTE))!=null)
225 person.setNameNote(value);
227 // Set values in the Term Information Group
228 PersonTermGroupList termList = new PersonTermGroupList();
229 if (terms == null || terms.isEmpty()) {
230 terms = getTermGroupInstance(getGeneratedIdentifier());
232 termList.getPersonTermGroup().addAll(terms);
233 person.setPersonTermGroupList(termList);
235 if (personRepeatablesInfo != null) {
236 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.GROUPS))!=null) {
237 GroupList groupsList = new GroupList();
238 List<String> groups = groupsList.getGroup();
239 groups.addAll(values);
240 person.setGroups(groupsList);
242 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.NATIONALITIES))!=null) {
243 NationalityList nationalitiesList = new NationalityList();
244 List<String> nationalities = nationalitiesList.getNationality();
245 nationalities.addAll(values);
246 person.setNationalities(nationalitiesList);
249 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.OCCUPATIONS))!=null) {
250 OccupationList occupationsList = new OccupationList();
251 List<String> occupations = occupationsList.getOccupation();
252 occupations.addAll(values);
253 person.setOccupations(occupationsList);
255 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.SCHOOLS_OR_STYLES))!=null) {
256 SchoolOrStyleList schoolOrStyleList = new SchoolOrStyleList();
257 List<String> schoolsOrStyles = schoolOrStyleList.getSchoolOrStyle();
258 schoolsOrStyles.addAll(values);
259 person.setSchoolsOrStyles(schoolOrStyleList);
264 PoxPayloadOut multipart = new PoxPayloadOut(PersonAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
265 PayloadOutputPart commonPart = multipart.addPart(person,
266 MediaType.APPLICATION_XML_TYPE);
267 commonPart.setLabel(headerLabel);
269 if(logger.isDebugEnabled()){
270 logger.debug("to be created, person common ", person, PersonsCommon.class);
277 * Creates the item in authority.
279 * @param vcsid the vcsid
280 * @param personAuthorityRefName the person authority ref name
281 * @param personMap the person map. PersonJAXBSchema.SHORT_IDENTIFIER is REQUIRED.
282 * @param client the client
285 public static String createItemInAuthority(String vcsid,
286 String personAuthorityRefName, Map<String,String> personMap,
287 List<PersonTermGroup> terms, Map<String, List<String>> personRepeatablesMap,
288 PersonAuthorityClient client ) {
289 // Expected status code: 201 Created
290 int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
291 // Type of service request being tested
292 ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
294 String displayName = "";
295 if (terms !=null && terms.size() > 0) {
296 displayName = terms.get(0).getTermDisplayName();
299 if(logger.isDebugEnabled()){
300 logger.debug("Creating item with display name: \"" + displayName
301 +"\" in personAuthority: \"" + vcsid +"\"");
303 PoxPayloadOut multipart =
304 createPersonInstance(vcsid, null /*personAuthorityRefName*/,
305 personMap, terms, personRepeatablesMap, client.getItemCommonPartName());
307 String result = null;
308 Response res = client.createItem(vcsid, multipart);
310 int statusCode = res.getStatus();
312 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
313 throw new RuntimeException("Could not create Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)
314 +"\" in personAuthority: \"" + vcsid //personAuthorityRefName
315 +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
317 if(statusCode != EXPECTED_STATUS_CODE) {
318 throw new RuntimeException("Unexpected Status when creating Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)
319 +"\" in personAuthority: \"" + vcsid /*personAuthorityRefName*/ +"\", Status:"+ statusCode);
322 result = extractId(res);
331 * Creates the personAuthority ref name.
333 * @param shortId the personAuthority shortIdentifier
334 * @param displaySuffix displayName to be appended, if non-null
338 public static String createPersonAuthRefName(String shortId, String displaySuffix) {
339 String refName = "urn:cspace:org.collectionspace.demo:personauthority:name("
341 if(displaySuffix!=null&&!displaySuffix.isEmpty())
342 refName += "'"+displaySuffix+"'";
348 * Creates the person ref name.
350 * @param personAuthRefName the person auth ref name
351 * @param shortId the person shortIdentifier
352 * @param displaySuffix displayName to be appended, if non-null
356 public static String createPersonRefName(
357 String personAuthRefName, String shortId, String displaySuffix) {
358 String refName = personAuthRefName+":person:name("+shortId+")";
359 if(displaySuffix!=null&&!displaySuffix.isEmpty())
360 refName += "'"+displaySuffix+"'";
371 public static String extractId(Response res) {
372 MultivaluedMap<String, Object> mvm = res.getMetadata();
373 // FIXME: This may throw an NPE if the Location: header isn't present
374 String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
375 if(logger.isDebugEnabled()){
376 logger.debug("extractId:uri=" + uri);
378 String[] segments = uri.split("/");
379 String id = segments[segments.length - 1];
380 if(logger.isDebugEnabled()){
381 logger.debug("id=" + id);
387 * Returns an error message indicating that the status code returned by a
388 * specific call to a service does not fall within a set of valid status
389 * codes for that service.
391 * @param serviceRequestType A type of service request (e.g. CREATE, DELETE).
393 * @param statusCode The invalid status code that was returned in the response,
394 * from submitting that type of request to the service.
396 * @return An error message.
398 public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
399 return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
400 requestType.validStatusCodesAsString();
406 * Produces a default displayName from the basic name and dates fields.
407 * @see PersonDocumentModelHandler.prepareDefaultDisplayName() which
408 * duplicates this logic, until we define a service-general utils package
409 * that is neither client nor service specific.
415 * @return display name
417 public static String prepareDefaultDisplayName(
418 String foreName, String middleName, String surName,
419 String birthDate, String deathDate) {
420 StringBuilder newStr = new StringBuilder();
421 final String sep = " ";
422 final String dateSep = "-";
423 List<String> nameStrings =
424 Arrays.asList(foreName, middleName, surName);
425 boolean firstAdded = false;
426 for(String partStr : nameStrings ){
427 if(null != partStr ) {
431 newStr.append(partStr);
435 // Now we add the dates. In theory could have dates with no name, but that is their problem.
436 boolean foundBirth = false;
437 if(null != birthDate) {
441 newStr.append(birthDate);
442 newStr.append(dateSep); // Put this in whether there is a death date or not
445 if(null != deathDate) {
450 newStr.append(dateSep);
452 newStr.append(deathDate);
454 return newStr.toString();
457 public static List<PersonTermGroup> getTermGroupInstance(String identifier) {
458 if (Tools.isBlank(identifier)) {
459 identifier = getGeneratedIdentifier();
461 List<PersonTermGroup> terms = new ArrayList<PersonTermGroup>();
462 PersonTermGroup term = new PersonTermGroup();
463 term.setTermDisplayName(identifier);
464 term.setTermName(identifier);
469 private static String getGeneratedIdentifier() {
470 return "id" + createIdentifier();
473 private static String createIdentifier() {
474 long identifier = System.currentTimeMillis() + random.nextInt();
475 return Long.toString(identifier);