コード例 #1
0
ファイル: HproseWriter.java プロジェクト: JesonRen/hprose
 public void writeDate(Timestamp time) throws IOException {
   ref.put(time, lastref++);
   Calendar calendar = Calendar.getInstance(HproseHelper.DefaultTZ);
   calendar.setTime(time);
   writeDateOfCalendar(calendar);
   writeTimeOfCalendar(calendar, false, true);
   int nanosecond = time.getNanos();
   if (nanosecond > 0) {
     stream.write(HproseTags.TagPoint);
     stream.write((byte) ('0' + (nanosecond / 100000000 % 10)));
     stream.write((byte) ('0' + (nanosecond / 10000000 % 10)));
     stream.write((byte) ('0' + (nanosecond / 1000000 % 10)));
     if (nanosecond % 1000000 > 0) {
       stream.write((byte) ('0' + (nanosecond / 100000 % 10)));
       stream.write((byte) ('0' + (nanosecond / 10000 % 10)));
       stream.write((byte) ('0' + (nanosecond / 1000 % 10)));
       if (nanosecond % 1000 > 0) {
         stream.write((byte) ('0' + (nanosecond / 100 % 10)));
         stream.write((byte) ('0' + (nanosecond / 10 % 10)));
         stream.write((byte) ('0' + (nanosecond % 10)));
       }
     }
   }
   stream.write(HproseTags.TagSemicolon);
 }
コード例 #2
0
  @Override
  public Instant fromNonNullValue(Timestamp value) {

    Instant instant = Instant.ofEpochMilli(value.getTime());
    instant = instant.with(ChronoField.NANO_OF_SECOND, value.getNanos());

    return instant;
  }
コード例 #3
0
  /**
   * Adds the number of months to the date. If the resulting month's number of days is less than the
   * original's day-of-month, the resulting day-of-months gets adjusted accordingly: <br>
   * 30.04.2007 - 2 months = 28.02.2007
   *
   * @param refDate the original date
   * @param nrOfMonthsToAdd the number of months to add
   * @return the new timestamp
   */
  public static Timestamp addMonths(Timestamp refDate, int nrOfMonthsToAdd) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(refDate);
    calendar.add(Calendar.MONTH, nrOfMonthsToAdd);

    Timestamp resultDate = new Timestamp(calendar.getTimeInMillis());
    resultDate.setNanos(refDate.getNanos());
    return resultDate;
  }
コード例 #4
0
 /** @return nanoseconds in this TimestampWritable */
 public int getNanos() {
   if (!timestampEmpty) {
     return timestamp.getNanos();
   } else if (!bytesEmpty) {
     return hasDecimalOrSecondVInt() ? TimestampWritable.getNanos(currentBytes, offset + 4) : 0;
   } else {
     throw new IllegalStateException("Both timestamp and bytes are empty");
   }
 }
コード例 #5
0
ファイル: TimestampValue.java プロジェクト: xieh/java-q
  /**
   * @param value Value
   * @return Timestamp
   */
  public static TimestampValue from(final Timestamp value) {
    if (value == null) {
      return new TimestampValue(value, TypeTimestamp.get());
    }

    // java does wired things with time zones (so we must correct this here)
    final long offset = TimeZone.getDefault().getOffset(value.getTime());
    final Timestamp timestamp = new Timestamp(value.getTime() - offset);
    timestamp.setNanos(value.getNanos());
    return new TimestampValue(timestamp, TypeTimestamp.get());
  }
コード例 #6
0
  public void addValue(Object object) {
    if (!(object instanceof Timestamp)) {
      throw new IllegalArgumentException();
    }

    Timestamp value = (Timestamp) object;
    long time = value.getTime();
    int nanos = value.getNanos();
    timeStore.add(time);
    nanoStore.add(nanos);
  }
コード例 #7
0
 /** @return double representation of the timestamp, accurate to nanoseconds */
 public double getDouble() {
   double seconds, nanos;
   if (bytesEmpty) {
     seconds = millisToSeconds(timestamp.getTime());
     nanos = timestamp.getNanos();
   } else {
     seconds = getSeconds();
     nanos = getNanos();
   }
   return seconds + ((double) nanos) / 1000000000;
 }
