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.person.GroupList;
\r
38 import org.collectionspace.services.person.NationalityList;
\r
39 import org.collectionspace.services.person.OccupationList;
\r
40 import org.collectionspace.services.person.PersonTermGroup;
\r
41 import org.collectionspace.services.person.PersonTermGroupList;
\r
42 import org.collectionspace.services.person.PersonsCommon;
\r
43 import org.collectionspace.services.person.PersonauthoritiesCommon;
\r
44 import org.collectionspace.services.person.SchoolOrStyleList;
\r
45 import org.jboss.resteasy.client.ClientResponse;
\r
46 //import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
\r
47 import org.slf4j.Logger;
\r
48 import org.slf4j.LoggerFactory;
\r
51 * The Class PersonAuthorityClientUtils.
\r
53 public class PersonAuthorityClientUtils {
\r
55 /** The Constant logger. */
\r
56 private static final Logger logger =
\r
57 LoggerFactory.getLogger(PersonAuthorityClientUtils.class);
\r
58 private static final ServiceRequestType READ_REQ = ServiceRequestType.READ;
\r
61 * @param csid the id of the PersonAuthority
\r
62 * @param client if null, creates a new client
\r
65 public static String getAuthorityRefName(String csid, PersonAuthorityClient client){
\r
66 if (client == null) {
\r
67 client = new PersonAuthorityClient();
\r
69 ClientResponse<String> res = client.read(csid);
\r
71 int statusCode = res.getStatus();
\r
72 if(!READ_REQ.isValidStatusCode(statusCode)
\r
73 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
\r
74 throw new RuntimeException("Invalid status code returned: "+statusCode);
\r
76 //FIXME: remove the following try catch once Aron fixes signatures
\r
78 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
\r
79 PersonauthoritiesCommon personAuthority =
\r
80 (PersonauthoritiesCommon) CollectionSpaceClientUtils.extractPart(input,
\r
81 client.getCommonPartName(), PersonauthoritiesCommon.class);
\r
82 if(personAuthority == null) {
\r
83 throw new RuntimeException("Null personAuthority returned from service.");
\r
85 return personAuthority.getRefName();
\r
86 } catch (Exception e) {
\r
87 throw new RuntimeException(e);
\r
90 res.releaseConnection();
\r
95 * @param csid the id of the PersonAuthority
\r
96 * @param client if null, creates a new client
\r
99 public static String getPersonRefName(String inAuthority, String csid, PersonAuthorityClient client){
\r
100 if ( client == null) {
\r
101 client = new PersonAuthorityClient();
\r
103 ClientResponse<String> res = client.readItem(inAuthority, csid);
\r
105 int statusCode = res.getStatus();
\r
106 if(!READ_REQ.isValidStatusCode(statusCode)
\r
107 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
\r
108 throw new RuntimeException("Invalid status code returned: "+statusCode);
\r
110 //FIXME: remove the following try catch once Aron fixes signatures
\r
112 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
\r
113 PersonsCommon person =
\r
114 (PersonsCommon) CollectionSpaceClientUtils.extractPart(input,
\r
115 client.getItemCommonPartName(), PersonsCommon.class);
\r
116 if (person == null) {
\r
117 throw new RuntimeException("Null person returned from service.");
\r
119 return person.getRefName();
\r
120 } catch (Exception e) {
\r
121 throw new RuntimeException(e);
\r
124 res.releaseConnection();
\r
129 * Creates the person authority instance.
\r
131 * @param displayName the display name
\r
132 * @param shortIdentifier the short Id
\r
133 * @param headerLabel the header label
\r
134 * @return the multipart output
\r
136 public static PoxPayloadOut createPersonAuthorityInstance(
\r
137 String displayName, String shortIdentifier, String headerLabel ) {
\r
138 PersonauthoritiesCommon personAuthority = new PersonauthoritiesCommon();
\r
139 personAuthority.setDisplayName(displayName);
\r
140 personAuthority.setShortIdentifier(shortIdentifier);
\r
141 //String refName = createPersonAuthRefName(shortIdentifier, displayName);
\r
142 //personAuthority.setRefName(refName);
\r
143 personAuthority.setVocabType("PersonAuthority");
\r
144 PoxPayloadOut multipart = new PoxPayloadOut(PersonAuthorityClient.SERVICE_PAYLOAD_NAME);
\r
145 PayloadOutputPart commonPart = multipart.addPart(personAuthority, MediaType.APPLICATION_XML_TYPE);
\r
146 commonPart.setLabel(headerLabel);
\r
148 if(logger.isDebugEnabled()){
\r
149 logger.debug("to be created, personAuthority common ",
\r
150 personAuthority, PersonauthoritiesCommon.class);
\r
157 * Creates a person instance.
\r
159 * @param inAuthority the owning authority
\r
160 * @param personAuthRefName the owning Authority ref name
\r
161 * @param personInfo the person info
\r
162 * @param headerLabel the header label
\r
163 * @return the multipart output
\r
165 public static PoxPayloadOut createPersonInstance(String inAuthority,
\r
166 String personAuthRefName,
\r
167 Map<String, String> personInfo,
\r
168 List<PersonTermGroup> terms,
\r
169 String headerLabel){
\r
170 if (terms == null || terms.isEmpty()) {
\r
171 terms = getTermGroupInstance(getGeneratedIdentifier());
\r
173 final Map<String, List<String>> EMPTY_PERSON_REPEATABLES_INFO =
\r
174 new HashMap<String, List<String>>();
\r
175 return createPersonInstance(inAuthority, null /*personAuthRefName*/,
\r
176 personInfo, terms, EMPTY_PERSON_REPEATABLES_INFO, headerLabel);
\r
180 * Creates a person instance.
\r
182 * @param inAuthority the owning authority
\r
183 * @param personAuthRefName the owning Authority ref name
\r
184 * @param personInfo the person info
\r
185 * @param terms a list of Person terms
\r
186 * @param personRepeatablesInfo names and values of repeatable scalar fields in the Person record
\r
187 * @param headerLabel the header label
\r
188 * @return the multipart output
\r
190 public static PoxPayloadOut createPersonInstance(String inAuthority,
\r
191 String personAuthRefName, Map<String, String> personInfo,
\r
192 List<PersonTermGroup> terms,
\r
193 Map<String, List<String>> personRepeatablesInfo, String headerLabel){
\r
194 PersonsCommon person = new PersonsCommon();
\r
195 person.setInAuthority(inAuthority);
\r
196 String shortId = personInfo.get(PersonJAXBSchema.SHORT_IDENTIFIER);
\r
197 if (shortId == null || shortId.isEmpty()) {
\r
198 throw new IllegalArgumentException("shortIdentifier cannot be null or empty");
\r
200 person.setShortIdentifier(shortId);
\r
203 List<String> values = null;
\r
205 if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_DATE))!=null)
\r
206 person.setBirthDate(value);
\r
207 if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_DATE))!=null)
\r
208 person.setDeathDate(value);
\r
209 if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_PLACE))!=null)
\r
210 person.setBirthPlace(value);
\r
211 if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_PLACE))!=null)
\r
212 person.setDeathPlace(value);
\r
213 if((value = (String)personInfo.get(PersonJAXBSchema.GENDER))!=null)
\r
214 person.setGender(value);
\r
215 if((value = (String)personInfo.get(PersonJAXBSchema.BIO_NOTE))!=null)
\r
216 person.setBioNote(value);
\r
217 if((value = (String)personInfo.get(PersonJAXBSchema.NAME_NOTE))!=null)
\r
218 person.setNameNote(value);
\r
220 // Set values in the Term Information Group
\r
221 PersonTermGroupList termList = new PersonTermGroupList();
\r
222 if (terms == null || terms.isEmpty()) {
\r
223 terms = getTermGroupInstance(getGeneratedIdentifier());
\r
225 termList.getPersonTermGroup().addAll(terms);
\r
226 person.setPersonTermGroupList(termList);
\r
228 if (personRepeatablesInfo != null) {
\r
229 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.GROUPS))!=null) {
\r
230 GroupList groupsList = new GroupList();
\r
231 List<String> groups = groupsList.getGroup();
\r
232 groups.addAll(values);
\r
233 person.setGroups(groupsList);
\r
235 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.NATIONALITIES))!=null) {
\r
236 NationalityList nationalitiesList = new NationalityList();
\r
237 List<String> nationalities = nationalitiesList.getNationality();
\r
238 nationalities.addAll(values);
\r
239 person.setNationalities(nationalitiesList);
\r
242 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.OCCUPATIONS))!=null) {
\r
243 OccupationList occupationsList = new OccupationList();
\r
244 List<String> occupations = occupationsList.getOccupation();
\r
245 occupations.addAll(values);
\r
246 person.setOccupations(occupationsList);
\r
248 if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.SCHOOLS_OR_STYLES))!=null) {
\r
249 SchoolOrStyleList schoolOrStyleList = new SchoolOrStyleList();
\r
250 List<String> schoolsOrStyles = schoolOrStyleList.getSchoolOrStyle();
\r
251 schoolsOrStyles.addAll(values);
\r
252 person.setSchoolsOrStyles(schoolOrStyleList);
\r
257 PoxPayloadOut multipart = new PoxPayloadOut(PersonAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
\r
258 PayloadOutputPart commonPart = multipart.addPart(person,
\r
259 MediaType.APPLICATION_XML_TYPE);
\r
260 commonPart.setLabel(headerLabel);
\r
262 if(logger.isDebugEnabled()){
\r
263 logger.debug("to be created, person common ", person, PersonsCommon.class);
\r
270 * Creates the item in authority.
\r
272 * @param vcsid the vcsid
\r
273 * @param personAuthorityRefName the person authority ref name
\r
274 * @param personMap the person map. PersonJAXBSchema.SHORT_IDENTIFIER is REQUIRED.
\r
275 * @param client the client
\r
276 * @return the string
\r
278 public static String createItemInAuthority(String vcsid,
\r
279 String personAuthorityRefName, Map<String,String> personMap,
\r
280 List<PersonTermGroup> terms, Map<String, List<String>> personRepeatablesMap,
\r
281 PersonAuthorityClient client ) {
\r
282 // Expected status code: 201 Created
\r
283 int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
\r
284 // Type of service request being tested
\r
285 ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
\r
287 String displayName = "";
\r
288 if (terms !=null && terms.size() > 0) {
\r
289 displayName = terms.get(0).getTermDisplayName();
\r
292 if(logger.isDebugEnabled()){
\r
293 logger.debug("Creating item with display name: \"" + displayName
\r
294 +"\" in personAuthority: \"" + vcsid +"\"");
\r
296 PoxPayloadOut multipart =
\r
297 createPersonInstance(vcsid, null /*personAuthorityRefName*/,
\r
298 personMap, terms, personRepeatablesMap, client.getItemCommonPartName());
\r
300 String result = null;
\r
301 ClientResponse<Response> res = client.createItem(vcsid, multipart);
\r
303 int statusCode = res.getStatus();
\r
305 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
\r
306 throw new RuntimeException("Could not create Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)
\r
307 +"\" in personAuthority: \"" + vcsid //personAuthorityRefName
\r
308 +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
\r
310 if(statusCode != EXPECTED_STATUS_CODE) {
\r
311 throw new RuntimeException("Unexpected Status when creating Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)
\r
312 +"\" in personAuthority: \"" + vcsid /*personAuthorityRefName*/ +"\", Status:"+ statusCode);
\r
315 result = extractId(res);
\r
317 res.releaseConnection();
\r
324 * Creates the personAuthority ref name.
\r
326 * @param shortId the personAuthority shortIdentifier
\r
327 * @param displaySuffix displayName to be appended, if non-null
\r
328 * @return the string
\r
331 public static String createPersonAuthRefName(String shortId, String displaySuffix) {
\r
332 String refName = "urn:cspace:org.collectionspace.demo:personauthority:name("
\r
334 if(displaySuffix!=null&&!displaySuffix.isEmpty())
\r
335 refName += "'"+displaySuffix+"'";
\r
341 * Creates the person ref name.
\r
343 * @param personAuthRefName the person auth ref name
\r
344 * @param shortId the person shortIdentifier
\r
345 * @param displaySuffix displayName to be appended, if non-null
\r
346 * @return the string
\r
349 public static String createPersonRefName(
\r
350 String personAuthRefName, String shortId, String displaySuffix) {
\r
351 String refName = personAuthRefName+":person:name("+shortId+")";
\r
352 if(displaySuffix!=null&&!displaySuffix.isEmpty())
\r
353 refName += "'"+displaySuffix+"'";
\r
361 * @param res the res
\r
362 * @return the string
\r
364 public static String extractId(ClientResponse<Response> res) {
\r
365 MultivaluedMap<String, Object> mvm = res.getMetadata();
\r
366 // FIXME: This may throw an NPE if the Location: header isn't present
\r
367 String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
\r
368 if(logger.isDebugEnabled()){
\r
369 logger.debug("extractId:uri=" + uri);
\r
371 String[] segments = uri.split("/");
\r
372 String id = segments[segments.length - 1];
\r
373 if(logger.isDebugEnabled()){
\r
374 logger.debug("id=" + id);
\r
380 * Returns an error message indicating that the status code returned by a
\r
381 * specific call to a service does not fall within a set of valid status
\r
382 * codes for that service.
\r
384 * @param serviceRequestType A type of service request (e.g. CREATE, DELETE).
\r
386 * @param statusCode The invalid status code that was returned in the response,
\r
387 * from submitting that type of request to the service.
\r
389 * @return An error message.
\r
391 public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
\r
392 return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
\r
393 requestType.validStatusCodesAsString();
\r
399 * Produces a default displayName from the basic name and dates fields.
\r
400 * @see PersonDocumentModelHandler.prepareDefaultDisplayName() which
\r
401 * duplicates this logic, until we define a service-general utils package
\r
402 * that is neither client nor service specific.
\r
404 * @param middleName
\r
408 * @return display name
\r
410 public static String prepareDefaultDisplayName(
\r
411 String foreName, String middleName, String surName,
\r
412 String birthDate, String deathDate ) {
\r
413 StringBuilder newStr = new StringBuilder();
\r
414 final String sep = " ";
\r
415 final String dateSep = "-";
\r
416 List<String> nameStrings =
\r
417 Arrays.asList(foreName, middleName, surName);
\r
418 boolean firstAdded = false;
\r
419 for(String partStr : nameStrings ){
\r
420 if(null != partStr ) {
\r
422 newStr.append(sep);
\r
424 newStr.append(partStr);
\r
428 // Now we add the dates. In theory could have dates with no name, but that is their problem.
\r
429 boolean foundBirth = false;
\r
430 if(null != birthDate) {
\r
432 newStr.append(sep);
\r
434 newStr.append(birthDate);
\r
435 newStr.append(dateSep); // Put this in whether there is a death date or not
\r
438 if(null != deathDate) {
\r
441 newStr.append(sep);
\r
443 newStr.append(dateSep);
\r
445 newStr.append(deathDate);
\r
447 return newStr.toString();
\r
450 public static List<PersonTermGroup> getTermGroupInstance(String identifier) {
\r
451 List<PersonTermGroup> terms = new ArrayList<PersonTermGroup>();
\r
452 PersonTermGroup term = new PersonTermGroup();
\r
453 term.setTermDisplayName(identifier);
\r
454 term.setTermName(identifier);
\r
459 private static String getGeneratedIdentifier() {
\r
460 return "id" + new Date().getTime();
\r