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:com.lonepulse.zombielink.request.QueryParamProcessor.java

/**
 * <p>Accepts the {@link InvocationContext} along with an {@link HttpRequestBase} and creates a 
 * <a href="http://en.wikipedia.org/wiki/Query_string">query string</a> using arguments annotated 
 * with @{@link QueryParam} and @{@link QueryParams}; which is subsequently appended to the URI.</p>
 * //from   www. j a  v a2  s  . c o  m
 * <p>See {@link AbstractRequestProcessor#process(InvocationContext, HttpRequestBase)}.</p>
 * 
 * @param context
 *          the {@link InvocationContext} which is used to discover annotated query parameters
 * <br><br>
 * @param request
 *          prefers an instance of {@link HttpGet} so as to conform with HTTP 1.1; however, other 
 *          request types will be entertained to allow compliance with unusual endpoint definitions 
 * <br><br>
  * @return the same instance of {@link HttpRequestBase} which was given for processing query parameters
 * <br><br>
 * @throws RequestProcessorException
 *          if the creation of a query string failed due to an unrecoverable errorS
 * <br><br>
 * @since 1.3.0
 */
@Override
protected HttpRequestBase process(InvocationContext context, HttpRequestBase request) {

    try {

        URIBuilder uriBuilder = new URIBuilder(request.getURI());

        //add static name and value pairs
        List<Param> constantQueryParams = RequestUtils.findStaticQueryParams(context);

        for (Param param : constantQueryParams) {

            uriBuilder.setParameter(param.name(), param.value());
        }

        //add individual name and value pairs
        List<Entry<QueryParam, Object>> queryParams = Metadata.onParams(QueryParam.class, context);

        for (Entry<QueryParam, Object> entry : queryParams) {

            String name = entry.getKey().value();
            Object value = entry.getValue();

            if (!(value instanceof CharSequence)) {

                StringBuilder errorContext = new StringBuilder().append("Query parameters can only be of type ")
                        .append(CharSequence.class.getName())
                        .append(". Please consider implementing CharSequence ")
                        .append("and providing a meaningful toString() representation for the ")
                        .append("<name> of the query parameter. ");

                throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
            }

            uriBuilder.setParameter(name, ((CharSequence) value).toString());
        }

        //add batch name and value pairs (along with any static params)
        List<Entry<QueryParams, Object>> queryParamMaps = Metadata.onParams(QueryParams.class, context);

        for (Entry<QueryParams, Object> entry : queryParamMaps) {

            Param[] constantParams = entry.getKey().value();

            if (constantParams != null && constantParams.length > 0) {

                for (Param param : constantParams) {

                    uriBuilder.setParameter(param.name(), param.value());
                }
            }

            Object map = entry.getValue();

            if (!(map instanceof Map)) {

                StringBuilder errorContext = new StringBuilder()
                        .append("@QueryParams can only be applied on <java.util.Map>s. ")
                        .append("Please refactor the method to provide a Map of name and value pairs. ");

                throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
            }

            Map<?, ?> nameAndValues = (Map<?, ?>) map;

            for (Entry<?, ?> nameAndValue : nameAndValues.entrySet()) {

                Object name = nameAndValue.getKey();
                Object value = nameAndValue.getValue();

                if (!(name instanceof CharSequence
                        && (value instanceof CharSequence || value instanceof Collection))) {

                    StringBuilder errorContext = new StringBuilder().append(
                            "The <java.util.Map> identified by @QueryParams can only contain mappings of type ")
                            .append("<java.lang.CharSequence, java.lang.CharSequence> or ")
                            .append("<java.lang.CharSequence, java.util.Collection<? extends CharSequence>>");

                    throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
                }

                if (value instanceof CharSequence) {

                    uriBuilder.addParameter(((CharSequence) name).toString(),
                            ((CharSequence) value).toString());
                } else { //add multi-valued query params 

                    Collection<?> multivalues = (Collection<?>) value;

                    for (Object multivalue : multivalues) {

                        if (!(multivalue instanceof CharSequence)) {

                            StringBuilder errorContext = new StringBuilder().append(
                                    "Values for the <java.util.Map> identified by @QueryParams can only contain collections ")
                                    .append("of type java.util.Collection<? extends CharSequence>");

                            throw new RequestProcessorException(
                                    new IllegalArgumentException(errorContext.toString()));
                        }

                        uriBuilder.addParameter(((CharSequence) name).toString(),
                                ((CharSequence) multivalue).toString());
                    }
                }
            }
        }

        request.setURI(uriBuilder.build());

        return request;
    } catch (Exception e) {

        throw (e instanceof RequestProcessorException) ? (RequestProcessorException) e
                : new RequestProcessorException(context, getClass(), e);
    }
}

