Java Code Examples for org.jruby.embed.ScriptingContainer

The following are top voted examples for showing how to use org.jruby.embed.ScriptingContainer. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: uosl   File: ScriptManager.java   Source Code and License 6 votes vote down vote up
private ScriptManager(String path) {
    this.basePath = path;
    this.packages = new LinkedList<Package>();
    this.ruby = new ScriptingContainer();
    this.commands = new HashMap<String, TextCommand>();
    this.items = new HashMap<String, ItemBehavior>();
    this.mobiles = new HashMap<String, MobileBehavior>();
    this.spells = new HashMap<Spell, SpellHandler>();

    log.config("Using Ruby " + ruby.getCompatVersion());
    Ruby.setThreadLocalRuntime(ruby.getProvider().getRuntime());
    ruby.setCompileMode(CompileMode.FORCE);
    ruby.runScriptlet("require 'yaml'");
    ruby.runScriptlet("java_import " + ScriptAPI.class.getName());
    ruby.runScriptlet("java_import " + ItemBehavior.class.getName());
    ruby.runScriptlet("java_import " + MobileBehavior.class.getName());
    ruby.runScriptlet("java_import " + TextCommand.class.getName());
    ruby.runScriptlet("java_import " + SpellHandler.class.getName());

    // Enumerations
    ruby.runScriptlet("java_import " + Spell.class.getName());
    ruby.runScriptlet("java_import " + Attribute.class.getName());
}
 
Example 2
Project: r01fb   File: RubySassEngine.java   Source Code and License 6 votes vote down vote up
/**
 * Transforms a sass content into css 
 * @param sassOptions sass framework options
 * @param sassCss the Sass content to process.
 */
public String process(final SassOptions sassOptions,
					  final String sassCss) throws ScriptException {
	if (Strings.isNullOrEmpty(sassCss)) return Strings.EMPTY;
	
	SassOptions theSassOptions = sassOptions == null ? SassOptions.DEFAULT_OPTIONS	
													 : sassOptions;
	
	String scriptTemplate = _buildCompileScript(theSassOptions);		
	String theSassToBeCompiled = sassCss.replace("'","\"");
	String theScript = Strings.create(theSassToBeCompiled.length() + scriptTemplate.length())
							  .add(scriptTemplate)
							  .replace("${SOURCE_SASS}",theSassToBeCompiled)
							  .asString();
	log.info(theScript);
	System.out.println(theScript);
	ScriptingContainer rubyEngine = _getOrCreateRubyEngine();
	String compiledCSS = rubyEngine.runScriptlet(theScript)
							   	   .toString();
	return compiledCSS;
}
 
Example 3
Project: embulk-filter-join_file   File: JoinFileFilterPlugin.java   Source Code and License 6 votes vote down vote up
private HashMap<String, TimestampParser> buildTimestampParserMap(ScriptingContainer jruby, List<ColumnConfig> columns, String joinedColumnPrefix, String timeZone)
{
    final HashMap<String, TimestampParser> timestampParserMap = Maps.newHashMap();
    for (ColumnConfig columnConfig: columns) {
        if (Types.TIMESTAMP.equals(columnConfig.getType())) {
            String format = columnConfig.getOption().get(String.class, "format");
            DateTimeZone timezone = DateTimeZone.forID(timeZone);
            TimestampParser parser = new TimestampParser(jruby, format, timezone);

            String columnName = joinedColumnPrefix + columnConfig.getName();

            timestampParserMap.put(columnName, parser);
        }
    }

    return timestampParserMap;
}
 
Example 4
Project: oauth-client-master   File: RubyJwtIntegrationTests.java   Source Code and License 6 votes vote down vote up
public JRubyJwtInstalled() {
	if (!setupOkSet) {
		setupOk = false;
		setupOkSet = true;
		try {
			String script =
					"require \"rubygems\"\n" +
					"require \"jwt\"\n" +
					"require \"bouncy-castle-java\"\n" +
					"require \"openssl\"";
			ScriptingContainer container = new ScriptingContainer();
			container.runScriptlet(script);
			setupOk = true;
		}
		catch (Exception e) {
			System.out.println("jruby.home not set or JWT gem not available. JWT ruby integration tests will be skipped" + e.getMessage());
		}
	}
}
 
