Example usage for org.apache.http.impl.nio DefaultHttpServerIODispatch DefaultHttpServerIODispatch

List of usage examples for org.apache.http.impl.nio DefaultHttpServerIODispatch DefaultHttpServerIODispatch

Introduction

In this page you can find the example usage for org.apache.http.impl.nio DefaultHttpServerIODispatch DefaultHttpServerIODispatch.

Prototype

public DefaultHttpServerIODispatch(final NHttpServerEventHandler handler, final ConnectionConfig config) 

Source Link

Usage

From source file:proxy.NHttpServer.java

public static void main(String[] args) throws Exception {
    if (args.length < 1) {
        System.err.println("Please specify document root directory");
        System.exit(1);// w ww.  j ava 2 s. com
    }
    // Document root directory
    File docRoot = new File(args[0]);
    int port = 8080;
    if (args.length >= 2) {
        port = Integer.parseInt(args[1]);
    }

    // Create HTTP protocol processing chain
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();
    // Create request handler registry
    UriHttpAsyncRequestHandlerMapper reqistry = new UriHttpAsyncRequestHandlerMapper();
    // Register the default handler for all URIs
    reqistry.register("*", new HttpFileHandler(docRoot));
    // Create server-side HTTP protocol handler
    HttpAsyncService protocolHandler = new HttpAsyncService(httpproc, reqistry) {

        @Override
        public void connected(final NHttpServerConnection conn) {
            System.out.println(conn + ": connection open");
            super.connected(conn);
        }

        @Override
        public void closed(final NHttpServerConnection conn) {
            System.out.println(conn + ": connection closed");
            super.closed(conn);
        }

    };
    // Create HTTP connection factory
    NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = NHttpServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            System.out.println("Keystore not found");
            System.exit(1);
        }
        KeyStore keystore = KeyStore.getInstance("jks");
        keystore.load(url.openStream(), "secret".toCharArray());
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keystore, "secret".toCharArray());
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, null, null);
        connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, ConnectionConfig.DEFAULT);
    } else {
        connFactory = new DefaultNHttpServerConnectionFactory(ConnectionConfig.DEFAULT);
    }
    // Create server-side I/O event dispatch
    IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory);
    // Set I/O reactor defaults
    IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(1).setSoTimeout(3000)
            .setConnectTimeout(3000).build();
    // Create server-side I/O reactor
    ListeningIOReactor ioReactor = new DefaultListeningIOReactor(config);
    try {
        // Listen of the given port
        ioReactor.listen(new InetSocketAddress(port));
        // Ready to go!
        ioReactor.execute(ioEventDispatch);
    } catch (InterruptedIOException ex) {
        System.err.println("Interrupted");
    } catch (IOException e) {
        System.err.println("I/O error: " + e.getMessage());
    }
    System.out.println("Shutdown");
}

From source file:yucatan.communication.server.NHttpServer.java

public static void main(String[] args) throws Exception {
    if (args.length < 1) {
        System.err.println("Please specify document root directory");
        System.exit(1);/*  w  ww.j  a v  a 2 s .com*/
    }
    // Document root directory
    File docRoot = new File(args[0]);
    int port = 8080;
    if (args.length >= 2) {
        port = Integer.parseInt(args[1]);
    }
    // HTTP parameters for the server
    HttpParams params = new SyncBasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpTest/1.1");
    // Create HTTP protocol processing chain
    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
            // Use standard server-side protocol interceptors
            new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() });
    // Create request handler registry
    HttpAsyncRequestHandlerRegistry reqistry = new HttpAsyncRequestHandlerRegistry();
    // Register the default handler for all URIs
    reqistry.register("*", new HttpFileHandler(docRoot));
    // Create server-side HTTP protocol handler
    HttpAsyncService protocolHandler = new HttpAsyncService(httpproc, new DefaultConnectionReuseStrategy(),
            reqistry, params) {

        @Override
        public void connected(final NHttpServerConnection conn) {
            System.out.println(conn + ": connection open");
            super.connected(conn);
        }

        @Override
        public void closed(final NHttpServerConnection conn) {
            System.out.println(conn + ": connection closed");
            super.closed(conn);
        }

    };
    // Create HTTP connection factory
    NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = NHttpServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            System.out.println("Keystore not found");
            System.exit(1);
        }
        KeyStore keystore = KeyStore.getInstance("jks");
        keystore.load(url.openStream(), "secret".toCharArray());
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keystore, "secret".toCharArray());
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, null, null);
        connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, params);
    } else {
        connFactory = new DefaultNHttpServerConnectionFactory(params);
    }
    // Create server-side I/O event dispatch
    IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory);
    // Create server-side I/O reactor
    ListeningIOReactor ioReactor = new DefaultListeningIOReactor();
    try {
        // Listen of the given port
        ioReactor.listen(new InetSocketAddress(port));
        // Ready to go!
        ioReactor.execute(ioEventDispatch);
    } catch (InterruptedIOException ex) {
        System.err.println("Interrupted");
    } catch (IOException e) {
        System.err.println("I/O error: " + e.getMessage());
    }
    System.out.println("Shutdown");
}