コード例 #8
0
 public Date deepCopyNotNull(Date value) {
   if (value instanceof Timestamp) {
     Timestamp orig = (Timestamp) value;
     Timestamp ts = new Timestamp(orig.getTime());
     ts.setNanos(orig.getNanos());
     return ts;
   } else {
     Date orig = value;
     return new Date(orig.getTime());
   }
 }
コード例 #9
0
 /**
  * Convert the timestamp using the specified calendar.
  *
  * @param x the time
  * @param calendar the calendar
  * @return the timestamp
  */
 public static ValueTimestamp convertTimestamp(Timestamp x, Calendar calendar) {
   if (calendar == null) {
     throw DbException.getInvalidValueException("calendar", null);
   }
   Calendar cal = (Calendar) calendar.clone();
   cal.setTimeInMillis(x.getTime());
   long dateValue = dateValueFromCalendar(cal);
   long nanos = nanosFromCalendar(cal);
   nanos += x.getNanos() % 1000000;
   return ValueTimestamp.fromDateValueAndNanos(dateValue, nanos);
 }
コード例 #10
0
ファイル: DateTimeConverter.java プロジェクト: zycgit/hasor
 /**
  * Convert the input object into a Date object of the specified type.
  *
  * <p>This method handles conversions between the following types:
  *
  * <ul>
  *   <li><code>java.util.Date</code>
  *   <li><code>java.util.Calendar</code>
  *   <li><code>java.sql.Date</code>
  *   <li><code>java.sql.Time</code>
  *   <li><code>java.sql.Timestamp</code>
  * </ul>
  *
  * It also handles conversion from a <code>String</code> to any of the above types.
  *
  * <p>For <code>String</code> conversion, if the converter has been configured with one or more
  * patterns (using <code>setPatterns()</code>), then the conversion is attempted with each of the
  * specified patterns. Otherwise the default <code>DateFormat</code> for the default locale (and
  * <i>style</i> if configured) will be used.
  *
  * @param targetType Data type to which this value should be converted.
  * @param value The input value to be converted.
  * @return The converted value.
  * @throws Exception if conversion cannot be performed successfully
  */
 @Override
 protected Object convertToType(final Class targetType, final Object value) throws Exception {
   Class sourceType = value.getClass();
   // Handle java.sql.Timestamp
   if (value instanceof java.sql.Timestamp) {
     // ---------------------- JDK 1.3 Fix ----------------------
     // N.B. Prior to JDK 1.4 the Timestamp's getTime() method
     //      didn't include the milliseconds. The following code
     //      ensures it works consistently accross JDK versions
     java.sql.Timestamp timestamp = (java.sql.Timestamp) value;
     long timeInMillis = timestamp.getTime() / 1000 * 1000;
     timeInMillis += timestamp.getNanos() / 1000000;
     // ---------------------- JDK 1.3 Fix ----------------------
     return this.toDate(targetType, timeInMillis);
   }
   // Handle Date (includes java.sql.Date & java.sql.Time)
   if (value instanceof Date) {
     Date date = (Date) value;
     return this.toDate(targetType, date.getTime());
   }
   // Handle Calendar
   if (value instanceof Calendar) {
     Calendar calendar = (Calendar) value;
     return this.toDate(targetType, calendar.getTime().getTime());
   }
   // Handle Long
   if (value instanceof Long) {
     Long longObj = (Long) value;
     return this.toDate(targetType, longObj.longValue());
   }
   // Convert all other types to String & handle
   String stringValue = value.toString().trim();
   if (stringValue.length() == 0) {
     return this.handleMissing(targetType);
   }
   // Parse the Date/Time
   if (this.useLocaleFormat) {
     Calendar calendar = null;
     if (this.patterns != null && this.patterns.length > 0) {
       calendar = this.parse(sourceType, targetType, stringValue);
     } else {
       DateFormat format = this.getFormat(this.locale, this.timeZone);
       calendar = this.parse(sourceType, targetType, stringValue, format);
     }
     if (Calendar.class.isAssignableFrom(targetType)) {
       return calendar;
     } else {
       return this.toDate(targetType, calendar.getTime().getTime());
     }
   }
   // Default String conversion
   return this.toDate(targetType, stringValue);
 }
