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:com.epam.reportportal.auth.integration.github.GitHubUserReplicator.java

public User synchronizeUser(String accessToken) {
    GitHubClient gitHubClient = GitHubClient.withAccessToken(accessToken);
    UserResource userInfo = gitHubClient.getUser();
    User user = userRepository.findOne(EntityUtils.normalizeUsername(userInfo.login));
    BusinessRule.expect(user, Objects::nonNull).verify(ErrorType.USER_NOT_FOUND, userInfo.login);
    BusinessRule.expect(user.getType(), userType -> Objects.equals(userType, UserType.GITHUB)).verify(
            ErrorType.INCORRECT_AUTHENTICATION_TYPE, "User '" + userInfo.login + "' is not GitHUB user");
    user.setFullName(userInfo.name);//from   w w w  .ja va  2  s.co  m
    user.getMetaInfo().setSynchronizationDate(Date.from(ZonedDateTime.now().toInstant()));

    String newPhotoId = uploadAvatar(gitHubClient, userInfo.name, userInfo.avatarUrl);
    if (!Strings.isNullOrEmpty(newPhotoId)) {
        dataStorage.deleteData(user.getPhotoId());
        user.setPhotoId(newPhotoId);
    }
    userRepository.save(user);
    return user;
}

From source file:org.codice.ddf.registry.federationadmin.service.impl.RegistryPublicationServiceImpl.java

@Override
public void publish(String registryId, String destinationRegistryId) throws FederationAdminException {
    Metacard metacard = getMetacard(registryId);
    String metacardId = metacard.getId();

    List<String> locations = RegistryUtility.getListOfStringAttribute(metacard,
            RegistryObjectMetacardType.PUBLISHED_LOCATIONS);

    if (locations.contains(destinationRegistryId)) {
        return;//from   ww w .  j a  va  2s  . c  o m
    }

    String sourceId = getSourceIdFromRegistryId(destinationRegistryId);
    if (sourceId == null) {
        throw new FederationAdminException(
                "Could not find a source id for registry-id " + destinationRegistryId);
    }

    LOGGER.info("Publishing registry entry {}:{} to {}", metacard.getTitle(), registryId, sourceId);

    federationAdminService.addRegistryEntry(metacard, Collections.singleton(sourceId));

    // need to reset the id since the framework reset it in the groomer plugin
    // and we don't want to update with the wrong id
    metacard.setAttribute(new AttributeImpl(Metacard.ID, metacardId));

    locations.add(destinationRegistryId);
    locations.remove(NO_PUBLICATIONS);

    ArrayList<String> locArr = new ArrayList<>(locations);

    metacard.setAttribute(new AttributeImpl(RegistryObjectMetacardType.PUBLISHED_LOCATIONS, locArr));
    metacard.setAttribute(new AttributeImpl(RegistryObjectMetacardType.LAST_PUBLISHED,
            Date.from(ZonedDateTime.now().toInstant())));

    federationAdminService.updateRegistryEntry(metacard);
}

From source file:org.openlmis.fulfillment.web.validator.ProofOfDeliveryValidatorTest.java

@Before
public void setUp() throws Exception {
    FieldUtils.writeField(messageService, "messageSource", messageSource, true);

    line = new ProofOfDeliveryLineItem();
    line.setQuantityReceived(10L);/*from ww  w . ja  va2  s.com*/

    pod = new ProofOfDelivery();
    pod.setDeliveredBy("Deliver guy");
    pod.setReceivedBy("Receiver");
    pod.setReceivedDate(ZonedDateTime.now());
    pod.setProofOfDeliveryLineItems(Lists.newArrayList(line));

    mockMessageSource(VALIDATION_ERROR_MUST_CONTAIN_VALUE, DELIVERED_BY, MUST_CONTAIN_A_VALUE);
    mockMessageSource(VALIDATION_ERROR_MUST_CONTAIN_VALUE, RECEIVED_BY, MUST_CONTAIN_A_VALUE);
    mockMessageSource(VALIDATION_ERROR_MUST_CONTAIN_VALUE, RECEIVED_DATE, MUST_CONTAIN_A_VALUE);
    mockMessageSource(VALIDATION_ERROR_MUST_CONTAIN_VALUE,
            PROOF_OF_DELIVERY_LINE_ITEMS + '.' + QUANTITY_RECEIVED, MUST_CONTAIN_A_VALUE);
    mockMessageSource(VALIDATION_ERROR_MUST_BE_GREATER_THAN_OR_EQUAL_TO_ZERO,
            PROOF_OF_DELIVERY_LINE_ITEMS + '.' + QUANTITY_RECEIVED,
            MUST_CONTAIN_A_VALUE_THAT_IS_GREATER_THAN_OR_EQUAL_TO_ZERO);
}

