Java Code Examples for org.joda.time.Duration#standardDays()

The following examples show how to use org.joda.time.Duration#standardDays() . 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: SegmentIntervalUtils.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
/**
 * Converts push frequency into duration. For invalid or less than 'hourly' push frequency, treats it as 'daily'.
 */
public static Duration convertToDuration(String pushFrequency) {
  if ("hourly".equalsIgnoreCase(pushFrequency)) {
    return Duration.standardHours(1L);
  }
  if ("daily".equalsIgnoreCase(pushFrequency)) {
    return Duration.standardDays(1L);
  }
  if ("weekly".equalsIgnoreCase(pushFrequency)) {
    return Duration.standardDays(7L);
  }
  if ("monthly".equalsIgnoreCase(pushFrequency)) {
    return Duration.standardDays(30L);
  }
  return Duration.standardDays(1L);
}
 
Example 2
Source File: DurationConverterTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testRoundTrip() {
  TestEntity entity = new TestEntity(Duration.standardDays(6));
  jpaTm().transact(() -> jpaTm().getEntityManager().persist(entity));
  assertThat(
          jpaTm()
              .transact(
                  () ->
                      jpaTm()
                          .getEntityManager()
                          .createNativeQuery(
                              "SELECT duration FROM \"TestEntity\" WHERE name = 'id'")
                          .getResultList()))
      .containsExactly(BigInteger.valueOf(Duration.standardDays(6).getMillis()));
  TestEntity persisted =
      jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id"));
  assertThat(persisted.duration).isEqualTo(Duration.standardDays(6));
}
 
Example 3
Source File: AlertTest.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Alerts are considered the same, if they have the same name.
 */
@Test
public void name_equality() {
    Alert alert1 = new Alert(t_past, alert_name, () -> "foo", Optional.of(true), Duration.standardDays(1), "test", EMPTY_MAP);
    Alert alert2 = new Alert(t0, alert_name, () -> "bar", Optional.of(false), Duration.standardDays(2), "test", EMPTY_MAP);

    assertEquals(alert1, alert2);
}
 
Example 4
Source File: AlertTest.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void extend_triggered() {
    Alert past_alert = new Alert(t_past, alert_name, () -> "", Optional.of(true), Duration.standardDays(1), "test", EMPTY_MAP);
    Alert alert = past_alert.extend(new Alert(t0, alert_name, () -> "", Optional.of(true), Duration.standardDays(1), "test", EMPTY_MAP));

    assertEquals(Optional.of(true), alert.isTriggered());
    assertEquals(false, alert.isFiring());
    assertEquals("Return timestamp of first detected trigger", t_past, alert.getStart());
    assertEquals("Return timestamp of last update", t0, alert.getCur());
}
 
Example 5
Source File: PeriodicStaleCheckingCacheStrategyTest.java    From alchemy with MIT License 5 votes vote down vote up
@Test
public void testDurationNotElapsed() {
    doReturn(true).when(cache).checkIfAnyStale();
    strategy = new PeriodicStaleCheckingCacheStrategy(Duration.standardDays(1));
    strategy.onCacheRead(context);
    verifyZeroInteractions(context);
    verifyZeroInteractions(cache);
}
 
