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