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