From source file:talkeeg.httpserver.HttpServer.java

public void run() {
    // Create HTTP connection factory
    NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
    connFactory = createConnectionFactory();
    // Create server-side I/O event dispatch
    IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory);
    // Create server-side I/O reactor
    try {//from w  ww.j a  v a 2s  .c o  m
        ListeningIOReactor ioReactor = new DefaultListeningIOReactor(reactorConfig);
        int portNumber = config.getPortNumber();
        ioReactor.listen(new InetSocketAddress(portNumber));
        ioReactor.execute(ioEventDispatch);
    } catch (IOException e) {
        logger.log(Level.SEVERE, "", e);
    }
}

From source file:com.ultrahook.test.utils.TestServer.java

public void start() throws Exception {
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();/*from   w  w w .ja  v  a2 s  . c  o m*/
    UriHttpAsyncRequestHandlerMapper reqistry = new UriHttpAsyncRequestHandlerMapper();
    reqistry.register("*", new HttpHandler());
    HttpAsyncService protocolHandler = new HttpAsyncService(httpproc, reqistry);
    NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
    connFactory = new DefaultNHttpServerConnectionFactory(ConnectionConfig.DEFAULT);
    final IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory);
    IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(1).setSoTimeout(3000)
            .setConnectTimeout(3000).build();
    ioReactor = new DefaultListeningIOReactor(config);
    ioReactor.listen(new InetSocketAddress(port));
    new Thread() {
        public void run() {
            try {
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException e) {
                e.printStackTrace();
            } catch (IOReactorException e) {
                e.printStackTrace();
            }
        };

    }.start();
}

From source file:se.ginkou.interfaceio.InterfaceServer.java

public static void startServer() throws Exception {
    // HTTP parameters for the server
    HttpParams params = new SyncBasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");

    // Create HTTP protocol processing chain
    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
            // Use standard server-side protocol interceptors
            new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() });

    // Set up request handlers
    HttpAsyncRequestHandlerRegistry reqistry = new HttpAsyncRequestHandlerRegistry();
    reqistry.register("*/datatables", new DataTablesHandler());
    reqistry.register("*/loginmodules", new RuleFileHandler());
    reqistry.register("*/login", new LoginHandler());
    reqistry.register("*", new HttpFileHandler(new File("website")));
    reqistry.register("*/ping", new TestHandler());

    // Create server-side HTTP protocol handler
    HttpAsyncService protocolHandler = new HttpAsyncService(httpproc, new DefaultConnectionReuseStrategy(),
            reqistry, params) {//w  w w. ja  v  a 2  s . c om

        @Override
        public void connected(final NHttpServerConnection conn) {
            System.out.println(conn + ": connection open");
            super.connected(conn);
        }

        @Override
        public void closed(final NHttpServerConnection conn) {
            System.out.println(conn + ": connection closed");
            super.closed(conn);
        }
    };
    // Create HTTP connection factory
    NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;

    //        // Initialize SSL context
    //        ClassLoader cl = NHttpServer.class.getClassLoader();
    //        URL url = cl.getResource("my.keystore");
    //        if (url == null) {
    //            System.out.println("Keystore not found");
    //            System.exit(1);
    //        }
    //        KeyStore keystore  = KeyStore.getInstance("jks");
    //        keystore.load(url.openStream(), "secret".toCharArray());
    //        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
    //                KeyManagerFactory.getDefaultAlgorithm());
    //        kmfactory.init(keystore, "secret".toCharArray());
    //        KeyManager[] keymanagers = kmfactory.getKeyManagers();
    //        SSLContext sslcontext = SSLContext.getInstance("TLS");
    //        sslcontext.init(keymanagers, null, null);
    //        connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, params);
    connFactory = new DefaultNHttpServerConnectionFactory(params);

    // Create server-side I/O event dispatch
    IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory);
    // Create server-side I/O reactor
    ListeningIOReactor ioReactor = new DefaultListeningIOReactor();
    try {
        // Listen of the given port
        ioReactor.listen(new InetSocketAddress(PORT));
        // Ready to go!
        ioReactor.execute(ioEventDispatch);
    } catch (InterruptedIOException ex) {
        System.err.println("Interrupted");
    } catch (IOException e) {
        System.err.println("I/O error: " + e.getMessage());
    }
    System.out.println("Shutdown");
}

