Example usage for java.sql Timestamp valueOf

List of usage examples for java.sql Timestamp valueOf

Introduction

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

Prototype

@SuppressWarnings("deprecation")
public static Timestamp valueOf(LocalDateTime dateTime) 

Source Link

Document

Obtains an instance of Timestamp from a LocalDateTime object, with the same year, month, day of month, hours, minutes, seconds and nanos date-time value as the provided LocalDateTime .

Usage

From source file:org.apache.stratos.usage.summary.helper.util.DataAccessObject.java

public String getAndUpdateLastServiceStatsHourlyTimestamp() throws SQLException {

    Timestamp lastSummaryTs = null;
    Connection connection = null;

    try {/*w  w  w  .  j a  v a2s . com*/
        connection = dataSource.getConnection();
        String sql = "SELECT TIMESTMP FROM SERVICE_STATS_LAST_HOURLY_TS WHERE ID='LatestTS'";
        PreparedStatement ps = connection.prepareStatement(sql);
        ResultSet resultSet = ps.executeQuery();
        if (resultSet.next()) {
            lastSummaryTs = resultSet.getTimestamp("TIMESTMP");
        } else {
            lastSummaryTs = new Timestamp(0);
        }

        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:00");
        Timestamp currentTs = Timestamp.valueOf(formatter.format(new Date()));

        String currentSql = "INSERT INTO SERVICE_STATS_LAST_HOURLY_TS (ID, TIMESTMP) VALUES('LatestTS',?) ON DUPLICATE KEY UPDATE TIMESTMP=?";
        PreparedStatement ps1 = connection.prepareStatement(currentSql);
        ps1.setTimestamp(1, currentTs);
        ps1.setTimestamp(2, currentTs);
        ps1.execute();

    } catch (SQLException e) {
        log.error("Error occurred while trying to get and update the last hourly timestamp. ", e);
    } finally {
        if (connection != null) {
            connection.close();
        }
    }

    return lastSummaryTs.toString();
}

From source file:it.cnr.icar.eric.server.persistence.rdb.AuditableEventDAO.java

