コード例 #1
0
ファイル: RubyTime.java プロジェクト: rizkyrukmana/jruby
  public RubyObject mdump() {
    RubyTime obj = this;
    DateTime dateTime = obj.dt.toDateTime(DateTimeZone.UTC);
    byte dumpValue[] = new byte[8];

    int pe =
        0x1 << 31
            | ((obj.gmt().isTrue()) ? 0x1 : 0x0) << 30
            | (dateTime.getYear() - 1900) << 14
            | (dateTime.getMonthOfYear() - 1) << 10
            | dateTime.getDayOfMonth() << 5
            | dateTime.getHourOfDay();
    int se =
        dateTime.getMinuteOfHour() << 26
            | dateTime.getSecondOfMinute() << 20
            | (dateTime.getMillisOfSecond() * 1000 + (int) usec); // dump usec, not msec

    for (int i = 0; i < 4; i++) {
      dumpValue[i] = (byte) (pe & 0xFF);
      pe >>>= 8;
    }
    for (int i = 4; i < 8; i++) {
      dumpValue[i] = (byte) (se & 0xFF);
      se >>>= 8;
    }
    return RubyString.newString(obj.getRuntime(), new ByteList(dumpValue));
  }
コード例 #2
0
ファイル: RubyTime.java プロジェクト: rizkyrukmana/jruby
 public static IRubyObject s_new(IRubyObject recv, IRubyObject[] args, Block block) {
   Ruby runtime = recv.getRuntime();
   RubyTime time =
       new RubyTime(runtime, (RubyClass) recv, new DateTime(getLocalTimeZone(runtime)));
   time.callInit(args, block);
   return time;
 }
コード例 #3
0
ファイル: RubyTime.java プロジェクト: rizkyrukmana/jruby
  private IRubyObject opMinus(RubyTime other) {
    long time = getTimeInMillis() * 1000 + getUSec();

    time -= other.getTimeInMillis() * 1000 + other.getUSec();

    return RubyFloat.newFloat(getRuntime(), time / 1000000.0); // float number of seconds
  }
コード例 #4
0
ファイル: RubyTime.java プロジェクト: rizkyrukmana/jruby
        public IRubyObject allocate(Ruby runtime, RubyClass klass) {
          DateTimeZone dtz = getLocalTimeZone(runtime);
          DateTime dt = new DateTime(dtz);
          RubyTime rt = new RubyTime(runtime, klass, dt);
          rt.setUSec(0);

          return rt;
        }
コード例 #5
0
ファイル: DataObjectsUtils.java プロジェクト: gryn/do
    public static IRubyObject prepareRubyTimeFromSqlDate(Ruby runtime, Date date) {

        if (date.getTime() + 3600000 == 0) {
            return runtime.getNil();
        }
        RubyTime rbTime = RubyTime.newTime(runtime, date.getTime());
        rbTime.extend(new IRubyObject[]{runtime.getModule("TimeFormatter")});
        return rbTime;
        // SimpleDateFormat sdf = new SimpleDateFormat("HH-mm-ss"); // TODO proper format?
        // return runtime.newString(sdf.format(rbTime.getJavaDate()));
    }
コード例 #6
0
ファイル: RubyTime.java プロジェクト: rizkyrukmana/jruby
 @JRubyMethod(name = "eql?", required = 1)
 @Override
 public IRubyObject eql_p(IRubyObject other) {
   if (other instanceof RubyTime) {
     RubyTime otherTime = (RubyTime) other;
     return (usec == otherTime.usec && getTimeInMillis() == otherTime.getTimeInMillis())
         ? getRuntime().getTrue()
         : getRuntime().getFalse();
   }
   return getRuntime().getFalse();
 }
コード例 #7
0
    @Specialization
    public RubyBasicObject timeDecompose(VirtualFrame frame, RubyTime time) {
      CompilerDirectives.transferToInterpreter();
      final DateTime dateTime = time.getDateTime();
      final int sec = dateTime.getSecondOfMinute();
      final int min = dateTime.getMinuteOfHour();
      final int hour = dateTime.getHourOfDay();
      final int day = dateTime.getDayOfMonth();
      final int month = dateTime.getMonthOfYear();
      final int year = dateTime.getYear();

      int wday = dateTime.getDayOfWeek();

      if (wday == 7) {
        wday = 0;
      }

      final int yday = dateTime.getDayOfYear();
      final boolean isdst = false;

      final String envTimeZoneString = readTimeZoneNode.executeRubyString(frame).toString();
      String zoneString = org.jruby.RubyTime.zoneHelper(envTimeZoneString, dateTime, false);
      Object zone;
      if (zoneString.matches(".*-\\d+")) {
        zone = nil();
      } else {
        zone = createString(zoneString);
      }

      final Object[] decomposed =
          new Object[] {sec, min, hour, day, month, year, wday, yday, isdst, zone};
      return createArray(decomposed, decomposed.length);
    }