From source file:com.aptana.webserver.internal.core.builtin.LocalWebServer.java

private void runServer(InetSocketAddress socketAddress, HttpAsyncRequestHandler httpRequestHandler) {
    HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, SOCKET_TIMEOUT)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, SOCKET_BUFFER_SIZE)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER,
                    "HttpComponents/" + EclipseUtil.getPluginVersion("org.apache.httpcomponents.httpcore")); //$NON-NLS-1$ //$NON-NLS-2$

    BasicHttpProcessor httpProcessor = new BasicHttpProcessor();
    httpProcessor.addInterceptor(new ResponseDate());
    httpProcessor.addInterceptor(new ResponseServer());
    httpProcessor.addInterceptor(new ResponseContent());
    httpProcessor.addInterceptor(new ResponseConnControl());

    HttpAsyncRequestHandlerRegistry handlerRegistry = new HttpAsyncRequestHandlerRegistry();
    handlerRegistry.register("*", httpRequestHandler); //$NON-NLS-1$

    HttpAsyncService serviceHandler = new HttpAsyncService(httpProcessor, new DefaultConnectionReuseStrategy(),
            handlerRegistry, params);//from   ww  w .  ja  v a 2s. com
    // serviceHandler.setEventListener(new LocalWebServerLogger());

    IOReactorConfig config = new IOReactorConfig();
    config.setIoThreadCount(WORKER_COUNT);
    config.setConnectTimeout(SOCKET_TIMEOUT);
    config.setTcpNoDelay(true);
    config.setSoKeepalive(true);

    DefaultHttpServerIODispatch eventDispatch = new DefaultHttpServerIODispatch(serviceHandler, params);
    try {
        reactor = new DefaultListeningIOReactor(config);
        reactor.listen(socketAddress);
        reactor.execute(eventDispatch);
    } catch (InterruptedIOException e) {
        return;
    } catch (IOReactorException e) {
        IdeLog.logWarning(WebServerCorePlugin.getDefault(), e);
    } catch (IOException e) {
        IdeLog.logError(WebServerCorePlugin.getDefault(), e);
    }
}

From source file:com.eislab.af.translator.spokes.HttpServer_spoke.java

public HttpServer_spoke(String ipaddress, String path) throws IOException, InterruptedException {

    address = ipaddress;//w w  w .  j a  va  2  s.  c om
    // HTTP parameters for the server
    HttpParams params = new SyncBasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, SOCKET_TIMEOUT)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, SOCKET_BUFFER_SIZE)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, SERVER_NAME);

    // Create HTTP protocol processing chain
    // Use standard server-side protocol interceptors
    HttpRequestInterceptor[] requestInterceptors = new HttpRequestInterceptor[] { new RequestAcceptEncoding() };
    HttpResponseInterceptor[] responseInterceptors = new HttpResponseInterceptor[] { new ResponseAllowCORS(),
            new ResponseContentEncoding(), new ResponseDate(), new ResponseServer(), new ResponseContent(),
            new ResponseConnControl() };
    HttpProcessor httpProcessor = new ImmutableHttpProcessor(requestInterceptors, responseInterceptors);

    // Create request handler registry
    HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();

    // register the handler that will reply to the proxy requests

    registry.register(path, new RequestHandler("", true));

    // Create server-side HTTP protocol handler
    HttpAsyncService protocolHandler = new HttpAsyncService(httpProcessor, new DefaultConnectionReuseStrategy(),
            registry, params);

    // Create HTTP connection factory
    NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory = new DefaultNHttpServerConnectionFactory(
            params);

    // Create server-side I/O event dispatch
    final IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory);

    try {
        // Create server-side I/O reactor
        ioReactor = new DefaultListeningIOReactor();
        // Listen of the given port

        InetSocketAddress socketAddress = new InetSocketAddress(ipaddress, 0);
        ListenerEndpoint endpoint1 = ioReactor.listen(socketAddress);

        // create the listener thread
        Thread listener = new Thread("Http listener") {

            @Override
            public void run() {
                try {
                    ioReactor.execute(ioEventDispatch);

                } catch (IOException e) {
                    //                     LOGGER.severe("I/O Exception: " + e.getMessage());
                }

            }
        };

        listener.setDaemon(false);
        listener.start();

        endpoint1.waitFor();

        if (address.contains(":")) {
            if (!address.startsWith("[")) {
                address = "[" + address + "]";
            }
        }

        address = address + ":" + Integer.toString(((InetSocketAddress) endpoint1.getAddress()).getPort())
                + "/";
        System.out.println(address);

    } catch (IOException e) {
        //            LOGGER.severe("I/O error: " + e.getMessage());
    }
}

