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:demo.admin.controller.UserController.java

@RequestMapping(value = "/user/downloadData")
@VerifyAuthentication(Trader = true, Admin = true, Operation = true)
public HttpEntity<byte[]> downloadUserData(String status, String securephone,
        @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
        @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate)
        throws IOException, DocumentException {
    if (securephone != null && securephone != "") {
        securephone = Where.$like$(securephone);
    }/*from  w w w  .ja va  2  s .  c o  m*/
    List<Map<String, Object>> users = userMapper.userExport(status, securephone, startDate, endDate);
    String type = status + "?";
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet(type);
    HSSFRow row = sheet.createRow(0);
    CellStyle cellStyle = wb.createCellStyle();
    cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
    cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);

    sheet.setVerticallyCenter(true);
    sheet.setHorizontallyCenter(true);
    String[] excelHeader = { "??", "???", "??", "", "??" };
    for (int i = 0; i < excelHeader.length; i++) {
        HSSFCell cell = row.createCell(i);
        cell.setCellValue(excelHeader[i]);
        cell.setCellStyle(cellStyle);
        sheet.autoSizeColumn(i, true);
    }
    for (int i = 0; i < users.size(); i++) {
        Map<String, Object> resultSet = users.get(i);
        sheet.autoSizeColumn(i, true);
        row = sheet.createRow(i + 1);
        row.setRowStyle(cellStyle);
        row.createCell(0).setCellValue(i + 1);
        row.createCell(1).setCellValue(String.valueOf(resultSet.get("name")));
        row.createCell(2).setCellValue(String.valueOf(resultSet.get("address")));
        row.createCell(3).setCellValue(String.valueOf(resultSet.get("registertime")));
        row.createCell(4).setCellValue(String.valueOf(resultSet.get("securephone")));

    }
    File file = File.createTempFile(".xls", ".xls");
    OutputStream out = new FileOutputStream(file);
    wb.write(out);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    headers.setContentDispositionFormData("attachment",
            URLEncoder.encode(type, "UTF-8") + LocalDate.now() + ".xls");
    return new HttpEntity<byte[]>(FileUtils.readFileToByteArray(file), headers);
}

From source file:alfio.manager.TicketReservationManagerIntegrationTest.java

