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