Example usage for org.apache.http.impl.nio.reactor DefaultListeningIOReactor DefaultListeningIOReactor

List of usage examples for org.apache.http.impl.nio.reactor DefaultListeningIOReactor DefaultListeningIOReactor

Introduction

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

Prototype

public DefaultListeningIOReactor(int workerCount, final HttpParams params) throws IOReactorException 

Source Link

Usage

From source file:niproxy.NiProxy.java

/**
 * Setups a monitoring http proxy and starts a non blocking listening
 * service based on a {@link NiProxyConfig}. This is based on the Apache 
 * Software Foundation's example code "Basic non-blocking HTTP server" that 
 * can be found from http://hc.apache.org/httpcomponents-core-ga/examples.html. 
 *///from   www  .  j a  v a 2s  . c  om
public NiProxy() {
    HttpParams params = new SyncBasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, NiProxyConfig.getHttpConnectionTimeout())
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);

    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(),
            new ResponseServer(), new ResponseContent(), new ResponseConnControl() });

    AsyncNHttpServiceHandler handler = new AsyncNHttpServiceHandler(httpproc, new DefaultHttpResponseFactory(),
            new DefaultConnectionReuseStrategy(), params);

    // Set up request handlers
    NHttpRequestHandlerRegistry registry = new NHttpRequestHandlerRegistry();
    registry.register("*", NiProxyMonitor.get());

    handler.setHandlerResolver(registry);

    // Provide an event logger
    handler.setEventListener(new EventLogger());

    IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(handler, params);
    try {
        logger.info("Setting up " + NiProxyConfig.getIOReactorWorkersCount() + " IOReactor workers");
        ListeningIOReactor ioReactor = new DefaultListeningIOReactor(NiProxyConfig.getIOReactorWorkersCount(),
                params);
        String host = NiProxyConfig.getNiProxyHost();
        int port = NiProxyConfig.getNiProxyPort();
        logger.info("Listening for connections at " + host + ":" + port);
        ioReactor.listen(new InetSocketAddress(host, port));
        logger.info("NiProxy set up done. Launching event dispatch...");
        ioReactor.execute(ioEventDispatch);
    } catch (Exception e) {
        logger.error("I/O reactor was interrupted. Exception: " + e);
        e.printStackTrace();
    }
    logger.info("NiProxy server shutdown.");
}

From source file:com.zotoh.maedr.device.apache.HttpIO.java

protected void onStart() throws Exception {

    // mostly copied from apache http tutotial...

    HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, (int) getSocetTimeoutMills())
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) // 8k?
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "Apache-HttpCore/4.x");

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

    ConnectionReuseStrategy strategy = new DefaultConnectionReuseStrategy();
    HttpResponseFactory rspFac = new DefaultHttpResponseFactory();
    NHttpServiceHandler svc;//from w ww  .  j  a v a2s  .  c om
    EventListener evt = new EventLogger(getId(), tlog());

    if (isAsync()) {
        AsyncNHttpServiceHandler handler = new AsyncNHttpServiceHandler(httpproc, rspFac, strategy, params);
        NHttpRequestHandlerRegistry r = new NHttpRequestHandlerRegistry();
        r.register("*", new HttpNRequestCB(this));
        handler.setHandlerResolver(r);
        handler.setEventListener(evt);
        svc = handler;
    } else {
        StreamedHttpServiceHandler handler = new StreamedHttpServiceHandler(httpproc, rspFac, strategy, params);
        HttpRequestHandlerRegistry r = new HttpRequestHandlerRegistry();
        r.register("*", new HttpRequestCB(this));
        handler.setHandlerResolver(r);
        handler.setEventListener(evt);
        svc = handler;
    }

    IOEventDispatch disp = isSSL() ? onSSL(svc, params) : onBasic(svc, params);
    ListeningIOReactor ioReactor;
    ioReactor = new DefaultListeningIOReactor(getWorkers(), params);
    ioReactor.listen(new InetSocketAddress(NetUte.getNetAddr(getHost()), getPort()));
    _curIO = ioReactor;

    // start...
    runServer(disp, ioReactor);
}