Example 5
Project: hive-ruby-scripting   File: GenericUDFRubyExec.java   Source Code and License 6 votes vote down vote up
private void initializeJRubyRuntime() {
    container = new ScriptingContainer(org.jruby.embed.LocalContextScope.SINGLETHREAD);

    if (jobConf != null) {
        container.getLoadPaths().add(jobConf.get(CONF_JRB_LOAD_PATH));
    }

    if (rbScriptParam.startsWith(MODE_METHOD_MARK)) {
        mode = MODE.METHOD;
        evaluateMethod = rbScriptParam.substring(1);
        container.setAttribute(AttributeName.SHARING_VARIABLES, false);
        receiver = container.runScriptlet(rbEnvScript);
    } else {
        mode = MODE.EVAL;
        evalUnit = container.parse(rbScriptParam);
    }

    LOG.info("initialized JRuby runtime (" +
            container.getCompatVersion() + ", " +
            container.getCompileMode()
            + ")");
}
 
Example 6
Project: sponge   File: JRubyProcEventCondition.java   Source Code and License 5 votes vote down vote up
/**
 * Checks rule event condition by evaluating the defined knowledge base rule method.
 *
 * @param rule rule.
 * @param event event.
 * @return {@code true} if this condition is met.
 */
@Override
public boolean condition(Rule rule, Event event) {
    ScriptingContainer scriptContainer =
            ((JRubyKnowledgeBaseInterpreter) rule.getKnowledgeBase().getInterpreter()).getScriptContainer();
    Object result = scriptContainer.callMethod(proc, "call", rule, event);

    if (!(result instanceof Boolean)) {
        throw new IllegalArgumentException("Condition method must return boolean value");
    }

    return (Boolean) result;
}
 
Example 7
Project: embulk-parser-jsonpath   File: TestColumnCaster.java   Source Code and License 5 votes vote down vote up
@Before
public void createResource()
{
    jruby = new ScriptingContainer();
    thrown = new DataException("any");
    Value[] kvs = new Value[2];
    kvs[0] = ValueFactory.newString("k");
    kvs[1] = ValueFactory.newString("v");
    mapValue = ValueFactory.newMap(kvs);
    parser = new TimestampParser(jruby, "%Y-%m-%d %H:%M:%S.%N", DateTimeZone.UTC);
}
 
Example 8
Project: miniscript   File: RubyScriptExecutor.java   Source Code and License 5 votes vote down vote up
@Override
public ScriptExecutionResult execute(GameScript<EmbedEvalUnit> s, ScriptBindings bindings,
		boolean returnResult) throws Exception {
	PerThreadGameScript<EmbedEvalUnit> script = (PerThreadGameScript<EmbedEvalUnit>) s;

	ScriptingContainer scriptingContainer = executorPool.getLocalScriptingContainer();
	
	for (String variableName : bindings.keySet()) {
		scriptingContainer.put(variableName, bindings.get(variableName));
	}
	if (!script.hasLocalScript()) {
		script.putLocalScript(scriptingContainer.parse(script.getContent()));
	}
	
	try {
		EmbedEvalUnit embedEvalUnit = script.getScript();
		embedEvalUnit.run();
	} catch (Exception e) {
		if(e.getCause() instanceof ScriptSkippedException) {
			throw new ScriptSkippedException();
		} else {
			throw e;
		}
	}

	if (!returnResult) {
		scriptingContainer.clear();
		return null;
	}		
	ScriptExecutionResult executionResult = new ScriptExecutionResult(scriptingContainer.getVarMap().getMap());
	scriptingContainer.clear();
	return executionResult;
}
 
Example 9
Project: miniscript   File: RubyScriptExecutorPool.java   Source Code and License 5 votes vote down vote up
public ScriptingContainer getLocalScriptingContainer() {
	long threadId = Thread.currentThread().getId();
	if (!threadCompilers.containsKey(threadId)) {
		ScriptingContainer scriptingContainer = new ScriptingContainer(LocalContextScope.THREADSAFE,
				LocalVariableBehavior.PERSISTENT);
		scriptingContainer.setCompileMode(CompileMode.JIT);
		threadCompilers.put(threadId, scriptingContainer);
	}
	return threadCompilers.get(threadId);
}
 
