Example usage for java.time ZonedDateTime now

List of usage examples for java.time ZonedDateTime now

Introduction

In this page you can find the example usage for java.time ZonedDateTime now.

Prototype

public static ZonedDateTime now() 

Source Link

Document

Obtains the current date-time from the system clock in the default time-zone.

Usage

From source file:org.apache.james.jmap.model.SetMessagesResponseTest.java

private ImmutableMap<CreationMessageId, Message> buildMessage(CreationMessageId messageId) {
    return ImmutableMap.of(messageId,
            Message.builder().id(MessageId.of(messageId.getId())).blobId(BlobId.of("blobId"))
                    .threadId("threadId").mailboxIds(ImmutableList.of()).headers(ImmutableMap.of())
                    .subject("subject").size(0).date(ZonedDateTime.now()).preview("preview").build());
}

From source file:org.thevortex.lighting.jinks.robot.Recurrence.java

/**
 * @return the ICAL-formatted string//from   w ww  . j ava2s. c o m
 */
@Override
public String toString() {
    StringBuilder formatted = new StringBuilder(DTSTART)
            .append(ZonedDateTime.now().with(startTime).truncatedTo(ChronoUnit.MINUTES).format(ICAL_DT));

    // if we have a duration, there's an end
    if (duration != null) {
        formatted.append('\n').append(DTEND).append(ZonedDateTime.now().with(startTime.plus(duration))
                .truncatedTo(ChronoUnit.MINUTES).format(ICAL_DT));
    }

    // always a frequency
    formatted.append('\n').append(RRULE).append(FREQ).append(frequency);

    if (frequency == Frequency.WEEKLY) {
        // build the buffer of days
        StringBuilder dayBuilder = new StringBuilder();
        boolean notFirst = false;
        DayOfWeek lastDay = null;
        for (DayOfWeek day : days) {
            if (notFirst) {
                dayBuilder.append(',');
            }
            notFirst = true;
            dayBuilder.append(day.name().substring(0, 2));
            lastDay = day;
        }
        String formattedDays = dayBuilder.toString();

        // if SUNDAY is at the end, move it to the front
        if (lastDay == DayOfWeek.SUNDAY) {
            formattedDays = "SU," + formattedDays.substring(0, formattedDays.lastIndexOf(","));
        }
        // spit it out
        formatted.append(';').append(BYDAY).append(formattedDays);
    }
    return formatted.toString();
}

From source file:com.sumzerotrading.eod.trading.strategy.ReportGeneratorTest.java

@Test
public void testOrderEvent_NotFilled() {
    order.setCurrentStatus(OrderStatus.Status.NEW);
    OrderEvent orderEvent = new OrderEvent(order,
            new OrderStatus(OrderStatus.Status.NEW, "", "", new StockTicker("QQQ"), ZonedDateTime.now()));
    reportGenerator.orderEvent(orderEvent);

    verify(reportGenerator, never()).writeRoundTripToFile(any(RoundTrip.class));
}

From source file:com.cosmicpush.pub.push.LqNotificationPush.java

public static LqNotificationPush newPush(String topic, String summary, String trackingId, Throwable throwable,
        Collection<LqAttachment> attachments, String callbackUrl, Map<String, String> traits) {

    InetAddress remoteAddress = PushUtils.getLocalHost();
    LqExceptionInfo exceptionInfo = (throwable == null) ? null : LqExceptionInfo.create(throwable);

    return new LqNotificationPush(topic, summary, trackingId, ZonedDateTime.now(), exceptionInfo, attachments,
            callbackUrl, remoteAddress.getCanonicalHostName(), remoteAddress.getHostAddress(), traits);
}

From source file:org.openlmis.fulfillment.testutils.DtoGenerator.java

