Java Code Examples for javax.ws.rs.client.Client#close()

The following examples show how to use javax.ws.rs.client.Client#close() . 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: NonDubboRestConsumer.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
private static void registerUser(String url, MediaType mediaType) {
    System.out.println("Registering user via " + url);
    User user = new User(1L, "larrypage");
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(url);
    Response response = target.request().post(Entity.entity(user, mediaType));

    try {
        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed with HTTP error code : " + response.getStatus());
        }
        System.out.println("Successfully got result: " + response.readEntity(String.class));
    } finally {
        response.close();
        client.close();
    }
}
 
Example 2
Source File: MetadataCommand.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
protected R run() {
    Client client = null;

    try {
        client = createClient();

        final WebTarget target = client.target(getMetadataURL());
        final Entity<?> entity = Entity.entity(parameters, MediaType.APPLICATION_JSON);

        return target.request(MediaType.APPLICATION_JSON).post(entity, type);
    } finally {
        if (client != null) {
            client.close();
        }
    }
}
 
Example 3
Source File: RestClient.java    From dubbox with Apache License 2.0 6 votes vote down vote up
private static void registerUser(String url, MediaType mediaType) {
    System.out.println("Registering user via " + url);
    User user = new User(1L, "larrypage");
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(url);
    Response response = target.request().post(Entity.entity(user, mediaType));

    try {
        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed with HTTP error code : " + response.getStatus());
        }
        System.out.println("Successfully got result: " + response.readEntity(String.class));
    } finally {
        response.close();
        client.close();
    }
}
 
Example 4
Source File: StateResource.java    From vespa with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
@GET
@Path("v1/tenant/{tenantName}/application/{applicationName}/environment/{environmentName}/region/{regionName}/instance/{instanceName}/service/{serviceIdentifier}/{apiParams: .*}")
@Produces(MediaType.APPLICATION_JSON)
public HashMap singleService(@PathParam("tenantName") String tenantName,
        @PathParam("applicationName") String applicationName,
        @PathParam("environmentName") String environmentName,
        @PathParam("regionName") String regionName,
        @PathParam("instanceName") String instanceName,
        @PathParam("serviceIdentifier") String identifier,
        @PathParam("apiParams") String apiParams) {
    ServiceModel model = new ServiceModel(getModelConfig(tenantName, applicationName, environmentName, regionName, instanceName));
    Service s = model.getService(identifier);
    int requestedPort = s.matchIdentifierWithPort(identifier);
    Client client = client();
    try {
        HealthClient resource = getHealthClient(apiParams, s, requestedPort, client);
        HashMap<?, ?> apiResult = resource.getHealthInfo();
        rewriteResourceLinks(apiResult, model, s, applicationIdentifier(tenantName, applicationName, environmentName, regionName, instanceName), identifier);
        return apiResult;
    } finally {
        client.close();
    }
}
 
Example 5
Source File: UserInfoTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_postMethod_header() throws Exception {
    Client client = ClientBuilder.newClient();

    try {
        AccessTokenResponse accessTokenResponse = executeGrantAccessTokenRequest(client);

        WebTarget userInfoTarget = UserInfoClientUtil.getUserInfoWebTarget(client);
        Response response = userInfoTarget.request()
                .header(HttpHeaders.AUTHORIZATION, "bearer " + accessTokenResponse.getToken())
                .post(Entity.form(new Form()));

        testSuccessfulUserInfoResponse(response);

    } finally {
        client.close();
    }
}
 
Example 6
Source File: AsyncTest.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
@Test
public void inject() {
    try (final Meecrowave meecrowave = new Meecrowave(
            new Meecrowave.Builder()
                    .randomHttpPort()
                    .includePackages(AsyncTest.class.getName())).bake()) {
        final Client client = ClientBuilder.newClient();
        try {
            assertEquals("asynced", client.target("http://localhost:" + meecrowave.getConfiguration().getHttpPort())
                    .path("AsyncTest/Async")
                    .request(TEXT_PLAIN_TYPE)
                    .get(String.class));
        } finally {
            client.close();
        }
    }
}
 
