Example #1
0
  protected LoadServiceResource tryResourceAsIs(String namePlusSuffix) throws RaiseException {
    LoadServiceResource foundResource = null;

    try {
      if (!Ruby.isSecurityRestricted()) {
        String reportedPath = namePlusSuffix;
        File actualPath;
        // we check length == 0 for 'load', which does not use load path
        if (new File(reportedPath).isAbsolute()) {
          // it's an absolute path, use it as-is
          actualPath =
              new File(RubyFile.expandUserPath(runtime.getCurrentContext(), namePlusSuffix));
        } else {
          // prepend ./ if . is not already there, since we're loading based on CWD
          if (reportedPath.charAt(0) == '.' && reportedPath.charAt(1) == '/') {
            reportedPath = reportedPath.replaceFirst("\\./", runtime.getCurrentDirectory());
          }

          actualPath =
              JRubyFile.create(
                  runtime.getCurrentDirectory(),
                  RubyFile.expandUserPath(runtime.getCurrentContext(), namePlusSuffix));
        }
        debugLogTry("resourceAsIs", actualPath.toString());
        if (actualPath.isFile() && actualPath.canRead()) {
          foundResource = new LoadServiceResource(actualPath, reportedPath);
          debugLogFound(foundResource);
        }
      }
    } catch (SecurityException secEx) {
    }

    return foundResource;
  }
Example #2
0
    public static IRubyObject prepareRubyDateTimeFromSqlTimestamp(Ruby runtime,Timestamp stamp){

       if (stamp.getTime() == 0) {
           return runtime.getNil();
       }

       gregCalendar.setTime(stamp);
       int month = gregCalendar.get(Calendar.MONTH);
       month++; // In Calendar January == 0, etc...

       int zoneOffset = gregCalendar.get(Calendar.ZONE_OFFSET)/3600000;
       RubyClass klazz = runtime.fastGetClass("DateTime");

       IRubyObject rbOffset = runtime.fastGetClass("Rational")
                .callMethod(runtime.getCurrentContext(), "new",new IRubyObject[]{
            runtime.newFixnum(zoneOffset),runtime.newFixnum(24)
        });

       return klazz.callMethod(runtime.getCurrentContext() , "civil",
                 new IRubyObject []{runtime.newFixnum(gregCalendar.get(Calendar.YEAR)),
                 runtime.newFixnum(month),
                 runtime.newFixnum(gregCalendar.get(Calendar.DAY_OF_MONTH)),
                 runtime.newFixnum(gregCalendar.get(Calendar.HOUR_OF_DAY)),
                 runtime.newFixnum(gregCalendar.get(Calendar.MINUTE)),
                 runtime.newFixnum(gregCalendar.get(Calendar.SECOND)),
                 rbOffset});
    }
Example #3
0
 // When a document is created from fragment with a context (reference) document,
 // namespace should be resolved based on the context document.
 public XmlDocument(Ruby ruby, RubyClass klass, Document document, XmlDocument contextDoc) {
   super(ruby, klass, document);
   nsCache = contextDoc.getNamespaceCache();
   XmlNamespace default_ns = nsCache.getDefault();
   String default_href = (String) (default_ns.href(ruby.getCurrentContext())).toJava(String.class);
   resolveNamespaceIfNecessary(
       ruby.getCurrentContext(), document.getDocumentElement(), default_href);
 }
