Author: elecharny
Date: Fri Dec  9 08:02:25 2011
New Revision: 1212267

URL: http://svn.apache.org/viewvc?rev=1212267&view=rev
Log:
Added a test for HTTPS

Added:
    
mina/trunk/examples/src/main/java/org/apache/mina/examples/http/BogusSslContextFactory.java
    
mina/trunk/examples/src/main/java/org/apache/mina/examples/http/BogusTrustManagerFactory.java
    
mina/trunk/examples/src/main/java/org/apache/mina/examples/http/HttpsTest.java
    mina/trunk/examples/src/main/resources/org/
    mina/trunk/examples/src/main/resources/org/apache/
    mina/trunk/examples/src/main/resources/org/apache/mina/
    mina/trunk/examples/src/main/resources/org/apache/mina/examples/
    mina/trunk/examples/src/main/resources/org/apache/mina/examples/http/
    
mina/trunk/examples/src/main/resources/org/apache/mina/examples/http/bogus.cert 
  (with props)

Added: 
mina/trunk/examples/src/main/java/org/apache/mina/examples/http/BogusSslContextFactory.java
URL: 
http://svn.apache.org/viewvc/mina/trunk/examples/src/main/java/org/apache/mina/examples/http/BogusSslContextFactory.java?rev=1212267&view=auto
==============================================================================
--- 
mina/trunk/examples/src/main/java/org/apache/mina/examples/http/BogusSslContextFactory.java
 (added)
+++ 
mina/trunk/examples/src/main/java/org/apache/mina/examples/http/BogusSslContextFactory.java
 Fri Dec  9 08:02:25 2011
@@ -0,0 +1,146 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.apache.mina.examples.http;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.GeneralSecurityException;
+import java.security.KeyStore;
+import java.security.Security;
+
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+
+/**
+ * Factory to create a bogus SSLContext.
+ *
+ * @author <a href="http://mina.apache.org";>Apache MINA Project</a>
+ */
+public class BogusSslContextFactory {
+
+    /**
+     * Protocol to use.
+     */
+    private static final String PROTOCOL = "TLS";
+
+    private static final String KEY_MANAGER_FACTORY_ALGORITHM;
+
+    static {
+        String algorithm = Security
+                .getProperty("ssl.KeyManagerFactory.algorithm");
+        if (algorithm == null) {
+            algorithm = KeyManagerFactory.getDefaultAlgorithm();
+        }
+
+        KEY_MANAGER_FACTORY_ALGORITHM = algorithm;
+    }
+
+    /**
+     * Bogus Server certificate keystore file name.
+     */
+    private static final String BOGUS_KEYSTORE = "bogus.cert";
+
+    // NOTE: The keystore was generated using keytool:
+    //   keytool -genkey -alias bogus -keysize 512 -validity 3650
+    //           -keyalg RSA -dname "CN=bogus.com, OU=XXX CA,
+    //               O=Bogus Inc, L=Stockholm, S=Stockholm, C=SE"
+    //           -keypass boguspw -storepass boguspw -keystore bogus.cert
+
+    /**
+     * Bougus keystore password.
+     */
+    private static final char[] BOGUS_PW = { 'b', 'o', 'g', 'u', 's', 'p', 'w' 
};
+
+    private static SSLContext serverInstance = null;
+    
+    private static SSLContext clientInstance = null;
+
+    /**
+     * Get SSLContext singleton.
+     *
+     * @return SSLContext
+     * @throws java.security.GeneralSecurityException
+     *
+     */
+    public static SSLContext getInstance(boolean server)
+            throws GeneralSecurityException {
+        SSLContext retInstance = null;
+        if (server) {
+            synchronized(BogusSslContextFactory.class) {
+                if (serverInstance == null) {
+                    try {
+                        serverInstance = createBougusServerSslContext();
+                    } catch (Exception ioe) {
+                        throw new GeneralSecurityException(
+                                "Can't create Server SSLContext:" + ioe);
+                    }
+                }
+            }
+            retInstance = serverInstance;
+        } else {
+            synchronized (BogusSslContextFactory.class) {
+                if (clientInstance == null) {
+                    clientInstance = createBougusClientSslContext();
+                }
+            }
+            retInstance = clientInstance;
+        }
+        return retInstance;
+    }
+
+    private static SSLContext createBougusServerSslContext()
+            throws GeneralSecurityException, IOException {
+        // Create keystore
+        KeyStore ks = KeyStore.getInstance("JKS");
+        InputStream in = null;
+        try {
+            in = BogusSslContextFactory.class
+                    .getResourceAsStream(BOGUS_KEYSTORE);
+            ks.load(in, BOGUS_PW);
+        } finally {
+            if (in != null) {
+                try {
+                    in.close();
+                } catch (IOException ignored) {
+                }
+            }
+        }
+
+        // Set up key manager factory to use our key store
+        KeyManagerFactory kmf = KeyManagerFactory
+                .getInstance(KEY_MANAGER_FACTORY_ALGORITHM);
+        kmf.init(ks, BOGUS_PW);
+
+        // Initialize the SSLContext to work with our key managers.
+        SSLContext sslContext = SSLContext.getInstance(PROTOCOL);
+        sslContext.init(kmf.getKeyManagers(),
+                BogusTrustManagerFactory.X509_MANAGERS, null);
+
+        return sslContext;
+    }
+
+    private static SSLContext createBougusClientSslContext()
+            throws GeneralSecurityException {
+        SSLContext context = SSLContext.getInstance(PROTOCOL);
+        context.init(null, BogusTrustManagerFactory.X509_MANAGERS, null);
+        return context;
+    }
+
+}

