Java 类java.time.ZonedDateTime 实例源码

项目:ta4j    文件:LowestValueIndicatorTest.java   
@Test
public void naNValuesInIntervall(){
    List<Tick> ticks = new ArrayList<>();
    for (long i = 0; i<= 10; i++){ // (NaN, 1, NaN, 2, NaN, 3, NaN, 4, ...)
        Decimal closePrice = i % 2 == 0 ? Decimal.valueOf(i): Decimal.NaN;
        Tick tick = new BaseTick(ZonedDateTime.now().plusDays(i),Decimal.NaN, Decimal.NaN,Decimal.NaN, Decimal.NaN, Decimal.NaN);
        ticks.add(tick);
    }

    BaseTimeSeries series = new BaseTimeSeries("NaN test",ticks);
    LowestValueIndicator lowestValue = new LowestValueIndicator(new ClosePriceIndicator(series), 2);
    for (int i = series.getBeginIndex(); i<= series.getEndIndex(); i++){
        if (i % 2 != 0){
            assertEquals(series.getTick(i-1).getClosePrice().toString(),lowestValue.getValue(i).toString());
        } else
        assertEquals(series.getTick(Math.max(0,i-1)).getClosePrice().toString(),lowestValue.getValue(i).toString());
    }
}
项目:jdk8u-jdk    文件:TCKOffsetPrinterParser.java   
@Test(dataProvider="print")
public void test_print_pattern_X(String offsetPattern, String noOffset, LocalDateTime ldt, ZoneId zone, String expected) {
    String pattern = null;
    if (offsetPattern.equals("+HHmm") && noOffset.equals("Z")) {
        pattern = "X";
    } else if (offsetPattern.equals("+HHMM") && noOffset.equals("Z")) {
        pattern = "XX";
    } else if (offsetPattern.equals("+HH:MM") && noOffset.equals("Z")) {
        pattern = "XXX";
    } else if (offsetPattern.equals("+HHMMss") && noOffset.equals("Z")) {
        pattern = "XXXX";
    } else if (offsetPattern.equals("+HH:MM:ss") && noOffset.equals("Z")) {
        pattern = "XXXXX";
    }
    if (pattern != null) {
        ZonedDateTime zdt = ldt.atZone(zone);
        builder.appendPattern(pattern);
        String output = builder.toFormatter().format(zdt);
        assertEquals(output, expected);
    }
}
项目:commercetools-sync-java    文件:InventorySyncMockUtils.java   
/**
 * Returns mock {@link InventoryEntry} instance. Executing getters on returned instance will return values passed
 * in parameters.
 *
 * @param sku result of calling {@link InventoryEntry#getSku()}
 * @param quantityOnStock result of calling {@link InventoryEntry#getQuantityOnStock()}
 * @param restockableInDays result of calling {@link InventoryEntry#getRestockableInDays()}
 * @param expectedDelivery result of calling {@link InventoryEntry#getExpectedDelivery()}
 * @param supplyChannel result of calling {@link InventoryEntry#getSupplyChannel()}
 * @param customFields result of calling {@link InventoryEntry#getCustom()}
 * @return mock instance of {@link InventoryEntry}
 */
