Example usage for java.sql Time valueOf

List of usage examples for java.sql Time valueOf

Introduction

In this page you can find the example usage for java.sql Time valueOf.

Prototype

@SuppressWarnings("deprecation")
public static Time valueOf(LocalTime time) 

Source Link

Document

Obtains an instance of Time from a LocalTime object with the same hour, minute and second time value as the given LocalTime .

Usage

From source file:org.motechproject.server.omod.web.controller.MotechModuleFormController.java

@RequestMapping(value = "/module/motechmodule/blackout", method = RequestMethod.POST)
public String saveBlackoutSettings(@RequestParam("startTime") String startTime,
        @RequestParam("endTime") String endTime, ModelMap model) {

    MotechService motechService = contextService.getMotechService();
    Blackout blackout = motechService.getBlackoutSettings();

    Time startTimeCvt = Time.valueOf(startTime);
    Time endTimeCvt = Time.valueOf(endTime);

    if (blackout != null) {
        blackout.setStartTime(startTimeCvt);
        blackout.setEndTime(endTimeCvt);
    } else {/*from   w w  w. ja va2s .c o m*/
        blackout = new Blackout(startTimeCvt, endTimeCvt);
    }

    motechService.setBlackoutSettings(blackout);

    model.addAttribute("startTime", blackout.getStartTime());
    model.addAttribute("endTime", blackout.getEndTime());

    return "/module/motechmodule/blackout";
}

From source file:main.UIController.java

public Time calculateSunset(Calendar calendar, String city, String country, boolean useCacheSunset) {
    Time time = null;/*w  w  w .  j ava  2s.c  o m*/
    boolean useCache = useCacheSunset;
    Preferences data = this.getCurrentPreferences();
    if (!useCache) {
        String place = this.makeLocationString(city, country);
        if (place.length() > 0) {
            GeoAddressStandardizer st = new GeoAddressStandardizer(Config.getGoogleMapsApiKey(),
                    Config.getRateLimitInterval());
            HttpClientParams params = st.getHttpClientParams();
            params.setSoTimeout(Config.getConnectionTimeout());
            st.setHttpClientParams(params);
            Location location = null;
            try {
                GeoCoordinate geo = st.standardizeToGeoCoordinate(place);
                double latitude = geo.getLatitude();
                double longitude = geo.getLongitude();
                location = new Location(Double.toString(latitude), Double.toString(longitude));
                String timezone = data.get(FIELD_TIMEZONE, DEF_TIMEZONE);
                SunriseSunsetCalculator calculator = new SunriseSunsetCalculator(location, timezone);
                String sunset = calculator.getOfficialSunsetForDate(calendar) + ":00";
                data.put(FIELD_CACHE_SUNSET, sunset);
                time = Time.valueOf(sunset);
            } catch (GeoException e) {
                useCache = true;
            }
        } else {
            useCache = true;
        }
    }
    if (useCache) {
        String cacheSunset = data.get(FIELD_CACHE_SUNSET, DEF_CACHE_SUNSET);
        if (!cacheSunset.isEmpty()) {
            time = Time.valueOf(cacheSunset);
        }
    }
    return time;
}

From source file:helpers.Methods.java

/**
 * This method will convert time in <b>00:00:00</b> 24 Hours format to date
 * object.//from ww w.  j a va 2 s  .  co m
 *
 * @param time The time string in "hh:mm:ss" format (24 Hours).
 * @return The {@link Date} object of the input time, or null if the input
 * is null.
 */
public static Time getTime(String time) {
    if (time != null) {
        return Time.valueOf(time);
    } else {
        return null;
    }
}

From source file:fr.juanwolf.mysqlbinlogreplicator.component.DomainClassAnalyzer.java

