Example usage for java.time LocalTime parse

List of usage examples for java.time LocalTime parse

Introduction

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

Prototype

public static LocalTime parse(CharSequence text) 

Source Link

Document

Obtains an instance of LocalTime from a text string such as 10:15 .

Usage

From source file:Main.java

public static void main(String[] args) {
    LocalTime l = LocalTime.parse("12:34");

    System.out.println(l);
}

From source file:org.dozer.converters.LocalTimeConverter.java

@Override
public Object convert(Class destClass, Object srcObj) {
    LocalTime convertedValue = null;
    try {//  w  w  w .java 2s .com
        if (srcObj instanceof String) {
            convertedValue = LocalTime.parse((String) srcObj);
        } else {
            LocalTime srcObject = (LocalTime) srcObj;
            convertedValue = LocalTime.of(srcObject.getHour(), srcObject.getMinute(), srcObject.getSecond(),
                    srcObject.getNano());
        }
    } catch (Exception e) {
        MappingUtils.throwMappingException("Cannot convert [" + srcObj + "] to LocalTime.", e);
    }
    return convertedValue;
}

From source file:org.openmhealth.shim.fitbit.mapper.FitbitIntradayStepCountDataPointMapper.java

@Override
protected Optional<DataPoint<StepCount>> asDataPoint(JsonNode listEntryNode) {

    BigDecimal stepCountValue = asRequiredBigDecimal(listEntryNode, "value");

    if (stepCountValue.intValue() == 0) {
        return Optional.empty();
    }/*from  w  w  w  . java2  s. c o m*/

    StepCount.Builder stepCountBuilder = new StepCount.Builder(stepCountValue);

    Optional<LocalDate> dateFromParent = getDateFromSummaryForDay();

    if (dateFromParent.isPresent()) {

        // Set the effective time frame only if we have access to the date and time
        asOptionalString(listEntryNode, "time").ifPresent(time -> stepCountBuilder.setEffectiveTimeFrame(
                ofStartDateTimeAndDuration(dateFromParent.get().atTime(LocalTime.parse(time)).atOffset(UTC),
                        new DurationUnitValue(MINUTE, 1)))); // We use 1 minute since the shim requests data at 1 minute granularity
    }

    return Optional.of(newDataPoint(stepCountBuilder.build(), null));
}

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

@Test
public void testSaveBooking() throws Exception {
    int personPk = analyticalDatastoreDAO.savePerson(getStaticPerson());
    assertEquals(1, personPk);//from ww w  . j  a  va2s .c  om

    Booking booking = new Booking();

    booking.setPersonId(personPk);
    booking.setBookingDate(LocalDate.parse("2013-12-17"));
    booking.setBookingTime(LocalTime.parse("09:30:00"));
    booking.setScheduledReleaseDate(LocalDate.parse("2014-12-17"));
    booking.setFacilityId(1);
    booking.setSupervisionUnitTypeId(2);
    booking.setBookingNumber("bookingNumber");
    booking.setInmateJailResidentIndicator(true);

    int bookingPk = analyticalDatastoreDAO.saveBooking(booking);
    assertEquals(1, bookingPk);

    analyticalDatastoreDAO.deleteBooking(bookingPk);

    Booking matchingBooking = analyticalDatastoreDAO.getBookingByBookingNumber("bookingNumber");
    assertNull(matchingBooking);

    personPk = analyticalDatastoreDAO.savePerson(getStaticPerson());
    booking.setPersonId(personPk);

    //Perform an subsequent save and confirm the same PK
    booking.setBookingId(bookingPk);
    int updatedbookingId = analyticalDatastoreDAO.saveBooking(booking);
    assertEquals(updatedbookingId, bookingPk);

}

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

