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.openlmis.fulfillment.service.OrderServiceTest.java

private void mockResponses() {
    when(programReferenceDataService.findOne(program.getId())).thenReturn(program);
    when(facilityReferenceDataService.findOne(facility.getId())).thenReturn(facility);
    when(periodReferenceDataService.findOne(period1.getId())).thenReturn(period1);
    when(orderableReferenceDataService.findByIds(any())).thenReturn(Collections.singletonList(orderable));

    when(userReferenceDataService.findOne(any())).thenReturn(userDto);

    when(orderNumberConfigurationRepository.findAll())
            .thenReturn(Collections.singletonList(orderNumberConfiguration));

    when(extensionManager.getExtension(OrderNumberGenerator.POINT_ID, OrderNumberGenerator.class))
            .thenReturn(new Base36EncodedOrderNumberGenerator());

    when(transferPropertiesRepository.findFirstByFacilityId(any())).thenReturn(properties);

    when(orderRepository.save(any(Order.class))).thenReturn(order);
    when(orderSender.send(order)).thenReturn(true);

    when(dateHelper.getCurrentDateTimeWithSystemZone()).thenReturn(ZonedDateTime.now());

    when(periodReferenceDataService.search(startDate, endDate)).thenReturn(asList(period1, period2));
}

From source file:org.cgiar.ccafs.marlo.action.summaries.InstitutionsSummaryAction.java

private TypedTableModel getMasterTableModel() {
    // Initialization of Model
    TypedTableModel model = new TypedTableModel(new String[] { "date", "center", "showDescription" },
            new Class[] { String.class, String.class, Boolean.class });
    String center = this.getLoggedCrp().getAcronym();

    ZonedDateTime timezone = ZonedDateTime.now();
    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm ");
    String zone = timezone.getOffset() + "";
    if (zone.equals("Z")) {
        zone = "+0";
    }/*from  ww  w. j  av a 2s.  co m*/
    String date = timezone.format(format) + "(GMT" + zone + ")";
    model.addRow(new Object[] { date, center, this.hasSpecificities(APConstants.CRP_REPORTS_DESCRIPTION) });
    return model;
}

From source file:alfio.manager.WaitingQueueManagerIntegrationTest.java

