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