コード例 #8
0
 @TruffleBoundary
 private DateTime localtime(long milliseconds, RubyString timeZone) {
   return new DateTime(
       milliseconds,
       org.jruby.RubyTime.getTimeZoneFromTZString(
           getContext().getRuntime(), timeZone.toString()));
 }
コード例 #9
0
ファイル: X509CRL.java プロジェクト: nahi/jruby-ossl-ext
 @JRubyMethod(name = "next_update=")
 public IRubyObject set_next_update(IRubyObject val) {
   changed = true;
   next_update = val.callMethod(getRuntime().getCurrentContext(), "getutc");
   ((RubyTime) next_update).setMicroseconds(0);
   generator.setNextUpdate(((RubyTime) next_update).getJavaDate());
   this.next_update = val;
   return val;
 }
コード例 #10
0
    private RubyTime buildTime(
        VirtualFrame frame,
        RubyClass timeClass,
        int sec,
        int min,
        int hour,
        int mday,
        int month,
        int year,
        int nsec,
        int isdst,
        boolean fromutc,
        Object utcoffset) {
      CompilerDirectives.transferToInterpreter();

      if (sec < 0
          || sec > 59
          || min < 0
          || min > 59
          || hour < 0
          || hour > 23
          || mday < 1
          || mday > 31
          || month < 1
          || month > 12) {
        throw new RaiseException(getContext().getCoreLibrary().argumentErrorOutOfRange(this));
      }

      final DateTimeZone zone;
      if (fromutc) {
        zone = DateTimeZone.UTC;
      } else if (utcoffset == nil()) {
        String tz = readTimeZoneNode.executeRubyString(frame).toString();
        zone = org.jruby.RubyTime.getTimeZoneFromTZString(getContext().getRuntime(), tz);
      } else if (utcoffset instanceof Integer) {
        zone = DateTimeZone.forOffsetMillis(((int) utcoffset) * 1_000);
      } else if (utcoffset instanceof Long) {
        zone = DateTimeZone.forOffsetMillis((int) ((long) utcoffset) * 1_000);
      } else if (utcoffset instanceof RubyBasicObject) {
        final int millis = cast(ruby(frame, "(offset * 1000).to_i", "offset", utcoffset));
        zone = DateTimeZone.forOffsetMillis(millis);
      } else {
        throw new UnsupportedOperationException(
            String.format("%s %s %s %s", isdst, fromutc, utcoffset, utcoffset.getClass()));
      }

      if (isdst == -1) {
        final DateTime dateTime =
            new DateTime(year, month, mday, hour, min, sec, nsec / 1_000_000, zone);
        return new RubyTime(timeClass, dateTime, utcoffset);
      } else {
        throw new UnsupportedOperationException(
            String.format("%s %s %s %s", isdst, fromutc, utcoffset, utcoffset.getClass()));
      }
    }
コード例 #11
0
ファイル: RubyTime.java プロジェクト: rizkyrukmana/jruby
  private IRubyObject opPlusCommon(long adjustment) {
    long micro = adjustment % 1000;
    adjustment = adjustment / 1000;

    long time = getTimeInMillis();
    time += adjustment;

    if ((getUSec() + micro) >= 1000) {
      time++;
      micro = (getUSec() + micro) - 1000;
    } else {
      micro = getUSec() + micro;
    }

    RubyTime newTime = new RubyTime(getRuntime(), getMetaClass());
    newTime.dt = new DateTime(time).withZone(dt.getZone());
    newTime.setUSec(micro);

    return newTime;
  }