From source file:org.apache.commons.vfs2.util.NHttpServer.java

public void runBlock(final int port, final File docRoot) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, UnrecoverableKeyException, KeyManagementException {
    if (docRoot == null) {
        throw new IllegalArgumentException("No doc root specified.");
    }//from w ww.ja v  a2  s  .  c om
    // HTTP parameters for the server
    final HttpParams params = new SyncBasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpTest/1.1");
    // Create HTTP protocol processing chain
    final HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
            // Use standard server-side protocol interceptors
            new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() });
    // Create request handler registry
    final HttpAsyncRequestHandlerRegistry reqistry = new HttpAsyncRequestHandlerRegistry();
    // Register the default handler for all URIs
    reqistry.register("*", new HttpFileHandler(docRoot));
    // Create server-side HTTP protocol handler
    final HttpAsyncService protocolHandler = new HttpAsyncService(httpproc,
            new DefaultConnectionReuseStrategy(), reqistry, params) {

        @Override
        public void closed(final NHttpServerConnection conn) {
            NHttpServer.debug(conn + ": connection closed");
            super.closed(conn);
        }

        @Override
        public void connected(final NHttpServerConnection conn) {
            NHttpServer.debug(conn + ": connection open");
            super.connected(conn);
        }

    };
    // Create HTTP connection factory
    NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
    if (port == 8443) {
        // Initialize SSL context
        final ClassLoader cl = NHttpServer.class.getClassLoader();
        final URL url = cl.getResource("my.keystore");
        if (url == null) {
            NHttpServer.debug("Keystore not found");
            System.exit(1);
        }
        final KeyStore keystore = KeyStore.getInstance("jks");
        keystore.load(url.openStream(), "secret".toCharArray());
        final KeyManagerFactory kmfactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keystore, "secret".toCharArray());
        final KeyManager[] keymanagers = kmfactory.getKeyManagers();
        final SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, null, null);
        connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, params);
    } else {
        connFactory = new DefaultNHttpServerConnectionFactory(params);
    }
    // Create server-side I/O event dispatch
    final IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory);
    // Create server-side I/O reactor
    this.ioReactor = new DefaultListeningIOReactor();
    try {
        // Listen of the given port
        this.ioReactor.listen(new InetSocketAddress(port));
        // Ready to go!
        this.ioReactor.execute(ioEventDispatch);
    } catch (final InterruptedIOException ex) {
        System.err.println("Interrupted");
    } catch (final IOException e) {
        System.err.println("I/O error: " + e.getMessage());
    }
    NHttpServer.debug("Shutdown");
}

From source file:com.bytelightning.opensource.pokerface.PokerFace.java

/**
 * Configures all the needed components, but does not actually start the server.
 * @param config   Contains all information needed to fully wire up the http, https, and httpclient components of this reverse proxy.
 * @throws Exception   Yeah, a lot can go wrong here, but at least it will be caught immediately :-)
 *//*from   w  w  w.ja  va2s  .  co m*/
