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:org.elasticsearch.client.RestClientSingleHostTests.java

private HttpUriRequest performRandomRequest(String method) throws Exception {
    String uriAsString = "/" + randomStatusCode(getRandom());
    URIBuilder uriBuilder = new URIBuilder(uriAsString);
    final Map<String, String> params = new HashMap<>();
    boolean hasParams = randomBoolean();
    if (hasParams) {
        int numParams = randomIntBetween(1, 3);
        for (int i = 0; i < numParams; i++) {
            String paramKey = "param-" + i;
            String paramValue = randomAsciiOfLengthBetween(3, 10);
            params.put(paramKey, paramValue);
            uriBuilder.addParameter(paramKey, paramValue);
        }/*from   www  .ja  va2  s.  com*/
    }
    if (randomBoolean()) {
        //randomly add some ignore parameter, which doesn't get sent as part of the request
        String ignore = Integer.toString(randomFrom(RestClientTestUtil.getAllErrorStatusCodes()));
        if (randomBoolean()) {
            ignore += "," + Integer.toString(randomFrom(RestClientTestUtil.getAllErrorStatusCodes()));
        }
        params.put("ignore", ignore);
    }
    URI uri = uriBuilder.build();

    HttpUriRequest request;
    switch (method) {
    case "DELETE":
        request = new HttpDeleteWithEntity(uri);
        break;
    case "GET":
        request = new HttpGetWithEntity(uri);
        break;
    case "HEAD":
        request = new HttpHead(uri);
        break;
    case "OPTIONS":
        request = new HttpOptions(uri);
        break;
    case "PATCH":
        request = new HttpPatch(uri);
        break;
    case "POST":
        request = new HttpPost(uri);
        break;
    case "PUT":
        request = new HttpPut(uri);
        break;
    case "TRACE":
        request = new HttpTrace(uri);
        break;
    default:
        throw new UnsupportedOperationException("method not supported: " + method);
    }

    HttpEntity entity = null;
    boolean hasBody = request instanceof HttpEntityEnclosingRequest && getRandom().nextBoolean();
    if (hasBody) {
        entity = new StringEntity(randomAsciiOfLengthBetween(10, 100), ContentType.APPLICATION_JSON);
        ((HttpEntityEnclosingRequest) request).setEntity(entity);
    }

    Header[] headers = new Header[0];
    final Set<String> uniqueNames = new HashSet<>();
    if (randomBoolean()) {
        headers = RestClientTestUtil.randomHeaders(getRandom(), "Header");
        for (Header header : headers) {
            request.addHeader(header);
            uniqueNames.add(header.getName());
        }
    }
    for (Header defaultHeader : defaultHeaders) {
        // request level headers override default headers
        if (uniqueNames.contains(defaultHeader.getName()) == false) {
            request.addHeader(defaultHeader);
        }
    }

    try {
        if (hasParams == false && hasBody == false && randomBoolean()) {
            restClient.performRequest(method, uriAsString, headers);
        } else if (hasBody == false && randomBoolean()) {
            restClient.performRequest(method, uriAsString, params, headers);
        } else {
            restClient.performRequest(method, uriAsString, params, entity, headers);
        }
    } catch (ResponseException e) {
        //all good
    }
    return request;
}

From source file:com.qwazr.crawler.web.manager.WebCrawlThread.java

/**
 * Remove any query parameter which match the parameters_matcher list
 *
 * @param uriBuilder/* ww w. j a va  2s . co m*/
 */
private void checkRemoveParameter(URIBuilder uriBuilder) {
    if (parametersMatcherList == null || parametersMatcherList.isEmpty())
        return;
    List<NameValuePair> oldParams = uriBuilder.getQueryParams();
    if (oldParams == null || oldParams.isEmpty())
        return;
    uriBuilder.clearParameters();
    for (NameValuePair param : oldParams)
        if (!checkRegExpMatcher(param.getName() + "=" + param.getValue(), parametersMatcherList))
            uriBuilder.addParameter(param.getName(), param.getValue());
}

From source file:de.ii.xtraplatform.ogc.api.wfs.client.WFSAdapter.java

