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:jgnash.ui.commodity.SecuritiesHistoryDialog.java

private void clearForm() {
    dateField.setDate(LocalDate.now());
    closeField.setDecimal(null);
    volumeField.setText(null);
    lowField.setDecimal(null);
    highField.setDecimal(null);
}

From source file:alfio.manager.EventManagerIntegrationTest.java

@Test(expected = IllegalArgumentException.class)
public void testEventGenerationWithOverflow() {
    List<TicketCategoryModification> categories = Arrays.asList(
            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),
            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),
            new TicketCategoryModification(null, "default", 0,
                    new DateTimeModification(LocalDate.now(), LocalTime.now()),
                    new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN,
                    false, "", false, null, null, null, null, null));
    Event event = initEvent(categories, organizationRepository, userManager, eventManager, eventRepository)
            .getKey();/*from w  w w  .j  av  a 2 s.c  o m*/
    List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
    assertNotNull(tickets);
    assertFalse(tickets.isEmpty());
    assertEquals(AVAILABLE_SEATS, tickets.size());
    assertTrue(tickets.stream().noneMatch(t -> t.getCategoryId() == null));
}

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

private void addEvents(final LocalDate date, final Collection<BookingEntry> upcomingBookings,
        final Collection<CleaningEntry> upcomingCleanings) {
    final VBox box = new VBox(4);
    if (date.equals(LocalDate.now())) {
        box.getStyleClass().add("first-day");
    } else if (date.equals(LocalDate.now().plusDays(1))) {
        box.getStyleClass().add("second-day");
    } else if (date.isAfter(LocalDate.now().plusDays(1))) {
        box.getStyleClass().add("later");
    }/*from   w w w .j  a va2  s  . c o  m*/

    if (upcomingBookings.stream().filter(b -> b.isCheckIn() || b.isCheckOut()).collect(Collectors.toList())
            .isEmpty() && upcomingCleanings.isEmpty()) {
        final Text t0 = new Text(getDateString(date));
        final Text t1 = new Text(" there are no events.");
        t0.getStyleClass().add("emphasis");
        final TextFlow tf = new TextFlow();
        tf.getChildren().addAll(t0, t1);
        box.getChildren().addAll(tf);
    } else {
        final List<CheckInOutDetails> checkInNotes = Collections.synchronizedList(new ArrayList<>());
        final List<CheckInOutDetails> checkOutNotes = Collections.synchronizedList(new ArrayList<>());
        upcomingBookings.forEach(b -> {
            if (b.isCheckIn()) {
                String note = "";
                if (b.getElement().getCheckInNote() != null) {
                    note = b.getElement().getCheckInNote();
                }
                if (b.getElement().getSpecialRequestNote() != null) {
                    note = note + "\n" + b.getElement().getSpecialRequestNote();
                }
                checkInNotes.add(new CheckInOutDetails(b.getRoom().getName(),
                        b.getElement().getBookingOrigin().getName(), note));
            } else if (b.isCheckOut()) {
                checkOutNotes.add(new CheckInOutDetails(b.getRoom().getName(),
                        b.getElement().getBookingOrigin().getName(), b.getElement().getCheckOutNote()));
            }
        });
        Collections.sort(checkInNotes);
        Collections.sort(checkOutNotes);
        addGeneralSummary(date, box, checkInNotes);
        addCheckOutSummary(date, box, checkOutNotes);
        addCheckOutNotes(date, box, checkOutNotes);
        addCheckInSummary(date, box, checkInNotes);
        addCheckInNotes(date, box, checkInNotes);
        addCleaningSummary(date, box, upcomingCleanings);
        addCleanings(date, box, upcomingCleanings);
    }

    this.box.getChildren().add(box);

}

From source file:org.apache.nifi.processors.orc.PutORCTest.java