@SuppressWarnings({ "rawtypes", "unchecked" })
protected void loadObject(Object obj, ResultSet rs) throws RegistryException {
    try {//from   w w  w .  j a v a2 s  . c  om
        if (!(obj instanceof AuditableEventType)) {
            throw new RegistryException(ServerResourceBundle.getInstance()
                    .getString("message.AuditableEventExpected", new Object[] { obj }));
        }

        AuditableEventType ebAuditableEventType = (AuditableEventType) obj;
        super.loadObject(obj, rs);

        //TODO: Fix so requestId is properly supported
        String requestId = rs.getString("requestId");
        if (requestId == null) {
            requestId = "Unknown";
        }
        ebAuditableEventType.setRequestId(requestId);

        String eventType = rs.getString("eventType");
        ebAuditableEventType.setEventType(eventType);

        //Workaround for bug in PostgreSQL 7.2.2 JDBC driver
        //java.sql.Timestamp timeStamp = rs.getTimestamp("timeStamp_"); --old
        String timestampStr = rs.getString("timeStamp_").substring(0, 19);
        Timestamp timeStamp = Timestamp.valueOf(timestampStr);

        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(timeStamp);
        XMLGregorianCalendar cal = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar);

        ebAuditableEventType.setTimestamp(cal);

        String userId = rs.getString("user_");
        ObjectRefType ebObjectRefType = bu.rimFac.createObjectRefType();
        ebObjectRefType.setId(userId);
        context.getObjectRefs().add(ebObjectRefType);
        ebAuditableEventType.setUser(userId);

        AffectedObjectDAO affectedDAO = new AffectedObjectDAO(context);
        affectedDAO.setParent(ebAuditableEventType);
        List affectedObjects = affectedDAO.getByParent();
        ObjectRefListType orefList = BindingUtility.getInstance().rimFac.createObjectRefListType();
        orefList.getObjectRef().addAll(affectedObjects);
        ebAuditableEventType.setAffectedObjects(orefList);

    } catch (SQLException e) {
        log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e);
        throw new RegistryException(e);
    } catch (DatatypeConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.opencommercesearch.remote.assetmanager.editor.service.DefaultRuleAssetValidator.java

/**
 * Checks that the start and end date are properly specified.
 * <p/>//from w w  w . j  a  va2 s  . c o m
 * A common error would be to enter an end date which is before the given start date. 
 */
protected void validateStartAndEndDateUpdate(AssetEditorInfo editorInfo, PropertyUpdate startDateProperty,
        PropertyUpdate endDateProperty) {
    Timestamp startDate = null;
    Timestamp endDate = null;

    if (startDateProperty == null) {
        //This field wasn't updated, so fetch the value from the asset.
        RepositoryItem currentItem = (RepositoryItem) editorInfo.getAssetWrapper().getAsset();
        startDate = (Timestamp) currentItem.getPropertyValue(RuleProperty.START_DATE);
    } else {
        String startDateValue = (String) startDateProperty.getPropertyValue();

        if (startDateValue != null && !startDateValue.isEmpty()) {
            startDate = Timestamp.valueOf(startDateValue); //Timestamp.valueOf understands ISO 8601 date format.
        }
    }

    if (endDateProperty == null) {
        //This field wasn't updated, so fetch the value from the asset.
        RepositoryItem currentItem = (RepositoryItem) editorInfo.getAssetWrapper().getAsset();
        endDate = (Timestamp) currentItem.getPropertyValue(RuleProperty.END_DATE);
    } else {
        String endDateValue = (String) endDateProperty.getPropertyValue();
        if (endDateValue == null || endDateValue.isEmpty()) {
            editorInfo.getAssetService().addError(RuleProperty.END_DATE, NULL_PROPERTY_ERROR_MSG);
            return; //Don't do more validation.
        } else {
            endDate = Timestamp.valueOf(endDateValue); //Timestamp.valueOf understands ISO 8601 date format.
        }
    }

    if (startDate != null && endDate.before(startDate)) {
        editorInfo.getAssetService().addError(RuleProperty.END_DATE, INVALID_END_DATE_ERROR_MSG);
    }
}

From source file:StorageEngineClient.FormatStorageSerDe.java

@Override
public Object deserialize(Writable field) throws SerDeException {
    IRecord record = (IRecord) field;//from   w w w .  j  a  v  a 2 s  . c  om

    ArrayList<Object> objectList = new ArrayList<Object>();

    int i = 0;
    for (Integer idx : this.idxs) {
        IRecord.IFValue val = record.getByIdx(idx);
        Object ooo = (val != null ? val.fieldValue(this.serdeParams.columnTypesFormat.get(i)) : null);
        if (serdeParams.columnTypes.get(i).getTypeName().equalsIgnoreCase(Constants.TIMESTAMP_TYPE_NAME)) {
            if (ooo != null) {
                Timestamp ttt = null;
                try {
                    ttt = Timestamp.valueOf((String) ooo);
                } catch (Exception e) {
                    LOG.error("LazyTimestamp init failed: " + (String) ooo);
                }
                objectList.add(ttt);
            } else {
                objectList.add(ooo);
            }
        } else {
            objectList.add(ooo);
        }

        i++;

    }
    return objectList;
}

From source file:mtsar.resources.WorkerResource.java

@PATCH
@Path("{worker}/answers/skip")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response postAnswersSkip(@Context Validator validator, @Context UriInfo uriInfo,
        @PathParam("worker") Integer id, @FormParam("tags") List<String> tags,
        @FormParam("datetime") String datetimeParam, @FormParam("tasks") List<Integer> tasks) {
    final Timestamp datetime = (datetimeParam == null) ? DateTimeUtils.now() : Timestamp.valueOf(datetimeParam);
    final Worker worker = fetchWorker(id);

    final Map<Answer, Set<ConstraintViolation<Object>>> answers = tasks.stream().map(taskId -> {
        final Task task = fetchTask(taskId);

        final Answer answer = new Answer.Builder().setStage(stage.getId()).addAllTags(tags)
                .setType(AnswerDAO.ANSWER_TYPE_SKIP).setTaskId(task.getId()).setWorkerId(worker.getId())
                .setDateTime(datetime).build();

        /* Since we are skipping the task, the only constraint we need is #answer-duplicate. */
        final Set<ConstraintViolation<Object>> violations = ParamsUtils.validate(validator,
                new AnswerValidation.Builder().setAnswer(answer).setAnswerDAO(answerDAO).build());

        return Pair.of(answer, violations);
    }).collect(Collectors.toMap(Pair::getLeft, Pair::getRight));

    final Set<ConstraintViolation<Object>> violations = answers.values().stream().flatMap(Set::stream)
            .collect(Collectors.toSet());
    if (!violations.isEmpty())
        throw new ConstraintViolationException(violations);

    final List<Answer> inserted = AnswerDAO.insert(answerDAO, answers.keySet());
    return Response.ok(inserted).build();
}

From source file:org.jumpmind.db.platform.oracle.OracleDdlReader.java

@Override
protected Column readColumn(DatabaseMetaDataWrapper metaData, Map<String, Object> values) throws SQLException {
    Column column = super.readColumn(metaData, values);
    if (column.getMappedTypeCode() == Types.DECIMAL) {
        // We're back-mapping the NUMBER columns returned by Oracle
        // Note that the JDBC driver returns DECIMAL for these NUMBER
        // columns
        if (column.getScale() <= -127 || column.getScale() >= 127) {
            if (column.getSizeAsInt() == 0) {
                /*/*w w w  .ja v a2  s .  co  m*/
                 * Latest oracle jdbc drivers for 11g return (0,-127) for
                 * types defined as integer resulting in bad mappings.
                 * NUMBER without scale or precision looks the same as
                 * INTEGER in the jdbc driver. We must check the Oracle
                 * meta data to see if type is an INTEGER.
                 */
                if (isColumnInteger((String) values.get("TABLE_NAME"), (String) values.get("COLUMN_NAME"))) {
                    column.setMappedTypeCode(Types.BIGINT);
                }
            } else if (column.getSizeAsInt() <= 63) {
                column.setMappedTypeCode(Types.REAL);
            } else {
                column.setMappedTypeCode(Types.DOUBLE);
            }
        }
    } else if (column.getMappedTypeCode() == Types.FLOAT) {
        // Same for REAL, FLOAT, DOUBLE PRECISION, which all back-map to
        // FLOAT but with
        // different sizes (63 for REAL, 126 for FLOAT/DOUBLE PRECISION)
        switch (column.getSizeAsInt()) {
        case 63:
            column.setMappedTypeCode(Types.REAL);
            break;
        case 126:
            column.setMappedTypeCode(Types.DOUBLE);
            break;
        }
    } else if ((column.getMappedTypeCode() == Types.DATE) || (column.getMappedTypeCode() == Types.TIMESTAMP)) {
        // we also reverse the ISO-format adaptation, and adjust the default
        // value to timestamp
        if (column.getDefaultValue() != null) {
            Timestamp timestamp = null;

            Matcher matcher = oracleIsoTimestampPattern.matcher(column.getDefaultValue());

            if (matcher.matches()) {
                String timestampVal = matcher.group(1);
                timestamp = Timestamp.valueOf(timestampVal);
            } else {
                matcher = oracleIsoDatePattern.matcher(column.getDefaultValue());
                if (matcher.matches()) {
                    String dateVal = matcher.group(1);
                    timestamp = new Timestamp(Date.valueOf(dateVal).getTime());
                } else {
                    matcher = oracleIsoTimePattern.matcher(column.getDefaultValue());
                    if (matcher.matches()) {
                        String timeVal = matcher.group(1);

                        timestamp = new Timestamp(Time.valueOf(timeVal).getTime());
                    }
                }
            }
            if (timestamp != null) {
                column.setDefaultValue(timestamp.toString());
            }
        }
    } else if (TypeMap.isTextType(column.getMappedTypeCode())) {
        String defaultValue = column.getDefaultValue();
        if (isNotBlank(defaultValue) && defaultValue.startsWith("('") && defaultValue.endsWith("')")) {
            defaultValue = defaultValue.substring(2, defaultValue.length() - 2);
        }
        column.setDefaultValue(unescape(defaultValue, "'", "''"));
    }
    return column;
}

From source file:org.wso2.carbon.apimgt.core.dao.impl.ApiResourceDAO.java

static void updateBinaryResourceForCategory(Connection connection, String apiID, ResourceCategory category,
        InputStream resourceValue, String updatedBy) throws SQLException {
    final String query = "UPDATE AM_API_RESOURCES SET RESOURCE_BINARY_VALUE = ?, UPDATED_BY = ?, "
            + "LAST_UPDATED_TIME = ? WHERE API_ID = ? AND RESOURCE_CATEGORY_ID = ?";

    try (PreparedStatement statement = connection.prepareStatement(query)) {
        statement.setBinaryStream(1, resourceValue);
        statement.setString(2, updatedBy);
        statement.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));
        statement.setString(4, apiID);/*from   w w  w  .ja v a2 s  . co  m*/
        statement.setInt(5, ResourceCategoryDAO.getResourceCategoryID(connection, category));

        statement.execute();
    }
}

