public Object[] transform(InputRow row) {
    Object[] inputValues = new Object[_inputValues.length];
    for (int i = 0; i < inputValues.length; i++) {
      Object value = row.getValue(_inputValues[i]);
      inputValues[i] = value;
    }

    IRubyObject[] rubyInputValues = JavaUtil.convertJavaArrayToRuby(_ruby, inputValues);
    IRubyObject rubyOutputCollector = JavaEmbedUtils.javaToRuby(_ruby, _rowCollector);

    Object[] arguments = new Object[] {rubyInputValues, rubyOutputCollector};

    JavaEmbedUtils.invokeMethod(_ruby, _transformerObject, "transform", arguments, Object.class);
    return null;
  }
  @Close
  public void close() {
    try {
      JavaEmbedUtils.invokeMethod(
          _ruby, _transformerObject, "close", new Object[0], IRubyObject.class);
    } catch (Exception e) {
      logger.error("Failed to call close() on RubyTransformer", e);
    }

    try {
      JavaEmbedUtils.terminate(_ruby);
    } catch (Exception e) {
      logger.error("Failed to terminate JRuby instance", e);
    }
  }
  @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);
  }
 public RackResponse call(final RackEnvironment env) {
   Ruby runtime = getRuntime();
   try {
     RackBaseInput io = createRackInput(runtime, env);
     try {
       IRubyObject servlet_env = JavaEmbedUtils.javaToRuby(runtime, env);
       adapter.setInstanceVariable(servlet_env, "@_io", io);
       IRubyObject response = __call(servlet_env);
       return (RackResponse) JavaEmbedUtils.rubyToJava(runtime, response, RackResponse.class);
     } finally {
       io.close();
     }
   } catch (IOException ex) {
     throw RaiseException.createNativeRaiseException(runtime, ex);
   }
 }
 private Object convertFromRuby(IRubyObject rubyResult, Class returnType) {
   Object result = JavaEmbedUtils.rubyToJava(this.ruby, rubyResult, returnType);
   if (result instanceof RubyArray && returnType.isArray()) {
     result = convertFromRubyArray(((RubyArray) result).toJavaArray(), returnType);
   }
   return result;
 }
Exemplo n.º 6
0
 /**
  * Call Ruby's respond_to? to find out if the Ruby object responds to a method.
  *
  * @param rubyObject The ruby object in the Java side
  * @param methodName The method name
  * @return true if the ruby object responds to that method
  */
 public boolean respondTo(Object rubyObject, String methodName) {
   Object res =
       JavaEmbedUtils.invokeMethod(
           runtime, rubyObject, "respond_to?", new Object[] {methodName}, Object.class);
   if (res instanceof Boolean) {
     return (Boolean) res;
   }
   throw new RuntimeException("Problem calling respond_to?!");
 }
Exemplo n.º 7
0
  private Object callMethodImpl(
      Object rubyObject, String methodName, Object[] params, Class<? extends Object> returnType) {

    String[] s = methodName.split("\\.");

    if (s.length == 1) {

      return JavaEmbedUtils.invokeMethod(runtime, rubyObject, methodName, params, returnType);

    } else {

      String m1 = s[0]; // first method...
      String m2 = getMethods(s); // remaining methods...

      Object temp = JavaEmbedUtils.invokeMethod(runtime, rubyObject, m1, EMPTY, Object.class);

      return callMethodImpl(temp, m2, params, returnType); // recursive...
    }
  }
  @Before
  public void setUp() {
    this.ruby = Ruby.newInstance();

    this.ruby.getLoadService().require("org/torquebox/web/component/mock_app");
    RubyModule mockAppClass = this.ruby.getClassFromPath("MockApp");
    this.rackApp =
        (IRubyObject)
            JavaEmbedUtils.invokeMethod(this.ruby, mockAppClass, "new", null, IRubyObject.class);
  }
 private IRubyObject[] convertToRuby(Object[] javaArgs) {
   if (javaArgs == null || javaArgs.length == 0) {
     return new IRubyObject[0];
   }
   IRubyObject[] rubyArgs = new IRubyObject[javaArgs.length];
   for (int i = 0; i < javaArgs.length; ++i) {
     rubyArgs[i] = JavaEmbedUtils.javaToRuby(this.ruby, javaArgs[i]);
   }
   return rubyArgs;
 }