Added: 
mina/trunk/examples/src/main/java/org/apache/mina/examples/http/BogusTrustManagerFactory.java
URL: 
http://svn.apache.org/viewvc/mina/trunk/examples/src/main/java/org/apache/mina/examples/http/BogusTrustManagerFactory.java?rev=1212267&view=auto
==============================================================================
--- 
mina/trunk/examples/src/main/java/org/apache/mina/examples/http/BogusTrustManagerFactory.java
 (added)
+++ 
mina/trunk/examples/src/main/java/org/apache/mina/examples/http/BogusTrustManagerFactory.java
 Fri Dec  9 08:02:25 2011
@@ -0,0 +1,74 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.apache.mina.examples.http;
+
+import java.security.InvalidAlgorithmParameterException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+
+import javax.net.ssl.ManagerFactoryParameters;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactorySpi;
+import javax.net.ssl.X509TrustManager;
+
+/**
+ * Bogus trust manager factory. Creates BogusX509TrustManager
+ *
+ * @author <a href="http://mina.apache.org";>Apache MINA Project</a>
+ */
+class BogusTrustManagerFactory extends TrustManagerFactorySpi {
+
+    static final X509TrustManager X509 = new X509TrustManager() {
+        public void checkClientTrusted(X509Certificate[] x509Certificates,
+                String s) throws CertificateException {
+        }
+
+        public void checkServerTrusted(X509Certificate[] x509Certificates,
+                String s) throws CertificateException {
+        }
+
+        public X509Certificate[] getAcceptedIssuers() {
+            return new X509Certificate[0];
+        }
+    };
+
+    static final TrustManager[] X509_MANAGERS = new TrustManager[] { X509 };
+
+    public BogusTrustManagerFactory() {
+    }
+
+    @Override
+    protected TrustManager[] engineGetTrustManagers() {
+        return X509_MANAGERS;
+    }
+
+    @Override
+    protected void engineInit(KeyStore keystore) throws KeyStoreException {
+        // noop
+    }
+
+    @Override
+    protected void engineInit(ManagerFactoryParameters 
managerFactoryParameters)
+            throws InvalidAlgorithmParameterException {
+        // noop
+    }
+}

