001: /*
002: * Speedo: an implementation of JDO compliant personality on top of JORM generic
003: * I/O sub-system.
004: * Copyright (C) 2001-2004 France Telecom R&D
005: *
006: * This library is free software; you can redistribute it and/or
007: * modify it under the terms of the GNU Lesser General Public
008: * License as published by the Free Software Foundation; either
009: * version 2 of the License, or (at your option) any later version.
010: *
011: * This library is distributed in the hope that it will be useful,
012: * but WITHOUT ANY WARRANTY; without even the implied warranty of
013: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
014: * Lesser General Public License for more details.
015: *
016: * You should have received a copy of the GNU Lesser General Public
017: * License along with this library; if not, write to the Free Software
018: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
019: *
020: *
021: */
022: package org.objectweb.speedo.runtime.jmx;
023:
024: import java.io.BufferedReader;
025: import java.io.InputStreamReader;
026: import java.io.OutputStream;
027: import java.net.HttpURLConnection;
028: import java.net.URL;
029: import java.net.URLConnection;
030: import java.util.Enumeration;
031: import java.util.Hashtable;
032: import java.util.StringTokenizer;
033:
034: import org.objectweb.util.monolog.api.BasicLevel;
035: import org.objectweb.util.monolog.api.Logger;
036:
037: /**
038: * This class provides with a simple method to perform some HTTP requests
039: * @author fmillevi@yahoo.com
040: */
041: public class HTTPTools {
042: static String redirectURL;
043:
044: /**
045: * Liste des cookies
046: */
047: static Hashtable cookies = null;
048:
049: /**
050: * Method getURL. This static method provides with the way to get and http response.
051: *
052: * @param urlString is the URL to be invoked
053: * @param paramString is the list of parameters like
054: * param1=value1¶m2=value2¶m3=....
055: * @param method POST or GET
056: * @return String flux HTTP de retour.
057: * @throws Exception when the getURL method fails due to unfound URL, or server errors
058: */
059: public static String getURL(String urlString, String paramString,
060: String method, Logger logger) throws Exception {
061: if (cookies == null) // C'est la premiere connection.
062: {
063: // create the hashtable used to store cookies values
064: cookies = new Hashtable();
065: //getURL(urlString, paramString, method, logger);
066: }
067:
068: String s = "Ok"; // return string
069:
070: try {
071: if (!method.equalsIgnoreCase("post")
072: && !paramString.equals("")) {
073: urlString = urlString + "?" + paramString;
074: }
075:
076: URL url = new URL(urlString);
077:
078: HttpURLConnection conn = (HttpURLConnection) url
079: .openConnection();
080:
081: //String userPassword = "xxxx:yyyy";
082: //String encoding =
083: // new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
084: //conn.setRequestProperty("Authorization", encoding);
085: //conn.setRequestProperty("Authorization", "Basic " + encoding);
086: conn.setRequestProperty("accept-language", "fr");
087: conn
088: .setRequestProperty("user-agent",
089: "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.0.3705)");
090:
091: conn.setRequestProperty("connection", "Keep-Alive");
092: //conn.setRequestProperty ("accept-encoding", "gzip, deflate");
093:
094: //accept http redirections
095: HttpURLConnection.setFollowRedirects(false);
096: //conn.setAllowUserInteraction(false);
097: conn.setUseCaches(false);
098:
099: setCookies(conn);
100:
101: if (method.equalsIgnoreCase("post")) {
102: byte[] bytes = paramString.getBytes();
103: conn.setDoOutput(true);
104: conn.setDoInput(true);
105: conn.setRequestMethod("POST");
106: conn.setRequestProperty("Content-length", String
107: .valueOf(bytes.length));
108: OutputStream out = conn.getOutputStream();
109: out.write(bytes);
110: out.flush();
111: }
112:
113: s = "" + conn.getResponseCode();
114:
115: if (conn.getResponseCode() != 200
116: && conn.getResponseCode() != 302) {
117: logger.log(BasicLevel.ERROR, "error "
118: + conn.getResponseCode());
119: } else if (conn.getResponseCode() == 200) { //parse HTML response
120: //read HTML response
121: BufferedReader is = new BufferedReader(
122: new InputStreamReader(conn.getInputStream()));
123: String line = null;
124: StringBuffer sourceTxt = new StringBuffer("");
125: while ((line = is.readLine()) != null)
126: sourceTxt.append(line);
127: is.close();
128: s = sourceTxt.toString();
129: }
130: getCookies(conn);
131: logger.log(BasicLevel.DEBUG, urlString + "\treturns:"
132: + conn.getResponseCode() + " ");
133:
134: while (s.equals("302")) {
135: s = getURL(redirectURL, "", "", logger);
136: }
137:
138: if (conn.getResponseCode() == 500)
139: throw new Exception("the URL " + url + " fails.");
140:
141: if (conn.getResponseCode() == 404)
142: throw new Exception("the URL " + url + " not found.");
143:
144: } catch (Exception ex) {
145: s = "";
146: logger.log(BasicLevel.DEBUG, urlString
147: + " throws Execption!", ex);
148: throw ex;
149: }
150:
151: return s;
152: }
153:
154: /**
155: * Method getCookies. Gets and stores in the Hashtable the cookies values found in the HTTP response.
156: *
157: * @param con HTTP Connexion
158: */
159: private static void getCookies(HttpURLConnection con) {
160: int n = 1;
161:
162: label0: for (boolean done = false; !done; n++) {
163: String headerKey = con.getHeaderFieldKey(n);
164: String headerVal = con.getHeaderField(n);
165: if (headerKey != null || headerVal != null) {
166: if ("location".equalsIgnoreCase(headerKey)) {
167: redirectURL = headerVal;
168: }
169: if (!"Set-Cookie".equals(headerKey))
170: continue;
171: StringTokenizer st = new StringTokenizer(headerVal, ";");
172: do {
173: if (!st.hasMoreTokens())
174: continue label0;
175: String pair = st.nextToken();
176: StringTokenizer stt = new StringTokenizer(pair, "=");
177: while (stt.hasMoreTokens()) {
178: String cookName = stt.nextToken();
179: String cookValue = "";
180: try {
181: cookValue = stt.nextToken();
182: } catch (Exception exception) {
183: }
184: if (!cookName.trim().equalsIgnoreCase("path")
185: && !cookName.trim().equalsIgnoreCase(
186: "expires")) {
187: //System.out.println("Set cookie :" + cookName +
188: // ":" + cookValue);
189: cookies.put(cookName.trim(), cookValue);
190: }
191: }
192: } while (true);
193: }
194: done = true;
195: }
196: }
197:
198: /**
199: * Method setCookies initialize the cookies values in the http request
200: * using the values found in the Hashtable
201: *
202: * @param con HTTP Connexion
203: */
204: private static void setCookies(URLConnection con) {
205: Enumeration en = cookies.keys();
206: String cookieString;
207: String key = "";
208: String val = "";
209: for (cookieString = ""; en.hasMoreElements(); cookieString = cookieString
210: + (key + "=" + val + ";")) {
211: key = (String) en.nextElement();
212: val = (String) cookies.get(key);
213: }
214: //System.out.println("Init cookies :" + cookieString);
215: con.setRequestProperty("Cookie", cookieString);
216: }
217: }
|