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.eclipse.rdf4j.http.client.RDF4JProtocolSession.java

public synchronized void commitTransaction() throws RDF4JException, IOException, UnauthorizedException {
    checkRepositoryURL();//from   w w w .  j  a va2  s .  com

    if (transactionURL == null) {
        throw new IllegalStateException("Transaction URL has not been set");
    }

    HttpPut method = null;
    try {
        URIBuilder url = new URIBuilder(transactionURL);
        url.addParameter(Protocol.ACTION_PARAM_NAME, Action.COMMIT.toString());
        method = new HttpPut(url.build());

        final HttpResponse response = execute(method);
        try {
            int code = response.getStatusLine().getStatusCode();
            if (code == HttpURLConnection.HTTP_OK) {
                // we're done.
                transactionURL = null;
            } else {
                throw new RepositoryException("unable to commit transaction. HTTP error code " + code);
            }
        } finally {
            EntityUtils.consumeQuietly(response.getEntity());
        }
    } catch (URISyntaxException e) {
        logger.error("could not create URL for transaction commit", e);
        throw new RuntimeException(e);
    } finally {
        if (method != null) {
            method.reset();
        }
    }
}

From source file:org.instagram4j.DefaultInstagramClient.java

private void addParams(URIBuilder uri, Parameter... params) {
    if (params != null && params.length != 0) {
        for (Parameter param : params)
            uri.addParameter(param.getName(), param.getValue());
    }//  ww w  . j  av  a 2s.co m
}

From source file:org.flowable.admin.service.engine.ProcessInstanceService.java

public void executeAction(ServerConfig serverConfig, String processInstanceId, JsonNode actionBody)
        throws FlowableServiceException {
    boolean validAction = false;

    if (actionBody.has("action")) {
        String action = actionBody.get("action").asText();

        if ("delete".equals(action)) {
            validAction = true;//w  w w  .  j a  v  a  2s  .com

            // Delete historic instance
            URIBuilder builder = clientUtil
                    .createUriBuilder(MessageFormat.format(HISTORIC_PROCESS_INSTANCE_URL, processInstanceId));
            HttpDelete delete = new HttpDelete(clientUtil.getServerUrl(serverConfig, builder));
            clientUtil.executeRequestNoResponseBody(delete, serverConfig, HttpStatus.SC_NO_CONTENT);

        } else if ("terminate".equals(action)) {
            validAction = true;

            // Delete runtime instance
            URIBuilder builder = clientUtil
                    .createUriBuilder(MessageFormat.format(RUNTIME_PROCESS_INSTANCE_URL, processInstanceId));
            if (actionBody.has("deleteReason")) {
                builder.addParameter("deleteReason", actionBody.get("deleteReason").asText());
            }

            HttpDelete delete = new HttpDelete(clientUtil.getServerUrl(serverConfig, builder));
            clientUtil.executeRequestNoResponseBody(delete, serverConfig, HttpStatus.SC_NO_CONTENT);
        }
    }

    if (!validAction) {
        throw new BadRequestException(
                "Action is missing in the request body or the given action is not supported.");
    }
}

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

