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
29 import java.util.ArrayList;
\r
30 import java.util.Arrays;
\r
31 import java.util.HashMap;
\r
32 import java.util.List;
\r
33 import java.util.Map;
\r
35 import javax.ws.rs.core.MediaType;
\r
36 import javax.ws.rs.core.MultivaluedMap;
\r
37 import javax.ws.rs.core.Response;
\r
39 import org.collectionspace.services.PersonJAXBSchema;
\r
40 import org.collectionspace.services.client.test.ServiceRequestType;
\r
41 import org.collectionspace.services.person.GroupList;
\r
42 import org.collectionspace.services.person.NationalityList;
\r
43 import org.collectionspace.services.person.OccupationList;
\r
44 import org.collectionspace.services.person.PersonsCommon;
\r
45 import org.collectionspace.services.person.PersonauthoritiesCommon;
\r
46 import org.collectionspace.services.person.SchoolOrStyleList;
\r
47 import org.jboss.resteasy.client.ClientResponse;
\r
48 //import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
\r
49 import org.slf4j.Logger;
\r
50 import org.slf4j.LoggerFactory;
\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 String headerLabel){
\r
171 final Map<String, List<String>> EMPTY_PERSON_REPEATABLES_INFO =
\r
172 new HashMap<String, List<String>>();
\r
173 return createPersonInstance(inAuthority, personAuthRefName, personInfo,
\r
174 EMPTY_PERSON_REPEATABLES_INFO, headerLabel);
\r
178 * Creates a person instance.
\r
180 * @param inAuthority the owning authority
\r
181 * @param personAuthRefName the owning Authority ref name
\r
182 * @param personInfo the person info
\r
183 * @param personRepeatablesInfo names and values of repeatable scalar fields in the Person record
\r
184 * @param headerLabel the header label
\r
185 * @return the multipart output
\r
187 public static PoxPayloadOut createPersonInstance(String inAuthority,
\r
188 String personAuthRefName, Map<String, String> personInfo,
\r
189 Map<String, List<String>> personRepeatablesInfo, String headerLabel){
\r
190 PersonsCommon person = new PersonsCommon();
\r
191 person.setInAuthority(inAuthority);
\r
192 String shortId = personInfo.get(PersonJAXBSchema.SHORT_IDENTIFIER);
\r
193 if (shortId == null || shortId.isEmpty()) {
\r
194 throw new IllegalArgumentException("shortIdentifier cannot be null or empty");
\r
196 person.setShortIdentifier(shortId);
\r
199 // If the 'DISPLAY_NAME_COMPUTED' property is null or empty then
\r
200 // we'll assume that the service consumer wants us to compute the
\r
201 // display name. Otherwise, we'll parse the value with the Boolean class.
\r
203 String booleanStr = personInfo.get(PersonJAXBSchema.DISPLAY_NAME_COMPUTED);
\r
204 boolean displayNameComputed = true;
\r
205 if (booleanStr != null && booleanStr.length() > 0) {
\r
206 displayNameComputed = Boolean.parseBoolean(booleanStr);
\r
208 person.setDisplayNameComputed(displayNameComputed);
\r
210 String displayName = personInfo.get(PersonJAXBSchema.DISPLAY_NAME);
\r
211 person.setDisplayName(displayName);
\r
212 if (displayNameComputed == false && displayName == null) {
\r
213 throw new IllegalArgumentException("displayName cannot be null when displayComputed is 'false'");
\r
216 booleanStr = personInfo.get(PersonJAXBSchema.SHORT_DISPLAY_NAME_COMPUTED);
\r
217 boolean shortDisplayNameComputed = true;
\r
218 if (booleanStr != null && booleanStr.length() > 0) {
\r
219 shortDisplayNameComputed = Boolean.parseBoolean(booleanStr);
\r
221 person.setShortDisplayNameComputed(shortDisplayNameComputed);
\r
223 String shortDisplayName = personInfo.get(PersonJAXBSchema.SHORT_DISPLAY_NAME);
\r
224 person.setShortDisplayName(shortDisplayName);
\r
225 if (shortDisplayNameComputed == false && shortDisplayName == null) {
\r
226 throw new IllegalArgumentException("shortDisplayName cannot be null when shortDisplayComputed is 'false'");
\r
229 String refName = createPersonRefName(personAuthRefName, shortId, displayName);
\r
230 person.setRefName(refName);
\r
233 List<String> values = null;
\r
234 if((value = (String)personInfo.get(PersonJAXBSchema.FORE_NAME))!=null) //FIXME: REM - I don't think we need to check for null -null is a valid value and won't cause any problems.
\r
235 person.setForeName(value);
\r
236 if((value = (String)personInfo.get(PersonJAXBSchema.MIDDLE_NAME))!=null)
\r
237 person.setMiddleName(value);
\r
238 if((value = (String)personInfo.get(PersonJAXBSchema.SUR_NAME))!=null)
\r
239 person.setSurName(value);
\r
240 if((value = (String)personInfo.get(PersonJAXBSchema.INITIALS))!=null)
\r
241 person.setInitials(value);
\r
242 if((value = (String)personInfo.get(PersonJAXBSchema.SALUTATIONS))!=null)
\r
243 person.setSalutation(value);
\r
244 if((value = (String)personInfo.get(PersonJAXBSchema.TITLE))!=null)
\r
245 person.setTitle(value);
\r
246 if((value = (String)personInfo.get(PersonJAXBSchema.NAME_ADDITIONS))!=null)
\r
247 person.setNameAdditions(value);
\r
248 if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_DATE))!=null)
\r
249 person.setBirthDate(value);
\r
250 if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_DATE))!=null)
\r
251 person.setDeathDate(value);
\r
252 if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_PLACE))!=null)
\r
253 person.setBirthPlace(value);
\r
254 if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_PLACE))!=null)
\r
255 person.setDeathPlace(value);
\r
256 if((value = (String)personInfo.get(PersonJAXBSchema.GENDER))!=null)
\r
257 person.setGender(value);
\r
258 if((value = (String)personInfo.get(PersonJAXBSchema.BIO_NOTE))!=null)
\r
259 person.setBioNote(value);
\r
260 if((value = (String)personInfo.get(PersonJAXBSchema.NAME_NOTE))!=null)
\r
261 person.setNameNote(value);
\r
263 if (personRepeatablesInfo != null) {
\r
264 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.GROUPS))!=null) {
\r
265 GroupList groupsList = new GroupList();
\r
266 List<String> groups = groupsList.getGroup();
\r
267 groups.addAll(values);
\r
268 person.setGroups(groupsList);
\r
270 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.NATIONALITIES))!=null) {
\r
271 NationalityList nationalitiesList = new NationalityList();
\r
272 List<String> nationalities = nationalitiesList.getNationality();
\r
273 nationalities.addAll(values);
\r
274 person.setNationalities(nationalitiesList);
\r
277 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.OCCUPATIONS))!=null) {
\r
278 OccupationList occupationsList = new OccupationList();
\r
279 List<String> occupations = occupationsList.getOccupation();
\r
280 occupations.addAll(values);
\r
281 person.setOccupations(occupationsList);
\r
283 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.SCHOOLS_OR_STYLES))!=null) {
\r
284 SchoolOrStyleList schoolOrStyleList = new SchoolOrStyleList();
\r
285 List<String> schoolsOrStyles = schoolOrStyleList.getSchoolOrStyle();
\r
286 schoolsOrStyles.addAll(values);
\r
287 person.setSchoolsOrStyles(schoolOrStyleList);
\r
292 PoxPayloadOut multipart = new PoxPayloadOut(PersonAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
\r
293 PayloadOutputPart commonPart = multipart.addPart(person,
\r
294 MediaType.APPLICATION_XML_TYPE);
\r
295 commonPart.setLabel(headerLabel);
\r
297 if(logger.isDebugEnabled()){
\r
298 logger.debug("to be created, person common ", person, PersonsCommon.class);
\r
305 * Creates the item in authority.
\r
307 * @param vcsid the vcsid
\r
308 * @param personAuthorityRefName the person authority ref name
\r
309 * @param personMap the person map. PersonJAXBSchema.SHORT_IDENTIFIER is REQUIRED.
\r
310 * @param client the client
\r
311 * @return the string
\r
313 public static String createItemInAuthority(String vcsid,
\r
314 String personAuthorityRefName, Map<String,String> personMap,
\r
315 Map<String, List<String>> personRepeatablesMap, PersonAuthorityClient client ) {
\r
316 // Expected status code: 201 Created
\r
317 int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
\r
318 // Type of service request being tested
\r
319 ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
\r
321 String displayName = personMap.get(PersonJAXBSchema.DISPLAY_NAME);
\r
322 String displayNameComputedStr = personMap.get(PersonJAXBSchema.DISPLAY_NAME_COMPUTED);
\r
323 boolean displayNameComputed = (displayNameComputedStr==null) || displayNameComputedStr.equalsIgnoreCase("true");
\r
324 if( displayName == null ) {
\r
325 if(!displayNameComputed) {
\r
326 throw new RuntimeException(
\r
327 "CreateItem: Must supply a displayName if displayNameComputed is set to false.");
\r
330 prepareDefaultDisplayName(
\r
331 personMap.get(PersonJAXBSchema.FORE_NAME),
\r
332 personMap.get(PersonJAXBSchema.MIDDLE_NAME),
\r
333 personMap.get(PersonJAXBSchema.SUR_NAME),
\r
334 personMap.get(PersonJAXBSchema.BIRTH_DATE),
\r
335 personMap.get(PersonJAXBSchema.DEATH_DATE));
\r
336 personMap.put(PersonJAXBSchema.DISPLAY_NAME, displayName);
\r
338 String shortDisplayName = personMap.get(PersonJAXBSchema.SHORT_DISPLAY_NAME);
\r
339 String shortDisplayNameComputedStr = personMap.get(PersonJAXBSchema.SHORT_DISPLAY_NAME_COMPUTED);
\r
340 boolean shortDisplayNameComputed = (shortDisplayNameComputedStr==null) || shortDisplayNameComputedStr.equalsIgnoreCase("true");
\r
341 if( shortDisplayName == null ) {
\r
342 if(!shortDisplayNameComputed) {
\r
343 throw new RuntimeException(
\r
344 "CreateItem: Must supply a shortDisplayName if shortDisplayNameComputed is set to false.");
\r
346 shortDisplayName =
\r
347 prepareDefaultDisplayName(
\r
348 personMap.get(PersonJAXBSchema.FORE_NAME), null,
\r
349 personMap.get(PersonJAXBSchema.SUR_NAME),null,null);
\r
350 personMap.put(PersonJAXBSchema.SHORT_DISPLAY_NAME, shortDisplayName);
\r
353 if(logger.isDebugEnabled()){
\r
354 logger.debug("Import: Create Item: \"" + displayName
\r
355 +"\" in personAuthorityulary: \"" + personAuthorityRefName +"\"");
\r
357 PoxPayloadOut multipart =
\r
358 createPersonInstance(vcsid, personAuthorityRefName,
\r
359 personMap, personRepeatablesMap, client.getItemCommonPartName());
\r
361 String result = null;
\r
362 ClientResponse<Response> res = client.createItem(vcsid, multipart);
\r
364 int statusCode = res.getStatus();
\r
366 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
\r
367 throw new RuntimeException("Could not create Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)
\r
368 +"\" in personAuthority: \"" + personAuthorityRefName
\r
369 +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
\r
371 if(statusCode != EXPECTED_STATUS_CODE) {
\r
372 throw new RuntimeException("Unexpected Status when creating Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)
\r
373 +"\" in personAuthority: \"" + personAuthorityRefName +"\", Status:"+ statusCode);
\r
376 result = extractId(res);
\r
378 res.releaseConnection();
\r
385 * Creates the personAuthority ref name.
\r
387 * @param shortId the personAuthority shortIdentifier
\r
388 * @param displaySuffix displayName to be appended, if non-null
\r
389 * @return the string
\r
391 public static String createPersonAuthRefName(String shortId, String displaySuffix) {
\r
392 String refName = "urn:cspace:org.collectionspace.demo:personauthority:name("
\r
394 if(displaySuffix!=null&&!displaySuffix.isEmpty())
\r
395 refName += "'"+displaySuffix+"'";
\r
400 * Creates the person ref name.
\r
402 * @param personAuthRefName the person auth ref name
\r
403 * @param shortId the person shortIdentifier
\r
404 * @param displaySuffix displayName to be appended, if non-null
\r
405 * @return the string
\r
407 public static String createPersonRefName(
\r
408 String personAuthRefName, String shortId, String displaySuffix) {
\r
409 String refName = personAuthRefName+":person:name("+shortId+")";
\r
410 if(displaySuffix!=null&&!displaySuffix.isEmpty())
\r
411 refName += "'"+displaySuffix+"'";
\r
418 * @param res the res
\r
419 * @return the string
\r
421 public static String extractId(ClientResponse<Response> res) {
\r
422 MultivaluedMap<String, Object> mvm = res.getMetadata();
\r
423 // FIXME: This may throw an NPE if the Location: header isn't present
\r
424 String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
\r
425 if(logger.isDebugEnabled()){
\r
426 logger.debug("extractId:uri=" + uri);
\r
428 String[] segments = uri.split("/");
\r
429 String id = segments[segments.length - 1];
\r
430 if(logger.isDebugEnabled()){
\r
431 logger.debug("id=" + id);
\r
437 * Returns an error message indicating that the status code returned by a
\r
438 * specific call to a service does not fall within a set of valid status
\r
439 * codes for that service.
\r
441 * @param serviceRequestType A type of service request (e.g. CREATE, DELETE).
\r
443 * @param statusCode The invalid status code that was returned in the response,
\r
444 * from submitting that type of request to the service.
\r
446 * @return An error message.
\r
448 public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
\r
449 return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
\r
450 requestType.validStatusCodesAsString();
\r
456 * Produces a default displayName from the basic name and dates fields.
\r
457 * @see PersonDocumentModelHandler.prepareDefaultDisplayName() which
\r
458 * duplicates this logic, until we define a service-general utils package
\r
459 * that is neither client nor service specific.
\r
461 * @param middleName
\r
465 * @return display name
\r
467 public static String prepareDefaultDisplayName(
\r
468 String foreName, String middleName, String surName,
\r
469 String birthDate, String deathDate ) {
\r
470 StringBuilder newStr = new StringBuilder();
\r
471 final String sep = " ";
\r
472 final String dateSep = "-";
\r
473 List<String> nameStrings =
\r
474 Arrays.asList(foreName, middleName, surName);
\r
475 boolean firstAdded = false;
\r
476 for(String partStr : nameStrings ){
\r
477 if(null != partStr ) {
\r
479 newStr.append(sep);
\r
481 newStr.append(partStr);
\r
485 // Now we add the dates. In theory could have dates with no name, but that is their problem.
\r
486 boolean foundBirth = false;
\r
487 if(null != birthDate) {
\r
489 newStr.append(sep);
\r
491 newStr.append(birthDate);
\r
492 newStr.append(dateSep); // Put this in whether there is a death date or not
\r
495 if(null != deathDate) {
\r
498 newStr.append(sep);
\r
500 newStr.append(dateSep);
\r
502 newStr.append(deathDate);
\r
504 return newStr.toString();
\r