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