io.dropwizard.util.Duration Java Examples

The following examples show how to use io.dropwizard.util.Duration. 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: ClientTimeoutTest.java    From tenacity with Apache License 2.0 6 votes vote down vote up
@Test
public void tenacityDoesntRaceWithJerseyTimeout() {
    clientConfiguration.setTimeout(Duration.milliseconds(1));
    tenacityConfiguration.setExecutionIsolationThreadTimeoutInMillis(300);
    registerTenacityProperties();

    final Client client = tenacityClientBuilder.build(buildClient());
    final WebTarget spyTarget = spy(client.target(uri));
    final VoidCommand command = new VoidCommand(spyTarget, Duration.milliseconds(500));

    boolean timeoutFailure = false;
    try {
        command.execute();
    } catch (HystrixRuntimeException err) {
        timeoutFailure = err.getFailureType().equals(HystrixRuntimeException.FailureType.TIMEOUT);
    }

    assertTrue(timeoutFailure);
    assertTrue(command.isResponseTimedOut());
}
 
Example #2
Source File: ElasticsearchUtilsTest.java    From foxtrot with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithDifferentTableprefixShouldCreateIndexWithTableName() throws Exception {
    ElasticsearchConfig config = new ElasticsearchConfig();
    config.setTableNamePrefix("azkaban");
    ElasticsearchUtils.setTableNamePrefix(config);
    TestRequest request = new TestRequest();
    LastFilter filter = new LastFilter();
    filter.setDuration(Duration.minutes(10));
    filter.setCurrentTime(TEST_CURRENT_TIME);
    request.setFilters(Collections.<Filter>singletonList(filter));
    String indexes[] = ElasticsearchUtils.getIndices("test", request,
                                                     new PeriodSelector(request.getFilters()).analyze(TEST_CURRENT_TIME)
                                                    );
    Assert.assertArrayEquals(new String[]{"azkaban-test-table-04-4-2015"}, indexes);
    config.setTableNamePrefix("foxtrot");
    ElasticsearchUtils.setTableNamePrefix(config);
}
 
Example #3
Source File: NotificationStore.java    From notification with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor
 *
 * @param client Riak client
 * @param idGenerator ID Generator
 * @param cursors Cursor data store
 * @param ruleStore Rule data store
 * @param timeout Riak server-side timeout
 * @param requestTimeout Riak client-side timeout
 */
public NotificationStore(
    final RiakClient client,
    final IdGenerator idGenerator,
    final CursorStore cursors,
    final RuleStore ruleStore,
    final Duration timeout,
    final Duration requestTimeout) {

  final MetricRegistry registry = SharedMetricRegistries.getOrCreate("default");
  this.fetchTimer = registry.timer(MetricRegistry.name(NotificationStore.class, "fetch"));
  this.updateTimer = registry.timer(MetricRegistry.name(NotificationStore.class, "store"));
  this.deleteTimer = registry.timer(MetricRegistry.name(NotificationStore.class, "delete"));

  this.client = Objects.requireNonNull(client, "client == null");
  this.idGenerator = Objects.requireNonNull(idGenerator, "idGenerator == null");
  this.cursors = Objects.requireNonNull(cursors, "cursors == null");
  this.ruleStore = Objects.requireNonNull(ruleStore, "ruleStore == null");

  this.timeout =
      Optional.ofNullable(timeout)
          .map(t -> Math.toIntExact(t.toMilliseconds()))
          .orElse(DEFAULT_TIMEOUT_MS);
  this.requestTimeout = Objects.requireNonNull(requestTimeout, "requestTimeout == null");
}
 
