Example usage for java.sql Timestamp toInstant

List of usage examples for java.sql Timestamp toInstant

Introduction

In this page you can find the example usage for java.sql Timestamp toInstant.

Prototype

@Override
public Instant toInstant() 

Source Link

Document

Converts this Timestamp object to an Instant .

Usage

From source file:Main.java

public static LocalDateTime localDateFromTimestamp(Timestamp timestamp) {
    return LocalDateTime.ofInstant(timestamp.toInstant(), ZoneOffset.ofHours(0));
}

From source file:ch.digitalfondue.npjt.mapper.InstantMapper.java

private static Instant toInstant(Timestamp ts) {
    return ts != null ? ts.toInstant() : null;
}

From source file:ch.digitalfondue.npjt.mapper.ZonedDateTimeMapper.java

private static Object toZonedDateTime(Timestamp timestamp) {
    if (timestamp == null) {
        return null;
    }// ww  w  . j a  v a2 s.c  om
    return ZonedDateTime.ofInstant(timestamp.toInstant(), UTC_Z_ID);
}

From source file:com.hotelbeds.hotelapimodel.auto.util.AssignUtils.java

public static ZonedDateTime getZonedDateTime(final Timestamp timestamp) {
    return timestamp != null ? ZonedDateTime.ofInstant(timestamp.toInstant(), ZoneId.systemDefault()) : null;
}

From source file:com.streamsets.pipeline.lib.jdbc.multithread.TableContextUtil.java

public static String generateNextPartitionOffset(TableContext tableContext, String column, String offset) {
    final String partitionSize = tableContext.getOffsetColumnToPartitionOffsetAdjustments().get(column);
    switch (tableContext.getOffsetColumnToType().get(column)) {
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
        final int int1 = Integer.parseInt(offset);
        final int int2 = Integer.parseInt(partitionSize);
        return String.valueOf(int1 + int2);
    case Types.TIMESTAMP:
        final Timestamp timestamp1 = getTimestampForOffsetValue(offset);
        final long timestampAdj = Long.parseLong(partitionSize);
        final Timestamp timestamp2 = Timestamp.from(timestamp1.toInstant().plusMillis(timestampAdj));
        return getOffsetValueForTimestamp(timestamp2);
    case Types.BIGINT:
        // TIME, DATE are represented as long (epoch)
    case Types.TIME:
    case Types.DATE:
        final long long1 = Long.parseLong(offset);
        final long long2 = Long.parseLong(partitionSize);
        return String.valueOf(long1 + long2);
    case Types.FLOAT:
    case Types.REAL:
        final float float1 = Float.parseFloat(offset);
        final float float2 = Float.parseFloat(partitionSize);
        return String.valueOf(float1 + float2);
    case Types.DOUBLE:
        final double double1 = Double.parseDouble(offset);
        final double double2 = Double.parseDouble(partitionSize);
        return String.valueOf(double1 + double2);
    case Types.NUMERIC:
    case Types.DECIMAL:
        final BigDecimal decimal1 = new BigDecimal(offset);
        final BigDecimal decimal2 = new BigDecimal(partitionSize);
        return decimal1.add(decimal2).toString();
    }/*from  ww w.j  a v a  2s. c o  m*/
    return null;
}

From source file:com.fluke.realtime.data.RediffParser.java

public void fillData() {
    Timestamp lastUpdated = dao.getLastTimeStamp(name);
    Timestamp currentTime = Timestamp.from(Calendar.getInstance().toInstant());
    int lastMins = lastUpdated != null ? Util.getMinutes(Date.from(lastUpdated.toInstant())) : ((9 * 60) + 15);
    int currentMins = Util.getMinutes(Date.from(currentTime.toInstant()));
    if (currentMins - lastMins < 4) {
        //lost data of less than 4 mins. no need to process further
        return;/*from  w  w w.  j ava 2s .c o m*/
    }
    YahooIntradayParser parser = new YahooIntradayParser();
    IntradayDetails data = parser.getIntradayDetails(name);
    fillOldData(data);
}

From source file:com.fluke.data.processor.ReatimeDBReader.java

private boolean tryAgain(String eq, List<RealtimeTicker> list) {
    if (list != null && !list.isEmpty()) {
        return false;
    }/*from  w  w  w . j  a va 2  s  . co m*/
    Timestamp maxTime = getMaxtimeNoted();
    if (maxTime == null) {
        return true;
        //probably the starting phase
    }
    Timestamp lastUpdated = getLastTimeStamp(eq);
    if (lastUpdated == null) {
        throw new DataStreamLostException();
    }
    int minsReached = Util.getMinutes(Date.from(maxTime.toInstant()));
    int minUpdated = Util.getMinutes(Date.from(lastUpdated.toInstant()));
    if (minsReached - minUpdated > 2) {
        throw new DataStreamLostException();
    }
    return true;
}

