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