javax.ws.rs.client.Client Java Examples

The following examples show how to use javax.ws.rs.client.Client. 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: TestHelper.java    From aries-jax-rs-whiteboard with Apache License 2.0 6 votes vote down vote up
protected WebTarget createDefaultTarget() {
    Client client = createClient();

    String[] runtimes = canonicalize(
        _runtimeServiceReference.getProperty("osgi.jaxrs.endpoint"));

    if (runtimes.length == 0) {
        throw new IllegalStateException(
            "No runtimes could be found on \"osgi.jaxrs.endpoint\" " +
                "runtime service property ");
    }

    String runtime = runtimes[0];

    return client.target(runtime);
}
 
Example #2
Source File: JAXRSAsyncClientTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonExistentJaxrs20WithGet() throws Exception {
    String address = "http://168.168.168.168/bookstore";
    Client c = ClientBuilder.newClient();
    c.register(new TestResponseFilter());
    WebTarget t1 = c.target(address);
    Future<Response> future = t1.request().async().get();
    try {
        future.get();
        fail("Exception expected");
    } catch (ExecutionException ex) {
        Throwable cause = ex.getCause();
        assertTrue(cause instanceof ProcessingException);
        assertTrue(ex.getCause().getCause() instanceof IOException);
    } finally {
        c.close();
    }
}
 
Example #3
Source File: MpMetricsResource.java    From javaee8-cookbook with Apache License 2.0 6 votes vote down vote up
private String getResource() {
    Client client = null;
    String response;

    try {
        client = ClientBuilder.newClient();
        WebTarget target = client.target("https://eldermoraes.com/book");
        response = target.request()
                .header("Content-Type", "application/json")
                .get(String.class);
    } finally {
        if (client != null) {
            client.close();
        }
    }

    return response;
}
 
Example #4
Source File: FlowOverrideTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testGrantAccessTokenWithClientOverride() throws Exception {
    String clientId = TEST_APP_DIRECT_OVERRIDE;
    Client httpClient = javax.ws.rs.client.ClientBuilder.newClient();
    String grantUri = oauth.getResourceOwnerPasswordCredentialGrantUrl();
    WebTarget grantTarget = httpClient.target(grantUri);

    {   // test no password
        String header = BasicAuthHelper.createHeader(clientId, "password");
        Form form = new Form();
        form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
        form.param("username", "test-user@localhost");
        Response response = grantTarget.request()
                .header(HttpHeaders.AUTHORIZATION, header)
                .post(Entity.form(form));
        assertEquals(200, response.getStatus());
        response.close();
    }

    httpClient.close();
    events.clear();
}
 
Example #5
Source File: VerifyServiceProviderFactory.java    From verify-service-provider with MIT License 6 votes vote down vote up
public VerifyServiceProviderFactory(
        VerifyServiceProviderConfiguration configuration,
        MetadataResolverBundle<VerifyServiceProviderConfiguration> verifyMetadataBundler,
        MetadataResolverBundle<VerifyServiceProviderConfiguration> msaMetadataBundle,
        Client client) throws KeyException {
    this.configuration = configuration;
    List<KeyPair> decryptionKeyPairs = getDecryptionKeyPairs(
            configuration.getSamlPrimaryEncryptionKey(),
            configuration.getSamlSecondaryEncryptionKey()
    );
    this.keyStore = new IdaKeyStore(null, decryptionKeyPairs);
    this.responseFactory = new ResponseFactory(decryptionKeyPairs);
    this.dateTimeComparator = new DateTimeComparator(configuration.getClockSkew());
    this.entityIdService = new EntityIdService(configuration.getServiceEntityIds());
    this.verifyMetadataBundler = verifyMetadataBundler;
    this.msaMetadataBundle = msaMetadataBundle;
    this.manifestReader = new ManifestReader();
    this.client = client;
    this.hubSignatureValidator = new SignatureValidatorFactory().getSignatureValidator(getHubSignatureTrustEngine());
}
 
