Java Code Examples for java.time.ZonedDateTime

The following are top voted examples for showing how to use java.time.ZonedDateTime. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ta4j   File: LowestValueIndicatorTest.java   Source Code and License 7 votes vote down vote up
@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());
    }
}
 
Example 2
Project: commercetools-sync-java   File: InventorySyncMockUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 3
Project: Armory   File: UserDTO.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 4
Project: sentry   File: GameServerService.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 5
Project: jdk8u-jdk   File: TCKOffsetPrinterParser.java   Source Code and License 6 votes vote down vote up
@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);
    }
}
 
Example 6
Project: openjdk-jdk10   File: TCKZonedDateTime.java   Source Code and License 6 votes vote down vote up
@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);
    }
}
 
Example 7
Project: ta4j   File: PivotPointIndicatorTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 8
Project: displaydirect   File: Kv78ParserTest.java   Source Code and License 6 votes vote down vote up
@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"));
}
 
Example 9
Project: db-queue   File: QueueRunnerInSeparateTransactionsTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 10
Project: OperatieBRP   File: BlobConverter.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 11
Project: rskj   File: FederationTest.java   Source Code and License 6 votes vote down vote up
@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));
}
 
Example 12
Project: db-queue   File: QueueActorDaoTest.java   Source Code and License 6 votes vote down vote up
@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();
    });
}
 
Example 13
Project: okhttp-awssigner   File: AwsSigningInterceptorTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 14
Project: cas-5.1.0   File: SamlProfileSamlAuthNStatementBuilder.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 15
Project: NioImapClient   File: TestUtils.java   Source Code and License 5 votes vote down vote up
public static ZonedDateTime msgToInternalDate(ImapMessage msg) {
  try {
    return msg.getInternalDate();
  } catch (UnfetchedFieldException ex) {
    throw Throwables.propagate(ex);
  }
}
 
Example 16
Project: openjdk-jdk10   File: TCKZonedDateTime.java   Source Code and License 5 votes vote down vote up
@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));
}
 
Example 17
Project: light-workflow-4j   File: StepFunctionBuilderTest.java   Source Code and License 5 votes vote down vote up
@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");
}
 
Example 18
Project: Armory   File: UserServiceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
public void assertThatResetKeyMustBeValid() {
    User user = userService.createUser("johndoe", "johndoe", "John", "Doe", "[email protected]", "http://placehold.it/50x50", "en-US");

    ZonedDateTime daysAgo = ZonedDateTime.now().minusHours(25);
    user.setActivated(true);
    user.setResetDate(daysAgo);
    user.setResetKey("1234");
    userRepository.save(user);
    Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
    assertThat(maybeUser.isPresent()).isFalse();
    userRepository.delete(user);
}
 
Example 19
Project: ta4j   File: MockTimeSeries.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 20
Project: generator-thundr-gae-react   File: ZonedDateTimeStringTranslatorFactoryTest.java   Source Code and License 5 votes vote down vote up
@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)
        ));
}
 
Example 21
Project: metamodel-membrane   File: RootInformationController.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 22
Project: db-queue   File: PickTaskDaoTest.java   Source Code and License 5 votes vote down vote up
@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));
    }
}
 
Example 23
Project: strongbox   File: FileTest.java   Source Code and License 5 votes vote down vote up
@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");
    }
}
 
Example 24
Project: Armory   File: UserService.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 25
Project: ta4j   File: MockTimeSeries.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 26
Project: uroborosql   File: SqlCoverageReport.java   Source Code and License 5 votes vote down vote up
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();
}
 
Example 27
Project: strongbox   File: SessionCacheSchema.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 28
Project: patient-portal   File: TestUtil.java   Source Code and License 5 votes vote down vote up
@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;
    }

}
 
