2 * PersonAuthorityClientUtils.java
\r
4 * {Purpose of This Class}
\r
6 * {Other Notes Relating to This Class (Optional)}
\r
9 * $LastChangedRevision: $
\r
10 * $LastChangedDate: $
\r
12 * This document is a part of the source code and related artifacts
\r
13 * for CollectionSpace, an open source collections management system
\r
14 * for museums and related institutions:
\r
16 * http://www.collectionspace.org
\r
17 * http://wiki.collectionspace.org
\r
19 * Copyright © 2009 {Contributing Institution}
\r
21 * Licensed under the Educational Community License (ECL), Version 2.0.
\r
22 * You may not use this file except in compliance with this License.
\r
24 * You may obtain a copy of the ECL 2.0 License at
\r
25 * https://source.collectionspace.org/collection-space/LICENSE.txt
\r
27 package org.collectionspace.services.client;
\r
31 import javax.ws.rs.core.MediaType;
\r
32 import javax.ws.rs.core.MultivaluedMap;
\r
33 import javax.ws.rs.core.Response;
\r
35 import org.collectionspace.services.PersonJAXBSchema;
\r
36 import org.collectionspace.services.client.test.ServiceRequestType;
\r
37 import org.collectionspace.services.common.api.Tools;
\r
38 import org.collectionspace.services.person.GroupList;
\r
39 import org.collectionspace.services.person.NationalityList;
\r
40 import org.collectionspace.services.person.OccupationList;
\r
41 import org.collectionspace.services.person.PersonTermGroup;
\r
42 import org.collectionspace.services.person.PersonTermGroupList;
\r
43 import org.collectionspace.services.person.PersonsCommon;
\r
44 import org.collectionspace.services.person.PersonauthoritiesCommon;
\r
45 import org.collectionspace.services.person.SchoolOrStyleList;
\r
46 import org.jboss.resteasy.client.ClientResponse;
\r
47 //import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
\r
48 import org.slf4j.Logger;
\r
49 import org.slf4j.LoggerFactory;
\r
50 import org.collectionspace.services.person.StructuredDateGroup;
\r
53 * The Class PersonAuthorityClientUtils.
\r
55 public class PersonAuthorityClientUtils {
\r
57 /** The Constant logger. */
\r
58 private static final Logger logger =
\r
59 LoggerFactory.getLogger(PersonAuthorityClientUtils.class);
\r
60 private static final ServiceRequestType READ_REQ = ServiceRequestType.READ;
\r
63 * @param csid the id of the PersonAuthority
\r
64 * @param client if null, creates a new client
\r
67 public static String getAuthorityRefName(String csid, PersonAuthorityClient client){
\r
68 if (client == null) {
\r
69 client = new PersonAuthorityClient();
\r
71 ClientResponse<String> res = client.read(csid);
\r
73 int statusCode = res.getStatus();
\r
74 if(!READ_REQ.isValidStatusCode(statusCode)
\r
75 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
\r
76 throw new RuntimeException("Invalid status code returned: "+statusCode);
\r
78 //FIXME: remove the following try catch once Aron fixes signatures
\r
80 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
\r
81 PersonauthoritiesCommon personAuthority =
\r
82 (PersonauthoritiesCommon) CollectionSpaceClientUtils.extractPart(input,
\r
83 client.getCommonPartName(), PersonauthoritiesCommon.class);
\r
84 if(personAuthority == null) {
\r
85 throw new RuntimeException("Null personAuthority returned from service.");
\r
87 return personAuthority.getRefName();
\r
88 } catch (Exception e) {
\r
89 throw new RuntimeException(e);
\r
92 res.releaseConnection();
\r
97 * @param csid the id of the PersonAuthority
\r
98 * @param client if null, creates a new client
\r
101 public static String getPersonRefName(String inAuthority, String csid, PersonAuthorityClient client){
\r
102 if ( client == null) {
\r
103 client = new PersonAuthorityClient();
\r
105 ClientResponse<String> res = client.readItem(inAuthority, csid);
\r
107 int statusCode = res.getStatus();
\r
108 if(!READ_REQ.isValidStatusCode(statusCode)
\r
109 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
\r
110 throw new RuntimeException("Invalid status code returned: "+statusCode);
\r
112 //FIXME: remove the following try catch once Aron fixes signatures
\r
114 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
\r
115 PersonsCommon person =
\r
116 (PersonsCommon) CollectionSpaceClientUtils.extractPart(input,
\r
117 client.getItemCommonPartName(), PersonsCommon.class);
\r
118 if (person == null) {
\r
119 throw new RuntimeException("Null person returned from service.");
\r
121 return person.getRefName();
\r
122 } catch (Exception e) {
\r
123 throw new RuntimeException(e);
\r
126 res.releaseConnection();
\r
131 * Creates the person authority instance.
\r
133 * @param displayName the display name
\r
134 * @param shortIdentifier the short Id
\r
135 * @param headerLabel the header label
\r
136 * @return the multipart output
\r
138 public static PoxPayloadOut createPersonAuthorityInstance(
\r
139 String displayName, String shortIdentifier, String headerLabel ) {
\r
140 PersonauthoritiesCommon personAuthority = new PersonauthoritiesCommon();
\r
141 personAuthority.setDisplayName(displayName);
\r
142 personAuthority.setShortIdentifier(shortIdentifier);
\r
143 //String refName = createPersonAuthRefName(shortIdentifier, displayName);
\r
144 //personAuthority.setRefName(refName);
\r
145 personAuthority.setVocabType("PersonAuthority");
\r
146 PoxPayloadOut multipart = new PoxPayloadOut(PersonAuthorityClient.SERVICE_PAYLOAD_NAME);
\r
147 PayloadOutputPart commonPart = multipart.addPart(personAuthority, MediaType.APPLICATION_XML_TYPE);
\r
148 commonPart.setLabel(headerLabel);
\r
150 if(logger.isDebugEnabled()){
\r
151 logger.debug("to be created, personAuthority common ",
\r
152 personAuthority, PersonauthoritiesCommon.class);
\r
159 * Creates a person instance.
\r
161 * @param inAuthority the owning authority
\r
162 * @param personAuthRefName the owning Authority ref name
\r
163 * @param personInfo the person info
\r
164 * @param headerLabel the header label
\r
165 * @return the multipart output
\r
167 public static PoxPayloadOut createPersonInstance(String inAuthority,
\r
168 String personAuthRefName,
\r
169 Map<String, String> personInfo,
\r
170 List<PersonTermGroup> terms,
\r
171 String headerLabel){
\r
172 if (terms == null || terms.isEmpty()) {
\r
173 terms = getTermGroupInstance(getGeneratedIdentifier());
\r
175 final Map<String, List<String>> EMPTY_PERSON_REPEATABLES_INFO =
\r
176 new HashMap<String, List<String>>();
\r
177 return createPersonInstance(inAuthority, null /*personAuthRefName*/,
\r
178 personInfo, terms, EMPTY_PERSON_REPEATABLES_INFO, headerLabel);
\r
182 * Creates a person instance.
\r
184 * @param inAuthority the owning authority
\r
185 * @param personAuthRefName the owning Authority ref name
\r
186 * @param personInfo the person info
\r
187 * @param terms a list of Person terms
\r
188 * @param personRepeatablesInfo names and values of repeatable scalar fields in the Person record
\r
189 * @param headerLabel the header label
\r
190 * @return the multipart output
\r
192 public static PoxPayloadOut createPersonInstance(String inAuthority,
\r
193 String personAuthRefName, Map<String, String> personInfo,
\r
194 List<PersonTermGroup> terms,
\r
195 Map<String, List<String>> personRepeatablesInfo, String headerLabel){
\r
196 PersonsCommon person = new PersonsCommon();
\r
197 person.setInAuthority(inAuthority);
\r
198 String shortId = personInfo.get(PersonJAXBSchema.SHORT_IDENTIFIER);
\r
199 if (shortId == null || shortId.isEmpty()) {
\r
200 throw new IllegalArgumentException("shortIdentifier cannot be null or empty");
\r
202 person.setShortIdentifier(shortId);
\r
205 List<String> values = null;
\r
207 if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_DATE))!=null) {
\r
208 StructuredDateGroup birthDate = new StructuredDateGroup();
\r
209 birthDate.setDateDisplayDate(value);
\r
210 person.setBirthDateGroup(birthDate);
\r
212 if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_DATE))!=null) {
\r
213 StructuredDateGroup deathDate = new StructuredDateGroup();
\r
214 deathDate.setDateDisplayDate(value);
\r
215 person.setDeathDateGroup(deathDate);
\r
217 if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_PLACE))!=null)
\r
218 person.setBirthPlace(value);
\r
219 if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_PLACE))!=null)
\r
220 person.setDeathPlace(value);
\r
221 if((value = (String)personInfo.get(PersonJAXBSchema.GENDER))!=null)
\r
222 person.setGender(value);
\r
223 if((value = (String)personInfo.get(PersonJAXBSchema.BIO_NOTE))!=null)
\r
224 person.setBioNote(value);
\r
225 if((value = (String)personInfo.get(PersonJAXBSchema.NAME_NOTE))!=null)
\r
226 person.setNameNote(value);
\r
228 // Set values in the Term Information Group
\r
229 PersonTermGroupList termList = new PersonTermGroupList();
\r
230 if (terms == null || terms.isEmpty()) {
\r
231 terms = getTermGroupInstance(getGeneratedIdentifier());
\r
233 termList.getPersonTermGroup().addAll(terms);
\r
234 person.setPersonTermGroupList(termList);
\r
236 if (personRepeatablesInfo != null) {
\r
237 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.GROUPS))!=null) {
\r
238 GroupList groupsList = new GroupList();
\r
239 List<String> groups = groupsList.getGroup();
\r
240 groups.addAll(values);
\r
241 person.setGroups(groupsList);
\r
243 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.NATIONALITIES))!=null) {
\r
244 NationalityList nationalitiesList = new NationalityList();
\r
245 List<String> nationalities = nationalitiesList.getNationality();
\r
246 nationalities.addAll(values);
\r
247 person.setNationalities(nationalitiesList);
\r
250 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.OCCUPATIONS))!=null) {
\r
251 OccupationList occupationsList = new OccupationList();
\r
252 List<String> occupations = occupationsList.getOccupation();
\r
253 occupations.addAll(values);
\r
254 person.setOccupations(occupationsList);
\r
256 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.SCHOOLS_OR_STYLES))!=null) {
\r
257 SchoolOrStyleList schoolOrStyleList = new SchoolOrStyleList();
\r
258 List<String> schoolsOrStyles = schoolOrStyleList.getSchoolOrStyle();
\r
259 schoolsOrStyles.addAll(values);
\r
260 person.setSchoolsOrStyles(schoolOrStyleList);
\r
265 PoxPayloadOut multipart = new PoxPayloadOut(PersonAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
\r
266 PayloadOutputPart commonPart = multipart.addPart(person,
\r
267 MediaType.APPLICATION_XML_TYPE);
\r
268 commonPart.setLabel(headerLabel);
\r
270 if(logger.isDebugEnabled()){
\r
271 logger.debug("to be created, person common ", person, PersonsCommon.class);
\r
278 * Creates the item in authority.
\r
280 * @param vcsid the vcsid
\r
281 * @param personAuthorityRefName the person authority ref name
\r
282 * @param personMap the person map. PersonJAXBSchema.SHORT_IDENTIFIER is REQUIRED.
\r
283 * @param client the client
\r
284 * @return the string
\r
286 public static String createItemInAuthority(String vcsid,
\r
287 String personAuthorityRefName, Map<String,String> personMap,
\r
288 List<PersonTermGroup> terms, Map<String, List<String>> personRepeatablesMap,
\r
289 PersonAuthorityClient client ) {
\r
290 // Expected status code: 201 Created
\r
291 int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
\r
292 // Type of service request being tested
\r
293 ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
\r
295 String displayName = "";
\r
296 if (terms !=null && terms.size() > 0) {
\r
297 displayName = terms.get(0).getTermDisplayName();
\r
300 if(logger.isDebugEnabled()){
\r
301 logger.debug("Creating item with display name: \"" + displayName
\r
302 +"\" in personAuthority: \"" + vcsid +"\"");
\r
304 PoxPayloadOut multipart =
\r
305 createPersonInstance(vcsid, null /*personAuthorityRefName*/,
\r
306 personMap, terms, personRepeatablesMap, client.getItemCommonPartName());
\r
308 String result = null;
\r
309 ClientResponse<Response> res = client.createItem(vcsid, multipart);
\r
311 int statusCode = res.getStatus();
\r
313 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
\r
314 throw new RuntimeException("Could not create Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)
\r
315 +"\" in personAuthority: \"" + vcsid //personAuthorityRefName
\r
316 +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
\r
318 if(statusCode != EXPECTED_STATUS_CODE) {
\r
319 throw new RuntimeException("Unexpected Status when creating Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)
\r
320 +"\" in personAuthority: \"" + vcsid /*personAuthorityRefName*/ +"\", Status:"+ statusCode);
\r
323 result = extractId(res);
\r
325 res.releaseConnection();
\r
332 * Creates the personAuthority ref name.
\r
334 * @param shortId the personAuthority shortIdentifier
\r
335 * @param displaySuffix displayName to be appended, if non-null
\r
336 * @return the string
\r
339 public static String createPersonAuthRefName(String shortId, String displaySuffix) {
\r
340 String refName = "urn:cspace:org.collectionspace.demo:personauthority:name("
\r
342 if(displaySuffix!=null&&!displaySuffix.isEmpty())
\r
343 refName += "'"+displaySuffix+"'";
\r
349 * Creates the person ref name.
\r
351 * @param personAuthRefName the person auth ref name
\r
352 * @param shortId the person shortIdentifier
\r
353 * @param displaySuffix displayName to be appended, if non-null
\r
354 * @return the string
\r
357 public static String createPersonRefName(
\r
358 String personAuthRefName, String shortId, String displaySuffix) {
\r
359 String refName = personAuthRefName+":person:name("+shortId+")";
\r
360 if(displaySuffix!=null&&!displaySuffix.isEmpty())
\r
361 refName += "'"+displaySuffix+"'";
\r
369 * @param res the res
\r
370 * @return the string
\r
372 public static String extractId(ClientResponse<Response> res) {
\r
373 MultivaluedMap<String, Object> mvm = res.getMetadata();
\r
374 // FIXME: This may throw an NPE if the Location: header isn't present
\r
375 String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
\r
376 if(logger.isDebugEnabled()){
\r
377 logger.debug("extractId:uri=" + uri);
\r
379 String[] segments = uri.split("/");
\r
380 String id = segments[segments.length - 1];
\r
381 if(logger.isDebugEnabled()){
\r
382 logger.debug("id=" + id);
\r
388 * Returns an error message indicating that the status code returned by a
\r
389 * specific call to a service does not fall within a set of valid status
\r
390 * codes for that service.
\r
392 * @param serviceRequestType A type of service request (e.g. CREATE, DELETE).
\r
394 * @param statusCode The invalid status code that was returned in the response,
\r
395 * from submitting that type of request to the service.
\r
397 * @return An error message.
\r
399 public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
\r
400 return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
\r
401 requestType.validStatusCodesAsString();
\r
407 * Produces a default displayName from the basic name and dates fields.
\r
408 * @see PersonDocumentModelHandler.prepareDefaultDisplayName() which
\r
409 * duplicates this logic, until we define a service-general utils package
\r
410 * that is neither client nor service specific.
\r
412 * @param middleName
\r
416 * @return display name
\r
418 public static String prepareDefaultDisplayName(
\r
419 String foreName, String middleName, String surName,
\r
420 String birthDate, String deathDate) {
\r
421 StringBuilder newStr = new StringBuilder();
\r
422 final String sep = " ";
\r
423 final String dateSep = "-";
\r
424 List<String> nameStrings =
\r
425 Arrays.asList(foreName, middleName, surName);
\r
426 boolean firstAdded = false;
\r
427 for(String partStr : nameStrings ){
\r
428 if(null != partStr ) {
\r
430 newStr.append(sep);
\r
432 newStr.append(partStr);
\r
436 // Now we add the dates. In theory could have dates with no name, but that is their problem.
\r
437 boolean foundBirth = false;
\r
438 if(null != birthDate) {
\r
440 newStr.append(sep);
\r
442 newStr.append(birthDate);
\r
443 newStr.append(dateSep); // Put this in whether there is a death date or not
\r
446 if(null != deathDate) {
\r
449 newStr.append(sep);
\r
451 newStr.append(dateSep);
\r
453 newStr.append(deathDate);
\r
455 return newStr.toString();
\r
458 public static List<PersonTermGroup> getTermGroupInstance(String identifier) {
\r
459 if (Tools.isBlank(identifier)) {
\r
460 identifier = getGeneratedIdentifier();
\r
462 List<PersonTermGroup> terms = new ArrayList<PersonTermGroup>();
\r
463 PersonTermGroup term = new PersonTermGroup();
\r
464 term.setTermDisplayName(identifier);
\r
465 term.setTermName(identifier);
\r
470 private static String getGeneratedIdentifier() {
\r
471 return "id" + new Date().getTime();
\r