From source file:org.openhab.binding.buienradar.internal.BuienradarHandler.java

private void refresh() {
    try {//from w  w w .j a v a  2  s . c o  m
        @SuppressWarnings("null")
        final List<Prediction> predictions = client.getPredictions(location);
        for (final Prediction prediction : predictions) {
            final BigDecimal intensity = prediction.getIntensity();
            final ZonedDateTime nowPlusThree = ZonedDateTime.now().plusMinutes(3);
            final ZonedDateTime lastFiveMinute = nowPlusThree.withMinute((nowPlusThree.getMinute() / 5) * 5)
                    .withSecond(0).withNano(0);
            final long minutesFromNow = lastFiveMinute.until(prediction.getDateTime(), ChronoUnit.MINUTES);
            final long minuteClass = minutesFromNow;
            logger.debug("Forecast for {} at {} is {}", minutesFromNow, prediction.getDateTime(), intensity);
            if (minuteClass >= 0 && minuteClass <= 115) {
                final String label = String.format(Locale.ENGLISH, "forecast_%d", minuteClass);

                /** @TODO: edejong 2019-04-03 Change to SmartHomeUnits.MILLIMETRE_PER_HOUR for OH 2.5 */
                updateState(label, new QuantityType<Speed>(intensity, MILLIMETRE_PER_HOUR));
            }
        }

        updateStatus(ThingStatus.ONLINE);
    } catch (IOException e) {
        logger.warn("Cannot retrieve predictions", e);
        updateStatus(ThingStatus.ONLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                String.format("Could not reach buienradar: %s", e.getMessage()));
    }
}

From source file:org.mascherl.example.service.SendMailService.java

@Transactional
public void sendMailFromSystem(Mail mail) {
    if (mail.getTo() == null || mail.getTo().isEmpty()) {
        throw new IllegalArgumentException("Receiver list cannot be empty");
    }/*from   ww w  .j  av  a 2 s  . c o  m*/

    ZonedDateTime sendTime = ZonedDateTime.now();

    List<String> receiveUserUuids = findReceiveUserUuids(mail);
    for (String receiveUserUuid : receiveUserUuids) {
        MailEntity receiveEntity = new MailEntity(MailType.RECEIVED);
        receiveEntity.setUser(em.getReference(UserEntity.class, receiveUserUuid));
        receiveEntity.setDateTime(sendTime);
        receiveEntity.setUnread(true);
        receiveEntity.setFrom(mail.getFrom());
        receiveEntity.setTo(mail.getTo());
        receiveEntity.setCc(mail.getCc());
        receiveEntity.setBcc(mail.getBcc());
        receiveEntity.setSubject(mail.getSubject());
        receiveEntity.setMessageText(mail.getMessageText());
        em.persist(receiveEntity);
    }

    em.flush();
}

From source file:com.sdl.odata.renderer.atom.AtomRenderer.java

protected AtomWriter initAtomWriter(ODataRequestContext requestContext) {
    return new AtomWriter(ZonedDateTime.now(), requestContext.getUri(), requestContext.getEntityDataModel(),
            new ODataV4AtomNSConfigurationProvider(), isWriteOperation(requestContext),
            isActionCallUri(requestContext.getUri()));
}

From source file:com.netflix.spinnaker.gate.ratelimit.RateLimitingInterceptor.java

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
    // Hystrix et-al can return 429's, which we'll want to intercept to provide a reset header
    if (response.getStatus() == 429 && !response.getHeaderNames().contains(Rate.RESET_HEADER)) {
        response.setIntHeader(Rate.CAPACITY_HEADER, -1);
        response.setIntHeader(Rate.REMAINING_HEADER, 0);
        response.setDateHeader(Rate.RESET_HEADER, ZonedDateTime.now().plusSeconds(5).toEpochSecond());
        response.setHeader(Rate.LEARNING_HEADER, "false");
    }//from   w  ww .  j  ava2  s . c  o m
}

