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: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 w  ww.  j  a  v a2s. c  o  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:org.apache.hawq.pxf.plugins.hive.HiveResolver.java

void initPartitionFields() {
    partitionFields = new LinkedList<>();
    if (partitionKeys.equals(HiveDataFragmenter.HIVE_NO_PART_TBL)) {
        return;/*from  w w w .jav  a 2  s .  c  o m*/
    }

    String[] partitionLevels = partitionKeys.split(HiveDataFragmenter.HIVE_PARTITIONS_DELIM);
    for (String partLevel : partitionLevels) {
        String[] levelKey = partLevel.split(HiveDataFragmenter.HIVE_1_PART_DELIM);
        String type = levelKey[1];
        String val = levelKey[2];
        DataType convertedType;
        Object convertedValue = null;
        boolean isDefaultPartition = false;

        LOG.debug("Partition type: " + type + ", value: " + val);
        // check if value is default partition
        isDefaultPartition = isDefaultPartition(type, val);
        // ignore the type's parameters
        String typeName = type.replaceAll("\\(.*\\)", "");

        switch (typeName) {
        case serdeConstants.STRING_TYPE_NAME:
            convertedType = TEXT;
            convertedValue = isDefaultPartition ? null : val;
            break;
        case serdeConstants.BOOLEAN_TYPE_NAME:
            convertedType = BOOLEAN;
            convertedValue = isDefaultPartition ? null : Boolean.valueOf(val);
            break;
        case serdeConstants.TINYINT_TYPE_NAME:
        case serdeConstants.SMALLINT_TYPE_NAME:
            convertedType = SMALLINT;
            convertedValue = isDefaultPartition ? null : Short.parseShort(val);
            break;
        case serdeConstants.INT_TYPE_NAME:
            convertedType = INTEGER;
            convertedValue = isDefaultPartition ? null : Integer.parseInt(val);
            break;
        case serdeConstants.BIGINT_TYPE_NAME:
            convertedType = BIGINT;
            convertedValue = isDefaultPartition ? null : Long.parseLong(val);
            break;
        case serdeConstants.FLOAT_TYPE_NAME:
            convertedType = REAL;
            convertedValue = isDefaultPartition ? null : Float.parseFloat(val);
            break;
        case serdeConstants.DOUBLE_TYPE_NAME:
            convertedType = FLOAT8;
            convertedValue = isDefaultPartition ? null : Double.parseDouble(val);
            break;
        case serdeConstants.TIMESTAMP_TYPE_NAME:
            convertedType = TIMESTAMP;
            convertedValue = isDefaultPartition ? null : Timestamp.valueOf(val);
            break;
        case serdeConstants.DATE_TYPE_NAME:
            convertedType = DATE;
            convertedValue = isDefaultPartition ? null : Date.valueOf(val);
            break;
        case serdeConstants.DECIMAL_TYPE_NAME:
            convertedType = NUMERIC;
            convertedValue = isDefaultPartition ? null : HiveDecimal.create(val).bigDecimalValue().toString();
            break;
        case serdeConstants.VARCHAR_TYPE_NAME:
            convertedType = VARCHAR;
            convertedValue = isDefaultPartition ? null : val;
            break;
        case serdeConstants.CHAR_TYPE_NAME:
            convertedType = BPCHAR;
            convertedValue = isDefaultPartition ? null : val;
            break;
        case serdeConstants.BINARY_TYPE_NAME:
            convertedType = BYTEA;
            convertedValue = isDefaultPartition ? null : val.getBytes();
            break;
        default:
            throw new UnsupportedTypeException("Unsupported partition type: " + type);
        }
        addOneFieldToRecord(partitionFields, convertedType, convertedValue);
    }
}

From source file:org.apache.ignite.internal.processors.query.h2.database.InlineIndexHelperTest.java

/** */
public void testTimestamp() throws Exception {
    testPutGet(ValueTimestamp.get(Timestamp.valueOf("2017-02-20 10:01:01")),
            ValueTimestamp.get(Timestamp.valueOf("2017-02-20 10:01:01")),
            ValueTimestamp.get(Timestamp.valueOf("2017-02-20 10:01:01")));
}

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

