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