Example #4
Source File: LatencyAwarePolicyFactoryTest.java    From dropwizard-cassandra with Apache License 2.0 6 votes vote down vote up
@Test
public void buildsPolicyWithAllParams() throws Exception {
    final LatencyAwarePolicyFactory factory = new LatencyAwarePolicyFactory();
    factory.setSubPolicy(subPolicyFactory);
    factory.setExclusionThreshold(1.0d);
    factory.setMinimumMeasurements(2);
    factory.setRetryPeriod(Duration.minutes(3));
    factory.setScale(Duration.milliseconds(100));
    factory.setUpdateRate(Duration.seconds(5));

    final LoadBalancingPolicy policy = factory.build();

    assertThat(policy).isSameAs(resultingPolicy);
    verify(subPolicyFactory).build();

    InOrder inOrder = inOrder(policyBuilder);
    inOrder.verify(policyBuilder).withExclusionThreshold(1.0d);
    inOrder.verify(policyBuilder).withMininumMeasurements(2);
    inOrder.verify(policyBuilder).withRetryPeriod(3L, TimeUnit.MINUTES);
    inOrder.verify(policyBuilder).withScale(100L, TimeUnit.MILLISECONDS);
    inOrder.verify(policyBuilder).withUpdateRate(5L, TimeUnit.SECONDS);
    inOrder.verify(policyBuilder).build();
}
 
Example #5
Source File: PoolingOptionsFactoryTest.java    From dropwizard-cassandra with Apache License 2.0 6 votes vote down vote up
@Test
public void buildsPoolingOptionsWithConfiguredValues() throws Exception {
    // given
    final PoolingOptionsFactory factory = new PoolingOptionsFactory();
    factory.setHeartbeatInterval(Duration.minutes(1));
    factory.setPoolTimeout(Duration.seconds(2));
    factory.setLocal(createHostDistanceOptions(1, 3, 5, 25));
    factory.setRemote(createHostDistanceOptions(2, 4, 6, 30));

    // when
    final PoolingOptions poolingOptions = factory.build();

    // then
    assertThat(poolingOptions.getHeartbeatIntervalSeconds()).isEqualTo(60);
    assertThat(poolingOptions.getPoolTimeoutMillis()).isEqualTo(2000);

    assertThat(poolingOptions.getCoreConnectionsPerHost(HostDistance.LOCAL)).isEqualTo(1);
    assertThat(poolingOptions.getMaxConnectionsPerHost(HostDistance.LOCAL)).isEqualTo(3);
    assertThat(poolingOptions.getMaxRequestsPerConnection(HostDistance.LOCAL)).isEqualTo(5);
    assertThat(poolingOptions.getNewConnectionThreshold(HostDistance.LOCAL)).isEqualTo(25);

    assertThat(poolingOptions.getCoreConnectionsPerHost(HostDistance.REMOTE)).isEqualTo(2);
    assertThat(poolingOptions.getMaxConnectionsPerHost(HostDistance.REMOTE)).isEqualTo(4);
    assertThat(poolingOptions.getMaxRequestsPerConnection(HostDistance.REMOTE)).isEqualTo(6);
    assertThat(poolingOptions.getNewConnectionThreshold(HostDistance.REMOTE)).isEqualTo(30);
}
 
Example #6
Source File: CreateRuleMutationTest.java    From notification with Apache License 2.0 6 votes vote down vote up
@Test
public void testStoreRule() throws Exception {
  when(environment.getArgument("category")).thenReturn("like");
  when(environment.getArgument("rule"))
      .thenReturn(ImmutableMap.of("maxSize", 3, "maxDuration", "3m", "matchOn", "like_id"));

  final Rule rule =
      Rule.builder()
          .withMaxSize(3)
          .withMatchOn("like_id")
          .withMaxDuration(Duration.minutes(3))
          .build();

  final Boolean actual = mutation.get(environment);
  verify(store).store(eq("like"), eq(rule));
  assertThat(actual).isTrue();
}
 
Example #7
Source File: MatcherTest.java    From notification with Apache License 2.0 6 votes vote down vote up
@Test
public void testCheckDuration() {
  final Rule rule = Rule.builder().withMaxDuration(Duration.minutes(10)).build();

  final Notification future =
      Notification.builder().withCreatedAt(ZonedDateTime.parse("2015-07-31T23:31:35Z")).build();
  final Notification future2 =
      Notification.builder().withCreatedAt(ZonedDateTime.parse("2015-07-31T23:21:36Z")).build();
  final Notification present =
      Notification.builder().withCreatedAt(ZonedDateTime.parse("2015-07-31T23:21:35Z")).build();
  final Notification past =
      Notification.builder().withCreatedAt(ZonedDateTime.parse("2015-07-31T23:11:35Z")).build();
  final Notification past2 =
      Notification.builder().withCreatedAt(ZonedDateTime.parse("2015-07-31T23:11:34Z")).build();

  final Matcher matcher = new Matcher(rule, notification);
  assertThat(matcher.checkDuration(future)).isFalse();
  assertThat(matcher.checkDuration(future2)).isFalse();
  assertThat(matcher.checkDuration(present)).isTrue();
  assertThat(matcher.checkDuration(past)).isTrue();
  assertThat(matcher.checkDuration(past2)).isFalse();
}
 