From source file:net.niyonkuru.koodroid.ui.OverviewFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (!data.moveToFirst())
        return;/*w  w  w .ja  v  a2 s .c  o  m*/

    int id = loader.getId();

    switch (id) {
    case SUBSCRIBER_TOKEN: {
        mSubscriberName.setText(data.getString(SubscribersQuery.FULL_NAME));
        break;
    }
    case BILL_TOKEN: {
        mBillTotal.setText(formatMoney(data.getString(BillsQuery.TOTAL)));
        mBillPastDueBalance.setText(formatMoney(data.getString(BillsQuery.PAST_DUE_BALANCE)));
        mBillCurrentBalance.setText(formatMoney(data.getString(BillsQuery.CURRENT_CHARGES)));

        if (!data.isNull(BillsQuery.DUE_DATE)) {
            mBillDueDate.setTag(Date.valueOf(data.getString(BillsQuery.DUE_DATE)));
        }
        mBillUpdateTime.setTag(Timestamp.valueOf(data.getString(BillsQuery.UPDATED)));
        break;
    }
    case TAB_TOKEN: {
        mTabBalance.setText(formatMoney(data.getString(TabsQuery.BALANCE)));
        mTabUpdateTime.setTag(Timestamp.valueOf(data.getString(TabsQuery.UPDATED)));
        break;
    }
    }

    updateTimestamps();
}

