Java Code Examples for org.apache.http.client.utils.URIBuilder#addParameter()

The following examples show how to use org.apache.http.client.utils.URIBuilder#addParameter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ListedContainers.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Iterator<Container> all() {
    final URIBuilder uriBuilder = new UncheckedUriBuilder(
        super.baseUri().toString().concat("/json")
    );
    uriBuilder.addParameter("all", "true");
    if (this.withSize) {
        uriBuilder.addParameter("size", "true");
    }
    final FilteredUriBuilder uri = new FilteredUriBuilder(
        uriBuilder,
        this.filters);

    return new ResourcesIterator<>(
        super.client(),
        new HttpGet(uri.build()),
        json -> new RtContainer(
            json,
            super.client(),
            URI.create(
                super.baseUri().toString() + "/" + json.getString("Id")
            ),
            super.docker()
        )
    );
}
 
Example 2
Source File: KilometricService.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Get JSON response from YOURS(Yet Another Openstreetmap Route Service) API.
 *
 * @param origins
 * @param destinations
 * @return
 * @throws AxelorException
 * @throws JSONException
 * @throws URISyntaxException
 * @throws IOException
 */
protected JSONObject getYOURSApiResponse(String origins, String destinations)
    throws AxelorException, JSONException, URISyntaxException, IOException {

  Map<String, Object> originMap = this.getLocationMap(origins);
  Map<String, Object> destinationMap = this.getLocationMap(destinations);

  String flat = originMap.get("latitude").toString();
  String flon = originMap.get("longitude").toString();
  String tlat = destinationMap.get("latitude").toString();
  String tlon = destinationMap.get("longitude").toString();

  URIBuilder ub = new URIBuilder("http://www.yournavigation.org/api/1.0/gosmore.php");
  ub.addParameter("format", "geojson");
  ub.addParameter("flat", flat);
  ub.addParameter("flon", flon);
  ub.addParameter("tlat", tlat);
  ub.addParameter("tlon", tlon);
  ub.addParameter("v", "motorcar");
  ub.addParameter("fast", "0");
  return this.getApiResponse(ub.toString(), IExceptionMessage.KILOMETRIC_ALLOWANCE_OSM_ERROR);
}
 
Example 3
Source File: CaseInstanceService.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
public JsonNode listCaseInstancesForCaseDefinition(ObjectNode bodyNode, ServerConfig serverConfig) {
    JsonNode resultNode = null;
    try {
        URIBuilder builder = new URIBuilder("cmmn-query/historic-case-instances");

        builder.addParameter("size", DEFAULT_CASEINSTANCE_SIZE);
        builder.addParameter("sort", "startTime");
        builder.addParameter("order", "desc");

        String uri = clientUtil.getUriWithPagingAndOrderParameters(builder, bodyNode);
        HttpPost post = clientUtil.createPost(uri, serverConfig);

        post.setEntity(clientUtil.createStringEntity(bodyNode.toString()));
        resultNode = clientUtil.executeRequest(post, serverConfig);
    } catch (Exception e) {
        throw new FlowableServiceException(e.getMessage(), e);
    }
    return resultNode;
}
 
Example 4
Source File: CelosClient.java    From celos with Apache License 2.0 6 votes vote down vote up
public WorkflowStatus getWorkflowStatus(WorkflowID workflowID, ScheduledTime startTime, ScheduledTime endTime) throws Exception {

        URIBuilder uriBuilder = new URIBuilder(address);
        uriBuilder.setPath(uriBuilder.getPath() + WORKFLOW_SLOTS_PATH);
        if (endTime != null) {
            uriBuilder.addParameter(END_TIME_PARAM, timeFormatter.formatPretty(endTime));
        }
        if (startTime != null) {
            uriBuilder.addParameter(START_TIME_PARAM, timeFormatter.formatPretty(startTime));
        }
        uriBuilder.addParameter(ID_PARAM, workflowID.toString());
        URI uri = uriBuilder.build();

        HttpGet workflowListGet = new HttpGet(uri);
        HttpResponse getResponse = execute(workflowListGet);
        InputStream content = getResponse.getEntity().getContent();
        return parseWorkflowStatus(workflowID, content);
    }
 
Example 5
Source File: RenderDataClient.java    From render with GNU General Public License v2.0 6 votes vote down vote up
private List<CanvasMatches> getMatches(final String context,
                                       final String urlString,
                                       final boolean excludeMatchDetails)
        throws IOException {
    final URI uri;
    try {
        final URIBuilder builder = new URIBuilder(urlString);
        if (excludeMatchDetails) {
            builder.addParameter("excludeMatchDetails", String.valueOf(excludeMatchDetails));
        }
        uri = builder.build();
    } catch (final URISyntaxException e) {
        throw new IOException(e.getMessage(), e);
    }

    final HttpGet httpGet = new HttpGet(uri);
    final String requestContext = "GET " + uri;
    final TypeReference<List<CanvasMatches>> typeReference = new TypeReference<List<CanvasMatches>>() {};
    final JsonUtils.GenericHelper<List<CanvasMatches>> helper = new JsonUtils.GenericHelper<>(typeReference);
    final JsonResponseHandler<List<CanvasMatches>> responseHandler = new JsonResponseHandler<>(requestContext,
                                                                                               helper);

    LOG.info(context + ": submitting {}", requestContext);

    return httpClient.execute(httpGet, responseHandler);
}
 