private HttpResponse requestGET(WFSOperation operation) throws ParserConfigurationException {
    URI url = findUrl(operation.getOperation(), WFS.METHOD.GET);

    HttpClient httpClient = url.getScheme().equals("https") ? this.untrustedSslHttpClient : this.httpClient;

    URIBuilder uri = new URIBuilder(url);

    Map<String, String> params = operation.getGETParameters(nsStore, versions);

    for (Map.Entry<String, String> param : params.entrySet()) {
        uri.addParameter(param.getKey(), param.getValue());
    }//w w  w . j a v a 2  s . com
    LOGGER.debug("GET Request {}: {}", operation, uri);

    boolean retried = false;
    HttpGet httpGet;
    HttpResponse response;

    try {

        // replace the + with %20
        String uristring = uri.build().toString();
        uristring = uristring.replaceAll("\\+", "%20");
        httpGet = new HttpGet(uristring);

        // TODO: temporary basic auth hack
        if (useBasicAuth) {
            httpGet.addHeader("Authorization", "Basic " + basicAuthCredentials);
        }

        response = httpClient.execute(httpGet, new BasicHttpContext());

        // check http status
        checkResponseStatus(response.getStatusLine().getStatusCode(), uri);

    } catch (SocketTimeoutException ex) {
        if (ignoreTimeouts) {
            LOGGER.warn("GET request timed out after %d ms, URL: {}",
                    HttpConnectionParams.getConnectionTimeout(httpClient.getParams()), uri);
        }
        response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "");
        response.setEntity(new StringEntity("", ContentType.TEXT_XML));
    } catch (IOException ex) {
        try {
            if (!isDefaultUrl(uri.build(), WFS.METHOD.GET)) {

                LOGGER.info("Removing URL: {}", uri);
                this.urls.remove(operation.getOperation().toString());

                LOGGER.info("Retry with default URL: {}", this.urls.get("default"));
                return requestGET(operation);
            }
        } catch (URISyntaxException ex0) {
        }
        LOGGER.error("Failed requesting URL: '{}'", uri);
        throw new ReadError("Failed requesting URL: '{}'", uri);
    } catch (URISyntaxException ex) {
        LOGGER.error("Failed requesting URL: '{}'", uri);
        throw new ReadError("Failed requesting URL: '{}'", uri);
    }
    LOGGER.debug("WFS request submitted");
    return response;
}

From source file:com.github.avarabyeu.restendpoint.http.HttpClientRestEndpoint.java

/**
 * Splice base URL and URL of resource//from   ww w  .jav a2  s.c om
 *
 * @param resource   REST Resource Path
 * @param parameters Map of query parameters
 * @return Absolute URL to the REST Resource including server and port
 * @throws RestEndpointIOException In case of incorrect URL format
 */
final URI spliceUrl(String resource, Map<String, String> parameters) throws RestEndpointIOException {
    try {
        URIBuilder builder;
        if (!Strings.isNullOrEmpty(baseUrl)) {
            builder = new URIBuilder(baseUrl);
            builder.setPath(builder.getPath() + resource);
        } else {
            builder = new URIBuilder(resource);
        }
        for (Entry<String, String> parameter : parameters.entrySet()) {
            builder.addParameter(parameter.getKey(), parameter.getValue());
        }
        return builder.build();
    } catch (URISyntaxException e) {
        throw new RestEndpointIOException(
                "Unable to builder URL with base url '" + baseUrl + "' and resouce '" + resource + "'", e);
    }
}

From source file:com.kolich.twitter.TwitterApiClient.java

public Either<HttpFailure, TweetSearchResults> searchTweets(final String query, final int count,
        final long sinceId, final OAuthConsumer consumer) {
    checkNotNull(query, "Query cannot be null!");
    return new TwitterApiGsonClosure<TweetSearchResults>(TweetSearchResults.class, consumer) {
        @Override/*from   ww  w . j ava2 s. co m*/
        public URI getFinalURI(final URI uri) throws Exception {
            final URIBuilder builder = new URIBuilder(uri).addParameter(API_QUERY_PARAM, query).addParameter(
                    API_COUNT_PARAM,
                    (count <= 0 || count > API_SEARCH_TWEETS_MAX_COUNT)
                            ? Integer.toString(API_TWEETS_DEFAULT_COUNT)
                            : Integer.toString(count));
            if (sinceId > 0L) {
                builder.addParameter(API_SINCEID_PARAM, Long.toString(sinceId));
            }
            return builder.build();
        }
    }.get(TWEET_SEARCH_URL);
}

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

private URIBuilder getUriBuilder(AuthenticationContext context, String requestedLocalClaims,
        String mandatoryLocalClaims) throws URISyntaxException {

    final String LOGIN_ENDPOINT = "login.do";
    final String CONSENT_ENDPOINT = "consent.do";

    String CONSENT_ENDPOINT_URL = ConfigurationFacade.getInstance().getAuthenticationEndpointURL()
            .replace(LOGIN_ENDPOINT, CONSENT_ENDPOINT);
    URIBuilder uriBuilder;
    uriBuilder = new URIBuilder(CONSENT_ENDPOINT_URL);

    if (isNotBlank(requestedLocalClaims)) {
        if (isDebugEnabled()) {
            logDebug("Appending requested local claims to redirect URI: " + requestedLocalClaims);
        }/*  w  w w  .  j  a  v  a 2  s. c o  m*/
        uriBuilder.addParameter(REQUESTED_CLAIMS_PARAM, requestedLocalClaims);
    }

    if (isNotBlank(mandatoryLocalClaims)) {
        if (isDebugEnabled()) {
            logDebug("Appending mandatory local claims to redirect URI: " + mandatoryLocalClaims);
        }
        uriBuilder.addParameter(MANDATORY_CLAIMS_PARAM, mandatoryLocalClaims);
    }
    uriBuilder.addParameter(FrameworkConstants.SESSION_DATA_KEY, context.getContextIdentifier());
    uriBuilder.addParameter(FrameworkConstants.REQUEST_PARAM_SP,
            context.getSequenceConfig().getApplicationConfig().getApplicationName());
    return uriBuilder;
}

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

