Example usage for java.time LocalDate parse

List of usage examples for java.time LocalDate parse

Introduction

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

Prototype

public static LocalDate parse(CharSequence text) 

Source Link

Document

Obtains an instance of LocalDate from a text string such as 2007-12-03 .

Usage

From source file:org.silverpeas.core.workflow.api.user.ReplacementListTest.java

@Test
void filterCurrentAndNextAt() {
    List<ReplacementImpl> result = replacements.stream().filterCurrentAndNextAt(LocalDate.parse("2019-04-10"))
            .collect(Collectors.toList());
    assertThat(toUserIdsAsString(result), is("12,34,56,13"));
    result = replacements.stream().filterCurrentAndNextAt(LocalDate.parse("2019-04-11"))
            .collect(Collectors.toList());
    assertThat(toUserIdsAsString(result), is("12,34,56,13"));
    result = replacements.stream().filterCurrentAndNextAt(LocalDate.parse("2019-04-12"))
            .collect(Collectors.toList());
    assertThat(toUserIdsAsString(result), is("34,56,13"));
    result = replacements.stream().filterCurrentAndNextAt(LocalDate.parse("2019-04-13"))
            .collect(Collectors.toList());
    assertThat(toUserIdsAsString(result), is("34,56,13"));
}

From source file:org.ojbc.adapters.analyticsstaging.custody.CamelContextPimaTest.java

