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