コード例 #12
0
ファイル: RubyTime.java プロジェクト: rizkyrukmana/jruby
  protected static RubyTime s_mload(IRubyObject recv, RubyTime time, IRubyObject from) {
    Ruby runtime = recv.getRuntime();

    DateTime dt = new DateTime(DateTimeZone.UTC);

    byte[] fromAsBytes = null;
    fromAsBytes = from.convertToString().getBytes();
    if (fromAsBytes.length != 8) {
      throw runtime.newTypeError("marshaled time format differ");
    }
    int p = 0;
    int s = 0;
    for (int i = 0; i < 4; i++) {
      p |= ((int) fromAsBytes[i] & 0xFF) << (8 * i);
    }
    for (int i = 4; i < 8; i++) {
      s |= ((int) fromAsBytes[i] & 0xFF) << (8 * (i - 4));
    }
    boolean utc = false;
    if ((p & (1 << 31)) == 0) {
      dt = dt.withMillis(p * 1000L);
      time.setUSec((s & 0xFFFFF) % 1000);
    } else {
      p &= ~(1 << 31);
      utc = ((p >>> 30 & 0x1) == 0x1);
      dt = dt.withYear(((p >>> 14) & 0xFFFF) + 1900);
      dt = dt.withMonthOfYear(((p >>> 10) & 0xF) + 1);
      dt = dt.withDayOfMonth(((p >>> 5) & 0x1F));
      dt = dt.withHourOfDay((p & 0x1F));
      dt = dt.withMinuteOfHour(((s >>> 26) & 0x3F));
      dt = dt.withSecondOfMinute(((s >>> 20) & 0x3F));
      // marsaling dumps usec, not msec
      dt = dt.withMillisOfSecond((s & 0xFFFFF) / 1000);
      time.setUSec((s & 0xFFFFF) % 1000);
    }
    time.setDateTime(dt);
    if (!utc) time.localtime();

    from.getInstanceVariables().copyInstanceVariablesInto(time);
    return time;
  }
コード例 #13
0
ファイル: RubyTime.java プロジェクト: rizkyrukmana/jruby
  private IRubyObject opMinusCommon(IRubyObject other) {
    long time = getTimeInMillis();
    long adjustment = Math.round(RubyNumeric.num2dbl(other) * 1000000);
    long micro = adjustment % 1000;
    adjustment = adjustment / 1000;

    time -= adjustment;

    if (getUSec() < micro) {
      time--;
      micro = 1000 - (micro - getUSec());
    } else {
      micro = getUSec() - micro;
    }

    RubyTime newTime = new RubyTime(getRuntime(), getMetaClass());
    newTime.dt = new DateTime(time).withZone(dt.getZone());
    newTime.setUSec(micro);

    return newTime;
  }
コード例 #14
0
ファイル: RubyTime.java プロジェクト: rizkyrukmana/jruby
  private int cmp(RubyTime other) {
    long millis = getTimeInMillis();
    long millis_other = other.getTimeInMillis();
    long usec_other = other.usec;

    if (millis > millis_other || (millis == millis_other && usec > usec_other)) {
      return 1;
    } else if (millis < millis_other || (millis == millis_other && usec < usec_other)) {
      return -1;
    }

    return 0;
  }
コード例 #15
0
ファイル: RubyTime.java プロジェクト: rizkyrukmana/jruby
  @JRubyMethod(name = "at", meta = true)
  public static IRubyObject at(
      ThreadContext context, IRubyObject recv, IRubyObject arg1, IRubyObject arg2) {
    Ruby runtime = context.getRuntime();

    RubyTime time =
        new RubyTime(runtime, (RubyClass) recv, new DateTime(0L, getLocalTimeZone(runtime)));

    long seconds = RubyNumeric.num2long(arg1);
    long millisecs = 0;
    long microsecs = 0;

    long tmp = RubyNumeric.num2long(arg2);
    millisecs = tmp / 1000;
    microsecs = tmp % 1000;

    time.setUSec(microsecs);
    time.dt = time.dt.withMillis(seconds * 1000 + millisecs);

    time.getMetaClass().getBaseCallSites()[RubyClass.CS_IDX_INITIALIZE].call(context, recv, time);

    return time;
  }