@Test
public void testBookingReportServiceRoute() throws Exception, IOException {
    Exchange senderExchange = createSenderExchange(
            "src/test/resources/xmlInstances/bookingReport/BookingReport-Pima.xml");

    Person person = analyticalDatastoreDAO.getPerson(1);
    Assert.assertNull(person);/*from  ww w  .jav  a2 s  .  c o  m*/

    Booking booking = analyticalDatastoreDAO.getBookingByBookingNumber("eDocumentID");
    assertNull(booking);

    List<BookingCharge> bookingCharges = analyticalDatastoreDAO.getBookingCharges(1);
    assertTrue(bookingCharges.isEmpty());

    List<BookingArrest> bookingArrests = analyticalDatastoreDAO.getBookingArrests(1);
    assertTrue(bookingArrests.isEmpty());

    //Send the one-way exchange.  Using template.send will send an one way message
    Exchange returnExchange = template.send("direct:bookingReportServiceEndpoint", senderExchange);

    //Use getException to see if we received an exception
    if (returnExchange.getException() != null) {
        throw new Exception(returnExchange.getException());
    }

    person = analyticalDatastoreDAO.getPerson(1);
    Assert.assertNotNull(person);

    Assert.assertEquals(Integer.valueOf(1), person.getPersonId());
    assertThat(person.getPersonSexId(), is(3));
    assertThat(person.getPersonRaceId(), is(5));
    assertThat(person.getPersonSexDescription(), is("Unknown"));
    assertThat(person.getPersonRaceDescription(), is("Caucasian"));
    assertThat(person.getLanguage(), is("English Speaker"));
    assertThat(person.getPersonBirthDate(), is(LocalDate.parse("1969-01-01")));
    Assert.assertEquals("e807f1fcf82d132f9bb018ca6738a19f", person.getPersonUniqueIdentifier());
    assertThat(person.getLanguageId(), is(41));
    assertThat(person.getSexOffenderStatusTypeId(), nullValue());
    assertNull(person.getMilitaryServiceStatusType().getValue());

    assertNull(person.getEducationLevel());
    assertNull(person.getOccupation());
    assertThat(person.getDomicileStatusTypeId(), is(2));
    assertThat(person.getProgramEligibilityTypeId(), is(2));

    List<BehavioralHealthAssessment> behavioralHealthAssessments = analyticalDatastoreDAO
            .getBehavioralHealthAssessments(1);
    assertFalse(behavioralHealthAssessments.isEmpty());

    BehavioralHealthAssessment behavioralHealthAssessment = behavioralHealthAssessments.get(0);

    assertTrue(behavioralHealthAssessment.getBehavioralHealthDiagnoses().size() == 1);
    assertThat(behavioralHealthAssessment.getBehavioralHealthDiagnoses().get(0), is("Schizophrenia 295.10"));
    assertThat(behavioralHealthAssessment.getPersonId(), is(1));
    assertThat(behavioralHealthAssessment.getBehavioralHealthAssessmentId(), is(1));
    assertThat(behavioralHealthAssessment.getSeriousMentalIllness(), is(true));
    assertThat(behavioralHealthAssessment.getCareEpisodeStartDate(), is(LocalDate.parse("2016-01-01")));
    assertThat(behavioralHealthAssessment.getCareEpisodeEndDate(), is(LocalDate.parse("2016-04-01")));
    assertThat(behavioralHealthAssessment.getEnrolledProviderName(), is("79"));
    assertThat(behavioralHealthAssessment.getMedicaidStatusTypeId(), is(2));

    List<Treatment> treatments = analyticalDatastoreDAO.getTreatments(1);
    assertThat(treatments.size(), is(1));

    Treatment treatment = treatments.get(0);
    assertThat(treatment.getBehavioralHealthAssessmentID(), is(1));
    assertThat(treatment.getTreatmentStartDate(), is(LocalDate.parse("2016-01-01")));
    assertThat(treatment.getTreatmentAdmissionReasonTypeId(), nullValue());
    assertThat(treatment.getTreatmentStatusTypeId(), nullValue());
    assertThat(treatment.getTreatmentProviderName(), is("Treatment Providing Organization Name"));

    List<PrescribedMedication> prescribedMedications = analyticalDatastoreDAO.getPrescribedMedication(1);
    assertThat(prescribedMedications.size(), is(1));

    PrescribedMedication prescribedMedication = prescribedMedications.get(0);
    assertThat(prescribedMedication.getBehavioralHealthAssessmentID(), is(1));
    assertThat(prescribedMedication.getMedicationDescription(), is("Zyprexa"));
    assertThat(prescribedMedication.getMedicationDispensingDate(), is(LocalDate.parse("2016-01-01")));
    assertThat(prescribedMedication.getMedicationDoseMeasure(), is("3mg"));

    booking = analyticalDatastoreDAO.getBookingByBookingNumber("234567890");
    assertNotNull(booking);

    assertEquals(LocalDate.parse("2016-05-12"), booking.getBookingDate());
    assertEquals(LocalTime.parse("00:36:00"), booking.getBookingTime());
    assertThat(booking.getFacilityId(), is(1));
    assertThat(booking.getSupervisionUnitTypeId(), is(84));
    assertEquals("234567890", booking.getBookingNumber());
    assertNull(booking.getScheduledReleaseDate());
    assertThat(booking.getInmateJailResidentIndicator(), is(false));

    bookingArrests = analyticalDatastoreDAO.getBookingArrests(1);
    assertThat(bookingArrests.size(), is(1));
    BookingArrest bookingArrest = bookingArrests.get(0);

    assertTrue(bookingArrest.getBookingId() == 1);
    assertTrue(bookingArrest.getBookingArrestId() == 1);
    assertTrue(bookingArrest.getAddress().isEmpty());
    assertThat(bookingArrest.getArrestAgencyId(), is(16));

    bookingCharges = analyticalDatastoreDAO.getBookingCharges(1);
    assertThat(bookingCharges.size(), is(1));

    BookingCharge bookingCharge = bookingCharges.get(0);
    assertThat(bookingCharge.getChargeCode(), is("ARS13-1105"));
    assertNull(bookingCharge.getChargeDisposition());
    assertTrue(bookingCharge.getBookingArrestId() == 1);
    assertTrue(bookingCharge.getBondAmount().doubleValue() == 250000.00);
    assertThat(bookingCharge.getBondType(), nullValue());
    assertThat(bookingCharge.getAgencyId(), nullValue());
    assertThat(bookingCharge.getChargeClassTypeId(), is(2));
    assertThat(bookingCharge.getBondStatusTypeId(), is(1));
    assertThat(bookingCharge.getChargeJurisdictionTypeId(), is(8));

    CustodyRelease custodyRelease = analyticalDatastoreDAO.getCustodyReleaseByBookingId(1);
    assertNull(custodyRelease);
}