From source file:com.github.ibm.domino.client.CalendarClientTest.java

@Test
public void test9DeleteEvents() {
    System.out.println("deleteEvents");
    DominoRestClient instance = initClient();
    java.util.Calendar calendar = java.util.Calendar.getInstance();

    List<String> eventIds = new ArrayList<>();
    eventIds.add("EvEnTiD...wE...DO..not...EXPECT...to...FIND...EVER!!!");
    List<String> eventsNotDeleted = instance.deleteEvent(eventIds);
    assertTrue(eventsNotDeleted.size() == 1);

    instance.since(ZonedDateTime.now().minusHours(1));
    List<CalendarEvent> result = instance.getEvents();

    eventIds.clear();/*  www. ja v a2 s .  c o m*/
    result.stream().forEach((calendarEvent) -> {
        eventIds.add(calendarEvent.getId());
    });
    eventsNotDeleted = instance.deleteEvent(eventIds);
    assertTrue(eventsNotDeleted.isEmpty());
}

From source file:sorcer.file.ScratchDirManager.java

private boolean isCutoffTime(Path path, long cutOffTime) throws IOException {
    ZonedDateTime now = ZonedDateTime.now();
    BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
    ZonedDateTime created = ZonedDateTime.ofInstant(attrs.creationTime().toInstant(), now.getZone());

    created = created.withYear(now.getYear()).withMonth(now.getMonthValue());

    ZonedDateTime cutoff = created.plus(cutOffTime, MILLIS);

    log.info("Created {}", created);
    log.info("now     {}", now);
    log.info("cutoff  {}", cutoff);

    return now.isAfter(cutoff);
}

From source file:alfio.manager.PaymentManager.java

/**
 * This method processes the pending payment using the configured payment gateway (at the time of writing, only STRIPE)
 * and returns a PaymentResult./*from ww w .  j a  v  a 2s. c  o  m*/
 * In order to preserve the consistency of the payment, when a non-gateway Exception is thrown, it rethrows an IllegalStateException
 *
 * @param reservationId
 * @param gatewayToken
 * @param price
 * @param event
 * @param email
 * @param customerName
 * @param billingAddress
 * @return PaymentResult
 * @throws java.lang.IllegalStateException if there is an error after charging the credit card
 */
PaymentResult processStripePayment(String reservationId, String gatewayToken, int price, Event event,
        String email, CustomerName customerName, String billingAddress) {
    try {
        final Optional<Charge> optionalCharge = stripeManager.chargeCreditCard(gatewayToken, price, event,
                reservationId, email, customerName.getFullName(), billingAddress);
        return optionalCharge.map(charge -> {
            log.info("transaction {} paid: {}", reservationId, charge.getPaid());
            Pair<Long, Long> fees = Optional.ofNullable(charge.getBalanceTransactionObject()).map(bt -> {
                List<Fee> feeDetails = bt.getFeeDetails();
                return Pair.of(
                        Optional.ofNullable(StripeManager.getFeeAmount(feeDetails, "application_fee"))
                                .map(Long::parseLong).orElse(0L),
                        Optional.ofNullable(StripeManager.getFeeAmount(feeDetails, "stripe_fee"))
                                .map(Long::parseLong).orElse(0L));
            }).orElse(null);

            transactionRepository.insert(charge.getId(), null, reservationId, ZonedDateTime.now(), price,
                    event.getCurrency(), charge.getDescription(), PaymentProxy.STRIPE.name(),
                    fees != null ? fees.getLeft() : 0L, fees != null ? fees.getRight() : 0L);
            return PaymentResult.successful(charge.getId());
        }).orElseGet(() -> PaymentResult.unsuccessful("error.STEP2_UNABLE_TO_TRANSITION"));
    } catch (Exception e) {
        if (e instanceof StripeException) {
            return PaymentResult.unsuccessful(stripeManager.handleException((StripeException) e));
        }
        throw new IllegalStateException(e);
    }

}