public static InventoryEntry getMockInventoryEntry(final String sku,
                                                   final Long quantityOnStock,
                                                   final Integer restockableInDays,
                                                   final ZonedDateTime expectedDelivery,
                                                   final Reference<Channel> supplyChannel,
                                                   final CustomFields customFields) {
    final InventoryEntry inventoryEntry = mock(InventoryEntry.class);
    when(inventoryEntry.getSku()).thenReturn(sku);
    when(inventoryEntry.getQuantityOnStock()).thenReturn(quantityOnStock);
    when(inventoryEntry.getRestockableInDays()).thenReturn(restockableInDays);
    when(inventoryEntry.getExpectedDelivery()).thenReturn(expectedDelivery);
    when(inventoryEntry.getSupplyChannel()).thenReturn(supplyChannel);
    when(inventoryEntry.getCustom()).thenReturn(customFields);
    return inventoryEntry;
}
项目:Armory    文件:UserDTO.java   
public UserDTO(Long id, String login, String firstName, String lastName,
    String email, boolean activated, String imageUrl, String langKey,
    String createdBy, ZonedDateTime createdDate, String lastModifiedBy, ZonedDateTime lastModifiedDate,
    Set<String> authorities) {

    this.id = id;
    this.login = login;
    this.firstName = firstName;
    this.lastName = lastName;
    this.email = email;
    this.activated = activated;
    this.imageUrl = imageUrl;
    this.langKey = langKey;
    this.createdBy = createdBy;
    this.createdDate = createdDate;
    this.lastModifiedBy = lastModifiedBy;
    this.lastModifiedDate = lastModifiedDate;
    this.authorities = authorities;
}
项目:sentry    文件:GameServerService.java   
public long refreshExpirationDates(Map<String, Integer> expirationSeconds) {
    ZonedDateTime now = ZonedDateTime.now();
    return gameServerRepository.findByIdIn(expirationSeconds.keySet()).parallelStream()
        .map(server -> {
            int seconds = expirationSeconds.get(server.getId());
            if (seconds != 0) {
                server.setExpirationDate(now.plusSeconds(seconds));
                if (server.getPlayers() > 0 && seconds < 60 * 15) {
                    ZonedDateTime lastRconAnnounce = Optional.ofNullable(server.getLastRconAnnounce())
                        .orElse(Instant.EPOCH.atZone(ZoneId.systemDefault()));
                    // announce only once per interval to avoid spamming
                    if (lastRconAnnounce.plusMinutes(getRconSayIntervalMinutes()).isBefore(ZonedDateTime.now())) {
                        Result<String> result = tryRcon(server,
                            "say [GameServers] Server will expire in " + humanizeShort(Duration.ofSeconds(seconds)));
                        if (result.isSuccessful()) {
                            server.setLastRconAnnounce(ZonedDateTime.now());
                        }
                    }
                }
            }
            server.setExpirationCheckDate(now);
            return server;
        })
        .map(gameServerRepository::save)
        .count();
}
项目:openjdk-jdk10    文件:TCKZonedDateTime.java   
@Test
public void now_Clock_allSecsInDay_utc() {
    for (int i = 0; i < (2 * 24 * 60 * 60); i++) {
        Instant instant = Instant.ofEpochSecond(i).plusNanos(123456789L);
        Clock clock = Clock.fixed(instant, ZoneOffset.UTC);
        ZonedDateTime test = ZonedDateTime.now(clock);
        assertEquals(test.getYear(), 1970);
        assertEquals(test.getMonth(), Month.JANUARY);
        assertEquals(test.getDayOfMonth(), (i < 24 * 60 * 60 ? 1 : 2));
        assertEquals(test.getHour(), (i / (60 * 60)) % 24);
        assertEquals(test.getMinute(), (i / 60) % 60);
        assertEquals(test.getSecond(), i % 60);
        assertEquals(test.getNano(), 123456789);
        assertEquals(test.getOffset(), ZoneOffset.UTC);
        assertEquals(test.getZone(), ZoneOffset.UTC);
    }
}
项目:ta4j    文件:PivotPointIndicatorTest.java   
@Before
public void initDataForYearlyTimeFrame(){

    String[] dataLine = rawData_1_week.split("\n");
    List<Tick> ticks = new ArrayList<>();
    for (int i = 0; i < dataLine.length; i++) {
        String[] tickData = dataLine[i].split(",");
        ZonedDateTime date = LocalDate.parse(tickData[0], DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay(ZoneId.systemDefault());
        double open = Double.parseDouble(tickData[1]);
        double high = Double.parseDouble(tickData[2]);
        double low = Double.parseDouble(tickData[3]);
        double close = Double.parseDouble(tickData[4]);
        double volume = Double.parseDouble(tickData[6]);
        ticks.add(new BaseTick(date, open, high, low, close, volume));
    }
    series_1_weeks = new BaseTimeSeries("FB_daily",ticks);
}
项目:displaydirect    文件:Kv78ParserTest.java   
@Test
public void parseGeneralMessageDelete() {
    String data = "\\GKV8turbo_generalmessages|KV8turbo_generalmessages|openOV RET|||UTF-8|0.1|2017-04-11T22:05:46+02:00|\uFEFF\r\n" +
            "\\TGENERALMESSAGEDELETE|GENERALMESSAGEDELETE|start object\r\n" +
            "\\LDataOwnerCode|MessageCodeDate|MessageCodeNumber|TimingPointDataOwnerCode|TimingPointCode\r\n" +
            "RET|2017-04-11|27|ALGEMEEN|31001347\r\n";
    Kv78Packet p = Kv78Parser.parseMessage(data);

    Assert.assertEquals("KV8turbo_generalmessages", p.getType());
    Assert.assertEquals("openOV RET", p.getComment());
    Assert.assertEquals("UTF-8", p.getEncoding());
    Assert.assertEquals("0.1", p.getVersion());
    Assert.assertEquals(ZonedDateTime.parse("2017-04-11T22:05:46+02:00"), p.getGenerated());

    Assert.assertEquals("GENERALMESSAGEDELETE", p.getTables().get(0).getTableName());
    Assert.assertEquals("start object", p.getTables().get(0).getTableComment());

    Assert.assertEquals(1, p.getTables().get(0).getRecords().size());
    Map<String, String> record = p.getTables().get(0).getRecords().get(0);
    Assert.assertEquals(5, record.size());
    Assert.assertEquals("RET", record.get("DataOwnerCode"));
    Assert.assertEquals("2017-04-11", record.get("MessageCodeDate"));
    Assert.assertEquals("27", record.get("MessageCodeNumber"));
    Assert.assertEquals("ALGEMEEN", record.get("TimingPointDataOwnerCode"));
    Assert.assertEquals("31001347", record.get("TimingPointCode"));
}
项目:db-queue    文件:QueueRunnerInSeparateTransactionsTest.java   
@Test
public void should_wait_betweentasktimeout_when_task_found() throws Exception {
    Duration betweenTaskTimeout = Duration.ofHours(1L);
    Duration noTaskTimeout = Duration.ofMillis(5L);

    QueueConsumer queueConsumer = mock(QueueConsumer.class);
    TaskPicker taskPicker = mock(TaskPicker.class);
    TaskRecord taskRecord = new TaskRecord(0, null, 0, ZonedDateTime.now(),
            ZonedDateTime.now(), null, null);
    when(taskPicker.pickTask(queueConsumer)).thenReturn(taskRecord);
    TaskProcessor taskProcessor = mock(TaskProcessor.class);


    when(queueConsumer.getQueueConfig()).thenReturn(new QueueConfig(testLocation1,
            QueueSettings.builder().withBetweenTaskTimeout(betweenTaskTimeout).withNoTaskTimeout(noTaskTimeout).build()));
    QueueProcessingStatus status = new QueueRunnerInSeparateTransactions(taskPicker, taskProcessor).runQueue(queueConsumer);

    assertThat(status, equalTo(QueueProcessingStatus.PROCESSED));

    verify(taskPicker).pickTask(queueConsumer);
    verify(taskProcessor).processTask(queueConsumer, taskRecord);
}
项目:OperatieBRP    文件:BlobConverter.java   
private void converteerAttributen(final MetaRecord record, final BlobRecord blobRecord) {
    for (final Map.Entry<AttribuutElement, MetaAttribuut> entry : record.getAttributen().entrySet()) {
        final AttribuutElement element = entry.getKey();
        final Object huidigeWaarde = entry.getValue().getWaarde();
        final Object value;

        if (huidigeWaarde instanceof Date) {
            value = ((Date) huidigeWaarde).getTime();
        } else if (huidigeWaarde instanceof ZonedDateTime) {
            value = ((ZonedDateTime) huidigeWaarde).toInstant().toEpochMilli();
        } else {
            value = huidigeWaarde;
        }

        blobRecord.addAttribuut(element.getId(), value);
    }
}
项目:rskj    文件:FederationTest.java   
@Test
public void testEquals_differentCreationTime() {
    Federation otherFederation = new Federation(
            Arrays.asList(new BtcECKey[]{
                    BtcECKey.fromPrivate(BigInteger.valueOf(100)),
                    BtcECKey.fromPrivate(BigInteger.valueOf(200)),
                    BtcECKey.fromPrivate(BigInteger.valueOf(300)),
                    BtcECKey.fromPrivate(BigInteger.valueOf(400)),
                    BtcECKey.fromPrivate(BigInteger.valueOf(500)),
                    BtcECKey.fromPrivate(BigInteger.valueOf(600)),
            }),
            ZonedDateTime.parse("2017-06-10T02:30:01Z").toInstant(),
            0L,
            NetworkParameters.fromID(NetworkParameters.ID_REGTEST)
    );
    Assert.assertFalse(federation.equals(otherFederation));
}
项目:db-queue    文件:QueueActorDaoTest.java   
@Test
public void reenqueue_should_update_process_time() throws Exception {
    QueueLocation location = generateUniqueLocation();
    String actor = "abc123";
    Long enqueueId = executeInTransaction(() ->
            queueDao.enqueue(location, new EnqueueParams<String>().withActor(actor)));

    ZonedDateTime beforeExecution = ZonedDateTime.now();
    Duration executionDelay = Duration.ofHours(1L);
    Boolean reenqueueResult = executeInTransaction(() -> queueActorDao.reenqueue(location, actor, executionDelay));
    Assert.assertThat(reenqueueResult, equalTo(true));
    jdbcTemplate.query("select * from " + QueueDatabaseInitializer.DEFAULT_TABLE_NAME + " where id=" + enqueueId, rs -> {
        ZonedDateTime afterExecution = ZonedDateTime.now();
        Assert.assertThat(rs.next(), equalTo(true));
        ZonedDateTime processTime = ZonedDateTime.ofInstant(rs.getTimestamp("process_time").toInstant(),
                ZoneId.systemDefault());

        Assert.assertThat(processTime.isAfter(beforeExecution.plus(executionDelay)), equalTo(true));
        Assert.assertThat(processTime.isBefore(afterExecution.plus(executionDelay)), equalTo(true));
        return new Object();
    });
}
项目:okhttp-awssigner    文件:AwsSigningInterceptorTest.java   
@Test
public void test_AWS_SIG4_string_to_sign() throws IOException {
    String expected = "AWS4-HMAC-SHA256\n" +
            "20150830T123600Z\n" +
            "20150830/us-east-1/iam/aws4_request\n" +
            "f536975d06c0309214f805bb90ccff089219ecd68b2577efef23edd43b7e1a59";

    ZonedDateTime aDate = ZonedDateTime.parse("2015-08-30T12:36:00.000Z", DateTimeFormatter.ISO_DATE_TIME);
    Supplier<ZonedDateTime> clock = () -> aDate;
    AwsSigningInterceptor interceptor = new AwsSigningInterceptor(cfg, clock);


    String requestHash = "f536975d06c0309214f805bb90ccff089219ecd68b2577efef23edd43b7e1a59";
    String stringToSign = interceptor.createStringToSign(aDate, requestHash);

    assertThat(stringToSign).isEqualTo(expected);
}
项目:cas-5.1.0    文件:SamlProfileSamlAuthNStatementBuilder.java   
/**
 * Creates an authentication statement for the current request.
 *
 * @param assertion    the assertion
 * @param authnRequest the authn request
 * @param adaptor      the adaptor
 * @param service      the service
 * @return constructed authentication statement
 * @throws SamlException the saml exception
 */
private AuthnStatement buildAuthnStatement(final Assertion assertion, final AuthnRequest authnRequest,
                                           final SamlRegisteredServiceServiceProviderMetadataFacade adaptor,
                                           final SamlRegisteredService service) throws SamlException {

    final String authenticationMethod = this.authnContextClassRefBuilder.build(assertion, authnRequest, adaptor, service);
    final String id = '_' + String.valueOf(Math.abs(new SecureRandom().nextLong()));
    final AuthnStatement statement = newAuthnStatement(authenticationMethod, DateTimeUtils.zonedDateTimeOf(assertion.getAuthenticationDate()), id);
    if (assertion.getValidUntilDate() != null) {
        final ZonedDateTime dt = DateTimeUtils.zonedDateTimeOf(assertion.getValidUntilDate());
        statement.setSessionNotOnOrAfter(
                DateTimeUtils.dateTimeOf(dt.plusSeconds(casProperties.getAuthn().getSamlIdp().getResponse().getSkewAllowance())));
    }
    statement.setSubjectLocality(buildSubjectLocality(assertion, authnRequest, adaptor));
    return statement;
}
项目:NioImapClient    文件:TestUtils.java   
public static ZonedDateTime msgToInternalDate(ImapMessage msg) {
  try {
    return msg.getInternalDate();
  } catch (UnfetchedFieldException ex) {
    throw Throwables.propagate(ex);
  }
}
项目:openjdk-jdk10    文件:TCKZonedDateTime.java   
@Test
public void test_plusWeeks() {
    LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0);
    ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100);
    ZonedDateTime test = base.plusWeeks(1);
    assertEquals(test, ZonedDateTime.of(ldt.plusWeeks(1), ZONE_0100));
}
项目:light-workflow-4j    文件:StepFunctionBuilderTest.java   
@Test
public void singleWaitState_WaitUntilTimestampWithTimezone() {
    long epochMilli = ZonedDateTime.parse("2016-03-14T01:59:00.123-08:00").toInstant().toEpochMilli();
    final StateMachine stateMachine = StepFunctionBuilder.stateMachine()
            .startAt("InitialState")
            .state("InitialState", StepFunctionBuilder.waitState()
                    .waitFor(StepFunctionBuilder.timestamp(new Date(epochMilli)))
                    .transition(StepFunctionBuilder.end()))
            .build();

    assertStateMachine(stateMachine, "SingleWaitStateWithTimestampWithTimezone.json");
}
项目:ta4j    文件:MockTimeSeries.java   
private static List<Tick> timesToTicks(ZonedDateTime... dates) {
    ArrayList<Tick> ticks = new ArrayList<>();
    int i = 1;
    for (ZonedDateTime date : dates) {
        ticks.add(new MockTick(date, i++));
    }
    return ticks;
}
项目:generator-thundr-gae-react    文件:ZonedDateTimeStringTranslatorFactoryTest.java   
@Test
public void testLoad_willReturnZonedDate_whenSystemDateTimeIsNotUTC() throws Exception {
    new ExecuteAsTimeZone(TimeZone.getTimeZone(ZoneOffset.ofHours(10)))
        .run(() -> assertThat(
            load("2017-08-28T07:09:36.000000042Z")
                .isEqual(ZonedDateTime.of(2017, 8, 28, 17, 9, 36, 42, ZoneOffset.ofHours(10))),
            is(true)
        ));
}
项目:metamodel-membrane    文件:RootInformationController.java   
private HelloResponseServertime getServerTime() {
    final ZonedDateTime now = ZonedDateTime.now();
    final String dateFormatted = now.format(DateTimeFormatter.ISO_INSTANT);

    final HelloResponseServertime serverTime = new HelloResponseServertime();
    serverTime.timestamp(new Date().getTime());
    serverTime.iso8601(dateFormatted);
    return serverTime;
}
项目:db-queue    文件:PickTaskDaoTest.java   
@Test
public void pick_task_should_delay_with_arithmetic_strategy() {
    QueueLocation location = generateUniqueLocation();
    Duration expectedDelay;
    ZonedDateTime beforePickingTask;
    ZonedDateTime afterPickingTask;
    TaskRecord taskRecord;

    RetryTaskStrategy retryTaskStrategy = new RetryTaskStrategy.ArithmeticBackoff(
            QueueSettings.builder().withNoTaskTimeout(Duration.ZERO)
                    .withBetweenTaskTimeout(Duration.ZERO)
                    .build()
    );


    Long enqueueId = executeInTransaction(() -> queueDao.enqueue(location, new EnqueueParams<>()));

    for (int attempt = 1; attempt < 10; attempt++) {
        beforePickingTask = ZonedDateTime.now();
        taskRecord = resetProcessTimeAndPick(location, retryTaskStrategy, enqueueId);
        afterPickingTask = ZonedDateTime.now();
        expectedDelay = Duration.ofMinutes((long) (1 + (attempt - 1) * 2));
        Assert.assertThat(taskRecord.getAttemptsCount(), equalTo((long) attempt));
        Assert.assertThat(taskRecord.getProcessTime().isAfter(beforePickingTask.plus(expectedDelay.minus(WINDOWS_OS_DELAY))), equalTo(true));
        Assert.assertThat(taskRecord.getProcessTime().isBefore(afterPickingTask.plus(expectedDelay.plus(WINDOWS_OS_DELAY))), equalTo(true));
    }
}
项目:strongbox    文件:FileTest.java   
@Test
public void file_try_with_resources() {
    String path = "test.sbx";
    SecretIdentifier secretIdentifier1 = new SecretIdentifier("MySecret");
    long version1 = 1;
    State state1 = State.ENABLED;
    byte[] payload = Encoder.asUTF8("encryptedPayload");
    RawSecretEntry entry1 = new RawSecretEntry(secretIdentifier1, version1, state1, Optional.empty(), Optional.empty(), payload);

    SecretIdentifier secretIdentifier2 = new SecretIdentifier("MySecret2");
    long version2 = 2;
    Optional<ZonedDateTime> notBeforeValue = Optional.of(ZonedDateTime.of(2016, 5, 4, 2, 0 ,0, 0, ZoneId.of("UTC")));
    RawSecretEntry entry2 = new RawSecretEntry(secretIdentifier2, version2, state1, notBeforeValue, Optional.empty(), payload);

    try (File store = new File(new java.io.File(path), new DummyEncryptor(), new FileEncryptionContext(group), new ReentrantReadWriteLock())) {
        if (store.exists()) {
            store.delete();
        }
        store.create(entry1);
        store.create(entry2);
    } // auto closeable should write the results to disk when exiting the try clause, and thus be readable in the next section

    try (File file = new File(new java.io.File(path), new DummyEncryptor(), new FileEncryptionContext(group), new ReentrantReadWriteLock())) {
        List<RawSecretEntry> list = file.stream().toList();
        boolean t = list.get(1).equals(entry2);
        assertThat(list, containsInAnyOrder(entry1, entry2));
    }

    java.io.File f = new java.io.File(path);
    if (!f.delete()) {
        throw new UnexpectedStateException(path, "EXISTS", "DELETED", "File store deletion failed");
    }
}
项目:Armory    文件:UserService.java   
public User createUser(UserDTO userDTO) {
    User user = new User();
    user.setLogin(userDTO.getLogin());
    user.setFirstName(userDTO.getFirstName());
    user.setLastName(userDTO.getLastName());
    user.setEmail(userDTO.getEmail());
    user.setImageUrl(userDTO.getImageUrl());
    if (userDTO.getLangKey() == null) {
        user.setLangKey("en"); // default language
    } else {
        user.setLangKey(userDTO.getLangKey());
    }
    if (userDTO.getAuthorities() != null) {
        Set<Authority> authorities = new HashSet<>();
        userDTO.getAuthorities().forEach(
            authority -> authorities.add(authorityRepository.findOne(authority))
        );
        user.setAuthorities(authorities);
    }
    String encryptedPassword = passwordEncoder.encode(RandomUtil.generatePassword());
    user.setPassword(encryptedPassword);
    user.setResetKey(RandomUtil.generateResetKey());
    user.setResetDate(ZonedDateTime.now());
    user.setActivated(true);
    userRepository.save(user);
    log.debug("Created Information for User: {}", user);
    return user;
}
项目:ta4j    文件:MockTimeSeries.java   
private static List<Tick> doublesToTicks(double... data) {
    ArrayList<Tick> ticks = new ArrayList<>();
    for (int i = 0; i < data.length; i++) {
        ticks.add(new MockTick(ZonedDateTime.now().with(ChronoField.MILLI_OF_SECOND, i), data[i]));
    }
    return ticks;
}
项目:uroborosql    文件:SqlCoverageReport.java   
private void writeSuffix(BufferedWriter writer) throws IOException {
    writer.append("<div class=\"footer\">code coverage report generated by ")
            .append("<a href=\"https://github.com/future-architect/uroborosql\" target=\"_blank\">uroboroSQL</a> at ")
            .append(ZonedDateTime.now().format(DateTimeFormatter.ISO_ZONED_DATE_TIME))
            .append(".</div>");
    writer.newLine();
    writer.append("</body>");
    writer.newLine();
    writer.append("</html>");
    writer.newLine();
}
项目:strongbox    文件:SessionCacheSchema.java   
public Credentials(final BasicSessionCredentials credentials,
                   final ZonedDateTime expiration) {
    this.accessKeyId = credentials.getAWSAccessKeyId();
    this.secretAccessKey = credentials.getAWSSecretKey();
    this.sessionToken = credentials.getSessionToken();
    this.expiration = expiration.format(DateTimeFormatter.ISO_INSTANT);
}
项目:patient-portal    文件:TestUtil.java   
@Override
protected boolean matchesSafely(String item, Description mismatchDescription) {
    try {
        if (!date.isEqual(ZonedDateTime.parse(item))) {
            mismatchDescription.appendText("was ").appendValue(item);
            return false;
        }
        return true;
    } catch (DateTimeParseException e) {
        mismatchDescription.appendText("was ").appendValue(item)
            .appendText(", which could not be parsed as a ZonedDateTime");
        return false;
    }

}
项目:bittrex4j    文件:WalletHealth.java   
@JsonCreator
public WalletHealth(@JsonProperty("Currency") String currency, @JsonProperty("DepositQueueDepth") int depositQueueDepth, @JsonProperty("WithdrawQueueDepth") int withdrawQueueDepth,
                    @JsonProperty("BlockHeight") long blockHeight, @JsonProperty("WalletBalance") int walletBalance,
                    @JsonProperty("WalletConnections") int walletConnections, @JsonProperty("MinutesSinceBHUpdated") int minutesSinceBHUpdated,
                    @JsonProperty("LastChecked") ZonedDateTime lastChecked, @JsonProperty("IsActive") boolean isActive) {
    this.currency = currency;
    this.depositQueueDepth = depositQueueDepth;
    this.withdrawQueueDepth = withdrawQueueDepth;
    this.blockHeight = blockHeight;
    this.walletBalance = walletBalance;
    this.walletConnections = walletConnections;
    this.minutesSinceBHUpdated = minutesSinceBHUpdated;
    this.lastChecked = lastChecked;
    this.isActive = isActive;
}
项目:cas-5.1.0    文件:TokenWebApplicationServiceResponseBuilder.java   
/**
 * Generate token string.
 *
 * @param service    the service
 * @param parameters the parameters
 * @return the jwt
 */
