Example usage for java.time LocalDate now

List of usage examples for java.time LocalDate now

Introduction

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

Prototype

public static LocalDate now() 

Source Link

Document

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

Usage

From source file:alfio.manager.EventManagerIntegrationTest.java

@Test
public void testDecreaseRestrictedCategory() {
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", 10, new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()),

            DESCRIPTION, BigDecimal.TEN, true, "", true, null, null, null, null, null));
    Pair<Event, String> pair = initEvent(categories, organizationRepository, userManager, eventManager,
            eventRepository);//from   w  w w  . j  a  v  a2  s . c  o m

    Event event = pair.getLeft();
    String username = pair.getRight();

    TicketCategory category = ticketCategoryRepository.findByEventId(event.getId()).get(0);
    Map<String, String> categoryDescription = ticketCategoryDescriptionRepository
            .descriptionForTicketCategory(category.getId());

    TicketCategoryModification tcm = new TicketCategoryModification(category.getId(), category.getName(), 9,
            DateTimeModification.fromZonedDateTime(category.getUtcInception()),
            DateTimeModification.fromZonedDateTime(category.getUtcExpiration()), categoryDescription,
            category.getPrice(), true, "", true, null, null, null, null, null);
    Result<TicketCategory> result = eventManager.updateCategory(category.getId(), event, tcm, username);
    assertTrue(result.isSuccess());
    assertEquals(9, ticketRepository.countFreeTickets(event.getId(), category.getId()).intValue());
    assertEquals(1, ticketRepository.countReleasedUnboundedTickets(event.getId()).intValue());
}

From source file:org.silverpeas.core.webapi.calendar.CalendarWebManager.java

/**
 * Gets the next event occurrences from now.
 * @param componentIds identifiers of aimed component instance.
 * @param calendarIdsToExclude identifier of calendars which linked occurrences must be excluded
 * from the result.// ww w .  ja v  a  2  s .co  m
 * @param usersToInclude identifiers of users which linked occurrences must be included into the
 * result
 * @param calendarIdsToInclude identifier of calendars which linked occurrences must be included
 * into the result.
 * @param zoneId the identifier of the zone.
 * @param limit the maximum occurrences the result must have (must be lower than 500)
 * @return a list of {@link CalendarEventOccurrence}.
 */
public Stream<CalendarEventOccurrence> getNextEventOccurrences(final List<String> componentIds,
        final Set<String> calendarIdsToExclude, final Set<User> usersToInclude,
        final Set<String> calendarIdsToInclude, final ZoneId zoneId, final Integer limit) {
    final User currentRequester = User.getCurrentRequester();
    // load calendars
    final List<Calendar> calendars = componentIds.stream().flatMap(i -> getCalendarsHandledBy(i).stream())
            .distinct().collect(Collectors.toList());
    // includes/excludes
    calendarIdsToInclude.removeAll(calendarIdsToExclude);
    calendars.removeIf(c -> calendarIdsToExclude.contains(c.getId()));
    if (!calendarIdsToInclude.isEmpty()) {
        calendars.forEach(c -> calendarIdsToInclude.remove(c.getId()));
        calendarIdsToInclude.forEach(i -> {
            Calendar calendarToInclude = Calendar.getById(i);
            if (calendarToInclude.canBeAccessedBy(currentRequester)) {
                calendars.add(calendarToInclude);
            }
        });
    }
    // loading occurrences
    final int nbOccLimit = (limit != null && limit > 0 && limit <= 500) ? limit : DEFAULT_NB_MAX_NEXT_OCC;
    final LocalDate startDate = zoneId != null ? LocalDateTime.now(zoneId).toLocalDate() : LocalDate.now();
    final Set<CalendarEventOccurrence> occurrences = new HashSet<>();
    for (int nbMonthsToAdd : getNextEventTimeWindows()) {
        occurrences.clear();
        LocalDate endDate = startDate.plusMonths(nbMonthsToAdd);
        occurrences.addAll(getEventOccurrencesOf(startDate, endDate, calendars));
        if (!usersToInclude.isEmpty()) {
            getAllEventOccurrencesByUserIds(Pair.of(componentIds, currentRequester), startDate, endDate,
                    usersToInclude).forEach((u, o) -> occurrences.addAll(o));
        }
        if (occurrences.size() >= nbOccLimit) {
            break;
        }
    }
    return occurrences.stream().sorted(COMPARATOR_BY_DATE_ASC).limit(nbOccLimit);
}

From source file:alfio.manager.EventManagerIntegrationTest.java

