Java 类org.joda.time.DateTimeUtils 实例源码

项目:verify-hub    文件:AuthnResponseFromCountryServiceTest.java   
@Before
public void setup() {
    DateTimeUtils.setCurrentMillisFixed(TIMESTAMP.getMillis());
    service = new AuthnResponseFromCountryService(
        samlEngineProxy,
        samlSoapProxyProxy,
        matchingServiceConfigProxy,
        policyConfiguration,
        sessionRepository,
        samlAuthnResponseTranslatorDtoFactory,
        countriesService,
        assertionRestrictionFactory);
    when(sessionRepository.getStateController(SESSION_ID, CountrySelectedState.class)).thenReturn(stateController);
    when(stateController.getAssertionConsumerServiceUri()).thenReturn(ASSERTION_CONSUMER_SERVICE_URI);
    when(stateController.getRequestIssuerEntityId()).thenReturn(TEST_RP);
    when(stateController.getMatchingServiceEntityId()).thenReturn(TEST_RP_MS);
    when(stateController.getRequestId()).thenReturn(REQUEST_ID);
    when(samlAuthnResponseTranslatorDtoFactory.fromSamlAuthnResponseContainerDto(SAML_AUTHN_RESPONSE_CONTAINER_DTO, TEST_RP_MS)).thenReturn(SAML_AUTHN_RESPONSE_TRANSLATOR_DTO);
    when(samlEngineProxy.translateAuthnResponseFromCountry(SAML_AUTHN_RESPONSE_TRANSLATOR_DTO)).thenReturn(INBOUND_RESPONSE_FROM_COUNTRY);
    when(samlEngineProxy.generateEidasAttributeQuery(EIDAS_ATTRIBUTE_QUERY_REQUEST_DTO)).thenReturn(ATTRIBUTE_QUERY_CONTAINER_DTO);
    when(matchingServiceConfigProxy.getMatchingService(TEST_RP_MS)).thenReturn(MATCHING_SERVICE_CONFIG_ENTITY_DATA_DTO);
    when(policyConfiguration.getMatchingServiceResponseWaitPeriod()).thenReturn(MATCHING_SERVICE_RESPONSE_WAIT_PERIOD);
    when(assertionRestrictionFactory.getAssertionExpiry()).thenReturn(TIMESTAMP.plus(ASSERTION_EXPIRY));
}
项目:oma-riista-web    文件:HarvestReportReminderTest.java   
@Test
public void testHarvestReminderNeverSentBeforeButNowTooEarly() {
    try {
        createHarvest(HarvestReportRequired.REQUIRED, AuthorIsRegistered.REGISTERED);

        persistInNewTransaction();

        runInTransaction(() -> {
            DateTime fakeNow = getTestStartTime().plus(HarvestReportReminderFeature.FIRST_REMINDER_DELAY).minusSeconds(1);
            DateTimeUtils.setCurrentMillisFixed(fakeNow.getMillis());

            Map<Long, Set<String>> res = harvestReportReminder.sendReminders();

            assertEquals(0, res.size());
        });

    } finally {
        DateTimeUtils.setCurrentMillisSystem();
    }
}
项目:oma-riista-web    文件:HarvestReportReminderTest.java   
@Test
public void testHarvestReminderNeverSentBeforeNowOldEnough() {
    try {
        final Harvest harvest = createHarvest(HarvestReportRequired.REQUIRED, AuthorIsRegistered.REGISTERED);

        persistInNewTransaction();

        final DateTime fakeNow = getTestStartTime().plus(HarvestReportReminderFeature.FIRST_REMINDER_DELAY).plusSeconds(1);
        DateTimeUtils.setCurrentMillisFixed(fakeNow.getMillis());

        runInTransaction(() -> {
            final Map<Long, Set<String>> res = harvestReportReminder.sendReminders();

            assertEquals(1, res.size());
            assertThat(res, hasKey(harvest.getId()));
        });

        runInTransaction(() -> {
            final DateTime reminderSentTime = harvestRepository.getOne(harvest.getId()).getEmailReminderSentTime();
            assertEquals(fakeNow, reminderSentTime);
        });

    } finally {
        DateTimeUtils.setCurrentMillisSystem();
    }
}
项目:oma-riista-web    文件:HarvestReportReminderTest.java   
@Test
public void testHarvestReminderIsSentButNowTooEarly() {
    try {
        final Harvest harvest = createHarvest(HarvestReportRequired.REQUIRED, AuthorIsRegistered.REGISTERED);
        harvest.setEmailReminderSentTime(getTestStartTime());

        persistInNewTransaction();

        final DateTime fakeNow = getTestStartTime().plus(HarvestReportReminderFeature.REMINDER_INTERVAL).minusSeconds(1);
        DateTimeUtils.setCurrentMillisFixed(fakeNow.getMillis());

        runInTransaction(() -> {
            final Map<Long, Set<String>> res = harvestReportReminder.sendReminders();
            assertEquals(0, res.size());
        });

    } finally {
        DateTimeUtils.setCurrentMillisSystem();
    }
}
项目:oma-riista-web    文件:HarvestReportReminderTest.java   
@Test
public void testUpdateOnlyThoseWhichEmailIsSent() {
    try {
        final Harvest harvest = createHarvest(HarvestReportRequired.REQUIRED, AuthorIsRegistered.REGISTERED);
        final Harvest harvest2 = createHarvest(HarvestReportRequired.REQUIRED, AuthorIsRegistered.NOT_REGISTERED);

        persistInNewTransaction();

        final DateTime fakeNow = getTestStartTime().plus(HarvestReportReminderFeature.FIRST_REMINDER_DELAY).plusSeconds(1);
        DateTimeUtils.setCurrentMillisFixed(fakeNow.getMillis());

        runInTransaction(() -> {
            final Map<Long, Set<String>> res = harvestReportReminder.sendReminders();

            assertEquals(1, res.size());
            assertThat(res, hasKey(harvest.getId()));
        });

        runInTransaction(() -> assertNull(harvestRepository.getOne(harvest2.getId()).getEmailReminderSentTime()));

    } finally {
        DateTimeUtils.setCurrentMillisSystem();
    }
}
项目:graylog-plugin-backup-configuration    文件:BackConfigurationPeriodicalTest.java   
@Test
public void canStartBackup()
{
    final DateTime initialTime = new DateTime(2016, 9, 26, 23, 0, 35, 0, DateTimeZone.UTC);

    final InstantMillisProvider clock = new InstantMillisProvider(initialTime);
    DateTimeUtils.setCurrentMillisProvider(clock);

    BackupConfiguration testinfo = BackupConfiguration.builder( ).enabled(false).scheduledPeriod(Period.days(1))
        .mongoDumpPath(StringUtils.EMPTY)
        .restorePath(StringUtils.EMPTY)
        .backupPath(StringUtils.EMPTY)
        .lastbackupTime(Tools.nowUTC( )).build( );

    BackupConfigurationPeriodical configuration = new BackupConfigurationPeriodical(null, null);
    assertThat(configuration.canStartBackup(testinfo)).isFalse( );

    DateTime lastBackup = new DateTime(2016, 9, 26, 22, 56, 0, 0);
    testinfo = BackupConfiguration.builder( ).enabled(true).scheduledPeriod(Period.minutes(1)).mongoDumpPath("").restorePath("").backupPath("").lastbackupTime(lastBackup).build( );
    assertThat(configuration.canStartBackup(testinfo)).isTrue( );

    lastBackup = new DateTime(2016, 9, 26, 23, 2, 0, 0, DateTimeZone.UTC);
    testinfo = BackupConfiguration.builder( ).enabled(true).scheduledPeriod(Period.minutes(1)).mongoDumpPath("").restorePath("").backupPath("").lastbackupTime(lastBackup).build( );
    assertThat(configuration.canStartBackup(testinfo)).isFalse( );

}
项目:android-oss    文件:KSRobolectricTestCase.java   
@Override
@Before
public void setUp() throws Exception {
  super.setUp();

  final MockTrackingClient testTrackingClient = new MockTrackingClient();
  this.koalaTest = new TestSubscriber<>();
  testTrackingClient.eventNames.subscribe(this.koalaTest);
  DateTimeUtils.setCurrentMillisFixed(new DateTime().getMillis());

  this.environment = application().component().environment().toBuilder()
    .apiClient(new MockApiClient())
    .currentConfig(new MockCurrentConfig())
    .webClient(new MockWebClient())
    .koala(new Koala(testTrackingClient))
    .build();
}
项目:beam    文件:PipelineOptions.java   
@Override
public String create(PipelineOptions options) {
  String appName = options.as(ApplicationNameOptions.class).getAppName();
  String normalizedAppName = appName == null || appName.length() == 0 ? "BeamApp"
      : appName.toLowerCase()
               .replaceAll("[^a-z0-9]", "0")
               .replaceAll("^[^a-z]", "a");
  String userName = MoreObjects.firstNonNull(System.getProperty("user.name"), "");
  String normalizedUserName = userName.toLowerCase()
                                      .replaceAll("[^a-z0-9]", "0");
  String datePart = FORMATTER.print(DateTimeUtils.currentTimeMillis());

  String randomPart = Integer.toHexString(ThreadLocalRandom.current().nextInt());
  return String.format("%s-%s-%s-%s",
      normalizedAppName, normalizedUserName, datePart, randomPart);
}
项目:Wiab.pro    文件:RemoteDisco.java   
/**
 * Construct a new RemoteDisco - purely for testing - with an already
 * determined result. Either jid or error must be passed.
 *
 * @param remoteDomain the name of the remote domain (not JID)
 * @param jid          the domain's remote JID
 * @param error        the error from disco
 */
