org.jruby.RubyArray Java Examples

The following examples show how to use org.jruby.RubyArray. 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: MarathonRuby.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static RubyArray map2list(Ruby ruby, List<?> list) {
    RubyArray array = new RubyArray(ruby, list.size());
    int index = 0;
    for (Object v : list) {
        if (v instanceof String) {
            array.set(index++, RubyString.newString(ruby, (String) v));
        } else if (v instanceof Boolean) {
            array.set(index++, RubyBoolean.newBoolean(ruby, (boolean) v));
        } else if (v instanceof List) {
            array.set(index++, map2list(ruby, (List<?>) v));
        } else {
            array.set(index++, map2hash(ruby, (Map<String, Object>) v));
        }
    }
    return array;
}
 
Example #2
Source File: JRubyProcessor.java    From asciidoctorj with Apache License 2.0 6 votes vote down vote up
@Override
public PhraseNode createPhraseNode(ContentNode parent, String context, List<String> text, Map<String, Object> attributes, Map<Object, Object> options) {

    Ruby rubyRuntime = JRubyRuntimeContext.get(parent);

    options.put(Options.ATTRIBUTES, attributes);

    RubyHash convertMapToRubyHashWithSymbols = RubyHashUtil.convertMapToRubyHashWithSymbolsIfNecessary(rubyRuntime,
            options);

    RubyArray rubyText = rubyRuntime.newArray();
    rubyText.addAll(text);

    IRubyObject[] parameters = {
            ((ContentNodeImpl) parent).getRubyObject(),
            RubyUtils.toSymbol(rubyRuntime, context),
            rubyText,
            convertMapToRubyHashWithSymbols};
    return (PhraseNode) NodeConverter.createASTNode(rubyRuntime, NodeConverter.NodeType.INLINE_CLASS, parameters);
}
 
Example #3
Source File: AbstractScriptRunner.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * applyLoadPaths
 * 
 * @param container
 */
protected void applyLoadPaths(Ruby runtime)
{
	if (this._loadPaths != null && this._loadPaths.size() > 0)
	{
		IRubyObject object = runtime.getLoadService().getLoadPath();

		if (object instanceof RubyArray)
		{
			RubyArray loadPathArray = (RubyArray) object;

			// save copy for later
			this._originalLoadPaths = (RubyArray) loadPathArray.dup();

			// Add our custom load paths
			for (String loadPath : this._loadPaths)
			{
				RubyString toAdd = runtime.newString(loadPath.replace('\\', '/'));

				loadPathArray.append(toAdd);
			}
		}
	}
}
 
Example #4
Source File: AbstractScriptRunner.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * unapplyLoadPaths
 * 
 * @param runtime
 */
protected void unapplyLoadPaths(Ruby runtime)
{
	if (this._loadPaths != null && this._loadPaths.size() > 0)
	{
		IRubyObject object = runtime.getLoadService().getLoadPath();

		if (object != null && object instanceof RubyArray)
		{
			RubyArray loadPathArray = (RubyArray) object;

			// Restore original content
			loadPathArray.replace(this._originalLoadPaths);

			// lose reference
			this._originalLoadPaths = null;
		}
	}
}
 
Example #5
Source File: NodeConverter.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isInstance(IRubyObject object) {
    if (!super.isInstance(object)) {
        return false;
    }
    RubyArray array = (RubyArray) object;
    boolean ret = array.size() == 2
            && object.getRuntime().getArray().isInstance((IRubyObject) array.get(0))
            && (null == array.get(1) || LIST_ITEM_CLASS.isInstance((IRubyObject) array.get(1)));
    return ret;
}
 
Example #6
Source File: JRubyRackApplication.java    From rack-servlet with Apache License 2.0 5 votes vote down vote up
private RackResponse convertToJavaRackResponse(RubyArray response) {
  int status = Integer.parseInt(response.get(0).toString(), 10);
  Map headers = (Map) response.get(1);
  IRubyObject body = (IRubyObject) response.get(2);

  return new RackResponse(status, headers, new JRubyRackBodyIterator(body));
}
 
Example #7
Source File: JRubyRackApplication.java    From rack-servlet with Apache License 2.0 5 votes vote down vote up
/**
 * Calls the delegate Rack application, translating into and back out of the JRuby interpreter.
 *
 * @param environment the Rack environment
 * @return the Rack response
 */
