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