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:com.ebay.nest.io.sede.lazy.LazyTimestamp.java

/**
 * Initilizes LazyTimestamp object by interpreting the input bytes
 * as a JDBC timestamp string/*from  w  w w .  j a v  a  2s  . c  om*/
 *
 * @param bytes
 * @param start
 * @param length
 */
@Override
public void init(ByteArrayRef bytes, int start, int length) {
    String s = null;
    try {
        s = new String(bytes.getData(), start, length, "US-ASCII");
    } catch (UnsupportedEncodingException e) {
        LOG.error(e);
        s = "";
    }

    Timestamp t = null;
    if (s.compareTo("NULL") == 0) {
        isNull = true;
        logExceptionMessage(bytes, start, length, "TIMESTAMP");
    } else {
        try {
            t = Timestamp.valueOf(s);
            isNull = false;
        } catch (IllegalArgumentException e) {
            isNull = true;
            logExceptionMessage(bytes, start, length, "TIMESTAMP");
        }
    }
    data.set(t);
}

From source file:com.monkeyk.sos.infrastructure.jdbc.UserRepositoryJdbc.java

@Override
public void saveUser(final User user) {
    final String sql = " insert into user_(guid,archived,create_time,email,password,username,phone) "
            + " values (?,?,?,?,?,?,?) ";
    this.jdbcTemplate.update(sql, ps -> {
        ps.setString(1, user.guid());/*from w  w  w . j  av  a2  s  .c o m*/
        ps.setBoolean(2, user.archived());

        ps.setTimestamp(3, Timestamp.valueOf(user.createTime()));
        ps.setString(4, user.email());

        ps.setString(5, user.password());
        ps.setString(6, user.username());

        ps.setString(7, user.phone());
    });

    //get user id
    final Integer id = this.jdbcTemplate.queryForObject("select id from user_ where guid = ?",
            new Object[] { user.guid() }, Integer.class);

    //insert privileges
    for (final Privilege privilege : user.privileges()) {
        this.jdbcTemplate.update("insert into user_privilege(user_id, privilege) values (?,?)", ps -> {
            ps.setInt(1, id);
            ps.setString(2, privilege.name());
        });
    }

}

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

static void addTextResource(Connection connection, String apiID, String resourceID, ResourceCategory category,
        String dataType, String textValue, String createdBy) throws SQLException {
    final String query = "INSERT INTO AM_API_RESOURCES (UUID, API_ID, RESOURCE_CATEGORY_ID, "
            + "DATA_TYPE, RESOURCE_TEXT_VALUE, CREATED_BY, CREATED_TIME, UPDATED_BY, LAST_UPDATED_TIME) "
            + "VALUES (?,?,?,?,?,?,?,?,?)";

    try (PreparedStatement statement = connection.prepareStatement(query)) {
        statement.setString(1, resourceID);
        statement.setString(2, apiID);//from w w w .j ava  2  s .  c  om
        statement.setInt(3, ResourceCategoryDAO.getResourceCategoryID(connection, category));
        statement.setString(4, dataType);
        statement.setString(5, textValue);
        statement.setString(6, createdBy);
        statement.setTimestamp(7, Timestamp.valueOf(LocalDateTime.now()));
        statement.setString(8, createdBy);
        statement.setTimestamp(9, Timestamp.valueOf(LocalDateTime.now()));
        statement.execute();
    }
}

From source file:com.fns.grivet.repo.JdbcEntityRepository.java

@Override
public Long newId(Integer cid, LocalDateTime createdTime) {
    return Long.valueOf(String.valueOf(new SimpleJdbcInsert(jdbcTemplate).withTableName("entity")
            .usingGeneratedKeyColumns("eid").usingColumns("cid", "created_time")
            .executeAndReturnKey(ImmutableMap.of("cid", cid, "created_time", Timestamp.valueOf(createdTime)))));
}

From source file:de.innovationgate.webgate.api.jdbc.custom.KeyMap.java

/**
 * @param key//w w w .  j av a 2s .  c om
 */
public KeyMap(JDBCSource jdbcSource, String key, String folder) throws ParseException {
    super();
    List keyColumns = (List) jdbcSource.getTables().get(folder);
    if (keyColumns == null) {
        throw new IllegalArgumentException("Table " + folder + " does not exist or has no primary key");
    }
    StringTokenizer tokens = new StringTokenizer(key, "--");
    int idx = 0;
    while (tokens.hasMoreTokens()) {
        String token = tokens.nextToken();
        char dataType = token.charAt(0);
        String valueStr = token.substring(1);
        Object value = null;
        if (dataType == '#') {
            value = NUMBER_FORMATTER.parse(WGUtils.strReplace(valueStr, "D", ".", true));
        } else if (dataType == '*') {
            value = Timestamp.valueOf(valueStr);
        } else {
            value = valueStr;
        }
        put(keyColumns.get(idx), value);
        idx++;
    }

}

From source file:com.thinkbiganalytics.spark.dataprofiler.columns.TimestampColumnStatistics.java

/**
 * Adds the specified value to the statistics for this column.
 *
 * @param columnValue the column value to be profiled
 * @param columnCount the number of rows containing the value
 *///  ww  w.  ja  v  a 2s.co m
@Override
public void accomodate(@Nullable final Object columnValue, @Nonnull Long columnCount) {
    // Update common statistics
    accomodateCommon(columnValue, columnCount);

    // Update timestamp-specific statistics
    String stringValue = (columnValue != null) ? columnValue.toString() : null;

    if (!StringUtils.isEmpty(stringValue)) {
        Timestamp timestamp = Timestamp.valueOf(stringValue);
        if (maxTimestamp == null || maxTimestamp.before(timestamp)) {
            maxTimestamp = timestamp;
        }
        if (minTimestamp == null || minTimestamp.after(timestamp)) {
            minTimestamp = timestamp;
        }
    }
}

