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.ecofactor.qa.automation.util.HttpUtil.java

/**
 * Gets the./*  w w w.  ja  v  a2  s  .co  m*/
 * @param url the url
 * @return the http response
 */
public static String get(String url, Map<String, String> params, int expectedStatus) {

    String content = null;
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
    URIBuilder builder = new URIBuilder(request.getURI());

    Set<String> keys = params.keySet();
    for (String key : keys) {
        builder.addParameter(key, params.get(key));
    }

    HttpResponse response = null;
    try {
        request.setURI(builder.build());
        DriverConfig.setLogString("URL " + request.getURI().toString(), true);
        response = httpClient.execute(request);
        content = IOUtils.toString(response.getEntity().getContent());
        DriverConfig.setLogString("Content " + content, true);
        Assert.assertEquals(response.getStatusLine().getStatusCode(), expectedStatus);
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    } finally {
        request.releaseConnection();
    }

    return content;
}

From source file:com.vmware.identity.openidconnect.protocol.URIUtils.java

public static URI appendQueryParameter(URI uri, String parameterName, String parameterValue) {
    Validate.notNull(uri, "uri");
    Validate.notEmpty(parameterName, "parameterName");
    Validate.notEmpty(parameterValue, "parameterValue");

    URIBuilder uriBuilder = new URIBuilder(uri);
    uriBuilder.addParameter(parameterName, parameterValue);
    try {//from   w w w .j av a  2  s  .c  o  m
        return uriBuilder.build();
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("failed to add parameter to uri", e);
    }
}

From source file:org.wso2.carbon.apimgt.authenticator.oidc.ui.common.Util.java

/**
 * Building authentication request/*from   w w  w  .  jav a  2s . c o m*/
 * @param nonce cryptographically random nonce
 * @param state cryptographically random state
 * @return url
 */
public static String buildAuthRequestUrl(String nonce, String state) {

    try {
        log.debug("Building Authentication request...");
        URIBuilder uriBuilder = new URIBuilder(authorizationEndpointURI);

        uriBuilder.addParameter(OIDCConstants.PARAM_RESPONSE_TYPE, responseType);
        uriBuilder.addParameter(OIDCConstants.PARAM_CLIENT_ID, clientId);
        uriBuilder.addParameter(OIDCConstants.PARAM_SCOPE, scope);
        uriBuilder.addParameter(OIDCConstants.PARAM_REDIRECT_URI, redirectURI);
        uriBuilder.addParameter(OIDCConstants.PARAM_NONCE, nonce);
        uriBuilder.addParameter(OIDCConstants.PARAM_STATE, state);

        return uriBuilder.build().toString();
    } catch (URISyntaxException e) {
        log.error("Build Auth Request Failed", e);
    }
    return null;
}

From source file:com.ecofactor.qa.automation.util.HttpsUtil.java

/**
 * Gets the./*w  ww.  j a va2  s  .  c  o  m*/
 * @param url the url
 * @return the https response
 */
public static String get(String url, Map<String, String> params, int expectedStatus) {

    String content = null;
    HttpGet request = new HttpGet(url);
    URIBuilder builder = new URIBuilder(request.getURI());

    if (params != null) {
        Set<String> keys = params.keySet();
        for (String key : keys) {
            builder.addParameter(key, params.get(key));
        }
    }

    try {
        request.setURI(builder.build());
        DriverConfig.setLogString("URL " + request.getURI().toString(), true);
        driver.navigate().to(request.getURI().toString());
        tinyWait();
        content = driver.findElement(By.tagName("Body")).getText();
        DriverConfig.setLogString("Content: " + content, true);
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    } finally {
        request.releaseConnection();
    }

    return content;
}

From source file:com.github.jjYBdx4IL.utils.fma.FMAClient.java