Example 6
Source File: WindowEvaluatorFactoryTest.java    From beam with Apache License 2.0 5 votes vote down vote up
@Test
public void singleWindowFnSucceeds() throws Exception {
  Duration windowDuration = Duration.standardDays(7);
  Window<Long> transform = Window.into(FixedWindows.of(windowDuration));
  PCollection<Long> windowed = input.apply(transform);

  CommittedBundle<Long> inputBundle = createInputBundle();

  UncommittedBundle<Long> outputBundle = createOutputBundle(windowed, inputBundle);

  BoundedWindow firstSecondWindow = new IntervalWindow(EPOCH, EPOCH.plus(windowDuration));
  BoundedWindow thirdWindow = new IntervalWindow(EPOCH.minus(windowDuration), EPOCH);

  TransformResult<Long> result = runEvaluator(windowed, inputBundle);

  assertThat(Iterables.getOnlyElement(result.getOutputBundles()), Matchers.equalTo(outputBundle));
  CommittedBundle<Long> committed = outputBundle.commit(Instant.now());

  assertThat(
      committed.getElements(),
      containsInAnyOrder(
          // value in global window
          isSingleWindowedValue(3L, new Instant(2L), firstSecondWindow, NO_FIRING),

          // value in just interval window
          isSingleWindowedValue(2L, new Instant(-10L), thirdWindow, intervalWindowPane),

          // value in global window and two interval windows
          isSingleWindowedValue(
              1L, EPOCH.plus(Duration.standardDays(3)), firstSecondWindow, multiWindowPane),
          isSingleWindowedValue(
              1L, EPOCH.plus(Duration.standardDays(3)), firstSecondWindow, multiWindowPane),
          isSingleWindowedValue(
              1L, EPOCH.plus(Duration.standardDays(3)), firstSecondWindow, multiWindowPane)));
}
 
Example 7
Source File: DeleteOldCommitLogsActionTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
  inject.setStaticField(Ofy.class, "clock", clock);
  action = new DeleteOldCommitLogsAction();
  action.mrRunner = makeDefaultRunner();
  action.response = response;
  action.clock = clock;
  action.maxAge = Duration.standardDays(30);

  ContactResource contact = DatastoreHelper.persistActiveContact("TheRegistrar");
  clock.advanceBy(Duration.standardDays(1));
  DatastoreHelper.persistResourceWithCommitLog(contact);

  prepareData();
}
 
Example 8
Source File: RdeStagingActionTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
  inject.setStaticField(Ofy.class, "clock", clock);
  action = new RdeStagingAction();
  action.clock = clock;
  action.mrRunner = makeDefaultRunner();
  action.lenient = false;
  action.reducerFactory = new RdeStagingReducer.Factory();
  action.reducerFactory.taskQueueUtils = new TaskQueueUtils(new Retrier(new SystemSleeper(), 1));
  action.reducerFactory.lockHandler = new FakeLockHandler(true);
  action.reducerFactory.gcsBufferSize = 0;
  action.reducerFactory.bucket = "rde-bucket";
  action.reducerFactory.lockTimeout = Duration.standardHours(1);
  action.reducerFactory.stagingKeyBytes = PgpHelper.convertPublicKeyToBytes(encryptKey);
  action.pendingDepositChecker = new PendingDepositChecker();
  action.pendingDepositChecker.brdaDayOfWeek = DateTimeConstants.TUESDAY;
  action.pendingDepositChecker.brdaInterval = Duration.standardDays(7);
  action.pendingDepositChecker.clock = clock;
  action.pendingDepositChecker.rdeInterval = Duration.standardDays(1);
  action.response = response;
  action.transactionCooldown = Duration.ZERO;
  action.directory = Optional.empty();
  action.modeStrings = ImmutableSet.of();
  action.tlds = ImmutableSet.of();
  action.watermarks = ImmutableSet.of();
  action.revision = Optional.empty();
}
 
Example 9
Source File: CachedActionInterceptor.java    From wisdom with Apache License 2.0 4 votes vote down vote up
/**
 * Intercepts a @Cached action method.
 * If the result of the action is cached, returned it immediately without having actually invoked the action method.
 * In this case, the interception chain is cut.
 * <p>
 * If the result is not yet cached, the interception chain continues, and the result is cached to be used during
 * the next invocation.
 *
 * @param configuration the interception configuration
 * @param context       the interception context
 * @return the result.
 * @throws Exception something bad happened
 */