Example #8
Source File: QueryTranslator.java    From foxtrot with Apache License 2.0 6 votes vote down vote up
private LastFilter parseWindowFunction(List expressions) {
    if(expressions == null || expressions.isEmpty() || expressions.size() > 3) {
        throw new FqlParsingException("last function has following format: last(duration, [start-time, [timestamp field]])");
    }
    LastFilter lastFilter = new LastFilter();
    lastFilter.setDuration(Duration.parse(QueryUtils.expressionToString((Expression)expressions.get(0))));
    if(expressions.size() > 1) {
        lastFilter.setCurrentTime(QueryUtils.expressionToNumber((Expression)expressions.get(1))
                                          .longValue());
    }
    if(expressions.size() > 2) {
        lastFilter.setField(QueryUtils.expressionToString((Expression)expressions.get(2))
                                    .replaceAll(Constants.SQL_FIELD_REGEX, ""));
    }
    return lastFilter;
}
 
Example #9
Source File: HttpZipkinFactoryTest.java    From dropwizard-zipkin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeConfigurable() throws IOException {
  ObjectMapper mapper =
      new ObjectMapper(new YAMLFactory()).setSubtypeResolver(new DiscoverableSubtypeResolver());

  final ZipkinFactory factory =
      mapper.readValue(
          "enabled: true\n"
              + "collector: http\n"
              + "baseUrl: http://example.com:1234/zipkin\n"
              + "connectTimeout: 1d\n"
              + "readTimeout: 2d\n"
              + "reportTimeout: 3d\n",
          ZipkinFactory.class);
  assertThat(factory).isInstanceOf(HttpZipkinFactory.class);
  HttpZipkinFactory httpFactory = (HttpZipkinFactory) factory;
  assertThat(httpFactory.getBaseUrl()).isEqualTo("http://example.com:1234/zipkin");
  assertThat(httpFactory.getReportTimeout()).isEqualTo(Duration.days(3));
}
 
Example #10
Source File: KafkaZipkinFactoryTest.java    From dropwizard-zipkin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeConfigurable() throws IOException {
  ObjectMapper mapper =
      new ObjectMapper(new YAMLFactory()).setSubtypeResolver(new DiscoverableSubtypeResolver());

  final ZipkinFactory factory =
      mapper.readValue(
          "enabled: true\n"
              + "collector: kafka\n"
              + "bootstrapServers: example.com:1234\n"
              + "topic: foo\n"
              + "overrides:\n"
              + "  acks: all\n"
              + "reportTimeout: 3d\n",
          ZipkinFactory.class);
  assertThat(factory).isInstanceOf(KafkaZipkinFactory.class);
  KafkaZipkinFactory kafkaFactory = (KafkaZipkinFactory) factory;
  assertThat(kafkaFactory.getBootstrapServers()).isEqualTo("example.com:1234");
  assertThat(kafkaFactory.getTopic()).isEqualTo("foo");
  assertThat(kafkaFactory.getOverrides()).containsExactly(entry("acks", "all"));
  assertThat(kafkaFactory.getReportTimeout()).isEqualTo(Duration.days(3));
}
 
Example #11
Source File: CassandraStorage.java    From cassandra-reaper with Apache License 2.0 6 votes vote down vote up
private static void overridePoolingOptions(CassandraFactory cassandraFactory) {
  PoolingOptionsFactory newPoolingOptionsFactory = new PoolingOptionsFactory() {
    @Override
    public PoolingOptions build() {
      if (null == getPoolTimeout()) {
        setPoolTimeout(Duration.minutes(2));
      }
      return super.build().setMaxQueueSize(40960);
    }
  };
  cassandraFactory.getPoolingOptions().ifPresent((originalPoolingOptions) -> {
    newPoolingOptionsFactory.setHeartbeatInterval(originalPoolingOptions.getHeartbeatInterval());
    newPoolingOptionsFactory.setIdleTimeout(originalPoolingOptions.getIdleTimeout());
    newPoolingOptionsFactory.setLocal(originalPoolingOptions.getLocal());
    newPoolingOptionsFactory.setRemote(originalPoolingOptions.getRemote());
    newPoolingOptionsFactory.setPoolTimeout(originalPoolingOptions.getPoolTimeout());
  });
  cassandraFactory.setPoolingOptions(java.util.Optional.of(newPoolingOptionsFactory));
}
 