@Test
public void testTicketSelection() {
    List<TicketCategoryModification> categories = Arrays.asList(
            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),
            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> eventAndUsername = initEvent(categories, organizationRepository, userManager,
            eventManager, eventRepository);
    Event event = eventAndUsername.getKey();

    TicketCategory bounded = ticketCategoryRepository.findByEventId(event.getId()).stream()
            .filter(TicketCategory::isBounded).findFirst().orElseThrow(IllegalStateException::new);
    TicketCategory unbounded = ticketCategoryRepository.findByEventId(event.getId()).stream()
            .filter(t -> !t.isBounded()).findFirst().orElseThrow(IllegalStateException::new);

    assertEquals(0, eventStatisticsManager.loadModifiedTickets(event.getId(), bounded.getId(), 0, null).size());
    assertEquals(Integer.valueOf(0),
            eventStatisticsManager.countModifiedTicket(event.getId(), bounded.getId(), null));
    assertEquals(0,//  ww w.j a va  2  s . co  m
            eventStatisticsManager.loadModifiedTickets(event.getId(), unbounded.getId(), 0, null).size());

    TicketReservationModification tr = new TicketReservationModification();
    tr.setAmount(10);
    tr.setTicketCategoryId(bounded.getId());

    TicketReservationModification tr2 = new TicketReservationModification();
    tr2.setAmount(9);
    tr2.setTicketCategoryId(unbounded.getId());

    TicketReservationWithOptionalCodeModification mod = new TicketReservationWithOptionalCodeModification(tr,
            Optional.empty());
    TicketReservationWithOptionalCodeModification mod2 = new TicketReservationWithOptionalCodeModification(tr2,
            Optional.empty());
    String reservationId = ticketReservationManager.createTicketReservation(event, Arrays.asList(mod, mod2),
            Collections.emptyList(), DateUtils.addDays(new Date(), 1), Optional.empty(), Optional.empty(),
            Locale.ENGLISH, false);

    List<TicketReservation> reservations = ticketReservationManager
            .findAllReservationsInEvent(event.getId(), 0, null, null).getKey();
    assertTrue(reservations.size() == 1);
    assertEquals(reservationId, reservations.get(0).getId());

    List<Ticket> pendingTickets = ticketRepository
            .findPendingTicketsInCategories(Arrays.asList(bounded.getId(), unbounded.getId()));
    assertEquals(19, pendingTickets.size());
    pendingTickets.forEach(t -> assertEquals(1000, t.getFinalPriceCts()));
    List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
    assertEquals(1, tickets.size());
    assertTrue(tickets.stream().allMatch(t -> t.getCategoryId() == null));

    TotalPrice totalPrice = ticketReservationManager.totalReservationCostWithVAT(reservationId);

    assertEquals(0, ticketReservationManager.getPendingPayments(event).size());

    PaymentResult confirm = ticketReservationManager.confirm(null, null, event, reservationId,
            "email@example.com", new CustomerName("full name", "full", "name", event), Locale.ENGLISH,
            "billing address", totalPrice, Optional.empty(), Optional.of(PaymentProxy.OFFLINE), false, null,
            null, null);

    assertTrue(confirm.isSuccessful());

    assertEquals(TicketReservation.TicketReservationStatus.OFFLINE_PAYMENT,
            ticketReservationManager.findById(reservationId).get().getStatus());

    assertEquals(1, ticketReservationManager.getPendingPayments(event).size());

    Date now = new Date();
    Date from = DateUtils.addDays(now, -1);
    Date to = DateUtils.addDays(now, 1);

    assertTrue(ticketReservationRepository.getSoldStatistic(event.getId(), from, to).isEmpty()); // -> no reservations
    ticketReservationManager.validateAndConfirmOfflinePayment(reservationId, event, new BigDecimal("190.00"),
            eventAndUsername.getValue());

    assertEquals(19,
            ticketReservationRepository.getSoldStatistic(event.getId(), from, to).get(0).getTicketSoldCount()); // -> 19 tickets reserved

    assertEquals(10,
            eventStatisticsManager.loadModifiedTickets(event.getId(), bounded.getId(), 0, null).size());
    assertEquals(Integer.valueOf(10),
            eventStatisticsManager.countModifiedTicket(event.getId(), bounded.getId(), null));
    assertEquals(9,
            eventStatisticsManager.loadModifiedTickets(event.getId(), unbounded.getId(), 0, null).size());
    assertEquals(Integer.valueOf(9),
            eventStatisticsManager.countModifiedTicket(event.getId(), unbounded.getId(), null));

    assertEquals(TicketReservation.TicketReservationStatus.COMPLETE,
            ticketReservationManager.findById(reservationId).get().getStatus());

    //-------------------

    TicketReservationModification trForDelete = new TicketReservationModification();
    trForDelete.setAmount(1);
    trForDelete.setTicketCategoryId(unbounded.getId());
    TicketReservationWithOptionalCodeModification modForDelete = new TicketReservationWithOptionalCodeModification(
            trForDelete, Optional.empty());
    String reservationId2 = ticketReservationManager.createTicketReservation(event,
            Collections.singletonList(modForDelete), Collections.emptyList(), DateUtils.addDays(new Date(), 1),
            Optional.empty(), Optional.empty(), Locale.ENGLISH, false);

    ticketReservationManager.confirm(null, null, event, reservationId2, "email@example.com",
            new CustomerName("full name", "full", "name", event), Locale.ENGLISH, "billing address", totalPrice,
            Optional.empty(), Optional.of(PaymentProxy.OFFLINE), false, null, null, null);

    assertTrue(ticketReservationManager.findById(reservationId2).isPresent());

    ticketReservationManager.deleteOfflinePayment(event, reservationId2, false);

    Assert.assertFalse(ticketReservationManager.findById(reservationId2).isPresent());
}

From source file:se.omegapoint.facepalm.infrastructure.JPAUserRepository.java

@Override
public void addFriend(final String user, final String friendToAdd) {
    notBlank(user);//from  w w  w.j  av  a 2 s . co m
    notBlank(friendToAdd);

    eventService.publish(new GenericEvent(format("User[%s] is now friend of [%s]", user, friendToAdd)));

    entityManager.persist(new Friendship(user, friendToAdd, Date.valueOf(LocalDate.now())));
}

From source file:aajavafx.Schedule1Controller.java

