]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
60ba460c2ebdf523fada3fd4e84d46b2092ef8d0
[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.io.FileUtils;\r
31 \r
32 import java.io.BufferedReader;\r
33 import java.io.File;\r
34 import java.io.InputStreamReader;\r
35 import java.io.OutputStreamWriter;\r
36 import java.net.HttpURLConnection;\r
37 import java.net.URL;\r
38 import java.util.Arrays;\r
39 import java.util.HashMap;\r
40 import java.util.List;\r
41 import java.util.Map;\r
42 \r
43 import org.collectionspace.services.common.api.Tools;\r
44 \r
45 /**\r
46  *   @author Laramie Crocker\r
47  */\r
48 public class XmlReplayTransport {\r
49 \r
50     private static String BOUNDARY = "34d97c83-0d61-4958-80ab-6bf8d362290f";\r
51         private static String DD = "--";\r
52         private static String CRLF = "\r\n";\r
53 \r
54     public static ServiceResult doGET(String urlString, String authForTest, String fromTestID) throws Exception {\r
55         ServiceResult pr = new ServiceResult();\r
56         pr.fromTestID = fromTestID;\r
57         pr.method = "GET";\r
58         //HACK for speed testing.\r
59         //pr.CSID = "2";\r
60         //pr.overrideGotExpectedResult();\r
61         //if (true) return pr;\r
62         //END-HACK\r
63         HttpClient client = new HttpClient();\r
64         GetMethod getMethod = new GetMethod(urlString);\r
65         getMethod.addRequestHeader("Accept", "multipart/mixed");\r
66         getMethod.addRequestHeader("Accept", "application/xml");\r
67         getMethod.setRequestHeader("Authorization", "Basic " + authForTest); //"dGVzdDp0ZXN0");\r
68         getMethod.setRequestHeader("X-XmlReplay-fromTestID", fromTestID);\r
69         try {\r
70             int statusCode1 = client.executeMethod(getMethod);\r
71             pr.responseCode = statusCode1;\r
72             pr.result = getMethod.getResponseBodyAsString();\r
73             pr.responseMessage = getMethod.getStatusText();\r
74             Header[] headers = getMethod.getResponseHeaders();\r
75             pr.responseHeaders = Arrays.copyOf(headers, headers.length);\r
76             Header hdr = getMethod.getResponseHeader("CONTENT-TYPE");\r
77             if (hdr!=null){\r
78                 String hdrStr = hdr.toExternalForm();\r
79                 pr.boundary = PayloadLogger.parseBoundary(hdrStr);\r
80             }\r
81             pr.contentLength = getMethod.getResponseContentLength();\r
82             getMethod.releaseConnection();\r
83         } catch (Throwable t){\r
84             //System.err.println("ERROR getting content from response: "+t);\r
85             pr.error = t.toString();\r
86         }\r
87 \r
88 \r
89         return pr;\r
90     }\r
91 \r
92     public static ServiceResult doDELETE(String urlString, String authForTest, String testID, String fromTestID) throws Exception {\r
93         ServiceResult pr = new ServiceResult();\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     public static ServiceResult doPOST_PUTFromXML_Multipart(List<String> filesList,\r
137                                                             List<String> partsList,\r
138                                                             List<Map<String,String>> varsList,\r
139                                                             String protoHostPort,\r
140                                                             String uri,\r
141                                                             String method,\r
142                                                             XmlReplayEval evalStruct,\r
143                                                             String authForTest,\r
144                                                             String fromTestID)\r
145                                                              throws Exception {\r
146         if (  filesList==null||filesList.size()==0\r
147             ||partsList==null||partsList.size()==0\r
148             ||(partsList.size() != filesList.size())){\r
149             throw new Exception("filesList and partsList must not be empty and must have the same number of items each.");\r
150         }\r
151         String content = DD + BOUNDARY;\r
152         Map<String, String> contentRaw = new HashMap<String, String>();\r
153         for (int i=0; i<partsList.size(); i++){\r
154             String fileName = filesList.get(i);\r
155             String commonPartName = partsList.get(i);\r
156             byte[] b = FileUtils.readFileToByteArray(new File(fileName));\r
157             String xmlString = new String(b);\r
158 \r
159             xmlString = evalStruct.eval(xmlString, evalStruct.serviceResultsMap, varsList.get(i), evalStruct.jexl, evalStruct.jc);\r
160             contentRaw.put(commonPartName, xmlString);\r
161             content = content + CRLF + "label: "+commonPartName + CRLF\r
162                               + "Content-Type: application/xml" + CRLF\r
163                               + CRLF\r
164                               + xmlString + CRLF\r
165                               + DD + BOUNDARY;\r
166         }\r
167         content = content + DD;\r
168         String urlString = protoHostPort+uri;\r
169         return doPOST_PUT(urlString, content, contentRaw, BOUNDARY, method, MULTIPART_MIXED, authForTest, fromTestID); //method is POST or PUT.\r
170     }\r
171 \r
172     public static ServiceResult doPOST_PUTFromXML_POX(List<String> filesList,\r
173                                                         List<String> partsList,\r
174                                                         List<Map<String,String>> varsList,\r
175                                                         String protoHostPort,\r
176                                                         String uri,\r
177                                                         String method,\r
178                                                         XmlReplayEval evalStruct,\r
179                                                         String authForTest,\r
180                                                         String fromTestID)\r
181                                                         throws Exception {\r
182         if (  filesList==null||filesList.size()==0\r
183             ||partsList==null||partsList.size()==0\r
184             ||(partsList.size() != filesList.size())){\r
185             throw new Exception("filesList and partsList must not be empty and must have the same number of items each.");\r
186         }\r
187         //NO: Patrick sez all test files should be complete XML now:  StringBuffer content = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");\r
188         StringBuffer content = new StringBuffer();\r
189         //content.append(CRLF).append("<document name=\"objectexit\">").append(CRLF);\r
190         Map<String, String> contentRaw = new HashMap<String, String>();\r
191         for (int i=0; i<partsList.size(); i++){\r
192             String fileName = filesList.get(i);\r
193             String commonPartName = partsList.get(i);\r
194             byte[] b = FileUtils.readFileToByteArray(new File(fileName));\r
195             String xmlString = new String(b);\r
196 \r
197             xmlString = evalStruct.eval(xmlString, evalStruct.serviceResultsMap, varsList.get(i), evalStruct.jexl, evalStruct.jc);\r
198             contentRaw.put(commonPartName, xmlString);\r
199             \r
200             content.append(xmlString).append(CRLF);\r
201         }\r
202         //content.append("</document>");\r
203         String urlString = protoHostPort+uri;\r
204         String POX_BOUNDARY = "";//empty for POX.\r
205         return doPOST_PUT(urlString, content.toString(), contentRaw, POX_BOUNDARY, method,APPLICATION_XML, authForTest, fromTestID); //method is POST or PUT.\r
206     }\r
207 \r
208 \r
209     /** Use this overload for NON-multipart messages, that is, regular POSTs. */\r
210     public static ServiceResult doPOST_PUTFromXML(String fileName,\r
211                                                       Map<String,String> vars,\r
212                                                       String protoHostPort,\r
213                                                       String uri,\r
214                                                       String method,\r
215                                                       String contentType,\r
216                                                       XmlReplayEval evalStruct,\r
217                                                       String authForTest,\r
218                                                       String fromTestID)\r
219     throws Exception {\r
220         byte[] b = FileUtils.readFileToByteArray(new File(fileName));\r
221         String xmlString = new String(b);\r
222         xmlString = evalStruct.eval(xmlString, evalStruct.serviceResultsMap, vars, evalStruct.jexl, evalStruct.jc);\r
223         String urlString = protoHostPort+uri;\r
224         Map<String, String> contentRaw = new HashMap<String, String>();\r
225         contentRaw.put("default", xmlString);\r
226         return doPOST_PUT(urlString, xmlString, contentRaw, BOUNDARY, method, contentType, authForTest, fromTestID); //method is POST or PUT.\r
227     }\r
228 \r
229 \r
230     public static ServiceResult doPOST_PUT(String urlString, String content, Map<String,String> contentRaw,\r
231                                            String boundary, String method, String contentType,\r
232                                            String authForTest, String fromTestID) throws Exception {\r
233         ServiceResult result = new ServiceResult();\r
234         result.method = method;\r
235         //HACK for speed testing.  Result: XmlReplay takes 9ms to process one test\r
236         // right up to the point of actually firing an HTTP request.\r
237         // or ~ 120 records per second.\r
238         //result.CSID = "2";\r
239         //result.overrideGotExpectedResult();\r
240         //if (true) return result;\r
241         //END-HACK\r
242         try {\r
243             URL url = new URL(urlString);\r
244             HttpURLConnection conn;\r
245             conn = (HttpURLConnection) url.openConnection();\r
246 \r
247             if (MULTIPART_MIXED.equalsIgnoreCase(contentType)){\r
248                 conn.setRequestProperty("Accept", "multipart/mixed");\r
249                 conn.setRequestProperty("content-type", "multipart/mixed; boundary=" + boundary);\r
250             } else {\r
251                 conn.setRequestProperty("Accept", "application/xml");\r
252                 conn.setRequestProperty("content-type", contentType);\r
253             }\r
254             conn.setRequestProperty("Authorization", "Basic " + authForTest);  //TODO: remove test user : hard-coded as "dGVzdDp0ZXN0"\r
255             conn.setRequestProperty("Connection", "close");\r
256             conn.setRequestProperty("X-XmlReplay-fromTestID", fromTestID);\r
257             conn.setDoOutput(true);\r
258             conn.setDoInput(true);\r
259             conn.setRequestMethod(method); // "POST" or "PUT"\r
260             OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());\r
261             wr.write(content);\r
262             wr.flush();\r
263 \r
264 \r
265             try {\r
266                 result.requestPayload = content;\r
267                 result.requestPayloadsRaw = contentRaw;\r
268                 result.responseCode = conn.getResponseCode();\r
269                 //System.out.println("responseCode: "+result.responseCode);\r
270                 if (400 <= result.responseCode && result.responseCode <= 499){\r
271                     return result;\r
272                 }\r
273                 BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));\r
274                 String line;\r
275                 StringBuffer sb = new StringBuffer();\r
276                 while ((line = rd.readLine()) != null) {\r
277                     sb.append(line).append("\r\n");\r
278                 }\r
279                 String msg = sb.toString();\r
280                 result.result = msg;\r
281                 result.boundary = PayloadLogger.parseBoundary(conn.getHeaderField("CONTENT-TYPE"));\r
282 \r
283                 rd.close();\r
284             } catch (Throwable t){\r
285                 //System.err.println("ERROR getting content from response: "+t);\r
286                 result.error = t.toString();\r
287             }\r
288             wr.close();\r
289 \r
290 \r
291             String deleteURL = "";\r
292             String location = "";\r
293             Map<String, List<String>> headers = conn.getHeaderFields();\r
294             List<String> locations = headers.get("Location");\r
295             if (locations != null){\r
296                 String locationZero = locations.get(0);\r
297                 if (locationZero != null){\r
298                     String[] segments = locationZero.split("/");\r
299                     location = segments[segments.length - 1];\r
300                     deleteURL = Tools.glue(urlString, "/", location);\r
301                 }\r
302             }\r
303             result.location = location;\r
304             result.deleteURL = deleteURL;\r
305             result.CSID = location;\r
306 \r
307         } catch (Throwable t2){\r
308             result.error = "ERROR in XmlReplayTransport: "+t2;\r
309         }\r
310         return result;\r
311     }\r
312 \r
313 }\r