From source file:de.jfachwert.rechnung.Rechnungsmonat.java

private static LocalDate toLocalDate(String monat) {
    String normalized = monat.replaceAll("[/.\\s]", "-");
    String[] parts = monat.split("-");
    if (parts.length == 2) {
        normalized = "1-" + normalized;
    } else if (parts.length != 3) {
        throw new InvalidValueException(monat, MONTH);
    }/*from w w  w  .j a va2s.  co  m*/
    try {
        return LocalDate.parse(normalized);
    } catch (DateTimeParseException ex) {
        return guessLocalDate(normalized, ex);
    }
}

From source file:org.ambraproject.wombat.controller.MediaCurationController.java

/**
 * Validate the input from the form/*www  .j  a v  a2 s .c  o  m*/
 *
 * @param model data passed in from the view
 * @param link  link pointing to media content relating to the article
 * @param name  name of the user submitting the media curation request
 * @param email email of the user submitting the media curation request
 * @return true if everything is ok
 */

private boolean validateMediaCurationInput(Model model, String link, String name, String email, String title,
        String publishedOn, String consent) throws IOException {

    boolean isValid = true;

    UrlValidator urlValidator = new UrlValidator(new String[] { "http", "https" });

    if (consent == null || !"true".equals(consent)) {
        model.addAttribute("consentError", "This field is required.");
        isValid = false;
    }

    if (StringUtils.isBlank(link)) {
        model.addAttribute("linkError", "This field is required.");
        isValid = false;
    } else if (!urlValidator.isValid(link)) {
        model.addAttribute("linkError", "Invalid Media link URL");
        isValid = false;
    }

    if (StringUtils.isBlank(name)) {
        model.addAttribute("nameError", "This field is required.");
        isValid = false;
    }

    if (StringUtils.isBlank(title)) {
        model.addAttribute("titleError", "This field is required.");
        isValid = false;
    }

    if (StringUtils.isBlank(publishedOn)) {
        model.addAttribute("publishedOnError", "This field is required.");
        isValid = false;
    } else {
        try {
            LocalDate.parse(publishedOn);
        } catch (DateTimeParseException e) {
            model.addAttribute("publishedOnError", "Invalid Date Format, should be YYYY-MM-DD");
            isValid = false;
        }
    }

    if (StringUtils.isBlank(email)) {
        model.addAttribute("emailError", "This field is required.");
        isValid = false;
    } else if (!EmailValidator.getInstance().isValid(email)) {
        model.addAttribute("emailError", "Invalid e-mail address");
        isValid = false;
    }

    model.addAttribute("isValid", isValid);
    return isValid;
}

From source file:com.ccstats.crypto.io.JSONEncryptedStatement.java

/**
 * Reads an encrypted .json statement file and attempts to decrypt it. Once decrypted, the transactions can be
 * pooled and returned as a joint statement.
 *
 * @param absolutePath The absolute path to the encrypted statement, including the file name.
 * @param password The password sequence to be used while attempting the decryption.
 *
 * @return A statement object containing all the discovered transactions as a pool.
 *///  w w  w  .j  av a  2 s .  c  om
