Java Code Examples for org.apache.http.client.utils.URIUtils#extractHost()

The following examples show how to use org.apache.http.client.utils.URIUtils#extractHost() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AsyncInternalClient.java    From fc-java-sdk with MIT License 6 votes vote down vote up
protected <Res> void asyncSend(HttpRequest request, AbstractResponseConsumer<Res> consumer, FutureCallback<Res> callback,
                               String contentType, HttpMethod method, boolean httpInvoke)
        throws ClientException {
    try{
        // try refresh credentials if CredentialProvider set
        config.refreshCredentials();

        // Add all needed headers
        if (!httpInvoke
                || !ANONYMOUS.equals(((HttpInvokeFunctionRequest) request).getAuthType())) {
            FcUtil.signRequest(config, request, contentType, method, httpInvoke);
        }

        // Construct HttpRequest
        PrepareUrl prepareUrl = FcUtil.prepareUrl(request.getPath(), request.getQueryParams(), this.config);
        RequestBuilder requestBuilder = RequestBuilder.create(method.name())
                .setUri(prepareUrl.getUrl());
        copyToRequest(request, requestBuilder);
        HttpUriRequest httpRequest = requestBuilder.build();

        HttpHost httpHost = URIUtils.extractHost(httpRequest.getURI());
        httpClient.execute(new FcRequestProducer(httpHost, httpRequest), consumer, callback);
    } catch (Exception e) {
        throw new ClientException(e);
    }
}
 
Example 2
Source File: OTSUri.java    From aliyun-tablestore-java-sdk with Apache License 2.0 6 votes vote down vote up
public OTSUri(String endpoint, String action) {
    this.action = action;

    final String delimiter = "/";
    if (!endpoint.endsWith(delimiter)) {
        endpoint += delimiter;
    }

    // keep only one '/' in the end
    int index = endpoint.length() - 1;
    while (index > 0 && endpoint.charAt(index - 1) == '/') {
        index--;
    }

    endpoint = endpoint.substring(0, index + 1);

    try {
        this.uri = new URI(endpoint + action);
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("The endpoint is invalid.", e);
    }

    this.host = URIUtils.extractHost(uri);
}
 
Example 3
Source File: FormatClientSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
protected CloseableHttpResponse execute(final HttpUriRequest request, String username, String password)
    throws IOException
{
  log.debug("Authorizing request for {} using credentials provided for username: {}",
      request.getURI(), username);
  CredentialsProvider credsProvider = new BasicCredentialsProvider();
  credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

  HttpHost host = URIUtils.extractHost(request.getURI());

  AuthCache authCache = new BasicAuthCache();
  authCache.put(host, new BasicScheme());

  HttpClientContext clientContext = new HttpClientContext(httpClientContext);
  clientContext.setAuthCache(authCache);
  clientContext.setCredentialsProvider(credsProvider);

  return execute(request, clientContext);
}
 
Example 4
Source File: FormatClientSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
protected CloseableHttpResponse execute(final HttpUriRequest request, String username, String password)
    throws IOException
{
  log.debug("Authorizing request for {} using credentials provided for username: {}",
      request.getURI(), username);
  CredentialsProvider credsProvider = new BasicCredentialsProvider();
  credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

  HttpHost host = URIUtils.extractHost(request.getURI());

  AuthCache authCache = new BasicAuthCache();
  authCache.put(host, new BasicScheme());

  HttpClientContext clientContext = new HttpClientContext(httpClientContext);
  clientContext.setAuthCache(authCache);
  clientContext.setCredentialsProvider(credsProvider);

  return execute(request, clientContext);
}
 
Example 5
Source File: PentahoParameterRefreshHandler.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * HttpClient does not support preemptive authentication out of the box, because if misused or used incorrectly the
 * preemptive authentication can lead to significant security issues, such as sending user credentials in clear text
 * to an unauthorized third party. Therefore, users are expected to evaluate potential benefits of preemptive
 * authentication versus security risks in the context of their specific application environment.
 *
 * Nonetheless one can configure HttpClient to authenticate preemptively by prepopulating the authentication data cache.
 *
 * @see https://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html
 *
 * @param target target URI
 * @param auth login data
 * @return
 */
