Example usage for java.sql Time getTime

List of usage examples for java.sql Time getTime

Introduction

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

Prototype

public long getTime() 

Source Link

Document

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

Usage

From source file:org.apache.nifi.avro.AvroTypeUtil.java

@SuppressWarnings("unchecked")
private static Object convertToAvroObject(final Object rawValue, final Schema fieldSchema,
        final String fieldName, final Charset charset) {
    if (rawValue == null) {
        return null;
    }// w  w w  .ja  va 2  s .  c o  m

    switch (fieldSchema.getType()) {
    case INT: {
        final LogicalType logicalType = fieldSchema.getLogicalType();
        if (logicalType == null) {
            return DataTypeUtils.toInteger(rawValue, fieldName);
        }

        if (LOGICAL_TYPE_DATE.equals(logicalType.getName())) {
            final String format = AvroTypeUtil.determineDataType(fieldSchema).getFormat();
            final Date date = DataTypeUtils.toDate(rawValue, () -> DataTypeUtils.getDateFormat(format),
                    fieldName);
            final Duration duration = Duration.between(new Date(0L).toInstant(),
                    new Date(date.getTime()).toInstant());
            final long days = duration.toDays();
            return (int) days;
        } else if (LOGICAL_TYPE_TIME_MILLIS.equals(logicalType.getName())) {
            final String format = AvroTypeUtil.determineDataType(fieldSchema).getFormat();
            final Time time = DataTypeUtils.toTime(rawValue, () -> DataTypeUtils.getDateFormat(format),
                    fieldName);
            final Date date = new Date(time.getTime());
            final Duration duration = Duration.between(date.toInstant().truncatedTo(ChronoUnit.DAYS),
                    date.toInstant());
            final long millisSinceMidnight = duration.toMillis();
            return (int) millisSinceMidnight;
        }

        return DataTypeUtils.toInteger(rawValue, fieldName);
    }
    case LONG: {
        final LogicalType logicalType = fieldSchema.getLogicalType();
        if (logicalType == null) {
            return DataTypeUtils.toLong(rawValue, fieldName);
        }

        if (LOGICAL_TYPE_TIME_MICROS.equals(logicalType.getName())) {
            final long longValue = getLongFromTimestamp(rawValue, fieldSchema, fieldName);
            final Date date = new Date(longValue);
            final Duration duration = Duration.between(date.toInstant().truncatedTo(ChronoUnit.DAYS),
                    date.toInstant());
            return duration.toMillis() * 1000L;
        } else if (LOGICAL_TYPE_TIMESTAMP_MILLIS.equals(logicalType.getName())) {
            final String format = AvroTypeUtil.determineDataType(fieldSchema).getFormat();
            Timestamp t = DataTypeUtils.toTimestamp(rawValue, () -> DataTypeUtils.getDateFormat(format),
                    fieldName);
            return getLongFromTimestamp(rawValue, fieldSchema, fieldName);
        } else if (LOGICAL_TYPE_TIMESTAMP_MICROS.equals(logicalType.getName())) {
            return getLongFromTimestamp(rawValue, fieldSchema, fieldName) * 1000L;
        }

        return DataTypeUtils.toLong(rawValue, fieldName);
    }
    case BYTES:
    case FIXED:
        final LogicalType logicalType = fieldSchema.getLogicalType();
        if (logicalType != null && LOGICAL_TYPE_DECIMAL.equals(logicalType.getName())) {
            final LogicalTypes.Decimal decimalType = (LogicalTypes.Decimal) logicalType;
            final BigDecimal rawDecimal;
            if (rawValue instanceof BigDecimal) {
                rawDecimal = (BigDecimal) rawValue;

            } else if (rawValue instanceof Double) {
                rawDecimal = BigDecimal.valueOf((Double) rawValue);

            } else if (rawValue instanceof String) {
                rawDecimal = new BigDecimal((String) rawValue);

            } else if (rawValue instanceof Integer) {
                rawDecimal = new BigDecimal((Integer) rawValue);

            } else if (rawValue instanceof Long) {
                rawDecimal = new BigDecimal((Long) rawValue);

            } else {
                throw new IllegalTypeConversionException("Cannot convert value " + rawValue + " of type "
                        + rawValue.getClass() + " to a logical decimal");
            }
            // If the desired scale is different than this value's coerce scale.
            final int desiredScale = decimalType.getScale();
            final BigDecimal decimal = rawDecimal.scale() == desiredScale ? rawDecimal
                    : rawDecimal.setScale(desiredScale, BigDecimal.ROUND_HALF_UP);
            return new Conversions.DecimalConversion().toBytes(decimal, fieldSchema, logicalType);
        }
        if (rawValue instanceof byte[]) {
            return ByteBuffer.wrap((byte[]) rawValue);
        }
        if (rawValue instanceof String) {
            return ByteBuffer.wrap(((String) rawValue).getBytes(charset));
        }
        if (rawValue instanceof Object[]) {
            return AvroTypeUtil.convertByteArray((Object[]) rawValue);
        } else {
            throw new IllegalTypeConversionException("Cannot convert value " + rawValue + " of type "
                    + rawValue.getClass() + " to a ByteBuffer");
        }
    case MAP:
        if (rawValue instanceof Record) {
            final Record recordValue = (Record) rawValue;
            final Map<String, Object> map = new HashMap<>();
            for (final RecordField recordField : recordValue.getSchema().getFields()) {
                final Object v = recordValue.getValue(recordField);
                if (v != null) {
                    map.put(recordField.getFieldName(), v);
                }
            }

            return map;
        } else if (rawValue instanceof Map) {
            final Map<String, Object> objectMap = (Map<String, Object>) rawValue;
            final Map<String, Object> map = new HashMap<>(objectMap.size());
            for (final String s : objectMap.keySet()) {
                final Object converted = convertToAvroObject(objectMap.get(s), fieldSchema.getValueType(),
                        fieldName + "[" + s + "]", charset);
                map.put(s, converted);
            }
            return map;
        } else {
            throw new IllegalTypeConversionException(
                    "Cannot convert value " + rawValue + " of type " + rawValue.getClass() + " to a Map");
        }
    case RECORD:
        final GenericData.Record avroRecord = new GenericData.Record(fieldSchema);

        final Record record = (Record) rawValue;
        for (final RecordField recordField : record.getSchema().getFields()) {
            final Object recordFieldValue = record.getValue(recordField);
            final String recordFieldName = recordField.getFieldName();

            final Field field = fieldSchema.getField(recordFieldName);
            if (field == null) {
                continue;
            }

            final Object converted = convertToAvroObject(recordFieldValue, field.schema(),
                    fieldName + "/" + recordFieldName, charset);
            avroRecord.put(recordFieldName, converted);
        }
        return avroRecord;
    case UNION:
        return convertUnionFieldValue(rawValue, fieldSchema,
                schema -> convertToAvroObject(rawValue, schema, fieldName, charset), fieldName);
    case ARRAY:
        final Object[] objectArray = (Object[]) rawValue;
        final List<Object> list = new ArrayList<>(objectArray.length);
        int i = 0;
        for (final Object o : objectArray) {
            final Object converted = convertToAvroObject(o, fieldSchema.getElementType(),
                    fieldName + "[" + i + "]", charset);
            list.add(converted);
            i++;
        }
        return list;
    case BOOLEAN:
        return DataTypeUtils.toBoolean(rawValue, fieldName);
    case DOUBLE:
        return DataTypeUtils.toDouble(rawValue, fieldName);
    case FLOAT:
        return DataTypeUtils.toFloat(rawValue, fieldName);
    case NULL:
        return null;
    case ENUM:
        return new GenericData.EnumSymbol(fieldSchema, rawValue);
    case STRING:
        return DataTypeUtils.toString(rawValue, (String) null, charset);
    }

    return rawValue;
}

