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:com.github.drbookings.excel.FileFormatBookingXLS.java

public static LocalDate getDate(final Cell cell) {
    if (cell != null) {
        final String result = cell.getStringCellValue();
        if (result != null && !StringUtils.isEmpty(result)) {
            return LocalDate.parse(result);
        }/*  www. jav  a2  s.c o m*/
    }
    return null;
}

From source file:de.lgblaumeiser.ptm.analysis.analyzer.ProjectComputer.java

private Collection<Booking> getRelevantBookings(final Collection<String> dayOrMonthParameter) {
    if (dayOrMonthParameter.size() > 0) {
        String dayOrMonthString = Iterables.get(dayOrMonthParameter, 0);
        if (dayOrMonthString.length() == 10) {
            return getBookingsForDay(LocalDate.parse(dayOrMonthString));
        }/*from w w  w  . java  2  s  . com*/
        if (dayOrMonthString.length() == 7) {
            return getBookingsForMonth(YearMonth.parse(dayOrMonthString));
        }
    }
    return getBookingsForMonth(YearMonth.now());
}

From source file:svc.data.citations.datasources.tyler.TylerCitationDataSourceTest.java

@SuppressWarnings("unchecked")
@Test//  w  w w .  j  a va 2s.c  o m
public void returnsCitationsGivenLicenseAndDOB() {
    final String DRIVERSLICENSENUMBER = "ABCDE";
    final String DRIVERSLICENSESTATE = "AZ";
    final LocalDate DOB = LocalDate.parse("2000-06-01");
    mockTylerConfiguration.rootUrl = "http://myURL.com";
    mockTylerConfiguration.apiKey = "1234";
    final Citation CITATION = new Citation();
    CITATION.id = 3;
    final List<Citation> CITATIONS = Lists.newArrayList(CITATION);
    final List<TylerCitation> tylerCitations = Lists.newArrayList();
    Mockito.doReturn(tylerCitations).when(tylerCitationsResponseSpy).getBody();

    when(restTemplate.exchange(any(URI.class), eq(HttpMethod.GET), any(HttpEntity.class),
            any(ParameterizedTypeReference.class))).thenReturn(tylerCitationsResponseSpy);

    when(mockCitationTransformer.fromTylerCitations(tylerCitations)).thenReturn(CITATIONS);
    when(mockCitationFilter.RemoveCitationsWithExpiredDates(CITATIONS)).thenReturn(CITATIONS);

    List<Citation> citations = mockTylerCitationDataSource.getByLicenseAndDOB(DRIVERSLICENSENUMBER,
            DRIVERSLICENSESTATE, DOB);

    assertThat(citations.get(0).id, is(3));
}

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

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

    if (search == null) {
        context.getFlashScope().error("error.invalidSearch");
        return Results.redirect(
                router.getReverseRoute(GoogleGroupController.class, "view", "groupId", group.getId()));
    }//from ww w . ja  v  a2 s .  com

    Run minRun = baseDB.run.findFirst(Module.GOOGLE, STATUSES_DONE, null);
    Run maxRun = baseDB.run.findLast(Module.GOOGLE, STATUSES_DONE, null);
    if (maxRun == null || minRun == null) {
        return Results.ok().render("search", search);
    }

    LocalDate minDay = minRun.getDay();
    LocalDate maxDay = maxRun.getDay();

    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) {
        }
    }

    if (startDate == null || endDate == null || endDate.isBefore(startDate)) {
        startDate = maxDay.minusDays(30);
        endDate = maxDay;
    }

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

    if (firstRun == null || lastRun == null || firstRun.getDay().isAfter(lastRun.getDay())) {
        return Results.ok()
                .render("f_warning", msg.get("error.noDataForThisPeriod", context, Optional.absent()).or(""))
                .render("startDate", startDate).render("endDate", endDate).render("minDate", minDay)
                .render("maxDate", maxDay).render("search", search);
    }

    startDate = firstRun.getDay();
    endDate = lastRun.getDay();

    String jsonEvents = null;
    try {
        jsonEvents = objectMapper.writeValueAsString(baseDB.event.list(group, startDate, endDate));
    } catch (JsonProcessingException ex) {
        jsonEvents = "[]";
    }

    GoogleSerp lastSerp = googleDB.serp.get(lastRun.getId(), search.getId());

    List<GoogleTarget> targets = getTargets(context);

    Map<Integer, GoogleBest> bestRankings = new HashMap<>();
    for (GoogleTarget target : targets) {
        GoogleBest best = googleDB.rank.getBest(target.getGroupId(), target.getId(), search.getId());
        if (best != null) {
            bestRankings.put(best.getGoogleTargetId(), best);
        }
    }

    String jsonRanks = getJsonRanks(group, targets, firstRun, lastRun, searchId);
    Config config = baseDB.config.getConfig();

    return Results.ok().render("displayMode", config.getDisplayGoogleSearch()).render("events", jsonEvents)
            .render("targets", targets).render("chart", jsonRanks).render("search", search)
            .render("serp", lastSerp).render("startDate", startDate).render("endDate", endDate)
            .render("minDate", minDay).render("maxDate", maxDay).render("bestRankings", bestRankings);
}

