KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > test > security > service > HttpsClient


1 /*
2   * JBoss, Home of Professional Open Source
3   * Copyright 2005, JBoss Inc., and individual contributors as indicated
4   * by the @authors tag. See the copyright.txt in the distribution for a
5   * full listing of individual contributors.
6   *
7   * This is free software; you can redistribute it and/or modify it
8   * under the terms of the GNU Lesser General Public License as
9   * published by the Free Software Foundation; either version 2.1 of
10   * the License, or (at your option) any later version.
11   *
12   * This software is distributed in the hope that it will be useful,
13   * but WITHOUT ANY WARRANTY; without even the implied warranty of
14   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   * Lesser General Public License for more details.
16   *
17   * You should have received a copy of the GNU Lesser General Public
18   * License along with this software; if not, write to the Free
19   * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20   * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21   */

22 package org.jboss.test.security.service;
23
24 import java.io.File JavaDoc;
25 import java.io.FileOutputStream JavaDoc;
26 import java.io.InputStream JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.net.JarURLConnection JavaDoc;
29 import java.net.Socket JavaDoc;
30 import java.net.URL JavaDoc;
31 import java.net.HttpURLConnection JavaDoc;
32 import java.net.MalformedURLException JavaDoc;
33 import java.security.Provider JavaDoc;
34 import java.security.Security JavaDoc;
35 import java.util.StringTokenizer JavaDoc;
36 import java.util.jar.JarEntry JavaDoc;
37 import java.util.jar.JarFile JavaDoc;
38 import javax.net.ssl.SSLSocketFactory;
39
40 import org.jboss.logging.Logger;
41 import org.jboss.system.ServiceMBeanSupport;
42 import org.jboss.invocation.http.interfaces.Util;
43 import org.jboss.test.util.SecurityProviderUtil;
44
45 /** A test mbean service that reads input from an https url passed in
46  to its readURL method.
47
48  @author Scott.Stark@jboss.org
49  @version $Revision: 56898 $
50  */

