io.dropwizard.client.JerseyClientBuilder Java Examples

The following examples show how to use io.dropwizard.client.JerseyClientBuilder. 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: TenacityAuthenticatorTest.java    From tenacity with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotTransformAuthenticationExceptionIntoMappedException() throws AuthenticationException {
    when(AuthenticatorApp.getMockAuthenticator().authenticate(any(BasicCredentials.class))).thenThrow(new AuthenticationException("test"));
    final Client client = new JerseyClientBuilder(new MetricRegistry())
            .using(executorService, Jackson.newObjectMapper())
            .build("dropwizard-app-rule");

    client.register(HttpAuthenticationFeature.basicBuilder()
            .nonPreemptive()
            .credentials("user", "stuff")
            .build());

    final Response response = client
            .target(URI.create("http://localhost:" + RULE.getLocalPort() + "/auth"))
            .request()
            .get(Response.class);

    assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());

    verify(AuthenticatorApp.getMockAuthenticator(), times(1)).authenticate(any(BasicCredentials.class));
    verifyZeroInteractions(AuthenticatorApp.getTenacityContainerExceptionMapper());
    verify(AuthenticatorApp.getTenacityExceptionMapper(), times(1)).toResponse(any(HystrixRuntimeException.class));
}
 
Example #2
Source File: AuthnRequestAcceptanceTest.java    From verify-service-provider with MIT License 6 votes vote down vote up
@Test
public void shouldGenerateValidAuthnRequestWhenNoParams() throws Exception {
    Client client = new JerseyClientBuilder(singleTenantApplication.getEnvironment()).build("Test Client");

    setupComplianceToolWithDefaultEntityId(client);

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

    RequestResponseBody authnSaml = authnResponse.readEntity(RequestResponseBody.class);

    Response complianceToolResponse = client
            .target(authnSaml.getSsoLocation())
            .request()
            .buildPost(Entity.form(new MultivaluedHashMap<>(ImmutableMap.of("SAMLRequest", authnSaml.getSamlRequest()))))
            .invoke();

    JSONObject complianceToolResponseBody = new JSONObject(complianceToolResponse.readEntity(String.class));
    assertThat(complianceToolResponseBody.getJSONObject("status").get("message")).isEqualTo(null);
    assertThat(complianceToolResponseBody.getJSONObject("status").getString("status")).isEqualTo("PASSED");
}
 
Example #3
Source File: AuthnRequestAcceptanceTest.java    From verify-service-provider with MIT License 6 votes vote down vote up
@Test
public void shouldGenerateValidAuthnRequestUsingDefaultEntityId() throws Exception {
    Client client = new JerseyClientBuilder(singleTenantApplication.getEnvironment()).build("Test Client");

    setupComplianceToolWithDefaultEntityId(client);

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

    RequestResponseBody authnSaml = authnResponse.readEntity(RequestResponseBody.class);

    Response complianceToolResponse = client
        .target(authnSaml.getSsoLocation())
        .request()
        .buildPost(Entity.form(new MultivaluedHashMap<>(ImmutableMap.of("SAMLRequest", authnSaml.getSamlRequest()))))
        .invoke();

    JSONObject complianceToolResponseBody = new JSONObject(complianceToolResponse.readEntity(String.class));
    assertThat(complianceToolResponseBody.getJSONObject("status").get("message")).isEqualTo(null);
    assertThat(complianceToolResponseBody.getJSONObject("status").getString("status")).isEqualTo("PASSED");
}
 
Example #4
Source File: AuthnRequestAcceptanceTest.java    From verify-service-provider with MIT License 6 votes vote down vote up
@Test
public void shouldGenerateValidAuthnRequestWhenPassedAnEntityId() 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(MULTI_ENTITY_ID_1)))
        .invoke();

    RequestResponseBody authnSaml = authnResponse.readEntity(RequestResponseBody.class);

    Response complianceToolResponse = client
        .target(authnSaml.getSsoLocation())
        .request()
        .buildPost(Entity.form(new MultivaluedHashMap<>(ImmutableMap.of("SAMLRequest", authnSaml.getSamlRequest()))))
        .invoke();

    JSONObject complianceToolResponseBody = new JSONObject(complianceToolResponse.readEntity(String.class));
    assertThat(complianceToolResponseBody.getJSONObject("status").get("message")).isEqualTo(null);
    assertThat(complianceToolResponseBody.getJSONObject("status").getString("status")).isEqualTo("PASSED");
}
 
