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.hp.rest.UtilitiesHandle.java

@POST
@Path("/putSetLunch")
@Consumes(MediaType.APPLICATION_JSON)/*from w w  w.java  2s.  com*/
public Response putSetLunch(String pData) {
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SetLunchDAO setLunchDAO = new SetLunchDAOImpl();

    ObjectMapper mapper = new ObjectMapper();
    SetLunch setLunch = new SetLunch();
    try {
        setLunch = mapper.readValue(pData, SetLunch.class);

    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (setLunch == null)
        return Response.status(200).entity("false").build();

    Date today = new Date();
    setLunch.setTimeAt(Timestamp.valueOf(dateFormat.format(today)));

    List<SetLunch> setLunchList = setLunchDAO.getSetLunchList(setLunch.getStaff(), setLunch.getTimeAt());

    if (setLunchList != null && setLunchList.size() > 0) {
        return Response.status(200).entity("existsetlunch").build();
    }

    setLunch.setCreatedTime(Timestamp.valueOf(dateFormat.format(today)));

    return Response.status(200).entity(setLunchDAO.saveOrUpdate(setLunch) + "").build();
}

From source file:idgs.IdgsDriver.java

@SuppressWarnings("unchecked")
@Override//w  w w . j  a  va2  s.com
public boolean getResults(@SuppressWarnings("rawtypes") List result)
        throws IOException, CommandNeedRetryException {
    int maxRows = 100;
    try {
        maxRows = (Integer) maxRowsField.get(this);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    ResultSet resultSet = getResultSet();
    if (resultSet == null) {
        return super.getResults(result);
    }

    List<RowData> results = resultSet.getResults(maxRows);
    if (results == null) {
        return false;
    }

    List<FieldSchema> fieldSchemas = getSchema().getFieldSchemas();
    for (RowData rowData : results) {
        Object[] row = new Object[fieldSchemas.size()];

        for (int i = 0; i < fieldSchemas.size(); ++i) {
            FieldSchema schema = fieldSchemas.get(i);
            Object value = rowData.getFieldValue(schema.getName());
            row[i] = null;

            if (value != null) {
                String type = schema.getType();
                if (type.equalsIgnoreCase("smallint")) {
                    if (value instanceof Integer) {
                        row[i] = ((Integer) value).shortValue();
                    }
                    row[i] = Short.valueOf(value.toString());
                } else if (type.equalsIgnoreCase("tinyint")) {
                    if (value instanceof Integer) {
                        row[i] = ((Integer) value).byteValue();
                    }
                } else if (type.equalsIgnoreCase("binary")) {
                    if (value instanceof String) {
                        row[i] = ((String) value).getBytes();
                    }
                } else if (type.equalsIgnoreCase("timestamp")) {
                    if (value instanceof String) {
                        try {
                            row[i] = Timestamp.valueOf((String) value);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else if (type.equalsIgnoreCase("date")) {
                    if (value instanceof String) {
                        try {
                            row[i] = Date.valueOf((String) value);
                        } catch (Exception e) {
                        }
                    }
                } else {
                    row[i] = value;
                }
            }
        }

        result.add(row);
    }

    return true;
}

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

/**
 * Test of getOrder method, of class OrderDAO.
 *//*from   w  ww  . jav a2s .c  o  m*/
@Test
public void testGetOrder() throws Exception {
    performDAOTest(new DAOTest() {
        @Override
        public void test(final Connection connection) throws Exception {
            Order order = OrderDAO.getByCriteria(connection,
                    MediaOrderCriteria.fromComponentInstanceId(INSTANCE_A).identifierIsOneOf("100"));
            assertThat(order, nullValue());

            assertThat(OrderDAO.findByCriteria(connection, MediaOrderCriteria
                    .fromComponentInstanceId(INSTANCE_A).identifierIsOneOf("100", "200", "201", "202")),
                    hasSize(2));

            order = OrderDAO.getByCriteria(connection,
                    MediaOrderCriteria.fromComponentInstanceId(INSTANCE_A).identifierIsOneOf("201"));

            assertThat(order.getOrderId(), is("201"));
            assertThat(order.getUserId(), is(writerUser.getId()));
            assertThat(order.getInstanceId(), is(INSTANCE_A));
            assertThat(order.getCreationDate(), is(CREATE_DATE));
            assertThat(order.getProcessDate().getTime(),
                    is(Timestamp.valueOf("2014-06-30 12:59:59.999").getTime()));
            assertThat(order.getProcessUserId(), is(adminAccessUser.getId()));

            // This block is for orderer testing.
            assertThat(order.getUserName(), is(writerUser.getDisplayedName()));
            order.setUserId(adminAccessUser.getId());
            assertThat(order.getUserName(), is(adminAccessUser.getDisplayedName()));
            order.setOrderer(publisherUser);
            assertThat(order.getUserId(), is(publisherUser.getId()));
            assertThat(order.getUserName(), is(publisherUser.getDisplayedName()));

            assertThat(order.getRows(), hasSize(2));

            OrderRow orderRow = order.getRows().get(0);
            if (!orderRow.getOrderId().equals("v_2")) {
                orderRow = order.getRows().get(1);
            }
            assertThat(orderRow.getOrderId(), is("201"));
            assertThat(orderRow.getMediaId(), is("v_2"));
            assertThat(orderRow.getInstanceId(), is(INSTANCE_A));
            assertThat(orderRow.getDownloadDate().getTime(),
                    is(Timestamp.valueOf("2014-12-31 12:59:59.999").getTime()));
            assertThat(orderRow.getDownloadDecision(), is("T"));
        }
    });
}

From source file:org.apache.synapse.mediators.db.AbstractDBMediator.java

/**
 * Return a Prepared statement for the given Statement object, which is ready to be executed
 *
 * @param stmnt  SQL stataement to be executed
 * @param con    The connection to be used
 * @param msgCtx Current message context
 * @return a PreparedStatement/*from w w w. j  a v a 2  s. com*/
 * @throws SQLException on error
 */
protected PreparedStatement getPreparedStatement(Statement stmnt, Connection con, MessageContext msgCtx)
        throws SQLException {

    SynapseLog synLog = getLog(msgCtx);

    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Getting a connection from DataSource " + getDSName()
                + " and preparing statement : " + stmnt.getRawStatement());
    }

    if (con == null) {
        String msg = "Connection from DataSource " + getDSName() + " is null.";
        log.error(msg);
        throw new SynapseException(msg);
    }

    if (dataSource instanceof BasicDataSource) {

        BasicDataSource basicDataSource = (BasicDataSource) dataSource;
        int numActive = basicDataSource.getNumActive();
        int numIdle = basicDataSource.getNumIdle();
        String connectionId = Integer.toHexString(con.hashCode());

        DBPoolView dbPoolView = getDbPoolView();
        if (dbPoolView != null) {
            dbPoolView.setNumActive(numActive);
            dbPoolView.setNumIdle(numIdle);
            dbPoolView.updateConnectionUsage(connectionId);
        }

        if (synLog.isTraceOrDebugEnabled()) {
            synLog.traceOrDebug("[ DB Connection : " + con + " ]");
            synLog.traceOrDebug("[ DB Connection instance identifier : " + connectionId + " ]");
            synLog.traceOrDebug("[ Number of Active Connection : " + numActive + " ]");
            synLog.traceOrDebug("[ Number of Idle Connection : " + numIdle + " ]");
        }
    }

    PreparedStatement ps = con.prepareStatement(stmnt.getRawStatement());

    // set parameters if any
    List<Statement.Parameter> params = stmnt.getParameters();
    int column = 1;

    for (Statement.Parameter param : params) {
        if (param == null) {
            continue;
        }
        String value = (param.getPropertyName() != null ? param.getPropertyName()
                : param.getXpath().stringValueOf(msgCtx));

        if (synLog.isTraceOrDebugEnabled()) {
            synLog.traceOrDebug("Setting as parameter : " + column + " value : " + value + " as JDBC Type : "
                    + param.getType() + "(see java.sql.Types for valid " + "types)");
        }

        switch (param.getType()) {
        // according to J2SE 1.5 /docs/guide/jdbc/getstart/mapping.html
        case Types.CHAR:
        case Types.VARCHAR:
        case Types.LONGVARCHAR: {
            if (value != null && value.length() != 0) {
                ps.setString(column++, value);
            } else {
                ps.setString(column++, null);
            }
            break;
        }
        case Types.NUMERIC:
        case Types.DECIMAL: {
            if (value != null && value.length() != 0) {
                ps.setBigDecimal(column++, new BigDecimal(value));
            } else {
                ps.setBigDecimal(column++, null);
            }
            break;
        }
        case Types.BIT: {
            if (value != null && value.length() != 0) {
                ps.setBoolean(column++, Boolean.parseBoolean(value));
            } else {
                ps.setNull(column++, Types.BIT);
            }
            break;
        }
        case Types.TINYINT: {
            if (value != null && value.length() != 0) {
                ps.setByte(column++, Byte.parseByte(value));
            } else {
                ps.setNull(column++, Types.TINYINT);
            }
            break;
        }
        case Types.SMALLINT: {
            if (value != null && value.length() != 0) {
                ps.setShort(column++, Short.parseShort(value));
            } else {
                ps.setNull(column++, Types.SMALLINT);
            }
            break;
        }
        case Types.INTEGER: {
            if (value != null && value.length() != 0) {
                ps.setInt(column++, Integer.parseInt(value));
            } else {
                ps.setNull(column++, Types.INTEGER);
            }
            break;
        }
        case Types.BIGINT: {
            if (value != null && value.length() != 0) {
                ps.setLong(column++, Long.parseLong(value));
            } else {
                ps.setNull(column++, Types.BIGINT);
            }
            break;
        }
        case Types.REAL: {
            if (value != null && value.length() != 0) {
                ps.setFloat(column++, Float.parseFloat(value));
            } else {
                ps.setNull(column++, Types.REAL);
            }
            break;
        }
        case Types.FLOAT: {
            if (value != null && value.length() != 0) {
                ps.setDouble(column++, Double.parseDouble(value));
            } else {
                ps.setNull(column++, Types.FLOAT);
            }
            break;
        }
        case Types.DOUBLE: {
            if (value != null && value.length() != 0) {
                ps.setDouble(column++, Double.parseDouble(value));
            } else {
                ps.setNull(column++, Types.DOUBLE);
            }
            break;
        }
        // skip BINARY, VARBINARY and LONGVARBINARY
        case Types.DATE: {
            if (value != null && value.length() != 0) {
                ps.setDate(column++, Date.valueOf(value));
            } else {
                ps.setNull(column++, Types.DATE);
            }
            break;
        }
        case Types.TIME: {
            if (value != null && value.length() != 0) {
                ps.setTime(column++, Time.valueOf(value));
            } else {
                ps.setNull(column++, Types.TIME);
            }
            break;
        }
        case Types.TIMESTAMP: {
            if (value != null && value.length() != 0) {
                ps.setTimestamp(column++, Timestamp.valueOf(value));
            } else {
                ps.setNull(column++, Types.TIMESTAMP);
            }
            break;
        }
        // skip CLOB, BLOB, ARRAY, DISTINCT, STRUCT, REF, JAVA_OBJECT
        default: {
            String msg = "Trying to set an un-supported JDBC Type : " + param.getType() + " against column : "
                    + column + " and statement : " + stmnt.getRawStatement()
                    + " used by a DB mediator against DataSource : " + getDSName()
                    + " (see java.sql.Types for valid type values)";
            handleException(msg, msgCtx);
        }
        }
    }

    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Successfully prepared statement : " + stmnt.getRawStatement()
                + " against DataSource : " + getDSName());
    }
    return ps;
}

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

private void saveUsageTimestamps(Cursor cursor) {
    if (!cursor.isNull(UsagesQuery.UPDATED)) {
        Timestamp new_timestamp = Timestamp.valueOf(cursor.getString(UsagesQuery.UPDATED));
        Object old_timestamp = mDataUpdatedTime.getTag();

        if (old_timestamp == null || new_timestamp.after((Timestamp) old_timestamp)) {
            mDataUpdatedTime.setTag(new_timestamp);
        }/*from ww w  .j av  a  2  s. co  m*/
    }
}

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

private void btnStatiticsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStatiticsActionPerformed
    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(TableService.getStatiticsService(tsStart, tsToDate, ConnectDB.conn()));
    tbResult.getColumnModel().getColumn(4).setCellRenderer(new NumberCellRenderer());
    tbResult.getTableHeader().setReorderingAllowed(false);
    showChart();// w ww. ja v a  2  s  . c om
    int total = 0;
    for (int i = 0; i < tbResult.getRowCount(); i++) {
        int x = 0;
        try {
            x = Integer.parseInt(tbResult.getValueAt(i, 4).toString().replaceAll("\\.", ""));
        } catch (Exception e) {
            x = Integer.parseInt(tbResult.getValueAt(i, 4).toString().replaceAll(",", ""));
        }
        total = total + x;
    }
    DecimalFormat df = new DecimalFormat("#,###,###");
    lbTotalPay.setText(df.format(total) + " VN?");
}

