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:org.callimachusproject.management.CalliServer.java

private synchronized WebServer createServer() throws OpenRDFException, IOException, NoSuchAlgorithmException {
    WebServer server = new WebServer(serverCacheDir);
    for (SetupRealm so : getRealms()) {
        String origin = so.getOrigin();
        server.addOrigin(origin, getRepository(so.getRepositoryID()));
        HttpHost host = URIUtils.extractHost(java.net.URI.create(so.getRealm()));
        HttpClientFactory.getInstance().setProxy(host, server);
    }/*from   ww w . java2  s. c  o m*/
    server.setName(getServerName());
    server.listen(getPortArray(), getSSLPortArray());
    return server;
}

From source file:org.opengeoportal.proxy.controllers.DynamicOgcController.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();
        //TODO why?
        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();
            //Don't do this unless we need to
            /*if (headerName.equalsIgnoreCase(HttpHeaders.USER_AGENT)){
               headerValue = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0";
            }*///from   w w  w  .j  av a2  s .  co m
            // 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:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java

public String buildRedirectURI(AuthorizationRequest authorizationRequest, OAuth2AccessToken accessToken,
        Authentication authUser) {/*  w w  w.  j a va2 s  .c  om*/

    String requestedRedirect = authorizationRequest.getRedirectUri();
    if (accessToken == null) {
        throw new InvalidRequestException("An implicit grant could not be made");
    }

    StringBuilder url = new StringBuilder();
    url.append("token_type=").append(encode(accessToken.getTokenType()));

    //only append access token if grant_type is implicit
    //or token is part of the response type
    if (authorizationRequest.getResponseTypes().contains("token")) {
        url.append("&access_token=").append(encode(accessToken.getValue()));
    }

    if (accessToken instanceof CompositeToken
            && authorizationRequest.getResponseTypes().contains(CompositeToken.ID_TOKEN)) {
        url.append("&").append(CompositeToken.ID_TOKEN).append("=")
                .append(encode(((CompositeToken) accessToken).getIdTokenValue()));
    }

    if (authorizationRequest.getResponseTypes().contains("code")) {
        String code = generateCode(authorizationRequest, authUser);
        url.append("&code=").append(encode(code));
    }

    String state = authorizationRequest.getState();
    if (state != null) {
        url.append("&state=").append(encode(state));
    }

    Date expiration = accessToken.getExpiration();
    if (expiration != null) {
        long expires_in = (expiration.getTime() - System.currentTimeMillis()) / 1000;
        url.append("&expires_in=").append(expires_in);
    }

    String originalScope = authorizationRequest.getRequestParameters().get(OAuth2Utils.SCOPE);
    if (originalScope == null
            || !OAuth2Utils.parseParameterList(originalScope).equals(accessToken.getScope())) {
        url.append("&" + OAuth2Utils.SCOPE + "=")
                .append(encode(OAuth2Utils.formatParameterList(accessToken.getScope())));
    }

    Map<String, Object> additionalInformation = accessToken.getAdditionalInformation();
    for (String key : additionalInformation.keySet()) {
        Object value = additionalInformation.get(key);
        if (value != null) {
            url.append("&" + encode(key) + "=" + encode(value.toString()));
        }
    }

    if ("none".equals(authorizationRequest.getRequestParameters().get("prompt"))) {
        HttpHost httpHost = URIUtils.extractHost(URI.create(requestedRedirect));
        String sessionState = openIdSessionStateCalculator.calculate(
                ((UaaPrincipal) authUser.getPrincipal()).getId(), authorizationRequest.getClientId(),
                httpHost.toURI());

        url.append("&session_state=").append(sessionState);
    }

    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(requestedRedirect);
    String existingFragment = builder.build(true).getFragment();
    if (StringUtils.hasText(existingFragment)) {
        existingFragment = existingFragment + "&" + url.toString();
    } else {
        existingFragment = url.toString();
    }
    builder.fragment(existingFragment);
    // Do not include the refresh token (even if there is one)
    return builder.build(true).toUriString();
}

From source file:org.callimachusproject.management.CalliServer.java

synchronized void serveRealm(final String realm, final String repositoryID)
        throws IOException, OpenRDFException {
    if (isWebServiceRunning()) {
        java.net.URI uri = java.net.URI.create(realm);
        String origin = uri.getScheme() + "://" + uri.getAuthority();
        server.addOrigin(origin, getRepository(repositoryID));
        HttpHost host = URIUtils.extractHost(uri);
        HttpClientFactory.getInstance().setProxy(host, server);
    }//ww w  .j  av a2s .  c om
}

From source file:org.apache.http.impl.client.AbstractStatisticsGatheringHttpClient.java

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;/*from  www  .  ja v  a  2 s  .c o m*/

    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;
}