Example 6
Source File: ReportUtils.java    From Quantum with MIT License 5 votes vote down vote up
private static void downloadExecutionSummaryReport(String deviceId, String driverExecutionId, String accessToken)
		throws Exception {
	URIBuilder uriBuilder = new URIBuilder(REPORTING_SERVER_URL + "/export/api/v1/test-executions/pdf");
	uriBuilder.addParameter("externalId[0]", driverExecutionId);
	// downloadFileAuthenticated(driverExecutionId, uriBuilder.build(),
	// ".pdf", "execution summary PDF report",
	// accessToken);
	downloadFileAuthenticated(deviceId + "_ExecutionSummaryReport", uriBuilder.build(), ".pdf",
			"execution summary PDF report", accessToken);

}
 
Example 7
Source File: HttpRemoteService.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private HttpGet createGet(String url, MultiValueMap<String, String> params) throws URISyntaxException {
    URIBuilder uri = new URIBuilder(url);

    for (Map.Entry<String, List<String>> entry : params.entrySet()) {
        String key = entry.getKey();

        for (String value : entry.getValue()) {
            uri.addParameter(key, value);
        }
    }

    return new HttpGet(uri.build());
}
 
Example 8
Source File: CreateChildFolder.java    From data-prep with Apache License 2.0 5 votes vote down vote up
private HttpRequestBase onExecute(final String parentId, final String path) {
    try {

        URIBuilder uriBuilder = new URIBuilder(preparationServiceUrl + "/folders");
        if (parentId != null) {
            uriBuilder.addParameter("parentId", parentId);
        }
        uriBuilder.addParameter("path", path);
        return new HttpPut(uriBuilder.build());
    } catch (URISyntaxException e) {
        throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
    }
}
 
Example 9
Source File: SharethroughUriBuilderUtil.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates uri with parameters for sharethrough request
 */
static String buildSharethroughUrl(String baseUri, String supplyId, String strVersion, String formattedDate,
                                   StrUriParameters params) {
    final URIBuilder uriBuilder = new URIBuilder()
            .setPath(baseUri)
            .addParameter("placement_key", params.getPkey())
            .addParameter("bidId", params.getBidID())
            .addParameter("consent_required", getBooleanStringValue(params.getConsentRequired()))
            .addParameter("consent_string", params.getConsentString())
            .addParameter("us_privacy", params.getUsPrivacySignal())
            .addParameter("instant_play_capable", getBooleanStringValue(params.getInstantPlayCapable()))
            .addParameter("stayInIframe", getBooleanStringValue(params.getIframe()))
            .addParameter("height", String.valueOf(params.getHeight()))
            .addParameter("width", String.valueOf(params.getWidth()))
            .addParameter("adRequestAt", formattedDate)
            .addParameter("supplyId", supplyId)
            .addParameter("strVersion", strVersion);

    final String ttduid = params.getTheTradeDeskUserId();
    if (StringUtils.isNotBlank(ttduid)) {
        uriBuilder.addParameter("ttduid", ttduid);
    }
    final String stxuid = params.getSharethroughUserId();
    if (StringUtils.isNotBlank(stxuid)) {
        uriBuilder.addParameter("stxuid", stxuid);
    }

    return uriBuilder.toString();
}
 
Example 10
Source File: CelosClient.java    From celos with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes the specified register value.
 */
public void deleteRegister(BucketID bucket, RegisterKey key) throws Exception {
    URIBuilder uriBuilder = new URIBuilder(address);
    uriBuilder.setPath(uriBuilder.getPath() + REGISTER_PATH);
    uriBuilder.addParameter(BUCKET_PARAM, bucket.toString());
    uriBuilder.addParameter(KEY_PARAM, key.toString());
    executeDelete(uriBuilder.build());
}
 