Exemplo n.º 10
0
 private Block createBlock(AbstractBlock parent, String context, Map<String, Object> options) {
   IRubyObject rubyClass = rubyRuntime.evalScriptlet("Asciidoctor::Block");
   RubyHash convertMapToRubyHashWithSymbols =
       RubyHashUtil.convertMapToRubyHashWithSymbols(rubyRuntime, options);
   Object[] parameters = {
     parent.delegate(), RubyUtils.toSymbol(rubyRuntime, context), convertMapToRubyHashWithSymbols
   };
   return (Block)
       JavaEmbedUtils.invokeMethod(rubyRuntime, rubyClass, "new", parameters, Block.class);
 }
Exemplo n.º 11
0
 /** Test of getRuntime method, of class ScriptingContainer. */
 @Test
 public void testGetRuntime() {
   System.out.println("getRuntime");
   ScriptingContainer instance = new ScriptingContainer();
   Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());
   Ruby result = instance.getRuntime();
   Class expClazz = runtime.getClass();
   Class resultClazz = result.getClass();
   assertEquals(expClazz, resultClazz);
   instance = null;
 }
Exemplo n.º 12
0
 /**
  * @param runtime
  * @param factory
  * @return
  */
 public static RubyClass createCommandClass(final Ruby runtime, DriverDefinition factory) {
   RubyModule doModule = runtime.getModule(DATA_OBJECTS_MODULE_NAME);
   RubyClass superClass = doModule.getClass(RUBY_CLASS_NAME);
   RubyModule driverModule = (RubyModule) doModule.getConstant(factory.getModuleName());
   RubyClass commandClass =
       runtime.defineClassUnder("Command", superClass, COMMAND_ALLOCATOR, driverModule);
   commandClass.setInstanceVariable("@__factory", JavaEmbedUtils.javaToRuby(runtime, factory));
   commandClass.defineAnnotatedMethods(Command.class);
   setDriverDefinition(commandClass, runtime, factory);
   return commandClass;
 }
Exemplo n.º 13
0
 public void testExceptionsAcrossTheBridge() {
   final IRubyObject wrappedThrower = JavaEmbedUtils.javaToRuby(runtime, new ExceptionThrower());
   boolean exceptionThrown = false;
   try {
     // call throwException via JRuby
     JavaEmbedUtils.invokeMethod(
         runtime, wrappedThrower, "throwException", new Object[] {}, Object.class);
   } catch (final RaiseException e) {
     exceptionThrown = true;
     final NativeException ne = (NativeException) e.getException();
     final ExpectedException ee = (ExpectedException) ne.getCause();
     assertEquals(
         "The unpacked exception we receive should be the one we threw.",
         ExceptionThrower.expectedException,
         ee);
   } finally {
     assertTrue(
         "Java Exception should have been thrown and wrapped as a RaiseException",
         exceptionThrown);
   }
 }
Exemplo n.º 14
0
 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);
     }
   }
 }
Exemplo n.º 15
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());
    }
  }
Exemplo n.º 16
0
  public Object eval(Reader script, ScriptContext scriptContext) throws ScriptException {
    Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);

    SlingScriptHelper helper = (SlingScriptHelper) bindings.get(SlingBindings.SLING);
    if (helper == null) {
      throw new ScriptException("SlingScriptHelper missing from bindings");
    }

    // ensure GET request
    if (helper.getRequest() != null && !"GET".equals(helper.getRequest().getMethod())) {
      throw new ScriptException("JRuby scripting only supports GET requests");
    }

    final ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
    try {
      Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
      StringBuffer scriptString = new StringBuffer();
      BufferedReader bufferedScript = new BufferedReader(script);
      String nextLine = bufferedScript.readLine();
      while (nextLine != null) {
        scriptString.append(nextLine);
        scriptString.append("\n");
        nextLine = bufferedScript.readLine();
      }

      IRubyObject scriptRubyString = JavaEmbedUtils.javaToRuby(runtime, scriptString.toString());
      IRubyObject erb =
          (IRubyObject)
              JavaEmbedUtils.invokeMethod(
                  runtime, erbModule, "new", new Object[] {scriptRubyString}, IRubyObject.class);

      JavaEmbedUtils.invokeMethod(
          runtime,
          erb,
          "set_props",
          new Object[] {JavaEmbedUtils.javaToRuby(runtime, bindings)},
          IRubyObject.class);

      IRubyObject binding =
          (IRubyObject)
              JavaEmbedUtils.invokeMethod(
                  runtime, erb, "send", new Object[] {bindingSym}, IRubyObject.class);

      scriptContext
          .getWriter()
          .write(
              (String)
                  JavaEmbedUtils.invokeMethod(
                      runtime, erb, "result", new Object[] {binding}, String.class));
    } catch (Throwable t) {
      final ScriptException ex = new ScriptException("Failure running Ruby script:" + t);
      ex.initCause(t);
      throw ex;
    } finally {
      Thread.currentThread().setContextClassLoader(oldClassLoader);
    }
    return null;
  }