public void config(HierarchicalConfiguration config) throws Exception {
    List<HierarchicalConfiguration> lconf;
    HttpAsyncRequester executor = null;
    BasicNIOConnPool connPool = null;
    ObjectPool<ByteBuffer> byteBufferPool = null;
    LinkedHashMap<String, TargetDescriptor> mappings = null;
    ConcurrentMap<String, HttpHost> hosts = null;

    handlerRegistry = new UriHttpAsyncRequestHandlerMapper();

    // Initialize the keystore (if one was specified)
    KeyStore keystore = null;
    char[] keypass = null;
    String keystoreUri = config.getString("keystore");
    if ((keystoreUri != null) && (keystoreUri.trim().length() > 0)) {
        Path keystorePath = Utils.MakePath(keystoreUri);
        if (!Files.exists(keystorePath))
            throw new ConfigurationException("Keystore does not exist.");
        if (Files.isDirectory(keystorePath))
            throw new ConfigurationException("Keystore is not a file");
        String storepass = config.getString("storepass");
        if ((storepass != null) && "null".equals(storepass))
            storepass = null;
        keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream keyStoreStream = Files.newInputStream(keystorePath)) {
            keystore.load(keyStoreStream, storepass == null ? null : storepass.trim().toCharArray());
        } catch (IOException ex) {
            Logger.error("Unable to load https server keystore from " + keystoreUri);
            return;
        }
        keypass = config.getString("keypass").trim().toCharArray();
    }

    // Wire up the listening reactor
    lconf = config.configurationsAt("server");
    if ((lconf == null) || (lconf.size() != 1))
        throw new ConfigurationException("One (and only one) server configuration element is allowed.");
    else {
        Builder builder = IOReactorConfig.custom();
        builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("server[@cpu]", 0.667)));
        builder.setSoTimeout(config.getInt("server[@soTimeout]", 0));
        builder.setSoLinger(config.getInt("server[@soLinger]", -1));
        builder.setSoReuseAddress(true);
        builder.setTcpNoDelay(false);
        builder.setSelectInterval(100);

        IOReactorConfig rconfig = builder.build();
        Logger.info("Configuring server with options: " + rconfig.toString());
        listeningReactor = new DefaultListeningIOReactor(rconfig);

        lconf = config.configurationsAt("server.listen");
        InetSocketAddress addr;
        boolean hasNonWildcardSecure = false;
        LinkedHashMap<SocketAddress, SSLContext> addrSSLContext = new LinkedHashMap<SocketAddress, SSLContext>();
        if ((lconf == null) || (lconf.size() == 0)) {
            addr = new InetSocketAddress("127.0.0.1", 8080);
            ListenerEndpoint ep = listeningReactor.listen(addr);
            Logger.warn("Configured " + ep.getAddress());
        } else {
            TrustManager[] trustManagers = null;
            KeyManagerFactory kmf = null;
            // Create all the specified listeners.
            for (HierarchicalConfiguration hc : lconf) {
                String addrStr = hc.getString("[@address]");
                if ((addrStr == null) || (addrStr.length() == 0))
                    addrStr = "0.0.0.0";
                String alias = hc.getString("[@alias]");
                int port = hc.getInt("[@port]", alias != null ? 443 : 80);
                addr = new InetSocketAddress(addrStr, port);
                ListenerEndpoint ep = listeningReactor.listen(addr);
                String protocol = hc.containsKey("[@protocol]") ? hc.getString("[@protocol]") : null;
                Boolean secure = hc.containsKey("[@secure]") ? hc.getBoolean("[@secure]") : null;
                if ((alias != null) && (secure == null))
                    secure = true;
                if ((protocol != null) && (secure == null))
                    secure = true;
                if ((secure != null) && secure) {
                    if (protocol == null)
                        protocol = "TLS";
                    if (keystore == null)
                        throw new ConfigurationException(
                                "An https listening socket was requested, but no keystore was specified.");
                    if (kmf == null) {
                        kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                        kmf.init(keystore, keypass);
                    }
                    // Are we going to trust all clients or just specific ones?
                    if (hc.getBoolean("[@trustAny]", true))
                        trustManagers = new TrustManager[] { new X509TrustAllManager() };
                    else {
                        TrustManagerFactory instance = TrustManagerFactory
                                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                        instance.init(keystore);
                        trustManagers = instance.getTrustManagers();
                    }
                    KeyManager[] keyManagers = kmf.getKeyManagers();
                    if (alias != null)
                        for (int i = 0; i < keyManagers.length; i++) {
                            if (keyManagers[i] instanceof X509ExtendedKeyManager)
                                keyManagers[i] = new PokerFaceKeyManager(alias,
                                        (X509ExtendedKeyManager) keyManagers[i]);
                        }
                    SSLContext sslCtx = SSLContext.getInstance(protocol);
                    sslCtx.init(keyManagers, trustManagers, new SecureRandom());
                    if (addr.getAddress().isAnyLocalAddress()) {
                        // This little optimization helps us respond faster for every connection as we don't have to extrapolate a local connection address to wild card.
                        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                                .hasMoreElements();) {
                            NetworkInterface intf = en.nextElement();
                            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                                    .hasMoreElements();) {
                                addr = new InetSocketAddress(enumIpAddr.nextElement(), port);
                                addrSSLContext.put(addr, sslCtx);
                            }
                        }
                    } else {
                        addrSSLContext.put(addr, sslCtx);
                        hasNonWildcardSecure = true;
                    }
                }
                Logger.warn("Configured " + (alias == null ? "" : (protocol + " on")) + ep.getAddress());
            }
        }
        // We will need an HTTP protocol processor for the incoming connections
        String serverAgent = config.getString("server.serverAgent", "PokerFace/" + Utils.Version);
        HttpProcessor inhttpproc = new ImmutableHttpProcessor(
                new HttpResponseInterceptor[] { new ResponseDateInterceptor(), new ResponseServer(serverAgent),
                        new ResponseContent(), new ResponseConnControl() });
        HttpAsyncService serviceHandler = new HttpAsyncService(inhttpproc, new DefaultConnectionReuseStrategy(),
                null, handlerRegistry, null) {
            public void exception(final NHttpServerConnection conn, final Exception cause) {
                Logger.warn(cause.getMessage());
                super.exception(conn, cause);
            }
        };
        if (addrSSLContext.size() > 0) {
            final SSLContext defaultCtx = addrSSLContext.values().iterator().next();
            final Map<SocketAddress, SSLContext> sslMap;
            if ((!hasNonWildcardSecure) || (addrSSLContext.size() == 1))
                sslMap = null;
            else
                sslMap = addrSSLContext;
            listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler,
                    new SSLNHttpServerConnectionFactory(defaultCtx, null, ConnectionConfig.DEFAULT) {
                        protected SSLIOSession createSSLIOSession(IOSession iosession, SSLContext sslcontext,
                                SSLSetupHandler sslHandler) {
                            SSLIOSession retVal;
                            SSLContext sktCtx = sslcontext;
                            if (sslMap != null) {
                                SocketAddress la = iosession.getLocalAddress();
                                if (la != null) {
                                    sktCtx = sslMap.get(la);
                                    if (sktCtx == null)
                                        sktCtx = sslcontext;
                                }
                                retVal = new SSLIOSession(iosession, SSLMode.SERVER, sktCtx, sslHandler);
                            } else
                                retVal = super.createSSLIOSession(iosession, sktCtx, sslHandler);
                            if (sktCtx != null)
                                retVal.setAttribute("com.bytelightning.opensource.pokerface.secure", true);
                            return retVal;
                        }
                    });
        } else
            listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler, ConnectionConfig.DEFAULT);
    }

    // Configure the httpclient reactor that will be used to do reverse proxing to the specified targets.
    lconf = config.configurationsAt("targets");
    if ((lconf != null) && (lconf.size() > 0)) {
        HierarchicalConfiguration conf = lconf.get(0);
        Builder builder = IOReactorConfig.custom();
        builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("targets[@cpu]", 0.667)));
        builder.setSoTimeout(conf.getInt("targets[@soTimeout]", 0));
        builder.setSoLinger(config.getInt("targets[@soLinger]", -1));
        builder.setConnectTimeout(conf.getInt("targets[@connectTimeout]", 0));
        builder.setSoReuseAddress(true);
        builder.setTcpNoDelay(false);
        connectingReactor = new DefaultConnectingIOReactor(builder.build());

        final int bufferSize = conf.getInt("targets[@bufferSize]", 1024) * 1024;
        byteBufferPool = new SoftReferenceObjectPool<ByteBuffer>(new BasePooledObjectFactory<ByteBuffer>() {
            @Override
            public ByteBuffer create() throws Exception {
                return ByteBuffer.allocateDirect(bufferSize);
            }

            @Override
            public PooledObject<ByteBuffer> wrap(ByteBuffer buffer) {
                return new DefaultPooledObject<ByteBuffer>(buffer);
            }
        });

        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;

        if (keystore != null) {
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(keystore, keypass);
            keyManagers = kmf.getKeyManagers();
        }
        // Will the httpclient's trust any remote target, or only specific ones.
        if (conf.getBoolean("targets[@trustAny]", false))
            trustManagers = new TrustManager[] { new X509TrustAllManager() };
        else if (keystore != null) {
            TrustManagerFactory instance = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            instance.init(keystore);
            trustManagers = instance.getTrustManagers();
        }
        SSLContext clientSSLContext = SSLContext.getInstance(conf.getString("targets[@protocol]", "TLS"));
        clientSSLContext.init(keyManagers, trustManagers, new SecureRandom());

        // Setup an SSL capable connection pool for the httpclients.
        connPool = new BasicNIOConnPool(connectingReactor,
                new BasicNIOConnFactory(clientSSLContext, null, ConnectionConfig.DEFAULT),
                conf.getInt("targets[@connectTimeout]", 0));
        connPool.setMaxTotal(conf.getInt("targets[@connMaxTotal]", 1023));
        connPool.setDefaultMaxPerRoute(conf.getInt("targets[@connMaxPerRoute]", 1023));

        // Set up HTTP protocol processor for outgoing connections
        String userAgent = conf.getString("targets.userAgent", "PokerFace/" + Utils.Version);
        HttpProcessor outhttpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                new RequestContent(), new RequestTargetHost(), new RequestConnControl(),
                new RequestUserAgent(userAgent), new RequestExpectContinue(true) });
        executor = new HttpAsyncRequester(outhttpproc, new DefaultConnectionReuseStrategy());

        // Now set up all the configured targets.
        mappings = new LinkedHashMap<String, TargetDescriptor>();
        hosts = new ConcurrentHashMap<String, HttpHost>();
        String[] scheme = { null };
        String[] host = { null };
        int[] port = { 0 };
        String[] path = { null };
        int[] stripPrefixCount = { 0 };
        for (HierarchicalConfiguration targetConfig : conf.configurationsAt("target")) {
            String match = targetConfig.getString("[@pattern]");
            if ((match == null) || (match.trim().length() < 1)) {
                Logger.error("Unable to configure target;  Invalid url match pattern");
                continue;
            }
            String key = RequestForTargetConsumer.UriToTargetKey(targetConfig.getString("[@url]"), scheme, host,
                    port, path, stripPrefixCount);
            if (key == null) {
                Logger.error("Unable to configure target");
                continue;
            }
            HttpHost targetHost = hosts.get(key);
            if (targetHost == null) {
                targetHost = new HttpHost(host[0], port[0], scheme[0]);
                hosts.put(key, targetHost);
            }
            TargetDescriptor desc = new TargetDescriptor(targetHost, path[0], stripPrefixCount[0]);
            mappings.put(match, desc);
        }
        connectionDispatcher = new DefaultHttpClientIODispatch(new HttpAsyncRequestExecutor(),
                ConnectionConfig.DEFAULT);
    }
    // Allocate the script map which will be populated by it's own executor thread.
    if (config.containsKey("scripts.rootDirectory")) {
        Path tmp = Utils.MakePath(config.getProperty("scripts.rootDirectory"));
        if (!Files.exists(tmp))
            throw new FileNotFoundException("Scripts directory does not exist.");
        if (!Files.isDirectory(tmp))
            throw new FileNotFoundException("'scripts' path is not a directory.");
        scripts = new ConcurrentSkipListMap<String, ScriptObjectMirror>();
        boolean watch = config.getBoolean("scripts.dynamicWatch", false);
        List<Path> jsLibs;
        Object prop = config.getProperty("scripts.library");
        if (prop != null) {
            jsLibs = new ArrayList<Path>();
            if (prop instanceof Collection<?>) {
                @SuppressWarnings("unchecked")
                Collection<Object> oprop = (Collection<Object>) prop;
                for (Object obj : oprop)
                    jsLibs.add(Utils.MakePath(obj));
            } else {
                jsLibs.add(Utils.MakePath(prop));
            }
        } else
            jsLibs = null;

        lconf = config.configurationsAt("scripts.scriptConfig");
        if (lconf != null) {
            if (lconf.size() > 1)
                throw new ConfigurationException("Only one scriptConfig element is allowed.");
            if (lconf.size() == 0)
                lconf = null;
        }

        HierarchicalConfiguration scriptConfig;
        if (lconf == null)
            scriptConfig = new HierarchicalConfiguration();
        else
            scriptConfig = lconf.get(0);
        scriptConfig.setProperty("pokerface.scripts.rootDirectory", tmp.toString());

        configureScripts(jsLibs, scriptConfig, tmp, watch);
        if (watch)
            ScriptDirectoryWatcher = new DirectoryWatchService();
    }

    // Configure the static file directory (if any)
    Path staticFilesPath = null;
    if (config.containsKey("files.rootDirectory")) {
        Path tmp = Utils.MakePath(config.getProperty("files.rootDirectory"));
        if (!Files.exists(tmp))
            throw new FileNotFoundException("Files directory does not exist.");
        if (!Files.isDirectory(tmp))
            throw new FileNotFoundException("'files' path is not a directory.");
        staticFilesPath = tmp;
        List<HierarchicalConfiguration> mimeEntries = config.configurationsAt("files.mime-entry");
        if (mimeEntries != null) {
            for (HierarchicalConfiguration entry : mimeEntries) {
                entry.setDelimiterParsingDisabled(true);
                String type = entry.getString("[@type]", "").trim();
                if (type.length() == 0)
                    throw new ConfigurationException("Invalid mime type entry");
                String extensions = entry.getString("[@extensions]", "").trim();
                if (extensions.length() == 0)
                    throw new ConfigurationException("Invalid mime extensions for: " + type);
                ScriptHelperImpl.AddMimeEntry(type, extensions);
            }
        }
    }

    handlerRegistry.register("/*",
            new RequestHandler(executor, connPool, byteBufferPool, staticFilesPath, mappings,
                    scripts != null ? Collections.unmodifiableNavigableMap(scripts) : null,
                    config.getBoolean("scripts.allowScriptsToSpecifyDynamicHosts", false) ? hosts : null));
}

