Example usage for org.apache.http.protocol RequestUserAgent RequestUserAgent

List of usage examples for org.apache.http.protocol RequestUserAgent RequestUserAgent

Introduction

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

Prototype

public RequestUserAgent(String str) 

Source Link

Usage

From source file:com.alexjalg.gson_google.EjecutarHttpClient.java

public static void main(String[] args) throws Exception {
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new RequestContent())
            .add(new RequestTargetHost()).add(new RequestConnControl()).add(new RequestUserAgent("Test/1.1"))
            .add(new RequestExpectContinue(true)).build();

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpCoreContext coreContext = HttpCoreContext.create();
    HttpHost host = new HttpHost("jsonplaceholder.typicode.com", 80);
    coreContext.setTargetHost(host);/*from   w  ww.ja va2 s  .c om*/

    DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
    ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;

    try {
        String[] targets = { "/posts" };
        for (int i = 0; i < targets.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket);
            }
            BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            httpexecutor.preProcess(request, httpproc, coreContext);
            HttpResponse response = httpexecutor.execute(request, conn, coreContext);
            httpexecutor.postProcess(response, httpproc, coreContext);

            System.out.println("<< Response: " + response.getStatusLine());

            //                System.out.println(EntityUtils.toString(response.getEntity()));
            String json = EntityUtils.toString(response.getEntity());

            ArrayList<Posts> listPosts = new ArrayList<Posts>();
            Type listType = new TypeToken<ArrayList<Posts>>() {
            }.getType();
            listPosts = new Gson().fromJson(json, listType);

            for (Posts post : listPosts) {
                System.out.println("");
                System.out.println(post.getUserId());
                System.out.println(post.getId());
                System.out.println(post.getTitle());
                System.out.println(post.getBody());
            }

            System.out.println("==============");
            if (!connStrategy.keepAlive(response, coreContext)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }
}

From source file:cn.heroes.ud.protocol.ElementalHttpGet.java

public static void main(String[] args) throws Exception {
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new RequestContent())
            .add(new RequestTargetHost()).add(new RequestConnControl()).add(new RequestUserAgent("Test/1.1"))
            .add(new RequestExpectContinue(true)).build();

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpCoreContext coreContext = HttpCoreContext.create();
    HttpHost host = new HttpHost("localhost", 8080);
    coreContext.setTargetHost(host);/*from w  ww  .j  a v  a  2s .  co  m*/

    DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
    ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;

    try {

        String[] targets = { "/", "/servlets-examples/servlet/RequestInfoExample", "/somewhere%20in%20pampa" };

        for (int i = 0; i < targets.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket);
            }
            BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            httpexecutor.preProcess(request, httpproc, coreContext);
            HttpResponse response = httpexecutor.execute(request, conn, coreContext);
            httpexecutor.postProcess(response, httpproc, coreContext);

            System.out.println("<< Response: " + response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
            if (!connStrategy.keepAlive(response, coreContext)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }
}

From source file:com.yulore.demo.NHttpClient.java

public static void main(String[] args) throws Exception {
    // Create HTTP protocol processing chain
    HttpProcessor httpproc = HttpProcessorBuilder.create()
            // Use standard client-side protocol interceptors
            .add(new RequestContent()).add(new RequestTargetHost()).add(new RequestConnControl())
            .add(new RequestUserAgent("Test/1.1")).add(new RequestExpectContinue(true)).build();
    // Create client-side HTTP protocol handler
    HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor();
    // Create client-side I/O event dispatch
    final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler,
            ConnectionConfig.DEFAULT);//from  w w w .ja  v  a  2 s  . c  om
    // Create client-side I/O reactor
    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
    // Create HTTP connection pool
    BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, ConnectionConfig.DEFAULT);
    // Limit total number of connections to just two
    pool.setDefaultMaxPerRoute(2);
    pool.setMaxTotal(2);
    // Run the I/O reactor in a separate thread
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                // 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");
        }

    });
    // Start the client thread
    t.start();
    // Create HTTP requester
    HttpAsyncRequester requester = new HttpAsyncRequester(httpproc);
    // Execute HTTP GETs to the following hosts and
    HttpHost[] targets = new HttpHost[] { new HttpHost("www.apache.org", 80, "http"),
            new HttpHost("www.verisign.com", 443, "https"), new HttpHost("www.google.com", 80, "http") };
    final CountDownLatch latch = new CountDownLatch(targets.length);
    for (final HttpHost target : targets) {
        BasicHttpRequest request = new BasicHttpRequest("GET", "/");
        HttpCoreContext coreContext = HttpCoreContext.create();
        requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(),
                pool, coreContext,
                // Handle HTTP response from a callback
                new FutureCallback<HttpResponse>() {

                    public void completed(final HttpResponse response) {
                        latch.countDown();
                        System.out.println(target + "->" + response.getStatusLine());
                    }

                    public void failed(final Exception ex) {
                        latch.countDown();
                        System.out.println(target + "->" + ex);
                    }

                    public void cancelled() {
                        latch.countDown();
                        System.out.println(target + " cancelled");
                    }

                });
    }
    latch.await();
    System.out.println("Shutting down I/O reactor");
    ioReactor.shutdown();
    System.out.println("Done");

}

