Example usage for org.apache.http.client.utils URIBuilder URIBuilder

List of usage examples for org.apache.http.client.utils URIBuilder URIBuilder

Introduction

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

Prototype

public URIBuilder() 

Source Link

Document

Constructs an empty instance.

Usage

From source file:org.nebula.framework.client.NebulaRestClient.java

private static String buildQueryString(Object object) throws Exception {

    Map<String, Object> map = convertValue(object, Map.class);

    URIBuilder builder = new URIBuilder();
    for (String key : map.keySet()) {
        Object value = map.get(key);
        if (value == null) {
            continue;
        } else if (value instanceof List) {
            List v = (List) value;
            for (int i = 0; i < v.size(); i++) {
                builder.addParameter(key + "[" + i + "]", v.get(i).toString());
            }//from   www.j  av  a  2s. c  o  m
        } else {
            builder.addParameter(key, map.get(key).toString());
        }
    }

    return builder.build().toString();
}

From source file:org.olat.modules.tu.TunnelMapper.java

@Override
public MediaResource handle(String relPath, HttpServletRequest hreq) {
    String method = hreq.getMethod();
    String uri = relPath;//  w w w.  j  a  v a 2  s  .  com
    HttpUriRequest meth = null;

    try {
        URIBuilder builder = new URIBuilder();
        builder.setScheme(proto).setHost(host).setPort(port.intValue());
        if (uri == null) {
            uri = (startUri == null) ? "" : startUri;
        }
        if (uri.length() > 0 && uri.charAt(0) != '/') {
            uri = "/" + uri;
        }
        if (StringHelper.containsNonWhitespace(uri)) {
            builder.setPath(uri);
        }

        if (method.equals("GET")) {
            String queryString = hreq.getQueryString();
            if (StringHelper.containsNonWhitespace(queryString)) {
                builder.setCustomQuery(queryString);
            }
            meth = new HttpGet(builder.build());
        } else if (method.equals("POST")) {
            Map<String, String[]> params = hreq.getParameterMap();
            HttpPost pmeth = new HttpPost(builder.build());
            List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
            for (String key : params.keySet()) {
                String vals[] = params.get(key);
                for (String val : vals) {
                    pairs.add(new BasicNameValuePair(key, val));
                }
            }

            HttpEntity entity = new UrlEncodedFormEntity(pairs, "UTF-8");
            pmeth.setEntity(entity);
            meth = pmeth;
        }

        // Add olat specific headers to the request, can be used by external
        // applications to identify user and to get other params
        // test page e.g. http://cgi.algonet.se/htbin/cgiwrap/ug/test.py
        if ("enabled".equals(
                CoreSpringFactory.getImpl(BaseSecurityModule.class).getUserInfosTunnelCourseBuildingBlock())) {
            User u = ident.getUser();
            meth.addHeader("X-OLAT-USERNAME", ident.getName());
            meth.addHeader("X-OLAT-LASTNAME", u.getProperty(UserConstants.LASTNAME, null));
            meth.addHeader("X-OLAT-FIRSTNAME", u.getProperty(UserConstants.FIRSTNAME, null));
            meth.addHeader("X-OLAT-EMAIL", u.getProperty(UserConstants.EMAIL, null));
            meth.addHeader("X-OLAT-USERIP", ipAddress);
        }

        HttpResponse response = httpClient.execute(meth);
        if (response == null) {
            // error
            return new NotFoundMediaResource(relPath);
        }

        // get or post successfully
        Header responseHeader = response.getFirstHeader("Content-Type");
        if (responseHeader == null) {
            // error
            EntityUtils.consumeQuietly(response.getEntity());
            return new NotFoundMediaResource(relPath);
        }
        return new HttpRequestMediaResource(response);
    } catch (ClientProtocolException e) {
        log.error("", e);
        return null;
    } catch (URISyntaxException e) {
        log.error("", e);
        return null;
    } catch (IOException e) {
        log.error("Error loading URI: " + (meth == null ? "???" : meth.getURI()), e);
        return null;
    }
}

