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