Example #4
0
  protected static String printBacktraceRubinius(RubyException exception) {
    Ruby runtime = exception.getRuntime();
    ThreadContext.RubyStackTraceElement[] frames = exception.getBacktraceElements();

    ArrayList firstParts = new ArrayList();
    int longestFirstPart = 0;
    for (ThreadContext.RubyStackTraceElement frame : frames) {
      String firstPart = frame.getClassName() + "#" + frame.getMethodName();
      if (firstPart.length() > longestFirstPart) longestFirstPart = firstPart.length();
      firstParts.add(firstPart);
    }

    // determine spacing
    int center =
        longestFirstPart
            + 2 // initial spaces
            + 1; // spaces before "at"

    StringBuilder buffer = new StringBuilder();

    buffer.append("An exception has occurred:\n").append("    ");

    if (exception.getMetaClass() == runtime.getRuntimeError()
        && exception.message(runtime.getCurrentContext()).toString().length() == 0) {
      buffer.append("No current exception (RuntimeError)");
    } else {
      buffer.append(exception.message(runtime.getCurrentContext()).toString());
    }

    buffer.append('\n').append('\n').append("Backtrace:\n");

    int i = 0;
    for (ThreadContext.RubyStackTraceElement frame : frames) {
      String firstPart = (String) firstParts.get(i);
      String secondPart = frame.getFileName() + ":" + frame.getLineNumber();

      if (i == 0) {
        buffer.append(FIRST_COLOR);
      } else if (frame.isBinding() || frame.getFileName().equals("(eval)")) {
        buffer.append(EVAL_COLOR);
      } else if (frame.getFileName().indexOf(".java") != -1) {
        buffer.append(KERNEL_COLOR);
      }
      buffer.append("  ");
      for (int j = 0; j < center - firstPart.length(); j++) {
        buffer.append(' ');
      }
      buffer.append(firstPart);
      buffer.append(" at ");
      buffer.append(secondPart);
      buffer.append(CLEAR_COLOR);
      buffer.append('\n');
      i++;
    }

    return buffer.toString();
  }
Example #5
0
 public void testStrConvEncThatGrows() throws Exception {
   String javaStr = "--- こんにちは!";
   RubyString rubyStr = RubyString.newString(runtime, javaStr);
   rubyStr =
       EncodingUtils.strConvEnc(
           runtime.getCurrentContext(), rubyStr, rubyStr.getEncoding(), SJISEncoding.INSTANCE);
   assertEquals(rubyStr.getEncoding(), SJISEncoding.INSTANCE);
   rubyStr =
       EncodingUtils.strConvEnc(
           runtime.getCurrentContext(), rubyStr, SJISEncoding.INSTANCE, UTF8Encoding.INSTANCE);
   assertEquals(rubyStr.getEncoding(), UTF8Encoding.INSTANCE);
 }
Example #6
0
  public static void createX509Store(Ruby runtime, RubyModule mX509) {
    RubyClass cX509Store =
        mX509.defineClassUnder("Store", runtime.getObject(), X509STORE_ALLOCATOR);
    RubyClass openSSLError = runtime.getModule("OpenSSL").getClass("OpenSSLError");
    mX509.defineClassUnder("StoreError", openSSLError, openSSLError.getAllocator());
    cX509Store.addReadWriteAttribute(runtime.getCurrentContext(), "verify_callback");
    cX509Store.addReadWriteAttribute(runtime.getCurrentContext(), "error");
    cX509Store.addReadWriteAttribute(runtime.getCurrentContext(), "error_string");
    cX509Store.addReadWriteAttribute(runtime.getCurrentContext(), "chain");
    cX509Store.defineAnnotatedMethods(X509Store.class);

    X509StoreCtx.createX509StoreCtx(runtime, mX509);
  }
Example #7
0
  protected LoadServiceResource tryResourceFromCWD(
      SearchState state, String baseName, SuffixType suffixType) throws RaiseException {
    LoadServiceResource foundResource = null;

    for (String suffix : suffixType.getSuffixes()) {
      String namePlusSuffix = baseName + suffix;
      // check current directory; if file exists, retrieve URL and return resource
      try {
        JRubyFile file =
            JRubyFile.create(
                runtime.getCurrentDirectory(),
                RubyFile.expandUserPath(runtime.getCurrentContext(), namePlusSuffix));
        debugLogTry("resourceFromCWD", file.toString());
        if (file.isFile() && file.isAbsolute() && file.canRead()) {
          boolean absolute = true;
          String s = namePlusSuffix;
          if (!namePlusSuffix.startsWith("./")) {
            s = "./" + s;
          }
          foundResource = new LoadServiceResource(file, s, absolute);
          debugLogFound(foundResource);
          state.loadName = resolveLoadName(foundResource, namePlusSuffix);
          break;
        }
      } catch (IllegalArgumentException illArgEx) {
      } catch (SecurityException secEx) {
      }
    }

    return foundResource;
  }