public String getAndUpdateLastServiceStatsDailyTimestamp() throws SQLException {

    Timestamp lastSummaryTs = null;
    Connection connection = null;

    try {//w w  w .  ja v  a  2s. com
        connection = dataSource.getConnection();
        String sql = "SELECT TIMESTMP FROM SERVICE_STATS_LAST_DAILY_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:00:00");
        Timestamp currentTs = Timestamp.valueOf(formatter.format(new Date()));

        String currentSql = "INSERT INTO SERVICE_STATS_LAST_DAILY_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 daily timestamp. ", e);
    } finally {
        if (connection != null) {
            connection.close();
        }
    }

    return lastSummaryTs.toString();
}

From source file:com.lyft.hive.serde.DynamoDbSerDe.java

private Timestamp parseTimestamp(String timestampString) {
    if (timestampFormat == null) {
        return Timestamp.valueOf(timestampString);
    }/*from w  w w .j ava  2 s . c om*/

    return new Timestamp(timestampFormat.parseDateTime(timestampString).getMillis());
}

From source file:org.nanoframework.commons.format.ClassCastTest.java

@Test
public void castByStringTest() {
    Object val = ClassCast.cast("1", Integer.class.getName());
    assertEquals(1, val);

    val = ClassCast.cast("1", Long.class.getName());
    assertEquals(1L, val);

    val = ClassCast.cast("1.0", Double.class.getName());
    assertEquals(1D, val);

    val = ClassCast.cast("1.0", Float.class.getName());
    assertEquals(1F, val);

    String now = "2015-01-01 12:00:00.000";
    val = ClassCast.cast(String.valueOf(now), Timestamp.class.getName());
    assertEquals(Timestamp.valueOf(now), val);

    Map<String, String> map = new HashMap<String, String>() {
        private static final long serialVersionUID = 1L;
        {/*from w  w  w  .j  a  v a 2  s  .c o m*/
            put("id", "id0");
            put("name", "name0");
        }
    };

    val = ClassCast.cast(JSON.toJSONString(map), UseEntity.class.getName());
    assertEquals(UseEntity.class.getName(), val.getClass().getName());
    assertEquals("id0", ((UseEntity) val).getId());
    assertEquals("name0", ((UseEntity) val).getName());
}

From source file:com.silverpeas.gallery.dao.OrderDAOTest.java

/**
 * Test of updateOrder method, of class OrderDAO.
 *///  w  w w  . j  a  v  a2 s.  com
@Test
public void testUpdateOrder() throws Exception {
    performDAOTest(new DAOTest() {
        @Override
        public void test(final Connection connection) throws Exception {
            Date now = DateUtil.getNow();
            Order order = OrderDAO.getByCriteria(connection,
                    MediaOrderCriteria.fromComponentInstanceId(INSTANCE_A).identifierIsOneOf("201"));
            order.setProcessUserId(adminAccessUser.getId());
            for (OrderRow orderRow : order.getRows()) {
                orderRow.setDownloadDecision("D");
            }
            OrderDAO.updateOrder(connection, order);

            IDataSet actualDataSet = getActualDataSet();
            ITable mediaTable = actualDataSet.getTable("SC_Gallery_Media");
            assertThat(mediaTable.getRowCount(), is(MEDIA_ROW_COUNT));
            ITable internalTable = actualDataSet.getTable("SC_Gallery_Internal");
            assertThat(internalTable.getRowCount(), is(MEDIA_INTERNAL_ROW_COUNT));
            ITable photoTable = actualDataSet.getTable("SC_Gallery_Photo");
            assertThat(photoTable.getRowCount(), is(MEDIA_PHOTO_ROW_COUNT));
            ITable videoTable = actualDataSet.getTable("SC_Gallery_Video");
            assertThat(videoTable.getRowCount(), is(MEDIA_VIDEO_ROW_COUNT));
            ITable soundTable = actualDataSet.getTable("SC_Gallery_Sound");
            assertThat(soundTable.getRowCount(), is(MEDIA_SOUND_ROW_COUNT));
            ITable streamingTable = actualDataSet.getTable("SC_Gallery_Streaming");
            assertThat(streamingTable.getRowCount(), is(MEDIA_STREAMING_ROW_COUNT));
            ITable pathTable = actualDataSet.getTable("SC_Gallery_Path");
            assertThat(pathTable.getRowCount(), is(MEDIA_PATH_ROW_COUNT));
            ITable orderTable = actualDataSet.getTable("SC_Gallery_Order");
            assertThat(orderTable.getRowCount(), is(MEDIA_ORDER_ROW_COUNT));
            ITable orderDetailTable = actualDataSet.getTable("SC_Gallery_OrderDetail");
            assertThat(orderDetailTable.getRowCount(), is(MEDIA_ORDER_DETAIL_ROW_COUNT));

            TableRow orderRow = getTableRowFor(orderTable, "orderId", order.getOrderId());
            assertThat(orderRow.getString("userId"), is(order.getUserId()));
            assertThat(orderRow.getString("instanceId"), is(INSTANCE_A));
            assertThat(orderRow.getDate("createDate"), lessThan(now));
            assertThat(orderRow.getDate("processDate"), greaterThanOrEqualTo(now));
            assertThat(orderRow.getString("processUser"), is(adminAccessUser.getId()));

            List<TableRow> orderDetails = getTableRowsFor(orderDetailTable, "orderId", order.getOrderId());
            assertThat(orderDetails, hasSize(2));
            for (TableRow orderDetail : orderDetails) {
                assertThat(orderDetail.getString("orderId"), is(order.getOrderId()));
                assertThat(orderDetail.getString("instanceId"), is(INSTANCE_A));
                if (orderDetail.getString("mediaId").equals("1")) {
                    assertThat(orderDetail.getDate("downloadDate"), nullValue());
                } else {
                    assertThat(orderDetail.getDate("downloadDate").getTime(),
                            is(Timestamp.valueOf("2014-12-31 12:59:59.999").getTime()));
                }
                assertThat(orderDetail.getString("downloadDecision"), is("D"));
            }
        }
    });
}

