org.jruby.RubyHash Java Examples

The following examples show how to use org.jruby.RubyHash. 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 RubyHash map2hash(Ruby ruby, Map<String, Object> ourCaps) {
    RubyHash hash = new RubyHash(ruby);
    Set<String> keySet = ourCaps.keySet();
    for (String key : keySet) {
        RubySymbol keySym = RubySymbol.newSymbol(ruby, key);
        Object v = ourCaps.get(key);
        if (v instanceof String) {
            hash.put(keySym, RubyString.newString(ruby, (String) v));
        } else if (v instanceof Boolean) {
            hash.put(keySym, RubyBoolean.newBoolean(ruby, (boolean) v));
        } else if (v instanceof List) {
            hash.put(keySym, map2list(ruby, (List<?>) v));
        } else {
            hash.put(keySym, map2hash(ruby, (Map<String, Object>) v));
        }
    }
    return hash;
}
 
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: JRubyProcessor.java    From asciidoctorj with Apache License 2.0 6 votes vote down vote up
@Override
public PhraseNode createPhraseNode(ContentNode parent, String context, String text, Map<String, Object> attributes, Map<String, Object> options) {

    Ruby rubyRuntime = JRubyRuntimeContext.get(parent);

    options.put(Options.ATTRIBUTES, RubyHashUtil.convertMapToRubyHashWithStrings(rubyRuntime, attributes));

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

    IRubyObject[] parameters = {
            ((ContentNodeImpl) parent).getRubyObject(),
            RubyUtils.toSymbol(rubyRuntime, context),
            text == null ? rubyRuntime.getNil() : rubyRuntime.newString(text),
            convertedOptions};
    return (PhraseNode) NodeConverter.createASTNode(rubyRuntime, NodeConverter.NodeType.INLINE_CLASS, parameters);
}
 
Example #4
Source File: PigJrubyLibrary.java    From spork with Apache License 2.0 6 votes vote down vote up
/**
 * A type specific conversion routine for Pig Maps. This only deals with maps
 * with String keys, which is all that Pig supports.
 *
 * @param  ruby          the Ruby runtime to create objects in
 * @param  object        map to convert. In Pig, only maps with String keys are
 *                       supported
 * @return               analogous Ruby type
 * @throws ExecException object contains a key that can't be convert to a Ruby type
 */
public static <T> RubyHash pigToRuby(Ruby ruby, Map<T, ?> object) throws ExecException {
    RubyHash newMap = RubyHash.newHash(ruby);

    boolean checkType = false;

    for (Map.Entry<T, ?> entry : object.entrySet()) {
        T key = entry.getKey();
        if (!checkType) {
            if (!(key instanceof String))
                throw new ExecException("pigToRuby only supports converting Maps with String keys");
            checkType = true;
        }
        newMap.put(key, pigToRuby(ruby, entry.getValue()));
    }

    return newMap;
}
 
Example #5
Source File: PigJrubyLibrary.java    From spork with Apache License 2.0 6 votes vote down vote up
/**
 * A type specific conversion routine.
 *
 * @param  rbObject object to convert
 * @return          analogous Pig type
 */
@SuppressWarnings("unchecked")
public static Map<String, ?> rubyToPig(RubyHash rbObject) throws ExecException {
    Map<String, Object> newMap = Maps.newHashMap();
    for (Map.Entry<Object, Object> entry : (Set<Map.Entry<Object, Object>>)rbObject.entrySet()) {
        Object key = entry.getKey();

        if (!(key instanceof String || key instanceof RubyString || key instanceof RubySymbol))
            throw new ExecException("Hash must have String or Symbol key. Was given: " + key.getClass().getName());

        String keyStr = key.toString();
        if (entry.getValue() instanceof IRubyObject) {
            newMap.put(keyStr, rubyToPig((IRubyObject)entry.getValue()));
        } else {
            newMap.put(keyStr, entry.getValue());
        }
    }
    return newMap;
}
 
Example #6
Source File: CommandBlockRunner.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * unapplyEnvironment
 */
protected void unapplyEnvironment()
{
	Ruby runtime = this.getRuntime();
	IRubyObject env = runtime.getObject().getConstant(ENV_PROPERTY);

	if (env != null && env instanceof RubyHash)
	{
		RubyHash hash = (RubyHash) env;

		// restore original content
		hash.replace(runtime.getCurrentContext(), this._originalEnvironment);

		// lose reference
		this._originalEnvironment = null;
	}
}
 
Example #7
Source File: RubyHashUtil.java    From asciidoctorj with Apache License 2.0 6 votes vote down vote up
public static RubyHash convertMapToRubyHashWithStrings(Ruby rubyRuntime, Map<String, Object> attributes) {

        if (attributes instanceof RubyHashMapDecorator) {
            return ((RubyHashMapDecorator) attributes).getRubyHash();
        } else if (attributes instanceof RubyHash) {
            return (RubyHash) attributes;
        }

        RubyHash rubyHash = new RubyHash(rubyRuntime);

        Set<Entry<String, Object>> optionsSet = attributes.entrySet();

        for (Entry<String, Object> entry : optionsSet) {

            String key = entry.getKey();
            Object value = entry.getValue();

            RubyString newKey = rubyRuntime.newString(key);
            IRubyObject iRubyValue = toRubyObject(rubyRuntime, value);

            rubyHash.put(newKey, iRubyValue);
        }
        return rubyHash;
    }
 