public String getRequestUrl(WfsOperation operation) {
    try {//from  www  . j a  v  a  2s. com
        URIBuilder uri = new URIBuilder(findUrl(operation.getOperation(), WFS.METHOD.GET));

        Map<String, String> params = operation.asKvp(new XMLDocumentFactory(nsStore), versions);

        for (Map.Entry<String, String> param : params.entrySet()) {
            uri.addParameter(param.getKey(), param.getValue());
        }

        return uri.build().toString();
    } catch (URISyntaxException | ParserConfigurationException | TransformerException | IOException
            | SAXException e) {
        return "";
    }
}

From source file:com.revo.deployr.client.core.impl.RProjectImpl.java

public InputStream downloadFiles(List<String> files) throws RClientException, RSecurityException {

    try {/*from w w w .j  av a 2s . c  o m*/

        String fileNames = null;
        if (files != null) {
            for (String fileName : files) {
                if (fileNames != null) {
                    fileNames = fileNames + "," + fileName;
                } else {
                    fileNames = fileName;
                }
            }
        }

        String urlPath = liveContext.serverurl + REndpoints.RPROJECTDIRECTORYDOWNLOAD;
        urlPath = urlPath + ";jsessionid=" + liveContext.httpcookie;

        URIBuilder builder = new URIBuilder(urlPath);
        builder.addParameter("project", this.about.id);
        if (fileNames != null) {
            builder.addParameter("filename", fileNames);
        }
        return liveContext.executor.download(builder);
    } catch (Exception ex) {
        throw new RClientException("Download failed: " + ex.getMessage());
    }
}

From source file:eu.esdihumboldt.hale.io.wfs.ui.capabilities.WFSCapabilitiesFieldEditor.java

private boolean getValidState() {
    String value = getValue();/*from   ww  w.  ja  v  a2  s  . c om*/

    DialogPage page = getPage();

    // try to create a URL
    try {
        new URI(value);
    } catch (Exception e) {
        if (page != null) {
            page.setErrorMessage(e.getLocalizedMessage());
        }
        return false;
    }

    // try to get capabilities
    try {
        URIBuilder builder = new URIBuilder(value);

        // add fixed parameters
        boolean requestPresent = false;
        boolean servicePresent = false;
        String versionParam = null;
        for (NameValuePair param : builder.getQueryParams()) {
            String name = param.getName().toLowerCase();
            if (name.equals("request"))
                requestPresent = true;
            if (name.equals("service"))
                servicePresent = true;
            if (name.equals("version"))
                versionParam = param.getName();
        }
        if (!requestPresent) {
            builder.addParameter("REQUEST", "GetCapabilities");
        }
        if (!servicePresent) {
            builder.addParameter("SERVICE", "WFS");
        }
        WFSVersion version = getWFSVersion();
        if (version != null) {
            if (versionParam == null) {
                versionParam = "VERSION";
            }
            builder.setParameter(versionParam, version.toString());
        }

        usedUrl = builder.build().toURL();

        try (InputStream in = usedUrl.openStream()) {
            capabilities = CapabilitiesHelper.loadCapabilities(in);
        }
    } catch (Exception e) {
        if (page != null) {
            page.setErrorMessage(e.getLocalizedMessage());
        }
        return false;
    }

    // passed all tests
    if (page != null) {
        page.setErrorMessage(null);
    }
    return true;
}

From source file:com.cisco.oss.foundation.http.apache.ApacheHttpClient.java