Example #5
Source File: HelloWorldApplication.java    From dropwizard-zipkin with Apache License 2.0 6 votes vote down vote up
@Override
public void run(HelloWorldConfiguration configuration, Environment environment) throws Exception {

  final Optional<HttpTracing> tracing = zipkinBundle.getHttpTracing();

  final Client client;
  if (tracing.isPresent()) {
    client =
        new ZipkinClientBuilder(environment, tracing.get())
            .build(configuration.getZipkinClient());
  } else {
    final ZipkinClientConfiguration clientConfig = configuration.getZipkinClient();
    client =
        new JerseyClientBuilder(environment)
            .using(clientConfig)
            .build(clientConfig.getServiceName());
  }

  // Register resources
  final HelloWorldResource resource = new HelloWorldResource(client);
  environment.jersey().register(resource);
}
 
Example #6
Source File: MsaMetadataFeatureTest.java    From verify-service-provider with MIT License 6 votes vote down vote up
@Test
public void shouldFailHealthcheckWhenMsaMetadataUnavailable() {
    wireMockServer.stubFor(
        get(urlEqualTo("/matching-service/metadata"))
            .willReturn(aResponse()
                .withStatus(500)
            )
    );

    applicationTestSupport.before();
    Client client = new JerseyClientBuilder(applicationTestSupport.getEnvironment()).build("test client");

    Response response = client
        .target(URI.create(format(HEALTHCHECK_URL, applicationTestSupport.getLocalPort())))
        .request()
        .buildGet()
        .invoke();

    String expectedResult = format("\"%s\":{\"healthy\":false", getMsaMetadataUrl());

    wireMockServer.verify(getRequestedFor(urlEqualTo("/matching-service/metadata")));

    assertThat(response.getStatus()).isEqualTo(INTERNAL_SERVER_ERROR.getStatusCode());
    assertThat(response.readEntity(String.class)).contains(expectedResult);
}
 
Example #7
Source File: MsaMetadataFeatureTest.java    From verify-service-provider with MIT License 6 votes vote down vote up
@Test
public void shouldPassHealthcheckWhenMsaMetadataAvailable() {
    wireMockServer.stubFor(
        get(urlEqualTo("/matching-service/metadata"))
            .willReturn(aResponse()
                .withStatus(200)
                .withBody(MockMsaServer.msaMetadata())
            )
    );

    applicationTestSupport.before();
    Client client = new JerseyClientBuilder(applicationTestSupport.getEnvironment()).build("test client");

    Response response = client
        .target(URI.create(format(HEALTHCHECK_URL, applicationTestSupport.getLocalPort())))
        .request()
        .buildGet()
        .invoke();

    String expectedResult = format("\"%s\":{\"healthy\":true", getMsaMetadataUrl());

    wireMockServer.verify(getRequestedFor(urlEqualTo("/matching-service/metadata")));

    assertThat(response.getStatus()).isEqualTo(OK.getStatusCode());
    assertThat(response.readEntity(String.class)).contains(expectedResult);
}
 
Example #8
Source File: HubMetadataFeatureTest.java    From verify-service-provider with MIT License 6 votes vote down vote up
@Test
public void shouldFailHealthcheckWhenHubMetadataUnavailable() {
    wireMockServer.stubFor(
        get(urlEqualTo("/SAML2/metadata"))
            .willReturn(aResponse()
                .withStatus(500)
            )
    );

    applicationTestSupport.before();
    Client client = new JerseyClientBuilder(applicationTestSupport.getEnvironment()).build("test client");

    Response response = client
        .target(URI.create(format(HEALTHCHECK_URL, applicationTestSupport.getLocalPort())))
        .request()
        .buildGet()
        .invoke();

    String expectedResult = format("\"%s\":{\"healthy\":false", getHubMetadataUrl());

    wireMockServer.verify(getRequestedFor(urlEqualTo("/SAML2/metadata")));

    assertThat(response.getStatus()).isEqualTo(INTERNAL_SERVER_ERROR.getStatusCode());
    assertThat(response.readEntity(String.class)).contains(expectedResult);
}
 