From source file:org.apache.marmotta.client.util.HTTPUtil.java

public static HttpPost createPost(String path, ClientConfiguration config) throws URISyntaxException {
    final URIBuilder uriBuilder = new URIBuilder(config.getMarmottaUri());
    uriBuilder.setPath(uriBuilder.getPath() + path);

    if (StringUtils.isNotBlank(config.getMarmottaContext())) {
        uriBuilder.addParameter(CONTEXT, config.getMarmottaContext());
    }/*ww w. j av  a2  s  . co m*/

    final HttpPost post = new HttpPost(uriBuilder.build());

    if (StringUtils.isNotBlank(config.getMarmottaUser()) && StringUtils.isNotBlank(config.getMarmottaUser())) {
        final String credentials = String.format("%s:%s", config.getMarmottaUser(),
                config.getMarmottaPassword());
        try {
            final String encoded = DatatypeConverter.printBase64Binary(credentials.getBytes("UTF-8"));
            post.setHeader("Authorization", String.format("Basic %s", encoded));
        } catch (UnsupportedEncodingException e) {
            System.err.println("Error encoding credentials: " + e.getMessage());
        }
    }

    return post;
}

From source file:org.codice.ddf.commands.solr.BackupCommand.java

@Override
public Object doExecute() throws Exception {

    String backupUrl = getBackupUrl(coreName);

    URIBuilder uriBuilder = new URIBuilder(backupUrl);
    uriBuilder.addParameter("command", "backup");

    if (StringUtils.isNotBlank(backupLocation)) {
        uriBuilder.addParameter("location", backupLocation);
    }//from w  w w .j  a va2s  .  com
    if (numberToKeep > 0) {
        uriBuilder.addParameter("numberToKeep", Integer.toString(numberToKeep));
    }

    URI backupUri = uriBuilder.build();
    LOGGER.debug("Sending request to {}", backupUri.toString());

    HttpWrapper httpClient = getHttpClient();

    processResponse(httpClient.execute(backupUri));

    return null;
}

From source file:org.codice.ddf.commands.solr.RestoreCommand.java

private void performSingleNodeSolrRestore() throws URISyntaxException {
    String restoreUrl = getReplicationUrl(coreName);

    try {//from w ww.  j  a  v a2 s . co  m
        createSolrCore();

        httpBuilder = new org.codice.solr.factory.impl.HttpClientBuilder(encryptionService);
        URIBuilder uriBuilder = new URIBuilder(restoreUrl);
        uriBuilder.addParameter("command", "restore");

        if (StringUtils.isNotBlank(backupLocation)) {
            uriBuilder.addParameter("location", backupLocation);
        }

        URI restoreUri = uriBuilder.build();
        LOGGER.debug("Sending request to {}", restoreUri);

        printResponse(sendGetRequest(restoreUri));
    } catch (IOException | SolrServerException e) {
        LOGGER.info("Unable to perform single node Solr restore, core: {}", coreName, e);
    }
}

From source file:org.elasticsearch.client.RestClient.java

static URI buildUri(String pathPrefix, String path, Map<String, String> params) {
    Objects.requireNonNull(path, "path must not be null");
    try {/*from   w w  w .jav a 2  s  . c om*/
        String fullPath;
        if (pathPrefix != null) {
            if (path.startsWith("/")) {
                fullPath = pathPrefix + path;
            } else {
                fullPath = pathPrefix + "/" + path;
            }
        } else {
            fullPath = path;
        }

        URIBuilder uriBuilder = new URIBuilder(fullPath);
        for (Map.Entry<String, String> param : params.entrySet()) {
            uriBuilder.addParameter(param.getKey(), param.getValue());
        }
        return uriBuilder.build();
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }
}

From source file:org.flowable.ui.admin.service.engine.AppDeploymentService.java