@Override
public Result call(Cached configuration, RequestContext context) throws Exception {
    // Can we use the Cached version ?
    boolean nocache =
            HeaderNames.NOCACHE_VALUE.equalsIgnoreCase(context.context().header(HeaderNames.CACHE_CONTROL));

    String key;
    if (Strings.isNullOrEmpty(configuration.key())) {
        key = context.request().uri();
    } else {
        key = configuration.key();
    }

    Result result = null;
    if (!nocache) {
        result = (Result) cache.get(key);
    }

    if (result == null) {
        result = context.proceed();
    } else {
        LOGGER.info("Returning cached result for {} (key:{})",
                context.request().uri(), key);
        return result;
    }

    Duration duration;
    if (configuration.duration() == 0) {
        // Eternity == 1 year.
        duration = Duration.standardDays(365);
    } else {
        duration = Duration.standardSeconds(configuration.duration());
    }


    cache.set(key, result, duration);
    LoggerFactory.getLogger(this.getClass()).info("Caching result of {} for {} seconds (key:{})",
            context.request().uri(), configuration.duration(), key);

    return result;
}
 
Example 10
Source File: RegistryConfig.java    From nomulus with Apache License 2.0 4 votes vote down vote up
/** Returns the global automatic transfer length for contacts. */
public static Duration getContactAutomaticTransferLength() {
  return Duration.standardDays(CONFIG_SETTINGS.get().registryPolicy.contactAutomaticTransferDays);
}
 
Example 11
Source File: RegistryConfig.java    From nomulus with Apache License 2.0 4 votes vote down vote up
/**
 * Amount of time public HTTP proxies are permitted to cache our WHOIS responses.
 *
 * @see google.registry.whois.WhoisHttpAction
 */
@Provides
@Config("whoisHttpExpires")
public static Duration provideWhoisHttpExpires() {
  return Duration.standardDays(1);
}
 
Example 12
Source File: RegistryConfig.java    From nomulus with Apache License 2.0 4 votes vote down vote up
/**
 * Amount of time between BRDA deposits.
 *
 * @see google.registry.rde.PendingDepositChecker
 */
@Provides
@Config("brdaInterval")
public static Duration provideBrdaInterval() {
  return Duration.standardDays(7);
}
 
Example 13
Source File: WindowEvaluatorFactoryTest.java    From beam with Apache License 2.0 4 votes vote down vote up
@Test
public void multipleWindowsWindowFnSucceeds() throws Exception {
  Duration windowDuration = Duration.standardDays(6);
  Duration slidingBy = Duration.standardDays(3);
  Window<Long> transform = Window.into(SlidingWindows.of(windowDuration).every(slidingBy));
  PCollection<Long> windowed = input.apply(transform);

  CommittedBundle<Long> inputBundle = createInputBundle();
  UncommittedBundle<Long> outputBundle = createOutputBundle(windowed, inputBundle);

  TransformResult<Long> result = runEvaluator(windowed, inputBundle);

  assertThat(Iterables.getOnlyElement(result.getOutputBundles()), Matchers.equalTo(outputBundle));
  CommittedBundle<Long> committed = outputBundle.commit(Instant.now());

  BoundedWindow w1 = new IntervalWindow(EPOCH, EPOCH.plus(windowDuration));
  BoundedWindow w2 =
      new IntervalWindow(EPOCH.plus(slidingBy), EPOCH.plus(slidingBy).plus(windowDuration));
  BoundedWindow wMinus1 = new IntervalWindow(EPOCH.minus(windowDuration), EPOCH);
  BoundedWindow wMinusSlide =
      new IntervalWindow(EPOCH.minus(windowDuration).plus(slidingBy), EPOCH.plus(slidingBy));

  assertThat(
      committed.getElements(),
      containsInAnyOrder(
          // Value in global window mapped to one windowed value in multiple windows
          isWindowedValue(
              valueInGlobalWindow.getValue(),
              valueInGlobalWindow.getTimestamp(),
              ImmutableSet.of(w1, wMinusSlide),
              NO_FIRING),

          // Value in interval window mapped to one windowed value in multiple windows
          isWindowedValue(
              valueInIntervalWindow.getValue(),
              valueInIntervalWindow.getTimestamp(),
              ImmutableSet.of(wMinus1, wMinusSlide),
              valueInIntervalWindow.getPane()),

          // Value in three windows mapped to three windowed values in the same multiple windows
          isWindowedValue(
              valueInGlobalAndTwoIntervalWindows.getValue(),
              valueInGlobalAndTwoIntervalWindows.getTimestamp(),
              ImmutableSet.of(w1, w2),
              valueInGlobalAndTwoIntervalWindows.getPane()),
          isWindowedValue(
              valueInGlobalAndTwoIntervalWindows.getValue(),
              valueInGlobalAndTwoIntervalWindows.getTimestamp(),
              ImmutableSet.of(w1, w2),
              valueInGlobalAndTwoIntervalWindows.getPane()),
          isWindowedValue(
              valueInGlobalAndTwoIntervalWindows.getValue(),
              valueInGlobalAndTwoIntervalWindows.getTimestamp(),
              ImmutableSet.of(w1, w2),
              valueInGlobalAndTwoIntervalWindows.getPane())));
}
 
