org.jruby.anno.JRubyMethod Java Examples

The following examples show how to use org.jruby.anno.JRubyMethod. 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: JavaDissectorLibrary.java    From logstash-filter-dissect with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #3
Source File: RubyRipper.java    From gocd with Apache License 2.0 6 votes vote down vote up
@JRubyMethod(meta = true)
public static IRubyObject lex_state_name(ThreadContext context, IRubyObject self, IRubyObject lexStateParam) {
    int lexState = lexStateParam.convertToInteger().getIntValue();

    boolean needsSeparator = false;
    RubyString name = null;
    for (int i = 0; i < lexStateNames.length; i++) {
        if ((lexState & (1<<i)) != 0) {
            if (!needsSeparator) {
                name = context.runtime.newString(lexStateNames[i]);
                needsSeparator = true;
            } else {
                name.cat('|');
                name.catString(lexStateNames[i]);
            }
        }
    }

    if (name == null) name = context.runtime.newString("EXPR_NONE");

    return name;
}
 
Example #4
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 #5
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 #6
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 #7
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 #8
Source File: SyntaxHighlighterProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@JRubyMethod(name = "write_stylesheet", required = 2)
public IRubyObject writeStylesheet(ThreadContext context, IRubyObject document, IRubyObject to_dir) {
  StylesheetWriter writer = (StylesheetWriter) delegate;
  Document doc = (Document) NodeConverter.createASTNode(document);

  File toDir = new File(to_dir.asJavaString());

  writer.writeStylesheet(doc, toDir);
  return getRuntime().getNil();
}
 
Example #9
Source File: RubyDataByteArray.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * This calls the compareTo method of the encapsulated DataByteArray.
 *
 * @param context the context the method is being executed in
 * @param arg     a RubyDataByteArray or byte array to compare to the
 *                encapsulated DataByteArray
 * @return        the result of compareTo on the encapsulated DataByteArray
                  and arg
 */
@JRubyMethod
public RubyFixnum compareTo(ThreadContext context, IRubyObject arg) {
    int compResult;
    if (arg instanceof RubyDataByteArray) {
        compResult = internalDBA.compareTo(((RubyDataByteArray)arg).getDBA());
    } else {
        compResult = internalDBA.compareTo(new DataByteArray((byte[])arg.toJava(byte[].class)));
    }
    return RubyFixnum.newFixnum(context.getRuntime(), compResult);
}
 
Example #10
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 #11
Source File: RubyDataByteArray.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * This method calls the set method of the underlying DataByteArray with one exception:
 * if given a RubyDataByteArray, it will set the encapsulated DataByteArray to be equal.
 *
 * @param arg an object to set the encapsulated DataByteArray's bits to. In the case of
 *            a RubyString or byte array, the underlying bytes will be sit directly. In
 *            the case of a RubyDataByteArray, the encapsulated DataByteArray will be set
 *            equal to arg.
 */
@JRubyMethod
public void set(IRubyObject arg) {
    if (arg instanceof RubyDataByteArray) {
        internalDBA = ((RubyDataByteArray)arg).getDBA();
    } else if (arg instanceof RubyString) {
        internalDBA.set(arg.toString());
    } else {
        internalDBA.set((byte[])arg.toJava(byte[].class));
    }
}
 
Example #12
Source File: RubyDataBag.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * The initialize method is the method used on the Ruby side to construct
 * the RubyDataBag object. The default is just an empty bag.
 *
 * @return the initialized RubyDataBag
 */
@JRubyMethod
@SuppressWarnings("deprecation")
public RubyDataBag initialize() {
    internalDB = mBagFactory.newDefaultBag();
    return this;
}
 
Example #13
Source File: IncludeProcessorProxy.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 #14
Source File: TreeprocessorProxy.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: RubyDataBag.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * This method returns a string representation of the RubyDataBag. If given an optional
 * argument, then if that argument is true, the contents of the bag will also be printed.
 *
 * @param context the context the method is being executed in
 * @param args    optional true/false argument passed to inspect
 * @return        string representation of the RubyDataBag
 */