51 public class HttpsClient extends ServiceMBeanSupport
52    implements HttpsClientMBean
53 {
54    // Constants -----------------------------------------------------
55

56    // Attributes ----------------------------------------------------
57
private boolean addedHttpsHandler;
58    
59    private boolean addedJSSEProvider;
60
61    // Static --------------------------------------------------------
62

63    // Constructors --------------------------------------------------
64
public HttpsClient()
65    {
66    }
67
68    public String JavaDoc getName()
69    {
70       return "HttpsClient";
71    }
72
73    /** Read the contents of the given URL and return it. */
74    public String JavaDoc readURL(String JavaDoc urlString) throws IOException JavaDoc
75    {
76       try
77       {
78          String JavaDoc reply = internalReadURL(urlString);
79          log.debug("readURL -> "+reply);
80          return reply;
81       }
82       catch(Throwable JavaDoc e)
83       {
84          log.error("Failed to readURL", e);
85          throw new IOException JavaDoc("Failed to readURL, ex="+e.getMessage());
86       }
87    }
88    private String JavaDoc internalReadURL(String JavaDoc urlString) throws Exception JavaDoc
89    {
90       log.debug("Creating URL from string: "+urlString);
91       URL JavaDoc url = new URL JavaDoc(urlString);
92       log.debug("Created URL object from string, protocol="+url.getProtocol());
93       HttpURLConnection JavaDoc conn = (HttpURLConnection JavaDoc) url.openConnection();
94       /* Override the host verifier so we can use a test server cert with
95        a hostname that may not match the https url hostname.
96       */

97       System.setProperty("org.jboss.security.ignoreHttpsHost", "true");
98       Util.configureHttpsHostVerifier(conn);
99
100       log.debug("Connecting to URL: "+url);
101       byte[] buffer = new byte[1024];
102       int length = conn.getContentLength();
103       log.debug("ContentLength: "+length);
104       InputStream JavaDoc is = conn.getInputStream();
105       StringBuffer JavaDoc reply = new StringBuffer JavaDoc();
106       while( (length = is.read(buffer)) > 0 )
107          reply.append(new String JavaDoc(buffer, 0, length));
108       log.debug("Done, closing streams");
109       is.close();
110       return reply.toString();
111    }
112
113    // Public --------------------------------------------------------
114
protected void startService() throws Exception JavaDoc
115    {
116       addedJSSEProvider = false;
117       try
118       {
119          new URL JavaDoc("https://www.https.test");
120       }
121       catch(MalformedURLException JavaDoc e)
122       {
123          // Install the default JSSE security provider
124
Provider JavaDoc provider = SecurityProviderUtil.getJSSEProvider();
125          log.debug("Adding " + provider.getName());
126          
127          addedJSSEProvider = Security.addProvider(provider) != -1;
128          if (addedJSSEProvider)
129          {
130             log.debug("Added " + provider.getName());
131          }
132          
133          addedHttpsHandler = false;
134          // Install the JSSE https handler if it has not already been added
135
String JavaDoc protocolHandler = SecurityProviderUtil.getProtocolHandlerName();
136
137          String JavaDoc handlers = System.getProperty("java.protocol.handler.pkgs");
138          if( handlers == null || handlers.indexOf(protocolHandler ) < 0 )
139          {
140             handlers += "|" + protocolHandler;
141             log.debug("Adding https handler to java.protocol.handler.pkgs");
142             System.setProperty("java.protocol.handler.pkgs", handlers);
143             addedHttpsHandler = true;
144          }
145       }
146
147       // Install the trust store
148
ClassLoader JavaDoc loader = Thread.currentThread().getContextClassLoader();
149       URL JavaDoc keyStoreURL = loader.getResource("META-INF/tst.keystore");
150       if( keyStoreURL == null )
151          throw new IOException JavaDoc("Failed to find resource tst.keystore");
152       if( keyStoreURL.getProtocol().equals("jar") )
153       {
154          JarURLConnection JavaDoc conn = (JarURLConnection JavaDoc) keyStoreURL.openConnection();
155          JarFile JavaDoc jar = conn.getJarFile();
156          JarEntry JavaDoc entry = jar.getJarEntry("META-INF/tst.keystore");
157          InputStream JavaDoc is = jar.getInputStream(entry);
158          File JavaDoc tmp = File.createTempFile("tst-", ".keystore");
159          tmp.deleteOnExit();
160          FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(tmp);
161          byte[] buffer = new byte[1024];
162          int bytes;
163          while( (bytes = is.read(buffer)) > 0 )
164             fos.write(buffer, 0, bytes);
165          fos.close();
166          is.close();
167          keyStoreURL = tmp.toURL();
168       }
169       log.debug("Setting javax.net.ssl.trustStore to: "+keyStoreURL.getPath());
170       System.setProperty("javax.net.ssl.trustStore", keyStoreURL.getPath());
171    }
172    protected void stopService() throws Exception JavaDoc
173    {
174       if (addedJSSEProvider)
175       {
176          Provider JavaDoc provider = SecurityProviderUtil.getJSSEProvider();
177          String JavaDoc name = provider.getName();
178          log.debug("Removing " + name);
179          Security.removeProvider(name);
180        }
181
182       if( addedHttpsHandler == true )
183       {
184          log.debug("Removing https handler from java.protocol.handler.pkgs");
185          String JavaDoc protocolHandler = SecurityProviderUtil.getProtocolHandlerName();
186          String JavaDoc handlers = System.getProperty("java.protocol.handler.pkgs");
187          StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(handlers, "|");
188          StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
189          while( tokenizer.hasMoreTokens() )
190          {
191             String JavaDoc handler = tokenizer.nextToken();
192             if( handler.equals(protocolHandler) == false )
193             {
194                buffer.append('|');
195                buffer.append(handler);
196             }
197          }
198          System.setProperty("java.protocol.handler.pkgs", buffer.toString());
199       }
200    }
201
202    /** A SSLSocketFactory that logs the createSocket calls.
203     */

204    class DebugSSLSocketFactory extends SSLSocketFactory
205    {
206       SSLSocketFactory factoryDelegate;
207       Logger theLog;
208       DebugSSLSocketFactory(SSLSocketFactory factoryDelegate, Logger theLog)
209       {
210          this.factoryDelegate = factoryDelegate;
211          this.theLog = theLog;
212       }
213
214       public Socket JavaDoc createSocket(java.net.InetAddress JavaDoc host, int port) throws java.io.IOException JavaDoc
215       {
216          theLog.debug("createSocket, host="+host+", port="+port);
217          Socket JavaDoc s = factoryDelegate.createSocket(host, port);
218          theLog.debug("created socket="+s);
219          return s;
220       }
221
222       public Socket JavaDoc createSocket(String JavaDoc host, int port)
223          throws java.io.IOException JavaDoc, java.net.UnknownHostException JavaDoc
224       {
225          theLog.debug("createSocket, host="+host+", port="+port);
226          Socket JavaDoc s = factoryDelegate.createSocket(host, port);
227          theLog.debug("created socket="+s);
228          return s;
229       }
230
231       public Socket JavaDoc createSocket(Socket JavaDoc socket, String JavaDoc host, int port, boolean autoClose)
232          throws java.io.IOException JavaDoc
233       {
234          theLog.debug("createSocket, socket="+socket+", host="+host+", port="+port);
235          Socket JavaDoc s = factoryDelegate.createSocket(socket, host, port, autoClose);
236          theLog.debug("created socket="+s);
237          return s;
238       }
239
240       public Socket JavaDoc createSocket(java.net.InetAddress JavaDoc host, int port, java.net.InetAddress JavaDoc clientAddress, int clientPort)
241          throws java.io.IOException JavaDoc
242       {
243          theLog.debug("createSocket, host="+host+", port="+port+", clientAddress="+clientAddress+", clientPort="+clientPort);
244          Socket JavaDoc s = factoryDelegate.createSocket(host, port, clientAddress, clientPort);
245          theLog.debug("created socket="+s);
246          return s;
247       }
248
249       public Socket JavaDoc createSocket(String JavaDoc host, int port, java.net.InetAddress JavaDoc clientAddress, int clientPort)
250          throws java.io.IOException JavaDoc, java.net.UnknownHostException JavaDoc
251       {
252          theLog.debug("createSocket, host="+host+", port="+port+", addr="+clientAddress);
253          Socket JavaDoc s = factoryDelegate.createSocket(host, port, clientAddress, clientPort);
254          theLog.debug("created socket="+s);
255          return s;
256       }
257
258       public String JavaDoc[] getDefaultCipherSuites()
259       {
260          return factoryDelegate.getDefaultCipherSuites();
261       }
262
263       public String JavaDoc[] getSupportedCipherSuites()
264       {
265          return factoryDelegate.getSupportedCipherSuites();
266       }
267    }
268
269 }
270
Popular Tags