Example 10
Project: apex-malhar   File: RubyOperator.java   Source Code and License 5 votes vote down vote up
@Override
public void setup(OperatorContext context)
{
  sc = new ScriptingContainer(LocalVariableBehavior.PERSISTENT);
  for (String s : setupScripts) {
    EvalUnit unit = sc.parse(s);
    unit.run();
  }
  if (type == Type.EVAL) {
    unit = sc.parse(script);
  }
}
 
Example 11
Project: embulk-parser-jsonl   File: TestColumnCaster.java   Source Code and License 5 votes vote down vote up
@Before
public void createResource()
{
    jruby = new ScriptingContainer();
    thrown = new DataException("any");
    Value[] kvs = new Value[2];
    kvs[0] = ValueFactory.newString("k");
    kvs[1] = ValueFactory.newString("v");
    mapValue = ValueFactory.newMap(kvs);
    parser = new TimestampParser(jruby, "%Y-%m-%d %H:%M:%S.%N", DateTimeZone.UTC);
}
 
Example 12
Project: zeppelin   File: HbaseInterpreter.java   Source Code and License 5 votes vote down vote up
@Override
public void open() throws InterpreterException {
  this.scriptingContainer  = new ScriptingContainer(LocalContextScope.SINGLETON);
  this.writer = new StringWriter();
  scriptingContainer.setOutput(this.writer);

  if (!Boolean.parseBoolean(getProperty(HBASE_TEST_MODE))) {
    String hbase_home = getProperty(HBASE_HOME);
    String ruby_src = getProperty(HBASE_RUBY_SRC);
    Path abs_ruby_src = Paths.get(hbase_home, ruby_src).toAbsolutePath();

    logger.info("Home:" + hbase_home);
    logger.info("Ruby Src:" + ruby_src);

    File f = abs_ruby_src.toFile();
    if (!f.exists() || !f.isDirectory()) {
      throw new InterpreterException("HBase ruby sources is not available at '" + abs_ruby_src
          + "'");
    }

    logger.info("Absolute Ruby Source:" + abs_ruby_src.toString());
    // hirb.rb:41 requires the following system properties to be set.
    Properties sysProps = System.getProperties();
    sysProps.setProperty(HBASE_RUBY_SRC, abs_ruby_src.toString());

    Path abs_hirb_path = Paths.get(hbase_home, "bin/hirb.rb");
    try {
      FileInputStream fis = new FileInputStream(abs_hirb_path.toFile());
      this.scriptingContainer.runScriptlet(fis, "hirb.rb");
      fis.close();
    } catch (IOException e) {
      throw new InterpreterException(e.getCause());
    }
  }
}
 
Example 13
Project: jpublish   File: HamlViewRenderer.java   Source Code and License 5 votes vote down vote up
/**
 * Load the Haml viewer configuration for the view.
 *
 * @param configuration The configuration object
 */
public void loadConfiguration(Configuration configuration)
        throws ConfigurationException {

    List<String> loadPaths = new ArrayList<String>();
    // SINGLETHREAD is not threadsafe: http://www.ruby-forum.com/topic/206056#new
    container = new ScriptingContainer(LocalContextScope.THREADSAFE);
    scriptingContainerConfiguration = configuration;

    RubyInstanceConfig config = container.getProvider().getRubyInstanceConfig();

    if (scriptingContainerConfiguration != null) {

        jrubyhome = scriptingContainerConfiguration.getChildValue("jruby_home");

        if (jrubyhome != null) {
            config.setJRubyHome(jrubyhome);
            loadPaths.add(jrubyhome);
        }

        String userHamlScript = scriptingContainerConfiguration.getChildValue("haml");
        if (userHamlScript != null) {
            haml_rb = userHamlScript; //just a bit of inversion of control
        }
    }

    haml_rb_unit = container.parse(haml_rb);

    log.info("haml enabled ... have fun!");
}
 
Example 14
Project: APICloud-Studio   File: ScriptingEngine.java   Source Code and License 5 votes vote down vote up
/**
 * getScriptingContainer
 * 
 * @return
 */
public synchronized ScriptingContainer getScriptingContainer()
{
	if (this._scriptingContainer == null)
	{
		this._scriptingContainer = this.createScriptingContainer(LocalContextScope.SINGLETON);
	}

	return this._scriptingContainer;
}
 
