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