org.jruby.javasupport.JavaEmbedUtils Java Examples

The following examples show how to use org.jruby.javasupport.JavaEmbedUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RubyHashUtil.java    From asciidoctorj with Apache License 2.0 6 votes vote down vote up
private static IRubyObject toRubyObject(Ruby rubyRuntime, Object value) {

        if (value instanceof List) {
            return toRubyArray(rubyRuntime, (List<Object>) value);
        } else if (value instanceof Map) {
        	return convertMapToRubyHashWithStrings(rubyRuntime, (Map<String, Object>) value);
        } else {

            if (isNotARubySymbol(value)) {
                CharSequence stringValue = ((CharSequence) value);

                if (stringValue.length() > 0 && stringValue.charAt(0) == ':') {
                    return RubyUtils.toSymbol(rubyRuntime, stringValue.subSequence(1, stringValue.length()).toString());
                }
            }

            IRubyObject iRubyObject = JavaEmbedUtils.javaToRuby(rubyRuntime, value);
            return iRubyObject;
        }
    }
 
Example #2
Source File: ConverterProxy.java    From asciidoctorj with Apache License 2.0 6 votes vote down vote up
@JRubyMethod(required = 1, optional = 2)
public IRubyObject convert(ThreadContext context, IRubyObject[] args) {
    ContentNode node = NodeConverter.createASTNode(args[0]);

    T ret = null;
    if (args.length == 1) {
        ret = delegate.convert(
                node,
                null,
                Collections.emptyMap());
    } else if (args.length == 2) {
        ret = delegate.convert(
                node,
                (String) JavaEmbedUtils.rubyToJava(getRuntime(), args[1], String.class),
                Collections.emptyMap());//RubyString.objAsString(context, args[1]).asJavaString());
    } else if (args.length == 3) {
        ret = (T) delegate.convert(
                node,
                (String) JavaEmbedUtils.rubyToJava(getRuntime(), args[1], String.class),
                (Map) JavaEmbedUtils.rubyToJava(getRuntime(), args[2], Map.class));
    }
    this.output = ret;
    return JavaEmbedUtils.javaToRuby(getRuntime(), ret);
}
 
Example #3
Source File: EditorContextContributor.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
public void modifyContext(CommandElement command, CommandContext context)
{
	IEditorPart editor = this.getActiveEditor();

	if (editor != null && command != null)
	{
		Ruby runtime = command.getRuntime();

		if (runtime != null)
		{
			IRubyObject rubyInstance = ScriptUtils.instantiateClass(runtime, ScriptUtils.RUBLE_MODULE,
					EDITOR_RUBY_CLASS, JavaEmbedUtils.javaToRuby(runtime, editor));

			context.put(EDITOR_PROPERTY_NAME, rubyInstance);
		}
		else
		{
			context.put(EDITOR_PROPERTY_NAME, null);
		}
	}
}
 
Example #4
Source File: RubyScriptTest.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
@Test(enabled = false)
public void resultsCapturesJavaError() throws Exception {
    RubyScript script = new RubyScript(out, err, converToCode(SCRIPT_CONTENTS_ERROR_FROM_JAVA),
            new File(System.getProperty(Constants.PROP_PROJECT_DIR), "dummyfile.rb").getAbsolutePath(), false, null,
            Constants.FRAMEWORK_SWING);
    script.setDriverURL("");
    Ruby interpreter = script.getInterpreter();
    assertTrue("Collector not defined", interpreter.isClassDefined("Collector"));
    RubyClass collectorClass = interpreter.getClass("Collector");
    IRubyObject presult = JavaEmbedUtils.javaToRuby(interpreter, result);
    IRubyObject collector = collectorClass.newInstance(interpreter.getCurrentContext(), new IRubyObject[0], new Block(null));
    IRubyObject rubyObject = interpreter.evalScriptlet("proc { my_function }");
    try {
        collector.callMethod(interpreter.getCurrentContext(), "callprotected", new IRubyObject[] { rubyObject, presult });
    } catch (Throwable t) {

    }
    assertEquals(1, result.failureCount());
    Failure[] failures = result.failures();
    assertTrue("Should end with TestRubyScript.java. but has " + failures[0].getTraceback()[0].fileName,
            failures[0].getTraceback()[0].fileName.endsWith("TestRubyScript.java"));
    assertEquals("throwError", failures[0].getTraceback()[0].functionName);
}
 
