Example usage for org.apache.http.params CoreConnectionPNames TCP_NODELAY

List of usage examples for org.apache.http.params CoreConnectionPNames TCP_NODELAY

Introduction

In this page you can find the example usage for org.apache.http.params CoreConnectionPNames TCP_NODELAY.

Prototype

String TCP_NODELAY

To view the source code for org.apache.http.params CoreConnectionPNames TCP_NODELAY.

Click Source Link

Usage

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

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

    address = ipaddress;//from   ww  w .  ja  v a2 s.  c o  m
    // 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.camel.itest.http.HttpTestServer.java

/**
 * Obtains a set of reasonable default parameters for a server.
 *
 * @return  default parameters/*from  w  ww .j av  a  2s .co  m*/
 */
protected HttpParams newDefaultParams() {
    HttpParams params = new SyncBasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "LocalTestServer/1.1");
    return params;
}

From source file:com.mfizz.observer.core.ServiceObserver.java

public ServiceObserver(ServiceObserverConfiguration serviceConfig, ExecutorService executor, Class<D> dataClass,
        Class<A> aggregateClass, Class<S> summaryClass, ContentParser<D> contentParser,
        ObserverNamingStrategy ons) {/*  w w w. java  2  s.c  o  m*/
    this.serviceConfig = serviceConfig;
    this.executor = executor;
    this.observers = new ConcurrentHashMap<String, Observer<D>>();
    this.dataClass = dataClass;
    this.aggregateClass = aggregateClass;
    this.summaryClass = summaryClass;
    this.contentParser = contentParser;
    if (ons == null) {
        this.ons = ObserverNamingStrategy.DEFAULT;
    } else {
        this.ons = ons;
    }
    this.snapshotAllTimer = Metrics.newTimer(
            new MetricName("com.mfizz.observer.ServiceObservers", serviceConfig.getName(), "snapshot-all-time"),
            TimeUnit.MILLISECONDS, TimeUnit.MILLISECONDS);
    this.snapshotAllAttemptedCounter = new AtomicLong();
    this.snapshotAllCompletedCounter = new AtomicLong();
    this.lastSnapshotAllResult = new AtomicReference<SnapshotAllResult>();

    //this.lastSnapshotAllTimestamp = new AtomicLong(0);
    //this.lastSnapshotsCompletedCounter = new AtomicInteger();
    //this.lastSnapshotsFailedCounter = new AtomicInteger();

    this.groups = new TreeSet<String>();
    this.summary = new ConcurrentHashMap<String, SummaryGroup<S>>();
    this.snapshots = new ConcurrentHashMap<String, TimeSeries<ObserveAggregateSnapshot<A>>>();

    // always make sure "current" is added to set of vars to track
    // "current" always tracked for all
    this.serviceConfig.getPeriods().add(SummaryPeriod.parse("current"));

    //
    // create high performance http client that can be reused by all observers
    //
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    // increase max total connection to 200
    cm.setMaxTotal(200);
    // increase default max connection per route to 20
    cm.setDefaultMaxPerRoute(20);

    this.httpclient = new DefaultHttpClient(cm);
    this.httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            // always return false -- we never want a request retried
            return false;
        }
    });
    this.httpclient.getParams()
            .setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
                    new Integer((int) serviceConfig.getSocketTimeout()))
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                    new Integer((int) serviceConfig.getConnectionTimeout()))
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
}

From source file:org.apache.http.localserver.LocalTestServer.java

/**
 * Obtains a set of reasonable default parameters for a server.
 *
 * @return  default parameters//from  w  w  w . ja  v a  2 s .  co  m
 */
protected HttpParams newDefaultParams() {
    HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "org.apache.http.localserver.LocalTestServer/1.1");
    return params;
}

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   w w  w . j  a v  a  2s.  com*/
        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.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/*from  w  w  w . jav a2 s  . com*/
 */
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: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.");
    }//  w  w w.j a  v  a2 s .c o m
    // 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:net.facework.core.http.TinyHttpServer.java