@FilterWith(XSRFFilter.class)
public Result update(Context context, @Param("displayHome") String displayHome,
        @Param("displayGoogleTarget") String displayGoogleTarget,
        @Param("displayGoogleSearch") String displayGoogleSearch, @Param("cronTime") String cronTime,
        @Param("dbcUser") String dbcUser, @Param("dbcPass") String dbcPass,
        @Param("decaptcherUser") String decaptcherUser, @Param("decaptcherPass") String decaptcherPass,
        @Param("anticaptchaApiKey") String anticaptchaApiKey, @Param("pruneRuns") Integer pruneRuns) {
    FlashScope flash = context.getFlashScope();

    Config config = new Config();

    if (cronTime == null || cronTime.isEmpty()) {
        config.setCronTime("");
    } else {/*from   w w  w .j  a  v a 2s  .co m*/
        try {
            config.setCronTime(LocalTime.parse(cronTime));
        } catch (Exception ex) {
            flash.error("admin.settings.cronTimeError");
            return Results.redirect(router.getReverseRoute(SettingsController.class, "settings"));
        }
        //            Matcher matcher = PATTERN_CRONTIME.matcher(cronTime);
        //            if(!matcher.find()){
        //                flash.error("admin.settings.cronTimeError");
        //                return Results.redirect(router.getReverseRoute(SettingsController.class, "settings"));
        //            }
        //            config.setCronTime(LocalTime.of(Integer.parseInt(matcher.group(0)), Integer.parseInt(matcher.group(1))));
    }

    if (!Validator.isEmpty(dbcUser) && !Validator.isEmpty(dbcPass)) {
        config.setDbcUser(dbcUser);
        config.setDbcPass(dbcPass);
    }

    if (!Validator.isEmpty(decaptcherUser) && !Validator.isEmpty(decaptcherPass)) {
        config.setDecaptcherUser(decaptcherUser);
        config.setDecaptcherPass(decaptcherPass);
    }

    if (!Validator.isEmpty(anticaptchaApiKey)) {
        config.setAnticaptchaKey(anticaptchaApiKey);
    }

    if (pruneRuns == null || pruneRuns == 0) {
        config.setPruneRuns(0);
    } else {
        config.setPruneRuns(pruneRuns);
    }

    if (displayHome != null && !Config.DEFAULT_DISPLAY_HOME.equals(displayHome)
            && Config.VALID_DISPLAY_HOME.contains(displayHome)) {
        config.setDisplayHome(displayHome);
    }

    if (displayGoogleTarget != null && !Config.DEFAULT_DISPLAY_GOOGLE_TARGET.equals(displayGoogleTarget)
            && Config.VALID_DISPLAY_GOOGLE_TARGET.contains(displayGoogleTarget)) {
        config.setDisplayGoogleTarget(displayGoogleTarget);
    }

    if (displayGoogleSearch != null && !Config.DEFAULT_DISPLAY_GOOGLE_SEARCH.equals(displayGoogleSearch)
            && Config.VALID_DISPLAY_GOOGLE_SEARCH.contains(displayGoogleSearch)) {
        config.setDisplayGoogleSearch(displayGoogleSearch);
    }

    baseDB.config.updateConfig(config);

    flash.success("label.settingsUpdated");
    return Results.redirect(router.getReverseRoute(SettingsController.class, "settings"));
}

From source file:agendapoo.Control.ControlAtividade.java

/**
 * Mtodo responsvel por construir um objeto de Atividade e logo em seguida, Cadastra-lo no banco, seja usando arquivo ou um sgbd.
 * @param descricao - A descrio da atividade
 * @param local - O local em que a atividade ser realizada
 * @param data - A data que a atividade ser realizada
 * @param horaInicio - O horrio que a atividade comea.
 * @param horaFim - O horrio que a atividade termina.
 * @param convidados - Os convidados que participaro da atividade e sero notificados por e-mail sobre a atividade.
 * @param tipo - O tipo da atividade, podendo ser PROFISSIONAL, ACADEMICO ou PESSOAL.
 * @param u - O Usurio que est cadastrando a atividade.
 * @throws SQLException//from   w  w w.  java2 s .c o m
 * @throws IOException
 * @throws ClassNotFoundException
 * @throws InvalidTimeRangeException - A exceo  lanada caso o horrio inicial da atividade seja maior que o horrio final.
 * @throws TimeInterferenceException - A exceo  lanado caso o horrio da atividade entre em conflito com outras atividades cadastradas.
 * @throws EmailException - A exceo  lanada caso no consiga enviar os e-mails para os convidados da atividade.
 */
