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