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.abixen.platform.service.businessintelligence.multivisualisation.application.service.JsonFilterService.java

private String prepareDataSection(DataValueType dataValueType, String data) {
    switch (dataValueType) {
    case DOUBLE:/*from  w ww.ja  v a 2 s .c  o  m*/
        return data;
    case DATE:
        return "'" + LocalDate.parse(data.substring(DATA_BEGIN_INDEX, DATA_END_INDEX)) + "'";
    case INTEGER:
        return data;
    case STRING:
        return "'" + data + "'";
    default:
        throw new NotImplementedException("Not recognized column type.");
    }
}

From source file:uom.research.thalassemia.ui.PatientUI.java

/**
 * check for empty fields./*from w w  w.j  av  a  2 s .co  m*/
 *
 * @return boolean boolean
 */
private boolean hasEmptyFields() {
    patient = new Patient();
    if (txtNIC.getText().trim().isEmpty()) {
        if (!Validator.validateNIC(txtNIC.getText().trim())) {
            return true;
        }
        patient.setNic("");
    } else {
        patient.setNic(txtNIC.getText());
    }
    patient.setTitle(cmbTitle.getSelectedItem().toString());
    if (txtFirstName.getText().trim().isEmpty()) {
        return true;
    } else {
        patient.setFirstName(txtFirstName.getText());
    }
    if (txtMiddleName.getText().trim().isEmpty()) {
        return true;
    } else {
        patient.setMiddleName(txtMiddleName.getText());
    }
    if (txtLastName.getText().trim().isEmpty()) {
        return true;
    } else {
        patient.setLastName(txtLastName.getText());
    }
    if (dtBirthDate.getDate().toString().isEmpty()) {
        return true;
    } else {
        patient.setBirthDate(LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(dtBirthDate.getDate())));
    }
    if (radMale.isSelected()) {
        patient.setSex("Male");
    } else if (radFemale.isSelected()) {
        patient.setSex("Female");
    } else {
        return true;
    }
    if (txtAddress1.getText().isEmpty()) {
        return true;
    } else {
        patient.setAddress1(txtAddress1.getText());
    }
    patient.setAddress2(txtAddress2.getText());
    if (txtCity.getText().isEmpty()) {
        return true;
    } else {
        patient.setCity(txtCity.getText());
    }
    if (txtMobile.getText().isEmpty()) {
        return true;
    } else {
        patient.setMobile(Integer.valueOf(txtMobile.getText()));
    }
    patient.setEmail(txtEmail.getText());
    if (txtPhoto.getText().isEmpty()) {
        patient.setImagePath(DEFAULT_PHOTO);
    } else {
        File file = new File(txtPhoto.getText());
        if (file.exists()) {
            patient.setImagePath(file.getName());
        } else {
            return true;
        }
    }
    if (txtContactName.getText().isEmpty()) {
        return true;
    } else {
        contactPerson = new ContactPerson();
        contactPerson.setTitle("Mr. ");
        contactPerson.setName(txtContactName.getText());
    }
    if (txtContactMobile.getText().isEmpty()) {
        return true;
    } else {
        contactPerson.setMobile(Integer.parseInt(txtContactMobile.getText()));
        contactPerson.setEmail("");
    }
    patient.setContactPerson(contactPerson);
    patient.setIsActive(true);
    return false;
}

From source file:com.gigglinggnus.controllers.StudentMakeAppointmentController.java