@Test
public void testAssignTicketToWaitingQueueUnboundedCategorySelected() {
    LocalDateTime start = LocalDateTime.now().minusHours(1);
    LocalDateTime end = LocalDateTime.now().plusHours(1);

    List<TicketCategoryModification> categories = Arrays.asList(
            new TicketCategoryModification(null, "default", AVAILABLE_SEATS,
                    new DateTimeModification(start.toLocalDate(), start.toLocalTime()),
                    new DateTimeModification(end.toLocalDate(), end.toLocalTime()), DESCRIPTION, BigDecimal.TEN,
                    false, "", false, null, null, null, null, null),
            new TicketCategoryModification(null, "default2", AVAILABLE_SEATS,
                    new DateTimeModification(start.toLocalDate(), start.toLocalTime()),
                    new DateTimeModification(end.toLocalDate(), end.toLocalTime()), DESCRIPTION, BigDecimal.TEN,
                    false, "", false, null, null, null, null, null));

    configurationManager.saveSystemConfiguration(ConfigurationKeys.ENABLE_WAITING_QUEUE, "true");

    Event event = initEvent(categories, organizationRepository, userManager, eventManager, eventRepository)
            .getKey();/*w  w  w.  ja v a 2 s .c o  m*/

    List<TicketCategory> ticketCategories = ticketCategoryRepository.findByEventId(event.getId());
    TicketCategory first = ticketCategories.get(0);
    TicketCategory second = ticketCategories.get(1);

    TicketReservationModification tr2 = new TicketReservationModification();
    tr2.setAmount(1);
    tr2.setTicketCategoryId(second.getId());

    TicketReservationModification tr3 = new TicketReservationModification();
    tr3.setAmount(1);
    tr3.setTicketCategoryId(first.getId());

    reserveTickets(event, first, AVAILABLE_SEATS - 2);

    String reservationIdSingleFirst = reserveTickets(event, second, 1);
    String reservationIdSingleSecond = reserveTickets(event, second, 1);

    assertEquals(0, eventRepository.findStatisticsFor(event.getId()).getDynamicAllocation());

    assertTrue(waitingQueueManager.subscribe(event, customerJohnDoe(event), "john@doe.com", first.getId(),
            Locale.ENGLISH));
    assertTrue(waitingQueueManager.subscribe(event, new CustomerName("John Doe 2", "John", "Doe 2", event),
            "john@doe2.com", second.getId(), Locale.ENGLISH));

    ticketReservationManager.deleteOfflinePayment(event, reservationIdSingleFirst, false);
    ticketReservationManager.deleteOfflinePayment(event, reservationIdSingleSecond, false);

    List<Triple<WaitingQueueSubscription, TicketReservationWithOptionalCodeModification, ZonedDateTime>> subscriptions = waitingQueueManager
            .distributeSeats(event).collect(Collectors.toList());
    assertEquals(2, subscriptions.size());
    Triple<WaitingQueueSubscription, TicketReservationWithOptionalCodeModification, ZonedDateTime> subscriptionDetail = subscriptions
            .get(0);
    assertEquals("john@doe.com", subscriptionDetail.getLeft().getEmailAddress());
    TicketReservationWithOptionalCodeModification reservation = subscriptionDetail.getMiddle();
    assertEquals(Integer.valueOf(first.getId()), reservation.getTicketCategoryId());
    assertEquals(Integer.valueOf(1), reservation.getAmount());
    assertTrue(subscriptionDetail.getRight().isAfter(ZonedDateTime.now()));

    subscriptionDetail = subscriptions.get(1);
    assertEquals("john@doe2.com", subscriptionDetail.getLeft().getEmailAddress());
    reservation = subscriptionDetail.getMiddle();
    assertEquals(Integer.valueOf(second.getId()), reservation.getTicketCategoryId());
    assertEquals(Integer.valueOf(1), reservation.getAmount());
    assertTrue(subscriptionDetail.getRight().isAfter(ZonedDateTime.now()));
}

From source file:org.sakaiproject.assignment.impl.AssignmentServiceImpl.java

@Override
public HttpAccess getHttpAccess() {
    return (req, res, ref, copyrightAcceptedRefs) -> {
        if (sessionManager.getCurrentSessionUserId() == null) {
            log.warn("Only logged in users can access assignment downloads");
        } else {/*w  ww  . j av a 2 s .c  om*/
            // determine the type of download to create using the reference that was requested
            AssignmentReferenceReckoner.AssignmentReference refReckoner = AssignmentReferenceReckoner.reckoner()
                    .reference(ref.getReference()).reckon();
            if (REFERENCE_ROOT.equals("/" + refReckoner.getType())) {
                // don't process any references that are not of type assignment
                switch (refReckoner.getSubtype()) {
                case REF_TYPE_CONTENT:
                case REF_TYPE_ASSIGNMENT:
                    String date = DateTimeFormatter.ofPattern("yyyyMMddHHmmss")
                            .withZone(userTimeService.getLocalTimeZone().toZoneId())
                            .format(ZonedDateTime.now());
                    String queryString = req.getQueryString();
                    if (StringUtils.isNotBlank(refReckoner.getId())) {
                        // if subtype is assignment then were downloading all submissions for an assignment
                        try {
                            Assignment a = getAssignment(refReckoner.getId());
                            String filename = a.getTitle() + "_" + date;
                            res.setContentType("application/zip");
                            res.setHeader("Content-Disposition",
                                    "attachment; filename = \"" + filename + ".zip\"");

                            transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                                @Override
                                protected void doInTransactionWithoutResult(TransactionStatus status) {
                                    try (OutputStream out = res.getOutputStream()) {
                                        getSubmissionsZip(out, ref.getReference(), queryString);
                                    } catch (Exception e) {
                                        log.warn("Could not stream the submissions for reference: {}",
                                                ref.getReference(), e);
                                    }
                                }
                            });
                        } catch (Exception e) {
                            log.warn("Could not find assignment for ref = {}", ref.getReference(), e);
                        }
                    } else {
                        String filename = "bulk_download_" + date;
                        // if subtype is assignment and there is no assignmentId then were downloading grades
                        res.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                        res.setHeader("Content-Disposition",
                                "attachment; filename = \"export_grades_" + filename + ".xlsx\"");

                        try (OutputStream out = res.getOutputStream()) {
                            gradeSheetExporter.getGradesSpreadsheet(out, ref.getReference(), queryString);
                        } catch (Exception e) {
                            log.warn("Could not stream the grades for reference: {}", ref.getReference(), e);
                        }
                    }
                    break;
                case REF_TYPE_SUBMISSION:
                default:
                    log.warn("Assignments download unhandled download type for reference: {}",
                            ref.getReference());
                }
            }
        }
    };
}

