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.apache.stratos.lb.endpoint.endpoint.TenantAwareLoadBalanceEndpoint.java

public void send(MessageContext synCtx) {
    /*   setCookieHeader(synCtx);     */
    Member currentMember = null;/*w ww .j  a  va  2s .co m*/
    SessionInformation sessionInformation = null;
    String actualHost = null;

    //Gathering required information for domain mapping
    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 port = "";
    boolean containsPort = false;
    if (targetHost.contains(":")) {
        containsPort = true;
        port = targetHost.substring(targetHost.indexOf(':') + 1, targetHost.length());
        targetHost = targetHost.substring(0, targetHost.indexOf(':'));
    }
    //Gathering required information for domain mapping done

    boolean isValidHost = tlbMembershipHandler.isAValidHostName(targetHost);
    DomainMapping domainMapping = null;
    if (!isValidHost) {
        //check if the host is valid, if not valid, execute following code to check whether it is a mapped domain
        domainMapping = mappingCache.getMapping(targetHost);
        if (domainMapping == null) {
            registryManager = new RegistryManager();
            domainMapping = registryManager.getMapping(targetHost);
            mappingCache.addValidMapping(targetHost, domainMapping);
        }
        if (domainMapping != null) {
            actualHost = domainMapping.getActualHost();

            if (containsPort) {
                transportHeaders.put(HTTP.TARGET_HOST, actualHost + ":" + port);
            } else {
                transportHeaders.put(HTTP.TARGET_HOST, actualHost);
            }
            ((Axis2MessageContext) synCtx).getAxis2MessageContext().setProperty("TRANSPORT_HEADERS",
                    transportHeaders);

        } else {
            String msg = "Invalid host name : " + targetHost;
            log.error(msg);
            throw new SynapseException(msg);
        }
    }

    if (isSessionAffinityBasedLB()) {
        // first check if this session is associated with a session. if so, get the endpoint
        // associated for that session.
        sessionInformation = (SessionInformation) synCtx
                .getProperty(SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION);

        currentMember = (Member) synCtx.getProperty(SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_MEMBER);

        if (sessionInformation == null && currentMember == null) {
            sessionInformation = dispatcher.getSession(synCtx);
            if (sessionInformation != null) {

                if (log.isDebugEnabled()) {
                    log.debug("Current session id : " + sessionInformation.getId());
                }

                currentMember = sessionInformation.getMember();
                synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_MEMBER, currentMember);
                // This is for reliably recovery any session information if while response is getting ,
                // session information has been removed by cleaner.
                // This will not be a cost as  session information a not heavy data structure
                synCtx.setProperty(SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION, sessionInformation);
            }
        }

    }

    // Dispatch request the relevant member
    //        String targetHost = getTargetHost(synCtx);
    ConfigurationContext configCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext()
            .getConfigurationContext();

    if (tlbMembershipHandler.getConfigurationContext() == null) {
        tlbMembershipHandler.setConfigurationContext(configCtx);
    }

    if (tlbMembershipHandler.getClusteringAgent() == null) {
        tlbMembershipHandler.setConfigurationContext(configCtx);
    }

    TenantDynamicLoadBalanceFaultHandlerImpl faultHandler = new TenantDynamicLoadBalanceFaultHandlerImpl();
    log.debug("************* Actual Host: " + actualHost + " ****** Target Host: " + targetHost);
    faultHandler.setHost(actualHost != null ? actualHost : targetHost);

    if (sessionInformation != null && currentMember != null) {
        //send message on current session
        sessionInformation.updateExpiryTime();
        sendToApplicationMember(synCtx, currentMember, faultHandler, false);
    } else {
        //            prepare for a new session
        int tenantId = getTenantId(synCtx);
        //check if this is a valid host name registered in ELB
        if (tlbMembershipHandler.isAValidHostName(targetHost)) {
            currentMember = tlbMembershipHandler.getNextApplicationMember(targetHost, tenantId);
            if (currentMember == null) {
                String msg = "No application members available";
                log.error(msg);
                throw new SynapseException(msg);
            }
            sendToApplicationMember(synCtx, currentMember, faultHandler, true);
        } else {
            if (domainMapping == null) {
                registryManager = new RegistryManager();
                domainMapping = registryManager.getMapping(targetHost);
                mappingCache.addValidMapping(targetHost, domainMapping);
            }
            if (domainMapping != null) {

                actualHost = domainMapping.getActualHost();

                log.debug("************* Actual Host: " + actualHost + " ****** Target Host: " + targetHost);
                faultHandler.setHost(actualHost != null ? actualHost : targetHost);

                if (containsPort) {
                    transportHeaders.put(HTTP.TARGET_HOST, actualHost + ":" + port);
                } else {
                    transportHeaders.put(HTTP.TARGET_HOST, actualHost);
                }
                ((Axis2MessageContext) synCtx).getAxis2MessageContext().setProperty("TRANSPORT_HEADERS",
                        transportHeaders);

                currentMember = tlbMembershipHandler.getNextApplicationMember(actualHost, tenantId);
                sendToApplicationMember(synCtx, currentMember, faultHandler, true);
            } else {
                String msg = "Invalid host name : " + targetHost;
                log.error(msg);
                throw new SynapseException(msg);
            }
        }
    }
}

From source file:org.opennms.core.web.HttpClientWrapper.java