@Test
public void testDecreaseRestrictedCategoryWithAlreadySentToken() {

    ensureMinimalConfiguration(configurationRepository);

    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", 4, new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()),

            DESCRIPTION, BigDecimal.TEN, true, "", true, null, null, null, null, null));
    Pair<Event, String> pair = initEvent(categories, organizationRepository, userManager, eventManager,
            eventRepository);/*from w w w. ja va2 s.c  o  m*/

    Event event = pair.getLeft();
    String username = pair.getRight();

    TicketCategory category = ticketCategoryRepository.findByEventId(event.getId()).get(0);
    Map<String, String> categoryDescription = ticketCategoryDescriptionRepository
            .descriptionForTicketCategory(category.getId());

    specialPriceTokenGenerator.generatePendingCodesForCategory(category.getId());

    List<SendCodeModification> linked = specialPriceManager.linkAssigneeToCode(
            Arrays.asList(new SendCodeModification(null, "test1", "test@test.com", "it"),
                    new SendCodeModification(null, "test2", "test@test.com", "it")),
            event.getShortName(), category.getId(), username);

    specialPriceManager.sendCodeToAssignee(linked, event.getShortName(), category.getId(), username);

    TicketCategoryModification tcmOk = new TicketCategoryModification(category.getId(), category.getName(), 2,
            DateTimeModification.fromZonedDateTime(category.getUtcInception()),
            DateTimeModification.fromZonedDateTime(category.getUtcExpiration()), categoryDescription,
            category.getPrice(), true, "", true, null, null, null, null, null);
    Result<TicketCategory> resOk = eventManager.updateCategory(category.getId(), event, tcmOk, username);
    Assert.assertTrue(resOk.isSuccess());

    TicketCategoryModification tcm = new TicketCategoryModification(category.getId(), category.getName(), 1,
            DateTimeModification.fromZonedDateTime(category.getUtcInception()),
            DateTimeModification.fromZonedDateTime(category.getUtcExpiration()), categoryDescription,
            category.getPrice(), true, "", true, null, null, null, null, null);
    Result<TicketCategory> res = eventManager.updateCategory(category.getId(), event, tcm, username);
    Assert.assertFalse(res.isSuccess());
    Assert.assertTrue(res.getErrors().contains(ErrorCode.CategoryError.NOT_ENOUGH_FREE_TOKEN_FOR_SHRINK));
}

From source file:gov.va.isaac.gui.preferences.plugins.ViewCoordinatePreferencesPluginViewController.java