@Test
public void testWriteORCWithAvroLogicalTypes() throws IOException, InitializationException {
    final String avroSchema = IOUtils.toString(
            new FileInputStream("src/test/resources/user_logical_types.avsc"), StandardCharsets.UTF_8);
    schema = new Schema.Parser().parse(avroSchema);
    Calendar now = Calendar.getInstance();
    LocalTime nowTime = LocalTime.now();
    LocalDateTime nowDateTime = LocalDateTime.now();
    LocalDate epoch = LocalDate.ofEpochDay(0);
    LocalDate nowDate = LocalDate.now();

    final int timeMillis = nowTime.get(ChronoField.MILLI_OF_DAY);
    final Timestamp timestampMillis = Timestamp.valueOf(nowDateTime);
    final Date dt = Date.valueOf(nowDate);
    final double dec = 1234.56;

    configure(proc, 10, (numUsers, readerFactory) -> {
        for (int i = 0; i < numUsers; i++) {
            readerFactory.addRecord(i, timeMillis, timestampMillis, dt, dec);
        }//from  ww w .ja  va  2s.  c  o m
        return null;
    });

    final String filename = "testORCWithDefaults-" + System.currentTimeMillis();

    final Map<String, String> flowFileAttributes = new HashMap<>();
    flowFileAttributes.put(CoreAttributes.FILENAME.key(), filename);

    testRunner.setProperty(PutORC.HIVE_TABLE_NAME, "myTable");

    testRunner.enqueue("trigger", flowFileAttributes);
    testRunner.run();
    testRunner.assertAllFlowFilesTransferred(PutORC.REL_SUCCESS, 1);

    final Path orcFile = new Path(DIRECTORY + "/" + filename);

    // verify the successful flow file has the expected attributes
    final MockFlowFile mockFlowFile = testRunner.getFlowFilesForRelationship(PutORC.REL_SUCCESS).get(0);
    mockFlowFile.assertAttributeEquals(PutORC.ABSOLUTE_HDFS_PATH_ATTRIBUTE, orcFile.getParent().toString());
    mockFlowFile.assertAttributeEquals(CoreAttributes.FILENAME.key(), filename);
    mockFlowFile.assertAttributeEquals(PutORC.RECORD_COUNT_ATTR, "10");
    // DDL will be created with field names normalized (lowercased, e.g.) for Hive by default
    mockFlowFile.assertAttributeEquals(PutORC.HIVE_DDL_ATTRIBUTE,
            "CREATE EXTERNAL TABLE IF NOT EXISTS `myTable` (`id` INT, `timemillis` INT, `timestampmillis` TIMESTAMP, `dt` DATE, `dec` DOUBLE) STORED AS ORC");

    // verify we generated a provenance event
    final List<ProvenanceEventRecord> provEvents = testRunner.getProvenanceEvents();
    assertEquals(1, provEvents.size());

    // verify it was a SEND event with the correct URI
    final ProvenanceEventRecord provEvent = provEvents.get(0);
    assertEquals(ProvenanceEventType.SEND, provEvent.getEventType());
    // If it runs with a real HDFS, the protocol will be "hdfs://", but with a local filesystem, just assert the filename.
    Assert.assertTrue(provEvent.getTransitUri().endsWith(DIRECTORY + "/" + filename));

    // verify the content of the ORC file by reading it back in
    verifyORCUsers(orcFile, 10, (x, currUser) -> {
        assertEquals((int) currUser, ((IntWritable) x.get(0)).get());
        assertEquals(timeMillis, ((IntWritable) x.get(1)).get());
        assertEquals(timestampMillis, ((TimestampWritableV2) x.get(2)).getTimestamp().toSqlTimestamp());
        final DateFormat noTimeOfDayDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        noTimeOfDayDateFormat.setTimeZone(TimeZone.getTimeZone("gmt"));
        assertEquals(noTimeOfDayDateFormat.format(dt), ((DateWritableV2) x.get(3)).get().toString());
        assertEquals(dec, ((DoubleWritable) x.get(4)).get(), Double.MIN_VALUE);
        return null;
    });

    // verify we don't have the temp dot file after success
    final File tempOrcFile = new File(DIRECTORY + "/." + filename);
    Assert.assertFalse(tempOrcFile.exists());

    // verify we DO have the CRC file after success
    final File crcAvroORCFile = new File(DIRECTORY + "/." + filename + ".crc");
    Assert.assertTrue(crcAvroORCFile.exists());
}

From source file:org.vaadin.peholmst.samples.dddwebinar.TestDataGenerator.java