/**
 *
 * @param request servlet request//from w  w w  .j a  v  a 2 s .  c  o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    EntityManager em = (EntityManager) request.getSession().getAttribute("em");

    String msg = request.getParameter("msg");
    User user = (User) (request.getSession().getAttribute("user"));
    Clock clk = (Clock) (request.getSession().getAttribute("clock"));

    if (msg.equals("lookup_student")) {
        String studId = request.getParameter("studentId");
        List<Exam> exams = user.getRegistrableExams();
        JSONObject json = new JSONObject();
        json.put("students_idNumber", studId);
        json.put("firstName", user.getFirstName());
        json.put("lastName", user.getLastName());
        JSONArray jExams = new JSONArray();
        for (Exam exam : exams) {
            JSONObject elem = new JSONObject();

            String examId = exam.getExamId();
            String termId = exam.getTerm().getTermId();
            String start = exam.getInterval().getStart().atZone(ZoneId.systemDefault()).toLocalDate()
                    .toString();
            String end = exam.getInterval().getEnd().atZone(ZoneId.systemDefault()).toLocalDate().toString();
            elem.put("examId", examId);
            elem.put("termId", termId);
            if (exam instanceof CourseExam) {
                String courseId = ((CourseExam) exam).getCourse().getCourseId();
                elem.put("courseId", courseId);
                elem.put("examType", "Course");
            } else {
                elem.put("courseId", "N/A");
                elem.put("examType", "AdHoc");
            }
            elem.put("start", start);
            elem.put("end", end);
            jExams.put(elem);
        }
        json.put("exams", jExams);
        response.getWriter().write(json.toString());
    } else if (msg.equals("exam_available_timeslots")) {
        String examId = request.getParameter("examId");
        String dateStr = request.getParameter("date");
        Exam exam = em.find(Exam.class, examId);
        LocalDate apptDate = LocalDate.parse(dateStr);
        List<LocalTime> timeslots = exam.getTimeslotsForDay(apptDate);

        JSONObject json = new JSONObject();
        json.put("examId", examId);
        JSONArray jTimeSlots = new JSONArray();
        for (LocalTime timeslot : timeslots) {
            String start = timeslot.toString();
            String end = timeslot.plus(exam.getDuration()).toString();
            JSONObject elem = new JSONObject();
            elem.put("start", start);
            elem.put("end", end);
            jTimeSlots.put(elem);
        }
        json.put("timeSlots", jTimeSlots);
        response.getWriter().write(json.toString());
    } else if (msg.equals("submit-appointment")) {
        String studId = request.getParameter("studentId");
        String examId = request.getParameter("examId");
        String stDate = request.getParameter("examDate");
        String stTime = request.getParameter("startTime") + ":00";
        String stSeat = request.getParameter("seatType");

        Exam exam = em.find(Exam.class, examId);
        LocalDate lDate = LocalDate.parse(stDate);
        LocalTime lTime = LocalTime.parse(stTime);
        Instant inst = ZonedDateTime.of(lDate, lTime, ZoneId.systemDefault()).toInstant();
        JSONObject json = new JSONObject();
        try {
            em.getTransaction().begin();
            user.makeAppointment(exam, inst, clk);
            em.getTransaction().commit();
            json.put("success", "Appointment Made!");
            response.getWriter().write(json.toString());
        } catch (Exception e) {
            em.getTransaction().rollback();
            json.put("error", e.toString());
            response.getWriter().write(json.toString());
        }
    } else {
        JSONObject json = new JSONObject();
        json.put("error", msg);
        response.getWriter().write(json.toString());
    }
}

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

@SuppressWarnings("unchecked")
@Test/*from   ww  w. j a  v  a 2  s .c  o  m*/
public void returnsEmptyCitationsOnRestTemplateError() {
    final String CITATIONNUMBER = "F3453";
    final LocalDate DOB = LocalDate.parse("2000-06-01");
    mockTylerConfiguration.rootUrl = "http://myURL.com";
    mockTylerConfiguration.apiKey = "1234";
    final Citation CITATION = new Citation();
    CITATION.id = 3;

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

    List<Citation> citations = mockTylerCitationDataSource.getByCitationNumberAndDOB(CITATIONNUMBER, DOB);

    assertThat(citations.size(), is(0));
}

From source file:com.gigglinggnus.controllers.AdminMakeAppointmentController.java