public Region getContent() {
    Task<Void> task = new Task<Void>() {
        @Override//from www  .jav a2s .c o m
        protected Void call() throws Exception {
            log.debug("initializing content");

            try {
                if (!contentLoaded) {
                    contentLoaded = true;

                    // Populate selectableModules
                    final ConceptVersionBI moduleRootConcept = OTFUtility.getConceptVersion(
                            IsaacMetadataAuxiliaryBinding.MODULE.getPrimodialUuid(), panelViewCoordinate);
                    final Set<ConceptVersionBI> moduleConcepts = new HashSet<>();
                    try {
                        moduleConcepts.addAll(OTFUtility.getAllChildrenOfConcept(moduleRootConcept.getNid(),
                                panelViewCoordinate, false));
                    } catch (Exception e) {
                        log.error("Failed loading module concepts as children of " + moduleRootConcept, e);
                        e.printStackTrace();
                        AppContext.getCommonDialogs()
                                .showErrorDialog("Failed loading module concepts as children of "
                                        + moduleRootConcept + ". See logs.", e);
                    }
                    List<SelectableModule> modules = new ArrayList<>();
                    for (ConceptVersionBI cv : moduleConcepts) {
                        modules.add(new SelectableModule(cv.getNid()));
                    }
                    selectableModules.clear();
                    selectableModules.addAll(modules);

                    allModulesMarker.selected.addListener((observable, oldValue, newValue) -> {
                        if (newValue) {
                            for (SelectableModule module : selectableModules) {
                                module.selectedProperty().set(false);
                            }
                        }
                    });
                    selectableModules.forEach(selectableModule -> selectableModule.selectedProperty()
                            .addListener((observable, wasSelected, isSelected) -> {
                                if (isSelected) {
                                    if (!wasSelected) {
                                        //log.debug("Adding module nid={}, uuid={}, desc={}", selectableModule.getNid(), selectableModule.getUuid(), selectableModule.getDescription());
                                        selectedModules.add(selectableModule.getUuid());
                                        allModulesMarker.selectedProperty().set(false);
                                    }
                                } else {
                                    if (wasSelected) {
                                        //log.debug("Removing module nid={}, uuid={}, desc={}", selectableModule.getNid(), selectableModule.getUuid(), selectableModule.getDescription());
                                        selectedModules.remove(selectableModule.getUuid());

                                        if (selectedModules.size() == 0) {
                                            allModulesMarker.selectedProperty().set(true);
                                        }
                                    }
                                }
                            }));
                    selectableModuleListView.getItems().clear();
                    selectableModuleListView.getItems().add(allModulesMarker);
                    Collections.sort(selectableModules);
                    selectableModuleListView.getItems().addAll(selectableModules);

                    runLaterIfNotFXApplicationThread(
                            () -> pathComboBox.setTooltip(new Tooltip("Default path is \""
                                    + OTFUtility.getDescription(getDefaultPath(), panelViewCoordinate)
                                    + "\"")));

                    pathComboBox.getItems().clear();
                    pathComboBox.getItems().addAll(getPathOptions());
                }

                // Reload persisted values every time

                UserProfile loggedIn = ExtendedAppContext.getCurrentlyLoggedInUserProfile();
                pathComboBox.getSelectionModel().select(loggedIn.getViewCoordinatePath());

                // Reload storedStatedInferredOption
                loadStoredStatedInferredOption();

                // Reload storedStatuses
                loadStoredStatuses();

                // Reload storedModules
                final Set<UUID> storedModuleUuids = getStoredModules();
                if (storedModuleUuids.size() == 0) {
                    allModulesMarker.setSelected(true);
                } else {
                    // Check to make sure that stored UUID refers to an existing, known module
                    for (UUID storedModuleUuid : storedModuleUuids) {
                        boolean foundStoredUuidModuleInSelectableModules = false;
                        for (SelectableModule selectableModule : selectableModules) {
                            if (storedModuleUuid.equals(selectableModule.getUuid())) {
                                foundStoredUuidModuleInSelectableModules = true;
                                break;
                            }
                        }

                        if (!foundStoredUuidModuleInSelectableModules) {
                            log.error(
                                    "Loaded module (uuid={}) from user preferences that does not currently exist",
                                    storedModuleUuid);
                            AppContext.getCommonDialogs().showErrorDialog("Unsupported Module",
                                    "Loaded a module UUID from UserProfile that does not correspond to existing module",
                                    "Concept (UUID=" + storedModuleUuid
                                            + ") not a valid module.  Must be one of "
                                            + Arrays.toString(selectableModules.toArray()));
                        }
                    }
                    for (SelectableModule module : selectableModules) {
                        if (storedModuleUuids.contains(module.getUuid())) {
                            module.setSelected(true);
                        } else {
                            module.setSelected(false);
                        }
                    }
                }

                Long storedTime = getStoredTime();
                if (storedTime.equals(Long.MAX_VALUE)) {
                    dateSelectionMethodComboBox.getSelectionModel().select(DateSelectionMethod.USE_LATEST);
                    currentTimeProperty.set(Long.MAX_VALUE);
                    runLaterIfNotFXApplicationThread(() -> datePicker.setValue(LocalDate.now()));
                } else {
                    dateSelectionMethodComboBox.getSelectionModel().select(DateSelectionMethod.SPECIFY);
                    currentTimeProperty.set(storedTime);
                    setDatePickerFromCurrentTimeProperty();
                }

                return null;
            } catch (Exception e) {
                log.error("initContent() task caught " + e.getClass().getName() + " " + e.getLocalizedMessage(),
                        e);
                e.printStackTrace();
                throw e;
            }
        }

        @Override
        protected void succeeded() {
            log.debug("Content initialization succeeded");

            removeProgressIndicator();
        }

        @Override
        protected void failed() {
            removeProgressIndicator();

            Throwable ex = getException();
            log.error("loadContent() caught " + ex.getClass().getName() + " " + ex.getLocalizedMessage(), ex);
            AppContext.getCommonDialogs().showErrorDialog("Failed loading content. See logs.", ex);
        }
    };

    addProgressIndicator();

    Utility.execute(task);

    return gridPaneInRootStackPane;
}

From source file:jef.tools.DateUtils.java

/**
 * Convert LocalTime to jud./*from  w  ww.j av a2s .  c o m*/
 * 
 * @param time
 *            LocalTime
 * @return java.util.Date
 */
public static Date fromLocalTime(LocalTime time) {
    return time == null ? null
            : Date.from(LocalDateTime.of(LocalDate.now(), time).atZone(ZoneId.systemDefault()).toInstant());
}

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);//from ww w .j a  va  2s  .c  om
    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());
}

From source file:jef.tools.DateUtils.java

/**
 * Converts LocalTime to Timestamp (null safety)
 * @param localTime LocalTime//from  w  w w  . j  a  v  a  2s  .co m
 * @return Timestamp
 */