Example #9
Source File: ResourcesClient.java    From microservices-testing-examples with MIT License 5 votes vote down vote up
public ResourcesClient(Environment environment, int port) {
  this.client = new JerseyClientBuilder(checkNotNull(environment))
      .build(ResourcesClient.class.getName())
      .property(CONNECT_TIMEOUT, 2000)
      .property(READ_TIMEOUT, 10000)
      .register(new LoggingFeature(getLogger(DEFAULT_LOGGER_NAME), INFO, PAYLOAD_ANY, 1024));
  this.resourcesUrls = new ResourcesUrls(port);
}
 
Example #10
Source File: RibbonJerseyClientBuilder.java    From dropwizard-consul with Apache License 2.0 5 votes vote down vote up
/**
 * Builds a new {@link RibbonJerseyClient} using the provided service discoverer
 *
 * @param name Jersey client name
 * @param serviceDiscoverer Service discoverer
 * @return new RibbonJerseyClient
 */
public RibbonJerseyClient build(
    final String name, final ConsulServiceDiscoverer serviceDiscoverer) {

  // create a new Jersey client
  final Client jerseyClient =
      new JerseyClientBuilder(environment).using(configuration).build(name);

  return build(name, jerseyClient, serviceDiscoverer);
}
 
Example #11
Source File: SpecialMembershipServiceApplication.java    From microservices-testing-examples with MIT License 5 votes vote down vote up
private CreditScoreService createCreditScoreService(
    SpecialMembershipServiceConfiguration configuration, Environment environment) {
  WebTarget webTarget = new JerseyClientBuilder(environment)
      .using(environment.getObjectMapper().copy())
      .build(getName())
      .property(CONNECT_TIMEOUT, 1000)
      .property(READ_TIMEOUT, 2000)
      .target(configuration.getCreditScoreServiceUrl());
  return new CreditScoreService(webTarget);
}
 
Example #12
Source File: ResourcesClient.java    From microservices-testing-examples with MIT License 5 votes vote down vote up
public ResourcesClient(Environment environment, int port) {
  this.client = new JerseyClientBuilder(checkNotNull(environment))
      .build(ResourcesClient.class.getName())
      .property(CONNECT_TIMEOUT, 2000)
      .property(READ_TIMEOUT, 10000)
      .register(new LoggingFeature(getLogger(DEFAULT_LOGGER_NAME), INFO, PAYLOAD_ANY, 1024));
  this.resourcesUrls = new ResourcesUrls(port);
}
 
Example #13
Source File: NotificationClientTest.java    From notification with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUp() {
  final Client jerseyClient = new JerseyClientBuilder(resources.getEnvironment()).build("test");
  client =
      new NotificationClient(
          resources.getEnvironment().metrics(), jerseyClient, resources.baseUri());
}
 
Example #14
Source File: ClientBuilder.java    From soabase with Apache License 2.0 5 votes vote down vote up
public Client buildJerseyClient(JerseyClientConfiguration configuration, String clientName)
{
    ConnectorProvider localConnectorProvider;
    if ( connectorProvider != null )
    {
        localConnectorProvider = connectorProvider;
    }
    else
    {
        HttpClientBuilder apacheHttpClientBuilder = new HttpClientBuilder(environment).using(configuration);
        CloseableHttpClient closeableHttpClient = apacheHttpClientBuilder.build(clientName);
        localConnectorProvider = new JerseyRetryConnectorProvider(retryComponents, closeableHttpClient, configuration.isChunkedEncodingEnabled());
    }
    JerseyClientBuilder builder = new JerseyClientBuilder(environment)
        .using(configuration)
        .using(localConnectorProvider);
    for ( Class<?> klass : providerClasses )
    {
        builder = builder.withProvider(klass);
    }
    for ( Object provider : providers )
    {
        builder = builder.withProvider(provider);
    }
    Client client = builder
        .build(clientName);

    SoaBundle.getFeatures(environment).putNamed(client, Client.class, clientName);

    return client;
}
 
Example #15
Source File: HelloModule.java    From microservices-comparison with Apache License 2.0 5 votes vote down vote up
@Provides
public Client createHttpClient(Environment environment, DropwizardServerConfiguration configuration) {
    if (client == null) {
        client = new JerseyClientBuilder(environment).using(configuration.getJerseyClientConfiguration()).build("internal client");
    }
    return client;
}
 