Example 15
Project: APICloud-Studio   File: ScriptingEngine.java   Source Code and License 5 votes vote down vote up
public synchronized ScriptingContainer getInitializedScriptingContainer()
{
	ScriptingContainer sc = getScriptingContainer();
	if (!initialized)
	{
		sc.runScriptlet("require 'ruble'"); //$NON-NLS-1$
		initialized = true;
	}
	return sc;
}
 
Example 16
Project: rubygems-servlets   File: LegacyRubygemsServletContextListener.java   Source Code and License 5 votes vote down vote up
public void doContextInitialized( Helper configor ) throws IOException 
{
    // TODO use IsolatedScriptingContainer
    RubygemsGateway gateway = new DefaultRubygemsGateway(new ScriptingContainer());
    File path = configor.getFile( "GEM_PROXY_STORAGE", "var/cache/rubygems/proxy" );
    if ( path == null )
    {
        throw new RuntimeException( "no storage path given");
    }
    ProxyStorage storage = new CachingProxyStorage( path, new URL( "https://rubygems.org" ) );
    RubygemsFileSystem rubygems = new LegacyRubygemsFileSystem( gateway, storage );
    configor.register( RubygemsFileSystem.class.getName(), null, rubygems );
    configor.register( Storage.class.getName(), null, storage );
}
 
Example 17
Project: oauth-client-master   File: RubyJwtIntegrationTests.java   Source Code and License 5 votes vote down vote up
@Test
public void rubyCanDecodeHmacSignedToken() throws Exception {
	Jwt jwt = JwtHelper.encode(TEST_CLAIMS, hmac);
	ScriptingContainer container = new ScriptingContainer();
	container.put("@token", jwt.getEncoded());
	container.put("@claims", "");
	String script =
			"require \"rubygems\"\n" +
			"require \"jwt\"\n" +
			"@claims = JWT.decode(@token, \"secret\", \"HS256\").to_json\n" +
			"puts @claims";
	container.runScriptlet(script);
	assertEquals(TEST_CLAIMS, container.get("@claims"));
}
 
Example 18
Project: oauth-client-master   File: RubyJwtIntegrationTests.java   Source Code and License 5 votes vote down vote up
@Test
public void canDecodeRubyHmacSignedToken() throws Exception {
	ScriptingContainer container = new ScriptingContainer();
	container.put("@token", "xxx");
	String script =
			"require \"rubygems\"\n" +
			"require \"jwt\"\n" +
			"@token = JWT.encode({\"some\" => \"payload\"}, \"secret\", \"HS256\")\n" +
			"puts @token";
	container.runScriptlet(script);
	String token = (String) container.get("@token");
	Jwt jwt = JwtHelper.decodeAndVerify(token, hmac);
	assertEquals(TEST_CLAIMS, jwt.getClaims());
	container.terminate();
}
 
Example 19
Project: hive-ruby-scripting   File: GenericUDAFRubyInject.java   Source Code and License 5 votes vote down vote up
private void initializeJRubyRuntime() {
    container = new ScriptingContainer(org.jruby.embed.LocalContextScope.SINGLETHREAD);

    if (jobConf != null) {
        container.getLoadPaths().add(jobConf.get(RubyScriptingUtils.CONF_JRB_LOAD_PATH));
    }
    container.setAttribute(AttributeName.SHARING_VARIABLES, false);
    receiver = container.runScriptlet(rbEnvScript);

    LOG.info("initialized JRuby runtime (" +
            container.getCompatVersion() + ", " +
            container.getCompileMode()
            + ")");
}
 
Example 20
Project: opoopress   File: CompassBuilder.java   Source Code and License 5 votes vote down vote up
private Properties createCache(File configFile, File cacheFile) {
    ScriptingContainer container = new ScriptingContainer(LocalVariableBehavior.PERSISTENT);
    container.runScriptlet(PathType.ABSOLUTE, configFile.getAbsolutePath());

    @SuppressWarnings("unchecked")
    BiVariableMap<String, Object> varMap = container.getVarMap();
    @SuppressWarnings("unchecked")
    Set<Map.Entry<String, Object>> entrySet = varMap.entrySet();

    Properties props = new Properties();
    for (Map.Entry<String, Object> en : entrySet) {
        if (en.getValue() instanceof String) {
            props.setProperty(en.getKey(), (String) en.getValue());
        }
    }

    //save
    FileOutputStream outputStream = null;
    try {
        outputStream = new FileOutputStream(cacheFile);
        props.store(outputStream, "Compass config cache");
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }

    return props;
}
 
