org.jruby.runtime.ThreadContext Java Examples

The following examples show how to use org.jruby.runtime.ThreadContext. 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: RubyDataByteArray.java    From spork with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
}
 
Example #2
Source File: JavaLogger.java    From asciidoctorj with Apache License 2.0 6 votes vote down vote up
/**
 * @param threadContext
 * @param args
 */
@JRubyMethod(name = "add", required = 1, optional = 2)
public IRubyObject add(final ThreadContext threadContext, final IRubyObject[] args, Block block) {
  final IRubyObject rubyMessage;
  if (args.length >= 2 && !args[1].isNil()) {
    rubyMessage = args[1];
  } else if (block.isGiven()) {
    rubyMessage = block.yield(threadContext, getRuntime().getNil());
  } else {
    rubyMessage = args[2];
  }
  final Cursor cursor = getSourceLocation(rubyMessage);
  final String message = formatMessage(rubyMessage);
  final Severity severity = mapRubyLogLevel(args[0]);

  final LogRecord record = createLogRecord(threadContext, severity, cursor, message);

  rootLogHandler.log(record);
  return getRuntime().getNil();
}
 
Example #3
Source File: RubyDataBag.java    From spork with Apache License 2.0 6 votes vote down vote up
/**
 * This is an implementation of the each method which opens up the Enumerable interface,
 * and makes it very convenient to iterate over the elements of a DataBag. Note that currently,
 * due to a deficiency in JRuby, it is not possible to call each without a block given.
 *
 * @param context the context the method is being executed in
 * @param block   a block to call on the elements of the bag
 * @return        enumerator object if null block given, nil otherwise
 */
@JRubyMethod
public IRubyObject each(ThreadContext context, Block block) throws ExecException{
    Ruby runtime = context.getRuntime();

    if (!block.isGiven())
        return PigJrubyLibrary.enumeratorize(runtime, this, "each");
    /*  In a future release of JRuby when enumeratorize is made public (which is planned), should replace the above with the below
    if (!block.isGiven())
        return RubyEnumerator.enumeratorize(context.getRuntime(), this, "each");
    */

    for (Tuple t : this)
        block.yield(context, PigJrubyLibrary.pigToRuby(runtime, t));

    return context.nil;
}
 
Example #4
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 #5
Source File: RubyDataBag.java    From spork with Apache License 2.0 6 votes vote down vote up
/**
 * This is a convenience method which will run the given block on the first element
 * of each tuple contained.
 *
 * @param context the context the method is being executed in
 * @param block   a block to call on the elements of the bag
 * @return        enumerator object if null block given, nil otherwise
 */
@JRubyMethod(name = {"flat_each", "flatten"})
public IRubyObject flatten(ThreadContext context, Block block) throws ExecException {
    Ruby runtime = context.getRuntime();

    if (!block.isGiven())
        return PigJrubyLibrary.enumeratorize(runtime, this, "flatten");
    /*  In a future release of JRuby when enumeratorize is made public (which is planned), should replace the above with the below
    if (!block.isGiven())
        return RubyEnumerator.enumeratorize(context.getRuntime(), this, "flatten");
    */

    for (Tuple t : this)
        block.yield(context, PigJrubyLibrary.pigToRuby(runtime, t.get(0)));

    return context.nil;
}
 
Example #6
Source File: RubySchema.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * This is a ruby method which takes an array of arguments and constructs a Bag schema from them. The name
 * will be set automatically.
 *
 * @param context the context the method is being executed in
 * @param self    the RubyClass for the Class object this was invoked on
 * @param arg     a list of arguments to instantiate the new RubySchema
 * @return        the new RubySchema
 */
@JRubyMethod(meta = true, name = {"b", "bag"})
public static RubySchema bag(ThreadContext context, IRubyObject self, IRubyObject arg) {
    Schema s = tuple(context, self, arg).getInternalSchema();
    Ruby runtime = context.getRuntime();
    try {
        return new RubySchema(runtime, runtime.getClass("Schema"), new Schema(new Schema.FieldSchema("bag_0", s, DataType.BAG)));
    } catch (FrontendException e) {
        throw new RuntimeException("Error making map", e);
    }
}
 