@VisibleForTesting
RemoteDisco(String remoteDomain, String jid, FederationError error) {
  Preconditions.checkArgument((jid != null)^(error != null));

  manager = null;
  status = new AtomicReference<Status>(Status.COMPLETE);
  pending = null;
  this.remoteDomain = remoteDomain;
  this.remoteJid = jid;
  this.error = error;
  // defaults for testing
  this.creationTimeMillis = DateTimeUtils.currentTimeMillis();
  this.failExpirySecs = 2 * 60;
  this.successExpirySecs = 2 * 60 * 60;
}
项目:Wiab.pro    文件:RemoteDisco.java   
/**
 * Returns true if this RemoteDisco's time to live is exceeded.
 *
 * We can't use MapMaker's expiration code as it won't let us have different expiry for
 * successful and failed cases.
 *
 * @return whether this object should be deleted and recreated
 */
public boolean ttlExceeded() {
  if (status.get() == Status.COMPLETE) {
    if (remoteJid == null) {
      // Failed disco case
      if (DateTimeUtils.currentTimeMillis() >
          (creationTimeMillis + (1000 * failExpirySecs))) {
        return true;
      }
    } else {
      // Successful disco case
      if (DateTimeUtils.currentTimeMillis() >
          (creationTimeMillis + (1000 * successExpirySecs))) {
        return true;
      }
    }
  }
  return false;
}
项目:substitution-schedule-parser    文件:ParserUtilsTest.java   
@Test
public void testNewYear() {
    DateTimeUtils.setCurrentMillisFixed(1450911600000L); // 24.12.2015
    ParserUtils.init();
    assertEquals(2016, ParserUtils.parseDate("1.1. Freitag").getYear());
    assertEquals(2015, ParserUtils.parseDate("31.12. Donnerstag").getYear());
    assertEquals(2016, ParserUtils.parseDateTime("1.1. Freitag 12:00").getYear());
    assertEquals(2015, ParserUtils.parseDateTime("31.12. Donnerstag 12:00").getYear());

    DateTimeUtils.setCurrentMillisFixed(1452034800000L); // 06.01.2016
    ParserUtils.init();
    assertEquals(2016, ParserUtils.parseDate("1.1. Freitag").getYear());
    assertEquals(2015, ParserUtils.parseDate("31.12. Donnerstag").getYear());
    assertEquals(2016, ParserUtils.parseDateTime("1.1. Freitag 12:00").getYear());
    assertEquals(2015, ParserUtils.parseDateTime("31.12. Donnerstag 12:00").getYear());
}
项目:cassandra-reaper    文件:RepairRunResourceTest.java   
@Test
public void testTriggerAlreadyRunningRun() throws InterruptedException, ReaperException {
  DateTimeUtils.setCurrentMillisFixed(TIME_CREATE);

  context.repairManager
      .initializeThreadPool(THREAD_CNT, REPAIR_TIMEOUT_S, TimeUnit.SECONDS, RETRY_DELAY_S, TimeUnit.SECONDS);

  RepairRunResource resource = new RepairRunResource(context);
  Response response = addDefaultRepairRun(resource);
  assertTrue(response.getEntity().toString(), response.getEntity() instanceof RepairRunStatus);
  RepairRunStatus repairRunStatus = (RepairRunStatus) response.getEntity();
  UUID runId = repairRunStatus.getId();

  DateTimeUtils.setCurrentMillisFixed(TIME_START);
  Optional<String> newState = Optional.of(RepairRun.RunState.RUNNING.toString());
  resource.modifyRunState(uriInfo, runId, newState);
  Thread.sleep(1000);
  response = resource.modifyRunState(uriInfo, runId, newState);
  assertEquals(Response.Status.NOT_MODIFIED.getStatusCode(), response.getStatus());
}
项目:cassandra-reaper    文件:RepairRunResourceTest.java   
@Test
public void testPauseNotRunningRun() throws InterruptedException, ReaperException {
  DateTimeUtils.setCurrentMillisFixed(TIME_CREATE);
  context.repairManager.initializeThreadPool(THREAD_CNT, REPAIR_TIMEOUT_S, TimeUnit.SECONDS,
      RETRY_DELAY_S, TimeUnit.SECONDS);
  RepairRunResource resource = new RepairRunResource(context);
  Response response = addDefaultRepairRun(resource);
  assertTrue(response.getEntity().toString(), response.getEntity() instanceof RepairRunStatus);
  RepairRunStatus repairRunStatus = (RepairRunStatus) response.getEntity();
  UUID runId = repairRunStatus.getId();

  response = resource.modifyRunState(uriInfo, runId,
      Optional.of(RepairRun.RunState.PAUSED.toString()));
  Thread.sleep(200);

  assertEquals(405, response.getStatus());
  RepairRun repairRun = context.storage.getRepairRun(runId).get();
  // the run should be paused
  assertEquals(RepairRun.RunState.NOT_STARTED, repairRun.getRunState());
  // but the running segment should be untouched
  assertEquals(0,
      context.storage.getSegmentAmountForRepairRunWithState(runId,
          RepairSegment.State.RUNNING));
}
项目:cassandra-reaper    文件:RepairRunResourceTest.java   
@Test
public void testModifyIntensity() throws ReaperException {
  DateTimeUtils.setCurrentMillisFixed(TIME_CREATE);

  context.repairManager
      .initializeThreadPool(THREAD_CNT, REPAIR_TIMEOUT_S, TimeUnit.SECONDS, RETRY_DELAY_S, TimeUnit.SECONDS);

  RepairRunResource resource = new RepairRunResource(context);
  Response response = addDefaultRepairRun(resource);
  assertTrue(response.getEntity().toString(), response.getEntity() instanceof RepairRunStatus);
  RepairRunStatus repairRunStatus = (RepairRunStatus) response.getEntity();
  UUID runId = repairRunStatus.getId();

  response = resource.modifyRunState(uriInfo, runId, Optional.of(RepairRun.RunState.RUNNING.toString()));
  assertEquals(200, response.getStatus());
  response = resource.modifyRunState(uriInfo, runId, Optional.of(RepairRun.RunState.PAUSED.toString()));
  assertEquals(200, response.getStatus());
  response = resource.modifyRunIntensity(uriInfo, runId, Optional.of("0.1"));
  assertTrue(response.getEntity() instanceof RepairRunStatus);
  repairRunStatus = (RepairRunStatus) response.getEntity();
  assertEquals(0.1, repairRunStatus.getIntensity(), 0.09);
}
项目:TinyTravelTracker    文件:BaseSingleFieldPeriod.java   
/**
 * Calculates the number of whole units between the two specified partial datetimes.
 * <p>
 * The two partials must contain the same fields, for example you can specify
 * two <code>LocalDate</code> objects.
 *
 * @param start  the start partial date, validated to not be null
 * @param end  the end partial date, validated to not be null
 * @param zeroInstance  the zero instance constant, must not be null
 * @return the period
 * @throws IllegalArgumentException if the partials are null or invalid
 */
