01: /*
02: * Copyright 2007 The Kuali Foundation.
03: *
04: * Licensed under the Educational Community License, Version 1.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.opensource.org/licenses/ecl1.php
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package edu.yale.its.tp.cas.util;
17:
18: import java.io.BufferedReader;
19: import java.io.IOException;
20: import java.io.InputStreamReader;
21: import java.net.URL;
22: import java.net.URLConnection;
23:
24: /**
25: * <p>
26: * A class housing some utility functions exposing secure URL validation and content retrieval. The rules are intended to be about
27: * as restrictive as a common browser with respect to server-certificate validation.
28: * </p>
29: * NOTE: Depends on JSSE or JDK 1.4!
30: */
31: public class SecureURL {
32:
33: /**
34: * For testing only...
35: */
36: public static void main(String args[]) throws IOException {
37: System.setProperty("java.protocol.handler.pkgs",
38: "com.sun.net.ssl.internal.www.protocol");
39: System.out.println(SecureURL.retrieve(args[0]));
40: }
41:
42: /**
43: * Retrieve the contents from the given URL as a String, assuming the URL's server matches what we expect it to match.
44: */
45: public static String retrieve(String url) throws IOException {
46: BufferedReader r = null;
47: try {
48: URL u = new URL(url);
49: if (!u.getProtocol().equals("https"))
50: throw new IOException(
51: "only 'https' URLs are valid for this method");
52: URLConnection uc = u.openConnection();
53: uc.setRequestProperty("Connection", "close");
54: r = new BufferedReader(new InputStreamReader(uc
55: .getInputStream()));
56: String line;
57: StringBuffer buf = new StringBuffer();
58: while ((line = r.readLine()) != null)
59: buf.append(line + "\n");
60: return buf.toString();
61: } finally {
62: try {
63: if (r != null)
64: r.close();
65: } catch (IOException ex) {
66: // ignore
67: }
68: }
69: }
70: }
|