From source file:org.frameworkset.spi.remote.http.HttpServer.java

private void startHttp() throws IOException {

    try {//from  w  ww  .j a va 2s .c o m
        this.ioReactor = new DefaultListeningIOReactor(workerCount, serverParams);

        EventListener serverEventListener = new EventListener() {

            // @Override
            public void connectionClosed(NHttpConnection conn) {
                // closedServerConns.decrement();
                // super.connectionClosed(conn);
                //               System.out.println("connectionClosed:" + conn);
            }

            public void connectionOpen(NHttpConnection conn) {
                //               System.out.println("connectionOpen:" + conn);

            }

            public void connectionTimeout(NHttpConnection conn) {
                System.out.println("connectionTimeout:" + conn);

            }

            public void fatalIOException(IOException ex, NHttpConnection conn) {
                //               System.out.println("fatalIOException:" + conn);
                ex.printStackTrace();
            }

            public void fatalProtocolException(HttpException ex, NHttpConnection conn) {
                //               System.out.println("fatalProtocolException:" + conn);
                ex.printStackTrace();

            }

        };

        final NHttpServiceHandler serviceHandler = createHttpServiceHandler(HttpUtil.getHttpBaseRPCIOHandler(),
                null, serverEventListener);
        this.endpoint = this.ioReactor.listen(new InetSocketAddress(ip, port));
        IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(serviceHandler, serverParams);
        //         this.execute(serviceHandler, ioEventDispatch);
        this.thread = new IOReactorThread(ioEventDispatch);
        this.thread.start();
        try {
            thread.join(1000);
            this.started = true;
        } catch (InterruptedException e) {

            e.printStackTrace();
        }

    } catch (IOReactorException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:NioHttpServer.java

public NioHttpServer(int port, // TCP port for the server.
        HttpRequestHandler request_responder, // Scheme level responder for HTTP requests from clients.
        EventListener connection_listener) throws Exception {

    HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");

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

    BufferingHttpServiceHandler service_handler = new BufferingHttpServiceHandler(httpproc,
            new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), params);

    // Set up request handlers
    HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
    reqistry.register("*", request_responder);

    service_handler.setHandlerResolver(reqistry);

    service_handler.setEventListener(connection_listener); // Provide a connection listener.

    // Use two worker threads for the IO reactor.
    io_reactor = new DefaultListeningIOReactor(2, params);
    io_event_dispatch = new DefaultServerIOEventDispatch(handler, params);
    this.port = port; // Set the listening TCP port.
}

From source file:marytts.tools.perceptiontest.PerceptionTestHttpServer.java

public void run() {
    logger.info("Starting server.");
    System.out.println("Starting server....");
    //int localPort = MaryProperties.needInteger("socket.port");
    int localPort = serverPort;

    HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0) // 0 means no timeout, any positive value means time out in miliseconds (i.e. 50000 for 50 seconds)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");

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

    BufferingHttpServiceHandler handler = new BufferingHttpServiceHandler(httpproc,
            new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), params);

    // Set up request handlers
    HttpRequestHandlerRegistry registry = new HttpRequestHandlerRegistry();
    //registry.register("/perceptionTest", new FileDataRequestHandler("perception.html"));
    //registry.register("/process", new FileDataRequestHandler("perception.html"));
    //registry.register("/perceptionTest", new UtterancePlayRequestHandler());

    DataRequestHandler infoRH = new DataRequestHandler(this.testXmlName);
    UserRatingStorer userRatingRH = new UserRatingStorer(this.userRatingsDirectory, infoRH);
    registry.register("/options", infoRH);
    registry.register("/queryStatement", infoRH);
    registry.register("/process", new UtterancePlayRequestHandler(infoRH));
    registry.register("/perceptionTest", new PerceptionRequestHandler(infoRH, userRatingRH));
    registry.register("/userRating", new StoreRatingRequestHandler(infoRH, userRatingRH));
    registry.register("*", new FileDataRequestHandler());

    handler.setHandlerResolver(registry);

    // Provide an event logger
    handler.setEventListener(new EventLogger());

    IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(handler, params);

    //int numParallelThreads = MaryProperties.getInteger("server.http.parallelthreads", 5);
    int numParallelThreads = 5;

    logger.info("Waiting for client to connect on port " + localPort);
    System.out.println("Waiting for client to connect on port " + localPort);

    try {//from  ww w.jav a2s .  c o m
        ListeningIOReactor ioReactor = new DefaultListeningIOReactor(numParallelThreads, params);
        ioReactor.listen(new InetSocketAddress(localPort));
        ioReactor.execute(ioEventDispatch);
    } catch (InterruptedIOException ex) {
        logger.info("Interrupted", ex);
        System.out.println("Interrupted" + ex.toString());
    } catch (IOException e) {
        logger.info("Problem with HTTP connection ", e);
        System.out.println("Problem with HTTP connection " + e.toString());
    }
    logger.debug("Shutdown");
    System.out.println("Shutdown");
}