From source file:org.cgiar.ccafs.marlo.action.center.summaries.ProjectSummaryAction.java

/**
 * Get the main information of the report
 * //from   w  w  w.ja v  a 2 s .c om
 * @return
 */
private TypedTableModel getMasterTableModel() {
    // Initialization of Model
    final TypedTableModel model = new TypedTableModel(
            new String[] { "shortTitle", "currentDate", "projectSubmission", "imageUrl" },
            new Class[] { String.class, String.class, String.class, String.class });
    // Set short title
    String shortTitle = "";
    if ((project.getName() != null) && !project.getName().isEmpty()) {
        shortTitle += project.getName() + " - ";
    }
    if ((loggedCenter.getAcronym() != null) && !loggedCenter.getAcronym().isEmpty()) {
        shortTitle += loggedCenter.getAcronym() + " - ";
    }
    shortTitle += "P" + Long.toString(projectID);

    // Set currentDate
    String currentDate = "";
    // Get datetime
    final ZonedDateTime timezone = ZonedDateTime.now();
    final DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d 'at' HH:mm ");
    currentDate = timezone.format(format) + this.getTimeZone();

    // Set projectSubmission
    final String projectSubmission = "";

    // set CIAT imgage URL from repo

    String imageUrl = this.getBaseUrl() + "/global/images/centers/CIAT.png";

    model.addRow(new Object[] { shortTitle, currentDate, projectSubmission, imageUrl });
    return model;
}

From source file:nu.yona.server.analysis.service.ActivityUpdateServiceTest.java

private ZonedDateTime now() {
    return ZonedDateTime.now().withZoneSameInstant(userAnonZoneId);
}

From source file:org.openlmis.fulfillment.web.OrderControllerIntegrationTest.java

private List<StatusChangeDto> sampleStatusChanges() {
    UserDto user = new UserDto();
    user.setUsername("user");
    user.setId(UUID.randomUUID());

    List<StatusChangeDto> list = new ArrayList<>();

    list.add(new StatusChangeDto(ExternalStatus.INITIATED, user.getId(), ZonedDateTime.now(), user));
    list.add(new StatusChangeDto(ExternalStatus.SUBMITTED, user.getId(), ZonedDateTime.now(), user));
    list.add(new StatusChangeDto(ExternalStatus.AUTHORIZED, user.getId(), ZonedDateTime.now(), user));
    list.add(new StatusChangeDto(ExternalStatus.IN_APPROVAL, user.getId(), ZonedDateTime.now(), user));
    list.add(new StatusChangeDto(ExternalStatus.REJECTED, user.getId(), ZonedDateTime.now(), user));
    list.add(new StatusChangeDto(ExternalStatus.SUBMITTED, user.getId(), ZonedDateTime.now(), user));
    list.add(new StatusChangeDto(ExternalStatus.AUTHORIZED, user.getId(), ZonedDateTime.now(), user));
    list.add(new StatusChangeDto(ExternalStatus.IN_APPROVAL, user.getId(), ZonedDateTime.now(), user));
    list.add(new StatusChangeDto(ExternalStatus.APPROVED, user.getId(), ZonedDateTime.now(), user));

    return list;/*from   ww  w  . ja v a2s .co m*/
}