Example 29
Project: bittrex4j   File: WalletHealth.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 30
Project: cas-5.1.0   File: TokenWebApplicationServiceResponseBuilder.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 31
Project: flow-platform   File: CmdResult.java   Source Code and License 5 votes vote down vote up
public void setFinishTime(ZonedDateTime finishTime) {
    if (finishTime != null) {
        this.finishTime = finishTime;
        if (this.startTime != null) {
            this.totalDuration = ChronoUnit.SECONDS.between(this.startTime, this.finishTime);
        }
    }
}
 
Example 32
Project: cas-5.1.0   File: DigestAuthenticationUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
}
 
Example 33
Project: sentry   File: PlayerCountService.java   Source Code and License 5 votes vote down vote up
@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);
        });
}
 
Example 34
Project: vind   File: SearchService.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 35
Project: OperatieBRP   File: MaakLo3BerichtServiceImpl.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 36
Project: d2g-api   File: PurchasedItemServiceImpl.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 37
Project: jdk8u-jdk   File: TCKZonedDateTime.java   Source Code and License 5 votes vote down vote up
@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));
}
 
Example 38
Project: jdk8u-jdk   File: TCKZonedDateTime.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 39
Project: OperatieBRP   File: MaakAntwoordBerichtResultaat.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 40
Project: sentry   File: GameServerService.java   Source Code and License 5 votes vote down vote up
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());
}
 
Example 41
Project: cas-5.1.0   File: ThresholdExpiredCRLRevocationPolicyTests.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the unit test parameters.
 *
 * @return  Test parameter data.
 * @throws Exception if there is an exception getting the test parameters.
 */
@Parameters
public static Collection<Object[]> getTestParameters() throws Exception {
    final Collection<Object[]> params = new ArrayList<>();

    final ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
    final ZonedDateTime twoHoursAgo = now.minusHours(2);
    final ZonedDateTime oneHourAgo = now.minusHours(1);
    final ZonedDateTime halfHourAgo = now.minusMinutes(30);
    final X500Principal issuer = new X500Principal("CN=CAS");

    // Test case #1
    // Expect expired for zero leniency on CRL expiring 1ms ago
    final ThresholdExpiredCRLRevocationPolicy zeroThreshold = new ThresholdExpiredCRLRevocationPolicy(0);
    params.add(new Object[] {
            zeroThreshold,
            new MockX509CRL(issuer, DateTimeUtils.dateOf(oneHourAgo), DateTimeUtils.dateOf(now.minusSeconds(1))),
            new ExpiredCRLException("CN=CAS", ZonedDateTime.now(ZoneOffset.UTC)),
    });

    // Test case #2
    // Expect expired for 1h leniency on CRL expired 1 hour 1ms ago
    final ThresholdExpiredCRLRevocationPolicy oneHourThreshold = new ThresholdExpiredCRLRevocationPolicy(3600);
    params.add(new Object[] {
            oneHourThreshold,
            new MockX509CRL(issuer, DateTimeUtils.dateOf(twoHoursAgo), DateTimeUtils.dateOf(oneHourAgo.minusSeconds(1))),
            new ExpiredCRLException("CN=CAS", ZonedDateTime.now(ZoneOffset.UTC)),
    });

    // Test case #3
    // Expect valid for 1h leniency on CRL expired 30m ago
    params.add(new Object[] {
            oneHourThreshold,
            new MockX509CRL(issuer, DateTimeUtils.dateOf(twoHoursAgo), DateTimeUtils.dateOf(halfHourAgo)),
            null,
    });

    return params;
}
 
Example 42
Project: OperatieBRP   File: PlaatsAfnemerindicatieParams.java   Source Code and License 5 votes vote down vote up
/**
 * Constructor voor de input parameters.
 * @param toegangLeveringsautorisatie de toegang leveringautorisatie
 * @param persoonHisVolledig de persoon waar de indicatie op geplaatst wordt
 * @param datumAanvangMaterielePeriode de datum waarop de indicatie gaat gelden
 * @param datumEindeVolgen de datum waarop de indicatie verloopt
 * @param tijdstipRegistratie het moment van registreren
 * @param verantwoordingDienstId het id van de dienst welke de plaatsing verantwoordt.
 */