Example 21
Project: rack-servlet   File: MultiValuedHeadersTest.java   Source Code and License 5 votes vote down vote up
@Before public void setUp() throws Exception {
  // Silence logging.
  System.setProperty(DEFAULT_LOG_LEVEL_KEY, "WARN");

  // Build the Rack servlet.
  ScriptingContainer ruby = new ScriptingContainer();
  IRubyObject application = ruby.parse(CLASSPATH, "application.rb").run();
  RackServlet servlet = new RackServlet(new JRubyRackApplication(application));

  server = new ExampleServer(servlet, "/*");
  server.start();
  client = new DefaultHttpClient();
  localhost = new HttpHost("localhost", server.getPort());
}
 
Example 22
Project: rack-servlet   File: HeaderFlushingTest.java   Source Code and License 5 votes vote down vote up
@Before public void setUp() throws Exception {
  // Silence logging.
  System.setProperty(DEFAULT_LOG_LEVEL_KEY, "WARN");

  // Build the Rack servlet.
  ScriptingContainer ruby = new ScriptingContainer();
  IRubyObject application = ruby.parse(CLASSPATH, "application.rb").run();
  RackServlet servlet = new RackServlet(new JRubyRackApplication(application));

  server = new ExampleServer(servlet, "/*");
  server.start();
  client = new DefaultHttpClient();
  localhost = new HttpHost("localhost", server.getPort());
}
 
Example 23
Project: rack-servlet   File: ExampleService.java   Source Code and License 5 votes vote down vote up
private IRubyObject createApplication() {
  // There's a lot you could do here; for now, we just read a rackup file from the classpath,
  // then build a Rack application based on it.
  ScriptingContainer container = new ScriptingContainer();
  container.put("builder_script", readResource("config.ru"));
  return container.parse("require 'rack'; Rack::Builder.new_from_string(builder_script)").run();
}
 
Example 24
Project: rack-servlet   File: ExampleServerTest.java   Source Code and License 5 votes vote down vote up
@Before public void setUp() throws Exception {
  // Silence logging.
  System.setProperty(DEFAULT_LOG_LEVEL_KEY, "WARN");

  // Build the Rack servlet.
  ScriptingContainer ruby = new ScriptingContainer();
  IRubyObject application = ruby.parse("lambda { |env| [200, {}, ['Hello, World!']] }").run();
  RackServlet servlet = new RackServlet(new JRubyRackApplication(application));

  server = new ExampleServer(servlet, "/*");
  server.start();
  client = new DefaultHttpClient();
  localhost = new HttpHost("localhost", server.getPort());
}
 
Example 25
Project: jcompass   File: CompassCompiler.java   Source Code and License 5 votes vote down vote up
public JavaEmbedUtils.EvalUnit getScript() throws FileNotFoundException {
    if (this.unit == null) {
        if (!this.configFile.exists()) {
            throw new FileNotFoundException("Configuration file does not exist");
        }

        ScriptingContainer scriptingContainer = new ScriptingContainer(
                LocalContextScope.THREADSAFE,
                LocalVariableBehavior.PERSISTENT);

        scriptingContainer.setOutput(new PrintStream(new NullOutputStream()));

        StringBuilder script = new StringBuilder()
                .append("require 'compass'\n")
                .append("require 'compass/sass_compiler'\n")
                .append("Compass.reset_configuration!\n")
                .append("Compass.add_project_configuration configLocation\n")

                        // remove color codes since they cannot be proceeded correctly by IDE consoles
                .append("Compass.configuration.color_output = false\n")

                .append("Compass.configure_sass_plugin!\n")
                .append("Compass.configuration.on_stylesheet_saved { |filename| callback_logger.onStylesheetSaved(filename) }\n")
                .append("Compass.configuration.on_stylesheet_error { |filename, message| callback_logger.onStylesheetError(filename, message) }\n")
                .append("Compass.configuration.on_sprite_saved { |filename| callback_logger.onSpriteSaved(filename) }\n")
                .append("Dir.chdir(File.dirname(configLocation)) do\n")
                .append("  Compass.sass_compiler.compile!\n")
                .append("end\n");

        scriptingContainer.put("configLocation", this.configFile.getAbsolutePath().replaceAll("\\\\", "/"));
        scriptingContainer.put("callback_logger", callbackLogger);
        this.unit = scriptingContainer.parse(script.toString());
    }

    return this.unit;
}
 
