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