Example usage for org.apache.http.nio.protocol HttpAsyncService HttpAsyncService

List of usage examples for org.apache.http.nio.protocol HttpAsyncService HttpAsyncService

Introduction

In this page you can find the example usage for org.apache.http.nio.protocol HttpAsyncService HttpAsyncService.

Prototype

@Deprecated
public HttpAsyncService(final HttpProcessor httpProcessor, final ConnectionReuseStrategy connStrategy,
        final HttpAsyncRequestHandlerResolver handlerResolver, final HttpParams params) 

Source Link

Document

Creates new instance of <tt>HttpAsyncServerProtocolHandler</tt>.

Usage

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);//ww  w  .j  a  v  a  2 s  . c om
    }
    // 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: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) {//from   w  w w. j  a va 2 s .  co  m

        @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 w ww.j av  a2s .  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;/*  www  .  j av a  2 s.  com*/
    // 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.opcfoundation.ua.transport.https.HttpsServer.java

public HttpsServer(Application application) throws ServiceResultException {
    super(CloseableObjectState.Closed, CloseableObjectState.Closed);

    this.application = application;
    this.ioConfig = new IOReactorConfig();
    this.securityPolicies = application.getHttpsSettings().getHttpsSecurityPolicies();

    // Disable Nagle's
    ioConfig.setTcpNoDelay(false);/*w  ww . j  ava 2  s.  c  o m*/

    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
            // Use standard server-side protocol interceptors
            new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() });
    // Create request handler registry
    registry = new RequestResolver();
    // Register the default handler for all URIs
    final Map<NHttpServerConnection, HttpsServerConnection> connMap = Collections
            .synchronizedMap(new HashMap<NHttpServerConnection, HttpsServerConnection>());
    // Create connection re-use strategy
    connectionReuseStrategy = new DefaultConnectionReuseStrategy();

    // Create server-side HTTP protocol handler
    protocolHandler = new HttpAsyncService(httpproc, connectionReuseStrategy, registry, getHttpParams()) {

        @Override
        public void connected(final NHttpServerConnection conn) {
            NHttpConnectionBase conn2 = (NHttpConnectionBase) conn;
            log.info("connected: {} {}<-> {} context={} socketTimeout={}",
                    HttpsServer.this.getBoundSocketAddresses(), conn2.getLocalAddress(),
                    conn2.getRemoteAddress(), conn2.getContext(), conn2.getSocketTimeout());
            HttpsServerConnection httpsConnection = new HttpsServerConnection(HttpsServer.this, conn);
            connMap.put(conn, httpsConnection);
            connections.addConnection(httpsConnection);
            super.connected(conn);
        }

        @Override
        public void closed(final NHttpServerConnection conn) {
            NHttpConnectionBase conn2 = (NHttpConnectionBase) conn;
            log.info("closed: {} {}<-> {} context={} socketTimeout={}",
                    HttpsServer.this.getBoundSocketAddresses(), conn2.getLocalAddress(),
                    conn2.getRemoteAddress(), conn2.getContext(), conn2.getSocketTimeout());
            HttpsServerConnection conn3 = connMap.remove(conn);
            connections.removeConnection(conn3);
            super.closed(conn);
        }

    };

    // Create a service server for connections that query endpoints (url = "")
    discoveryServer = new Server(application);
    discoveryServer.setEndpointBindings(endpointBindings);
    EndpointBinding discoveryBinding = new EndpointBinding(this, discoveryEndpoint, discoveryServer);
    discoveryHandler = new HttpsServerEndpointHandler(discoveryBinding);
}

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  va2s  .  com
    // 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");
}