From source file:com.fns.grivet.service.NamedQueryServiceSprocTest.java

@Test
public void testSuccessfulNamedQueryExecution() throws IOException {
    Resource r = resolver.getResource("classpath:TestSprocQuery.json");
    String json = IOUtils.toString(r.getInputStream(), Charset.defaultCharset());
    NamedQuery namedQuery = objectMapper.readValue(json, NamedQuery.class);
    namedQueryService.create(namedQuery);

    MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
    Timestamp tomorrow = Timestamp.valueOf(LocalDateTime.now().plusDays(1));
    params.add("createdTime", tomorrow);
    String result = namedQueryService.get("sproc.getAttributesCreatedBefore", params);
    String[] expected = { "bigint", "varchar", "decimal", "datetime", "int", "text", "json", "boolean" };
    List<String> actual = JsonPath.given(result).getList("NAME");
    Assertions.assertTrue(actual.size() == 8, "Result should contain 8 attributes");
    Assertions.assertTrue(actual.containsAll(Arrays.asList(expected)));
}

From source file:example.unittest.ExampleDbUnitTest.java

@Test
public void exampleTest() throws Exception {
    // load your data
    loadData(ds);//w  w w.jav a2s  .c o m

    // Now run your test once the setup is done
    QueryRunner jdbc = new QueryRunner(ds);

    List<Map<String, Object>> tableCResults = jdbc.query("select * from DYN_TABLE_C ORDER BY C_ID",
            new MapListHandler());
    System.out.println("Print DYN_TABLE_C for debug");
    for (Map<String, Object> result : tableCResults) {
        System.out.println("DYN_TABLE_C ROW: " + result);
    }
    assertEquals(5, tableCResults.size());
    assertTableCRow(tableCResults, 0, 1, 1, "row1", null);
    assertTableCRow(tableCResults, 1, 2, 2, "row  2", Timestamp.valueOf("2013-01-02 12:34:56"));
    assertTableCRow(tableCResults, 2, 3, 2, "", Timestamp.valueOf("2013-01-02 12:34:56.1"));
    assertTableCRow(tableCResults, 3, 4, 2, "  row  4  ", Timestamp.valueOf("2013-01-02 12:34:56.234"));
    assertTableCRow(tableCResults, 4, 5, 2, null, Timestamp.valueOf("2013-01-02 12:34:56.567891"));

    List<Map<String, Object>> tableDResults = jdbc.query("select * from DYN_TABLE_D ORDER BY D_ID",
            new MapListHandler());
    System.out.println("Print DYN_TABLE_D for debug");
    for (Map<String, Object> result : tableDResults) {
        System.out.println("DYN_TABLE_D ROW: " + result);
    }
    assertEquals(3, tableDResults.size());
    assertTableDRow(tableDResults, 0, 1);
    assertTableDRow(tableDResults, 1, 2);
    assertTableDRow(tableDResults, 2, 3);
}

From source file:eu.domibus.common.dao.ErrorLogDao.java

public List<ErrorLogEntry> findPaged(int from, int max, String column, boolean asc,
        HashMap<String, Object> filters) {
    CriteriaBuilder cb = this.em.getCriteriaBuilder();
    CriteriaQuery<ErrorLogEntry> cq = cb.createQuery(ErrorLogEntry.class);
    Root<ErrorLogEntry> ele = cq.from(ErrorLogEntry.class);
    cq.select(ele);//from  ww  w  . j  a  v a2  s . com
    List<Predicate> predicates = new ArrayList<Predicate>();
    for (Map.Entry<String, Object> filter : filters.entrySet()) {
        if (filter.getValue() != null) {
            if (filter.getValue() instanceof String) {
                if (!filter.getValue().toString().isEmpty()) {
                    switch (filter.getKey().toString()) {
                    case "":
                        break;
                    case "timestampFrom":
                        predicates.add(cb.greaterThanOrEqualTo(ele.<Date>get("timestamp"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    case "timestampTo":
                        predicates.add(cb.lessThanOrEqualTo(ele.<Date>get("timestamp"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    case "notifiedFrom":
                        predicates.add(cb.greaterThanOrEqualTo(ele.<Date>get("notified"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    case "notifiedTo":
                        predicates.add(cb.lessThanOrEqualTo(ele.<Date>get("notified"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    default:
                        predicates.add(cb.like(ele.<String>get(filter.getKey()), (String) filter.getValue()));
                        break;
                    }
                }
            } else {
                predicates.add(cb.equal(ele.<String>get(filter.getKey()), filter.getValue()));
            }
        }
    }
    cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
    if (column != null) {
        if (asc) {
            cq.orderBy(cb.asc(ele.get(column)));
        } else {
            cq.orderBy(cb.desc(ele.get(column)));
        }

    }
    final TypedQuery<ErrorLogEntry> query = this.em.createQuery(cq);
    query.setFirstResult(from);
    query.setMaxResults(max);
    return query.getResultList();
}

From source file:vn.edu.vttu.ui.PanelStatiticsPaymentRawmaterialInvoice.java

private void statiticsDay() {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String datetimeStart = formatter.format(dtFormDate.getDate());
    Timestamp tsStart = Timestamp.valueOf(datetimeStart);
    String datetimeEnd = formatter.format(dtToDate.getDate());
    Timestamp tsToDate = Timestamp.valueOf(datetimeEnd);
    tbResult.setModel(// w w  w.  j  ava 2s  .c  o  m
            PaymentInvoice.getPaymentInvoiceRawmaterialInvoiceByDay(tsStart, tsToDate, ConnectDB.conn()));
}