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:us.mn.state.health.lims.patient.action.PatientManagementUpdateAction.java

private void setLastUpdatedTimeStamps(PatientManagementInfo patientInfo) {
    String patientUpdate = patientInfo.getPatientLastUpdated();
    if (!GenericValidator.isBlankOrNull(patientUpdate)) {
        Timestamp timeStamp = Timestamp.valueOf(patientUpdate);
        patient.setLastupdated(timeStamp);
    }//from  www .  ja  v  a 2s.com

    String personUpdate = patientInfo.getPersonLastUpdated();
    if (!GenericValidator.isBlankOrNull(personUpdate)) {
        Timestamp timeStamp = Timestamp.valueOf(personUpdate);
        person.setLastupdated(timeStamp);
    }
}

From source file:com.hp.rest.GenericResource.java

@Path("/putJourney")
@POST//  w  w w  .j  a  va  2 s.  c  om
@Produces(MediaType.TEXT_XML)
public String updateJourney(@FormParam("data") String str) {
    RoadManagementDAO roadManagementDAO = new RoadManagementDAOImpl();
    //Get current time
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = new Date();
    Calendar cal = Calendar.getInstance();
    System.out.println(dateFormat.format(cal.getTime()));

    String pXML = "";
    try {
        pXML = new String(str.getBytes("UTF-8"), "UTF-8");
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(new InputSource(new StringReader(pXML)));

        doc.getDocumentElement().normalize();

        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

        NodeList nList = doc.getElementsByTagName("road");

        System.out.println("----------------------------");

        for (int temp = 0; temp < nList.getLength(); temp++) {
            //init customer
            Customer customer = new Customer();

            Node nNode = nList.item(temp);

            System.out.println("\nCurrent Element :" + nNode.getNodeName());

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;

                String customerid = eElement.getAttribute("id");

                float x = Float.parseFloat(eElement.getElementsByTagName("x").item(0).getTextContent());
                float y = Float.parseFloat(eElement.getElementsByTagName("y").item(0).getTextContent());
                String staffid = eElement.getElementsByTagName("staffid").item(0).getTextContent();

                System.out.println("customer id : " + customerid);
                System.out.println("staff id : " + staffid);
                System.out.println("X : " + x);
                System.out.println("Y : " + y);
                System.out.println("TIME : " + "");

                //UPDATE into Database
                RoadManagement roadManagement = new RoadManagement();
                roadManagement.setMaNhanVien(staffid);
                roadManagement.setTenNhanVien(customerid);
                roadManagement.setViDo(x);
                roadManagement.setKinhDo(y);
                roadManagement.setThoiGian(Timestamp.valueOf(dateFormat.format(cal.getTime())));

                roadManagementDAO.saveOrUpdate(roadManagement);

            }
        }

        return "OK";
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "ERROR";
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "ERROR";
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "ERROR";
    }
}

From source file:jp.co.tis.gsp.tools.dba.dialect.SqlserverDialect.java

@Override
public void setObjectInStmt(PreparedStatement stmt, int parameterIndex, String value, int sqlType)
        throws SQLException {
    if (sqlType == UN_USABLE_TYPE) {
        stmt.setNull(parameterIndex, Types.NULL);
    } else if (StringUtil.isBlank(value) || "".equals(value)) {
        stmt.setNull(parameterIndex, sqlType);
    } else if (sqlType == Types.TIME) {
        stmt.setTimestamp(parameterIndex, Timestamp.valueOf("1970-01-01 " + value));
    } else {/*from   www .  ja  v a 2  s  .co m*/
        stmt.setObject(parameterIndex, value, sqlType);
    }
}

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

public String getAndUpdateLastServiceStatsMonthlyTimestamp() throws SQLException {

    Timestamp lastSummaryTs = null;
    Connection connection = null;

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

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

    return lastSummaryTs.toString();
}

From source file:org.openxdata.server.export.rdbms.engine.DataBuilder.java

private Object getColumnValue(Document schemaDocument, Node node) {
    String x = node.getTextContent();
    if (x == null || x.trim().length() == 0) {
        return null;
    }//from  w  w  w  .  j  av  a2 s. co m
    String columnType = Functions.resolveType(schemaDocument, node.getNodeName());
    if (columnType.equalsIgnoreCase(Constants.TYPE_DATE)) {
        java.sql.Date date = java.sql.Date.valueOf(x); // must be yyyy-MM-dd format
        return date;
    }
    if (columnType.equalsIgnoreCase(Constants.TYPE_TIME)) {
        Time time = null;
        String xTime = x.toUpperCase();
        try {
            if (xTime.contains("PM") || xTime.contains("AM")) {
                time = new Time(new SimpleDateFormat("hh:mm:ss aaa").parse(xTime).getTime());
            } else {
                time = Time.valueOf(x); // must be HH:mm:ss format
            }
        } catch (Exception e) {
            log.warn("Could not convert time '" + x + "' to sql Time", e);
        }
        return time;
    }
    if (columnType.equalsIgnoreCase(Constants.TYPE_DATETIME)) {
        Timestamp datetime = Timestamp.valueOf(x); // must be yyyy-MM-dd HH:mm:ss format
        return datetime;
    }
    if (columnType.equalsIgnoreCase(Constants.TYPE_BOOLEAN)) {
        Boolean bool = new Boolean(x); // note: see Functions.resolveType - boolean is actually VARCHAR
        return bool;
    }
    if (columnType.equalsIgnoreCase(Constants.TYPE_DECIMAL)) {
        Double dub = new Double(x);
        return dub;
    }
    if (columnType.equalsIgnoreCase(Constants.TYPE_INTEGER)) {
        Integer in = new Integer(x);
        return in;
    }
    // VARCHAR or CHAR
    return x;
}

