下面列出了怎么用java.sql.Timestamp的API类实例代码及写法,或者点击链接到github查看源代码。
public String appStuTestPaper() throws Exception{
Map<String, Object> map=new HashMap<String, Object>();
Class_ classFind=classService.findById(classId);
if(classFind==null){
map.put("name", "noClass");
}
else{
Timestamp nowTime=new Timestamp(new Date().getTime());
List<TestPaper> testPaperList=testPaperService.findByClass(classFind,nowTime);
if(testPaperList.size()<1){
map.put("name", "noTestPaper");
}
else{
ClassPropertyFilter.ListTestPaperFilter(map, testPaperList);
map.put("name", "success");
}
}
JsonUtil.toJson(ServletActionContext.getResponse(), map);
return null;
}
@Test
public void testCastEscapeOperator() {
doInJPA(entityManager -> {
List<Post> posts = entityManager.createNativeQuery(
"SELECT * " +
"FROM post " +
"WHERE " +
" date_part('dow', created_on) = " +
" date_part('dow', :datetime\\:\\:date)", Post.class)
.setParameter("datetime", Timestamp.valueOf(
LocalDateTime.now().with(
TemporalAdjusters.next(DayOfWeek.MONDAY)))
)
.getResultList();
assertEquals(1, posts.size());
assertEquals("High-Performance Java Persistence, Part 1", posts.get(0).getTitle());
});
}
/**
* Convert the specified input object into an output object of the
* specified type.
*
* @param type Data type to which this value should be converted
* @param value The input value to be converted
*
* @exception org.apache.commons.beanutils.ConversionException if conversion cannot be performed
* successfully
*/
public Object convert(Class type, Object value) {
if (value == null) {
if (useDefault) {
return (defaultValue);
} else {
throw new ConversionException("No value specified");
}
}
if (value instanceof Timestamp) {
return (value);
}
try {
return (Timestamp.valueOf(value.toString()));
} catch (Exception e) {
if (useDefault) {
return (defaultValue);
} else {
throw new ConversionException(e);
}
}
}
public void incrementUntil(MithraDatedTransactionalObject mithraObject, TemporalContainer container,
AttributeUpdateWrapper updateWrapper, Timestamp until)
{
checkInfinityDate(mithraObject);
container.enrollInWrite(mithraObject.zGetCurrentData());
Cache cache = mithraObject.zGetCache();
MithraTransaction tx = MithraManagerProvider.getMithraManager().getCurrentTransaction();
Timestamp asOfDate = businessDateAttribute.timestampValueOf(mithraObject);
Timestamp fromDate = this.getBusinessFromDateForBusinessDate(asOfDate);
Timestamp endDate = getBusinessFromDateForBusinessDate(until);
InternalList inTxObjects = this.sortByBusinessFrom(container.getObjectsForRange(mithraObject,
fromDate, endDate));
incrementMultipleWrappersUntil(inTxObjects, fromDate, endDate, cache, tx,
new AttributeUpdateWrapper[] { updateWrapper} , container);
mithraObject.zClearTxData();
}
public void testTimestampHavingLessThanForPrimitiveBeanList() throws ParseException
{
Timestamp ts = new Timestamp(timestampFormat.parse("2004-02-13 00:00:00.0").getTime());
Timestamp ts3 = new Timestamp(timestampFormat.parse("2004-02-12 01:00:00.0").getTime());
Timestamp ts4 = new Timestamp(timestampFormat.parse("2004-02-12 02:00:00.0").getTime());
Operation op = SaleFinder.all();
AggregateBeanList<PrimitiveAggregateBean> aggregateBeanList = new AggregateBeanList<PrimitiveAggregateBean>(op, PrimitiveAggregateBean.class);
aggregateBeanList.addAggregateAttribute("maxSaleDate", SaleFinder.saleDate().max());
aggregateBeanList.addGroupBy("id", SaleFinder.sellerId());
aggregateBeanList.setHavingOperation(SaleFinder.saleDate().max().lessThan(ts));
assertEquals(2, aggregateBeanList.size());
for (PrimitiveAggregateBean data : aggregateBeanList)
{
if (data.getId() == 3)
{
assertEquals(ts3, data.getMaxSaleDate());
}
else if (data.getId() == 4)
{
assertEquals(ts4, data.getMaxSaleDate());
}
else
{
fail("Invalid seller id");
}
}
}
public void testRetrieveOneRowUsingTimestampInOperation()
throws ParseException
{
Operation op = AllTypesFinder.timestampValue().eq(new Timestamp(timestampFormat.parse("2007-01-01 01:01:01.999").getTime()));
String sql = "select * from " + getSchemaName() + ".ALL_TYPES where TIMESTAMP_COL = '01-JAN-07 01:01:01.999'";
validateMithraResult(op, sql);
}
@Override
public void setItemComplete(Long taskListItemUid, Long userId, Long sessionId) {
TaskListItemVisitLog log = taskListItemVisitDao.getTaskListItemLog(taskListItemUid, userId);
if (log == null) {
log = new TaskListItemVisitLog();
TaskListItem item = taskListItemDao.getByUid(taskListItemUid);
log.setTaskListItem(item);
TaskListUser user = taskListUserDao.getUserByUserIDAndSessionID(userId, sessionId);
log.setUser(user);
log.setSessionId(sessionId);
log.setAccessDate(new Timestamp(new Date().getTime()));
}
log.setComplete(true);
taskListItemVisitDao.saveObject(log);
}
/**
* Creates a new EventServiceLog. This method will automatically determine
* if the subscriber is an implementation of {@link LoggableSubscriber} and
* if so, will log the event. If not, then nothing will be logged and this
* method will return null.
* @param clazz the class of the subscriber task that handles the event
* @return a new EventServiceLog
*/
public EventServiceLog createEventServiceLog(Class<? extends Subscriber> clazz) {
if (LoggableSubscriber.class.isAssignableFrom(clazz)) {
pm.currentTransaction().begin();
final EventServiceLog log = new EventServiceLog();
log.setSubscriberClass(clazz.getCanonicalName());
log.setStarted(new Timestamp(new Date().getTime()));
pm.makePersistent(log);
pm.currentTransaction().commit();
return getObjectById(EventServiceLog.class, log.getId());
}
return null;
}
@Test
public void testFilter() throws Exception
{
DateRange range = new DateRange(quickDate(20), quickDate(40));
Timestamp dates[] = {quickDate(50), quickDate(40), quickDate(30), quickDate(20), quickDate(10)};
Approvals.verifyAll("Dates", Query.where(dates, d -> range.contains(d)));
}
private static void print(LocalDateTime ldt, Timestamp ts) {
ZonedDateTime zdt = ZonedDateTime.of(ldt, ZoneId.systemDefault());
System.out.printf("ldt:ts %d/%d, %d/%d, %d/%d, %d/%d, %d/%d, %d/%d, nano:[%d/%d]%n",
zdt.getYear(), ts.getYear() + 1900,
zdt.getMonthValue(), ts.getMonth() + 1,
zdt.getDayOfMonth(), ts.getDate(),
zdt.getHour(), ts.getHours(),
zdt.getMinute(), ts.getMinutes(),
zdt.getSecond(), ts.getSeconds(),
zdt.getNano(), ts.getNanos());
}
private void addTypeAdaptersForDate(String datePattern, int dateStyle, int timeStyle, List<TypeAdapterFactory> factories) {
DefaultDateTypeAdapter dateTypeAdapter;
if (datePattern != null && !"".equals(datePattern.trim())) {
dateTypeAdapter = new DefaultDateTypeAdapter(datePattern);
} else if (dateStyle != 2 && timeStyle != 2) {
dateTypeAdapter = new DefaultDateTypeAdapter(dateStyle, timeStyle);
} else {
return;
}
factories.add(TreeTypeAdapter.newFactory(TypeToken.get(Date.class), dateTypeAdapter));
factories.add(TreeTypeAdapter.newFactory(TypeToken.get(Timestamp.class), dateTypeAdapter));
factories.add(TreeTypeAdapter.newFactory(TypeToken.get(java.sql.Date.class), dateTypeAdapter));
}
@Override
public void loadDependentObjectsFor(List ownerObjects, List<Timestamp> businessDates, Timestamp loadEndTime, CacheLoaderMonitor monitor)
{
if (ownerObjects != null && !ownerObjects.isEmpty())
{
CacheLoaderContext context = new CacheLoaderContext(this, businessDates);
context.setQualifiedLoadContext(new QualifiedByOwnerObjectListLoadContext(ownerObjects));
context.execute(monitor);
}
}
protected boolean insertToDerbyTable(Connection conn, int oid, int cid, int sid, int qty,
String status, Timestamp time, BigDecimal bid) throws SQLException{
PreparedStatement stmt = getStmt(conn, insert);
int tid = getMyTid();
int count = -1;
Log.getLogWriter().info("Insert into derby, myTid is " + tid);
try {
count = insertToTable(stmt, oid, cid, sid, qty, status, time, bid, tid);
Log.getLogWriter().info("derby inserts " + count + " record");
} catch (SQLException se) {
if (!SQLHelper.checkDerbyException(conn, se)) return false; //for retry
else throw se;
}
return true;
}
/**
* Update the tps_service table with latest tps values.
*
*/
public static void updateTpsService(final int envId, int componentId, float tpsVaule, float latencyValue){
Session session = HibernateConfig.getSessionFactory().getCurrentSession();
Transaction txn = session.beginTransaction();
Query query = session.createQuery(HQLConstants.UPDATE_TPS_SERVICE_DETAILS);
query.setFloat("tpsVaule", tpsVaule);
query.setFloat("latencyValue", latencyValue);
query.setTimestamp("lastUpdateDate", new java.sql.Timestamp(System.currentTimeMillis()));
query.setLong("compId", componentId);
query.setLong("environmentId", envId);
query.executeUpdate();
txn.commit();
}
@Override
protected StaffAddressOutVO handleAddStaffAddress(
AuthenticationVO auth, StaffAddressInVO newStaffAddress) throws Exception {
checkStaffAddressInput(newStaffAddress);
StaffAddressDao addressDao = this.getStaffAddressDao();
StaffAddress address = addressDao.staffAddressInVOToEntity(newStaffAddress);
Timestamp now = new Timestamp(System.currentTimeMillis());
User user = CoreUtil.getUser();
CoreUtil.modifyVersion(address, now, user);
address = addressDao.create(address);
StaffAddressOutVO result = addressDao.toStaffAddressOutVO(address);
logSystemMessage(address.getStaff(), result.getStaff(), now, user, SystemMessageCodes.STAFF_ADDRESS_CREATED, result, null, this.getJournalEntryDao());
return result;
}
public void testRetrieveOneRowUsingTimestampInOperation()
throws ParseException
{
Operation op = AllTypesFinder.timestampValue().eq(new Timestamp(timestampFormat.parse("2007-01-01 01:01:01.999").getTime()));
String sql = "select " + getAllTypesColumns() + " from public.ALL_TYPES where TIMESTAMP_COL = '01-JAN-07 01:01:01.999'";
validateMithraResult(op, sql);
}
public void setValidatedDate(DateTime validatedDate) {
if ( validatedDate != null ) {
this.validatedDate = new Timestamp(validatedDate.getMillis());
} else {
this.validatedDate = null;
}
}
private void validateManyTypes(String tableName) throws Exception {
KuduTable kuduTable = harness.getClient().openTable(tableName);
Schema schema = kuduTable.getSchema();
assertEquals(Type.STRING, schema.getColumn("first").getType());
assertEquals(Type.BOOL, schema.getColumn("second").getType());
assertEquals(Type.BINARY, schema.getColumn("third").getType());
assertEquals(Type.INT8, schema.getColumn("fourth").getType());
assertEquals(Type.INT16, schema.getColumn("fifth").getType());
assertEquals(Type.INT32, schema.getColumn("sixth").getType());
assertEquals(Type.INT64, schema.getColumn("seventh").getType());
assertEquals(Type.FLOAT, schema.getColumn("eighth").getType());
assertEquals(Type.DOUBLE, schema.getColumn("ninth").getType());
assertEquals(Type.UNIXTIME_MICROS, schema.getColumn("tenth").getType());
KuduScanner scanner = harness.getClient().newScannerBuilder(kuduTable).build();
List<RowResult> rows = new ArrayList<>();
scanner.forEach(rows::add);
assertEquals(1, rows.size());
assertEquals("f", rows.get(0).getString(0));
assertEquals(false, rows.get(0).getBoolean(1));
assertEquals(ByteBuffer.wrap("bbbb".getBytes()), rows.get(0).getBinary(2));
assertEquals(12, rows.get(0).getByte(3));
assertEquals(34, rows.get(0).getShort(4));
assertEquals(56, rows.get(0).getInt(5));
assertEquals(78, rows.get(0).getLong(6));
assertEquals(3.14, rows.get(0).getFloat(7), 0.01);
assertEquals(1.2345, rows.get(0).getDouble(8), 0.0001);
assertEquals(Timestamp.valueOf("2020-04-15 12:34:56.123"), rows.get(0).getTimestamp(9));
}
protected Timestamp getAnotherObject() {
return new Timestamp(0L);
}
public Object getObjectFromData(MithraDataObject data, Timestamp[] asOfDates)
{
throw new RuntimeException("This cache does not support dated objects!");
}
@Override
public Class<Timestamp> timestampType() {
return Timestamp.class;
}
public String parmType(Timestamp value)
{
return "java.sql.Timestamp parameter";
}
private void appendColumn(List<Object> values, Page page, int position, int channel)
{
Block block = page.getBlock(channel);
Type type = columnTypes.get(channel);
if (block.isNull(position)) {
values.add(null);
}
else if (BOOLEAN.equals(type)) {
values.add(type.getBoolean(block, position));
}
else if (BIGINT.equals(type)) {
values.add(type.getLong(block, position));
}
else if (INTEGER.equals(type)) {
values.add(toIntExact(type.getLong(block, position)));
}
else if (SMALLINT.equals(type)) {
values.add(Shorts.checkedCast(type.getLong(block, position)));
}
else if (TINYINT.equals(type)) {
values.add(SignedBytes.checkedCast(type.getLong(block, position)));
}
else if (DOUBLE.equals(type)) {
values.add(type.getDouble(block, position));
}
else if (REAL.equals(type)) {
values.add(intBitsToFloat(toIntExact(type.getLong(block, position))));
}
else if (DATE.equals(type)) {
values.add(toCassandraDate.apply(type.getLong(block, position)));
}
else if (TIMESTAMP.equals(type)) {
values.add(new Timestamp(type.getLong(block, position)));
}
else if (isVarcharType(type)) {
values.add(type.getSlice(block, position).toStringUtf8());
}
else if (VARBINARY.equals(type)) {
values.add(type.getSlice(block, position).toByteBuffer());
}
else {
throw new PrestoException(NOT_SUPPORTED, "Unsupported column type: " + type.getDisplayName());
}
}
public Timestamp getTimestamp(int columnIndex) throws SQLException {
return this.currentResultSet.getTimestamp(columnIndex);
}
/**
* Tests that with the output to file option set, the scrutiny tool outputs invalid rows to file
*/
@Test public void testOutputInvalidRowsToFile() throws Exception {
insertOneValid_OneBadVal_OneMissingTarget();
String[]
argValues =
getArgValues(schemaName, dataTableName, indexTableName, 10L, SourceTable.DATA_TABLE_SOURCE, true, OutputFormat.FILE, null);
runScrutiny(argValues);
// check the output files
Path outputPath = CsvBulkImportUtil.getOutputPath(new Path(outputDir), dataTableFullName);
DistributedFileSystem fs = getUtility().getDFSCluster().getFileSystem();
List<Path> paths = Lists.newArrayList();
Path firstPart = null;
for (FileStatus outputFile : fs.listStatus(outputPath)) {
if (outputFile.getPath().getName().startsWith("part")) {
if (firstPart == null) {
firstPart = outputFile.getPath();
} else {
paths.add(outputFile.getPath());
}
}
}
if (dataTableDdl.contains("SALT_BUCKETS")) {
fs.concat(firstPart, paths.toArray(new Path[0]));
}
Path outputFilePath = firstPart;
assertTrue(fs.exists(outputFilePath));
FSDataInputStream fsDataInputStream = fs.open(outputFilePath);
BufferedReader reader = new BufferedReader(new InputStreamReader(fsDataInputStream));
TreeSet<String> lines = Sets.newTreeSet();
try {
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} finally {
IOUtils.closeQuietly(reader);
IOUtils.closeQuietly(fsDataInputStream);
}
Iterator<String> lineIterator = lines.iterator();
assertEquals("[2, name-2, " + new Timestamp(testTime).toString() + ", 95123]\t[2, name-2, "
+ new Timestamp(testTime).toString() + ", 9999]", lineIterator.next());
assertEquals("[3, name-3, " + new Timestamp(testTime).toString() + ", 95123]\tTarget row not found",
lineIterator.next());
}
/**
* {@inheritDoc}
*/
@Override
public MdClassActionsRecord value6(Timestamp value) {
setCreated(value);
return this;
}
@Test(dataProvider = "rowsetUsingDataTypes")
public void commonCachedRowSetTest0040(CachedRowSet rs, JDBCType type) throws Exception {
rs.beforeFirst();
assertTrue(rs.next());
switch (type) {
case INTEGER:
assertFalse(rs.columnUpdated(1));
rs.updateInt(1, Integer.MIN_VALUE);
assertTrue(rs.columnUpdated(1));
break;
case CHAR:
assertFalse(rs.columnUpdated(2));
rs.updateString(2, "foo");
assertTrue(rs.columnUpdated(2));
break;
case VARCHAR:
assertFalse(rs.columnUpdated(3));
rs.updateString(3, "foo");
assertTrue(rs.columnUpdated(3));
break;
case BIGINT:
assertFalse(rs.columnUpdated(4));
rs.updateLong(4, Long.MIN_VALUE);
assertTrue(rs.columnUpdated(4));
break;
case BOOLEAN:
assertFalse(rs.columnUpdated(5));
rs.updateBoolean(5, false);
assertTrue(rs.columnUpdated(5));
break;
case SMALLINT:
assertFalse(rs.columnUpdated(6));
rs.updateShort(6, Short.MIN_VALUE);
assertTrue(rs.columnUpdated(6));
break;
case DOUBLE:
assertFalse(rs.columnUpdated(7));
rs.updateDouble(7, Double.MIN_VALUE);
assertTrue(rs.columnUpdated(7));
break;
case DECIMAL:
assertFalse(rs.columnUpdated(8));
rs.updateBigDecimal(8, BigDecimal.TEN);
assertTrue(rs.columnUpdated(8));
break;
case REAL:
assertFalse(rs.columnUpdated(9));
rs.updateFloat(9, Float.MIN_VALUE);
assertTrue(rs.columnUpdated(9));
break;
case TINYINT:
assertFalse(rs.columnUpdated(10));
rs.updateByte(10, Byte.MIN_VALUE);
assertTrue(rs.columnUpdated(10));
break;
case DATE:
assertFalse(rs.columnUpdated(11));
rs.updateDate(11, Date.valueOf(LocalDate.now()));
assertTrue(rs.columnUpdated(11));
break;
case TIME:
assertFalse(rs.columnUpdated(12));
rs.updateTime(12, Time.valueOf(LocalTime.now()));
assertTrue(rs.columnUpdated(12));
break;
case TIMESTAMP:
assertFalse(rs.columnUpdated(13));
rs.updateTimestamp(13, Timestamp.valueOf(LocalDateTime.now()));
assertTrue(rs.columnUpdated(13));
break;
case VARBINARY:
assertFalse(rs.columnUpdated(14));
rs.updateBytes(14, new byte[1]);
assertTrue(rs.columnUpdated(14));
break;
case ARRAY:
assertFalse(rs.columnUpdated(15));
rs.updateArray(15, new StubArray("VARCHAR", new Object[10]));
assertTrue(rs.columnUpdated(15));
break;
case REF:
assertFalse(rs.columnUpdated(16));
rs.updateRef(16, new StubRef("INTEGER", query));
assertTrue(rs.columnUpdated(16));
break;
case FLOAT:
assertFalse(rs.columnUpdated(17));
rs.updateDouble(17, Double.MIN_NORMAL);
assertTrue(rs.columnUpdated(17));
}
}
@PrePersist
public void onCreate() {
updatedAt = new Timestamp(System.currentTimeMillis());
createdAt = updatedAt;
}
@Override
public void updateTimestamp(int columnIndex, Timestamp x)
throws SQLException {
rs.updateTimestamp(columnIndex, x);
}
public TamsMithraAccountArbsClassification(Timestamp businessDate)
{
super(businessDate);
}