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