/** @author nicksieger */
public class DefaultRackApplication implements RackApplication {
  private final RubyObjectAdapter adapter = JavaEmbedUtils.newObjectAdapter();
  private IRubyObject application;

  public DefaultRackApplication() {}

  public RackResponse call(final RackEnvironment env) {
    Ruby runtime = getRuntime();
    try {
      RackBaseInput io = createRackInput(runtime, env);
      try {
        IRubyObject servlet_env = JavaEmbedUtils.javaToRuby(runtime, env);
        adapter.setInstanceVariable(servlet_env, "@_io", io);
        IRubyObject response = __call(servlet_env);
        return (RackResponse) JavaEmbedUtils.rubyToJava(runtime, response, RackResponse.class);
      } finally {
        io.close();
      }
    } catch (IOException ex) {
      throw RaiseException.createNativeRaiseException(runtime, ex);
    }
  }

  public void init() throws RackInitializationException {}

  public void destroy() {}

  public Ruby getRuntime() {
    return application.getRuntime();
  }

  public void setApplication(IRubyObject application) {
    this.application = application;
  }

  /** Only used for testing. */
  public IRubyObject __call(final IRubyObject env) {
    return adapter.callMethod(application, "call", env);
  }

  private RackBaseInput createRackInput(Ruby runtime, RackEnvironment env) throws IOException {
    if (env.getContext().getConfig().isRewindable()) {
      return new RackRewindableInput(runtime, env);
    } else {
      return new RackNonRewindableInput(runtime, env);
    }
  }
}
Exemplo n.º 18
0
  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();
      }
    }
  }
Exemplo n.º 19
0
Arquivo: Command.java Projeto: gryn/do
 public static RubyClass createCommandClass(
     final Ruby runtime,
     final String moduleName,
     final String errorName,
     final DriverDefinition driverDefinition) {
   RubyModule doModule = runtime.getModule(DATA_OBJECTS_MODULE_NAME);
   RubyClass superClass = doModule.getClass(RUBY_CLASS_NAME);
   RubyModule driverModule = (RubyModule) doModule.getConstant(moduleName);
   RubyClass commandClass =
       runtime.defineClassUnder("Command", superClass, COMMAND_ALLOCATOR, driverModule);
   Command.api = JavaEmbedUtils.newObjectAdapter();
   Command.driver = driverDefinition;
   Command.moduleName = moduleName;
   Command.errorName = errorName;
   commandClass.defineAnnotatedMethods(Command.class);
   return commandClass;
 }
  @Test
  public void testCall() throws Exception {
    RackApplicationComponent component = new RackApplicationComponent(this.rackApp);
    RackEnvironment env = mock(RackEnvironment.class);
    RubyHash envHash = RubyHash.newHash(this.ruby);
    when(env.getEnv()).thenReturn(envHash);

    Object response = component.call(env);

    assertNotNull(response);

    RubyHash internalEnvHash =
        (RubyHash)
            JavaEmbedUtils.invokeMethod(this.ruby, this.rackApp, "env", null, RubyHash.class);

    assertSame(envHash, internalEnvHash);
  }
Exemplo n.º 21
0
  /** Test of parse method, of class ScriptingContainer. */
  @Test
  public void testParse_String_intArr() {
    System.out.println("parse");
    String script = null;
    int[] lines = null;
    ScriptingContainer instance = new ScriptingContainer();
    EmbedEvalUnit expResult = null;
    EmbedEvalUnit result = instance.parse(script, lines);
    assertEquals(expResult, result);

    script = "";
    Ruby runtime = JavaEmbedUtils.initialize(new ArrayList());
    Node node = runtime.parseEval(script, "<script>", null, 0);
    IRubyObject expRet = runtime.runInterpreter(node);
    result = instance.parse(script);
    IRubyObject ret = result.run();
    assertEquals(expRet.toJava(String.class), ret.toJava(String.class));
    // Maybe bug. This returns RubyNil, but it should be ""
    // assertEquals("", ret.toJava(String.class));

    script = "def say_something()" + "\"はろ〜、わぁ〜るど!\"\n" + "end\n" + "say_something";
    expRet = runtime.runInterpreter(runtime.parseEval(script, "<script>", null, 0));
    ret = instance.parse(script).run();
    assertEquals(expRet.toJava(String.class), ret.toJava(String.class));

    // sharing variables
    instance.put("what", "Trick or Treat.");
    script = "\"Did you say, #{what}?\"";
    result = instance.parse(script);
    ret = result.run();
    assertEquals("Did you say, Trick or Treat.?", ret.toJava(String.class));

    // line number test
    script = "puts \"Hello World!!!\"\nputs \"Have a nice day!";
    StringWriter writer = new StringWriter();
    instance.setErrorWriter(writer);
    try {
      instance.parse(script, 1);
    } catch (Exception e) {
      assertTrue(writer.toString().contains("<script>:3:"));
    }

    instance.getVarMap().clear();
    instance = null;
  }