Example 11
Source File: GoogleTranslator.java    From AndroidLocalizePlugin with Apache License 2.0 5 votes vote down vote up
@Override
public String query() throws Exception {
    URIBuilder uri = new URIBuilder(url);
    for (String key : formData.keySet()) {
        String value = formData.get(key);
        uri.addParameter(key, value);
    }
    HttpGet request = new HttpGet(uri.toString());

    RequestConfig.Builder builder = RequestConfig.copy(RequestConfig.DEFAULT)
            .setSocketTimeout(5000)
            .setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000);

    if (PluginConfig.isEnableProxy()) {
        HttpHost proxy = new HttpHost(PluginConfig.getHostName(), PluginConfig.getPortNumber());
        builder.setProxy(proxy);
    }

    RequestConfig config = builder.build();
    request.setConfig(config);
    CloseableHttpResponse response = httpClient.execute(request);
    HttpEntity entity = response.getEntity();

    String result = EntityUtils.toString(entity, "UTF-8");
    EntityUtils.consume(entity);
    response.getEntity().getContent().close();
    response.close();

    return result;
}
 
Example 12
Source File: OWLServerSimSearchTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected HttpUriRequest createBogusRequest(int n) throws URISyntaxException {
	URIBuilder uriBuilder = new URIBuilder()
		.setScheme("http")
		.setHost("localhost").setPort(9031)
		.setPath("/owlsim/searchByAttributeSet/");
		
	uriBuilder.addParameter("a", "BOGUS:1234567");
	uriBuilder.addParameter("limit","5");
	URI uri = uriBuilder.build();
	LOG.info("Getting URL="+uri);
	HttpUriRequest httpUriRequest = new HttpGet(uri);
	LOG.info("Got URL="+uri);
	return httpUriRequest;
}
 
Example 13
Source File: RenderDataClient.java    From render with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param  stack  name of stack.
 * @param  minZ   (optional) minimum value to include in list.
 * @param  maxZ   (optional) maximum value to include in list.
 *
 * @return z values for the specified stack.
 *
 * @throws IOException
 *   if the request fails for any reason.
 */
public List<Double> getStackZValues(final String stack,
                                    final Double minZ,
                                    final Double maxZ)
        throws IOException {

    final URIBuilder builder = new URIBuilder(getUri(urls.getStackUrlString(stack) + "/zValues"));

    if (minZ != null) {
        builder.addParameter("minZ", minZ.toString());
    }
    if (maxZ != null) {
        builder.addParameter("maxZ", maxZ.toString());
    }

    final URI uri;
    try {
        uri = builder.build();
    } catch (final URISyntaxException e) {
        throw new IOException(e.getMessage(), e);
    }

    final HttpGet httpGet = new HttpGet(uri);
    final String requestContext = "GET " + uri;
    final TypeReference<List<Double>> typeReference = new TypeReference<List<Double>>() {};
    final JsonUtils.GenericHelper<List<Double>> helper = new JsonUtils.GenericHelper<>(typeReference);
    final JsonResponseHandler<List<Double>> responseHandler = new JsonResponseHandler<>(requestContext, helper);

    LOG.info("getStackZValues: submitting {}", requestContext);

    return httpClient.execute(httpGet, responseHandler);
}
 
Example 14
Source File: Client.java    From geoportal-server-harvester with Apache License 2.0 5 votes vote down vote up
private URI createXmlUri(String id) throws URISyntaxException, IOException {
  URIBuilder b = new URIBuilder(url.toURI().resolve(REST_ITEM_URL + "/" + id + "/xml"));
  if (cred != null && !cred.isEmpty()) {
    b.addParameter("access_token", getAccessToken());
  }
  return b.build();
}
 
Example 15
Source File: IRIBuilderServiceImpl.java    From elucidate-server with MIT License 5 votes vote down vote up
private String buildIri(String id, Map<String, Object> params) {
    try {
        URIBuilder builder = new URIBuilder(baseUrl);
        builder.setPath(String.format("%s/%s", builder.getPath(), id));
        if (params != null && !params.isEmpty()) {
            for (Entry<String, Object> param : params.entrySet()) {
                builder.addParameter(param.getKey(), String.valueOf(param.getValue()));
            }
        }
        return builder.toString();
    } catch (URISyntaxException e) {
        throw new InvalidIRIException(String.format("An error occurred building IRI with base URL [%s] with ID [%s] and parameters [%s]", baseUrl, id, params), e);
    }
}
 