public PlaatsAfnemerindicatieParams(final ToegangLeveringsAutorisatie toegangLeveringsautorisatie, final Persoonslijst persoonHisVolledig,
                                    final Integer datumAanvangMaterielePeriode, final Integer datumEindeVolgen,
                                    final ZonedDateTime tijdstipRegistratie, final int verantwoordingDienstId) {
    this.toegangLeveringsautorisatie = toegangLeveringsautorisatie;
    this.persoonslijst = persoonHisVolledig;
    this.datumAanvangMaterielePeriode = datumAanvangMaterielePeriode;
    this.datumEindeVolgen = datumEindeVolgen;
    this.tijdstipRegistratie = tijdstipRegistratie;
    this.verantwoordingDienstId = verantwoordingDienstId;
}
 
Example 43
Project: OperatieBRP   File: PeilmomentHistorievormPredicate.java   Source Code and License 5 votes vote down vote up
private boolean doApply(final MetaRecord record) {

        final boolean materieelTotEnMetAkkoord;
        if (record.getParentGroep().getGroepElement().getHistoriePatroon() == HistoriePatroon.G
                || record.getParentGroep().getGroepElement().getVerantwoordingCategorie() == VerantwoordingCategorie.G) {
            return true;
        } else if (record.getParentGroep().getGroepElement().isFormeel()) {
            // Materiele historie is niet relevant hier, dus standaard akkoord.
            materieelTotEnMetAkkoord = true;
        } else {
            final Integer aanvangDatum = record.getDatumAanvangGeldigheid();
            Integer eindeDatum = null;
            if (record.getDatumEindeGeldigheid() != null) {
                eindeDatum = record.getDatumEindeGeldigheid();
            }
            materieelTotEnMetAkkoord = GeldigheidUtil.materieelGeldig(aanvangDatum, eindeDatum, historievorm, materieelTotEnMetMoment);
        }
        boolean formeelAkkoord = false;
        if (materieelTotEnMetAkkoord) {
            final ZonedDateTime registratieDatumTijd;
            ZonedDateTime vervalDatumTijd = null;
            if (record.getParentGroep().getGroepElement().getVerantwoordingCategorie() == VerantwoordingCategorie.D) {
                final MetaAttribuut tijdstipRegistratie = record.getAttribuut(Element.PERSOON_AFNEMERINDICATIE_TIJDSTIPREGISTRATIE);
                final MetaAttribuut tijdstipVerval = record.getAttribuut(Element.PERSOON_AFNEMERINDICATIE_TIJDSTIPVERVAL);
                registratieDatumTijd = tijdstipRegistratie.getWaarde();
                if (tijdstipVerval != null) {
                    vervalDatumTijd = tijdstipVerval.getWaarde();
                }
            } else {
                registratieDatumTijd = record.getTijdstipRegistratieAttribuut();
                vervalDatumTijd = record.getDatumTijdVervalAttribuut();
            }
            // We nemen dit record mee als de materiele en formele historie akkoord zijn.
            formeelAkkoord = GeldigheidUtil.formeelGeldig(registratieDatumTijd, vervalDatumTijd, historievorm, formeelPeilmoment);
        }

        return formeelAkkoord;
    }
 
Example 44
Project: jdk8u-jdk   File: TCKZonedDateTime.java   Source Code and License 5 votes vote down vote up
@Test
public void test_minusMonths_zero() {
    LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0);
    ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100);
    ZonedDateTime test = base.minusMonths(0);
    assertEquals(test, base);
}
 
