]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
f800a0ad9d437baa267cb3b612eb7f4d3f087e1e
[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         String refName = createPersonRefName(personAuthRefName, shortId, displayName);\r
215         person.setRefName(refName);\r
216         \r
217         String value;\r
218         List<String> values = null;\r
219         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
220                 person.setForeName(value);\r
221         if((value = (String)personInfo.get(PersonJAXBSchema.MIDDLE_NAME))!=null)\r
222                 person.setMiddleName(value);\r
223         if((value = (String)personInfo.get(PersonJAXBSchema.SUR_NAME))!=null)\r
224                 person.setSurName(value);\r
225         if((value = (String)personInfo.get(PersonJAXBSchema.INITIALS))!=null)\r
226                 person.setInitials(value);\r
227         if((value = (String)personInfo.get(PersonJAXBSchema.SALUTATIONS))!=null)\r
228                 person.setSalutation(value);\r
229         if((value = (String)personInfo.get(PersonJAXBSchema.TITLE))!=null)\r
230                 person.setTitle(value);\r
231         if((value = (String)personInfo.get(PersonJAXBSchema.NAME_ADDITIONS))!=null)\r
232                 person.setNameAdditions(value);\r
233         if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_DATE))!=null)\r
234                 person.setBirthDate(value);\r
235         if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_DATE))!=null)\r
236                 person.setDeathDate(value);\r
237         if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_PLACE))!=null)\r
238                 person.setBirthPlace(value);\r
239         if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_PLACE))!=null)\r
240                 person.setDeathPlace(value);\r
241         if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.GROUPS))!=null) {\r
242                 GroupList groupsList = new GroupList();\r
243                 List<String> groups = groupsList.getGroup();\r
244                 groups.addAll(values);\r
245                 person.setGroups(groupsList);\r
246         }\r
247         if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.NATIONALITIES))!=null) {\r
248                 NationalityList nationalitiesList = new NationalityList();\r
249                 List<String> nationalities = nationalitiesList.getNationality();\r
250                 nationalities.addAll(values);\r
251                 person.setNationalities(nationalitiesList);\r
252         }\r
253         if((value = (String)personInfo.get(PersonJAXBSchema.GENDER))!=null)\r
254                 person.setGender(value);\r
255         if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.OCCUPATIONS))!=null) {\r
256                 OccupationList occupationsList = new OccupationList();\r
257                 List<String> occupations = occupationsList.getOccupation();\r
258                 occupations.addAll(values);\r
259                 person.setOccupations(occupationsList);\r
260         }\r
261         if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.SCHOOLS_OR_STYLES))!=null) {\r
262                 SchoolOrStyleList schoolOrStyleList = new SchoolOrStyleList();\r
263                 List<String> schoolsOrStyles = schoolOrStyleList.getSchoolOrStyle();\r
264                 schoolsOrStyles.addAll(values);\r
265                 person.setSchoolsOrStyles(schoolOrStyleList);\r
266         }\r
267         if((value = (String)personInfo.get(PersonJAXBSchema.BIO_NOTE))!=null)\r
268                 person.setBioNote(value);\r
269         if((value = (String)personInfo.get(PersonJAXBSchema.NAME_NOTE))!=null)\r
270                 person.setNameNote(value);\r
271         \r
272         MultipartOutput multipart = new MultipartOutput();\r
273         OutputPart commonPart = multipart.addPart(person,\r
274             MediaType.APPLICATION_XML_TYPE);\r
275         commonPart.getHeaders().add("label", headerLabel);\r
276 \r
277         if(logger.isDebugEnabled()){\r
278                 logger.debug("to be created, person common ", person, PersonsCommon.class);\r
279         }\r
280 \r
281         return multipart;\r
282     }\r
283     \r
284     /**\r
285      * Creates the item in authority.\r
286      *\r
287      * @param vcsid the vcsid\r
288      * @param personAuthorityRefName the person authority ref name\r
289      * @param personMap the person map. PersonJAXBSchema.SHORT_IDENTIFIER is REQUIRED.\r
290      * @param client the client\r
291      * @return the string\r
292      */\r
293     public static String createItemInAuthority(String vcsid, \r
294                 String personAuthorityRefName, Map<String,String> personMap,\r
295                 Map<String, List<String>> personRepeatablesMap, PersonAuthorityClient client ) {\r
296         // Expected status code: 201 Created\r
297         int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();\r
298         // Type of service request being tested\r
299         ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;\r
300         \r
301         String displayName = personMap.get(PersonJAXBSchema.DISPLAY_NAME);\r
302         String displayNameComputedStr = personMap.get(PersonJAXBSchema.DISPLAY_NAME_COMPUTED);\r
303         boolean displayNameComputed = (displayNameComputedStr==null) || displayNameComputedStr.equalsIgnoreCase("true");\r
304         if( displayName == null ) {\r
305                 if(!displayNameComputed) {\r
306                         throw new RuntimeException(\r
307                         "CreateItem: Must supply a displayName if displayNameComputed is set to false.");\r
308                 }\r
309                 displayName = \r
310                         prepareDefaultDisplayName(\r
311                         personMap.get(PersonJAXBSchema.FORE_NAME),\r
312                         personMap.get(PersonJAXBSchema.MIDDLE_NAME),\r
313                         personMap.get(PersonJAXBSchema.SUR_NAME),\r
314                         personMap.get(PersonJAXBSchema.BIRTH_DATE),\r
315                         personMap.get(PersonJAXBSchema.DEATH_DATE));\r
316                 personMap.put(PersonJAXBSchema.DISPLAY_NAME, displayName);\r
317         }\r
318         \r
319         if(logger.isDebugEnabled()){\r
320                 logger.debug("Import: Create Item: \"" + displayName\r
321                                 +"\" in personAuthorityulary: \"" + personAuthorityRefName +"\"");\r
322         }\r
323         MultipartOutput multipart = \r
324                 createPersonInstance(vcsid, personAuthorityRefName,\r
325                         personMap, personRepeatablesMap, client.getItemCommonPartName());\r
326         \r
327         String result = null;\r
328         ClientResponse<Response> res = client.createItem(vcsid, multipart);\r
329         try {\r
330                 int statusCode = res.getStatus();\r
331         \r
332                 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {\r
333                         throw new RuntimeException("Could not create Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)\r
334                                         +"\" in personAuthority: \"" + personAuthorityRefName\r
335                                         +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));\r
336                 }\r
337                 if(statusCode != EXPECTED_STATUS_CODE) {\r
338                         throw new RuntimeException("Unexpected Status when creating Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)\r
339                                         +"\" in personAuthority: \"" + personAuthorityRefName +"\", Status:"+ statusCode);\r
340                 }\r
341         \r
342                 result = extractId(res);\r
343         } finally {\r
344                 res.releaseConnection();\r
345         }\r
346         \r
347         return result;\r
348     }\r
349 \r
350     /**\r
351      * Creates the personAuthority ref name.\r
352      *\r
353      * @param shortId the personAuthority shortIdentifier\r
354      * @param displaySuffix displayName to be appended, if non-null\r
355      * @return the string\r
356      */\r
357     public static String createPersonAuthRefName(String shortId, String displaySuffix) {\r
358         String refName = "urn:cspace:org.collectionspace.demo:personauthority:name("\r
359                         +shortId+")";\r
360         if(displaySuffix!=null&&!displaySuffix.isEmpty())\r
361                 refName += "'"+displaySuffix+"'";\r
362         return refName;\r
363     }\r
364 \r
365     /**\r
366      * Creates the person ref name.\r
367      *\r
368      * @param personAuthRefName the person auth ref name\r
369      * @param shortId the person shortIdentifier\r
370      * @param displaySuffix displayName to be appended, if non-null\r
371      * @return the string\r
372      */\r
373     public static String createPersonRefName(\r
374                                                 String personAuthRefName, String shortId, String displaySuffix) {\r
375         String refName = personAuthRefName+":person:name("+shortId+")";\r
376         if(displaySuffix!=null&&!displaySuffix.isEmpty())\r
377                 refName += "'"+displaySuffix+"'";\r
378         return refName;\r
379     }\r
380 \r
381     /**\r
382      * Extract id.\r
383      *\r
384      * @param res the res\r
385      * @return the string\r
386      */\r
387     public static String extractId(ClientResponse<Response> res) {\r
388         MultivaluedMap<String, Object> mvm = res.getMetadata();\r
389         String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);\r
390         if(logger.isDebugEnabled()){\r
391                 logger.debug("extractId:uri=" + uri);\r
392         }\r
393         String[] segments = uri.split("/");\r
394         String id = segments[segments.length - 1];\r
395         if(logger.isDebugEnabled()){\r
396                 logger.debug("id=" + id);\r
397         }\r
398         return id;\r
399     }\r
400     \r
401     /**\r
402      * Returns an error message indicating that the status code returned by a\r
403      * specific call to a service does not fall within a set of valid status\r
404      * codes for that service.\r
405      *\r
406      * @param serviceRequestType  A type of service request (e.g. CREATE, DELETE).\r
407      *\r
408      * @param statusCode  The invalid status code that was returned in the response,\r
409      *                    from submitting that type of request to the service.\r
410      *\r
411      * @return An error message.\r
412      */\r
413     public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {\r
414         return "Status code '" + statusCode + "' in response is NOT within the expected set: " +\r
415                 requestType.validStatusCodesAsString();\r
416     }\r
417 \r
418 \r
419     \r
420     /**\r
421      * Produces a default displayName from the basic name and dates fields.\r
422      * @see PersonDocumentModelHandler.prepareDefaultDisplayName() which\r
423      * duplicates this logic, until we define a service-general utils package\r
424      * that is neither client nor service specific.\r
425      * @param foreName  \r
426      * @param middleName\r
427      * @param surName\r
428      * @param birthDate\r
429      * @param deathDate\r
430      * @return display name\r
431      */\r
432     public static String prepareDefaultDisplayName(\r
433                 String foreName, String middleName, String surName,\r
434                 String birthDate, String deathDate ) {\r
435         StringBuilder newStr = new StringBuilder();\r
436                 final String sep = " ";\r
437                 final String dateSep = "-";\r
438                 List<String> nameStrings = \r
439                         Arrays.asList(foreName, middleName, surName);\r
440                 boolean firstAdded = false;\r
441         for(String partStr : nameStrings ){\r
442                         if(null != partStr ) {\r
443                                 if(firstAdded) {\r
444                                         newStr.append(sep);\r
445                                 }\r
446                                 newStr.append(partStr);\r
447                                 firstAdded = true;\r
448                         }\r
449         }\r
450         // Now we add the dates. In theory could have dates with no name, but that is their problem.\r
451         boolean foundBirth = false;\r
452                 if(null != birthDate) {\r
453                         if(firstAdded) {\r
454                                 newStr.append(sep);\r
455                         }\r
456                         newStr.append(birthDate);\r
457                 newStr.append(dateSep);         // Put this in whether there is a death date or not\r
458                         foundBirth = true;\r
459                 }\r
460                 if(null != deathDate) {\r
461                         if(!foundBirth) {\r
462                                 if(firstAdded) {\r
463                                         newStr.append(sep);\r
464                                 }\r
465                         newStr.append(dateSep);\r
466                         }\r
467                         newStr.append(deathDate);\r
468                 }\r
469                 return newStr.toString();\r
470     }\r
471     \r
472 \r
473 \r
474 }\r