Example #16
Source File: ShoppingApplication.java    From bookstore-cqrs-example with Apache License 2.0 5 votes vote down vote up
@Override
public void run(ShoppingConfiguration configuration, Environment environment) throws Exception {
  CartRepository cartRepository = new InMemoryCartRepository();
  final Client client = new JerseyClientBuilder(environment).using(configuration.httpClient).build(getName());
  ProductCatalogClient productCatalogClient = ProductCatalogClient.create(client,
      configuration.productCatalogServiceUrl);
  environment.jersey().register(new CartResource(productCatalogClient, cartRepository));
  environment.jersey().setUrlPattern("/service/*");
  logger.info("ShoppingApplication started!");
}
 
Example #17
Source File: DashboardTestApplication.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
@Override
public void run(DashboardTestConfiguration configuration, Environment environment) throws Exception {
    // Generating  HTTP Clients
    Client jerseyClient = new JerseyClientBuilder(environment).using(configuration.getJerseyClientConfiguration())
            .build(getName());

    // Configuring HealthChecks
    environment.healthChecks().register(getName(), new HealthCheck() {
        @Override
        protected Result check() throws Exception {
            return Result.healthy();
        }
    });
}
 
Example #18
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 #19
Source File: TenacityResourcesServletTest.java    From tenacity with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void initialization() {
    CLIENT = new TenacityClientBuilder(APP_RULE.getEnvironment(), ServletKeys.KEY_ONE)
            .build();
    URI_ROOT = URI.create("http://127.0.0.1:" + APP_RULE.getAdminPort());
    JERSEY_CLIENT = new JerseyClientBuilder(APP_RULE.getEnvironment())
            .build("test");
}
 
Example #20
Source File: TenacityConfiguredBundleTest.java    From tenacity with Apache License 2.0 5 votes vote down vote up
private static void validateAppIsRunning(DropwizardAppRule<Configuration> app) {
    final Client client = new JerseyClientBuilder(app.getEnvironment()).build("appOne");
    final Response response = client
            .target(String.format("http://localhost:%d", app.getLocalPort()))
            .request()
            .get();
    assertThat(response.getStatus()).isEqualTo(Response.Status.NO_CONTENT.getStatusCode());

    response.close();
}
 
Example #21
Source File: SnowizardApplicationTest.java    From snowizard with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testCanGetIdOverHttp() throws Exception {
    final String response = new JerseyClientBuilder(RULE.getEnvironment())
            .build("").target("http://localhost:" + RULE.getLocalPort())
            .request(MediaType.TEXT_PLAIN)
            .header(HttpHeaders.USER_AGENT, AGENT).get(String.class);
    final long id = Long.valueOf(response);
    assertThat(id).isNotNull();
}
 
Example #22
Source File: BaseRoleConnectHelper.java    From emodb with Apache License 2.0 5 votes vote down vote up
protected Client getClient () {
    if (_client == null) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        _client = new JerseyClientBuilder(_metricRegistry).using(_config.getHttpClientConfiguration()).using(executorService, new ObjectMapper()).build("dw");
    }
    return _client;
}
 
Example #23
Source File: ComplianceToolModeConfiguration.java    From verify-service-provider with MIT License 5 votes vote down vote up
public ComplianceToolClient createComplianceToolService(Environment environment, String url, Integer timeout) {
    JerseyClientConfiguration configuration = new JerseyClientConfiguration();
    configuration.setConnectionRequestTimeout(Duration.seconds(timeout));
    configuration.setTimeout(Duration.seconds(timeout));
    configuration.setConnectionTimeout(Duration.seconds(timeout));
    Client client = new JerseyClientBuilder(environment).using(configuration).build("Compliance Tool Initiation Client");
    return new ComplianceToolClient(client, url, serviceEntityId, getSigningCertificate(), getEncryptionCertificate());
}
 
Example #24
Source File: VerifyServiceProviderApplication.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Override
public void run(VerifyServiceProviderConfiguration configuration, Environment environment) throws Exception {
    Client client = new JerseyClientBuilder(environment).build(getName());
    VerifyServiceProviderFactory factory = new VerifyServiceProviderFactory(configuration, hubMetadataBundle, msaMetadataBundle, client);

    environment.jersey().register(new JerseyViolationExceptionMapper());
    environment.jersey().register(new JsonProcessingExceptionMapper());
    environment.jersey().register(new InvalidEntityIdExceptionMapper());
    environment.jersey().register(factory.getVersionNumberResource());
    environment.jersey().register(factory.getGenerateAuthnRequestResource());
    environment.jersey().register(factory.getTranslateSamlResponseResource());
    environment.lifecycle().addServerLifecycleListener(new VerifyServiceProviderServerListener(environment));
}
 
