javax.ws.rs.client.Invocation Java Examples

The following examples show how to use javax.ws.rs.client.Invocation. 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 Project: FHIR   Author: IBM   File: FHIRClientImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public FHIRResponse history(String resourceType, String resourceId, FHIRParameters parameters, FHIRRequestHeader... headers) throws Exception {
    if (resourceType == null) {
        throw new IllegalArgumentException("The 'resourceType' argument is required but was null.");
    }
    if (resourceId == null) {
        throw new IllegalArgumentException("The 'resourceId' argument is required but was null.");
    }
    WebTarget endpoint = getWebTarget();
    endpoint = endpoint.path(resourceType).path(resourceId).path("_history");
    endpoint = addParametersToWebTarget(endpoint, parameters);
    Invocation.Builder builder = endpoint.request(getDefaultMimeType());
    builder = addRequestHeaders(builder, headers);
    Response response = builder.get();
    return new FHIRResponseImpl(response);
}
 
Example #2
Source Project: timbuctoo   Author: HuygensING   File: IntegrationTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
private Invocation.Builder call(String path) {
  String server;
  if (path.startsWith("http://") || path.startsWith("https://")) {
    server = path;
  } else {
    int localPort = APP.getLocalPort();
    // int localPort = 8080;
    server = format("http://localhost:%d" + path, localPort);
  }
  return client
    .target(server)
    .register(MultiPartFeature.class)
    // .register(new LoggingFilter(Logger.getLogger(LoggingFilter.class.getName()), true))
    .request()
    .header("Authorization", AUTH);
}
 
Example #3
Source Project: FHIR   Author: IBM   File: FHIRClientImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public FHIRResponse invoke(String resourceType, String operationName, FHIRParameters parameters, FHIRRequestHeader... headers) throws Exception {
    if (resourceType == null) {
        throw new IllegalArgumentException("The 'resourceType' argument is required but was null.");
    }
    if (operationName == null) {
        throw new IllegalArgumentException("The 'operationName' argument is required but was null.");
    }
    WebTarget endpoint = getWebTarget();
    endpoint = endpoint.path(resourceType).path(operationName);
    endpoint = addParametersToWebTarget(endpoint, parameters);
    Invocation.Builder builder = endpoint.request(getDefaultMimeType());
    builder = addRequestHeaders(builder, headers);
    Response response = builder.get();
    return new FHIRResponseImpl(response);
}
 
Example #4
Source Project: etcd-viewer   Author: nikfoundas   File: EtcdV2ProxyImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public EtcdNode deleteNode(EtcdNode node, boolean recursive) {

    WebTarget target = getWebTarget().path("/v2/keys/{key}").resolveTemplate("key", normalizeKey(node.getKey()), false);

    if (node.isDir()) {
        if (recursive) {
            target = target.queryParam("recursive", recursive);
        } else {
            target = target.queryParam("dir", node.isDir());
        }
    }

    Invocation deleteInvocation = target.request(MediaType.APPLICATION_JSON).buildDelete();

    return new ExceptionHandlingProcessor<>(EtcdResponse.class).process(deleteInvocation).getNode();
}
 
Example #5
Source Project: docker-client   Author: spotify   File: DefaultDockerClient.java    License: Apache License 2.0 6 votes vote down vote up
private LogStream getLogStream(final String method, final WebTarget resource,
                               final String containerId)
    throws DockerException, InterruptedException {
  try {
    final Invocation.Builder request = resource.request("application/vnd.docker.raw-stream");
    return request(method, LogStream.class, resource, request);
  } catch (DockerRequestException e) {
    switch (e.status()) {
      case 400:
        throw new BadParamException(getQueryParamMap(resource), e);
      case 404:
        throw new ContainerNotFoundException(containerId);
      default:
        throw e;
    }
  }
}
 
