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<NoticeResponse> createNotice(NoticeRequest request) {
    HttpPost httpRequest = new HttpPost(buildSafe(createUri("/notices")));
    initHeaders(httpRequest);/*from  w  w  w . java2s .c  om*/
    httpRequest.setEntity(createEntity(request));

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

From source file:org.callimachusproject.repository.SparqlServiceCredentialManager.java

private synchronized Credentials getCredentials(String serviceUrl, String base)
        throws OpenRDFException, IOException {
    String origin = getOrigin(base);
    CalliRepository repository = repositories.get(origin);
    if (repository == null)
        return null;
    CredentialsProvider provider = repository.getRealm(base).getCredentialsProvider();
    if (provider == null)
        return null;
    HttpHost authority = URIUtils.extractHost(URI.create(serviceUrl));
    Credentials credential = provider.getCredentials(new AuthScope(authority));
    if (credential != null) {
        credentials.get(repository).add(credential);
    }/*from  w  w w  .  j  a va2 s. c  om*/
    return credential;
}

From source file:org.sonar.runner.Main.java

private int executeTask() {
    Stats stats = new Stats().start();
    try {// w  w w.  j av  a 2 s . co  m
        if (cli.isDisplayStackTrace()) {
            Logs.info("Error stacktraces are turned on.");
        }
        runnerFactory.create(conf.properties()).execute();

    } catch (Exception e) {
        displayExecutionResult(stats, "FAILURE");
        showError("Error during Sonar runner execution", e, cli.isDisplayStackTrace());
        return Exit.ERROR;
    }

    // add permission to buildUserId
    try {
        String buildUserId = System.getProperty("build.user.id");
        Properties props = conf.properties();
        String login = props.getProperty("sonar.login");

        String hostUrl = (String) props.get("sonar.host.url");
        Map<String, String> env = System.getenv();

        String password = SonarContext.getInstance(props).getSonarPassword();
        String project_key = props.getProperty("sonar.projectKey");
        String command;
        Process proc;
        BufferedReader reader;
        String line = "";
        //String tid = (new Long(Thread.currentThread())).toString();
        String tid = String.valueOf(Thread.currentThread().getId());
        String cookie = "cookie-" + Long.toString(new SecureRandom().nextLong());

        // login
        HttpPost httpRequest;
        ArrayList<BasicNameValuePair> postParameters = new ArrayList<BasicNameValuePair>();

        String reqUrl = URIUtils.extractHost(new URI(hostUrl)).toString() + "/dologin";
        httpRequest = new HttpPost(reqUrl);
        postParameters.clear();
        postParameters.add(new BasicNameValuePair("username", login));
        postParameters.add(new BasicNameValuePair("password", password));
        httpRequest.setEntity(new UrlEncodedFormEntity(postParameters));
        doRequest(httpRequest);
        Logs.info("Login succeed");

        //user permission remove anyone
        reqUrl = hostUrl + "/api/permissions/remove"; //permission=user&group=anyone&component=" + project_key ;
        httpRequest = new HttpPost(reqUrl);
        postParameters.clear();
        postParameters.add(new BasicNameValuePair("permission", "user"));
        postParameters.add(new BasicNameValuePair("group", "anyone"));
        postParameters.add(new BasicNameValuePair("component", project_key));
        httpRequest.setEntity(new UrlEncodedFormEntity(postParameters));
        doRequest(httpRequest);
        Logs.info("Removed permission 'user' from group anyone");

        //user permission to sonar-users
        reqUrl = hostUrl + "/api/permissions/add"; //?permission=user&group=sonar-users&component=" + project_key;
        httpRequest = new HttpPost(reqUrl);
        postParameters.clear();
        postParameters.add(new BasicNameValuePair("permission", "user"));
        postParameters.add(new BasicNameValuePair("group", "sonar-users"));
        postParameters.add(new BasicNameValuePair("component", project_key));
        httpRequest.setEntity(new UrlEncodedFormEntity(postParameters));
        doRequest(httpRequest);
        Logs.info("Added permission 'user' to group sonar-users");

        //admin permission to sonar-administrators
        reqUrl = hostUrl + "/api/permissions/add"; //?permission=admin&group=sonar-administrators&component=" + project_key + "'";
        httpRequest = new HttpPost(reqUrl);
        postParameters.clear();
        postParameters.add(new BasicNameValuePair("permission", "admin"));
        postParameters.add(new BasicNameValuePair("group", "sonar-administrators"));
        postParameters.add(new BasicNameValuePair("component", project_key));
        httpRequest.setEntity(new UrlEncodedFormEntity(postParameters));
        doRequest(httpRequest);
        Logs.info("Added permission 'admin' to group sonar-administrators");

        //admin permission to self
        reqUrl = hostUrl + "/api/permissions/add"; //?permission=admin&user=" + buildUserId + "&component=" + project_key + "'";
        httpRequest = new HttpPost(reqUrl);
        postParameters.clear();
        postParameters.add(new BasicNameValuePair("permission", "admin"));
        postParameters.add(new BasicNameValuePair("user", buildUserId));
        postParameters.add(new BasicNameValuePair("component", project_key));
        httpRequest.setEntity(new UrlEncodedFormEntity(postParameters));
        doRequest(httpRequest);
        Logs.info("Added permission 'admin' to user " + buildUserId);

        //codeviewer permission to self, maybe unnecessary
        reqUrl = hostUrl + "/api/permissions/add"; //?permission=codeviewer&user=" + buildUserId + "&component=" + project_key;
        httpRequest = new HttpPost(reqUrl);
        postParameters.clear();
        postParameters.add(new BasicNameValuePair("permission", "codeviewer"));
        postParameters.add(new BasicNameValuePair("user", buildUserId));
        postParameters.add(new BasicNameValuePair("component", project_key));
        httpRequest.setEntity(new UrlEncodedFormEntity(postParameters));
        doRequest(httpRequest);
        Logs.info("Added permission 'codeviewer' to user " + buildUserId);

        //remove codeviewer permission from anyone
        reqUrl = hostUrl + "/api/permissions/remove"; //?permission=codeviewer&group=anyone&component=" + project_key + "'";
        httpRequest = new HttpPost(reqUrl);
        postParameters.clear();
        postParameters.add(new BasicNameValuePair("permission", "codeviewer"));
        postParameters.add(new BasicNameValuePair("group", "anyone"));
        postParameters.add(new BasicNameValuePair("component", project_key));
        httpRequest.setEntity(new UrlEncodedFormEntity(postParameters));
        doRequest(httpRequest);
        Logs.info("Removed permission 'codeviewer' from group anyone");

    } catch (Exception e) {
        showError("Error during Sonar runner execution", e, cli.isDisplayStackTrace());
        return Exit.ERROR;
    }

    displayExecutionResult(stats, "SUCCESS");
    return Exit.SUCCESS;
}

From source file:com.minws.frame.sdk.webqq.service.ApacheHttpService.java

/** {@inheritDoc} */
@Override//w  w w  .  jav  a2s  .c  o m
public Future<QQHttpResponse> executeHttpRequest(QQHttpRequest request, QQHttpListener listener)
        throws QQException {
    try {
        URI uri = URI.create(request.getUrl());

        if (request.getMethod().equals("POST")) {
            HttpPost httppost = new HttpPost(uri);
            HttpHost httphost = URIUtils.extractHost(uri);
            if (httphost == null) {
                LOG.error("host is null, url: " + uri.toString());
                httphost = new HttpHost(uri.getHost());
            }

            if (request.getReadTimeout() > 0) {
                HttpConnectionParams.setSoTimeout(httppost.getParams(), request.getReadTimeout());
            }
            if (request.getConnectTimeout() > 0) {
                HttpConnectionParams.setConnectionTimeout(httppost.getParams(), request.getConnectTimeout());
            }

            if (request.getFileMap().size() > 0) {
                MultipartEntity entity = new MultipartEntity();
                String charset = request.getCharset();

                Map<String, String> postMap = request.getPostMap();
                for (String key : postMap.keySet()) {
                    String value = postMap.get(key);
                    value = value == null ? "" : value;
                    entity.addPart(key, new StringBody(value, Charset.forName(charset)));
                }

                Map<String, File> fileMap = request.getFileMap();
                for (String key : fileMap.keySet()) {
                    File value = fileMap.get(key);
                    entity.addPart(new FormBodyPart(key, new FileBody(value, getMimeType(value))));
                }
                httppost.setEntity(entity);
            } else if (request.getPostMap().size() > 0) {
                List<NameValuePair> list = new ArrayList<NameValuePair>();

                Map<String, String> postMap = request.getPostMap();
                for (String key : postMap.keySet()) {
                    String value = postMap.get(key);
                    value = value == null ? "" : value;
                    list.add(new BasicNameValuePair(key, value));
                }
                httppost.setEntity(new UrlEncodedFormEntity(list, request.getCharset()));
            }
            Map<String, String> headerMap = request.getHeaderMap();
            for (String key : headerMap.keySet()) {
                httppost.addHeader(key, headerMap.get(key));
            }
            QQHttpPostRequestProducer producer = new QQHttpPostRequestProducer(httphost, httppost, listener);
            QQHttpResponseConsumer consumer = new QQHttpResponseConsumer(request, listener, cookieJar);
            QQHttpResponseCallback callback = new QQHttpResponseCallback(listener);
            Future<QQHttpResponse> future = asyncHttpClient.execute(producer, consumer, callback);
            return new ProxyFuture(future, consumer, producer);

        } else if (request.getMethod().equals("GET")) {
            HttpGet httpget = new HttpGet(uri);
            HttpHost httphost = URIUtils.extractHost(uri);
            if (httphost == null) {
                LOG.error("host is null, url: " + uri.toString());
                httphost = new HttpHost(uri.getHost());
            }
            Map<String, String> headerMap = request.getHeaderMap();
            for (String key : headerMap.keySet()) {
                httpget.addHeader(key, headerMap.get(key));
            }
            if (request.getReadTimeout() > 0) {
                HttpConnectionParams.setSoTimeout(httpget.getParams(), request.getReadTimeout());
            }
            if (request.getConnectTimeout() > 0) {
                HttpConnectionParams.setConnectionTimeout(httpget.getParams(), request.getConnectTimeout());
            }

            return asyncHttpClient.execute(new QQHttpGetRequestProducer(httphost, httpget),
                    new QQHttpResponseConsumer(request, listener, cookieJar),
                    new QQHttpResponseCallback(listener));

        } else {
            throw new QQException(QQErrorCode.IO_ERROR, "not support http method:" + request.getMethod());
        }
    } catch (IOException e) {
        throw new QQException(QQErrorCode.IO_ERROR);
    }
}

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

@Override
public Future<NoticeResponse> updateNotice(NoticeRequest request) {
    HttpPut httpRequest = new HttpPut(buildSafe(createUri("/notice/" + request.getId())));
    initHeaders(httpRequest);//from   ww  w .  j a  v a2  s  .c o  m
    httpRequest.setEntity(createEntity(request));

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

From source file:io.mapzone.controller.vm.http.HttpRequestForwarder.java

public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, URISyntaxException {
    targetUriObj = new URI(targetUri.get());
    targetHost = URIUtils.extractHost(targetUriObj);

    // Make the Request
    // note: we won't transfer the protocol version because I'm not sure it would
    // truly be compatible
    String method = request.getMethod();
    String proxyRequestUri = rewriteUrlFromRequest(request);

    // 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);
        // Add the input entity (streamed)
        // note: we don't bother ensuring we close the servletInputStream since
        // the container handles it
        eProxyRequest.setEntity(new InputStreamEntity(request.getInputStream(), request.getContentLength()));
        proxyRequest = eProxyRequest;//from  w  w w  .  j  a  va2  s . com
    } else {
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
    }

    copyRequestHeaders(request);

    setXForwardedForHeader(request);

    // Execute the request
    try {
        active.set(this);

        log.debug("REQUEST " + "[" + StringUtils.right(Thread.currentThread().getName(), 2) + "] " + method
                + ": " + request.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri());
        proxyResponse = proxyClient.execute(targetHost, proxyRequest);
    } 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 {
        active.set(null);
    }
    // Note: Don't need to close servlet outputStream:
    // http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter
}

From source file:eionet.webq.service.CDREnvelopeServiceImpl.java

@Override
public String submitRequest(UserFile file, String uri, String body) throws URISyntaxException {
    HttpHeaders authorization = new HttpHeaders();
    // use user provided auth info only when the remote file is in the same host as UserFile.
    LOGGER.info(URIUtils.extractHost(new URI(uri)));
    if (URIUtils.extractHost(new URI(uri)).equals(URIUtils.extractHost(new URI(file.getEnvelope())))) {
        authorization = getAuthorizationHeader(file);
    }// w  w  w  . j  a  v a2 s .c  o m
    HttpEntity<String> httpEntity = new HttpEntity<String>(body, authorization);
    return restOperations.postForObject(new URI(uri), httpEntity, String.class);
}

From source file:httpmultiplexer.httpproxy.ProxyServlet.java

protected void initTarget() throws ServletException {
    targetUri = Config.getParam("main", P_TARGET_URI, "None");
    if ("None".equals(targetUri)) {
        throw new ServletException(P_TARGET_URI + " is required.");
    }//w  w w .  jav a2 s . c om
    //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);

    // second one
    secondTargetUri = Config.getParam("main", P_2NDTARGET_URI, "None");
    if ("None".equals(secondTargetUri)) {
        throw new ServletException(P_2NDTARGET_URI + " is required.");
    }
    //test it's valid
    try {
        secondTargetUriObj = new URI(secondTargetUri);
    } catch (Exception e) {
        throw new ServletException("Trying to process targetUri init parameter: " + e, e);
    }
    secondTargetHost = URIUtils.extractHost(secondTargetUriObj);

}

From source file:org.apache.karaf.cellar.http.balancer.CellarBalancerProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    String location = locations.get(new Random().nextInt(locations.size()));
    URI locationUri = URI.create(location);
    HttpHost host = URIUtils.extractHost(locationUri);

    LOGGER.debug("CELLAR HTTP BALANCER: proxying to");
    LOGGER.debug("CELLAR HTTP BALANCER:     URI: {}", locationUri);
    LOGGER.debug("CELLAR HTTP BALANCER:     Host: {}", host);

    // 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();
    LOGGER.debug("CELLAR HTTP BALANCER:     Method: {}", method);
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest, location);
    LOGGER.debug("CELLAR HTTP BALANCER:     Proxy Request URI: {}", proxyRequestUri);
    HttpRequest proxyRequest;//from   w  ww.  ja  v a2 s. c  om
    //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);

    LOGGER.debug("CELLAR HTTP BALANCER:     copying request headers");
    copyRequestHeaders(servletRequest, proxyRequest, host);

    LOGGER.debug("CELLAR HTTP BALANCER:     set X-Forwarded header");
    setXForwardedForHeader(servletRequest, proxyRequest);

    HttpResponse proxyResponse = null;
    try {
        // Execute the request
        LOGGER.debug("CELLAR HTTP BALANCER:     executing proxy request");
        proxyResponse = proxyClient.execute(host, proxyRequest);

        // Process the response
        int statusCode = proxyResponse.getStatusLine().getStatusCode();
        LOGGER.debug("CELLAR HTTP BALANCER:     status code: {}", statusCode);

        // copying response headers to make sure SESSIONID or other Cookie which comes from remote server
        // will be saved in client when the proxied url was redirected to another one.
        // see issue [#51](https://github.com/mitre/HTTP-Proxy-Servlet/issues/51)
        LOGGER.debug("CELLAR HTTP BALANCER:     copying response headers");
        copyResponseHeaders(proxyResponse, servletRequest, servletResponse);

        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode,
                location)) {
            //the response is already "committed" now without any body to send
            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
        LOGGER.debug("CELLAR HTTP BALANCER:     set response status code");
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        // Send the content to the client
        LOGGER.debug("CELLAR HTTP BALANCER:     copying response entity");
        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:xyz.cloudbans.client.DefaultClient.java

@Override
public Future<NoticeResponse> deleteNotice(UUID noticeId) {
    HttpDelete httpRequest = new HttpDelete(buildSafe(createUri("/notice/" + noticeId)));
    initHeaders(httpRequest);/*from   w  ww.  j  a v  a2  s  .c o  m*/

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