Example #6
Source File: SystemEndpointIT.java    From boost with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testGetProperties() {
    // String port = System.getProperty("liberty.test.port");
    String port = System.getProperty("boost_http_port");
    // String port = "9000";
    String url = "http://localhost:" + port + "/";

    Client client = ClientBuilder.newClient();
    client.register(JsrJsonpProvider.class);

    WebTarget target = client.target(url + "system/properties");
    Response response = target.request().get();

    assertEquals("Incorrect response code from " + url, 200, response.getStatus());

    JsonObject obj = response.readEntity(JsonObject.class);

    assertEquals("The system property for the local and remote JVM should match", System.getProperty("os.name"),
            obj.getString("os.name"));

    response.close();
}
 
Example #7
Source File: SpringContextJerseyTest.java    From demo-restWS-spring-jersey-tomcat-mybatis with MIT License 6 votes vote down vote up
/**
 * Utility method that safely closes a client instance without throwing an exception.
 *
 * @param clients client instances to close. Each instance may be {@code null}.
 * @since 2.5
 */
public final void close(final Client... clients) {
    if (clients == null || clients.length == 0) {
        return;
    }

    for (Client c : clients) {
        if (c == null) {
            continue;
        }
        try {
            c.close();
        } catch (Throwable t) {
            LOGGER.log(Level.WARNING, "Error closing a client instance.", t);
        }

    }
}
 
Example #8
Source File: PreferenceEndpoint.java    From istio-tutorial with Apache License 2.0 6 votes vote down vote up
@GET
@Produces("text/plain")
public Response getPreference(@HeaderParam("user-agent") String userAgent) {
    try {
        Client client = ClientBuilder.newClient();
        Response res = client.target(remoteURL).request("text/plain").header("user-agent", userAgent).get();
        if (res.getStatus() == Response.Status.OK.getStatusCode()){
            return Response.ok(String.format(RESPONSE_STRING_FORMAT, res.readEntity(String.class))).build();
        }else{
            logger.warn("Non HTTP 20x trying to get the response from preference service: " + res.getStatus());
            return Response
                    .status(Response.Status.SERVICE_UNAVAILABLE)
                    .entity(String.format(RESPONSE_STRING_FORMAT,
                            String.format("Error: %d - %s", res.getStatus(), res.readEntity(String.class)))
                    )
                    .build();
        }
    } catch (ProcessingException ex) {
        logger.warn("Exception trying to get the response from recommendation service.", ex);
        return Response
                .status(Response.Status.SERVICE_UNAVAILABLE)
                .entity(String.format(RESPONSE_STRING_FORMAT, ex.getCause().getClass().getSimpleName() + ": " + ex.getCause().getMessage()))
                .build();
    }
}
 
Example #9
Source File: PrincipalCreator.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private void checkTheAvailabilityWithResourceLogin(String objectId, String tenantId, AzureApplication app, Client client) {
    WebTarget loginResource = client.target(LOGIN_MICROSOFTONLINE + tenantId);
    Map<String, String> formData = new HashMap<>();
    formData.put("grant_type", "client_credentials");
    formData.put("client_id", app.getAppId());
    formData.put("client_secret", app.getAzureApplicationCreationView().getAppSecret());
    formData.put("resource", app.getAzureApplicationCreationView().getAppIdentifierURI());
    try (Response loginResponse = loginResource.path("/oauth2/token")
            .request()
            .accept(MediaType.APPLICATION_JSON)
            .header("Content-Type", "application/x-www-form-urlencoded")
            .post(Entity.form(new MultivaluedHashMap<>(formData)))) {
        if (loginResponse.getStatus() != HttpStatus.SC_OK) {
            throw new RetryException("Principal with objectId (" + objectId + ") hasn't been available yet");
        }
    }
}
 