/**
 *
 * @param request servlet request//from  ww w .  java  2s  .  c  om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    EntityManager em = (EntityManager) request.getSession().getAttribute("em");

    String msg = request.getParameter("msg");
    User user = (User) (request.getSession().getAttribute("user"));
    Clock clk = (Clock) (request.getSession().getAttribute("clock"));

    if (msg.equals("lookup_student")) {
        String studId = request.getParameter("studentId");
        User student = em.find(User.class, studId);
        List<Exam> exams = student.getRegistrableExams();
        JSONObject json = new JSONObject();
        json.put("students_idNumber", studId);
        json.put("firstName", student.getFirstName());
        json.put("lastName", student.getLastName());
        JSONArray jExams = new JSONArray();
        for (Exam exam : exams) {
            JSONObject elem = new JSONObject();

            String examId = exam.getExamId();
            String termId = exam.getTerm().getTermId();
            String start = exam.getInterval().getStart().atZone(ZoneId.systemDefault()).toLocalDate()
                    .toString();
            String end = exam.getInterval().getEnd().atZone(ZoneId.systemDefault()).toLocalDate().toString();
            elem.put("examId", examId);
            elem.put("termId", termId);
            if (exam instanceof CourseExam) {
                String courseId = ((CourseExam) exam).getCourse().getCourseId();
                elem.put("courseId", courseId);
                elem.put("examType", "Course");
            } else {
                elem.put("courseId", "N/A");
                elem.put("examType", "AdHoc");
            }
            elem.put("start", start);
            elem.put("end", end);
            jExams.put(elem);
        }
        json.put("exams", jExams);
        response.getWriter().write(json.toString());
    } else if (msg.equals("exam_available_timeslots")) {
        String examId = request.getParameter("examId");
        String dateStr = request.getParameter("date");
        Exam exam = em.find(Exam.class, examId);
        LocalDate apptDate = LocalDate.parse(dateStr);
        List<LocalTime> timeslots = exam.getTimeslotsForDay(apptDate);

        JSONObject json = new JSONObject();
        json.put("examId", examId);
        JSONArray jTimeSlots = new JSONArray();
        for (LocalTime timeslot : timeslots) {
            String start = timeslot.toString();
            String end = timeslot.plus(exam.getDuration()).toString();
            JSONObject elem = new JSONObject();
            elem.put("start", start);
            elem.put("end", end);
            jTimeSlots.put(elem);
        }
        json.put("timeSlots", jTimeSlots);
        response.getWriter().write(json.toString());
    } else if (msg.equals("submit-appointment")) {
        String studId = request.getParameter("studentId");
        String examId = request.getParameter("examId");
        String stDate = request.getParameter("examDate");
        String stTime = request.getParameter("startTime") + ":00";
        String stSeat = request.getParameter("seatType");

        User student = em.find(User.class, studId);
        Exam exam = em.find(Exam.class, examId);
        LocalDate lDate = LocalDate.parse(stDate);
        LocalTime lTime = LocalTime.parse(stTime);
        Instant inst = ZonedDateTime.of(lDate, lTime, ZoneId.systemDefault()).toInstant();
        JSONObject json = new JSONObject();
        try {
            em.getTransaction().begin();
            if (stSeat.equals("normal")) {
                user.makeAppointment(student, Seating.NORMAL, exam, inst, clk);
                em.getTransaction().commit();
                json.put("success", "Appointment Made!");
                response.getWriter().write(json.toString());
            } else if (stSeat.equals("setaside")) {
                user.makeAppointment(student, Seating.SETASIDE, exam, inst, clk);
                em.getTransaction().commit();
                json.put("success", "Appointment Made!");
                response.getWriter().write(json.toString());
            } else {
                em.getTransaction().rollback();
                json.put("error", "invalid choice of seating");
                response.getWriter().write(json.toString());
            }
        } catch (Exception e) {
            em.getTransaction().rollback();
            json.put("error", e.toString());
            response.getWriter().write(json.toString());
        }
    } else {
        JSONObject json = new JSONObject();
        json.put("error", msg);
        response.getWriter().write(json.toString());
    }
}

From source file:net.jmhertlein.alphonseirc.MSTDeskEngRunner.java

private static void loadConfig() {
    boolean read = false;
    File f = CONFIG_FILE;/*  w w  w .j  av  a  2s .  com*/
    if (!f.exists()) {
        read = true;
        try {
            f.getParentFile().mkdirs();
            f.createNewFile();
            java.nio.file.Files.setPosixFilePermissions(Paths.get(f.toURI()),
                    PosixFilePermissions.fromString("rw-------"));
        } catch (IOException ex) {
            Logger.getLogger(MSTDeskEngRunner.class.getName()).log(Level.SEVERE, null, ex);
            System.err.println("Error writing empty config.yml!");
        }
    }

    Map<String, Object> config;

    if (read) {
        Console console = System.console();
        console.printf("Nick: \n->");
        nick = console.readLine();
        console.printf("\nPassword: \n-|");
        pass = new String(console.readPassword());
        console.printf("\nServer: \n->");
        server = console.readLine();
        console.printf("\nChannels: (ex: #java,#linux,#gnome)\n->");
        channels = Arrays.asList(console.readLine().split(","));
        System.out.println("Fetching max XKCD...");
        maxXKCD = fetchMaxXKCD();
        System.out.println("Fetched.");
        cachedUTC = System.currentTimeMillis();

        dadLeaveTimes = new HashMap<>();
        noVoiceNicks = new HashSet<>();

        writeConfig();
        System.out.println("Wrote config to file: " + CONFIG_FILE.getAbsolutePath());

    } else {
        try (FileInputStream fis = new FileInputStream(f)) {
            Yaml y = new Yaml();
            config = y.loadAs(fis, Map.class);
        } catch (IOException ex) {
            Logger.getLogger(MSTDeskEngRunner.class.getName()).log(Level.SEVERE, null, ex);
            System.err.println("Error parsing config!");
            return;
        }

        nick = (String) config.get("nick");
        pass = (String) config.get("password");
        server = (String) config.get("server");
        channels = (List<String>) config.get("channels");
        maxXKCD = (Integer) config.get("cachedMaxXKCD");
        cachedUTC = (Long) config.get("cachedUTC");
        noVoiceNicks = (Set<String>) config.get("noVoiceNicks");
        masters = (Set<String>) config.get("masters");
        if (masters == null) {
            masters = new HashSet<>();
            masters.add("Everdras");
        }

        if (noVoiceNicks == null)
            noVoiceNicks = new HashSet<>();

        noVoiceNicks.stream().forEach((s) -> System.out.println("Loaded novoice nick: " + s));
        masters.stream().forEach((s) -> System.out.println("Loaded master nick: " + s));

        if (checkXKCDUpdate())
            writeConfig();
        else
            System.out.println("Loaded cached XKCD.");

        Map<String, Object> serialDadLeaveTimes = (Map<String, Object>) config.get("dadLeaveTimes");
        dadLeaveTimes = new HashMap<>();
        if (serialDadLeaveTimes != null)
            serialDadLeaveTimes.keySet().stream().forEach((time) -> {
                dadLeaveTimes.put(LocalDate.parse(time),
                        LocalTime.parse((String) serialDadLeaveTimes.get(time)));
            });

    }
}

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

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