Example #5
Source File: RubyObjectWrapper.java    From asciidoctorj with Apache License 2.0 6 votes vote down vote up
public IRubyObject getRubyProperty(String propertyName, Object... args) {
    ThreadContext threadContext = runtime.getThreadService().getCurrentContext();

    IRubyObject result;
    if (propertyName.startsWith("@")) {
        if (args != null && args.length > 0) {
            throw new IllegalArgumentException("No args allowed for direct field access");
        }
        result = rubyNode.getInstanceVariables().getInstanceVariable(propertyName);
    } else {
        if (args == null) {
            result = rubyNode.callMethod(threadContext, propertyName);
        } else {
            IRubyObject[] rubyArgs = new IRubyObject[args.length];
            for (int i = 0; i < args.length; i++) {
                if (args[i] instanceof RubyObjectWrapper) {
                    rubyArgs[i] = ((RubyObjectWrapper) args[i]).getRubyObject();
                } else {
                    rubyArgs[i] = JavaEmbedUtils.javaToRuby(runtime, args[i]);
                }
            }
            result = rubyNode.callMethod(threadContext, propertyName, rubyArgs);
        }
    }
    return result;
}
 
Example #6
Source File: RubyScript.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
protected Callable<Ruby> getInitRuby(final Writer out, final Writer err) {
    return new Callable<Ruby>() {
        @Override
        public Ruby call() throws Exception {
            RubyInstanceConfig config = new RubyInstanceConfig();
            config.setCompileMode(CompileMode.OFF);
            List<String> loadPaths = new ArrayList<String>();
            setModule(loadPaths);
            String appRubyPath = System.getProperty(PROP_APPLICATION_RUBYPATH);
            if (appRubyPath != null) {
                StringTokenizer tok = new StringTokenizer(appRubyPath, ";");
                while (tok.hasMoreTokens()) {
                    loadPaths.add(tok.nextToken().replace('/', File.separatorChar));
                }
            }
            config.setOutput(new PrintStream(new WriterOutputStream(out)));
            config.setError(new PrintStream(new WriterOutputStream(err)));
            Ruby interpreter = JavaEmbedUtils.initialize(loadPaths, config);
            interpreter.evalScriptlet("require 'selenium/webdriver'");
            interpreter.evalScriptlet("require 'marathon/results'");
            interpreter.evalScriptlet("require 'marathon/playback-" + framework + "'");
            return interpreter;
        }
    };
}
 
Example #7
Source File: RubyHashMapDecorator.java    From asciidoctorj with Apache License 2.0 6 votes vote down vote up
private Object convertRubyValue(Object rubyValue) {
    if (rubyValue == null) {
        return null;
    } else if (rubyValue instanceof IRubyObject) {
        IRubyObject rubyObject = (IRubyObject) rubyValue;

        if (RubyClass.KindOf.DEFAULT_KIND_OF.isKindOf(rubyObject, getAbstractNodeClass())) {
            return NodeConverter.createASTNode(rubyObject);
        }
        if (rubyObject instanceof RubySymbol) {
            return ":" + rubyObject.asString();
        }
        return JavaEmbedUtils.rubyToJava((IRubyObject) rubyValue);
    } else {
        return rubyValue;
    }
}
 
Example #8
Source File: RubyAttributesMapDecorator.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
private IRubyObject convertJavaValue(Object value) {
    if (value == null) {
        return null;
    } else if (value instanceof String && ((String) value).startsWith(":")) {
        return rubyHash.getRuntime().getSymbolTable().getSymbol(((String) value).substring(1));
    } else {
        return JavaEmbedUtils.javaToRuby(rubyHash.getRuntime(), value);
    }
}
 
Example #9
Source File: RubyAttributesMapDecorator.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
private Object convertRubyValue(Object rubyValue) {
    if (rubyValue == null) {
        return null;
    } else if (rubyValue instanceof IRubyObject) {
        return JavaEmbedUtils.rubyToJava((IRubyObject) rubyValue);
    } else {
        return rubyValue;
    }
}
 
Example #10
Source File: AbstractProcessorProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
protected IRubyObject convertProcessorResult(Object o) {
    if (o instanceof ContentNodeImpl) {
        return ((ContentNodeImpl) o).getRubyObject();
    } else {
        return JavaEmbedUtils.javaToRuby(getRuntime(), o);
    }
}
 
Example #11
Source File: RubyHashUtil.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
private static Object toJavaObject(Object rubyObject) {
    if (rubyObject instanceof IRubyObject) {
        IRubyObject iRubyObject = (IRubyObject) rubyObject;
        return JavaEmbedUtils.rubyToJava(iRubyObject);
    }

    return rubyObject;
}
 