Example 45
Project: OperatieBRP   File: SynchroniseerStamgegevenServiceImpl.java   Source Code and License 5 votes vote down vote up
private void archiveer(final SynchronisatieVerzoek verzoek, final BepaalStamgegevenResultaat resultaat,
                       final MaakAntwoordBerichtResultaat antwoordBericht) {
    final Autorisatiebundel autorisatiebundel = resultaat.getAutorisatiebundel();
    //INGAAND
    final ArchiveringOpdracht dtoIn = new ArchiveringOpdracht(Richting.INGAAND, ZonedDateTime.now());
    dtoIn.setData(verzoek.getXmlBericht());
    dtoIn.setReferentienummer(verzoek.getStuurgegevens().getReferentieNummer());
    dtoIn.setZendendeSysteem(verzoek.getStuurgegevens().getZendendSysteem());
    dtoIn.setSoortBericht(SoortBericht.LVG_SYN_GEEF_SYNCHRONISATIE_STAMGEGEVEN);
    if (autorisatiebundel != null) {
        dtoIn.setDienstId(autorisatiebundel.getDienst() == null ? null : autorisatiebundel.getDienst().getId());
        dtoIn.setLeveringsAutorisatieId(autorisatiebundel.getLeveringsautorisatieId());
        dtoIn.setZendendePartijId(autorisatiebundel.getPartij() == null ? null : autorisatiebundel.getPartij().getId());
    }
    dtoIn.setTijdstipVerzending(verzoek.getStuurgegevens().getTijdstipVerzending());
    dtoIn.setTijdstipOntvangst(BrpNu.get().getDatum());
    archiveringService.archiveer(dtoIn);

    //UITGAAND
    final ArchiveringOpdracht dtoUit = new ArchiveringOpdracht(Richting.UITGAAND, ZonedDateTime.now());
    dtoUit.setData(antwoordBericht.getXml());
    dtoUit.setTijdstipVerzending(antwoordBericht.getDatumVerzending());
    dtoUit.setSoortBericht(SoortBericht.LVG_SYN_GEEF_SYNCHRONISATIE_STAMGEGEVEN_R);
    dtoUit.setReferentienummer(antwoordBericht.getReferentienummerAttribuutAntwoord());
    dtoUit.setCrossReferentienummer(verzoek.getStuurgegevens().getReferentieNummer());
    dtoUit.setLeveringsAutorisatieId(
            autorisatiebundel == null ? null : autorisatiebundel.getToegangLeveringsautorisatie().getLeveringsautorisatie().getId());
    dtoUit.setVerwerkingsresultaat(resultaat.getMeldingList().isEmpty() ? VerwerkingsResultaat.GESLAAGD : VerwerkingsResultaat.FOUTIEF);
    dtoUit.setZendendePartijId(resultaat.getBrpPartij().getId());
    dtoUit.setZendendeSysteem(BasisBerichtGegevens.BRP_SYSTEEM);
    dtoUit.setOntvangendePartijId(autorisatiebundel != null && autorisatiebundel.getPartij() != null ? autorisatiebundel.getPartij().getId() : null);
    archiveringService.archiveer(dtoUit);
}
 
Example 46
Project: powsybl-core   File: MapDbAppStorage.java   Source Code and License 5 votes vote down vote up
@Override
public void updateModificationTime(String nodeId) {
    UUID nodeUuid = checkNodeId(nodeId);
    NodeInfo nodeInfo = getNodeInfo(nodeId);
    long modificationTime = ZonedDateTime.now().toInstant().toEpochMilli();
    nodeInfo.setModificationTime(modificationTime);
    nodeInfoMap.put(nodeUuid, nodeInfo);
}
 