From source file:serposcope.controllers.admin.DebugController.java

@FilterWith(XSRFFilter.class)
public Result dryRun(Context context, @Param("startDate") String start, @Param("endDate") String end) {
    long _start = System.currentTimeMillis();
    FlashScope flash = context.getFlashScope();

    LocalDate startDate = null;/*from www .  j  av a 2  s  .  c o  m*/
    LocalDate endDate = null;

    try {
        startDate = LocalDate.parse(start);
        endDate = LocalDate.parse(end);
    } catch (Exception ex) {
    }

    if (startDate == null || endDate == null || startDate.isAfter(endDate)) {
        flash.error("error.invalidDate");
        return Results.redirect(router.getReverseRoute(DebugController.class, "debug"));
    }

    Run lastRun = baseDB.run.findLast(Module.GOOGLE, null, null);
    if (lastRun != null && lastRun.getDay().isAfter(startDate)) {
        flash.error("error.invalidDate");
        return Results.redirect(router.getReverseRoute(DebugController.class, "debug"));
    }

    LocalDate date = LocalDate.from(startDate);

    GoogleSettings ggOptions = googleDB.options.get();

    int minPauseBetweenPageSec = ggOptions.getMinPauseBetweenPageSec();
    int maxPauseBetweenPageSec = ggOptions.getMaxPauseBetweenPageSec();
    ggOptions.setMinPauseBetweenPageSec(0);
    ggOptions.setMaxPauseBetweenPageSec(0);
    googleDB.options.update(ggOptions);

    try {
        while (date.isBefore(endDate)) {
            LOG.debug("dry run {}", date);
            if (!taskManager
                    .startGoogleTask(new Run(Run.Mode.MANUAL, Module.GOOGLE, date.atTime(13, 37, 00)))) {
                LOG.error("can't startGoogleTask");
                flash.error("can't startGoogleTask");
                return Results.redirect(router.getReverseRoute(DebugController.class, "debug"));
            }
            taskManager.joinGoogleTask();
            date = date.plusDays(1);
        }
    } catch (Exception ex) {
        LOG.error("an error occured", ex);
        flash.error("an error occured");
        return Results.redirect(router.getReverseRoute(DebugController.class, "debug"));
    } finally {
        ggOptions.setMinPauseBetweenPageSec(minPauseBetweenPageSec);
        ggOptions.setMaxPauseBetweenPageSec(maxPauseBetweenPageSec);
        googleDB.options.update(ggOptions);
    }

    LOG.debug("dry run timing : {}",
            DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - _start));
    flash.success("ok");
    return Results.redirect(router.getReverseRoute(DebugController.class, "debug"));
}