Example #12
Source File: MultiTimeQueryActionTest.java    From foxtrot with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultiTimeQuery() throws FoxtrotException, JsonProcessingException {
    Query query = new Query();
    query.setTable(TestUtils.TEST_TABLE_NAME);
    ResultSort resultSort = new ResultSort();
    resultSort.setOrder(ResultSort.Order.asc);
    resultSort.setField("_timestamp");
    query.setSort(resultSort);
    BetweenFilter betweenFilter = new BetweenFilter("_timestamp", 1397658117000L, 1397658118005L, false);
    query.setFilters(Arrays.asList(betweenFilter));

    Duration duration = Duration.days(1);
    MultiTimeQueryRequest multiTimeQueryRequest = new MultiTimeQueryRequest(1, duration, query);
    ActionResponse actionResponse = getQueryExecutor().execute(multiTimeQueryRequest);
    MultiTimeQueryResponse multiTimeQueryResponse = null;
    if(actionResponse instanceof MultiTimeQueryResponse) {
        multiTimeQueryResponse = (MultiTimeQueryResponse)actionResponse;
    }
    assertNotNull(multiTimeQueryResponse);

    QueryResponse queryResponse = (QueryResponse)multiTimeQueryResponse.getResponses()
            .get("1397658117000");

    assertEquals(9, queryResponse.getTotalHits());
}
 
Example #13
Source File: ConsulBundle.java    From dropwizard-consul with Apache License 2.0 6 votes vote down vote up
protected void setupEnvironment(ConsulFactory consulConfig, Environment environment) {

    final Consul consul = consulConfig.build();
    final String serviceId = consulConfig.getServiceId().orElse(UUID.randomUUID().toString());
    final ConsulAdvertiser advertiser =
        new ConsulAdvertiser(environment, consulConfig, consul, serviceId);

    final Optional<Duration> retryInterval = consulConfig.getRetryInterval();
    final Optional<ScheduledExecutorService> scheduler =
        retryInterval.map(i -> Executors.newScheduledThreadPool(1));

    // Register a Jetty listener to get the listening host and port
    environment
        .lifecycle()
        .addServerLifecycleListener(
            new ConsulServiceListener(advertiser, retryInterval, scheduler));

    // Register a ping healthcheck to the Consul agent
    environment.healthChecks().register("consul", new ConsulHealthCheck(consul));

    // Register a shutdown manager to deregister the service
    environment.lifecycle().manage(new ConsulAdvertiserManager(advertiser, scheduler));

    // Add an administrative task to toggle maintenance mode
    environment.admin().addTask(new MaintenanceTask(consul, serviceId));
  }
 
Example #14
Source File: ConstantSpeculativeExecutionPolicyFactoryTest.java    From dropwizard-cassandra with Apache License 2.0 5 votes vote down vote up
@Test
public void buildsPolicyWithConfiguredValues() throws Exception {
    final ConstantSpeculativeExecutionPolicyFactory factory = new ConstantSpeculativeExecutionPolicyFactory();
    factory.setDelay(Duration.seconds(5));
    factory.setMaxSpeculativeExecutions(2);

    final SpeculativeExecutionPolicy policy = factory.build();

    assertThat(policy).isExactlyInstanceOf(ConstantSpeculativeExecutionPolicy.class);
}
 
