]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
651a97fbe51859d073a883a3bbabe6eed3bbaa35
[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.OrgTermGroup;\r
48 import org.collectionspace.services.organization.OrgTermGroupList;\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, List<OrgTermGroup> terms, Map<String, String> orgInfo,\r
172                 Map<String, List<String>> orgRepeatablesInfo, 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, terms, orgRepeatablesInfo, 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,\r
220                 List<OrgTermGroup> terms, 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, terms, 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 PoxPayloadOut createOrganizationInstance( \r
239                 String orgAuthRefName, Map<String, String> orgInfo, List<OrgTermGroup> terms,\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         \r
250         \r
251         // Handle terms here\r
252 \r
253         if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.CONTACT_NAMES))!=null) {\r
254                 ContactNameList contactsList = new ContactNameList();\r
255                 List<String> contactNames = contactsList.getContactName();\r
256                 contactNames.addAll(values);\r
257                 organization.setContactNames(contactsList);\r
258         }\r
259         if((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_DATE))!=null)\r
260                 organization.setFoundingDate(value);\r
261         if((value = (String)orgInfo.get(OrganizationJAXBSchema.DISSOLUTION_DATE))!=null)\r
262                 organization.setDissolutionDate(value);\r
263         if((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_PLACE))!=null)\r
264                 organization.setFoundingPlace(value);\r
265         if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.GROUPS))!=null) {\r
266                 GroupList groupsList = new GroupList();\r
267                 List<String> groups = groupsList.getGroup();\r
268                 groups.addAll(values);\r
269                 organization.setGroups(groupsList);\r
270         }\r
271         if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.FUNCTIONS))!=null) {\r
272                 FunctionList functionsList = new FunctionList();\r
273                 List<String> functions = functionsList.getFunction();\r
274                 functions.addAll(values);\r
275                 organization.setFunctions(functionsList);\r
276         }\r
277         if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.HISTORY_NOTES))!=null) {\r
278                 HistoryNoteList historyNotesList = new HistoryNoteList();\r
279                 List<String> historyNotes = historyNotesList.getHistoryNote();\r
280                 historyNotes.addAll(values);\r
281                 organization.setHistoryNotes(historyNotesList);\r
282         }\r
283 \r
284         PoxPayloadOut multipart = new PoxPayloadOut(OrgAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);\r
285         PayloadOutputPart commonPart = multipart.addPart(organization,\r
286             MediaType.APPLICATION_XML_TYPE);\r
287         commonPart.setLabel(headerLabel);\r
288 \r
289         if(logger.isDebugEnabled()){\r
290                 logger.debug("to be created, organization common ", organization, OrganizationsCommon.class);\r
291         }\r
292 \r
293         return multipart;\r
294     }\r
295 \r
296     /**\r
297      * Returns an error message indicating that the status code returned by a\r
298      * specific call to a service does not fall within a set of valid status\r
299      * codes for that service.\r
300      *\r
301      * @param serviceRequestType  A type of service request (e.g. CREATE, DELETE).\r
302      *\r
303      * @param statusCode  The invalid status code that was returned in the response,\r
304      *                    from submitting that type of request to the service.\r
305      *\r
306      * @return An error message.\r
307      */\r
308     public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {\r
309         return "Status code '" + statusCode + "' in response is NOT within the expected set: " +\r
310                 requestType.validStatusCodesAsString();\r
311     }\r
312 \r
313     /**\r
314      * Extract id.\r
315      *\r
316      * @param res the res\r
317      * @return the string\r
318      */\r
319     public static String extractId(ClientResponse<Response> res) {\r
320         MultivaluedMap<String, Object> mvm = res.getMetadata();\r
321         String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);\r
322         if(logger.isDebugEnabled()){\r
323                 logger.info("extractId:uri=" + uri);\r
324         }\r
325         String[] segments = uri.split("/");\r
326         String id = segments[segments.length - 1];\r
327         if(logger.isDebugEnabled()){\r
328                 logger.debug("id=" + id);\r
329         }\r
330         return id;\r
331     }\r
332     \r
333     /**\r
334      * Creates the org auth ref name.\r
335      *\r
336      * @param shortId the orgAuthority shortIdentifier\r
337      * @param displaySuffix displayName to be appended, if non-null\r
338      * @return the string\r
339      */\r
340     /*\r
341     public static String createOrgAuthRefName(String shortId, String displaySuffix) {\r
342         String refName = "urn:cspace:org.collectionspace.demo:orgauthority:name("\r
343                         +shortId+")";\r
344         if(displaySuffix!=null&&!displaySuffix.isEmpty())\r
345                 refName += "'"+displaySuffix+"'";\r
346         return refName;\r
347     }\r
348     */\r
349 \r
350     /**\r
351      * Creates the organization ref name.\r
352      *\r
353      * @param orgAuthRefName the org auth ref name\r
354      * @param shortId the person shortIdentifier\r
355      * @param displaySuffix displayName to be appended, if non-null\r
356      * @return the string\r
357      */\r
358     /*\r
359     public static String createOrganizationRefName(\r
360                         String orgAuthRefName, String shortId, String displaySuffix) {\r
361         String refName = orgAuthRefName+":organization:name("+shortId+")";\r
362         if(displaySuffix!=null&&!displaySuffix.isEmpty())\r
363                 refName += "'"+displaySuffix+"'";\r
364         return refName;\r
365     }\r
366     */\r
367 \r
368     /**\r
369      * Produces a default displayName from the basic name and foundingPlace fields.\r
370      * @see OrgAuthorityDocumentModelHandler.prepareDefaultDisplayName() which\r
371      * duplicates this logic, until we define a service-general utils package\r
372      * that is neither client nor service specific.\r
373      * @param shortName\r
374      * @param foundingPlace\r
375      * @return\r
376      * @throws Exception\r
377      */\r
378     public static String prepareDefaultDisplayName(\r
379                 String shortName, String foundingPlace ) {\r
380         StringBuilder newStr = new StringBuilder();\r
381                 final String sep = " ";\r
382                 boolean firstAdded = false;\r
383                 if(null != shortName ) {\r
384                         newStr.append(shortName);\r
385                         firstAdded = true;\r
386                 }\r
387         // Now we add the place\r
388                 if(null != foundingPlace ) {\r
389                         if(firstAdded) {\r
390                                 newStr.append(sep);\r
391                         }\r
392                         newStr.append(foundingPlace);\r
393                 }\r
394                 return newStr.toString();\r
395     }\r
396 \r
397     public static String createDisplayName(Map<String, String> orgInfo) {\r
398         String displayName = orgInfo.get(OrganizationJAXBSchema.DISPLAY_NAME);\r
399         String displayNameComputedStr = orgInfo.get(OrganizationJAXBSchema.DISPLAY_NAME_COMPUTED);\r
400         boolean displayNameComputed = (displayNameComputedStr==null) || displayNameComputedStr.equalsIgnoreCase("true");\r
401         if( displayName == null ) {\r
402             if(!displayNameComputed) {\r
403                 throw new RuntimeException(\r
404                 "CreateItem: Must supply a displayName if displayNameComputed is set to false.");\r
405             }\r
406             displayName = prepareDefaultDisplayName(\r
407                 orgInfo.get(OrganizationJAXBSchema.SHORT_NAME ),\r
408                 orgInfo.get(OrganizationJAXBSchema.FOUNDING_PLACE ));\r
409         }\r
410         return displayName;\r
411     }\r
412     \r
413 }\r