Example #6
Source Project: mutual-tls-ssl   Author: Hakky54   File: JerseyClientServiceShould.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void executeRequest() {
    WebTarget webTarget = mock(WebTarget.class);
    Invocation.Builder requestBuilder = mock(Invocation.Builder.class);
    Response response = mock(Response.class);

    when(client.target(HTTP_URL)).thenReturn(webTarget);
    when(webTarget.request(MediaType.TEXT_PLAIN_TYPE)).thenReturn(requestBuilder);
    when(requestBuilder.header(HEADER_KEY_CLIENT_TYPE, ClientType.JERSEY_CLIENT.getValue())).thenReturn(requestBuilder);
    when(requestBuilder.get()).thenReturn(response);
    when(response.readEntity(String.class)).thenReturn("Hello");
    when(response.getStatus()).thenReturn(200);

    ClientResponse clientResponse = victim.executeRequest(HTTP_URL);

    assertThat(clientResponse.getStatusCode()).isEqualTo(200);
    assertThat(clientResponse.getResponseBody()).isEqualTo("Hello");
}
 
Example #7
Source Project: cxf   Author: apache   File: JAXRSAsyncClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNonExistentJaxrs20WithPost() throws Exception {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target("http://168.168.168.168/");
    Invocation.Builder builder = target.request();
    Entity<String> entity = Entity.entity("entity", MediaType.WILDCARD_TYPE);
    Invocation invocation = builder.buildPost(entity);
    Future<String> future = invocation.submit(
        new GenericType<String>() {
        }
    );

    try {
        future.get();
    } catch (Exception ex) {
        Throwable cause = ex.getCause();
        assertTrue(cause instanceof ProcessingException);
    }
}
 
Example #8
Source Project: cxf   Author: apache   File: ClientCacheTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetJaxbBookCacheByValue() {
    // org.apache.cxf.jaxrs.client.cache.CacheControlFeature.storeByValue
    CacheControlFeature feature = new CacheControlFeature();
    try {
        final WebTarget base = ClientBuilder.newBuilder()
            .property("org.apache.cxf.jaxrs.client.cache.CacheControlFeature.storeByValue", "true")
            .register(feature).build().target(ADDRESS);
        final Invocation.Builder cached =
            setAsLocal(base.request("application/xml")).header(HttpHeaders.CACHE_CONTROL, "public");
        final Response r = cached.get();
        assertEquals(Response.Status.OK.getStatusCode(), r.getStatus());
        final Book b1 = r.readEntity(Book.class);
        assertEquals("JCache", b1.getName());
        assertNotNull(b1.getId());
        waitABit();
        assertEquals(b1, cached.get().readEntity(Book.class));
    } finally {
        feature.close();
    }
}
 
Example #9
Source Project: tessera   Author: jpmorganchase   File: RestPayloadPublisherTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void publishReturnsError() {

    Invocation.Builder invocationBuilder = mockClient.getWebTarget().getMockInvocationBuilder();

    doAnswer((invocation) -> {
        return Response.serverError().build();
    }).when(invocationBuilder).post(any(javax.ws.rs.client.Entity.class));

    String targetUrl = "http://someplace.com";

    EncodedPayload encodedPayload = mock(EncodedPayload.class);
    byte[] payloadData = "Some Data".getBytes();
    when(encoder.encode(encodedPayload)).thenReturn(payloadData);

    try {
        publisher.publishPayload(encodedPayload, targetUrl);
        failBecauseExceptionWasNotThrown(PublishPayloadException.class);
    } catch (PublishPayloadException ex) {
        verify(encoder).encode(encodedPayload);
        verify(invocationBuilder).post(any(javax.ws.rs.client.Entity.class));
    }

}
 