Example #8
0
 public int call(Object a1, Object a2) throws Exception {
   StoreContext ctx = (StoreContext) a2;
   int ok = ((Integer) a1).intValue();
   IRubyObject proc = (IRubyObject) ctx.getExtraData(1);
   if (null == proc) {
     proc = (IRubyObject) ctx.ctx.getExtraData(0);
   }
   if (null == proc) {
     return ok;
   }
   if (!proc.isNil()) {
     Ruby rt = proc.getRuntime();
     RubyClass cStoreContext = Utils.getClassFromPath(rt, "OpenSSL::X509::StoreContext");
     X509StoreCtx rctx = new X509StoreCtx(rt, cStoreContext, ctx);
     RubyBoolean rok = rt.newBoolean(ok != 0);
     IRubyObject ret =
         proc.callMethod(rt.getCurrentContext(), "call", new IRubyObject[] {rok, rctx});
     if (ret.isTrue()) {
       ctx.setError(X509Utils.V_OK);
       ok = 1;
     } else {
       if (ctx.getError() == X509Utils.V_OK) {
         ctx.setError(X509Utils.V_ERR_CERT_REJECTED);
       }
       ok = 0;
     }
   }
   return ok;
 }
 private IRubyObject callEachType(
     MethodType type, IRubyObject rubyReceiver, String methodName, Block block, Object... args) {
   Ruby runtime = rubyReceiver.getRuntime();
   IRubyObject[] rubyArgs = null;
   if (args != null && args.length > 0) {
     rubyArgs = JavaUtil.convertJavaArrayToRuby(runtime, args);
     for (int i = 0; i < rubyArgs.length; i++) {
       IRubyObject obj = rubyArgs[i];
       if (obj instanceof JavaObject) {
         rubyArgs[i] = Java.wrap(runtime, obj);
       }
     }
   }
   ThreadContext context = runtime.getCurrentContext();
   switch (type) {
     case CALLMETHOD_NOARG:
       return RuntimeHelpers.invoke(context, rubyReceiver, methodName);
     case CALLMETHOD:
       return RuntimeHelpers.invoke(context, rubyReceiver, methodName, rubyArgs);
     case CALLMETHOD_WITHBLOCK:
       return RuntimeHelpers.invoke(context, rubyReceiver, methodName, rubyArgs, block);
     case CALLSUPER:
       return RuntimeHelpers.invokeSuper(context, rubyReceiver, rubyArgs, Block.NULL_BLOCK);
     case CALLSUPER_WITHBLOCK:
       return RuntimeHelpers.invokeSuper(context, rubyReceiver, rubyArgs, block);
     default:
       break;
   }
   return null;
 }
Example #10
0
  public static IRubyObject interpretCommonEval(
      Ruby runtime,
      String file,
      int lineNumber,
      String backtraceName,
      RootNode rootNode,
      IRubyObject self,
      Block block) {
    // SSS FIXME: Is this required here since the IR version cannot change from eval-to-eval? This
    // is much more of a global setting.
    boolean is_1_9 = runtime.is1_9();
    if (is_1_9) IRBuilder.setRubyVersion("1.9");

    StaticScope ss = rootNode.getStaticScope();
    IRScope containingIRScope = getEvalContainerScope(runtime, ss);
    IREvalScript evalScript =
        IRBuilder.createIRBuilder(runtime, runtime.getIRManager())
            .buildEvalRoot(ss, containingIRScope, file, lineNumber, rootNode);
    evalScript.prepareForInterpretation(false);
    //        evalScript.runCompilerPass(new CallSplitter());
    ThreadContext context = runtime.getCurrentContext();
    runBeginEndBlocks(
        evalScript.getBeginBlocks(), context, self, null); // FIXME: No temp vars yet right?
    IRubyObject rv =
        evalScript.call(
            context,
            self,
            evalScript.getStaticScope().getModule(),
            rootNode.getScope(),
            block,
            backtraceName);
    runBeginEndBlocks(evalScript.getEndBlocks(), context, self, null); // FIXME: No temp vars right?
    return rv;
  }
  private <T> T call(
      MethodType type,
      Class<T> returnType,
      Object receiver,
      String methodName,
      Block block,
      EmbedEvalUnit unit,
      Object... args) {
    if (methodName == null || methodName.length() == 0) {
      return null;
    }
    Ruby runtime = container.getProvider().getRuntime();
    RubyObject rubyReceiver = getReceiverObject(runtime, receiver);

    boolean sharing_variables = true;
    Object obj = container.getAttribute(AttributeName.SHARING_VARIABLES);
    if (obj != null && obj instanceof Boolean && ((Boolean) obj) == false) {
      sharing_variables = false;
    }
    try {
      if (sharing_variables) {
        ManyVarsDynamicScope scope;
        if (unit != null && unit.getScope() != null) scope = unit.getScope();
        else scope = EmbedRubyRuntimeAdapterImpl.getManyVarsDynamicScope(container, 0);
        container.getVarMap().inject(scope, 0, rubyReceiver);
        runtime.getCurrentContext().pushScope(scope);
      }
      IRubyObject result = callEachType(type, rubyReceiver, methodName, block, args);
      if (sharing_variables) {
        container.getVarMap().retrieve(rubyReceiver);
      }
      if (!(result instanceof RubyNil) && returnType != null) {
        Object ret = JavaEmbedUtils.rubyToJava(runtime, result, returnType);
        return ret != null ? returnType.cast(ret) : null;
      }
      return null;
    } catch (RaiseException e) {
      runtime.printError(e.getException());
      throw new InvokeFailedException(e.getMessage(), e);
    } catch (Throwable e) {
      throw new InvokeFailedException(e);
    } finally {
      if (sharing_variables) {
        runtime.getCurrentContext().popScope();
      }
    }
  }