Example #7
Source File: RubyRipper.java    From gocd with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #8
Source File: BlockMacroProcessorProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@JRubyMethod(name = "process", required = 3)
public IRubyObject process(ThreadContext context, IRubyObject parent, IRubyObject target, IRubyObject attributes) {
    Object o = getProcessor().process(
            (StructuralNode) NodeConverter.createASTNode(parent),
            RubyUtils.rubyToJava(getRuntime(), target, String.class),
            new RubyAttributesMapDecorator((RubyHash) attributes));

    return convertProcessorResult(o);

}
 
Example #9
Source File: ConcurrentHashMapV8.java    From thread_safe with Apache License 2.0 5 votes vote down vote up
int rubyCompare(RubyObject l, RubyObject r) {
    ThreadContext context = l.getMetaClass().getRuntime().getCurrentContext();
    IRubyObject result;
    try {
        result = l.callMethod(context, "<=>", r);
    } catch (RaiseException e) {
        // handle objects "lying" about responding to <=>, ie: an Array containing non-comparable keys
        if (context.runtime.getNoMethodError().isInstance(e.getException())) {
            return 0;
        }
        throw e;
    }

    return result.isNil() ? 0 : RubyNumeric.num2int(result.convertToInteger());
}
 
Example #10
Source File: JavaDissectorLibrary.java    From logstash-filter-dissect with Apache License 2.0 5 votes vote down vote up
@JRubyMethod(name = "dissect", required = 1)
public final IRubyObject dissect(final ThreadContext ctx, final IRubyObject arg1) {
    final JrubyEventExtLibrary.RubyEvent rubyEvent = (JrubyEventExtLibrary.RubyEvent) arg1;
    if (rubyEvent.ruby_cancelled(ctx).isTrue()) {
        return ctx.nil;
    }
    final Event event = rubyEvent.getEvent();
    try {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Event before dissection", addLoggableEvent(ctx, rubyEvent, createLoggableHash(ctx)));
        }

        if (dissectors.length > 0) {
            invokeDissection(ctx, rubyEvent, event);
        }
        if (conversions.length > 0) {
            invokeConversions(event);
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Event after dissection", addLoggableEvent(ctx, rubyEvent, createLoggableHash(ctx)));
        }
    } catch (final Exception ex) {
        invokeFailureTagsAndMetric(ctx, event);
        logException(ex);
    }
    return ctx.nil;
}
 
Example #11
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 #12
Source File: JavaDissectorLibrary.java    From logstash-filter-dissect with Apache License 2.0 5 votes vote down vote up
private String[] fetchFailureTags(final ThreadContext ctx) {
    final DynamicMethod method = DynamicMethodCache.get(pluginMetaClass, TAG_ON_FAILURE);
    String[] result = EMPTY_STRINGS_ARRAY;
    if (!method.isUndefined()) {
        final IRubyObject obj = method.call(ctx, plugin, pluginMetaClass, TAG_ON_FAILURE);
        if (obj instanceof RubyArray) {
            final RubyArray tags = (RubyArray) obj;
            result = new String[tags.size()];
            for(int idx = 0; idx < result.length; idx++) {
                result[idx] = tags.entry(idx).asJavaString();
            }
        }
    }
    return result;
}
 
Example #13
Source File: PreprocessorProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@JRubyMethod(name = "process", required = 2)
public IRubyObject process(ThreadContext context, IRubyObject document, IRubyObject preprocessorReader) {
    getProcessor().process(
            (Document) NodeConverter.createASTNode(document),
            new PreprocessorReaderImpl(preprocessorReader));

    return getRuntime().getNil();
}
 
Example #14
Source File: PostprocessorProxy.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(),
                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;
}
 
Example #15
Source File: PostprocessorProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@JRubyMethod(name = "process", required = 2)
public IRubyObject process(ThreadContext context, IRubyObject document, IRubyObject output) {
    Object o = getProcessor().process(
            (Document) NodeConverter.createASTNode(document),
            RubyUtils.rubyToJava(getRuntime(), output, String.class));

    return convertProcessorResult(o);
}
 