@Override
public void cadastraAtividade(String descricao, String local, String data, String horaInicio, String horaFim,
        List<String> convidados, TipoAtividade tipo, Usuario u) throws SQLException, IOException,
        ClassNotFoundException, TimeInterferenceException, InvalidTimeRangeException, EmailException {
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    LocalDate data_aux = LocalDate.parse(data, dtf);
    LocalTime start = LocalTime.parse(horaInicio);
    LocalTime end = LocalTime.parse(horaFim);
    if (start.compareTo(end) == 0)
        throw new TimeInterferenceException("U, sua atividade vai durar 0 minutos? Por favor, ajeita isso!");
    if (!isTimeRangeValid(start, end))
        throw new InvalidTimeRangeException(
                "U, sua atividade vai durar um tempo negativo? Por favor, ajeita isso!");
    if (isValidTimeByUser(data_aux, start, end, u)) {
        Atividade a = new Atividade(descricao, local, data_aux, start, end, tipo, u);
        a.setConvidados(convidados);
        if (!convidados.isEmpty())
            sender.sendEmail(a, a.getUsuario(), TipoEmail.CREATE);
        dao.add(a);
    } else
        throw new TimeInterferenceException(
                "Houve um choque de horrio com outras atividades cadastradas. \nPor favor, selecione um outro horrio!");
}

From source file:de.dplatz.padersprinter.control.TripService.java

Optional<Trip> parseTrip(Node node) {
    final XPath xpath = XPathFactory.newInstance().newXPath();
    final LocalTime begin;
    final LocalTime end;
    final String duration;
    final int transferCount;
    try {/*from   w  ww . j  a v  a 2 s. c  om*/
        begin = LocalTime.parse(parseStringNode(node,
                "./div[contains(@class, 'panel-heading')]/table[contains(@class, 'tripTable')]//tbody/tr/td[2]/text()",
                xpath));
        end = LocalTime.parse(parseStringNode(node,
                "./div[contains(@class, 'panel-heading')]/table[contains(@class, 'tripTable')]//tbody/tr/td[3]/text()",
                xpath));
        duration = parseStringNode(node,
                "./div[contains(@class, 'panel-heading')]/table[contains(@class, 'tripTable')]//tbody/tr/td[4]/text()",
                xpath);
        transferCount = parseIntegerNode(node,
                "./div[contains(@class, 'panel-heading')]/table[contains(@class, 'tripTable')]//tbody/tr/td[5]/text()",
                xpath);
    } catch (Exception ex) {
        logger.log(Level.ERROR, null, ex);
        return Optional.empty();
    }

    Optional<List<Leg>> legs = parseLegs(node);
    if (legs.isPresent()) {
        Trip t = new Trip(begin, end, duration, transferCount, legs.get());
        logger.debug("Parsed trip: " + t);
        return Optional.of(t);
    } else {
        return Optional.empty();
    }
}

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 w  ww. j  ava 2 s. c o  m
    });

    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:net.jmhertlein.alphonseirc.MSTDeskEngRunner.java

private static void loadConfig() {
    boolean read = false;
    File f = CONFIG_FILE;/*from  w w w.ja va 2s. c o  m*/
    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:de.dplatz.padersprinter.control.TripService.java

Optional<Leg> parseLeg(Node legNode, XPath xpath) throws XPathExpressionException {
    final Node startNode = getNode(legNode, "./tbody/tr[./td[text() = 'ab']]", xpath);
    final Node endNode = getNode(legNode, "./tbody/tr[./td[text() = 'an']]", xpath);

    LocalTime startTime = LocalTime.parse(parseStringNode(startNode, "./td[1]", xpath));
    String startLocation = parseStringNode(startNode, "./td[4]", xpath);

    LocalTime endTime = LocalTime.parse(parseStringNode(endNode, "./td[1]", xpath));
    String endLocation = parseStringNode(endNode, "./td[4]", xpath);

    if (isNodePresent(legNode, ".//i[contains(@class, 'icon-pedestrian')]", xpath)) {
        final String id = parseStringNode(legNode,
                "./tbody/tr[.//i[contains(@class, 'icon-pedestrian')]]/td[4]", xpath);
        Leg l = new Leg(Transport.walk(id), startTime, startLocation, endTime, endLocation);
        return Optional.of(l);
    } else if (isNodePresent(legNode, ".//i[contains(@class, 'fa-bus')]", xpath)) {
        final String id = parseStringNode(legNode, "./tbody/tr[.//i[contains(@class, 'fa-bus')]]/td[4]", xpath);
        Leg l = new Leg(Transport.bus(id), startTime, startLocation, endTime, endLocation);
        return Optional.of(l);
    } else {//  ww w.  ja v a  2  s  . co m
        logger.debug("Unknown leg-type: " + legNode);
        return Optional.empty();
    }
}