From source file:investiagenofx2.view.InvestiaGenOFXController.java

/**
 * Initializes the controller class.//from  www  .  j  a  va 2  s  .c o m
 *
 * @param url
 * @param rb
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    txt_investiaURL.setText(PropertiesInit.getInvestiaURL());
    dtp_lastDate.setValue(LocalDate.parse(PropertiesInit.getLastGenUsedDate()));
    String[] clientNums = PropertiesInit.getClientNumList().split(",");
    for (String clientNum : clientNums) {
        if (!clientNum.trim().isEmpty()) {
            cbo_clientNum.getItems().add(clientNum.trim());
        }
    }
    Arrays.fill(linkAccountToLocalAccountIndex, -1);
    resetControls();

    cbo_clientNum.getEditor().addEventFilter(KeyEvent.KEY_PRESSED, event -> {
        if (event.getCode() == KeyCode.DELETE) {
            cbo_clientNum.getItems().remove(cbo_clientNum.getValue());
            event.consume();
        }
    });

    dtp_lastDate.setConverter(new StringConverter<LocalDate>() {
        final String pattern = "yyyy-MM-dd";
        final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(pattern);

        {
            dtp_lastDate.setPromptText(pattern.toLowerCase());
        }

        @Override
        public String toString(LocalDate date) {
            if (date != null) {
                return dateFormatter.format(date);
            } else {
                return "";
            }
        }

        @Override
        public LocalDate fromString(String string) {
            if (string != null && !string.isEmpty()) {
                return LocalDate.parse(string, dateFormatter);
            } else {
                return null;
            }
        }
    });

    //This deals with the bug located here where the datepicker value is not updated on focus lost
    //https://bugs.openjdk.java.net/browse/JDK-8092295?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel
    dtp_lastDate.focusedProperty().addListener(new ChangeListener<Boolean>() {
        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            if (!newValue) {
                dtp_lastDate
                        .setValue(dtp_lastDate.getConverter().fromString(dtp_lastDate.getEditor().getText()));
            }
        }
    });
}

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

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

    String display = context.getParameter("display", config.getDisplayGoogleTarget());
    if (!Config.VALID_DISPLAY_GOOGLE_TARGET.contains(display) && !"export".equals(display)) {
        display = Config.DEFAULT_DISPLAY_GOOGLE_TARGET;
    }/*from w w  w. jav a 2  s . c  om*/

    if (target == null) {
        context.getFlashScope().error("error.invalidTarget");
        return Results.redirect(
                router.getReverseRoute(GoogleGroupController.class, "view", "groupId", group.getId()));
    }

    Run minRun = baseDB.run.findFirst(group.getModule(), RunDB.STATUSES_DONE, null);
    Run maxRun = baseDB.run.findLast(group.getModule(), RunDB.STATUSES_DONE, null);

    if (maxRun == null || minRun == null || searches.isEmpty()) {
        String fallbackDisplay = "export".equals(display) ? "table" : display;
        return Results.ok()
                .template("/serposcope/views/google/GoogleTargetController/" + fallbackDisplay + ".ftl.html")
                .render("startDate", "").render("endDate", "").render("display", fallbackDisplay)
                .render("target", target);
    }

    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(group.getModule(), RunDB.STATUSES_DONE, startDate);
    Run lastRun = baseDB.run.findLast(group.getModule(), RunDB.STATUSES_DONE, endDate);

    List<Run> runs = baseDB.run.listDone(firstRun.getId(), lastRun.getId());

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

    switch (display) {
    case "table":
    case "variation":
        return Results.ok().template("/serposcope/views/google/GoogleTargetController/" + display + ".ftl.html")
                .render("target", target).render("searches", searches).render("startDate", startDate.toString())
                .render("endDate", endDate.toString()).render("minDate", minDay).render("maxDate", maxDay)
                .render("display", display);
    case "chart":
        return renderChart(group, target, searches, runs, minDay, maxDay, startDate, endDate);
    case "export":
        return renderExport(group, target, searches, runs, minDay, maxDay, startDate, endDate);
    default:
        throw new IllegalStateException();
    }

}