From source file:org.openhab.binding.darksky.internal.handler.DarkSkyWeatherAndForecastHandler.java

/**
 * Schedules or reschedules a job for the channel with the given id if the given timestamp is in the future.
 *
 * @param channelId id of the channel//from  w w w .  jav a  2s .c  o  m
 * @param dateTime timestamp of the job represented as {@link ZonedDateTime}
 */
@SuppressWarnings("null")
private synchronized void scheduleJob(String channelId, ZonedDateTime dateTime) {
    long delay = dateTime.toEpochSecond() - ZonedDateTime.now().toEpochSecond();
    if (delay > 0) {
        Job job = JOBS.get(channelId);
        if (job == null || job.getFuture().isCancelled()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Schedule job for '{}' in {} s (at '{}').", channelId, delay,
                        dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
            }
            JOBS.put(channelId, new Job(channelId, delay));
        } else {
            if (delay != job.getDelay()) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Reschedule job for '{}' in {} s (at '{}').", channelId, delay,
                            dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
                }
                job.getFuture().cancel(true);
                JOBS.put(channelId, new Job(channelId, delay));
            }
        }
    }
}

From source file:org.eclipse.smarthome.ui.internal.items.ItemUIRegistryImpl.java

private boolean matchStateToValue(State state, String value, String matchCondition) {
    // Check if the value is equal to the supplied value
    boolean matched = false;

    // Remove quotes - this occurs in some instances where multiple types
    // are defined in the xtext definitions
    String unquotedValue = value;
    if (unquotedValue.startsWith("\"") && unquotedValue.endsWith("\"")) {
        unquotedValue = unquotedValue.substring(1, unquotedValue.length() - 1);
    }//from   w ww. j a  v a2 s.co m

    // Convert the condition string into enum
    Condition condition = Condition.EQUAL;
    if (matchCondition != null) {
        condition = Condition.fromString(matchCondition);
        if (condition == null) {
            logger.warn("matchStateToValue: unknown match condition '{}'", matchCondition);
            return matched;
        }
    }

    if (unquotedValue.equals(UnDefType.NULL.toString()) || unquotedValue.equals(UnDefType.UNDEF.toString())) {
        switch (condition) {
        case EQUAL:
            if (unquotedValue.equals(state.toString())) {
                matched = true;
            }
            break;
        case NOT:
        case NOTEQUAL:
            if (!unquotedValue.equals(state.toString())) {
                matched = true;
            }
            break;
        default:
            break;
        }
    } else {
        if (state instanceof DecimalType || state instanceof QuantityType<?>) {
            try {
                double compareDoubleValue = Double.parseDouble(unquotedValue);
                double stateDoubleValue;
                if (state instanceof DecimalType) {
                    stateDoubleValue = ((DecimalType) state).doubleValue();
                } else {
                    stateDoubleValue = ((QuantityType<?>) state).doubleValue();
                }
                switch (condition) {
                case EQUAL:
                    if (stateDoubleValue == compareDoubleValue) {
                        matched = true;
                    }
                    break;
                case LTE:
                    if (stateDoubleValue <= compareDoubleValue) {
                        matched = true;
                    }
                    break;
                case GTE:
                    if (stateDoubleValue >= compareDoubleValue) {
                        matched = true;
                    }
                    break;
                case GREATER:
                    if (stateDoubleValue > compareDoubleValue) {
                        matched = true;
                    }
                    break;
                case LESS:
                    if (stateDoubleValue < compareDoubleValue) {
                        matched = true;
                    }
                    break;
                case NOT:
                case NOTEQUAL:
                    if (stateDoubleValue != compareDoubleValue) {
                        matched = true;
                    }
                    break;
                }
            } catch (NumberFormatException e) {
                logger.debug("matchStateToValue: Decimal format exception: ", e);
            }
        } else if (state instanceof DateTimeType) {
            ZonedDateTime val = ((DateTimeType) state).getZonedDateTime();
            ZonedDateTime now = ZonedDateTime.now();
            long secsDif = ChronoUnit.SECONDS.between(val, now);

            try {
                switch (condition) {
                case EQUAL:
                    if (secsDif == Integer.parseInt(unquotedValue)) {
                        matched = true;
                    }
                    break;
                case LTE:
                    if (secsDif <= Integer.parseInt(unquotedValue)) {
                        matched = true;
                    }
                    break;
                case GTE:
                    if (secsDif >= Integer.parseInt(unquotedValue)) {
                        matched = true;
                    }
                    break;
                case GREATER:
                    if (secsDif > Integer.parseInt(unquotedValue)) {
                        matched = true;
                    }
                    break;
                case LESS:
                    if (secsDif < Integer.parseInt(unquotedValue)) {
                        matched = true;
                    }
                    break;
                case NOT:
                case NOTEQUAL:
                    if (secsDif != Integer.parseInt(unquotedValue)) {
                        matched = true;
                    }
                    break;
                }
            } catch (NumberFormatException e) {
                logger.debug("matchStateToValue: Decimal format exception: ", e);
            }
        } else {
            // Strings only allow = and !=
            switch (condition) {
            case NOT:
            case NOTEQUAL:
                if (!unquotedValue.equals(state.toString())) {
                    matched = true;
                }
                break;
            default:
                if (unquotedValue.equals(state.toString())) {
                    matched = true;
                }
                break;
            }
        }
    }

    return matched;
}

