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 File: Evaluator.java    From openscoring with 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 #2
Source File: FHIRClientImpl.java    From FHIR with 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 #3
Source File: ClientCacheTest.java    From cxf with 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 #4
Source File: IntegrationTest.java    From timbuctoo with 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 #5
Source File: FHIRClientImpl.java    From FHIR with 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 #6
Source File: EtcdV2ProxyImpl.java    From etcd-viewer with 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 #7
Source File: DefaultDockerClient.java    From docker-client with 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 #8
Source File: JerseyClientServiceShould.java    From mutual-tls-ssl with 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 #9
Source File: JAXRSAsyncClientTest.java    From cxf with 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 #10
Source File: RestPayloadPublisherTest.java    From tessera with 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 #11
Source File: DigdagClient.java    From digdag with 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 #12
Source File: BaseClientUtils.java    From dremio-oss with 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 #13
Source File: CloudantStoreTest.java    From todo-apps with 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 #14
Source File: ClientCacheTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTimeString() {
    CacheControlFeature feature = new CacheControlFeature();
    try {
        final WebTarget base = ClientBuilder.newBuilder().register(feature).build().target(ADDRESS);
        final Invocation.Builder cached = base.request("text/plain").header(HttpHeaders.CACHE_CONTROL, "public");
        final Response r = cached.get();
        assertEquals(Response.Status.OK.getStatusCode(), r.getStatus());
        final String r1 = r.readEntity(String.class);
        waitABit();
        assertEquals(r1, cached.get().readEntity(String.class));
    } finally {
        feature.close();
    }
}
 
Example #15
Source File: DefaultAlertsPoliciesApi.java    From newrelic-alerts-configurator with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<AlertsPolicy> getByName(String alertsPolicyName) {
    Invocation.Builder builder = client
            .target(POLICIES_URL)
            .queryParam("filter[name]", alertsPolicyName)
            .request(APPLICATION_JSON_TYPE);
    return getPageable(builder, AlertsPolicyList.class)
            .filter(alertsPolicy -> alertsPolicy.getName().equals(alertsPolicyName))
            .getSingle();
}
 
Example #16
Source File: DefaultServersApi.java    From newrelic-alerts-configurator with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<Server> getByName(String serverName) {
    String serverNameEncoded = UriComponent.encode(serverName, QUERY_PARAM_SPACE_ENCODED);
    Invocation.Builder builder = client
            .target(SERVERS_URL)
            .queryParam("filter[name]", serverNameEncoded)
            .request(APPLICATION_JSON_TYPE);
    return getPageable(builder, ServerList.class)
            .filter(application -> application.getName().equals(serverName))
            .getSingle();
}
 
Example #17
Source File: DefaultServersApiTest.java    From newrelic-alerts-configurator with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    NewRelicClient clientMock = mock(NewRelicClient.class);
    WebTarget webTargetMock = mock(WebTarget.class);
    Invocation.Builder builderMock = mock(Invocation.Builder.class);

    when(clientMock.target("/v2/servers.json")).thenReturn(webTargetMock);
    when(webTargetMock.queryParam("filter[name]", "server")).thenReturn(webTargetMock);
    when(webTargetMock.request(APPLICATION_JSON_TYPE)).thenReturn(builderMock);
    when(builderMock.get()).thenReturn(responseMock);

    testee = new DefaultServersApi(clientMock);
}
 
Example #18
Source File: CreateExperimentRequestBuilder.java    From alchemy with 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 #19
Source File: TestCustomAuth.java    From jobson with Apache License 2.0 5 votes vote down vote up
@Test
public void testAcceptsCredentialsHardCodedByTheCustomAuthScheme() {
    final Invocation.Builder b = generateRequest(RULE, HTTP_USERS_PATH + "/current");
    authenticate(b, USERNAME_IN_CONFIG_TEMPLATE, PASSWORD_IN_CONFIG_TEMPLATE);

    final Response response = b.get();

    assertThat(response.getStatus()).isEqualTo(OK);
}
 
Example #20
Source File: Keycloak.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
private Invocation.Builder rest(String path) {
    if(token == null)
        throw new RuntimeException("Have to login first.");

    Client client = ClientBuilder.newClient(); // TODO cache this?
    return client.target(baseUrl + "/auth/admin").path(path)
            .request(MediaType.APPLICATION_JSON_TYPE)
            .header("Authorization", "bearer " + token);
}
 
Example #21
Source File: YandexTranslate.java    From nifi with Apache License 2.0 5 votes vote down vote up
protected Invocation prepareResource(final String key, final List<String> text, final String sourceLanguage, final String destLanguage) {
    Invocation.Builder builder = client.target(URL).request(MediaType.APPLICATION_JSON);

    final MultivaluedHashMap entity = new MultivaluedHashMap();
    entity.put("text", text);
    entity.add("key", key);
    if ((StringUtils.isBlank(sourceLanguage))) {
        entity.add("lang", destLanguage);
    } else {
        entity.add("lang", sourceLanguage + "-" + destLanguage);
    }

    return builder.buildPost(Entity.form(entity));
}
 