@Override public RackResponse call(RackEnvironment environment) {
  RubyHash environmentHash = convertToRubyHash(environment.entrySet());

  RubyArray response = callRackApplication(environmentHash);

  return convertToJavaRackResponse(response);
}
 
Example #8
Source File: RubyObjectWrapper.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
public <T> List<T> getList(String propertyName, Class<T> elementClass, Object... args) {
    IRubyObject result = getRubyProperty(propertyName, args);
    if (result instanceof RubyNil) {
        return null;
    } else {
        List<T> ret = new ArrayList<T>();
        RubyArray array = (RubyArray) result;
        for (int i = 0; i < array.size(); i++) {
            ret.add(RubyUtils.rubyToJava(runtime, array.at(RubyFixnum.newFixnum(runtime, i)), elementClass));
        }
        return ret;
    }
}
 
Example #9
Source File: StructuralNodeImpl.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@Override
public void setSubstitutions(String... substitutions) {
    RubyArray subs = (RubyArray) getRubyProperty("@subs");
    subs.clear();
    if (substitutions != null) {
        for (String substitution : substitutions) {
            subs.add(RubyUtils.toSymbol(getRuntime(), substitution));
        }
    }
}
 
Example #10
Source File: BlockImpl.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@Override
public void setLines(List<String> lines) {
    RubyArray newLines = getRuntime().newArray(lines.size());
    for (String s: lines) {
        newLines.add(getRuntime().newString(s));
    }
    setRubyProperty("lines", newLines);
}
 
Example #11
Source File: JRubyProcessor.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@Override
public Row createTableRow(Table parent) {
    Ruby rubyRuntime = JRubyRuntimeContext.get(parent);

    RubyArray rubyRow = rubyRuntime.newArray();
    return new RowImpl(rubyRow);
}
 
Example #12
Source File: ReaderImpl.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
static ReaderImpl createReader(Ruby runtime, List<String> lines) {
    RubyArray rubyLines = runtime.newArray(lines.size());
    for (String line : lines) {
        rubyLines.add(runtime.newString(line));
    }

    RubyClass readerClass = runtime.getModule("Asciidoctor").getClass("Reader");
    return new ReaderImpl(readerClass.callMethod("new", rubyLines));
}
 
Example #13
Source File: AbstractProcessorProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
private static void handlePositionalAttributesAnnotation(Class<? extends Processor> processor, RubyClass rubyClass) {
    Ruby rubyRuntime = rubyClass.getRuntime();
    if (processor.isAnnotationPresent(PositionalAttributes.class)) {
        PositionalAttributes positionalAttributes = processor.getAnnotation(PositionalAttributes.class);
        RubyArray positionalAttrs = RubyArray.newArray(rubyRuntime);
        for (String positionalAttribute : positionalAttributes.value()) {
            positionalAttrs.add(positionalAttribute);
        }
        rubyClass.callMethod(rubyRuntime.getCurrentContext(), "option", new IRubyObject[]{
                rubyRuntime.newSymbol("positional_attrs"),
                positionalAttrs
        });
    }
}
 
Example #14
Source File: AbstractProcessorProxy.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
private static void handleContextsAnnotation(Class<? extends Processor> processor, RubyClass rubyClass) {
    Ruby rubyRuntime = rubyClass.getRuntime();
    if (processor.isAnnotationPresent(Contexts.class)) {
        Contexts contexts = processor.getAnnotation(Contexts.class);
        RubyArray contextList = rubyRuntime.newArray();
        for (String value : contexts.value()) {
            contextList.add(rubyRuntime.newSymbol(value.substring(1)));
        }
        rubyClass.callMethod(rubyRuntime.getCurrentContext(), "option", new IRubyObject[]{
                rubyRuntime.newSymbol("contexts"),
                contextList
        });

    }
}
 
Example #15
Source File: JrubyScriptEngine.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * Consults the scripting container, after the script has been evaluated, to
 * determine what dependencies to ship.
 * <p>
 * FIXME: Corner cases like the following: "def foobar; require 'json'; end"
 * are NOT dealt with using this method
 */