Example 47
Project: stroom-stats   File: GenerateSampleStatisticsData.java   Source Code and License 4 votes vote down vote up
private static Collection<Statistics.Statistic> buildEvents(final ZonedDateTime initialEventTime,
                                                            final StatisticType statisticType,
                                                            final int iterationCount) {
    final ZonedDateTime eventTime = initialEventTime;

    Collection<Statistics.Statistic> statisticList = new ConcurrentLinkedQueue<>();

    Set<Tuple4<ZonedDateTime, String, String, String>> perms = new HashSet<>();

    IntStream.range(0, iterationCount).forEach(i -> {
        ZonedDateTime time = eventTime.plus(i * EVENT_TIME_DELTA_MS, ChronoUnit.MILLIS);

        for (final String user : USERS) {
            for (final String colour : COLOURS) {
                for (final String state : STATES) {

                    Statistics.Statistic statistic;
                    if (statisticType.equals(StatisticType.COUNT)) {
                        statistic = StatisticsHelper.buildCountStatistic(
                                time,
                                COUNT_STAT_VALUE,
                                StatisticsHelper.buildTagType(TAG_USER, user),
                                StatisticsHelper.buildTagType(TAG_COLOUR, colour),
                                StatisticsHelper.buildTagType(TAG_STATE, state));

                    } else if (statisticType.equals(StatisticType.VALUE)) {
                        //give each different colour a different value
                        double val = VALUE_STAT_VALUE_MAP.get(colour);

                        statistic = StatisticsHelper.buildValueStatistic(
                                time,
                                val,
                                StatisticsHelper.buildTagType(TAG_USER, user),
                                StatisticsHelper.buildTagType(TAG_COLOUR, colour),
                                StatisticsHelper.buildTagType(TAG_STATE, state));
                    } else {
                        throw new RuntimeException(String.format("Unexpected type %s", statisticType));
                    }

                    statisticList.add(statistic);

                    perms.add(new Tuple4<>(time, user, colour, state));
                }
            }
        }
    });

    long distinctCount = perms.size();

    LOGGER.info("Returning {} statistic events, ({} distinct)", statisticList.size(), distinctCount);
    return statisticList;
}
 
Example 48
Project: NioImapClient   File: Envelope.java   Source Code and License 4 votes vote down vote up
public Optional<ZonedDateTime> getDate() {
  return this.date;
}
 
Example 49
Project: jdk8u-jdk   File: TCKOffsetDateTime.java   Source Code and License 4 votes vote down vote up
@Test
public void test_atZone() {
    OffsetDateTime t = OffsetDateTime.of(2008, 6, 30, 11, 30, 0, 0, OFFSET_MTWO);
    assertEquals(t.atZoneSameInstant(ZONE_PARIS),
            ZonedDateTime.of(2008, 6, 30, 15, 30, 0, 0, ZONE_PARIS));
}
 
Example 50
Project: jdk8u-jdk   File: TCKZonedDateTime.java   Source Code and License 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void factory_parse_nullText() {
    ZonedDateTime.parse((String) null);
}
 
Example 51
Project: generator-thundr-gae-react   File: ZonedDateTimeDateTranslatorFactoryTest.java   Source Code and License 4 votes vote down vote up
private ZonedDateTime load(Date val) {
    return translator.load(val, null, null);
}
 
Example 52
Project: bittrex4j   File: Order.java   Source Code and License 4 votes vote down vote up
public ZonedDateTime getClosed() {
    return closed;
}
 
Example 53
Project: sentry   File: StreamerDTO.java   Source Code and License 4 votes vote down vote up
public ZonedDateTime getLastAnnouncement() {
    return lastAnnouncement;
}
 
Example 54
Project: saluki   File: JSR310DateConverters.java   Source Code and License 4 votes vote down vote up
@Override
public Date convert(ZonedDateTime source) {
    return source == null ? null : Date.from(source.toInstant());
}
 
Example 55
Project: strongbox   File: ProfileCredentialProvider.java   Source Code and License 4 votes vote down vote up
/**
 * Resolve AWS credentials based on MFA/Assume role
 *
 * We will assume that if mfa_serial is defined, then role_arn and source_profile also has to be specified.
 *
 * Please note that Strongbox differ from the AWS CLI in the following:
 * AWS CLI: 'Note that configuration variables for using IAM roles can only be in the AWS CLI config file.'
 * Strongbox: '--assume-role' can be specified explicitly
 *
 * https://docs.aws.amazon.com/cli/latest/topic/config-vars.html#using-aws-iam-roles
 */
