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.GenericResource.java

@POST
@Path("/updateDetailOrder")
@Consumes(MediaType.APPLICATION_JSON)// w  w  w .  j  av a2 s.  com
public Response updateDetailOrder(String pTakeOrder) {

    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Calendar cal = Calendar.getInstance();
    String time = sdf2.format(cal.getTime());

    // pair to object
    ObjectMapper mapper = new ObjectMapper();
    TakeOrderDetail takeOrderDetail = new TakeOrderDetail();
    try {
        //         File jsonFile = new File(jsonFilePath);
        takeOrderDetail = mapper.readValue(pTakeOrder, TakeOrderDetail.class);
        //System.out.println(track.getMMaKhachHang());
    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    //Update location
    TakeOrderDetailDAO takeOrderDetailDAO = new TakeOrderDetailDAOImpl();
    boolean st = takeOrderDetailDAO.update(takeOrderDetail);
    if (!st)
        return Response.status(200).entity(st + "").build();

    //Update the order
    List<TakeOrderDetail> list = new ArrayList<TakeOrderDetail>();

    list = takeOrderDetailDAO.getDetailTakeOrdersList(takeOrderDetail.getTakeOrderID());
    float priceTotal = 0;
    for (int i = 0; i < list.size(); i++) {
        priceTotal += list.get(i).getPriceTotal();
    }

    TakeOrder takeOrder = new TakeOrder();
    TakeOrderDAO takeOrderDAO = new TakeOrderDAOImpl();

    takeOrder = takeOrderDAO.getTakeOrder(takeOrderDetail.getTakeOrderID());
    takeOrder.setAfterPrivate(priceTotal - priceTotal * takeOrder.getDiscount() / 100);

    takeOrder.setOrderEditDate(Timestamp.valueOf(time));

    boolean st2 = takeOrderDAO.update(takeOrder);
    //            String output = pTrack.toString();
    System.out.println("____ " + pTakeOrder + "___ " + st);
    return Response.status(200).entity(st2 + "").build();
}

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

@POST
@Path("/updateAddingTakeOrder")
@Consumes(MediaType.APPLICATION_JSON)/* www. j  av  a  2 s  .  c  om*/
public Response updateAddingTakeOrder(String pOrder) {
    // pair to object

    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Calendar cal = Calendar.getInstance();
    String time = sdf2.format(cal.getTime());

    ObjectMapper mapper = new ObjectMapper();
    TakeOrder takeOrder = new TakeOrder();
    try {
        //         File jsonFile = new File(jsonFilePath);
        takeOrder = mapper.readValue(pOrder, TakeOrder.class);
        //System.out.println(track.getmMaKhachHang());
    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    takeOrder.setOrderEditDate(Timestamp.valueOf(time));

    TakeOrderDAO takeOrderDAO = new TakeOrderDAOImpl();
    boolean b = takeOrderDAO.update(takeOrder);

    return Response.status(200).entity(b + "").build();
}

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

@POST
@Path("/updateAddingInventory")
@Consumes(MediaType.APPLICATION_JSON)/*from w ww  .  j  a v a 2  s. com*/
public Response updateAddingInventory(String pOrder) {

    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Calendar cal = Calendar.getInstance();
    String time = sdf2.format(cal.getTime());

    // pair to object
    ObjectMapper mapper = new ObjectMapper();
    InventoryManager inventoryManager = new InventoryManager();
    try {
        //         File jsonFile = new File(jsonFilePath);
        inventoryManager = mapper.readValue(pOrder, InventoryManager.class);
        //System.out.println(track.getmMaKhachHang());
    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    inventoryManager.setOrderEditDate(Timestamp.valueOf(time));

    InventoryManagerDAO inventoryManagerDAO = new InventoryManagerDAOImpl();
    boolean b = inventoryManagerDAO.update(inventoryManager);

    return Response.status(200).entity(b + "").build();
}

From source file:com.alibaba.wasp.jdbc.TestPreparedStatement.java

public void testObject() throws SQLException {
    Statement stat = conn.createStatement();
    ResultSet rs;//  w  w w.  j a  v  a2s. c o m
    stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
    stat.execute("INSERT INTO TEST VALUES(1, 'Hello')");
    PreparedStatement prep = conn
            .prepareStatement("SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? FROM TEST");
    prep.setObject(1, Boolean.TRUE);
    prep.setObject(2, "Abc");
    prep.setObject(3, new BigDecimal("10.2"));
    prep.setObject(4, new Byte((byte) 0xff));
    prep.setObject(5, new Short(Short.MAX_VALUE));
    prep.setObject(6, new Integer(Integer.MIN_VALUE));
    prep.setObject(7, new Long(Long.MAX_VALUE));
    prep.setObject(8, new Float(Float.MAX_VALUE));
    prep.setObject(9, new Double(Double.MAX_VALUE));
    prep.setObject(10, Date.valueOf("2001-02-03"));
    prep.setObject(11, Time.valueOf("04:05:06"));
    prep.setObject(12, Timestamp.valueOf("2001-02-03 04:05:06.123456789"));
    prep.setObject(13, new java.util.Date(Date.valueOf("2001-02-03").getTime()));
    prep.setObject(14, new byte[] { 10, 20, 30 });
    prep.setObject(15, new Character('a'), Types.OTHER);
    prep.setObject(16, "2001-01-02", Types.DATE);
    // converting to null seems strange...
    prep.setObject(17, "2001-01-02", Types.NULL);
    prep.setObject(18, "3.725", Types.DOUBLE);
    prep.setObject(19, "23:22:21", Types.TIME);
    prep.setObject(20, new java.math.BigInteger("12345"), Types.OTHER);
    rs = prep.executeQuery();
    rs.next();
    assertTrue(rs.getObject(1).equals(Boolean.TRUE));
    assertTrue(rs.getObject(2).equals("Abc"));
    assertTrue(rs.getObject(3).equals(new BigDecimal("10.2")));
    assertTrue(rs.getObject(4).equals((byte) 0xff));
    assertTrue(rs.getObject(5).equals(new Short(Short.MAX_VALUE)));
    assertTrue(rs.getObject(6).equals(new Integer(Integer.MIN_VALUE)));
    assertTrue(rs.getObject(7).equals(new Long(Long.MAX_VALUE)));
    assertTrue(rs.getObject(8).equals(new Float(Float.MAX_VALUE)));
    assertTrue(rs.getObject(9).equals(new Double(Double.MAX_VALUE)));
    assertTrue(rs.getObject(10).equals(Date.valueOf("2001-02-03")));
    assertEquals("04:05:06", rs.getObject(11).toString());
    assertTrue(rs.getObject(11).equals(Time.valueOf("04:05:06")));
    assertTrue(rs.getObject(12).equals(Timestamp.valueOf("2001-02-03 04:05:06.123456789")));
    assertTrue(rs.getObject(13).equals(Timestamp.valueOf("2001-02-03 00:00:00")));
    assertEquals(new byte[] { 10, 20, 30 }, (byte[]) rs.getObject(14));
    assertTrue(rs.getObject(15).equals('a'));
    assertTrue(rs.getObject(16).equals(Date.valueOf("2001-01-02")));
    assertTrue(rs.getObject(17) == null && rs.wasNull());
    assertTrue(rs.getObject(18).equals(new Double(3.725)));
    assertTrue(rs.getObject(19).equals(Time.valueOf("23:22:21")));
    assertTrue(rs.getObject(20).equals(new java.math.BigInteger("12345")));

    // } else if(x instanceof java.io.Reader) {
    // return session.createLob(Value.CLOB,
    // TypeConverter.getInputStream((java.io.Reader)x), 0);
    // } else if(x instanceof java.io.InputStream) {
    // return session.createLob(Value.BLOB, (java.io.InputStream)x, 0);
    // } else {
    // return ValueBytes.get(TypeConverter.serialize(x));

    stat.execute("DROP TABLE TEST");

}

From source file:com.alibaba.wasp.jdbc.TestJdbcResultSet.java

@Test
public void testDatetime() throws SQLException {
    trace("test DATETIME");
    ResultSet rs;// www. ja  v  a2  s. c  o  m
    Object o;

    // rs = stat.executeQuery("call date '99999-12-23'");
    // rs.next();
    // assertEquals("99999-12-23", rs.getString(1));
    // rs = stat.executeQuery("call timestamp '99999-12-23 01:02:03.000'");
    // rs.next();
    // assertEquals("99999-12-23 01:02:03.0", rs.getString(1));
    // rs = stat.executeQuery("call date '-99999-12-23'");
    // rs.next();
    // assertEquals("-99999-12-23", rs.getString(1));
    // rs = stat.executeQuery("call timestamp '-99999-12-23 01:02:03.000'");
    // rs.next();
    // assertEquals("-99999-12-23 01:02:03.0", rs.getString(1));

    stat = conn.createStatement();
    // stat.execute("CREATE TABLE test(ID INT PRIMARY KEY,VALUE DATETIME)");
    stat.execute(
            "INSERT INTO test (column1,column6,column2,column3) VALUES (1,'2011-11-11 0:0:0', 13, 'testDatetime')");
    stat.execute(
            "INSERT INTO test (column1,column6,column2,column3) VALUES (2,'2002-02-02 02:02:02', 13, 'testDatetime')");
    stat.execute(
            "INSERT INTO test (column1,column6,column2,column3) VALUES (3,'1800-01-01 0:0:0', 13, 'testDatetime')");
    stat.execute(
            "INSERT INTO test (column1,column6,column2,column3) VALUES (4,'9999-12-31 23:59:59', 13, 'testDatetime')");
    stat.execute(
            "INSERT INTO test (column1,column6,column2,column3) VALUES (5,'9999-12-31 23:59:59', 13, 'testDatetime')");
    // stat.execute("INSERT INTO test (column1,column6,column2,column3) VALUES(5,NULL)");
    rs = stat.executeQuery("SELECT column1,column6 FROM test where column3='testDatetime' ORDER BY column1");
    // assertResultSetMeta(rs, 2, new String[] { "ID", "VALUE" }, new int[] {
    // Types.INTEGER, Types.TIMESTAMP }, new int[] { 10, 23 }, new int[] { 0,
    // 10 });
    // rs = stat.executeQuery("SELECT * FROM test ORDER BY ID");
    // assertResultSetMeta(rs, 2, new String[] { "ID", "VALUE" }, new int[] {
    // Types.INTEGER, Types.TIMESTAMP }, new int[] { 10, 23 }, new int[] { 0,
    // 10 });
    rs.next();
    java.sql.Date date;
    java.sql.Time time;
    Timestamp ts;
    date = rs.getDate(2);
    assertTrue(!rs.wasNull());
    time = rs.getTime(2);
    assertTrue(!rs.wasNull());
    ts = rs.getTimestamp(2);
    assertTrue(!rs.wasNull());
    trace("Date: " + date.toString() + " Time:" + time.toString() + " Timestamp:" + ts.toString());
    trace("Date ms: " + date.getTime() + " Time ms:" + time.getTime() + " Timestamp ms:" + ts.getTime());
    trace("1970 ms: " + Timestamp.valueOf("1970-01-01 00:00:00.0").getTime());
    assertEquals(Timestamp.valueOf("2011-11-11 00:00:00.0").getTime(), date.getTime());
    assertEquals(Timestamp.valueOf("1970-01-01 00:00:00.0").getTime(), time.getTime());
    assertEquals(Timestamp.valueOf("2011-11-11 00:00:00.0").getTime(), ts.getTime());
    assertTrue(date.equals(java.sql.Date.valueOf("2011-11-11")));
    assertTrue(time.equals(java.sql.Time.valueOf("00:00:00")));
    assertTrue(ts.equals(Timestamp.valueOf("2011-11-11 00:00:00.0")));
    assertFalse(rs.wasNull());
    o = rs.getObject(2);
    trace(o.getClass().getName());
    assertTrue(o instanceof Timestamp);
    assertTrue(((Timestamp) o).equals(Timestamp.valueOf("2011-11-11 00:00:00")));
    assertFalse(rs.wasNull());
    rs.next();
    date = rs.getDate("COLUMN6");
    assertTrue(!rs.wasNull());
    time = rs.getTime("COLUMN6");
    assertTrue(!rs.wasNull());
    ts = rs.getTimestamp("COLUMN6");
    assertTrue(!rs.wasNull());
    trace("Date: " + date.toString() + " Time:" + time.toString() + " Timestamp:" + ts.toString());
    assertEquals("2002-02-02", date.toString());
    assertEquals("02:02:02", time.toString());
    assertEquals("2002-02-02 02:02:02.0", ts.toString());
    rs.next();
    assertEquals("1800-01-01", rs.getDate("column6").toString());
    assertEquals("00:00:00", rs.getTime("column6").toString());
    assertEquals("1800-01-01 00:00:00.0", rs.getTimestamp("column6").toString());
    rs.next();
    assertEquals("9999-12-31", rs.getDate("Column6").toString());
    assertEquals("23:59:59", rs.getTime("Column6").toString());
    assertEquals("9999-12-31 23:59:59.0", rs.getTimestamp("Column6").toString());
    // assertTrue(!rs.next());
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.cdc.oracle.OracleCDCSource.java

private void generateRecords(Offset startingOffset, PreparedStatement selectChanges) {
    // When this is called the first time, Logminer was started either from SCN or from a start date, so we just keep
    // track of the start date etc.
    LOG.info("Attempting to generate records");
    boolean error;
    StringBuilder query = new StringBuilder();
    BigDecimal lastCommitSCN = new BigDecimal(startingOffset.scn);
    int sequenceNumber = startingOffset.sequence;
    LocalDateTime startTime = adjustStartTime(startingOffset.timestamp);
    String lastTxnId = startingOffset.txnId;
    LocalDateTime endTime = getEndTimeForStartTime(startTime);
    ResultSet resultSet = null;//from w w w .jav  a 2 s . c  o  m
    while (!getContext().isStopped()) {
        error = false;
        generationStarted = true;
        try {
            recordQueue.put(new RecordOffset(dummyRecord,
                    new Offset(version, startTime, lastCommitSCN.toPlainString(), sequenceNumber, lastTxnId)));
            selectChanges = getSelectChangesStatement();
            if (!useLocalBuffering) {
                selectChanges.setBigDecimal(1, lastCommitSCN);
                selectChanges.setInt(2, sequenceNumber);
                selectChanges.setBigDecimal(3, lastCommitSCN);
                if (shouldTrackDDL) {
                    selectChanges.setBigDecimal(4, lastCommitSCN);
                }
            }
            selectChanges.setFetchSize(configBean.jdbcFetchSize);
            resultSet = selectChanges.executeQuery();
            while (resultSet.next() && !getContext().isStopped()) {
                String queryFragment = resultSet.getString(5);
                BigDecimal scnDecimal = resultSet.getBigDecimal(1);
                String scn = scnDecimal.toPlainString();
                String xidUsn = String.valueOf(resultSet.getLong(10));
                String xidSlt = String.valueOf(resultSet.getString(11));
                String xidSqn = String.valueOf(resultSet.getString(12));
                String xid = xidUsn + "." + xidSlt + "." + xidSqn;
                // Query Fragment is not null -> we need to process
                // Query Fragment is null AND the query string buffered from previous rows due to CSF == 0 is null,
                // nothing to do, go to next row
                // Query Fragment is null, but there is previously buffered data in the query, go ahead and process.
                if (queryFragment != null) {
                    query.append(queryFragment);
                } else if (queryFragment == null && query.length() == 0) {
                    LOG.debug(READ_NULL_QUERY_FROM_ORACLE, scn, xid);
                    continue;
                }

                // CSF is 1 if the query is incomplete, so read the next row before parsing
                // CSF being 0 means query is complete, generate the record
                if (resultSet.getInt(9) == 0) {
                    if (query.length() == 0) {
                        LOG.debug(READ_NULL_QUERY_FROM_ORACLE, scn, xid);
                        continue;
                    }
                    String queryString = query.toString();
                    query.setLength(0);
                    String username = resultSet.getString(2);
                    short op = resultSet.getShort(3);
                    String timestamp = resultSet.getString(4);
                    LocalDateTime tsDate = Timestamp.valueOf(timestamp).toLocalDateTime();
                    delay.getValue().put("delay", getDelay(tsDate));
                    String table = resultSet.getString(6);
                    BigDecimal commitSCN = resultSet.getBigDecimal(7);
                    int seq = resultSet.getInt(8);

                    String rsId = resultSet.getString(13);
                    Object ssn = resultSet.getObject(14);
                    String schema = String.valueOf(resultSet.getString(15));
                    int rollback = resultSet.getInt(16);
                    String rowId = resultSet.getString(17);
                    SchemaAndTable schemaAndTable = new SchemaAndTable(schema, table);
                    TransactionIdKey key = new TransactionIdKey(xid);
                    bufferedRecordsLock.lock();
                    try {
                        if (useLocalBuffering && bufferedRecords.containsKey(key) && bufferedRecords.get(key)
                                .contains(new RecordSequence(null, null, 0, 0, rsId, ssn, null))) {
                            continue;
                        }
                    } finally {
                        bufferedRecordsLock.unlock();
                    }
                    Offset offset = null;
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(
                                "Commit SCN = {}, SCN = {}, Operation = {}, Txn Id = {}, Timestamp = {}, Row Id = {}, Redo SQL = {}",
                                commitSCN, scn, op, xid, tsDate, rowId, queryString);
                    }

                    if (op != DDL_CODE && op != COMMIT_CODE && op != ROLLBACK_CODE) {
                        if (!useLocalBuffering) {
                            offset = new Offset(version, tsDate, commitSCN.toPlainString(), seq, xid);
                        }
                        Map<String, String> attributes = new HashMap<>();
                        attributes.put(SCN, scn);
                        attributes.put(USER, username);
                        attributes.put(TIMESTAMP_HEADER, timestamp);
                        attributes.put(TABLE, table);
                        attributes.put(SEQ, String.valueOf(seq));
                        attributes.put(XID, xid);
                        attributes.put(RS_ID, rsId);
                        attributes.put(SSN, ssn.toString());
                        attributes.put(SCHEMA, schema);
                        attributes.put(ROLLBACK, String.valueOf(rollback));
                        attributes.put(ROWID_KEY, rowId);
                        if (!useLocalBuffering || getContext().isPreview()) {
                            if (commitSCN.compareTo(lastCommitSCN) < 0
                                    || (commitSCN.compareTo(lastCommitSCN) == 0 && seq < sequenceNumber)) {
                                continue;
                            }
                            lastCommitSCN = commitSCN;
                            sequenceNumber = seq;
                            if (configBean.keepOriginalQuery) {
                                attributes.put(QUERY_KEY, queryString);
                            }
                            try {
                                Record record = generateRecord(queryString, attributes, op);
                                if (record != null && record.getEscapedFieldPaths().size() > 0) {
                                    recordQueue.put(new RecordOffset(record, offset));
                                }
                            } catch (UnparseableSQLException ex) {
                                LOG.error("Parsing failed", ex);
                                unparseable.offer(queryString);
                            }
                        } else {
                            bufferedRecordsLock.lock();
                            try {
                                HashQueue<RecordSequence> records = bufferedRecords.computeIfAbsent(key, x -> {
                                    x.setTxnStartTime(tsDate);
                                    return createTransactionBuffer(key.txnId);
                                });

                                int nextSeq = records.isEmpty() ? 1 : records.tail().seq + 1;
                                RecordSequence node = new RecordSequence(attributes, queryString, nextSeq, op,
                                        rsId, ssn, tsDate);
                                records.add(node);
                            } finally {
                                bufferedRecordsLock.unlock();
                            }
                        }
                    } else if (!getContext().isPreview() && useLocalBuffering
                            && (op == COMMIT_CODE || op == ROLLBACK_CODE)) {
                        // so this commit was previously processed or it is a rollback, so don't care.
                        if (op == ROLLBACK_CODE || scnDecimal.compareTo(lastCommitSCN) < 0) {
                            bufferedRecordsLock.lock();
                            try {
                                bufferedRecords.remove(key);
                            } finally {
                                bufferedRecordsLock.unlock();
                            }
                        } else {
                            bufferedRecordsLock.lock();
                            try {
                                HashQueue<RecordSequence> records = bufferedRecords.getOrDefault(key,
                                        EMPTY_LINKED_HASHSET);
                                if (lastCommitSCN.equals(scnDecimal) && xid.equals(lastTxnId)) {
                                    removeProcessedRecords(records, sequenceNumber);
                                }
                                int bufferedRecordsToBeRemoved = records.size();
                                LOG.debug(FOUND_RECORDS_IN_TRANSACTION, bufferedRecordsToBeRemoved, xid);
                                lastCommitSCN = scnDecimal;
                                lastTxnId = xid;
                                sequenceNumber = addRecordsToQueue(tsDate, scn, xid);
                            } finally {
                                bufferedRecordsLock.unlock();
                            }
                        }
                    } else {
                        offset = new Offset(version, tsDate, scn, 0, xid);
                        boolean sendSchema = false;
                        // Commit/rollback in Preview will also end up here, so don't really do any of the following in preview
                        // Don't bother with DDL events here.
                        if (!getContext().isPreview()) {
                            // Event is sent on every DDL, but schema is not always sent.
                            // Schema sending logic:
                            // CREATE/ALTER: Schema is sent if the schema after the ALTER is newer than the cached schema
                            // (which we would have sent as an event earlier, at the last alter)
                            // DROP/TRUNCATE: Schema is not sent, since they don't change schema.
                            DDL_EVENT type = getDdlType(queryString);
                            if (type == DDL_EVENT.ALTER || type == DDL_EVENT.CREATE) {
                                sendSchema = refreshSchema(scnDecimal, new SchemaAndTable(schema, table));
                            }
                            recordQueue.put(new RecordOffset(createEventRecord(type, queryString,
                                    schemaAndTable, offset.toString(), sendSchema, timestamp), offset));
                        }
                    }
                    query.setLength(0);
                }
            }
        } catch (SQLException ex) {
            error = true;
            // force a restart from the same timestamp.
            if (ex.getErrorCode() == MISSING_LOG_FILE) {
                LOG.warn("SQL Exception while retrieving records", ex);
                addToStageExceptionsQueue(new StageException(JDBC_86, ex));
            } else if (ex.getErrorCode() != RESULTSET_CLOSED_AS_LOGMINER_SESSION_CLOSED) {
                LOG.warn("SQL Exception while retrieving records", ex);
            } else if (ex.getErrorCode() == QUERY_TIMEOUT) {
                LOG.warn("LogMiner select query timed out");
            } else if (ex.getErrorCode() == LOGMINER_START_MUST_BE_CALLED) {
                LOG.warn("Last LogMiner session did not start successfully. Will retry", ex);
            } else {
                LOG.error("Error while reading data", ex);
                addToStageExceptionsQueue(new StageException(JDBC_52, ex));
            }
        } catch (StageException e) {
            LOG.error("Error while reading data", e);
            error = true;
            addToStageExceptionsQueue(e);
        } catch (InterruptedException ex) {
            LOG.error("Interrupted while waiting to add data");
            Thread.currentThread().interrupt();
        } catch (Exception ex) {
            LOG.error("Error while reading data", ex);
            error = true;
            addToStageExceptionsQueue(new StageException(JDBC_52, ex));
        } finally {
            // If an incomplete batch is seen, it means we are going to move the window forward
            // Ending this session and starting a new one helps reduce PGA memory usage.
            try {
                if (resultSet != null && !resultSet.isClosed()) {
                    resultSet.close();
                }
                if (selectChanges != null && !selectChanges.isClosed()) {
                    selectChanges.close();
                }
            } catch (SQLException ex) {
                LOG.warn("Error while attempting to close SQL statements", ex);
            }
            try {
                endLogMnr.execute();
            } catch (SQLException ex) {
                LOG.warn("Error while trying to close logminer session", ex);
            }
            try {
                if (error) {
                    resetConnectionsQuietly();
                } else {
                    discardOldUncommitted(startTime);
                    startTime = adjustStartTime(endTime);
                    endTime = getEndTimeForStartTime(startTime);
                }
                startLogMinerUsingGivenDates(startTime.format(dateTimeColumnHandler.dateFormatter),
                        endTime.format(dateTimeColumnHandler.dateFormatter));
            } catch (SQLException ex) {
                LOG.error("Error while attempting to start LogMiner", ex);
                addToStageExceptionsQueue(new StageException(JDBC_52, ex));
            } catch (StageException ex) {
                LOG.error("Error while attempting to start logminer for redo log dictionary", ex);
                addToStageExceptionsQueue(ex);
            }
        }
    }
}

From source file:org.apache.drill.test.TestBuilder.java

/**
 * Helper method for the timestamp values that depend on the local timezone
 * @param value expected timestamp value in UTC
 * @return timestamp value for the local timezone
 *//*from  w  ww .  j a va  2 s.c o  m*/
public static Timestamp convertToLocalTimestamp(String value) {
    long UTCTimestamp = Timestamp.valueOf(value).getTime();
    return new Timestamp(DateTimeZone.getDefault().convertUTCToLocal(UTCTimestamp));
}

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

@POST
@Path("/updateAddingSaleOrder")
@Consumes(MediaType.APPLICATION_JSON)//  ww w . j a  v  a  2s  .  c  o m
public Response updateAddingSaleOrder(String pOrder) {

    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Calendar cal = Calendar.getInstance();
    String time = sdf2.format(cal.getTime());

    // pair to object
    ObjectMapper mapper = new ObjectMapper();
    SaleOrder saleOrder = new SaleOrder();
    try {
        //         File jsonFile = new File(jsonFilePath);
        saleOrder = mapper.readValue(pOrder, SaleOrder.class);
        //System.out.println(track.getmMaKhachHang());
    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    saleOrder.setOrderEditDate(Timestamp.valueOf(time));

    SaleOrderDAO saleOrderDAO = new SaleOrderDAOImpl();
    boolean b = saleOrderDAO.update(saleOrder);

    return Response.status(200).entity(b + "").build();
}

From source file:org.ofbiz.widget.form.MacroFormRenderer.java

public void renderDateTimeField(Appendable writer, Map<String, Object> context, DateTimeField dateTimeField)
        throws IOException {
    ModelFormField modelFormField = dateTimeField.getModelFormField();
    String paramName = modelFormField.getParameterName(context);
    String defaultDateTimeString = dateTimeField.getDefaultDateTimeString(context);
    String className = "";
    String alert = "false";
    String name = "";
    String formattedMask = "";
    String event = modelFormField.getEvent();
    String action = modelFormField.getAction(context);
    if (UtilValidate.isNotEmpty(modelFormField.getWidgetStyle())) {
        className = modelFormField.getWidgetStyle();
        if (modelFormField.shouldBeRed(context)) {
            alert = "true";
        }//from   ww  w.  java2s .c  om
    }
    boolean useTimeDropDown = "time-dropdown".equals(dateTimeField.getInputMethod());
    String stepString = dateTimeField.getStep();
    int step = 1;
    StringBuilder timeValues = new StringBuilder();
    if (useTimeDropDown && UtilValidate.isNotEmpty(step)) {
        try {
            step = Integer.valueOf(stepString).intValue();
        } catch (IllegalArgumentException e) {
            Debug.logWarning("Inavalid value for step property for field[" + paramName
                    + "] with input-method=\"time-dropdown\" " + " Found Value [" + stepString + "]  "
                    + e.getMessage(), module);
        }
        timeValues.append("[");
        for (int i = 0; i <= 59;) {
            if (i != 0) {
                timeValues.append(", ");
            }
            timeValues.append(i);
            i += step;
        }
        timeValues.append("]");
    }
    Map<String, String> uiLabelMap = UtilGenerics.checkMap(context.get("uiLabelMap"));
    if (uiLabelMap == null) {
        Debug.logWarning("Could not find uiLabelMap in context", module);
    }
    String localizedInputTitle = "", localizedIconTitle = "";

    // whether the date field is short form, yyyy-mm-dd
    boolean shortDateInput = ("date".equals(dateTimeField.getType()) || useTimeDropDown ? true : false);

    if (useTimeDropDown) {
        name = UtilHttp.makeCompositeParam(paramName, "date");
    } else {
        name = paramName;
    }

    // the default values for a timestamp
    int size = 25;
    int maxlength = 30;

    if (shortDateInput) {
        size = maxlength = 10;
        if (uiLabelMap != null) {
            localizedInputTitle = uiLabelMap.get("CommonFormatDate");
        }
    } else if ("time".equals(dateTimeField.getType())) {
        size = maxlength = 8;
        if (uiLabelMap != null) {
            localizedInputTitle = uiLabelMap.get("CommonFormatTime");
        }
    } else {
        if (uiLabelMap != null) {
            localizedInputTitle = uiLabelMap.get("CommonFormatDateTime");
        }
    }

    String contextValue = null;
    // If time-dropdown deactivate encodingOutput for found hour and minutes
    boolean memEncodeOutput = modelFormField.getEncodeOutput();
    if (useTimeDropDown)
        // FIXME: This is not thread-safe! Never modify a model's state!
        modelFormField.setEncodeOutput(false);
    // FIXME: modelFormField.getEntry ignores shortDateInput when converting Date objects to Strings.
    // Object type conversion should be done by the renderer, not by the model.
    contextValue = modelFormField.getEntry(context, dateTimeField.getDefaultValue(context));
    if (useTimeDropDown)
        modelFormField.setEncodeOutput(memEncodeOutput);

    String value = contextValue;
    if (UtilValidate.isNotEmpty(value)) {
        if (value.length() > maxlength) {
            value = value.substring(0, maxlength);
        }
    }
    String id = modelFormField.getCurrentContainerId(context);
    String formName = modelFormField.getModelForm().getCurrentFormName(context);
    String timeDropdown = dateTimeField.getInputMethod();
    String timeDropdownParamName = "";
    String classString = "";
    boolean isTwelveHour = false;
    String timeHourName = "";
    int hour2 = 0, hour1 = 0, minutes = 0;
    String timeMinutesName = "";
    String amSelected = "", pmSelected = "", ampmName = "";
    String compositeType = "";
    // search for a localized label for the icon
    if (uiLabelMap != null) {
        localizedIconTitle = uiLabelMap.get("CommonViewCalendar");
    }

    if (!"time".equals(dateTimeField.getType())) {
        String tempParamName;
        if (useTimeDropDown) {
            tempParamName = UtilHttp.makeCompositeParam(paramName, "date");
        } else {
            tempParamName = paramName;
        }
        timeDropdownParamName = tempParamName;
        defaultDateTimeString = UtilHttp.encodeBlanks(modelFormField.getEntry(context, defaultDateTimeString));
    }

    // if we have an input method of time-dropdown, then render two
    // dropdowns
    if (useTimeDropDown) {
        className = modelFormField.getWidgetStyle();
        classString = (className != null ? className : "");
        isTwelveHour = "12".equals(dateTimeField.getClock());

        // set the Calendar to the default time of the form or now()
        Calendar cal = null;
        try {
            Timestamp defaultTimestamp = Timestamp.valueOf(contextValue);
            cal = Calendar.getInstance();
            cal.setTime(defaultTimestamp);
        } catch (IllegalArgumentException e) {
            Debug.logWarning("Form widget field [" + paramName
                    + "] with input-method=\"time-dropdown\" was not able to understand the default time ["
                    + defaultDateTimeString + "]. The parsing error was: " + e.getMessage(), module);
        }

        timeHourName = UtilHttp.makeCompositeParam(paramName, "hour");
        if (cal != null) {
            int hour = cal.get(Calendar.HOUR_OF_DAY);
            hour2 = hour;
            if (hour == 0) {
                hour = 12;
            }
            if (hour > 12) {
                hour -= 12;
            }
            hour1 = hour;
            minutes = cal.get(Calendar.MINUTE);
        }
        timeMinutesName = UtilHttp.makeCompositeParam(paramName, "minutes");
        compositeType = UtilHttp.makeCompositeParam(paramName, "compositeType");
        // if 12 hour clock, write the AM/PM selector
        if (isTwelveHour) {
            amSelected = ((cal != null && cal.get(Calendar.AM_PM) == Calendar.AM) ? "selected" : "");
            pmSelected = ((cal != null && cal.get(Calendar.AM_PM) == Calendar.PM) ? "selected" : "");
            ampmName = UtilHttp.makeCompositeParam(paramName, "ampm");
        }
    }

    //check for required field style on single forms
    if ("single".equals(modelFormField.getModelForm().getType()) && modelFormField.getRequiredField()) {
        String requiredStyle = modelFormField.getRequiredFieldStyle();
        if (UtilValidate.isEmpty(requiredStyle))
            requiredStyle = "required";
        if (UtilValidate.isEmpty(className))
            className = requiredStyle;
        else
            className = requiredStyle + " " + className;
    }

    String mask = dateTimeField.getMask();
    if ("Y".equals(mask)) {
        if ("date".equals(dateTimeField.getType())) {
            formattedMask = "9999-99-99";
        } else if ("time".equals(dateTimeField.getType())) {
            formattedMask = "99:99:99";
        } else if ("timestamp".equals(dateTimeField.getType())) {
            formattedMask = "9999-99-99 99:99:99";
        }
    }
    StringWriter sr = new StringWriter();
    sr.append("<@renderDateTimeField ");
    sr.append("name=\"");
    sr.append(name);
    sr.append("\" className=\"");
    sr.append(className);
    sr.append("\" alert=\"");
    sr.append(alert);
    sr.append("\" value=\"");
    sr.append(value);
    sr.append("\" title=\"");
    sr.append(localizedInputTitle);
    sr.append("\" size=\"");
    sr.append(Integer.toString(size));
    sr.append("\" maxlength=\"");
    sr.append(Integer.toString(maxlength));
    sr.append("\" step=\"");
    sr.append(Integer.toString(step));
    sr.append("\" timeValues=\"");
    sr.append(timeValues.toString());
    sr.append("\" id=\"");
    sr.append(id);
    sr.append("\" event=\"");
    sr.append(event);
    sr.append("\" action=\"");
    sr.append(action);
    sr.append("\" dateType=\"");
    sr.append(dateTimeField.getType());
    sr.append("\" shortDateInput=");
    sr.append(Boolean.toString(shortDateInput));
    sr.append(" timeDropdownParamName=\"");
    sr.append(timeDropdownParamName);
    sr.append("\" defaultDateTimeString=\"");
    sr.append(defaultDateTimeString);
    sr.append("\" localizedIconTitle=\"");
    sr.append(localizedIconTitle);
    sr.append("\" timeDropdown=\"");
    sr.append(timeDropdown);
    sr.append("\" timeHourName=\"");
    sr.append(timeHourName);
    sr.append("\" classString=\"");
    sr.append(classString);
    sr.append("\" hour1=");
    sr.append(Integer.toString(hour1));
    sr.append(" hour2=");
    sr.append(Integer.toString(hour2));
    sr.append(" timeMinutesName=\"");
    sr.append(timeMinutesName);
    sr.append("\" minutes=");
    sr.append(Integer.toString(minutes));
    sr.append(" isTwelveHour=");
    sr.append(Boolean.toString(isTwelveHour));
    sr.append(" ampmName=\"");
    sr.append(ampmName);
    sr.append("\" amSelected=\"");
    sr.append(amSelected);
    sr.append("\" pmSelected=\"");
    sr.append(pmSelected);
    sr.append("\" compositeType=\"");
    sr.append(compositeType);
    sr.append("\" formName=\"");
    sr.append(formName);
    sr.append("\" mask=\"");
    sr.append(formattedMask);
    sr.append("\" />");
    executeMacro(writer, sr.toString());
    this.addAsterisks(writer, context, modelFormField);
    this.appendTooltip(writer, context, modelFormField);
}

From source file:org.shengrui.oa.util.UtilDateTime.java

/**
 * //from  ww w .j a  va  2  s.  c  om
 * @param date
 * @param daySeed
 * @return
 */
public static Date getDayByMonthSeed(Date date, int monthSeed) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.add(Calendar.MONTH, monthSeed);
    String dstr = toDateString(calendar.getTime());
    return Timestamp.valueOf(dstr + " 00:00:00");
    //return calendar.getTime();
}