Example #10
Source Project: digdag   Author: treasure-data   File: DigdagClient.java    License: Apache License 2.0 6 votes vote down vote up
public InputStream getProjectArchive(Id projId, String revision)
{
    WebTarget webTarget = target("/api/projects/{id}/archive")
            .resolveTemplate("id", projId)
            .queryParam("revision", revision);
    webTarget = addDisableDirectDownloadParam(webTarget);
    return withFollowingRedirect(webTarget,
            (wt, lastResponse) -> {
                Invocation.Builder request = wt.request();
                if (!lastResponse.isPresent()) {
                    // Headers shouldn't be appended when redirecting.
                    // With headers S3 can return "Bad Request"
                    request.headers(headers.get());
                }
                return invokeWithRetry(request.buildGet())
                        .readEntity(InputStream.class);
            }
    );
}
 
Example #11
Source Project: dremio-oss   Author: dremio   File: BaseClientUtils.java    License: Apache License 2.0 6 votes vote down vote up
protected Response expect(ResponseExpectation expectation, Invocation i) {
  try (Timer.TimedBlock b = Timer.time("request")) {
    Response response = i.invoke();
    response.bufferEntity();
    try {
      expectation.validate(response);
    } catch (AssertionError e) {
      // this will show the body of the response in the error message
      // if an error occurred it will show the server side error.
      // response.toString() does not show the content
      String body = response.readEntity(String.class);
      throw new AssertionError(String.format("%s\n%s\n%s", e.getMessage(), response.toString(), body), e);
    }
    return response;
  }
}
 
Example #12
Source Project: todo-apps   Author: IBM-Cloud   File: CloudantStoreTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGet() throws Exception {
  IMocksControl control = createControl();
  Response resp = control.createMock(Response.class);
  expect(resp.getStatus()).andReturn(200).times(3);
  Capture<Class<CloudantToDo>> classCapture = new Capture<Class<CloudantToDo>>();
  expect(resp.readEntity(capture(classCapture))).andReturn(ctd1);
  replay(resp);
  WebTarget wt = createMockWebTarget();
  Invocation.Builder builder = createBuilder();
  expect(builder.get()).andReturn(resp).times(3);
  replay(builder);
  expect(wt.path(eq("bluemix-todo"))).andReturn(wt).times(2);
  expect(wt.path(eq("todos"))).andReturn(wt);
  expect(wt.path(eq("_design"))).andReturn(wt).times(1);
  expect(wt.path(eq("123"))).andReturn(wt);
  expect(wt.request(eq("application/json"))).andReturn(builder).anyTimes();
  replay(wt);
  CloudantStore store = new CloudantStore(wt);
  assertEquals(ctd1.getToDo(), store.get("123"));
  assertEquals(CloudantToDo.class, classCapture.getValue());
  verify(resp);
  verify(wt);
  verify(builder);
}
 
Example #13
Source Project: openscoring   Author: openscoring   File: Evaluator.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public EvaluationResponse evaluate() throws Exception {
	Operation<EvaluationResponse> operation = new Operation<EvaluationResponse>(){

		@Override
		public EvaluationResponse perform(WebTarget target) throws Exception {
			EvaluationRequest request = new EvaluationRequest()
				.setArguments(getArguments());

			Invocation invocation = target.request(MediaType.APPLICATION_JSON).buildPost(Entity.json(request));

			Response response = invocation.invoke();

			return response.readEntity(EvaluationResponse.class);
		}
	};

	return execute(operation);
}
 
Example #14
Source Project: alchemy   Author: RentTheRunway   File: CreateExperimentRequestBuilder.java    License: MIT License 5 votes vote down vote up
public CreateExperimentRequestBuilder(String name, Invocation.Builder builder) {
    this.name = name;
    this.builder = builder;
    this.treatments = Lists.newArrayList();
    this.allocations = Lists.newArrayList();
    this.overrides = Lists.newArrayList();
}
 
Example #15
Source Project: tool.accelerate.core   Author: WASdev   File: EndpointTest.java    License: Apache License 2.0 5 votes vote down vote up
public Response sendRequest(String url, String requestType) {
    Client client = ClientBuilder.newClient();
    System.out.println("Testing " + url);
    WebTarget target = client.target(url);
    Invocation.Builder invoBuild = target.request();
    Response response = invoBuild.build(requestType).invoke();
    return response;
}
 
