Ejemplo n.º 1
0
 private void initContainer() {
   container = makeContainer(getConfig());
   logger.info("new JRuby runtime: {}", container);
   container.runScriptlet("require 'rubylet_helper'");
   helper = container.runScriptlet("RubyletHelper.new");
   boot();
 }
Ejemplo n.º 2
0
 JRubyVerticle(String scriptName, ClassLoader cl) {
   this.container = new ScriptingContainer(LocalContextScope.SINGLETHREAD);
   container.setClassLoader(cl);
   // Prevent JRuby from logging errors to stderr - we want to log ourselves
   container.setErrorWriter(new NullWriter());
   this.cl = cl;
   this.scriptName = scriptName;
 }
Ejemplo n.º 3
0
 Engine(File root) {
   List<String> loadPaths = new ArrayList<String>();
   loadPaths.add(new File(root, "lib").getAbsolutePath());
   for (VirtualFile vf : Play.roots) {
     loadPaths.add(new File(vf.getRealFile(), "public/stylesheets").getAbsolutePath());
   }
   scriptingContainer = new ScriptingContainer();
   scriptingContainer.getProvider().setLoadPaths(loadPaths);
   scriptingContainer.setErrorWriter(errors);
 }
Ejemplo n.º 4
0
 @Test
 public void testEachArrayList() {
   List<Object> list = new ArrayList<Object>();
   list.add("one");
   list.add("two");
   ScriptingContainer container = new ScriptingContainer();
   container.put("list", list);
   String each = "list.each do |v|\n" + "  puts v\n" + "end";
   container.runScriptlet(each);
 }
  // Preload classes that will be needed to test the Ruby submission in the
  // IsolatedTask.
  static {
    new RubyTester();
    TestResultUtil.createResultForTimeout();

    // Compile and run a trivial ruby script, so that all needed JRuby classes are loaded
    ScriptingContainer container = new ScriptingContainer(LocalContextScope.SINGLETHREAD);
    Object result = container.runScriptlet("true");
    if (!(result instanceof Boolean) || !(Boolean) result) {
      throw new InternalBuilderException(
          TestRubyMethodBuildStep.class, "Failed to execute trivial Ruby script");
    }
  }
 public IRubyObject getInstanceVariable(IRubyObject obj, String variableName) {
   BiVariableMap map = container.getVarMap();
   synchronized (map) {
     if (map.containsKey(variableName)) {
       BiVariable bv =
           map.getVariable(
               (RubyObject) container.getProvider().getRuntime().getTopSelf(), variableName);
       return bv.getRubyObject();
     }
   }
   return null;
 }
 public IRubyObject setInstanceVariable(IRubyObject obj, String variableName, IRubyObject value) {
   BiVariableMap map = container.getVarMap();
   synchronized (map) {
     if (map.containsKey(variableName)) {
       BiVariable bv =
           map.getVariable(
               (RubyObject) container.getProvider().getRuntime().getTopSelf(), variableName);
       bv.setRubyObject(value);
     } else {
       InstanceVariable iv = new InstanceVariable(obj, variableName, value);
       map.update(variableName, iv);
     }
   }
   return obj.getInstanceVariables().setInstanceVariable(variableName, value);
 }
Ejemplo n.º 8
0
  public <T> T newPlugin(Class<T> iface, PluginType type) throws PluginSourceNotMatchException {
    String name = type.getName();

    String category;
    if (InputPlugin.class.isAssignableFrom(iface)) {
      category = "input";
    } else if (OutputPlugin.class.isAssignableFrom(iface)) {
      category = "output";
    } else if (ParserPlugin.class.isAssignableFrom(iface)) {
      category = "parser";
    } else if (FormatterPlugin.class.isAssignableFrom(iface)) {
      category = "formatter";
    } else if (DecoderPlugin.class.isAssignableFrom(iface)) {
      category = "decoder";
    } else if (EncoderPlugin.class.isAssignableFrom(iface)) {
      category = "encoder";
    } else if (FilterPlugin.class.isAssignableFrom(iface)) {
      category = "filter";
    } else if (GuessPlugin.class.isAssignableFrom(iface)) {
      category = "guess";
    } else if (ExecutorPlugin.class.isAssignableFrom(iface)) {
      category = "executor";
    } else {
      // unsupported plugin category
      throw new PluginSourceNotMatchException(
          "Plugin interface " + iface + " is not supported in JRuby");
    }

    String methodName = "new_java_" + category;
    try {
      return jruby.callMethod(rubyPluginManager, methodName, name, iface);
    } catch (InvokeFailedException ex) {
      throw new PluginSourceNotMatchException(ex.getCause());
    }
  }
  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();
      }
    }
  }
Ejemplo n.º 10
0
  @Inject
  public JRubyPluginSource(ScriptingContainer jruby) {
    this.jruby = jruby;

    // get Embulk::Plugin
    // this.rubyPluginManager = ((RubyModule) jruby.get("Embulk")).const_get(
    //        RubySymbol.newSymbol(
    //            jruby.getProvider().getRuntime(), "Plugin"));
    this.rubyPluginManager = jruby.runScriptlet("Embulk::Plugin");
  }