From source file:org.wso2.security.tools.findsecbugs.scanner.NotificationManager.java

public static void notifyScanStatus(String status) throws NotificationManagerException {
    int i = 0;//from  ww  w . ja va2 s.c om
    while (i < 10) {
        try {
            URI uri = (new URIBuilder()).setHost(automationManagerHost).setPort(automationManagerPort)
                    .setScheme("http").setPath(SCAN_STATUS).addParameter("containerId", myContainerId)
                    .addParameter("status", status).build();
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpGet get = new HttpGet(uri);
            HttpResponse response = httpClient.execute(get);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                LOGGER.info("Notified successfully");
                return;
            } else {
                i++;
            }
            Thread.sleep(2000);
        } catch (URISyntaxException | InterruptedException | IOException e) {
            LOGGER.error("Error occurred while notifying the scan status to automation manager", e);
            i++;
        }
    }
    throw new NotificationManagerException("Error occurred while notifying status to Automation Manager");
}

From source file:com.github.dziga.orest.client.HttpRestClient.java

int Post(String body) throws URISyntaxException, IOException {
    URIBuilder b = new URIBuilder().setScheme(scheme).setHost(host).setPath(path);
    addQueryParams(b);//  w ww.jav a2s  . com
    URI fullUri = b.build();
    HttpPost postMethod = new HttpPost(fullUri);
    HttpEntity entity = new StringEntity(body);
    postMethod.setEntity(entity);
    postMethod = (HttpPost) addHeadersToMethod(postMethod);

    processResponse(httpClient.execute(postMethod));

    return getResponseCode();
}

From source file:Vdisk.java

public JSONObject get_user_info() throws IOException, URISyntaxException {
    URI uri = new URIBuilder().setScheme("https").setHost("api.weipan.cn/2/account/info")
            .setParameter("access_token", this.access_token).build();
    return vdisk_post_operation(uri);
}

From source file:com.m3958.apps.anonymousupload.integration.java.FileUploadTest.java

@Test
public void testPostNone() throws ClientProtocolException, IOException, URISyntaxException {

    File f = new File("README.md");

    Assert.assertTrue(f.exists());//from   www. ja  v  a2  s .c om

    String c = Request.Post(new URIBuilder().setScheme("http").setHost("localhost").setPort(8080).build())
            .body(MultipartEntityBuilder.create().addTextBody("fn", "abcfn.md").build()).execute()
            .returnContent().asString();

    String url = c.trim();
    Assert.assertEquals("1", url);

    testComplete();
}

From source file:com.cognifide.aet.proxy.RestProxyServer.java

@Override
public void addHeader(String name, String value) {
    CloseableHttpClient httpClient = HttpClients.createSystem();
    try {//from  w w  w . j a  v  a2 s  . co m
        URIBuilder uriBuilder = new URIBuilder().setScheme(HTTP).setHost(server.getAPIHost())
                .setPort(server.getAPIPort());
        // Request BMP to add header
        HttpPost request = new HttpPost(
                uriBuilder.setPath(String.format("/proxy/%d/headers", server.getProxyPort())).build());
        request.setHeader("Content-Type", "application/json");
        JSONObject json = new JSONObject();
        json.put(name, value);
        request.setEntity(new StringEntity(json.toString()));
        // Execute request
        CloseableHttpResponse response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != STATUS_CODE_OK) {
            throw new UnableToAddHeaderException(
                    "Invalid HTTP Response when attempting to add header" + statusCode);
        }
        response.close();
    } catch (Exception e) {
        throw new BMPCUnableToConnectException(String.format("Unable to connect to BMP Proxy at '%s:%s'",
                server.getAPIHost(), server.getAPIPort()), e);
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            LOGGER.warn("Unable to close httpClient", e);
        }
    }
}

From source file:com.blackducksoftware.tools.scmconnector.integrations.mercurial.MercurialConnector.java