Example #16
Source Project: FHIR   Author: IBM   File: FHIRClientImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public FHIRResponse search(String resourceType, FHIRParameters parameters, FHIRRequestHeader... headers) throws Exception {
    if (resourceType == null) {
        throw new IllegalArgumentException("The 'resourceType' argument is required but was null.");
    }
    WebTarget endpoint = getWebTarget();
    endpoint = endpoint.path(resourceType);
    endpoint = addParametersToWebTarget(endpoint, parameters);
    Invocation.Builder builder = endpoint.request(getDefaultMimeType());
    builder = addRequestHeaders(builder, headers);
    Response response = builder.get();
    return new FHIRResponseImpl(response);
}
 
Example #17
Source Project: TeaStore   Author: DescartesResearch   File: Tracing.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This function is used to inject the current span context into the request to
 * be made.
 *
 * @param requestBuilder The requestBuilder object that gets injected
 */
public static void inject(Invocation.Builder requestBuilder) {
  Span activeSpan = GlobalTracer.get().activeSpan();
  if (activeSpan != null) {
    GlobalTracer.get().inject(activeSpan.context(), Format.Builtin.HTTP_HEADERS,
        Tracing.requestBuilderCarrier(requestBuilder));
  }
}
 
Example #18
Source Project: dremio-oss   Author: dremio   File: TestPhysicalDatasets.java    License: Apache License 2.0 5 votes vote down vote up
private Invocation getExcelTestQueryInvocation(String filePath, String sheet, boolean extractHeader,
                                               boolean hasMergedCells) {
  ExcelFileConfig fileConfig = new ExcelFileConfig();
  fileConfig.setSheetName(sheet);
  if (extractHeader) {
    fileConfig.setExtractHeader(true);
  } // false is the default value
  if (hasMergedCells) {
    fileConfig.setHasMergedCells(true);
  } // false is the default value

  return getBuilder(getAPIv2().path("/source/dacfs_test/file_preview" + filePath))
    .buildPost(Entity.json(fileConfig));
}
 
Example #19
Source Project: nifi   Author: apache   File: ClientUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Performs a POST using the specified url and form data.
 *
 * @param uri the uri to post to
 * @param formData the data to post
 * @return the client response of the post
 */
public Response post(URI uri, Map<String, String> formData) {
    // convert the form data
    final MultivaluedHashMap<String, String> entity = new MultivaluedHashMap();
    for (String key : formData.keySet()) {
        entity.add(key, formData.get(key));
    }

    // get the resource
    Invocation.Builder builder = client.target(uri).request().accept(MediaType.APPLICATION_JSON);

    // get the resource
    return builder.post(Entity.form(entity));
}
 
Example #20
Source Project: FHIR   Author: IBM   File: FHIRClientImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public FHIRResponse invoke(String operationName, FHIRParameters parameters, FHIRRequestHeader... headers) throws Exception {
    if (operationName == null) {
        throw new IllegalArgumentException("The 'operationName' argument is required but was null.");
    }
    WebTarget endpoint = getWebTarget();
    endpoint = endpoint.path(operationName);
    endpoint = addParametersToWebTarget(endpoint, parameters);
    Invocation.Builder builder = endpoint.request(getDefaultMimeType());
    builder = addRequestHeaders(builder, headers);
    Response response = builder.get();
    return new FHIRResponseImpl(response);
}
 
