Java Code Examples for javax.ws.rs.client.WebTarget#queryParam()

The following examples show how to use javax.ws.rs.client.WebTarget#queryParam() . 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: DefaultDockerClient.java    From docker-client with Apache License 2.0 6 votes vote down vote up
@Override
public InputStream save(final String... images)
    throws DockerException, IOException, InterruptedException {
  WebTarget resource;
  if (images.length == 1) {
    resource = resource().path("images").path(images[0]).path("get");
  } else {
    resource = resource().path("images").path("get");
    if (images.length > 1) {
      for (final String image : images) {
        if (!isNullOrEmpty(image)) {
          resource = resource.queryParam("names", urlEncode(image));
        }
      }
    }
  }

  return request(
      GET,
      InputStream.class,
      resource,
      resource.request(APPLICATION_JSON_TYPE));
}
 
Example 2
Source File: DefaultDockerClient.java    From docker-client with Apache License 2.0 6 votes vote down vote up
@Override
public void execResizeTty(final String execId,
                          final Integer height,
                          final Integer width)
    throws DockerException, InterruptedException {
  checkTtyParams(height, width);

  WebTarget resource = resource().path("exec").path(execId).path("resize");
  if (height != null && height > 0) {
    resource = resource.queryParam("h", height);
  }
  if (width != null && width > 0) {
    resource = resource.queryParam("w", width);
  }

  try {
    request(POST, resource, resource.request(TEXT_PLAIN_TYPE));
  } catch (DockerRequestException e) {
    switch (e.status()) {
      case 404:
        throw new ExecNotFoundException(execId, e);
      default:
        throw e;
    }
  }
}
 
Example 3
Source File: Image.java    From rapid with MIT License 6 votes vote down vote up
@GET
@Path("json")
public Response listImages(@DefaultValue("false") @QueryParam("all") String all,
                           @DefaultValue("false") @QueryParam("digests") String digests,
                           @QueryParam("filters") String filters) throws UnsupportedEncodingException {

    WebTarget target = resource().path(IMAGES).path("json")
            .queryParam("all", all)
            .queryParam("digests", digests);

    if (Objects.nonNull(filters))
        target = target.queryParam(FILTERS, URLEncoder.encode(filters, "UTF-8"));

    Response response = getResponse(target);
    try {
        String raw = response.readEntity(String.class);
        JsonReader reader = Json.createReader(new StringReader(raw));
        return Response.status(response.getStatus()).entity(reader.read()).build();
    } finally {
        response.close();
    }
}
 
Example 4
Source File: AbstractTestClass.java    From helix with Apache License 2.0 6 votes vote down vote up
protected String get(String uri, Map<String, String> queryParams, int expectedReturnStatus,
    boolean expectBodyReturned) {
  WebTarget webTarget = target(uri);
  if (queryParams != null) {
    for (Map.Entry<String, String> entry : queryParams.entrySet()) {
      webTarget = webTarget.queryParam(entry.getKey(), entry.getValue());
    }
  }
  final Response response = webTarget.request().get();
  Assert.assertEquals(response.getStatus(), expectedReturnStatus);

  // NOT_FOUND and BAD_REQUEST will throw text based html
  if (expectedReturnStatus != Response.Status.NOT_FOUND.getStatusCode()
      && expectedReturnStatus != Response.Status.BAD_REQUEST.getStatusCode()) {
    Assert.assertEquals(response.getMediaType().getType(), "application");
  } else {
    Assert.assertEquals(response.getMediaType().getType(), "text");
  }

  String body = response.readEntity(String.class);
  if (expectBodyReturned) {
    Assert.assertNotNull(body);
  }

  return body;
}
 
Example 5
Source File: Container.java    From rapid with MIT License 6 votes vote down vote up
@POST
@Path("create")
public Response createContainer(@QueryParam("name") String name, JsonObject content) {

    WebTarget target = resource().path(CONTAINERS).path("create");

    if (Objects.nonNull(name))
        target = target.queryParam("name", name);

    Response response = postResponse(target, content);
    try {
        return Response.status(response.getStatus())
                .entity(response.readEntity(JsonObject.class))
                .build();
    } finally {
        response.close();
    }
}
 
