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;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
52 * The Class PersonAuthorityClientUtils.
54 public class PersonAuthorityClientUtils {
56 /** The Constant logger. */
57 private static final Logger logger =
58 LoggerFactory.getLogger(PersonAuthorityClientUtils.class);
59 private static final ServiceRequestType READ_REQ = ServiceRequestType.READ;
60 static private final Random random = new Random(System.currentTimeMillis());
63 * @param csid the id of the PersonAuthority
64 * @param client if null, creates a new client
67 public static String getAuthorityRefName(String csid, PersonAuthorityClient client){
69 client = new PersonAuthorityClient();
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
101 public static String getPersonRefName(String inAuthority, String csid, PersonAuthorityClient client){
102 if ( client == null) {
103 client = new PersonAuthorityClient();
105 Response res = client.readItem(inAuthority, csid);
107 int statusCode = res.getStatus();
108 if(!READ_REQ.isValidStatusCode(statusCode)
109 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
110 throw new RuntimeException("Invalid status code returned: "+statusCode);
112 //FIXME: remove the following try catch once Aron fixes signatures
114 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
115 PersonsCommon person =
116 (PersonsCommon) CollectionSpaceClientUtils.extractPart(input,
117 client.getItemCommonPartName(), PersonsCommon.class);
118 if (person == null) {
119 throw new RuntimeException("Null person returned from service.");
121 return person.getRefName();
122 } catch (Exception e) {
123 throw new RuntimeException(e);
131 * Creates the person authority instance.
133 * @param displayName the display name
134 * @param shortIdentifier the short Id
135 * @param headerLabel the header label
136 * @return the multipart output
138 public static PoxPayloadOut createPersonAuthorityInstance(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,
193 Map<String, String> personInfo,
194 List<PersonTermGroup> terms,
195 Map<String, List<String>> personRepeatablesInfo,
197 PersonsCommon person = new PersonsCommon();
198 person.setInAuthority(inAuthority);
199 String shortId = personInfo.get(PersonJAXBSchema.SHORT_IDENTIFIER);
200 if (shortId == null || shortId.isEmpty()) {
201 throw new IllegalArgumentException("shortIdentifier cannot be null or empty");
203 person.setShortIdentifier(shortId);
206 List<String> values = null;
208 if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_DATE))!=null) {
209 StructuredDateGroup birthDate = new StructuredDateGroup();
210 birthDate.setDateDisplayDate(value);
211 person.setBirthDateGroup(birthDate);
213 if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_DATE))!=null) {
214 StructuredDateGroup deathDate = new StructuredDateGroup();
215 deathDate.setDateDisplayDate(value);
216 person.setDeathDateGroup(deathDate);
218 if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_PLACE))!=null)
219 person.setBirthPlace(value);
220 if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_PLACE))!=null)
221 person.setDeathPlace(value);
222 if((value = (String)personInfo.get(PersonJAXBSchema.GENDER))!=null)
223 person.setGender(value);
224 if((value = (String)personInfo.get(PersonJAXBSchema.BIO_NOTE))!=null)
225 person.setBioNote(value);
226 if((value = (String)personInfo.get(PersonJAXBSchema.NAME_NOTE))!=null)
227 person.setNameNote(value);
229 // Set values in the Term Information Group
230 PersonTermGroupList termList = new PersonTermGroupList();
231 if (terms == null || terms.isEmpty()) {
232 terms = getTermGroupInstance(getGeneratedIdentifier());
234 termList.getPersonTermGroup().addAll(terms);
235 person.setPersonTermGroupList(termList);
237 if (personRepeatablesInfo != null) {
238 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.GROUPS))!=null) {
239 GroupList groupsList = new GroupList();
240 List<String> groups = groupsList.getGroup();
241 groups.addAll(values);
242 person.setGroups(groupsList);
244 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.NATIONALITIES))!=null) {
245 NationalityList nationalitiesList = new NationalityList();
246 List<String> nationalities = nationalitiesList.getNationality();
247 nationalities.addAll(values);
248 person.setNationalities(nationalitiesList);
251 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.OCCUPATIONS))!=null) {
252 OccupationList occupationsList = new OccupationList();
253 List<String> occupations = occupationsList.getOccupation();
254 occupations.addAll(values);
255 person.setOccupations(occupationsList);
257 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.SCHOOLS_OR_STYLES))!=null) {
258 SchoolOrStyleList schoolOrStyleList = new SchoolOrStyleList();
259 List<String> schoolsOrStyles = schoolOrStyleList.getSchoolOrStyle();
260 schoolsOrStyles.addAll(values);
261 person.setSchoolsOrStyles(schoolOrStyleList);
266 PoxPayloadOut multipart = new PoxPayloadOut(PersonAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
267 PayloadOutputPart commonPart = multipart.addPart(person,
268 MediaType.APPLICATION_XML_TYPE);
269 commonPart.setLabel(headerLabel);
271 if(logger.isDebugEnabled()){
272 logger.debug("to be created, person common ", person, PersonsCommon.class);
279 * Creates the item in authority.
281 * @param vcsid the vcsid
282 * @param personAuthorityRefName the person authority ref name
283 * @param personMap the person map. PersonJAXBSchema.SHORT_IDENTIFIER is REQUIRED.
284 * @param client the client
287 public static String createItemInAuthority(String vcsid,
288 String personAuthorityRefName, Map<String,String> personMap,
289 List<PersonTermGroup> terms, Map<String, List<String>> personRepeatablesMap,
290 PersonAuthorityClient client ) {
291 // Expected status code: 201 Created
292 int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
293 // Type of service request being tested
294 ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
296 String displayName = "";
297 if (terms !=null && terms.size() > 0) {
298 displayName = terms.get(0).getTermDisplayName();
301 if(logger.isDebugEnabled()){
302 logger.debug("Creating item with display name: \"" + displayName
303 +"\" in personAuthority: \"" + vcsid +"\"");
305 PoxPayloadOut multipart =
306 createPersonInstance(vcsid, null /*personAuthorityRefName*/,
307 personMap, terms, personRepeatablesMap, client.getItemCommonPartName());
309 String result = null;
310 Response res = client.createItem(vcsid, multipart);
312 int statusCode = res.getStatus();
314 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
315 throw new RuntimeException("Could not create Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)
316 +"\" in personAuthority: \"" + vcsid //personAuthorityRefName
317 +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
319 if(statusCode != EXPECTED_STATUS_CODE) {
320 throw new RuntimeException("Unexpected Status when creating Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)
321 +"\" in personAuthority: \"" + vcsid /*personAuthorityRefName*/ +"\", Status:"+ statusCode);
324 result = extractId(res);
333 * Creates the personAuthority ref name.
335 * @param shortId the personAuthority shortIdentifier
336 * @param displaySuffix displayName to be appended, if non-null
340 public static String createPersonAuthRefName(String shortId, String displaySuffix) {
341 String refName = "urn:cspace:org.collectionspace.demo:personauthority:name("
343 if(displaySuffix!=null&&!displaySuffix.isEmpty())
344 refName += "'"+displaySuffix+"'";
350 * Creates the person ref name.
352 * @param personAuthRefName the person auth ref name
353 * @param shortId the person shortIdentifier
354 * @param displaySuffix displayName to be appended, if non-null
358 public static String createPersonRefName(
359 String personAuthRefName, String shortId, String displaySuffix) {
360 String refName = personAuthRefName+":person:name("+shortId+")";
361 if(displaySuffix!=null&&!displaySuffix.isEmpty())
362 refName += "'"+displaySuffix+"'";
373 public static String extractId(Response res) {
374 MultivaluedMap<String, Object> mvm = res.getMetadata();
375 // FIXME: This may throw an NPE if the Location: header isn't present
376 String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
377 if(logger.isDebugEnabled()){
378 logger.debug("extractId:uri=" + uri);
380 String[] segments = uri.split("/");
381 String id = segments[segments.length - 1];
382 if(logger.isDebugEnabled()){
383 logger.debug("id=" + id);
389 * Returns an error message indicating that the status code returned by a
390 * specific call to a service does not fall within a set of valid status
391 * codes for that service.
393 * @param serviceRequestType A type of service request (e.g. CREATE, DELETE).
395 * @param statusCode The invalid status code that was returned in the response,
396 * from submitting that type of request to the service.
398 * @return An error message.
400 public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
401 return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
402 requestType.validStatusCodesAsString();
408 * Produces a default displayName from the basic name and dates fields.
409 * @see PersonDocumentModelHandler.prepareDefaultDisplayName() which
410 * duplicates this logic, until we define a service-general utils package
411 * that is neither client nor service specific.
417 * @return display name
419 public static String prepareDefaultDisplayName(
420 String foreName, String middleName, String surName,
421 String birthDate, String deathDate) {
422 StringBuilder newStr = new StringBuilder();
423 final String sep = " ";
424 final String dateSep = "-";
425 List<String> nameStrings =
426 Arrays.asList(foreName, middleName, surName);
427 boolean firstAdded = false;
428 for(String partStr : nameStrings ){
429 if(null != partStr ) {
433 newStr.append(partStr);
437 // Now we add the dates. In theory could have dates with no name, but that is their problem.
438 boolean foundBirth = false;
439 if(null != birthDate) {
443 newStr.append(birthDate);
444 newStr.append(dateSep); // Put this in whether there is a death date or not
447 if(null != deathDate) {
452 newStr.append(dateSep);
454 newStr.append(deathDate);
456 return newStr.toString();
459 public static List<PersonTermGroup> getTermGroupInstance(String identifier) {
460 if (Tools.isBlank(identifier)) {
461 identifier = getGeneratedIdentifier();
463 List<PersonTermGroup> terms = new ArrayList<PersonTermGroup>();
464 PersonTermGroup term = new PersonTermGroup();
465 term.setTermDisplayName(identifier);
466 term.setTermName(identifier);
471 private static String getGeneratedIdentifier() {
472 return "id" + createIdentifier();
475 private static String createIdentifier() {
476 long identifier = System.currentTimeMillis() + random.nextInt();
477 return Long.toString(identifier);