Example #22
Source File: BaseTestServer.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
protected DatasetUI delete(String datasetResourcePath, String savedVersion) {
  final Invocation invocation =
      getBuilder(
          getAPIv2()
              .path(datasetResourcePath)
              .queryParam("savedTag", savedVersion)
      ).buildDelete();

  return expectSuccess(invocation, DatasetUI.class);
}
 
Example #23
Source File: EndpointTest.java    From tool.accelerate.core with 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 #24
Source File: RestPayloadPublisherTest.java    From tessera with Apache License 2.0 5 votes vote down vote up
@Test
public void publishReturns201() {

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

    List<javax.ws.rs.client.Entity> postedEntities = new ArrayList<>();

    doAnswer((invocation) -> {
        postedEntities.add(invocation.getArgument(0));
        return Response.created(URI.create("http://location")).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);

    publisher.publishPayload(encodedPayload, targetUrl);

    assertThat(postedEntities).hasSize(1);

    Entity entity = postedEntities.get(0);
    assertThat(entity.getMediaType()).isEqualTo(MediaType.APPLICATION_OCTET_STREAM_TYPE);
    assertThat(entity.getEntity()).isSameAs(payloadData);

    verify(encoder).encode(encodedPayload);
    verify(invocationBuilder).post(any(javax.ws.rs.client.Entity.class));
}
 
Example #25
Source File: BasicRESTClient.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Override
public Response deleteRequestWithHeaders(final URL url, final Map<String, Object> headers)
        throws MalformedURLException, URISyntaxException {
    if (sessionToken == null) {
        LOGGER.log(Level.SEVERE, String.format("Token is null in call to RESTClient for url: %s", url.toString()));
        return null;
    }
    Invocation.Builder builder = client.target(url.toURI()).request(MediaType.APPLICATION_JSON);
    builder = getCommonRequestBuilder(sessionToken, builder, headers);
    Invocation i = builder.buildDelete();
    return i.invoke();
}
 
Example #26
Source File: CloudantStoreTest.java    From todo-apps with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAll() throws Exception {
  IMocksControl control = createControl();
  Response resp = control.createMock(Response.class);
  expect(resp.getStatus()).andReturn(200).times(3);
  Capture<Class<CloudantAllDocs>> classCapture = new Capture<Class<CloudantAllDocs>>();
  expect(resp.readEntity(capture(classCapture))).andReturn(docs);
  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).times(2);
  expect(wt.path(eq("_design"))).andReturn(wt).times(2);
  expect(wt.path(eq("_view"))).andReturn(wt);
  expect(wt.path(eq("allTodos"))).andReturn(wt);
  expect(wt.queryParam(eq("reduce"), eq(false))).andReturn(wt);
  //expect(wt.queryParam(eq("include_docs"), eq(true))).andReturn(wt);
  expect(wt.request(eq("application/json"))).andReturn(builder).anyTimes();
  replay(wt);
  CloudantStore store = new CloudantStore(wt);
  Collection<ToDo> todos = store.getAll();
  List<ToDo> testToDos = new ArrayList<ToDo>();
  testToDos.add(ctd1.getToDo());
  testToDos.add(ctd2.getToDo());
  testToDos.add(ctd3.getToDo());
  assertEquals(testToDos, todos);
  assertEquals(CloudantAllDocs.class, classCapture.getValue());
  verify(resp);
  verify(wt);
  verify(builder);
}
 
Example #27
Source File: BasicRESTClient.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Override
public Response getRequestWithHeaders(final URL url, final Map<String, Object> headers) throws URISyntaxException {
    if (sessionToken == null) {
        LOGGER.log(Level.SEVERE, String.format("Token is null in call to RESTClient for url: %s", url.toString()));
        return null;
    }
    Invocation.Builder builder = client.target(url.toURI()).request(MediaType.APPLICATION_JSON);
    builder = getCommonRequestBuilder(sessionToken, builder, headers);
    Invocation i = builder.buildGet();
    return i.invoke();
}
 
Example #28
Source File: BaseTestServer.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
protected void saveExpectConflict(DatasetUI datasetUI, String saveVersion) {
  final Invocation invocation =
      getBuilder(
          getAPIv2()
              .path(versionedResourcePath(datasetUI) + "/save")
              .queryParam("savedTag", saveVersion)
      ).buildPost(entity("", JSON));

  expectStatus(Status.CONFLICT, invocation);
}
 
Example #29
Source File: BaseTestServer.java    From dremio-oss with 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);
}
 
Example #30
Source File: TestPhysicalDatasets.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Test
public void testXlsNullSheetName() throws Exception {
  Invocation inv = getXlsTestQueryInvocation(getUrlPath("/testfiles/excel.xls"), null, false, false);
  JobDataFragment data = expectSuccess(inv, JobDataFragment.class);
  assertEquals(6, data.getReturnedRowCount());
  assertEquals(5, data.getColumns().size());
}