Example 7
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 8
Source File: DemoServletsAdapterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testNullBearerToken() {
    Client client = new ResteasyClientBuilder().httpEngine(new FollowRedirectsEngine()).build();
    WebTarget target = client.target(customerDb.toString());
    Response response = target.request().get();
    assertEquals(401, response.getStatus());
    response.close();
    response = target.request().header(HttpHeaders.AUTHORIZATION, "Bearer null").get();
    assertEquals(401, response.getStatus());
    response.close();
    client.close();
}
 
Example 9
Source File: MyService.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Traced
public String call() {
    // tag::client-registration[]
    Client client = ClientTracingRegistrar.configure(ClientBuilder.newBuilder()).build();
    // end::client-registration[]
    try {
        String response = client.target("http://localhost:8080")
                .path("/simple")
                .request()
                .get(String.class);
        return "Called an external service successfully, it responded: " + response;
    } finally {
        client.close();
    }
}
 
Example 10
Source File: ClientBuilderImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void withCustomInstantiator() {
    final AtomicInteger create = new AtomicInteger();
    final AtomicInteger close = new AtomicInteger();
    final Client build = new ClientBuilderImpl().register(new ConfigurableImpl.Instantiator() {
        @Override
        public <T> Object create(final Class<T> cls) {
            try {
                create.incrementAndGet();
                return cls.newInstance();
            } catch (final InstantiationException | IllegalAccessException e) {
                fail(e.getMessage());
            }
            return null;
        }

        @Override
        public void release(final Object instance) {
            close.incrementAndGet();
        }
    }).register(PrimitiveTextProvider.class).build();
    assertEquals(1, create.get());
    assertEquals(0, close.get());
    build.close();
    assertEquals(1, create.get());
    assertEquals(1, close.get());
}
 
Example 11
Source File: MetricsRestServiceTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testHealthEndpoint() {
    Client client = ClientBuilder.newClient();

    try (Response response = client.target("http://" + MGMT_HOST + ":" + MGMT_PORT + "/health").request().get()) {
        Assert.assertThat(response, statusCodeIs(Status.OK));
        Assert.assertThat(response, body(containsString("{\"status\":\"UP\",\"checks\":[]}")));
    } finally {
        client.close();
    }
}
 
Example 12
Source File: RestClient.java    From dubbox with Apache License 2.0 5 votes vote down vote up
private static void getUser(String url) {
    System.out.println("Getting user via " + url);
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(url);
    Response response = target.request().get();
    try {
        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed with HTTP error code : " + response.getStatus());
        }
        System.out.println("Successfully got result: " + response.readEntity(String.class));
    } finally {
        response.close();
        client.close();
    }
}
 
Example 13
Source File: RestClient.java    From dubbox with Apache License 2.0 5 votes vote down vote up
private static void getUser(String url) {
    System.out.println("Getting user via " + url);
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(url);
    Response response = target.request().get();
    try {
        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed with HTTP error code : " + response.getStatus());
        }
        System.out.println("Successfully got result: " + response.readEntity(String.class));
    } finally {
        response.close();
        client.close();
    }
}
 
Example 14
Source File: SocialLoginTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private AccessTokenResponse checkFeature(int expectedStatusCode, String username) {
    Client httpClient = ClientBuilder.newClient();
    Response response = null;
    try {
        testingClient.server().run(SocialLoginTest::setupClientExchangePermissions);

        WebTarget exchangeUrl = getExchangeUrl(httpClient);
        response = exchangeUrl.request()
                .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader(EXCHANGE_CLIENT, "secret"))
                .post(Entity.form(
                        new Form()
                                .param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE)
                                .param(OAuth2Constants.REQUESTED_SUBJECT, username)
                                .param(OAuth2Constants.REQUESTED_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE)
                                .param(OAuth2Constants.REQUESTED_ISSUER, currentTestProvider.id())
                ));
        Assert.assertEquals(expectedStatusCode, response.getStatus());
        if (expectedStatusCode == Response.Status.OK.getStatusCode())
            return response.readEntity(AccessTokenResponse.class);
        else
            return null;
    } finally {
        if (response != null)
            response.close();
        httpClient.close();
    }
}
 