From source file:org.frameworkset.spi.remote.http.HttpServer.java

private void startHttps() throws Exception {

    try {/*from   w ww.java  2s  . co  m*/
        this.ioReactor = new DefaultListeningIOReactor(workerCount, serverParams);

        EventListener serverEventListener = new EventListener() {

            // @Override
            public void connectionClosed(NHttpConnection conn) {
                // closedServerConns.decrement();
                // super.connectionClosed(conn);
                //               System.out.println("connectionClosed:" + conn);
            }

            public void connectionOpen(NHttpConnection conn) {
                //               System.out.println("connectionOpen:" + conn);

            }

            public void connectionTimeout(NHttpConnection conn) {
                System.out.println("connectionTimeout:" + conn);

            }

            public void fatalIOException(IOException ex, NHttpConnection conn) {
                //               System.out.println("fatalIOException:" + conn);
                ex.printStackTrace();
            }

            public void fatalProtocolException(HttpException ex, NHttpConnection conn) {
                //               System.out.println("fatalProtocolException:" + conn);
                ex.printStackTrace();

            }

        };

        final NHttpServiceHandler serviceHandler = createHttpServiceHandler(HttpUtil.getHttpBaseRPCIOHandler(),
                null, serverEventListener);
        this.endpoint = this.ioReactor.listen(new InetSocketAddress(ip, port));
        ProMap ssls = ApplicationContext.getApplicationContext().getMapProperty("rpc.protocol.http.ssl.server");
        if (ssls == null) {
            throw new Exception(
                    "?ssl? rpc.protocol.http.ssl.server ?org/frameworkset/spi/manager-rpc-http.xml??");
        }
        String keyStore = ssls.getString("keyStore");
        String keyStorePassword = ssls.getString("keyStorePassword");
        String trustStore = ssls.getString("trustStore");
        String trustStorePassword = ssls.getString("trustStorePassword");
        SSLContext sslcontext = SSLHelper.createSSLContext(keyStore, keyStorePassword, trustStore,
                trustStorePassword);

        IOEventDispatch ioEventDispatch = new SSLServerIOEventDispatch(serviceHandler, sslcontext,
                serverParams);
        //         IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(
        //               serviceHandler, serverParams);
        //         this.execute(serviceHandler, ioEventDispatch);
        this.thread = new IOReactorThread(ioEventDispatch);
        this.thread.start();
        try {
            thread.join(1000);
            this.started = true;
        } catch (InterruptedException e) {

            e.printStackTrace();
        }

        //         ClassLoader cl = this.getClass().getClassLoader();
        //           URL url = cl.getResource("test.keystore");
        //           KeyStore keystore  = KeyStore.getInstance("jks");
        //           keystore.load(url.openStream(), "nopassword".toCharArray());
        //           KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
        //                   KeyManagerFactory.getDefaultAlgorithm());
        //           kmfactory.init(keystore, "nopassword".toCharArray());
        //           KeyManager[] keymanagers = kmfactory.getKeyManagers(); 
        //           SSLContext sslcontext = SSLContext.getInstance("TLS");
        //           sslcontext.init(keymanagers, null, null);
        //           

        // Set up request handlers
        //           HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
        //           reqistry.register("*", new HttpFileHandler(args[0]));
        //           
        //           handler.setHandlerResolver(reqistry);
        //           
        //           // Provide an event logger
        //           handler.setEventListener(new EventLogger());
        //           
        //          
        //           
        //           ListeningIOReactor ioReactor = new DefaultListeningIOReactor(2, params);
        //           try {
        //               ioReactor.listen(new InetSocketAddress(8080));
        //               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");

    } catch (IOReactorException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.apache.synapse.transport.nhttp.HttpCoreNIOListener.java

/**
 * Initialize the transport listener, and execute reactor in new separate thread
 * @param "cfgCtx" the Axis2 configuration context
 * @param transportIn the description of the http/s transport from Axis2 configuration
 * @throws AxisFault on error/* w w w  .  j a  va  2  s.  c  o  m*/
 */
public void init(ConfigurationContext ctx, TransportInDescription transportIn) throws AxisFault {

    cfgCtx = ctx;
    Map<String, String> o = (Map<String, String>) cfgCtx.getProperty(NhttpConstants.EPR_TO_SERVICE_NAME_MAP);
    if (o != null) {
        this.eprToServiceNameMap = o;
    } else {
        eprToServiceNameMap = new HashMap<String, String>();
        cfgCtx.setProperty(NhttpConstants.EPR_TO_SERVICE_NAME_MAP, eprToServiceNameMap);
    }

    NHttpConfiguration cfg = NHttpConfiguration.getInstance();

    // Initialize connection factory
    params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
            cfg.getProperty(NhttpConstants.SO_TIMEOUT_RECEIVER, 60000))
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE,
                    cfg.getProperty(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024))
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "Synapse-HttpComponents-NIO");
    //                .setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET,
    //                        cfg.getStringValue(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, HTTP.DEFAULT_PROTOCOL_CHARSET)); //TODO:This does not works with HTTPCore 4.3

    name = transportIn.getName().toUpperCase(Locale.US) + " Listener";
    scheme = initScheme();

    // Setup listener context
    listenerContext = new ListenerContextBuilder(transportIn).parse().build();

    System.setProperty(transportIn.getName() + ".nio.port", String.valueOf(listenerContext.getPort()));

    // Setup connection factory
    HttpHost host = new HttpHost(listenerContext.getHostname(), listenerContext.getPort(), scheme.getName());
    connFactory = initConnFactoryBuilder(transportIn, host).build(params);

    // configure the IO reactor on the specified port
    try {
        String prefix = name + " I/O dispatcher";
        IOReactorConfig ioReactorConfig = new IOReactorConfig();
        ioReactorConfig.setIoThreadCount(cfg.getServerIOWorkers());
        ioReactorConfig.setSoTimeout(cfg.getProperty(NhttpConstants.SO_TIMEOUT_RECEIVER, 60000));
        ioReactorConfig.setTcpNoDelay(cfg.getProperty(CoreConnectionPNames.TCP_NODELAY, 1) == 1);
        if (cfg.getBooleanValue("http.nio.interest-ops-queueing", false)) {
            ioReactorConfig.setInterestOpQueued(true);
        }
        ioReactorConfig.setSoReuseAddress(cfg.getBooleanValue(CoreConnectionPNames.SO_REUSEADDR, false));

        ioReactor = new DefaultListeningIOReactor(ioReactorConfig,
                new NativeThreadFactory(new ThreadGroup(prefix + " thread group"), prefix));

        ioReactor.setExceptionHandler(new IOReactorExceptionHandler() {
            public boolean handle(IOException ioException) {
                log.warn("System may be unstable: IOReactor encountered a checked exception : "
                        + ioException.getMessage(), ioException);
                return true;
            }

            public boolean handle(RuntimeException runtimeException) {
                log.warn("System may be unstable: IOReactor encountered a runtime exception : "
                        + runtimeException.getMessage(), runtimeException);
                return true;
            }
        });
    } catch (IOException e) {
        handleException("Error creating IOReactor", e);
    }

    metrics = new NhttpMetricsCollector(true, transportIn.getName());

    handler = new ServerHandler(cfgCtx, scheme, listenerContext, metrics);
    iodispatch = new ServerIODispatch(handler, connFactory);

    Parameter param = transportIn.getParameter(NhttpConstants.WSDL_EPR_PREFIX);
    if (param != null) {
        serviceEPRPrefix = getServiceEPRPrefix(cfgCtx, (String) param.getValue());
        customEPRPrefix = (String) param.getValue();
        EPRPrefixCheck = false;
    } else {
        serviceEPRPrefix = getServiceEPRPrefix(cfgCtx, listenerContext.getHostname(),
                listenerContext.getPort());
        customEPRPrefix = scheme.getName() + "://" + listenerContext.getHostname() + ":"
                + (listenerContext.getPort() == scheme.getDefaultPort() ? "" : listenerContext.getPort()) + "/";
    }

    // register to receive updates on services for lifetime management
    cfgCtx.getAxisConfiguration().addObservers(axisObserver);

    // register with JMX
    mbeanSupport = new TransportMBeanSupport(this, "nio-" + transportIn.getName());
    mbeanSupport.register();
}