@JRubyMethod(name = {"inspect", "to_s", "to_string"}, optional = 1)
public RubyString inspect(ThreadContext context, IRubyObject[] args) {
    Ruby runtime = context.getRuntime();
    StringBuilder sb = new StringBuilder();
    sb.append("[DataBag: size: ").append(internalDB.size());
    if (args.length > 0 && args[0].isTrue())
        sb.append(" = ").append(internalDB.toString());
    sb.append("]");
    return RubyString.newString(runtime, sb);
}
 
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: 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 #18
Source File: JRubyRackInput.java    From rack-servlet with Apache License 2.0 5 votes vote down vote up
@JRubyMethod(optional = 1) public IRubyObject read(ThreadContext context, IRubyObject[] args) {
  Integer length = null;

  if (args.length > 0) {
    long arg = args[0].convertToInteger("to_i").getLongValue();
    length = (int) Math.min(arg, Integer.MAX_VALUE);
  }

  try {
    return toRubyString(rackInput.read(length));
  } catch (IOException e) {
    throw getRuntime().newIOErrorFromException(e);
  }
}
 
Example #19
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 #20
Source File: RubyDataByteArray.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #21
Source File: RubyDataByteArray.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * This is the default initializer, which returns an empty DataByteArray.
 *
 * @return the initialized RubyDataByteArray
 */
@JRubyMethod
@SuppressWarnings("deprecation")
public RubyDataByteArray initialize() {
    internalDBA = new DataByteArray();
    return this;
}
 
Example #22
Source File: RubyDataBag.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * The initialize method can optionally receive a DataBag. In the case of
 * a RubyDataBag, a RubyDataBag will be returned that directly encapsulates it.
 *
 * @param arg an IRubyObject that is a RubyDataBag to encapsulate
 * @return    the initialized RubyDataBag
 */
@JRubyMethod
public RubyDataBag initialize(IRubyObject arg) {
    if (arg instanceof RubyDataBag) {
        internalDB = ((RubyDataBag)arg).getBag();
    } else {
        throw new IllegalArgumentException("Bag argument passed to DataBag initializer");
    }
    return this;
}
 
Example #23
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 #24
Source File: JRubyRackInput.java    From rack-servlet with Apache License 2.0 5 votes vote down vote up
@JRubyMethod public IRubyObject rewind() {
  try {
    rackInput.rewind();
  } catch (IOException e) {
    throw getRuntime().newIOErrorFromException(e);
  }
  return getRuntime().getNil();
}
 
Example #25
Source File: IncludeProcessorProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@JRubyMethod(name = "process", required = 4)
public IRubyObject process(ThreadContext context, IRubyObject[] args) {
    Document document = (Document) NodeConverter.createASTNode(args[0]);
    PreprocessorReader reader = new PreprocessorReaderImpl(args[1]);
    String target = RubyUtils.rubyToJava(getRuntime(), args[2], String.class);
    Map<String, Object> attributes = new RubyAttributesMapDecorator((RubyHash) args[3]);
    getProcessor().process(document, reader, target, attributes);
    return null;
}
 
Example #26
Source File: RubySchema.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * This is a version of [] which allows the range to be specified as such: [1,2].
 *
 * @param context the context the method is being executed in
 * @param arg1    a Fixnum start index
 * @param arg2    a Fixnum end index
 * @return        the RubySchema object encapsulated the found Schema
 */
@JRubyMethod(name = {"[]", "slice"})
public RubySchema get(ThreadContext context, IRubyObject arg1, IRubyObject arg2) {
    if (arg1 instanceof RubyFixnum && arg2 instanceof RubyFixnum) {
        Ruby runtime = context.getRuntime();
        int min = (int)((RubyFixnum)arg1).getLongValue();
        int max = (int)((RubyFixnum)arg2).getLongValue() - 1;
        return new RubySchema(runtime, runtime.getClass("Schema"), new Schema(internalSchema.getFields().subList(min, max + 1)), false);
    } else {
        throw new RuntimeException("Bad arguments given to get function: ( " + arg1.toString() + " , " + arg2.toString()+ " )");
    }
}
 