public void instantiateField(Object object, Field field, Object value, int columnType, String tablename)
        throws ParseException, IllegalAccessException {
    field.setAccessible(true);/*from   ww  w .ja v  a  2s. co  m*/
    if (columnType == ColumnType.DATETIME.getCode() && field.getType() == Date.class) {
        Date date = BINLOG_DATETIME_FORMATTER.parse((String) value);
        field.set(object, date);
    } else if (columnType == ColumnType.DATE.getCode() && field.getType() == Date.class) {
        Date date = BINLOG_DATE_FORMATTER.parse((String) value);
        field.set(object, date);
    } else if (columnType == ColumnType.DATETIME.getCode() && field.getType() == String.class) {
        Date date = BINLOG_DATETIME_FORMATTER.parse((String) value);
        if (binlogOutputDateFormatter != null) {
            field.set(object, binlogOutputDateFormatter.format(date));
        } else {
            log.warn("No date.output DateFormat found in your property file. If you want anything else than"
                    + "the timestamp as output of your date, set this property with a java DateFormat.");
            field.set(object, date.toString());
        }
    } else if (columnType == ColumnType.TIME.getCode() && field.getType() == Time.class) {
        Time time = Time.valueOf((String) value);
        field.set(object, time);
    } else if (columnType == ColumnType.TIMESTAMP.getCode() || field.getType() == Timestamp.class) {
        Timestamp timestamp = Timestamp.valueOf((String) value);
        field.set(object, timestamp);
    } else if ((columnType == ColumnType.BIT.getCode() || columnType == ColumnType.TINY.getCode())
            && field.getType() == boolean.class) {
        boolean booleanField = ((Byte) value) != 0;
        field.set(object, booleanField);
    } else if (columnType == ColumnType.LONG.getCode() && field.getType() == long.class) {
        field.set(object, Long.parseLong((String) value));
    } else if (columnType == ColumnType.LONG.getCode() && isInteger(field)) {
        field.set(object, Integer.parseInt((String) value));
    } else if (columnType == ColumnType.FLOAT.getCode() && field.getType() == float.class) {
        field.set(object, Float.parseFloat((String) value));
    } else if (field.getType() == String.class) {
        field.set(object, value);
    } else {
        if (mappingTablesExpected.contains(tablename)) {
            Object nestedObject = generateNestedField(field, value, tablename);
            field.set(object, nestedObject);
        }
    }
}

From source file:main.UIController.java

public void showDateOfToday(boolean useCacheSunset) {
    Preferences data = this.getCurrentPreferences();
    String city = data.get(FIELD_CITY, DEF_CITY);
    String country = data.get(FIELD_COUNTRY, DEF_COUNTRY);
    TimeZone tz = TimeZone.getTimeZone(data.get(FIELD_TIMEZONE, DEF_TIMEZONE));
    GregorianCalendar gcal = new GregorianCalendar(tz);
    Time time = this.calculateSunsetForActualLocation(gcal, useCacheSunset);
    ImladrisCalendar cal;/*from  w ww.  j  a v a  2s  .co  m*/
    String sunsetStr = "";
    String locationInfo = "";
    if (time == null) {
        cal = new ImladrisCalendar(gcal);
    } else {
        cal = new ImladrisCalendar(time, gcal);
        /*check if before sunset*/
        String gtimeStr = gcal.get(GregorianCalendar.HOUR_OF_DAY) + ":" + gcal.get(GregorianCalendar.MINUTE)
                + ":" + gcal.get(GregorianCalendar.SECOND);
        Time gtime = Time.valueOf(gtimeStr);
        if (gtime.before(time)) { // before sunset
            sunsetStr = " - before sunset";
        } else { // after/during sunset
            sunsetStr = " - after sunset";
        }
        String sunsetTimeStr = time.toString();
        sunsetTimeStr = sunsetTimeStr.substring(0, sunsetTimeStr.length() - 3);
        sunsetStr += " " + Lang.punctuation.parenthesis_open + "occurring at " + sunsetTimeStr
                + Lang.punctuation.parenthesis_close;
        locationInfo = this.makeLocationString(city, country);
        if (locationInfo.length() > 0) {
            locationInfo = Lang.punctuation.parenthesis_open + Lang.common.location_label
                    + Lang.punctuation.double_dot + " " + locationInfo + " " + Lang.punctuation.pipe + " "
                    + Lang.common.timezone_label + Lang.punctuation.double_dot + " "
                    + data.get(FIELD_TIMEZONE, DEF_TIMEZONE) + Lang.punctuation.parenthesis_close;
        }
    }
    String gstr = this.gregorianToString(gcal);
    String istr = cal.toString();
    UI ui = this.getUi();
    ui.getTodayGregorian().setText(gstr + sunsetStr);
    ui.getTodayImladris().setText(istr);
    ui.getLocationInfo().setText(locationInfo);
}

From source file:controller.PlayController.java