private HttpClientContext buildPreemptiveAuthRequestContext( final URI target, final AuthenticationData auth ) {

  if ( target == null || auth == null || StringUtils.isEmpty( auth.getUsername() ) ) {
    return null; // nothing to do here; if no credentials were passed, there's no need to create a preemptive auth Context
  }

  HttpHost targetHost = URIUtils.extractHost( target );

  CredentialsProvider credsProvider = new BasicCredentialsProvider();
  credsProvider.setCredentials( new AuthScope( targetHost.getHostName(), targetHost.getPort() ),
      new UsernamePasswordCredentials( auth.getUsername(), auth.getPassword() ) );

  // Create AuthCache instance
  AuthCache authCache = new BasicAuthCache();

  // Generate BASIC scheme object and add it to the local auth cache
  BasicScheme basicAuth = new BasicScheme();
  authCache.put( targetHost, basicAuth );

  HttpClientContext context = HttpClientContext.create();
  context.setCredentialsProvider( credsProvider );
  context.setAuthCache( authCache );

  return context;
}
 
Example 6
Source File: GridUtility.java    From Selenium-Foundation with Apache License 2.0 5 votes vote down vote up
/**
 * Extract HTTP host object from the specified URL.
 * 
 * @param url {@link URL} from which to extract HTTP host
 * @return {@link HttpHost} object
 */
public static HttpHost extractHost(URL url) {
    if (url != null) {
        try {
            return URIUtils.extractHost(url.toURI());
        } catch (URISyntaxException e) {
            throw UncheckedThrow.throwUnchecked(e);
        }
    }
    return null;
}
 
Example 7
Source File: TracedHttpClient.java    From aws-xray-sdk-java with Apache License 2.0 5 votes vote down vote up
public static HttpHost determineTarget(final HttpUriRequest request) throws ClientProtocolException {
    // A null target may be acceptable if there is a default target.
    // Otherwise, the null target is detected in the director.
    HttpHost target = null;

    final URI requestUri = request.getURI();
    if (requestUri.isAbsolute()) {
        target = URIUtils.extractHost(requestUri);
        if (target == null) {
            throw new ClientProtocolException("URI does not specify a valid host name: "
                    + requestUri);
        }
    }
    return target;
}
 
Example 8
Source File: MCRHttpUtils.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public static HttpHost getHttpHost(String serverUrl) {
    HttpHost host = null;
    //determine host name
    HttpGet serverGet = new HttpGet(serverUrl);
    final URI requestURI = serverGet.getURI();
    if (requestURI.isAbsolute()) {
        host = URIUtils.extractHost(requestURI);
    }
    return host;
}
 
Example 9
Source File: ApacheCloudStackClient.java    From apache-cloudstack-java-client with Apache License 2.0 5 votes vote down vote up
/**
 *  It configures the cookie domain with the domain of the Apache CloudStack that is being accessed.
 *  The domain is extracted from {@link #url} variable.
 */
protected void configureDomainForCookie(BasicClientCookie cookie) {
    try {
        HttpHost httpHost = URIUtils.extractHost(new URI(url));
        String domain = httpHost.getHostName();
        cookie.setDomain(domain);
    } catch (URISyntaxException e) {
        throw new ApacheCloudStackClientRuntimeException(e);
    }
}
 
Example 10
Source File: ApiProxyServlet.java    From onboard with Apache License 2.0 5 votes vote down vote up
protected void initTarget() throws ServletException {
    targetUri = getConfigParam(P_TARGET_URI);
    if (targetUri == null)
        throw new ServletException(P_TARGET_URI + " is required.");
    // test it's valid
    try {
        targetUriObj = new URI(targetUri);
    } catch (Exception e) {
        throw new ServletException("Trying to process targetUri init parameter: " + e, e);
    }
    targetHost = URIUtils.extractHost(targetUriObj);
}
 
Example 11
Source File: ProxyServlet.java    From aem-solr-search with Apache License 2.0 5 votes vote down vote up
/** Copy request headers from the servlet client to the proxy request. */
protected void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest) {
    // Get an Enumeration of all of the header names sent by the client
    Enumeration enumerationOfHeaderNames = servletRequest.getHeaderNames();
    while (enumerationOfHeaderNames.hasMoreElements()) {
        String headerName = (String) enumerationOfHeaderNames.nextElement();
        //Instead the content-length is effectively set via InputStreamEntity
        if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH))
            continue;
        if (hopByHopHeaders.containsHeader(headerName))
            continue;

        Enumeration headers = servletRequest.getHeaders(headerName);
        while (headers.hasMoreElements()) {//sometimes more than one value
            String headerValue = (String) headers.nextElement();
            // In case the proxy host is running multiple virtual servers,
            // rewrite the Host header to ensure that we get content from
            // the correct virtual server
            if (headerName.equalsIgnoreCase(HttpHeaders.HOST)) {
                HttpHost host = URIUtils.extractHost(this.targetUri);
                headerValue = host.getHostName();
                if (host.getPort() != -1)
                    headerValue += ":"+host.getPort();
            }
            proxyRequest.addHeader(headerName, headerValue);
        }
    }
}
 