Example #27
Source File: RubySchema.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * This allows the users to set an index or a range of values to
 * a specified RubySchema. The first argument must be a Fixnum or Range,
 * and the second argument may optionally be a Fixnum. The given index
 * (or range of indices) will be replaced by a RubySchema instantiated
 * based on the remaining arguments.
 *
 * @param context the contextthe method is being executed in
 * @param args    a varargs which has to be at least length two.
 * @return        the RubySchema that was added
 */
@JRubyMethod(name = {"[]=", "set"}, required = 2, rest = true)
public RubySchema set(ThreadContext context, IRubyObject[] args) {
    IRubyObject arg1 = args[0];
    IRubyObject arg2 = args[1];
    IRubyObject[] arg3 = Arrays.copyOfRange(args, 1, args.length);
    Schema s = internalSchema;
    Ruby runtime = context.getRuntime();
    List<Schema.FieldSchema> lfs = s.getFields();
    int min, max;
    if (arg1 instanceof RubyFixnum && arg2 instanceof RubyFixnum) {
        min = (int)((RubyFixnum)arg1).getLongValue();
        max = (int)((RubyFixnum)arg2).getLongValue();
        arg3 = Arrays.copyOfRange(args, 2, args.length);
    } else if (arg1 instanceof RubyFixnum) {
        min = (int)((RubyFixnum)arg1).getLongValue();
        max = min + 1;
    } else if (arg1 instanceof RubyRange) {
        min = (int)((RubyFixnum)((RubyRange)arg1).min(context, Block.NULL_BLOCK)).getLongValue();
        max = (int)((RubyFixnum)((RubyRange)arg1).max(context, Block.NULL_BLOCK)).getLongValue() + 1;
    } else {
        throw new RuntimeException("Bad arguments given to get function: ( " + arg1.toString() + " , " + arg2.toString()+ " )");
    }
    for (int i = min; i < max; i++)
        lfs.remove(min);
    if (arg3 == null || arg3.length == 0)
        throw new RuntimeException("Must have schema argument for []=");
    RubySchema rs = new RubySchema(runtime, runtime.getClass("Schema")).initialize(arg3);
    for (Schema.FieldSchema fs : rs.getInternalSchema().getFields())
        lfs.add(min++, fs);
    RubySchema.fixSchemaNames(internalSchema);
    return rs;
}
 
Example #28
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 #29
Source File: RubySchema.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * Given a field name this string will search the RubySchema for a FieldSchema
 * with that name and return it encapsulated in a Schema.
 *
 * @param context the context the method is being executed in
 * @param arg     a RubyString serving as an alias to look
 *                for in the Schema
 * @return        the found RubySchema
 */
@JRubyMethod
public RubySchema find(ThreadContext context, IRubyObject arg) {
    if (arg instanceof RubyString) {
        Ruby runtime = context.getRuntime();
        return new RubySchema(runtime, runtime.getClass("Schema"), RubySchema.find(internalSchema, arg.toString()), false);
    } else {
        throw new RuntimeException("Invalid arguement passed to find: " + arg);
    }
}
 
Example #30
Source File: RubySchema.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * Given a field name, this will return the index of it in the schema.
 *
 * @param context the context the method is being executed in
 * @param arg     a field name to look for
 * @return        the index for that field name
 */
@JRubyMethod
public RubyFixnum index(ThreadContext context, IRubyObject arg) {
    if (arg instanceof RubyString) {
        try {
            return new RubyFixnum(context.getRuntime(), internalSchema.getPosition(arg.toString()));
        } catch (FrontendException e) {
            throw new RuntimeException("Unable to find position for argument: " + arg);
        }
    } else {
        throw new RuntimeException("Invalid arguement passed to index: " + arg);
    }
}