Example #10
Source File: GetPaymentRefundsServiceTest.java    From pay-publicapi with MIT License 6 votes vote down vote up
@Before
public void setUp() {
    when(mockConfiguration.getLedgerUrl()).thenReturn(ledgerRule.getUrl());
    when(mockConfiguration.getConnectorUrl()).thenReturn(connectorRule.getUrl());
    when(mockConfiguration.getBaseUrl()).thenReturn("http://publicapi.test.localhost/");

    PublicApiUriGenerator publicApiUriGenerator = new PublicApiUriGenerator(mockConfiguration);
    LedgerUriGenerator ledgerUriGenerator = new LedgerUriGenerator(mockConfiguration);

    Client client = RestClientFactory.buildClient(new RestClientConfig(false));
    LedgerService ledgerService = new LedgerService(client, ledgerUriGenerator);

    ConnectorUriGenerator connectorUriGenerator = new ConnectorUriGenerator(mockConfiguration);
    ConnectorService connectorService = new ConnectorService(client, connectorUriGenerator);

    getPaymentRefundsService = new GetPaymentRefundsService(connectorService, ledgerService, publicApiUriGenerator);
}
 
Example #11
Source File: ServerSentEventServiceTest.java    From mangooio with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloseConnection() throws InterruptedException {
	//given
	ServerSentEventService ServerSentEventService = Application.getInstance(ServerSentEventService.class);
	Config config = Application.getInstance(Config.class);
	Client client = ClientBuilder.newClient();

	//when
	WebTarget webTarget = client.target("http://" + config.getConnectorHttpHost() + ":" + config.getConnectorHttpPort() + "/sse");
	SseEventSource sseEventSource = SseEventSource.target(webTarget).build();
	sseEventSource.register((sseEvent) -> {eventData = sseEvent.readData();}, (e) -> e.printStackTrace());
	sseEventSource.open();
	ServerSentEventService.close("/sse");
	sseEventSource.close();
	client.close();

	//then
	assertThat(ServerSentEventService.getConnections("/sse"), not(nullValue()));
	assertThat(ServerSentEventService.getConnections("/sse").size(), equalTo(0));
}
 
Example #12
Source File: Keycloak.java    From apicurio-studio with Apache License 2.0 6 votes vote down vote up
public void login() {
    Client client = ClientBuilder.newClient();

    Form form = new Form();
    form.param("client_id", "admin-cli");
    form.param("username", "admin");
    form.param("password", "admin");
    form.param("grant_type", "password");
    Entity<Form> entity = Entity.form(form);

    Response response = client.target(baseUrl + "/auth/realms/master/protocol/openid-connect/token")
            .request(MediaType.APPLICATION_JSON_TYPE)
            .post(entity);
    JsonObject data = (JsonObject) asJson(response);
    this.token = data.getString("access_token");
}
 
Example #13
Source File: FilesApiTest.java    From mattermost4j with Apache License 2.0 6 votes vote down vote up
@Test
public void getPublicFileLink() throws URISyntaxException, IOException {
  Path filePath = th.getResourcePath(TestHelper.EMOJI_GLOBE);
  String channelId = th.basicChannel().getId();
  FileUploadResult uploadResult = assertNoError(client.uploadFile(channelId, filePath)).readEntity();
  FileInfo fileInfo = uploadResult.getFileInfos()[0];
  String fileId = fileInfo.getId();

  Post post = new Post(channelId, "file attached post");
  post.setFileIds(Collections.singletonList(fileId));
  post = assertNoError(client.createPost(post)).readEntity();

  String publicLink = assertNoError(client.getPublicFileLink(fileId)).readEntity();

  Client jaxrsClient = ClientBuilder.newClient();
  WebTarget target = jaxrsClient.target(publicLink);
  Response response = target.request().get();
  InputStream downloadFile = response.readEntity(InputStream.class);
  Path tempFile = Files.createTempFile(null, null);
  Files.copy(downloadFile, tempFile, StandardCopyOption.REPLACE_EXISTING);

  assertSameFile(filePath, tempFile);
}
 
Example #14
Source File: OccasionResourceTest.java    From sample-acmegifts with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Helper method to send a simple http request without a payload
 *
 * @param url the url to call
 * @param requestType the http method to invoke
 * @return the response from the server
 */
public Response sendRequest(String url, String requestType) {
  String method = "sendRequest";
  logger.entering(clazz, method);
  logger.fine("  url: " + url);
  logger.fine("  requestType: " + requestType);

  String jwt = null;
  try {
    jwt = new JWTVerifier().createJWT("fred");
  } catch (Throwable t) {
    throw new RuntimeException(t);
  }

  Client client = ClientBuilder.newClient();
  WebTarget target = client.target(url);
  Invocation.Builder invoBuild = target.request();

  invoBuild.header(HttpHeaders.AUTHORIZATION, "Bearer " + jwt);
  Response response = invoBuild.build(requestType).invoke();

  logger.exiting(
      clazz, method, "\n\n- - - - - Exiting " + method + " with: " + response + "\n\n");
  return response;
}
 