From source file:alfio.manager.EventManagerIntegrationTest.java

@Test
public void testNewBoundedCategoryWithExistingBoundedAndPendingTicket() {
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", AVAILABLE_SEATS, new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            false, null, null, null, null, null));
    Pair<Event, String> pair = initEvent(categories, organizationRepository, userManager, eventManager,
            eventRepository);/* w  w  w .j a  v  a 2 s.co m*/
    Event event = pair.getLeft();
    String username = pair.getRight();
    assertEquals(new Integer(AVAILABLE_SEATS), ticketRepository.countFreeTicketsForUnbounded(event.getId()));
    TicketReservationModification trm = new TicketReservationModification();
    trm.setAmount(1);
    trm.setTicketCategoryId(ticketCategoryRepository.findByEventId(event.getId()).get(0).getId());
    TicketReservationWithOptionalCodeModification reservation = new TicketReservationWithOptionalCodeModification(
            trm, Optional.empty());
    ticketReservationManager.createTicketReservation(event, Collections.singletonList(reservation),
            Collections.emptyList(), DateUtils.addDays(new Date(), 1), Optional.empty(), Optional.empty(),
            Locale.ENGLISH, false);
    TicketCategoryModification tcm = new TicketCategoryModification(null, "new", 1,
            DateTimeModification.fromZonedDateTime(ZonedDateTime.now()),
            DateTimeModification.fromZonedDateTime(ZonedDateTime.now().plusDays(1)), Collections.emptyMap(),
            BigDecimal.TEN, false, "", true, null, null, null, null, null);
    Result<Integer> insertResult = eventManager.insertCategory(event, tcm, username);
    assertTrue(insertResult.isSuccess());
    Integer categoryID = insertResult.getData();
    tcm = new TicketCategoryModification(categoryID, tcm.getName(), AVAILABLE_SEATS, tcm.getInception(),
            tcm.getExpiration(), tcm.getDescription(), tcm.getPrice(), false, "", true, null, null, null, null,
            null);
    Result<TicketCategory> result = eventManager.updateCategory(categoryID, event, tcm, username);
    assertFalse(result.isSuccess());
}