KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > test > security > test > HttpsUnitTestCase


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.test;
23
24 import javax.net.ssl.KeyManagerFactory;
25 import javax.net.ssl.SSLContext;
26 import javax.net.ssl.TrustManager;
27 import javax.net.ssl.TrustManagerFactory;
28
29 import java.io.InputStream JavaDoc;
30 import java.io.IOException JavaDoc;
31 import java.io.OutputStream JavaDoc;
32 import java.net.InetAddress JavaDoc;
33 import java.net.ServerSocket JavaDoc;
34 import java.net.Socket JavaDoc;
35 import java.net.URL JavaDoc;
36 import java.security.KeyStore JavaDoc;
37 import java.security.Security JavaDoc;
38 import java.text.SimpleDateFormat JavaDoc;
39 import java.util.Date JavaDoc;
40 import java.util.TimeZone JavaDoc;
41 import javax.management.ObjectName JavaDoc;
42 import javax.net.ServerSocketFactory;
43 import javax.net.ssl.SSLServerSocket;
44 import javax.net.ssl.SSLServerSocketFactory;
45
46 import junit.extensions.TestSetup;
47 import junit.framework.Test;
48 import junit.framework.TestSuite;
49
50 import org.jboss.logging.Logger;
51 import org.jboss.test.JBossTestCase;
52 import org.jboss.test.JBossTestSetup;
53 import org.jboss.test.util.SecurityProviderUtil;
54
55 /** Test of using https urls inside of the JBoss server. This testcase
56  creates a simple https server and deploys a service that tries to
57  connect to the server using the https url passed to the service.
58
59  @author Scott.Stark@jboss.org
60  @version $Revision: 58115 $
61  */