Example #16
Source File: JRubyCacheBackendLibrary.java    From thread_safe with Apache License 2.0 5 votes vote down vote up
private ConcurrentHashMap<IRubyObject, IRubyObject> toCHM(ThreadContext context, IRubyObject options) {
    Ruby runtime = context.getRuntime();
    if (!options.isNil() && options.respondsTo("[]")) {
        IRubyObject rInitialCapacity = options.callMethod(context, "[]", runtime.newSymbol("initial_capacity"));
        IRubyObject rLoadFactor      = options.callMethod(context, "[]", runtime.newSymbol("load_factor"));
        int initialCapacity = !rInitialCapacity.isNil() ? RubyNumeric.num2int(rInitialCapacity.convertToInteger()) : DEFAULT_INITIAL_CAPACITY;
        float loadFactor    = !rLoadFactor.isNil() ?      (float)RubyNumeric.num2dbl(rLoadFactor.convertToFloat()) : DEFAULT_LOAD_FACTOR;
        return newCHM(initialCapacity, loadFactor);
    } else {
        return newCHM();
    }
}
 
Example #17
Source File: JRubyCacheBackendLibrary.java    From thread_safe with Apache License 2.0 5 votes vote down vote up
@JRubyMethod
 public IRubyObject each_pair(ThreadContext context, Block block) {
    for (Map.Entry<IRubyObject,IRubyObject> entry : map.entrySet()) {
        block.yieldSpecific(context, entry.getKey(), entry.getValue());
    }
    return this;
}
 
Example #18
Source File: RubyDataBag.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * This method returns a copy of the encapsulated DataBag.
 *
 * @param context the context the method is being executed in
 * @return        the copied RubyDataBag
 */
//TODO see if a deepcopy is necessary as well (and consider adding to DataBag and Tuple)
@JRubyMethod
public RubyDataBag clone(ThreadContext context) {
    DataBag b = mBagFactory.newDefaultBag();
    for (Tuple t : this)
        b.add(t);
    Ruby runtime = context.getRuntime();
    return new RubyDataBag(runtime, runtime.getClass("DataBag"), b);
}
 
Example #19
Source File: RubyDataByteArray.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * Overrides equality leveraging DataByteArray's equality.
 *
 * @param context the context the method is being executed in
 * @param arg     a RubyDataByteArray against which to test equality
 * @return        true if they are equal, false otherwise
 */
@JRubyMethod(name = {"eql?", "=="})
public RubyBoolean equals(ThreadContext context, IRubyObject arg) {
    Ruby runtime = context.getRuntime();
    if (arg instanceof RubyDataByteArray) {
        return RubyBoolean.newBoolean(runtime, internalDBA.equals(((RubyDataByteArray)arg).getDBA()));
    } else {
        return runtime.getFalse();
    }
}
 
Example #20
Source File: RubyRipper.java    From gocd with Apache License 2.0 5 votes vote down vote up
@JRubyMethod(meta = true)
public static IRubyObject dedent_string(ThreadContext context, IRubyObject self, IRubyObject _input, IRubyObject _width) {
    RubyString input = _input.convertToString();
    int wid = _width.convertToInteger().getIntValue();
    input.modify19();
    int col = LexingCommon.dedent_string(input.getByteList(), wid);
    return context.runtime.newFixnum(col);
}
 
Example #21
Source File: RubySchema.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * This method allows the user to see the name of the alias of the FieldSchema of the encapsulated
 * Schema. This method only works if the Schema has one FieldSchema.
 *
 * @param context the context the method is being executed in
 * @return        the name of the Schema
 */
@JRubyMethod(name = "name")
public RubyString getName(ThreadContext context) {
    try {
        if (internalSchema.size() != 1)
             throw new RuntimeException("Can only get name if there is one schema present");

        return RubyString.newString(context.getRuntime(), internalSchema.getField(0).alias);
    } catch (FrontendException e) {
        throw new RuntimeException("Unable to get field from Schema", e);
    }
}
 
Example #22
Source File: RubySchema.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * This method allows access into the Schema nested in the encapsulated Schema. For example,
 * if the encapsulated Schema is a bag Schema, this allows the user to access the schema of
 * the interior Tuple.
 *
 * @param context the context the method is being executed in
 * @return        a RubySchema encapsulating the nested Schema
 */
