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