From source file:dk.dbc.rawrepo.oai.OAIWorker.java

/**
 * http://www.openarchives.org/OAI/openarchivesprotocol.html#Identify
 *
 * @param oaipmh response object/*  w ww.  j a v a  2s .  c  o m*/
 */
public void identify(OAIPMH oaipmh) {
    setRequest(oaipmh, VerbType.IDENTIFY);

    Timestamp timestamp = EPOCH;
    try (PreparedStatement stmt = connection.prepareStatement("SELECT MIN(changed) FROM oairecords");
            ResultSet resultSet = stmt.executeQuery()) {
        if (resultSet.next()) {
            timestamp = resultSet.getTimestamp(1);
        }
    } catch (SQLException ex) {
        log.error("Exception: " + ex.getMessage());
        log.debug("Exception:", ex);
        throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR, "Internal Error");
    }

    String ts = DateTimeFormatter.ISO_INSTANT.format(timestamp.toInstant());

    IdentifyType identify = OBJECT_FACTORY.createIdentifyType();
    identify.setRepositoryName(config.getRepositoryName());
    identify.setBaseURL(config.getBaseUrl());
    identify.setProtocolVersion("2.0");
    identify.setEarliestDatestamp(ts);
    identify.setDeletedRecord(DeletedRecordType.TRANSIENT);
    identify.setGranularity(GranularityType.YYYY_MM_DD_THH_MM_SS_Z);
    oaipmh.setIdentify(identify);
}

From source file:com.streamsets.pipeline.lib.jdbc.JdbcUtil.java

public Map<String, String> getMinimumOffsetValues(Connection connection, String schema, String tableName,
        QuoteChar quoteChar, Collection<String> offsetColumnNames) throws SQLException {
    Map<String, String> minOffsetValues = new HashMap<>();
    final String qualifiedName = TableContextUtil.getQuotedQualifiedTableName(schema, tableName,
            quoteChar.getQuoteCharacter());
    for (String offsetColumn : offsetColumnNames) {
        final String minOffsetQuery = String.format(MIN_OFFSET_VALUE_QUERY, offsetColumn, qualifiedName);
        try (Statement st = connection.createStatement(); ResultSet rs = st.executeQuery(minOffsetQuery)) {
            if (rs.next()) {
                String minValue = null;
                final int colType = rs.getMetaData().getColumnType(MIN_OFFSET_VALUE_QUERY_RESULT_SET_INDEX);
                switch (colType) {
                case Types.DATE:
                    java.sql.Date date = rs.getDate(MIN_OFFSET_VALUE_QUERY_RESULT_SET_INDEX);
                    if (date != null) {
                        minValue = String.valueOf(date.toInstant().toEpochMilli());
                    }/* w w w .  ja v a  2  s  .c o m*/
                    break;
                case Types.TIME:
                    java.sql.Time time = rs.getTime(MIN_OFFSET_VALUE_QUERY_RESULT_SET_INDEX);
                    if (time != null) {
                        minValue = String.valueOf(time.toInstant().toEpochMilli());
                    }
                    break;
                case Types.TIMESTAMP:
                    Timestamp timestamp = rs.getTimestamp(MIN_OFFSET_VALUE_QUERY_RESULT_SET_INDEX);
                    if (timestamp != null) {
                        final Instant instant = timestamp.toInstant();
                        minValue = String.valueOf(instant.toEpochMilli());
                    }
                    break;
                default:
                    minValue = rs.getString(MIN_OFFSET_VALUE_QUERY_RESULT_SET_INDEX);
                    break;
                }
                if (minValue != null) {
                    minOffsetValues.put(offsetColumn, minValue);
                }
            } else {
                LOG.warn("Unable to get minimum offset value using query {}; result set had no rows",
                        minOffsetQuery);
            }
        }
    }

    return minOffsetValues;
}

From source file:dk.dbc.rawrepo.oai.OAIIdentifierCollection.java

/**
 * Fetch identifiers from database/*from w  ww  .j av a 2  s .c  om*/
 *
 * json argument is object with: null null null null null     {@literal
 * f: fromTimestamp*
 * u: untilTimestamp*
 * m: metadataPrefix
 * o: fromOffset (how many records with fromTimestamp has been seen)*
 * s: set*
 * }
 *
 * @param json  as described
 * @param limit how many records to fetch
 * @return json as described or null if no more records
 */
@SuppressFBWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING")
public ObjectNode fetch(ObjectNode json, int limit) {
    log.debug("limit = " + limit);
    StringBuilder sb = new StringBuilder();
    String set = json.path("s").asText(null);
    String from = json.path("f").asText(null);
    String until = json.path("u").asText(null);
    String metadataPrefix = json.path("m").asText("");
    int offset = json.path("o").asInt(0);
    sb.append("SELECT pid, changed, deleted FROM oairecords JOIN oairecordsets USING (pid) WHERE");
    if (set != null) {
        sb.append(" setSpec = ?");
    } else if (allowedSets.isEmpty()) {
        return null;
    } else {
        sb.append(" setSpec IN ('");
        sb.append(allowedSets.stream().sorted().collect(Collectors.joining("', '")));
        sb.append("')");
    }
    sb.append(" AND ? in (SELECT prefix FROM oaiformats)");

    if (from != null) {
        sb.append(" AND");
        if (from.contains(".")) {
            sb.append(
                    " DATE_TRUNC('milliseconds', changed) >= DATE_TRUNC('milliseconds', ?::timestamp AT TIME ZONE 'UTC')");
        } else if (from.contains("T")) {
            sb.append(
                    " DATE_TRUNC('second', changed) >= DATE_TRUNC('second', ?::timestamp AT TIME ZONE 'UTC')");
        } else {
            sb.append(" DATE_TRUNC('day', changed) >= DATE_TRUNC('day', ?::timestamp AT TIME ZONE 'UTC')");
        }
    }
    if (until != null) {
        sb.append(" AND");
        if (until.contains(".")) {
            sb.append(
                    " DATE_TRUNC('milliseconds', changed) <= DATE_TRUNC('milliseconds', ?::timestamp AT TIME ZONE 'UTC')");
        } else if (until.contains("T")) {
            sb.append(
                    " DATE_TRUNC('second', changed) <= DATE_TRUNC('second', ?::timestamp AT TIME ZONE 'UTC')");
        } else {
            sb.append(" DATE_TRUNC('day', changed) <= DATE_TRUNC('day', ?::timestamp AT TIME ZONE 'UTC')");
        }
    }
    sb.append(" GROUP BY pid");
    if (set != null) {
        sb.append(", gone");
    }
    sb.append(" ORDER BY changed, pid OFFSET ? LIMIT ?");
    String query = sb.toString();
    log.debug("query = " + query);

    sb = new StringBuilder();
    sb.append("SELECT setSpec FROM oairecordsets WHERE pid = ? AND setSpec IN ('")
            .append(allowedSets.stream().sorted().collect(Collectors.joining("', '")))
            .append("') AND NOT gone ORDER BY setSpec");
    String setQuery = sb.toString();

    Timestamp last = null;
    int row = 0;
    try (PreparedStatement stmt = connection.prepareStatement(query);
            PreparedStatement sets = connection.prepareStatement(setQuery)) {
        int i = 1;
        if (set != null) {
            stmt.setString(i++, set);
        }
        stmt.setString(i++, metadataPrefix);
        if (from != null) {
            stmt.setString(i++, from);
        }
        if (until != null) {
            stmt.setString(i++, until);
        }
        stmt.setInt(i++, offset);
        stmt.setInt(i++, limit + 1);
        try (ResultSet resultSet = stmt.executeQuery()) {
            while (resultSet.next()) {
                row++;
                String pid = resultSet.getString(1);
                Timestamp changed = resultSet.getTimestamp(2);
                Boolean deleted = resultSet.getBoolean(3);
                if (row <= limit) {
                    OAIIdentifier oaiRecord = new OAIIdentifier(pid, changed, deleted);
                    sets.setString(1, pid);
                    try (ResultSet setsResult = sets.executeQuery()) {
                        while (setsResult.next()) {
                            oaiRecord.add(setsResult.getString(1));
                        }
                    }
                    if (oaiRecord.isEmpty() && !oaiRecord.isDeleted()) {
                        oaiRecord = new OAIIdentifier(pid, changed, true);
                    }
                    add(oaiRecord);
                    if (changed.equals(last)) {
                        offset++;
                    } else {
                        last = changed;
                        offset = 1;
                    }
                } else {
                    ObjectNode obj = OBJECT_MAPPER.createObjectNode();
                    String continueFrom = changed.toInstant().atZone(ZoneId.systemDefault())
                            .format(DateTimeFormatter.ISO_INSTANT);
                    obj.put("f", continueFrom);
                    if (changed.equals(last)) {
                        obj.put("o", offset);
                    }
                    if (until != null) {
                        obj.put("u", until);
                    }
                    if (set != null) {
                        obj.put("s", set);
                    }
                    if (metadataPrefix != null) {
                        obj.put("m", metadataPrefix);
                    }
                    log.debug("continueFrom = " + obj);
                    return obj;
                }
            }
        }
    } catch (SQLException ex) {
        log.error("Exception: " + ex.getMessage());
        log.debug("Exception:", ex);
        throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR, "Internal Error");
    }
    return null;
}