Added: 
mina/trunk/examples/src/main/java/org/apache/mina/examples/http/HttpsTest.java
URL: 
http://svn.apache.org/viewvc/mina/trunk/examples/src/main/java/org/apache/mina/examples/http/HttpsTest.java?rev=1212267&view=auto
==============================================================================
--- 
mina/trunk/examples/src/main/java/org/apache/mina/examples/http/HttpsTest.java 
(added)
+++ 
mina/trunk/examples/src/main/java/org/apache/mina/examples/http/HttpsTest.java 
Fri Dec  9 08:02:25 2011
@@ -0,0 +1,118 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ * 
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ * 
+ */
+package org.apache.mina.examples.http;
+
+import java.net.InetSocketAddress;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.mina.api.DefaultIoFilter;
+import org.apache.mina.api.IoSession;
+import org.apache.mina.filter.logging.LoggingFilter;
+import org.apache.mina.filterchain.ReadFilterChainController;
+import org.apache.mina.http.DateUtil;
+import org.apache.mina.http.HttpServerCodec;
+import org.apache.mina.http.api.DefaultHttpResponse;
+import org.apache.mina.http.api.HttpEndOfContent;
+import org.apache.mina.http.api.HttpMethod;
+import org.apache.mina.http.api.HttpRequest;
+import org.apache.mina.http.api.HttpStatus;
+import org.apache.mina.http.api.HttpVersion;
+import org.apache.mina.service.OneThreadSelectorStrategy;
+import org.apache.mina.service.SelectorFactory;
+import org.apache.mina.transport.tcp.NioSelectorProcessor;
+import org.apache.mina.transport.tcp.nio.NioTcpServer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpsTest {
+
+    private static final Logger LOG = LoggerFactory.getLogger(HttpsTest.class);
+
+    public static void main(String[] args) throws Exception {
+
+        OneThreadSelectorStrategy strategy = new OneThreadSelectorStrategy(new 
SelectorFactory(
+                NioSelectorProcessor.class));
+        NioTcpServer acceptor = new NioTcpServer(strategy);
+        
+        // Make it use https, injecting a default SSLContext instance
+        acceptor.setSslContext(BogusSslContextFactory
+            .getInstance(true));
+        
+        acceptor.setFilters(new LoggingFilter("INCOMING"), new 
HttpServerCodec(), new LoggingFilter("DECODED"),
+                new DummyHttpSever());
+
+        acceptor.getSessionConfig().setTcpNoDelay(true);
+
+        acceptor.bind(new InetSocketAddress(8080));
+
+        // run for 20 seconds
+        Thread.sleep(2000000);
+        acceptor.unbindAll();
+
+    }
+
+    private static class DummyHttpSever extends DefaultIoFilter {
+
+        private HttpRequest incomingRequest;
+
+        private List<ByteBuffer> body;
+
+        @Override
+        public void messageReceived(IoSession session, Object message, 
ReadFilterChainController controller) {
+            if (message instanceof HttpRequest) {
+                incomingRequest = (HttpRequest) message;
+                body = new ArrayList<ByteBuffer>();
+
+                // check if this request is going to be followed by and HTTP 
body or not
+                if (incomingRequest.getMethod() != HttpMethod.POST && 
incomingRequest.getMethod() != HttpMethod.PUT) {
+                    sendResponse(session, incomingRequest);
+                } else {
+
+                }
+            } else if (message instanceof ByteBuffer) {
+                body.add((ByteBuffer) message);
+            } else if (message instanceof HttpEndOfContent) {
+                // we received all the post content, send the crap back
+                sendResponse(session, incomingRequest);
+            }
+
+        }
+
+        public void sendResponse(IoSession session, HttpRequest request) {
+            Map<String, String> headers = new HashMap<String, String>();
+            headers.put("Server", "Apache MINA Dummy test server/0.0.");
+            headers.put("Date", DateUtil.getCurrentAsString());
+            headers.put("Connection", "Close");
+            String strContent = "Hello ! we reply to request !";
+            ByteBuffer content = ByteBuffer.wrap(strContent.getBytes());
+
+            // compute content len
+            headers.put("Content-Length", String.valueOf(content.remaining()));
+            session.write(new DefaultHttpResponse(HttpVersion.HTTP_1_1, 
HttpStatus.SUCCESS_OK, headers));
+            session.write(content);
+            session.write(new HttpEndOfContent());
+
+        }
+    }
+}

Added: 
mina/trunk/examples/src/main/resources/org/apache/mina/examples/http/bogus.cert
URL: 
http://svn.apache.org/viewvc/mina/trunk/examples/src/main/resources/org/apache/mina/examples/http/bogus.cert?rev=1212267&view=auto
==============================================================================
Binary file - no diff available.

Propchange: 
mina/trunk/examples/src/main/resources/org/apache/mina/examples/http/bogus.cert
------------------------------------------------------------------------------
    svn:mime-type = application/octet-stream


Reply via email to