Example 12
Source File: NFHttpClient.java    From ribbon with Apache License 2.0 5 votes vote down vote up
private static HttpHost determineTarget(HttpUriRequest request) throws ClientProtocolException {
	// A null target may be acceptable if there is a default target.
	// Otherwise, the null target is detected in the director.
	HttpHost target = null;
	URI requestURI = request.getURI();
	if (requestURI.isAbsolute()) {
		target = URIUtils.extractHost(requestURI);
		if (target == null) {
			throw new ClientProtocolException(
					"URI does not specify a valid host name: " + requestURI);
		}
	}
	return target;
}
 
Example 13
Source File: PrerenderSeoService.java    From prerender-java with MIT License 5 votes vote down vote up
/**
 * Copy request headers from the servlet client to the proxy request.
 *
 * @throws java.net.URISyntaxException
 */
private void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest)
        throws URISyntaxException {
    // Get an Enumeration of all of the header names sent by the client
    Enumeration<?> enumerationOfHeaderNames = servletRequest.getHeaderNames();
    while (enumerationOfHeaderNames.hasMoreElements()) {
        String headerName = (String) enumerationOfHeaderNames.nextElement();
        //Instead the content-length is effectively set via InputStreamEntity
        if (!headerName.equalsIgnoreCase(CONTENT_LENGTH) && !hopByHopHeaders.containsHeader(headerName)) {
            Enumeration<?> headers = servletRequest.getHeaders(headerName);
            while (headers.hasMoreElements()) {//sometimes more than one value
                String headerValue = (String) headers.nextElement();
                // In case the proxy host is running multiple virtual servers,
                // rewrite the Host header to ensure that we get content from
                // the correct virtual server
                if (headerName.equalsIgnoreCase(HOST)) {
                    HttpHost host = URIUtils.extractHost(new URI(prerenderConfig.getPrerenderServiceUrl()));
                    headerValue = host.getHostName();
                    if (host.getPort() != -1) {
                        headerValue += ":" + host.getPort();
                    }
                }
                proxyRequest.addHeader(headerName, headerValue);
            }
        }
    }
}
 
Example 14
Source File: AgpClient.java    From geoportal-server-harvester with Apache License 2.0 4 votes vote down vote up
private String execute(HttpUriRequest req, Integer redirectDepth) throws IOException {
  // Determine if we've reached the limit of redirection attempts
  if (redirectDepth > this.maxRedirects) {
    throw new HttpResponseException(HttpStatus.SC_GONE, "Too many redirects, aborting");
  }

  try (CloseableHttpResponse httpResponse = httpClient.execute(req); InputStream contentStream = httpResponse.getEntity().getContent();) {
    if (httpResponse.getStatusLine().getStatusCode()>=400) {
      throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
    } else if (httpResponse.getStatusLine().getStatusCode() >= 300) {
      // See if we can redirect the command
      Header locationHeader = httpResponse.getFirstHeader("Location");
      if (locationHeader != null) {
        try {
          HttpRequestWrapper newReq = HttpRequestWrapper.wrap(req);

          // Determine if this is a relataive redirection
          URI redirUrl = new URI(locationHeader.getValue());
          if (!redirUrl.isAbsolute()) {
            HttpHost target = URIUtils.extractHost(newReq.getURI());

            redirUrl = URI.create(
              String.format(
                "%s://%s%s",
                target.getSchemeName(),
                target.toHostString(),
                locationHeader.getValue()
              )
            );
          }
          
          newReq.setURI(redirUrl);

          return execute(newReq, ++redirectDepth);
        } catch (IOException | URISyntaxException e) {
          LOG.debug("Error executing request", e);
          throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
        }
      }
    }
    return IOUtils.toString(contentStream, "UTF-8");
  }
}
 
Example 15
Source File: UriUtils.java    From esigate with Apache License 2.0 2 votes vote down vote up
/**
 * Extracts the {@link HttpHost} from a URI.
 * 
 * @param uri
 *            the URI
 * @return the {@link HttpHost}
 */
public static HttpHost extractHost(final String uri) {
    return URIUtils.extractHost(createURI(uri));
}
 
Example 16
Source File: UriUtils.java    From esigate with Apache License 2.0 2 votes vote down vote up
/**
 * Extracts the {@link HttpHost} from a URI.
 * 
 * @param uri
 *            the {@link URI}
 * @return the {@link HttpHost}
 */
public static HttpHost extractHost(final URI uri) {
    return URIUtils.extractHost(uri);
}