From source file:org.plos.repo.rest.ObjectController.java

private Timestamp getValidateTimestamp(String timestampString, RepoException.Type errorType,
        Timestamp defaultTimestamp) throws RepoException {
    if (timestampString != null) {
        try {/*from w w  w  .  j  a va 2s.co  m*/
            return Timestamp.valueOf(timestampString);
        } catch (IllegalArgumentException e) {
            throw new RepoException(errorType);
        }
    }
    return defaultTimestamp;
}

From source file:org.apache.hadoop.hive.ql.exec.vector.RandomRowObjectSource.java

public static Timestamp getRandTimestamp(Random r) {
    String optionalNanos = "";
    if (r.nextInt(2) == 1) {
        optionalNanos = String.format(".%09d", Integer.valueOf(0 + r.nextInt(DateUtils.NANOS_PER_SEC)));
    }//  w  w w  . j a  v  a  2 s  .  c om
    String timestampStr = String.format("%d-%02d-%02d %02d:%02d:%02d%s", Integer.valueOf(1970 + r.nextInt(200)), // year
            Integer.valueOf(1 + r.nextInt(12)), // month
            Integer.valueOf(1 + r.nextInt(28)), // day
            Integer.valueOf(0 + r.nextInt(24)), // hour
            Integer.valueOf(0 + r.nextInt(60)), // minute
            Integer.valueOf(0 + r.nextInt(60)), // second
            optionalNanos);
    Timestamp timestampVal = Timestamp.valueOf(timestampStr);
    return timestampVal;
}