From source file:org.apache.hadoop.hive.serde2.RegexSerDe.java

@Override
public Object deserialize(Writable blob) throws SerDeException {

    Text rowText = (Text) blob;
    Matcher m = inputPattern.matcher(rowText.toString());

    if (m.groupCount() != numColumns) {
        throw new SerDeException("Number of matching groups doesn't match the number of columns");
    }//from   www . j a v a2s.c  om

    // If do not match, ignore the line, return a row with all nulls.
    if (!m.matches()) {
        unmatchedRowsCount++;
        if (!alreadyLoggedNoMatch) {
            // Report the row if its the first time
            LOG.warn("" + unmatchedRowsCount + " unmatched rows are found: " + rowText);
            alreadyLoggedNoMatch = true;
        }
        return null;
    }

    // Otherwise, return the row.
    for (int c = 0; c < numColumns; c++) {
        try {
            String t = m.group(c + 1);
            TypeInfo typeInfo = columnTypes.get(c);

            // Convert the column to the correct type when needed and set in row obj
            PrimitiveTypeInfo pti = (PrimitiveTypeInfo) typeInfo;
            switch (pti.getPrimitiveCategory()) {
            case STRING:
                row.set(c, t);
                break;
            case BYTE:
                Byte b;
                b = Byte.valueOf(t);
                row.set(c, b);
                break;
            case SHORT:
                Short s;
                s = Short.valueOf(t);
                row.set(c, s);
                break;
            case INT:
                Integer i;
                i = Integer.valueOf(t);
                row.set(c, i);
                break;
            case LONG:
                Long l;
                l = Long.valueOf(t);
                row.set(c, l);
                break;
            case FLOAT:
                Float f;
                f = Float.valueOf(t);
                row.set(c, f);
                break;
            case DOUBLE:
                Double d;
                d = Double.valueOf(t);
                row.set(c, d);
                break;
            case BOOLEAN:
                Boolean bool;
                bool = Boolean.valueOf(t);
                row.set(c, bool);
                break;
            case TIMESTAMP:
                Timestamp ts;
                ts = Timestamp.valueOf(t);
                row.set(c, ts);
                break;
            case DATE:
                Date date;
                date = Date.valueOf(t);
                row.set(c, date);
                break;
            case DECIMAL:
                HiveDecimal bd = HiveDecimal.create(t);
                row.set(c, bd);
                break;
            case CHAR:
                HiveChar hc = new HiveChar(t, ((CharTypeInfo) typeInfo).getLength());
                row.set(c, hc);
                break;
            case VARCHAR:
                HiveVarchar hv = new HiveVarchar(t, ((VarcharTypeInfo) typeInfo).getLength());
                row.set(c, hv);
                break;
            default:
                throw new SerDeException("Unsupported type " + typeInfo);
            }
        } catch (RuntimeException e) {
            partialMatchedRowsCount++;
            if (!alreadyLoggedPartialMatch) {
                // Report the row if its the first row
                LOG.warn("" + partialMatchedRowsCount + " partially unmatched rows are found, "
                        + " cannot find group " + c + ": " + rowText);
                alreadyLoggedPartialMatch = true;
            }
            row.set(c, null);
        }
    }
    return row;
}

