Пример #1
0
  public void testRubyExceptionWithoutCause() throws Exception {
    try {
      RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();

      evaler.eval(runtime, "no_method_with_this_name");
      fail("Expected ScriptException");
    } catch (RaiseException re) {
      assertEquals(
          "(NameError) undefined local variable or method `no_method_with_this_name' for main:Object",
          re.getMessage());
    }
  }
  @Initialize
  public void initialize() {
    _ruby = JavaEmbedUtils.initialize(Collections.EMPTY_LIST);
    _runtimeAdapter = JavaEmbedUtils.newRuntimeAdapter();

    // load the class def
    _runtimeAdapter.eval(_ruby, _code);

    _transformerObject = _runtimeAdapter.eval(_ruby, "Transformer.new()");

    logger.info("Evaluated Ruby code to: {}", _transformerObject);

    JavaEmbedUtils.invokeMethod(
        _ruby, _transformerObject, "init", new Object[0], IRubyObject.class);
  }
  /**
   * {@inheritDoc}
   *
   * <p>Latest method of invoking jruby script have been adapted from <a
   * href="http://wiki.jruby.org/wiki/Java_Integration" title="Click to visit JRuby Wiki"> JRuby
   * wiki:</a>
   *
   * @todo create a way to prevent initialization and shutdown with each script invocation.
   */
  protected PicoContainer createContainerFromScript(
      PicoContainer parentContainer, Object assemblyScope) {
    if (parentContainer == null) {
      parentContainer = new EmptyPicoContainer();
    }
    parentContainer =
        new DefaultClassLoadingPicoContainer(
            getClassLoader(), new DefaultPicoContainer(new Caching(), parentContainer));

    RubyInstanceConfig rubyConfig = new RubyInstanceConfig();
    rubyConfig.setLoader(this.getClassLoader());
    Ruby ruby = JavaEmbedUtils.initialize(Collections.EMPTY_LIST, rubyConfig);
    ruby.getLoadService().require("org/picocontainer/script/jruby/scriptedbuilder");
    ruby.defineReadonlyVariable("$parent", JavaEmbedUtils.javaToRuby(ruby, parentContainer));
    ruby.defineReadonlyVariable("$assembly_scope", JavaEmbedUtils.javaToRuby(ruby, assemblyScope));

    try {

      // IRubyObject result = ruby.executeScript(script);
      IRubyObject result = JavaEmbedUtils.newRuntimeAdapter().eval(ruby, script);
      return (PicoContainer) JavaEmbedUtils.rubyToJava(ruby, result, PicoContainer.class);
    } catch (RaiseException re) {
      if (re.getCause() instanceof ScriptedPicoContainerMarkupException) {
        throw (ScriptedPicoContainerMarkupException) re.getCause();
      }
      String message =
          (String) JavaEmbedUtils.rubyToJava(ruby, re.getException().message, String.class);
      if (message.startsWith(MARKUP_EXCEPTION_PREFIX)) {
        throw new ScriptedPicoContainerMarkupException(
            message.substring(MARKUP_EXCEPTION_PREFIX.length()));
      } else {
        throw new PicoCompositionException(message, re);
      }
    } finally {
      JavaEmbedUtils.terminate(ruby);
    }
  }
Пример #4
0
/** @author nicksieger */
public class DefaultQueueManager implements QueueManager {
  private ConnectionFactory connectionFactory = null;
  private RackContext context;
  private Context jndiContext;
  private Map<String, Connection> queues = new HashMap<String, Connection>();
  private RubyRuntimeAdapter rubyRuntimeAdapter = JavaEmbedUtils.newRuntimeAdapter();
  private RubyObjectAdapter rubyObjectAdapter = JavaEmbedUtils.newObjectAdapter();

  public DefaultQueueManager() {}

  public DefaultQueueManager(ConnectionFactory qcf, Context ctx) {
    this.connectionFactory = qcf;
    this.jndiContext = ctx;
  }

  public void init(RackContext context) throws Exception {
    this.context = context;
    String jndiName = context.getInitParameter("jms.connection.factory");
    if (jndiName != null && connectionFactory == null) {
      Properties properties = new Properties();
      String jndiProperties = context.getInitParameter("jms.jndi.properties");
      if (jndiProperties != null) {
        properties.load(new ByteArrayInputStream(jndiProperties.getBytes("UTF-8")));
      }
      jndiContext = new InitialContext(properties);
      connectionFactory = (ConnectionFactory) jndiContext.lookup(jndiName);
    }
  }