private static Object generateBaseValue(Class<?> propertyType) {
    if (String.class.isAssignableFrom(propertyType)) {
        return randomAlphanumeric(10);
    }/*from www .  j  a  v a 2 s. c  om*/

    if (Number.class.isAssignableFrom(propertyType)) {
        return parseNumber(String.valueOf(RANDOM.nextInt(1000)), (Class<Number>) propertyType);
    }

    if (UUID.class.isAssignableFrom(propertyType)) {
        return randomUUID();
    }

    if (Boolean.class.isAssignableFrom(propertyType) || boolean.class.isAssignableFrom(propertyType)) {
        return true;
    }

    if (LocalDate.class.isAssignableFrom(propertyType)) {
        return LocalDate.now();
    }

    if (ZonedDateTime.class.isAssignableFrom(propertyType)) {
        return ZonedDateTime.now();
    }

    if (Enum.class.isAssignableFrom(propertyType)) {
        int idx = RANDOM.nextInt(propertyType.getEnumConstants().length);
        return propertyType.getEnumConstants()[idx];
    }

    return null;
}

From source file:com.sumzerotrading.reporting.csv.ReportGeneratorTest.java

@Test
public void testOrderEvent_NotFilled() throws Exception {
    order.setCurrentStatus(OrderStatus.Status.NEW);
    OrderEvent orderEvent = new OrderEvent(order,
            new OrderStatus(OrderStatus.Status.NEW, "", "", new StockTicker("QQQ"), ZonedDateTime.now()));
    reportGenerator.orderEvent(orderEvent);

    verify(reportGenerator, never()).writeRoundTripToFile(any(PairTradeRoundTrip.class));
    verify(reportGenerator, never()).savePartial(Matchers.anyString(), anyObject());
}

From source file:com.seleniumtests.util.logging.SeleniumRobotLogger.java

/**
 * Clean result directories//w  w w. j  a  v  a  2 s  .  c  o m
 * Delete the directory that will be used to write these test results
 * Delete also directories in "test-output" which are older than 300 minutes. Especially useful when test is requested to write result
 * to a sub-directory of test-output with timestamp (for example). Without this mechanism, results would never be cleaned
 */
private static void cleanResults() {
    // clean output dir
    try {
        FileUtils.deleteDirectory(new File(outputDirectory));
        WaitHelper.waitForSeconds(1);
    } catch (IOException e) {
        // do nothing
    }

    new File(outputDirectory).mkdirs();
    WaitHelper.waitForSeconds(1);

    if (new File(defaultOutputDirectory).exists()) {
        for (File directory : new File(defaultOutputDirectory).listFiles(file -> file.isDirectory())) {
            try {
                if (Files.readAttributes(directory.toPath(), BasicFileAttributes.class).lastAccessTime()
                        .toInstant().atZone(ZoneOffset.UTC).toLocalTime().isBefore(ZonedDateTime.now()
                                .minusMinutes(300).withZoneSameInstant(ZoneOffset.UTC).toLocalTime())) {
                    FileUtils.deleteDirectory(directory);
                }
            } catch (IOException e) {
            }

        }
    }
}

From source file:alfio.manager.PaymentManager.java

PaymentResult processPayPalPayment(String reservationId, String token, String payerId, int price, Event event) {
    try {/*from  w  w w  .  j  a  va 2 s.c  o m*/
        Pair<String, String> captureAndPaymentId = paypalManager.commitPayment(reservationId, token, payerId,
                event);
        String captureId = captureAndPaymentId.getLeft();
        String paymentId = captureAndPaymentId.getRight();
        Supplier<String> feeSupplier = () -> FeeCalculator.getCalculator(event, configurationManager)
                .apply(ticketRepository.countTicketsInReservation(reservationId), (long) price)
                .map(String::valueOf).orElse("0");
        Pair<Long, Long> fees = paypalManager.getInfo(paymentId, captureId, event, feeSupplier).map(i -> {
            Long platformFee = Optional.ofNullable(i.getPlatformFee()).map(Long::parseLong).orElse(0L);
            Long gatewayFee = Optional.ofNullable(i.getFee()).map(Long::parseLong).orElse(0L);
            return Pair.of(platformFee, gatewayFee);
        }).orElseGet(() -> Pair.of(0L, 0L));
        transactionRepository.insert(captureId, paymentId, reservationId, ZonedDateTime.now(), price,
                event.getCurrency(), "Paypal confirmation", PaymentProxy.PAYPAL.name(), fees.getLeft(),
                fees.getRight());
        return PaymentResult.successful(captureId);
    } catch (Exception e) {
        log.warn("errow while processing paypal payment: " + e.getMessage(), e);
        if (e instanceof PayPalRESTException) {
            return PaymentResult.unsuccessful(ErrorsCode.STEP_2_PAYPAL_UNEXPECTED);
        } else if (e instanceof PaypalManager.HandledPaypalErrorException) {
            return PaymentResult.unsuccessful(e.getMessage());
        }
        throw new IllegalStateException(e);
    }
}

