]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
69520c7b18e85ce74f3bf1130759394123fd278c
[tmp/jakarta-migration.git] /
1 /**     
2  * This document is a part of the source code and related artifacts
3  * for CollectionSpace, an open source collections management system
4  * for museums and related institutions:
5  *
6  * http://www.collectionspace.org
7  * http://wiki.collectionspace.org
8  *
9  * Copyright © 2009 University of California, Berkeley
10  *
11  * Licensed under the Educational Community License (ECL), Version 2.0.
12  * You may not use this file except in compliance with this License.
13  *
14  * You may obtain a copy of the ECL 2.0 License at
15  * https://source.collectionspace.org/collection-space/LICENSE.txt
16  */
17 package org.collectionspace.services.client;
18
19 import java.util.ArrayList;
20 import java.util.Date;
21 import java.util.HashMap;
22 import java.util.List;
23 import java.util.Map;
24
25 import javax.ws.rs.core.MediaType;
26 import javax.ws.rs.core.MultivaluedMap;
27 import javax.ws.rs.core.Response;
28
29 import org.collectionspace.services.OrganizationJAXBSchema;
30 import org.collectionspace.services.client.test.ServiceRequestType;
31 import org.collectionspace.services.common.api.Tools;
32
33 import org.collectionspace.services.organization.StructuredDateGroup;
34 import org.collectionspace.services.organization.ContactNameList;
35 import org.collectionspace.services.organization.FunctionList;
36 import org.collectionspace.services.organization.GroupList;
37 import org.collectionspace.services.organization.HistoryNoteList;
38 import org.collectionspace.services.organization.OrganizationsCommon;
39 import org.collectionspace.services.organization.OrgauthoritiesCommon;
40 import org.collectionspace.services.organization.OrgTermGroup;
41 import org.collectionspace.services.organization.OrgTermGroupList;
42
43 import org.jboss.resteasy.client.ClientResponse;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * OrgAuthorityClientUtils.
49  */
50 public class OrgAuthorityClientUtils {
51     
52     /** The Constant logger. */
53     private static final Logger logger =
54         LoggerFactory.getLogger(OrgAuthorityClientUtils.class);
55         private static final ServiceRequestType READ_REQ = ServiceRequestType.READ;
56
57     /**
58      * @param csid the id of the OrgAuthority
59      * @param client if null, creates a new client
60      * @return
61      * @throws Exception 
62      */
63     public static String getAuthorityRefName(String csid, OrganizationClient client) throws Exception{
64         if (client==null) {
65                 client = new OrganizationClient();
66         }
67         
68         Response res = client.read(csid);
69         try {
70                 int statusCode = res.getStatus();
71                 if (!READ_REQ.isValidStatusCode(statusCode) || statusCode != CollectionSpaceClientUtils.STATUS_OK) {
72                         throw new RuntimeException("Invalid status code returned: "+statusCode);
73                 }
74                 //FIXME: remove the following try catch once Aron fixes signatures
75                 try {
76                     PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
77                     OrgauthoritiesCommon orgAuthority = 
78                         (OrgauthoritiesCommon) CollectionSpaceClientUtils.extractPart(input,
79                             client.getCommonPartName(), OrgauthoritiesCommon.class);
80                         if(orgAuthority==null) {
81                                 throw new RuntimeException("Null orgAuthority returned from service.");
82                         }
83                     return orgAuthority.getRefName();
84                 } catch (Exception e) {
85                     throw new RuntimeException(e);
86                 }
87         } finally {
88                 res.close();
89         }
90     }
91
92     /**
93      * @param inAuthority the ID of the parent OrgAuthority
94      * @param csid the ID of the Organization
95      * @param client if null, creates a new client
96      * @return
97      * @throws Exception 
98      */
99     public static String getOrgRefName(String inAuthority, String csid, OrganizationClient client) throws Exception{
100         if (client == null) {
101                 client = new OrganizationClient();
102         }
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                     OrganizationsCommon org = 
115                         (OrganizationsCommon) CollectionSpaceClientUtils.extractPart(input,
116                             client.getItemCommonPartName(), OrganizationsCommon.class);
117                         if(org==null) {
118                                 throw new RuntimeException("Null Organization returned from service.");
119                         }
120                     return org.getRefName();
121                 } catch (Exception e) {
122                     throw new RuntimeException(e);
123                 }
124         } finally {
125                 res.close();
126         }
127     }
128
129     /**
130      * Creates the org 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 createOrgAuthorityInstance(
138                 String displayName, String shortIdentifier, String headerLabel ) {
139         OrgauthoritiesCommon orgAuthority = new OrgauthoritiesCommon();
140         orgAuthority.setDisplayName(displayName);
141         orgAuthority.setShortIdentifier(shortIdentifier);
142         //String refName = createOrgAuthRefName(shortIdentifier, displayName);
143         //orgAuthority.setRefName(refName);
144         orgAuthority.setVocabType("OrgAuthority");
145         PoxPayloadOut multipart = new PoxPayloadOut(OrganizationClient.SERVICE_PAYLOAD_NAME);
146         PayloadOutputPart commonPart = multipart.addPart(orgAuthority, MediaType.APPLICATION_XML_TYPE);
147         commonPart.setLabel(headerLabel);
148
149         if(logger.isDebugEnabled()){
150                 logger.debug("to be created, orgAuthority common ",
151                         orgAuthority, OrgauthoritiesCommon.class);
152         }
153
154         return multipart;
155     }
156
157     /**
158      * Creates the item in authority.
159      *
160      * @param inAuthority the owning authority
161      * @param orgAuthorityRefName the owning Authority ref name
162      * @param orgInfo the org info. OrganizationJAXBSchema.SHORT_IDENTIFIER is REQUIRED.
163      * @param client the client
164      * @return the string
165      */
166     public static String createItemInAuthority( String inAuthority,
167                 String orgAuthorityRefName, Map<String, String> orgInfo, List<OrgTermGroup> terms,
168                 Map<String, List<String>> orgRepeatablesInfo, OrganizationClient client) {
169         // Expected status code: 201 Created
170         int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
171         // Type of service request being tested
172         ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
173
174         String displayName = "";
175         if ((terms !=null) && (! terms.isEmpty())) {
176             displayName = terms.get(0).getTermDisplayName();
177         }
178
179         if(logger.isDebugEnabled()){
180                 logger.debug("Import: Create Item: \""+displayName
181                                 +"\" in orgAuthority: \"" + orgAuthorityRefName +"\"");
182         }
183         PoxPayloadOut multipart =
184                 createOrganizationInstance(orgAuthorityRefName, 
185                                 orgInfo, terms, orgRepeatablesInfo, client.getItemCommonPartName());
186
187         Response res = client.createItem(inAuthority, multipart);
188         String result;
189         try {   
190                 int statusCode = res.getStatus();
191         
192                 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
193                         throw new RuntimeException("Could not create Item: \""+orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER)
194                                         +"\" in orgAuthority: \"" + orgAuthorityRefName
195                                         +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
196                 }
197                 if(statusCode != EXPECTED_STATUS_CODE) {
198                         throw new RuntimeException("Unexpected Status when creating Item: \""+ orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER)
199                                         +"\" in orgAuthority: \"" + orgAuthorityRefName +"\", Status:"+ statusCode);
200                 }
201         
202                 result = extractId(res);
203         } finally {
204                 res.close();
205         }
206         
207         return result;
208     }
209     
210     public static List<OrgTermGroup> getTermGroupInstance(String shortIdentifier, String displayName) {
211         if (Tools.isBlank(shortIdentifier)) {
212             shortIdentifier = getGeneratedIdentifier();
213         }
214         if (Tools.isBlank(shortIdentifier)) {
215             displayName = shortIdentifier;
216         }
217         
218         List<OrgTermGroup> terms = new ArrayList<OrgTermGroup>();
219         OrgTermGroup term = new OrgTermGroup();
220         term.setTermDisplayName(displayName);
221         term.setTermName(shortIdentifier);
222         terms.add(term);
223         return terms;
224     }
225     
226     /*
227      * Create a very simple Organization term -just a short ID and display name.
228      */
229     public static PoxPayloadOut createOrganizationInstance(String shortIdentifier, String displayName,
230             String headerLabel) {
231         List<OrgTermGroup> terms = getTermGroupInstance(shortIdentifier, displayName);
232         
233         Map<String, String> orgInfo = new HashMap<String, String>();
234         orgInfo.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortIdentifier);
235         
236         final Map<String, List<String>> EMPTY_ORG_REPEATABLES_INFO = new HashMap<String, List<String>>();
237
238         return createOrganizationInstance(null, orgInfo, terms, EMPTY_ORG_REPEATABLES_INFO, headerLabel);
239     }      
240
241     /**
242      * Creates the organization instance.
243      *
244      * @param orgAuthRefName the owning Authority ref name
245      * @param orgInfo the org info
246      * @param headerLabel the header label
247      * @return the multipart output
248      */
249         public static PoxPayloadOut createOrganizationInstance(
250                         String orgAuthRefName,
251                         Map<String,     String> orgInfo,
252                         List<OrgTermGroup> terms,
253                         String headerLabel) {
254                 final Map<String, List<String>> EMPTY_ORG_REPEATABLES_INFO = new HashMap<String, List<String>>();
255                 return createOrganizationInstance(orgAuthRefName, orgInfo, terms,
256                                 EMPTY_ORG_REPEATABLES_INFO, headerLabel);
257         }
258
259     /**
260      * Creates the organization instance.
261      *
262      * @param orgAuthRefName the owning Authority ref name
263      * @param orgInfo the org info
264      * @param orgRepeatablesInfo names and values of repeatable scalar
265      *        fields in the Organization record
266      * @param headerLabel the header label
267      * @return the multipart output
268      */
269     public static PoxPayloadOut createOrganizationInstance( 
270                         String orgAuthRefName, 
271                         Map<String, String> orgInfo, 
272                         List<OrgTermGroup> terms,
273                         Map<String, List<String>> orgRepeatablesInfo,
274                         String headerLabel) {
275         
276         OrganizationsCommon organization = new OrganizationsCommon();
277                 String shortId = orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER);
278                 if (shortId == null || shortId.isEmpty()) {
279                         throw new IllegalArgumentException("shortIdentifier cannot be null or empty");
280                 }       
281                 organization.setShortIdentifier(shortId);
282         String value = null;
283         List<String> values = null;
284         
285         // Set values in the Term Information Group
286         OrgTermGroupList termList = new OrgTermGroupList();
287         if (terms == null || terms.isEmpty()) {
288             terms = getTermGroupInstance(getGeneratedIdentifier());
289         }
290         termList.getOrgTermGroup().addAll(terms); 
291         organization.setOrgTermGroupList(termList);
292         
293         if ((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.CONTACT_NAMES))!=null) {
294                 ContactNameList contactsList = new ContactNameList();
295                 List<String> contactNames = contactsList.getContactName();
296                 contactNames.addAll(values);
297                 organization.setContactNames(contactsList);
298         }
299         if ((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_DATE))!=null) {
300             StructuredDateGroup foundingDate = new StructuredDateGroup();
301             foundingDate.setDateDisplayDate(value);
302             organization.setFoundingDateGroup(foundingDate);
303         }
304         if ((value = (String)orgInfo.get(OrganizationJAXBSchema.DISSOLUTION_DATE))!=null) {
305             StructuredDateGroup dissolutionDate = new StructuredDateGroup();
306             dissolutionDate.setDateDisplayDate(value);
307             organization.setDissolutionDateGroup(dissolutionDate);
308         }
309         if ((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_PLACE))!=null)
310                 organization.setFoundingPlace(value);
311         if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.GROUPS))!=null) {
312                 GroupList groupsList = new GroupList();
313                 List<String> groups = groupsList.getGroup();
314                 groups.addAll(values);
315                 organization.setGroups(groupsList);
316         }
317         if ((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.FUNCTIONS))!=null) {
318                 FunctionList functionsList = new FunctionList();
319                 List<String> functions = functionsList.getFunction();
320                 functions.addAll(values);
321                 organization.setFunctions(functionsList);
322         }
323         if ((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.HISTORY_NOTES))!=null) {
324                 HistoryNoteList historyNotesList = new HistoryNoteList();
325                 List<String> historyNotes = historyNotesList.getHistoryNote();
326                 historyNotes.addAll(values);
327                 organization.setHistoryNotes(historyNotesList);
328         }
329
330         PoxPayloadOut multipart = new PoxPayloadOut(OrganizationClient.SERVICE_ITEM_PAYLOAD_NAME);
331         PayloadOutputPart commonPart = multipart.addPart(organization,
332             MediaType.APPLICATION_XML_TYPE);
333         commonPart.setLabel(headerLabel);
334
335         if(logger.isDebugEnabled()){
336                     logger.debug("to be created, organization common ", organization, OrganizationsCommon.class);
337         }
338
339         return multipart;
340     }
341
342     /**
343      * Returns an error message indicating that the status code returned by a
344      * specific call to a service does not fall within a set of valid status
345      * codes for that service.
346      *
347      * @param serviceRequestType  A type of service request (e.g. CREATE, DELETE).
348      *
349      * @param statusCode  The invalid status code that was returned in the response,
350      *                    from submitting that type of request to the service.
351      *
352      * @return An error message.
353      */
354     public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
355         return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
356                 requestType.validStatusCodesAsString();
357     }
358
359     /**
360      * Extract id.
361      *
362      * @param res the res
363      * @return the string
364      */
365     public static String extractId(Response res) {
366         MultivaluedMap<String, Object> mvm = res.getMetadata();
367         String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
368         if(logger.isDebugEnabled()){
369                 logger.info("extractId:uri=" + uri);
370         }
371         String[] segments = uri.split("/");
372         String id = segments[segments.length - 1];
373         if(logger.isDebugEnabled()){
374                 logger.debug("id=" + id);
375         }
376         return id;
377     }
378     
379     /**
380      * Creates the org auth ref name.
381      *
382      * @param shortId the orgAuthority shortIdentifier
383      * @param displaySuffix displayName to be appended, if non-null
384      * @return the string
385      */
386     /*
387     public static String createOrgAuthRefName(String shortId, String displaySuffix) {
388         String refName = "urn:cspace:org.collectionspace.demo:orgauthority:name("
389                         +shortId+")";
390         if(displaySuffix!=null&&!displaySuffix.isEmpty())
391                 refName += "'"+displaySuffix+"'";
392         return refName;
393     }
394     */
395
396     /**
397      * Creates the organization ref name.
398      *
399      * @param orgAuthRefName the org auth ref name
400      * @param shortId the person shortIdentifier
401      * @param displaySuffix displayName to be appended, if non-null
402      * @return the string
403      */
404     /*
405     public static String createOrganizationRefName(
406                         String orgAuthRefName, String shortId, String displaySuffix) {
407         String refName = orgAuthRefName+":organization:name("+shortId+")";
408         if(displaySuffix!=null&&!displaySuffix.isEmpty())
409                 refName += "'"+displaySuffix+"'";
410         return refName;
411     }
412     */
413
414     /**
415      * Produces a default displayName from the basic name and foundingPlace fields.
416      * @see OrgAuthorityDocumentModelHandler.prepareDefaultDisplayName() which
417      * duplicates this logic, until we define a service-general utils package
418      * that is neither client nor service specific.
419      * @param shortName
420      * @param foundingPlace
421      * @return
422      * @throws Exception
423      */
424     public static String prepareDefaultDisplayName(
425                 String shortName, String foundingPlace ) {
426         StringBuilder newStr = new StringBuilder();
427                 final String sep = " ";
428                 boolean firstAdded = false;
429                 if(null != shortName ) {
430                         newStr.append(shortName);
431                         firstAdded = true;
432                 }
433         // Now we add the place
434                 if(null != foundingPlace ) {
435                         if(firstAdded) {
436                                 newStr.append(sep);
437                         }
438                         newStr.append(foundingPlace);
439                 }
440                 return newStr.toString();
441     }
442
443     public static List<OrgTermGroup> getTermGroupInstance(String identifier) {
444         if (Tools.isBlank(identifier)) {
445             identifier = getGeneratedIdentifier();
446         }
447         List<OrgTermGroup> terms = new ArrayList<OrgTermGroup>();
448         OrgTermGroup term = new OrgTermGroup();
449         term.setTermDisplayName(identifier);
450         term.setTermName(identifier);
451         terms.add(term);
452         return terms;
453     }
454     
455     private static String getGeneratedIdentifier() {
456         return "id" + new Date().getTime(); 
457    }
458     
459 }