コード例 #11
0
 @Override
 public String translateLiteralTimestamp(Timestamp timestampValue) {
   if (timestampValue.getNanos() == 0) {
     String val = formatDateValue(timestampValue);
     val = val.substring(0, val.length() - 2);
     return "to_date('"
         + val
         + "', '"
         + DATETIME_FORMAT
         + "')"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
   }
   return super.translateLiteralTimestamp(timestampValue);
 }
  @SuppressWarnings("static-access")
  @Test
  public void testPersistence() throws Exception {

    out.println(
        "\n\n_______________________ Iconix Case Persistence Test _______________________\n\n");

    String baseDir = System.getProperty("basedir");
    String filesPath =
        baseDir + "/target/test-classes/test-data/isatab/isatab_v1_200810/iconix_20081107red";
    ISATABLoader loader = new ISATABLoader(filesPath);
    FormatSetInstance isatabInstance = loader.load();

    out.println("\n\n_____ Loaded, now mapping");
    BIIObjectStore store = new BIIObjectStore();
    ISATABMapper isatabMapper = new ISATABMapper(store, isatabInstance);

    isatabMapper.map();
    assertTrue("Oh no! No mapped object! ", store.size() > 0);

    out.println("\n_____________ Persisting");
    // Test the repository too
    String repoPath = baseDir + "/target/bii_test_repo/meta_data";
    File repoDir = new File(repoPath);
    if (!repoDir.exists()) {
      FileUtils.forceMkdir(repoDir);
    }

    ISATABPersister persister = new ISATABPersister(store, DaoFactory.getInstance(entityManager));
    Timestamp ts = persister.persist(filesPath);
    transaction.commit();

    for (Study study : store.valuesOfType(Study.class)) {
      assertTrue(
          "Oh no! Submission didn't go to the repository!",
          new File(repoPath + "/study_" + DataLocationManager.getObfuscatedStudyFileName(study))
              .exists());
    }

    out.println(
        "\n\n\n\n________________ Done, Submission TS: "
            + ts.getTime()
            + " ("
            + ts
            + " + "
            + ts.getNanos()
            + "ns)");
    out.println(
        "\n\n___________________ /end: Iconix Case Persistence Test ___________________\n\n");
  }
コード例 #13
0
ファイル: DbTimestampType.java プロジェクト: enenuki/phd
 /*  95:    */
 /*  96:    */ private Timestamp useCallableStatement(
     String callString, SessionImplementor session)
       /*  97:    */ {
   /*  98:122 */ CallableStatement cs = null;
   /*  99:    */ try
   /* 100:    */ {
     /* 101:124 */ cs =
         (CallableStatement)
             session
                 .getTransactionCoordinator()
                 .getJdbcCoordinator()
                 .getStatementPreparer()
                 .prepareStatement(callString, true);
     /* 102:    */
     /* 103:    */
     /* 104:    */
     /* 105:128 */ cs.registerOutParameter(1, 93);
     /* 106:129 */ cs.execute();
     /* 107:130 */ Timestamp ts = cs.getTimestamp(1);
     /* 108:131 */ if (LOG.isTraceEnabled()) {
       /* 109:132 */ LOG.tracev(
           "Current timestamp retreived from db : {0} (nanos={1}, time={2})",
           ts, Integer.valueOf(ts.getNanos()), Long.valueOf(ts.getTime()));
       /* 110:    */ }
     /* 111:134 */ return ts;
     /* 112:    */ }
   /* 113:    */ catch (SQLException e)
   /* 114:    */ {
     /* 115:137 */ throw session
         .getFactory()
         .getSQLExceptionHelper()
         .convert(e, "could not call current db timestamp function", callString);
     /* 116:    */ }
   /* 117:    */ finally
   /* 118:    */ {
     /* 119:144 */ if (cs != null) {
       /* 120:    */ try
       /* 121:    */ {
         /* 122:146 */ cs.close();
         /* 123:    */ }
       /* 124:    */ catch (SQLException sqle)
       /* 125:    */ {
         /* 126:149 */ LOG.unableToCleanUpCallableStatement(sqle);
         /* 127:    */ }
       /* 128:    */ }
     /* 129:    */ }
   /* 130:    */ }