public JsonNode listDeployments(ServerConfig serverConfig, Map<String, String[]> parameterMap) {

    URIBuilder builder = null;
    try {//  w w w  .jav a 2  s. co m
        builder = new URIBuilder("app-repository/deployments");
    } catch (Exception e) {
        LOGGER.error("Error building uri", e);
        throw new FlowableServiceException("Error building uri", e);
    }

    for (String name : parameterMap.keySet()) {
        builder.addParameter(name, parameterMap.get(name)[0]);
    }

    HttpGet get = new HttpGet(clientUtil.getServerUrl(serverConfig, builder.toString()));
    return clientUtil.executeRequest(get, serverConfig);
}

From source file:org.flowable.ui.admin.service.engine.CmmnDeploymentService.java

public JsonNode listDeployments(ServerConfig serverConfig, Map<String, String[]> parameterMap) {

    URIBuilder builder = null;
    try {/*  w w  w .j av a  2s . co m*/
        builder = new URIBuilder("cmmn-repository/deployments");
    } catch (Exception e) {
        LOGGER.error("Error building uri", e);
        throw new FlowableServiceException("Error building uri", e);
    }

    for (String name : parameterMap.keySet()) {
        builder.addParameter(name, parameterMap.get(name)[0]);
    }

    HttpGet get = new HttpGet(clientUtil.getServerUrl(serverConfig, builder.toString()));
    return clientUtil.executeRequest(get, serverConfig);
}

From source file:org.flowable.ui.admin.service.engine.DecisionTableDeploymentService.java

public JsonNode listDeployments(ServerConfig serverConfig, Map<String, String[]> parameterMap) {

    URIBuilder builder = null;
    try {/*from ww w. j a v a  2 s . co m*/
        builder = new URIBuilder("dmn-repository/deployments");
    } catch (Exception e) {
        LOGGER.error("Error building uri", e);
        throw new FlowableServiceException("Error building uri", e);
    }

    for (String name : parameterMap.keySet()) {
        builder.addParameter(name, parameterMap.get(name)[0]);
    }
    HttpGet get = new HttpGet(clientUtil.getServerUrl(serverConfig, builder.toString()));
    return clientUtil.executeRequest(get, serverConfig);
}

From source file:org.flowable.ui.admin.service.engine.DeploymentService.java

public JsonNode listDeployments(ServerConfig serverConfig, Map<String, String[]> parameterMap) {

    URIBuilder builder = null;
    try {//from   ww  w.  j a va2  s. co m
        builder = new URIBuilder("repository/deployments");
    } catch (Exception e) {
        LOGGER.error("Error building uri", e);
        throw new FlowableServiceException("Error building uri", e);
    }

    for (String name : parameterMap.keySet()) {
        builder.addParameter(name, parameterMap.get(name)[0]);
    }
    HttpGet get = new HttpGet(clientUtil.getServerUrl(serverConfig, builder.toString()));
    return clientUtil.executeRequest(get, serverConfig);
}

From source file:org.flowable.ui.admin.service.engine.DeploymentService.java

public JsonNode uploadDeployment(ServerConfig serverConfig, String name, InputStream inputStream)
        throws IOException {

    String deploymentKey = null;//from   ww  w  . java  2  s .com
    String deploymentName = null;

    byte[] inputStreamByteArray = IOUtils.toByteArray(inputStream);

    // special handling for exported bar files
    if (name != null && (name.endsWith(".zip") || name.endsWith(".bar"))) {
        JsonNode appDefinitionJson = getAppDefinitionJson(new ByteArrayInputStream(inputStreamByteArray));

        if (appDefinitionJson != null) {
            if (appDefinitionJson.has("key") && appDefinitionJson.get("key") != null) {
                deploymentKey = appDefinitionJson.get("key").asText();
            }
            if (appDefinitionJson.has("name") && appDefinitionJson.get("name") != null) {
                deploymentName = appDefinitionJson.get("name").asText();
            }
        }
    }

    URIBuilder uriBuilder = clientUtil.createUriBuilder("repository/deployments");

    if (StringUtils.isNotEmpty(deploymentKey)) {
        uriBuilder.addParameter("deploymentKey", encode(deploymentKey));
    }
    if (StringUtils.isNotEmpty(deploymentName)) {
        uriBuilder.addParameter("deploymentName", encode(deploymentName));
    }

    HttpPost post = new HttpPost(clientUtil.getServerUrl(serverConfig, uriBuilder));
    HttpEntity reqEntity = MultipartEntityBuilder.create()
            .addBinaryBody(name, inputStreamByteArray, ContentType.APPLICATION_OCTET_STREAM, name).build();
    post.setEntity(reqEntity);
    return clientUtil.executeRequest(post, serverConfig, 201);
}