Example 6
Source File: Plugin.java    From rapid with MIT License 6 votes vote down vote up
@POST
@Path("pull")
public JsonStructure pullPlugin(@QueryParam("remote") String remote,
                                @QueryParam("name") String name,
                                JsonStructure content) {

    WebTarget target = resource().path("plugins").path("pull");

    if (Objects.nonNull(remote))
        target = target.queryParam("remote", remote);
    if (Objects.nonNull(name))
        target = target.queryParam("name", name);

    Response response = postResponse(target, content);
    String entity = response.readEntity(String.class);
    response.close();

    JsonStructure result;
    if (entity.isEmpty()) {
        result = Json.createObjectBuilder().add("message", "plugin pulled.").build();
    } else {
        result = Json.createReader(new StringReader(entity)).read();
    }
    return result;
}
 
Example 7
Source File: SearchRequest.java    From quandl4j with Apache License 2.0 6 votes vote down vote up
/**
 * Append any specified parameters to the provided WebTarget.
 * 
 * @param webTarget a web target used by the Jersey Client API, not null
 * @return the WebTarget with any path and query parameters appended
 */
public WebTarget appendPathAndQueryParameters(final WebTarget webTarget) {
  ArgumentChecker.notNull(webTarget, "webTarget");
  WebTarget resultTarget = webTarget;
  resultTarget = resultTarget.path(DATASETS_RELATIVE_URL + EXTENSION);
  if (_databaseCode != null) {
    resultTarget = resultTarget.queryParam(DATABASE_CODE_PARAM, _databaseCode);
  }
  if (_query != null) {
    resultTarget = resultTarget.queryParam(QUERY_PARAM, _query);
  }
  if (_pageNumber != null) {
    resultTarget = resultTarget.queryParam(PAGE_PARAM, _pageNumber);
  }
  if (_maxDocsPerPage != null) {
    resultTarget = resultTarget.queryParam(PER_PAGE_PARAM, _maxDocsPerPage);
  }
  return resultTarget;
}
 
Example 8
Source File: DefaultDockerClient.java    From docker-client with Apache License 2.0 6 votes vote down vote up
@Override
public void resizeTty(final String containerId, final Integer height, final Integer width)
    throws DockerException, InterruptedException {
  checkTtyParams(height, width);

  WebTarget resource = resource().path("containers").path(containerId).path("resize");
  if (height != null && height > 0) {
    resource = resource.queryParam("h", height);
  }
  if (width != null && width > 0) {
    resource = resource.queryParam("w", width);
  }

  try {
    request(POST, resource, resource.request(TEXT_PLAIN_TYPE));
  } catch (DockerRequestException e) {
    switch (e.status()) {
      case 404:
        throw new ContainerNotFoundException(containerId, e);
      default:
        throw e;
    }
  }
}
 
Example 9
Source File: DefaultDockerClient.java    From docker-client with Apache License 2.0 6 votes vote down vote up
private WebTarget addParameters(WebTarget resource, final Param... params)
    throws DockerException {
  final Map<String, List<String>> filters = newHashMap();
  for (final Param param : params) {
    if (param instanceof FilterParam) {
      List<String> filterValueList;
      if (filters.containsKey(param.name())) {
        filterValueList = filters.get(param.name());
      } else {
        filterValueList = Lists.newArrayList();
      }
      filterValueList.add(param.value());
      filters.put(param.name(), filterValueList);
    } else {
      resource = resource.queryParam(urlEncode(param.name()), urlEncode(param.value()));
    }
  }

  if (!filters.isEmpty()) {
    // If filters were specified, we must put them in a JSON object and pass them using the
    // 'filters' query param like this: filters={"dangling":["true"]}. If filters is an empty map,
    // urlEncodeFilters will return null and queryParam() will remove that query parameter.
    resource = resource.queryParam("filters", urlEncodeFilters(filters));
  }
  return resource;
}
 