Example 26
Project: sponge   File: JRubyKnowledgeBaseInterpreter.java   Source Code and License 4 votes vote down vote up
@Override
protected void prepareInterpreter() {
    container = new ScriptingContainer(LocalContextScope.SINGLETHREAD, LocalVariableBehavior.PERSISTENT);
    setLoadPaths(getEngineOperations() != null ? getEngineOperations().getEngine() : null);

    addSpecific();

    PROCESSOR_CLASSES.forEach((interfaceClass, scriptClass) -> addImport(scriptClass, interfaceClass.getSimpleName()));
    addImport(JRubyPlugin.class, Plugin.class.getSimpleName());

    getStandardImportClasses().forEach(cls -> addImport(cls));

    addImport(RubyUtils.class);

    container.put(createVariableName(KnowledgeBaseConstants.VAR_ENGINE_OPERATIONS), getEngineOperations());

    container.setErrorWriter(new JRubyLogErrorWriter());
}
 
Example 27
Project: sponge   File: JRubyKnowledgeBaseInterpreter.java   Source Code and License 4 votes vote down vote up
public ScriptingContainer getScriptContainer() {
    return container;
}
 
Example 28
Project: FatJar   File: RubyScript.java   Source Code and License 4 votes vote down vote up
public RubyScript() {
    container = new ScriptingContainer();
}
 
Example 29
Project: embulk-parser-jsonpath   File: TestStringCast.java   Source Code and License 4 votes vote down vote up
@Before
public void createResource()
{
    jruby = new ScriptingContainer();
}
 
Example 30
Project: embulk-filter-typecast   File: ColumnCaster.java   Source Code and License 4 votes vote down vote up
@Override
public ScriptingContainer getJRuby()
{
    return null;
}
 
Example 31
Project: embulk-filter-typecast   File: ColumnCaster.java   Source Code and License 4 votes vote down vote up
@Override
public ScriptingContainer getJRuby()
{
    return null;
}
 
Example 32
Project: embulk-filter-timestamp_format   File: TimestampParser.java   Source Code and License 4 votes vote down vote up
@Override
public ScriptingContainer getJRuby()
{
    return null;
}
 
Example 33
Project: embulk-parser-jsonl   File: TestStringCast.java   Source Code and License 4 votes vote down vote up
@Before
public void createResource()
{
    jruby = new ScriptingContainer();
}
 
Example 34
Project: golo-jmh-benchmarks   File: JRubyContainerAndReceiver.java   Source Code and License 4 votes vote down vote up
public JRubyContainerAndReceiver(ScriptingContainer container, Object receiver) {
  this.container = container;
  this.receiver = receiver;
}
 
Example 35
Project: golo-jmh-benchmarks   File: JRubyContainerAndReceiver.java   Source Code and License 4 votes vote down vote up
public ScriptingContainer container() {
  return container;
}
 
Example 36
Project: golo-jmh-benchmarks   File: CodeLoader.java   Source Code and License 4 votes vote down vote up
public JRubyContainerAndReceiver jruby(String file) {
  ScriptingContainer container = new ScriptingContainer();
  String filename = "snippets/jruby/" + file + ".rb";
  return new JRubyContainerAndReceiver(container,
      container.runScriptlet(CodeLoader.class.getResourceAsStream("/" + filename), filename));
}
 
Example 37
Project: embulk-filter-row   File: ParserLiteral.java   Source Code and License 4 votes vote down vote up
@Override
public ScriptingContainer getJRuby()
{
    return null;
}
 
Example 38
Project: embulk-filter-row   File: ConditionFactory.java   Source Code and License 4 votes vote down vote up
@Override
public ScriptingContainer getJRuby()
{
    return null;
}
 
Example 39
Project: embulk-input-hdfs   File: Strftime.java   Source Code and License 4 votes vote down vote up
@ConfigInject
ScriptingContainer getJRuby();
 