@JRubyMethod(name = {"get", "inner", "in"})
public RubySchema get(ThreadContext context) {
    if (internalSchema.size() != 1)
        throw new RuntimeException("Can only return nested schema if there is one schema to get");
    Ruby runtime = context.getRuntime();
    try {
        return new RubySchema(runtime, runtime.getClass("Schema"), internalSchema.getField(0).schema, false);
    } catch (FrontendException e) {
        throw new RuntimeException("Schema does not have a nested FieldScema", e);
    }
}
 
Example #23
Source File: RubyRipper.java    From gocd with Apache License 2.0 5 votes vote down vote up
@JRubyMethod
public IRubyObject lineno(ThreadContext context) {
    if (!parser.hasStarted()) throw context.runtime.newArgumentError("method called for uninitialized object");

    if (!parseStarted) return context.nil;

    return context.runtime.newFixnum(parser.getLineno());
}
 
Example #24
Source File: BlockProcessorProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@JRubyMethod(name = "process", required = 3)
public IRubyObject process(ThreadContext context, IRubyObject parent, IRubyObject reader, IRubyObject attributes) {
    Object o = getProcessor().process(
            (StructuralNode) NodeConverter.createASTNode(parent),
            new ReaderImpl(reader),
            new RubyAttributesMapDecorator((RubyHash) attributes));

    return convertProcessorResult(o);
}
 
Example #25
Source File: RubySchema.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * This is a ruby method which takes an array of arguments and constructs a Tuple schema from them. The name
 * will be set automatically.
 *
 * @param context the context the method is being executed in
 * @param self    the RubyClass for the Class object this was invoked on
 * @param arg     a list of arguments to instantiate the new RubySchema
 * @return        the new RubySchema
 */
@JRubyMethod(meta = true, name = {"t", "tuple"})
public static RubySchema tuple(ThreadContext context, IRubyObject self, IRubyObject arg) {
    if (arg instanceof RubyArray) {
        Schema s = rubyArgToSchema(arg);
        Ruby runtime = context.getRuntime();
        return new RubySchema(runtime, runtime.getClass("Schema"), s);
    } else {
        throw new RuntimeException("Bad argument given to Schema.tuple");
    }
}
 
Example #26
Source File: SyntaxHighlighterProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@JRubyMethod(name = "format", required = 3)
public IRubyObject format(ThreadContext context, IRubyObject blockRuby, IRubyObject langRuby, IRubyObject optionsRuby) {
  Formatter formatter = (Formatter) delegate;

  Block block = (Block) NodeConverter.createASTNode(blockRuby);
  String lang = langRuby.asJavaString();
  Map<String, Object> options = new RubyHashMapDecorator((RubyHash) optionsRuby);

  String result = formatter.format(block, lang, options);

  return getRuntime().newString(result);
}
 
Example #27
Source File: RubySchema.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * This is a ruby method which takes an array of arguments and constructs a Map schema from them. The name
 * will be set automatically.
 *
 * @param context the context the method is being executed in
 * @param self    the RubyClass for the Class object this was invoked on
 * @param arg     a list of arguments to instantiate the new RubySchema
 * @return        the new RubySchema
 */
@JRubyMethod(meta = true, name = {"m", "map"})
public static RubySchema map(ThreadContext context, IRubyObject self, IRubyObject arg) {
    Schema s = tuple(context, self, arg).getInternalSchema();
    Ruby runtime = context.getRuntime();
    try {
        return new RubySchema(runtime, runtime.getClass("Schema"), new Schema(new Schema.FieldSchema("map_0", s.getField(0).schema, DataType.MAP)));
    } catch (FrontendException e) {
        throw new RuntimeException("Error making map", e);
    }
}
 
Example #28
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 #29
Source File: BlockProcessorProxy.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 #30
Source File: JavaLogger.java    From asciidoctorj with Apache License 2.0 4 votes vote down vote up
@JRubyMethod(name = "info?")
public IRubyObject info(final ThreadContext threadContext) {
  return getRuntime().getTrue();
}