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.nuxeo.connect.registration.RegistrationHelper.java

protected static HttpClientContext getHttpClientContext(String url, String login, String password) {
    HttpClientContext context = HttpClientContext.create();

    // Set credentials provider
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    if (login != null) {
        Credentials ba = new UsernamePasswordCredentials(login, password);
        credentialsProvider.setCredentials(AuthScope.ANY, ba);
    }//w ww  .j a v a  2 s  .  c  o  m
    context.setCredentialsProvider(credentialsProvider);

    // Create AuthCache instance for preemptive authentication
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    try {
        authCache.put(URIUtils.extractHost(new URI(url)), basicAuth);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    context.setAuthCache(authCache);

    // Create request configuration
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setConnectTimeout(10000);

    // Configure the http proxy if needed
    ProxyHelper.configureProxyIfNeeded(requestConfigBuilder, credentialsProvider, url);

    context.setRequestConfig(requestConfigBuilder.build());
    return context;
}

From source file:xyz.cloudbans.client.DefaultClient.java

@Override
public Future<BanResponse> getActiveBan(UUID serverUuid, String playerIdentifier) {
    HttpGet httpRequest = new HttpGet(
            buildSafe(createUri("/server/" + serverUuid + "/check/" + escape(playerIdentifier))));
    initHeaders(httpRequest);//w  ww .ja  v a  2  s.co  m

    return client.execute(new BasicAsyncRequestProducer(URIUtils.extractHost(config.getBaseUri()), httpRequest),
            SerializerConsumer.create(config.getSerializer(), BanResponse.class),
            DeafFutureCallback.<BanResponse>instance());
}

From source file:org.github.oauth2.AccessTokenClient.java

/**
 * Get access token using given code// ww w .  ja  va2s  .c o  m
 * 
 * @param code
 * @return fetched token
 * @throws IOException
 */
public String fetch(final String code) throws IOException {
    URI uri = URI.create(client.getAccessTokenUrl());
    HttpHost target = URIUtils.extractHost(uri);
    List<NameValuePair> params = getParams(code);
    HttpPost request = new HttpPost(uri.getRawPath());
    if (params != null && !params.isEmpty())
        request.setEntity(new UrlEncodedFormEntity(params));
    HttpResponse response = execute(target, request);
    String token = getToken(response.getEntity());
    if (token == null)
        throw new IOException("Access token not present in response"); //$NON-NLS-1$
    return token;
}

From source file:xyz.cloudbans.client.DefaultClient.java

@Override
public Future<BanResponse> createBan(BanRequest request) {
    HttpPost httpRequest = new HttpPost(buildSafe(createUri("/bans")));
    initHeaders(httpRequest);/*from   www .  jav a  2 s  .  c o  m*/
    httpRequest.setEntity(createEntity(request));

    return client.execute(new BasicAsyncRequestProducer(URIUtils.extractHost(config.getBaseUri()), httpRequest),
            SerializerConsumer.create(config.getSerializer(), BanResponse.class),
            DeafFutureCallback.<BanResponse>instance());
}

From source file:io.hops.hopsworks.api.jupyter.URITemplateProxyServlet.java

protected void initTarget() throws ServletException {
    targetUriTemplate = getConfigParam(P_TARGET_URI);
    if (targetUriTemplate == null) {
        throw new ServletException(P_TARGET_URI + " is required.");
    }//from ww  w.  j a  v  a 2 s.c om

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

    //leave this.target* null to prevent accidental mis-use
}

From source file:org.callimachusproject.setup.WebappArchiveImporter.java

private void importArchive(InputStream carStream, String folderUri, String webapp, CalliRepository repository)
        throws IOException, OpenRDFException, NoSuchMethodException, InvocationTargetException {
    HttpHost host = URIUtils.extractHost(java.net.URI.create(webapp));
    UnavailableRequestDirector service = new UnavailableRequestDirector();
    HttpClientFactory.getInstance().setProxyIfAbsent(host, service);
    try {/*from   w ww.ja  va 2 s  .c o  m*/
        if (schemaGraphs != null) {
            for (URI schemaGraph : schemaGraphs) {
                repository.addSchemaGraph(schemaGraph);
            }
        } else {
            repository.setSchemaGraphType(webapp + SCHEMA_GRAPH);
        }
        repository.setCompileRepository(true);
        ObjectConnection con = repository.getConnection();
        try {
            disableAuditingRemoval(con);
            con.begin();
            if (schemaGraphs != null && schemaGraphs.length > 0) {
                con.clear(schemaGraphs);
            }
            Object folder = con.getObject(folderUri);
            Method UploadFolderComponents = findUploadFolderComponents(folder);
            try {
                logger.info("Importing {}", folderUri);
                int argc = UploadFolderComponents.getParameterTypes().length;
                Object[] args = new Object[argc];
                args[0] = carStream;
                UploadFolderComponents.invoke(folder, args);
            } catch (IllegalAccessException e) {
                throw new AssertionError(e);
            }
            repository.setCompileRepository(false);
            con.commit();
        } finally {
            con.close();
            HttpClientFactory.getInstance().removeProxy(host, service);
        }
    } finally {
        repository.setCompileRepository(false);
        if (schemaGraphs != null) {
            for (URI schemaGraph : schemaGraphs) {
                repository.removeSchemaGraph(schemaGraph);
            }
        }
    }
}

From source file:xyz.cloudbans.client.DefaultClient.java

@Override
public Future<BanResponse> updateBan(BanRequest request) {
    HttpPut httpRequest = new HttpPut(buildSafe(createUri("/ban/" + request.getId())));
    initHeaders(httpRequest);//from   w ww. j a  va 2 s  .c o m
    httpRequest.setEntity(createEntity(request));

    return client.execute(new BasicAsyncRequestProducer(URIUtils.extractHost(config.getBaseUri()), httpRequest),
            SerializerConsumer.create(config.getSerializer(), BanResponse.class),
            DeafFutureCallback.<BanResponse>instance());
}

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

@SuppressWarnings("deprecation")
@Override//from w w  w  .  ja va 2s  .  c  o m
protected void service(final HttpServletRequest servletRequest, final HttpServletResponse servletResponse)
        throws ServletException, IOException {
    final String proxyRequestUri = rewriteUrlFromRequest(servletRequest);
    final HttpRequest proxyRequest = newProxyRequest(servletRequest, proxyRequestUri);

    copyRequestHeaders(servletRequest, proxyRequest);
    setXForwardedForHeader(servletRequest, proxyRequest);

    proxyPrepared(proxyRequest);

    try {
        final HttpResponse proxyResponse = _client.execute(URIUtils.extractHost(_targetUri), proxyRequest);

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

        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) {
            //just to be sure, but is probably a no-op
            EntityUtils.consume(proxyResponse.getEntity());
            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.
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        copyResponseHeaders(proxyResponse, servletResponse);

        // Send the content to the client
        copyResponseEntity(proxyResponse, servletResponse);
    } catch (final Exception e) {
        //abort request, according to best practice with HttpClient
        if (proxyRequest instanceof Cancellable) {
            final Cancellable cancellable = (Cancellable) proxyRequest;
            cancellable.cancel();
        }
        handleError(e);
    }
}

From source file:org.overlord.apiman.service.client.http.HTTPServiceClient.java

/**
 * {@inheritDoc}//from w  w  w  . j  a v  a  2  s  . c o m
 */
@Override
public Response process(Request request) throws Exception {
    String method = "GET";

    if (request instanceof HTTPGatewayRequest) {
        method = ((HTTPGatewayRequest) request).getHTTPMethod();
    }

    String proxyRequestUri = rewriteUrlFromRequest(request);

    HttpRequest proxyRequest;

    //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
    if (request.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || request.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
        HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);

        java.io.InputStream is = new java.io.ByteArrayInputStream(request.getContent());

        InputStreamEntity entity = new InputStreamEntity(is, request.getContent().length);

        is.close();

        eProxyRequest.setEntity(entity);

        proxyRequest = eProxyRequest;
    } else {
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
    }

    copyRequestHeaders(request, proxyRequest);

    try {
        // Execute the request
        if (LOG.isLoggable(Level.FINER)) {
            LOG.finer("proxy " + method + " uri: " + request.getSourceURI() + " -- "
                    + proxyRequest.getRequestLine().getUri());
        }

        HttpResponse proxyResponse = _proxyClient
                .execute(URIUtils.extractHost(new java.net.URI(request.getServiceURI())), proxyRequest);

        Response resp = new HTTPGatewayResponse(proxyResponse);

        return (resp);

    } 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;
        }
        //noinspection ConstantConditions
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        throw new RuntimeException(e);
    }
}

From source file:org.mitre.dsmiley.httpproxy.DynamicProxyServlet.java

private HttpHost getTargetHost(HttpServletRequest servletRequest) {
    try {/*from   ww  w.j  a  v a  2 s .c  om*/
        return URIUtils.extractHost(new URI(extractTargetUrl(servletRequest)));
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}