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.List;
\r
32 import java.util.Map;
\r
34 import javax.ws.rs.core.MediaType;
\r
35 import javax.ws.rs.core.MultivaluedMap;
\r
36 import javax.ws.rs.core.Response;
\r
38 import org.collectionspace.services.PersonJAXBSchema;
\r
39 import org.collectionspace.services.client.test.ServiceRequestType;
\r
40 import org.collectionspace.services.person.PersonsCommon;
\r
41 import org.collectionspace.services.person.PersonauthoritiesCommon;
\r
42 import org.jboss.resteasy.client.ClientResponse;
\r
43 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
\r
44 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
\r
45 import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
\r
46 import org.slf4j.Logger;
\r
47 import org.slf4j.LoggerFactory;
\r
50 * The Class PersonAuthorityClientUtils.
\r
52 public class PersonAuthorityClientUtils {
\r
54 /** The Constant logger. */
\r
55 private static final Logger logger =
\r
56 LoggerFactory.getLogger(PersonAuthorityClientUtils.class);
\r
57 private static final ServiceRequestType READ_REQ = ServiceRequestType.READ;
\r
60 * @param csid the id of the PersonAuthority
\r
61 * @param client if null, creates a new client
\r
64 public static String getAuthorityRefName(String csid, PersonAuthorityClient client){
\r
66 client = new PersonAuthorityClient();
\r
67 ClientResponse<MultipartInput> res = client.read(csid);
\r
69 int statusCode = res.getStatus();
\r
70 if(!READ_REQ.isValidStatusCode(statusCode)
\r
71 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
\r
72 throw new RuntimeException("Invalid status code returned: "+statusCode);
\r
74 //FIXME: remove the following try catch once Aron fixes signatures
\r
76 MultipartInput input = (MultipartInput) res.getEntity();
\r
77 PersonauthoritiesCommon personAuthority =
\r
78 (PersonauthoritiesCommon) CollectionSpaceClientUtils.extractPart(input,
\r
79 client.getCommonPartName(), PersonauthoritiesCommon.class);
\r
80 if(personAuthority==null) {
\r
81 throw new RuntimeException("Null personAuthority returned from service.");
\r
83 return personAuthority.getRefName();
\r
84 } catch (Exception e) {
\r
85 throw new RuntimeException(e);
\r
88 res.releaseConnection();
\r
93 * @param csid the id of the PersonAuthority
\r
94 * @param client if null, creates a new client
\r
97 public static String getPersonRefName(String inAuthority, String csid, PersonAuthorityClient client){
\r
99 client = new PersonAuthorityClient();
\r
100 ClientResponse<MultipartInput> res = client.readItem(inAuthority, csid);
\r
102 int statusCode = res.getStatus();
\r
103 if(!READ_REQ.isValidStatusCode(statusCode)
\r
104 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
\r
105 throw new RuntimeException("Invalid status code returned: "+statusCode);
\r
107 //FIXME: remove the following try catch once Aron fixes signatures
\r
109 MultipartInput input = (MultipartInput) res.getEntity();
\r
110 PersonsCommon person =
\r
111 (PersonsCommon) CollectionSpaceClientUtils.extractPart(input,
\r
112 client.getItemCommonPartName(), PersonsCommon.class);
\r
114 throw new RuntimeException("Null person returned from service.");
\r
116 return person.getRefName();
\r
117 } catch (Exception e) {
\r
118 throw new RuntimeException(e);
\r
121 res.releaseConnection();
\r
126 * Creates the person authority instance.
\r
128 * @param displayName the display name
\r
129 * @param shortIdentifier the short Id
\r
130 * @param headerLabel the header label
\r
131 * @return the multipart output
\r
133 public static MultipartOutput createPersonAuthorityInstance(
\r
134 String displayName, String shortIdentifier, String headerLabel ) {
\r
135 PersonauthoritiesCommon personAuthority = new PersonauthoritiesCommon();
\r
136 personAuthority.setDisplayName(displayName);
\r
137 personAuthority.setShortIdentifier(shortIdentifier);
\r
138 String refName = createPersonAuthRefName(shortIdentifier, displayName);
\r
139 personAuthority.setRefName(refName);
\r
140 personAuthority.setVocabType("PersonAuthority");
\r
141 MultipartOutput multipart = new MultipartOutput();
\r
142 OutputPart commonPart = multipart.addPart(personAuthority, MediaType.APPLICATION_XML_TYPE);
\r
143 commonPart.getHeaders().add("label", headerLabel);
\r
145 if(logger.isDebugEnabled()){
\r
146 logger.debug("to be created, personAuthority common ",
\r
147 personAuthority, PersonauthoritiesCommon.class);
\r
154 * Creates the person instance.
\r
156 * @param inAuthority the owning authority
\r
157 * @param personAuthRefName the owning Authority ref name
\r
158 * @param personInfo the person info
\r
159 * @param headerLabel the header label
\r
160 * @return the multipart output
\r
162 public static MultipartOutput createPersonInstance(String inAuthority,
\r
163 String personAuthRefName, Map<String, String> personInfo, String headerLabel){
\r
164 PersonsCommon person = new PersonsCommon();
\r
165 person.setInAuthority(inAuthority);
\r
166 String shortId = personInfo.get(PersonJAXBSchema.SHORT_IDENTIFIER);
\r
167 if (shortId == null || shortId.isEmpty()) {
\r
168 throw new IllegalArgumentException("shortIdentifier cannot be null or empty");
\r
170 person.setShortIdentifier(shortId);
\r
173 // If the 'DISPLAY_NAME_COMPUTED' property is null or empty then
\r
174 // we'll assume that the service consumer wants us to compute the
\r
175 // display name. Otherwise, we'll parse the value with the Boolean class.
\r
177 String booleanStr = personInfo.get(PersonJAXBSchema.DISPLAY_NAME_COMPUTED);
\r
178 boolean displayNameComputed = true;
\r
179 if (booleanStr != null && booleanStr.length() > 0) {
\r
180 displayNameComputed = Boolean.parseBoolean(booleanStr);
\r
182 person.setDisplayNameComputed(displayNameComputed);
\r
184 String displayName = personInfo.get(PersonJAXBSchema.DISPLAY_NAME);
\r
185 person.setDisplayName(displayName);
\r
186 if (displayNameComputed == false && displayName == null) {
\r
187 throw new IllegalArgumentException("displayName cannot be null when displayComputed is 'false'");
\r
189 String refName = createPersonRefName(personAuthRefName, shortId, displayName);
\r
190 person.setRefName(refName);
\r
193 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
194 person.setForeName(value);
\r
195 if((value = (String)personInfo.get(PersonJAXBSchema.MIDDLE_NAME))!=null)
\r
196 person.setMiddleName(value);
\r
197 if((value = (String)personInfo.get(PersonJAXBSchema.SUR_NAME))!=null)
\r
198 person.setSurName(value);
\r
199 if((value = (String)personInfo.get(PersonJAXBSchema.INITIALS))!=null)
\r
200 person.setInitials(value);
\r
201 if((value = (String)personInfo.get(PersonJAXBSchema.SALUTATIONS))!=null)
\r
202 person.setSalutation(value);
\r
203 if((value = (String)personInfo.get(PersonJAXBSchema.TITLE))!=null)
\r
204 person.setTitle(value);
\r
205 if((value = (String)personInfo.get(PersonJAXBSchema.NAME_ADDITIONS))!=null)
\r
206 person.setNameAdditions(value);
\r
207 if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_DATE))!=null)
\r
208 person.setBirthDate(value);
\r
209 if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_DATE))!=null)
\r
210 person.setDeathDate(value);
\r
211 if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_PLACE))!=null)
\r
212 person.setBirthPlace(value);
\r
213 if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_PLACE))!=null)
\r
214 person.setDeathPlace(value);
\r
215 if((value = (String)personInfo.get(PersonJAXBSchema.GROUP))!=null)
\r
216 person.setGroup(value);
\r
217 if((value = (String)personInfo.get(PersonJAXBSchema.NATIONALITY))!=null)
\r
218 person.setNationality(value);
\r
219 if((value = (String)personInfo.get(PersonJAXBSchema.GENDER))!=null)
\r
220 person.setGender(value);
\r
221 if((value = (String)personInfo.get(PersonJAXBSchema.OCCUPATION))!=null)
\r
222 person.setOccupation(value);
\r
223 if((value = (String)personInfo.get(PersonJAXBSchema.SCHOOL_OR_STYLE))!=null)
\r
224 person.setSchoolOrStyle(value);
\r
225 if((value = (String)personInfo.get(PersonJAXBSchema.BIO_NOTE))!=null)
\r
226 person.setBioNote(value);
\r
227 if((value = (String)personInfo.get(PersonJAXBSchema.NAME_NOTE))!=null)
\r
228 person.setNameNote(value);
\r
230 MultipartOutput multipart = new MultipartOutput();
\r
231 OutputPart commonPart = multipart.addPart(person,
\r
232 MediaType.APPLICATION_XML_TYPE);
\r
233 commonPart.getHeaders().add("label", headerLabel);
\r
235 if(logger.isDebugEnabled()){
\r
236 logger.debug("to be created, person common ", person, PersonsCommon.class);
\r
243 * Creates the item in authority.
\r
245 * @param vcsid the vcsid
\r
246 * @param personAuthorityRefName the person authority ref name
\r
247 * @param personMap the person map. PersonJAXBSchema.SHORT_IDENTIFIER is REQUIRED.
\r
248 * @param client the client
\r
249 * @return the string
\r
251 public static String createItemInAuthority(String vcsid,
\r
252 String personAuthorityRefName, Map<String,String> personMap,
\r
253 PersonAuthorityClient client ) {
\r
254 // Expected status code: 201 Created
\r
255 int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
\r
256 // Type of service request being tested
\r
257 ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
\r
259 String displayName = personMap.get(PersonJAXBSchema.DISPLAY_NAME);
\r
260 String displayNameComputedStr = personMap.get(PersonJAXBSchema.DISPLAY_NAME_COMPUTED);
\r
261 boolean displayNameComputed = (displayNameComputedStr==null) || displayNameComputedStr.equalsIgnoreCase("true");
\r
262 if( displayName == null ) {
\r
263 if(!displayNameComputed) {
\r
264 throw new RuntimeException(
\r
265 "CreateItem: Must supply a displayName if displayNameComputed is set to false.");
\r
268 prepareDefaultDisplayName(
\r
269 personMap.get(PersonJAXBSchema.FORE_NAME),
\r
270 personMap.get(PersonJAXBSchema.MIDDLE_NAME),
\r
271 personMap.get(PersonJAXBSchema.SUR_NAME),
\r
272 personMap.get(PersonJAXBSchema.BIRTH_DATE),
\r
273 personMap.get(PersonJAXBSchema.DEATH_DATE));
\r
274 personMap.put(PersonJAXBSchema.DISPLAY_NAME, displayName);
\r
277 if(logger.isDebugEnabled()){
\r
278 logger.debug("Import: Create Item: \"" + displayName
\r
279 +"\" in personAuthorityulary: \"" + personAuthorityRefName +"\"");
\r
281 MultipartOutput multipart =
\r
282 createPersonInstance(vcsid, personAuthorityRefName,
\r
283 personMap, client.getItemCommonPartName());
\r
285 String result = null;
\r
286 ClientResponse<Response> res = client.createItem(vcsid, multipart);
\r
288 int statusCode = res.getStatus();
\r
290 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
\r
291 throw new RuntimeException("Could not create Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)
\r
292 +"\" in personAuthority: \"" + personAuthorityRefName
\r
293 +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
\r
295 if(statusCode != EXPECTED_STATUS_CODE) {
\r
296 throw new RuntimeException("Unexpected Status when creating Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)
\r
297 +"\" in personAuthority: \"" + personAuthorityRefName +"\", Status:"+ statusCode);
\r
300 result = extractId(res);
\r
302 res.releaseConnection();
\r
309 * Creates the personAuthority ref name.
\r
311 * @param shortId the personAuthority shortIdentifier
\r
312 * @param displaySuffix displayName to be appended, if non-null
\r
313 * @return the string
\r
315 public static String createPersonAuthRefName(String shortId, String displaySuffix) {
\r
316 String refName = "urn:cspace:org.collectionspace.demo:personauthority:name("
\r
318 if(displaySuffix!=null&&!displaySuffix.isEmpty())
\r
319 refName += "'"+displaySuffix+"'";
\r
324 * Creates the person ref name.
\r
326 * @param personAuthRefName the person auth ref name
\r
327 * @param shortId the person shortIdentifier
\r
328 * @param displaySuffix displayName to be appended, if non-null
\r
329 * @return the string
\r
331 public static String createPersonRefName(
\r
332 String personAuthRefName, String shortId, String displaySuffix) {
\r
333 String refName = personAuthRefName+":person:name("+shortId+")";
\r
334 if(displaySuffix!=null&&!displaySuffix.isEmpty())
\r
335 refName += "'"+displaySuffix+"'";
\r
342 * @param res the res
\r
343 * @return the string
\r
345 public static String extractId(ClientResponse<Response> res) {
\r
346 MultivaluedMap<String, Object> mvm = res.getMetadata();
\r
347 String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
\r
348 if(logger.isDebugEnabled()){
\r
349 logger.debug("extractId:uri=" + uri);
\r
351 String[] segments = uri.split("/");
\r
352 String id = segments[segments.length - 1];
\r
353 if(logger.isDebugEnabled()){
\r
354 logger.debug("id=" + id);
\r
360 * Returns an error message indicating that the status code returned by a
\r
361 * specific call to a service does not fall within a set of valid status
\r
362 * codes for that service.
\r
364 * @param serviceRequestType A type of service request (e.g. CREATE, DELETE).
\r
366 * @param statusCode The invalid status code that was returned in the response,
\r
367 * from submitting that type of request to the service.
\r
369 * @return An error message.
\r
371 public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
\r
372 return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
\r
373 requestType.validStatusCodesAsString();
\r
379 * Produces a default displayName from the basic name and dates fields.
\r
380 * @see PersonDocumentModelHandler.prepareDefaultDisplayName() which
\r
381 * duplicates this logic, until we define a service-general utils package
\r
382 * that is neither client nor service specific.
\r
384 * @param middleName
\r
388 * @return display name
\r
390 public static String prepareDefaultDisplayName(
\r
391 String foreName, String middleName, String surName,
\r
392 String birthDate, String deathDate ) {
\r
393 StringBuilder newStr = new StringBuilder();
\r
394 final String sep = " ";
\r
395 final String dateSep = "-";
\r
396 List<String> nameStrings =
\r
397 Arrays.asList(foreName, middleName, surName);
\r
398 boolean firstAdded = false;
\r
399 for(String partStr : nameStrings ){
\r
400 if(null != partStr ) {
\r
402 newStr.append(sep);
\r
404 newStr.append(partStr);
\r
408 // Now we add the dates. In theory could have dates with no name, but that is their problem.
\r
409 boolean foundBirth = false;
\r
410 if(null != birthDate) {
\r
412 newStr.append(sep);
\r
414 newStr.append(birthDate);
\r
415 newStr.append(dateSep); // Put this in whether there is a death date or not
\r
418 if(null != deathDate) {
\r
421 newStr.append(sep);
\r
423 newStr.append(dateSep);
\r
425 newStr.append(deathDate);
\r
427 return newStr.toString();
\r