Example #21
Source Project: athenz   Author: yahoo   File: InstanceProviderClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInstanceProviderClientRefreshConfirmation() {
    String url = "http://localhost:10099/instance";
    ProviderHostnameVerifier hostnameVerifier = new ProviderHostnameVerifier("athenz.provider");
    InstanceProviderClient provClient = new InstanceProviderClient(url, null, hostnameVerifier, 10000, 10000);

    WebTarget base = Mockito.mock(WebTarget.class);
    provClient.setBase(base);
    
    WebTarget target = Mockito.mock(WebTarget.class);
    Mockito.when(base.path("/refresh")).thenReturn(target);

    Invocation.Builder builder = Mockito.mock(Invocation.Builder.class);
    Mockito.when(target.request("application/json")).thenReturn(builder);
    Mockito.when(builder.header("Athenz-Principal-Token", "v=S1;d=athenz;n=service;s=signature")).thenReturn(builder);

    InstanceConfirmation confirmation = new InstanceConfirmation()
            .setAttestationData("data").setDomain("athenz")
            .setProvider("provider").setService("service");
    Entity<?> entity = Entity.entity(confirmation, "application/json");
    Response response = Mockito.mock(Response.class);
    Mockito.when(builder.post(entity)).thenReturn(response);
    Mockito.when(response.getStatus()).thenReturn(200);
    Mockito.when(response.readEntity(InstanceConfirmation.class)).thenReturn(confirmation);
    
    InstanceConfirmation result = provClient.postRefreshConfirmation(confirmation);
    assertEquals(result.getAttestationData(), "data");
    assertEquals(result.getDomain(), "athenz");
    assertEquals(result.getProvider(), "provider");
    assertEquals(result.getService(), "service");
    
    provClient.close();
}
 
Example #22
Source Project: jcypher   Author: Wolfgang-Schuetzelhofer   File: RemoteDBAccess.java    License: Apache License 2.0 5 votes vote down vote up
private synchronized Invocation.Builder getInvocationBuilder() {
	if (this.invocationBuilder == null) {
		this.invocationBuilder = getTransactionalTarget().request(MediaType.APPLICATION_JSON_TYPE);
		if (this.auth != null)
			this.invocationBuilder = this.invocationBuilder.header(authHeader, this.auth);
	}
	return this.invocationBuilder;
}
 
Example #23
Source Project: development   Author: servicecatalog   File: RestDAO.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Send a GET request and get the plain text in the response
 * 
 * @param webResource
 *            a web resource
 * @return the text from the response
 * @throws BillingException
 *             if the GET request fails
 */
public String getTextResponse(WebTarget webResource)
        throws BillingException {

    Invocation invocation = webResource
            .request(MediaType.TEXT_PLAIN_TYPE).buildGet();
    try {
        return invocation.invoke(String.class);
    } catch (RuntimeException e) {
        throw new BillingException(
                "Error when processing response from File Billing Application",
                e);
    }
}
 
Example #24
Source Project: keycloak   Author: keycloak   File: DBAllocatorServiceClient.java    License: Apache License 2.0 5 votes vote down vote up
public EraseResult erase(AllocationResult allocationResult) throws DBAllocatorException {
    Objects.requireNonNull(allocationResult, "Previous allocation result must not be null");
    Objects.requireNonNull(allocationResult.getUUID(), "UUID must not be null");

    Invocation.Builder target = restClient
            .target(allocatorServletURI)
            .queryParam("operation", "erase")
            .queryParam("uuid", allocationResult.getUUID())
            .request();

    try (Response response = retryPolicy.retryTillHttpOk(() -> target.get())) {
        return EraseResult.successful(allocationResult.getUUID());
    }
}
 
Example #25
Source Project: alchemy   Author: RentTheRunway   File: AlchemyClient.java    License: MIT License 5 votes vote down vote up
protected Invocation.Builder resource(String path, Map<String, ?> pathParams) {
    return
        client
            .target(assembleRequestURI(pathParams, EMPTY_QUERY_PARAMS, path))
            .request()
            .accept(MediaType.APPLICATION_JSON_TYPE);
}
 