Example 10
Source File: ShopifySdk.java    From shopify-sdk with Apache License 2.0 6 votes vote down vote up
public ShopifyPage<ShopifyCustomer> getCustomers(final ShopifyGetCustomersRequest shopifyGetCustomersRequest) {
	WebTarget target = getWebTarget().path(VERSION_2020_01).path(CUSTOMERS);
	if (shopifyGetCustomersRequest.getPageInfo() != null) {
		target = target.queryParam(PAGE_INFO_QUERY_PARAMETER, shopifyGetCustomersRequest.getPageInfo());
	}
	if (shopifyGetCustomersRequest.getLimit() != 0) {
		target = target.queryParam(LIMIT_QUERY_PARAMETER, shopifyGetCustomersRequest.getLimit());
	} else {
		target = target.queryParam(LIMIT_QUERY_PARAMETER, DEFAULT_REQUEST_LIMIT);
	}
	if (shopifyGetCustomersRequest.getIds() != null) {
		target = target.queryParam(IDS_QUERY_PARAMETER, String.join(",", shopifyGetCustomersRequest.getIds()));
	}
	if (shopifyGetCustomersRequest.getSinceId() != null) {
		target = target.queryParam(SINCE_ID_QUERY_PARAMETER, shopifyGetCustomersRequest.getSinceId());
	}
	if (shopifyGetCustomersRequest.getCreatedAtMin() != null) {
		target = target.queryParam(CREATED_AT_MIN_QUERY_PARAMETER, shopifyGetCustomersRequest.getCreatedAtMin());
	}
	if (shopifyGetCustomersRequest.getCreatedAtMax() != null) {
		target = target.queryParam(CREATED_AT_MAX_QUERY_PARAMETER, shopifyGetCustomersRequest.getCreatedAtMax());
	}
	final Response response = get(target);
	return getCustomers(response);
}
 
Example 11
Source File: DirectDebitMandateSearchService.java    From pay-publicapi with MIT License 5 votes vote down vote up
private WebTarget addQueryParams(Map<String, String> params, WebTarget originalWebTarget) {
    WebTarget webTargetWithQueryParams = originalWebTarget;
    for (Map.Entry<String, String> entry : params.entrySet()) {
        webTargetWithQueryParams = webTargetWithQueryParams.queryParam(entry.getKey(), entry.getValue());
    }
    return webTargetWithQueryParams;
}
 
Example 12
Source File: ClientUtils.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the content at the specified URI using the given query parameters.
 *
 * @param uri the URI to get the content of
 * @param queryParams the query parameters to use in the request
 * @return the client response resulting from getting the content of the URI
 */
public Response get(final URI uri, final Map<String, String> queryParams) {
    // perform the request
    WebTarget webTarget = client.target(uri);
    if (queryParams != null) {
        for (final Map.Entry<String, String> queryEntry : queryParams.entrySet()) {
            webTarget = webTarget.queryParam(queryEntry.getKey(), queryEntry.getValue());
        }
    }

    return webTarget.request().accept(MediaType.APPLICATION_JSON).get();
}
 
Example 13
Source File: DefaultDockerClient.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@Override
public void pull(final String image, final RegistryAuth registryAuth,
                 final ProgressHandler handler)
    throws DockerException, InterruptedException {
  final ImageRef imageRef = new ImageRef(image);

  WebTarget resource = resource().path("images").path("create");

  resource = resource.queryParam("fromImage", imageRef.getImage());
  if (imageRef.getTag() != null) {
    resource = resource.queryParam("tag", imageRef.getTag());
  }

  try {
    requestAndTail(POST, handler, resource,
            resource
                .request(APPLICATION_JSON_TYPE)
                .header("X-Registry-Auth", authHeader(registryAuth)));
  } catch (DockerRequestException e) {
    switch (e.status()) {
      case 404:
        throw new ImageNotFoundException(image, e);
      default:
        throw e;
    }
  }
}
 
Example 14
Source File: MultiMetaDataRequest.java    From quandl4j with Apache License 2.0 5 votes vote down vote up
/**
 * Append any specified parameters to the provided WebTarget.
 * 
 * @param webTarget a web target used by the Jersey Client API, not null
 * @return the WebTarget with any path and query parameters appended, not null
 */
public WebTarget appendPathAndQueryParameters(final WebTarget webTarget) {
  ArgumentChecker.notNull(webTarget, "webTarget");
  WebTarget resultTarget = webTarget;
  resultTarget = resultTarget.path(MULTI_SET_NAME + EXTENSION);
  resultTarget = resultTarget.queryParam(COLUMNS_PARAM, buildCodeList(_quandlCodes));
  // This is a hack that stops Quandl from returning all the data as part of the query
  resultTarget = resultTarget.queryParam(EXCLUDE_DATA_PARAM, INFINITE_FUTURE);
  return resultTarget;
}
 
