Example usage for org.apache.http.client.utils URIUtils extractHost

List of usage examples for org.apache.http.client.utils URIUtils extractHost

Introduction

In this page you can find the example usage for org.apache.http.client.utils URIUtils extractHost.

Prototype

public static HttpHost extractHost(final URI uri) 

Source Link

Document

Extracts target host from the given URI .

Usage

From source file:io.uploader.drive.drive.largefile.DriveResumableUpload.java

public long getCurrentByte() throws IOException {
    logger.info("Querying status of resumable upload...");

    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    long lastbyte = -1;
    try {//from   w w w. j  a  v  a2 s  .  com
        httpclient = getHttpClient();
        BasicHttpRequest httpreq = new BasicHttpRequest("PUT", location);
        httpreq.addHeader("Authorization", auth.getAuthHeader());
        httpreq.addHeader("Content-Length", "0");
        httpreq.addHeader("Content-Range", "bytes */" + getFileSizeString());
        //logger.info(httpreq.toString());
        response = httpclient.execute(URIUtils.extractHost(uri), httpreq);
        @SuppressWarnings("unused")
        BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity());
        EntityUtils.consume(response.getEntity());
        if (response.getStatusLine().getStatusCode() == 200
                || response.getStatusLine().getStatusCode() == 201) {
            lastbyte = fileSize;
        }
        if (response.getStatusLine().getStatusCode() == 308) {
            if (response.getHeaders("Range").length > 0) {
                String range = response.getHeaders("Range")[0].getValue();
                String[] parts = range.split("-");
                lastbyte = Long.parseLong(parts[1]) + 1;
            } else {
                // nothing uploaded, but file is there to start upload!
                lastbyte = 0;
            }
        }
        return lastbyte;
    } finally {
        if (response != null) {
            response.close();
        }
        if (httpclient != null) {
            httpclient.close();
        }
    }
}

From source file:com.redhat.jenkins.nodesharing.RestEndpoint.java

private @Nonnull HttpClientContext getAuthenticatingContext(@Nonnull HttpRequestBase method) {
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(URIUtils.extractHost(method.getURI()), basicAuth);

    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new org.apache.http.auth.UsernamePasswordCredentials(
            creds.getUsername(), creds.getPassword().getPlainText()));
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(provider);
    context.setAuthCache(authCache);/*w  w  w  .  ja  v  a 2  s.c o  m*/
    return context;
}

From source file:x.y.z.DefaultRequestDirector.java

