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, DateTimeFormatter formatter) 

Source Link

Document

Obtains an instance of LocalDate from a text string using a specific formatter.

Usage

From source file:controller.SignUpController.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*ww  w.j av 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 {

    CreditDao creditDao = new CreditDaoImpl();

    try {

        boolean creditExist = false;

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> it = items.iterator();
        HttpSession session = request.getSession(false);
        User user = new User();
        Credit credit = new Credit();
        UserDao userDaoImpl = new UserDaoImpl();
        ArrayList<String> newInterests = new ArrayList<>();
        while (it.hasNext()) {
            FileItem item = it.next();
            if (!item.isFormField()) {
                byte[] image = item.get();
                if (image != null && image.length != 0) {
                    user.setImage(image);
                }
                System.out.println(user.getImage());
            } else {
                switch (item.getFieldName()) {
                case "name":
                    user.setUserName(item.getString());
                    break;
                case "mail":
                    user.setEmail(item.getString());

                    break;
                case "password":
                    user.setPassword(item.getString());
                    break;
                case "job":
                    user.setJob(item.getString());
                    break;
                case "date":
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    LocalDate date = LocalDate.parse(item.getString(), formatter);
                    user.setDOB(date);
                    break;
                case "address":
                    user.setAddress(item.getString());
                    break;
                case "credit":
                    user.setCreditNumber(item.getString());
                    credit.setNumber(item.getString());
                    if (creditDao.checkCredit(credit)) {//credit number is exist is 
                        if (!(userDaoImpl.isCreditNumberAssigned(credit))) {
                            creditExist = true;
                            System.out.println("creditExist = true;");
                        } else {

                            creditExist = false;
                            System.out.println("creditExist = falsefalse;");

                        }
                    } else {
                        creditExist = false;

                        System.out.println("creditExist=false;");

                    }
                    break;

                default:
                    newInterests.add(item.getString());
                    System.out.println(item.getFieldName() + " : " + item.getString());
                }
            }
        }

        // check if user exist in Db 
        if (creditExist) {
            user.setInterests(newInterests);
            UserDaoImpl userDao = new UserDaoImpl();

            //
            userDao.signUp(user);
            session.setAttribute("user", user);

            System.out.println(user.getInterests());
            System.out.println(user.getImage());

            response.sendRedirect("index.jsp");
        } else {

            response.sendRedirect("sign_up.jsp");
            System.out.println("user didnt saved");

        }
    } catch (FileUploadException ex) {
        Logger.getLogger(SignUpController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:squash.booking.lambdas.core.RuleManagerTest.java

@Before
public void beforeTest() {

    // Set up the rules' booking
    ruleBookingDate = "2016-07-21"; // Thursday
    ruleBooking = new Booking(1, 2, 3, 2, "J.Power/A.Shabana");
    ruleBooking.setDate(ruleBookingDate);

    // Set up the existing test booking rules
    existingThursdayNonRecurringRule = new BookingRule(ruleBooking, false, new String[0]);
    // Tweak day-of-week to avoid clash
    String newDate = LocalDate.parse(ruleBookingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).plusDays(1)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    ruleBooking.setDate(newDate); // Friday;
    existingFridayRecurringRuleWithoutExclusions = new BookingRule(ruleBooking, true, new String[0]);
    // Tweak day-of-week again to avoid clash
    newDate = LocalDate.parse(ruleBookingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).plusDays(2)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    ruleBooking.setDate(newDate); // Saturday
    // Create an exclusion date
    ruleExclusionDate = "2016-09-17"; // Saturday
    existingSaturdayRecurringRuleWithExclusion = new BookingRule(ruleBooking, true,
            new String[] { ruleExclusionDate });
    existingBookingRules = new ArrayList<>();
    existingBookingRules.add(existingThursdayNonRecurringRule);
    existingBookingRules.add(existingFridayRecurringRuleWithoutExclusions);
    existingBookingRules.add(existingSaturdayRecurringRuleWithExclusion);

    // Set up mock logger
    mockLogger = mockery.mock(LambdaLogger.class);
    mockery.checking(new Expectations() {
        {/*from   w w  w  . j a va 2  s  .com*/
            ignoring(mockLogger);
        }
    });
    mockBookingManager = mockery.mock(IBookingManager.class);
    mockOptimisticPersister = mockery.mock(IOptimisticPersister.class);

    // Set up mock lifecycle manager
    mockLifecycleManager = mockery.mock(ILifecycleManager.class);
    mockery.checking(new Expectations() {
        {
            ignoring(mockLifecycleManager);
        }
    });

    // Set up the rule manager
    fakeCurrentSaturdayDate = LocalDate.of(2015, 12, 24);
    fakeCurrentSaturdayDateString = fakeCurrentSaturdayDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    ruleManager = new squash.booking.lambdas.core.RuleManagerTest.TestRuleManager();
    ruleManager.setOptimisticPersister(mockOptimisticPersister);
    ruleManager.setCurrentLocalDate(fakeCurrentSaturdayDate);
    adminSnsTopicArn = "adminSnsTopicArn";
    ruleManager.setAdminSnsTopicArn(adminSnsTopicArn);

    ruleItemName = "BookingRulesAndExclusions";
}

From source file:agendavital.modelo.data.Noticia.java

/**
 * Funcion coloreadora del calendario/*  w ww .  j  ava 2  s . c  o m*/
 *
 * @return
 * @throws agendavital.modelo.excepciones.ConexionBDIncorrecta
 *
 */
public static TreeMap<LocalDate, String> getNoticiasFecha() throws ConexionBDIncorrecta {
    ResultSet rs = null;
    TreeMap<LocalDate, String> noticias = new TreeMap<>();
    try (Connection conexion = ConfigBD.conectar()) {
        String consulta = String.format("SELECT categoria, fecha from Noticias;");
        rs = conexion.createStatement().executeQuery(consulta);
        while (rs.next()) {
            String categoria = rs.getString("categoria");
            String fecha = rs.getString("fecha");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
            LocalDate date = LocalDate.parse(fecha, formatter);
            noticias.put(date, categoria);
        }
    } catch (SQLException e) {
        throw new ConexionBDIncorrecta();
    }
    return noticias;
}

From source file:eg.agrimarket.controller.SignUpController.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from w w w . j ava  2  s  . 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 {

    CreditDao creditDao = new CreditDaoImpl();

    try {

        boolean creditExist = false;

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> it = items.iterator();
        HttpSession session = request.getSession(false);
        User user = new User();
        Credit credit = new Credit();
        UserDao userDaoImpl = new UserDaoImpl();
        ArrayList<eg.agrimarket.model.dto.Interest> newInterests = new ArrayList<>();
        while (it.hasNext()) {
            FileItem item = it.next();
            if (!item.isFormField()) {
                byte[] image = item.get();
                if (image != null && image.length != 0) {
                    user.setImage(image);
                }
                System.out.println(user.getImage());
            } else {
                switch (item.getFieldName()) {
                case "name":
                    user.setUserName(item.getString());
                    break;
                case "mail":
                    user.setEmail(item.getString());

                    break;
                case "password":
                    user.setPassword(item.getString());
                    break;
                case "job":
                    user.setJob(item.getString());
                    break;
                case "date":
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    LocalDate date = LocalDate.parse(item.getString(), formatter);
                    user.setDOB(date);
                    break;
                case "address":
                    user.setAddress(item.getString());
                    break;
                case "credit":
                    user.setCreditNumber(item.getString());
                    credit.setNumber(item.getString());
                    if (creditDao.checkCredit(credit)) {//credit number is exist is 
                        if (!(userDaoImpl.isCreditNumberAssigned(credit))) {
                            creditExist = true;
                            System.out.println("creditExist = true;");
                        } else {

                            creditExist = false;
                            System.out.println("creditExist = falsefalse;");

                        }
                    } else {
                        creditExist = false;

                        System.out.println("creditExist=false;");

                    }
                    break;

                default:
                    eg.agrimarket.model.dto.Interest interest = new eg.agrimarket.model.dto.Interest();
                    interest.setId(Integer.parseInt(item.getString()));
                    interest.setName(item.getFieldName());
                    newInterests.add(interest);
                    System.out.println(item.getFieldName() + " : " + item.getString());
                }
            }
        }

        // check if user exist in Db 
        if (creditExist) {
            user.setInterests(newInterests);
            UserDaoImpl userDao = new UserDaoImpl();

            //
            userDao.signUp(user);
            session.setAttribute("user", user);

            System.out.println(user.getInterests());
            System.out.println(user.getImage());

            response.sendRedirect("index.jsp");
        } else {

            response.sendRedirect("sign_up.jsp");
            System.out.println("user didnt saved");

        }
    } catch (FileUploadException ex) {
        Logger.getLogger(SignUpController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:io.manasobi.utils.DateUtils.java

/**
 * ? ? ?? ?  ?.<br><br>//from  w  ww  . j  av  a 2  s .co  m
 *
 * DateUtils.equals(new LocalDate(1292252400000l), "2010/12/14", "yyyy/MM/dd") = true
 *
 * @param date Date? ??
 * @param dateStr ?? ??
 * @param pattern  ?
 * @return ? ? ??  true  false .
 */
public static boolean equals(LocalDate date, String dateStr, String pattern) {

    java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern(pattern);
    LocalDate parsedDate = LocalDate.parse(dateStr, formatter);

    return equals(date, parsedDate);
}

From source file:agendapoo.View.FrmMinhaAtividade.java

private void saveChanges(Atividade a) throws SQLException, IOException, ClassNotFoundException, EmailException,
        InvalidTimeRangeException, TimeInterferenceException {
    List<String> lista = new ArrayList<>();
    getStringListFromListModel().stream().forEach((email) -> {
        lista.add(email);//from ww  w . ja  va  2  s.c om
    });

    selectedAtividade.setConvidados(lista);
    selectedAtividade.setData(LocalDate.parse(textData.getText(), DateTimeFormatter.ofPattern("dd/MM/yyyy")));
    selectedAtividade.setHoraInicio(LocalTime.parse(textHoraInicio.getText()));
    selectedAtividade.setHoraFim(LocalTime.parse(textHoraFinal.getText()));
    selectedAtividade.setLocal(textLocal.getText());
    selectedAtividade.setTipo(TipoAtividade.valueOf(comboTipoAtividade.getSelectedItem().toString()));
    AtividadeController ca = new ControlAtividade();
    ca.atualizaAtividade(a);
}

From source file:com.publictransitanalytics.scoregenerator.datalayer.directories.GTFSReadingServiceTypeCalendar.java

private void parseCalendarDatesFile(final Reader calendarDatesReader,
        final Multimap<LocalDate, String> serviceTypesMap) throws FileNotFoundException, IOException {

    final CSVParser calendarDatesParser = new CSVParser(calendarDatesReader, CSVFormat.DEFAULT.withHeader());
    final List<CSVRecord> calendarDatesRecords = calendarDatesParser.getRecords();

    for (final CSVRecord record : calendarDatesRecords) {
        final String serviceType = record.get("service_id");
        final LocalDate date = LocalDate.parse(record.get("date"), DateTimeFormatter.BASIC_ISO_DATE);
        final String exceptionType = record.get("exception_type");

        switch (exceptionType) {
        case "1":
            serviceTypesMap.put(date, serviceType);
            break;
        case "2":
            serviceTypesMap.remove(date, serviceType);
            break;
        default:/*from  w  w w .ja va 2 s. c o m*/
            throw new ScoreGeneratorFatalException(String.format("Invalid exception type %s", exceptionType));
        }
    }
}

From source file:org.tightblog.rendering.requests.WeblogPageRequest.java

static boolean isValidDateString(String dateString) {
    boolean valid = false;

    if (StringUtils.isNumeric(dateString) && (dateString.length() == 6 || dateString.length() == 8)) {
        try {/* w w  w. ja  v  a 2  s .  com*/
            if (dateString.length() == 6) {
                LocalDate.parse(dateString + "01", Utilities.YMD_FORMATTER);
            } else {
                LocalDate.parse(dateString, Utilities.YMD_FORMATTER);
            }
            valid = true;
        } catch (DateTimeParseException ignored) {
        }
    }
    return valid;
}

From source file:de.steilerdev.myVerein.server.controller.admin.EventManagementController.java

/**
 * Returns all events, that are taking place on a specified date. The date parameter needs to be formatted according to the following pattern: YYYY/MM/DD. This function is invoked by GETting the URI /api/admin/event/date
 * @param date The selected date, correctly formatted (YYYY/MM/DD)
 * @return An HTTP response with a status code. If the function succeeds, a list of events is returned, otherwise an error code is returned.
 *///from   w  ww  . j  a  va  2 s.  co  m
@RequestMapping(value = "date", produces = "application/json", method = RequestMethod.GET)
public ResponseEntity<List<Event>> getEventsOfDate(@RequestParam String date, @CurrentUser User currentUser) {
    logger.trace("[" + currentUser + "] Getting events of date " + date);
    LocalDateTime startOfDay, endOfDay, startOfMonth, endOfMonth;
    ArrayList<Event> eventsOfDay = new ArrayList<>();
    try {
        // Get start of day and start of next day
        startOfDay = LocalDate.parse(date, DateTimeFormatter.ISO_LOCAL_DATE).atStartOfDay();
        endOfDay = startOfDay.plusDays(1);

        startOfMonth = LocalDate.of(startOfDay.getYear(), startOfDay.getMonth(), 1).atStartOfDay();
        endOfMonth = startOfMonth.plusMonths(1);
        logger.debug("[" + currentUser + "] Converted to date object: " + startOfDay.toString());
    } catch (DateTimeParseException e) {
        logger.warn("[" + currentUser + "] Unable to parse date: " + date + ": " + e.toString());
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    logger.debug("Getting all single day events...");
    eventsOfDay.addAll(eventRepository.findAllByStartDateTimeBetweenAndMultiDate(startOfDay, endOfDay, false));
    logger.debug("All single day events retrieved, got " + eventsOfDay.size() + " events so far");

    logger.debug("Getting all multi day events...");
    //Collecting all multi date events, that either start or end within the selected month (which means that events that are spanning over several months are not collected)
    eventsOfDay.addAll(Stream.concat(
            eventRepository.findAllByStartDateTimeBetweenAndMultiDate(startOfMonth, endOfMonth, true).stream(), //All multi date events starting within the month
            eventRepository.findAllByEndDateTimeBetweenAndMultiDate(startOfMonth, endOfMonth, true).stream()) //All multi date events ending within the month
            .distinct() //Removing all duplicated events
            .parallel()
            .filter(event -> event.getStartDate().isEqual(startOfDay.toLocalDate())
                    || event.getEndDate().isEqual(startOfDay.toLocalDate())
                    || (event.getEndDate().isAfter(endOfDay.toLocalDate())
                            && event.getStartDate().isBefore(startOfDay.toLocalDate()))) //Filter all multi date events that do not span over the date
            .collect(Collectors.toList()));
    logger.debug("All multi day events gathered, got " + eventsOfDay.size() + " events so far");

    if (eventsOfDay.isEmpty()) {
        logger.warn("[" + currentUser + "] The events list of " + date + " is empty");
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    } else {
        eventsOfDay.replaceAll(Event::getSendingObjectOnlyNameTimeId);
        logger.debug("[" + currentUser + "] Returning " + eventsOfDay.size() + " events for " + date);
        return new ResponseEntity<>(eventsOfDay, HttpStatus.OK);
    }
}

From source file:org.talend.dataprep.transformation.actions.date.DateParser.java

/**
 * Parse the date from the given patterns.
 *
 * @param value the text to parse.//  w  w  w.  j  ava 2 s .c  o m
 * @param patterns the patterns to use.
 * @return the parsed date-time
 */
public LocalDateTime parseDateFromPatterns(String value, List<DatePattern> patterns) {

    // take care of the null value
    if (value == null) {
        throw new DateTimeException("cannot parse null");
    }

    for (DatePattern pattern : patterns) {
        final DateTimeFormatter formatter = new DateTimeFormatterBuilder().parseCaseInsensitive()
                .append(pattern.getFormatter()).toFormatter(Locale.ENGLISH);

        // first try to parse directly as LocalDateTime
        try {
            return LocalDateTime.parse(value, formatter);
        } catch (DateTimeException e) {
            LOGGER.trace("Unable to parse date '{}' using LocalDateTime.", value, e);
            // if it fails, let's try the LocalDate first
            try {
                LocalDate temp = LocalDate.parse(value, formatter);
                return temp.atStartOfDay();
            } catch (DateTimeException e2) {
                LOGGER.trace("Unable to parse date '{}' using LocalDate.", value, e2);
                // nothing to do here, just try the next formatter
            }
        }
    }
    throw new DateTimeException("'" + value + "' does not match any known pattern");
}