Exemplo n.º 22
0
  public Inline createInline(
      AbstractBlock parent,
      String context,
      String text,
      Map<String, Object> attributes,
      Map<String, Object> options) {

    options.put(Options.ATTRIBUTES, attributes);

    IRubyObject rubyClass = rubyRuntime.evalScriptlet("Asciidoctor::Inline");
    RubyHash convertMapToRubyHashWithSymbols =
        RubyHashUtil.convertMapToRubyHashWithSymbols(rubyRuntime, options);
    Object[] parameters = {
      parent.delegate(),
      RubyUtils.toSymbol(rubyRuntime, context),
      text,
      convertMapToRubyHashWithSymbols
    };
    return (Inline)
        JavaEmbedUtils.invokeMethod(rubyRuntime, rubyClass, "new", parameters, Inline.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);
    }
  }
Exemplo n.º 24
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();
  }
Exemplo n.º 25
0
/**
 * Implementation of {@link EmbedRubyObjectAdapter}. Users get an instance of this class by
 * newObjectAdapter() method of {@link ScriptingContainer}.
 *
 * @author Yoko Harada <*****@*****.**>
 */
public class EmbedRubyObjectAdapterImpl implements EmbedRubyObjectAdapter {
  private RubyObjectAdapter adapter = JavaEmbedUtils.newObjectAdapter();
  private ScriptingContainer container;

  public enum MethodType {
    CALLMETHOD_NOARG,
    CALLMETHOD,
    CALLMETHOD_WITHBLOCK,
    CALLSUPER,
    CALLSUPER_WITHBLOCK
  }

  public EmbedRubyObjectAdapterImpl(ScriptingContainer container) {
    this.container = container;
  }

  public boolean isKindOf(IRubyObject value, RubyModule rubyModule) {
    return adapter.isKindOf(value, rubyModule);
  }

  public IRubyObject[] convertToJavaArray(IRubyObject array) {
    return adapter.convertToJavaArray(array);
  }

  public RubyInteger convertToRubyInteger(IRubyObject obj) {
    return adapter.convertToRubyInteger(obj);
  }