public Statement read(String absolutePath, String password)
        throws IOException, ParseException, BadPaddingException {
    TransactionPool transactions = new TransactionPool();
    JSONParser parser = new JSONParser();

    JSONObject main = (JSONObject) parser.parse(new FileReader(absolutePath));
    JSONObject encryptedTransactions = (JSONObject) main.get("transactions");

    worker.setKeyLength(Integer.valueOf((String) main.get("aes-key-length")));
    try {

        JSONObject current;
        String date, description, amount, authorized;
        for (Object o : encryptedTransactions.values()) {
            current = (JSONObject) o;
            date = new String(worker.decrypt(password, (String) current.get("date")));
            description = new String(worker.decrypt(password, (String) current.get("description")));
            amount = new String(worker.decrypt(password, (String) current.get("amount")));
            authorized = new String(worker.decrypt(password, (String) current.get("authorized")));

            transactions.add(new Transaction(description, LocalDate.parse(date), Double.valueOf(amount),
                    Boolean.valueOf(authorized)));
        }

    } catch (InvalidKeySpecException | NoSuchAlgorithmException | DecoderException | InvalidKeyException
            | InvalidAlgorithmParameterException | IllegalBlockSizeException | NoSuchPaddingException e) {
        e.printStackTrace();
    }

    return new Statement(transactions);
}

From source file:serposcope.controllers.google.GoogleSearchController.java

public Result urlRanks(Context context, @PathParam("searchId") Integer searchId, @Param("url") String url,
        @Param("startDate") String startDateStr, @Param("endDate") String endDateStr) {
    Group group = (Group) context.getAttribute("group");

    GoogleSearch search = getSearch(context, searchId);
    if (search == null) {
        context.getFlashScope().error("error.invalidSearch");
        return Results.redirect(
                router.getReverseRoute(GoogleGroupController.class, "view", "groupId", group.getId()));
    }// w w  w .  ja  va2  s  .  c  o m

    LocalDate startDate = null;
    if (startDateStr != null) {
        try {
            startDate = LocalDate.parse(startDateStr);
        } catch (Exception ex) {
        }
    }
    LocalDate endDate = null;
    if (endDateStr != null) {
        try {
            endDate = LocalDate.parse(endDateStr);
        } catch (Exception ex) {
        }
    }

    Run firstRun = baseDB.run.findFirst(Module.GOOGLE, STATUSES_DONE, startDate);
    Run lastRun = baseDB.run.findLast(Module.GOOGLE, STATUSES_DONE, endDate);

    if (url == null || firstRun == null || lastRun == null) {
        return Results.badRequest().text();
    }

    StringBuilder builder = new StringBuilder("{");
    googleDB.serp.stream(firstRun.getId(), lastRun.getId(), search.getId(), (GoogleSerp t) -> {
        int position = 0;
        for (int i = 0; i < t.getEntries().size(); i++) {
            if (t.getEntries().get(i).getUrl().equals(url)) {
                position = i + 1;
                break;
            }
        }

        builder.append("\"").append(t.getRunDay().toEpochSecond(ZoneOffset.UTC) * 1000l).append("\":")
                .append(position).append(",");
    });

    if (builder.charAt(builder.length() - 1) == ',') {
        builder.setCharAt(builder.length() - 1, '}');
    } else {
        builder.append('}');
    }

    return Results.ok().text().render(builder.toString());
}

From source file:serposcope.controllers.google.GoogleTargetController.java