From source file:org.openmhealth.shim.withings.mapper.WithingsDailyCaloriesBurnedDataPointMapper.java

/**
 * Maps an individual list node from the array in the Withings activity measure endpoint response into a {@link
 * CaloriesBurned} data point.//from   w  ww .  j a  v  a 2 s  .  c om
 * <p>
 * <p>Note: the start datetime and end datetime values for the mapped {@link CaloriesBurned} {@link DataPoint}
 * assume that
 * the start timezone and end time zone are the same, both equal to the "timezone" property in the Withings
 * response
 * datapoints. However, according to Withings, the property value they provide is specifically the end datetime
 * timezone.</p>
 *
 * @param node activity node from the array "activites" contained in the "body" of the endpoint response
 * @return a {@link DataPoint} object containing a {@link CaloriesBurned} measure with the appropriate values from
 * the JSON node parameter, wrapped as an {@link Optional}
 */
@Override
Optional<DataPoint<CaloriesBurned>> asDataPoint(JsonNode node) {

    long caloriesBurnedValue = asRequiredLong(node, "calories");
    CaloriesBurned.Builder caloriesBurnedBuilder = new CaloriesBurned.Builder(
            new KcalUnitValue(KcalUnit.KILOCALORIE, caloriesBurnedValue));

    Optional<String> dateString = asOptionalString(node, "date");
    Optional<String> timeZoneFullName = asOptionalString(node, "timezone");
    // We assume that timezone is the same for both the startdate and enddate timestamps, even though Withings only
    // provides the enddate timezone as the "timezone" property.
    // TODO: Revisit once Withings can provide start_timezone and end_timezone
    if (dateString.isPresent() && timeZoneFullName.isPresent()) {
        LocalDateTime localStartDateTime = LocalDate.parse(dateString.get()).atStartOfDay();
        ZoneId zoneId = ZoneId.of(timeZoneFullName.get());
        ZonedDateTime zonedDateTime = ZonedDateTime.of(localStartDateTime, zoneId);
        ZoneOffset offset = zonedDateTime.getOffset();
        OffsetDateTime offsetStartDateTime = OffsetDateTime.of(localStartDateTime, offset);
        LocalDateTime localEndDateTime = LocalDate.parse(dateString.get()).atStartOfDay().plusDays(1);

        OffsetDateTime offsetEndDateTime = OffsetDateTime.of(localEndDateTime, offset);
        caloriesBurnedBuilder.setEffectiveTimeFrame(
                TimeInterval.ofStartDateTimeAndEndDateTime(offsetStartDateTime, offsetEndDateTime));
    }

    Optional<String> userComment = asOptionalString(node, "comment");
    if (userComment.isPresent()) {
        caloriesBurnedBuilder.setUserNotes(userComment.get());
    }

    CaloriesBurned caloriesBurned = caloriesBurnedBuilder.build();
    DataPoint<CaloriesBurned> caloriesBurnedDataPoint = newDataPoint(caloriesBurned, null, true, null);

    return Optional.of(caloriesBurnedDataPoint);

}