@Override
public void onCreate() {

    super.onCreate();

    mContext = getApplicationContext();/*w  ww. j  a  va2  s. c o  m*/
    mRegistry = new MHttpRequestHandlerRegistry();
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    mParams = new BasicHttpParams();
    mParams.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, "MajorKernelPanic HTTP Server");

    // Set up the HTTP protocol processor
    mHttpProcessor = new BasicHttpProcessor();
    mHttpProcessor.addInterceptor(new ResponseDate());
    mHttpProcessor.addInterceptor(new ResponseServer());
    mHttpProcessor.addInterceptor(new ResponseContent());
    mHttpProcessor.addInterceptor(new ResponseConnControl());

    // Will be used in the "Last-Modifed" entity-header field
    try {
        String packageName = mContext.getPackageName();
        mLastModified = new Date(mContext.getPackageManager().getPackageInfo(packageName, 0).lastUpdateTime);
    } catch (NameNotFoundException e) {
        mLastModified = new Date(0);
    }

    // Let's restore the state of the service 
    mHttpPort = Integer.parseInt(mSharedPreferences.getString(mHttpPortKey, String.valueOf(mHttpPort)));
    mHttpsPort = Integer.parseInt(mSharedPreferences.getString(mHttpsPortKey, String.valueOf(mHttpsPort)));
    mHttpEnabled = mSharedPreferences.getBoolean(mHttpEnabledKey, mHttpEnabled);
    mHttpsEnabled = mSharedPreferences.getBoolean(mHttpsEnabledKey, mHttpsEnabled);

    // If the configuration is modified, the server will adjust
    mSharedPreferences.registerOnSharedPreferenceChangeListener(mOnSharedPreferenceChangeListener);

    // Loads plugins available in the package net.majorkernelpanic.http
    for (int i = 0; i < MODULES.length; i++) {
        try {
            Class<?> pluginClass = Class
                    .forName(TinyHttpServer.class.getPackage().getName() + "." + MODULES[i]);
            Constructor<?> pluginConstructor = pluginClass.getConstructor(new Class[] { TinyHttpServer.class });
            addRequestHandler((String) pluginClass.getField("PATTERN").get(null),
                    (HttpRequestHandler) pluginConstructor.newInstance(this));
        } catch (ClassNotFoundException ignore) {
            // Module disabled
        } catch (Exception e) {
            Log.e(TAG, "Bad module: " + MODULES[i]);
            e.printStackTrace();
        }
    }

    start();

}

From source file:com.google.apphosting.vmruntime.VmApiProxyDelegate.java

/**
 * Create an HTTP post request suitable for sending to the API server.
 *
 * @param environment The current VMApiProxyEnvironment
 * @param packageName The API call package
 * @param methodName The API call method
 * @param requestData The POST payload./*  w ww . ja  va  2s  .co  m*/
 * @param timeoutMs The timeout for this request
 * @return an HttpPost object to send to the API.
 */
// 
static HttpPost createRequest(VmApiProxyEnvironment environment, String packageName, String methodName,
        byte[] requestData, int timeoutMs) {
    // Wrap the payload in a RemoteApi Request.
    RemoteApiPb.Request remoteRequest = new RemoteApiPb.Request();
    remoteRequest.setServiceName(packageName);
    remoteRequest.setMethod(methodName);
    remoteRequest.setRequestId(environment.getTicket());
    remoteRequest.setRequestAsBytes(requestData);

    HttpPost request = new HttpPost("http://" + environment.getServer() + REQUEST_ENDPOINT);
    request.setHeader(RPC_STUB_ID_HEADER, REQUEST_STUB_ID);
    request.setHeader(RPC_METHOD_HEADER, REQUEST_STUB_METHOD);

    // Set TCP connection timeouts.
    HttpParams params = new BasicHttpParams();
    params.setLongParameter(ConnManagerPNames.TIMEOUT, timeoutMs + ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS);
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
            timeoutMs + ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS);
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeoutMs + ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS);

    // Performance tweaks.
    params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, Boolean.TRUE);
    params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, Boolean.FALSE);
    request.setParams(params);

    // The request deadline can be overwritten by the environment, read deadline if available.
    Double deadline = (Double) (environment.getAttributes().get(API_DEADLINE_KEY));
    if (deadline == null) {
        request.setHeader(RPC_DEADLINE_HEADER,
                Double.toString(TimeUnit.SECONDS.convert(timeoutMs, TimeUnit.MILLISECONDS)));
    } else {
        request.setHeader(RPC_DEADLINE_HEADER, Double.toString(deadline));
    }

    // If the incoming request has a dapper trace header: set it on outgoing API calls
    // so they are tied to the original request.
    Object dapperHeader = environment.getAttributes()
            .get(VmApiProxyEnvironment.AttributeMapping.DAPPER_ID.attributeKey);
    if (dapperHeader instanceof String) {
        request.setHeader(VmApiProxyEnvironment.AttributeMapping.DAPPER_ID.headerKey, (String) dapperHeader);
    }

    // If the incoming request has a Cloud trace header: set it on outgoing API calls
    // so they are tied to the original request.
    // TODO(user): For now, this uses the incoming span id - use the one from the active span.
    Object traceHeader = environment.getAttributes()
            .get(VmApiProxyEnvironment.AttributeMapping.CLOUD_TRACE_CONTEXT.attributeKey);
    if (traceHeader instanceof String) {
        request.setHeader(VmApiProxyEnvironment.AttributeMapping.CLOUD_TRACE_CONTEXT.headerKey,
                (String) traceHeader);
    }

    ByteArrayEntity postPayload = new ByteArrayEntity(remoteRequest.toByteArray(),
            ContentType.APPLICATION_OCTET_STREAM);
    postPayload.setChunked(false);
    request.setEntity(postPayload);

    return request;
}