private static LocalDate randomDate(int yearsBack) {
    LocalDate now = LocalDate.now();
    return LocalDate.of(now.getYear() - RND.nextInt(yearsBack), RND.nextInt(12) + 1, RND.nextInt(28) + 1);
}

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

@Test
public void testAlreadyMigratedEvent() {
    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 {/* w  w w . j  a v  a  2 s  .c o m*/
        ZonedDateTime migrationTs = ZonedDateTime.now(ZoneId.of("UTC"));
        eventMigrationRepository.insertMigrationData(event.getId(), currentVersion, migrationTs,
                EventMigration.Status.COMPLETE.toString());
        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(migrationTs.toString(), eventMigration.getBuildTimestamp().toString());
        assertEquals(currentVersion, eventMigration.getCurrentVersion());

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

From source file:AppMain.java

@Override
public void handle(Request request, Response response) {

    long time = System.currentTimeMillis();
    System.out.print(request.getPath().toString() + "\t" + request.getValues("Host") + " ");
    System.out.println(request.getValues("User-agent") + " ");
    response.setDate("Date", time);
    try {/* w  w  w. j av  a  2 s. co  m*/

        //static? send the file
        if (request.getPath().toString().startsWith("/static/")) {
            String path = request.getPath().toString().substring("/static/".length());
            File requested = new File("static" + File.separatorChar + path.replace('/', File.separatorChar));
            if (!requested.getCanonicalPath().startsWith(new File("static").getCanonicalPath())) {
                System.err.println("Error, path outside the static folder:" + path);
                return;
            }
            if (!requested.isFile()) {
                System.err.println("Error, file not found:" + path);
                return;
            }
            //valid path, send it
            String mimet = URLConnection.guessContentTypeFromName(path);
            if (path.endsWith(".js"))
                mimet = "application/javascript";
            if (path.endsWith(".css"))
                mimet = "text/css";
            System.out.println("sending static resource:'" + path + "' mimetype:" + mimet);
            response.setDate("Date", requested.lastModified());
            try (PrintStream body = response.getPrintStream()) {
                response.setValue("Content-Type", mimet);
                FileInputStream fis = new FileInputStream(requested);
                //copy the stream
                IOUtils.copy(fis, body);
                fis.close();
            }
            return;
        }
        //main page, show the index
        if (request.getPath().toString().equals("/")) {
            try (PrintStream body = response.getPrintStream()) {
                response.setValue("Content-Type", "text/html;charset=utf-8");
                File file = new File("index.html");
                System.out.println(file.getAbsolutePath());
                byte[] data;
                try (FileInputStream fis = new FileInputStream(file)) {
                    data = new byte[(int) file.length()];
                    fis.read(data);
                }
                body.write(data);
            }
        }

        if (request.getPath().toString().startsWith("/parse")) {
            response.setValue("Content-Type", "application/json;charset=utf-8");
            try (PrintStream body = response.getPrintStream()) {
                String text = request.getQuery().get("text");
                String pattern = request.getQuery().get("pattern");
                if (text == null || pattern == null) {
                    body.write("{'error':'pattern or text not specified'}".getBytes("UTF-8"));
                    body.close();
                }
                System.err.println("request to parse text: " + text + "\nfor pattern: " + pattern);
                MatchingResults results = null;
                JSONObject ret = new JSONObject();
                try {
                    long start = System.currentTimeMillis();
                    results = fm.matches(text, pattern, FlexiMatcher.getDefaultAnnotator(), true, false, true);
                    ret.put("time to parse", System.currentTimeMillis() - start);
                } catch (RuntimeException r) {
                    body.write(("{\"error\":" + JSONObject.quote(r.getMessage()) + "}").getBytes("UTF-8"));
                    body.close();
                    return;
                }
                ret.put("matches", results.isMatching());
                ret.put("empty_match", results.isEmptyMatch());
                ret.put("text", text);
                ret.put("pattern", pattern);
                if (!results.getAnnotations().isPresent()) {
                    body.write(ret.toString().getBytes("UTF-8"));
                    body.close();
                    return;
                }
                for (LinkedList<TextAnnotation> interpretation : results.getAnnotations().get()) {
                    JSONObject addMe = new JSONObject();

                    for (TextAnnotation v : interpretation) {
                        addMe.append("annotations", new JSONObject(v.toJSON()));
                    }
                    ret.append("interpretations", addMe);
                }
                body.write(ret.toString(1).getBytes("UTF-8"));
            }
            return;
        }

        if (request.getPath().toString().startsWith("/trace")) {
            response.setValue("Content-Type", "application/json;charset=utf-8");
            try (PrintStream body = response.getPrintStream()) {
                String text = request.getQuery().get("text");
                String pattern = request.getQuery().get("pattern");
                if (text == null || pattern == null) {
                    body.write("{'error':'pattern or text not specified'}".getBytes("UTF-8"));
                    body.close();
                }
                System.err.println("request to parse text: " + text + "\nfor pattern: " + pattern);
                JSONObject ret = new JSONObject();
                ListingAnnotatorHandler ah;
                try {
                    long start = System.currentTimeMillis();
                    ah = new ListingAnnotatorHandler();
                    fm.matches(text, pattern, ah, true, false, true);
                    ret.put("time", System.currentTimeMillis() - start);
                } catch (RuntimeException r) {
                    body.write(("{\"error\":" + JSONObject.quote(r.getMessage()) + "}").getBytes("UTF-8"));
                    body.close();
                    return;
                }
                ret.put("text", text);
                ret.put("pattern", pattern);
                LinkedList<TextAnnotation> nonOverlappingTA = new LinkedList<>();
                JSONObject addMe = new JSONObject();
                for (TextAnnotation v : ah.getAnnotations()) {
                    if (nonOverlappingTA.stream().anyMatch(p -> p.getSpan().intersects(v.getSpan()))) {
                        ret.append("interpretations", addMe);
                        addMe = new JSONObject();
                        addMe.append("annotations", new JSONObject(v.toJSON()));
                        nonOverlappingTA.clear();
                    } else {
                        addMe.append("annotations", new JSONObject(v.toJSON()));
                    }
                    nonOverlappingTA.add(v);

                }
                ret.append("interpretations", addMe);
                body.write(ret.toString(1).getBytes("UTF-8"));
            }
            return;
        }

        if (request.getPath().toString().startsWith("/addtag")) {
            if (tagCount == 0)
                fwTag.write("\n#tags added from web interface at " + LocalDate.now().toString() + "\n");

            tagCount++;
            response.setValue("Content-Type", "application/json;charset=utf-8");
            try (PrintStream body = response.getPrintStream()) {
                String tag = request.getQuery().getOrDefault("tag", "");
                String pattern = request.getQuery().getOrDefault("pattern", "");

                if (tag.isEmpty() || pattern.isEmpty()) {
                    body.write("{\"error\":\"tag or pattern not specified\"}".getBytes("UTF-8"));
                    body.close();
                    return;
                }

                String identifier = request.getQuery().getOrDefault("identifier", "");
                String annotationTemplate = request.getQuery().getOrDefault("annotation_template", "").trim();

                if (identifier.isEmpty()) {
                    identifier = "auto_" + LocalDate.now().toString() + "_" + tagCount;
                }

                //check that rule identifiers are known
                for (String part : ExpressionParser.split(pattern)) {
                    if (!part.startsWith("["))
                        continue;
                    if (!fm.isBoundRule(ExpressionParser.ruleName(part))) {
                        body.write(("{\"error\":\"rule '" + ExpressionParser.ruleName(part) + "' non known\"}")
                                .getBytes("UTF-8"));
                        body.close();
                        return;
                    }
                }

                fwTag.write(tag + "\t" + pattern + "\t" + identifier + "\t" + annotationTemplate + "\n");
                fwTag.flush();
                if (annotationTemplate.isEmpty())
                    fm.addTagRule(tag, pattern, identifier);
                else
                    fm.addTagRule(tag, pattern, identifier, annotationTemplate);
                body.write(("{\"identifier\":" + JSONObject.quote(identifier) + "}").getBytes("UTF-8"));
            }
            return;

        }
        //unknown request
        try (PrintStream body = response.getPrintStream()) {
            response.setValue("Content-Type", "text/plain");
            response.setDate("Last-Modified", time);
            response.setCode(401);
            body.println("HTTP request for page '" + request.getPath().toString() + "' non understood in "
                    + this.getClass().getCanonicalName());
        }
    } catch (IOException | JSONException e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:alfio.manager.WaitingQueueManagerIntegrationTest.java

@Test
public void testWaitingQueueForUnboundedCategory() {
    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));
    Event event = initEvent(categories, organizationRepository, userManager, eventManager, eventRepository)
            .getKey();//from ww  w.jav  a2  s  . c  o m
    TicketCategory unbounded = ticketCategoryRepository.findByEventId(event.getId()).get(0);

    TicketReservationModification tr = new TicketReservationModification();
    tr.setAmount(AVAILABLE_SEATS);
    tr.setTicketCategoryId(unbounded.getId());

    TicketReservationWithOptionalCodeModification mod = new TicketReservationWithOptionalCodeModification(tr,
            Optional.empty());
    String reservationId = ticketReservationManager.createTicketReservation(event,
            Collections.singletonList(mod), Collections.emptyList(), DateUtils.addDays(new Date(), 1),
            Optional.<String>empty(), Optional.<String>empty(), Locale.ENGLISH, false);
    TotalPrice reservationCost = ticketReservationManager.totalReservationCostWithVAT(reservationId);
    PaymentResult result = ticketReservationManager.confirm("", null, event, reservationId, "test@test.ch",
            new CustomerName("Full Name", "Full", "Name", event), Locale.ENGLISH, "", reservationCost,
            Optional.empty(), Optional.of(PaymentProxy.OFFLINE), false, null, null, null);
    assertTrue(result.isSuccessful());

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

From source file:alfio.manager.EventManagerIntegrationTest.java

/**
 * When adding an unbounded category, we won't update the tickets status, because:
 * 1) if the unbounded category is using existing seats, the event cannot be already sold-out
 * 2) if the unbounded category has been added after an event edit (add seats), then the tickets are already "RELEASED"
 * 3) if there is another unbounded category, then it is safe not to update the tickets' status, in order to not
 *    interfere with the existing category
 *
 */// ww  w.  j ava2s.c o m
@Test
public void testAddUnboundedCategory() {
    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);
    Event event = pair.getKey();
    TicketCategoryModification tcm = new TicketCategoryModification(null, "default", -1,
            new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            false, null, null, null, null, null);
    eventManager.insertCategory(event.getId(), tcm, pair.getValue());
    List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
    assertNotNull(tickets);
    assertFalse(tickets.isEmpty());
    assertEquals(AVAILABLE_SEATS, tickets.size());
    assertEquals(10, tickets.stream().filter(t -> t.getCategoryId() == null).count());
}

From source file:org.silverpeas.core.calendar.CalendarSynchronizationIT.java

@Test
public void testEventAddingUpdateAndDeletionAfterSynchronization() throws Exception {
    final Calendar calendar = prepareSynchronizedCalendar();
    OffsetDateTime lastSynchronizationDate = calendar.getLastSynchronizationDate().get();

    List<CalendarEvent> events = Calendar.getEvents().filter(f -> f.onCalendar(calendar)).stream()
            .collect(Collectors.toList());
    final String externalId = UUID.randomUUID().toString();
    updateLastUpdateDate(events.get(0), UPDATE_DATETIME);
    updateExternalId(events.get(1), externalId);

    ICalendarImportResult result = calendar.synchronize();
    assertThat(result.added(), is(1));/*ww w  .j av a 2  s .c o  m*/
    assertThat(result.updated(), is(1));
    assertThat(result.deleted(), is(1));

    Calendar synchronizedCalendar = Calendar.getById(CALENDAR_ID);
    assertThat(synchronizedCalendar.getLastSynchronizationDate().get(), greaterThan(lastSynchronizationDate));
    assertThat(synchronizedCalendar.externalEvent(externalId).isPresent(), is(false));
    assertThat(synchronizedCalendar.event(externalId).isPresent(), is(false));

    events = Calendar.getEvents().filter(f -> f.onCalendar(synchronizedCalendar)).stream()
            .collect(Collectors.toList());
    assertThat(events.size(), is(2));
    events.forEach(e -> {
        assertThat(e.getLastSynchronizationDate().toLocalDate(), is(LocalDate.now()));
    });
}