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, PersonAuthorityClient client) throws Exception{
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
102 public static String getPersonRefName(String inAuthority, String csid, PersonAuthorityClient client) throws Exception{
103 if ( client == null) {
104 client = new PersonAuthorityClient();
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(PersonAuthorityClient.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 * Creates a person instance.
161 * @param inAuthority the owning authority
162 * @param personAuthRefName the owning Authority ref name
163 * @param personInfo the person info
164 * @param headerLabel the header label
165 * @return the multipart output
167 public static PoxPayloadOut createPersonInstance(String inAuthority,
168 String personAuthRefName,
169 Map<String, String> personInfo,
170 List<PersonTermGroup> terms,
172 if (terms == null || terms.isEmpty()) {
173 terms = getTermGroupInstance(getGeneratedIdentifier());
175 final Map<String, List<String>> EMPTY_PERSON_REPEATABLES_INFO =
176 new HashMap<String, List<String>>();
177 return createPersonInstance(inAuthority, null /*personAuthRefName*/,
178 personInfo, terms, EMPTY_PERSON_REPEATABLES_INFO, headerLabel);
182 * Creates a person instance.
184 * @param inAuthority the owning authority
185 * @param personAuthRefName the owning Authority ref name
186 * @param personInfo the person info
187 * @param terms a list of Person terms
188 * @param personRepeatablesInfo names and values of repeatable scalar fields in the Person record
189 * @param headerLabel the header label
190 * @return the multipart output
192 public static PoxPayloadOut createPersonInstance(String inAuthority,
193 String personAuthRefName,
194 Map<String, String> personInfo,
195 List<PersonTermGroup> terms,
196 Map<String, List<String>> personRepeatablesInfo,
198 PersonsCommon person = new PersonsCommon();
199 person.setInAuthority(inAuthority);
200 String shortId = personInfo.get(PersonJAXBSchema.SHORT_IDENTIFIER);
201 if (shortId == null || shortId.isEmpty()) {
202 throw new IllegalArgumentException("shortIdentifier cannot be null or empty");
204 person.setShortIdentifier(shortId);
207 List<String> values = null;
209 if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_DATE))!=null) {
210 StructuredDateGroup birthDate = new StructuredDateGroup();
211 birthDate.setDateDisplayDate(value);
212 person.setBirthDateGroup(birthDate);
214 if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_DATE))!=null) {
215 StructuredDateGroup deathDate = new StructuredDateGroup();
216 deathDate.setDateDisplayDate(value);
217 person.setDeathDateGroup(deathDate);
219 if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_PLACE))!=null)
220 person.setBirthPlace(value);
221 if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_PLACE))!=null)
222 person.setDeathPlace(value);
223 if((value = (String)personInfo.get(PersonJAXBSchema.GENDER))!=null)
224 person.setGender(value);
225 if((value = (String)personInfo.get(PersonJAXBSchema.BIO_NOTE))!=null)
226 person.setBioNote(value);
227 if((value = (String)personInfo.get(PersonJAXBSchema.NAME_NOTE))!=null)
228 person.setNameNote(value);
230 // Set values in the Term Information Group
231 PersonTermGroupList termList = new PersonTermGroupList();
232 if (terms == null || terms.isEmpty()) {
233 terms = getTermGroupInstance(getGeneratedIdentifier());
235 termList.getPersonTermGroup().addAll(terms);
236 person.setPersonTermGroupList(termList);
238 if (personRepeatablesInfo != null) {
239 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.GROUPS))!=null) {
240 GroupList groupsList = new GroupList();
241 List<String> groups = groupsList.getGroup();
242 groups.addAll(values);
243 person.setGroups(groupsList);
245 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.NATIONALITIES))!=null) {
246 NationalityList nationalitiesList = new NationalityList();
247 List<String> nationalities = nationalitiesList.getNationality();
248 nationalities.addAll(values);
249 person.setNationalities(nationalitiesList);
252 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.OCCUPATIONS))!=null) {
253 OccupationList occupationsList = new OccupationList();
254 List<String> occupations = occupationsList.getOccupation();
255 occupations.addAll(values);
256 person.setOccupations(occupationsList);
258 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.SCHOOLS_OR_STYLES))!=null) {
259 SchoolOrStyleList schoolOrStyleList = new SchoolOrStyleList();
260 List<String> schoolsOrStyles = schoolOrStyleList.getSchoolOrStyle();
261 schoolsOrStyles.addAll(values);
262 person.setSchoolsOrStyles(schoolOrStyleList);
267 PoxPayloadOut multipart = new PoxPayloadOut(PersonAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
268 PayloadOutputPart commonPart = multipart.addPart(person,
269 MediaType.APPLICATION_XML_TYPE);
270 commonPart.setLabel(headerLabel);
272 if(logger.isDebugEnabled()){
273 logger.debug("to be created, person common ", person, PersonsCommon.class);
280 * Creates the item in authority.
282 * @param vcsid the vcsid
283 * @param personAuthorityRefName the person authority ref name
284 * @param personMap the person map. PersonJAXBSchema.SHORT_IDENTIFIER is REQUIRED.
285 * @param client the client
288 public static String createItemInAuthority(String vcsid,
289 String personAuthorityRefName, Map<String,String> personMap,
290 List<PersonTermGroup> terms, Map<String, List<String>> personRepeatablesMap,
291 PersonAuthorityClient client ) {
292 // Expected status code: 201 Created
293 int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
294 // Type of service request being tested
295 ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
297 String displayName = "";
298 if (terms !=null && terms.size() > 0) {
299 displayName = terms.get(0).getTermDisplayName();
302 if(logger.isDebugEnabled()){
303 logger.debug("Creating item with display name: \"" + displayName
304 +"\" in personAuthority: \"" + vcsid +"\"");
306 PoxPayloadOut multipart =
307 createPersonInstance(vcsid, null /*personAuthorityRefName*/,
308 personMap, terms, personRepeatablesMap, client.getItemCommonPartName());
310 String result = null;
311 Response res = client.createItem(vcsid, multipart);
313 int statusCode = res.getStatus();
315 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
316 throw new RuntimeException("Could not create Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)
317 +"\" in personAuthority: \"" + vcsid //personAuthorityRefName
318 +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
320 if(statusCode != EXPECTED_STATUS_CODE) {
321 throw new RuntimeException("Unexpected Status when creating Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)
322 +"\" in personAuthority: \"" + vcsid /*personAuthorityRefName*/ +"\", Status:"+ statusCode);
325 result = extractId(res);
334 * Creates the personAuthority ref name.
336 * @param shortId the personAuthority shortIdentifier
337 * @param displaySuffix displayName to be appended, if non-null
341 public static String createPersonAuthRefName(String shortId, String displaySuffix) {
342 String refName = "urn:cspace:org.collectionspace.demo:personauthority:name("
344 if(displaySuffix!=null&&!displaySuffix.isEmpty())
345 refName += "'"+displaySuffix+"'";
351 * Creates the person ref name.
353 * @param personAuthRefName the person auth ref name
354 * @param shortId the person shortIdentifier
355 * @param displaySuffix displayName to be appended, if non-null
359 public static String createPersonRefName(
360 String personAuthRefName, String shortId, String displaySuffix) {
361 String refName = personAuthRefName+":person:name("+shortId+")";
362 if(displaySuffix!=null&&!displaySuffix.isEmpty())
363 refName += "'"+displaySuffix+"'";
374 public static String extractId(Response res) {
375 MultivaluedMap<String, Object> mvm = res.getMetadata();
376 // FIXME: This may throw an NPE if the Location: header isn't present
377 String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
378 if(logger.isDebugEnabled()){
379 logger.debug("extractId:uri=" + uri);
381 String[] segments = uri.split("/");
382 String id = segments[segments.length - 1];
383 if(logger.isDebugEnabled()){
384 logger.debug("id=" + id);
390 * Returns an error message indicating that the status code returned by a
391 * specific call to a service does not fall within a set of valid status
392 * codes for that service.
394 * @param serviceRequestType A type of service request (e.g. CREATE, DELETE).
396 * @param statusCode The invalid status code that was returned in the response,
397 * from submitting that type of request to the service.
399 * @return An error message.
401 public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
402 return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
403 requestType.validStatusCodesAsString();
409 * Produces a default displayName from the basic name and dates fields.
410 * @see PersonDocumentModelHandler.prepareDefaultDisplayName() which
411 * duplicates this logic, until we define a service-general utils package
412 * that is neither client nor service specific.
418 * @return display name
420 public static String prepareDefaultDisplayName(
421 String foreName, String middleName, String surName,
422 String birthDate, String deathDate) {
423 StringBuilder newStr = new StringBuilder();
424 final String sep = " ";
425 final String dateSep = "-";
426 List<String> nameStrings =
427 Arrays.asList(foreName, middleName, surName);
428 boolean firstAdded = false;
429 for(String partStr : nameStrings ){
430 if(null != partStr ) {
434 newStr.append(partStr);
438 // Now we add the dates. In theory could have dates with no name, but that is their problem.
439 boolean foundBirth = false;
440 if(null != birthDate) {
444 newStr.append(birthDate);
445 newStr.append(dateSep); // Put this in whether there is a death date or not
448 if(null != deathDate) {
453 newStr.append(dateSep);
455 newStr.append(deathDate);
457 return newStr.toString();
460 public static List<PersonTermGroup> getTermGroupInstance(String identifier) {
461 if (Tools.isBlank(identifier)) {
462 identifier = getGeneratedIdentifier();
464 List<PersonTermGroup> terms = new ArrayList<PersonTermGroup>();
465 PersonTermGroup term = new PersonTermGroup();
466 term.setTermDisplayName(identifier);
467 term.setTermName(identifier);
472 private static String getGeneratedIdentifier() {
473 return "id" + createIdentifier();
476 private static String createIdentifier() {
477 long identifier = System.currentTimeMillis() + random.nextInt();
478 return Long.toString(identifier);