01: /*
02: * All content copyright (c) 2003-2007 Terracotta, Inc., except as may otherwise be noted in a separate copyright
03: * notice. All rights reserved.
04: */
05: package com.tc.test.server.util;
06:
07: import java.io.BufferedReader;
08: import java.io.IOException;
09: import java.io.InputStreamReader;
10: import java.net.HttpURLConnection;
11: import java.net.URL;
12: import java.net.URLConnection;
13: import java.util.HashMap;
14: import java.util.Iterator;
15: import java.util.List;
16: import java.util.Map;
17:
18: /**
19: * Dummy webclient to test out Http no response exception
20: * This is to be used only in test framework since it sends
21: * along cookies (got from first response) every time regardless
22: * expires, domain, path properties
23: *
24: * @author hhuynh
25: */
26: public class WebClient {
27: private Map cookies = new HashMap();
28:
29: public String getResponseAsString(URL url) throws IOException {
30: HttpURLConnection http = (HttpURLConnection) url
31: .openConnection();
32: http.setRequestProperty("Cookie", getCookiesAsString());
33: http.connect();
34: if (http.getResponseCode() != HttpURLConnection.HTTP_OK) {
35: throw new IOException("Response code is not OK: "
36: + http.getResponseMessage() + "\nRequest: " + url);
37: }
38: extractCookies(http);
39: BufferedReader in = new BufferedReader(new InputStreamReader(
40: http.getInputStream()));
41: StringBuffer buffer = new StringBuffer(100);
42: String line;
43: try {
44: while ((line = in.readLine()) != null) {
45: buffer.append(line).append("\n");
46: }
47: } finally {
48: try {
49: if (in != null)
50: in.close();
51: } catch (Exception ignored) { // nop
52: }
53: }
54:
55: return buffer.toString().trim();
56: }
57:
58: public int getResponseAsInt(URL url) throws IOException {
59: String response = getResponseAsString(url);
60: return Integer.parseInt(response);
61: }
62:
63: public void setCookies(Map cookies) {
64: this .cookies = cookies;
65: System.out.println(cookies);
66: }
67:
68: public Map getCookies() {
69: return cookies;
70: }
71:
72: private String getCookiesAsString() {
73: StringBuffer cookiesString = new StringBuffer(100);
74: for (Iterator it = cookies.entrySet().iterator(); it.hasNext();) {
75: Map.Entry e = (Map.Entry) it.next();
76: cookiesString.append(e.getKey().toString()).append("=")
77: .append(e.getValue().toString());
78: if (it.hasNext()) {
79: cookiesString.append("; ");
80: }
81: }
82: return cookiesString.toString();
83: }
84:
85: private void extractCookies(URLConnection urlConnect) {
86: Map headerFields = urlConnect.getHeaderFields();
87: List cookieList = (List) headerFields.get("Set-Cookie");
88: if (cookieList != null) {
89: for (Iterator it = cookieList.iterator(); it.hasNext();) {
90: String cookie = (String) it.next();
91: // parse first name=value, ignore the rest
92: cookie = cookie.substring(0, cookie.indexOf(";"));
93: String[] pair = cookie.split("=", 2);
94: cookies.put(pair[0], pair[1]);
95: }
96: }
97: }
98: }
|