Example #12
Source File: ExtensionGroupImpl.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@JRubyMethod(name = "register_extensions", required = 2)
public IRubyObject registerExtensions(ThreadContext context, IRubyObject registry, IRubyObject rubyRegistrators) {
  List<Registrator> registrators = (List<Registrator>) JavaEmbedUtils.rubyToJava(rubyRegistrators);
  for (Registrator registrator: registrators) {
    registrator.register(registry);
  }
  return context.getRuntime().getNil();
}
 
Example #13
Source File: ExtensionGroupImpl.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@Override
public void register() {
  IRubyObject callback = extensionGroupClass.newInstance(rubyRuntime.getCurrentContext(), Block.NULL_BLOCK);
  asciidoctorModule.callMethod("register_extension_group",
      rubyRuntime.newString(this.groupName),
      callback,
      JavaEmbedUtils.javaToRuby(rubyRuntime, registrators));
}
 
Example #14
Source File: JRubyAsciidoctor.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
private static Ruby createRubyRuntime(Map<String, String> environmentVars, List<String> loadPaths, ClassLoader classloader) {
    Map<String, String> env = environmentVars != null ? new HashMap<>(environmentVars) : new HashMap<>();

    RubyInstanceConfig config = createOptimizedConfiguration();
    if (classloader != null) {
        config.setLoader(classloader);
    }
    injectEnvironmentVariables(config, env);

    return JavaEmbedUtils.initialize(loadPaths, config);
}
 
Example #15
Source File: MarathonRuby.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
@Override
public String getProperty(String name) {
    Ruby runtime = o.getRuntime();
    o = marathon.callMethod(runtime.getCurrentContext(), "refresh_if_stale", o);
    marathon.callMethod(runtime.getCurrentContext(), "setContext", o);
    if ("tag_name".equals(name) || "tagName".equals(name)) {
        return o.callMethod(runtime.getCurrentContext(), "tag_name").toString().toUpperCase();
    }
    return o.callMethod(runtime.getCurrentContext(), "attribute", JavaEmbedUtils.javaToRuby(runtime, name)).toString();
}
 
Example #16
Source File: PreprocessorProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@JRubyMethod(name = "initialize", required = 1)
public IRubyObject initialize(ThreadContext context, IRubyObject options) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    if (getProcessor() != null) {
        // Instance was created in Java and has options set, so we pass these
        // instead of those passed by asciidoctor
        Helpers.invokeSuper(
                context,
                this,
                getMetaClass(),
                "initialize",
                new IRubyObject[]{ JavaEmbedUtils.javaToRuby(getRuntime(), getProcessor().getConfig()) },
                Block.NULL_BLOCK);
    } else {
        // First create only the instance passing in the block name
        setProcessor(instantiateProcessor(new HashMap<String, Object>()));

        // Then create the config hash that may contain config options defined in the Java constructor
        RubyHash config = RubyHashUtil.convertMapToRubyHashWithSymbols(context.getRuntime(), getProcessor().getConfig());

        // Initialize the Ruby part and pass in the config options
        Helpers.invokeSuper(context, this, getMetaClass(), METHOD_NAME_INITIALIZE, new IRubyObject[]{config}, Block.NULL_BLOCK);

        // Reset the Java config options to the decorated Ruby hash, so that Java and Ruby work on the same config map
        getProcessor().setConfig(new RubyHashMapDecorator((RubyHash) getInstanceVariable(MEMBER_NAME_CONFIG)));
    }

    finalizeJavaConfig();

    return null;
}
 
Example #17
Source File: RubyHashMapDecorator.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
private IRubyObject convertJavaValue(Object value) {
    if (value == null) {
        return null;
    } else if (value instanceof String && ((String) value).startsWith(":")) {
        return rubyHash.getRuntime().getSymbolTable().getSymbol(((String) value).substring(1));
    } else {
        return JavaEmbedUtils.javaToRuby(rubyHash.getRuntime(), value);
    }
}
 
