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

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

Introduction

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

Prototype

public URIBuilder addParameter(final String param, final String value) 

Source Link

Document

Adds parameter to URI query.

Usage

From source file:eu.eubrazilcc.lvl.storage.gravatar.Gravatar.java

public URL imageUrl() {
    try {/*from   ww  w. j  a v  a 2  s. c o  m*/
        final URIBuilder uriBuilder = new URIBuilder(
                (secure ? SECURE_URL_BASE : DEFAULT_URL_BASE) + emailHash(email)).addParameter("s",
                        Integer.toString(imageSize));
        if (imageRating != Rating.GENERAL_AUDIENCES) {
            uriBuilder.addParameter("r", imageRating.getCode());
        }
        if (defaultImage != DefaultImage.DEFAULT) {
            uriBuilder.addParameter("d", defaultImage.getCode());
        }
        return uriBuilder.build().toURL();
    } catch (Exception e) {
        throw new IllegalStateException("Failed to get Gravatar image URL", e);
    }
}

From source file:com.geoxp.oss.client.OSSClient.java

public static void genSecret(String ossURL, String secretName, String sshKeyFingerprint) throws OSSException {

    SSHAgentClient agent = null;//from   w  ww.j  av  a  2  s .co m

    HttpClient httpclient = null;

    try {

        agent = new SSHAgentClient();

        List<SSHKey> sshkeys = agent.requestIdentities();

        //
        // If no SSH Key fingerprint was provided, try all SSH keys available in the agent
        //

        List<String> fingerprints = new ArrayList<String>();

        if (null == sshKeyFingerprint) {
            for (SSHKey key : sshkeys) {
                fingerprints.add(key.fingerprint);
            }
        } else {
            fingerprints.add(sshKeyFingerprint.toLowerCase().replaceAll("[^0-9a-f]", ""));
        }

        int idx = 0;

        for (String fingerprint : fingerprints) {
            idx++;

            //
            // Check if the signing key is available in the agent
            //

            byte[] keyblob = null;

            for (SSHKey key : sshkeys) {
                if (key.fingerprint.equals(fingerprint)) {
                    keyblob = key.blob;
                    break;
                }
            }

            //
            // Throw an exception if this condition is encountered as it can only happen if
            // there was a provided fingerprint which is not in the agent.
            //

            if (null == keyblob) {
                throw new OSSException("SSH Key " + sshKeyFingerprint + " was not found by your SSH agent.");
            }

            //
            // Build OSS Token
            //
            // <TS> <SECRET_NAME> <SSH Signing Key Blob> <SSH Signature Blob>
            //

            ByteArrayOutputStream token = new ByteArrayOutputStream();

            byte[] tsdata = nowBytes();

            token.write(CryptoHelper.encodeNetworkString(tsdata));

            token.write(CryptoHelper.encodeNetworkString(secretName.getBytes("UTF-8")));

            token.write(CryptoHelper.encodeNetworkString(keyblob));

            //
            // Generate signature
            //

            byte[] sigblob = agent.sign(keyblob, token.toByteArray());

            token.write(CryptoHelper.encodeNetworkString(sigblob));

            String b64token = new String(Base64.encode(token.toByteArray()), "UTF-8");

            //
            // Send request
            //

            httpclient = newHttpClient();

            URIBuilder builder = new URIBuilder(ossURL + GuiceServletModule.SERVLET_PATH_GEN_SECRET);

            builder.addParameter("token", b64token);

            URI uri = builder.build();

            String qs = uri.getRawQuery();

            HttpPost post = new HttpPost(
                    uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + uri.getPath());

            post.setHeader("Content-Type", "application/x-www-form-urlencoded");

            post.setEntity(new StringEntity(qs));

            HttpResponse response = httpclient.execute(post);
            post.reset();

            if (HttpServletResponse.SC_OK != response.getStatusLine().getStatusCode()) {
                // Only throw an exception if this is the last SSH key we could try
                if (idx == fingerprints.size()) {
                    throw new OSSException("None of the provided keys (" + idx
                            + ") could be used to generate secret. Latest error message was: "
                            + response.getStatusLine().getReasonPhrase());
                } else {
                    continue;
                }
            }

            return;
        }
    } catch (OSSException osse) {
        throw osse;
    } catch (Exception e) {
        throw new OSSException(e);
    } finally {
        if (null != httpclient) {
            httpclient.getConnectionManager().shutdown();
        }
        if (null != agent) {
            agent.close();
        }
    }
}

