]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
7e15847660da41f84cb6cd25de5590fb3cd56321
[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 import org.collectionspace.services.person.StructuredDateGroup;\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,\r
169                 Map<String, String> personInfo,\r
170                 List<PersonTermGroup> terms,\r
171                 String headerLabel){\r
172         if (terms == null || terms.isEmpty()) {\r
173             terms = getTermGroupInstance(getGeneratedIdentifier());\r
174         }\r
175         final Map<String, List<String>> EMPTY_PERSON_REPEATABLES_INFO =\r
176                 new HashMap<String, List<String>>();\r
177         return createPersonInstance(inAuthority, null /*personAuthRefName*/,\r
178                 personInfo, terms, EMPTY_PERSON_REPEATABLES_INFO, headerLabel);\r
179     }\r
180 \r
181     /**\r
182      * Creates a person instance.\r
183      *\r
184      * @param inAuthority the owning authority\r
185      * @param personAuthRefName the owning Authority ref name\r
186      * @param personInfo the person info\r
187      * @param terms a list of Person terms\r
188      * @param personRepeatablesInfo names and values of repeatable scalar fields in the Person record\r
189      * @param headerLabel the header label\r
190      * @return the multipart output\r
191      */\r
192     public static PoxPayloadOut createPersonInstance(String inAuthority, \r
193                 String personAuthRefName, Map<String, String> personInfo,\r
194                 List<PersonTermGroup> terms,\r
195                 Map<String, List<String>> personRepeatablesInfo, String headerLabel){\r
196         PersonsCommon person = new PersonsCommon();\r
197         person.setInAuthority(inAuthority);\r
198         String shortId = personInfo.get(PersonJAXBSchema.SHORT_IDENTIFIER);\r
199         if (shortId == null || shortId.isEmpty()) {\r
200                 throw new IllegalArgumentException("shortIdentifier cannot be null or empty");\r
201         }       \r
202         person.setShortIdentifier(shortId);\r
203         \r
204         String value;\r
205         List<String> values = null;\r
206 \r
207         if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_DATE))!=null) {\r
208             StructuredDateGroup birthDate = new StructuredDateGroup();\r
209             birthDate.setDateDisplayDate(value);\r
210             person.setBirthDateGroup(birthDate);\r
211         }\r
212         if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_DATE))!=null) {\r
213             StructuredDateGroup deathDate = new StructuredDateGroup();\r
214             deathDate.setDateDisplayDate(value);\r
215             person.setDeathDateGroup(deathDate);\r
216         }\r
217         if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_PLACE))!=null)\r
218                 person.setBirthPlace(value);\r
219         if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_PLACE))!=null)\r
220                 person.setDeathPlace(value);\r
221         if((value = (String)personInfo.get(PersonJAXBSchema.GENDER))!=null)\r
222                 person.setGender(value);\r
223          if((value = (String)personInfo.get(PersonJAXBSchema.BIO_NOTE))!=null)\r
224                 person.setBioNote(value);\r
225         if((value = (String)personInfo.get(PersonJAXBSchema.NAME_NOTE))!=null)\r
226                 person.setNameNote(value);\r
227         \r
228         // Set values in the Term Information Group\r
229         PersonTermGroupList termList = new PersonTermGroupList();\r
230         if (terms == null || terms.isEmpty()) {\r
231             terms = getTermGroupInstance(getGeneratedIdentifier());\r
232         }\r
233         termList.getPersonTermGroup().addAll(terms); \r
234         person.setPersonTermGroupList(termList);\r
235         \r
236         if (personRepeatablesInfo != null) {\r
237             if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.GROUPS))!=null) {\r
238                     GroupList groupsList = new GroupList();\r
239                     List<String> groups = groupsList.getGroup();\r
240                     groups.addAll(values);\r
241                     person.setGroups(groupsList);\r
242             }\r
243             if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.NATIONALITIES))!=null) {\r
244                     NationalityList nationalitiesList = new NationalityList();\r
245                     List<String> nationalities = nationalitiesList.getNationality();\r
246                     nationalities.addAll(values);\r
247                     person.setNationalities(nationalitiesList);\r
248             }\r
249 \r
250             if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.OCCUPATIONS))!=null) {\r
251                     OccupationList occupationsList = new OccupationList();\r
252                     List<String> occupations = occupationsList.getOccupation();\r
253                     occupations.addAll(values);\r
254                     person.setOccupations(occupationsList);\r
255             }\r
256             if((values = (List<String>)personRepeatablesInfo.get(PersonJAXBSchema.SCHOOLS_OR_STYLES))!=null) {\r
257                     SchoolOrStyleList schoolOrStyleList = new SchoolOrStyleList();\r
258                     List<String> schoolsOrStyles = schoolOrStyleList.getSchoolOrStyle();\r
259                     schoolsOrStyles.addAll(values);\r
260                     person.setSchoolsOrStyles(schoolOrStyleList);\r
261             }        \r
262         }\r
263 \r
264         \r
265         PoxPayloadOut multipart = new PoxPayloadOut(PersonAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);\r
266         PayloadOutputPart commonPart = multipart.addPart(person,\r
267             MediaType.APPLICATION_XML_TYPE);\r
268         commonPart.setLabel(headerLabel);\r
269 \r
270         if(logger.isDebugEnabled()){\r
271                 logger.debug("to be created, person common ", person, PersonsCommon.class);\r
272         }\r
273 \r
274         return multipart;\r
275     }\r
276     \r
277     /**\r
278      * Creates the item in authority.\r
279      *\r
280      * @param vcsid the vcsid\r
281      * @param personAuthorityRefName the person authority ref name\r
282      * @param personMap the person map. PersonJAXBSchema.SHORT_IDENTIFIER is REQUIRED.\r
283      * @param client the client\r
284      * @return the string\r
285      */\r
286     public static String createItemInAuthority(String vcsid, \r
287                 String personAuthorityRefName, Map<String,String> personMap,\r
288                 List<PersonTermGroup> terms, Map<String, List<String>> personRepeatablesMap,\r
289                 PersonAuthorityClient client ) {\r
290         // Expected status code: 201 Created\r
291         int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();\r
292         // Type of service request being tested\r
293         ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;\r
294         \r
295         String displayName = "";\r
296         if (terms !=null && terms.size() > 0) {\r
297             displayName = terms.get(0).getTermDisplayName();\r
298         }\r
299         \r
300         if(logger.isDebugEnabled()){\r
301                 logger.debug("Creating item with display name: \"" + displayName\r
302                                 +"\" in personAuthority: \"" + vcsid +"\"");\r
303         }\r
304         PoxPayloadOut multipart = \r
305                 createPersonInstance(vcsid, null /*personAuthorityRefName*/,\r
306                         personMap, terms, personRepeatablesMap, client.getItemCommonPartName());\r
307         \r
308         String result = null;\r
309         ClientResponse<Response> res = client.createItem(vcsid, multipart);\r
310         try {\r
311                 int statusCode = res.getStatus();\r
312         \r
313                 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {\r
314                         throw new RuntimeException("Could not create Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)\r
315                                         +"\" in personAuthority: \"" + vcsid //personAuthorityRefName\r
316                                         +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));\r
317                 }\r
318                 if(statusCode != EXPECTED_STATUS_CODE) {\r
319                         throw new RuntimeException("Unexpected Status when creating Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER)\r
320                                         +"\" in personAuthority: \"" + vcsid /*personAuthorityRefName*/ +"\", Status:"+ statusCode);\r
321                 }\r
322         \r
323                 result = extractId(res);\r
324         } finally {\r
325                 res.releaseConnection();\r
326         }\r
327         \r
328         return result;\r
329     }\r
330 \r
331     /**\r
332      * Creates the personAuthority ref name.\r
333      *\r
334      * @param shortId the personAuthority shortIdentifier\r
335      * @param displaySuffix displayName to be appended, if non-null\r
336      * @return the string\r
337      */\r
338     /*\r
339     public static String createPersonAuthRefName(String shortId, String displaySuffix) {\r
340         String refName = "urn:cspace:org.collectionspace.demo:personauthority:name("\r
341                         +shortId+")";\r
342         if(displaySuffix!=null&&!displaySuffix.isEmpty())\r
343                 refName += "'"+displaySuffix+"'";\r
344         return refName;\r
345     }\r
346     */\r
347 \r
348     /**\r
349      * Creates the person ref name.\r
350      *\r
351      * @param personAuthRefName the person auth ref name\r
352      * @param shortId the person shortIdentifier\r
353      * @param displaySuffix displayName to be appended, if non-null\r
354      * @return the string\r
355      */\r
356     /*\r
357     public static String createPersonRefName(\r
358                                                 String personAuthRefName, String shortId, String displaySuffix) {\r
359         String refName = personAuthRefName+":person:name("+shortId+")";\r
360         if(displaySuffix!=null&&!displaySuffix.isEmpty())\r
361                 refName += "'"+displaySuffix+"'";\r
362         return refName;\r
363     }\r
364     */\r
365 \r
366     /**\r
367      * Extract id.\r
368      *\r
369      * @param res the res\r
370      * @return the string\r
371      */\r
372     public static String extractId(ClientResponse<Response> res) {\r
373         MultivaluedMap<String, Object> mvm = res.getMetadata();\r
374         // FIXME: This may throw an NPE if the Location: header isn't present\r
375         String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);\r
376         if(logger.isDebugEnabled()){\r
377                 logger.debug("extractId:uri=" + uri);\r
378         }\r
379         String[] segments = uri.split("/");\r
380         String id = segments[segments.length - 1];\r
381         if(logger.isDebugEnabled()){\r
382                 logger.debug("id=" + id);\r
383         }\r
384         return id;\r
385     }\r
386     \r
387     /**\r
388      * Returns an error message indicating that the status code returned by a\r
389      * specific call to a service does not fall within a set of valid status\r
390      * codes for that service.\r
391      *\r
392      * @param serviceRequestType  A type of service request (e.g. CREATE, DELETE).\r
393      *\r
394      * @param statusCode  The invalid status code that was returned in the response,\r
395      *                    from submitting that type of request to the service.\r
396      *\r
397      * @return An error message.\r
398      */\r
399     public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {\r
400         return "Status code '" + statusCode + "' in response is NOT within the expected set: " +\r
401                 requestType.validStatusCodesAsString();\r
402     }\r
403 \r
404 \r
405     \r
406     /**\r
407      * Produces a default displayName from the basic name and dates fields.\r
408      * @see PersonDocumentModelHandler.prepareDefaultDisplayName() which\r
409      * duplicates this logic, until we define a service-general utils package\r
410      * that is neither client nor service specific.\r
411      * @param foreName  \r
412      * @param middleName\r
413      * @param surName\r
414      * @param birthDate\r
415      * @param deathDate\r
416      * @return display name\r
417      */\r
418     public static String prepareDefaultDisplayName(\r
419                 String foreName, String middleName, String surName, \r
420             String birthDate, String deathDate) {\r
421         StringBuilder newStr = new StringBuilder();\r
422                 final String sep = " ";\r
423                 final String dateSep = "-";\r
424                 List<String> nameStrings = \r
425                         Arrays.asList(foreName, middleName, surName);\r
426                 boolean firstAdded = false;\r
427         for(String partStr : nameStrings ){\r
428                         if(null != partStr ) {\r
429                                 if(firstAdded) {\r
430                                         newStr.append(sep);\r
431                                 }\r
432                                 newStr.append(partStr);\r
433                                 firstAdded = true;\r
434                         }\r
435         }\r
436         // Now we add the dates. In theory could have dates with no name, but that is their problem.\r
437         boolean foundBirth = false;\r
438         if(null != birthDate) {\r
439          if(firstAdded) {\r
440              newStr.append(sep);\r
441          }\r
442          newStr.append(birthDate);\r
443                  newStr.append(dateSep);     // Put this in whether there is a death date or not\r
444          foundBirth = true;\r
445         }\r
446         if(null != deathDate) {\r
447          if(!foundBirth) {\r
448              if(firstAdded) {\r
449                  newStr.append(sep);\r
450              }\r
451              newStr.append(dateSep);\r
452          }\r
453          newStr.append(deathDate);\r
454         }\r
455                 return newStr.toString();\r
456     }\r
457     \r
458     public static List<PersonTermGroup> getTermGroupInstance(String identifier) {\r
459         if (Tools.isBlank(identifier)) {\r
460             identifier = getGeneratedIdentifier();\r
461         }\r
462         List<PersonTermGroup> terms = new ArrayList<PersonTermGroup>();\r
463         PersonTermGroup term = new PersonTermGroup();\r
464         term.setTermDisplayName(identifier);\r
465         term.setTermName(identifier);\r
466         terms.add(term);\r
467         return terms;\r
468     }\r
469     \r
470     private static String getGeneratedIdentifier() {\r
471         return "id" + new Date().getTime(); \r
472    }\r
473 \r
474 }\r