]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
a734425a3e46d54c69fb68e6a07fe4b1649b4633
[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.List;\r
32 import java.util.Map;\r
33 \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
37 \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
48 \r
49 /**\r
50  * The Class PersonAuthorityClientUtils.\r
51  */\r
52 public class PersonAuthorityClientUtils {\r
53     \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
58 \r
59     /**\r
60      * @param csid the id of the PersonAuthority\r
61      * @param client if null, creates a new client\r
62      * @return\r
63      */\r
64     public static String getAuthorityRefName(String csid, PersonAuthorityClient client){\r
65         if(client==null)\r
66                 client = new PersonAuthorityClient();\r
67         ClientResponse<MultipartInput> res = client.read(csid);\r
68         try {\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
73                 }\r
74                 //FIXME: remove the following try catch once Aron fixes signatures\r
75                 try {\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
82                         }\r
83                     return personAuthority.getRefName();\r
84                 } catch (Exception e) {\r
85                     throw new RuntimeException(e);\r
86                 }\r
87         } finally {\r
88                 res.releaseConnection();\r
89         }\r
90     }\r
91 \r
92     /**\r
93      * @param csid the id of the PersonAuthority\r
94      * @param client if null, creates a new client\r
95      * @return\r
96      */\r
97     public static String getPersonRefName(String inAuthority, String csid, PersonAuthorityClient client){\r
98         if(client==null)\r
99                 client = new PersonAuthorityClient();\r
100         ClientResponse<MultipartInput> res = client.readItem(inAuthority, csid);\r
101         try {\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
106                 }\r
107                 //FIXME: remove the following try catch once Aron fixes signatures\r
108                 try {\r
109                     MultipartInput input = (MultipartInput) res.getEntity();\r
110                     PersonsCommon person = \r
111                         (PersonsCommon) CollectionSpaceClientUtils.extractPart(input,\r
112                             client.getItemCommonPartName(), PersonsCommon.class);\r
113                         if(person==null) {\r
114                                 throw new RuntimeException("Null person returned from service.");\r
115                         }\r
116                     return person.getRefName();\r
117                 } catch (Exception e) {\r
118                     throw new RuntimeException(e);\r
119                 }\r
120         } finally {\r
121                 res.releaseConnection();\r
122         }\r
123     }\r
124 \r
125     /**\r
126      * Creates the person authority instance.\r
127      *\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
132      */\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
144 \r
145         if(logger.isDebugEnabled()){\r
146                 logger.debug("to be created, personAuthority common ", \r
147                                         personAuthority, PersonauthoritiesCommon.class);\r
148         }\r
149 \r
150         return multipart;\r
151     }\r
152 \r
153     /**\r
154      * Creates the person instance.\r
155      *\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
161      */\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
169         }       \r
170         person.setShortIdentifier(shortId);\r
171         \r
172         //\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
176         //\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
181         }\r
182         person.setDisplayNameComputed(displayNameComputed);\r
183 \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
188         }       \r
189         String refName = createPersonRefName(personAuthRefName, shortId, displayName);\r
190         person.setRefName(refName);\r
191         \r
192         String value;\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
229         \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
234 \r
235         if(logger.isDebugEnabled()){\r
236                 logger.debug("to be created, person common ", person, PersonsCommon.class);\r
237         }\r
238 \r
239         return multipart;\r
240     }\r
241     \r
242     /**\r
243      * Creates the item in authority.\r
244      *\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
250      */\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
258         \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
266                 }\r
267                 displayName = \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
275         }\r
276         \r
277         if(logger.isDebugEnabled()){\r
278                 logger.debug("Import: Create Item: \"" + displayName\r
279                                 +"\" in personAuthorityulary: \"" + personAuthorityRefName +"\"");\r
280         }\r
281         MultipartOutput multipart = \r
282                 createPersonInstance(vcsid, personAuthorityRefName,\r
283                         personMap, client.getItemCommonPartName());\r
284         \r
285         String result = null;\r
286         ClientResponse<Response> res = client.createItem(vcsid, multipart);\r
287         try {\r
288                 int statusCode = res.getStatus();\r
289         \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
294                 }\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
298                 }\r
299         \r
300                 result = extractId(res);\r
301         } finally {\r
302                 res.releaseConnection();\r
303         }\r
304         \r
305         return result;\r
306     }\r
307 \r
308     /**\r
309      * Creates the personAuthority ref name.\r
310      *\r
311      * @param shortId the personAuthority shortIdentifier\r
312      * @param displaySuffix displayName to be appended, if non-null\r
313      * @return the string\r
314      */\r
315     public static String createPersonAuthRefName(String shortId, String displaySuffix) {\r
316         String refName = "urn:cspace:org.collectionspace.demo:personauthority:name("\r
317                         +shortId+")";\r
318         if(displaySuffix!=null&&!displaySuffix.isEmpty())\r
319                 refName += "'"+displaySuffix+"'";\r
320         return refName;\r
321     }\r
322 \r
323     /**\r
324      * Creates the person ref name.\r
325      *\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
330      */\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
336         return refName;\r
337     }\r
338 \r
339     /**\r
340      * Extract id.\r
341      *\r
342      * @param res the res\r
343      * @return the string\r
344      */\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
350         }\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
355         }\r
356         return id;\r
357     }\r
358     \r
359     /**\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
363      *\r
364      * @param serviceRequestType  A type of service request (e.g. CREATE, DELETE).\r
365      *\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
368      *\r
369      * @return An error message.\r
370      */\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
374     }\r
375 \r
376 \r
377     \r
378     /**\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
383      * @param foreName  \r
384      * @param middleName\r
385      * @param surName\r
386      * @param birthDate\r
387      * @param deathDate\r
388      * @return display name\r
389      */\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
401                                 if(firstAdded) {\r
402                                         newStr.append(sep);\r
403                                 }\r
404                                 newStr.append(partStr);\r
405                                 firstAdded = true;\r
406                         }\r
407         }\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
411                         if(firstAdded) {\r
412                                 newStr.append(sep);\r
413                         }\r
414                         newStr.append(birthDate);\r
415                 newStr.append(dateSep);         // Put this in whether there is a death date or not\r
416                         foundBirth = true;\r
417                 }\r
418                 if(null != deathDate) {\r
419                         if(!foundBirth) {\r
420                                 if(firstAdded) {\r
421                                         newStr.append(sep);\r
422                                 }\r
423                         newStr.append(dateSep);\r
424                         }\r
425                         newStr.append(deathDate);\r
426                 }\r
427                 return newStr.toString();\r
428     }\r
429     \r
430 \r
431 \r
432 }\r