Example #8
Source File: SyntaxHighlighterProxy.java    From asciidoctorj with Apache License 2.0 6 votes vote down vote up
@JRubyMethod(name = "highlight", required = 4)
public IRubyObject highlight(ThreadContext context, IRubyObject[] args) {
  Highlighter highlighter = (Highlighter) delegate;
  IRubyObject blockRuby = args[0];
  Block block = (Block) NodeConverter.createASTNode(blockRuby);

  IRubyObject sourceRuby = args[1];
  String source = sourceRuby.asJavaString();

  IRubyObject langRuby = args[2];
  String lang = langRuby.asJavaString();

  RubyHash optionsRuby = (RubyHash) args[3];
  Map<String, Object> options = new RubyHashMapDecorator(optionsRuby);

  HighlightResult result = highlighter.highlight(block, source, lang, options);
  if (result.getLineOffset() != null) {
    return getRuntime().newArray(getRuntime().newString(result.getHighlightedSource()), getRuntime().newFixnum(result.getLineOffset()));
  } else {
    return getRuntime().newString(result.getHighlightedSource());
  }
}
 
Example #9
Source File: RubyHashUtil.java    From asciidoctorj with Apache License 2.0 6 votes vote down vote up
public static Map<String, Object> convertRubyHashMapToStringObjectMap(RubyHash rubyHashMap) {

        Map<String, Object> map = new HashMap<String, Object>();

        Set<Entry<Object, Object>> elements = rubyHashMap.entrySet();

        for (Entry<Object, Object> element : elements) {
            if(element.getKey() instanceof RubySymbol) {
                map.put(toJavaString((RubySymbol)element.getKey()), toJavaObject(element.getValue()));
            } else if (element.getKey() instanceof RubyString) {
                map.put(((RubyString) element.getKey()).asJavaString(), toJavaObject(element.getValue()));
            } else if (element.getKey() instanceof String) {
                map.put((String) element.getKey(), toJavaObject(element.getValue()));
            }
        }

        return map;

    }
 
Example #10
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 #11
Source File: JRubyRackApplication.java    From rack-servlet with Apache License 2.0 6 votes vote down vote up
private RubyHash convertToRubyHash(Set<Map.Entry<String, Object>> entries) {
  RubyHash hash = newHash(runtime);

  for (Map.Entry<String, Object> entry : entries) {
    String key = entry.getKey();
    Object value = entry.getValue();

    if (key.equals("rack.input")) {
      value = new JRubyRackInput(runtime, (RackInput) value);
    }

    if (key.equals("rack.version")) {
      value = convertToRubyArray((List<Integer>) value);
    }

    hash.put(key, value);
  }

  return hash;
}
 
Example #12
Source File: PreprocessorReaderImpl.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@Override
public void push_include(String data, String file, String path, int lineNumber, Map<String, Object> attributes) {

    RubyHash attributeHash = RubyHash.newHash(getRuntime());
    attributeHash.putAll(attributes);

    getRubyProperty("push_include", data, file, path, lineNumber, attributes);
}
 
Example #13
Source File: JRubyProcessor.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@Override
public Table createTable(StructuralNode parent, Map<String, Object> attributes) {
    Ruby rubyRuntime = JRubyRuntimeContext.get(parent);

    RubyHash rubyAttributes = RubyHash.newHash(rubyRuntime);
    rubyAttributes.putAll(attributes);

    IRubyObject[] parameters = {
            ((StructuralNodeImpl) parent).getRubyObject(),
            rubyAttributes};
    Table ret = (Table) NodeConverter.createASTNode(rubyRuntime, NodeConverter.NodeType.TABLE_CLASS, parameters);
    ret.setAttribute("rowcount", 0, false);
    return ret;
}
 
Example #14
Source File: MarathonRuby.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
public static RubyHash get_browser_caps(RubyHash caps) {
    @SuppressWarnings("unchecked")
    Map<String, Object> ourCaps = (Map<String, Object>) TestAttributes.get("capabilities");
    if (ourCaps == null)
        return new RubyHash(caps.getRuntime());
    return map2hash(caps.getRuntime(), ourCaps);
}
 
Example #15
Source File: JRubyProcessor.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #16
Source File: JRubyProcessor.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@Override
public Column createTableColumn(Table parent, int index, Map<String, Object> attributes) {
    Ruby rubyRuntime = JRubyRuntimeContext.get(parent);

    RubyHash rubyAttributes = RubyHash.newHash(rubyRuntime);
    rubyAttributes.putAll(attributes);

    IRubyObject[] parameters = {
            ((StructuralNodeImpl) parent).getRubyObject(),
            RubyFixnum.newFixnum(rubyRuntime, index),
            rubyAttributes}; // No cursor parameter yet

    return (Column) NodeConverter.createASTNode(rubyRuntime, NodeConverter.NodeType.TABLE_COLUMN_CLASS, parameters);
}
 