From source file:at.ac.tuwien.qse.sepm.dao.impl.JDBCPhotoDAO.java

@Override
public List<Photo> readPhotosBetween(LocalDateTime start, LocalDateTime end) throws DAOException {
    if (start == null)
        throw new IllegalArgumentException();
    if (end == null)
        throw new IllegalArgumentException();
    logger.debug("retrieving photos between {} and {}", start, end);

    try {/*from  w ww  . j a  v  a  2s  . c  o m*/
        List<Photo> photos = jdbcTemplate.query(READ_INTERVAL_STATEMENT, new PhotoRowMapper(),
                Timestamp.valueOf(start), Timestamp.valueOf(end));
        logger.debug("Successfully retrieved photos");
        return photos;
    } catch (DataAccessException ex) {
        logger.error("Failed to read photos from given interval", ex);
        throw new DAOException("Failed to read photos from given interval", ex);
    } catch (ValidationException.Unchecked | DAOException.Unchecked ex) {
        logger.error("Failed to read photos from given interval", ex);
        throw new DAOException("Failed to read photos from given interval", ex.getCause());
    }
}

From source file:com.hp.avmon.home.service.LicenseService.java

/**
 * ?/*from w ww  .j a  v  a2  s. c om*/
 * 
 * @return
 */
public boolean isDateValidLicense() {

    String regisCode = getRgsCode();// ?
    if (regisCode.length() < 1) {
        return false;
    }
    // 
    String overTimeStr = regisCode.substring(16);
    overTimeStr = replaceStr(overTimeStr);
    boolean isValid = false;
    try {
        String tmstpStr = this.getOverDateLicense(overTimeStr);
        if (!checkDate(tmstpStr)) {
            return false;
        }

        if (getCurrentTime().after(Timestamp.valueOf(tmstpStr + " 24:00:00"))) {
            isValid = false;
        } else {
            isValid = true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return isValid;
}

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

static int updateBinaryResource(Connection connection, String resourceID, InputStream resourceValue,
        String dataType, String updatedBy) throws SQLException {
    final String query = "UPDATE AM_API_RESOURCES SET RESOURCE_BINARY_VALUE = ?, DATA_TYPE = ?, UPDATED_BY = ?, "
            + "LAST_UPDATED_TIME = ? WHERE UUID = ?";
    try (PreparedStatement statement = connection.prepareStatement(query)) {
        statement.setBinaryStream(1, resourceValue);
        statement.setString(2, dataType);
        statement.setString(3, updatedBy);
        statement.setTimestamp(4, Timestamp.valueOf(LocalDateTime.now()));
        statement.setString(5, resourceID);
        return statement.executeUpdate();
    }/*from ww  w .j  av a 2 s .  co  m*/
}

From source file:jp.co.tis.gsp.tools.dba.dialect.MysqlDialect.java

@Override
public void setObjectInStmt(PreparedStatement stmt, int parameterIndex, String value, int sqlType)
        throws SQLException {
    if (sqlType == UN_USABLE_TYPE) {
        stmt.setNull(parameterIndex, Types.NULL);
    } else if (StringUtil.isBlank(value) || "".equals(value)) {
        stmt.setNull(parameterIndex, sqlType);
    } else if (sqlType == Types.TIMESTAMP) {
        stmt.setTimestamp(parameterIndex, Timestamp.valueOf(value));
    } else {//from   w  ww.  ja  v  a 2 s.co  m
        stmt.setObject(parameterIndex, value, sqlType);
    }
}

From source file:org.apache.hadoop.hive.ql.optimizer.calcite.druid.DruidIntervalUtils.java

private static Comparable toTimestamp(Object literal) {
    if (literal instanceof Timestamp) {
        return (Timestamp) literal;
    }/*from www . j  a  v  a2 s .  c o  m*/
    if (literal instanceof Date) {
        return new Timestamp(((Date) literal).getTime());
    }
    if (literal instanceof Number) {
        return new Timestamp(((Number) literal).longValue());
    }
    if (literal instanceof String) {
        String string = (String) literal;
        if (StringUtils.isNumeric(string)) {
            return new Timestamp(Long.valueOf(string));
        }
        try {
            return Timestamp.valueOf(string);
        } catch (NumberFormatException e) {
            // ignore
        }
    }
    return null;
}