下面列出了java.sql.Timestamp#getNanos ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public Timestamp getOrAddToCache(Timestamp newValue, boolean hard, boolean offHeap)
{
if (newValue == null || newValue instanceof CachedImmutableTimestamp || newValue == NullDataTimestamp.getInstance())
{
return newValue;
}
if (offHeap)
{
if ((newValue.getNanos() % 1000000) != 0)
{
newValue = new ImmutableTimestamp(newValue.getTime());
}
return tempPool.getIfAbsentPut(newValue);
}
return (Timestamp) weakPool.getIfAbsentPut(newValue, hard);
}
private void myAssert(RecordEntry record, DsColumn[] columns) {
if (record == null || columns == null) {
Assert.fail();
}
TupleRecordData recordData = (TupleRecordData) record.getRecordData();
Assert.assertEquals(recordData.getField("c1"), columns[0].getAfterValue());
Assert.assertEquals(recordData.getField("c2"), Long.valueOf(columns[1].getAfterValue()));
Assert.assertEquals(recordData.getField("c3"), Double.valueOf(columns[2].getAfterValue()));
Assert.assertEquals(recordData.getField("c4"), Boolean.valueOf(columns[3].getAfterValue()));
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Timestamp ts = Timestamp.valueOf(columns[4].getAfterValue());
long timeStamp = ts.getTime() * 1000 + (ts.getNanos() % 1000000 / 1000);
Assert.assertEquals(recordData.getField("c5"), timeStamp);
Assert.assertEquals(recordData.getField("c6"), new BigDecimal(columns[5].getAfterValue()));
}
/**
* Returns the number of micros since epoch from java.sql.Timestamp.
*/
public static long fromJavaTimestamp(Timestamp t) {
if (t != null) {
return t.getTime() * 1000L + ((long) t.getNanos() / 1000) % 1000L;
} else {
return 0L;
}
}
public static long formatLong(Timestamp timestamp) throws StandardException {
int nanos = timestamp.getNanos();
// 1. Round milliseconds down to the nearest second, e.g. -1001 ms becomes -2000 ms.
// 2. Shift 3 decimal places to the left, so there's a total of 6 zeroes in the rightmost digits.
// 3. Divide nanoseconds by 1000 to produce microseconds, and add that to the final value.
long micros = (timestamp.getTime() - (nanos / 1000000)) * 1000 + (nanos / 1000);
return micros;
}
private static boolean isEqual(LocalDateTime ldt, Timestamp ts) {
ZonedDateTime zdt = ZonedDateTime.of(ldt, ZoneId.systemDefault());
return 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 static boolean isEqual(LocalDateTime ldt, Timestamp ts) {
ZonedDateTime zdt = ZonedDateTime.of(ldt, ZoneId.systemDefault());
return 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();
}
public static SpearalDateTime forSQLTimestamp(Timestamp timestamp) {
GregorianCalendar calendar = new GregorianCalendar(UTC, Locale.US);
calendar.setTimeInMillis(timestamp.getTime());
return new SpearalDateTime(
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH) + 1,
calendar.get(Calendar.DATE),
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
calendar.get(Calendar.SECOND),
timestamp.getNanos(),
true, true
);
}
/**
* SCIPIO: Converts a timestamp into a Date
*
* @param timestamp a Timestamp
* @return The corresponding Date
*/
public static java.util.Date toDate(Timestamp timestamp) {
if (timestamp == null) {
return null;
}
long milliseconds = timestamp.getTime() + (timestamp.getNanos() / 1000000);
return new Date(milliseconds);
}
/**
* Helper to set {@link WebSocketMessageDTO#timestamp} and {@link WebSocketMessageDTO#dateTime}.
*
* @param ts
*/
public void setTime(Timestamp ts) {
timestamp = ts.getTime() + (ts.getNanos() / 1000000000);
synchronized (dateFormatter) {
dateTime = dateFormatter.format(ts);
}
String nanos = Integer.toString(ts.getNanos()).replaceAll("0+$", "");
if (nanos.length() == 0) {
nanos = "0";
}
dateTime = dateTime.replaceFirst("([0-9]+:[0-9]+:[0-9]+)", "$1." + nanos);
}
private static boolean isEqual(LocalDateTime ldt, Timestamp ts) {
ZonedDateTime zdt = ZonedDateTime.of(ldt, ZoneId.systemDefault());
return 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();
}
@Override
public Long getInteger( Object object ) throws KettleValueException {
Timestamp timestamp = getTimestamp( object );
if ( timestamp == null ) {
return null;
}
long milliseconds = timestamp.getTime();
if ( Const.KETTLE_TIMESTAMP_NUMBER_CONVERSION_MODE_NANOSECONDS.equalsIgnoreCase( conversionMode ) ) {
long seconds = TimeUnit.SECONDS.convert( milliseconds, TimeUnit.MILLISECONDS );
return seconds * 1000000000L + timestamp.getNanos();
} else {
return milliseconds;
}
}
private static void processTimestampToken(TimeZone tz, StringBuilder newSql, String token, boolean serverSupportsFractionalSecond,
boolean serverTruncatesFractionalSecond, ExceptionInterceptor exceptionInterceptor) throws SQLException {
int startPos = token.indexOf('\'') + 1;
int endPos = token.lastIndexOf('\''); // no }
if ((startPos == -1) || (endPos == -1)) {
newSql.append(token); // it's just part of the query, push possible syntax errors onto server's shoulders
} else {
String argument = token.substring(startPos, endPos);
try {
Timestamp ts = Timestamp.valueOf(argument);
ts = TimeUtil.adjustTimestampNanosPrecision(ts, 6, !serverTruncatesFractionalSecond);
SimpleDateFormat tsdf = TimeUtil.getSimpleDateFormat(null, "''yyyy-MM-dd HH:mm:ss", null, tz);
newSql.append(tsdf.format(ts));
if (serverSupportsFractionalSecond && ts.getNanos() > 0) {
newSql.append('.');
newSql.append(TimeUtil.formatNanos(ts.getNanos(), 6));
}
newSql.append('\'');
} catch (IllegalArgumentException illegalArgumentException) {
SQLException sqlEx = SQLError.createSQLException(Messages.getString("EscapeProcessor.2", new Object[] { argument }),
MysqlErrorNumbers.SQL_STATE_SYNTAX_ERROR, exceptionInterceptor);
sqlEx.initCause(illegalArgumentException);
throw sqlEx;
}
}
}
/**
* Make sure the Timestamp will return getTime() accurate to the millisecond
* (if possible) and truncate away nanoseconds.
*/
private Date timestampToDate(Timestamp ts) {
long millis = ts.getTime();
int nanos = ts.getNanos();
return new Date(millis / 1000 * 1000 + nanos / 1000000);
}
public static long formatLong(Timestamp timestamp) throws StandardException {
long millis = SQLTimestamp.checkV2Bounds(timestamp);
long micros = timestamp.getNanos() / NANOS_TO_MICROS;
return millis * MICROS_TO_SECOND + micros;
}
public static void main(String[] args) throws Throwable {
int N = 10000;
long t1970 = new java.util.Date(70, 0, 01).getTime();
Random r = new Random();
for (int i = 0; i < N; i++) {
int days = r.nextInt(50) * 365 + r.nextInt(365);
long secs = t1970 + days * 86400 + r.nextInt(86400);
int nanos = r.nextInt(NANOS_PER_SECOND);
int nanos_ms = nanos / 1000000 * 1000000; // millis precision
long millis = secs * 1000 + r.nextInt(1000);
LocalDateTime ldt = LocalDateTime.ofEpochSecond(secs, nanos, ZoneOffset.UTC);
LocalDateTime ldt_ms = LocalDateTime.ofEpochSecond(secs, nanos_ms, ZoneOffset.UTC);
Instant inst = Instant.ofEpochSecond(secs, nanos);
Instant inst_ms = Instant.ofEpochSecond(secs, nanos_ms);
//System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
/////////// Timestamp ////////////////////////////////
Timestamp ta = new Timestamp(millis);
ta.setNanos(nanos);
if (!isEqual(ta.toLocalDateTime(), ta)) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
print(ta.toLocalDateTime(), ta);
throw new RuntimeException("FAILED: j.s.ts -> ldt");
}
if (!isEqual(ldt, Timestamp.valueOf(ldt))) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
print(ldt, Timestamp.valueOf(ldt));
throw new RuntimeException("FAILED: ldt -> j.s.ts");
}
Instant inst0 = ta.toInstant();
if (ta.getTime() != inst0.toEpochMilli() ||
ta.getNanos() != inst0.getNano() ||
!ta.equals(Timestamp.from(inst0))) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: j.s.ts -> instant -> j.s.ts");
}
inst = Instant.ofEpochSecond(secs, nanos);
Timestamp ta0 = Timestamp.from(inst);
if (ta0.getTime() != inst.toEpochMilli() ||
ta0.getNanos() != inst.getNano() ||
!inst.equals(ta0.toInstant())) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: instant -> timestamp -> instant");
}
////////// java.sql.Date /////////////////////////////
// j.s.d/t uses j.u.d.equals() !!!!!!!!
java.sql.Date jsd = new java.sql.Date(millis);
if (!isEqual(jsd.toLocalDate(), jsd)) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
print(jsd.toLocalDate(), jsd);
throw new RuntimeException("FAILED: j.s.d -> ld");
}
LocalDate ld = ldt.toLocalDate();
if (!isEqual(ld, java.sql.Date.valueOf(ld))) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
print(ld, java.sql.Date.valueOf(ld));
throw new RuntimeException("FAILED: ld -> j.s.d");
}
////////// java.sql.Time /////////////////////////////
java.sql.Time jst = new java.sql.Time(millis);
if (!isEqual(jst.toLocalTime(), jst)) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
print(jst.toLocalTime(), jst);
throw new RuntimeException("FAILED: j.s.t -> lt");
}
// millis precision
LocalTime lt = ldt_ms.toLocalTime();
if (!isEqual(lt, java.sql.Time.valueOf(lt))) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
print(lt, java.sql.Time.valueOf(lt));
throw new RuntimeException("FAILED: lt -> j.s.t");
}
}
System.out.println("Passed!");
}
public static void main(String[] args) throws Throwable {
int N = 10000;
long t1970 = new java.util.Date(70, 0, 01).getTime();
Random r = new Random();
for (int i = 0; i < N; i++) {
int days = r.nextInt(50) * 365 + r.nextInt(365);
long secs = t1970 + days * 86400 + r.nextInt(86400);
int nanos = r.nextInt(NANOS_PER_SECOND);
int nanos_ms = nanos / 1000000 * 1000000; // millis precision
long millis = secs * 1000 + r.nextInt(1000);
LocalDateTime ldt = LocalDateTime.ofEpochSecond(secs, nanos, ZoneOffset.UTC);
LocalDateTime ldt_ms = LocalDateTime.ofEpochSecond(secs, nanos_ms, ZoneOffset.UTC);
Instant inst = Instant.ofEpochSecond(secs, nanos);
Instant inst_ms = Instant.ofEpochSecond(secs, nanos_ms);
//System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
/////////// Timestamp ////////////////////////////////
Timestamp ta = new Timestamp(millis);
ta.setNanos(nanos);
if (!isEqual(ta.toLocalDateTime(), ta)) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
print(ta.toLocalDateTime(), ta);
throw new RuntimeException("FAILED: j.s.ts -> ldt");
}
if (!isEqual(ldt, Timestamp.valueOf(ldt))) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
print(ldt, Timestamp.valueOf(ldt));
throw new RuntimeException("FAILED: ldt -> j.s.ts");
}
Instant inst0 = ta.toInstant();
if (ta.getTime() != inst0.toEpochMilli() ||
ta.getNanos() != inst0.getNano() ||
!ta.equals(Timestamp.from(inst0))) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: j.s.ts -> instant -> j.s.ts");
}
inst = Instant.ofEpochSecond(secs, nanos);
Timestamp ta0 = Timestamp.from(inst);
if (ta0.getTime() != inst.toEpochMilli() ||
ta0.getNanos() != inst.getNano() ||
!inst.equals(ta0.toInstant())) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
throw new RuntimeException("FAILED: instant -> timestamp -> instant");
}
////////// java.sql.Date /////////////////////////////
// j.s.d/t uses j.u.d.equals() !!!!!!!!
java.sql.Date jsd = new java.sql.Date(millis);
if (!isEqual(jsd.toLocalDate(), jsd)) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
print(jsd.toLocalDate(), jsd);
throw new RuntimeException("FAILED: j.s.d -> ld");
}
LocalDate ld = ldt.toLocalDate();
if (!isEqual(ld, java.sql.Date.valueOf(ld))) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
print(ld, java.sql.Date.valueOf(ld));
throw new RuntimeException("FAILED: ld -> j.s.d");
}
////////// java.sql.Time /////////////////////////////
java.sql.Time jst = new java.sql.Time(millis);
if (!isEqual(jst.toLocalTime(), jst)) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
print(jst.toLocalTime(), jst);
throw new RuntimeException("FAILED: j.s.t -> lt");
}
// millis precision
LocalTime lt = ldt_ms.toLocalTime();
if (!isEqual(lt, java.sql.Time.valueOf(lt))) {
System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt);
print(lt, java.sql.Time.valueOf(lt));
throw new RuntimeException("FAILED: lt -> j.s.t");
}
}
System.out.println("Passed!");
}
public int compare(DataValueDescriptor other)
throws StandardException
{
/* Use compare method from dominant type, negating result
* to reflect flipping of sides.
*/
if (typePrecedence() < other.typePrecedence())
{
return -Integer.signum(other.compare(this));
}
boolean thisNull, otherNull;
thisNull = this.isNull();
otherNull = other.isNull();
/*
* thisNull otherNull return
* T T 0 (this == other)
* F T -1 (this < other)
* T F 1 (this > other)
*/
if (thisNull || otherNull)
{
if (!thisNull) // otherNull must be true
return -1;
if (!otherNull) // thisNull must be true
return 1;
return 0;
}
/*
Neither are null compare them
*/
int comparison;
/* get the comparison date values */
int otherEncodedDate = 0;
int otherEncodedTime = 0;
int otherNanos = 0;
/* if the argument is another SQLTimestamp, look up the value
*/
if (other instanceof SQLTimestamp)
{
SQLTimestamp st = (SQLTimestamp)other;
otherEncodedDate= st.encodedDate;
otherEncodedTime= st.encodedTime;
otherNanos= st.nanos;
}
else
{
/* O.K. have to do it the hard way and calculate the numeric value
* from the value
*/
GregorianCalendar cal = ClientSharedData.getDefaultCleanCalendar();
Timestamp otherts = other.getTimestamp(cal);
otherEncodedDate = SQLTimestamp.computeEncodedDate(otherts, cal);
otherEncodedTime = SQLTimestamp.computeEncodedTime(otherts, cal);
otherNanos = otherts.getNanos();
}
if (encodedDate < otherEncodedDate)
comparison = -1;
else if (encodedDate > otherEncodedDate)
comparison = 1;
else if (encodedTime < otherEncodedTime)
comparison = -1;
else if (encodedTime > otherEncodedTime)
comparison = 1;
else if (nanos < otherNanos)
comparison = -1;
else if (nanos > otherNanos)
comparison = 1;
else
comparison = 0;
return comparison;
}
/**
* Compares two Timestamps with the expected result.
*
* @param ts1 the first Timestamp
* @param ts2 the second Timestamp
* @param expect the expected relation between ts1 and ts2; 0 if
* ts1 equals to ts2, or 1 if ts1 is after ts2, or -1 if ts1 is
* before ts2.
*/
private void compareTimestamps(Timestamp ts1, Timestamp ts2, int expected) {
boolean expectedResult = expected > 0;
boolean result = ts1.after(ts2);
if (result != expectedResult) {
errln("ts1.after(ts2) returned " + result
+ ". (ts1=" + ts1 + ", ts2=" + ts2 + ")");
}
expectedResult = expected < 0;
result = ts1.before(ts2);
if (result != expectedResult) {
errln("ts1.before(ts2) returned " + result
+ ". (ts1=" + ts1 + ", ts2=" + ts2 + ")");
}
expectedResult = expected == 0;
result = ts1.equals(ts2);
if (result != expectedResult) {
errln("ts1.equals(ts2) returned " + result
+ ". (ts1=" + ts1 + ", ts2=" + ts2 + ")");
}
int x = ts1.compareTo(ts2);
int y = (x > 0) ? 1 : (x < 0) ? -1 : 0;
if (y != expected) {
errln("ts1.compareTo(ts2) returned " + x + ", expected "
+ relation(expected, "") + "0"
+ ". (ts1=" + ts1 + ", ts2=" + ts2 + ")");
}
long t1 = ts1.getTime();
long t2 = ts2.getTime();
int z = (t1 > t2) ? 1 : (t1 < t2) ? -1 : 0;
if (z == 0) {
int n1 = ts1.getNanos();
int n2 = ts2.getNanos();
z = (n1 > n2) ? 1 : (n1 < n2) ? -1 : 0;
}
if (z != expected) {
errln("ts1.getTime() " + relation(z, "==") + " ts2.getTime(), expected "
+ relation(expected, "==")
+ ". (ts1=" + ts1 + ", ts2=" + ts2 + ")");
}
}
/**
@see java.sql.ResultSet#next
@exception SQLException If database access error occurs.
*/
public boolean next() throws SQLException
{
if (! gotFile)
{
gotFile = true;
try
{
inputFileStreamReader = new InputStreamReader(new FileInputStream(inputFileName));
bufferedReader = new BufferedReader(inputFileStreamReader, 32*1024);
}
catch (FileNotFoundException ex)
{
throw new SQLException(ex.getMessage());
}
hashTable = new Hashtable();
}
while (true)
{
try
{
line = bufferedReader.readLine();
}
catch (java.io.IOException ioe)
{
throw new SQLException(ioe.getMessage());
}
if (line == null)
{
return false;
}
gmtIndex = line.indexOf(GMT_STRING);
threadIndex = line.indexOf(BEGIN_THREAD_STRING);
xidIndex = line.indexOf(BEGIN_XID_STRING);
lccidIndex = line.indexOf(BEGIN_XID_STRING, xidIndex + 1);
if (gmtIndex != -1 && threadIndex != -1)
{
/* Build a row */
String[] newRow = new String[6];
for (int index = 1;
index <= 5;
index++)
{
newRow[index - 1] = setupColumn(index);
}
/* NOTE: We need to use the LCCID as the key
*/
Object previousRow = hashTable.put(newRow[3],
newRow);
if (previousRow == null)
{
continue;
}
currentRow = (String[]) previousRow;
/* Figure out the duration. */
Timestamp endTs = Timestamp.valueOf(newRow[0]);
long end = endTs.getTime() + endTs.getNanos() / 1000000;
Timestamp startTs = Timestamp.valueOf(currentRow[0]);
long start = startTs.getTime() + startTs.getNanos() / 1000000;
currentRow[5] = Long.toString(end - start);
return true;
}
}
}
@Override
protected void prepareReadFileWithTypes(String file, int rowSize) throws IOException {
// NOTE: orc has field name information, so name should be same as orc
TypeDescription schema =
TypeDescription.fromString(
"struct<" +
"f0:float," +
"f1:double," +
"f2:timestamp," +
"f3:tinyint," +
"f4:smallint" +
">");
org.apache.hadoop.fs.Path filePath = new org.apache.hadoop.fs.Path(file);
Configuration conf = new Configuration();
Writer writer =
OrcFile.createWriter(filePath,
OrcFile.writerOptions(conf).setSchema(schema));
VectorizedRowBatch batch = schema.createRowBatch(rowSize);
DoubleColumnVector col0 = (DoubleColumnVector) batch.cols[0];
DoubleColumnVector col1 = (DoubleColumnVector) batch.cols[1];
TimestampColumnVector col2 = (TimestampColumnVector) batch.cols[2];
LongColumnVector col3 = (LongColumnVector) batch.cols[3];
LongColumnVector col4 = (LongColumnVector) batch.cols[4];
col0.noNulls = false;
col1.noNulls = false;
col2.noNulls = false;
col3.noNulls = false;
col4.noNulls = false;
for (int i = 0; i < rowSize - 1; i++) {
col0.vector[i] = i;
col1.vector[i] = i;
Timestamp timestamp = toTimestamp(i);
col2.time[i] = timestamp.getTime();
col2.nanos[i] = timestamp.getNanos();
col3.vector[i] = i;
col4.vector[i] = i;
}
col0.isNull[rowSize - 1] = true;
col1.isNull[rowSize - 1] = true;
col2.isNull[rowSize - 1] = true;
col3.isNull[rowSize - 1] = true;
col4.isNull[rowSize - 1] = true;
batch.size = rowSize;
writer.addRowBatch(batch);
batch.reset();
writer.close();
}