From source file:marytts.server.http.MaryHttpServer.java

public void run() {
    logger.info("Starting server.");

    int localPort = MaryProperties.needInteger("socket.port");

    HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0) // 0 means no timeout, any positive value means time out in miliseconds (i.e. 50000 for 50 seconds)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");

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

    BufferingHttpServiceHandler handler = new BufferingHttpServiceHandler(httpproc,
            new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), params);

    // Set up request handlers
    HttpRequestHandlerRegistry registry = new HttpRequestHandlerRegistry();
    registry.register("/process", new SynthesisRequestHandler());
    InfoRequestHandler infoRH = new InfoRequestHandler();
    registry.register("/version", infoRH);
    registry.register("/datatypes", infoRH);
    registry.register("/locales", infoRH);
    registry.register("/voices", infoRH);
    registry.register("/audioformats", infoRH);
    registry.register("/exampletext", infoRH);
    registry.register("/audioeffects", infoRH);
    registry.register("/audioeffect-default-param", infoRH);
    registry.register("/audioeffect-full", infoRH);
    registry.register("/audioeffect-help", infoRH);
    registry.register("/audioeffect-is-hmm-effect", infoRH);
    registry.register("/features", infoRH);
    registry.register("/features-discrete", infoRH);
    registry.register("/vocalizations", infoRH);
    registry.register("/styles", infoRH);
    registry.register("*", new FileRequestHandler());

    handler.setHandlerResolver(registry);

    // Provide an event logger
    handler.setEventListener(new EventLogger());

    IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(handler, params);

    int numParallelThreads = MaryProperties.getInteger("server.http.parallelthreads", 5);

    logger.info("Waiting for client to connect on port " + localPort);

    try {//from   ww w.j  a va 2s . co m
        ListeningIOReactor ioReactor = new DefaultListeningIOReactor(numParallelThreads, params);
        ioReactor.listen(new InetSocketAddress(localPort));
        isReady = true;
        ioReactor.execute(ioEventDispatch);
    } catch (InterruptedIOException ex) {
        logger.info("Interrupted", ex);
    } catch (IOException e) {
        logger.info("Problem with HTTP connection", e);
    }
    logger.debug("Shutdown");
}

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   w w w.  j a  v a2  s .  co  m*/

    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);
    }
}