Example #26
Source Project: tool.accelerate.core   Author: WASdev   File: EndpointTest.java    License: Apache License 2.0 5 votes vote down vote up
public Response sendRequest(String url, String requestType) {
    Client client = ClientBuilder.newClient();
    System.out.println("Testing " + url);
    WebTarget target = client.target(url);
    Invocation.Builder invoBuild = target.request();
    Response response = invoBuild.build(requestType).invoke();
    return response;
}
 
Example #27
Source Project: microprofile-lra   Author: eclipse   File: LRAClientOps.java    License: Apache License 2.0 5 votes vote down vote up
private synchronized Response invokeRestEndpoint(URI lra, String basePath, String path, int coerceResponse) {
    WebTarget resourcePath = target.path(basePath).path(path).queryParam(STATUS_CODE_QUERY_NAME, coerceResponse);
    Invocation.Builder builder = resourcePath.request();

    if (lra != null) {
        builder.header(LRA.LRA_HTTP_CONTEXT_HEADER, lra);
    }

    return builder.put(Entity.text(""));
}
 
Example #28
Source Project: athenz   Author: yahoo   File: InstanceProviderClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInstanceProviderClientHostnameVerifier() {
    String url = "http://localhost:10099/instance";
    ProviderHostnameVerifier hostnameVerifier = new ProviderHostnameVerifier("athenz.production");
    InstanceProviderClient provClient = new InstanceProviderClient(url, null, hostnameVerifier, 10000, 10000);
    
    WebTarget base = Mockito.mock(WebTarget.class);
    provClient.setBase(base);
    
    WebTarget target = Mockito.mock(WebTarget.class);
    Mockito.when(base.path("/instance")).thenReturn(target);

    Invocation.Builder builder = Mockito.mock(Invocation.Builder.class);
    Mockito.when(target.request("application/json")).thenReturn(builder);
    Mockito.when(builder.header("Athenz-Principal-Token", "v=S1;d=athenz;n=service;s=signature")).thenReturn(builder);

    InstanceConfirmation confirmation = new InstanceConfirmation()
            .setAttestationData("data").setDomain("athenz")
            .setProvider("provider").setService("service");
    Entity<?> entity = Entity.entity(confirmation, "application/json");
    Response response = Mockito.mock(Response.class);
    Mockito.when(builder.post(entity)).thenReturn(response);
    Mockito.when(response.getStatus()).thenReturn(200);
    Mockito.when(response.readEntity(InstanceConfirmation.class)).thenReturn(confirmation);
    
    InstanceConfirmation result = provClient.postInstanceConfirmation(confirmation);
    assertEquals(result.getAttestationData(), "data");
    assertEquals(result.getDomain(), "athenz");
    assertEquals(result.getProvider(), "provider");
    assertEquals(result.getService(), "service");
    
    provClient.close();
}
 
Example #29
Source Project: openapi-generator   Author: OpenAPITools   File: ApiClient.java    License: Apache License 2.0 5 votes vote down vote up
private Response sendRequest(String method, Invocation.Builder invocationBuilder, Entity<?> entity) {
  Response response;
  if ("POST".equals(method)) {
    response = invocationBuilder.post(entity);
  } else if ("PUT".equals(method)) {
    response = invocationBuilder.put(entity);
  } else if ("DELETE".equals(method)) {
    response = invocationBuilder.method("DELETE", entity);
  } else if ("PATCH".equals(method)) {
    response = invocationBuilder.method("PATCH", entity);
  } else {
    response = invocationBuilder.method(method);
  }
  return response;
}
 
Example #30
Source Project: dremio-oss   Author: dremio   File: BaseTestServer.java    License: Apache License 2.0 5 votes vote down vote up
protected DatasetUI move(DatasetPath currenPath, DatasetPath newPath) {
  final Invocation invocation =
      getBuilder(
          getAPIv2()
              .path("dataset/" + currenPath.toString() + "/moveTo/" + newPath.toString())
      ).buildPost(null);

  return expectSuccess(invocation, DatasetUI.class);
}