Example #15
Source File: FlowOverrideTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testClientOverrideFlowUsingDirectGrantHttpChallenge() {
    Client httpClient = javax.ws.rs.client.ClientBuilder.newClient();
    String grantUri = oauth.getResourceOwnerPasswordCredentialGrantUrl();
    WebTarget grantTarget = httpClient.target(grantUri);

    // no username/password
    Form form = new Form();
    form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
    form.param(OAuth2Constants.CLIENT_ID, TEST_APP_HTTP_CHALLENGE);
    Response response = grantTarget.request()
            .post(Entity.form(form));
    assertEquals("Basic realm=\"test\"", response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE));
    assertEquals(401, response.getStatus());
    response.close();

    // now, username password using basic challenge response
    response = grantTarget.request()
            .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("test-user@localhost", "password"))
            .post(Entity.form(form));
    assertEquals(200, response.getStatus());
    response.close();

    httpClient.close();
    events.clear();
}
 
Example #16
Source File: GitLabApiClient.java    From gitlab4j-api with MIT License 6 votes vote down vote up
protected Client createApiClient() {

        // Explicitly use an instance of the JerseyClientBuilder, this allows this
        // library to work when both Jersey and Resteasy are present
        ClientBuilder clientBuilder = new JerseyClientBuilder().withConfig(clientConfig);

        // Register JacksonJson as the ObjectMapper provider.
        clientBuilder.register(JacksonJson.class);

        if (ignoreCertificateErrors) {
            clientBuilder.sslContext(openSslContext).hostnameVerifier(openHostnameVerifier);
        }

        apiClient = clientBuilder.build();
        return (apiClient);
    }
 
Example #17
Source File: ChannelBufferManager.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Calls the manager's public collection REST API.
 * @return publiclyListed value of given channel name
 */
@SuppressWarnings("unchecked")
public Boolean getChannelPublicStatus(String channelName) {
	String channelCode = parseChannelName(channelName);
	Response clientResponse = null;
	Client client = ClientBuilder.newBuilder().register(JacksonFeature.class).build();
	try {
		WebTarget webResource = client.target(managerMainUrl 
				+ "/public/collection/getChannelPublicFlagStatus?channelCode=" + channelCode);

		clientResponse = webResource.request(MediaType.APPLICATION_JSON).get();
		Map<String, Boolean> collectionMap = new HashMap<String, Boolean>();

		if (clientResponse.getStatus() == 200) {
			//convert JSON string to Map
			collectionMap = clientResponse.readEntity(Map.class);
			logger.info("Channel info received from manager: " + collectionMap);
			if (collectionMap != null) {
				return collectionMap.get(channelCode);
			}
		} else {
			logger.warn("Couldn't contact AIDRFetchManager for publiclyListed status, channel: " + channelName);
		}
	} catch (Exception e) {
		logger.error("Error in querying manager for running collections: " + clientResponse);
	}
	return true;		// Question: should default be true or false?
}
 
Example #18
Source File: GcpDiskEncryptionService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private String getGooglePublicKey() {
    Client client = RestClientUtil.get();
    WebTarget target = createWebTarget(client);
    try (Response response = target.request().get()) {
        if (!Family.SUCCESSFUL.equals(response.getStatusInfo().getFamily())) {
            throw new CloudbreakServiceException("GET request to [" + googlePublicCertUrl + "] failed with status code: " + response.getStatus());
        }

        return response.readEntity(String.class);
    } catch (ProcessingException e) {
        throw new CloudbreakServiceException("Failed to connect to URI: " + googlePublicCertUrl, e);
    }
}
 
Example #19
Source File: SimpleClientTest.java    From resteasy-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testProxy() throws Exception
{
   Client client = ClientBuilder.newClient();
   CustomerProxy proxy = ((ResteasyClient) client).target("http://localhost:9095").proxy(CustomerProxy.class);
   Customer cust = proxy.getCustomer("Monica");
   Assert.assertEquals("Monica", cust.getName());
   client.close();
}
 