From source file:com.hp.action.CalendarAction.java

public String edit() throws IOException {
    HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
            .get(ServletActionContext.HTTP_REQUEST);
    HttpServletResponse response = (HttpServletResponse) ActionContext.getContext()
            .get(ServletActionContext.HTTP_RESPONSE);

    HttpSession session = request.getSession();

    response.setContentType("text/html; charset=UTF-8");
    response.setCharacterEncoding("text/html; charset=UTF-8");

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    String id = StringUtils.trimToEmpty(request.getParameter("id"));
    String contributor = StringUtils.trimToEmpty(request.getParameter("contributor"));
    String support = StringUtils.trimToEmpty(request.getParameter("support"));
    String mission = StringUtils.trimToEmpty(request.getParameter("mission"));
    String report = StringUtils.trimToEmpty(request.getParameter("report"));
    String statusParam = StringUtils.trimToEmpty(request.getParameter("status"));

    int stt = 0;/*  ww  w. j a  v  a  2 s.c  o  m*/
    int status = -1;
    try {
        stt = Integer.parseInt(id);
        status = Integer.parseInt(statusParam);

    } catch (Exception e) {
        e.printStackTrace();
        response.getOutputStream().write("Li khng xc nh, hy th li sau!".getBytes("UTF-8"));
        return null;
    }

    Calendar calendar = null;
    if (stt > 0)
        calendar = calendarDAO.getCalendar(stt);

    if (calendar != null && calendar.getStatus() != 2) {
        calendar.setContributor(contributor);
        calendar.setMission(mission);
        calendar.setReport(report);
        calendar.setSupport(support);

        calendar.setUpdatedTime(Timestamp.valueOf(df.format(new Date())));

        if (status != -1)
            calendar.setStatus(status);

        if (calendarDAO.update(calendar)) {
            response.getOutputStream().write("Cp nht lch cng tc thnh cng".getBytes("UTF-8"));
            return null;
        }
    }

    response.getOutputStream()
            .write("Cp nht lch cng tc tht bi, hy th li sau!".getBytes("UTF-8"));

    return null;
}

