Example usage for org.apache.http.protocol HTTP TARGET_HOST

List of usage examples for org.apache.http.protocol HTTP TARGET_HOST

Introduction

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

Prototype

String TARGET_HOST

To view the source code for org.apache.http.protocol HTTP TARGET_HOST.

Click Source Link

Usage

From source file:org.openremote.container.web.ProxyWebClientBuilder.java

@SuppressWarnings("deprecation")
@Override/*from  w  w  w .j  av  a 2 s. co m*/
protected ClientHttpEngine initDefaultEngine() {
    ApacheHttpClient4Engine engine = (ApacheHttpClient4Engine) super.initDefaultEngine();
    DefaultHttpClient httpClient = (DefaultHttpClient) engine.getHttpClient();
    httpClient.addRequestInterceptor((request, context) -> request.setHeader(HTTP.TARGET_HOST,
            new HttpHost(proxyHost, proxyPort).toHostString()));
    return engine;
}

From source file:com.subgraph.vega.internal.http.proxy.UriRequestCreator.java

private String requestHostHeaderValue(HttpRequest request) {
    final Header hostHeader = request.getFirstHeader(HTTP.TARGET_HOST);
    if (hostHeader == null) {
        return null;
    }//from w w  w  .  j  av a 2 s  .  c om

    final String hostValue = hostHeader.getValue();
    return (hostValue == null || hostValue.isEmpty()) ? (null) : (hostValue);
}

From source file:org.apache.stratos.mediator.autoscale.lbautoscale.mediators.AutoscaleInMediator.java

public boolean mediate(MessageContext synCtx) {

    if (log.isDebugEnabled()) {
        log.debug("Mediation started .......... " + AutoscaleInMediator.class.getName());

    }//from w w w  . jav a 2s  .c om

    ConfigurationContext configCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext()
            .getConfigurationContext();
    String uuid = org.apache.axiom.util.UIDGenerator.generateUID();
    synCtx.setProperty(AutoscaleConstants.REQUEST_ID, uuid);

    Map<String, Map<String, ?>> appDomainContexts = AutoscaleUtil.getAppDomainContexts(configCtx, lbConfig);
    org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) synCtx)
            .getAxis2MessageContext();
    Map<String, String> transportHeaders = (Map<String, String>) axis2MessageContext
            .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    String targetHost = transportHeaders.get(HTTP.TARGET_HOST);

    String toAddress = synCtx.getTo().getAddress();
    if (targetHost.contains(":")) {
        targetHost = targetHost.substring(0, targetHost.indexOf(':'));
    }

    int tenantId = AutoscaleUtil.getTenantId(synCtx.getTo().toString());

    String domain = null, subDomain = null;

    log.debug("************ Target Host: " + targetHost + " -- Tenant id : " + tenantId);

    HostContext ctxt = hostCtxts.get(targetHost);

    if (ctxt == null) {

        DomainMapping domainMapping = mappingCache.getMapping(targetHost);
        if (domainMapping == null) {
            registryManager = new RegistryManager();
            domainMapping = registryManager.getMapping(targetHost);
            mappingCache.addValidMapping(targetHost, domainMapping);
        }
        if (domainMapping != null) {

            String actualHost = domainMapping.getActualHost();

            // get the HostContext from the actual host name in the case of domain 
            // mapping.
            ctxt = hostCtxts.get(actualHost);

        }
    }

    if (ctxt == null) {
        log.debug("Host Context is null.");
        // we don't need to do anything 
        return true;
    }

    // gets the corresponding domain
    domain = ctxt.getDomainFromTenantId(tenantId);
    synCtx.setProperty(AutoscaleConstants.TARGET_DOMAIN, domain);

    // gets the corresponding sub domain
    subDomain = ctxt.getSubDomainFromTenantId(tenantId);
    synCtx.setProperty(AutoscaleConstants.TARGET_SUB_DOMAIN, subDomain);

    if (appDomainContexts.get(domain) == null) {
        // if we do not find a correct context, we just ignore
        log.debug("AppDomainContext not found for domain " + domain);

    } else {
        AppDomainContext appDomainContext = (AppDomainContext) appDomainContexts.get(domain).get(subDomain);

        if (appDomainContext != null) {
            appDomainContext.addRequestToken(uuid);
            System.setProperty(AutoscaleConstants.IS_TOUCHED, "true");

        } else {
            // if we do not find a correct context, we just ignore
            log.debug("AppDomainContext not found for sub domain: " + subDomain + " of domain: " + domain);
        }
    }

    return true;
}

