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:
6 * http://www.collectionspace.org
7 * http://wiki.collectionspace.org
9 * Copyright (c) 2009 Regents of the University of California
11 * Licensed under the Educational Community License (ECL), Version 2.0.
12 * You may not use this file except in compliance with this License.
14 * You may obtain a copy of the ECL 2.0 License at
15 * https://source.collectionspace.org/collection-space/LICENSE.txt
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.
24 package org.collectionspace.services.IntegrationTests.xmlreplay;
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;
33 import java.io.BufferedReader;
35 import java.io.InputStreamReader;
36 import java.io.OutputStreamWriter;
37 import java.net.HttpURLConnection;
39 import java.util.Arrays;
40 import java.util.List;
43 import org.collectionspace.services.common.api.Tools;
46 * @author Laramie Crocker
48 public class XmlReplayTransport {
50 private static String BOUNDARY = "34d97c83-0d61-4958-80ab-6bf8d362290f";
51 private static String DD = "--";
52 private static String CRLF = "\r\n";
54 public static ServiceResult doGET(String urlString, String authForTest, String fromTestID) throws Exception {
55 ServiceResult pr = new ServiceResult();
56 pr.fromTestID = fromTestID;
58 //HACK for speed testing.
60 //pr.overrideGotExpectedResult();
61 //if (true) return pr;
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);
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");
78 String hdrStr = hdr.toExternalForm();
79 pr.boundary = PayloadLogger.parseBoundary(hdrStr);
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();
90 public static ServiceResult doDELETE(String urlString, String authForTest, String testID, String fromTestID) throws Exception {
91 ServiceResult pr = new ServiceResult();
92 pr.failureReason = "";
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;
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);
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();
119 pr.responseCode = statusCode1;
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);
128 return doGET(urlString, authForTest, fromTestID);
131 public static final String MULTIPART_MIXED = "multipart/mixed";
132 public static final String APPLICATION_XML = "application/xml";
134 /** Use this overload for multipart messages. */
136 public static ServiceResult doPOST_PUTFromXML_Multipart(List<String> filesList,
137 List<String> partsList,
138 List<Map<String,String>> varsList,
139 String protoHostPort,
142 XmlReplayEval evalStruct,
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.");
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);
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
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.
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,
180 XmlReplayEval evalStruct,
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.
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.
197 //result.overrideGotExpectedResult();
198 //if (true) return result;
201 public static ServiceResult doPOST_PUT(String urlString,
208 String fromTestID) throws Exception {
209 ServiceResult result = new ServiceResult();
210 result.method = method;
211 String deleteURL = "";
212 String location = "";
214 URL url = new URL(urlString);
215 HttpURLConnection conn;
216 conn = (HttpURLConnection) url.openConnection();
218 if (MULTIPART_MIXED.equalsIgnoreCase(contentType)){
219 conn.setRequestProperty("Accept", "multipart/mixed");
220 conn.setRequestProperty("content-type", "multipart/mixed; boundary=" + boundary);
222 conn.setRequestProperty("Accept", "application/xml");
223 conn.setRequestProperty("content-type", contentType);
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());
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){
243 readStream(conn, result);
244 } catch (Throwable t){
245 //System.err.println("ERROR getting content from response: "+t);
246 result.error = t.toString();
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);
260 result.location = location;
261 result.deleteURL = deleteURL;
262 result.CSID = location;
263 } catch (Throwable t2){
264 result.error = "ERROR in XmlReplayTransport: "+t2;
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 = "";
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();
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);
303 postMethod.releaseConnection();
304 } catch (Throwable t){
305 result.error = t.toString();
308 result.location = location;
309 result.deleteURL = deleteURL;
310 result.CSID = location;
311 } catch (Throwable t2){
312 result.error = "ERROR in XmlReplayTransport: "+t2;
317 private static void readStream(HttpURLConnection conn, ServiceResult result) throws Throwable {
318 BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
321 StringBuffer sb = new StringBuffer();
322 while ((line = rd.readLine()) != null) {
323 sb.append(line).append("\r\n");
325 String msg = sb.toString();
327 result.boundary = PayloadLogger.parseBoundary(conn.getHeaderField("CONTENT-TYPE"));