]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
a1f5a1f53933d9ca32167a7d4b28c8f446f02a62
[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.PersonTermGroup;\r
45 import org.collectionspace.services.person.PersonTermGroupList;\r
46 import org.collectionspace.services.person.PersonsCommon;\r
47 import org.collectionspace.services.person.PersonauthoritiesCommon;\r
48 import org.collectionspace.services.person.SchoolOrStyleList;\r
49 import org.jboss.resteasy.client.ClientResponse;\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         }\r
73         ClientResponse<String> res = client.read(csid);\r
74         try {\r
75                 int statusCode = res.getStatus();\r
76                 if(!READ_REQ.isValidStatusCode(statusCode)\r
77                         ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {\r
78                         throw new RuntimeException("Invalid status code returned: "+statusCode);\r
79                 }\r
80                 //FIXME: remove the following try catch once Aron fixes signatures\r
81                 try {\r
82                     PoxPayloadIn input = new PoxPayloadIn(res.getEntity());\r
83                     PersonauthoritiesCommon personAuthority = \r
84                         (PersonauthoritiesCommon) CollectionSpaceClientUtils.extractPart(input,\r
85                             client.getCommonPartName(), PersonauthoritiesCommon.class);\r
86                         if(personAuthority == null) {\r
87                                 throw new RuntimeException("Null personAuthority returned from service.");\r
88                         }\r
89                     return personAuthority.getRefName();\r
90                 } catch (Exception e) {\r
91                     throw new RuntimeException(e);\r
92                 }\r
93         } finally {\r
94                 res.releaseConnection();\r
95         }\r
96     }\r
97 \r
98     /**\r
99      * @param csid the id of the PersonAuthority\r
100      * @param client if null, creates a new client\r
101      * @return\r
102      */\r
103     public static String getPersonRefName(String inAuthority, String csid, PersonAuthorityClient client){\r
104         if ( client == null) {\r
105                 client = new PersonAuthorityClient();\r
106         }\r
107         ClientResponse<String> res = client.readItem(inAuthority, csid);\r
108         try {\r
109                 int statusCode = res.getStatus();\r
110                 if(!READ_REQ.isValidStatusCode(statusCode)\r
111                                 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {\r
112                         throw new RuntimeException("Invalid status code returned: "+statusCode);\r
113                 }\r
114                 //FIXME: remove the following try catch once Aron fixes signatures\r
115                 try {\r
116                     PoxPayloadIn input = new PoxPayloadIn(res.getEntity());\r
117                     PersonsCommon person = \r
118                         (PersonsCommon) CollectionSpaceClientUtils.extractPart(input,\r
119                             client.getItemCommonPartName(), PersonsCommon.class);\r
120                         if (person == null) {\r
121                                 throw new RuntimeException("Null person returned from service.");\r
122                         }\r
123                     return person.getRefName();\r
124                 } catch (Exception e) {\r
125                     throw new RuntimeException(e);\r
126                 }\r
127         } finally {\r
128                 res.releaseConnection();\r
129         }\r
130     }\r
131 \r
132     /**\r
133      * Creates the person authority instance.\r
134      *\r
135      * @param displayName the display name\r
136      * @param shortIdentifier the short Id \r
137      * @param headerLabel the header label\r
138      * @return the multipart output\r
139      */\r
140     public static PoxPayloadOut createPersonAuthorityInstance(\r
141                 String displayName, String shortIdentifier, String headerLabel ) {\r
142         PersonauthoritiesCommon personAuthority = new PersonauthoritiesCommon();\r
143         personAuthority.setDisplayName(displayName);\r
144         personAuthority.setShortIdentifier(shortIdentifier);\r
145         //String refName = createPersonAuthRefName(shortIdentifier, displayName);\r
146         //personAuthority.setRefName(refName);\r
147         personAuthority.setVocabType("PersonAuthority");\r
148         PoxPayloadOut multipart = new PoxPayloadOut(PersonAuthorityClient.SERVICE_PAYLOAD_NAME);\r
149         PayloadOutputPart commonPart = multipart.addPart(personAuthority, MediaType.APPLICATION_XML_TYPE);\r
150         commonPart.setLabel(headerLabel);\r
151 \r
152         if(logger.isDebugEnabled()){\r
153                 logger.debug("to be created, personAuthority common ", \r
154                                         personAuthority, PersonauthoritiesCommon.class);\r
155         }\r
156 \r
157         return multipart;\r
158     }\r
159 \r
160     /**\r
161      * Creates a person instance.\r
162      *\r
163      * @param inAuthority the owning authority\r
164      * @param personAuthRefName the owning Authority ref name\r
165      * @param personInfo the person info\r
166      * @param headerLabel the header label\r
167      * @return the multipart output\r
168      */\r
169     public static PoxPayloadOut createPersonInstance(String inAuthority,\r
170                 String personAuthRefName,\r
171                 Map<String, String> personInfo,\r
172                 List<PersonTermGroup> terms,\r
173                 String headerLabel){\r
174         final Map<String, List<String>> EMPTY_PERSON_REPEATABLES_INFO =\r
175                 new HashMap<String, List<String>>();\r
176         return createPersonInstance(inAuthority, null /*personAuthRefName*/,\r
177                 personInfo, terms, EMPTY_PERSON_REPEATABLES_INFO, headerLabel);\r
178     }\r
179 \r
180     /**\r
181      * Creates a person instance.\r
182      *\r
183      * @param inAuthority the owning authority\r
184      * @param personAuthRefName the owning Authority ref name\r
185      * @param personInfo the person info\r
186      * @param terms a list of Person terms\r
187      * @param personRepeatablesInfo names and values of repeatable scalar fields in the Person record\r
188      * @param headerLabel the header label\r
189      * @return the multipart output\r
190      */\r
191     public static PoxPayloadOut createPersonInstance(String inAuthority, \r
192                 String personAuthRefName, Map<String, String> personInfo,\r
193                 List<PersonTermGroup> terms,\r
194                 Map<String, List<String>> personRepeatablesInfo, String headerLabel){\r
195         PersonsCommon person = new PersonsCommon();\r
196         person.setInAuthority(inAuthority);\r
197         String shortId = personInfo.get(PersonJAXBSchema.SHORT_IDENTIFIER);\r
198         if (shortId == null || shortId.isEmpty()) {\r
199                 throw new IllegalArgumentException("shortIdentifier cannot be null or empty");\r
200         }       \r
201         person.setShortIdentifier(shortId);\r
202         \r
203         String value;\r
204         List<String> values = null;\r
205 \r
206         if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_DATE))!=null)\r
207                 person.setBirthDate(value);\r
208         if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_DATE))!=null)\r
209                 person.setDeathDate(value);\r
210         if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_PLACE))!=null)\r
211                 person.setBirthPlace(value);\r
212         if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_PLACE))!=null)\r
213                 person.setDeathPlace(value);\r
214         if((value = (String)personInfo.get(PersonJAXBSchema.GENDER))!=null)\r
215                 person.setGender(value);\r
216          if((value = (String)personInfo.get(PersonJAXBSchema.BIO_NOTE))!=null)\r
217                 person.setBioNote(value);\r
218         if((value = (String)personInfo.get(PersonJAXBSchema.NAME_NOTE))!=null)\r
219                 person.setNameNote(value);\r
220         \r
221         // Set values in the Term Information Group\r
222         PersonTermGroupList termList = new PersonTermGroupList();\r
223         termList.getPersonTermGroup().addAll(terms);\r
224         person.setPersonTermGroupList(termList);\r
225         \r
226         \r
227         if (personRepeatablesInfo != null) {\r
228             if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.GROUPS))!=null) {\r
229                     GroupList groupsList = new GroupList();\r
230                     List<String> groups = groupsList.getGroup();\r
231                     groups.addAll(values);\r
232                     person.setGroups(groupsList);\r
233             }\r
234             if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.NATIONALITIES))!=null) {\r
235                     NationalityList nationalitiesList = new NationalityList();\r
236                     List<String> nationalities = nationalitiesList.getNationality();\r
237                     nationalities.addAll(values);\r
238                     person.setNationalities(nationalitiesList);\r
239             }\r
240 \r
241             if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.OCCUPATIONS))!=null) {\r
242                     OccupationList occupationsList = new OccupationList();\r
243                     List<String> occupations = occupationsList.getOccupation();\r
244                     occupations.addAll(values);\r
245                     person.setOccupations(occupationsList);\r
246             }\r
247             if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.SCHOOLS_OR_STYLES))!=null) {\r
248                     SchoolOrStyleList schoolOrStyleList = new SchoolOrStyleList();\r
249                     List<String> schoolsOrStyles = schoolOrStyleList.getSchoolOrStyle();\r
250                     schoolsOrStyles.addAll(values);\r
251                     person.setSchoolsOrStyles(schoolOrStyleList);\r
252             }        \r
253         }\r
254 \r
255         \r
256         PoxPayloadOut multipart = new PoxPayloadOut(PersonAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);\r
257         PayloadOutputPart commonPart = multipart.addPart(person,\r
258             MediaType.APPLICATION_XML_TYPE);\r
259         commonPart.setLabel(headerLabel);\r
260 \r
261         if(logger.isDebugEnabled()){\r
262                 logger.debug("to be created, person common ", person, PersonsCommon.class);\r
263         }\r
264 \r
265         return multipart;\r
266     }\r
267     \r
268     /**\r
269      * Creates the item in authority.\r
270      *\r
271      * @param vcsid the vcsid\r
272      * @param personAuthorityRefName the person authority ref name\r
273      * @param personMap the person map. PersonJAXBSchema.SHORT_IDENTIFIER is REQUIRED.\r
274      * @param client the client\r
275      * @return the string\r
276      */\r
277     public static String createItemInAuthority(String vcsid, \r
278                 String personAuthorityRefName, Map<String,String> personMap,\r
279                 List<PersonTermGroup> terms, Map<String, List<String>> personRepeatablesMap,\r
280                 PersonAuthorityClient client ) {\r
281         // Expected status code: 201 Created\r
282         int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();\r
283         // Type of service request being tested\r
284         ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;\r
285         \r
286         String displayName = "";\r
287         if (terms !=null && terms.size() > 0) {\r
288             displayName = terms.get(0).getTermDisplayName();\r
289         }\r
290         \r
291         if(logger.isDebugEnabled()){\r
292                 logger.debug("Creating item with display name: \"" + displayName\r
293                                 +"\" in personAuthority: \"" + vcsid +"\"");\r
294         }\r
295         PoxPayloadOut multipart = \r
296                 createPersonInstance(vcsid, null /*personAuthorityRefName*/,\r
297                         personMap, terms, personRepeatablesMap, client.getItemCommonPartName());\r
298         \r
299         String result = null;\r
300         ClientResponse<Response> res = client.createItem(vcsid, multipart);\r
301         try {\r
302                 int statusCode = res.getStatus();\r
303         \r
304                 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {\r
305                         throw new RuntimeException("Could not create Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)\r
306                                         +"\" in personAuthority: \"" + vcsid //personAuthorityRefName\r
307                                         +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));\r
308                 }\r
309                 if(statusCode != EXPECTED_STATUS_CODE) {\r
310                         throw new RuntimeException("Unexpected Status when creating Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)\r
311                                         +"\" in personAuthority: \"" + vcsid /*personAuthorityRefName*/ +"\", Status:"+ statusCode);\r
312                 }\r
313         \r
314                 result = extractId(res);\r
315         } finally {\r
316                 res.releaseConnection();\r
317         }\r
318         \r
319         return result;\r
320     }\r
321 \r
322     /**\r
323      * Creates the personAuthority ref name.\r
324      *\r
325      * @param shortId the personAuthority shortIdentifier\r
326      * @param displaySuffix displayName to be appended, if non-null\r
327      * @return the string\r
328      */\r
329     /*\r
330     public static String createPersonAuthRefName(String shortId, String displaySuffix) {\r
331         String refName = "urn:cspace:org.collectionspace.demo:personauthority:name("\r
332                         +shortId+")";\r
333         if(displaySuffix!=null&&!displaySuffix.isEmpty())\r
334                 refName += "'"+displaySuffix+"'";\r
335         return refName;\r
336     }\r
337     */\r
338 \r
339     /**\r
340      * Creates the person ref name.\r
341      *\r
342      * @param personAuthRefName the person auth ref name\r
343      * @param shortId the person shortIdentifier\r
344      * @param displaySuffix displayName to be appended, if non-null\r
345      * @return the string\r
346      */\r
347     /*\r
348     public static String createPersonRefName(\r
349                                                 String personAuthRefName, String shortId, String displaySuffix) {\r
350         String refName = personAuthRefName+":person:name("+shortId+")";\r
351         if(displaySuffix!=null&&!displaySuffix.isEmpty())\r
352                 refName += "'"+displaySuffix+"'";\r
353         return refName;\r
354     }\r
355     */\r
356 \r
357     /**\r
358      * Extract id.\r
359      *\r
360      * @param res the res\r
361      * @return the string\r
362      */\r
363     public static String extractId(ClientResponse<Response> res) {\r
364         MultivaluedMap<String, Object> mvm = res.getMetadata();\r
365         // FIXME: This may throw an NPE if the Location: header isn't present\r
366         String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);\r
367         if(logger.isDebugEnabled()){\r
368                 logger.debug("extractId:uri=" + uri);\r
369         }\r
370         String[] segments = uri.split("/");\r
371         String id = segments[segments.length - 1];\r
372         if(logger.isDebugEnabled()){\r
373                 logger.debug("id=" + id);\r
374         }\r
375         return id;\r
376     }\r
377     \r
378     /**\r
379      * Returns an error message indicating that the status code returned by a\r
380      * specific call to a service does not fall within a set of valid status\r
381      * codes for that service.\r
382      *\r
383      * @param serviceRequestType  A type of service request (e.g. CREATE, DELETE).\r
384      *\r
385      * @param statusCode  The invalid status code that was returned in the response,\r
386      *                    from submitting that type of request to the service.\r
387      *\r
388      * @return An error message.\r
389      */\r
390     public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {\r
391         return "Status code '" + statusCode + "' in response is NOT within the expected set: " +\r
392                 requestType.validStatusCodesAsString();\r
393     }\r
394 \r
395 \r
396     \r
397     /**\r
398      * Produces a default displayName from the basic name and dates fields.\r
399      * @see PersonDocumentModelHandler.prepareDefaultDisplayName() which\r
400      * duplicates this logic, until we define a service-general utils package\r
401      * that is neither client nor service specific.\r
402      * @param foreName  \r
403      * @param middleName\r
404      * @param surName\r
405      * @param birthDate\r
406      * @param deathDate\r
407      * @return display name\r
408      */\r
409     public static String prepareDefaultDisplayName(\r
410                 String foreName, String middleName, String surName,\r
411                 String birthDate, String deathDate ) {\r
412         StringBuilder newStr = new StringBuilder();\r
413                 final String sep = " ";\r
414                 final String dateSep = "-";\r
415                 List<String> nameStrings = \r
416                         Arrays.asList(foreName, middleName, surName);\r
417                 boolean firstAdded = false;\r
418         for(String partStr : nameStrings ){\r
419                         if(null != partStr ) {\r
420                                 if(firstAdded) {\r
421                                         newStr.append(sep);\r
422                                 }\r
423                                 newStr.append(partStr);\r
424                                 firstAdded = true;\r
425                         }\r
426         }\r
427         // Now we add the dates. In theory could have dates with no name, but that is their problem.\r
428         boolean foundBirth = false;\r
429                 if(null != birthDate) {\r
430                         if(firstAdded) {\r
431                                 newStr.append(sep);\r
432                         }\r
433                         newStr.append(birthDate);\r
434                 newStr.append(dateSep);         // Put this in whether there is a death date or not\r
435                         foundBirth = true;\r
436                 }\r
437                 if(null != deathDate) {\r
438                         if(!foundBirth) {\r
439                                 if(firstAdded) {\r
440                                         newStr.append(sep);\r
441                                 }\r
442                         newStr.append(dateSep);\r
443                         }\r
444                         newStr.append(deathDate);\r
445                 }\r
446                 return newStr.toString();\r
447     }\r
448     \r
449 \r
450 \r
451 }\r