protected HttpClientWrapper() {
    m_cookieStore = new BasicCookieStore();
    // According to the HTTP specification, adding the default ports to the host header is optional.
    // If the default ports are added, several Web Servers like Microsoft IIS 7.5 will complain about it, and could lead to unwanted results.
    addRequestInterceptor(new HttpRequestInterceptor() {
        @Override/* w  ww.  ja  v a  2s .  com*/
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            Header host = request.getFirstHeader(HTTP.TARGET_HOST);
            if (host != null) {
                if (host.getValue().endsWith(":80") || host.getValue().endsWith(":443")) {
                    request.setHeader(HTTP.TARGET_HOST, host.getValue().replaceFirst(":\\d+", ""));
                    LOG.info("httpRequestInterceptor: removing default port from host header");
                }
            }
        }
    });
}

From source file:org.opennms.core.web.HttpClientWrapper.java

/**
 * Execute the given HTTP method, returning an HTTP response.
 * /*from   ww w. j  av a 2s.  c  om*/
 * Note that when you are done with the response, you must call {@link #closeResponse()} so that it gets cleaned up properly.
 */
public CloseableHttpResponse execute(final HttpUriRequest method) throws ClientProtocolException, IOException {
    LOG.debug("execute: " + this.toString() + "; method: " + method.toString());
    // override some headers with our versions
    final HttpRequestWrapper requestWrapper = HttpRequestWrapper.wrap(method);
    if (!isEmpty(m_userAgent)) {
        requestWrapper.setHeader(HTTP.USER_AGENT, m_userAgent);
    }
    if (!isEmpty(m_virtualHost)) {
        requestWrapper.setHeader(HTTP.TARGET_HOST, m_virtualHost);
    }

    if (m_version != null) {
        if (HttpVersion.HTTP_1_1.equals(m_version) && isEmpty(m_virtualHost)) {
            // NMS-7506, set HTTP version to 1.0 if virtual host is not set (since 1.1 requires a virtual host)
            requestWrapper.setProtocolVersion(HttpVersion.HTTP_1_0);
        } else {
            requestWrapper.setProtocolVersion(m_version);
        }
    }

    return getClient().execute(requestWrapper);
}

From source file:org.opennms.netmgt.collectd.HttpCollector.java

private static HttpRequestBase buildHttpMethod(final HttpCollectionSet collectionSet)
        throws URISyntaxException {
    HttpRequestBase method;/*from   www  .j ava 2s.co  m*/
    URI uri = buildUri(collectionSet);
    if ("GET".equals(collectionSet.getUriDef().getUrl().getMethod())) {
        method = buildGetMethod(uri, collectionSet);
    } else {
        method = buildPostMethod(uri, collectionSet);
    }

    final String virtualHost = collectionSet.getUriDef().getUrl().getVirtualHost();
    if (virtualHost != null && !virtualHost.trim().isEmpty()) {
        method.setHeader(HTTP.TARGET_HOST, virtualHost);
    }
    return method;
}

From source file:org.opennms.netmgt.ncs.northbounder.NCSNorthbounder.java

private void postAlarms(HttpEntity entity) {
    //Need a configuration bean for these

    int connectionTimeout = 3000;
    int socketTimeout = 3000;
    Integer retryCount = 3;/*from  www  .ja  va  2 s.  c om*/

    HttpVersion httpVersion = determineHttpVersion(m_config.getHttpVersion());

    URI uri = m_config.getURI();
    System.err.println("uri = " + uri);

    final HttpClientWrapper clientWrapper = HttpClientWrapper.create().setSocketTimeout(socketTimeout)
            .setConnectionTimeout(connectionTimeout).setRetries(retryCount).useBrowserCompatibleCookies()
            .dontReuseConnections();

    if ("https".equals(uri.getScheme())) {
        try {
            clientWrapper.useRelaxedSSL("https");
        } catch (final GeneralSecurityException e) {
            throw new NorthbounderException("Failed to configure Relaxed SSL handling.", e);
        }
    }

    final HttpEntityEnclosingRequestBase method = m_config.getMethod().getRequestMethod(uri);

    if (m_config.getVirtualHost() != null && !m_config.getVirtualHost().trim().isEmpty()) {
        method.setHeader(HTTP.TARGET_HOST, m_config.getVirtualHost());
    }
    if (m_config.getUserAgent() != null && !m_config.getUserAgent().trim().isEmpty()) {
        method.setHeader(HTTP.USER_AGENT, m_config.getUserAgent());
    }
    method.setProtocolVersion(httpVersion);
    method.setEntity(entity);

    CloseableHttpResponse response = null;
    try {
        System.err.println("execute: " + method);
        response = clientWrapper.execute(method);
    } catch (ClientProtocolException e) {
        throw new NorthbounderException(e);
    } catch (IOException e) {
        throw new NorthbounderException(e);
    } finally {
        IOUtils.closeQuietly(clientWrapper);
    }

    if (response != null) {
        try {
            int code = response.getStatusLine().getStatusCode();
            final HttpResponseRange range = new HttpResponseRange("200-399");
            if (!range.contains(code)) {
                LOG.warn("response code out of range for uri: {}.  Expected {} but received {}", uri, range,
                        code);
                throw new NorthbounderException("response code out of range for uri:" + uri + ".  Expected "
                        + range + " but received " + code);
            }
        } finally {
            IOUtils.closeQuietly(clientWrapper);
        }
    }

    LOG.debug(response != null ? response.getStatusLine().getReasonPhrase() : "Response was null");
}