@Override
public void initialize(URL url, ResourceBundle rb) {
    schIdColumn.setCellValueFactory(cellData -> cellData.getValue().schIdProperty().asObject());
    schDateColumn.setCellValueFactory(cellData -> cellData.getValue().schDateProperty());
    schFromTimeColumn.setCellValueFactory(cellData -> cellData.getValue().schFromTimeProperty());
    schUntilTimeColumn.setCellValueFactory(cellData -> cellData.getValue().schUntilTimeProperty());
    emplVisitedCustColumn//from w  w w.j a v  a 2 s  .  c o m
            .setCellValueFactory(cellData -> cellData.getValue().emplVisitedCustProperty().asObject());
    customersCuIdColumn.setCellValueFactory(cellData -> cellData.getValue().customersCuIdProperty());
    employeesEmpIdColumn.setCellValueFactory(cellData -> cellData.getValue().employeesEmpIdProperty());

    empIdColumn.setCellValueFactory(cellData -> cellData.getValue().idProperty().asObject());
    empFirstNameColumn.setCellValueFactory(cellData -> cellData.getValue().firstNProperty());
    empLastColumn.setCellValueFactory(cellData -> cellData.getValue().lastNameProperty());
    empUserNameColumn.setCellValueFactory(cellData -> cellData.getValue().empUserNameProperty());

    cuIdColumn.setCellValueFactory(cellData -> cellData.getValue().customerIdProperty().asObject());
    cuFirstNameColumn.setCellValueFactory(cellData -> cellData.getValue().firstNameProperty());
    cuLastNameColumn.setCellValueFactory(cellData -> cellData.getValue().lastNameProperty());
    cuPersonnumerColumn.setCellValueFactory(cellData -> cellData.getValue().personnumerProperty());

    pickADate.setValue(LocalDate.now());
    pickADate.setOnAction(new EventHandler() {
        public void handle(Event t) {
            LocalDate date = pickADate.getValue();
            System.err.println("Selected date: " + date);
            setDate(pickADate.getValue().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            System.out.println("Date now: " + getDate());

        }

    });

    try {

        tableEmployee.setItems(getEmployee());
        tableCustomer.setItems(getCustomer());
        tableSchedule.setItems(getSchedule());
    } catch (IOException ex) {
        Logger.getLogger(EmployeeController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JSONException ex) {
        Logger.getLogger(EmployeeController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:org.openhab.binding.openuv.internal.handler.OpenUVBridgeHandler.java

public @Nullable OpenUVResult getUVData(String latitude, String longitude, @Nullable String altitude) {
    StringBuilder urlBuilder = new StringBuilder(BASE_URL).append("?lat=").append(latitude).append("&lng=")
            .append(longitude);//from w w  w .  j a  va 2s  . c  o m

    if (altitude != null) {
        urlBuilder.append("&alt=").append(altitude);
    }
    String errorMessage = null;
    try {
        String jsonData = HttpUtil.executeUrl("GET", urlBuilder.toString(), header, null, null,
                REQUEST_TIMEOUT);
        OpenUVResponse uvResponse = gson.fromJson(jsonData, OpenUVResponse.class);
        if (uvResponse.getError() == null) {
            updateStatus(ThingStatus.ONLINE);
            return uvResponse.getResult();
        } else {
            errorMessage = uvResponse.getError();
        }
    } catch (IOException e) {
        errorMessage = e.getMessage();
    }

    if (errorMessage.startsWith(ERROR_QUOTA_EXCEEDED)) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, errorMessage);
        LocalDate today = LocalDate.now();
        LocalDate tomorrow = today.plusDays(1);
        LocalDateTime tomorrowMidnight = tomorrow.atStartOfDay().plusMinutes(2);

        logger.warn("Quota Exceeded, going OFFLINE for today, will retry at : {} ", tomorrowMidnight);
        scheduler.schedule(this::initiateConnexion,
                Duration.between(LocalDateTime.now(), tomorrowMidnight).toMinutes(), TimeUnit.MINUTES);

    } else if (errorMessage.startsWith(ERROR_WRONG_KEY)) {
        logger.error("Error occured during API query : {}", errorMessage);
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, errorMessage);
    }
    return null;
}

From source file:fi.helsinki.opintoni.SpringTest.java

protected TeacherRequestChain defaultTeacherRequestChain() {
    return new TeacherRequestChain(TestConstants.TEACHER_NUMBER,
            DateTimeUtil.getSemesterStartDateString(LocalDate.now()), oodiServer, coursePageServer);
}

From source file:com.gnadenheimer.mg.utils.Utils.java

public Map<String, String> getPersistenceMap() {
    try {//from   ww  w .j a  va2  s  . c  o m
        Properties p = System.getProperties();
        p.setProperty("derby.system.home", Preferences.userRoot().node("MG").get("Datadir",
                (new JFileChooser()).getFileSystemView().getDefaultDirectory().toString() + "\\javadb"));
        p.setProperty("derby.drda.host", "0.0.0.0");
        p.setProperty("derby.language.sequence.preallocator", "1");
        String databaseIP;
        databaseIP = Preferences.userRoot().node("MG").get("DatabaseIP", "127.0.0.1");
        Map<String, String> persistenceMap = new HashMap<>();
        persistenceMap.put("javax.persistence.jdbc.url",
                "jdbc:derby://" + databaseIP + ":1527/mgdb;create=true");
        persistenceMap.put("javax.persistence.jdbc.user", "mg");
        persistenceMap.put("javax.persistence.jdbc.password", "123456");
        persistenceMap.put("javax.persistence.jdbc.driver", "org.apache.derby.jdbc.ClientDriver");
        persistenceMap.put("backUpDir",
                Preferences.userRoot().node("MG").get("Datadir",
                        (new JFileChooser()).getFileSystemView().getDefaultDirectory().toString() + "\\javadb")
                        + "\\autoBackUp");
        persistenceMap.put("anoActivo",
                Preferences.userRoot().node("MG").get("anoActivo", String.valueOf(LocalDate.now().getYear())));
        return persistenceMap;
    } catch (Exception exx) {
        JOptionPane.showMessageDialog(null,
                Thread.currentThread().getStackTrace()[1].getMethodName() + " - " + exx.getMessage());
        LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), exx);
        return null;
    }
}