From source file:org.opcfoundation.ua.transport.https.HttpsServer.java

protected void initReactor() throws ServiceResultException {
    boolean https = false, http = false;
    for (SocketHandle sh : socketHandles.values()) {
        https |= sh.scheme.equals(UriUtil.SCHEME_HTTPS);
        http |= sh.scheme.equals(UriUtil.SCHEME_HTTP);
    }/*from ww w  .  j  a v  a2s .c om*/

    try {
        if (https && sslSetupHandler == null) {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(application.getHttpsSettings().getKeyManagers(),
                    application.getHttpsSettings().getTrustManagers(), null);

            // SSL Setup Handler
            sslSetupHandler = new SSLSetupHandler() {
                public void verify(IOSession iosession, SSLSession sslsession) throws SSLException {
                }

                public void initalize(SSLEngine sslengine) throws SSLException {
                    //sslengine.setEnabledCipherSuites( calcCipherSuites() );
                }
            };

            // Create HTTP connection factory
            sslConnFactory = new SSLNHttpServerConnectionFactory(sslcontext, sslSetupHandler, getHttpParams());

            // Create server-side I/O event dispatch
            sslIoEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, sslConnFactory);

            // Create ssl engine
            sslEngine = sslcontext.createSSLEngine();
            log.info("Enabled protocols in SSL Engine are {}",
                    Arrays.toString(sslEngine.getEnabledProtocols()));
            enabledCipherSuites = sslEngine.getEnabledCipherSuites();
            log.info("Enabled CipherSuites in SSL Engine are {}", Arrays.toString(enabledCipherSuites));
        }

        if (https) {
            // Create list of cipher suites
            String[] oldCipherSuiteSelection = cipherSuites;
            cipherSuitePatterns = calcCipherSuitePatterns();
            //securityPolicies = calcSecurityPolicies().toArray( new SecurityPolicy[0] );
            cipherSuites = CryptoUtil.filterCipherSuiteList(enabledCipherSuites, cipherSuitePatterns);
            sslEngine.setEnabledCipherSuites(cipherSuites);

            if (oldCipherSuiteSelection == null || !Arrays.equals(oldCipherSuiteSelection, cipherSuites)) {
                log.info("CipherSuites for policies ({}) are {}", Arrays.toString(securityPolicies),
                        Arrays.toString(cipherSuites));
            }
        }

        if (http && plainConnFactory == null) {
            plainConnFactory = new DefaultNHttpServerConnectionFactory(getHttpParams());

            // Create server-side I/O event dispatch
            plainIoEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, plainConnFactory);
        }

        if (ioReactor == null) {
            // Create server-side I/O reactor
            ioReactor = new DefaultListeningIOReactor(ioConfig, null);
        }
    } catch (KeyManagementException e1) {
        throw new ServiceResultException(e1);
    } catch (NoSuchAlgorithmException e1) {
        throw new ServiceResultException(e1);
    } catch (IOReactorException e1) {
        throw new ServiceResultException(e1);
    }
}