From source file:framework.httpclient.nio.NHttpClient.java

public static void main(String[] args) throws Exception {
    // Create HTTP protocol processing chain
    HttpProcessor httpproc = HttpProcessorBuilder.create()
            // Use standard client-side protocol interceptors
            .add(new RequestContent()).add(new RequestTargetHost()).add(new RequestConnControl())
            .add(new RequestUserAgent("LinkedHashSetVsTreeSet/1.1")).add(new RequestExpectContinue(true))
            .build();//from  w w w . j a  v a 2s.  co  m

    // Create client-side HTTP protocol handler
    HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor();

    // Create client-side I/O event dispatch
    //   IO 
    final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler,
            ConnectionConfig.DEFAULT);

    // Create client-side I/O reactor
    //   IO reactor
    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();

    // Create HTTP connection pool
    //  HTTP 
    BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, ConnectionConfig.DEFAULT);

    // Limit total number of connections to just two
    pool.setDefaultMaxPerRoute(2);
    pool.setMaxTotal(2);

    // Run the I/O reactor in a separate thread
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                // 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");
        }

    });
    // Start the client thread
    t.start();

    // Create HTTP requester
    //  HTTP 
    HttpAsyncRequester requester = new HttpAsyncRequester(httpproc);

    // Execute HTTP GETs to the following hosts and
    HttpHost[] targets = new HttpHost[] { new HttpHost("www.baidu.org", -1, "https"),
            //            new HttpHost("www.zhihu.com", -1, "https"),
            new HttpHost("www.bilibili.com", -1, "https") };

    final CountDownLatch latch = new CountDownLatch(targets.length);

    for (final HttpHost target : targets) {
        BasicHttpRequest request = new BasicHttpRequest("GET", "/");
        HttpCoreContext coreContext = HttpCoreContext.create();
        requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(),
                pool, coreContext,
                // Handle HTTP response from a callback
                new FutureCallback<HttpResponse>() {

                    public void completed(final HttpResponse response) {
                        latch.countDown();
                        System.out.println(target + "->" + response.getStatusLine());
                    }

                    public void failed(final Exception ex) {
                        latch.countDown();
                        System.err.println(target + "->" + ex);
                        ex.printStackTrace();
                    }

                    public void cancelled() {
                        latch.countDown();
                        System.out.println(target + " cancelled");
                    }

                });
    }
    latch.await();
    System.out.println("Shutting down I/O reactor");
    ioReactor.shutdown();
    System.out.println("Done");
}

From source file:proxy.ElementalHttpGet.java

public static void main(String[] args) throws Exception {
    //      String localIp = args[0];
    //      System.out.println("localIp: " + localIp);
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new RequestContent())
            .add(new RequestTargetHost()).add(new RequestConnControl()).add(new RequestUserAgent("Test/1.1"))
            .add(new RequestExpectContinue(true)).build();

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpCoreContext coreContext = HttpCoreContext.create();
    HttpHost host = new HttpHost("api.weibo.com", 443, "https");
    coreContext.setTargetHost(host);/*w w  w.ja  v a  2s  .  c  o m*/
    //      for (InetAddress localinetAddress : getAllIp("eth0")) {
    //         System.out.println(localinetAddress.getHostAddress());
    request(httpproc, httpexecutor, coreContext, host, InetAddress.getByName("60.169.74.152"));
    //      }

}

From source file:com.oracle.jes.samples.hellostorage.HttpElementPost.java