Example 40
Project: embulk-output-hdfs   File: StrftimeUtil.java   Source Code and License 4 votes vote down vote up
public static String strftime(String format, int rewindSeconds)
{
    String script = buildScript(format, rewindSeconds);
    return new ScriptingContainer().runScriptlet(script).toString();
}
 
Example 41
Project: Redux   File: ReduxJRubyEngine.java   Source Code and License 4 votes vote down vote up
public void init() {
    engineContainer = new ScriptingContainer(LocalContextScope.SINGLETON);
    addJavaObject("ReduxAPI", new ReduxAPI(this));
}
 
Example 42
Project: APICloud-Studio   File: ScriptingEngine.java   Source Code and License 4 votes vote down vote up
/**
 * createScriptingContainer
 * 
 * @param scope
 * @return
 */
private ScriptingContainer createScriptingContainer(LocalContextScope scope)
{
	// ScriptingContainer result = new ScriptingContainer(scope, LocalVariableBehavior.PERSISTENT);
	ScriptingContainer result = new ScriptingContainer(scope, LocalVariableBehavior.TRANSIENT);

	try
	{
		File jrubyHome = null;
		Bundle jruby = Platform.getBundle("org.jruby"); //$NON-NLS-1$
		// try just exploding the jruby lib dir
		URL url = FileLocator.find(jruby, new Path("lib"), null); //$NON-NLS-1$

		if (url != null)
		{
			File lib = ResourceUtil.resourcePathToFile(url);
			// Ok, now use the parent of exploded lib dir as JRuby Home
			jrubyHome = lib.getParentFile();
		}
		else
		{
			// Ok, just assume the plugin is unpacked and pass the root of the plugin as JRuby Home
			jrubyHome = FileLocator.getBundleFile(jruby);
		}

		result.setHomeDirectory(jrubyHome.getAbsolutePath());

		// TODO Generate two containers? A global one for loading bundles, a threadsafe one for executing
		// commands/snippets/etc?
		// Pre-load 'ruble' framework files!
		List<String> loadPaths = result.getLoadPaths();
		loadPaths.addAll(0, getContributedLoadPaths());
		result.setLoadPaths(loadPaths);
	}
	catch (IOException e)
	{
		String message = MessageFormat.format(Messages.ScriptingEngine_Error_Setting_JRuby_Home,
				new Object[] { e.getMessage() });

		IdeLog.logError(ScriptingActivator.getDefault(), message, e);
		ScriptLogger.logError(message);
	}

	return result;
}
 
Example 43
Project: Mewtwo   File: JRubyWrapper.java   Source Code and License 4 votes vote down vote up
/**
 * Create a new JRuby wrapper.
 * @param profile whether or not profiling is enabled
 */
public JRubyWrapper(boolean profile) {
    rb = new ScriptingContainer(LocalContextScope.THREADSAFE);
    rb.setCompatVersion(CompatVersion.RUBY1_9);
    rb.setCurrentDirectory(Paths.get("").toAbsolutePath().toString()); // set working directory of scripts to working directory of application

    @SuppressWarnings("unchecked")
    Map<String, String> env = new HashMap<>(rb.getEnvironment());

    env.put("GEM_PATH", Paths.get("lib/gems").toAbsolutePath().toString());
    MewtwoMain.mewtwoLogger.info("Setting GEM_PATH of container to " + env.get("GEM_PATH"));

    rb.setEnvironment(env);

    ArrayList<String> loadPaths = new ArrayList<>();

    File gemsFile = Paths.get("lib/gems").toFile();
    File[] files = gemsFile.listFiles();

    for(File child : files != null ? files : new File[0]) {
        String subPath = Paths.get(child.getAbsolutePath()).resolve("lib").toString();
        MewtwoMain.mewtwoLogger.info("Adding '" + subPath + "' to loadPaths");
        loadPaths.add(subPath);
    }

    rb.setLoadPaths(loadPaths);


    swOut = new StringWriter();
    swErr = new StringWriter();

    PrintWriter pwOut = new PrintWriter(swOut);
    PrintWriter pwErr = new PrintWriter(swErr);

    rb.setOutput(pwOut);
    rb.setError(pwErr);

    if(profile) {
            rb.setProfile(RubyInstanceConfig.ProfilingMode.GRAPH);
        try {
            rb.setProfileOutput(new ProfileOutput(new File("profile.txt")));
        } catch(IOException e) {
            MewtwoMain.mewtwoLogger.error("Could not initialize JRuby profiler! Disabling profiling.");
        }
    }

    long time = System.currentTimeMillis();
    MewtwoMain.mewtwoLogger.info("Initializing ScriptingContainer - this might take a few seconds!");

    rb.runScriptlet("require 'java'; Java::Meew0Mewtwo::MewtwoMain.mewtwoLogger.info('Hello world! This is JRuby')");

    MewtwoMain.mewtwoLogger.info("ScriptingContainer successfully initialized in " +
            (System.currentTimeMillis() - time) + " ms");
}
 