public static Timestamp toSqlTimeStamp(LocalTime localTime) {
    return localTime == null ? null : java.sql.Timestamp.valueOf(LocalDateTime.of(LocalDate.now(), localTime));
}

From source file:alfio.manager.EventManagerIntegrationTest.java

private Pair<Event, String> generateAndEditEvent(int newEventSize) {
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", 10, new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            true, null, null, null, null, null));
    Pair<Event, String> pair = initEvent(categories, organizationRepository, userManager, eventManager,
            eventRepository);/*from  w w  w. j av  a2s . c o m*/

    Event event = pair.getKey();
    if (newEventSize != AVAILABLE_SEATS) {
        EventModification update = new EventModification(event.getId(), Event.EventType.INTERNAL, null, null,
                null, null, null, null, null, event.getOrganizationId(), null, null, null,
                event.getZoneId().toString(), Collections.emptyMap(),
                DateTimeModification.fromZonedDateTime(event.getBegin()),
                DateTimeModification.fromZonedDateTime(event.getEnd()), event.getRegularPrice(),
                event.getCurrency(), newEventSize, event.getVat(), event.isVatIncluded(),
                event.getAllowedPaymentProxies(), null, event.isFreeOfCharge(), null, 7, null, null);
        eventManager.updateEventPrices(event, update, pair.getValue());
    }
    List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
    assertNotNull(tickets);
    assertFalse(tickets.isEmpty());
    assertEquals(AVAILABLE_SEATS, tickets.size());
    if (newEventSize > AVAILABLE_SEATS) {
        assertEquals(newEventSize - AVAILABLE_SEATS,
                ticketRepository.countReleasedUnboundedTickets(event.getId()).intValue());
    }
    assertEquals(10, tickets.stream().filter(t -> t.getCategoryId() != null).count());
    return Pair.of(eventRepository.findById(event.getId()), pair.getRight());
}

From source file:org.apache.james.jmap.methods.integration.GetMessageListMethodTest.java

@Test
public void getMessageListShouldSortMessagesWhenSortedByDateDefault() throws Exception {
    mailboxProbe.createMailbox(MailboxConstants.USER_NAMESPACE, username, "mailbox");

    LocalDate date = LocalDate.now();
    ComposedMessageId message1 = mailboxProbe.appendMessage(username,
            new MailboxPath(MailboxConstants.USER_NAMESPACE, username, "mailbox"),
            new ByteArrayInputStream("Subject: test\r\n\r\ntestmail".getBytes()),
            convertToDate(date.plusDays(1)), false, new Flags());
    ComposedMessageId message2 = mailboxProbe.appendMessage(username,
            new MailboxPath(MailboxConstants.USER_NAMESPACE, username, "mailbox"),
            new ByteArrayInputStream("Subject: test2\r\n\r\ntestmail".getBytes()), convertToDate(date), false,
            new Flags());
    await();/*  w ww.j  a v  a 2 s  .c o m*/

    given().header("Authorization", accessToken.serialize())
            .body("[[\"getMessageList\", {\"sort\":[\"date\"]}, \"#0\"]]").when().post("/jmap").then()
            .statusCode(200).body(NAME, equalTo("messageList")).body(ARGUMENTS + ".messageIds",
                    contains(message1.getMessageId().serialize(), message2.getMessageId().serialize()));
}

From source file:org.apache.james.jmap.methods.integration.GetMessageListMethodTest.java

@Test
public void getMessageListShouldSortMessagesWhenSortedByDateAsc() throws Exception {
    mailboxProbe.createMailbox(MailboxConstants.USER_NAMESPACE, username, "mailbox");

    LocalDate date = LocalDate.now();
    ComposedMessageId message1 = mailboxProbe.appendMessage(username,
            new MailboxPath(MailboxConstants.USER_NAMESPACE, username, "mailbox"),
            new ByteArrayInputStream("Subject: test\r\n\r\ntestmail".getBytes()),
            convertToDate(date.plusDays(1)), false, new Flags());
    ComposedMessageId message2 = mailboxProbe.appendMessage(username,
            new MailboxPath(MailboxConstants.USER_NAMESPACE, username, "mailbox"),
            new ByteArrayInputStream("Subject: test2\r\n\r\ntestmail".getBytes()), convertToDate(date), false,
            new Flags());
    await();/*from w ww  . j  a  v a2s .  co  m*/

    given().header("Authorization", accessToken.serialize())
            .body("[[\"getMessageList\", {\"sort\":[\"date asc\"]}, \"#0\"]]").when().post("/jmap").then()
            .statusCode(200).body(NAME, equalTo("messageList")).body(ARGUMENTS + ".messageIds",
                    contains(message2.getMessageId().serialize(), message1.getMessageId().serialize()));
}