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
52 * The Class PersonAuthorityClientUtils.
\r
54 public class PersonAuthorityClientUtils {
\r
56 /** The Constant logger. */
\r
57 private static final Logger logger =
\r
58 LoggerFactory.getLogger(PersonAuthorityClientUtils.class);
\r
59 private static final ServiceRequestType READ_REQ = ServiceRequestType.READ;
\r
62 * @param csid the id of the PersonAuthority
\r
63 * @param client if null, creates a new client
\r
66 public static String getAuthorityRefName(String csid, PersonAuthorityClient client){
\r
67 if (client == null) {
\r
68 client = new PersonAuthorityClient();
\r
70 ClientResponse<String> res = client.read(csid);
\r
72 int statusCode = res.getStatus();
\r
73 if(!READ_REQ.isValidStatusCode(statusCode)
\r
74 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
\r
75 throw new RuntimeException("Invalid status code returned: "+statusCode);
\r
77 //FIXME: remove the following try catch once Aron fixes signatures
\r
79 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
\r
80 PersonauthoritiesCommon personAuthority =
\r
81 (PersonauthoritiesCommon) CollectionSpaceClientUtils.extractPart(input,
\r
82 client.getCommonPartName(), PersonauthoritiesCommon.class);
\r
83 if(personAuthority == null) {
\r
84 throw new RuntimeException("Null personAuthority returned from service.");
\r
86 return personAuthority.getRefName();
\r
87 } catch (Exception e) {
\r
88 throw new RuntimeException(e);
\r
91 res.releaseConnection();
\r
96 * @param csid the id of the PersonAuthority
\r
97 * @param client if null, creates a new client
\r
100 public static String getPersonRefName(String inAuthority, String csid, PersonAuthorityClient client){
\r
101 if ( client == null) {
\r
102 client = new PersonAuthorityClient();
\r
104 ClientResponse<String> res = client.readItem(inAuthority, csid);
\r
106 int statusCode = res.getStatus();
\r
107 if(!READ_REQ.isValidStatusCode(statusCode)
\r
108 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
\r
109 throw new RuntimeException("Invalid status code returned: "+statusCode);
\r
111 //FIXME: remove the following try catch once Aron fixes signatures
\r
113 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
\r
114 PersonsCommon person =
\r
115 (PersonsCommon) CollectionSpaceClientUtils.extractPart(input,
\r
116 client.getItemCommonPartName(), PersonsCommon.class);
\r
117 if (person == null) {
\r
118 throw new RuntimeException("Null person returned from service.");
\r
120 return person.getRefName();
\r
121 } catch (Exception e) {
\r
122 throw new RuntimeException(e);
\r
125 res.releaseConnection();
\r
130 * Creates the person authority instance.
\r
132 * @param displayName the display name
\r
133 * @param shortIdentifier the short Id
\r
134 * @param headerLabel the header label
\r
135 * @return the multipart output
\r
137 public static PoxPayloadOut createPersonAuthorityInstance(
\r
138 String displayName, String shortIdentifier, String headerLabel ) {
\r
139 PersonauthoritiesCommon personAuthority = new PersonauthoritiesCommon();
\r
140 personAuthority.setDisplayName(displayName);
\r
141 personAuthority.setShortIdentifier(shortIdentifier);
\r
142 //String refName = createPersonAuthRefName(shortIdentifier, displayName);
\r
143 //personAuthority.setRefName(refName);
\r
144 personAuthority.setVocabType("PersonAuthority");
\r
145 PoxPayloadOut multipart = new PoxPayloadOut(PersonAuthorityClient.SERVICE_PAYLOAD_NAME);
\r
146 PayloadOutputPart commonPart = multipart.addPart(personAuthority, MediaType.APPLICATION_XML_TYPE);
\r
147 commonPart.setLabel(headerLabel);
\r
149 if(logger.isDebugEnabled()){
\r
150 logger.debug("to be created, personAuthority common ",
\r
151 personAuthority, PersonauthoritiesCommon.class);
\r
158 * Creates a person instance.
\r
160 * @param inAuthority the owning authority
\r
161 * @param personAuthRefName the owning Authority ref name
\r
162 * @param personInfo the person info
\r
163 * @param headerLabel the header label
\r
164 * @return the multipart output
\r
166 public static PoxPayloadOut createPersonInstance(String inAuthority,
\r
167 String personAuthRefName,
\r
168 Map<String, String> personInfo,
\r
169 List<PersonTermGroup> terms,
\r
170 String headerLabel){
\r
171 if (terms == null || terms.isEmpty()) {
\r
172 terms = getTermGroupInstance(getGeneratedIdentifier());
\r
174 final Map<String, List<String>> EMPTY_PERSON_REPEATABLES_INFO =
\r
175 new HashMap<String, List<String>>();
\r
176 return createPersonInstance(inAuthority, null /*personAuthRefName*/,
\r
177 personInfo, terms, EMPTY_PERSON_REPEATABLES_INFO, headerLabel);
\r
181 * Creates a person instance.
\r
183 * @param inAuthority the owning authority
\r
184 * @param personAuthRefName the owning Authority ref name
\r
185 * @param personInfo the person info
\r
186 * @param terms a list of Person terms
\r
187 * @param personRepeatablesInfo names and values of repeatable scalar fields in the Person record
\r
188 * @param headerLabel the header label
\r
189 * @return the multipart output
\r
191 public static PoxPayloadOut createPersonInstance(String inAuthority,
\r
192 String personAuthRefName, Map<String, String> personInfo,
\r
193 List<PersonTermGroup> terms,
\r
194 Map<String, List<String>> personRepeatablesInfo, String headerLabel){
\r
195 PersonsCommon person = new PersonsCommon();
\r
196 person.setInAuthority(inAuthority);
\r
197 String shortId = personInfo.get(PersonJAXBSchema.SHORT_IDENTIFIER);
\r
198 if (shortId == null || shortId.isEmpty()) {
\r
199 throw new IllegalArgumentException("shortIdentifier cannot be null or empty");
\r
201 person.setShortIdentifier(shortId);
\r
204 List<String> values = null;
\r
206 if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_DATE))!=null)
\r
207 person.setBirthDate(value);
\r
208 if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_DATE))!=null)
\r
209 person.setDeathDate(value);
\r
210 if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_PLACE))!=null)
\r
211 person.setBirthPlace(value);
\r
212 if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_PLACE))!=null)
\r
213 person.setDeathPlace(value);
\r
214 if((value = (String)personInfo.get(PersonJAXBSchema.GENDER))!=null)
\r
215 person.setGender(value);
\r
216 if((value = (String)personInfo.get(PersonJAXBSchema.BIO_NOTE))!=null)
\r
217 person.setBioNote(value);
\r
218 if((value = (String)personInfo.get(PersonJAXBSchema.NAME_NOTE))!=null)
\r
219 person.setNameNote(value);
\r
221 // Set values in the Term Information Group
\r
222 PersonTermGroupList termList = new PersonTermGroupList();
\r
223 if (terms == null || terms.isEmpty()) {
\r
224 terms = getTermGroupInstance(getGeneratedIdentifier());
\r
226 termList.getPersonTermGroup().addAll(terms);
\r
227 person.setPersonTermGroupList(termList);
\r
229 if (personRepeatablesInfo != null) {
\r
230 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.GROUPS))!=null) {
\r
231 GroupList groupsList = new GroupList();
\r
232 List<String> groups = groupsList.getGroup();
\r
233 groups.addAll(values);
\r
234 person.setGroups(groupsList);
\r
236 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.NATIONALITIES))!=null) {
\r
237 NationalityList nationalitiesList = new NationalityList();
\r
238 List<String> nationalities = nationalitiesList.getNationality();
\r
239 nationalities.addAll(values);
\r
240 person.setNationalities(nationalitiesList);
\r
243 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.OCCUPATIONS))!=null) {
\r
244 OccupationList occupationsList = new OccupationList();
\r
245 List<String> occupations = occupationsList.getOccupation();
\r
246 occupations.addAll(values);
\r
247 person.setOccupations(occupationsList);
\r
249 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.SCHOOLS_OR_STYLES))!=null) {
\r
250 SchoolOrStyleList schoolOrStyleList = new SchoolOrStyleList();
\r
251 List<String> schoolsOrStyles = schoolOrStyleList.getSchoolOrStyle();
\r
252 schoolsOrStyles.addAll(values);
\r
253 person.setSchoolsOrStyles(schoolOrStyleList);
\r
258 PoxPayloadOut multipart = new PoxPayloadOut(PersonAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
\r
259 PayloadOutputPart commonPart = multipart.addPart(person,
\r
260 MediaType.APPLICATION_XML_TYPE);
\r
261 commonPart.setLabel(headerLabel);
\r
263 if(logger.isDebugEnabled()){
\r
264 logger.debug("to be created, person common ", person, PersonsCommon.class);
\r
271 * Creates the item in authority.
\r
273 * @param vcsid the vcsid
\r
274 * @param personAuthorityRefName the person authority ref name
\r
275 * @param personMap the person map. PersonJAXBSchema.SHORT_IDENTIFIER is REQUIRED.
\r
276 * @param client the client
\r
277 * @return the string
\r
279 public static String createItemInAuthority(String vcsid,
\r
280 String personAuthorityRefName, Map<String,String> personMap,
\r
281 List<PersonTermGroup> terms, Map<String, List<String>> personRepeatablesMap,
\r
282 PersonAuthorityClient client ) {
\r
283 // Expected status code: 201 Created
\r
284 int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
\r
285 // Type of service request being tested
\r
286 ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
\r
288 String displayName = "";
\r
289 if (terms !=null && terms.size() > 0) {
\r
290 displayName = terms.get(0).getTermDisplayName();
\r
293 if(logger.isDebugEnabled()){
\r
294 logger.debug("Creating item with display name: \"" + displayName
\r
295 +"\" in personAuthority: \"" + vcsid +"\"");
\r
297 PoxPayloadOut multipart =
\r
298 createPersonInstance(vcsid, null /*personAuthorityRefName*/,
\r
299 personMap, terms, personRepeatablesMap, client.getItemCommonPartName());
\r
301 String result = null;
\r
302 ClientResponse<Response> res = client.createItem(vcsid, multipart);
\r
304 int statusCode = res.getStatus();
\r
306 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
\r
307 throw new RuntimeException("Could not create Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)
\r
308 +"\" in personAuthority: \"" + vcsid //personAuthorityRefName
\r
309 +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
\r
311 if(statusCode != EXPECTED_STATUS_CODE) {
\r
312 throw new RuntimeException("Unexpected Status when creating Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)
\r
313 +"\" in personAuthority: \"" + vcsid /*personAuthorityRefName*/ +"\", Status:"+ statusCode);
\r
316 result = extractId(res);
\r
318 res.releaseConnection();
\r
325 * Creates the personAuthority ref name.
\r
327 * @param shortId the personAuthority shortIdentifier
\r
328 * @param displaySuffix displayName to be appended, if non-null
\r
329 * @return the string
\r
332 public static String createPersonAuthRefName(String shortId, String displaySuffix) {
\r
333 String refName = "urn:cspace:org.collectionspace.demo:personauthority:name("
\r
335 if(displaySuffix!=null&&!displaySuffix.isEmpty())
\r
336 refName += "'"+displaySuffix+"'";
\r
342 * Creates the person ref name.
\r
344 * @param personAuthRefName the person auth ref name
\r
345 * @param shortId the person shortIdentifier
\r
346 * @param displaySuffix displayName to be appended, if non-null
\r
347 * @return the string
\r
350 public static String createPersonRefName(
\r
351 String personAuthRefName, String shortId, String displaySuffix) {
\r
352 String refName = personAuthRefName+":person:name("+shortId+")";
\r
353 if(displaySuffix!=null&&!displaySuffix.isEmpty())
\r
354 refName += "'"+displaySuffix+"'";
\r
362 * @param res the res
\r
363 * @return the string
\r
365 public static String extractId(ClientResponse<Response> res) {
\r
366 MultivaluedMap<String, Object> mvm = res.getMetadata();
\r
367 // FIXME: This may throw an NPE if the Location: header isn't present
\r
368 String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
\r
369 if(logger.isDebugEnabled()){
\r
370 logger.debug("extractId:uri=" + uri);
\r
372 String[] segments = uri.split("/");
\r
373 String id = segments[segments.length - 1];
\r
374 if(logger.isDebugEnabled()){
\r
375 logger.debug("id=" + id);
\r
381 * Returns an error message indicating that the status code returned by a
\r
382 * specific call to a service does not fall within a set of valid status
\r
383 * codes for that service.
\r
385 * @param serviceRequestType A type of service request (e.g. CREATE, DELETE).
\r
387 * @param statusCode The invalid status code that was returned in the response,
\r
388 * from submitting that type of request to the service.
\r
390 * @return An error message.
\r
392 public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
\r
393 return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
\r
394 requestType.validStatusCodesAsString();
\r
400 * Produces a default displayName from the basic name and dates fields.
\r
401 * @see PersonDocumentModelHandler.prepareDefaultDisplayName() which
\r
402 * duplicates this logic, until we define a service-general utils package
\r
403 * that is neither client nor service specific.
\r
405 * @param middleName
\r
409 * @return display name
\r
411 public static String prepareDefaultDisplayName(
\r
412 String foreName, String middleName, String surName,
\r
413 String birthDate, String deathDate ) {
\r
414 StringBuilder newStr = new StringBuilder();
\r
415 final String sep = " ";
\r
416 final String dateSep = "-";
\r
417 List<String> nameStrings =
\r
418 Arrays.asList(foreName, middleName, surName);
\r
419 boolean firstAdded = false;
\r
420 for(String partStr : nameStrings ){
\r
421 if(null != partStr ) {
\r
423 newStr.append(sep);
\r
425 newStr.append(partStr);
\r
429 // Now we add the dates. In theory could have dates with no name, but that is their problem.
\r
430 boolean foundBirth = false;
\r
431 if(null != birthDate) {
\r
433 newStr.append(sep);
\r
435 newStr.append(birthDate);
\r
436 newStr.append(dateSep); // Put this in whether there is a death date or not
\r
439 if(null != deathDate) {
\r
442 newStr.append(sep);
\r
444 newStr.append(dateSep);
\r
446 newStr.append(deathDate);
\r
448 return newStr.toString();
\r
451 public static List<PersonTermGroup> getTermGroupInstance(String identifier) {
\r
452 if (Tools.isBlank(identifier)) {
\r
453 identifier = getGeneratedIdentifier();
\r
455 List<PersonTermGroup> terms = new ArrayList<PersonTermGroup>();
\r
456 PersonTermGroup term = new PersonTermGroup();
\r
457 term.setTermDisplayName(identifier);
\r
458 term.setTermName(identifier);
\r
463 private static String getGeneratedIdentifier() {
\r
464 return "id" + new Date().getTime();
\r