private AWSCredentials assumeRole(ClientConfiguration clientConfiguration,
                                  ConfigProviderChain configProvider,
                                  ProfileIdentifier profile,
                                  RoleARN roleToAssume) {

    Optional<ProfileIdentifier> sourceProfile = configProvider.getSourceProfile(profile);
    if (!sourceProfile.isPresent()) {
        throw new IllegalStateException(String.format("'%s' must be specified when using '%s' for profile '%s'",
                AWSConfigPropertyKey.SOURCE_PROFILE,
                AWSConfigPropertyKey.ROLE_ARN,
                profile.name));
    }

    SessionCache sessionCache = new SessionCache(profile, roleToAssume);
    Optional<BasicSessionCredentials> cachedCredentials = sessionCache.load();

    if (cachedCredentials.isPresent()) {
        return cachedCredentials.get();
    } else {
        AWSCredentialsProvider staticCredentialsProvider = new AWSStaticCredentialsProvider(getStaticCredentials(configProvider, sourceProfile.get()));

        AWSSecurityTokenService client = AWSSecurityTokenServiceClientBuilder.standard()
                .withCredentials(staticCredentialsProvider)
                .withClientConfiguration(transformAndVerifyOrThrow(clientConfiguration))
                .withRegion(RegionResolver.getRegion())
                .build();

        String sessionId = String.format("strongbox-cli-session-%s", ZonedDateTime.now().toEpochSecond());

        AssumeRoleRequest request = new AssumeRoleRequest();
        request.withRoleArn(roleToAssume.toArn())
                .withRoleSessionName(sessionId);

        Optional<String> mfaSerial = configProvider.getMFASerial(profile);
        if (mfaSerial.isPresent()) {
            MFAToken mfaToken = mfaTokenSupplier.get();

            request.withSerialNumber(mfaSerial.get())
                    .withTokenCode(mfaToken.value);
        }

        AssumeRoleResult result = client.assumeRole(request);
        Credentials credentials = result.getCredentials();

        BasicSessionCredentials basicSessionCredentials = new BasicSessionCredentials(credentials.getAccessKeyId(), credentials.getSecretAccessKey(), credentials.getSessionToken());

        sessionCache.save(result.getAssumedRoleUser(),
                basicSessionCredentials,
                ZonedDateTime.ofInstant(credentials.getExpiration().toInstant(), ZoneId.of("UTC")));

        return basicSessionCredentials;
    }
}
 
Example 56
Project: spring-boot-gae   File: ZonedDateTimeSerializationTest.java   Source Code and License 4 votes vote down vote up
public ZonedDateTimeEntity(String id, ZonedDateTime value) {
    this.id = id;
    this.value = value;
}
 
Example 57
Project: strongbox   File: ZonedDateTimeConverter.java   Source Code and License 4 votes vote down vote up
@Override
public ZonedDateTime fromObject(Object value) {
    return FormattedTimestamp.fromEpoch((Long)value);
}
 
Example 58
Project: spring-boot-gae   File: DefaultSearchConversionServiceTest.java   Source Code and License 4 votes vote down vote up
@Test
public void convert_willHandleZonedDateTimeValues() {
    ZonedDateTime time = ZonedDateTime.of(2017, 10, 11, 17, 24, 36, 123456789, ZoneOffset.UTC);
    assertThat(convert(time)).isEqualTo("2017-10-11");
}
 
Example 59
Project: vind   File: NewsItem.java   Source Code and License 4 votes vote down vote up
public ZonedDateTime getCreated() {
    return created;
}
 
Example 60
Project: klask-io   File: JSR310DateConverters.java   Source Code and License 4 votes vote down vote up
@Override
public LocalDate convert(Date source) {
    return source == null ? null : ZonedDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault()).toLocalDate();
}