protected RoutedRequest handleResponse(final RoutedRequest roureq, final HttpResponse response,
            final HttpContext context) throws HttpException, IOException {
        test();/*  w w w  . j a va 2s  .c  o  m*/
        String something = new String();
        String somethingElse = "";
        List<Something> somethingList = null;
        test(something);
        final HttpRoute route = roureq.getRoute();
        final RequestWrapper request = roureq.getRequest();
        final HttpParams params = request.getParams();
        int i = org.apache.http.params.HttpConnectionParams.getConnectionTimeout(parmas);
        javax.rmi.CORBA obj;
        if (HttpClientParams.isAuthenticating(params)) {
            HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            if (target == null) {
                target = route.getTargetHost();
            }
            if (target.getPort() < 0) {
                final Scheme scheme = connManager.getSchemeRegistry().getScheme(target);
                target = new HttpHost(target.getHostName(), scheme.getDefaultPort(), target.getSchemeName());
            }
            final boolean targetAuthRequested = this.authenticator.isAuthenticationRequested(target, response,
                    this.targetAuthStrategy, targetAuthState, context);
            HttpHost proxy = route.getProxyHost();
            if (proxy == null) {
                proxy = route.getTargetHost();
            }
            final boolean proxyAuthRequested = this.authenticator.isAuthenticationRequested(proxy, response,
                    this.proxyAuthStrategy, proxyAuthState, context);
            if (targetAuthRequested) {
                if (this.authenticator.authenticate(target, response, this.targetAuthStrategy, this.targetAuthState,
                        context)) {
                    return roureq;
                }
            }
            if (proxyAuthRequested) {
                if (this.authenticator.authenticate(proxy, response, this.proxyAuthStrategy, this.proxyAuthState,
                        context)) {
                    return roureq;
                }
            }
        }
        if (HttpClientParams.isRedirecting(params)
                && this.redirectStrategy.isRedirected(request, response, context)) {
            if (redirectCount >= maxRedirects) {
                throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
            }
            redirectCount++;
            virtualHost = null;
            final HttpUriRequest redirect = redirectStrategy.getRedirect(request, response, context);
            final HttpRequest orig = request.getOriginal();
            redirect.setHeaders(orig.getAllHeaders());
            final URI uri = redirect.getURI();
            final HttpHost newTarget = URIUtils.extractHost(uri);
            if (newTarget == null) {
                throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri);
            }
            if (!route.getTargetHost().equals(newTarget)) {
                this.log.debug("Resetting target auth state");
                targetAuthState.reset();
                final AuthScheme authScheme = proxyAuthState.getAuthScheme();
                if (authScheme != null && authScheme.isConnectionBased()) {
                    this.log.debug("Resetting proxy auth state");
                    proxyAuthState.reset();
                }
            }
            final RequestWrapper wrapper = wrapRequest(redirect);
            wrapper.setParams(params);
            final HttpRoute newRoute = determineRoute(newTarget, wrapper, context);
            final RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute);
            if (this.log.isDebugEnabled()) {
                this.log.debug("Redirecting to '" + uri + "' via " + newRoute);
            }
            return newRequest;
        }
        return null;
    }

From source file:org.realityforge.proxy_servlet.AbstractProxyServlet.java

/**
 * Copy request headers from the servlet client to the proxy request.
 *//*w w w  .  j a v a 2s  .  c  o m*/
private void copyRequestHeaders(final HttpServletRequest servletRequest, final HttpRequest proxyRequest) {
    // Get an Enumeration of all of the header names sent by the client
    final Enumeration enumerationOfHeaderNames = servletRequest.getHeaderNames();
    while (enumerationOfHeaderNames.hasMoreElements()) {
        final String headerName = (String) enumerationOfHeaderNames.nextElement();
        //Instead the content-length is effectively set via InputStreamEntity
        if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) {
            continue;
        } else if (HOP_BY_HOP_HEADERS.containsHeader(headerName)) {
            continue;
        }

        final 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)) {
                final HttpHost host = URIUtils.extractHost(_targetUri);
                headerValue = host.getHostName();
                if (-1 != host.getPort()) {
                    headerValue += ":" + host.getPort();
                }
            }
            proxyRequest.addHeader(headerName, headerValue);
        }
    }
}