Example 14
Source File: ReduceFnRunnerTest.java    From beam with Apache License 2.0 4 votes vote down vote up
/**
 * If the trigger does not care about the watermark, the ReduceFnRunner should still emit an
 * element for the ON_TIME pane.
 */
@Test
public void testNoWatermarkTriggerNoHold() throws Exception {
  Duration allowedLateness = Duration.standardDays(1);
  ReduceFnTester<Integer, Iterable<Integer>, IntervalWindow> tester =
      ReduceFnTester.nonCombining(
          WindowingStrategy.of(FixedWindows.of(Duration.millis(10)))
              .withTrigger(
                  Repeatedly.forever(
                      AfterProcessingTime.pastFirstElementInPane()
                          .plusDelayOf(Duration.standardSeconds(5))))
              .withAllowedLateness(allowedLateness));

  // First, an element comes in on time in [0, 10) but ReduceFnRunner should
  // not set a hold or timer for 9. That is the trigger's job.
  IntervalWindow expectedWindow = new IntervalWindow(new Instant(0), new Instant(10));
  tester.advanceInputWatermark(new Instant(0));
  tester.advanceProcessingTime(new Instant(0));

  tester.injectElements(TimestampedValue.of(1, new Instant(1)));

  // Since some data arrived, the element hold will be the end of the window.
  assertThat(tester.getWatermarkHold(), equalTo(expectedWindow.maxTimestamp()));

  tester.advanceProcessingTime(new Instant(6000));

  // Sanity check; we aren't trying to verify output in this test
  assertThat(tester.getOutputSize(), equalTo(1));

  // Since we did not request empty final panes, no hold
  assertThat(tester.getWatermarkHold(), nullValue());

  // So when the input watermark advanced, the output advances with it (automated by tester)
  tester.advanceInputWatermark(
      new Instant(expectedWindow.maxTimestamp().plus(Duration.standardHours(1))));

  // Now late data arrives
  tester.injectElements(TimestampedValue.of(3, new Instant(3)));

  // The ReduceFnRunner should set a GC hold since the element was too late and its timestamp
  // will be ignored for the purposes of the watermark hold
  assertThat(
      tester.getWatermarkHold(), equalTo(expectedWindow.maxTimestamp().plus(allowedLateness)));
}
 
Example 15
Source File: ReduceFnRunnerTest.java    From beam with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that the garbage collection time for a fixed window does not overflow the end of time.
 */