From source file:org.sakaiproject.component.section.sakai.CourseSectionImpl.java

public static final String convertTimeToString(Time time) {
    if (time == null) {
        return null;
    }/*from  w  w w.j av  a 2 s  . c  o  m*/
    SimpleDateFormat sdf = new SimpleDateFormat(CourseSectionImpl.TIME_FORMAT_DATE_TZ);
    // Time zone from user
    TimeZone userTz = timeService.getLocalTimeZone();
    sdf.setTimeZone(userTz);

    // Today at 0.00
    Calendar date = new GregorianCalendar(userTz);
    date.set(Calendar.HOUR_OF_DAY, 0);
    date.set(Calendar.MINUTE, 0);

    // Add the RawOffset of server, to write REAL TIME in STRING detached from server
    date.setTimeInMillis(date.getTimeInMillis() + time.getTime() + TimeZone.getDefault().getRawOffset());
    sdf.setCalendar(date);

    return sdf.format(date.getTime());
}

From source file:fr.certu.chouette.validation.checkpoint.AbstractValidation.java

protected long getTimeInSeconds(Time time) {
    TimeZone tz = TimeZone.getDefault();
    long millis = 0;
    millis = time.getTime() + tz.getRawOffset();
    return millis / 1000;
}

From source file:org.apache.sqoop.mapreduce.hcat.SqoopHCatExportHelper.java