Ejemplo n.º 11
0
  private void setupJRuby(Activity startActivity) {
    System.setProperty("jruby.bytecode.version", "1.5");

    // enable proxy classes
    System.setProperty(
        "jruby.ji.proxyClassFactory", "com.rickbutton.rubydroid.DalvikProxyClassFactory");
    System.setProperty("jruby.ji.upper.case.package.name.allowed", "true");
    System.setProperty("jruby.class.cache.path", appContext.getDir("dex", 0).getAbsolutePath());

    // setup jruby home
    String apkName = getApkName();
    String jrubyHome = "file:" + apkName + "!/jruby.home";
    System.setProperty("jruby.home", jrubyHome);

    // configure jruby
    System.setProperty("jruby.compile.mode", "OFF"); // OFF OFFIR JITIR? FORCE FORCEIR
    // System.setProperty("jruby.compile.backend", "DALVIK");
    System.setProperty("jruby.bytecode.version", "1.6");
    System.setProperty("jruby.interfaces.useProxy", "true");
    System.setProperty("jruby.management.enabled", "false");
    System.setProperty("jruby.objectspace.enabled", "false");
    System.setProperty("jruby.thread.pooling", "true");
    System.setProperty("jruby.native.enabled", "false");
    System.setProperty("jruby.ir.passes", "LocalOptimizationPass,DeadCodeElimination");
    System.setProperty("jruby.backtrace.style", "normal"); // normal raw full mri

    ClassLoader loader = new PathClassLoader(apkName, RubySystem.class.getClassLoader());

    // disable gems
    RubyInstanceConfig config = new RubyInstanceConfig();
    config.setDisableGems(true);
    config.setLoader(loader);
    Ruby.newInstance(config);

    container =
        new ScriptingContainer(LocalContextScope.SINGLETON, LocalVariableBehavior.PERSISTENT);
    container.setClassLoader(loader);

    Thread.currentThread().setContextClassLoader(loader);

    if (appContext.getFilesDir() != null) {
      container.setCurrentDirectory(appContext.getFilesDir().getPath());
    }

    container.put("$package_name", appContext.getPackageName());

    container.put("app_context", appContext);
    container.put("system", this);
    rubyContext = container.runScriptlet(PathType.CLASSPATH, "ruby/droid/init.rb");

    Object mainActivity = container.get("MainActivity");
    container.callMethod(rubyContext, "start_ruby_activity", mainActivity, startActivity);
  }
Ejemplo n.º 12
0
 public void start() throws Exception {
   InputStream is = cl.getResourceAsStream(scriptName);
   if (is == null) {
     throw new IllegalArgumentException("Cannot find verticle: " + scriptName);
   }
   container.runScriptlet(is, scriptName);
   try {
     is.close();
   } catch (IOException ignore) {
   }
 }
Ejemplo n.º 13
0
  public static ScriptingContainer makeContainer(RubyConfig config) {
    // Required global setting for when JRuby fakes up Kernel.system('ruby')
    // calls.
    // Since this is global, other JRuby servlets in this servlet container
    // are affected...
    //
    // TODO: move to a better location in the code?  remove?
    if (config.getJrubyHome() != null) {
      System.setProperty("jruby.home", config.getJrubyHome());
    }

    final ScriptingContainer container = new ScriptingContainer(config.getScope());

    container.setCompileMode(config.getCompileMode());
    if (config.getJrubyHome() != null) {
      container.setHomeDirectory(config.getJrubyHome());
    }
    container.setCompatVersion(config.getCompatVersion());
    container.setCurrentDirectory(config.getAppRoot());
    // don't propagate ENV to global JVM level
    container.getProvider().getRubyInstanceConfig().setUpdateNativeENVEnabled(false);

    logger.info(
        "new ScriptingContainer scope={} compileMode={} jrubyHome={} compatVersion={}, pwd={}",
        new Object[] {
          config.getScope(),
          config.getCompileMode(),
          config.getJrubyHome(),
          config.getCompatVersion(),
          config.getAppRoot()
        });

    return container;
  }
Ejemplo n.º 14
0
 @Override
 public void buildWorld(List<String> gluePaths, World world) {
   this.world = world;
   jruby.put("$world", new Object());
   for (String gluePath : gluePaths) {
     Resources.scan(
         gluePath.replace('.', '/'),
         ".rb",
         new Consumer() {
           public void consume(Resource resource) {
             jruby.runScriptlet(resource.getReader(), resource.getPath());
           }
         });
   }
 }
Ejemplo n.º 15
0
 public void stop() throws Exception {
   try {
     // We call the script with receiver = null - this causes the method to be called on the top
     // level
     // script
     container.callMethod(null, "vertx_stop");
   } catch (InvokeFailedException e) {
     Throwable cause = e.getCause();
     if (cause instanceof RaiseException) {
       // Gosh, this is a bit long winded!
       RaiseException re = (RaiseException) cause;
       String msg = "(NoMethodError) undefined method `vertx_stop'";
       if (re.getMessage().startsWith(msg)) {
         // OK - method is not mandatory
         return;
       }
     }
     throw e;
   }
 }