From source file:alfio.manager.system.DataMigratorIntegrationTest.java

@Test
public void testMigration() {
    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> eventUsername = initEvent(categories);
    Event event = eventUsername.getKey();

    try {/*ww w  .  ja va2s. co  m*/
        eventRepository.updatePrices("CHF", 40, false, BigDecimal.ONE, "STRIPE", event.getId(),
                PriceContainer.VatStatus.NOT_INCLUDED, 1000);

        dataMigrator.migrateEventsToCurrentVersion();
        EventMigration eventMigration = eventMigrationRepository.loadEventMigration(event.getId());
        assertNotNull(eventMigration);
        //assertEquals(buildTimestamp, eventMigration.getBuildTimestamp().toString());
        assertEquals(currentVersion, eventMigration.getCurrentVersion());

        List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
        assertNotNull(tickets);
        assertFalse(tickets.isEmpty());
        assertEquals(AVAILABLE_SEATS, tickets.size());
        assertTrue(tickets.stream().allMatch(t -> t.getCategoryId() == null));
    } finally {
        eventManager.deleteEvent(event.getId(), eventUsername.getValue());
    }
}

From source file:com.github.drbookings.ui.controller.BookingDetailsController.java

static void addNewPayment(String paymentString, BookingBean be) {
    if (StringUtils.isBlank(paymentString)) {
        return;// w w w . jav a  2  s .  c  o m
    }
    double paymentAmount = Double.parseDouble(paymentString);
    LocalDate paymentDate = LocalDate.now();
    Payment payment = new Payment(paymentDate, paymentAmount);
    be.getPayments().add(payment);

}

From source file:org.openlmis.fulfillment.repository.ProofOfDeliveryRepositoryIntegrationTest.java

@Test
public void shouldLogChangesInProofOfDelivery() {
    ProofOfDelivery pod = generateInstance();
    ProofOfDeliveryLineItem lineItem = pod.getLineItems().get(0);

    ProofOfDeliveryDto podDto = new ProofOfDeliveryDto();
    ProofOfDeliveryLineItemDto lineItemDto = new ProofOfDeliveryLineItemDto();

    proofOfDeliveryRepository.save(pod);

    pod.export(podDto);/*  www.j a va  2  s  . c  om*/
    lineItem.export(lineItemDto);

    podDto.setReceivedBy("Test receiver");
    podDto.setDeliveredBy("Test deliverer");
    podDto.setReceivedDate(LocalDate.now());
    pod = ProofOfDelivery.newInstance(podDto);

    proofOfDeliveryRepository.save(pod);

    pod.export(podDto);
    lineItem.export(lineItemDto);

    List<CdoSnapshot> podSnapshots = getSnapshots(pod.getId(), ProofOfDelivery.class);
    List<CdoSnapshot> lineSnapshots = getSnapshots(lineItem.getId(), ProofOfDeliveryLineItem.class);

    assertThat(EXPECTED_NEW_POD_SNAPSHOT, podSnapshots, hasSize(2));
    verifyAuditLog(podSnapshots.get(0), SnapshotType.UPDATE,
            new String[] { "receivedBy", "deliveredBy", "receivedDate" },
            new Object[] { podDto.getReceivedBy(), podDto.getDeliveredBy(), podDto.getReceivedDate() });

    assertThat(NOT_EXPECTED_NEW_POD_LINE_ITEM_SNAPSHOT, lineSnapshots, hasSize(1));
}