From source file:com.subgraph.vega.internal.http.proxy.VegaHttpRequestParser.java

@Override
public HttpMessage parse() throws IOException, HttpException {
    RequestLine requestLine;//from ww  w.  java 2  s  . c  om
    try {
        requestLine = parseRequestLine(sessionBuffer);
    } catch (ParseException px) {
        throw new ProtocolException(px.getMessage(), px);
    }

    List<CharArrayBuffer> headerLines = new ArrayList<CharArrayBuffer>();
    Header[] headers = AbstractMessageParser.parseHeaders(sessionBuffer, maxHeaderCount, maxLineLen, lineParser,
            headerLines);

    if (conn.isSslConnection()) {
        URI uri;
        try {
            uri = new URI(requestLine.getUri());
        } catch (URISyntaxException e) {
            throw new ProtocolException("Invalid URI: " + requestLine.getUri(), e);
        }
        if (uri.getScheme() == null) {
            final Header hostHeader = getFirstHeader(headers, HTTP.TARGET_HOST);
            final StringBuilder buf = new StringBuilder();
            if (hostHeader != null) {
                // REVISIT: does using the Host header value instead of the SSL host risk opening another connection?
                buf.append("https://");
                buf.append(hostHeader.getValue());
            } else {
                buf.append(conn.getSslHost().toURI());
            }
            buf.append(uri.getRawPath());
            if (uri.getRawQuery() != null) {
                buf.append("?");
                buf.append(uri.getRawQuery());
            }

            requestLine = new BasicRequestLine(requestLine.getMethod(), buf.toString(),
                    requestLine.getProtocolVersion());
        }
    }

    HttpMessage message = requestFactory.newHttpRequest(requestLine);
    message.setHeaders(headers);
    return message;
}

From source file:org.peterbaldwin.vlcremote.sweep.Worker.java

@Override
public void run() {
    // Note: InetAddress#isReachable(int) always returns false for Windows
    // hosts because applications do not have permission to perform ICMP
    // echo requests.
    for (;;) {//from ww  w  .ja va2 s  .  co m
        byte[] ipAddress = mManager.pollIpAddress();
        if (ipAddress == null) {
            break;
        }
        try {
            InetAddress address = InetAddress.getByAddress(ipAddress);
            String hostAddress = address.getHostAddress();
            URL url = createUrl("http", hostAddress, mPort, mPath);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(1000);
            try {
                int responseCode = connection.getResponseCode();
                String responseMessage = connection.getResponseMessage();
                InputStream inputStream = (responseCode == HttpURLConnection.HTTP_OK)
                        ? connection.getInputStream()
                        : connection.getErrorStream();
                if (inputStream != null) {
                    try {
                        int length = connection.getContentLength();
                        InputStreamEntity entity = new InputStreamEntity(inputStream, length);
                        entity.setContentType(connection.getContentType());

                        // Copy the entire response body into memory
                        // before the HTTP connection is closed:
                        String body = EntityUtils.toString(entity);

                        ProtocolVersion version = new ProtocolVersion("HTTP", 1, 1);
                        String hostname = address.getHostName();
                        StatusLine statusLine = new BasicStatusLine(version, responseCode, responseMessage);
                        HttpResponse response = new BasicHttpResponse(statusLine);
                        response.setHeader(HTTP.TARGET_HOST, hostname + ":" + mPort);
                        response.setEntity(new StringEntity(body));
                        mCallback.onReachable(ipAddress, response);
                    } finally {
                        inputStream.close();
                    }
                } else {
                    Log.w(TAG, "InputStream is null");
                }
            } finally {
                connection.disconnect();
            }
        } catch (IOException e) {
            mCallback.onUnreachable(ipAddress, e);
        }
    }
}