From source file:com.controller.schedule.GetScheduledEntitiesServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w  w w. jav  a  2 s  .  c  o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    try {
        HttpSession session = request.getSession();
        if (session.getAttribute("UID") == null) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "User is not logged in");
            response.getWriter().write(AppConstants.GSON.toJson(error));
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().flush();
            return;
        }
        Integer userId = Integer.parseInt(session.getAttribute("UID").toString());
        List<String> errorMsgs = new ArrayList<>();

        if (StringUtils.isEmpty(request.getParameter("from"))) {
            errorMsgs.add("from date parameter is missing");
        }
        if (StringUtils.isEmpty(request.getParameter("to"))) {
            errorMsgs.add("to date parameter is missing");
        }

        if (!errorMsgs.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            Map<String, Object> responseMap = new HashMap<>();
            responseMap.put("error", errorMsgs);
            response.getWriter().write(AppConstants.GSON.toJson(responseMap));
            response.getWriter().flush();
            return;
        }

        LocalDate fromDate = null;
        LocalDate toDate = null;
        //Dates have to follow the format: 2011-12-03
        try {
            fromDate = LocalDate.parse(request.getParameter("from"));
        } catch (DateTimeParseException ex) {
            errorMsgs.add("from parameter is not in the required yyyy-mm-dd format");
            logger.log(Level.SEVERE, "", ex);
        }

        try {
            toDate = LocalDate.parse(request.getParameter("to"));
        } catch (DateTimeParseException ex) {
            errorMsgs.add("to parameter is not in the required yyyy-mm-dd format");
            logger.log(Level.SEVERE, "", ex);
        }
        if (!errorMsgs.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            Map<String, Object> responseMap = new HashMap<>();
            responseMap.put("error", errorMsgs);
            response.getWriter().write(AppConstants.GSON.toJson(responseMap));
            response.getWriter().flush();
            return;
        }

        JSONObject scheduledEntities = ScheduleDAO.getScheduledEntities(userId, fromDate, toDate);
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(AppConstants.GSON.toJson(scheduledEntities));
        response.getWriter().flush();
    } catch (SQLException ex) {
        Logger.getLogger(GetScheduledEntitiesServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:net.straylightlabs.archivo.controller.UpdateCheckTask.java

private SoftwareUpdateDetails getCurrentRelease(JSONObject json) {
    logger.debug("Release JSON: {}", json);
    try {/*from   w  ww  .ja  v a  2s  .co m*/
        if (json.getBoolean("update_available")) {
            URL location = new URL(json.getString("location"));
            List<String> changes = parseChangeList(json);
            LocalDate date = LocalDate.parse(json.getString("date"));
            return new SoftwareUpdateDetails(
                    SoftwareUpdateDetails.versionToString(json.getInt("major_ver"), json.getInt("minor_ver"),
                            json.getInt("release_ver"), json.getBoolean("is_beta"), json.getInt("beta_ver")),
                    location, date, changes);
        } else {
            return SoftwareUpdateDetails.UNAVAILABLE;
        }
    } catch (MalformedURLException e) {
        logger.error("Error parsing update location: {}", e.getLocalizedMessage());
        return SoftwareUpdateDetails.UNAVAILABLE;
    }
}

From source file:com.swcguild.dvdlibraryv3.DVDLibraryController.java

private void addDVD() {
    String title = con.readString("Enter the title: ");

    List<Dvd> arr = dvds.getByTitle(title); //dvdsRack.findDVDsByTitle(title);
    if (arr.isEmpty()) {
        con.print("There's no DVD with the title " + title);

    } else {//w ww . j a  v  a2 s. co  m
        con.print("There're already DVDs with that title. ");
        if (con.readYorN("Do you want to change the title? [Y/N]").equalsIgnoreCase("Y")) {
            title = con.readString("Enter the title: ");
        }
    }
    String dateStr = con.readDate("Enter the release date in format YYYY-mm-dd");
    LocalDate date = LocalDate.parse(dateStr);

    String mpaaRating = con
            .readMPAARating("Enter the mpaa rating as \"G\", \"PG\", \"PG-13\", \"R\", \"NC-17\":");
    String directorName = con.readString("Enter the director name");
    String studio = con.readString("Enter the studio name");
    String userNotes = con.readString("Enter your note");
    //userNotes.add(con.readString("Enter your note"));
    //System.out.println(userNotes);
    Dvd d = new Dvd();//(title, date, mpaaRating, directorName, studio, userNotes);

    //id++;
    d.setTitle(title);
    d.setReleaseDate(date);
    d.setMpaaRating(mpaaRating);
    d.setDirector(directorName);
    d.setStudio(studio);
    d.setNote(userNotes);
    //d.setId(id);

    printDVD(d);
    dvds.add(d);

}

From source file:org.ojbc.adapters.analyticsstaging.custody.dao.TestAnalyticalDatastoreDAOImpl.java

protected Person getStaticPerson() {
    Person person = new Person();

    person.setPersonRaceId(1);/*from w  ww  .java  2  s  .co  m*/
    person.setPersonSexId(2);
    person.setPersonEthnicityTypeId(2);
    person.setPersonBirthDate(LocalDate.parse("1966-06-01"));
    person.setPersonUniqueIdentifier("123332123123unique");
    person.setLanguageId(2);
    person.setPersonAgeAtBooking(50);
    person.setEducationLevel("College");
    person.setOccupation("Lawyer");
    person.setDomicileStatusTypeId(1);
    person.setProgramEligibilityTypeId(1);
    person.setWorkReleaseStatusTypeId(2);
    person.setMilitaryServiceStatusType(new KeyValue(1, null));
    return person;
}

From source file:com.thesoftwareguild.capstoneblog.dao.BlogDaoTest.java

/**
 * Test of addPost method, of class BlogDao.
 *///from   ww w  .j  a  v  a  2  s. co  m
@Test
public void testAddPost() {
    System.out.println("addPost");
    Post post = new Post("admin", "Title1", "This post is added in a test. That's all it's good for.",
            LocalDate.parse("2016-11-15"), LocalDate.parse("2016-11-15"),
            new ArrayList<>(asList("TestCategory")), new ArrayList<>(asList("#TestTwo")),
            new ArrayList<>(asList("test comment. Nothing else.")));
    Post expResult = post;
    Post result = dao.addPost(post);
    assertEquals(expResult, result);
}