62 public class HttpsUnitTestCase extends JBossTestCase
63 {
64    static final String JavaDoc JAR = "https-service.sar";
65    static final String JavaDoc KEYSTORE_PASSWORD = "unit-tests";
66
67    public HttpsUnitTestCase(String JavaDoc name)
68    {
69       super(name);
70    }
71
72    /** Test the JSSE installation
73     */

74    public void testJSSE() throws Exception JavaDoc
75    {
76       log.debug("+++ testJSSE");
77       ServerSocketFactory factory =
78          SSLServerSocketFactory.getDefault();
79       SSLServerSocket sslSocket = (SSLServerSocket)
80          factory.createServerSocket(0);
81       int port = sslSocket.getLocalPort();
82
83       String JavaDoc [] cipherSuites = sslSocket.getEnabledCipherSuites();
84       for(int i = 0; i < cipherSuites.length; i++)
85       {
86          getLog().debug("Cipher Suite " + i +
87          " = " + cipherSuites[i]);
88       }
89       sslSocket.close();
90    }
91
92    /** Test a login against the SRP service using the SRPLoginModule
93     */

94    public void testHttpsURL() throws Exception JavaDoc
95    {
96       log.debug("+++ testHttpsURL");
97       // Setup the SSL listening port
98
String JavaDoc httpsURL = initServer();
99       log.debug("Setup SSL socket, URL="+httpsURL);
100       // Have the service in JBoss use the https url
101
ObjectName JavaDoc name = new ObjectName JavaDoc("jboss.security.tests:service=HttpsClient");
102       String JavaDoc method = "readURL";
103       Object JavaDoc[] args = {httpsURL};
104       String JavaDoc[] sig = {"java.lang.String"};
105       String JavaDoc reply = (String JavaDoc) invoke(name, method, args, sig);
106       log.debug("Reply for url="+httpsURL+" is: "+reply);
107    }
108
109    private String JavaDoc initServer() throws Exception JavaDoc
110    {
111       String JavaDoc httpsURL = null;
112       SSLContext sslCtx = null;
113       try
114       {
115          sslCtx = SSLContext.getInstance("TLS");
116          ClassLoader JavaDoc loader = getClass().getClassLoader();
117          URL JavaDoc keyStoreURL = loader.getResource("tst.keystore");
118          if( keyStoreURL == null )
119             throw new IOException JavaDoc("Failed to find resource tst.keystore");
120          log.debug("Opening KeyStore: "+keyStoreURL);
121          KeyStore JavaDoc keyStore = KeyStore.getInstance("JKS");
122          InputStream JavaDoc is = keyStoreURL.openStream();
123          keyStore.load(is, KEYSTORE_PASSWORD.toCharArray());
124          String JavaDoc algorithm = KeyManagerFactory.getDefaultAlgorithm();
125          KeyManagerFactory keyMgr = KeyManagerFactory.getInstance(algorithm);
126          keyMgr.init(keyStore, KEYSTORE_PASSWORD.toCharArray());
127          algorithm = TrustManagerFactory.getDefaultAlgorithm();
128          TrustManagerFactory trustMgr = TrustManagerFactory.getInstance(algorithm);
129          trustMgr.init(keyStore);
130          TrustManager[] trustMgrs = trustMgr.getTrustManagers();
131          sslCtx.init(keyMgr.getKeyManagers(), trustMgrs, null);
132       }
133       catch(Exception JavaDoc e)
134       {
135          log.error("Failed to init SSLContext", e);
136          throw new IOException JavaDoc("Failed to get SSLContext for TLS algorithm");
137       }
138
139       ServerSocketFactory factory = sslCtx.getServerSocketFactory();
140       ServerSocket JavaDoc serverSocket = factory.createServerSocket(0);
141       getLog().debug("Created serverSocket: "+serverSocket);
142       int port = serverSocket.getLocalPort();
143       InetAddress JavaDoc addr = serverSocket.getInetAddress();
144       httpsURL = "https://localhost:" + port + '/';
145       AcceptThread thread = new AcceptThread(serverSocket, getLog(), httpsURL);
146       synchronized( httpsURL )
147       {
148          log.debug("Starting server socket thread");
149          thread.start();
150          log.debug("Waiting for accept thread notify");
151          httpsURL.wait();
152       }
153       return httpsURL;
154    }
155
156    /**
157     * Setup the test suite.
158     */

159    public static Test suite() throws Exception JavaDoc
160    {
161       TestSuite suite = new TestSuite();
162       suite.addTest(new TestSuite(HttpsUnitTestCase.class));
163
164       // Create an initializer for the test suite
165
TestSetup wrapper = new JBossTestSetup(suite)
166       {
167          protected void setUp() throws Exception JavaDoc
168          {
169             super.setUp();
170             deploy(JAR);
171             Security.addProvider(SecurityProviderUtil.getJSSEProvider());
172          }
173          protected void tearDown() throws Exception JavaDoc
174          {
175             undeploy(JAR);
176             super.tearDown();
177          }
178       };
179       return wrapper;
180    }
181
182    /** A subclass of Thread that processes a single request sent to
183     the serverSocket.
184     */

185    static class AcceptThread extends Thread JavaDoc
186    {
187       ServerSocket JavaDoc serverSocket;
188       Logger log;
189       Object JavaDoc lock;
190       AcceptThread(ServerSocket JavaDoc serverSocket, Logger log, Object JavaDoc lock)
191       {
192          super("AcceptThread");
193          super.setDaemon(true);
194          this.serverSocket = serverSocket;
195          this.log = log;
196          this.lock = lock;
197       }
198
199       public void run()
200       {
201          SimpleDateFormat JavaDoc fmt = new SimpleDateFormat JavaDoc("E, dd MMM yyyy HH:mm:ss z");
202          fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
203          Date JavaDoc now = new Date JavaDoc();
204          String JavaDoc dateString = fmt.format(now);
205          String JavaDoc content = "<html><head><title>HttpsUnitTestCase</title></head>"
206             + "<body>"+dateString+"</body></html>\r\n";
207          String JavaDoc reply = "HTTP/1.1 200 OK\r\n"
208             + "Date: "+dateString+"\r\n"
209             + "Server: HttpsUnitTestCase/JSSE SSL\r\n"
210             + "Last-Modified: "+dateString+"\r\n"
211             + "Content-Length: "+content.length()+"\r\n"
212             + "Connection: close\r\n"
213             + "Content-Type: text/html\r\n\r\n"
214             + content;
215
216          while( true )
217          {
218             try
219             {
220                log.debug("Waiting for client connection");
221                synchronized( lock )
222                {
223                   lock.notify();
224                }
225                Socket JavaDoc client = serverSocket.accept();
226                log.debug("Accepted client: "+client);
227                InputStream JavaDoc is = client.getInputStream();
228                OutputStream JavaDoc os = client.getOutputStream();
229                byte[] buffer = new byte[4096];
230                int bytes = is.read(buffer);
231                log.debug("Read: "+bytes);
232                os.write(reply.getBytes());
233                os.flush();
234                log.debug("Wrote: "+reply.length());
235                log.debug("ReplyData: "+reply);
236                os.close();
237                is.close();
238                client.close();
239                log.debug("Closed client");
240             }
241             catch(Exception JavaDoc e)
242             {
243                log.error("Failed to process request", e);
244                break;
245             }
246          }
247
248          try
249          {
250             serverSocket.close();
251          }
252          catch(Exception JavaDoc e)
253          {
254             log.error("Failed to close server socket", e);
255          }
256       }
257    }
258 }
259
Popular Tags