Example #12
0
  public static RaiseException argTypesDoNotMatch(
      Ruby runtime, IRubyObject receiver, JavaCallable[] methods, Object... args) {
    Class[] argTypes = new Class[args.length];
    for (int i = 0; i < args.length; i++) {
      argTypes[i] = argClassTypeError(args[i]);
    }

    return argumentError(runtime.getCurrentContext(), methods, receiver, argTypes);
  }
Example #13
0
    @JRubyMethod(name = "pop")
    @SuppressWarnings("unchecked")
    public static IRubyObject s_pop(IRubyObject recv) throws Exception {
      Ruby runtime = recv.getRuntime();
      ConsoleHolder holder = getHolder(runtime);

      if (holder.history.size() == 0) return runtime.getNil();

      return runtime.newString((String) holder.history.pop()).taint(runtime.getCurrentContext());
    }
Example #14
0
    @JRubyMethod(name = "each")
    public static IRubyObject s_hist_each(IRubyObject recv, Block block) {
      Ruby runtime = recv.getRuntime();
      ThreadContext context = runtime.getCurrentContext();
      ConsoleHolder holder = getHolder(runtime);

      for (Iterator i = holder.history.getHistoryList().iterator(); i.hasNext(); ) {
        block.yield(context, runtime.newString((String) i.next()).taint(context));
      }
      return recv;
    }
Example #15
0
  /**
   * Retrieves the Handle object associated with a {@link RubyObject}. Retrieval is either done
   * through the {@link GC} for Handles that have already been created, or depending on the object's
   * native class index.<br>
   * Fixnum's and Symbol's native Handles are created through bit-shifting on their values, File and
   * Float Handles are created using special JNI methods. All other objects are passed to the
   * generic {@link Native#newHandle} method.<br>
   * Once a Handle has been created, it is registered with the {@link GC} to prevent
   * garbage-collection during native method runs.
   */
  static Handle valueOf(IRubyObject obj) {
    Handle h = GC.lookup(obj);
    if (h != null) {
      return h;
    }

    Ruby runtime = obj.getRuntime();
    long nativeHandle;

    if (obj instanceof RubyObject) {
      int type = ((RubyObject) obj).getNativeTypeIndex();
      switch (type) {
        case ClassIndex.FIXNUM:
          {
            final long val = ((RubyFixnum) obj).getLongValue();
            nativeHandle =
                (val <= FIXNUM_MAX && val >= FIXNUM_MIN)
                    ? ((val << FIXNUM_SHIFT) | FIXNUM_FLAG)
                    : Native.getInstance(runtime).newFixnumHandle(obj, val);
          }
          break;

        case ClassIndex.FLOAT:
          nativeHandle =
              Native.getInstance(runtime).newFloatHandle(obj, ((RubyNumeric) obj).getDoubleValue());
          break;

        case ClassIndex.SYMBOL:
          nativeHandle = ((long) ((RubySymbol) obj).getId() << SYMBOL_SHIFT) | SYMBOL_FLAG;
          break;

        case ClassIndex.FILE: // RubyIO uses FILE as type index, matching MRI's T_FILE
          nativeHandle =
              Native.getInstance(runtime)
                  .newIOHandle(
                      obj,
                      (int) ((RubyIO) obj).fileno(runtime.getCurrentContext()).getLongValue(),
                      ((RubyIO) obj).getOpenFile().getMode());
          break;

        default:
          nativeHandle = Native.getInstance(runtime).newHandle(obj, type);
          break;
      }
    } else {
      nativeHandle = Native.getInstance(runtime).newHandle(obj, ClassIndex.OBJECT);
    }

    Handle handle = newHandle(runtime, obj, nativeHandle);

    GC.register(obj, handle);

    return handle;
  }