コード例 #16
0
ファイル: RubyTime.java プロジェクト: rizkyrukmana/jruby
  @JRubyMethod(name = "at", meta = true)
  public static IRubyObject at(ThreadContext context, IRubyObject recv, IRubyObject arg) {
    Ruby runtime = context.getRuntime();
    final RubyTime time;

    if (arg instanceof RubyTime) {
      RubyTime other = (RubyTime) arg;
      time = new RubyTime(runtime, (RubyClass) recv, other.dt);
      time.setUSec(other.getUSec());
    } else {
      time = new RubyTime(runtime, (RubyClass) recv, new DateTime(0L, getLocalTimeZone(runtime)));

      long seconds = RubyNumeric.num2long(arg);
      long millisecs = 0;
      long microsecs = 0;

      // In the case of two arguments, MRI will discard the portion of
      // the first argument after a decimal point (i.e., "floor").
      // However in the case of a single argument, any portion after
      // the decimal point is honored.
      if (arg instanceof RubyFloat || arg instanceof RubyRational) {
        double dbl = RubyNumeric.num2dbl(arg);
        long micro = Math.round((dbl - seconds) * 1000000);
        if (dbl < 0 && micro != 0) {
          micro += 1000000;
        }
        millisecs = micro / 1000;
        microsecs = micro % 1000;
      }
      time.setUSec(microsecs);
      time.dt = time.dt.withMillis(seconds * 1000 + millisecs);
    }

    time.getMetaClass().getBaseCallSites()[RubyClass.CS_IDX_INITIALIZE].call(context, recv, time);

    return time;
  }
コード例 #17
0
ファイル: DataObjectsUtils.java プロジェクト: gryn/do
 public static IRubyObject parse_date_time(Ruby runtime, Timestamp ts) {
     RubyTime time = RubyTime.newTime(runtime, ts.getTime());
     time.extend(new IRubyObject[] {runtime.getModule("DatetimeFormatter")});
     return time;
 }
コード例 #18
0
ファイル: DataObjectsUtils.java プロジェクト: gryn/do
 public static IRubyObject parse_date(Ruby runtime, Date dt) {
     RubyTime time = RubyTime.newTime(runtime, dt.getTime());
     time.extend(new IRubyObject[] {runtime.getModule("DateFormatter")});
     return time;
 }