From source file:com.msopentech.odatajclient.engine.uri.ODataURIBuilder.java

/**
 * Build OData URI./*  w  ww.  jav a 2s . c o  m*/
 *
 * @return OData URI.
 */
public URI build() {
    final StringBuilder segmentsBuilder = new StringBuilder();
    for (Segment seg : segments) {
        if (segmentsBuilder.length() > 0 && seg.type != SegmentType.KEY) {
            segmentsBuilder.append('/');
        }

        segmentsBuilder.append(seg.value);
    }

    try {
        final URIBuilder builder = new URIBuilder(segmentsBuilder.toString());

        for (Map.Entry<String, String> option : queryOptions.entrySet()) {
            builder.addParameter("$" + option.getKey(), option.getValue());
        }

        return builder.build().normalize();
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Could not build valid URI", e);
    }
}

From source file:com.seleniumtests.connectors.selenium.SeleniumRobotGridConnector.java

/**
 * In case an app is required on the node running the test, upload it to the grid hub
 * This will then be made available through HTTP GET URL to the node (appium will receive an url instead of a file)
 * /*from  w  w  w .  j a  v  a  2s . co  m*/
 */
@Override
public void uploadMobileApp(Capabilities caps) {

    String appPath = (String) caps.getCapability(MobileCapabilityType.APP);

    // check whether app is given and app path is a local file
    if (appPath != null && new File(appPath).isFile()) {

        try (CloseableHttpClient client = HttpClients.createDefault();) {
            // zip file
            List<File> appFiles = new ArrayList<>();
            appFiles.add(new File(appPath));
            File zipFile = FileUtility.createZipArchiveFromFiles(appFiles);

            HttpHost serverHost = new HttpHost(hubUrl.getHost(), hubUrl.getPort());
            URIBuilder builder = new URIBuilder();
            builder.setPath("/grid/admin/FileServlet/");
            builder.addParameter("output", "app");
            HttpPost httpPost = new HttpPost(builder.build());
            httpPost.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.OCTET_STREAM.toString());
            FileInputStream fileInputStream = new FileInputStream(zipFile);
            InputStreamEntity entity = new InputStreamEntity(fileInputStream);
            httpPost.setEntity(entity);

            CloseableHttpResponse response = client.execute(serverHost, httpPost);
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new SeleniumGridException(
                        "could not upload application file: " + response.getStatusLine().getReasonPhrase());
            } else {
                // set path to the mobile application as an URL on the grid hub
                ((DesiredCapabilities) caps).setCapability(MobileCapabilityType.APP,
                        IOUtils.toString(response.getEntity().getContent()) + "/" + appFiles.get(0).getName());
            }

        } catch (IOException | URISyntaxException e) {
            throw new SeleniumGridException("could not upload application file", e);
        }
    }
}

From source file:org.talend.dataprep.api.service.command.preparation.PreparationList.java

private HttpRequestBase onExecute(Sort sort, Order order, Format format) {
    try {//from w  ww  .  j av a  2 s  . c om
        URIBuilder uriBuilder;
        if (Format.SHORT.equals(format)) {
            uriBuilder = new URIBuilder(preparationServiceUrl + "/preparations"); //$NON-NLS-1$
        } else if (Format.SUMMARY.equals(format)) {
            uriBuilder = new URIBuilder(preparationServiceUrl + "/preparations/summaries"); //$NON-NLS-1$
        } else {
            uriBuilder = new URIBuilder(preparationServiceUrl + "/preparations/details"); //$NON-NLS-1$
        }

        uriBuilder.addParameter("sort", sort.camelName());
        uriBuilder.addParameter("order", order.camelName());
        return new HttpGet(uriBuilder.build());
    } catch (URISyntaxException e) {
        throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
    }
}

