]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
58ec12861f21f4e06ec9726c7668ad8dfd8f9e51
[tmp/jakarta-migration.git] /
1 /**\r
2  * This document is a part of the source code and related artifacts\r
3  * for CollectionSpace, an open source collections management system\r
4  * for museums and related institutions:\r
5  *\r
6  * http://www.collectionspace.org\r
7  * http://wiki.collectionspace.org\r
8  *\r
9  * Copyright (c) 2009 Regents of the University of California\r
10  *\r
11  * Licensed under the Educational Community License (ECL), Version 2.0.\r
12  * You may not use this file except in compliance with this License.\r
13  *\r
14  * You may obtain a copy of the ECL 2.0 License at\r
15  * https://source.collectionspace.org/collection-space/LICENSE.txt\r
16  *\r
17  *  Unless required by applicable law or agreed to in writing, software\r
18  *  distributed under the License is distributed on an "AS IS" BASIS,\r
19  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
20  *  See the License for the specific language governing permissions and\r
21  *  limitations under the License.\r
22  */\r
23 \r
24 package org.collectionspace.services.IntegrationTests.xmlreplay;\r
25 \r
26 import org.apache.commons.httpclient.Header;\r
27 import org.apache.commons.httpclient.HttpClient;\r
28 import org.apache.commons.httpclient.methods.DeleteMethod;\r
29 import org.apache.commons.httpclient.methods.GetMethod;\r
30 import org.apache.commons.httpclient.methods.PostMethod;\r
31 import org.apache.commons.io.FileUtils;\r
32 \r
33 import java.io.BufferedReader;\r
34 import java.io.File;\r
35 import java.io.InputStreamReader;\r
36 import java.io.OutputStreamWriter;\r
37 import java.net.HttpURLConnection;\r
38 import java.net.URL;\r
39 import java.util.Arrays;\r
40 import java.util.HashMap;\r
41 import java.util.List;\r
42 import java.util.Map;\r
43 \r
44 import org.collectionspace.services.common.api.Tools;\r
45 \r
46 /**\r
47  *   @author Laramie Crocker\r
48  */\r
49 public class XmlReplayTransport {\r
50 \r
51     private static String BOUNDARY = "34d97c83-0d61-4958-80ab-6bf8d362290f";\r
52         private static String DD = "--";\r
53         private static String CRLF = "\r\n";\r
54 \r
55     public static ServiceResult doGET(String urlString, String authForTest, String fromTestID) throws Exception {\r
56         ServiceResult pr = new ServiceResult();\r
57         pr.fromTestID = fromTestID;\r
58         pr.method = "GET";\r
59         //HACK for speed testing.\r
60         //pr.CSID = "2";\r
61         //pr.overrideGotExpectedResult();\r
62         //if (true) return pr;\r
63         //END-HACK\r
64         HttpClient client = new HttpClient();\r
65         GetMethod getMethod = new GetMethod(urlString);\r
66         getMethod.addRequestHeader("Accept", "multipart/mixed");\r
67         getMethod.addRequestHeader("Accept", "application/xml");\r
68         getMethod.setRequestHeader("Authorization", "Basic " + authForTest); //"dGVzdDp0ZXN0");\r
69         getMethod.setRequestHeader("X-XmlReplay-fromTestID", fromTestID);\r
70         try {\r
71             int statusCode1 = client.executeMethod(getMethod);\r
72             pr.responseCode = statusCode1;\r
73             pr.result = getMethod.getResponseBodyAsString();\r
74             pr.responseMessage = getMethod.getStatusText();\r
75             Header[] headers = getMethod.getResponseHeaders();\r
76             pr.responseHeaders = Arrays.copyOf(headers, headers.length);\r
77             Header hdr = getMethod.getResponseHeader("CONTENT-TYPE");\r
78             if (hdr!=null){\r
79                 String hdrStr = hdr.toExternalForm();\r
80                 pr.boundary = PayloadLogger.parseBoundary(hdrStr);\r
81             }\r
82             pr.contentLength = getMethod.getResponseContentLength();\r
83             getMethod.releaseConnection();\r
84         } catch (Throwable t){\r
85             //System.err.println("ERROR getting content from response: "+t);\r
86             pr.error = t.toString();\r
87         }\r
88         return pr;\r
89     }\r
90 \r
91     public static ServiceResult doDELETE(String urlString, String authForTest, String testID, String fromTestID) throws Exception {\r
92         ServiceResult pr = new ServiceResult();\r
93         pr.failureReason = "";\r
94         pr.method = "DELETE";\r
95         pr.fullURL = urlString;\r
96         pr.fromTestID = fromTestID;\r
97         if (Tools.isEmpty(urlString)){\r
98             pr.error = "url was empty.  Check the result for fromTestID: "+fromTestID+". currentTest: "+testID;\r
99             return pr;\r
100         }\r
101         HttpClient client = new HttpClient();\r
102         DeleteMethod deleteMethod = new DeleteMethod(urlString);\r
103         deleteMethod.setRequestHeader("Accept", "multipart/mixed");\r
104         deleteMethod.addRequestHeader("Accept", "application/xml");\r
105         deleteMethod.setRequestHeader("Authorization", "Basic " + authForTest);\r
106         deleteMethod.setRequestHeader("X-XmlReplay-fromTestID", fromTestID);\r
107         int statusCode1 = 0;\r
108         String res = "";\r
109         try {\r
110             statusCode1 = client.executeMethod(deleteMethod);\r
111             pr.responseCode = statusCode1;\r
112             //System.out.println("statusCode: "+statusCode1+" statusLine ==>" + deleteMethod.getStatusLine());\r
113             pr.responseMessage = deleteMethod.getStatusText();\r
114             res = deleteMethod.getResponseBodyAsString();\r
115             deleteMethod.releaseConnection();\r
116         } catch (Throwable t){\r
117             pr.error = t.toString();\r
118         }\r
119         pr.result = res;\r
120         pr.responseCode = statusCode1;\r
121         return pr;\r
122     }\r
123 \r
124     public static ServiceResult doLIST(String urlString, String listQueryParams, String authForTest, String fromTestID) throws Exception {\r
125         //String u = Tools.glue(urlString, "/", "items/");\r
126         if (Tools.notEmpty(listQueryParams)){\r
127             urlString = Tools.glue(urlString, "?", listQueryParams);\r
128         }\r
129         return doGET(urlString, authForTest, fromTestID);\r
130     }\r
131 \r
132     public static final String MULTIPART_MIXED = "multipart/mixed";\r
133     public static final String APPLICATION_XML = "application/xml";\r
134 \r
135     /** Use this overload for multipart messages. */\r
136     /**\r
137     public static ServiceResult doPOST_PUTFromXML_Multipart(List<String> filesList,\r
138                                                             List<String> partsList,\r
139                                                             List<Map<String,String>> varsList,\r
140                                                             String protoHostPort,\r
141                                                             String uri,\r
142                                                             String method,\r
143                                                             XmlReplayEval evalStruct,\r
144                                                             String authForTest,\r
145                                                             String fromTestID)\r
146                                                              throws Exception {\r
147         if (  filesList==null||filesList.size()==0\r
148             ||partsList==null||partsList.size()==0\r
149             ||(partsList.size() != filesList.size())){\r
150             throw new Exception("filesList and partsList must not be empty and must have the same number of items each.");\r
151         }\r
152         String content = DD + BOUNDARY;\r
153         Map<String, String> contentRaw = new HashMap<String, String>();\r
154         for (int i=0; i<partsList.size(); i++){\r
155             String fileName = filesList.get(i);\r
156             String commonPartName = partsList.get(i);\r
157             byte[] b = FileUtils.readFileToByteArray(new File(fileName));\r
158             String xmlString = new String(b);\r
159 \r
160             xmlString = evalStruct.eval(xmlString, evalStruct.serviceResultsMap, varsList.get(i), evalStruct.jexl, evalStruct.jc);\r
161             contentRaw.put(commonPartName, xmlString);\r
162             content = content + CRLF + "label: "+commonPartName + CRLF\r
163                               + "Content-Type: application/xml" + CRLF\r
164                               + CRLF\r
165                               + xmlString + CRLF\r
166                               + DD + BOUNDARY;\r
167         }\r
168         content = content + DD;\r
169         String urlString = protoHostPort+uri;\r
170         return doPOST_PUT(urlString, content, contentRaw, BOUNDARY, method, MULTIPART_MIXED, authForTest, fromTestID); //method is POST or PUT.\r
171     }\r
172     */\r
173 \r
174     /** Use this overload for NON-multipart messages, that is, regular POSTs. */\r
175     public static ServiceResult doPOST_PUTFromXML(String fileName,\r
176                                                       Map<String,String> vars,\r
177                                                       String protoHostPort,\r
178                                                       String uri,\r
179                                                       String method,\r
180                                                       String contentType,\r
181                                                       XmlReplayEval evalStruct,\r
182                                                       String authForTest,\r
183                                                       String fromTestID)\r
184     throws Exception {\r
185         byte[] b = FileUtils.readFileToByteArray(new File(fileName));\r
186         String xmlString = new String(b);\r
187         String contentRaw = xmlString;\r
188         xmlString = evalStruct.eval(xmlString, evalStruct.serviceResultsMap, vars, evalStruct.jexl, evalStruct.jc);\r
189         String urlString = protoHostPort+uri;\r
190         return doPOST_PUT(urlString, xmlString, contentRaw, BOUNDARY, method, contentType, authForTest, fromTestID); //method is POST or PUT.\r
191     }\r
192 \r
193         //HACK for speed testing in doPOST_PUT.\r
194         //  Result: XmlReplay takes 9ms to process one test\r
195         // right up to the point of actually firing an HTTP request.\r
196         // or ~ 120 records per second.\r
197         //result.CSID = "2";\r
198         //result.overrideGotExpectedResult();\r
199         //if (true) return result;\r
200         //END-HACK\r
201 \r
202     public static ServiceResult doPOST_PUT(String urlString,\r
203                                                                      String content,\r
204                                                                      String contentRaw,\r
205                                                                      String boundary,\r
206                                                                      String method,\r
207                                                                      String contentType,\r
208                                                                      String authForTest,\r
209                                                                      String fromTestID) throws Exception {\r
210         ServiceResult result = new ServiceResult();\r
211         result.method = method;\r
212         String deleteURL = "";\r
213         String location = "";\r
214         try {\r
215             URL url = new URL(urlString);\r
216             HttpURLConnection conn;\r
217             conn = (HttpURLConnection) url.openConnection();\r
218 \r
219             if (MULTIPART_MIXED.equalsIgnoreCase(contentType)){\r
220                 conn.setRequestProperty("Accept", "multipart/mixed");\r
221                 conn.setRequestProperty("content-type", "multipart/mixed; boundary=" + boundary);\r
222             } else {\r
223                 conn.setRequestProperty("Accept", "application/xml");\r
224                 conn.setRequestProperty("content-type", contentType);\r
225             }\r
226             conn.setRequestProperty("Authorization", "Basic " + authForTest);  //TODO: remove test user : hard-coded as "dGVzdDp0ZXN0"\r
227             conn.setRequestProperty("Connection", "close");\r
228             conn.setRequestProperty("X-XmlReplay-fromTestID", fromTestID);\r
229             conn.setDoOutput(true);\r
230             conn.setDoInput(true);\r
231             conn.setRequestMethod(method); // "POST" or "PUT"\r
232             OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());\r
233             wr.write(content);\r
234             wr.flush();\r
235 \r
236             try {\r
237                 result.requestPayload = content;\r
238                 result.requestPayloadsRaw = contentRaw;\r
239                 result.responseCode = conn.getResponseCode();\r
240                 //System.out.println("responseCode: "+result.responseCode);\r
241                 if (400 <= result.responseCode && result.responseCode <= 499){\r
242                     return result;\r
243                 }\r
244                 readStream(conn, result);\r
245             } catch (Throwable t){\r
246                 //System.err.println("ERROR getting content from response: "+t);\r
247                 result.error = t.toString();\r
248             }\r
249             wr.close();\r
250 \r
251             Map<String, List<String>> headers = conn.getHeaderFields();\r
252             List<String> locations = headers.get("Location");\r
253             if (locations != null){\r
254                 String locationZero = locations.get(0);\r
255                 if (locationZero != null){\r
256                     String[] segments = locationZero.split("/");\r
257                     location = segments[segments.length - 1];\r
258                     deleteURL = Tools.glue(urlString, "/", location);\r
259                 }\r
260             }\r
261             result.location = location;\r
262             result.deleteURL = deleteURL;\r
263             result.CSID = location;\r
264         } catch (Throwable t2){\r
265             result.error = "ERROR in XmlReplayTransport: "+t2;\r
266         }\r
267         return result;\r
268     }\r
269 \r
270     public static ServiceResult doPOST_PUT_PostMethod(String urlString, String content, Map<String,String> contentRaw,\r
271                                            String boundary, String method, String contentType,\r
272                                            String authForTest, String fromTestID) throws Exception {\r
273         ServiceResult result = new ServiceResult();\r
274         result.method = method;\r
275         String deleteURL = "";\r
276         String location = "";\r
277         try {\r
278             HttpClient client = new HttpClient();\r
279             PostMethod postMethod = new PostMethod(urlString);\r
280             postMethod.setRequestHeader("Accept", "multipart/mixed");\r
281             postMethod.addRequestHeader("Accept", "application/xml");\r
282             postMethod.setRequestHeader("Authorization", "Basic " + authForTest);\r
283             postMethod.setRequestHeader("X-XmlReplay-fromTestID", fromTestID);\r
284             //this method takes an array of params.  Not sure what they expect us to do with a raw post:\r
285             //   postMethod.setRequestBody();\r
286             int statusCode1 = 0;\r
287             String res = "";\r
288             try {\r
289                 statusCode1 = client.executeMethod(postMethod);\r
290                 result.responseCode = statusCode1;\r
291                 //System.out.println("statusCode: "+statusCode1+" statusLine ==>" + postMethod.getStatusLine());\r
292                 result.responseMessage = postMethod.getStatusText();\r
293                 res = postMethod.getResponseBodyAsString();\r
294                 Header[] headers = postMethod.getResponseHeaders("Location");\r
295                 if (headers.length>0) {\r
296                     System.out.println("headers[0]:  "+headers[0]);\r
297                     String locationZero = headers[0].getValue();\r
298                     if (locationZero != null){\r
299                         String[] segments = locationZero.split("/");\r
300                         location = segments[segments.length - 1];\r
301                         deleteURL = Tools.glue(urlString, "/", location);\r
302                     }\r
303                 }\r
304                 postMethod.releaseConnection();\r
305             } catch (Throwable t){\r
306                 result.error = t.toString();\r
307             }\r
308             result.result = res;\r
309             result.location = location;\r
310             result.deleteURL = deleteURL;\r
311             result.CSID = location;\r
312         } catch (Throwable t2){\r
313             result.error = "ERROR in XmlReplayTransport: "+t2;\r
314         }\r
315         return result;\r
316     }\r
317 \r
318     private static void readStream(HttpURLConnection  conn, ServiceResult result) throws Throwable {\r
319         BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));\r
320         try {\r
321                 String line;\r
322                 StringBuffer sb = new StringBuffer();\r
323                 while ((line = rd.readLine()) != null) {\r
324                     sb.append(line).append("\r\n");\r
325                 }\r
326                 String msg = sb.toString();\r
327                 result.result = msg;\r
328                 result.boundary = PayloadLogger.parseBoundary(conn.getHeaderField("CONTENT-TYPE"));\r
329         } finally {\r
330             rd.close();\r
331         }\r
332     }\r
333 \r
334 }\r