Example #15
Source File: LdapBasicAuthenticatorTest.java    From eagle with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetContextEnvironmentNormal() {
    String username = "username";
    String secretPhrase = "secret-phrase";
    Hashtable<String, String> env = AUTHENTICATOR_FOR_UTIL_METHODS_WITHOUT_SSL.getContextEnvironment(username, secretPhrase);

    Assert.assertEquals("unexpected ldap context factory name", LDAP_CTX_FACTORY_NAME, env.get(Context.INITIAL_CONTEXT_FACTORY));
    Assert.assertEquals("unexpected ldap service provider url", LDAP_SERVICE_PROVIDER_URL, env.get(Context.PROVIDER_URL));
    Assert.assertEquals("unexpected connecting timeout value", String.valueOf(Duration.parse(CONNECTING_TIMEOUT_VALUE).toMilliseconds()), env.get(LDAP_CONNECT_TIMEOUT_KEY));
    Assert.assertEquals("unexpected reading timeout value", String.valueOf(Duration.parse(READING_TIMEOUT_VALUE).toMilliseconds()), env.get(LDAP_READ_TIMEOUT_KEY));
    Assert.assertEquals("unexpected username", username+USERNAME_SUFFIX, env.get(Context.SECURITY_PRINCIPAL));
    Assert.assertEquals("unexpected secret credentials", secretPhrase, env.get(Context.SECURITY_CREDENTIALS));
    Assert.assertEquals("unexpected strategy", STRATEGY_SIMPLE, env.get(Context.SECURITY_AUTHENTICATION));
}
 
Example #16
Source File: DefaultSlabAllocator.java    From emodb with Apache License 2.0 5 votes vote down vote up
private static ScheduledExecutorService defaultExecutor(LifeCycleRegistry lifeCycle, String metricsGroup) {
    String nameFormat = "Events Slab Allocator Cleanup-" + metricsGroup.substring(metricsGroup.lastIndexOf('.') + 1) + "-%d";
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(nameFormat).setDaemon(true).build();
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1, threadFactory);
    lifeCycle.manage(new ExecutorServiceManager(executor, Duration.seconds(5), nameFormat));
    return executor;
}
 
Example #17
Source File: ArchaiusPropertyRegister.java    From tenacity with Apache License 2.0 5 votes vote down vote up
public void register(BreakerboxConfiguration breakerboxConfiguration) {
    if (breakerboxConfiguration.getUrls().isEmpty()) {
        return;
    }

    final TenacityPollingScheduler tenacityPollingScheduler = new TenacityPollingScheduler(
            Ints.checkedCast(breakerboxConfiguration.getInitialDelay().toMilliseconds()),
            Ints.checkedCast(breakerboxConfiguration.getDelay().toMilliseconds()),
            true);

    final CountDownLatch countDownLatch = new CountDownLatch(1);

    if (breakerboxConfiguration.isWaitForInitialLoad()) {
        tenacityPollingScheduler.addPollListener((eventType, lastResult, exception) -> countDownLatch.countDown());
    }

    final DynamicConfiguration dynConfig = new DynamicConfiguration(
            new URLConfigurationSource(breakerboxConfiguration.getUrls().split(",")),
            tenacityPollingScheduler);

    ConfigurationManager.getConfigInstance();
    ConfigurationManager.loadPropertiesFromConfiguration(dynConfig);

    if (breakerboxConfiguration.isWaitForInitialLoad()) {
        final Duration duration = breakerboxConfiguration.getWaitForInitialLoad();
        try {
            final boolean success = countDownLatch.await(duration.getQuantity(), duration.getUnit());
            LOGGER.info("Breakerbox initial configuration load: {}", success ? "SUCCESS" : "FAILURE");
        } catch (Exception err) {
            LOGGER.warn("Failed waiting for Breakerbox initial load", err);
        }
    }
}
 
Example #18
Source File: ClientTimeoutTest.java    From tenacity with Apache License 2.0 5 votes vote down vote up
@Test
public void tenacityConfigurationOverridesDefaultConfiguration() {
    clientConfiguration.setTimeout(Duration.milliseconds(1));
    final Client tenacityClient = tenacityClientBuilder.build(buildClient());

    postSettingTheTimeoutOnResource(tenacityClient.target(uri), Duration.milliseconds(100));

}
 