Example 15
Source File: ClientRedirectTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testRedirectStatusCode() {
    oauth.doLogin("test-user@localhost", "password");
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    String token = oauth.doAccessTokenRequest(code, "password").getAccessToken();

    Client client = javax.ws.rs.client.ClientBuilder.newClient();
    String redirectUrl = getAuthServerRoot().toString() + "realms/test/clients/launchpad-test/redirect";
    Response response = client.target(redirectUrl).request().header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    assertEquals(303, response.getStatus());
    client.close();
}
 
Example 16
Source File: RestClient.java    From dubbox with Apache License 2.0 5 votes vote down vote up
private static void getUser(String url) {
    System.out.println("Getting user via " + url);
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(url);
    Response response = target.request().get();
    try {
        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed with HTTP error code : " + response.getStatus());
        }
        System.out.println("Successfully got result: " + response.readEntity(String.class));
    } finally {
        response.close();
        client.close();
    }
}
 
Example 17
Source File: BasicQueryTest.java    From resteasy-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void basicTest() {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target("http://localhost:8081/type");
    assertEquals(ResteasyContextParameters.RESTEASY_TRACING_TYPE_ALL, target.request().get(String.class));

    target = client.target("http://localhost:8081/level");
    assertEquals(ResteasyContextParameters.RESTEASY_TRACING_LEVEL_VERBOSE, target.request().get(String.class));

    target = client.target("http://localhost:8081/logger");
    assertEquals(RESTEasyTracingLogger.class.getName(), target.request().get(String.class));

    client.close();

}
 
Example 18
Source File: UserInfoTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testSuccessSignedResponse() throws Exception {
    // Require signed userInfo request
    ClientResource clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
    ClientRepresentation clientRep = clientResource.toRepresentation();
    OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setUserInfoSignedResponseAlg(Algorithm.RS256);
    clientResource.update(clientRep);

    // test signed response
    Client client = ClientBuilder.newClient();

    try {
        AccessTokenResponse accessTokenResponse = executeGrantAccessTokenRequest(client);

        Response response = UserInfoClientUtil.executeUserInfoRequest_getMethod(client, accessTokenResponse.getToken());

        events.expect(EventType.USER_INFO_REQUEST)
                .session(Matchers.notNullValue(String.class))
                .detail(Details.AUTH_METHOD, Details.VALIDATE_ACCESS_TOKEN)
                .detail(Details.USERNAME, "test-user@localhost")
                .detail(Details.SIGNATURE_REQUIRED, "true")
                .detail(Details.SIGNATURE_ALGORITHM, Algorithm.RS256.toString())
                .assertEvent();

        // Check signature and content
        PublicKey publicKey = PemUtils.decodePublicKey(ApiUtil.findActiveKey(adminClient.realm("test")).getPublicKey());

        Assert.assertEquals(200, response.getStatus());
        Assert.assertEquals(response.getHeaderString(HttpHeaders.CONTENT_TYPE), MediaType.APPLICATION_JWT);
        String signedResponse = response.readEntity(String.class);
        response.close();

        JWSInput jwsInput = new JWSInput(signedResponse);
        Assert.assertTrue(RSAProvider.verify(jwsInput, publicKey));

        UserInfo userInfo = JsonSerialization.readValue(jwsInput.getContent(), UserInfo.class);

        Assert.assertNotNull(userInfo);
        Assert.assertNotNull(userInfo.getSubject());
        Assert.assertEquals("test-user@localhost", userInfo.getEmail());
        Assert.assertEquals("test-user@localhost", userInfo.getPreferredUsername());

        Assert.assertTrue(userInfo.hasAudience("test-app"));
        String expectedIssuer = Urls.realmIssuer(new URI(AUTH_SERVER_ROOT), "test");
        Assert.assertEquals(expectedIssuer, userInfo.getIssuer());

    } finally {
        client.close();
    }

    // Revert signed userInfo request
    OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setUserInfoSignedResponseAlg(null);
    clientResource.update(clientRep);
}
 
