KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > maverick > ssl > https > HttpsURLConnection


1 /*
2  * SSL-Explorer
3  *
4  * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */

19             
20 package com.maverick.ssl.https;
21
22 import java.io.BufferedOutputStream JavaDoc;
23 import java.io.ByteArrayOutputStream JavaDoc;
24 import java.io.DataInputStream JavaDoc;
25 import java.io.DataOutputStream JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.io.InputStream JavaDoc;
28 import java.io.OutputStream JavaDoc;
29 import java.io.PushbackInputStream JavaDoc;
30 import java.net.HttpURLConnection JavaDoc;
31 import java.net.Socket JavaDoc;
32 import java.net.URL JavaDoc;
33 import java.text.MessageFormat JavaDoc;
34 import java.text.SimpleDateFormat JavaDoc;
35 import java.util.Date JavaDoc;
36 import java.util.Hashtable JavaDoc;
37 import java.util.StringTokenizer JavaDoc;
38 import java.util.TimeZone JavaDoc;
39 import java.util.Vector JavaDoc;
40
41 import com.maverick.http.AuthenticationCancelledException;
42 import com.maverick.http.ConnectMethod;
43 import com.maverick.http.HttpClient;
44 import com.maverick.http.HttpException;
45 import com.maverick.http.HttpMethod;
46 import com.maverick.http.HttpResponse;
47 import com.maverick.http.PasswordCredentials;
48 import com.maverick.http.UnsupportedAuthenticationException;
49 import com.maverick.ssl.SSLException;
50 import com.maverick.ssl.SSLIOException;
51 import com.maverick.ssl.SSLSocket;
52
53 /**
54  *
55  * @author Lee David Painter <a HREF="mailto:lee@3sp.com">&lt;lee@3sp.com&gt;</a>
56  */