protected String generateToken(final Service service, final Map<String, String> parameters) {
    try {
        final String ticketId = parameters.get(CasProtocolConstants.PARAMETER_TICKET);
        final Cas30ServiceTicketValidator validator = new Cas30ServiceTicketValidator(casProperties.getServer().getPrefix());
        final Assertion assertion = validator.validate(ticketId, service.getId());
        final JWTClaimsSet.Builder claims =
                new JWTClaimsSet.Builder()
                        .audience(service.getId())
                        .issuer(casProperties.getServer().getPrefix())
                        .jwtID(ticketId)
                        .issueTime(assertion.getAuthenticationDate())
                        .subject(assertion.getPrincipal().getName());
        assertion.getAttributes().forEach(claims::claim);
        assertion.getPrincipal().getAttributes().forEach(claims::claim);

        if (assertion.getValidUntilDate() != null) {
            claims.expirationTime(assertion.getValidUntilDate());
        } else {
            final ZonedDateTime dt = ZonedDateTime.now().plusSeconds(ticketGrantingTicketExpirationPolicy.getTimeToLive());
            claims.expirationTime(DateTimeUtils.dateOf(dt));
        }
        final JWTClaimsSet claimsSet = claims.build();
        final JSONObject object = claimsSet.toJSONObject();
        return tokenCipherExecutor.encode(object.toJSONString());
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
项目:flow-platform    文件:CmdResult.java   
public void setFinishTime(ZonedDateTime finishTime) {
    if (finishTime != null) {
        this.finishTime = finishTime;
        if (this.startTime != null) {
            this.totalDuration = ChronoUnit.SECONDS.between(this.startTime, this.finishTime);
        }
    }
}
项目:cas-5.1.0    文件:DigestAuthenticationUtils.java   
/**
 * Create nonce string.
 *
 * @return the nonce
 */
public static String createNonce() {
    final String fmtDate = ZonedDateTime.now().toString();
    final SecureRandom rand = new SecureRandom();
    final Integer randomInt = rand.nextInt();
    return DigestUtils.md5Hex(fmtDate + randomInt);
}
项目:sentry    文件:PlayerCountService.java   
@Scheduled(cron = "10 * * * * ?")
void storePlayerCountMetrics() {
    ZonedDateTime timestamp = ZonedDateTime.now().truncatedTo(MINUTES);

    Map<String, AtomicLong> aggregations = new ConcurrentHashMap<>();

    metricRegistry.getGauges((name, metric) -> name.startsWith("UGC.GameServer.player_count"))
        .entrySet().stream()
        // all servers -> group into regions
        .collect(toMultimap(
            entry -> extractRegion(entry.getKey()),
            Map.Entry::getValue,
            MultimapBuilder.treeKeys().arrayListValues()::build))
        .entries()
        .forEach(entry -> aggregations.computeIfAbsent(entry.getKey(), k -> new AtomicLong())
            .addAndGet((Integer) entry.getValue().getValue()));

    aggregations.entrySet().stream()
        .filter(entry -> entry.getValue().get() > 0 || lastValueMap.getOrDefault(entry.getKey(), 0L) != 0)
        .forEach(entry -> {
            String region = entry.getKey();
            Long value = entry.getValue().get();
            if (lastValueMap.getOrDefault(entry.getKey(), 0L) == 0) {
                if (playerCountRepository.countByRegionAndValueAndTimestamp(region, value, timestamp) == 0) {
                    // add a 0 to the previous minute
                    playerCountRepository.save(new PlayerCount()
                        .timestamp(timestamp.minusMinutes(1))
                        .region(region)
                        .value(0L));
                }
            }
            playerCountRepository.save(new PlayerCount()
                .timestamp(timestamp)
                .region(region)
                .value(value));
            lastValueMap.put(region, value);
        });
}
项目:vind    文件:SearchService.java   
private Document createNewsItem(String _id, String _title, ZonedDateTime _created, int _ranking, String ... _categories) {
    Document document = newsItems.createDoc(_id);
    document.setValue(title, _title);
    document.setValue(created, _created);
    document.setValues(category, Arrays.asList(_categories));
    document.setValue(ranking, _ranking);
    return document;
}
项目:OperatieBRP    文件:MaakLo3BerichtServiceImpl.java   
private ArchiveringOpdracht maakArchiveringOpdracht(final Mutatielevering mutatielevering, final Bericht bericht, final Persoonslijst persoonslijst,
                                                    final ZonedDateTime nu, final String lo3Bericht) {
    final ArchiveringOpdracht archiveringOpdracht = new ArchiveringOpdracht(Richting.UITGAAND, ZonedDateTime.now());
    archiveringOpdracht.setZendendePartijId(partijService.geefBrpPartij().getId());
    archiveringOpdracht.setZendendeSysteem(BasisBerichtGegevens.BRP_SYSTEEM);
    archiveringOpdracht.setOntvangendePartijId(mutatielevering.getAutorisatiebundel().getPartij().getId());
    archiveringOpdracht.setLeveringsAutorisatieId(mutatielevering.getAutorisatiebundel().getLeveringsautorisatieId());
    archiveringOpdracht.setRolId(mutatielevering.getAutorisatiebundel().getRol().getId());
    archiveringOpdracht.setTijdstipVerzending(nu);
    archiveringOpdracht.addTeArchiverenPersoon(persoonslijst.getId());
    archiveringOpdracht.setDienstId(mutatielevering.getAutorisatiebundel().getDienst().getId());
    archiveringOpdracht.setSoortSynchronisatie(bericht.getSoortSynchronisatie());
    archiveringOpdracht.setData(lo3Bericht);
    return archiveringOpdracht;
}
项目:d2g-api    文件:PurchasedItemServiceImpl.java   
@Override
public PurchasedItemsExpensesPayload getCurrentUserExpensesForLastMonth(String email) throws D2GBaseException {
    User owner = userService.findUserByEmail(email);
    if (owner==null) throw new D2GBaseException(D2GBaseExceptionCodes.USER_NOT_EXIST);
    PurchasedItemsExpensesPayload payload = new PurchasedItemsExpensesPayload();
    ZonedDateTime date = ZonedDateTime.now(ZoneOffset.UTC).minusMonths(1);
    payload.setExpenses(purchasedItemRepository.getOwnerExpensesForLastMonth(owner,date));
    return payload;
}
项目:jdk8u-jdk    文件:TCKZonedDateTime.java   
@Test
public void test_plusNanos_nanos() {
    LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0);
    ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100);
    ZonedDateTime test = base.plusNanos(1);
    assertEquals(test, ZonedDateTime.of(ldt.plusNanos(1), ZONE_0100));
}
项目:jdk8u-jdk    文件:TCKZonedDateTime.java   
@Test
public void test_minus_TemporalAmount_Duration() {
    Duration duration = Duration.ofSeconds(4L * 60 * 60 + 5L * 60 + 6L);
    ZonedDateTime t = ZonedDateTime.of(LocalDateTime.of(2008, 6, 1, 12, 30, 59, 500), ZONE_0100);
    ZonedDateTime expected = ZonedDateTime.of(LocalDateTime.of(2008, 6, 1, 8, 25, 53, 500), ZONE_0100);
    assertEquals(t.minus(duration), expected);
}
项目:OperatieBRP    文件:MaakAntwoordBerichtResultaat.java   
/**
 * Constructor.
 * @param xml het response bericht in XML formaat
 * @param datumVerzending de datum verzending dat is opgenomen in het bericht
 * @param referentienummerAttribuutAntwoord het referentienummer dat is opgenomen in het bericht
 */
MaakAntwoordBerichtResultaat(final String xml, final ZonedDateTime datumVerzending,
                             final String referentienummerAttribuutAntwoord) {
    this.xml = xml;
    this.datumVerzending = datumVerzending;
    this.referentienummerAttribuutAntwoord = referentienummerAttribuutAntwoord;
}
项目:sentry    文件:GameServerService.java   
private boolean isUnclaimedCase(GameServer s, List<String> keys) {
    if (s.getExpirationDate() == null) {
        return false;
    }
    ZonedDateTime now = ZonedDateTime.now();
    return keys.stream().anyMatch("unclaimed"::equals)
        && now.isAfter(s.getExpirationDate());
}