From source file:org.iff.infra.util.servlet.ProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    // Make the Request
    //note: we won't transfer the protocol version because I'm not sure it would truly be compatible
    String method = servletRequest.getMethod();
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);
    HttpRequest proxyRequest;/*from  ww  w . j  ava  2  s  . c o  m*/
    //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
    if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
        HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
        // Add the input entity (streamed)
        //  note: we don't bother ensuring we close the servletInputStream since the container handles it
        eProxyRequest.setEntity(
                new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
        proxyRequest = eProxyRequest;
    } else {
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
    }

    copyRequestHeaders(servletRequest, proxyRequest);

    setXForwardedForHeader(servletRequest, proxyRequest);

    {//add by tylerchen
        String header = initParameterMap.get("header");
        if (header != null) {
            String[] split = header.split("@@@");
            for (String s : split) {
                String[] headerPaire = s.split("=");
                if (headerPaire.length == 2) {
                    proxyRequest.addHeader(headerPaire[0], headerPaire[1]);
                }
            }
        }
    }

    HttpResponse proxyResponse = null;
    try {
        // Execute the request
        if (doLog) {
            log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- "
                    + proxyRequest.getRequestLine().getUri());
        }
        proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUriObj), proxyRequest);

        // Process the response
        int statusCode = proxyResponse.getStatusLine().getStatusCode();

        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) {
            //the response is already "committed" now without any body to send
            //TODO copy response headers?
            return;
        }

        // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the
        //  reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        copyResponseHeaders(proxyResponse, servletResponse);

        if ("true".equals(initParameterMap.get("cached"))) {//add cache by tylerchen
            //servlet??
            //?????20
            //20????servlet
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            Date date = new Date();
            response.setDateHeader("Last-Modified", date.getTime()); //Last-Modified:??? 
            response.setDateHeader("Expires", date.getTime() * 100); //Expires:? 
            response.setHeader("Cache-Control", "public"); //Cache-Control???,public:?????
            response.setHeader("Cache-Control", "max-age=" + date.getTime() * 100);
            response.setHeader("Pragma", "Pragma"); //Pragma:??Pragmano-cache?

            //???????
            /*response.setHeader( "Pragma", "no-cache" );   
            response.setDateHeader("Expires", 0);   
            response.addHeader( "Cache-Control", "no-cache" );//?????
            response.addHeader( "Cache-Control", "no-store" );//????    
            response.addHeader( "Cache-Control", "must-revalidate" );*///??????
        }

        // Send the content to the client
        copyResponseEntity(proxyResponse, servletResponse);

    } catch (Exception e) {
        //abort request, according to best practice with HttpClient
        if (proxyRequest instanceof AbortableHttpRequest) {
            AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
            abortableHttpRequest.abort();
        }
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        if (e instanceof ServletException)
            throw (ServletException) e;
        //noinspection ConstantConditions
        if (e instanceof IOException)
            throw (IOException) e;
        throw new RuntimeException(e);

    } finally {
        // make sure the entire entity was consumed, so the connection is released
        if (proxyResponse != null)
            consumeQuietly(proxyResponse.getEntity());
        //Note: Don't need to close servlet outputStream:
        // http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter
    }
}

From source file:uk.ac.ebi.phenotype.web.proxy.ExternalUrlConfiguratbleProxyServlet.java

/** 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();
        if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH))
            continue;
        // As per the Java Servlet API 2.5 documentation:
        // Some headers, such as Accept-Language can be sent by clients
        // as several headers each with a different value rather than
        // sending the header as a comma separated list.
        // Thus, we get an Enumeration of the header values sent by the
        // client
        Enumeration headers = servletRequest.getHeaders(headerName);
        while (headers.hasMoreElements()) {
            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();
            }/*from ww  w. ja v a  2 s . c o m*/
            proxyRequest.addHeader(headerName, headerValue);
        }
    }
}

From source file:com.springsource.insight.plugin.apache.http.hc4.HttpClientExecutionCollectionAspectTest.java

private void runHostResponseHandlerTest(String testName, HttpContext context) throws Exception {
    runResponseHandlerTest(testName, URIUtils.extractHost(new URI(createTestUri(testName))), context);
}

From source file:snoopware.api.ProxyServlet.java

/**
 * Copy request headers from the servlet client to the proxy request.
 *//*from   w w w  . j  ava  2 s.  c om*/
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);
        }
    }
}

From source file:be.milieuinfo.core.proxy.controller.ProxyServlet.java

/** 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;
        // As per the Java Servlet API 2.5 documentation:
        //      Some headers, such as Accept-Language can be sent by clients
        //      as several headers each with a different value rather than
        //      sending the header as a comma separated list.
        // Thus, we get an Enumeration of the header values sent by the client
        Enumeration headers = servletRequest.getHeaders(headerName);
        while (headers.hasMoreElements()) {
            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();
            }/* w w w.  j  av  a  2  s  . c o m*/
            proxyRequest.addHeader(headerName, headerValue);
        }
    }
}

From source file:org.redhat.jboss.httppacemaker.ProxyServlet.java

/** Copy request headers from the servlet client to the proxy request. */
@SuppressWarnings("rawtypes")
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();
            }/*from   ww w.  jav a  2  s.c o m*/
            proxyRequest.addHeader(headerName, headerValue);
        }
    }
}