public Result jsonVariation(Context context, @PathParam("targetId") Integer targetId,
        @Param("endDate") String endDateStr) {
    GoogleTarget target = getTarget(context, targetId);
    List<GoogleSearch> searches = context.getAttribute("searches", List.class);
    Group group = context.getAttribute("group", Group.class);

    final LocalDate endDate;
    try {/*from ww  w.  j  a v  a 2 s  .  c  o  m*/
        endDate = LocalDate.parse(endDateStr);
    } catch (Exception ex) {
        return Results.json().renderRaw("[[],[],[]]");
    }
    Run lastRun = baseDB.run.findLast(group.getModule(), RunDB.STATUSES_DONE, endDate);

    List<TargetVariation> ranksUp = new ArrayList<>();
    List<TargetVariation> ranksDown = new ArrayList<>();
    List<TargetVariation> ranksSame = new ArrayList<>();

    Map<Integer, GoogleSearch> searchesById = searches.stream()
            .collect(Collectors.toMap(GoogleSearch::getId, Function.identity()));

    List<GoogleRank> ranks = googleDB.rank.list(lastRun.getId(), group.getId(), target.getId());
    for (GoogleRank rank : ranks) {

        GoogleSearch search = searchesById.get(rank.googleSearchId);
        if (search == null) {
            continue;
        }

        if (rank.diff > 0) {
            ranksDown.add(new TargetVariation(search, rank));
        } else if (rank.diff < 0) {
            ranksUp.add(new TargetVariation(search, rank));
        } else {
            ranksSame.add(new TargetVariation(search, rank));
        }
    }

    Collections.sort(ranksUp,
            (TargetVariation o1, TargetVariation o2) -> Integer.compare(o1.rank.diff, o2.rank.diff));
    Collections.sort(ranksDown,
            (TargetVariation o1, TargetVariation o2) -> -Integer.compare(o1.rank.diff, o2.rank.diff));
    Collections.sort(ranksSame,
            (TargetVariation o1, TargetVariation o2) -> Integer.compare(o1.rank.rank, o2.rank.rank));

    return Results.ok().json().render((Context context0, Result result) -> {
        PrintWriter writer = null;
        OutputStream os = null;
        try {

            String acceptEncoding = context0.getHeader("Accept-Encoding");
            if (acceptEncoding != null && acceptEncoding.contains("gzip")) {
                result.addHeader("Content-Encoding", "gzip");
            }

            ResponseStreams response = context0.finalizeHeaders(result);
            os = response.getOutputStream();
            if (acceptEncoding != null && acceptEncoding.contains("gzip")) {
                os = new GZIPOutputStream(os);
            }

            writer = new PrintWriter(os);

            writer.append("[");
            int id = 0;

            writer.append("[");
            for (int i = 0; i < ranksUp.size(); i++) {
                TargetVariation var = ranksUp.get(i);
                writer.append("{").append("\"id\":").append(Integer.toString(id++)).append(",\"search\":")
                        .append(searchToJson(var.search)).append(",\"now\":")
                        .append(Integer.toString(var.rank.rank)).append(",\"prv\":")
                        .append(Integer.toString(var.rank.previousRank)).append(",\"diff\":")
                        .append(Integer.toString(var.rank.diff)).append("}");

                if (i != ranksUp.size() - 1) {
                    writer.append(',');
                }
            }

            writer.append("],[");

            for (int i = 0; i < ranksDown.size(); i++) {
                TargetVariation var = ranksDown.get(i);
                writer.append("{").append("\"id\":").append(Integer.toString(id++)).append(",\"search\":")
                        .append(searchToJson(var.search)).append(",\"now\":")
                        .append(Integer.toString(var.rank.rank)).append(",\"prv\":")
                        .append(Integer.toString(var.rank.previousRank)).append(",\"diff\":")
                        .append(Integer.toString(var.rank.diff)).append("}");

                if (i != ranksDown.size() - 1) {
                    writer.append(',');
                }
            }

            writer.append("],[");

            for (int i = 0; i < ranksSame.size(); i++) {
                TargetVariation var = ranksSame.get(i);
                writer.append("{").append("\"id\":").append(Integer.toString(id++)).append(",\"search\":")
                        .append(searchToJson(var.search)).append(",\"now\":")
                        .append(Integer.toString(var.rank.rank)).append("}");

                if (i != ranksSame.size() - 1) {
                    writer.append(',');
                }
            }
            writer.append("]]");

        } catch (Exception ex) {
            LOG.warn("HTTP error", ex);
        } finally {
            if (os != null) {
                try {
                    writer.close();
                    os.close();
                } catch (Exception ex) {
                }
            }
        }
    });
}

From source file:arxiv.xml.XMLParser.java

/**
 * Parse the datestamp of a record.//from ww w .ja  va 2s . co m
 * @throws ParseException if there is a parsing error
 */