Example 44
Project: asciidoctorj   File: JRubyAsciidoctor.java   Source Code and License 4 votes vote down vote up
private static Asciidoctor createJRubyAsciidoctorInstance(ClassLoader classloader, String gemPath) {

        Map<String, Object> env = new HashMap<String, Object>();
        env.put(GEM_PATH, gemPath);

        ScriptingContainer container = new ScriptingContainer();
        injectEnvironmentVariables(container.getProvider().getRubyInstanceConfig(), env);
        container.setClassLoader(classloader);
        Ruby rubyRuntime = container.getProvider().getRuntime();

        JRubyRuntimeContext.set(rubyRuntime);

        JRubyAsciidoctorModuleFactory jRubyAsciidoctorModuleFactory = new JRubyAsciidoctorModuleFactory(rubyRuntime);

        AsciidoctorModule asciidoctorModule = jRubyAsciidoctorModuleFactory.createAsciidoctorModule();
        JRubyAsciidoctor jRubyAsciidoctor = new JRubyAsciidoctor(asciidoctorModule, rubyRuntime);

        return jRubyAsciidoctor;
    }
 
Example 45
Project: opoopress   File: CompassV2.java   Source Code and License 4 votes vote down vote up
private void runScriptlet(String script) {
    log.debug(script);
    new ScriptingContainer().runScriptlet(script);
}
 
Example 46
Project: opoopress   File: Compass.java   Source Code and License 4 votes vote down vote up
private void runScriptlet(String script) {
    log.debug(script);
    new ScriptingContainer().runScriptlet(script);
}
 
Example 47
Project: rack-servlet   File: ExampleServerTest.java   Source Code and License 4 votes vote down vote up
@Provides IRubyObject provideApplication() {
  ScriptingContainer ruby = new ScriptingContainer();
  return ruby.parse("lambda { |env| [200, {}, ['Hello, World!']] }").run();
}
 
Example 48
Project: rack-servlet   File: JRubyRackBodyIteratorTest.java   Source Code and License 4 votes vote down vote up
@Before public void setUp() {
  scriptingContainer = new ScriptingContainer();
  scriptingContainer.runScriptlet(PathType.CLASSPATH, "enumerable_with_close.rb");
}
 
Example 49
Project: jruby-java-clojure-red-bridge   File: JavaJRubyRedBridge.java   Source Code and License 4 votes vote down vote up
public ScriptingContainer getScriptingContainer() throws IOException {
  if (valueScriptingContainer == null) {
    throw new IOException("SCRIPTING CONTAINER IS NULL");
  }
  return valueScriptingContainer;
}
 
Example 50
Project: jruby-java-clojure-red-bridge   File: JavaJRubyRedBridge.java   Source Code and License 4 votes vote down vote up
public void setScriptingContainer(ScriptingContainer newContainer)  {
  valueScriptingContainer = newContainer;
}
 
Example 51
Project: jruby-java-clojure-red-bridge   File: JavaJRubyRedBridge.java   Source Code and License 4 votes vote down vote up
public ScriptingContainer findScriptingContainer() throws IOException {
  if (! haveScriptingContainer()) {
    setScriptingContainer(newScriptingContainer());
  }
  return getScriptingContainer();
}
 
Example 52
Project: jruby-java-clojure-red-bridge   File: JavaJRubyRedBridge.java   Source Code and License 3 votes vote down vote up
public ScriptingContainer newScriptingContainer() throws IOException {

    ScriptingContainer newContainer = new ScriptingContainer();

    logger.info("JJRB::newScriptingContainer <=> NEW CONTAINER >{}<", newContainer);

    return newContainer;

  }