  public synchronized void listen(String queueName) {
    Connection conn = queues.get(queueName);
    if (conn == null) {
      try {
        conn = connectionFactory.createConnection();
        Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination dest = (Destination) lookup(queueName);
        MessageConsumer consumer = session.createConsumer(dest);
        consumer.setMessageListener(new RubyObjectMessageListener(queueName));
        queues.put(queueName, conn);
        conn.start();
      } catch (Exception e) {
        context.log("Unable to listen to '" + queueName + "': " + e.getMessage(), e);
      }
      // } else { ... already listening on that queue
    }
  }

  public ConnectionFactory getConnectionFactory() {
    return connectionFactory;
  }

  public Object lookup(String name) throws javax.naming.NamingException {
    return jndiContext.lookup(name);
  }

  public void destroy() {
    for (Iterator it = queues.entrySet().iterator(); it.hasNext(); ) {
      Map.Entry<String, Connection> entry = (Map.Entry<String, Connection>) it.next();
      try {
        entry.getValue().close();
      } catch (Exception e) {
        context.log("exception while closing connection: " + e.getMessage(), e);
      }
    }
    queues.clear();
    connectionFactory = null;
  }

  private class RubyObjectMessageListener implements MessageListener {
    private String queueName;
    private RackApplicationFactory rackFactory;

    public RubyObjectMessageListener(String name) {
      this.queueName = name;
      this.rackFactory = context.getRackFactory();
    }

    public void onMessage(Message message) {
      RackApplication app = null;
      try {
        app = rackFactory.getApplication();
        Ruby runtime = app.getRuntime();
        IRubyObject obj = rubyRuntimeAdapter.eval(runtime, "JRuby::Rack::Queues");
        rubyObjectAdapter.callMethod(
            obj,
            "receive_message",
            new IRubyObject[] {
              JavaEmbedUtils.javaToRuby(runtime, queueName),
              JavaEmbedUtils.javaToRuby(runtime, message)
            });
      } catch (Exception e) {
        context.log("exception during message reception: " + e.getMessage(), e);
      } finally {
        if (app != null) {
          rackFactory.finishedWithApplication(app);
        }
      }
    }
  }
}
Пример #5
0
  private JRubyInterpreter() throws IOException {

    // set env variables...

    boolean isWindows = Platform.IS_WINDOWS;

    String SEP = isWindows ? "\\" : "/";

    String jruby_home = System.getenv("JRUBY_HOME");
    String jruby_lib = System.getenv("JRUBY_LIB");
    String jruby_shell = System.getenv("JRUBY_SHELL");
    String jruby_script = System.getenv("JRUBY_SCRIPT");
    String jruby_opts = System.getenv("JRUBY_OPTS");

    if (jruby_home != null) System.setProperty("jruby.home", jruby_home);

    if (jruby_lib != null) {
      System.setProperty("jruby.lib", jruby_lib);
    } else if (jruby_home != null) {
      System.setProperty("jruby.lib", jruby_home + SEP + "lib");
    }

    if (jruby_shell != null) {
      System.setProperty("jruby.shell", jruby_shell);
    } else {
      if (isWindows) {
        System.setProperty("jruby.shell", "cmd.exe");
      } else {
        System.setProperty("jruby.shell", "/bin/sh");
      }
    }

    if (jruby_script != null) {
      System.setProperty("jruby.script", jruby_script);
    } else {
      if (isWindows) {
        System.setProperty("jruby.script", "jruby.bat");
      } else {
        System.setProperty("jruby.script", "jruby");
      }
    }

    String realPath = ApplicationManager.getRealPath();

    List<String> loadPaths = new ArrayList<String>();
    loadPaths.add(".");
    loadPaths.add(realPath + SEP + "WEB-INF" + SEP + "ruby");

    runtime = JavaEmbedUtils.initialize(loadPaths);

    evaler = JavaEmbedUtils.newRuntimeAdapter();

    // require rubygems...

    if (jruby_home != null && jruby_opts != null && jruby_opts.indexOf("-rubygems") != -1) {

      require("rubygems");
    }

    // UTF through -Ku

    if (jruby_home != null && jruby_opts != null && jruby_opts.indexOf("-K") != -1) {

      int start = jruby_opts.indexOf("-K");

      String s = jruby_opts.substring(start + 2);

      int end = s.indexOf(" ");

      if (end > 0) s = s.substring(0, end);

      eval("$KCODE = '" + s + "'");
    }

    loadFileFromClasspath("org/mentawai/jruby/loader.rb");

    loadFileFromClasspath("org/mentawai/jruby/action_manager.rb");

    loadFileFromClasspath("org/mentawai/jruby/utils.rb");

    loadFileFromClasspath("org/mentawai/jruby/ruby_action.rb");

    rubyLoader = eval("Mentawai::JRuby::Loader.new('" + realPath + "')");

    reloadFiles();

    thread = new Thread(this);

    running = true;

    thread.setDaemon(true);

    thread.start();
  }