]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
60f1723176b9557d62f30a33b2bd7ab48a3b38b6
[tmp/jakarta-migration.git] /
1 /**     \r
2  * PersonAuthorityClientUtils.java\r
3  *\r
4  * {Purpose of This Class}\r
5  *\r
6  * {Other Notes Relating to This Class (Optional)}\r
7  *\r
8  * $LastChangedBy: $\r
9  * $LastChangedRevision: $\r
10  * $LastChangedDate: $\r
11  *\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
15  *\r
16  * http://www.collectionspace.org\r
17  * http://wiki.collectionspace.org\r
18  *\r
19  * Copyright © 2009 {Contributing Institution}\r
20  *\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
23  *\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
26  */\r
27 package org.collectionspace.services.client;\r
28 \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
34 \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
38 \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.MultipartInput;\r
49 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;\r
50 import org.jboss.resteasy.plugins.providers.multipart.OutputPart;\r
51 import org.slf4j.Logger;\r
52 import org.slf4j.LoggerFactory;\r
53 \r
54 /**\r
55  * The Class PersonAuthorityClientUtils.\r
56  */\r
57 public class PersonAuthorityClientUtils {\r
58     \r
59     /** The Constant logger. */\r
60     private static final Logger logger =\r
61         LoggerFactory.getLogger(PersonAuthorityClientUtils.class);\r
62         private static final ServiceRequestType READ_REQ = ServiceRequestType.READ;\r
63 \r
64     /**\r
65      * @param csid the id of the PersonAuthority\r
66      * @param client if null, creates a new client\r
67      * @return\r
68      */\r
69     public static String getAuthorityRefName(String csid, PersonAuthorityClient client){\r
70         if(client==null)\r
71                 client = new PersonAuthorityClient();\r
72         ClientResponse<MultipartInput> res = client.read(csid);\r
73         try {\r
74                 int statusCode = res.getStatus();\r
75                 if(!READ_REQ.isValidStatusCode(statusCode)\r
76                         ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {\r
77                         throw new RuntimeException("Invalid status code returned: "+statusCode);\r
78                 }\r
79                 //FIXME: remove the following try catch once Aron fixes signatures\r
80                 try {\r
81                     MultipartInput input = (MultipartInput) res.getEntity();\r
82                     PersonauthoritiesCommon personAuthority = \r
83                         (PersonauthoritiesCommon) CollectionSpaceClientUtils.extractPart(input,\r
84                             client.getCommonPartName(), PersonauthoritiesCommon.class);\r
85                         if(personAuthority==null) {\r
86                                 throw new RuntimeException("Null personAuthority returned from service.");\r
87                         }\r
88                     return personAuthority.getRefName();\r
89                 } catch (Exception e) {\r
90                     throw new RuntimeException(e);\r
91                 }\r
92         } finally {\r
93                 res.releaseConnection();\r
94         }\r
95     }\r
96 \r
97     /**\r
98      * @param csid the id of the PersonAuthority\r
99      * @param client if null, creates a new client\r
100      * @return\r
101      */\r
102     public static String getPersonRefName(String inAuthority, String csid, PersonAuthorityClient client){\r
103         if(client==null)\r
104                 client = new PersonAuthorityClient();\r
105         ClientResponse<MultipartInput> res = client.readItem(inAuthority, csid);\r
106         try {\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
111                 }\r
112                 //FIXME: remove the following try catch once Aron fixes signatures\r
113                 try {\r
114                     MultipartInput input = (MultipartInput) 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
120                         }\r
121                     return person.getRefName();\r
122                 } catch (Exception e) {\r
123                     throw new RuntimeException(e);\r
124                 }\r
125         } finally {\r
126                 res.releaseConnection();\r
127         }\r
128     }\r
129 \r
130     /**\r
131      * Creates the person authority instance.\r
132      *\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
137      */\r
138     public static MultipartOutput 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         MultipartOutput multipart = new MultipartOutput();\r
147         OutputPart commonPart = multipart.addPart(personAuthority, MediaType.APPLICATION_XML_TYPE);\r
148         commonPart.getHeaders().add("label", headerLabel);\r
149 \r
150         if(logger.isDebugEnabled()){\r
151                 logger.debug("to be created, personAuthority common ", \r
152                                         personAuthority, PersonauthoritiesCommon.class);\r
153         }\r
154 \r
155         return multipart;\r
156     }\r
157 \r
158     /**\r
159      * Creates a person instance.\r
160      *\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
166      */\r
167     public static MultipartOutput createPersonInstance(String inAuthority,\r
168                 String personAuthRefName, Map<String, String> personInfo,\r
169                 String headerLabel){\r
170         final Map<String, List<String>> EMPTY_PERSON_REPEATABLES_INFO =\r
171                 new HashMap<String, List<String>>();\r
172         return createPersonInstance(inAuthority, personAuthRefName, personInfo,\r
173                 EMPTY_PERSON_REPEATABLES_INFO, headerLabel);\r
174     }\r
175 \r
176     /**\r
177      * Creates a person instance.\r
178      *\r
179      * @param inAuthority the owning authority\r
180      * @param personAuthRefName the owning Authority ref name\r
181      * @param personInfo the person info\r
182      * @param personRepeatablesInfo names and values of repeatable scalar fields in the Person record\r
183      * @param headerLabel the header label\r
184      * @return the multipart output\r
185      */\r
186     public static MultipartOutput createPersonInstance(String inAuthority, \r
187                 String personAuthRefName, Map<String, String> personInfo,\r
188                 Map<String, List<String>> personRepeatablesInfo, String headerLabel){\r
189         PersonsCommon person = new PersonsCommon();\r
190         person.setInAuthority(inAuthority);\r
191         String shortId = personInfo.get(PersonJAXBSchema.SHORT_IDENTIFIER);\r
192         if (shortId == null || shortId.isEmpty()) {\r
193                 throw new IllegalArgumentException("shortIdentifier cannot be null or empty");\r
194         }       \r
195         person.setShortIdentifier(shortId);\r
196         \r
197         //\r
198         // If the 'DISPLAY_NAME_COMPUTED' property is null or empty then\r
199         // we'll assume that the service consumer wants us to compute the\r
200         // display name.  Otherwise, we'll parse the value with the Boolean class.\r
201         //\r
202         String booleanStr = personInfo.get(PersonJAXBSchema.DISPLAY_NAME_COMPUTED);\r
203         boolean displayNameComputed = true;\r
204         if (booleanStr != null && booleanStr.length() > 0) {\r
205                 displayNameComputed = Boolean.parseBoolean(booleanStr);\r
206         }\r
207         person.setDisplayNameComputed(displayNameComputed);\r
208 \r
209         String displayName = personInfo.get(PersonJAXBSchema.DISPLAY_NAME);\r
210         person.setDisplayName(displayName);\r
211         if (displayNameComputed == false && displayName == null) {\r
212                 throw new IllegalArgumentException("displayName cannot be null when displayComputed is 'false'");\r
213         }       \r
214 \r
215         booleanStr = personInfo.get(PersonJAXBSchema.SHORT_DISPLAY_NAME_COMPUTED);\r
216         boolean shortDisplayNameComputed = true;\r
217         if (booleanStr != null && booleanStr.length() > 0) {\r
218                 shortDisplayNameComputed = Boolean.parseBoolean(booleanStr);\r
219         }\r
220         person.setShortDisplayNameComputed(shortDisplayNameComputed);\r
221 \r
222         String shortDisplayName = personInfo.get(PersonJAXBSchema.SHORT_DISPLAY_NAME);\r
223         person.setShortDisplayName(shortDisplayName);\r
224         if (shortDisplayNameComputed == false && shortDisplayName == null) {\r
225                 throw new IllegalArgumentException("shortDisplayName cannot be null when shortDisplayComputed is 'false'");\r
226         }       \r
227 \r
228         String refName = createPersonRefName(personAuthRefName, shortId, displayName);\r
229         person.setRefName(refName);\r
230         \r
231         String value;\r
232         List<String> values = null;\r
233         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
234                 person.setForeName(value);\r
235         if((value = (String)personInfo.get(PersonJAXBSchema.MIDDLE_NAME))!=null)\r
236                 person.setMiddleName(value);\r
237         if((value = (String)personInfo.get(PersonJAXBSchema.SUR_NAME))!=null)\r
238                 person.setSurName(value);\r
239         if((value = (String)personInfo.get(PersonJAXBSchema.INITIALS))!=null)\r
240                 person.setInitials(value);\r
241         if((value = (String)personInfo.get(PersonJAXBSchema.SALUTATIONS))!=null)\r
242                 person.setSalutation(value);\r
243         if((value = (String)personInfo.get(PersonJAXBSchema.TITLE))!=null)\r
244                 person.setTitle(value);\r
245         if((value = (String)personInfo.get(PersonJAXBSchema.NAME_ADDITIONS))!=null)\r
246                 person.setNameAdditions(value);\r
247         if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_DATE))!=null)\r
248                 person.setBirthDate(value);\r
249         if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_DATE))!=null)\r
250                 person.setDeathDate(value);\r
251         if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_PLACE))!=null)\r
252                 person.setBirthPlace(value);\r
253         if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_PLACE))!=null)\r
254                 person.setDeathPlace(value);\r
255         if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.GROUPS))!=null) {\r
256                 GroupList groupsList = new GroupList();\r
257                 List<String> groups = groupsList.getGroup();\r
258                 groups.addAll(values);\r
259                 person.setGroups(groupsList);\r
260         }\r
261         if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.NATIONALITIES))!=null) {\r
262                 NationalityList nationalitiesList = new NationalityList();\r
263                 List<String> nationalities = nationalitiesList.getNationality();\r
264                 nationalities.addAll(values);\r
265                 person.setNationalities(nationalitiesList);\r
266         }\r
267         if((value = (String)personInfo.get(PersonJAXBSchema.GENDER))!=null)\r
268                 person.setGender(value);\r
269         if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.OCCUPATIONS))!=null) {\r
270                 OccupationList occupationsList = new OccupationList();\r
271                 List<String> occupations = occupationsList.getOccupation();\r
272                 occupations.addAll(values);\r
273                 person.setOccupations(occupationsList);\r
274         }\r
275         if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.SCHOOLS_OR_STYLES))!=null) {\r
276                 SchoolOrStyleList schoolOrStyleList = new SchoolOrStyleList();\r
277                 List<String> schoolsOrStyles = schoolOrStyleList.getSchoolOrStyle();\r
278                 schoolsOrStyles.addAll(values);\r
279                 person.setSchoolsOrStyles(schoolOrStyleList);\r
280         }\r
281         if((value = (String)personInfo.get(PersonJAXBSchema.BIO_NOTE))!=null)\r
282                 person.setBioNote(value);\r
283         if((value = (String)personInfo.get(PersonJAXBSchema.NAME_NOTE))!=null)\r
284                 person.setNameNote(value);\r
285         \r
286         MultipartOutput multipart = new MultipartOutput();\r
287         OutputPart commonPart = multipart.addPart(person,\r
288             MediaType.APPLICATION_XML_TYPE);\r
289         commonPart.getHeaders().add("label", headerLabel);\r
290 \r
291         if(logger.isDebugEnabled()){\r
292                 logger.debug("to be created, person common ", person, PersonsCommon.class);\r
293         }\r
294 \r
295         return multipart;\r
296     }\r
297     \r
298     /**\r
299      * Creates the item in authority.\r
300      *\r
301      * @param vcsid the vcsid\r
302      * @param personAuthorityRefName the person authority ref name\r
303      * @param personMap the person map. PersonJAXBSchema.SHORT_IDENTIFIER is REQUIRED.\r
304      * @param client the client\r
305      * @return the string\r
306      */\r
307     public static String createItemInAuthority(String vcsid, \r
308                 String personAuthorityRefName, Map<String,String> personMap,\r
309                 Map<String, List<String>> personRepeatablesMap, PersonAuthorityClient client ) {\r
310         // Expected status code: 201 Created\r
311         int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();\r
312         // Type of service request being tested\r
313         ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;\r
314         \r
315         String displayName = personMap.get(PersonJAXBSchema.DISPLAY_NAME);\r
316         String displayNameComputedStr = personMap.get(PersonJAXBSchema.DISPLAY_NAME_COMPUTED);\r
317         boolean displayNameComputed = (displayNameComputedStr==null) || displayNameComputedStr.equalsIgnoreCase("true");\r
318         if( displayName == null ) {\r
319                 if(!displayNameComputed) {\r
320                         throw new RuntimeException(\r
321                         "CreateItem: Must supply a displayName if displayNameComputed is set to false.");\r
322                 }\r
323                 displayName = \r
324                         prepareDefaultDisplayName(\r
325                         personMap.get(PersonJAXBSchema.FORE_NAME),\r
326                         personMap.get(PersonJAXBSchema.MIDDLE_NAME),\r
327                         personMap.get(PersonJAXBSchema.SUR_NAME),\r
328                         personMap.get(PersonJAXBSchema.BIRTH_DATE),\r
329                         personMap.get(PersonJAXBSchema.DEATH_DATE));\r
330                 personMap.put(PersonJAXBSchema.DISPLAY_NAME, displayName);\r
331         }\r
332         String shortDisplayName = personMap.get(PersonJAXBSchema.SHORT_DISPLAY_NAME);\r
333         String shortDisplayNameComputedStr = personMap.get(PersonJAXBSchema.SHORT_DISPLAY_NAME_COMPUTED);\r
334         boolean shortDisplayNameComputed = (shortDisplayNameComputedStr==null) || shortDisplayNameComputedStr.equalsIgnoreCase("true");\r
335         if( shortDisplayName == null ) {\r
336                 if(!shortDisplayNameComputed) {\r
337                         throw new RuntimeException(\r
338                         "CreateItem: Must supply a shortDisplayName if shortDisplayNameComputed is set to false.");\r
339                 }\r
340                 shortDisplayName = \r
341                         prepareDefaultDisplayName(\r
342                         personMap.get(PersonJAXBSchema.FORE_NAME), null,\r
343                         personMap.get(PersonJAXBSchema.SUR_NAME),null,null);\r
344                 personMap.put(PersonJAXBSchema.SHORT_DISPLAY_NAME, shortDisplayName);\r
345         }\r
346         \r
347         if(logger.isDebugEnabled()){\r
348                 logger.debug("Import: Create Item: \"" + displayName\r
349                                 +"\" in personAuthorityulary: \"" + personAuthorityRefName +"\"");\r
350         }\r
351         MultipartOutput multipart = \r
352                 createPersonInstance(vcsid, personAuthorityRefName,\r
353                         personMap, personRepeatablesMap, client.getItemCommonPartName());\r
354         \r
355         String result = null;\r
356         ClientResponse<Response> res = client.createItem(vcsid, multipart);\r
357         try {\r
358                 int statusCode = res.getStatus();\r
359         \r
360                 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {\r
361                         throw new RuntimeException("Could not create Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)\r
362                                         +"\" in personAuthority: \"" + personAuthorityRefName\r
363                                         +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));\r
364                 }\r
365                 if(statusCode != EXPECTED_STATUS_CODE) {\r
366                         throw new RuntimeException("Unexpected Status when creating Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)\r
367                                         +"\" in personAuthority: \"" + personAuthorityRefName +"\", Status:"+ statusCode);\r
368                 }\r
369         \r
370                 result = extractId(res);\r
371         } finally {\r
372                 res.releaseConnection();\r
373         }\r
374         \r
375         return result;\r
376     }\r
377 \r
378     /**\r
379      * Creates the personAuthority ref name.\r
380      *\r
381      * @param shortId the personAuthority shortIdentifier\r
382      * @param displaySuffix displayName to be appended, if non-null\r
383      * @return the string\r
384      */\r
385     public static String createPersonAuthRefName(String shortId, String displaySuffix) {\r
386         String refName = "urn:cspace:org.collectionspace.demo:personauthority:name("\r
387                         +shortId+")";\r
388         if(displaySuffix!=null&&!displaySuffix.isEmpty())\r
389                 refName += "'"+displaySuffix+"'";\r
390         return refName;\r
391     }\r
392 \r
393     /**\r
394      * Creates the person ref name.\r
395      *\r
396      * @param personAuthRefName the person auth ref name\r
397      * @param shortId the person shortIdentifier\r
398      * @param displaySuffix displayName to be appended, if non-null\r
399      * @return the string\r
400      */\r
401     public static String createPersonRefName(\r
402                                                 String personAuthRefName, String shortId, String displaySuffix) {\r
403         String refName = personAuthRefName+":person:name("+shortId+")";\r
404         if(displaySuffix!=null&&!displaySuffix.isEmpty())\r
405                 refName += "'"+displaySuffix+"'";\r
406         return refName;\r
407     }\r
408 \r
409     /**\r
410      * Extract id.\r
411      *\r
412      * @param res the res\r
413      * @return the string\r
414      */\r
415     public static String extractId(ClientResponse<Response> res) {\r
416         MultivaluedMap<String, Object> mvm = res.getMetadata();\r
417         String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);\r
418         if(logger.isDebugEnabled()){\r
419                 logger.debug("extractId:uri=" + uri);\r
420         }\r
421         String[] segments = uri.split("/");\r
422         String id = segments[segments.length - 1];\r
423         if(logger.isDebugEnabled()){\r
424                 logger.debug("id=" + id);\r
425         }\r
426         return id;\r
427     }\r
428     \r
429     /**\r
430      * Returns an error message indicating that the status code returned by a\r
431      * specific call to a service does not fall within a set of valid status\r
432      * codes for that service.\r
433      *\r
434      * @param serviceRequestType  A type of service request (e.g. CREATE, DELETE).\r
435      *\r
436      * @param statusCode  The invalid status code that was returned in the response,\r
437      *                    from submitting that type of request to the service.\r
438      *\r
439      * @return An error message.\r
440      */\r
441     public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {\r
442         return "Status code '" + statusCode + "' in response is NOT within the expected set: " +\r
443                 requestType.validStatusCodesAsString();\r
444     }\r
445 \r
446 \r
447     \r
448     /**\r
449      * Produces a default displayName from the basic name and dates fields.\r
450      * @see PersonDocumentModelHandler.prepareDefaultDisplayName() which\r
451      * duplicates this logic, until we define a service-general utils package\r
452      * that is neither client nor service specific.\r
453      * @param foreName  \r
454      * @param middleName\r
455      * @param surName\r
456      * @param birthDate\r
457      * @param deathDate\r
458      * @return display name\r
459      */\r
460     public static String prepareDefaultDisplayName(\r
461                 String foreName, String middleName, String surName,\r
462                 String birthDate, String deathDate ) {\r
463         StringBuilder newStr = new StringBuilder();\r
464                 final String sep = " ";\r
465                 final String dateSep = "-";\r
466                 List<String> nameStrings = \r
467                         Arrays.asList(foreName, middleName, surName);\r
468                 boolean firstAdded = false;\r
469         for(String partStr : nameStrings ){\r
470                         if(null != partStr ) {\r
471                                 if(firstAdded) {\r
472                                         newStr.append(sep);\r
473                                 }\r
474                                 newStr.append(partStr);\r
475                                 firstAdded = true;\r
476                         }\r
477         }\r
478         // Now we add the dates. In theory could have dates with no name, but that is their problem.\r
479         boolean foundBirth = false;\r
480                 if(null != birthDate) {\r
481                         if(firstAdded) {\r
482                                 newStr.append(sep);\r
483                         }\r
484                         newStr.append(birthDate);\r
485                 newStr.append(dateSep);         // Put this in whether there is a death date or not\r
486                         foundBirth = true;\r
487                 }\r
488                 if(null != deathDate) {\r
489                         if(!foundBirth) {\r
490                                 if(firstAdded) {\r
491                                         newStr.append(sep);\r
492                                 }\r
493                         newStr.append(dateSep);\r
494                         }\r
495                         newStr.append(deathDate);\r
496                 }\r
497                 return newStr.toString();\r
498     }\r
499     \r
500 \r
501 \r
502 }\r