public static FMASearchResult search(String query, boolean commercialUseAllowedOnly) throws IOException {
    URIBuilder b = new URIBuilder();
    b.setScheme("http");
    b.setHost("freemusicarchive.org");
    b.setPath("/search/.json");
    b.addParameter("duration_from", "");
    b.addParameter("duration_to", "");
    b.addParameter("adv", "1");
    b.addParameter("search-genre", "Genres");
    b.addParameter("sort", "track_date_published");
    b.addParameter("d", "1");

    if (commercialUseAllowedOnly) {
        b.addParameter("music-filter-CC-attribution-only", "on");
        b.addParameter("music-filter-CC-attribution-sharealike", "1");
        b.addParameter("music-filter-CC-attribution-noderivatives", "1");
        b.addParameter("music-filter-public-domain", "1");
        b.addParameter("music-filter-commercial-allowed", "1");
    }/*from w ww.  ja  v  a2  s .  c  o m*/

    b.addParameter("quicksearch", query != null ? query : "");
    b.addParameter("per_page", Integer.toString(RESULTS_PER_PAGE));

    int page = 0;
    boolean moreData = true;
    Gson gson = new Gson();
    FMASearchResult result = new FMASearchResult();
    while (moreData) {
        try {
            page++;
            b.setParameter("page", Integer.toString(page));
            byte[] data = cache.retrieve(b.build().toURL());
            FMASearchResult _result = gson.fromJson(new String(data), FMASearchResult.class);
            result.merge(_result);
            moreData = _result.aTracks.size() == RESULTS_PER_PAGE;
        } catch (URISyntaxException ex) {
            throw new IOException(ex);
        }
    }

    return result;
}

From source file:com.sheepdog.mashmesh.Itinerary.java

public static Itinerary fetch(String fromLocation, String toLocation, String viaLocation, DateTime arrivalTime)
        throws URISyntaxException, IOException {
    URIBuilder uriBuilder = new URIBuilder(DIRECTIONS_ENDPOINT_URL);
    uriBuilder.addParameter("origin", fromLocation);
    uriBuilder.addParameter("destination", toLocation);
    uriBuilder.addParameter("mode", "driving");
    uriBuilder.addParameter("language", "en_US"); // TODO: Configurable?
    uriBuilder.addParameter("region", "us");
    uriBuilder.addParameter("waypoints", viaLocation);
    uriBuilder.addParameter("sensor", "false");

    URL url = uriBuilder.build().toURL();
    BufferedReader responseReader = new BufferedReader(new InputStreamReader(url.openStream()));

    JsonParser parser = new JsonParser();
    JsonObject responseObject = parser.parse(responseReader).getAsJsonObject();
    JsonObject route = responseObject.getAsJsonArray("routes").get(0).getAsJsonObject();
    JsonArray legs = route.getAsJsonArray("legs");

    JsonObject startLeg = legs.get(0).getAsJsonObject();
    JsonObject endLeg = legs.get(legs.size() - 1).getAsJsonObject();

    DateTime departureTime = arrivalTime;
    List<Leg> directionLegs = new ArrayList<Leg>();

    Preconditions.checkState(legs.size() == 2, "Expected two direction legs in response");

    // Process the legs in reverse order so that we can compute departure and arrival
    //  times by working backwards from the desired arrival time.
    for (int i = legs.size() - 1; i >= 0; i--) {
        JsonObject leg = legs.get(i).getAsJsonObject();
        List<Step> directionSteps = new ArrayList<Step>();
        DateTime legArrivalTime = departureTime;

        for (JsonElement stepElement : leg.getAsJsonArray("steps")) {
            JsonObject stepObject = stepElement.getAsJsonObject();
            int duration = stepObject.getAsJsonObject("duration").get("value").getAsInt();
            String htmlInstructions = stepObject.get("html_instructions").getAsString();
            String distance = stepObject.getAsJsonObject("distance").get("text").getAsString();

            departureTime = departureTime.minusSeconds(duration);
            directionSteps.add(new Step(htmlInstructions, distance));
        }/*  w ww  .j a  v a  2s. c  om*/

        Leg directionLeg = new Leg();
        directionLeg.departureTime = departureTime;
        directionLeg.startLatLng = getLatLng(leg.getAsJsonObject("start_location"));
        directionLeg.arrivalTime = legArrivalTime;
        directionLeg.endLatLng = getLatLng(leg.getAsJsonObject("end_location"));
        directionLeg.distanceMeters = leg.getAsJsonObject("distance").get("value").getAsInt();
        directionLeg.steps = Collections.unmodifiableList(directionSteps);
        directionLegs.add(directionLeg);
    }

    Collections.reverse(directionLegs);

    Itinerary itinerary = new Itinerary();
    itinerary.startAddress = startLeg.get("start_address").getAsString();
    itinerary.endAddress = endLeg.get("end_address").getAsString();
    itinerary.legs = Collections.unmodifiableList(directionLegs);
    itinerary.overviewPolyline = route.getAsJsonObject("overview_polyline").get("points").getAsString();

    return itinerary;
}