Example #19
Source File: TenacityObservableCommandTest.java    From tenacity with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldTimeoutAndRespectsKeyProperties() throws InterruptedException {
    final TenacityConfiguration tenacityConfiguration = new TenacityConfiguration();
    tenacityConfiguration.setExecutionIsolationThreadTimeoutInMillis(100);

    new TenacityPropertyRegister(
            ImmutableMap.<TenacityPropertyKey, TenacityConfiguration>of(DependencyKey.OBSERVABLE_TIMEOUT, tenacityConfiguration),
            new BreakerboxConfiguration())
            .register();

    executeTimeoutAndVerify(new TimeoutObservable(Duration.milliseconds(300)));
}
 
Example #20
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 #21
Source File: DefaultClaimStore.java    From emodb with Apache License 2.0 5 votes vote down vote up
private static ScheduledExecutorService defaultScheduledExecutor(LifeCycleRegistry lifeCycle, String metricsGroup) {
    String nameFormat = "Events Claim Cleanup-" + metricsGroup.substring(metricsGroup.lastIndexOf('.') + 1) + "-%d";
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1,
            new ThreadFactoryBuilder().setNameFormat(nameFormat).setDaemon(true).build());
    lifeCycle.manage(new ExecutorServiceManager(executor, Duration.seconds(5), nameFormat));
    return executor;
}
 
Example #22
Source File: TenacityObservablesTest.java    From tenacity with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAttemptSecondAfterTimeoutInFirst() {
    assertTrue(TenacityObservables.execute(
            new TimeoutObservable(Duration.seconds(3)),
            TenacityCommand.<Boolean>builder(DependencyKey.GENERAL).run(() -> true).lazyObservable()));

    assertTrue(TenacityObservables.execute(
            new TimeoutObservable(Duration.seconds(3)),
            TenacityObservableCommand.<Boolean>builder(DependencyKey.GENERAL).run(() -> Observable.just(true)).lazyObservable()));
}
 
Example #23
Source File: ConsulServiceListenerTest.java    From dropwizard-consul with Apache License 2.0 5 votes vote down vote up
@Test
public void testRegister() {
  final ConsulServiceListener listener =
      new ConsulServiceListener(
          advertiser, Optional.of(Duration.milliseconds(1)), Optional.of(scheduler));

  when(advertiser.register(anyString(), anyInt(), anyInt()))
      .thenThrow(new ConsulException("Cannot connect to Consul"))
      .thenReturn(true);

  listener.register(null, 0, 0);

  verify(advertiser, timeout(100).atLeast(1)).register(null, 0, 0);
}
 
Example #24
Source File: ClientTimeoutTest.java    From tenacity with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    clientConfiguration = new JerseyClientConfiguration();
    clientConfiguration.setConnectionTimeout(Duration.milliseconds(100));
    tenacityConfiguration = new TenacityConfiguration();
    metricRegistry = new MetricRegistry();
    executorService = Executors.newSingleThreadExecutor();
}
 
Example #25
Source File: ConsulFactoryTest.java    From dropwizard-consul with Apache License 2.0 5 votes vote down vote up
private ConsulFactory createFullyPopulatedConsulFactory() {
  final ConsulFactory consulFactory = new ConsulFactory();
  consulFactory.setSeviceName("serviceName");
  consulFactory.setEnabled(true);
  consulFactory.setServicePort(1000);
  consulFactory.setAdminPort(2000);
  consulFactory.setServiceAddress("localhost");
  consulFactory.setTags(ImmutableList.of("tag1", "tag2"));
  consulFactory.setRetryInterval(Duration.seconds(5));
  consulFactory.setCheckInterval(Duration.seconds(1));
  consulFactory.setAclToken("acl-token");
  consulFactory.setServicePing(false);
  return consulFactory;
}
 
Example #26
Source File: ErrorAwarePolicyFactoryTest.java    From dropwizard-cassandra with Apache License 2.0 5 votes vote down vote up
@Test
public void buildsPolicyWithChildPolicy() throws Exception {
    final ErrorAwarePolicyFactory factory = new ErrorAwarePolicyFactory();
    factory.setSubPolicy(subPolicyFactory);
    factory.setMaxErrorsPerMinute(5);
    factory.setRetryPeriod(Duration.days(7));

    final ErrorAwarePolicy policy = (ErrorAwarePolicy) factory.build();

    assertThat(policy.getChildPolicy()).isSameAs(subPolicy);
}
 