Example #16
0
 public Object invoke(Object proxy, JavaProxyMethod method, Object[] nargs) throws Throwable {
   final int length = nargs == null ? 0 : nargs.length;
   final IRubyObject[] rubyArgs = new IRubyObject[length + 2];
   rubyArgs[0] = JavaObject.wrap(runtime, proxy);
   rubyArgs[1] = method;
   for (int i = 0; i < length; i++) {
     rubyArgs[i + 2] = JavaUtil.convertJavaToRuby(runtime, nargs[i]);
   }
   IRubyObject procResult = proc.call(runtime.getCurrentContext(), rubyArgs);
   return procResult.toJava(method.getReturnType());
 }
Example #17
0
  protected LoadServiceResource tryResourceFromLoadPath(String namePlusSuffix, String loadPathEntry)
      throws RaiseException {
    LoadServiceResource foundResource = null;

    try {
      if (!Ruby.isSecurityRestricted()) {
        String reportedPath = loadPathEntry + "/" + namePlusSuffix;
        JRubyFile actualPath;
        boolean absolute = false;
        // we check length == 0 for 'load', which does not use load path
        if (new File(reportedPath).isAbsolute()) {
          absolute = true;
          // it's an absolute path, use it as-is
          actualPath =
              JRubyFile.create(
                  loadPathEntry,
                  RubyFile.expandUserPath(runtime.getCurrentContext(), namePlusSuffix));
        } else {
          absolute = false;
          // prepend ./ if . is not already there, since we're loading based on CWD
          if (reportedPath.charAt(0) != '.') {
            reportedPath = "./" + reportedPath;
          }
          actualPath =
              JRubyFile.create(
                  JRubyFile.create(runtime.getCurrentDirectory(), loadPathEntry).getAbsolutePath(),
                  RubyFile.expandUserPath(runtime.getCurrentContext(), namePlusSuffix));
        }
        debugLogTry(
            "resourceFromLoadPath",
            "'" + actualPath.toString() + "' " + actualPath.isFile() + " " + actualPath.canRead());
        if (actualPath.isFile() && actualPath.canRead()) {
          foundResource = new LoadServiceResource(actualPath, reportedPath, absolute);
          debugLogFound(foundResource);
        }
      }
    } catch (SecurityException secEx) {
    }

    return foundResource;
  }
Example #18
0
    @JRubyMethod(name = "shift")
    public static IRubyObject s_hist_shift(IRubyObject recv) {
      Ruby runtime = recv.getRuntime();
      ConsoleHolder holder = getHolder(runtime);

      if (holder.history.size() == 0) return runtime.getNil();

      try {
        return runtime.newString(holder.history.remove(0)).taint(runtime.getCurrentContext());
      } catch (IndexOutOfBoundsException ioobe) {
        throw runtime.newIndexError("history shift error");
      }
    }