From source file:de.ii.xtraplatform.feature.provider.wfs.FeatureProviderDataWfsFromMetadata.java

static URI parseAndCleanWfsUrl(URI inUri) throws URISyntaxException {
    URIBuilder outUri = new URIBuilder(inUri).removeQuery();

    if (inUri.getQuery() != null && !inUri.getQuery().isEmpty()) {
        for (String inParam : inUri.getQuery().split("&")) {
            String[] param = inParam.split("=");
            if (!WFS.hasKVPKey(param[0].toUpperCase())) {
                outUri.addParameter(param[0], param[1]);
            }//from  w w  w .j  a  va  2 s .c o m
        }
    }

    return outUri.build();
}

From source file:org.apache.vxquery.app.util.RestUtils.java

/**
 * Builds the {@link URI} once the {@link QueryRequest} is given. Only the
 * parameters given (different from the default values) are put in the
 * {@link URI}// w  ww . ja  v a 2 s .co  m
 * 
 * @param request
 *            {@link QueryRequest} to be converted to a {@link URI}
 * @param restIpAddress
 *            Ip address of the REST server
 * @param restPort
 *            port of the REST server
 * @return generated {@link URI}
 * @throws URISyntaxException
 */
public static URI buildQueryURI(QueryRequest request, String restIpAddress, int restPort)
        throws URISyntaxException {
    URIBuilder builder = new URIBuilder().setScheme("http").setHost(restIpAddress).setPort(restPort)
            .setPath(QUERY_ENDPOINT);

    if (request.getStatement() != null) {
        builder.addParameter(STATEMENT, request.getStatement());
    }
    if (request.isCompileOnly()) {
        builder.addParameter(COMPILE_ONLY, String.valueOf(request.isCompileOnly()));
    }
    if (request.getOptimization() != QueryRequest.DEFAULT_OPTIMIZATION) {
        builder.addParameter(OPTIMIZATION, String.valueOf(request.getOptimization()));
    }
    if (request.getFrameSize() != QueryRequest.DEFAULT_FRAMESIZE) {
        builder.addParameter(FRAME_SIZE, String.valueOf(request.getFrameSize()));
    }
    if (request.getRepeatExecutions() != 1) {
        builder.addParameter(REPEAT_EXECUTIONS, String.valueOf(request.getRepeatExecutions()));
    }
    if (request.isShowMetrics()) {
        builder.addParameter(METRICS, String.valueOf(request.isShowMetrics()));
    }
    if (request.isShowAbstractSyntaxTree()) {
        builder.addParameter(SHOW_AST, String.valueOf(request.isShowAbstractSyntaxTree()));
    }
    if (request.isShowTranslatedExpressionTree()) {
        builder.addParameter(SHOW_TET, String.valueOf(request.isShowTranslatedExpressionTree()));
    }
    if (request.isShowOptimizedExpressionTree()) {
        builder.addParameter(SHOW_OET, String.valueOf(request.isShowOptimizedExpressionTree()));
    }
    if (request.isShowRuntimePlan()) {
        builder.addParameter(SHOW_RP, String.valueOf(request.isShowRuntimePlan()));
    }
    if (!request.isAsync()) {
        builder.addParameter(MODE, request.isAsync() ? MODE_ASYNC : MODE_SYNC);
    }

    return builder.build();
}

From source file:com.mbeddr.pluginmanager.com.intellij.ide.plugins.RepositoryHelper.java