private Object convertStringTypes(Object val, String javaColType) {
    String valStr = val.toString();
    if (javaColType.equals(BIG_DECIMAL_TYPE)) {
        return new BigDecimal(valStr);
    } else if (javaColType.equals(DATE_TYPE) || javaColType.equals(TIME_TYPE)
            || javaColType.equals(TIMESTAMP_TYPE)) {
        // Oracle expects timestamps for Date also by default based on version
        // Just allow all date types to be assignment compatible
        if (valStr.length() == 10 && valStr.matches("^\\d{4}-\\d{2}-\\d{2}$")) {
            // Date in yyyy-mm-dd format
            Date d = Date.valueOf(valStr);
            if (javaColType.equals(DATE_TYPE)) {
                return d;
            } else if (javaColType.equals(TIME_TYPE)) {
                return new Time(d.getTime());
            } else if (javaColType.equals(TIMESTAMP_TYPE)) {
                return new Timestamp(d.getTime());
            }//from   w  w w . j a v  a2 s . c o m
        } else if (valStr.length() == 8 && valStr.matches("^\\d{2}:\\d{2}:\\d{2}$")) {
            // time in hh:mm:ss
            Time t = Time.valueOf(valStr);
            if (javaColType.equals(DATE_TYPE)) {
                return new Date(t.getTime());
            } else if (javaColType.equals(TIME_TYPE)) {
                return t;
            } else if (javaColType.equals(TIMESTAMP_TYPE)) {
                return new Timestamp(t.getTime());
            }
        } else if (valStr.length() >= 19 && valStr.length() <= 26
                && valStr.matches("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}(.\\d+)?$")) {
            // timestamp in yyyy-mm-dd hh:mm:ss
            Timestamp ts = Timestamp.valueOf(valStr);
            if (javaColType.equals(DATE_TYPE)) {
                return new Date(ts.getTime());
            } else if (javaColType.equals(TIME_TYPE)) {
                return new Time(ts.getTime());
            } else if (javaColType.equals(TIMESTAMP_TYPE)) {
                return ts;
            }
        } else {
            return null;
        }
    } else if (javaColType.equals(STRING_TYPE)) {
        return valStr;
    } else if (javaColType.equals(BOOLEAN_TYPE)) {
        return Boolean.valueOf(valStr);
    } else if (javaColType.equals(BYTE_TYPE)) {
        return Byte.parseByte(valStr);
    } else if (javaColType.equals(SHORT_TYPE)) {
        return Short.parseShort(valStr);
    } else if (javaColType.equals(INTEGER_TYPE)) {
        return Integer.parseInt(valStr);
    } else if (javaColType.equals(LONG_TYPE)) {
        return Long.parseLong(valStr);
    } else if (javaColType.equals(FLOAT_TYPE)) {
        return Float.parseFloat(valStr);
    } else if (javaColType.equals(DOUBLE_TYPE)) {
        return Double.parseDouble(valStr);
    }
    return null;
}

From source file:com.appeligo.alerts.KeywordAlertChecker.java

/**
 * @param timeZone the user's timezone/*from w w  w .j a v  a2  s . co  m*/
 * @param startOfDay We're using the value of earliestSmsTime (user account setting) as a starting point,
 * so anything before this time is credited to the previous day)
 * @return 12am (midnight) using system time (not user time) because "Date" objects stored in SQL
 * come back in system time.
 */