Example 15
Source File: NonBalancedCRUDOperations.java    From TeaStore with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a list of Entities of the relevant type after filtering using a path
 * param query. Example: "category", 2, 1, 3 will return 3 items in Category
 * with ID 2, beginning from item with index 1 (skipping item 0). Note that the
 * AbstractCRUDEndpoint does not offer this feature by default.
 * 
 * @param client
 *          The REST client to use.
 * @param filterURI
 *          Name of the objects to filter for. E.g., "category".
 * @param filterId
 *          Id of the Object to filter for. E.g, 2
 * @param startIndex
 *          The index of the first entity to return (index, not ID!). -1, if you
 *          don't want to set an index.
 * @param limit
 *          Maximum amount of entities to return. -1, for no max.
 * @param <T>
 *          Type of entity to handle.
 * @throws NotFoundException
 *           If 404 was returned.
 * @throws TimeoutException
 *           If 408 was returned.
 * @return List of entities; empty list if non were found.
 */
public static <T> List<T> getEntities(RESTClient<T> client, String filterURI, long filterId,
    int startIndex, int limit) throws NotFoundException, TimeoutException {
  WebTarget target = client.getEndpointTarget().path(filterURI).path(String.valueOf(filterId));
  if (startIndex >= 0) {
    target = target.queryParam("start", startIndex);
  }
  if (limit >= 0) {
    target = target.queryParam("max", limit);
  }
  Response response = ResponseWrapper.wrap(HttpWrapper.wrap(target).get());
  List<T> entities = new ArrayList<T>();
  if (response != null && response.getStatus() == 200) {
    try {
      entities = response.readEntity(client.getGenericListType());
    } catch (ProcessingException e) {
      e.printStackTrace();
      LOG.warn("Response did not conform to expected entity type. List expected.");
    }
  } else if (response != null) {
    response.bufferEntity();
  }
  if (response != null && response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
    throw new NotFoundException();
  } else if (response != null && response.getStatus() == Status.REQUEST_TIMEOUT.getStatusCode()) {
    throw new TimeoutException();
  }
  return entities;
}
 
Example 16
Source File: DelimitedRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private Response testMapPreview(String fileName, String jsonld, Map<String, Object> params) {
    FormDataMultiPart fd = new FormDataMultiPart();
    fd.field("jsonld", jsonld);
    WebTarget wt = target().path("delimited-files/" + fileName + "/map-preview");
    if (params != null) {
        for (String k : params.keySet()) {
            wt = wt.queryParam(k, params.get(k));
        }
    }
    Response response = wt.request().post(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA));
    assertEquals(response.getStatus(), 200);
    return response;
}
 
Example 17
Source File: TopicsImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Void> updatePartitionedTopicAsync(String topic, int numPartitions,
        boolean updateLocalTopicOnly) {
    checkArgument(numPartitions > 0, "Number of partitions must be more than 0");
    TopicName tn = validateTopic(topic);
    WebTarget path = topicPath(tn, "partitions");
    path = path.queryParam("updateLocalTopicOnly", Boolean.toString(updateLocalTopicOnly));
    return asyncPostRequest(path, Entity.entity(numPartitions, MediaType.APPLICATION_JSON));
}
 
Example 18
Source File: ExportOperationTest.java    From FHIR with Apache License 2.0 5 votes vote down vote up
/**
 * add query parameter list
 */
public WebTarget addQueryParameterList(WebTarget target, String header, List<String> vals) {
    if (header != null && vals != null && !vals.isEmpty()) {
        target = target.queryParam(header, vals.stream().collect(Collectors.joining(",")));
    }
    return target;
}
 
Example 19
Source File: PlanDefinitionApplyOperationTest.java    From FHIR with Apache License 2.0 5 votes vote down vote up
/**
 * adds the query parameter
 * 
 * @param target
 * @param header
 * @param val
 * @return
 */
public WebTarget addQueryParameter(WebTarget target, String header, String val) {
    if (header != null) {
        if (val != null) {
            target = target.queryParam(header, val);
        }

    }
    return target;
}
 
Example 20
Source File: AnswerResourceTest.java    From batfish with Apache License 2.0 4 votes vote down vote up
private static WebTarget addSnapshotQuery(WebTarget webTarget, @Nullable String snapshot) {
  return snapshot == null ? webTarget : webTarget.queryParam("snapshot", snapshot);
}