Example 16
Source File: AbstractRetrieveGolr.java    From owltools with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
URI createGolrRequest(List<String []> tagvalues, String category, int start, int pagination) throws IOException {
	try {
		URIBuilder builder = new URIBuilder(server);
		String currentPath = StringUtils.trimToEmpty(builder.getPath());
		builder.setPath(currentPath+"/select");
		builder.addParameter("defType", "edismax");
		builder.addParameter("qt", "standard");
		builder.addParameter("wt", "json");
		if (isIndentJson()) {
			builder.addParameter("indent","on");
		}
		builder.addParameter("fl",StringUtils.join(getRelevantFields(), ','));
		builder.addParameter("facet","false");
		builder.addParameter("json.nl","arrarr");
		builder.addParameter("q","*:*");
		builder.addParameter("rows", Integer.toString(pagination));
		builder.addParameter("start", Integer.toString(start));
		builder.addParameter("fq", "document_category:\""+category+"\"");
		for (String [] tagvalue : tagvalues) {
			if (tagvalue.length == 2) {
				builder.addParameter("fq", tagvalue[0]+":\""+tagvalue[1]+"\"");
			}
			else if (tagvalue.length > 2) {
				// if there is more than one value, assume that this is an OR query
				StringBuilder value = new StringBuilder();
				value.append(tagvalue[0]).append(":(");
				for (int i = 1; i < tagvalue.length; i++) {
					if (i > 1) {
						value.append(" OR ");
					}
					value.append('"').append(tagvalue[i]).append('"');
				}
				value.append(')');
				builder.addParameter("fq", value.toString());
			}
		}
		return builder.build();
	} catch (URISyntaxException e) {
		throw new IOException("Could not build URI for Golr request", e);
	}
}
 
Example 17
Source File: DownloadStepdefs.java    From james-project with Apache License 2.0 4 votes vote down vote up
private Request queryParameterDownloadRequest(URIBuilder uriBuilder, String blobId, String username) throws URISyntaxException {
    AccessToken accessToken = userStepdefs.authenticate(username);
    AttachmentAccessTokenKey key = new AttachmentAccessTokenKey(username, blobId);
    uriBuilder.addParameter("access_token", attachmentAccessTokens.get(key).serialize());
    return Request.Get(uriBuilder.build());
}
 
Example 18
Source File: Client.java    From geoportal-server-harvester with Apache License 2.0 4 votes vote down vote up
/**
 * Query ids.
 *
 * @param term term to query
 * @param value value of the term
 * @param batchSize batch size (note: size 1 indicates looking for the first
 * only)
 * @return listIds of ids
 * @throws IOException if reading response fails
 * @throws URISyntaxException if URL has invalid syntax
 */
private List<String> queryIds(String term, String value, long batchSize) throws IOException, URISyntaxException {
  Set<String> ids = new HashSet<>();
  String search_after = null;

  ObjectNode root = mapper.createObjectNode();
  root.put("size", batchSize);
  root.set("_source", mapper.createArrayNode().add("_id"));
  root.set("sort", mapper.createArrayNode().add(mapper.createObjectNode().put("_id", "asc")));
  if (term != null && value != null) {
    root.set("query", mapper.createObjectNode().set("match", mapper.createObjectNode().put(term, value)));
  }

  do {
    URIBuilder builder = new URIBuilder(url.toURI().resolve(createElasticSearchUrl()));
    if (cred != null && !cred.isEmpty()) {
      builder = builder.addParameter("access_token", getAccessToken());
    }
  
    if (search_after != null) {
      root.set("search_after", mapper.createArrayNode().add(search_after));
    }

    String json = mapper.writeValueAsString(root);
    HttpEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);

    QueryResponse response = query(builder, entity);
    if (response!=null && response.status!=null && response.status==400 && search_after==null) {
      // This indicates it could be an old version of Elastic Search behind the Geoportal.
      // Fall back to using scroll API
      return queryIdsScroll(term, value, batchSize);
    }

    search_after = null;
    if (response != null && response.hasHits()) {
      List<String> responseIds = response.hits.hits.stream().map(hit -> hit._id).collect(Collectors.toList());
      ids.addAll(responseIds);

      // if argument 'size' is 1 that means looking for the first one only; otherwise looking for every possible
      search_after = batchSize > 1 ? responseIds.get(responseIds.size() - 1) : null;
    }
  } while (search_after != null && !Thread.currentThread().isInterrupted());

  return ids.stream().collect(Collectors.toList());
}
 
Example 19
Source File: HttpClientManage.java    From bbs with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * 执行带有参数的get请求
 *
 * @param url
 * @param paramMap
 * @return
 * @throws IOException
 * @throws URISyntaxException
 */
public String doGet(String url, Map<String, String> paramMap) throws IOException, URISyntaxException {
    URIBuilder builder = new URIBuilder(url);
    for (String s : paramMap.keySet()) {
        builder.addParameter(s, paramMap.get(s));
    }
    return doGet(builder.build().toString());
}
 
Example 20
Source File: SparqlBasedRequestProcessorForTPFs.java    From Server.Java with MIT License 3 votes vote down vote up
/**
 * This method adds 'email' and 'password' parameters to the provided URIBuilder
 * Note: This credentials approach is very specific to the VIVO (https://github.com/vivo-project/VIVO)
 * application and should be refactored once another use-case/example is required.
 *
 * @param uriBuilder of SPARQL-Query endpoint
 */
private void addCredentials(URIBuilder uriBuilder) {
    if (username != null && password != null) {
        uriBuilder.addParameter("email", username);
        uriBuilder.addParameter("password", password);
    }
}