Example #18
Source File: BundleContextContributor.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
public void modifyContext(CommandElement command, CommandContext context)
{
	if (command != null)
	{
		Ruby runtime = command.getRuntime();
		
		if (runtime != null)
		{
			IRubyObject rubyInstance = ScriptUtils.instantiateClass(runtime, ScriptUtils.RUBLE_MODULE,
					COMMAND_RUBY_CLASS, JavaEmbedUtils.javaToRuby(runtime, command));
			
			context.put(COMMAND_PROPERTY_NAME, rubyInstance);
			
			BundleElement bundle = command.getOwningBundle();
			
			if (bundle != null)
			{
				rubyInstance = ScriptUtils.instantiateClass(runtime, ScriptUtils.RUBLE_MODULE, BUNDLE_RUBY_CLASS,
						JavaEmbedUtils.javaToRuby(runtime, bundle));
				
				context.put(BUNDLE_PROPERTY_NAME, rubyInstance);
			}
			else
			{
				context.put(BUNDLE_PROPERTY_NAME, null);
			}
		}
		else
		{
			context.put(COMMAND_PROPERTY_NAME, null);
			context.put(BUNDLE_PROPERTY_NAME, null);
		}
	}
}
 
Example #19
Source File: JRubyScriptUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #20
Source File: RubyScript.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
private void defineVariable(String variable, Object value) {
    try {
        GlobalVariable v = new GlobalVariable(interpreter, "$" + variable, JavaEmbedUtils.javaToRuby(interpreter, value));
        interpreter.defineVariable(v, Scope.GLOBAL);
    } catch (Throwable t) {
        throw new ScriptException("Failed to define variable " + variable + " value = " + value + ":" + t.getMessage(), t);
    }
}
 
Example #21
Source File: RubyScript.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
private void findAssertionProviderMethods() {
    IRubyObject ro = interpreter.evalScriptlet("Object.private_instance_methods");
    String[] methods = (String[]) JavaEmbedUtils.rubyToJava(interpreter, ro, String[].class);
    assertionProviderList = new ArrayList<String>();
    for (Object method : methods) {
        if (method.toString().startsWith("marathon_assert_")) {
            assertionProviderList.add(method.toString());
        }
    }
}
 
Example #22
Source File: JRubyScriptUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #23
Source File: DocumentController.java    From sc-generator with Apache License 2.0 5 votes vote down vote up
@Bean
public Asciidoctor asciidoctor() {
    RubyInstanceConfig rubyInstanceConfig = new RubyInstanceConfig();
    rubyInstanceConfig.setLoader(this.getClass().getClassLoader());
    JavaEmbedUtils.initialize(Arrays.asList("META-INF/jruby.home/lib/ruby/2.0", "classpath:/gems/asciidoctor-1.5.4/lib"), rubyInstanceConfig);
    return create(this.getClass().getClassLoader());
}
 
Example #24
Source File: JRubyScriptUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example #25
Source File: JRubyScriptUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example #26
Source File: RubyDebugger.java    From marathonv5 with Apache License 2.0 4 votes vote down vote up
private void addEventHook() {
    String script = "set_trace_func proc { |event, file, line, id, binding, classname| "
            + "$marathon_trace_func.event(event, file, java.lang.Integer.new(line), classname.to_s) }";
    interpreter.defineReadonlyVariable("$marathon_trace_func", JavaEmbedUtils.javaToRuby(interpreter, this), Scope.GLOBAL);
    interpreter.evalScriptlet(script);
}
 
Example #27
Source File: AbstractMacroProcessorProxy.java    From asciidoctorj with Apache License 2.0 4 votes vote down vote up
@JRubyMethod(name = "name", required = 0)
public IRubyObject getName(ThreadContext context) {
    return JavaEmbedUtils.javaToRuby(getRuntime(), getProcessor().getName());
}
 
Example #28
Source File: RubyScript.java    From marathonv5 with Apache License 2.0 4 votes vote down vote up
private void readGlobals() {
    interpreter.evalScriptlet("RubyMarathon.new('" + driverURL + "')");
    IRubyObject marathon = interpreter.evalScriptlet("$marathon");
    interpreter.evalScriptlet("$test = proc { test }");
    runtime = (MarathonRuby) JavaEmbedUtils.rubyToJava(interpreter, marathon, MarathonRuby.class);
}
 
Example #29
Source File: RubyObjectWrapper.java    From asciidoctorj with Apache License 2.0 4 votes vote down vote up
public <T> T toJava(IRubyObject rubyObject, Class<T> targetClass) {
    return (T) JavaEmbedUtils.rubyToJava(runtime, rubyObject, targetClass);
}
 
Example #30
Source File: RubyObjectWrapper.java    From asciidoctorj with Apache License 2.0 4 votes vote down vote up
public Object toJava(IRubyObject rubyObject) {
    return JavaEmbedUtils.rubyToJava(rubyObject);
}