コード例 #19
0
ファイル: RubyTime.java プロジェクト: rizkyrukmana/jruby
  private static RubyTime createTime(IRubyObject recv, IRubyObject[] args, boolean gmt) {
    Ruby runtime = recv.getRuntime();
    int len = ARG_SIZE;
    Boolean isDst = null;

    DateTimeZone dtz;
    if (gmt) {
      dtz = DateTimeZone.UTC;
    } else if (args.length == 10 && args[9] instanceof RubyString) {
      dtz = getTimeZone(runtime, ((RubyString) args[9]).toString());
    } else {
      dtz = getLocalTimeZone(runtime);
    }

    if (args.length == 10) {
      if (args[8] instanceof RubyBoolean) {
        isDst = ((RubyBoolean) args[8]).isTrue();
      }
      args =
          new IRubyObject[] {
            args[5], args[4], args[3], args[2], args[1], args[0], runtime.getNil()
          };
    } else {
      // MRI accepts additional wday argument which appears to be ignored.
      len = args.length;

      if (len < ARG_SIZE) {
        IRubyObject[] newArgs = new IRubyObject[ARG_SIZE];
        System.arraycopy(args, 0, newArgs, 0, args.length);
        for (int i = len; i < ARG_SIZE; i++) {
          newArgs[i] = runtime.getNil();
        }
        args = newArgs;
        len = ARG_SIZE;
      }
    }

    if (args[0] instanceof RubyString) {
      args[0] = RubyNumeric.str2inum(runtime, (RubyString) args[0], 10, false);
    }

    int year = (int) RubyNumeric.num2long(args[0]);
    int month = 1;

    if (len > 1) {
      if (!args[1].isNil()) {
        IRubyObject tmp = args[1].checkStringType();
        if (!tmp.isNil()) {
          String monthString = tmp.toString().toLowerCase();
          Integer monthInt = MONTHS_MAP.get(monthString);

          if (monthInt != null) {
            month = monthInt;
          } else {
            try {
              month = Integer.parseInt(monthString);
            } catch (NumberFormatException nfExcptn) {
              throw runtime.newArgumentError("Argument out of range.");
            }
          }
        } else {
          month = (int) RubyNumeric.num2long(args[1]);
        }
      }
      if (1 > month || month > 12) {
        throw runtime.newArgumentError("Argument out of range: for month: " + month);
      }
    }

    int[] int_args = {1, 0, 0, 0, 0, 0};

    for (int i = 0; int_args.length >= i + 2; i++) {
      if (!args[i + 2].isNil()) {
        if (!(args[i + 2] instanceof RubyNumeric)) {
          args[i + 2] = args[i + 2].callMethod(runtime.getCurrentContext(), "to_i");
        }

        long value = RubyNumeric.num2long(args[i + 2]);
        if (time_min[i] > value || value > time_max[i]) {
          throw runtime.newArgumentError("argument out of range.");
        }
        int_args[i] = (int) value;
      }
    }

    if (!runtime.is1_9()) {
      if (0 <= year && year < 39) {
        year += 2000;
      } else if (69 <= year && year < 139) {
        year += 1900;
      }
    }

    DateTime dt;
    // set up with min values and then add to allow rolling over
    try {
      dt = new DateTime(year, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC);

      dt =
          dt.plusMonths(month - 1)
              .plusDays(int_args[0] - 1)
              .plusHours(int_args[1])
              .plusMinutes(int_args[2])
              .plusSeconds(int_args[3]);
      if (runtime.is1_9() && !args[5].isNil()) {
        double millis = RubyFloat.num2dbl(args[5]);
        int int_millis = (int) (millis * 1000) % 1000;
        dt = dt.plusMillis(int_millis);
      }

      dt = dt.withZoneRetainFields(dtz);

      // we might need to perform a DST correction
      if (isDst != null) {
        // the instant at which we will ask dtz what the difference between DST and
        // standard time is
        long offsetCalculationInstant = dt.getMillis();

        // if we might be moving this time from !DST -> DST, the offset is assumed
        // to be the same as it was just before we last moved from DST -> !DST
        if (dtz.isStandardOffset(dt.getMillis())) {
          offsetCalculationInstant = dtz.previousTransition(offsetCalculationInstant);
        }

        int offset =
            dtz.getStandardOffset(offsetCalculationInstant)
                - dtz.getOffset(offsetCalculationInstant);

        if (!isDst && !dtz.isStandardOffset(dt.getMillis())) {
          dt = dt.minusMillis(offset);
        }
        if (isDst && dtz.isStandardOffset(dt.getMillis())) {
          dt = dt.plusMillis(offset);
        }
      }
    } catch (org.joda.time.IllegalFieldValueException e) {
      throw runtime.newArgumentError("time out of range");
    }

    RubyTime time = new RubyTime(runtime, (RubyClass) recv, dt);
    // Ignores usec if 8 args (for compatibility with parsedate) or if not supplied.
    if (args.length != 8 && !args[6].isNil()) {
      int usec = int_args[4] % 1000;
      int msec = int_args[4] / 1000;

      if (int_args[4] < 0) {
        msec -= 1;
        usec += 1000;
      }
      time.dt = dt.withMillis(dt.getMillis() + msec);
      time.setUSec(usec);
    }

    time.callInit(IRubyObject.NULL_ARRAY, Block.NULL_BLOCK);
    return time;
  }
コード例 #20
0
ファイル: DataObjectsUtils.java プロジェクト: gryn/do
 public static IRubyObject parse_time(Ruby runtime, Time tm) {
     RubyTime time = RubyTime.newTime(runtime, tm.getTime());
     time.extend(new IRubyObject[] {runtime.getModule("TimeFormatter")});
     return (time.getUSec() != 0) ? time : runtime.getNil();
 }
