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