From source file:org.sahli.asciidoc.confluence.publisher.client.http.HttpRequestFactory.java

HttpGet getChildPagesByIdRequest(String parentContentId, Integer limit, Integer start, String expandOptions) {
    assertMandatoryParameter(isNotBlank(parentContentId), "parentContentId");
    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setPath(this.confluenceRestApiEndpoint + "/content/" + parentContentId + "/child/page");

    if (limit != null) {
        uriBuilder.addParameter("limit", limit.toString());
    }/*from w w w  . j  av a2s . c  o m*/
    if (start != null) {
        uriBuilder.addParameter("start", start.toString());
    }
    if (isNotBlank(expandOptions)) {
        uriBuilder.addParameter("expand", expandOptions);
    }

    HttpGet getChildPagesByIdRequest;
    try {
        getChildPagesByIdRequest = new HttpGet(uriBuilder.build().toString());
    } catch (URISyntaxException e) {
        throw new RuntimeException("Invalid URL", e);
    }

    return getChildPagesByIdRequest;
}

From source file:org.sahli.asciidoc.confluence.publisher.client.http.HttpRequestFactory.java

public HttpGet getAttachmentsRequest(String contentId, Integer limit, Integer start, String expandOptions) {
    assertMandatoryParameter(isNotBlank(contentId), "contentId");
    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setPath(this.confluenceRestApiEndpoint + "/content/" + contentId + "/child/attachment");

    if (limit != null) {
        uriBuilder.addParameter("limit", limit.toString());
    }//from w w  w  .j  a  v a 2s.  co m
    if (start != null) {
        uriBuilder.addParameter("start", start.toString());
    }
    if (isNotBlank(expandOptions)) {
        uriBuilder.addParameter("expand", expandOptions);
    }

    HttpGet getAttachmentsRequest;
    try {
        getAttachmentsRequest = new HttpGet(uriBuilder.build().toString());
    } catch (URISyntaxException e) {
        throw new RuntimeException("Invalid URL", e);
    }

    return getAttachmentsRequest;
}

From source file:de.rwth.dbis.acis.activitytracker.service.ActivityTrackerService.java

public HttpResponse addPaginationToHtppResponse(PaginationResult paginationResult, String path,
        Map<String, String> httpParameter, HttpResponse httpResponse) throws URISyntaxException {
    httpResponse.setHeader("X-Limit", String.valueOf(paginationResult.getPageable().getLimit()));

    if (paginationResult.getPageable().getSortDirection() == Pageable.SortDirection.ASC) {
        if (paginationResult.getPrevCursor() != -1) {
            httpResponse.setHeader("X-Cursor-Before", String.valueOf(paginationResult.getPrevCursor()));
        }// w w  w .j av a2 s  . c  o  m
        if (paginationResult.getNextCursor() != -1) {
            httpResponse.setHeader("X-Cursor-After", String.valueOf(paginationResult.getNextCursor()));
        }
    } else {
        if (paginationResult.getNextCursor() != -1) {
            httpResponse.setHeader("X-Cursor-Before", String.valueOf(paginationResult.getNextCursor()));
        }
        if (paginationResult.getPrevCursor() != -1) {
            httpResponse.setHeader("X-Cursor-After", String.valueOf(paginationResult.getPrevCursor()));
        }
    }

    URIBuilder uriBuilder = new URIBuilder(baseURL + path);
    for (Map.Entry<String, String> entry : httpParameter.entrySet()) {
        uriBuilder.addParameter(entry.getKey(), entry.getValue());
    }
    String links = new String();
    if (paginationResult.getPageable().getSortDirection() == Pageable.SortDirection.ASC) {
        if (paginationResult.getPrevCursor() != -1) {
            URIBuilder uriBuilderTemp = new URIBuilder(uriBuilder.build());
            links = links.concat("<" + uriBuilderTemp
                    .addParameter("before", String.valueOf(paginationResult.getPrevCursor())).build()
                    + ">; rel=\"prev\",");
        }
        if (paginationResult.getNextCursor() != -1) {
            URIBuilder uriBuilderTemp = new URIBuilder(uriBuilder.build());
            links = links.concat(
                    "<" + uriBuilderTemp.addParameter("after", String.valueOf(paginationResult.getNextCursor()))
                            .build() + ">; rel=\"next\"");
        }
    } else {
        if (paginationResult.getNextCursor() != -1) {
            URIBuilder uriBuilderTemp = new URIBuilder(uriBuilder.build());
            links = links.concat("<" + uriBuilderTemp
                    .addParameter("before", String.valueOf(paginationResult.getNextCursor())).build()
                    + ">; rel=\"prev\",");
        }
        if (paginationResult.getPrevCursor() != -1) {
            URIBuilder uriBuilderTemp = new URIBuilder(uriBuilder.build());
            links = links.concat(
                    "<" + uriBuilderTemp.addParameter("after", String.valueOf(paginationResult.getPrevCursor()))
                            .build() + ">; rel=\"next\"");
        }
    }

    httpResponse.setHeader("Link", links);
    return httpResponse;
}