private URI buildUri(HttpRequest request, Joiner joiner) {
    URI requestUri = request.getUri();

    Map<String, Collection<String>> queryParams = request.getQueryParams();
    if (queryParams != null && !queryParams.isEmpty()) {
        URIBuilder uriBuilder = new URIBuilder();
        StringBuilder queryStringBuilder = new StringBuilder();
        boolean hasQuery = !queryParams.isEmpty();
        for (Map.Entry<String, Collection<String>> stringCollectionEntry : queryParams.entrySet()) {
            String key = stringCollectionEntry.getKey();
            Collection<String> queryParamsValueList = stringCollectionEntry.getValue();
            if (request.isQueryParamsParseAsMultiValue()) {
                for (String queryParamsValue : queryParamsValueList) {
                    uriBuilder.addParameter(key, queryParamsValue);
                    queryStringBuilder.append(key).append("=").append(queryParamsValue).append("&");
                }//w w w  .j a  va  2s. c om
            } else {
                String value = joiner.join(queryParamsValueList);
                uriBuilder.addParameter(key, value);
                queryStringBuilder.append(key).append("=").append(value).append("&");
            }
        }
        uriBuilder.setFragment(requestUri.getFragment());
        uriBuilder.setHost(requestUri.getHost());
        uriBuilder.setPath(requestUri.getPath());
        uriBuilder.setPort(requestUri.getPort());
        uriBuilder.setScheme(requestUri.getScheme());
        uriBuilder.setUserInfo(requestUri.getUserInfo());
        try {

            if (!autoEncodeUri) {
                String urlPath = "";
                if (requestUri.getRawPath() != null && requestUri.getRawPath().startsWith("/")) {
                    urlPath = requestUri.getRawPath();
                } else {
                    urlPath = "/" + requestUri.getRawPath();
                }

                if (hasQuery) {
                    String query = queryStringBuilder.substring(0, queryStringBuilder.length() - 1);
                    requestUri = new URI(requestUri.getScheme() + "://" + requestUri.getHost() + ":"
                            + requestUri.getPort() + urlPath + "?" + query);
                } else {
                    requestUri = new URI(requestUri.getScheme() + "://" + requestUri.getHost() + ":"
                            + requestUri.getPort() + urlPath);
                }
            } else {
                requestUri = uriBuilder.build();
            }
        } catch (URISyntaxException e) {
            LOGGER.warn("could not update uri: {}", requestUri);
        }
    }
    return requestUri;
}

From source file:com.mxhero.plugin.cloudstorage.onedrive.api.Items.java

/**
 * Simple upload./*from   w ww .  j  ava  2s . c om*/
 *
 * @param path the path
 * @param file the file
 * @param conflictBehavior the conflict behavior
 * @return the item
 * @throws IllegalArgumentException the illegal argument exception
 */
private Item simpleUpload(final String path, final File file, final ConflictBehavior conflictBehavior) {
    final Command<Item> command = this.commandFactory.create();
    command.validate(Validator.builder().file().name(file.getName()).build());
    return command.excecute(new CommandHandler<Item>() {

        @Override
        public Item response(HttpResponse response) {
            try {
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED
                        || response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    return OneDrive.JACKSON.readValue(EntityUtils.toString(response.getEntity()), Item.class);
                }
                if (response.getStatusLine().getStatusCode() > 399) {
                    throw new ApiException(response);
                }
                throw new IllegalArgumentException(
                        "error reading response body with code " + response.getStatusLine().getStatusCode());
            } catch (Exception e) {
                throw new IllegalArgumentException("error reading response", e);
            }
        }

        /* (non-Javadoc)
         * @see com.mxhero.plugin.cloudstorage.onedrive.api.command.CommandHandler#request()
         */
        @Override
        public HttpUriRequest request() {
            try {
                URIBuilder builder = new URIBuilder(command.baseUrl() + path);
                builder.addParameter("@name.conflictBehavior", conflictBehavior.name());
                HttpPut httpPut = new HttpPut(builder.build().toString());
                httpPut.setHeader("Content-Type", "text/plain");
                httpPut.setEntity(new FileEntity(file, ContentType.TEXT_PLAIN));
                return httpPut;
            } catch (Exception e) {
                throw new IllegalArgumentException("couldn't create query", e);
            }
        }
    });
}

From source file:org.eclipse.rdf4j.http.client.RDF4JProtocolSession.java

public long size(Resource... contexts) throws IOException, RepositoryException, UnauthorizedException {
    checkRepositoryURL();// w  w w  .java  2s .co m

    try {
        final boolean useTransaction = transactionURL != null;

        String baseLocation = useTransaction ? appendAction(transactionURL, Action.SIZE)
                : Protocol.getSizeLocation(getQueryURL());
        URIBuilder url = new URIBuilder(baseLocation);

        String[] encodedContexts = Protocol.encodeContexts(contexts);
        for (int i = 0; i < encodedContexts.length; i++) {
            url.addParameter(Protocol.CONTEXT_PARAM_NAME, encodedContexts[i]);
        }

        final HttpRequestBase method = useTransaction ? new HttpPut(url.build()) : new HttpGet(url.build());

        try {
            String response = EntityUtils.toString(executeOK(method).getEntity());

            try {
                return Long.parseLong(response);
            } catch (NumberFormatException e) {
                throw new RepositoryException("Server responded with invalid size value: " + response);
            }
        } finally {
            method.reset();
        }
    } catch (URISyntaxException e) {
        throw new AssertionError(e);
    } catch (RepositoryException e) {
        throw e;
    } catch (RDF4JException e) {
        throw new RepositoryException(e);
    }
}