コード例 #14
0
ファイル: DbTimestampType.java プロジェクト: enenuki/phd
 /*  59:    */
 /*  60:    */ private Timestamp usePreparedStatement(
     String timestampSelectString, SessionImplementor session)
       /*  61:    */ {
   /*  62: 88 */ PreparedStatement ps = null;
   /*  63:    */ try
   /*  64:    */ {
     /*  65: 90 */ ps =
         session
             .getTransactionCoordinator()
             .getJdbcCoordinator()
             .getStatementPreparer()
             .prepareStatement(timestampSelectString, false);
     /*  66:    */
     /*  67:    */
     /*  68:    */
     /*  69: 94 */ ResultSet rs = ps.executeQuery();
     /*  70: 95 */ rs.next();
     /*  71: 96 */ Timestamp ts = rs.getTimestamp(1);
     /*  72: 97 */ if (LOG.isTraceEnabled()) {
       /*  73: 98 */ LOG.tracev(
           "Current timestamp retreived from db : {0} (nanos={1}, time={2})",
           ts, Integer.valueOf(ts.getNanos()), Long.valueOf(ts.getTime()));
       /*  74:    */ }
     /*  75:100 */ return ts;
     /*  76:    */ }
   /*  77:    */ catch (SQLException e)
   /*  78:    */ {
     /*  79:103 */ throw session
         .getFactory()
         .getSQLExceptionHelper()
         .convert(e, "could not select current db timestamp", timestampSelectString);
     /*  80:    */ }
   /*  81:    */ finally
   /*  82:    */ {
     /*  83:110 */ if (ps != null) {
       /*  84:    */ try
       /*  85:    */ {
         /*  86:112 */ ps.close();
         /*  87:    */ }
       /*  88:    */ catch (SQLException sqle)
       /*  89:    */ {
         /*  90:115 */ LOG.unableToCleanUpPreparedStatement(sqle);
         /*  91:    */ }
       /*  92:    */ }
     /*  93:    */ }
   /*  94:    */ }
コード例 #15
0
  /** Transformation method */
  @Override
  @SuppressWarnings("unchecked")
  public <T> T transform(Object in, Class<T> toClass, PropertyInfo info) {
    Map<Object, Object> cloneMap = _beanTransformer.getClonedMap();
    Object clone = cloneMap.get(in);

    if (clone != null) {
      return (T) clone;
    }

    Timestamp date = (Timestamp) in;
    clone = new Timestamp(date.getTime());

    ((Timestamp) clone).setNanos(date.getNanos());
    cloneMap.put(in, clone);

    return (T) clone;
  }
コード例 #16
0
  /**
   * Gets the end time of the recurrence rule or 0 if none.
   *
   * @return long The timestamp of the end time for this rule or 0 for none.
   */
  public long getEndTime() {
    if (rule == null) {
      Debug.logVerbose("Rule is null.", module);
      return -1;
    }
    long time = 0;
    java.sql.Timestamp stamp = null;

    stamp = rule.getTimestamp("untilDateTime");
    Debug.logVerbose("Stamp value: " + stamp, module);

    if (stamp != null) {
      long nanos = stamp.getNanos();
      time = stamp.getTime();
      time += (nanos / 1000000);
    }
    Debug.logVerbose("Returning time: " + time, module);
    return time;
  }
コード例 #17
0
  /**
   * Writes a Timestamp's serialized value to byte array b at the given offset
   *
   * @param timestamp to convert to bytes
   * @param b destination byte array
   * @param offset destination offset in the byte array
   */
  public static void convertTimestampToBytes(Timestamp t, byte[] b, int offset) {
    long millis = t.getTime();
    int nanos = t.getNanos();

    long seconds = millisToSeconds(millis);
    boolean hasSecondVInt = seconds < 0 || seconds > Integer.MAX_VALUE;
    boolean hasDecimal = setNanosBytes(nanos, b, offset + 4, hasSecondVInt);

    int firstInt = (int) seconds;
    if (hasDecimal || hasSecondVInt) {
      firstInt |= DECIMAL_OR_SECOND_VINT_FLAG;
    } else {
      firstInt &= LOWEST_31_BITS_OF_SEC_MASK;
    }
    intToBytes(firstInt, b, offset);

    if (hasSecondVInt) {
      LazyBinaryUtils.writeVLongToByteArray(
          b, offset + 4 + WritableUtils.decodeVIntSize(b[offset + 4]), seconds >> 31);
    }
  }