From source file:org.jasig.portlet.proxy.service.web.HttpContentServiceImpl.java

protected HttpUriRequest getHttpRequest(HttpContentRequestImpl proxyRequest, PortletRequest request) {
    final HttpUriRequest httpRequest;

    // if this is a form request, we may need to use a POST or add form parameters
    if (proxyRequest.isForm()) {

        // handle POST form request
        final Map<String, IFormField> params = proxyRequest.getParameters();
        if ("POST".equalsIgnoreCase(proxyRequest.getMethod())) {

            final List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            for (Map.Entry<String, IFormField> param : params.entrySet()) {
                for (String value : param.getValue().getValues()) {
                    if (value != null) {
                        pairs.add(new BasicNameValuePair(param.getKey(), value));
                    }//  w  w w. j  av  a  2s .c o m
                }
            }

            // construct a new POST request and set the form data
            try {
                httpRequest = new HttpPost(proxyRequest.getProxiedLocation());
                if (pairs.size() > 0) {
                    ((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
                }
            } catch (UnsupportedEncodingException e) {
                log.error("Failed to encode form parameters", e);
                throw new RuntimeException(e);
            }

        }

        // handle GET form requests
        else {

            try {

                // build a URL including any passed form parameters
                final URIBuilder builder = new URIBuilder(proxyRequest.getProxiedLocation());
                for (Map.Entry<String, IFormField> param : params.entrySet()) {
                    for (String value : param.getValue().getValues()) {
                        builder.addParameter(param.getKey(), value);
                    }
                }
                final URI uri = builder.build();
                httpRequest = new HttpGet(uri);

            } catch (URISyntaxException e) {
                log.error("Failed to build URI for proxying", e);
                throw new RuntimeException(e);
            }

        }

    }

    // not a form, simply a normal get request
    else {
        log.debug("Submitting a GET request to proxied location [{}]", proxyRequest.getProxiedLocation());
        httpRequest = new HttpGet(proxyRequest.getProxiedLocation());
    }

    // set any configured request headers
    for (Map.Entry<String, String> header : proxyRequest.getHeaders().entrySet()) {
        httpRequest.setHeader(header.getKey(), header.getValue());
    }

    return httpRequest;
}

From source file:eu.esdihumboldt.hale.io.geoserver.rest.AbstractResourceManager.java

private URI buildRequestUri(String url, Map<String, String> parameters) throws URISyntaxException {

    URIBuilder uriBuilder = new URIBuilder(url);
    if (parameters != null) {
        parameters.forEach((param, value) -> uriBuilder.addParameter(param, value));
    }/*from   www  .j  ava2 s  .  c o  m*/

    return uriBuilder.build();
}