  public RubyString convertToRubyString(IRubyObject obj) {
    return adapter.convertToRubyString(obj);
  }

  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);
  }

  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 callMethod(IRubyObject receiver, String methodName) {
    return adapter.callMethod(receiver, methodName);
  }

  public IRubyObject callMethod(IRubyObject receiver, String methodName, IRubyObject singleArg) {
    return adapter.callMethod(receiver, methodName, singleArg);
  }

  public IRubyObject callMethod(IRubyObject receiver, String methodName, IRubyObject[] args) {
    return adapter.callMethod(receiver, methodName, args);
  }

  public IRubyObject callMethod(
      IRubyObject receiver, String methodName, IRubyObject[] args, Block block) {
    return adapter.callMethod(receiver, methodName, args, block);
  }

  public IRubyObject callSuper(IRubyObject receiver, IRubyObject[] args) {
    return adapter.callSuper(receiver, args);
  }

  public IRubyObject callSuper(IRubyObject receiver, IRubyObject[] args, Block block) {
    return adapter.callSuper(receiver, args, block);
  }

  public <T> T callMethod(Object receiver, String methodName, Class<T> returnType) {
    try {
      return call(MethodType.CALLMETHOD_NOARG, returnType, receiver, methodName, null, null);
    } catch (InvokeFailedException e) {
      throw e;
    } catch (Throwable e) {
      throw new InvokeFailedException(e);
    }
  }

  public <T> T callMethod(
      Object receiver, String methodName, Object singleArg, Class<T> returnType) {
    try {
      return call(MethodType.CALLMETHOD, returnType, receiver, methodName, null, null, singleArg);
    } catch (InvokeFailedException e) {
      throw e;
    } catch (Throwable e) {
      throw new InvokeFailedException(e);
    }
  }

  public <T> T callMethod(Object receiver, String methodName, Object[] args, Class<T> returnType) {
    try {
      return call(MethodType.CALLMETHOD, returnType, receiver, methodName, null, null, args);
    } catch (InvokeFailedException e) {
      throw e;
    } catch (Throwable e) {
      throw new InvokeFailedException(e);
    }
  }

  public <T> T callMethod(
      Object receiver, String methodName, Object[] args, Block block, Class<T> returnType) {
    try {
      return call(
          MethodType.CALLMETHOD_WITHBLOCK, returnType, receiver, methodName, block, null, args);
    } catch (InvokeFailedException e) {
      throw e;
    } catch (Throwable e) {
      throw new InvokeFailedException(e);
    }
  }

  public <T> T callMethod(
      Object receiver, String methodName, Class<T> returnType, EmbedEvalUnit unit) {
    try {
      return call(MethodType.CALLMETHOD_NOARG, returnType, receiver, methodName, null, unit);
    } catch (InvokeFailedException e) {
      throw e;
    } catch (Throwable e) {
      throw new InvokeFailedException(e);
    }
  }

  public <T> T callMethod(
      Object receiver, String methodName, Object[] args, Class<T> returnType, EmbedEvalUnit unit) {
    try {
      return call(MethodType.CALLMETHOD, returnType, receiver, methodName, null, unit, args);
    } catch (InvokeFailedException e) {
      throw e;
    } catch (Throwable e) {
      throw new InvokeFailedException(e);
    }
  }

  public <T> T callMethod(
      Object receiver,
      String methodName,
      Object[] args,
      Block block,
      Class<T> returnType,
      EmbedEvalUnit unit) {
    try {
      return call(
          MethodType.CALLMETHOD_WITHBLOCK, returnType, receiver, methodName, block, unit, args);
    } catch (InvokeFailedException e) {
      throw e;
    } catch (Throwable e) {
      throw new InvokeFailedException(e);
    }
  }

  public <T> T callSuper(Object receiver, Object[] args, Class<T> returnType) {
    try {
      return call(MethodType.CALLSUPER, returnType, receiver, null, null, null, args);
    } catch (InvokeFailedException e) {
      throw e;
    } catch (Throwable e) {
      throw new InvokeFailedException(e);
    }
  }

  public <T> T callSuper(Object receiver, Object[] args, Block block, Class<T> returnType) {
    try {
      return call(MethodType.CALLSUPER_WITHBLOCK, returnType, receiver, null, block, null, args);
    } catch (InvokeFailedException e) {
      throw e;
    } catch (Throwable e) {
      throw new InvokeFailedException(e);
    }
  }

  public Object callMethod(Object receiver, String methodName, Object... args) {
    try {
      if (args.length == 0) {
        return call(MethodType.CALLMETHOD_NOARG, Object.class, receiver, methodName, null, null);
      } else {
        return call(MethodType.CALLMETHOD, Object.class, receiver, methodName, null, null, args);
      }
    } catch (InvokeFailedException e) {
      throw e;
    } catch (Throwable e) {
      throw new InvokeFailedException(e);
    }
  }

  public Object callMethod(Object receiver, String methodName, Block block, Object... args) {
    try {
      if (args.length == 0) {
        throw new IllegalArgumentException("needs at least one argument in a method");
      }
      return call(
          MethodType.CALLMETHOD_WITHBLOCK, Object.class, receiver, methodName, block, null, args);
    } catch (InvokeFailedException e) {
      throw e;
    } catch (Throwable e) {
      throw new InvokeFailedException(e);
    }
  }

  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();
      }
    }
  }

  private RubyObject getReceiverObject(Ruby runtime, Object receiver) {
    if (receiver == null || !(receiver instanceof IRubyObject) || receiver instanceof RubyNil) {
      return (RubyObject) runtime.getTopSelf();
    } else if (receiver instanceof RubyObject) return (RubyObject) receiver;
    else return (RubyObject) ((IRubyObject) receiver).getRuntime().getTopSelf();
  }

  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;
  }
}
Exemplo n.º 26
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);
        }
      }
    }
  }
}
Exemplo n.º 27
0
 /** Initializes an instance of the {@link org.jruby.Ruby} runtime. */
 private static Ruby initializeRuntime() {
   return JavaEmbedUtils.initialize(Collections.EMPTY_LIST);
 }