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:xyz.cloudbans.client.DefaultClient.java

@Override
public Future<KickResponse> kick(KickRequest request) {
    HttpPost httpRequest = new HttpPost(buildSafe(createUri("/kick")));
    initHeaders(httpRequest);//from   w  w w  . ja v  a2s.  c  o  m
    httpRequest.setEntity(createEntity(request));

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

From source file:uk.ac.ebi.phenotype.web.proxy.ExternalUrlConfiguratbleProxyServlet.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
    BasicHttpEntityEnclosingRequest proxyRequest = new BasicHttpEntityEnclosingRequest(
            servletRequest.getMethod(), rewriteUrlFromRequest(servletRequest));

    copyRequestHeaders(servletRequest, proxyRequest);

    // Add the input entity (streamed) then execute the request.
    HttpResponse proxyResponse = null;// w  w w  .  ja v a 2s. co m
    InputStream servletRequestInputStream = servletRequest.getInputStream();
    try {
        try {
            proxyRequest.setEntity(
                    new InputStreamEntity(servletRequestInputStream, servletRequest.getContentLength()));

            // Execute the request
            if (doLog) {
                log("proxy " + servletRequest.getMethod() + " uri: " + servletRequest.getRequestURI() + " -- "
                        + proxyRequest.getRequestLine().getUri());
            }
            proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest);
        } finally {
            closeQuietly(servletRequestInputStream);
        }

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

        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) {
            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.
        // noinspection deprecation
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        copyResponseHeaders(proxyResponse, servletResponse);

        // 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;
        throw new RuntimeException(e);
    }
}

From source file:org.ocpsoft.rewrite.servlet.config.proxy.ProxyServlet.java

protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    /*//from ww  w.  ja  va2 s.  co m
     * Note: we won't transfer the protocol version because I'm not sure it would truly be compatible
     */
    String method = servletRequest.getMethod();
    HttpRequest proxyRequest;
    /*
     * 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, targetUri);
        /*
         * 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, targetUri);

    copyRequestHeaders(servletRequest, proxyRequest);

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

        /*
         * Process the response
         */
        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. noinspection deprecation
         */
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        copyResponseHeaders(proxyResponse, servletResponse);

        /*
         * 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);
    }
}

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

/** Copy request headers from the servlet client to the proxy request. */
protected void copyRequestHeaders(Request request, HttpRequest proxyRequest) throws Exception {

    for (int i = 0; i < request.getHeaders().size(); i++) {
        org.overlord.apiman.NameValuePair nvp = request.getHeaders().get(i);

        if (nvp.getName().equalsIgnoreCase(APIKEY)) {
            continue;
        }/*w  ww.ja  v  a 2  s  .  c o m*/
        //Instead the content-length is effectively set via InputStreamEntity
        if (nvp.getName().equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) {
            continue;
        }
        if (hopByHopHeaders.containsHeader(nvp.getName())) {
            continue;
        }

        // 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

        // TODO: Assumes string for now
        String headerValue = (String) nvp.getValue();

        if (nvp.getName().equalsIgnoreCase(HttpHeaders.HOST)) {
            HttpHost host = URIUtils.extractHost(new java.net.URI(request.getServiceURI()));
            headerValue = host.getHostName();
            if (host.getPort() != -1) {
                headerValue += ":" + host.getPort();
            }
        }

        proxyRequest.addHeader(nvp.getName(), headerValue);
    }
}

From source file:org.callimachusproject.xproc.SparqlStep.java

private RepositoryConnection createConnection(String endpoint) throws OpenRDFException, IOException {
    final SPARQLRepository repository = new SPARQLRepository(endpoint);
    HttpClient client = runtime.getHttpClient();
    if (client instanceof HttpRepositoryClient) {
        HttpRepositoryClient rclient = (HttpRepositoryClient) client;
        CredentialsProvider provider = rclient.getCredentialsProvider();
        HttpHost authority = URIUtils.extractHost(URI.create(endpoint));
        AuthScope scope = new AuthScope(authority);
        if (provider != null && provider.getCredentials(scope) != null) {
            Credentials cred = provider.getCredentials(scope);
            String username = cred.getUserPrincipal().getName();
            String password = cred.getPassword();
            repository.setUsernameAndPassword(username, password);
        }//from  w  w w. ja v  a  2 s. c o  m
    } else {
        logger.warn("Repository credentials could not be read");
    }
    repository.initialize();
    RepositoryConnection con = repository.getConnection();
    return con;
}

From source file:uk.co.bubobubo.web.HttpClientProxy.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   w  w  w . ja v  a  2 s  . c om*/
    //spec: RFC 2616, sec 4.3: either 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);

    try {
        // Execute the request
        if (doLog) {
            log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- "
                    + proxyRequest.getRequestLine().getUri());
        }

        proxyRequest.removeHeaders("authorization");
        if (targetUri.getUserInfo() != null && !targetUri.getUserInfo().equalsIgnoreCase("")
                && !targetUri.getUserInfo().equalsIgnoreCase(":")) {
            Credentials credentials = new UsernamePasswordCredentials(targetUri.getUserInfo().split(":")[0],
                    targetUri.getUserInfo().split(":")[1]);
            proxyClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
        }

        HttpResponse proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest);

        // Process the response
        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.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        copyResponseHeaders(proxyResponse, servletResponse);

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

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