Example #20
Source File: AbstractServerTest.java    From java-jaxrs with Apache License 2.0 5 votes vote down vote up
@Test
public void testTracedFalseMethod() {
    Client client = ClientBuilder.newClient();
    Response response = client.target(url("/tracedFalseIn"))
        .request()
        .get();
    response.close();
    List<MockSpan> mockSpans = mockTracer.finishedSpans();
    Assert.assertEquals(0, mockSpans.size());
}
 
Example #21
Source File: AuthnRequestAcceptanceTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldReturn400WhenPassedNoEntityIdForMultiTenantApplication() throws Exception {
    Client client = new JerseyClientBuilder(multiTenantApplication.getEnvironment()).build("Test Client");

    setupComplianceToolWithEntityId(client, MULTI_ENTITY_ID_1);

    Response authnResponse = client
        .target(URI.create(String.format("http://localhost:%d/generate-request", multiTenantApplication.getLocalPort())))
        .request()
        .buildPost(Entity.json(new RequestGenerationBody(null)))
        .invoke();

    assertThat(authnResponse.getStatus()).isEqualTo(BAD_REQUEST.getStatusCode());
}
 
Example #22
Source File: PartyInfoResourceTest.java    From tessera with Apache License 2.0 5 votes vote down vote up
@Before
public void onSetup() {
    this.partyInfoService = mock(PartyInfoService.class);
    this.partyInfoParser = mock(PartyInfoParser.class);
    this.enclave = mock(Enclave.class);
    this.restClient = mock(Client.class);
    this.payloadEncoder = mock(PayloadEncoder.class);
    this.partyInfoResource =
            new PartyInfoResource(partyInfoService, partyInfoParser, restClient, enclave, payloadEncoder, true);
}
 
Example #23
Source File: LoginTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testPOSTAuthenticationRequest() {
    Client client = ClientBuilder.newClient();

    //POST request to http://localhost:8180/auth/realms/test/protocol/openid-connect/auth;
    UriBuilder b = OIDCLoginProtocolService.authUrl(UriBuilder.fromUri(AUTH_SERVER_ROOT));
    Response response = client.target(b.build(oauth.getRealm())).request().post(oauth.getLoginEntityForPOST());
    
    Assert.assertThat(response.getStatus(), is(equalTo(200)));
    Assert.assertThat(response, Matchers.body(containsString("Log In")));

    response.close();
    client.close();
}
 
Example #24
Source File: TenacityClientBuilder.java    From tenacity with Apache License 2.0 5 votes vote down vote up
public TenacityClient build() {
    final Client client = new JerseyClientBuilder(environment)
            .using(jerseyConfiguration)
            .build("tenacity-" + tenacityPropertyKey);
    return new TenacityClient(environment.metrics(), TenacityJerseyClientBuilder
            .builder(tenacityPropertyKey)
            .build(client));
}
 
Example #25
Source File: RestDemoServiceIT.java    From demo-rest-jersey-spring with MIT License 5 votes vote down vote up
@Test
public void testGetLegacyPodcasts() throws JsonGenerationException,
		JsonMappingException, IOException {

	ClientConfig clientConfig = new ClientConfig();
	clientConfig.register(JacksonFeature.class);

	Client client = ClientBuilder.newClient(clientConfig);

	WebTarget webTarget = client
			.target("http://localhost:8888/demo-rest-jersey-spring/legacy/podcasts/");

	Builder request = webTarget.request();
	request.header("Content-type", MediaType.APPLICATION_JSON);

	Response response = request.get();
	Assert.assertTrue(response.getStatus() == 200);

	List<Podcast> podcasts = response
			.readEntity(new GenericType<List<Podcast>>() {
			});

	ObjectMapper mapper = new ObjectMapper();
	System.out.print(mapper.writerWithDefaultPrettyPrinter()
			.writeValueAsString(podcasts));

	Assert.assertTrue("At least one podcast is present in the LEGACY",
			podcasts.size() > 0);
}
 