Example #27
Source File: ConstantReconnectionPolicyFactoryTest.java    From dropwizard-cassandra with Apache License 2.0 5 votes vote down vote up
@Test
public void buildsPolicyWithDelayInMillis() throws Exception {
    final ConstantReconnectionPolicyFactory factory = new ConstantReconnectionPolicyFactory();
    factory.setDelay(Duration.seconds(5));

    final ConstantReconnectionPolicy policy = (ConstantReconnectionPolicy) factory.build();

    assertThat(policy.getConstantDelayMs()).isEqualTo(5000L);
}
 
Example #28
Source File: ClientTimeoutTest.java    From tenacity with Apache License 2.0 5 votes vote down vote up
@Test
public void regularClientTimesOut() {
    clientConfiguration.setTimeout(Duration.milliseconds(1));
    final Client regularClientWithNoTenacityOverride = buildClient();

    thrown.expectCause(any(SocketTimeoutException.class));
    postSettingTheTimeoutOnResource(regularClientWithNoTenacityOverride.target(uri), Duration.milliseconds(100));
}
 
Example #29
Source File: Utils.java    From dropwizard-grpc with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the given durations together. The implementation is not performant, use only for testing.
 *
 * @return a Duration that is the sum of <code>a</code> and <code>b</code>. If the unit of the 2 Durations is the
 *         same, it will be used, otherwise they're converted to nanoseconds before summing
 */
public static Duration add(final Duration a, final Duration b) {
    return a.getUnit() == b.getUnit()
            ? Duration.parse(
                String.valueOf(a.getQuantity() + b.getQuantity()) + " " + a.getUnit().toString().toLowerCase())
            : Duration.nanoseconds(a.toNanoseconds() + b.toNanoseconds());
}
 
Example #30
Source File: TenacityObservableCommandTest.java    From tenacity with Apache License 2.0 4 votes vote down vote up
@Test
public void observableCommandCanAdjustSemaphoreMaxConcurrentExecutions() throws InterruptedException {
    final SemaphoreConfiguration semaphoreConfiguration = new SemaphoreConfiguration();
    semaphoreConfiguration.setMaxConcurrentRequests(50);

    final TenacityConfiguration tenacityConfiguration = new TenacityConfiguration();
    tenacityConfiguration.setSemaphore(semaphoreConfiguration);
    tenacityConfiguration.setExecutionIsolationThreadTimeoutInMillis(3000);

    new TenacityPropertyRegister(
            ImmutableMap.<TenacityPropertyKey, TenacityConfiguration>of(DependencyKey.OBSERVABLE_TIMEOUT, tenacityConfiguration),
            new BreakerboxConfiguration())
            .register();

    new TimeoutObservable(Duration.milliseconds(500))
            .getCumulativeCommandEventCounterStream()
            .startCachingStreamValuesIfUnstarted();

    final int defaultSemaphoreMaxConcurrentRequests = new SemaphoreConfiguration().getMaxConcurrentRequests();

    final ImmutableList.Builder<Observable<Boolean>> observables = ImmutableList.builder();
    for (int i = 0; i < defaultSemaphoreMaxConcurrentRequests * 2; ++i) {
        final TimeoutObservable command = new TimeoutObservable(Duration.milliseconds(500));
        observables.add(command.observe());
    }

    for (Observable<Boolean> observable : observables.build()) {
        try {
            assertTrue(observable.toBlocking().single());
        } catch (HystrixRuntimeException err) {
            fail("Failed to execute an observe: " + err);
        }
    }

    Thread.sleep(1000);

    assertThat(TenacityObservableCommand
            .getCommandMetrics(DependencyKey.OBSERVABLE_TIMEOUT)
            .getCumulativeCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED))
            .isEqualTo(0);
    assertThat(TenacityObservableCommand
            .getCommandMetrics(DependencyKey.OBSERVABLE_TIMEOUT)
            .getCumulativeCount(HystrixRollingNumberEvent.TIMEOUT))
            .isEqualTo(0);
    assertThat(TenacityObservableCommand
            .getCommandMetrics(DependencyKey.OBSERVABLE_TIMEOUT)
            .getCumulativeCount(HystrixRollingNumberEvent.SUCCESS))
            .isEqualTo(observables.build().size());
}