From source file:org.apache.synapse.rest.APIDispatcherTest.java

public void testHostBasedAPIDispatch() throws Exception {
    API api = new API(TEST_API, "/test");
    api.setHost("synapse.apache.org");
    SynapseConfiguration synapseConfig = new SynapseConfiguration();
    synapseConfig.addAPI(TEST_API, api);

    RESTRequestHandler handler = new RESTRequestHandler();

    // Messages that don't have the proper host set should not be dispatched
    MessageContext synCtx = getMessageContext(synapseConfig, false, "/test", "GET");
    handler.process(synCtx);//  ww  w.ja v  a2 s .c  o  m
    assertNull(synCtx.getProperty(RESTConstants.SYNAPSE_REST_API));

    // Messages with the correct host should be dispatched
    synCtx = getMessageContext(synapseConfig, false, "/test/", "GET");
    addHttpHeader(HTTP.TARGET_HOST, "synapse.apache.org", synCtx);
    handler.process(synCtx);
    assertEquals(TEST_API, synCtx.getProperty(RESTConstants.SYNAPSE_REST_API));

    // API should be able to infer the default HTTP port
    api.setPort(80);
    handler.process(synCtx);
    assertEquals(TEST_API, synCtx.getProperty(RESTConstants.SYNAPSE_REST_API));

    // Messages with an incorrect port number should not be dispatched
    synCtx = getMessageContext(synapseConfig, false, "/test/foo/bar?a=5", "GET");
    addHttpHeader(HTTP.TARGET_HOST, "synapse.apache.org:8280", synCtx);
    handler.process(synCtx);
    assertNull(synCtx.getProperty(RESTConstants.SYNAPSE_REST_API));

    // Messages with the correct port number should be dispatched
    api.setPort(8280);
    handler.process(synCtx);
    assertEquals(TEST_API, synCtx.getProperty(RESTConstants.SYNAPSE_REST_API));

    api.setPort(443);
    synCtx = getMessageContext(synapseConfig, false, "/test/foo/bar?a=5", "GET");
    addHttpHeader(HTTP.TARGET_HOST, "synapse.apache.org", synCtx);
    handler.process(synCtx);
    assertNull(synCtx.getProperty(RESTConstants.SYNAPSE_REST_API));

    // API should accurately infer the default HTTPS port
    synCtx = getMessageContext(synapseConfig, true, "/test/foo/bar?a=5", "GET");
    addHttpHeader(HTTP.TARGET_HOST, "synapse.apache.org", synCtx);
    handler.process(synCtx);
    assertEquals(TEST_API, synCtx.getProperty(RESTConstants.SYNAPSE_REST_API));
}

From source file:net.oneandone.sushi.fs.webdav.WebdavRoot.java

public void send(WebdavConnection conn, HttpRequest request) throws IOException {
    // TODO: side effect
    request.addHeader(HTTP.TARGET_HOST, host.getHostName());
    if (authorization != null) {
        request.addHeader("Authorization", authorization);
    }//from w w w  .  j  a  v  a  2  s  .com
    // TODO: request.addHeader("Keep-Alive", "300");

    try {
        conn.sendRequestHeader(request);
        if (request instanceof HttpEntityEnclosingRequest) {
            conn.sendRequestEntity((HttpEntityEnclosingRequest) request);
        }
        conn.flush();
    } catch (IOException e) {
        free(null, conn);
        throw e;
    } catch (HttpException e) {
        free(null, conn);
        // TODO
        throw new IOException(e);
    } catch (RuntimeException e) {
        free(null, conn);
        throw e;
    }
}

From source file:net.kungfoo.grizzly.proxy.impl.ConnectingHandler.java