private HashSet<String> libsToShip() {
    RubyArray loadedLibs = (RubyArray)rubyEngine.get("$\"");
    RubyArray loadPaths = (RubyArray)rubyEngine.get("$LOAD_PATH");
    // Current directory first
    loadPaths.add(0, "");

    HashSet<String> toShip = new HashSet<String>();
    HashSet<Object> shippedLib = new HashSet<Object>();

    for (Object loadPath : loadPaths) {
        for (Object lib : loadedLibs) {
            if (lib.toString().equals("pigudf.rb"))
                continue;
            if (shippedLib.contains(lib))
                continue;
            String possiblePath = (loadPath.toString().isEmpty()?"":loadPath.toString() +
                    File.separator) + lib.toString();
            if ((new File(possiblePath)).exists()) {
                // remove prefix ./
                toShip.add(possiblePath.startsWith("./")?possiblePath.substring(2):
                    possiblePath);
                shippedLib.add(lib);
            }
        }
    }
    return toShip;
}
 
Example #16
Source File: PigJrubyLibrary.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * A type specific conversion routine.
 *
 * @param  ruby          the Ruby runtime to create objects in
 * @param  object        object to convert
 * @return               analogous Ruby type
 * @throws ExecException object contained an object that could not convert
 */
public static RubyArray pigToRuby(Ruby ruby, Tuple object) throws ExecException{
    RubyArray rubyArray = ruby.newArray();

    for (Object o : object.getAll())
        rubyArray.add(pigToRuby(ruby, o));

    return rubyArray;
}
 
Example #17
Source File: PigJrubyLibrary.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * This method facilitates conversion from Ruby objects to Pig objects. This is
 * a general class which detects the subclass and invokes the appropriate conversion
 * routine. It will fail on an unsupported datatype.
 *
 * @param  rbObject      a Ruby object to convert
 * @return               the Pig analogue of the Ruby object
 * @throws ExecException if rbObject is not of a known type that can be converted
 */
@SuppressWarnings("unchecked")
public static Object rubyToPig(IRubyObject rbObject) throws ExecException {
    if (rbObject == null || rbObject instanceof RubyNil) {
        return null;
    } else if (rbObject instanceof RubyArray) {
        return rubyToPig((RubyArray)rbObject);
    } else if (rbObject instanceof RubyHash) {
        return rubyToPig((RubyHash)rbObject);
    } else if (rbObject instanceof RubyString) {
        return rubyToPig((RubyString)rbObject);
    } else if (rbObject instanceof RubyBignum) {
        return rubyToPig((RubyBignum)rbObject);
    } else if (rbObject instanceof RubyFixnum) {
        return rubyToPig((RubyFixnum)rbObject);
    } else if (rbObject instanceof RubyFloat) {
        return rubyToPig((RubyFloat)rbObject);
    } else if (rbObject instanceof RubyInteger) {
        return rubyToPig((RubyInteger)rbObject);
    } else if (rbObject instanceof RubyDataBag) {
        return rubyToPig((RubyDataBag)rbObject);
    } else if (rbObject instanceof RubyDataByteArray) {
        return rubyToPig((RubyDataByteArray)rbObject);
    } else if (rbObject instanceof RubySchema) {
        return rubyToPig((RubySchema)rbObject);
    } else if (rbObject instanceof RubyBoolean) {
        return rubyToPig((RubyBoolean)rbObject);
    } else {
        throw new ExecException("Cannot cast into any pig supported type: " + rbObject.getClass().getName());
    }
}
 
Example #18
Source File: JRubyScriptUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private Object convertFromRuby(IRubyObject rubyResult, Class<?> returnType) {
	Object result = JavaEmbedUtils.rubyToJava(this.ruby, rubyResult, returnType);
	if (result instanceof RubyArray && returnType.isArray()) {
		result = convertFromRubyArray(((RubyArray) result).toJavaArray(), returnType);
	}
	return result;
}
 
Example #19
Source File: JRubyScriptUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private Object convertFromRuby(IRubyObject rubyResult, Class<?> returnType) {
	Object result = JavaEmbedUtils.rubyToJava(this.ruby, rubyResult, returnType);
	if (result instanceof RubyArray && returnType.isArray()) {
		result = convertFromRubyArray(((RubyArray) result).toJavaArray(), returnType);
	}
	return result;
}
 