From source file:com.epam.reportportal.auth.integration.github.GitHubUserReplicator.java

/**
 * Replicates GitHub user to internal database (if does NOT exist). Creates personal project for that user
 *
 * @param userInfo     GitHub user to be replicated
 * @param gitHubClient Configured github client
 * @return Internal User representation/*from   w  w  w. j  a  v  a  2  s .com*/
 */
public User replicateUser(UserResource userInfo, GitHubClient gitHubClient) {
    String login = EntityUtils.normalizeUsername(userInfo.login);
    User user = userRepository.findOne(login);
    if (null == user) {
        user = new User();
        user.setLogin(login);

        String email = userInfo.email;
        if (Strings.isNullOrEmpty(email)) {
            email = gitHubClient.getUserEmails().stream().filter(EmailResource::isVerified)
                    .filter(EmailResource::isPrimary).findAny().get().getEmail();
        }
        if (userRepository.exists(Filter.builder().withTarget(User.class)
                .withCondition(builder().eq("email", email).build()).build())) {
            throw new UserSynchronizationException("User with email '" + email + "' already exists");
        }
        user.setEmail(EntityUtils.normalizeEmail(email));

        if (!Strings.isNullOrEmpty(userInfo.name)) {
            user.setFullName(userInfo.name);
        }

        User.MetaInfo metaInfo = new User.MetaInfo();
        Date now = Date.from(ZonedDateTime.now().toInstant());
        metaInfo.setLastLogin(now);
        metaInfo.setSynchronizationDate(now);
        user.setMetaInfo(metaInfo);

        user.setType(UserType.GITHUB);
        user.setRole(UserRole.USER);
        Object avatarUrl = userInfo.avatarUrl;
        user.setPhotoId(uploadAvatar(gitHubClient, login, avatarUrl));

        user.setIsExpired(false);

        user.setDefaultProject(generatePersonalProject(user).getId());
        userRepository.save(user);

    } else if (!UserType.GITHUB.equals(user.getType())) {
        //if user with such login exists, but it's not GitHub user than throw an exception
        throw new UserSynchronizationException("User with login '" + user.getId() + "' already exists");
    }
    return user;
}

From source file:org.thingsboard.server.service.security.model.token.JwtTokenFactory.java

public JwtToken createRefreshToken(SecurityUser securityUser) {
    if (StringUtils.isBlank(securityUser.getEmail())) {
        throw new IllegalArgumentException("Cannot create JWT Token without username/email");
    }/* ww  w  .ja v  a 2 s  .com*/

    ZonedDateTime currentTime = ZonedDateTime.now();

    UserPrincipal principal = securityUser.getUserPrincipal();
    Claims claims = Jwts.claims().setSubject(principal.getValue());
    claims.put(SCOPES, Collections.singletonList(Authority.REFRESH_TOKEN.name()));
    claims.put(USER_ID, securityUser.getId().getId().toString());
    claims.put(IS_PUBLIC, principal.getType() == UserPrincipal.Type.PUBLIC_ID);

    String token = Jwts.builder().setClaims(claims).setIssuer(settings.getTokenIssuer())
            .setId(UUID.randomUUID().toString()).setIssuedAt(Date.from(currentTime.toInstant()))
            .setExpiration(Date.from(currentTime.plusSeconds(settings.getRefreshTokenExpTime()).toInstant()))
            .signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey()).compact();

    return new AccessJwtToken(token, claims);
}