From source file:org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.JITProvisioningPostAuthenticationHandler.java

/**
 * Call the relevant URL to add the new user.
 *
 * @param externalIdPConfig Relevant external IDP.
 * @param context           Authentication context.
 * @param localClaimValues  Local claim values.
 * @param response          HttpServlet response.
 * @param username          Relevant user name
 * @throws PostAuthenticationFailedException Post Authentication Failed Exception.
 *///from   www  .ja v a2 s.  c  o  m
private void redirectToAccountCreateUI(ExternalIdPConfig externalIdPConfig, AuthenticationContext context,
        Map<String, String> localClaimValues, HttpServletResponse response, String username,
        HttpServletRequest request) throws PostAuthenticationFailedException {

    try {
        URIBuilder uriBuilder;
        if (externalIdPConfig.isModifyUserNameAllowed()) {
            context.setProperty(FrameworkConstants.CHANGING_USERNAME_ALLOWED, true);
            uriBuilder = new URIBuilder(FrameworkUtils.getUserNameProvisioningUIUrl());
            uriBuilder.addParameter(FrameworkConstants.ALLOW_CHANGE_USER_NAME, String.valueOf(true));
            if (log.isDebugEnabled()) {
                log.debug(externalIdPConfig.getName() + " allow to change the username, redirecting to "
                        + "registration endpoint to provision the user: " + username);
            }
        } else {
            uriBuilder = new URIBuilder(FrameworkUtils.getPasswordProvisioningUIUrl());
            if (log.isDebugEnabled()) {
                if (externalIdPConfig.isPasswordProvisioningEnabled()) {
                    log.debug(externalIdPConfig.getName() + " supports password provisioning, redirecting to "
                            + "sign up endpoint to provision the user : " + username);
                }
            }
        }
        if (externalIdPConfig.isPasswordProvisioningEnabled()) {
            uriBuilder.addParameter(FrameworkConstants.PASSWORD_PROVISION_ENABLED, String.valueOf(true));
        }
        uriBuilder.addParameter(MultitenantConstants.TENANT_DOMAIN_HEADER_NAME, context.getTenantDomain());
        uriBuilder.addParameter(FrameworkConstants.SERVICE_PROVIDER,
                context.getSequenceConfig().getApplicationConfig().getApplicationName());
        uriBuilder.addParameter(FrameworkConstants.USERNAME, username);
        uriBuilder.addParameter(FrameworkConstants.SKIP_SIGN_UP_ENABLE_CHECK, String.valueOf(true));
        uriBuilder.addParameter(FrameworkConstants.SESSION_DATA_KEY, context.getContextIdentifier());
        addMissingClaims(uriBuilder, context);
        localClaimValues.forEach(uriBuilder::addParameter);
        response.sendRedirect(uriBuilder.build().toString());
    } catch (URISyntaxException | IOException e) {
        handleExceptions(
                String.format(ErrorMessages.ERROR_WHILE_TRYING_CALL_SIGN_UP_ENDPOINT_FOR_PASSWORD_PROVISIONING
                        .getMessage(), username, externalIdPConfig.getName()),
                ErrorMessages.ERROR_WHILE_TRYING_CALL_SIGN_UP_ENDPOINT_FOR_PASSWORD_PROVISIONING.getCode(), e);
    }
}

From source file:de.ii.xtraplatform.ogc.api.wfs.client.WFSAdapter.java

public String getRequestUrl(WFSOperation operation) {
    URIBuilder uri = new URIBuilder(findUrl(operation.getOperation(), WFS.METHOD.GET));

    Map<String, String> params = null;
    try {//from  w w  w. j  a v a2  s  .  c om
        params = operation.getGETParameters(nsStore, versions);
    } catch (ParserConfigurationException e) {
        return "";
    }

    for (Map.Entry<String, String> param : params.entrySet()) {
        uri.addParameter(param.getKey(), param.getValue());
    }

    try {
        return uri.build().toString();
    } catch (URISyntaxException e) {
        return "";
    }
}