Example #17
Source File: JRubyProcessor.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #18
Source File: JRubyProcessor.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@Override
public Section createSection(StructuralNode parent, Integer level, boolean numbered, Map<Object, Object> options) {

    Ruby rubyRuntime = JRubyRuntimeContext.get(parent);

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

    IRubyObject[] parameters = {
            ((StructuralNodeImpl) parent).getRubyObject(),
            level == null ? rubyRuntime.getNil() : rubyRuntime.newFixnum(level),
            rubyRuntime.newBoolean(numbered),
            convertMapToRubyHashWithSymbols};
    return (Section) NodeConverter.createASTNode(rubyRuntime, NodeConverter.NodeType.SECTION_CLASS, parameters);
}
 
Example #19
Source File: JRubyProcessor.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an inner document for the given parent document.
 * Inner documents are used for tables cells with style {@code asciidoc}.
 *
 * @param parentDocument The parent document of the new document.
 * @return A new inner document.
 */
@Override
public Document createDocument(Document parentDocument) {
    Ruby runtime = JRubyRuntimeContext.get(parentDocument);
    RubyHash options = RubyHash.newHash(runtime);
    options.put(
            runtime.newSymbol("parent"),
            ((DocumentImpl) parentDocument).getRubyObject());

    return (Document) NodeConverter.createASTNode(runtime, NodeConverter.NodeType.DOCUMENT_CLASS, runtime.getNil(), options);
}
 
Example #20
Source File: JRubyProcessor.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@Override
public org.asciidoctor.ast.List createList(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 (org.asciidoctor.ast.List) NodeConverter.createASTNode(rubyRuntime, NodeConverter.NodeType.LIST_CLASS, parameters);
}
 
Example #21
Source File: NodeCache.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
public static NodeCache get(IRubyObject rubyObject) {

        RubyHash cache = (RubyHash) rubyObject.getInstanceVariables().getInstanceVariable(ASCIIDOCTORJ_CACHE);
        if (cache == null) {
            cache = RubyHash.newHash(rubyObject.getRuntime());
            rubyObject.getInstanceVariables().setInstanceVariable(ASCIIDOCTORJ_CACHE, cache);
        }
        return new NodeCache(cache);
    }
 
Example #22
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 #23
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 #24
Source File: DocumentImpl.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
@Override
public Title getStructuredDoctitle() {
    Ruby runtime = getRubyObject().getRuntime();
    RubyHash options = RubyHash.newHash(runtime);
    RubySymbol partitioned = RubySymbol.newSymbol(runtime, "partition");
    options.put(partitioned, RubyBoolean.newBoolean(runtime, true));

    Object doctitle = getRubyProperty("doctitle", options);

    return toJava((IRubyObject) doctitle, Title.class);

}
 
Example #25
Source File: JavaLogger.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
private String formatMessage(final IRubyObject msg) {
  if (getRuntime().getString().equals(msg.getType())) {
    return msg.asJavaString();
  } else if (getRuntime().getHash().equals(msg.getType())) {
    final RubyHash hash = (RubyHash) msg;
    return Objects.toString(hash.get(getRuntime().newSymbol(LOG_PROPERTY_TEXT)));
  }
  throw new IllegalArgumentException(Objects.toString(msg));
}
 
Example #26
Source File: JavaLogger.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
private Cursor getSourceLocation(IRubyObject msg) {
  if (getRuntime().getHash().equals(msg.getType())) {
    final RubyHash hash = (RubyHash) msg;
    final Object sourceLocation = hash.get(getRuntime().newSymbol(LOG_PROPERTY_SOURCE_LOCATION));
    return new CursorImpl((IRubyObject) sourceLocation);
  }
  return null;
}
 
Example #27
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 #28
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 #29
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 #30
Source File: CommandBlockRunner.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * applyEnvironment
 * 
 * @param container
 */
protected void applyEnvironment()
{
	Ruby runtime = this.getRuntime();
	IRubyObject env = runtime.getObject().getConstant(ENV_PROPERTY);

	if (env != null && env instanceof RubyHash)
	{
		RubyHash hash = (RubyHash) env;

		// save copy for later
		this._originalEnvironment = (RubyHash) hash.dup();

		hash.putAll(this.getContributedEnvironment());

		// Grab all the matching env objects contributed via bundles that have scope matching!
		IModelFilter filter = new ScopeFilter((String) hash.get("TM_CURRENT_SCOPE")); //$NON-NLS-1$
		List<EnvironmentElement> envs = BundleManager.getInstance().getEnvs(filter);
		ScopeSelector.sort(envs);
		for (EnvironmentElement e : envs)
		{
			RubyProc invoke = e.getInvokeBlock();
			if (invoke != null)
			{
				invoke.call(runtime.getCurrentContext(), new IRubyObject[] { hash });
			}
		}
	}
}