From source file:org.silverpeas.test.jcr.JcrTest.java

protected Date randomDate() {
    long offset = Timestamp.valueOf("2014-01-01 00:00:00").getTime();
    long end = Timestamp.valueOf("2014-04-30 00:00:00").getTime();
    long diff = end - offset + 1;
    return new Timestamp(offset + (long) (Math.random() * diff));
}

From source file:org.apache.nifi.processors.orc.PutORCTest.java

@Test
public void testWriteORCWithAvroLogicalTypes() throws IOException, InitializationException {
    final String avroSchema = IOUtils.toString(
            new FileInputStream("src/test/resources/user_logical_types.avsc"), StandardCharsets.UTF_8);
    schema = new Schema.Parser().parse(avroSchema);
    Calendar now = Calendar.getInstance();
    LocalTime nowTime = LocalTime.now();
    LocalDateTime nowDateTime = LocalDateTime.now();
    LocalDate epoch = LocalDate.ofEpochDay(0);
    LocalDate nowDate = LocalDate.now();

    final int timeMillis = nowTime.get(ChronoField.MILLI_OF_DAY);
    final Timestamp timestampMillis = Timestamp.valueOf(nowDateTime);
    final Date dt = Date.valueOf(nowDate);
    final double dec = 1234.56;

    configure(proc, 10, (numUsers, readerFactory) -> {
        for (int i = 0; i < numUsers; i++) {
            readerFactory.addRecord(i, timeMillis, timestampMillis, dt, dec);
        }//from ww w  .ja  va 2  s.  co  m
        return null;
    });

    final String filename = "testORCWithDefaults-" + System.currentTimeMillis();

    final Map<String, String> flowFileAttributes = new HashMap<>();
    flowFileAttributes.put(CoreAttributes.FILENAME.key(), filename);

    testRunner.setProperty(PutORC.HIVE_TABLE_NAME, "myTable");

    testRunner.enqueue("trigger", flowFileAttributes);
    testRunner.run();
    testRunner.assertAllFlowFilesTransferred(PutORC.REL_SUCCESS, 1);

    final Path orcFile = new Path(DIRECTORY + "/" + filename);

    // verify the successful flow file has the expected attributes
    final MockFlowFile mockFlowFile = testRunner.getFlowFilesForRelationship(PutORC.REL_SUCCESS).get(0);
    mockFlowFile.assertAttributeEquals(PutORC.ABSOLUTE_HDFS_PATH_ATTRIBUTE, orcFile.getParent().toString());
    mockFlowFile.assertAttributeEquals(CoreAttributes.FILENAME.key(), filename);
    mockFlowFile.assertAttributeEquals(PutORC.RECORD_COUNT_ATTR, "10");
    // DDL will be created with field names normalized (lowercased, e.g.) for Hive by default
    mockFlowFile.assertAttributeEquals(PutORC.HIVE_DDL_ATTRIBUTE,
            "CREATE EXTERNAL TABLE IF NOT EXISTS `myTable` (`id` INT, `timemillis` INT, `timestampmillis` TIMESTAMP, `dt` DATE, `dec` DOUBLE) STORED AS ORC");

    // verify we generated a provenance event
    final List<ProvenanceEventRecord> provEvents = testRunner.getProvenanceEvents();
    assertEquals(1, provEvents.size());

    // verify it was a SEND event with the correct URI
    final ProvenanceEventRecord provEvent = provEvents.get(0);
    assertEquals(ProvenanceEventType.SEND, provEvent.getEventType());
    // If it runs with a real HDFS, the protocol will be "hdfs://", but with a local filesystem, just assert the filename.
    Assert.assertTrue(provEvent.getTransitUri().endsWith(DIRECTORY + "/" + filename));

    // verify the content of the ORC file by reading it back in
    verifyORCUsers(orcFile, 10, (x, currUser) -> {
        assertEquals((int) currUser, ((IntWritable) x.get(0)).get());
        assertEquals(timeMillis, ((IntWritable) x.get(1)).get());
        assertEquals(timestampMillis, ((TimestampWritableV2) x.get(2)).getTimestamp().toSqlTimestamp());
        final DateFormat noTimeOfDayDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        noTimeOfDayDateFormat.setTimeZone(TimeZone.getTimeZone("gmt"));
        assertEquals(noTimeOfDayDateFormat.format(dt), ((DateWritableV2) x.get(3)).get().toString());
        assertEquals(dec, ((DoubleWritable) x.get(4)).get(), Double.MIN_VALUE);
        return null;
    });

    // verify we don't have the temp dot file after success
    final File tempOrcFile = new File(DIRECTORY + "/." + filename);
    Assert.assertFalse(tempOrcFile.exists());

    // verify we DO have the CRC file after success
    final File crcAvroORCFile = new File(DIRECTORY + "/." + filename + ".crc");
    Assert.assertTrue(crcAvroORCFile.exists());
}