Ejemplo n.º 16
0
 public double rms() {
   return (Double) rubyContainer.callMethod(waveform, "rms");
 }
Ejemplo n.º 17
0
 @Test
 public void testPuts_persist() {
   ScriptingContainer container = new ScriptingContainer();
   container.put("x", 12345);
   container.runScriptlet(puts_x);
 }
Ejemplo n.º 18
0
  public String compile(File css, boolean dev) {
    // Cache ?
    CachedCSS cachedCSS = cache.get(css);
    if (cachedCSS != null) {
      if (!dev || cachedCSS.isStillValid()) {
        return cachedCSS.css;
      }
    }

    // Paths
    sassPaths = new ArrayList<String>();
    sassPaths.add(Play.getFile("public/stylesheets").getAbsolutePath());
    StringBuffer extensions = new StringBuffer();
    for (VirtualFile vf : Play.modules.values()) {
      File style = new File(vf.getRealFile(), "public/stylesheets");
      sassPaths.add(style.getAbsolutePath());
      if (style.exists()) {
        for (File f : style.listFiles()) {
          if (f.isFile() && f.getName().endsWith(".rb")) {
            extensions.append(
                "require '" + f.getName().subSequence(0, f.getName().length() - 3) + "'\n");
          }
        }
      }
    }

    // Compute dependencies
    List<File> dependencies = new ArrayList<File>();
    findDependencies(css, dependencies);

    // Compile
    synchronized (Engine.class) {
      StringBuffer result = new StringBuffer();
      errors.getBuffer().setLength(0);
      scriptingContainer.put("@result", result);
      StringBuffer pathsToLoad = new StringBuffer("[");
      for (int i = 0; i < sassPaths.size(); i++) {
        pathsToLoad.append("'");
        pathsToLoad.append(sassPaths.get(i));
        pathsToLoad.append("'");
        if (i < sassPaths.size() - 1) {
          pathsToLoad.append(",");
        }
      }
      pathsToLoad.append("]");

      String syntax = css.getName().endsWith(".scss") ? ":scss" : ":sass";

      try {
        scriptingContainer.runScriptlet(
            script(
                "require 'sass'",
                extensions.toString(),
                "options = {}",
                "options[:load_paths] = " + pathsToLoad,
                "options[:syntax] = " + syntax,
                "options[:style] = " + (dev ? ":expanded" : ":compressed") + "",
                "options[:line_comments] = " + (dev ? "true" : "false") + "",
                "input = File.new('" + css.getAbsolutePath() + "', 'r')",
                "tree = ::Sass::Engine.new(input.read(), options).to_tree",
                "@result.append(tree.render)"));
      } catch (Exception e) {
        // Log ?
        String error = "";
        Matcher matcher = extractLog.matcher(errors.toString());
        while (matcher.find()) {
          error = matcher.group(1);
          Logger.error(error);
        }
        matcher = extractLog2.matcher(errors.toString());
        while (matcher.find()) {
          error = matcher.group(1).replace("(sass)", css.getName());
          Logger.error(error);
        }
        if (error.equals("")) {
          Logger.error(e, "SASS Error");
          error = "Check logs";
        }
        return "/** The CSS was not generated because the "
            + css.getName()
            + " file has errors; check logs **/\n\n"
            + "body:before {display: block; color: #c00; white-space: pre; font-family: monospace; background: #FDD9E1; border-top: 1px solid pink; border-bottom: 1px solid pink; padding: 10px; content: \"[SASS ERROR] "
            + error.replace("\"", "'")
            + "\"; }";
      }

      cachedCSS = new CachedCSS(result.toString(), dependencies);
      cache.put(css, cachedCSS);

      return cachedCSS.css;
    }
  }
 /*
  * (non-Javadoc)
  *
  * @see org.apollo.util.plugin.PluginEnvironment#parse(java.io.InputStream, java.lang.String)
  */
 @Override
 public void parse(InputStream is, String name) {
   container.runScriptlet(is, name);
 }
 /*
  * (non-Javadoc)
  *
  * @see org.apollo.util.plugin.PluginEnvironment#setContext(org.apollo.util.plugin .PluginContext)
  */
 @Override
 public void setContext(PluginContext context) {
   container.put("$ctx", context);
 }
Ejemplo n.º 21
0
 public WaveformWrapper(double[] points) {
   Object waveformClass = rubyContainer.runScriptlet("Waveform");
   waveform = rubyContainer.callMethod(waveformClass, "new", points);
 }
Ejemplo n.º 22
0
 public JRubyBackend() throws UnsupportedEncodingException {
   jruby.put("$backend", this);
   jruby.runScriptlet(new InputStreamReader(getClass().getResourceAsStream(DSL), "UTF-8"), DSL);
 }
Ejemplo n.º 23
0
 @Override
 public void destroy() {
   if (container != null) container.terminate();
 }
Ejemplo n.º 24
0
 static {
   rubyContainer = new ScriptingContainer();
   rubyContainer.runScriptlet("require 'waveform'");
 }