コード例 #18
0
 /** {@inheritDoc} */
 public Object convert(final Object object) {
   java.sql.Timestamp timestamp = (java.sql.Timestamp) object;
   long date = timestamp.getTime() + timestamp.getNanos() / MILLION;
   return getCustomDateFormat().format(new Date(date));
 }
コード例 #19
0
  public static java.util.Date sqlTimestampToDate(Timestamp t) {

    return t != null ? new java.util.Date(Math.round(t.getTime() + t.getNanos() / 1000000D)) : null;
  }
コード例 #20
0
ファイル: RowsAdaptor.java プロジェクト: HackShare/database
 /**
  * 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);
 }
コード例 #21
0
 @Override
 public void write(Kryo kryo, Output output, Timestamp ts) {
   output.writeLong(ts.getTime());
   output.writeInt(ts.getNanos());
 }
コード例 #22
0
 /**
  * Convert SQL Timestamp into CSS Timestamp.
  *
  * @param time SQL Timestamp
  * @return CSS ITimestamp
  */
 public static ITimestamp fromSQLTimestamp(final java.sql.Timestamp sql_time) {
   final long millisecs = sql_time.getTime();
   final long seconds = millisecs / 1000;
   final long nanoseconds = sql_time.getNanos();
   return createTimestamp(seconds, nanoseconds);
 }