public List<Play> filterPlays(Play play, List<Play> plays) {
    Predicate<Play> selector = p -> p != null;
    String playName = play.getPlayName();
    Integer ticketPrice = play.getTicketPrice();
    if (playName != null && !playName.equals("")) {
        selector = selector.and(p -> p.getPlayName().equals(playName));
    }//  www  .j av  a  2  s .  co m
    if (play.getStartTime() != null) {
        Time startTime = Time.valueOf(play.getStartTime().toString());
        selector = selector.and(p -> (p.getStartTime().after(startTime) || p.getStartTime().equals(startTime)));
    }
    if (play.getEndTime() != null) {
        Time endTime = Time.valueOf(play.getEndTime().toString());
        selector = selector.and(p -> (p.getEndTime().before(endTime) || p.getEndTime().equals(endTime)));
    }
    if (play.getStartDate() != null) {
        Date startDate = Date.valueOf(play.getStartDate().toString());
        selector = selector.and(p -> p.getStartDate().equals(startDate));
    }
    if (ticketPrice != 0) {
        selector = selector.and(p -> p.getTicketPrice() == ticketPrice);
    }
    return lambdaFilter(selector, plays);
}

From source file:edu.ku.brc.specify.toycode.mexconabio.MexConvToSQLNew.java

public void convert(final String tableName, final String fileName) {
    String str = "";
    int fldLen = 0;
    int inx = 0;//from w  w  w  .j  ava  2s  . co  m

    Connection conn = null;
    Statement stmt = null;
    try {
        conn = DriverManager.getConnection(
                "jdbc:mysql://localhost/mex?characterEncoding=UTF-8&autoReconnect=true", "root", "root");
        stmt = conn.createStatement();

        int[] fieldLengths = null;

        BasicSQLUtils.deleteAllRecordsFromTable(conn, tableName, SERVERTYPE.MySQL);
        Vector<Integer> types = new Vector<Integer>();
        Vector<String> names = new Vector<String>();

        String selectStr = null;
        String prepareStr = null;
        try {
            prepareStr = FileUtils.readFileToString(new File("prepare_stmt.txt"));
            selectStr = FileUtils.readFileToString(new File("select.txt"));

        } catch (IOException e) {
            e.printStackTrace();
        }

        int idInx = selectStr.indexOf("ID,");
        if (idInx == 0) {
            selectStr = selectStr.substring(3);
        }

        File file = new File("/Users/rods/Documents/" + fileName);
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        //SimpleDateFormat stf = new SimpleDateFormat("k:mm:ss");

        int rowCnt = 0;
        try {
            System.out.println(prepareStr);

            PreparedStatement pStmt = conn.prepareStatement(prepareStr);
            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"));
            str = in.readLine();

            String[] fieldNames = StringUtils.split(str, ",");
            //String[] fieldNamesDB = StringUtils.split(selectStr, ",");

            String sql = "SELECT " + selectStr + " FROM " + tableName;
            System.out.println(sql);

            ResultSet rs = stmt.executeQuery(sql);
            ResultSetMetaData rsmd = rs.getMetaData();

            fieldLengths = new int[rsmd.getColumnCount()];
            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                fieldLengths[i - 1] = rsmd.getPrecision(i);
                types.add(rsmd.getColumnType(i));
                names.add(rsmd.getColumnName(i));
                System.out.println((i > 1 ? fieldNames[i - 2] : "ID") + " / " + rsmd.getColumnName(i) + " - "
                        + rsmd.getPrecision(i));
            }

            int numCols = rsmd.getColumnCount();
            rs.close();

            System.out.println("Number of Fields: " + numCols);

            str = in.readLine();
            while (str != null) {
                //System.err.println(str);

                str = StringUtils.replace(str.substring(1, str.length() - 1), "\",\"", "|");

                Vector<String> fields = split(str);
                if (fields.size() != numCols) {
                    System.out.println("numCols: " + numCols + " != " + fields.size() + "fields.size()");
                    continue;
                }

                int col = 1;
                inx = 0;
                for (String fld : fields) {
                    String field = fld.trim();
                    //if (field.length() > 1)
                    //{
                    //    field = field.substring(1, field.length()-1);
                    //}
                    //if (inx > 204) break;

                    fldLen = field.length();

                    pStmt.setObject(col, null);

                    switch (types.get(inx)) {
                    case java.sql.Types.LONGVARCHAR:
                    case java.sql.Types.VARCHAR:
                    case java.sql.Types.LONGNVARCHAR: {
                        if (field.length() > 0) {
                            if (field.length() <= fieldLengths[inx]) {
                                pStmt.setString(col, field);
                            } else {
                                System.err.println(String.format("The data for `%s` (%d) is too big %d f[%s]",
                                        names.get(inx), fieldLengths[inx], field.length(), field));
                                pStmt.setString(col, null);
                            }
                        } else {
                            pStmt.setString(col, null);
                        }
                    }
                        break;

                    case java.sql.Types.DOUBLE:
                    case java.sql.Types.FLOAT: {
                        if (StringUtils.isNotEmpty(field)) {
                            if (StringUtils.isNumeric(field)) {
                                pStmt.setDouble(col, field.length() > 0 ? Double.parseDouble(field) : null);
                            } else {
                                System.err.println(col + " Bad Number[" + field + "] ");
                                pStmt.setDate(col, null);
                            }
                        } else {
                            pStmt.setDate(col, null);
                        }
                    }
                        break;

                    case java.sql.Types.INTEGER: {
                        if (StringUtils.isNotEmpty(field)) {
                            if (StringUtils.isNumeric(field)) {
                                pStmt.setInt(col, field.length() > 0 ? Integer.parseInt(field) : null);
                            } else {
                                System.err.println(col + " Bad Number[" + field + "] ");
                                pStmt.setDate(col, null);
                            }
                        } else {
                            pStmt.setDate(col, null);
                        }
                    }
                        break;

                    case java.sql.Types.TIME: {
                        Time time = null;
                        try {
                            time = Time.valueOf(field);
                        } catch (Exception ex) {
                        }
                        pStmt.setTime(col, time);
                    }
                        break;

                    case java.sql.Types.DATE: {
                        try {
                            if (StringUtils.isNotEmpty(field)) {
                                if (StringUtils.contains(field, "/")) {
                                    field = StringUtils.replace(field, "/", "-");
                                } else if (StringUtils.contains(field, " ")) {
                                    field = StringUtils.replace(field, " ", "-");
                                }
                                pStmt.setDate(col,
                                        field.length() > 0 ? new java.sql.Date(sdf.parse(field).getTime())
                                                : null);
                            } else {
                                pStmt.setDate(col, null);
                            }
                        } catch (Exception ex) {
                            System.err.println(col + " Bad Date[" + field + "]\n" + str);
                            pStmt.setDate(col, null);
                        }
                    }
                        break;

                    default: {
                        System.err.println("Error - " + types.get(inx));
                    }
                    }
                    inx++;
                    col++;
                }
                pStmt.execute();
                str = in.readLine();
                rowCnt++;
            }
            in.close();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

        } catch (Exception e) {
            System.err.println("Row: " + rowCnt);
            System.err.println(str);
            System.err.println(inx + "  " + fieldLengths[inx] + " - Field Len: " + fldLen);
            e.printStackTrace();
        }

        /*BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        while (bis.available() > 0)
        {
        int bytesRead = bis.read(bytes);
        if (bytesRead > 0)
        {
            System.arraycopy(bytes, bytesRead, buffer, bufEndInx, bytesRead);
            bufEndInx += bytesRead;
            int inx = 0;
            while (inx < bufEndInx)
            {
                if (buffer[inx] != '\n')
                {
                    String line = 
                }
                inx++;
            }
        }
        }*/

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            stmt.close();
            conn.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:mondrian.spi.impl.JdbcDialectImpl.java

public void quoteTimeLiteral(StringBuilder buf, String value) {
    // NOTE jvs 1-Jan-2007:  See quoteDateLiteral for explanation.
    try {/* w ww  .  j  ava 2 s .  c  om*/
        Time.valueOf(value);
    } catch (IllegalArgumentException ex) {
        throw new NumberFormatException("Illegal TIME literal:  " + value);
    }
    buf.append("TIME ");
    Util.singleQuoteString(value, buf);
}

From source file:fr.juanwolf.mysqlbinlogreplicator.component.DomainClassAnalyzerTest.java

@Test
public void instantiateField_should_set_the_time_with_the_specific_time()
        throws ReflectiveOperationException, ParseException {
    // Given/*from   w w  w.  j a va2s  . com*/
    String timeString = "12:30:15";
    Time time = Time.valueOf(timeString);
    domainClassAnalyzer.postConstruct();
    User user = (User) domainClassAnalyzer.generateInstanceFromName("user");
    // When
    domainClassAnalyzer.instantiateField(user, user.getClass().getDeclaredField("creationTime"), timeString,
            ColumnType.TIME.getCode(), "user");
    // Then
    assertThat(user.getCreationTime()).isEqualTo(time);
}