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