コード例 #21
0
ファイル: X509CRL.java プロジェクト: nahi/jruby-ossl-ext
  @JRubyMethod(name = "initialize", rest = true, frame = true)
  public IRubyObject _initialize(IRubyObject[] args, Block block) {
    extensions = new ArrayList<IRubyObject>();
    if (org.jruby.runtime.Arity.checkArgumentCount(getRuntime(), args, 0, 1) == 0) {
      version = getRuntime().getNil();
      issuer = getRuntime().getNil();
      last_update = getRuntime().getNil();
      next_update = getRuntime().getNil();
      revoked = getRuntime().newArray();
      return this;
    }

    ByteArrayInputStream bis = new ByteArrayInputStream(args[0].convertToString().getBytes());
    try {
      // SunJCE throws java.security.cert.CRLException: Invalid encoding of
      // AuthorityKeyIdentifierExtension.
      // FIXME: use BC for now.
      CertificateFactory cf = OpenSSLReal.getX509CertificateFactoryBC();
      crl = (java.security.cert.X509CRL) cf.generateCRL(bis);
    } catch (GeneralSecurityException gse) {
      throw newX509CRLError(getRuntime(), gse.getMessage());
    }

    byte[] crl_bytes = args[0].convertToString().getBytes();
    // Parse PEM if we ever get passed some PEM contents
    try {
      StringReader in = new StringReader(args[0].toString());
      byte[] bytes = OpenSSLReal.getFormatHandler().readPEMToDER(in);
      if (bytes != null) crl_bytes = bytes;
      in.close();
    } catch (Exception e) {
      // this is not PEM encoded, let's use the default argument
    }

    try {
      crl_v = new ASN1InputStream(new ByteArrayInputStream(crl_bytes)).readObject();
    } catch (IOException ioe) {
      throw newX509CRLError(getRuntime(), ioe.getMessage());
    }

    DEREncodable v0 = ((DERSequence) (((DERSequence) crl_v).getObjectAt(0))).getObjectAt(0);
    if (v0 instanceof DERInteger) {
      set_version(getRuntime().newFixnum(((DERInteger) v0).getValue().intValue()));
    } else {
      set_version(getRuntime().newFixnum(2));
    }
    set_last_update(RubyTime.newTime(getRuntime(), crl.getThisUpdate().getTime()));
    set_next_update(RubyTime.newTime(getRuntime(), crl.getNextUpdate().getTime()));
    RubyString name = RubyString.newString(getRuntime(), crl.getIssuerX500Principal().getEncoded());
    set_issuer(Utils.newRubyInstance(getRuntime(), "OpenSSL::X509::Name", name));

    revoked = getRuntime().newArray();

    DERSequence seqa = (DERSequence) ((DERSequence) crl_v).getObjectAt(0);
    DERObject maybe_ext = (DERObject) seqa.getObjectAt(seqa.size() - 1);
    if (maybe_ext instanceof DERTaggedObject && ((DERTaggedObject) maybe_ext).getTagNo() == 0) {
      DERSequence exts = (DERSequence) ((DERTaggedObject) maybe_ext).getObject();
      for (int i = 0; i < exts.size(); i++) {
        DERSequence seq2 = (DERSequence) exts.getObjectAt(i);
        boolean critical = false;
        String oid = ((DERObjectIdentifier) seq2.getObjectAt(0)).getId();
        if (seq2.getObjectAt(1) == DERBoolean.TRUE) {
          critical = true;
        }
        byte[] value = crl.getExtensionValue(oid);
        IRubyObject mASN1 = getRuntime().getClassFromPath("OpenSSL::ASN1");
        IRubyObject rValue = null;
        try {
          rValue =
              ASN1.decode(
                  mASN1,
                  ASN1.decode(mASN1, RubyString.newString(getRuntime(), value))
                      .callMethod(getRuntime().getCurrentContext(), "value"));
        } catch (Exception e) {
          rValue = RubyString.newString(getRuntime(), value);
        }
        X509Extensions.Extension ext1 =
            (X509Extensions.Extension)
                Utils.newRubyInstance(getRuntime(), "OpenSSL::X509::Extension");
        ext1.setRealOid(ext1.getObjectIdentifier(oid));
        ext1.setRealValue(rValue);
        ext1.setRealCritical(critical);
        add_extension(ext1);
      }
    }

    changed = false;
    return this;
  }
コード例 #22
0
ファイル: RubyTime.java プロジェクト: rizkyrukmana/jruby
 public static RubyTime newTime(Ruby runtime, DateTime dt, long usec) {
   RubyTime t = new RubyTime(runtime, runtime.getTime(), dt);
   t.setUSec(usec);
   return t;
 }
コード例 #23
0
 @TruffleBoundary
 private DateTime now(RubyString timeZone) {
   return DateTime.now(
       org.jruby.RubyTime.getTimeZoneFromTZString(
           getContext().getRuntime(), timeZone.toString()));
 }
