Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.jruby.javasupport;

BEGIN LICENSE BLOCK ***** Version: EPL 1.0/GPL 2.0/LGPL 2.1 The contents of this file are subject to the Eclipse Public License Version 1.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.eclipse.org/legal/epl-v10.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Copyright (C) 2006 Thomas E Enebo <enebo@acm.org> Alternatively, the contents of this file may be used under the terms of either of the GNU General Public License Version 2 or later (the "GPL"), or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), in which case the provisions of the GPL or the LGPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of either the GPL or the LGPL, and not to allow others to use your version of this file under the terms of the EPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL or the LGPL. If you do not delete the provisions above, a recipient may use your version of this file under the terms of any one of the EPL, the GPL or the LGPL. END LICENSE BLOCK ***
 
 
 import java.util.List;
 
 import org.jruby.Ruby;
Utility functions to help embedders out. These function consolidate logic that is used between BSF and JSR 223. People who are embedding JRuby 'raw' should use these as well. If at a later date, we discover a flaw or change how we do things, this utility class should provide some insulation. Example: Ruby runtime = JavaEmbedUtils.initialize(new ArrayList()); RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter(); IRubyObject rubyObject = evaler.parse(runtime, expr.toString(), file, line).run()); SomeClassOrInterface javaObject = (SomeClassOrInterface) JavaEmbedUtils.rubyToJava(rubyObject); runtime.terminate();
 
 public class JavaEmbedUtils {
    
Get an instance of a JRuby runtime. Provide any loadpaths you want used at startup.

Parameters:
loadPaths to specify where to look for Ruby modules.
Returns:
an instance
 
     public static Ruby initialize(List loadPaths) {
         return initialize(loadPathsnew RubyInstanceConfig());
     }
    
    
Get an instance of a JRuby runtime. Provide any loadpaths you want used at startup.

Parameters:
loadPaths to specify where to look for Ruby modules.
classCache to use as a common repository for cached classes
Returns:
an instance
 
     public static Ruby initialize(List loadPathsClassCache classCache) {
         RubyInstanceConfig config = new RubyInstanceConfig();
         if (classCache != null) {
             config.setClassCache(classCache);
         }
         return initialize(loadPathsconfig);
     }

    
Get an instance of a JRuby runtime.

Parameters:
loadPaths additional load paths you wish to add
config a runtime configuration instance
Returns:
an instance
 
     public static Ruby initialize(List loadPathsRubyInstanceConfig config) {
         Ruby runtime = Ruby.newInstance(config);
         runtime.getLoadService().addPaths((List<String>)loadPaths);
         runtime.getLoadService().require("java");
 
         return runtime;
     }
    
    
Generate a class cache. This will end up setting max cache size per JRuby preferences (e.g. jruby.jit.max).

Parameters:
loader use the provided classloader to create the cache
Returns:
    public static ClassCache createClassCache(ClassLoader loader) {
        return new ClassCache(loadernew RubyInstanceConfig().getJitMax()); 
    }
    public static RubyObjectAdapter newObjectAdapter() {
        return new RubyObjectAdapter() {
            public boolean isKindOf(IRubyObject valueRubyModule rubyModule) {
                return rubyModule.isInstance(value);
            }
            public IRubyObject setInstanceVariable(IRubyObject objString variableNameIRubyObject value) {
                return obj.getInstanceVariables().setInstanceVariable(variableNamevalue);
            }
            public IRubyObject[] convertToJavaArray(IRubyObject array) {
                return ((RubyArrayarray).toJavaArray();
            }
            public RubyInteger convertToRubyInteger(IRubyObject obj) {
                return obj.convertToInteger();
            }
            public IRubyObject getInstanceVariable(IRubyObject objString variableName) {
                return obj.getInstanceVariables().getInstanceVariable(variableName);
            }
            public RubyString convertToRubyString(IRubyObject obj) {
                return obj.convertToString();
            }
            public IRubyObject callMethod(IRubyObject receiverString methodName) {
                return receiver.callMethod(receiver.getRuntime().getCurrentContext(), methodName);
            }
            public IRubyObject callMethod(IRubyObject receiverString methodNameIRubyObject singleArg) {
                return receiver.callMethod(receiver.getRuntime().getCurrentContext(), methodNamesingleArg);
            }
            public IRubyObject callMethod(IRubyObject receiverString methodNameIRubyObject[] args) {
                return receiver.callMethod(receiver.getRuntime().getCurrentContext(), methodNameargs);
            }
            public IRubyObject callMethod(IRubyObject receiverString methodNameIRubyObject[] argsBlock block) {
                return receiver.callMethod(receiver.getRuntime().getCurrentContext(), methodNameargsblock);
            }
            public IRubyObject callSuper(IRubyObject receiverIRubyObject[] args) {
                return Helpers.invokeSuper(receiver.getRuntime().getCurrentContext(), receiverargs.);
            }
            public IRubyObject callSuper(IRubyObject receiverIRubyObject[] argsBlock block) {
                return Helpers.invokeSuper(receiver.getRuntime().getCurrentContext(), receiverargsblock);
            }
        };
    }
    public static RubyRuntimeAdapter newRuntimeAdapter() {
        return new RubyRuntimeAdapter() {
            
Evaluate a script and return the last value in the script.

Parameters:
runtime to invoke the script under
script to be evaluated
Returns:
the last value of the script
            public IRubyObject eval(Ruby runtimeString script) {
                return runtime.evalScriptlet(script);
            }

            
Parse the script and return an object which can be run(). This allows the script to be parsed once and evaluated many times.

Parameters:
runtime to parse the script under
script to be parsed
filename the filename to display for parse errors and backtraces
lineNumber the linenumber to display for parse errors and backtraces
Returns:
an object which can be run
            public EvalUnit parse(Ruby runtimeString scriptString filenameint lineNumber) {
                return new InterpretedEvalUnit(runtimeruntime.parseEval(scriptfilenamenulllineNumber));
            }

            
Parse the script and return an object which can be run(). This allows the script to be parsed once and evaluated many times.

Parameters:
runtime to parse the script under
in the script as an inputstream to be parsed
filename the filename to display for parse errors and backtraces
lineNumber the linenumber to display for parse errors and backtraces
Returns:
an object which can be run
            public EvalUnit parse(Ruby runtimeInputStream inString filenameint lineNumber) {
                return new InterpretedEvalUnit(runtimeruntime.parseFile(infilenamenulllineNumber));
            }
        };
    }

    
All implementers can be run and will return the last value in the evaluation unit.
    public static interface EvalUnit {
        

Returns:
results of executing this evaluation unit.
        public IRubyObject run();
    }

    
An evaluation unit which is based on running JRuby's interpreter (as opposed to the compiler).
    public static class InterpretedEvalUnit implements EvalUnit {
        private Ruby runtime;
        private Node node;
        protected InterpretedEvalUnit(Ruby runtimeNode node) {
            this. = runtime;
            this. = node;
        }
        public IRubyObject run() {
            return .runInterpreter();
        }
    }

    
Dispose of the runtime you initialized.

Parameters:
runtime to be disposed of
    public static void terminate(Ruby runtime) {
        runtime.tearDown();
    }

    
Convenience function for embedders

Parameters:
runtime environment where the invoke will occur
receiver is the instance that will receive the method call
method is method to be called
args are the arguments to the method
returnType is the type we want it to conform to
Returns:
the result of the invocation.
    public static Object invokeMethod(Ruby runtimeObject receiverString methodObject[] args,
            Class returnType) {
        IRubyObject rubyReceiver = receiver != null ? JavaUtil.convertJavaToRuby(runtimereceiver) : runtime.getTopSelf();
        IRubyObject[] rubyArgs = JavaUtil.convertJavaArrayToRuby(runtimeargs);
        // Create Ruby proxies for any input arguments that are not primitives.
        for (int i = 0; i < rubyArgs.lengthi++) {
            IRubyObject obj = rubyArgs[i];
            if (obj instanceof JavaObjectrubyArgs[i] = Java.wrap(runtimeobj);
        }
        IRubyObject result = rubyReceiver.callMethod(runtime.getCurrentContext(), methodrubyArgs);
        return rubyToJava(runtimeresultreturnType);
    }

    
Convert a Ruby object to a Java object.
    public static Object rubyToJava(Ruby runtimeIRubyObject valueClass type) {
        return value.toJava(type);
    }

    
Convert the Ruby object to a Java Object.

Parameters:
value to be converted
Returns:
the converted object
    public static Object rubyToJava(IRubyObject value) {
        return value.toJava(Object.class);
    }

    
Convert a java object to a Ruby object.
    public static IRubyObject javaToRuby(Ruby runtimeObject value) {
        if (value instanceof IRubyObjectreturn (IRubyObjectvalue;
        IRubyObject result = JavaUtil.convertJavaToUsableRubyObject(runtimevalue);
        
        return result instanceof JavaObject ? Java.wrap(runtimeresult) : result
    }
    public static IRubyObject javaToRuby(Ruby runtimeboolean value) {
        return javaToRuby(runtimevalue ? . : .);
    }
    public static IRubyObject javaToRuby(Ruby runtimebyte value) {
        return javaToRuby(runtime, Byte.valueOf(value));
    }
    public static IRubyObject javaToRuby(Ruby runtimechar value) {
        return javaToRuby(runtime, Character.valueOf(value));
    }
    public static IRubyObject javaToRuby(Ruby runtimedouble value) {
        return javaToRuby(runtimenew Double(value));
    }
    public static IRubyObject javaToRuby(Ruby runtimefloat value) {
        return javaToRuby(runtimenew Float(value));
    }
    public static IRubyObject javaToRuby(Ruby runtimeint value) {
        return javaToRuby(runtime, Integer.valueOf(value));
    }
    public static IRubyObject javaToRuby(Ruby runtimelong value) {
        return javaToRuby(runtime, Long.valueOf(value));
    }
    public static IRubyObject javaToRuby(Ruby runtimeshort value) {
        return javaToRuby(runtime, Short.valueOf(value));
    }
New to GrepCode? Check out our FAQ X