Example 19
Source File: BrokerLinkAndTokenExchangeTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private void checkFeature(int statusCode) throws Exception {
    String accessToken = oauth.doGrantAccessTokenRequest(PARENT_IDP, PARENT2_USERNAME, "password", null, PARENT_CLIENT, "password").getAccessToken();

    if (statusCode != Response.Status.NOT_IMPLEMENTED.getStatusCode()) {
        Assert.assertEquals(0, adminClient.realm(CHILD_IDP).getClientSessionStats().size());
    }

    Client httpClient = ClientBuilder.newClient();
    try {
        WebTarget exchangeUrl = childTokenExchangeWebTarget(httpClient);
        {
            IdentityProviderRepresentation rep = adminClient.realm(CHILD_IDP).identityProviders().get(PARENT_IDP).toRepresentation();
            rep.getConfig().put(OIDCIdentityProviderConfig.VALIDATE_SIGNATURE, String.valueOf(false));
            adminClient.realm(CHILD_IDP).identityProviders().get(PARENT_IDP).update(rep);
            // test user info validation.
            Response response = exchangeUrl.request()
                    .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader(ClientApp.DEPLOYMENT_NAME, "password"))
                    .post(Entity.form(
                            new Form()
                                    .param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE)
                                    .param(OAuth2Constants.SUBJECT_TOKEN, accessToken)
                                    .param(OAuth2Constants.SUBJECT_TOKEN_TYPE, OAuth2Constants.JWT_TOKEN_TYPE)
                                    .param(OAuth2Constants.SUBJECT_ISSUER, PARENT_IDP)
                                    .param(OAuth2Constants.SCOPE, OAuth2Constants.SCOPE_OPENID)

                    ));
            Assert.assertEquals(statusCode, response.getStatus());

            if (statusCode != Response.Status.NOT_IMPLEMENTED.getStatusCode()) {
                AccessTokenResponse tokenResponse = response.readEntity(AccessTokenResponse.class);
                String idToken = tokenResponse.getIdToken();
                Assert.assertNotNull(idToken);
                response.close();

                Assert.assertEquals(1, adminClient.realm(CHILD_IDP).getClientSessionStats().size());

                // test logout
                response = childLogoutWebTarget(httpClient)
                        .queryParam("id_token_hint", idToken)
                        .request()
                        .get();
                response.close();

                Assert.assertEquals(0, adminClient.realm(CHILD_IDP).getClientSessionStats().size());
            }
        }
    } finally {
        httpClient.close();
    }
}
 
Example 20
Source File: FlowOverrideTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testDirectGrantHttpChallengeUserDisabled() {
    setupBruteForce();

    Client httpClient = javax.ws.rs.client.ClientBuilder.newClient();
    String grantUri = oauth.getResourceOwnerPasswordCredentialGrantUrl();
    WebTarget grantTarget = httpClient.target(grantUri);

    Form form = new Form();
    form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
    form.param(OAuth2Constants.CLIENT_ID, TEST_APP_HTTP_CHALLENGE);

    UserRepresentation user = adminClient.realm("test").users().search("test-user@localhost").get(0);
    user.setEnabled(false);
    adminClient.realm("test").users().get(user.getId()).update(user);

    // user disabled
    Response response = grantTarget.request()
            .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("test-user@localhost", "password"))
            .post(Entity.form(form));
    assertEquals(401, response.getStatus());
    assertEquals("Unauthorized", response.getStatusInfo().getReasonPhrase());
    response.close();

    user.setEnabled(true);
    adminClient.realm("test").users().get(user.getId()).update(user);

    // lock the user account
    grantTarget.request()
            .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("test-user@localhost", "wrongpassword"))
            .post(Entity.form(form));
    grantTarget.request()
            .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("test-user@localhost", "wrongpassword"))
            .post(Entity.form(form));
    // user is temporarily disabled
    response = grantTarget.request()
            .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("test-user@localhost", "password"))
            .post(Entity.form(form));
    assertEquals(401, response.getStatus());
    assertEquals("Unauthorized", response.getStatusInfo().getReasonPhrase());
    response.close();

    clearBruteForce();

    httpClient.close();
    events.clear();
}