@Override
public Future<ServerHeartbeatResponse> doHeartbeat(ServerHeartbeatRequest request) {
    HttpPost httpRequest = new HttpPost(buildSafe(createUri("/server/heartbeat")));
    initHeaders(httpRequest);/*from w ww  .j a  v  a  2s  .  c om*/
    httpRequest.setEntity(createEntity(request));

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

From source file:com.anaplan.client.transport.ApacheHttpProvider.java

/** {@inheritDoc} */
@Override//  w  ww  . j ava  2 s.  c o m
public void setServiceLocation(URI serviceLocation) throws AnaplanAPITransportException {

    super.setServiceLocation(serviceLocation);

    httpHost = URIUtils.extractHost(serviceLocation);
    httpContext = new BasicHttpContext();
    if (getServiceCredentials() != null) {
        // Set up the authorization again
        setServiceCredentials(getServiceCredentials());
    }
}

From source file:aiai.ai.Globals.java

@PostConstruct
public void init() throws GeneralSecurityException {
    if (publicKeyStr != null) {
        publicKey = SecUtils.getPublicKey(publicKeyStr);
    }//w ww. j  a  v a 2  s . c  om

    if (masterUsername != null && masterUsername.equals(restUsername)) {
        throw new IllegalStateException("masterUsername can't be the same as restUsername, masterUsername: "
                + masterUsername + ", restUsername: " + restUsername);
    }

    if (isSecureRestUrl) {

        if (isStationEnabled) {
            if (stationRestPassword == null) {
                throw new IllegalArgumentException(
                        "if aiai.secure-rest-url=true and aiai.station.enabled=true, then aiai.station.server-rest-password has to be not null");
            }
        }
    }

    final String restUrl = launchpadUrl + (isSecureRestUrl ? Consts.REST_AUTH_URL : Consts.REST_ANON_URL);

    serverRestUrl = restUrl + Consts.SERVER_REST_URL;
    payloadRestUrl = restUrl + Consts.PAYLOAD_REST_URL;
    uploadRestUrl = restUrl + Consts.UPLOAD_REST_URL;

    if (stationDir == null) {
        log.warn("Station is disabled, stationDir: {}, isStationEnabled: {}", stationDir, isStationEnabled);
        isStationEnabled = false;
    } else {
        stationSnippetDir = new File(stationDir, Consts.SNIPPET_DIR);
        stationSnippetDir.mkdirs();
        stationResourcesDir = new File(stationDir, Consts.RESOURCES_DIR);
        stationResourcesDir.mkdirs();
        stationTaskDir = new File(stationDir, Consts.TASK_DIR);
        stationTaskDir.mkdirs();

        timePeriods = TimePeriods.from(stationActiveTime);
    }

    if (isLaunchpadEnabled && launchpadDir == null) {
        log.warn("Launchpad is disabled, launchpadDir: {}, isLaunchpadEnabled: {}", launchpadDir,
                isLaunchpadEnabled);
        isLaunchpadEnabled = false;
    }

    if (isLaunchpadEnabled) {
        if (masterUsername == null || masterToken == null || masterPassword == null) {
            throw new IllegalArgumentException(
                    "if aiai.secure-rest-url=true, then aiai.master-username, aiai.master-token, and aiai.master-password have to be not null");
        }

        launchpadTempDir = new File(launchpadDir, "temp");
        launchpadTempDir.mkdirs();

        launchpadResourcesDir = new File(launchpadDir, Consts.RESOURCES_DIR);
        launchpadResourcesDir.mkdirs();

        try {
            launchpadHttpHostWithAuth = URIUtils.extractHost(new URL(launchpadUrl).toURI());
        } catch (Throwable th) {
            throw new IllegalArgumentException("Can't build HttpHost for " + launchpadUrl, th);
        }
    }
    //noinspection unused
    int i = 0;
}

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

public synchronized void start() throws IOException, OpenRDFException {
    running = true;// w w  w  .j a  va 2s  .co  m
    notifyAll();
    if (server != null) {
        try {
            logger.info("Callimachus is binding to {}", toString());
            for (SetupRealm origin : getRealms()) {
                HttpHost host = URIUtils.extractHost(java.net.URI.create(origin.getRealm()));
                HttpClientFactory.getInstance().setProxy(host, server);
            }
            for (CalliRepository repository : repositories.values()) {
                repository.setCompileRepository(true);
            }
            server.start();
            System.gc();
            Thread.yield();
            long uptime = ManagementFactory.getRuntimeMXBean().getUptime();
            logger.info("Callimachus started after {} seconds", uptime / 1000.0);
            if (listener != null) {
                listener.webServiceStarted(server);
            }
        } catch (IOException e) {
            logger.error(e.toString(), e);
        } catch (OpenRDFException e) {
            logger.error(e.toString(), e);
        }
    }
}