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.jboss.resteasy.client.ClientResponse;
47 //import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.collectionspace.services.person.StructuredDateGroup;
53 * The Class PersonAuthorityClientUtils.
55 public class PersonAuthorityClientUtils {
57 /** The Constant logger. */
58 private static final Logger logger =
59 LoggerFactory.getLogger(PersonAuthorityClientUtils.class);
60 private static final ServiceRequestType READ_REQ = ServiceRequestType.READ;
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((String)res.getEntity());
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((String)res.getEntity());
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(
139 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, Map<String, String> personInfo,
194 List<PersonTermGroup> terms,
195 Map<String, List<String>> personRepeatablesInfo, String headerLabel){
196 PersonsCommon person = new PersonsCommon();
197 person.setInAuthority(inAuthority);
198 String shortId = personInfo.get(PersonJAXBSchema.SHORT_IDENTIFIER);
199 if (shortId == null || shortId.isEmpty()) {
200 throw new IllegalArgumentException("shortIdentifier cannot be null or empty");
202 person.setShortIdentifier(shortId);
205 List<String> values = null;
207 if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_DATE))!=null) {
208 StructuredDateGroup birthDate = new StructuredDateGroup();
209 birthDate.setDateDisplayDate(value);
210 person.setBirthDateGroup(birthDate);
212 if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_DATE))!=null) {
213 StructuredDateGroup deathDate = new StructuredDateGroup();
214 deathDate.setDateDisplayDate(value);
215 person.setDeathDateGroup(deathDate);
217 if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_PLACE))!=null)
218 person.setBirthPlace(value);
219 if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_PLACE))!=null)
220 person.setDeathPlace(value);
221 if((value = (String)personInfo.get(PersonJAXBSchema.GENDER))!=null)
222 person.setGender(value);
223 if((value = (String)personInfo.get(PersonJAXBSchema.BIO_NOTE))!=null)
224 person.setBioNote(value);
225 if((value = (String)personInfo.get(PersonJAXBSchema.NAME_NOTE))!=null)
226 person.setNameNote(value);
228 // Set values in the Term Information Group
229 PersonTermGroupList termList = new PersonTermGroupList();
230 if (terms == null || terms.isEmpty()) {
231 terms = getTermGroupInstance(getGeneratedIdentifier());
233 termList.getPersonTermGroup().addAll(terms);
234 person.setPersonTermGroupList(termList);
236 if (personRepeatablesInfo != null) {
237 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.GROUPS))!=null) {
238 GroupList groupsList = new GroupList();
239 List<String> groups = groupsList.getGroup();
240 groups.addAll(values);
241 person.setGroups(groupsList);
243 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.NATIONALITIES))!=null) {
244 NationalityList nationalitiesList = new NationalityList();
245 List<String> nationalities = nationalitiesList.getNationality();
246 nationalities.addAll(values);
247 person.setNationalities(nationalitiesList);
250 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.OCCUPATIONS))!=null) {
251 OccupationList occupationsList = new OccupationList();
252 List<String> occupations = occupationsList.getOccupation();
253 occupations.addAll(values);
254 person.setOccupations(occupationsList);
256 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.SCHOOLS_OR_STYLES))!=null) {
257 SchoolOrStyleList schoolOrStyleList = new SchoolOrStyleList();
258 List<String> schoolsOrStyles = schoolOrStyleList.getSchoolOrStyle();
259 schoolsOrStyles.addAll(values);
260 person.setSchoolsOrStyles(schoolOrStyleList);
265 PoxPayloadOut multipart = new PoxPayloadOut(PersonAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
266 PayloadOutputPart commonPart = multipart.addPart(person,
267 MediaType.APPLICATION_XML_TYPE);
268 commonPart.setLabel(headerLabel);
270 if(logger.isDebugEnabled()){
271 logger.debug("to be created, person common ", person, PersonsCommon.class);
278 * Creates the item in authority.
280 * @param vcsid the vcsid
281 * @param personAuthorityRefName the person authority ref name
282 * @param personMap the person map. PersonJAXBSchema.SHORT_IDENTIFIER is REQUIRED.
283 * @param client the client
286 public static String createItemInAuthority(String vcsid,
287 String personAuthorityRefName, Map<String,String> personMap,
288 List<PersonTermGroup> terms, Map<String, List<String>> personRepeatablesMap,
289 PersonAuthorityClient client ) {
290 // Expected status code: 201 Created
291 int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
292 // Type of service request being tested
293 ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
295 String displayName = "";
296 if (terms !=null && terms.size() > 0) {
297 displayName = terms.get(0).getTermDisplayName();
300 if(logger.isDebugEnabled()){
301 logger.debug("Creating item with display name: \"" + displayName
302 +"\" in personAuthority: \"" + vcsid +"\"");
304 PoxPayloadOut multipart =
305 createPersonInstance(vcsid, null /*personAuthorityRefName*/,
306 personMap, terms, personRepeatablesMap, client.getItemCommonPartName());
308 String result = null;
309 Response res = client.createItem(vcsid, multipart);
311 int statusCode = res.getStatus();
313 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
314 throw new RuntimeException("Could not create Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)
315 +"\" in personAuthority: \"" + vcsid //personAuthorityRefName
316 +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
318 if(statusCode != EXPECTED_STATUS_CODE) {
319 throw new RuntimeException("Unexpected Status when creating Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)
320 +"\" in personAuthority: \"" + vcsid /*personAuthorityRefName*/ +"\", Status:"+ statusCode);
323 result = extractId(res);
332 * Creates the personAuthority ref name.
334 * @param shortId the personAuthority shortIdentifier
335 * @param displaySuffix displayName to be appended, if non-null
339 public static String createPersonAuthRefName(String shortId, String displaySuffix) {
340 String refName = "urn:cspace:org.collectionspace.demo:personauthority:name("
342 if(displaySuffix!=null&&!displaySuffix.isEmpty())
343 refName += "'"+displaySuffix+"'";
349 * Creates the person ref name.
351 * @param personAuthRefName the person auth ref name
352 * @param shortId the person shortIdentifier
353 * @param displaySuffix displayName to be appended, if non-null
357 public static String createPersonRefName(
358 String personAuthRefName, String shortId, String displaySuffix) {
359 String refName = personAuthRefName+":person:name("+shortId+")";
360 if(displaySuffix!=null&&!displaySuffix.isEmpty())
361 refName += "'"+displaySuffix+"'";
372 public static String extractId(Response res) {
373 MultivaluedMap<String, Object> mvm = res.getMetadata();
374 // FIXME: This may throw an NPE if the Location: header isn't present
375 String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
376 if(logger.isDebugEnabled()){
377 logger.debug("extractId:uri=" + uri);
379 String[] segments = uri.split("/");
380 String id = segments[segments.length - 1];
381 if(logger.isDebugEnabled()){
382 logger.debug("id=" + id);
387 public static String extractId(ClientResponse<Response> res) {
388 MultivaluedMap<String, Object> mvm = res.getMetadata();
389 // FIXME: This may throw an NPE if the Location: header isn't present
390 String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
391 if(logger.isDebugEnabled()){
392 logger.debug("extractId:uri=" + uri);
394 String[] segments = uri.split("/");
395 String id = segments[segments.length - 1];
396 if(logger.isDebugEnabled()){
397 logger.debug("id=" + id);
404 * Returns an error message indicating that the status code returned by a
405 * specific call to a service does not fall within a set of valid status
406 * codes for that service.
408 * @param serviceRequestType A type of service request (e.g. CREATE, DELETE).
410 * @param statusCode The invalid status code that was returned in the response,
411 * from submitting that type of request to the service.
413 * @return An error message.
415 public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
416 return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
417 requestType.validStatusCodesAsString();
423 * Produces a default displayName from the basic name and dates fields.
424 * @see PersonDocumentModelHandler.prepareDefaultDisplayName() which
425 * duplicates this logic, until we define a service-general utils package
426 * that is neither client nor service specific.
432 * @return display name
434 public static String prepareDefaultDisplayName(
435 String foreName, String middleName, String surName,
436 String birthDate, String deathDate) {
437 StringBuilder newStr = new StringBuilder();
438 final String sep = " ";
439 final String dateSep = "-";
440 List<String> nameStrings =
441 Arrays.asList(foreName, middleName, surName);
442 boolean firstAdded = false;
443 for(String partStr : nameStrings ){
444 if(null != partStr ) {
448 newStr.append(partStr);
452 // Now we add the dates. In theory could have dates with no name, but that is their problem.
453 boolean foundBirth = false;
454 if(null != birthDate) {
458 newStr.append(birthDate);
459 newStr.append(dateSep); // Put this in whether there is a death date or not
462 if(null != deathDate) {
467 newStr.append(dateSep);
469 newStr.append(deathDate);
471 return newStr.toString();
474 public static List<PersonTermGroup> getTermGroupInstance(String identifier) {
475 if (Tools.isBlank(identifier)) {
476 identifier = getGeneratedIdentifier();
478 List<PersonTermGroup> terms = new ArrayList<PersonTermGroup>();
479 PersonTermGroup term = new PersonTermGroup();
480 term.setTermDisplayName(identifier);
481 term.setTermName(identifier);
486 private static String getGeneratedIdentifier() {
487 return "id" + new Date().getTime();