@Test
public void testFixedWindowEndOfTimeGarbageCollection() throws Exception {
  Duration allowedLateness = Duration.standardDays(365);
  Duration windowSize = Duration.millis(10);
  WindowFn<Object, IntervalWindow> windowFn = FixedWindows.of(windowSize);

  // This timestamp falls into a window where the end of the window is before the end of the
  // global window - the "end of time" - yet its expiration time is after.
  final Instant elementTimestamp =
      GlobalWindow.INSTANCE.maxTimestamp().minus(allowedLateness).plus(1);

  IntervalWindow window =
      Iterables.getOnlyElement(
          windowFn.assignWindows(
              windowFn.new AssignContext() {
                @Override
                public Object element() {
                  throw new UnsupportedOperationException();
                }

                @Override
                public Instant timestamp() {
                  return elementTimestamp;
                }

                @Override
                public BoundedWindow window() {
                  throw new UnsupportedOperationException();
                }
              }));

  assertTrue(window.maxTimestamp().isBefore(GlobalWindow.INSTANCE.maxTimestamp()));
  assertTrue(
      window.maxTimestamp().plus(allowedLateness).isAfter(GlobalWindow.INSTANCE.maxTimestamp()));

  // Test basic execution of a trigger using a non-combining window set and accumulating mode.

  WindowingStrategy<?, IntervalWindow> strategy =
      WindowingStrategy.of((WindowFn<?, IntervalWindow>) windowFn)
          .withTimestampCombiner(TimestampCombiner.EARLIEST)
          .withTrigger(AfterWatermark.pastEndOfWindow().withLateFirings(Never.ever()))
          .withMode(AccumulationMode.DISCARDING_FIRED_PANES)
          .withAllowedLateness(allowedLateness);

  ReduceFnTester<Integer, Integer, IntervalWindow> tester =
      ReduceFnTester.combining(strategy, Sum.ofIntegers(), VarIntCoder.of());

  tester.injectElements(TimestampedValue.of(13, elementTimestamp));

  // Should fire ON_TIME pane and there will be a checkState that the cleanup time
  // is prior to timestamp max value
  tester.advanceInputWatermark(window.maxTimestamp());

  // Nothing in the ON_TIME pane (not governed by triggers, but by ReduceFnRunner)
  assertThat(tester.extractOutput(), emptyIterable());

  tester.injectElements(TimestampedValue.of(42, elementTimestamp));

  // Now the final pane should fire, demonstrating that the GC time was truncated
  tester.advanceInputWatermark(GlobalWindow.INSTANCE.maxTimestamp());
  assertThat(tester.extractOutput(), contains(isWindowedValue(equalTo(55))));
}
 
Example 16
Source File: AlertTest.java    From monsoon with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void predicate_string() {
    Alert alert = new Alert(t0, alert_name, () -> "bar", Optional.of(false), Duration.standardDays(2), "test", EMPTY_MAP);

    assertEquals("bar", alert.getRule());
}
 
Example 17
Source File: RegistryConfig.java    From nomulus with Apache License 2.0 2 votes vote down vote up
/**
 * The global automatic transfer length for contacts. After this amount of time has elapsed, the
 * transfer is automatically approved.
 *
 * @see google.registry.flows.contact.ContactTransferRequestFlow
 */
@Provides
@Config("contactAutomaticTransferLength")
public static Duration provideContactAutomaticTransferLength(RegistryConfigSettings config) {
  return Duration.standardDays(config.registryPolicy.contactAutomaticTransferDays);
}
 
Example 18
Source File: RegistryConfig.java    From nomulus with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the length of time before commit logs should be deleted from Datastore.
 *
 * <p>The only reason you'll want to retain this commit logs in Datastore is for performing
 * point-in-time restoration queries for subsystems like RDE.
 *
 * @see google.registry.backup.DeleteOldCommitLogsAction
 * @see google.registry.model.translators.CommitLogRevisionsTranslatorFactory
 */
public static Duration getCommitLogDatastoreRetention() {
  return Duration.standardDays(30);
}
 
Example 19
Source File: RegistryConfig.java    From nomulus with Apache License 2.0 2 votes vote down vote up
/**
 * Amount of time between RDE deposits.
 *
 * @see google.registry.rde.PendingDepositChecker
 * @see google.registry.rde.RdeReportAction
 * @see google.registry.rde.RdeUploadAction
 */
@Provides
@Config("rdeInterval")
public static Duration provideRdeInterval() {
  return Duration.standardDays(1);
}