public void putData2() throws Exception {
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new RequestContent())
            .add(new RequestTargetHost()).add(new RequestConnControl()).add(new RequestUserAgent("Test/1.1"))
            .add(new RequestExpectContinue(true)).build();

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpCoreContext coreContext = HttpCoreContext.create();
    HttpHost host = new HttpHost("192.168.1.5", 8080);
    coreContext.setTargetHost(host);//from   www. j a v a  2 s .  co m

    DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
    ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;

    try {

        HttpEntity[] requestBodies = {
                new StringEntity("This is the first test request",
                        ContentType.create("text/plain", Consts.UTF_8)),
                new ByteArrayEntity("This is the second test request".getBytes("UTF-8"),
                        ContentType.APPLICATION_OCTET_STREAM),
                new InputStreamEntity(
                        new ByteArrayInputStream(
                                "This is the third test request (will be chunked)".getBytes("UTF-8")),
                        ContentType.APPLICATION_OCTET_STREAM) };

        for (int i = 0; i < requestBodies.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket);
            }

            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
                    "/servlets-examples/servlet/RequestInfoExample");

            request.setEntity(requestBodies[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            httpexecutor.preProcess(request, httpproc, coreContext);
            HttpResponse response = httpexecutor.execute(request, conn, coreContext);
            httpexecutor.postProcess(response, httpproc, coreContext);

            System.out.println("<< Response: " + response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
            if (!connStrategy.keepAlive(response, coreContext)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }
}

From source file:com.cxic.ip.WebUrl.java

public String getResponseStr() {
    String userAgentCopy = VersionInfo.getUserAgent("Apache-HttpClient", "org.apache.http.client", getClass());

    HttpProcessor httpprocessorCopy = null;
    if (httpprocessorCopy == null) {
        final HttpProcessorBuilder b = HttpProcessorBuilder.create();
        b.addAll(new RequestDefaultHeaders(null), new RequestContent(), new RequestTargetHost(),
                //                    new RequestClientConnControl(),
                new RequestUserAgent(userAgentCopy), new RequestExpectContinue());
        b.add(new RequestAddCookies());
        b.add(new RequestAcceptEncoding());
        b.add(new RequestAuthCache());
        b.add(new ResponseProcessCookies());
        b.add(new ResponseContentEncoding());
        httpprocessorCopy = b.build();/*from   w w  w.j  a  v  a  2 s  .  c  om*/
    }

    HttpHost proxy = new HttpHost(ip, port, "http");
    //      DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
    CloseableHttpClient httpclient = HttpClients.custom()
            //              .setRoutePlanner(routePlanner)
            .setProxy(proxy).setHttpProcessor(httpprocessorCopy).build();

    String r = "";
    HttpGet httpGet = new HttpGet(url);

    //      httpGet.setHeader("GET http://www.stilllistener.com/checkpoint1/test2/ HTTP/1.1","");
    //      httpGet.setHeader("Host","www.stilllistener.com");
    //      httpGet.setHeader("User-Agent","Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) Gecko/20100101 Firefox/41.0");
    //      httpGet.setHeader("User-Agent","Baiduspider+(+http://www.baidu.com/search/spider.htm)");
    //      httpGet.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    //      httpGet.setHeader("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
    //      httpGet.setHeader("Accept-Encoding","gzip, deflate");
    //      httpGet.setHeader("Referer",url);
    //      httpGet.setHeader("Connection","keep-alive");
    //      httpGet.setHeader("Cache-Control","max-age=0");

    CloseableHttpResponse response1 = null;
    try {
        response1 = httpclient.execute(httpGet);
        HttpEntity entity1 = response1.getEntity();
        String line = response1.getStatusLine().getReasonPhrase();
        //         System.out.println(line);
        if (line.equals("OK")) {
            r = EntityUtils.toString(entity1);
            //            System.out.println(r);
            // do something useful with the response body
            // and ensure it is fully consumed
            //             InputStream in = entity1.getContent();
            //             System.out.println(EntityUtils.toString(entity1,"GB2312"));
            //System.out.println(in.toString());
        }
        // do something useful with the response body
        // and ensure it is fully consumed
        //          InputStream in = entity1.getContent();
        //          System.out.println(EntityUtils.toString(entity1,"GB2312"));
        //System.out.println(in.toString());

        //System.out.println(EntityUtils.toString(entity1));
        EntityUtils.consume(entity1);
        response1.close();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return r;
}

From source file:us.pserver.revok.channel.HttpRequestChannel.java

/**
 * Init some objects for http communication.
 *///from w ww . j ava 2s.co m
private void init() {
    algo = CryptAlgorithm.AES_CBC_PKCS5;
    context = HttpCoreContext.create();
    context.setTargetHost(
            new HttpHost((netc.getAddress() == null ? "localhost" : netc.getAddress()), netc.getPort()));
    processor = HttpProcessorBuilder.create().add(new RequestContent()).add(new RequestTargetHost())
            .add(new RequestUserAgent(HttpConsts.HD_VAL_USER_AGENT)).add(new RequestConnControl()).build();
}

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.j  a v a2s .  c o  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.apache.http.impl.execchain.MinimalClientExec.java

public MinimalClientExec(final HttpRequestExecutor requestExecutor,
        final HttpClientConnectionManager connManager, final ConnectionReuseStrategy reuseStrategy,
        final ConnectionKeepAliveStrategy keepAliveStrategy) {
    Args.notNull(requestExecutor, "HTTP request executor");
    Args.notNull(connManager, "Client connection manager");
    Args.notNull(reuseStrategy, "Connection reuse strategy");
    Args.notNull(keepAliveStrategy, "Connection keep alive strategy");
    this.httpProcessor = new ImmutableHttpProcessor(new RequestContent(), new RequestTargetHost(),
            new RequestClientConnControl(), new RequestUserAgent(
                    VersionInfo.getUserAgent("Apache-HttpClient", "org.apache.http.client", getClass())));
    this.requestExecutor = requestExecutor;
    this.connManager = connManager;
    this.reuseStrategy = reuseStrategy;
    this.keepAliveStrategy = keepAliveStrategy;
}