Example #19
0
  public void init(List additionalDirectories) {
    loadPath = RubyArray.newArray(runtime);
    loadedFeatures = RubyArray.newArray(runtime);
    loadedFeaturesInternal = Collections.synchronizedList(loadedFeatures);

    // add all startup load paths to the list first
    for (Iterator iter = additionalDirectories.iterator(); iter.hasNext(); ) {
      addPath((String) iter.next());
    }

    // add $RUBYLIB paths
    RubyHash env = (RubyHash) runtime.getObject().fastGetConstant("ENV");
    RubyString env_rubylib = runtime.newString("RUBYLIB");
    if (env.has_key_p(env_rubylib).isTrue()) {
      String rubylib = env.op_aref(runtime.getCurrentContext(), env_rubylib).toString();
      String[] paths = rubylib.split(File.pathSeparator);
      for (int i = 0; i < paths.length; i++) {
        addPath(paths[i]);
      }
    }

    // wrap in try/catch for security exceptions in an applet
    if (!Ruby.isSecurityRestricted()) {
      try {
        String jrubyHome = runtime.getJRubyHome();
        if (jrubyHome != null) {
          char sep = '/';
          String rubyDir = jrubyHome + sep + "lib" + sep + "ruby" + sep;

          // If we're running in 1.9 compat mode, add Ruby 1.9 libs to path before 1.8 libs
          if (runtime.is1_9()) {
            addPath(rubyDir + "site_ruby" + sep + Constants.RUBY1_9_MAJOR_VERSION);
            addPath(rubyDir + "site_ruby" + sep + "shared");
            addPath(rubyDir + "site_ruby" + sep + Constants.RUBY_MAJOR_VERSION);
            addPath(rubyDir + Constants.RUBY1_9_MAJOR_VERSION);
          } else {
            // Add 1.8 libs
            addPath(rubyDir + "site_ruby" + sep + Constants.RUBY_MAJOR_VERSION);
            addPath(rubyDir + "site_ruby" + sep + "shared");
            addPath(rubyDir + Constants.RUBY_MAJOR_VERSION);
          }
        }
      } catch (SecurityException e) {
      }
    }

    // "." dir is used for relative path loads from a given file, as in require '../foo/bar'
    if (runtime.getSafeLevel() == 0) {
      addPath(".");
    }
  }
Example #20
0
 private IRubyObject defaultTmpDir(Ruby runtime, IRubyObject[] args) {
   IRubyObject dir = null;
   if (args.length == 2) {
     dir = args[1];
   } else {
     // Dir::tmpdir
     runtime.getLoadService().require("tmpdir");
     dir = runtime.getDir().callMethod(runtime.getCurrentContext(), "tmpdir");
   }
   if (runtime.getSafeLevel() > 0 && dir.isTaint()) {
     dir = runtime.newString(DEFAULT_TMP_DIR);
   }
   return dir;
 }
Example #21
0
  @JRubyMethod(required = 1, optional = 1, visibility = PRIVATE)
  @Override
  public IRubyObject initialize(IRubyObject[] args, Block block) {
    Ruby runtime = getRuntime();
    IRubyObject basename = args[0];
    IRubyObject dir = defaultTmpDir(runtime, args);

    File tmp = null;
    synchronized (tmpFileLock) {
      while (true) {
        try {
          if (counter == -1) {
            counter = RND.nextInt() & 0xffff;
          }
          counter++;

          // We do this b/c make_tmpname might be overridden
          IRubyObject tmpname =
              callMethod(
                  runtime.getCurrentContext(),
                  "make_tmpname",
                  new IRubyObject[] {basename, runtime.newFixnum(counter)});
          tmp =
              JRubyFile.create(
                  getRuntime().getCurrentDirectory(),
                  new File(dir.convertToString().toString(), tmpname.convertToString().toString())
                      .getPath());
          if (tmp.createNewFile()) {
            tmpFile = tmp;
            path = tmp.getPath();
            try {
              tmpFile.deleteOnExit();
            } catch (NullPointerException npe) {
              // See JRUBY-4624.
              // Due to JDK bug, NPE could be thrown
              // when shutdown is in progress.
              // Do nothing.
            } catch (IllegalStateException ise) {
              // do nothing, shutdown in progress
            }
            initializeOpen();
            referenceSet.put(reaper = new Reaper(this, runtime, tmpFile, openFile), Boolean.TRUE);
            return this;
          }
        } catch (IOException e) {
          throw runtime.newIOErrorFromException(e);
        }
      }
    }
  }