Example #25
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 #26
Source File: AuthnRequestAcceptanceTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldReturn400WhenPassedInvalidEntityIdForMultiTenantApplication() 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("not a valid entityID")))
        .invoke();

    assertThat(authnResponse.getStatus()).isEqualTo(BAD_REQUEST.getStatusCode());
}
 
Example #27
Source File: ComplianceToolModeAcceptanceTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Before
public void setUpBefore() {
    JerseyClientConfiguration configuration = new JerseyClientConfiguration();
    configuration.setTimeout(Duration.seconds(10));
    configuration.setConnectionTimeout(Duration.seconds(10));
    configuration.setConnectionRequestTimeout(Duration.seconds(10));
    client = new JerseyClientBuilder(appRule.getEnvironment()).using(configuration).build(ComplianceToolModeAcceptanceTest.class.getName());
    complianceTool = new ComplianceToolService(client);
}
 
Example #28
Source File: HubMetadataFeatureTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldFailHealthcheckWhenHubMetadataIsSignedWithMD5() {
    String id = UUID.randomUUID().toString();
    Signature signature = SignatureBuilder.aSignature()
        .withDigestAlgorithm(id, new DigestMD5())
        .withX509Data(TestCertificateStrings.METADATA_SIGNING_A_PUBLIC_CERT)
        .withSigningCredential(new TestCredentialFactory(TestCertificateStrings.METADATA_SIGNING_A_PUBLIC_CERT,
                TestCertificateStrings.METADATA_SIGNING_A_PRIVATE_KEY).getSigningCredential()).build();
    String metadata = new MetadataFactory().metadata(new EntitiesDescriptorFactory().signedEntitiesDescriptor(id, signature));

    wireMockServer.stubFor(
            get(urlEqualTo("/SAML2/metadata"))
                    .willReturn(
                            aResponse()
                                    .withStatus(200)
                                    .withBody(metadata)
                    )
    );

    applicationTestSupport.before();
    Client client = new JerseyClientBuilder(applicationTestSupport.getEnvironment()).build("test client");

    Response response = client
        .target(URI.create(format(HEALTHCHECK_URL, applicationTestSupport.getLocalPort())))
        .request()
        .buildGet()
        .invoke();

    String expectedResult = format("\"%s\":{\"healthy\":false", getHubMetadataUrl());

    wireMockServer.verify(getRequestedFor(urlEqualTo("/SAML2/metadata")));

    assertThat(response.getStatus()).isEqualTo(INTERNAL_SERVER_ERROR.getStatusCode());
    assertThat(response.readEntity(String.class)).contains(expectedResult);
}
 
Example #29
Source File: HubMetadataFeatureTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldPassHealthcheckWhenHubMetadataAvailable() {
    wireMockServer.stubFor(
        get(urlEqualTo("/SAML2/metadata"))
            .willReturn(
                aResponse()
                    .withStatus(200)
                    .withBody(new MetadataFactory().defaultMetadata())
            )
    );

    applicationTestSupport.before();
    Client client = new JerseyClientBuilder(applicationTestSupport.getEnvironment()).build("test client");

    Response response = client
        .target(URI.create(format(HEALTHCHECK_URL, applicationTestSupport.getLocalPort())))
        .request()
        .buildGet()
        .invoke();

    String expectedResult = format("\"%s\":{\"healthy\":true", getHubMetadataUrl());

    wireMockServer.verify(getRequestedFor(urlEqualTo("/SAML2/metadata")));

    assertThat(response.getStatus()).isEqualTo(OK.getStatusCode());
    assertThat(response.readEntity(String.class)).contains(expectedResult);
}
 
Example #30
Source File: ZipkinClientBuilder.java    From dropwizard-zipkin with Apache License 2.0 5 votes vote down vote up
/**
 * Build a new Jersey Client that is instrumented for Zipkin
 *
 * @param configuration Configuration to use for the client
 * @return new Jersey Client
 */
public Client build(final ZipkinClientConfiguration configuration) {
  final Client client =
      new JerseyClientBuilder(environment)
          .using(configuration)
          .build(configuration.getServiceName());
  return build(client);
}