57 public class HttpsURLConnection extends HttpURLConnection JavaDoc {
58
59     boolean debugging;
60     ByteArrayOutputStream JavaDoc output = new ByteArrayOutputStream JavaDoc();
61     Vector JavaDoc requestKeys, requestValues;
62     Vector JavaDoc headers = new Vector JavaDoc(), headerKeys = new Vector JavaDoc();
63     Hashtable JavaDoc headerValues = new Hashtable JavaDoc();
64     Socket JavaDoc socket;
65     PushbackInputStream JavaDoc input;
66     int responseCode = -1;
67     String JavaDoc responseMessage;
68
69     /*
70      * public static final String httpsProxyHostPropertyName =
71      * "ssl.https.proxy.host";
72      *
73      * public static final String httpsProxyPortPropertyName =
74      * "ssl.https.proxy.port";
75      */

76
77     // #ifdef DEBUG
78
static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(HttpsURLConnection.class);
79     // #endif
80

81     public static final String JavaDoc httpProxyHostProperty = "com.maverick.ssl.https.HTTPProxyHostname"; //$NON-NLS-1$
82
public static final String JavaDoc httpProxyPortProperty = "com.maverick.ssl.https.HTTPProxyPort"; //$NON-NLS-1$
83
public static final String JavaDoc httpProxyUsernameProperty = "com.maverick.ssl.https.HTTPProxyUsername"; //$NON-NLS-1$
84
public static final String JavaDoc httpProxyPasswordProperty = "com.maverick.ssl.https.HTTPProxyPassword"; //$NON-NLS-1$
85
public static final String JavaDoc httpProxySecureProperty = "com.maverick.ssl.https.HTTPProxySecure"; //$NON-NLS-1$
86
public static final String JavaDoc httpProxyNonProxyHostsProperty = "com.maverick.ssl.https.HTTPProxyNonProxyHosts"; //$NON-NLS-1$
87

88     static Vector JavaDoc defaultRequestKeys = new Vector JavaDoc(), defaultRequestValues = new Vector JavaDoc();
89
90     static {
91         defaultRequestKeys.addElement("User-agent"); //$NON-NLS-1$
92
defaultRequestValues.addElement(HttpClient.USER_AGENT);
93     }
94
95     public HttpsURLConnection(URL JavaDoc url) {
96         super(url);
97         synchronized (defaultRequestKeys) {
98             requestKeys = (Vector JavaDoc) defaultRequestKeys.clone();
99             requestValues = (Vector JavaDoc) defaultRequestValues.clone();
100         }
101     }
102
103     public void addRequestProperty(String JavaDoc name, String JavaDoc value) {
104         setRequestProperty(name, value);
105     }
106
107     public static void setDefaultRequestProperty(String JavaDoc key, String JavaDoc value) {
108         synchronized (defaultRequestKeys) {
109             int i = 0;
110             while ((i < defaultRequestKeys.size()) && !(key.equalsIgnoreCase((String JavaDoc) defaultRequestKeys.elementAt(i)))) {
111                 ++i;
112             }
113             if (i < defaultRequestKeys.size()) {
114                 defaultRequestValues.removeElementAt(i);
115                 defaultRequestKeys.removeElementAt(i);
116             }
117             if (value != null) {
118                 defaultRequestValues.addElement(value);
119                 defaultRequestKeys.addElement(key);
120             }
121         }
122     }
123
124     public static String JavaDoc getDefaultRequestProperty(String JavaDoc key) {
125         synchronized (defaultRequestKeys) {
126             int i = 0;
127             while ((i < defaultRequestKeys.size()) && !(key.equalsIgnoreCase((String JavaDoc) defaultRequestKeys.elementAt(i)))) {
128                 ++i;
129             }
130             if (i < defaultRequestKeys.size()) {
131                 return (String JavaDoc) defaultRequestValues.elementAt(i);
132             } else {
133                 return null;
134             }
135         }
136     }
137
138     public synchronized void setRequestProperty(String JavaDoc key, String JavaDoc value) {
139         if (connected) {
140             throw new IllegalStateException JavaDoc(Messages.getString("HttpsURLConnection.alreadyConnected")); //$NON-NLS-1$
141
}
142         int i = 0;
143         while ((i < requestKeys.size()) && !(key.equalsIgnoreCase((String JavaDoc) requestKeys.elementAt(i)))) {
144             ++i;
145         }
146         if (i < requestKeys.size()) {
147             requestValues.removeElementAt(i);
148             requestKeys.removeElementAt(i);
149         }
150         if (value != null) {
151             requestValues.addElement(value);
152             requestKeys.addElement(key);
153         }
154     }
155
156     public String JavaDoc getRequestProperty(String JavaDoc key) {
157         int i = 0;
158         while ((i < requestKeys.size()) && !(key.equalsIgnoreCase((String JavaDoc) requestKeys.elementAt(i)))) {
159             ++i;
160         }
161         if (i < requestKeys.size()) {
162             return (String JavaDoc) requestValues.elementAt(i);
163         } else {
164             return null;
165         }
166     }
167
168     public OutputStream JavaDoc getOutputStream() throws IOException JavaDoc {
169         if (!doOutput) {
170             throw new IOException JavaDoc(Messages.getString("HttpsURLConnection.protocolOutputNotConfigured")); //$NON-NLS-1$
171
}
172         if (connected) {
173             throw new IOException JavaDoc(Messages.getString("HttpsURLConnection.alreadyConnected")); //$NON-NLS-1$
174
}
175         return output;
176     }
177
178     private boolean isNonProxiedHost(String JavaDoc host) {
179         String JavaDoc nonProxiedHosts = System.getProperty(httpProxyNonProxyHostsProperty);
180         if (nonProxiedHosts == null || nonProxiedHosts.equals("")) { //$NON-NLS-1$
181
return false;
182         }
183         StringTokenizer JavaDoc t = new StringTokenizer JavaDoc(nonProxiedHosts, "|"); //$NON-NLS-1$
184
// TODO add wildcard logic like the sun implementation
185
while (t.hasMoreTokens()) {
186             if (host.equalsIgnoreCase(t.nextToken())) {
187                 return true;
188             }
189         }
190         return false;
191     }
192
193     public synchronized void connect() throws IOException JavaDoc {
194
195         if (!connected) {
196
197             // #ifdef DEBUG
198
log.info(MessageFormat.format(Messages.getString("HttpsURLConnection.connecting"), new Object JavaDoc[] { url.getHost(), new Integer JavaDoc(url.getPort() == -1 ? 443 : url.getPort()) })); //$NON-NLS-1$
199
// #endif
200

201             String JavaDoc proxyHost = System.getProperty(httpProxyHostProperty);
202             if (proxyHost != null && !isNonProxiedHost(url.getHost())) {
203
204                 boolean isSecure = Boolean.valueOf(System.getProperty(httpProxySecureProperty, "true")).booleanValue(); //$NON-NLS-1$
205
String JavaDoc proxyPort = System.getProperty(httpProxyPortProperty);
206                 String JavaDoc proxyUsername = System.getProperty(httpProxyUsernameProperty);
207                 String JavaDoc proxyPassword = System.getProperty(httpProxyPasswordProperty);
208
209                 // #ifdef DEBUG
210
log.info(MessageFormat.format(Messages.getString("HttpsURLConnection.requiresProxyConnection"), new Object JavaDoc[] { isSecure ? "https" : "http://", proxyHost, new Integer JavaDoc(proxyPort) })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
211
log.info(MessageFormat.format(Messages.getString("HttpsURLConnection.proxyUsername"), new Object JavaDoc[] { proxyUsername == null || proxyUsername.equals("") ? "not set" : proxyUsername })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
212
// #endif
213
if (proxyPort == null) {
214                     throw new IOException JavaDoc(Messages.getString("HttpsURLConnection.noProxyPort")); //$NON-NLS-1$
215
}
216
217                 try {
218                     int port = Integer.parseInt(proxyPort);
219
220                     HttpClient client = new HttpClient(proxyHost, port, isSecure);
221                     HttpMethod method = new ConnectMethod(url.getHost(), url.getPort() == -1 ? 443 : url.getPort(), true);
222
223                     PasswordCredentials credentials = new PasswordCredentials();
224                     credentials.setUsername(proxyUsername);
225                     credentials.setPassword(proxyPassword);
226
227                     client.setCredentials(credentials);
228
229                     HttpResponse response = client.execute(method);
230                     socket = response.getConnection().getSocket();
231                 } catch (HttpException ex) {
232                     // #ifdef DEBUG
233
log.info(MessageFormat.format(Messages.getString("HttpsURLConnection.proxyConnectionFailed"), new Object JavaDoc[] { ex.getMessage(), new Integer JavaDoc(ex.getStatus()) })); //$NON-NLS-1$
234
// #endif
235
throw new IOException JavaDoc(MessageFormat.format(Messages.getString("HttpsURLConnection.proxyConnectionFailed"), new Object JavaDoc[] { ex.getMessage(), new Integer JavaDoc(ex.getStatus()) })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
236
} catch (UnsupportedAuthenticationException ex) {
237                     // #ifdef DEBUG
238
log.info(Messages.getString("HttpsURLConnection.proxyAuthenticationFailed"), ex); //$NON-NLS-1$
239
// #endif
240
throw new IOException JavaDoc(ex.getMessage());
241                 } catch (AuthenticationCancelledException ex) {
242                     throw new IOException JavaDoc(Messages.getString("HttpsURLConnection.userCancelledAuthenitcation")); //$NON-NLS-1$
243
}
244             } else {
245                 String JavaDoc host = url.getHost();
246                 if (host == null) {
247                     throw new IOException JavaDoc(Messages.getString("HttpsURLConnection.noHost")); //$NON-NLS-1$
248
}
249                 int port = url.getPort();
250                 try {
251                     socket = new SSLSocket(host, port == -1 ? 443 : port);
252                 } catch (SSLException ex1) {
253                     throw new SSLIOException(ex1);
254                 }
255             }
256
257             try {
258                 writeRequest(socket.getOutputStream());
259                 readResponse(input = new PushbackInputStream JavaDoc(socket.getInputStream(), 2048));
260             } catch (IOException JavaDoc ex) {
261                 try {
262                     socket.close();
263                 } catch (IOException JavaDoc ignored) {
264                 }
265                 throw ex;
266             }
267             connected = true;
268         }
269     }
270
271     void writeRequest(OutputStream JavaDoc out) throws IOException JavaDoc {
272         DataOutputStream JavaDoc data = new DataOutputStream JavaDoc(new BufferedOutputStream JavaDoc(out));
273         if ((doOutput) && (output == null)) {
274             throw new IOException JavaDoc(Messages.getString("HttpsURLConnection.noPOSTData")); //$NON-NLS-1$
275
}
276         if (ifModifiedSince != 0) {
277             Date JavaDoc date = new Date JavaDoc(ifModifiedSince);
278             SimpleDateFormat JavaDoc formatter = new SimpleDateFormat JavaDoc("EEE, d MMM yyyy hh:mm:ss z"); //$NON-NLS-1$
279
formatter.setTimeZone(TimeZone.getTimeZone("GMT")); //$NON-NLS-1$
280
setRequestProperty("If-Modified-Since", formatter.format(date)); //$NON-NLS-1$
281
}
282         if (doOutput) {
283             setRequestProperty("Content-length", "" + output.size()); //$NON-NLS-1$ //$NON-NLS-2$
284
}
285
286         data.writeBytes((doOutput ? "POST" : "GET") + " " + (url.getFile().equals("") ? "/" : url.getFile()) + " HTTP/1.0\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
287

288         for (int i = 0; i < requestKeys.size(); ++i) {
289             String JavaDoc key = (String JavaDoc) requestKeys.elementAt(i);
290             if (!key.startsWith("Proxy-")) { //$NON-NLS-1$
291
data.writeBytes(key + ": " + requestValues.elementAt(i) + "\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
292
}
293         }
294         data.writeBytes("\r\n"); //$NON-NLS-1$
295
data.flush();
296         if (doOutput) {
297             output.writeTo(out);
298         }
299         out.flush();
300     }
301
302     void readResponse(PushbackInputStream JavaDoc in) throws IOException JavaDoc {
303         DataInputStream JavaDoc data = new DataInputStream JavaDoc(in);
304         String JavaDoc line;
305         while (((line = data.readLine()) != null) && (line.length() > 0)) {
306             headers.addElement(line);
307             int index = line.indexOf(':');
308             if (index >= 0) {
309                 String JavaDoc key = line.substring(0, index);
310                 String JavaDoc value = line.substring(index + 1).trim();
311                 headerKeys.addElement(key);
312                 headerValues.put(key.toLowerCase(), value);
313             } else {
314                 // If the first line back is not a header, the unread as the
315
// rest is going to be content
316
if (headerValues.size() == 0) {
317
318                     // This is a response code
319
if (line.startsWith("HTTP/")) { //$NON-NLS-1$
320
try {
321                             int idx = line.indexOf(' ');
322                             while (line.charAt(++idx) == ' ') {
323                                 ;
324                             }
325                             responseMessage = line.substring(idx + 4);
326                             responseCode = Integer.parseInt(line.substring(idx, idx + 3));
327                         } catch (Throwable JavaDoc t) {
328                             responseCode = 200;
329                         }
330                     } else {
331                         // Just content
332
responseCode = 200;
333                         byte[] unread = line.getBytes();
334                         in.unread(unread);
335                         break;
336                     }
337
338                 }
339             }
340         }
341     }
342
343     public int getResponseCode() {
344         if (!connected) {
345             throw new IllegalStateException JavaDoc(Messages.getString("HttpsURLConnection.notConnected")); //$NON-NLS-1$
346
}
347         // if (responseCode == -1) {
348
// responseCode = 200; // Its possible that there wont be a response
349
// code
350
// if(headers.size() > 0) {
351
// String response = getHeaderField(0);
352
// System.out.println("!!!!! REMOVE ME
353
// maverick/src/com/maverick/ssl/https/HttpsURLConnection.getResponseCode()
354
// - response = " + response);
355
// int index = response.indexOf(' ');
356
// while (response.charAt(++index) == ' ') {
357
// ;
358
// }
359
// responseMessage = response.substring(index + 4);
360
// try {
361
// responseCode = Integer.parseInt(response.substring(index, index +
362
// 3));
363
// }
364
// catch(NumberFormatException nfe) {
365
// // ????
366
// }
367
// }
368
// }
369
return responseCode;
370     }
371
372     public String JavaDoc getResponseMessage() {
373         if (!connected) {
374             throw new IllegalStateException JavaDoc(Messages.getString("HttpsURLConnection.notConnected")); //$NON-NLS-1$
375
}
376         getResponseCode();
377         return responseMessage;
378     }
379
380     public String JavaDoc getHeaderField(String JavaDoc name) {
381         if (!connected) {
382             throw new IllegalStateException JavaDoc(Messages.getString("HttpsURLConnection.notConnected")); //$NON-NLS-1$
383
}
384         return (String JavaDoc) headerValues.get(name.toLowerCase());
385     }
386
387     public String JavaDoc getHeaderFieldKey(int n) {
388         if (!connected) {
389             throw new IllegalStateException JavaDoc(Messages.getString("HttpsURLConnection.notConnected")); //$NON-NLS-1$
390
}
391         if (n < headerKeys.size()) {
392             return (String JavaDoc) headerKeys.elementAt(n);
393         } else {
394             return null;
395         }
396     }
397
398     public String JavaDoc getHeaderField(int n) {
399         if (!connected) {
400             throw new IllegalStateException JavaDoc(Messages.getString("HttpsURLConnection.notConnected")); //$NON-NLS-1$
401
}
402         if (n < headers.size()) {
403             return (String JavaDoc) headers.elementAt(n);
404         } else {
405             return null;
406         }
407     }
408
409     public InputStream JavaDoc getInputStream() throws IOException JavaDoc {
410         if (!doInput) {
411             throw new IOException JavaDoc(Messages.getString("HttpsURLConnection.protocolInputNotConfigured")); //$NON-NLS-1$
412
}
413         connect();
414         return input;
415     }
416
417     public Socket JavaDoc getSocket() {
418         if (!connected) {
419             throw new IllegalStateException JavaDoc(Messages.getString("HttpsURLConnection.notConnected")); //$NON-NLS-1$
420
}
421         return socket;
422     }
423
424     public void disconnect() {
425
426     }
427
428     public boolean usingProxy() {
429         return System.getProperty(httpProxyHostProperty) != null;
430     }
431 }
432
Popular Tags