下面列出了org.eclipse.jface.text.source.projection.ProjectionAnnotation#org.jruby.runtime.builtin.IRubyObject 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
}
/**
* Create a new JRuby-scripted object from the given script source.
* @param scriptSource the script source text
* @param interfaces the interfaces that the scripted Java object is to implement
* @param classLoader the {@link ClassLoader} to create the script proxy with
* @return the scripted Java object
* @throws JumpException in case of JRuby parsing failure
*/
public static Object createJRubyObject(String scriptSource, Class<?>[] interfaces, ClassLoader classLoader) {
Ruby ruby = initializeRuntime();
Node scriptRootNode = ruby.parseEval(scriptSource, "", null, 0);
IRubyObject rubyObject = ruby.runNormally(scriptRootNode);
if (rubyObject instanceof RubyNil) {
String className = findClassName(scriptRootNode);
rubyObject = ruby.evalScriptlet("\n" + className + ".new");
}
// still null?
if (rubyObject instanceof RubyNil) {
throw new IllegalStateException("Compilation of JRuby script returned RubyNil: " + rubyObject);
}
return Proxy.newProxyInstance(classLoader, interfaces, new RubyObjectInvocationHandler(rubyObject, ruby));
}
/**
* Hooks this <code>TextAreaReadline</code> instance into the runtime,
* redefining the <code>Readline</code> module so that it uses this object.
* This method does not redefine the standard input-output streams. If you
* need that, use {@link #hookIntoRuntimeWithStreams(Ruby)}.
*
* @param runtime The runtime.
* @see #hookIntoRuntimeWithStreams(Ruby)
*/
public void hookIntoRuntime(final Ruby runtime) {
this.runtime = runtime;
/* Hack in to replace usual readline with this */
runtime.getLoadService().require("readline");
RubyModule readlineM = runtime.fastGetModule("Readline");
readlineM.defineModuleFunction("readline", new Callback() {
public IRubyObject execute(IRubyObject recv, IRubyObject[] args,
Block block) {
String line = readLine(args[0].toString());
if (line != null) {
return RubyString.newUnicodeString(runtime, line);
} else {
return runtime.getNil();
}
}
public Arity getArity() {
return Arity.twoArguments();
}
});
}
@JRubyMethod(name = "initialize", required = 2, optional = 2)
public IRubyObject rubyInitialize(final ThreadContext ctx, final IRubyObject[] args) {
final Ruby ruby = ctx.runtime;
try {
dissectors = DissectPair.createArrayFromHash((RubyHash) args[0]);
} catch (final InvalidFieldException e) {
throw new RaiseException(e, JavaDissectorLibrary.NativeExceptions.newFieldFormatError(ruby, e));
}
plugin = (RubyObject) args[1];
pluginMetaClass = plugin.getMetaClass();
conversions = ConvertPair.createArrayFromHash((RubyHash) args[2]);
for (final ConvertPair convertPair : conversions) {
if (convertPair.converter().isInvalid()) {
final RubyClass klass = ruby.getModule("LogStash").getClass("ConvertDatatypeFormatError");
final String errorMessage = String.format("Dissector datatype conversion, datatype not supported: %s", convertPair.type());
throw new RaiseException(ruby, klass, errorMessage, true);
}
}
runMatched = args[3] == null || args[3].isTrue();
failureTags = fetchFailureTags(ctx);
return ctx.nil;
}
/**
* setConsole
*
* @param ostream
*/
protected IRubyObject setConsole(OutputStream ostream)
{
Ruby runtime = getRuntime();
RubyClass object = runtime.getObject();
IRubyObject oldValue = null;
// CONSOLE will only exist already if one command invokes another
if (object.hasConstant(CONSOLE_CONSTANT))
{
oldValue = object.getConstant(CONSOLE_CONSTANT);
}
if (ostream != null)
{
RubyIO io = new RubyIO(runtime, ostream);
io.getOpenFile().getMainStream().setSync(true);
setConsole(io);
}
return oldValue;
}
/**
* This calls to the static method compare of DataByteArray. Given two DataByteArrays, it will call it
* on the underlying bytes.
*
* @param context the context the method is being executed in
* @param self an class which contains metadata on the calling class (required for static Ruby methods)
* @param arg1 a RubyDataByteArray or byte array to compare
* @param arg2 a RubyDataByteArray or byte array to compare
* @return the Fixnum result of comparing arg1 and arg2's bytes
*/
@JRubyMethod
public static RubyFixnum compare(ThreadContext context, IRubyObject self, IRubyObject arg1, IRubyObject arg2) {
byte[] buf1, buf2;
if (arg1 instanceof RubyDataByteArray) {
buf1 = ((RubyDataByteArray)arg1).getDBA().get();
} else {
buf1 = (byte[])arg1.toJava(byte[].class);
}
if (arg2 instanceof RubyDataByteArray) {
buf2 = ((RubyDataByteArray)arg2).getDBA().get();
} else {
buf2 = (byte[])arg2.toJava(byte[].class);
}
return RubyFixnum.newFixnum(context.getRuntime(), DataByteArray.compare(buf1, buf2));
}
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;
}
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, "Browser"); //$NON-NLS-1$
context.put("browser", rubyInstance); //$NON-NLS-1$
}
else
{
context.put("browser", null); //$NON-NLS-1$
}
}
}
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);
}
}
}
/**
* This method registers the class with the given runtime.
*
* @param runtime an instance of the Ruby runtime
* @return a RubyClass object with metadata about the registered class
*/
public static RubyClass define(Ruby runtime) {
RubyClass result = runtime.defineClass("Schema",runtime.getObject(), ALLOCATOR);
result.kindOf = new RubyModule.KindOf() {
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubySchema;
}
};
result.includeModule(runtime.getEnumerable());
result.defineAnnotatedMethods(RubySchema.class);
return result;
}
@Override
public T set(int index, T element) {
Object oldObject;
if (element instanceof IRubyObject) {
oldObject = rubyBlockList.set(index, element);
} else {
oldObject = rubyBlockList.set(index, ((ContentNodeImpl) element).getRubyObject());
}
return (T) NodeConverter.createASTNode(oldObject);
}
public static RubyClass register(final JRubyAsciidoctor asciidoctor, final BlockProcessor blockProcessor) {
RubyClass rubyClass = ProcessorProxyUtil.defineProcessorClass(asciidoctor.getRubyRuntime(), "BlockProcessor", new JRubyAsciidoctorObjectAllocator(asciidoctor) {
@Override
public IRubyObject allocate(Ruby runtime, RubyClass klazz) {
return new BlockProcessorProxy(asciidoctor, klazz, blockProcessor);
}
});
applyAnnotations(blockProcessor.getClass(), rubyClass);
ProcessorProxyUtil.defineAnnotatedMethods(rubyClass, BlockProcessorProxy.class);
return rubyClass;
}
@Override
public ExtensionGroup treeprocessor(final Class<? extends Treeprocessor> treeProcessor) {
final RubyClass rubyClass = TreeprocessorProxy.register(asciidoctor, treeProcessor);
registrators.add(new Registrator() {
@Override
public void register(IRubyObject registry) {
registry.callMethod(rubyRuntime.getCurrentContext(), "tree_processor", rubyClass);
}
});
return this;
}
@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(),
METHOD_NAME_INITIALIZE,
new IRubyObject[]{RubyHashUtil.convertMapToRubyHashWithSymbols(getRuntime(), getProcessor().getConfig())},
Block.NULL_BLOCK);
// The extension config in the Java extension is just a view on the @config member of the Ruby part
getProcessor().updateConfig(new RubyHashMapDecorator((RubyHash) getInstanceVariable(MEMBER_NAME_CONFIG)));
} 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;
}
@Test public void iteratingOverAThingThatRespondsToClose_shouldCloseTheThing() {
IRubyObject body = scriptingContainer.parse("EnumerableWithClose.new(%w(first second third))").run();
JRubyRackBodyIterator subject = new JRubyRackBodyIterator(body);
assertThat(isOpen(body)).isEqualTo(true);
while (subject.hasNext()) {
subject.next();
}
assertThat(isOpen(body)).isEqualTo(false);
}
@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());
}
/**
* This is just a convenience method which sets the name of the internalSchema to the argument that was given.
*
* @param arg a RubyString to set the name of the encapsulated Schema object
*/
private void setNameIf(IRubyObject arg) {
if (arg instanceof RubyString) {
setName(arg.toString());
} else {
throw new RuntimeException("Bad name given");
}
}
public static RubyClass register(final JRubyAsciidoctor asciidoctor, final Class<? extends BlockMacroProcessor> blockMacroProcessor) {
RubyClass rubyClass = ProcessorProxyUtil.defineProcessorClass(asciidoctor.getRubyRuntime(), "BlockMacroProcessor", new JRubyAsciidoctorObjectAllocator(asciidoctor) {
@Override
public IRubyObject allocate(Ruby runtime, RubyClass klazz) {
return new BlockMacroProcessorProxy(asciidoctor, klazz, blockMacroProcessor);
}
});
applyAnnotations(blockMacroProcessor, rubyClass);
ProcessorProxyUtil.defineAnnotatedMethods(rubyClass, BlockMacroProcessorProxy.class);
return rubyClass;
}
protected IRubyObject convertProcessorResult(Object o) {
if (o instanceof ContentNodeImpl) {
return ((ContentNodeImpl) o).getRubyObject();
} else {
return JavaEmbedUtils.javaToRuby(getRuntime(), o);
}
}
@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(),
METHOD_NAME_INITIALIZE,
new IRubyObject[]{
RubyHashUtil.convertMapToRubyHashWithSymbols(getRuntime(), getProcessor().getConfig())},
Block.NULL_BLOCK);
// The extension config in the Java extension is just a view on the @config member of the Ruby part
getProcessor().updateConfig(new RubyHashMapDecorator((RubyHash) getInstanceVariable(MEMBER_NAME_CONFIG)));
} 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;
}
@Override
public Cell createTableCell(Column column, String text, Map<String, Object> attributes) {
Ruby rubyRuntime = JRubyRuntimeContext.get(column);
RubyHash rubyAttributes = RubyHash.newHash(rubyRuntime);
rubyAttributes.putAll(attributes);
IRubyObject[] parameters = {
((ColumnImpl) column).getRubyObject(),
text != null ? rubyRuntime.newString(text) : rubyRuntime.getNil(),
rubyAttributes}; // No cursor parameter yet
return (Cell) NodeConverter.createASTNode(rubyRuntime, NodeConverter.NodeType.TABLE_CELL_CLASS, parameters);
}
static ConvertPair[] createArrayFromHash(final RubyHash hash) {
if (hash.isNil()) {
return EMPTY_ARRAY;
}
// a hash iterator that is independent of JRuby 1.7 and 9.0 (Visitor vs VisitorWithState)
// this does not use unchecked casts
// RubyHash inst.to_a() creates an array of arrays each having the key and value as elements
final IRubyObject[] convertPairs = hash.to_a().toJavaArray();
final ConvertPair[] pairs = new ConvertPair[convertPairs.length];
for (int idx = 0; idx < convertPairs.length; idx++) {
pairs[idx] = create((RubyArray) convertPairs[idx]);
}
return pairs;
}
/**
* Given two RubyDataByteArrays, initializes the encapsulated DataByteArray
* to be a concatentation of the copied bits of the first and second.
*
* @param arg1 the first RubyDataByteArray whose bits will be used
* @param arg2 the second RubyDataByteArray whose bits will be concatenated
after the first's
* @return the initialized RubyDataBytearray
*/
@JRubyMethod
public RubyDataByteArray initialize(IRubyObject arg1, IRubyObject arg2) {
if (arg1 instanceof RubyDataByteArray && arg2 instanceof RubyDataByteArray) {
internalDBA = new DataByteArray(((RubyDataByteArray)arg1).getDBA(), ((RubyDataByteArray)arg2).getDBA());
} else {
throw new IllegalArgumentException("Invalid arguments passed to DataByteArray");
}
return this;
}
@JRubyMethod(visibility = Visibility.PRIVATE)
public IRubyObject initialize(ThreadContext context, IRubyObject src,IRubyObject file, IRubyObject line) {
filename = filenameAsString(context, file).dup();
parser = new RipperParser(context, this, source(context, src, filename.asJavaString(), lineAsInt(context, line)));
return context.nil;
}
@Override
public ExtensionGroup rubyInlineMacro(final String macroName, final String inlineMacroProcessor) {
registrators.add(new Registrator() {
@Override
public void register(IRubyObject registry) {
registry.callMethod(rubyRuntime.getCurrentContext(), "inline_macro", new IRubyObject[]{rubyRuntime.newString(inlineMacroProcessor), rubyRuntime.newSymbol(macroName)});
}
});
return this;
}
@Override
public Block createBlock(StructuralNode parent, String context,
Map<Object, Object> options) {
Ruby rubyRuntime = JRubyRuntimeContext.get(parent);
RubyHash convertMapToRubyHashWithSymbols = RubyHashUtil.convertMapToRubyHashWithSymbolsIfNecessary(rubyRuntime,
filterBlockOptions(parent, options, "subs", ContentModel.KEY));
IRubyObject[] parameters = {
((StructuralNodeImpl) parent).getRubyObject(),
RubyUtils.toSymbol(rubyRuntime, context),
convertMapToRubyHashWithSymbols};
return (Block) NodeConverter.createASTNode(rubyRuntime, NodeConverter.NodeType.BLOCK_CLASS, parameters);
}
/**
* setReader
*
* @param io
*/
protected void setReader(IRubyObject io)
{
Ruby runtime = this.getRuntime();
runtime.defineVariable(new InputGlobalVariable(runtime, STDIN_GLOBAL, io));
runtime.defineGlobalConstant(STDIN_CONSTANT, io);
}
@JRubyMethod
public IRubyObject column(ThreadContext context) {
if (!parser.hasStarted()) throw context.runtime.newArgumentError("method called for uninitialized object");
if (!parseStarted) return context.nil;
return context.runtime.newFixnum(parser.getColumn());
}
@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();
}
public int getInt(String propertyName, Object... args) {
IRubyObject result = getRubyProperty(propertyName, args);
if (result instanceof RubyNil) {
return 0;
} else {
return (int) ((RubyNumeric) result).getLongValue();
}
}