@NotNull
public static Map<PluginId, List<Pair<String, IdeaPluginDescriptor>>> loadPluginsFromChannels(
        @Nullable BuildNumber buildnumber, @Nullable ProgressIndicator indicator) throws IOException {
    Map<PluginId, List<Pair<String, IdeaPluginDescriptor>>> result = new LinkedHashMap<PluginId, List<Pair<String, IdeaPluginDescriptor>>>();

    String url;/*  www .  j  ava2 s . co  m*/
    try {
        URIBuilder uriBuilder = new URIBuilder(ApplicationInfoImpl.getShadowInstance().getChannelsListUrl());
        uriBuilder.addParameter("build", (buildnumber != null ? buildnumber.asString()
                : ApplicationInfoImpl.getShadowInstance().getApiVersion()));
        url = uriBuilder.build().toString();
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }

    boolean forceHttps = IdeaApplication.isLoaded() && UpdateSettings.getInstance().canUseSecureConnection();
    List<String> channelList = HttpRequests.request(url).forceHttps(forceHttps)
            .connect(new HttpRequests.RequestProcessor<List<String>>() {
                @Override
                public List<String> process(@NotNull HttpRequests.Request request) throws IOException {
                    //{"channels":["alpha","eap","ideadev","nightly"]}
                    return (List<String>) JsonUtil.nextObject(new JsonReaderEx(request.getReader().readLine()))
                            .get("channels");
                }
            });

    for (String channel : channelList) {
        List<IdeaPluginDescriptor> channelPlugins = loadPlugins(null, buildnumber, channel, forceHttps,
                indicator);
        for (IdeaPluginDescriptor plugin : channelPlugins) {
            PluginId pluginId = plugin.getPluginId();
            List<Pair<String, IdeaPluginDescriptor>> pluginChannelDescriptors = result.get(pluginId);
            if (pluginChannelDescriptors == null) {
                pluginChannelDescriptors = new SmartList<Pair<String, IdeaPluginDescriptor>>();
                result.put(pluginId, pluginChannelDescriptors);
            }
            pluginChannelDescriptors.add(Pair.create(channel, plugin));
        }
    }

    return result;
}

From source file:com.meltmedia.cadmium.cli.HistoryCommand.java

/**
 * Retrieves the history of a Cadmium site.
 * /*from w w w  .  j  a v  a 2 s . c  o m*/
 * @param siteUri The uri of a cadmium site.
 * @param limit The maximum number of history entries to retrieve or if set to -1 tells the site to retrieve all history.
 * @param filter If true filters out the non revertable history entries.
 * @param token The Github API token to pass to the Cadmium site for authentication.
 * 
 * @return A list of {@link HistoryEntry} Objects that are populated with the history returned from the Cadmium site.
 * 
 * @throws URISyntaxException
 * @throws IOException
 * @throws ClientProtocolException
 * @throws Exception
 */
public static List<HistoryEntry> getHistory(String siteUri, int limit, boolean filter, String token)
        throws URISyntaxException, IOException, ClientProtocolException, Exception {

    if (!siteUri.endsWith("/system/history")) {
        siteUri += "/system/history";
    }

    List<HistoryEntry> history = null;

    HttpClient httpClient = httpClient();
    HttpGet get = null;
    try {
        URIBuilder uriBuilder = new URIBuilder(siteUri);
        if (limit > 0) {
            uriBuilder.addParameter("limit", limit + "");
        }
        if (filter) {
            uriBuilder.addParameter("filter", filter + "");
        }
        URI uri = uriBuilder.build();
        get = new HttpGet(uri);
        addAuthHeader(token, get);

        HttpResponse resp = httpClient.execute(get);
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = resp.getEntity();
            if (entity.getContentType().getValue().equals("application/json")) {
                String responseContent = EntityUtils.toString(entity);
                Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

                    @Override
                    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx)
                            throws JsonParseException {
                        return new Date(json.getAsLong());
                    }

                }).create();
                history = gson.fromJson(responseContent, new TypeToken<List<HistoryEntry>>() {
                }.getType());
            } else {
                System.err
                        .println("Invalid response content type [" + entity.getContentType().getValue() + "]");
                System.exit(1);
            }
        } else {
            System.err.println("Request failed due to a [" + resp.getStatusLine().getStatusCode() + ":"
                    + resp.getStatusLine().getReasonPhrase() + "] response from the remote server.");
            System.exit(1);
        }
    } finally {
        if (get != null) {
            get.releaseConnection();
        }
    }
    return history;
}