Example #26
Source File: AzureRoleManager.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Retryable(value = InteractiveLoginException.class, maxAttempts = 15, backoff = @Backoff(delay = 1000))
public void assignRole(String accessToken, String subscriptionId, String roleDefinitionId, String principalObjectId) throws InteractiveLoginException {
    Client client = ClientBuilder.newClient();
    WebTarget resource = client.target(AZURE_MANAGEMENT);
    Builder request = resource.path("subscriptions/" + subscriptionId + "/providers/Microsoft.Authorization/roleAssignments/"
            + UUID.randomUUID()).queryParam("api-version", "2015-07-01").request();
    request.accept(MediaType.APPLICATION_JSON);

    request.header("Authorization", "Bearer " + accessToken);

    JsonObject properties = new JsonObject();
    properties.addProperty("roleDefinitionId", roleDefinitionId);
    properties.addProperty("principalId", principalObjectId);

    JsonObject jsonObject = new JsonObject();
    jsonObject.add("properties", properties);

    try (Response response = request.put(Entity.entity(jsonObject.toString(), MediaType.APPLICATION_JSON))) {
        if (response.getStatusInfo().getFamily() != Family.SUCCESSFUL) {
            String errorResponse = response.readEntity(String.class);
            LOGGER.info("Assign role request error - status code: {} - error message: {}", response.getStatus(), errorResponse);
            if (response.getStatusInfo().getStatusCode() == Status.FORBIDDEN.getStatusCode()) {
                throw new InteractiveLoginException("You don't have enough permissions to assign roles, please contact with your administrator");
            } else {
                try {
                    String errorMessage = new ObjectMapper().readTree(errorResponse).get("error").get("message").asText();
                    throw new InteractiveLoginException("Failed to assing role: " + errorMessage);
                } catch (IOException e) {
                    throw new InteractiveLoginException("Failed to assing role (status " + response.getStatus() + "): " + errorResponse);
                }
            }
        } else {
            LOGGER.debug("Role assigned successfully. subscriptionId '{}', roleDefinitionId {}, principalObjectId {}",
                    subscriptionId, roleDefinitionId, principalObjectId);
        }
    }
}
 
Example #27
Source File: AbstractServerTest.java    From java-jaxrs with Apache License 2.0 5 votes vote down vote up
@Test
public void testRequestBlockedByFilter() {
    Client client = ClientBuilder.newClient();
    Response response = client.target(url("/filtered"))
            .request()
            .get();
    response.close();
    Assert.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus());

    List<MockSpan> mockSpans = mockTracer.finishedSpans();
    Assert.assertEquals(0, mockSpans.size());
}
 
Example #28
Source File: PriceResourceTest.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
@Test
void testPricesEventStream() {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(PRICES_SSE_ENDPOINT);

    List<Double> received = new CopyOnWriteArrayList<>();

    SseEventSource source = SseEventSource.target(target).build();
    source.register(inboundSseEvent -> received.add(Double.valueOf(inboundSseEvent.readData())));
    source.open();
    await().atMost(100000, MILLISECONDS).until(() -> received.size() == 3);
    source.close();
}
 
Example #29
Source File: RestAgent.java    From micro-server with Apache License 2.0 5 votes vote down vote up
public <T> T post(String url, Object payload, Class<T> type) {
    Client client = ClientBuilder.newClient();

    WebTarget resource = client.target(url);

    Builder request = resource.request();
    request.accept(MediaType.APPLICATION_JSON);

    return request
        .post(Entity.entity(JacksonUtil.serializeToJson(payload), MediaType.APPLICATION_JSON),
            type);
}
 
Example #30
Source File: SundialBundleITBase.java    From dropwizard-sundial with Apache License 2.0 5 votes vote down vote up
public static boolean stopJob(DropwizardAppExtension<TestConfiguration> app, Client client, String jobName) {
    Response response = client.target(
        String.format(
            "http://localhost:%d/%s/tasks/stopjob?JOB_NAME=%s",
            app.getAdminPort(), app.getEnvironment().getAdminContext().getContextPath(), jobName
        ))
        .request()
        .post(Entity.text(""));

    return response.getStatus() == 200;
}