Salut,
I suspect this test will fail if you don't have environment properties
named javax.net.ssl.keyStore and javax.net.ssl.trustStore. Does someone
knows how to set those using Maven 2? I suspect I will have to add a
dummy *Store and hardcode the location inside the test. Any recommendations?
Thanks
-- jeanfrancois
-------- Original Message --------
Subject: svn commit: r200 -
trunk/modules/grizzly/src/test/java/com/sun/grizzly/SSLServerTest.java
Date: Thu, 24 May 2007 16:54:02 +0000
From: jfarcand_at_dev.java.net
Reply-To: commits_at_grizzly.dev.java.net
To: commits_at_grizzly.dev.java.net
Author: jfarcand
Date: 2007-05-24 16:54:00+0000
New Revision: 200
Added:
trunk/modules/grizzly/src/test/java/com/sun/grizzly/SSLServerTest.java
Log:
Add an SSL/HTTP unit test.
Added:
trunk/modules/grizzly/src/test/java/com/sun/grizzly/SSLServerTest.java
Url:
https://grizzly.dev.java.net/source/browse/grizzly/trunk/modules/grizzly/src/test/java/com/sun/grizzly/SSLServerTest.java?view=auto&rev=200
==============================================================================
--- (empty file)
+++
trunk/modules/grizzly/src/test/java/com/sun/grizzly/SSLServerTest.java
2007-05-24 16:54:00+0000
@@ -0,0 +1,304 @@
+/*
+ * The contents of this file are subject to the terms
+ * of the Common Development and Distribution License
+ * (the License). You may not use this file except in
+ * compliance with the License.
+ *
+ * You can obtain a copy of the license at
+ *
https://glassfish.dev.java.net/public/CDDLv1.0.html or
+ * glassfish/bootstrap/legal/CDDLv1.0.txt.
+ * See the License for the specific language governing
+ * permissions and limitations under the License.
+ *
+ * When distributing Covered Code, include this CDDL
+ * Header Notice in each file and include the License file
+ * at glassfish/bootstrap/legal/CDDLv1.0.txt.
+ * If applicable, add the following below the CDDL Header,
+ * with the fields enclosed by brackets [] replaced by
+ * you own identifying information:
+ * "Portions Copyrighted [year] [name of copyright owner]"
+ *
+ * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
+ */
+
+package com.sun.grizzly;
+
+import com.sun.grizzly.filter.LogFilter;
+import com.sun.grizzly.filter.SSLReadFilter;
+import com.sun.grizzly.util.SSLByteBufferInputStream;
+import com.sun.grizzly.util.SSLOutputWriter;
+import com.sun.grizzly.util.WorkerThread;
+import java.io.IOException;
+import java.util.logging.Level;
+import junit.framework.TestCase;
+
+import com.sun.grizzly.util.net.SSLImplementation;
+import com.sun.grizzly.util.net.ServerSocketFactory;
+import java.io.BufferedReader;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.channels.SocketChannel;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetEncoder;
+import java.security.KeyStore;
+import java.util.Date;
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+
+/**
+ *
+ * @author Jeanfrancois Arcand
+ */
+public class SSLServerTest extends TestCase{
+ final Controller server = new Controller();
+
+ private HttpsURLConnection connection;
+
+ /**
+ * <code>CharBuffer</code> used to store the HTML response, containing
+ * the headers and the body of the response.
+ */
+ private static CharBuffer reponseBuffer = CharBuffer.allocate(4096);
+
+
+ /**
+ * Encoder used to encode the HTML response
+ */
+ private static CharsetEncoder encoder =
+ Charset.forName("UTF-8").newEncoder();
+
+ public SSLServerTest(String arg0){
+ super(arg0);
+ }
+
+
+ /*
+ * @see TestCase#setUp()
+ */
+ protected void setUp() throws Exception{
+ super.setUp();
+
+ final SSLReadFilter readFilter = new SSLReadFilter();
+ final LogFilter logFilter = new LogFilter();
+
+ System.out.println("Keystore location [-Djavax.net.ssl.keyStore]"
+ + System.getProperty("javax.net.ssl.keyStore"));
+ System.out.println("Truststore location
[-Djavax.net.ssl.trustStore]"
+ + System.getProperty("javax.net.ssl.trustStore"));
+ try{
+ SSLImplementation sslHelper = SSLImplementation.getInstance();
+ ServerSocketFactory serverSF =
+ sslHelper.getServerSocketFactory();
+ serverSF.setAttribute("keystoreType","JKS");
+ serverSF.setAttribute("keystore",
+ System.getProperty("javax.net.ssl.keyStore"));
+ serverSF.setAttribute("truststoreType","JKS");
+ serverSF.setAttribute("truststore",
+ System.getProperty("javax.net.ssl.trustStore"));
+ serverSF.init();
+ SSLContext sslContext = serverSF.getSSLContext();
+
+ server.setProtocolChainInstanceHandler(new
DefaultProtocolChainInstanceHandler(){
+ public ProtocolChain poll() {
+ ProtocolChain protocolChain = protocolChains.poll();
+ if (protocolChain == null){
+ protocolChain = new DefaultProtocolChain();
+ protocolChain.addFilter(readFilter);
+ protocolChain.addFilter(new ProtocolFilter(){
+
+ public boolean execute(Context ctx){
+ try{
+ SSLByteBufferInputStream
inputStream = new SSLByteBufferInputStream();
+ final WorkerThread workerThread =
((WorkerThread)Thread.currentThread());
+ ByteBuffer bb =
workerThread.getByteBuffer();
+ bb.flip();
+ inputStream.setByteBuffer(bb);
+
inputStream.setSelectionKey(ctx.getSelectionKey());
+
+ byte[] requestBytes = new byte[8192];
+ inputStream.read(requestBytes);
+ SocketChannel socketChannel =
+
(SocketChannel)ctx.getSelectionKey().channel();
+
+ reponseBuffer.clear();
+ reponseBuffer.put("HTTP/1.1 200
OK\r\n");
+ appendHeaderValue("Content-Type",
"text/html");
+ appendHeaderValue("Content-Length",
0 + "");
+ appendHeaderValue("Date", new
Date().toString());
+ appendHeaderValue("Connection",
"Close");
+ reponseBuffer.put("\r\n\r\n");
+ reponseBuffer.flip();
+ ByteBuffer rBuf =
encoder.encode(reponseBuffer);
+
SSLOutputWriter.flushChannel(socketChannel,rBuf);
+ } catch (Throwable t){
+ t.printStackTrace();
+ ctx.setAttribute(Context.THROWABLE,t);
+ }
+ ctx.setKeyRegistrationState(
+ Context.KeyRegistrationState.CANCEL);
+ return true;
+ }
+
+
+
+ /**
+ * Utility to add headers to the HTTP response.
+ */
+ private void appendHeaderValue(String name,
String value) {
+ reponseBuffer.put(name);
+ reponseBuffer.put(": ");
+ reponseBuffer.put(value);
+ reponseBuffer.put("\r\n");
+ }
+ public boolean postExecute(Context ctx){
+
+ return true;
+ }
+ });
+ }
+ return protocolChain;
+ }
+ });
+
+ SslTCPSelectorHandler sel = new SslTCPSelectorHandler();
+ sel.setSSLContext(sslContext);
+ sel.setPort(8888);
+ server.addSelectorHandler(sel);
+
+ SslSelectionKeyHandler keyHandler = new
SslSelectionKeyHandler();
+ keyHandler.setTimeout(2500);
+ server.setSelectionKeyHandler(keyHandler);
+ server.setPipeline(new SSLPipeline());
+
+ new Thread(){
+ public void run(){
+ try{
+ server.start();
+ } catch(IOException ex){
+ ex.printStackTrace();
+ }
+ }
+ }.start();
+ } catch(IOException ex){
+ ex.printStackTrace();
+ server.logger().log(Level.SEVERE,"Controller.start()",ex);
+ }
+ Thread.currentThread().sleep(1000);
+ }
+
+ /*
+ * @see TestCase#tearDown()
+ */
+ protected void tearDown() throws Exception{
+ super.tearDown();
+ server.stop();
+ }
+
+
+ public void testHandshake(){
+ try {
+ SSLSocketFactory ssf = getSSLSocketFactory(
+ System.getProperty("javax.net.ssl.trustStore"));
+ connection = doSSLHandshake("
https://localhost:8888/", ssf);
+ assertTrue(true);
+ } catch (Throwable t) {
+ fail("Unexpected exception");
+ t.printStackTrace();
+ }
+ }
+
+
+ public void testConnection(){
+ try{
+ SSLSocketFactory ssf = getSSLSocketFactory(
+ System.getProperty("javax.net.ssl.trustStore"));
+ connection = doSSLHandshake("
https://localhost:8888/", ssf);
+ connection.setConnectTimeout(5000);
+ int responseCode=connection.getResponseCode();
+ assertEquals("200", String.valueOf(responseCode));
+ } catch (Throwable t){
+ fail("Unexpected exception");
+ t.printStackTrace();
+ }
+ }
+
+
+
+ private static SSLSocketFactory getSSLSocketFactory(String
trustStorePath)
+ throws Exception {
+ SSLContext sc = SSLContext.getInstance("SSL");
+ sc.init(null, getTrustManagers(trustStorePath), null);
+ return sc.getSocketFactory();
+ }
+
+
+ private static HttpsURLConnection doSSLHandshake(String urlAddress,
+ SSLSocketFactory ssf)
+ throws Exception{
+ URL url = new URL(urlAddress);
+ HttpsURLConnection.setDefaultSSLSocketFactory(ssf);
+ HttpsURLConnection connection = (HttpsURLConnection)
url.openConnection();
+
+ connection.setHostnameVerifier(
+ new HostnameVerifier() {
+ public boolean verify(String rserver, SSLSession sses) {
+ return true;
+ }
+ });
+ connection.setDoOutput(true);
+ return connection;
+ }
+
+ private static void parseResponse(HttpsURLConnection connection)
+ throws Exception{
+
+ BufferedReader in = new BufferedReader(
+ new InputStreamReader(connection.getInputStream()));
+
+ String line = "";
+ int index;
+ while ((line = in.readLine()) != null) {
+ System.out.println(line);
+ }
+
+ in.close();
+ }
+
+ private static TrustManager[] getTrustManagers(String path)
+ throws Exception {
+
+ TrustManager[] tms = null;
+ InputStream istream = null;
+
+ try {
+ KeyStore trustStore = KeyStore.getInstance("JKS");
+ istream = new FileInputStream(path);
+ trustStore.load(istream, null);
+ istream.close();
+ istream = null;
+ TrustManagerFactory tmf =
TrustManagerFactory.getInstance("SunX509");
+ tmf.init(trustStore);
+ tms = tmf.getTrustManagers();
+
+ } finally {
+ if (istream != null) {
+ try {
+ istream.close();
+ } catch (IOException ioe) {
+ // Do nothing
+ }
+ }
+ }
+ return tms;
+ }
+}
+
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe_at_grizzly.dev.java.net
For additional commands, e-mail: commits-help_at_grizzly.dev.java.net