protected static int between(ReadablePartial start, ReadablePartial end, ReadablePeriod zeroInstance) {
    if (start == null || end == null) {
        throw new IllegalArgumentException("ReadablePartial objects must not be null");
    }
    if (start.size() != end.size()) {
        throw new IllegalArgumentException("ReadablePartial objects must have the same set of fields");
    }
    for (int i = 0, isize = start.size(); i < isize; i++) {
        if (start.getFieldType(i) != end.getFieldType(i)) {
            throw new IllegalArgumentException("ReadablePartial objects must have the same set of fields");
        }
    }
    if (DateTimeUtils.isContiguous(start) == false) {
        throw new IllegalArgumentException("ReadablePartial objects must be contiguous");
    }
    Chronology chrono = DateTimeUtils.getChronology(start.getChronology()).withUTC();
    int[] values = chrono.get(zeroInstance, chrono.set(start, 0L), chrono.set(end, 0L));
    return values[0];
}
项目:oap    文件:ChannelConnection.java   
@Override
public void write( byte[] buffer, int off, int length ) {
    try {
        ByteBuffer b = ByteBuffer.wrap( buffer, off, length );
        long start = DateTimeUtils.currentTimeMillis();
        while( b.hasRemaining() ) {
            if( channel.write( b ) == 0 ) {
                if( DateTimeUtils.currentTimeMillis() - start > timeout )
                    throw new SocketTimeoutException( "unable to write for " + timeout + "ms" );
                Threads.sleepSafely( 10 );
            } else start = DateTimeUtils.currentTimeMillis();
        }
    } catch( IOException e ) {
        throw new UncheckedIOException( e );
    }
}
项目:TinyTravelTracker    文件:GJChronology.java   
public int[] add(ReadablePartial partial, int fieldIndex, int[] values, int valueToAdd) {
    // overridden as superclass algorithm can't handle
    // 2004-02-29 + 48 months -> 2008-02-29 type dates
    if (valueToAdd == 0) {
        return values;
    }
    if (DateTimeUtils.isContiguous(partial)) {
        long instant = 0L;
        for (int i = 0, isize = partial.size(); i < isize; i++) {
            instant = partial.getFieldType(i).getField(GJChronology.this).set(instant, values[i]);
        }
        instant = add(instant, valueToAdd);
        return GJChronology.this.get(partial, instant);
    } else {
        return super.add(partial, fieldIndex, values, valueToAdd);
    }
}
项目:TinyTravelTracker    文件:BasicMonthOfYearDateTimeField.java   
public int[] add(ReadablePartial partial, int fieldIndex, int[] values, int valueToAdd) {
    // overridden as superclass algorithm can't handle
    // 2004-02-29 + 48 months -> 2008-02-29 type dates
    if (valueToAdd == 0) {
        return values;
    }
    if (DateTimeUtils.isContiguous(partial)) {
        long instant = 0L;
        for (int i = 0, isize = partial.size(); i < isize; i++) {
            instant = partial.getFieldType(i).getField(iChronology).set(instant, values[i]);
        }
        instant = add(instant, valueToAdd);
        return iChronology.get(partial, instant);
    } else {
        return super.add(partial, fieldIndex, values, valueToAdd);
    }
}
项目:aws-codepipeline-plugin-for-jenkins    文件:AWSCodePipelineJobCredentialsProviderTest.java   
@Test
public void refreshesCredentialsAfterFourteenMinutes() {
    // given
    final com.amazonaws.auth.AWSSessionCredentials firstCredentials = credentialsProvider.getCredentials();
    DateTimeUtils.setCurrentMillisFixed(Duration.standardMinutes(14).getMillis());
    final com.amazonaws.auth.AWSSessionCredentials secondCredentials = credentialsProvider.getCredentials();
    DateTimeUtils.setCurrentMillisFixed(Duration.standardMinutes(14).getMillis() + 1);

    // when
    final com.amazonaws.auth.AWSSessionCredentials thirdCredentials = credentialsProvider.getCredentials();

    // then
    verify(codePipelineClient, times(2)).getJobDetails(getJobDetailsRequestCaptor.capture());

    assertSame(firstCredentials, secondCredentials);
    assertNotSame(firstCredentials, thirdCredentials);
}
项目:welshare    文件:FacebookService.java   
@Override
@SqlTransactional
public void markNotificationsAsRead(User user) {
    if (!isServiceEnabled(user)) {
        return;
    }
    user = dao.getById(User.class, user.getId(), true);
    user.getFacebookSettings().setLastReadNotificationTimestamp(
            DateTimeUtils.currentTimeMillis());
    dao.persist(user);

    LegacyFacebookClient client = helper.getLegacyClient(user.getFacebookSettings().getToken());
    try {
        List<NotificationEvent> events = getUnreadNotifications(user);
        if (events.isEmpty()) {
            return;
        }
        List<String> ids = Lists.newArrayListWithCapacity(events.size());
        for (NotificationEvent event : events) {
            ids.add(((ExternalNotificationEvent) event).getExternalNotificationId());
        }
        client.execute("notifications.markRead", Parameter.with("notification_ids", ids));
    } catch (FacebookException ex) {
        handleException("Error marking messages as read", ex, user);
    }
}
项目:welshare    文件:UserServiceImpl.java   
private Login createLoginAndUpdateUserData(User user, String series, boolean remember, String ip) {
    Login login = new Login();
    login.setUser(user);
    login.setIp(ip);

    if (remember) {
        login.setToken(UUID.randomUUID().toString());
        login.setSeries(series != null ? series : UUID.randomUUID().toString());
        login.setLastLoginTime(new DateTime());

        save(login);
    }

    if (user.getProfile().isWarnOnMinutesPerDayLimit() && ActivitySessionService.shouldResetOnlineSecondsToday(user)) {
        user.setOnlineSecondsToday(0);
    }

    user.setLastLogin(DateTimeUtils.currentTimeMillis());
    save(user);

    return login;
}
项目:welshare    文件:UserServiceImpl.java   
@Override
@SqlTransactional
public boolean registerWaitingUser(String email) {

    if (getDao().getByEmail(email) != null
            || getDao().getByPropertyValue(WaitingUser.class, "email", email) != null) {
        return false;
    }

    WaitingUser user = new WaitingUser();
    user.setInvitationCode(UUID.randomUUID().toString());
    user.setEmail(email);
    user.setRegistered(false);
    user.setRegistrationTimestamp(DateTimeUtils.currentTimeMillis());

    getDao().persist(user);

    return true;
}
项目:verify-hub    文件:EidasAwaitingCycle3DataStateControllerTest.java   
@Before
public void setUp() throws Exception {
    DateTimeUtils.setCurrentMillisFixed(NOW.getMillis());
    ResponseFromHubFactory responseFromHubFactory = new ResponseFromHubFactory(idGenerator);
    state = anEidasAwaitingCycle3DataState().build();
    controller = new EidasAwaitingCycle3DataStateController(
        state,
        eventSinkHubEventLogger,
        stateTransitionAction,
        transactionsConfigProxy,
        responseFromHubFactory,
        policyConfiguration,
        assertionRestrictionsFactory,
        matchingServiceConfigProxy);
}
项目:NoraUi    文件:CucumberHooksUT.java   
@Before
public void setUp() throws InterruptedException {
    DateTime now = DateTime.now();
    // prepare mock
    mockDataInputProvider = Mockito.mock(ExcelDataProvider.class);
    PowerMockito.mockStatic(Context.class);
    when(Context.getDataInputProvider()).thenReturn(mockDataInputProvider);
    when(Context.getStartCurrentScenario()).thenReturn(now);
    DateTimeUtils.setCurrentMillisFixed(now.plusSeconds(5).getMillis());
}
项目:flume-release-1.7.0    文件:TimestampedEvent.java   
TimestampedEvent(Event base) {
  setBody(base.getBody());
  Map<String, String> headers = Maps.newHashMap(base.getHeaders());
  String timestampString = headers.get("timestamp");
  if (StringUtils.isBlank(timestampString)) {
    timestampString = headers.get("@timestamp");
  }
  if (StringUtils.isBlank(timestampString)) {
    this.timestamp = DateTimeUtils.currentTimeMillis();
    headers.put("timestamp", String.valueOf(timestamp ));
  } else {
    this.timestamp = Long.valueOf(timestampString);
  }
  setHeaders(headers);
}
项目:QDrill    文件:NullableFixedByteAlignedReaders.java   
@Override
void addNext(int start, int index) {
  int intValue;
  if (usingDictionary) {
    intValue =  pageReader.dictionaryValueReader.readInteger();
  } else {
    intValue = readIntLittleEndian(bytebuf, start);
  }

  dateVector.getMutator().set(index, DateTimeUtils.fromJulianDay(intValue - ParquetOutputRecordWriter.JULIAN_DAY_EPOC - 0.5));
}
项目:QDrill    文件:FixedByteAlignedReader.java   
@Override
void addNext(int start, int index) {
  int intValue;
  if (usingDictionary) {
    intValue =  pageReader.dictionaryValueReader.readInteger();
  } else {
    intValue = readIntLittleEndian(bytebuf, start);
  }

  mutator.set(index, DateTimeUtils.fromJulianDay(intValue - ParquetOutputRecordWriter.JULIAN_DAY_EPOC - 0.5));
}
项目:Elasticsearch    文件:CurrentTimestampFunction.java   
@Override
public Long evaluate(Input<Integer>... args) {
    long millis = DateTimeUtils.currentTimeMillis();
    if (args.length == 1) {
        Integer precision = args[0].value();
        if (precision == null) {
            throw new IllegalArgumentException(String.format(Locale.ENGLISH,
                    "NULL precision not supported for %s", NAME));
        }
        int factor;
        switch (precision) {
            case 0:
                factor = 1000;
                break;
            case 1:
                factor = 100;
                break;
            case 2:
                factor = 10;
                break;
            case 3:
                factor = 1;
                break;
            default:
                throw new IllegalArgumentException("Precision must be between 0 and 3");
        }
        millis = LongMath.divide(millis, factor, RoundingMode.DOWN) * factor;
    }
    return millis;
}
项目:angular-spring-starter    文件:TokenHelperTest.java   
@Before
public void init() {
    tokenHelper = new TokenHelper();
    DateTimeUtils.setCurrentMillisFixed(20L);
    ReflectionTestUtils.setField(tokenHelper, "EXPIRES_IN", 1);
    ReflectionTestUtils.setField(tokenHelper, "SECRET", "mySecret");
}
项目:verify-matching-service-adapter    文件:MatchingServiceAdapterMetadataRepositoryTest.java   
@Test
public void shouldGenerateMetadataValidFor1Hour() throws Exception {
    DateTimeUtils.setCurrentMillisFixed(DateTime.now().getMillis());
    when(certificateStore.getSigningCertificates()).thenReturn(asList(getCertificate()));

    Document matchingServiceAdapterMetadata = matchingServiceAdapterMetadataRepository.getMatchingServiceAdapterMetadata();
    EntitiesDescriptor entitiesDescriptor = getEntitiesDescriptor(matchingServiceAdapterMetadata);

    assertThat(entitiesDescriptor.getValidUntil()).isEqualTo(DateTime.now(DateTimeZone.UTC).plusHours(1));
}
项目:verify-matching-service-adapter    文件:ConditionsValidatorTest.java   
@Before
public void setUp() throws Exception {
    DateTimeUtils.setCurrentMillisFixed(NOW.getMillis());
    validator = new ConditionsValidator<>(conditions -> conditions, AUDIENCE_URI);

    audienceRestriction= new AudienceRestrictionBuilder().buildObject();
    Audience audience = new AudienceBuilder().buildObject();
    audience.setAudienceURI(AUDIENCE_URI);
    audienceRestriction.getAudiences().add(audience);
}
项目:oma-riista-web    文件:LupahallintaHarvestPermitImporterTest.java   
@Test
public void testNoLhSyncTimeIs24HoursBefore() {
    try {
        createIntegration(null);
        final SystemUser admin = createNewAdmin();
        persistInNewTransaction();

        DateTime fakeNow = new DateTime(2014, 6, 25, 12, 34, 0);
        DateTimeUtils.setCurrentMillisFixed(fakeNow.getMillis());

        authenticate(admin);

        LupahallintaHttpClient mockClient = createMockClient(header());
        LupahallintaImportMailHandler mockMailHandler = createMockMailHandler();
        LupahallintaHarvestPermitImporter importer = new LupahallintaHarvestPermitImporter(
                importFeature, mockClient, mockMailHandler);

        HarvestPermitImportResultDTO result = importer.doImport();

        assertNotNull(result);
        assertNoChanges(result);

        ArgumentCaptor<DateTime> argument = ArgumentCaptor.forClass(DateTime.class);
        verify(mockClient).getPermits(argument.capture());
        assertEquals(fakeNow.minusDays(1), argument.getValue());
        assertEquals(fakeNow, importFeature.getLastLhSyncTime());
    } finally {
        DateTimeUtils.setCurrentMillisSystem();
    }
}
项目:oma-riista-web    文件:LupahallintaHarvestPermitImporterTest.java   
@Test
public void testLhSyncTimeIsUpdated() {
    try {
        createIntegration(null);
        final SystemUser admin = createNewAdmin();
        persistInNewTransaction();

        authenticate(admin);

        DateTime fakeNow = new DateTime(2014, 6, 25, 12, 34, 0);
        DateTimeUtils.setCurrentMillisFixed(fakeNow.getMillis());
        new LupahallintaHarvestPermitImporter(importFeature, createMockClient(header()), createMockMailHandler())
                .doImport();

        DateTime newFakeNow = fakeNow.plusMinutes(11);
        DateTimeUtils.setCurrentMillisFixed(newFakeNow.getMillis());
        LupahallintaHttpClient mockClient = createMockClient(header());
        new LupahallintaHarvestPermitImporter(importFeature, mockClient, createMockMailHandler())
                .doImport();

        ArgumentCaptor<DateTime> argument = ArgumentCaptor.forClass(DateTime.class);
        verify(mockClient).getPermits(argument.capture());
        assertEquals(fakeNow, argument.getValue());
        assertEquals(newFakeNow, importFeature.getLastLhSyncTime());
    } finally {
        DateTimeUtils.setCurrentMillisSystem();
    }
}
项目:oma-riista-web    文件:HuntingLeaderFinderServiceTest.java   
private static <T> T runBackInTime(DateTime when, Supplier<T> cmd) {
    try {
        DateTimeUtils.setCurrentMillisFixed(when.getMillis());
        return cmd.get();
    } finally {
        DateTimeUtils.setCurrentMillisSystem();
    }
}
项目:oma-riista-web    文件:HarvestReportReminderTest.java   
@Test
public void testHarvestReminderIsSentButNowOldEnough() {
    try {
        final Harvest harvest = createHarvest(HarvestReportRequired.REQUIRED, AuthorIsRegistered.REGISTERED);
        harvest.setEmailReminderSentTime(getTestStartTime());

        persistInNewTransaction();

        final DateTime fakeNow = getTestStartTime().plus(HarvestReportReminderFeature.REMINDER_INTERVAL).plusSeconds(1);
        DateTimeUtils.setCurrentMillisFixed(fakeNow.getMillis());

        runInTransaction(() -> {
            final Map<Long, Set<String>> res = harvestReportReminder.sendReminders();

            assertEquals(1, res.size());
            assertThat(res, hasKey(harvest.getId()));
        });

        runInTransaction(() -> {
            final DateTime reminderSentTime = harvestRepository.getOne(harvest.getId()).getEmailReminderSentTime();
            assertEquals(fakeNow, reminderSentTime);
        });

    } finally {
        DateTimeUtils.setCurrentMillisSystem();
    }
}
项目:RIT-Dining-Planner-Android    文件:TestDateUtils.java   
@Override
protected void setUp() throws Exception {
    super.setUp();

    // Init zone info
    Context context = getInstrumentation().getContext();
    JodaTimeAndroid.init(context);

    // Force the system into 24-hour time for tests
    ContentResolver cr = context.getContentResolver();
    mOldTime1224Setting = Settings.System.getString(cr, Settings.System.TIME_12_24);
    Settings.System.putString(cr, Settings.System.TIME_12_24, "24");

    // Force all tests to be in the US locale; that way we can test output in consistent manner
    Application app = (Application) getInstrumentation().getContext().getApplicationContext();
    Resources res = app.getBaseContext().getResources();
    Configuration config = res.getConfiguration();
    Locale.setDefault(Locale.US);
    config.locale = Locale.US;
    res.updateConfiguration(config, res.getDisplayMetrics());

    // Force the default timezone
    mDefaultJodaTz = DateTimeZone.forID("America/New_York");
    mOldDefaultJodaTz = DateTimeZone.getDefault();
    DateTimeZone.setDefault(mDefaultJodaTz);

    // ...And for the system as well
    mDefaultSystemTz = TimeZone.getTimeZone("America/Chicago");
    mOldDefaultSystemTz = TimeZone.getDefault();
    TimeZone.setDefault(mDefaultSystemTz);

    // Force current "now" time, so all tests can be consistent
    mNow = new DateTime(YEAR, MONTH_OF_YEAR, DAY_OF_MONTH, HOUR_OF_DAY,
        MINUTE_OF_HOUR, SECOND_OF_MINUTE, MILLIS_OF_SECOND, mDefaultJodaTz);
    DateTimeUtils.setCurrentMillisFixed(mNow.getMillis());
}
项目:RIT-Dining-Planner-Android    文件:TestDateUtils.java   
@Override
protected void tearDown() throws Exception {
    super.tearDown();

    // Restore to normal "now" time
    DateTimeUtils.setCurrentMillisSystem();
    DateTimeZone.setDefault(mOldDefaultJodaTz);
    TimeZone.setDefault(mOldDefaultSystemTz);
    ContentResolver cr = getInstrumentation().getContext().getContentResolver();
    Settings.System.putString(cr, Settings.System.TIME_12_24, mOldTime1224Setting);
}
项目:RIT-Dining-Planner-Android    文件:TestDateTimeZone.java   
public void testGetOffset_RI() {
    DateTimeZone zone = DateTimeZone.forID("Europe/Paris");
    assertEquals(2L * DateTimeConstants.MILLIS_PER_HOUR, zone.getOffset(new Instant(TEST_TIME_SUMMER)));
    assertEquals(1L * DateTimeConstants.MILLIS_PER_HOUR, zone.getOffset(new Instant(TEST_TIME_WINTER)));

    assertEquals(zone.getOffset(DateTimeUtils.currentTimeMillis()), zone.getOffset(null));
}