]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
7f1b28230fe003f97ae8e937366a25b2e812e54c
[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.OutputPart;\r
49 import org.slf4j.Logger;\r
50 import org.slf4j.LoggerFactory;\r
51 \r
52 /**\r
53  * The Class PersonAuthorityClientUtils.\r
54  */\r
55 public class PersonAuthorityClientUtils {\r
56     \r
57     /** The Constant logger. */\r
58     private static final Logger logger =\r
59         LoggerFactory.getLogger(PersonAuthorityClientUtils.class);\r
60         private static final ServiceRequestType READ_REQ = ServiceRequestType.READ;\r
61 \r
62     /**\r
63      * @param csid the id of the PersonAuthority\r
64      * @param client if null, creates a new client\r
65      * @return\r
66      */\r
67     public static String getAuthorityRefName(String csid, PersonAuthorityClient client){\r
68         if (client == null) {\r
69                 client = new PersonAuthorityClient();\r
70         }\r
71         ClientResponse<String> res = client.read(csid);\r
72         try {\r
73                 int statusCode = res.getStatus();\r
74                 if(!READ_REQ.isValidStatusCode(statusCode)\r
75                         ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {\r
76                         throw new RuntimeException("Invalid status code returned: "+statusCode);\r
77                 }\r
78                 //FIXME: remove the following try catch once Aron fixes signatures\r
79                 try {\r
80                     PoxPayloadIn input = new PoxPayloadIn(res.getEntity());\r
81                     PersonauthoritiesCommon personAuthority = \r
82                         (PersonauthoritiesCommon) CollectionSpaceClientUtils.extractPart(input,\r
83                             client.getCommonPartName(), PersonauthoritiesCommon.class);\r
84                         if(personAuthority == null) {\r
85                                 throw new RuntimeException("Null personAuthority returned from service.");\r
86                         }\r
87                     return personAuthority.getRefName();\r
88                 } catch (Exception e) {\r
89                     throw new RuntimeException(e);\r
90                 }\r
91         } finally {\r
92                 res.releaseConnection();\r
93         }\r
94     }\r
95 \r
96     /**\r
97      * @param csid the id of the PersonAuthority\r
98      * @param client if null, creates a new client\r
99      * @return\r
100      */\r
101     public static String getPersonRefName(String inAuthority, String csid, PersonAuthorityClient client){\r
102         if ( client == null) {\r
103                 client = new PersonAuthorityClient();\r
104         }\r
105         ClientResponse<String> 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                     PoxPayloadIn input = new PoxPayloadIn(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 PoxPayloadOut 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         PoxPayloadOut multipart = new PoxPayloadOut(PersonAuthorityClient.SERVICE_PAYLOAD_NAME);\r
147         PayloadOutputPart commonPart = multipart.addPart(personAuthority, MediaType.APPLICATION_XML_TYPE);\r
148         commonPart.setLabel(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 PoxPayloadOut 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 PoxPayloadOut 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((value = (String)personInfo.get(PersonJAXBSchema.GENDER))!=null)\r
256                 person.setGender(value);\r
257          if((value = (String)personInfo.get(PersonJAXBSchema.BIO_NOTE))!=null)\r
258                 person.setBioNote(value);\r
259         if((value = (String)personInfo.get(PersonJAXBSchema.NAME_NOTE))!=null)\r
260                 person.setNameNote(value);\r
261         \r
262         if (personRepeatablesInfo != null) {\r
263             if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.GROUPS))!=null) {\r
264                     GroupList groupsList = new GroupList();\r
265                     List<String> groups = groupsList.getGroup();\r
266                     groups.addAll(values);\r
267                     person.setGroups(groupsList);\r
268             }\r
269             if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.NATIONALITIES))!=null) {\r
270                     NationalityList nationalitiesList = new NationalityList();\r
271                     List<String> nationalities = nationalitiesList.getNationality();\r
272                     nationalities.addAll(values);\r
273                     person.setNationalities(nationalitiesList);\r
274             }\r
275 \r
276             if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.OCCUPATIONS))!=null) {\r
277                     OccupationList occupationsList = new OccupationList();\r
278                     List<String> occupations = occupationsList.getOccupation();\r
279                     occupations.addAll(values);\r
280                     person.setOccupations(occupationsList);\r
281             }\r
282             if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.SCHOOLS_OR_STYLES))!=null) {\r
283                     SchoolOrStyleList schoolOrStyleList = new SchoolOrStyleList();\r
284                     List<String> schoolsOrStyles = schoolOrStyleList.getSchoolOrStyle();\r
285                     schoolsOrStyles.addAll(values);\r
286                     person.setSchoolsOrStyles(schoolOrStyleList);\r
287             }\r
288         }\r
289 \r
290         \r
291         PoxPayloadOut multipart = new PoxPayloadOut(PersonAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);\r
292         PayloadOutputPart commonPart = multipart.addPart(person,\r
293             MediaType.APPLICATION_XML_TYPE);\r
294         commonPart.setLabel(headerLabel);\r
295 \r
296         if(logger.isDebugEnabled()){\r
297                 logger.debug("to be created, person common ", person, PersonsCommon.class);\r
298         }\r
299 \r
300         return multipart;\r
301     }\r
302     \r
303     /**\r
304      * Creates the item in authority.\r
305      *\r
306      * @param vcsid the vcsid\r
307      * @param personAuthorityRefName the person authority ref name\r
308      * @param personMap the person map. PersonJAXBSchema.SHORT_IDENTIFIER is REQUIRED.\r
309      * @param client the client\r
310      * @return the string\r
311      */\r
312     public static String createItemInAuthority(String vcsid, \r
313                 String personAuthorityRefName, Map<String,String> personMap,\r
314                 Map<String, List<String>> personRepeatablesMap, PersonAuthorityClient client ) {\r
315         // Expected status code: 201 Created\r
316         int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();\r
317         // Type of service request being tested\r
318         ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;\r
319         \r
320         String displayName = personMap.get(PersonJAXBSchema.DISPLAY_NAME);\r
321         String displayNameComputedStr = personMap.get(PersonJAXBSchema.DISPLAY_NAME_COMPUTED);\r
322         boolean displayNameComputed = (displayNameComputedStr==null) || displayNameComputedStr.equalsIgnoreCase("true");\r
323         if( displayName == null ) {\r
324                 if(!displayNameComputed) {\r
325                         throw new RuntimeException(\r
326                         "CreateItem: Must supply a displayName if displayNameComputed is set to false.");\r
327                 }\r
328                 displayName = \r
329                         prepareDefaultDisplayName(\r
330                         personMap.get(PersonJAXBSchema.FORE_NAME),\r
331                         personMap.get(PersonJAXBSchema.MIDDLE_NAME),\r
332                         personMap.get(PersonJAXBSchema.SUR_NAME),\r
333                         personMap.get(PersonJAXBSchema.BIRTH_DATE),\r
334                         personMap.get(PersonJAXBSchema.DEATH_DATE));\r
335                 personMap.put(PersonJAXBSchema.DISPLAY_NAME, displayName);\r
336         }\r
337         String shortDisplayName = personMap.get(PersonJAXBSchema.SHORT_DISPLAY_NAME);\r
338         String shortDisplayNameComputedStr = personMap.get(PersonJAXBSchema.SHORT_DISPLAY_NAME_COMPUTED);\r
339         boolean shortDisplayNameComputed = (shortDisplayNameComputedStr==null) || shortDisplayNameComputedStr.equalsIgnoreCase("true");\r
340         if( shortDisplayName == null ) {\r
341                 if(!shortDisplayNameComputed) {\r
342                         throw new RuntimeException(\r
343                         "CreateItem: Must supply a shortDisplayName if shortDisplayNameComputed is set to false.");\r
344                 }\r
345                 shortDisplayName = \r
346                         prepareDefaultDisplayName(\r
347                         personMap.get(PersonJAXBSchema.FORE_NAME), null,\r
348                         personMap.get(PersonJAXBSchema.SUR_NAME),null,null);\r
349                 personMap.put(PersonJAXBSchema.SHORT_DISPLAY_NAME, shortDisplayName);\r
350         }\r
351         \r
352         if(logger.isDebugEnabled()){\r
353                 logger.debug("Import: Create Item: \"" + displayName\r
354                                 +"\" in personAuthorityulary: \"" + personAuthorityRefName +"\"");\r
355         }\r
356         PoxPayloadOut multipart = \r
357                 createPersonInstance(vcsid, personAuthorityRefName,\r
358                         personMap, personRepeatablesMap, client.getItemCommonPartName());\r
359         \r
360         String result = null;\r
361         ClientResponse<Response> res = client.createItem(vcsid, multipart);\r
362         try {\r
363                 int statusCode = res.getStatus();\r
364         \r
365                 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {\r
366                         throw new RuntimeException("Could not create Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)\r
367                                         +"\" in personAuthority: \"" + personAuthorityRefName\r
368                                         +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));\r
369                 }\r
370                 if(statusCode != EXPECTED_STATUS_CODE) {\r
371                         throw new RuntimeException("Unexpected Status when creating Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)\r
372                                         +"\" in personAuthority: \"" + personAuthorityRefName +"\", Status:"+ statusCode);\r
373                 }\r
374         \r
375                 result = extractId(res);\r
376         } finally {\r
377                 res.releaseConnection();\r
378         }\r
379         \r
380         return result;\r
381     }\r
382 \r
383     /**\r
384      * Creates the personAuthority ref name.\r
385      *\r
386      * @param shortId the personAuthority shortIdentifier\r
387      * @param displaySuffix displayName to be appended, if non-null\r
388      * @return the string\r
389      */\r
390     public static String createPersonAuthRefName(String shortId, String displaySuffix) {\r
391         String refName = "urn:cspace:org.collectionspace.demo:personauthority:name("\r
392                         +shortId+")";\r
393         if(displaySuffix!=null&&!displaySuffix.isEmpty())\r
394                 refName += "'"+displaySuffix+"'";\r
395         return refName;\r
396     }\r
397 \r
398     /**\r
399      * Creates the person ref name.\r
400      *\r
401      * @param personAuthRefName the person auth ref name\r
402      * @param shortId the person shortIdentifier\r
403      * @param displaySuffix displayName to be appended, if non-null\r
404      * @return the string\r
405      */\r
406     public static String createPersonRefName(\r
407                                                 String personAuthRefName, String shortId, String displaySuffix) {\r
408         String refName = personAuthRefName+":person:name("+shortId+")";\r
409         if(displaySuffix!=null&&!displaySuffix.isEmpty())\r
410                 refName += "'"+displaySuffix+"'";\r
411         return refName;\r
412     }\r
413 \r
414     /**\r
415      * Extract id.\r
416      *\r
417      * @param res the res\r
418      * @return the string\r
419      */\r
420     public static String extractId(ClientResponse<Response> res) {\r
421         MultivaluedMap<String, Object> mvm = res.getMetadata();\r
422         // FIXME: This may throw an NPE if the Location: header isn't present\r
423         String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);\r
424         if(logger.isDebugEnabled()){\r
425                 logger.debug("extractId:uri=" + uri);\r
426         }\r
427         String[] segments = uri.split("/");\r
428         String id = segments[segments.length - 1];\r
429         if(logger.isDebugEnabled()){\r
430                 logger.debug("id=" + id);\r
431         }\r
432         return id;\r
433     }\r
434     \r
435     /**\r
436      * Returns an error message indicating that the status code returned by a\r
437      * specific call to a service does not fall within a set of valid status\r
438      * codes for that service.\r
439      *\r
440      * @param serviceRequestType  A type of service request (e.g. CREATE, DELETE).\r
441      *\r
442      * @param statusCode  The invalid status code that was returned in the response,\r
443      *                    from submitting that type of request to the service.\r
444      *\r
445      * @return An error message.\r
446      */\r
447     public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {\r
448         return "Status code '" + statusCode + "' in response is NOT within the expected set: " +\r
449                 requestType.validStatusCodesAsString();\r
450     }\r
451 \r
452 \r
453     \r
454     /**\r
455      * Produces a default displayName from the basic name and dates fields.\r
456      * @see PersonDocumentModelHandler.prepareDefaultDisplayName() which\r
457      * duplicates this logic, until we define a service-general utils package\r
458      * that is neither client nor service specific.\r
459      * @param foreName  \r
460      * @param middleName\r
461      * @param surName\r
462      * @param birthDate\r
463      * @param deathDate\r
464      * @return display name\r
465      */\r
466     public static String prepareDefaultDisplayName(\r
467                 String foreName, String middleName, String surName,\r
468                 String birthDate, String deathDate ) {\r
469         StringBuilder newStr = new StringBuilder();\r
470                 final String sep = " ";\r
471                 final String dateSep = "-";\r
472                 List<String> nameStrings = \r
473                         Arrays.asList(foreName, middleName, surName);\r
474                 boolean firstAdded = false;\r
475         for(String partStr : nameStrings ){\r
476                         if(null != partStr ) {\r
477                                 if(firstAdded) {\r
478                                         newStr.append(sep);\r
479                                 }\r
480                                 newStr.append(partStr);\r
481                                 firstAdded = true;\r
482                         }\r
483         }\r
484         // Now we add the dates. In theory could have dates with no name, but that is their problem.\r
485         boolean foundBirth = false;\r
486                 if(null != birthDate) {\r
487                         if(firstAdded) {\r
488                                 newStr.append(sep);\r
489                         }\r
490                         newStr.append(birthDate);\r
491                 newStr.append(dateSep);         // Put this in whether there is a death date or not\r
492                         foundBirth = true;\r
493                 }\r
494                 if(null != deathDate) {\r
495                         if(!foundBirth) {\r
496                                 if(firstAdded) {\r
497                                         newStr.append(sep);\r
498                                 }\r
499                         newStr.append(dateSep);\r
500                         }\r
501                         newStr.append(deathDate);\r
502                 }\r
503                 return newStr.toString();\r
504     }\r
505     \r
506 \r
507 \r
508 }\r