private HttpResponse requestGET(WfsOperation operation)
        throws ParserConfigurationException, TransformerException, IOException, SAXException {
    URI url = findUrl(operation.getOperation(), WFS.METHOD.GET);

    HttpClient httpClient = url.getScheme().equals("https") ? this.untrustedSslHttpClient : this.httpClient;

    URIBuilder uri = new URIBuilder(url);

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

    for (Map.Entry<String, String> param : params.entrySet()) {
        uri.addParameter(param.getKey(), param.getValue());
    }/*from ww  w .  j a  va2  s  .  c o  m*/
    LOGGER.debug("GET Request {}: {}", operation, uri);

    boolean retried = false;
    HttpGet httpGet;
    HttpResponse response;

    try {

        // replace the + with %20
        String uristring = uri.build().toString();
        uristring = uristring.replaceAll("\\+", "%20");
        httpGet = new HttpGet(uristring);

        // TODO: temporary basic auth hack
        if (useBasicAuth) {
            httpGet.addHeader("Authorization", "Basic " + basicAuthCredentials);
        }

        response = httpClient.execute(httpGet, new BasicHttpContext());

        // check http status
        checkResponseStatus(response.getStatusLine().getStatusCode(), uri);

    } catch (SocketTimeoutException ex) {
        if (ignoreTimeouts) {
            LOGGER.warn("GET request timed out after %d ms, URL: {}",
                    HttpConnectionParams.getConnectionTimeout(httpClient.getParams()), uri);
        }
        response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "");
        response.setEntity(new StringEntity("", ContentType.TEXT_XML));
    } catch (IOException ex) {
        try {
            if (!isDefaultUrl(uri.build(), WFS.METHOD.GET)) {

                LOGGER.info("Removing URL: {}", uri);
                this.urls.remove(operation.getOperation().toString());

                LOGGER.info("Retry with default URL: {}", this.urls.get("default"));
                return requestGET(operation);
            }
        } catch (URISyntaxException ex0) {
        }
        LOGGER.error("Failed requesting URL: '{}'", uri);
        throw new ReadError("Failed requesting URL: '{}'", uri);
    } catch (URISyntaxException ex) {
        LOGGER.error("Failed requesting URL: '{}'", uri);
        throw new ReadError("Failed requesting URL: '{}'", uri);
    }
    LOGGER.debug("WFS request submitted");
    return response;
}

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

public InputStream export() throws RClientException, RSecurityException {

    try {//from  w  ww  .j av  a 2 s. c om
        String urlBase = this.liveContext.serverurl + REndpoints.RPROJECTEXPORT;
        String urlPath = urlBase + "/" + this.about.id + ";jsessionid=" + this.liveContext.httpcookie;
        URIBuilder builder = new URIBuilder(urlPath);
        builder.addParameter("project", this.about.id);
        return liveContext.executor.download(builder);
    } catch (Exception ex) {
        throw new RClientException("Export failed: " + ex.getMessage());
    }
}

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

public InputStream downloadResults() throws RClientException, RSecurityException {

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

        String urlPath = liveContext.serverurl + REndpoints.RPROJECTEXECUTERESULTDOWNLOAD;
        urlPath = urlPath + ";jsessionid=" + liveContext.httpcookie;
        URIBuilder builder = new URIBuilder(urlPath);
        builder.addParameter("project", this.about.id);
        return liveContext.executor.download(builder);
    } catch (Exception ex) {
        throw new RClientException("Download failed: " + ex.getMessage());
    }
}