コード例 #23
0
ファイル: Data.java プロジェクト: newsky/Lealone
 /**
  * Calculate the number of bytes required to encode the given value.
  *
  * @param v the value
  * @param handler the data handler for lobs
  * @return the number of bytes required to store this value
  */
 public static int getValueLen(Value v, DataHandler handler) {
   if (v == ValueNull.INSTANCE) {
     return 1;
   }
   switch (v.getType()) {
     case Value.BOOLEAN:
       return 1;
     case Value.BYTE:
       return 2;
     case Value.SHORT:
       return 3;
     case Value.INT:
       {
         int x = v.getInt();
         if (x < 0) {
           return 1 + getVarIntLen(-x);
         } else if (x < 16) {
           return 1;
         } else {
           return 1 + getVarIntLen(x);
         }
       }
     case Value.LONG:
       {
         long x = v.getLong();
         if (x < 0) {
           return 1 + getVarLongLen(-x);
         } else if (x < 8) {
           return 1;
         } else {
           return 1 + getVarLongLen(x);
         }
       }
     case Value.DOUBLE:
       {
         double x = v.getDouble();
         if (x == 1.0d) {
           return 1;
         }
         long d = Double.doubleToLongBits(x);
         if (d == ValueDouble.ZERO_BITS) {
           return 1;
         }
         return 1 + getVarLongLen(Long.reverse(d));
       }
     case Value.FLOAT:
       {
         float x = v.getFloat();
         if (x == 1.0f) {
           return 1;
         }
         int f = Float.floatToIntBits(x);
         if (f == ValueFloat.ZERO_BITS) {
           return 1;
         }
         return 1 + getVarIntLen(Integer.reverse(f));
       }
     case Value.STRING:
       {
         String s = v.getString();
         int len = s.length();
         if (len < 32) {
           return 1 + getStringWithoutLengthLen(s, len);
         }
         return 1 + getStringLen(s);
       }
     case Value.STRING_IGNORECASE:
     case Value.STRING_FIXED:
       return 1 + getStringLen(v.getString());
     case Value.DECIMAL:
       {
         BigDecimal x = v.getBigDecimal();
         if (BigDecimal.ZERO.equals(x)) {
           return 1;
         } else if (BigDecimal.ONE.equals(x)) {
           return 1;
         }
         int scale = x.scale();
         BigInteger b = x.unscaledValue();
         int bits = b.bitLength();
         if (bits <= 63) {
           if (scale == 0) {
             return 1 + getVarLongLen(b.longValue());
           }
           return 1 + getVarIntLen(scale) + getVarLongLen(b.longValue());
         }
         byte[] bytes = b.toByteArray();
         return 1 + getVarIntLen(scale) + getVarIntLen(bytes.length) + bytes.length;
       }
     case Value.TIME:
       if (SysProperties.STORE_LOCAL_TIME) {
         long nanos = ((ValueTime) v).getNanos();
         long millis = nanos / 1000000;
         nanos -= millis * 1000000;
         return 1 + getVarLongLen(millis) + getVarLongLen(nanos);
       }
       return 1 + getVarLongLen(DateTimeUtils.getTimeLocalWithoutDst(v.getTime()));
     case Value.DATE:
       {
         if (SysProperties.STORE_LOCAL_TIME) {
           long dateValue = ((ValueDate) v).getDateValue();
           return 1 + getVarLongLen(dateValue);
         }
         long x = DateTimeUtils.getTimeLocalWithoutDst(v.getDate());
         return 1 + getVarLongLen(x / MILLIS_PER_MINUTE);
       }
     case Value.TIMESTAMP:
       {
         if (SysProperties.STORE_LOCAL_TIME) {
           ValueTimestamp ts = (ValueTimestamp) v;
           long dateValue = ts.getDateValue();
           long nanos = ts.getNanos();
           long millis = nanos / 1000000;
           nanos -= millis * 1000000;
           return 1 + getVarLongLen(dateValue) + getVarLongLen(millis) + getVarLongLen(nanos);
         }
         Timestamp ts = v.getTimestamp();
         return 1
             + getVarLongLen(DateTimeUtils.getTimeLocalWithoutDst(ts))
             + getVarIntLen(ts.getNanos());
       }
     case Value.JAVA_OBJECT:
       {
         byte[] b = v.getBytesNoCopy();
         return 1 + getVarIntLen(b.length) + b.length;
       }
     case Value.BYTES:
       {
         byte[] b = v.getBytesNoCopy();
         int len = b.length;
         if (len < 32) {
           return 1 + b.length;
         }
         return 1 + getVarIntLen(b.length) + b.length;
       }
     case Value.UUID:
       return 1 + LENGTH_LONG + LENGTH_LONG;
     case Value.BLOB:
     case Value.CLOB:
       {
         int len = 1;
         ValueLob lob = (ValueLob) v;
         byte[] small = lob.getSmall();
         if (small == null) {
           len += getVarIntLen(-1);
           len += getVarIntLen(lob.getTableId());
           len += getVarLongLen(lob.getLobId());
           len += getVarLongLen(lob.getPrecision());
         } else {
           len += getVarIntLen(small.length);
           len += small.length;
         }
         return len;
       }
     case Value.ARRAY:
       {
         Value[] list = ((ValueArray) v).getList();
         int len = 1 + getVarIntLen(list.length);
         for (Value x : list) {
           len += getValueLen(x, handler);
         }
         return len;
       }
     case Value.RESULT_SET:
       {
         int len = 1;
         try {
           ResultSet rs = ((ValueResultSet) v).getResultSet();
           rs.beforeFirst();
           ResultSetMetaData meta = rs.getMetaData();
           int columnCount = meta.getColumnCount();
           len += getVarIntLen(columnCount);
           for (int i = 0; i < columnCount; i++) {
             len += getStringLen(meta.getColumnName(i + 1));
             len += getVarIntLen(meta.getColumnType(i + 1));
             len += getVarIntLen(meta.getPrecision(i + 1));
             len += getVarIntLen(meta.getScale(i + 1));
           }
           while (rs.next()) {
             len++;
             for (int i = 0; i < columnCount; i++) {
               int t = DataType.convertSQLTypeToValueType(meta.getColumnType(i + 1));
               Value val = DataType.readValue(null, rs, i + 1, t);
               len += getValueLen(val, handler);
             }
           }
           len++;
           rs.beforeFirst();
         } catch (SQLException e) {
           throw DbException.convert(e);
         }
         return len;
       }
     default:
       throw DbException.throwInternalError("type=" + v.getType());
   }
 }