From source file:net.mindengine.oculus.frontend.service.runs.JdbcTestRunDAO.java

/**
 * Collecting all the conditions//from  www .  ja  v  a 2 s  .  co  m
 * 
 * @param filter
 * @return
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public SqlSearchCondition createCondition(SearchFilter filter) throws IOException {

    SqlSearchCondition condition = new SqlSearchCondition();

    // TestName
    String testName = filter.getTestCaseName();
    if (testName != null && !testName.isEmpty()) {
        testName = testName.trim();
        // checking whether it is an id of test or just a name
        if (StringUtils.isNumeric(testName)) {
            // The id of a test was provided
            condition.append(condition.createSimpleCondition(false, "t.id", testName));
        } else {
            if (testName.contains(",")) {
                condition.append(condition.createArrayCondition(testName, "t.name", "tr.name"));
            } else {
                condition.append(condition.createSimpleCondition(testName, true, "t.name", "tr.name"));
            }
        }
    }

    // TestRun Statuses
    List<String> statuses = (List<String>) filter.getTestCaseStatusList();
    if (statuses != null && statuses.size() > 0) {
        String statusColumns[] = new String[statuses.size() * 2];
        int j = 0;
        for (int i = 0; i < statuses.size(); i++) {
            j = i * 2;
            String value = statuses.get(i);
            statusColumns[j] = "tr.status";
            statusColumns[j + 1] = value;
        }
        condition.append(condition.createSimpleCondition(false, statusColumns));
    }
    // TestRun Reason
    String reason = filter.getTestRunReason();
    if (reason != null && !reason.isEmpty()) {
        reason = "*" + reason + "*";
        condition.append(condition.createSimpleCondition(reason, true, "tr.reasons"));
    }
    // Root Project Id
    {
        String parentProject = filter.getRootProject();
        if (parentProject != null && !parentProject.isEmpty()) {
            // checking whether it is an id of project or just a name
            if (StringUtils.isNumeric(parentProject)) {
                Long projectId = Long.parseLong(parentProject);
                if (projectId > 0) {
                    // The id of a project was provided
                    condition.append(condition.createSimpleCondition(false, "pp.id", parentProject));
                }
            }
        }
    }
    // Project Name
    {
        String project = filter.getProject();
        if (project != null && !project.isEmpty()) {
            // checking whether it is an id of project or just a name
            if (StringUtils.isNumeric(project)) {
                // The id of a project was provided
                condition.append(condition.createSimpleCondition(false, "p.id", project));
            } else {
                if (project.contains(",")) {
                    condition.append(condition.createArrayCondition(project, "p.name"));
                } else {
                    condition.append(condition.createSimpleCondition(project, true, "p.name"));
                }
            }
        }
    }
    // Suite Run Name
    {
        String suiteRunName = filter.getSuite();
        if (suiteRunName != null && !suiteRunName.isEmpty()) {
            if (suiteRunName.contains(",")) {
                if (StringUtils.isNumeric(suiteRunName.replace(",", ""))) {
                    condition.append(condition.createArrayCondition(suiteRunName, "sr.id"));
                } else {
                    condition.append(condition.createArrayCondition(suiteRunName, "sr.name"));
                }
            } else {
                if (StringUtils.isNumeric(suiteRunName)) {
                    condition.append(condition.createSimpleCondition(suiteRunName, true, "sr.id"));
                } else {
                    condition.append(condition.createSimpleCondition(suiteRunName, true, "sr.name"));
                }
            }
        }
    }
    // Suite Run Start Time
    {
        String dateAfter = filter.getSuiteRunTimeAfter();
        if (dateAfter != null && !dateAfter.isEmpty()) {
            if (!dateAfter.contains(":")) {
                dateAfter += " 00:00:00";
            }

            // Checking whether the string is in date format
            try {
                Timestamp.valueOf(dateAfter);
                condition.append("tr.start_time >= '" + dateAfter + "'");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        String dateBefore = filter.getSuiteRunTimeBefore();
        if (dateBefore != null && !dateBefore.isEmpty()) {
            if (!dateBefore.contains(":")) {
                dateBefore += " 00:00:00";
            }

            // Checking whether the string is in date format
            try {
                Timestamp.valueOf(dateBefore);
                condition.append("tr.start_time <= '" + dateBefore + "'");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    // Suite Run Parameters
    {
        String suiteRunParameters = filter.getSuiteRunParameters();
        if (suiteRunParameters != null && !suiteRunParameters.isEmpty()) {
            // Parsing the suiteRunParameters template;
            Properties prop = new Properties();
            prop.load(new StringReader(suiteRunParameters));
            for (Entry<Object, Object> property : prop.entrySet()) {
                condition.append(condition.createSimpleCondition(
                        "*" + property.getKey() + "<v>" + property.getValue() + "*", true, "sr.parameters"));
            }
        }
    }
    // Suite Run Agent
    {
        String suiteRunAgent = filter.getSuiteRunAgent();
        if (suiteRunAgent != null && !suiteRunAgent.isEmpty()) {
            if (suiteRunAgent.contains(",")) {
                condition.append(condition.createArrayCondition(suiteRunAgent, "sr.agent_name"));
            } else {
                condition.append(condition.createSimpleCondition(suiteRunAgent, true, "sr.agent_name"));
            }
        }
    }
    // User designer
    {
        String designer = filter.getUserDesigner();
        if (designer != null && !designer.isEmpty()) {
            if (designer.contains(",")) {
                if (StringUtils.isNumeric(designer.replace(",", ""))) {
                    condition.append(condition.createArrayCondition(designer, "ud.id"));
                } else {
                    condition.append(condition.createArrayCondition(designer, "ud.login", "ud.name"));
                }
            } else {
                // checking whether it is an id of project or just a name
                if (StringUtils.isNumeric(designer)) {
                    // The id of a project was provided
                    condition.append(condition.createSimpleCondition(false, "ud.id", designer));
                } else {
                    condition.append(condition.createSimpleCondition(designer, true, "ud.login", "ud.name"));
                }
            }
        }
    }

    // User runner
    {
        String runner = filter.getUserRunner();
        if (runner != null && !runner.isEmpty()) {
            if (runner.contains(",")) {
                if (StringUtils.isNumeric(runner.replace(",", ""))) {
                    condition.append(condition.createArrayCondition(runner, "ur.id"));
                } else {
                    condition.append(condition.createArrayCondition(runner, "ur.login", "ur.name"));
                }
            } else {
                // checking whether it is an id of project or just a name
                if (StringUtils.isNumeric(runner)) {
                    // The id of a project was provided
                    condition.append(condition.createSimpleCondition(false, "ur.id", runner));
                } else {
                    condition.append(condition.createSimpleCondition(runner, true, "ur.login", "ur.name"));
                }
            }
        }
    }
    // Issue
    String issueName = filter.getIssue();
    if (issueName != null && !issueName.isEmpty()) {
        if (issueName.contains(",")) {
            condition.append(condition.createArrayCondition(issueName, "iss.name", "iss.link"));
        } else {
            condition.append(condition.createSimpleCondition(issueName, true, "iss.name", "iss.link"));
        }
    }
    return condition;
}

From source file:com.cisco.dvbu.ps.common.util.CommonUtils.java

public static XMLGregorianCalendar getXMLGregorianCalendarFromTimestamp(String timestamp)
        throws CompositeException {

    // -- e.g. "2011-02-10T14:18:42.000Z"

    timestamp = timestamp.replace("T", " ");
    timestamp = timestamp.replace("Z", "");

    Date date = Timestamp.valueOf(timestamp);

    DatatypeFactory df;// w w w.  j a va2  s  .co m
    try {
        df = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException e) {
        throw new CompositeException(e);
    }

    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(date);
    XMLGregorianCalendar retval = df.newXMLGregorianCalendar(cal);

    return retval;

}