Example #22
0
  /**
   * instantiateClass
   *
   * @param runtime
   * @param name
   * @param args
   * @return
   */
  public static IRubyObject instantiateClass(Ruby runtime, String name, IRubyObject... args) {
    ThreadContext threadContext = runtime.getCurrentContext();
    IRubyObject result = null;

    // try to load the class
    RubyClass rubyClass = runtime.getClass(name);

    // instantiate it, if it exists
    if (rubyClass != null) {
      result = rubyClass.newInstance(threadContext, args, Block.NULL_BLOCK);
    }

    return result;
  }
Example #23
0
    private IRubyObject invokeRuby(
        final DynamicMethod method,
        final JavaProxyMethod proxyMethod,
        final RubyClass metaClass,
        final String name,
        final Object[] nargs) {
      final IRubyObject[] newArgs = new IRubyObject[nargs.length];
      for (int i = nargs.length; --i >= 0; ) {
        newArgs[i] = JavaUtil.convertJavaToUsableRubyObject(runtime, nargs[i]);
      }

      final int arity = method.getArity().getValue();

      if (arity < 0 || arity == newArgs.length) {
        final ThreadContext context = runtime.getCurrentContext();
        return method.call(context, self, metaClass, name, newArgs);
      }
      if (proxyMethod.hasSuperImplementation()) {
        final ThreadContext context = runtime.getCurrentContext();
        final RubyClass superClass = metaClass.getSuperClass();
        return Helpers.invokeAs(context, superClass, self, name, newArgs, Block.NULL_BLOCK);
      }
      throw runtime.newArgumentError(newArgs.length, arity);
    }
Example #24
0
  protected LoadServiceResource tryResourceFromHome(
      SearchState state, String baseName, SuffixType suffixType) throws RaiseException {
    LoadServiceResource foundResource = null;

    RubyHash env = (RubyHash) runtime.getObject().fastGetConstant("ENV");
    RubyString env_home = runtime.newString("HOME");
    if (env.has_key_p(env_home).isFalse()) {
      return null;
    }
    String home = env.op_aref(runtime.getCurrentContext(), env_home).toString();
    String path = baseName.substring(2);

    for (String suffix : suffixType.getSuffixes()) {
      String namePlusSuffix = path + suffix;
      // check home directory; if file exists, retrieve URL and return resource
      try {
        JRubyFile file =
            JRubyFile.create(
                home, RubyFile.expandUserPath(runtime.getCurrentContext(), namePlusSuffix));
        debugLogTry("resourceFromHome", file.toString());
        if (file.isFile() && file.isAbsolute() && file.canRead()) {
          boolean absolute = true;
          String s = "~/" + namePlusSuffix;

          foundResource = new LoadServiceResource(file, s, absolute);
          debugLogFound(foundResource);
          state.loadName = resolveLoadName(foundResource, s);
          break;
        }
      } catch (IllegalArgumentException illArgEx) {
      } catch (SecurityException secEx) {
      }
    }

    return foundResource;
  }
Example #25
0
    @JRubyMethod(name = "[]")
    public static IRubyObject s_hist_get(IRubyObject recv, IRubyObject index) {
      Ruby runtime = recv.getRuntime();
      ConsoleHolder holder = getHolder(runtime);
      int i = (int) index.convertToInteger().getLongValue();

      if (i < 0) i += holder.history.size();

      try {
        ThreadContext context = runtime.getCurrentContext();

        return runtime.newString((String) holder.history.getHistoryList().get(i)).taint(context);
      } catch (IndexOutOfBoundsException ioobe) {
        throw runtime.newIndexError("invalid history index: " + i);
      }
    }
Example #26
0
    @JRubyMethod(name = "delete_at")
    public static IRubyObject s_hist_delete_at(IRubyObject recv, IRubyObject index) {
      Ruby runtime = recv.getRuntime();
      ThreadContext context = runtime.getCurrentContext();

      ConsoleHolder holder = getHolder(runtime);
      int i = RubyNumeric.num2int(index);

      if (i < 0) i += holder.history.size();

      try {
        return runtime.newString(holder.history.remove(i)).taint(context);
      } catch (IndexOutOfBoundsException ioobe) {
        throw runtime.newIndexError("invalid history index: " + i);
      }
    }