コード例 #24
0
ファイル: Command.java プロジェクト: gryn/do
 /**
  * @param ps the PreparedStatement for which the parameter should be set
  * @param recv
  * @param arg a parameter value
  * @param idx the index of the parameter
  * @throws java.sql.SQLException
  */
 private static void setPreparedStatementParam(
     PreparedStatement ps, IRubyObject recv, IRubyObject arg, int idx) throws SQLException {
   Integer jdbcTypeId = null;
   try {
     jdbcTypeId = ps.getMetaData().getColumnType(idx);
   } catch (Exception ex) {
   }
   String rubyTypeName = arg.getType().getName();
   if ("Fixnum".equals(rubyTypeName)) {
     ps.setInt(idx, Integer.parseInt(arg.toString()));
   } else if ("Bignum".equals(rubyTypeName)) {
     ps.setLong(idx, ((RubyBignum) arg).getLongValue());
   } else if ("Float".equals(rubyTypeName)) {
     ps.setDouble(idx, RubyNumeric.num2dbl(arg));
   } else if ("BigDecimal".equals(rubyTypeName)) {
     ps.setBigDecimal(idx, ((RubyBigDecimal) arg).getValue());
   } else if ("NilClass".equals(rubyTypeName)) {
     // XXX In fact this should looks like ps.setNull(idx, Types.YYY);
     // where YYY is a JDBC type of column i.e. Types.VARCHAR
     // but this code works for MySQL :)
     ps.setNull(idx, Types.NULL);
   } else if ("TrueClass".equals(rubyTypeName) || "FalseClass".equals(rubyTypeName)) {
     ps.setBoolean(idx, arg.toString().equals("true"));
   } else if ("Class".equals(rubyTypeName)) {
     ps.setString(idx, arg.toString());
   } else if ("Extlib::ByteArray".equals(rubyTypeName)) {
     ps.setBytes(idx, ((RubyString) arg).getBytes());
     // TODO: add support for ps.setBlob();
   } else if ("Date".equals(rubyTypeName)) {
     ps.setDate(idx, java.sql.Date.valueOf(arg.toString()));
   } else if ("Time".equals(rubyTypeName)) {
     RubyTime rubyTime = (RubyTime) arg;
     java.util.Date date = rubyTime.getJavaDate();
     GregorianCalendar cal = new GregorianCalendar();
     cal.setTime(date);
     cal.setTimeZone(
         TimeZone.getTimeZone("UTC")); // XXX works only if driver suports Calendars in PS
     java.sql.Timestamp ts;
     if (driver.supportsCalendarsInJDBCPreparedStatement() == true) {
       ts = new java.sql.Timestamp(cal.getTime().getTime());
       ts.setNanos(cal.get(GregorianCalendar.MILLISECOND) * 100000);
     } else {
       // XXX ugly workaround for MySQL and Hsqldb
       ts =
           new Timestamp(
               cal.get(GregorianCalendar.YEAR) - 1900,
               cal.get(GregorianCalendar.MONTH),
               cal.get(GregorianCalendar.DAY_OF_MONTH),
               cal.get(GregorianCalendar.HOUR_OF_DAY),
               cal.get(GregorianCalendar.MINUTE),
               cal.get(GregorianCalendar.SECOND),
               cal.get(GregorianCalendar.MILLISECOND) * 100000);
     }
     ps.setTimestamp(idx, ts, cal);
   } else if ("DateTime".equals(rubyTypeName)) {
     ps.setTimestamp(
         idx,
         java.sql.Timestamp.valueOf(
             arg.toString().replace('T', ' ').replaceFirst("[-+]..:..$", "")));
   } else if (arg.toString().indexOf("-") != -1 && arg.toString().indexOf(":") != -1) {
     // TODO: improve the above string pattern checking
     // Handle date patterns in strings
     java.util.Date parsedDate;
     try {
       parsedDate = FORMAT.parse(arg.asJavaString().replace('T', ' '));
       java.sql.Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
       ps.setTimestamp(idx, timestamp);
     } catch (ParseException ex) {
       ps.setString(idx, api.convertToRubyString(arg).getUnicodeValue());
     }
   } else if (arg.toString().indexOf(":") != -1 && arg.toString().length() == 8) {
     // Handle time patterns in strings
     ps.setTime(idx, java.sql.Time.valueOf(arg.asJavaString()));
   } else {
     if (jdbcTypeId == null) {
       ps.setString(idx, api.convertToRubyString(arg).getUnicodeValue());
     } else {
       // TODO: Here comes conversions like '.execute_reader("2")'
       // It definitly needs to be refactored...
       try {
         if (jdbcTypeId == Types.VARCHAR) {
           ps.setString(idx, api.convertToRubyString(arg).getUnicodeValue());
         } else if (jdbcTypeId == Types.INTEGER) {
           ps.setObject(idx, Integer.valueOf(arg.toString()), jdbcTypeId);
         } else {
           // I'm not sure is it correct in 100%
           ps.setString(idx, api.convertToRubyString(arg).getUnicodeValue());
         }
       } catch (NumberFormatException ex) { // i.e Integer.valueOf
         ps.setString(idx, api.convertToRubyString(arg).getUnicodeValue());
       }
     }
   }
 }