private Date calculateDay(TimeZone timeZone, Time startOfDay) {
    Calendar cal = Calendar.getInstance(timeZone);
    Calendar start = Calendar.getInstance();
    start.setTimeInMillis(startOfDay.getTime());
    cal.add(Calendar.HOUR_OF_DAY, 0 - start.get(Calendar.HOUR_OF_DAY));
    cal.add(Calendar.MINUTE, 0 - start.get(Calendar.MINUTE));
    cal.add(Calendar.SECOND, 0 - start.get(Calendar.SECOND));
    cal.clear(Calendar.MILLISECOND);
    cal.clear(Calendar.SECOND);
    cal.clear(Calendar.MINUTE);
    cal.clear(Calendar.HOUR_OF_DAY);
    cal.clear(Calendar.HOUR);
    cal.clear(Calendar.AM_PM);
    TimeZone systemTimeZone = TimeZone.getDefault();
    long now = System.currentTimeMillis();
    long difference = systemTimeZone.getOffset(now) - timeZone.getOffset(now);
    return new Date(cal.getTimeInMillis() - difference);
}

From source file:org.zaproxy.zap.extension.sse.db.TableEventStream.java

private List<ServerSentEventStream> buildStreams(ResultSet rs) throws SQLException {
    List<ServerSentEventStream> streams = new ArrayList<>();
    try {/*from  w w  w .j ava  2s  . c  o  m*/
        while (rs.next()) {
            ServerSentEventStream stream = new ServerSentEventStream();
            stream.setId(rs.getInt("stream_id"));
            stream.setHost(rs.getString("host"));
            stream.setPort(rs.getInt("port"));
            stream.setUrl(rs.getString("url"));
            stream.setStartTimestamp(rs.getTimestamp("start_timestamp").getTime());

            Time endTs = rs.getTime("end_timestamp");
            stream.setEndTimestamp((endTs != null) ? endTs.getTime() : null);

            stream.setHistoryId(rs.getInt("history_id"));

            streams.add(stream);
        }
    } finally {
        rs.close();
    }

    return streams;
}

From source file:com.qtplaf.library.util.Calendar.java

/**
 * Constructor assigning a <code>Time</code>.
 *
 * @param time The <code>Time</code>.
 *///  w  w  w  . j a  v a2s  . c o  m
public Calendar(java.sql.Time time) {
    setTimeInMillis(time.getTime());
}

From source file:fr.certu.chouette.exchange.gtfs.importer.NeptuneConverter.java

/**
 * shift a time on and offset/*from  w  ww  .j a  va2s .  c om*/
 * 
 * @param t
 *           time to shift
 * @param offset
 *           offset (seconds)
 * @return time shifted (new instance)
 */
private Time shiftTime(Time t, long offset) {
    return new Time((t.getTime() + offset) % (24 * 3600 * 1000));
}

From source file:org.zaproxy.zap.extension.websocket.db.TableWebSocket.java

private List<WebSocketChannelDTO> buildChannelDTOs(ResultSet rs) throws SQLException {
    ArrayList<WebSocketChannelDTO> channels = new ArrayList<>();
    try {//from ww  w . j  ava2  s. c  o m
        while (rs.next()) {
            WebSocketChannelDTO channel = new WebSocketChannelDTO();
            channel.id = rs.getInt("channel_id");
            channel.host = rs.getString("host");
            channel.port = rs.getInt("port");
            channel.url = rs.getString("url");
            channel.startTimestamp = rs.getTimestamp("start_timestamp").getTime();

            Time endTs = rs.getTime("end_timestamp");
            channel.endTimestamp = (endTs != null) ? endTs.getTime() : null;

            channel.historyId = rs.getInt("history_id");

            channels.add(channel);
        }
    } finally {
        rs.close();
    }

    channels.trimToSize();

    return channels;
}

From source file:net.sf.jasperreports.engine.JRResultSetDataSource.java

protected Object readTime(Integer columnIndex, JRField field) throws SQLException {
    Calendar calendar = getFieldCalendar(field);
    java.sql.Time objValue = calendar == null ? resultSet.getTime(columnIndex)
            : resultSet.getTime(columnIndex, calendar);
    if (resultSet.wasNull()) {
        objValue = null;/*w  w w  .ja  v  a  2s .  c om*/
    }
    if (log.isDebugEnabled()) {
        log.debug("time field " + field.getName() + " is "
                + (objValue == null ? "null" : (objValue + " (" + objValue.getTime() + ")")));
    }
    return objValue;
}