コード例 #24
0
ファイル: Data.java プロジェクト: newsky/Lealone
 /**
  * Append a value.
  *
  * @param v the value
  */
 public void writeValue(Value v) {
   int start = pos;
   if (v == ValueNull.INSTANCE) {
     data[pos++] = 0;
     return;
   }
   int type = v.getType();
   switch (type) {
     case Value.BOOLEAN:
       writeByte((byte) (v.getBoolean().booleanValue() ? BOOLEAN_TRUE : BOOLEAN_FALSE));
       break;
     case Value.BYTE:
       writeByte((byte) type);
       writeByte(v.getByte());
       break;
     case Value.SHORT:
       writeByte((byte) type);
       writeShortInt(v.getShort());
       break;
     case Value.INT:
       {
         int x = v.getInt();
         if (x < 0) {
           writeByte((byte) INT_NEG);
           writeVarInt(-x);
         } else if (x < 16) {
           writeByte((byte) (INT_0_15 + x));
         } else {
           writeByte((byte) type);
           writeVarInt(x);
         }
         break;
       }
     case Value.LONG:
       {
         long x = v.getLong();
         if (x < 0) {
           writeByte((byte) LONG_NEG);
           writeVarLong(-x);
         } else if (x < 8) {
           writeByte((byte) (LONG_0_7 + x));
         } else {
           writeByte((byte) type);
           writeVarLong(x);
         }
         break;
       }
     case Value.DECIMAL:
       {
         BigDecimal x = v.getBigDecimal();
         if (BigDecimal.ZERO.equals(x)) {
           writeByte((byte) DECIMAL_0_1);
         } else if (BigDecimal.ONE.equals(x)) {
           writeByte((byte) (DECIMAL_0_1 + 1));
         } else {
           int scale = x.scale();
           BigInteger b = x.unscaledValue();
           int bits = b.bitLength();
           if (bits <= 63) {
             if (scale == 0) {
               writeByte((byte) DECIMAL_SMALL_0);
               writeVarLong(b.longValue());
             } else {
               writeByte((byte) DECIMAL_SMALL);
               writeVarInt(scale);
               writeVarLong(b.longValue());
             }
           } else {
             writeByte((byte) type);
             writeVarInt(scale);
             byte[] bytes = b.toByteArray();
             writeVarInt(bytes.length);
             write(bytes, 0, bytes.length);
           }
         }
         break;
       }
     case Value.TIME:
       if (SysProperties.STORE_LOCAL_TIME) {
         writeByte((byte) LOCAL_TIME);
         ValueTime t = (ValueTime) v;
         long nanos = t.getNanos();
         long millis = nanos / 1000000;
         nanos -= millis * 1000000;
         writeVarLong(millis);
         writeVarLong(nanos);
       } else {
         writeByte((byte) type);
         writeVarLong(DateTimeUtils.getTimeLocalWithoutDst(v.getTime()));
       }
       break;
     case Value.DATE:
       {
         if (SysProperties.STORE_LOCAL_TIME) {
           writeByte((byte) LOCAL_DATE);
           long x = ((ValueDate) v).getDateValue();
           writeVarLong(x);
         } else {
           writeByte((byte) type);
           long x = DateTimeUtils.getTimeLocalWithoutDst(v.getDate());
           writeVarLong(x / MILLIS_PER_MINUTE);
         }
         break;
       }
     case Value.TIMESTAMP:
       {
         if (SysProperties.STORE_LOCAL_TIME) {
           writeByte((byte) LOCAL_TIMESTAMP);
           ValueTimestamp ts = (ValueTimestamp) v;
           long dateValue = ts.getDateValue();
           writeVarLong(dateValue);
           long nanos = ts.getNanos();
           long millis = nanos / 1000000;
           nanos -= millis * 1000000;
           writeVarLong(millis);
           writeVarLong(nanos);
         } else {
           Timestamp ts = v.getTimestamp();
           writeByte((byte) type);
           writeVarLong(DateTimeUtils.getTimeLocalWithoutDst(ts));
           writeVarInt(ts.getNanos());
         }
         break;
       }
     case Value.JAVA_OBJECT:
       {
         writeByte((byte) type);
         byte[] b = v.getBytesNoCopy();
         writeVarInt(b.length);
         write(b, 0, b.length);
         break;
       }
     case Value.BYTES:
       {
         byte[] b = v.getBytesNoCopy();
         int len = b.length;
         if (len < 32) {
           writeByte((byte) (BYTES_0_31 + len));
           write(b, 0, b.length);
         } else {
           writeByte((byte) type);
           writeVarInt(b.length);
           write(b, 0, b.length);
         }
         break;
       }
     case Value.UUID:
       {
         writeByte((byte) type);
         ValueUuid uuid = (ValueUuid) v;
         writeLong(uuid.getHigh());
         writeLong(uuid.getLow());
         break;
       }
     case Value.STRING:
       {
         String s = v.getString();
         int len = s.length();
         if (len < 32) {
           writeByte((byte) (STRING_0_31 + len));
           writeStringWithoutLength(s, len);
         } else {
           writeByte((byte) type);
           writeString(s);
         }
         break;
       }
     case Value.STRING_IGNORECASE:
     case Value.STRING_FIXED:
       writeByte((byte) type);
       writeString(v.getString());
       break;
     case Value.DOUBLE:
       {
         double x = v.getDouble();
         if (x == 1.0d) {
           writeByte((byte) (DOUBLE_0_1 + 1));
         } else {
           long d = Double.doubleToLongBits(x);
           if (d == ValueDouble.ZERO_BITS) {
             writeByte((byte) DOUBLE_0_1);
           } else {
             writeByte((byte) type);
             writeVarLong(Long.reverse(d));
           }
         }
         break;
       }
     case Value.FLOAT:
       {
         float x = v.getFloat();
         if (x == 1.0f) {
           writeByte((byte) (FLOAT_0_1 + 1));
         } else {
           int f = Float.floatToIntBits(x);
           if (f == ValueFloat.ZERO_BITS) {
             writeByte((byte) FLOAT_0_1);
           } else {
             writeByte((byte) type);
             writeVarInt(Integer.reverse(f));
           }
         }
         break;
       }
     case Value.BLOB:
     case Value.CLOB:
       {
         writeByte((byte) type);
         ValueLob lob = (ValueLob) v;
         byte[] small = lob.getSmall();
         if (small == null) {
           writeVarInt(-1);
           writeVarInt(lob.getTableId());
           writeVarLong(lob.getLobId());
           writeVarLong(lob.getPrecision());
         } else {
           writeVarInt(small.length);
           write(small, 0, small.length);
         }
         break;
       }
     case Value.ARRAY:
       {
         writeByte((byte) type);
         Value[] list = ((ValueArray) v).getList();
         writeVarInt(list.length);
         for (Value x : list) {
           writeValue(x);
         }
         break;
       }
     case Value.RESULT_SET:
       {
         writeByte((byte) type);
         try {
           ResultSet rs = ((ValueResultSet) v).getResultSet();
           rs.beforeFirst();
           ResultSetMetaData meta = rs.getMetaData();
           int columnCount = meta.getColumnCount();
           writeVarInt(columnCount);
           for (int i = 0; i < columnCount; i++) {
             writeString(meta.getColumnName(i + 1));
             writeVarInt(meta.getColumnType(i + 1));
             writeVarInt(meta.getPrecision(i + 1));
             writeVarInt(meta.getScale(i + 1));
           }
           while (rs.next()) {
             writeByte((byte) 1);
             for (int i = 0; i < columnCount; i++) {
               int t = DataType.convertSQLTypeToValueType(meta.getColumnType(i + 1));
               Value val = DataType.readValue(null, rs, i + 1, t);
               writeValue(val);
             }
           }
           writeByte((byte) 0);
           rs.beforeFirst();
         } catch (SQLException e) {
           throw DbException.convert(e);
         }
         break;
       }
     default:
       DbException.throwInternalError("type=" + v.getType());
   }
   if (SysProperties.CHECK2) {
     if (pos - start != getValueLen(v, handler)) {
       throw DbException.throwInternalError(
           "value size error: got " + (pos - start) + " expected " + getValueLen(v, handler));
     }
   }
 }
コード例 #25
0
 private Timestamp fromSQLTimestamp(final java.sql.Timestamp sql_time) {
   final long millisecs = sql_time.getTime();
   final long seconds = millisecs / 1000;
   final int nanoseconds = sql_time.getNanos();
   return Timestamp.of(seconds, nanoseconds);
 }
コード例 #26
0
 @Override
 protected void writeObject(ObjectOutput out, Object obj) throws IOException {
   Timestamp ts = (Timestamp) obj;
   out.writeLong(ts.getTime());
   out.writeInt(ts.getNanos());
 }