private LocalDate parseDatestamp(String value) {
    LocalDate datestamp;

    try {
        datestamp = LocalDate.parse(value);
    } catch (DateTimeParseException e) {
        throw new ParseException("Could not parse datestamp '" + value + "' in ISO_LOCAL_DATE format");
    }

    return datestamp;
}

From source file:org.silverpeas.core.workflow.api.user.ReplacementListTest.java

@Test
void filterAtAndFilterOnAtLeastOneRole() {
    List<ReplacementImpl> result = replacements.stream().filterCurrentAt(LocalDate.parse("2019-04-11"))
            .filterOnAtLeastOneRole(ROLE_B).collect(Collectors.toList());
    assertThat(toUserIdsAsString(result), is("12"));
    result = replacements.stream().filterCurrentAt(LocalDate.parse("2019-04-12")).filterOnAtLeastOneRole(ROLE_B)
            .collect(Collectors.toList());
    assertThat(result, empty());/*  w  w  w.  ja  va  2 s.  c  om*/
    result = replacements.stream().filterCurrentAt(LocalDate.parse("2019-04-12"))
            .filterOnAtLeastOneRole(ROLE_A, ROLE_B, ROLE_D).collect(Collectors.toList());
    assertThat(toUserIdsAsString(result), is("56"));
}

From source file:serposcope.controllers.google.GoogleSearchController.java

public Result exportSerp(Context context, @PathParam("searchId") Integer searchId,
        @Param("date") String pdate) {
    GoogleSerp serp = null;/*  ww  w. ja  va  2  s  . c om*/
    LocalDate date = null;
    try {
        date = LocalDate.parse(pdate);
    } catch (Exception ex) {
    }
    if (date != null) {
        List<Run> runs = baseDB.run.findByDay(Module.GOOGLE, date);
        if (!runs.isEmpty()) {
            GoogleSearch search = getSearch(context, searchId);
            if (search != null) {
                serp = googleDB.serp.get(runs.get(0).getId(), search.getId());
            }
        }
    }

    if (serp == null) {
        return Results.ok().text().renderRaw("SERP not found");
    }

    boolean exportRank = context.getParameter("rank") != null;
    boolean exportD1 = context.getParameter("d1") != null;
    boolean exportD7 = context.getParameter("d7") != null;
    boolean exportD30 = context.getParameter("d30") != null;
    boolean exportD90 = context.getParameter("d90") != null;

    int position = 0;
    StringBuilder builder = new StringBuilder();
    for (GoogleSerpEntry entry : serp.getEntries()) {
        ++position;
        if (exportRank) {
            builder.append(position).append(",");
        }
        builder.append(StringEscapeUtils.escapeCsv(entry.getUrl())).append(",");
        if (exportD1) {
            Short rank = entry.getMap().getOrDefault((short) 1, (short) GoogleRank.UNRANKED);
            builder.append(rank != GoogleRank.UNRANKED ? rank.intValue() : "").append(",");
        }
        if (exportD7) {
            Short rank = entry.getMap().getOrDefault((short) 7, (short) GoogleRank.UNRANKED);
            builder.append(rank != GoogleRank.UNRANKED ? rank.intValue() : "").append(",");
        }
        if (exportD30) {
            Short rank = entry.getMap().getOrDefault((short) 30, (short) GoogleRank.UNRANKED);
            builder.append(rank != GoogleRank.UNRANKED ? rank.intValue() : "").append(",");
        }
        if (exportD90) {
            Short rank = entry.getMap().getOrDefault((short) 90, (short) GoogleRank.UNRANKED);
            builder.append(rank != GoogleRank.UNRANKED ? rank.intValue() : "").append(",");
        }
        if (builder.length() > 0) {
            builder.setCharAt(builder.length() - 1, '\n');
        }
    }

    return Results.text()
            .addHeader("Content-Disposition",
                    "attachment; filename=\"" + serp.getRunDay().toLocalDate() + ".csv\"")
            .renderRaw(builder.toString());
}