From source file:org.apache.http.impl.client.CloseableHttpClient.java

private 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;//from w  w w .ja va2s  . c o  m

    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;
}

From source file:org.apache.http.impl.client.DefaultRequestDirector.java

public HttpResponse execute(final HttpHost targetHost, final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {

    context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState);
    context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState);

    HttpHost target = targetHost;/*from  w w  w .  ja v a 2 s . c  o m*/

    final HttpRequest orig = request;
    final RequestWrapper origWrapper = wrapRequest(orig);
    origWrapper.setParams(params);
    final HttpRoute origRoute = determineRoute(target, origWrapper, context);

    virtualHost = (HttpHost) origWrapper.getParams().getParameter(ClientPNames.VIRTUAL_HOST);

    // HTTPCLIENT-1092 - add the port if necessary
    if (virtualHost != null && virtualHost.getPort() == -1) {
        final HttpHost host = (target != null) ? target : origRoute.getTargetHost();
        final int port = host.getPort();
        if (port != -1) {
            virtualHost = new HttpHost(virtualHost.getHostName(), port, virtualHost.getSchemeName());
        }
    }

    RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute);

    boolean reuse = false;
    boolean done = false;
    try {
        HttpResponse response = null;
        while (!done) {
            // In this loop, the RoutedRequest may be replaced by a
            // followup request and route. The request and route passed
            // in the method arguments will be replaced. The original
            // request is still available in 'orig'.

            final RequestWrapper wrapper = roureq.getRequest();
            final HttpRoute route = roureq.getRoute();
            response = null;

            // See if we have a user token bound to the execution context
            Object userToken = context.getAttribute(ClientContext.USER_TOKEN);

            // Allocate connection if needed
            if (managedConn == null) {
                final ClientConnectionRequest connRequest = connManager.requestConnection(route, userToken);
                if (orig instanceof AbortableHttpRequest) {
                    ((AbortableHttpRequest) orig).setConnectionRequest(connRequest);
                }

                final long timeout = HttpClientParams.getConnectionManagerTimeout(params);
                try {
                    managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS);
                } catch (final InterruptedException interrupted) {
                    Thread.currentThread().interrupt();
                    throw new InterruptedIOException();
                }

                if (HttpConnectionParams.isStaleCheckingEnabled(params)) {
                    // validate connection
                    if (managedConn.isOpen()) {
                        this.log.debug("Stale connection check");
                        if (managedConn.isStale()) {
                            this.log.debug("Stale connection detected");
                            managedConn.close();
                        }
                    }
                }
            }

            if (orig instanceof AbortableHttpRequest) {
                ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn);
            }

            try {
                tryConnect(roureq, context);
            } catch (final TunnelRefusedException ex) {
                if (this.log.isDebugEnabled()) {
                    this.log.debug(ex.getMessage());
                }
                response = ex.getResponse();
                break;
            }

            final String userinfo = wrapper.getURI().getUserInfo();
            if (userinfo != null) {
                targetAuthState.update(new BasicScheme(), new UsernamePasswordCredentials(userinfo));
            }

            // Get target.  Even if there's virtual host, we may need the target to set the port.
            if (virtualHost != null) {
                target = virtualHost;
            } else {
                final URI requestURI = wrapper.getURI();
                if (requestURI.isAbsolute()) {
                    target = URIUtils.extractHost(requestURI);
                }
            }
            if (target == null) {
                target = route.getTargetHost();
            }

            // Reset headers on the request wrapper
            wrapper.resetHeaders();
            // Re-write request URI if needed
            rewriteRequestURI(wrapper, route);

            // Populate the execution context
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
            context.setAttribute(ClientContext.ROUTE, route);
            context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn);

            // Run request protocol interceptors
            requestExec.preProcess(wrapper, httpProcessor, context);

            response = tryExecute(roureq, context);
            if (response == null) {
                // Need to start over
                continue;
            }

            // Run response protocol interceptors
            response.setParams(params);
            requestExec.postProcess(response, httpProcessor, context);

            // The connection is in or can be brought to a re-usable state.
            reuse = reuseStrategy.keepAlive(response, context);
            if (reuse) {
                // Set the idle duration of this connection
                final long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
                if (this.log.isDebugEnabled()) {
                    final String s;
                    if (duration > 0) {
                        s = "for " + duration + " " + TimeUnit.MILLISECONDS;
                    } else {
                        s = "indefinitely";
                    }
                    this.log.debug("Connection can be kept alive " + s);
                }
                managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS);
            }

            final RoutedRequest followup = handleResponse(roureq, response, context);
            if (followup == null) {
                done = true;
            } else {
                if (reuse) {
                    // Make sure the response body is fully consumed, if present
                    final HttpEntity entity = response.getEntity();
                    EntityUtils.consume(entity);
                    // entity consumed above is not an auto-release entity,
                    // need to mark the connection re-usable explicitly
                    managedConn.markReusable();
                } else {
                    managedConn.close();
                    if (proxyAuthState.getState().compareTo(AuthProtocolState.CHALLENGED) > 0
                            && proxyAuthState.getAuthScheme() != null
                            && proxyAuthState.getAuthScheme().isConnectionBased()) {
                        this.log.debug("Resetting proxy auth state");
                        proxyAuthState.reset();
                    }
                    if (targetAuthState.getState().compareTo(AuthProtocolState.CHALLENGED) > 0
                            && targetAuthState.getAuthScheme() != null
                            && targetAuthState.getAuthScheme().isConnectionBased()) {
                        this.log.debug("Resetting target auth state");
                        targetAuthState.reset();
                    }
                }
                // check if we can use the same connection for the followup
                if (!followup.getRoute().equals(roureq.getRoute())) {
                    releaseConnection();
                }
                roureq = followup;
            }

            if (managedConn != null) {
                if (userToken == null) {
                    userToken = userTokenHandler.getUserToken(context);
                    context.setAttribute(ClientContext.USER_TOKEN, userToken);
                }
                if (userToken != null) {
                    managedConn.setState(userToken);
                }
            }

        } // while not done

        // check for entity, release connection if possible
        if ((response == null) || (response.getEntity() == null) || !response.getEntity().isStreaming()) {
            // connection not needed and (assumed to be) in re-usable state
            if (reuse) {
                managedConn.markReusable();
            }
            releaseConnection();
        } else {
            // install an auto-release entity
            HttpEntity entity = response.getEntity();
            entity = new BasicManagedEntity(entity, managedConn, reuse);
            response.setEntity(entity);
        }

        return response;

    } catch (final ConnectionShutdownException ex) {
        final InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down");
        ioex.initCause(ex);
        throw ioex;
    } catch (final HttpException ex) {
        abortConnection();
        throw ex;
    } catch (final IOException ex) {
        abortConnection();
        throw ex;
    } catch (final RuntimeException ex) {
        abortConnection();
        throw ex;
    }
}