コード例 #25
0
ファイル: X509CRL.java プロジェクト: nahi/jruby-ossl-ext
  @JRubyMethod
  public IRubyObject sign(final IRubyObject key, IRubyObject digest) {
    // System.err.println("WARNING: unimplemented method called: CRL#sign");
    // Have to obey some artificial constraints of the OpenSSL implementation. Stupid.
    String keyAlg = ((PKey) key).getAlgorithm();
    String digAlg = ((Digest) digest).getShortAlgorithm();

    if (("DSA".equalsIgnoreCase(keyAlg) && "MD5".equalsIgnoreCase(digAlg))
        || ("RSA".equalsIgnoreCase(keyAlg) && "DSS1".equals(((Digest) digest).name().toString()))
        || ("DSA".equalsIgnoreCase(keyAlg) && "SHA1".equals(((Digest) digest).name().toString()))) {
      throw newX509CRLError(getRuntime(), null);
    }

    sig_alg = getRuntime().newString(digAlg);
    generator.setSignatureAlgorithm(digAlg + "WITH" + keyAlg);

    for (IRubyObject obj : ((RubyArray) revoked).toJavaArray()) {
      X509Revoked rev = (X509Revoked) obj; // TODO: can throw CCE
      BigInteger serial =
          new BigInteger(rev.callMethod(getRuntime().getCurrentContext(), "serial").toString());
      IRubyObject t1 =
          rev.callMethod(getRuntime().getCurrentContext(), "time")
              .callMethod(getRuntime().getCurrentContext(), "getutc");
      ((RubyTime) t1).setMicroseconds(0);
      // Extensions ignored, for now
      generator.addCRLEntry(
          serial,
          ((RubyTime) t1).getJavaDate(),
          new org.bouncycastle.asn1.x509.X509Extensions(new Hashtable()));
    }

    try {
      for (Iterator<IRubyObject> iter = extensions.iterator(); iter.hasNext(); ) {
        X509Extensions.Extension ag = (X509Extensions.Extension) iter.next();
        generator.addExtension(ag.getRealOid(), ag.getRealCritical(), ag.getRealValueBytes());
      }
    } catch (IOException ioe) {
      throw newX509CRLError(getRuntime(), ioe.getMessage());
    }
    try {
      // X509V2CRLGenerator(generator) depends BC.
      OpenSSLReal.doWithBCProvider(
          new OpenSSLReal.Runnable() {

            public void run() throws GeneralSecurityException {
              crl = generator.generate(((PKey) key).getPrivateKey(), "BC");
            }
          });
    } catch (GeneralSecurityException gse) {
      throw newX509CRLError(getRuntime(), gse.getMessage());
    }

    try {
      crl_v = new ASN1InputStream(new ByteArrayInputStream(crl.getEncoded())).readObject();
    } catch (CRLException crle) {
      throw newX509CRLError(getRuntime(), crle.getMessage());
    } catch (IOException ioe) {
      throw newX509CRLError(getRuntime(), ioe.getMessage());
    }
    DERSequence v1 = (DERSequence) (((DERSequence) crl_v).getObjectAt(0));
    ASN1EncodableVector build1 = new ASN1EncodableVector();
    int copyIndex = 0;
    if (v1.getObjectAt(0) instanceof DERInteger) {
      copyIndex++;
    }
    build1.add(new DERInteger(new java.math.BigInteger(version.toString())));
    while (copyIndex < v1.size()) {
      build1.add(v1.getObjectAt(copyIndex++));
    }
    ASN1EncodableVector build2 = new ASN1EncodableVector();
    build2.add(new DERSequence(build1));
    build2.add(((DERSequence) crl_v).getObjectAt(1));
    build2.add(((DERSequence) crl_v).getObjectAt(2));
    crl_v = new DERSequence(build2);
    changed = false;
    return this;
  }