Example #20
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 #21
Source File: DissectPair.java    From logstash-filter-dissect with Apache License 2.0 5 votes vote down vote up
static DissectPair[] createArrayFromHash(final RubyHash hash) {
    if (hash.isNil()) {
        return EMPTY_ARRAY;
    }
    // a hash iterator that is independent of JRuby 1.7 and 9.0
    // 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[] dissectPairs = hash.to_a().toJavaArray();
    final DissectPair[] pairs = new DissectPair[dissectPairs.length];
    for (int idx = 0; idx < dissectPairs.length; idx++) {
        pairs[idx] = create((RubyArray) dissectPairs[idx]);
    }
    return pairs;
}
 
Example #22
Source File: ConvertPair.java    From logstash-filter-dissect with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #23
Source File: PigJrubyLibrary.java    From spork with Apache License 2.0 5 votes vote down vote up
/**
 * A type specific conversion routine.
 *
 * @param  rbObject object to convert
 * @return          analogous Pig type
 */
public static Tuple rubyToPig(RubyArray rbObject) throws ExecException {
    Tuple out = tupleFactory.newTuple(rbObject.size());
    int i = 0;
    for (IRubyObject arrayObj : rbObject.toJavaArray())
        out.set(i++, rubyToPig(arrayObj));
    return out;
}
 
Example #24
Source File: GrokHelper.java    From hadoop-solr with Apache License 2.0 5 votes vote down vote up
public static void addPatternDirToDC(Object array, JobConf conf) throws Exception {
  if (!array.getClass().getName().equals("org.jruby.RubyArray")) {
    throw new RuntimeException("Param is not RubyArray");
  }

  RubyArray rubyArray = (RubyArray) array;
  int size = rubyArray.size();
  for (int counter = 0; counter < size; counter++) {
    // Adding the prefix "file://" because the user will use the same LogStash
    // configuration file, and this configuration assumes that the additional
    // patterns are in local file system
    String path = "file://" + rubyArray.get(counter).toString();

    List<Path> filesToExplore = new ArrayList<Path>();
    try {
      Path currentPath = new Path(path);
      FileSystem fs = currentPath.getFileSystem(conf);
      if (fs.isDirectory(currentPath)) {
        filesToExplore = getAllSubPaths(currentPath, conf);
      } else {
        filesToExplore.add(currentPath);
      }
    } catch (Exception e) {
      log.error("Error while reading path " + path, e);
    }

    for (Path cPath : filesToExplore) {
      DistributedCacheHandler.addFileToCache(conf, cPath, cPath.toString());
      String currentPaths = conf.get(GrokIngestMapper.ADDITIONAL_PATTERNS);
      if (currentPaths != null) {
        currentPaths += ";" + cPath;
      } else {
        currentPaths = cPath.toString();
      }
      conf.set(GrokIngestMapper.ADDITIONAL_PATTERNS, currentPaths);
    }
  }
}
 
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: TableImpl.java    From asciidoctorj with Apache License 2.0 4 votes vote down vote up
private RowList getBody() {
    RubyArray bodyRows = (RubyArray) getRubyProperty("body");
    return new RowList(bodyRows);
}
 
Example #27
Source File: JRubyRackApplication.java    From rack-servlet with Apache License 2.0 4 votes vote down vote up
private RubyArray callRackApplication(RubyHash rubyHash) {
  return (RubyArray) application.callMethod(threadService.getCurrentContext(), "call", rubyHash);
}
 
Example #28
Source File: JRubyRackApplication.java    From rack-servlet with Apache License 2.0 4 votes vote down vote up
private RubyArray convertToRubyArray(List<Integer> list) {
  RubyArray array = RubyArray.newEmptyArray(runtime);
  array.addAll(list);
  return array;
}
 
Example #29
Source File: JavaDissectorLibrary.java    From logstash-filter-dissect with Apache License 2.0 4 votes vote down vote up
@JRubyMethod(name = "dissect_multi", required = 1)
public final IRubyObject dissectMulti(final ThreadContext ctx, final IRubyObject arg1) {
    final RubyArray events = (RubyArray) arg1;
    Arrays.stream(events.toJavaArray()).forEach(event -> dissect(ctx, event));
    return ctx.nil;
}
 
Example #30
Source File: RubyBlockListDecorator.java    From asciidoctorj with Apache License 2.0 4 votes vote down vote up
public RubyBlockListDecorator(RubyArray rubyBlockList) {
    this.rubyBlockList = rubyBlockList;
}