Example #27
0
    public static IRubyObject prepareRubyDateFromSqlDate(Ruby runtime,Date date){

       if (date.getTime() == 0) {
           return runtime.getNil();
       }

       gregCalendar.setTime(date);
       int month = gregCalendar.get(Calendar.MONTH);
       month++; // In Calendar January == 0, etc...
       RubyClass klazz = runtime.fastGetClass("Date");
       return klazz.callMethod(
                 runtime.getCurrentContext() ,"civil",
                 new IRubyObject []{ runtime.newFixnum(gregCalendar.get(Calendar.YEAR)),
                 runtime.newFixnum(month),
                 runtime.newFixnum(gregCalendar.get(Calendar.DAY_OF_MONTH))});
    }
Example #28
0
  /**
   * Output a log message
   *
   * @param logMessage
   * @param executionTime
   */
  private void debug(String logMessage, Long executionTime) {
    Ruby runtime = getRuntime();
    Connection connection_instance = (Connection) api.getInstanceVariable(this, "@connection");
    RubyModule doModule = runtime.getModule(DATA_OBJECTS_MODULE_NAME);
    RubyClass loggerClass = doModule.getClass("Logger");
    RubyClass messageClass = loggerClass.getClass("Message");

    IRubyObject loggerMsg =
        messageClass.newInstance(
            runtime.getCurrentContext(),
            runtime.newString(logMessage), // query
            runtime.newString(""), // start
            runtime.newFixnum(executionTime), // duration
            Block.NULL_BLOCK);

    api.callMethod(connection_instance, "log", loggerMsg);
  }
Example #29
0
  public static void createReadline(Ruby runtime) throws IOException {
    ConsoleHolder holder = new ConsoleHolder();
    holder.history = new ReadlineHistory();
    holder.currentCompletor = null;
    COMPLETION_CASE_FOLD = runtime.getNil();

    RubyModule mReadline = runtime.defineModule("Readline");

    mReadline.dataWrapStruct(holder);

    mReadline.defineAnnotatedMethods(Readline.class);
    IRubyObject hist = runtime.getObject().callMethod(runtime.getCurrentContext(), "new");
    mReadline.fastSetConstant("HISTORY", hist);
    hist.getSingletonClass().includeModule(runtime.getEnumerable());
    hist.getSingletonClass().defineAnnotatedMethods(HistoryMethods.class);

    // MRI does similar thing on MacOS X with 'EditLine wrapper'.
    mReadline.fastSetConstant("VERSION", runtime.newString("JLine wrapper"));
  }
Example #30
0
  public static IRubyObject interpret(Ruby runtime, Node rootNode, IRubyObject self) {
    if (runtime.is1_9()) IRBuilder.setRubyVersion("1.9");

    IRScriptBody root =
        (IRScriptBody)
            IRBuilder.createIRBuilder(runtime, runtime.getIRManager())
                .buildRoot((RootNode) rootNode);

    // We get the live object ball rolling here.  This give a valid value for the top
    // of this lexical tree.  All new scope can then retrieve and set based on lexical parent.
    if (root.getStaticScope().getModule() == null) { // If an eval this may already be setup.
      root.getStaticScope().setModule(runtime.getObject());
    }

    RubyModule currModule = root.getStaticScope().getModule();

    // Scope state for root?
    IRStaticScopeFactory.newIRLocalScope(null).setModule(currModule);
    ThreadContext context = runtime.getCurrentContext();

    try {
      runBeginEndBlocks(
          root.getBeginBlocks(), context, self, null); // FIXME: No temp vars yet...not needed?
      InterpretedIRMethod method = new InterpretedIRMethod(root, currModule);
      IRubyObject rv = method.call(context, self, currModule, "(root)", IRubyObject.NULL_ARRAY);
      runBeginEndBlocks(
          root.getEndBlocks(), context, self, null); // FIXME: No temp vars yet...not needed?
      if ((IRRuntimeHelpers.isDebug() || IRRuntimeHelpers.inProfileMode())
          && interpInstrsCount > 10000) {
        LOG.info("-- Interpreted instructions: {}", interpInstrsCount);
        /*
        for (Operation o: opStats.keySet()) {
            System.out.println(o + " = " + opStats.get(o).count);
        }
        */
      }
      return rv;
    } catch (IRBreakJump bj) {
      throw IRException.BREAK_LocalJumpError.getException(context.runtime);
    }
  }