From source file:org.apache.openjpa.jdbc.schema.Column.java

/**
 * Return the default value set for this column, if any. If only a default
 * string has been set, attempts to convert it to the right type based
 * on the Java type set for this column.
 *//* ww w .ja  va2  s  .co m*/
public Object getDefault() {
    if (_default != null)
        return _default;
    if (_defaultStr == null)
        return null;

    switch (_javaType) {
    case JavaTypes.BOOLEAN:
    case JavaTypes.BOOLEAN_OBJ:
        _default = ("true".equals(_defaultStr)) ? Boolean.TRUE : Boolean.FALSE;
        break;
    case JavaTypes.BYTE:
    case JavaTypes.BYTE_OBJ:
        _default = new Byte(_defaultStr);
        break;
    case JavaTypes.CHAR:
    case JavaTypes.CHAR_OBJ:
        _default = Character.valueOf(_defaultStr.charAt(0));
        break;
    case JavaTypes.DOUBLE:
    case JavaTypes.DOUBLE_OBJ:
        _default = new Double(_defaultStr);
        break;
    case JavaTypes.FLOAT:
    case JavaTypes.FLOAT_OBJ:
        _default = new Float(_defaultStr);
        break;
    case JavaTypes.INT:
    case JavaTypes.INT_OBJ:
        _default = Integer.parseInt(_defaultStr);
        break;
    case JavaTypes.LONG:
    case JavaTypes.LONG_OBJ:
        _default = Long.parseLong(_defaultStr);
        break;
    case JavaTypes.NUMBER:
    case JavaTypes.BIGDECIMAL:
        _default = new BigDecimal(_defaultStr);
        break;
    case JavaTypes.SHORT:
    case JavaTypes.SHORT_OBJ:
        _default = new Short(_defaultStr);
        break;
    case JavaTypes.DATE:
        _default = new java.util.Date(_defaultStr);
        break;
    case JavaTypes.BIGINTEGER:
        _default = new BigInteger(_defaultStr);
        break;
    case JavaSQLTypes.SQL_DATE:
        _default = Date.valueOf(_defaultStr);
        break;
    case JavaSQLTypes.TIMESTAMP:
        _default = Timestamp.valueOf(_defaultStr);
        break;
    case JavaSQLTypes.TIME:
        _default = Time.valueOf(_defaultStr);
        break;
    default:
        _default = _defaultStr;
    }
    return _default;
}