private static void requestReadyCleanUpHeaders(final HttpRequest request) {
    request.removeHeaders(HTTP.CONTENT_LEN);
    request.removeHeaders(HTTP.TRANSFER_ENCODING);
    request.removeHeaders(HTTP.CONN_DIRECTIVE);
    request.removeHeaders("Keep-Alive");
    request.removeHeaders("Proxy-Authenticate");
    request.removeHeaders("Proxy-Authorization");
    request.removeHeaders("TE");
    request.removeHeaders("Trailers");
    request.removeHeaders("Upgrade");
    // Remove host header
    request.removeHeaders(HTTP.TARGET_HOST);
}

From source file:com.flipkart.phantom.http.impl.HttpConnectionPool.java

/**
 * This method sets the headers to the http request base. This implementation adds the custom headers configured on this pool and subsequently adds
 * the headers that came with the specified Http request if {@link HttpConnectionPool#isForwardHeaders()} is set to 'true' and in this case sets the
 * {@link HTTP#TARGET_HOST} to the the value <HttpConnectionPool{@link #getHost()}:HttpConnectionPool{@link #getPort()}. Sub-types may override this method
 * to change this behavior./*from ww  w . j a  v  a 2  s .c om*/
 *
 * @param request {@link HttpRequestBase} to add headers to.
 * @param requestHeaders the List of header tuples which are added to the request
 */
protected void setRequestHeaders(HttpRequestBase request, List<Map.Entry<String, String>> requestHeaders) {
    if (this.headers != null && this.headers.isEmpty()) {
        for (String headerKey : this.headers.keySet()) {
            request.addHeader(headerKey, this.headers.get(headerKey));
        }
    }
    if (this.isForwardHeaders()) { // forward request headers only if specified

        if (requestHeaders != null && !requestHeaders.isEmpty()) {
            for (Map.Entry<String, String> headerMap : requestHeaders) {
                if (!HttpConnectionPool.REMOVE_HEADERS.contains(headerMap.getKey())) {
                    request.addHeader(headerMap.getKey(), headerMap.getValue());
                }
            }
        }
        // replace "Host" header with the that of the real target host
        request.setHeader(HTTP.TARGET_HOST, this.getHost() + ":" + this.getPort());
    }
}

From source file:org.apache.synapse.rest.APIDispatcherTest.java

public void testMultipleAPIDispatch() throws Exception {
    String apiName1 = "TestAPI1";
    String apiName2 = "TestAPI2";
    String apiName3 = "TestAPI3";

    API api1 = new API(apiName1, "/test");
    API api2 = new API(apiName2, "/dictionary");
    api2.setHost("synapse.apache.org");
    API api3 = new API(apiName3, "/foo/bar");

    SynapseConfiguration synapseConfig = new SynapseConfiguration();
    synapseConfig.addAPI(apiName1, api1);
    synapseConfig.addAPI(apiName2, api2);
    synapseConfig.addAPI(apiName3, api3);

    RESTRequestHandler handler = new RESTRequestHandler();
    MessageContext synCtx = getMessageContext(synapseConfig, false, "/test", "GET");
    handler.process(synCtx);/*ww  w  . j a  v a2  s.c o m*/
    assertEquals(apiName1, synCtx.getProperty(RESTConstants.SYNAPSE_REST_API));

    synCtx = getMessageContext(synapseConfig, false, "/dictionary/c/cat", "GET");
    addHttpHeader(HTTP.TARGET_HOST, "synapse.apache.org", synCtx);
    handler.process(synCtx);
    assertEquals(apiName2, synCtx.getProperty(RESTConstants.SYNAPSE_REST_API));

    synCtx = getMessageContext(synapseConfig, false, "/foo/bar/index.jsp?user=test", "GET");
    handler.process(synCtx);
    assertEquals(apiName3, synCtx.getProperty(RESTConstants.SYNAPSE_REST_API));

    synCtx = getMessageContext(synapseConfig, false, "/foo/index.jsp?user=test", "GET");
    handler.process(synCtx);
    assertNull(synCtx.getProperty(RESTConstants.SYNAPSE_REST_API));
}