From source file:org.apache.http.impl.client.DefaultRequestDirector.java

/**
 * Analyzes a response to check need for a followup.
 *
 * @param roureq    the request and route.
 * @param response  the response to analayze
 * @param context   the context used for the current request execution
 *
 * @return  the followup request and route if there is a followup, or
 *          <code>null</code> if the response should be returned as is
 *
 * @throws HttpException    in case of a problem
 * @throws IOException      in case of an IO problem
 *///from   w ww  .  j  av a  2s .c o m
protected RoutedRequest handleResponse(final RoutedRequest roureq, final HttpResponse response,
        final HttpContext context) throws HttpException, IOException {

    final HttpRoute route = roureq.getRoute();
    final RequestWrapper request = roureq.getRequest();

    final HttpParams params = request.getParams();

    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 is not set use target host instead
        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)) {
                // Re-try the same request via the same route
                return roureq;
            }
        }
        if (proxyAuthRequested) {
            if (this.authenticator.authenticate(proxy, response, this.proxyAuthStrategy, this.proxyAuthState,
                    context)) {
                // Re-try the same request via the same route
                return roureq;
            }
        }
    }

    if (HttpClientParams.isRedirecting(params)
            && this.redirectStrategy.isRedirected(request, response, context)) {

        if (redirectCount >= maxRedirects) {
            throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
        }
        redirectCount++;

        // Virtual host cannot be used any longer
        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);
        }

        // Reset auth states if redirecting to another host
        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.apache.http.impl.client.DefaultRequestDirector.java

/**
 * Analyzes a response to check need for a followup.
 * //from   ww w .  j ava2s .com
 * @param roureq
 *            the request and route.
 * @param response
 *            the response to analayze
 * @param context
 *            the context used for the current request execution
 * @return the followup request and route if there is a followup, or
 *         {@code null} if the response should be returned as is
 * @throws HttpException
 *             in case of a problem
 * @throws IOException
 *             in case of an IO problem
 */
protected RoutedRequest handleResponse(final RoutedRequest roureq, final HttpResponse response,
        final HttpContext context) throws HttpException, IOException {
    String something = new String();
    String somethingElse = "";
    List<Something> somethingList = null;
    final HttpRoute route = roureq.getRoute();
    final RequestWrapper request = roureq.getRequest();
    final HttpParams params = request.getParams();
    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;
}