/**
 * Constructs a valid HTTP url if a user *and* password is provided.
 *
 * @throws Exception//from  w w  w. j a  v  a 2 s .  c o m
 */
private void buildURL() throws Exception {
    if (StringUtils.isNotEmpty(user) && StringUtils.isNotEmpty(password)) {
        URL url = new URL(repositoryURL);
        String protocol = url.getProtocol();
        int port = url.getPort();
        String host = url.getHost();
        String path = url.getPath();

        URIBuilder builder = new URIBuilder();
        builder.setScheme(protocol);
        builder.setHost(host);
        builder.setPort(port);
        builder.setPath(path);
        builder.setUserInfo(user, password);

        repositoryURL = builder.toString();
        // log.info("Using path: " + repositoryURL); // Reveals password
    }
}

From source file:eu.fthevenet.util.github.GithubApi.java

/**
 * Returns a specific release from the specified repository.
 *
 * @param owner the repository's owner//from   w  ww  .  ja  va 2 s  .c  o m
 * @param repo  the repository's name
 * @param id    the id of the release to retrieve
 * @return An {@link Optional} that contains the specified release if it could be found.
 * @throws IOException        if an IO error occurs while communicating with GitHub.
 * @throws URISyntaxException if the crafted URI is incorrect.
 */
public Optional<GithubRelease> getRelease(String owner, String repo, String id)
        throws IOException, URISyntaxException {
    URIBuilder requestUrl = new URIBuilder().setScheme(URL_PROTOCOL).setHost(GITHUB_API_HOSTNAME)
            .setPath("/repos/" + owner + "/" + repo + "/releases/" + id);

    logger.debug(() -> "requestUrl = " + requestUrl);
    HttpGet httpget = new HttpGet(requestUrl.build());
    return Optional.ofNullable(httpClient.execute(httpget, new AbstractResponseHandler<GithubRelease>() {
        @Override
        public GithubRelease handleEntity(HttpEntity entity) throws IOException {
            return gson.fromJson(EntityUtils.toString(entity), GithubRelease.class);
        }
    }));
}

From source file:org.darkware.wpman.wpcli.WPCLI.java

/**
 * Update the local WP-CLI tool to the most recent version.
 *///from ww  w .j av  a 2  s.c  o  m
public static void update() {
    try {
        WPManager.log.info("Downloading new version of WP-CLI.");

        CloseableHttpClient httpclient = HttpClients.createDefault();

        URI pharURI = new URIBuilder().setScheme("http").setHost("raw.githubusercontent.com")
                .setPath("/wp-cli/builds/gh-pages/phar/wp-cli.phar").build();

        WPManager.log.info("Downloading from: {}", pharURI);
        HttpGet downloadRequest = new HttpGet(pharURI);

        CloseableHttpResponse response = httpclient.execute(downloadRequest);

        WPManager.log.info("Download response: {}", response.getStatusLine());
        WPManager.log.info("Download content type: {}", response.getFirstHeader("Content-Type").getValue());

        FileChannel wpcliFile = FileChannel.open(WPCLI.toolPath, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);

        response.getEntity().writeTo(Channels.newOutputStream(wpcliFile));
        wpcliFile.close();

        Set<PosixFilePermission> wpcliPerms = new HashSet<>();
        wpcliPerms.add(PosixFilePermission.OWNER_READ);
        wpcliPerms.add(PosixFilePermission.OWNER_WRITE);
        wpcliPerms.add(PosixFilePermission.OWNER_EXECUTE);
        wpcliPerms.add(PosixFilePermission.GROUP_READ);
        wpcliPerms.add(PosixFilePermission.GROUP_EXECUTE);

        Files.setPosixFilePermissions(WPCLI.toolPath, wpcliPerms);
    } catch (URISyntaxException e) {
        WPManager.log.error("Failure building URL for WPCLI download.", e);
        System.exit(1);
    } catch (IOException e) {
        WPManager.log.error("Error while downloading WPCLI client.", e);
        e.printStackTrace();
        System.exit(1);
    }
}