Java Code Examples for org.yaml.snakeyaml.nodes.MappingNode#getValue()

The following examples show how to use org.yaml.snakeyaml.nodes.MappingNode#getValue() . 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: BaseConstructor.java    From onedev with MIT License 6 votes vote down vote up
protected void constructSet2ndStep(MappingNode node, Set<Object> set) {
    List<NodeTuple> nodeValue = node.getValue();
    for (NodeTuple tuple : nodeValue) {
        Node keyNode = tuple.getKeyNode();
        Object key = constructObject(keyNode);
        if (key != null) {
            try {
                key.hashCode();// check circular dependencies
            } catch (Exception e) {
                throw new ConstructorException("while constructing a Set", node.getStartMark(),
                        "found unacceptable key " + key, tuple.getKeyNode().getStartMark(), e);
            }
        }
        if (keyNode.isTwoStepsConstruction()) {
            /*
             * if keyObject is created it 2 steps we should postpone putting
             * it into the set because it may have different hash after
             * initialization compared to clean just created one. And set of
             * course does not observe value hashCode changes.
             */
            sets2fill.add(0, new RecursiveTuple<Set<Object>, Object>(set, key));
        } else {
            set.add(key);
        }
    }
}
 
Example 2
Source File: BaseConstructor.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
protected void constructSet2ndStep(MappingNode node, Set<Object> set) {
    List<NodeTuple> nodeValue = (List<NodeTuple>) node.getValue();
    for (NodeTuple tuple : nodeValue) {
        Node keyNode = tuple.getKeyNode();
        Object key = constructObject(keyNode);
        if (key != null) {
            try {
                key.hashCode();// check circular dependencies
            } catch (Exception e) {
                throw new ConstructorException("while constructing a Set", node.getStartMark(),
                        "found unacceptable key " + key, tuple.getKeyNode().getStartMark(), e);
            }
        }
        if (keyNode.isTwoStepsConstruction()) {
            /*
             * if keyObject is created it 2 steps we should postpone putting
             * it into the set because it may have different hash after
             * initialization compared to clean just created one. And set of
             * course does not observe value hashCode changes.
             */
            sets2fill.add(0, new RecursiveTuple<Set<Object>, Object>(set, key));
        } else {
            set.add(key);
        }
    }
}
 
Example 3
Source File: YamlDeserializationData.java    From Diorite with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <K, T, M extends Map<K, T>> void getMap(String key, Function<String, K> keyMapper, Class<T> type, M map)
{
    Node node = this.getNode(this.node, key);
    if (! (node instanceof MappingNode))
    {
        throw new DeserializationException(type, this, "Can't find valid value for key: " + key);
    }
    MappingNode mappingNode = (MappingNode) node;
    Tag typeTag = new Tag(type);
    for (NodeTuple tuple : mappingNode.getValue())
    {
        Node keyNode = tuple.getKeyNode();
        keyNode.setTag(Tag.STR);
        K keyObj = keyMapper.apply(this.constructor.constructObject(keyNode).toString());

        Node valueNode = tuple.getValueNode();
        if (type != Object.class)
        {
            valueNode.setTag(typeTag);
        }

        map.put(keyObj, (T) this.constructor.constructObject(valueNode));
    }
}
 
Example 4
Source File: BaseConstructor.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
protected void constructMapping2ndStep(MappingNode node, Map<Object, Object> mapping) {
    List<NodeTuple> nodeValue = (List<NodeTuple>) node.getValue();
    for (NodeTuple tuple : nodeValue) {
        Node keyNode = tuple.getKeyNode();
        Node valueNode = tuple.getValueNode();
        Object key = constructObject(keyNode);
        if (key != null) {
            try {
                key.hashCode();// check circular dependencies
            } catch (Exception e) {
                throw new ConstructorException("while constructing a mapping",
                        node.getStartMark(), "found unacceptable key " + key, tuple
                                .getKeyNode().getStartMark(), e);
            }
        }
        Object value = constructObject(valueNode);
        if (keyNode.isTwoStepsConstruction()) {
            /*
             * if keyObject is created it 2 steps we should postpone putting
             * it in map because it may have different hash after
             * initialization compared to clean just created one. And map of
             * course does not observe key hashCode changes.
             */
            maps2fill.add(0,
                    new RecursiveTuple<Map<Object, Object>, RecursiveTuple<Object, Object>>(
                            mapping, new RecursiveTuple<Object, Object>(key, value)));
        } else {
            mapping.put(key, value);
        }
    }
}
 
Example 5
Source File: BundleCacher.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Grab the property value, assume it's a relative path and prepend the bundle's directory to make it an
 * absolute path.
 * 
 * @param node
 * @return
 */
protected String getPath(Node node, String propertyName)
{
	String relativePath = null;
	if (node instanceof MappingNode)
	{
		MappingNode map = (MappingNode) node;
		List<NodeTuple> nodes = map.getValue();
		for (NodeTuple tuple : nodes)
		{
			Node keyNode = tuple.getKeyNode();
			if (keyNode instanceof ScalarNode)
			{
				ScalarNode scalar = (ScalarNode) keyNode;
				String valueOfKey = scalar.getValue();
				if (propertyName.equals(valueOfKey))
				{
					Node valueNode = tuple.getValueNode();
					if (valueNode instanceof ScalarNode)
					{
						ScalarNode scalarValue = (ScalarNode) valueNode;
						relativePath = scalarValue.getValue();
						break;
					}
				}
			}
		}
	}
	if (relativePath != null)
	{
		IPath pathObj = Path.fromOSString(relativePath);
		if (!pathObj.isAbsolute())
		{
			// Prepend the bundle directory.
			relativePath = new File(bundleDirectory, relativePath).getAbsolutePath();
		}
	}
	return relativePath;
}
 
Example 6
Source File: AbstractUserAgentAnalyzerDirect.java    From yauaa with Apache License 2.0 5 votes vote down vote up
private void loadYamlLookup(MappingNode entry, String filename) {
    String name = null;
    Map<String, String> map = null;

    for (NodeTuple tuple : entry.getValue()) {
        switch (getKeyAsString(tuple, filename)) {
            case "name":
                name = getValueAsString(tuple, filename);
                break;
            case "map":
                if (map == null) {
                    map = new HashMap<>();
                }
                List<NodeTuple> mappings = getValueAsMappingNode(tuple, filename).getValue();
                for (NodeTuple mapping : mappings) {
                    String key = getKeyAsString(mapping, filename);
                    String value = getValueAsString(mapping, filename);

                    if (map.containsKey(key)) {
                        throw new InvalidParserConfigurationException(
                            "In the lookup \"" + name + "\" the key \"" + key + "\" appears multiple times.");
                    }

                    map.put(key, value);
                }
                break;
            default:
                break;
        }
    }

    require(name != null && map != null, entry, filename, "Invalid lookup specified");

    lookups.put(name, map);
}
 
Example 7
Source File: BaseConstructor.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
protected void constructMapping2ndStep(MappingNode node, Map<Object, Object> mapping) {
    List<NodeTuple> nodeValue = (List<NodeTuple>) node.getValue();
    for (NodeTuple tuple : nodeValue) {
        Node keyNode = tuple.getKeyNode();
        Node valueNode = tuple.getValueNode();
        Object key = constructObject(keyNode);
        if (key != null) {
            try {
                key.hashCode();// check circular dependencies
            } catch (Exception e) {
                throw new ConstructorException("while constructing a mapping",
                        node.getStartMark(), "found unacceptable key " + key, tuple
                                .getKeyNode().getStartMark(), e);
            }
        }
        Object value = constructObject(valueNode);
        if (keyNode.isTwoStepsConstruction()) {
            /*
             * if keyObject is created it 2 steps we should postpone putting
             * it in map because it may have different hash after
             * initialization compared to clean just created one. And map of
             * course does not observe key hashCode changes.
             */
            maps2fill.add(0,
                    new RecursiveTuple<Map<Object, Object>, RecursiveTuple<Object, Object>>(
                            mapping, new RecursiveTuple<Object, Object>(key, value)));
        } else {
            mapping.put(key, value);
        }
    }
}
 
Example 8
Source File: BaseConstructor.java    From onedev with MIT License 5 votes vote down vote up
protected void constructMapping2ndStep(MappingNode node, Map<Object, Object> mapping) {
    List<NodeTuple> nodeValue = node.getValue();
    for (NodeTuple tuple : nodeValue) {
        Node keyNode = tuple.getKeyNode();
        Node valueNode = tuple.getValueNode();
        Object key = constructObject(keyNode);
        if (key != null) {
            try {
                key.hashCode();// check circular dependencies
            } catch (Exception e) {
                throw new ConstructorException("while constructing a mapping",
                        node.getStartMark(), "found unacceptable key " + key,
                        tuple.getKeyNode().getStartMark(), e);
            }
        }
        Object value = constructObject(valueNode);
        if (keyNode.isTwoStepsConstruction()) {
            /*
             * if keyObject is created it 2 steps we should postpone putting
             * it in map because it may have different hash after
             * initialization compared to clean just created one. And map of
             * course does not observe key hashCode changes.
             */
            maps2fill.add(0,
                    new RecursiveTuple<Map<Object, Object>, RecursiveTuple<Object, Object>>(
                            mapping, new RecursiveTuple<Object, Object>(key, value)));
        } else {
            mapping.put(key, value);
        }
    }
}
 
Example 9
Source File: StaticFieldsTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
@Override
protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
    MappingNode node = super.representJavaBean(properties, javaBean);
    if (javaBean instanceof JavaBeanWithStaticState) {
        List<NodeTuple> value = node.getValue();
        value.add(new NodeTuple(representData("color"),
                representData(JavaBeanWithStaticState.color)));
        value.add(new NodeTuple(representData("type"),
                representData(JavaBeanWithStaticState.getType())));
    }
    return node;
}
 
Example 10
Source File: YamlDeserializationData.java    From Diorite with MIT License 5 votes vote down vote up
@Override
public <T, C extends Collection<T>> void getAsCollection(String key, Class<T> type, C collection)
{
    Node node = this.getNode(this.node, key);
    if (node == null)
    {
        throw new DeserializationException(type, this, "Can't find valid value for key: " + key);
    }
    if (node instanceof SequenceNode)
    {
        SequenceNode sequenceNode = (SequenceNode) node;
        for (Node nodeValue : sequenceNode.getValue())
        {
            collection.add(this.deserializeSpecial(type, nodeValue, null));
        }
    }
    else if (node instanceof MappingNode)
    {
        MappingNode mappingNode = (MappingNode) node;
        for (NodeTuple tuple : mappingNode.getValue())
        {
            collection.add(this.deserializeSpecial(type, tuple.getValueNode(), null));
        }
    }
    else
    {
        throw new DeserializationException(type, this, "Can't find valid value for key: " + key);
    }
}
 
Example 11
Source File: BundleCacher.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
public Object construct(Node node)
{
	node.setType(SmartTypingPairsElement.class);
	String path = getPath(node);
	SmartTypingPairsElement be = new SmartTypingPairsElement(path);
	MappingNode mapNode = (MappingNode) node;
	List<NodeTuple> tuples = mapNode.getValue();
	for (NodeTuple tuple : tuples)
	{
		ScalarNode keyNode = (ScalarNode) tuple.getKeyNode();
		String key = keyNode.getValue();
		// "pairs", "scope", "displayName" are required
		if ("pairs".equals(key)) //$NON-NLS-1$
		{
			SequenceNode pairsValueNode = (SequenceNode) tuple.getValueNode();
			List<Character> pairs = new ArrayList<Character>();
			List<Node> pairsValues = pairsValueNode.getValue();
			for (Node pairValue : pairsValues)
			{
				ScalarNode blah = (ScalarNode) pairValue;
				String pairCharacter = blah.getValue();
				pairs.add(Character.valueOf(pairCharacter.charAt(0)));
			}
			be.setPairs(pairs);
		}
		else if ("scope".equals(key)) //$NON-NLS-1$
		{
			ScalarNode scopeValueNode = (ScalarNode) tuple.getValueNode();
			be.setScope(scopeValueNode.getValue());
		}
		else if ("displayName".equals(key)) //$NON-NLS-1$
		{
			ScalarNode displayNameNode = (ScalarNode) tuple.getValueNode();
			be.setDisplayName(displayNameNode.getValue());
		}
	}
	return be;
}
 
Example 12
Source File: SafeConstructor.java    From snake-yaml with Apache License 2.0 4 votes vote down vote up
/**
 * Does merge for supplied mapping node.
 * 
 * @param node
 *            where to merge
 * @param isPreffered
 *            true if keys of node should take precedence over others...
 * @param key2index
 *            maps already merged keys to index from values
 * @param values
 *            collects merged NodeTuple
 * @return list of the merged NodeTuple (to be set as value for the
 *         MappingNode)
 */
private List<NodeTuple> mergeNode(MappingNode node, boolean isPreffered,
        Map<Object, Integer> key2index, List<NodeTuple> values) {
    List<NodeTuple> nodeValue = node.getValue();
    // reversed for http://code.google.com/p/snakeyaml/issues/detail?id=139
    Collections.reverse(nodeValue);
    for (Iterator<NodeTuple> iter = nodeValue.iterator(); iter.hasNext();) {
        final NodeTuple nodeTuple = iter.next();
        final Node keyNode = nodeTuple.getKeyNode();
        final Node valueNode = nodeTuple.getValueNode();
        if (keyNode.getTag().equals(Tag.MERGE)) {
            iter.remove();
            switch (valueNode.getNodeId()) {
            case mapping:
                MappingNode mn = (MappingNode) valueNode;
                mergeNode(mn, false, key2index, values);
                break;
            case sequence:
                SequenceNode sn = (SequenceNode) valueNode;
                List<Node> vals = sn.getValue();
                for (Node subnode : vals) {
                    if (!(subnode instanceof MappingNode)) {
                        throw new ConstructorException("while constructing a mapping",
                                node.getStartMark(),
                                "expected a mapping for merging, but found "
                                        + subnode.getNodeId(), subnode.getStartMark());
                    }
                    MappingNode mnode = (MappingNode) subnode;
                    mergeNode(mnode, false, key2index, values);
                }
                break;
            default:
                throw new ConstructorException("while constructing a mapping",
                        node.getStartMark(),
                        "expected a mapping or list of mappings for merging, but found "
                                + valueNode.getNodeId(), valueNode.getStartMark());
            }
        } else {
            // we need to construct keys to avoid duplications
            Object key = constructObject(keyNode);
            if (!key2index.containsKey(key)) { // 1st time merging key
                values.add(nodeTuple);
                // keep track where tuple for the key is
                key2index.put(key, values.size() - 1);
            } else if (isPreffered) { // there is value for the key, but we
                                      // need to override it
                // change value for the key using saved position
                values.set(key2index.get(key), nodeTuple);
            }
        }
    }
    return values;
}
 
Example 13
Source File: YamlDeserializationData.java    From Diorite with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <K, T, M extends Map<K, T>> void getMap(String key, Class<K> keyType, Class<T> type, M map)
{
    Node node = this.getNode(this.node, key);
    if (! (node instanceof MappingNode))
    {
        throw new DeserializationException(type, this, "Can't find valid value for key: " + key);
    }

    MappingNode mappingNode = (MappingNode) node;
    Tag keyTag = new Tag(keyType);
    Tag typeTag = new Tag(type);
    for (NodeTuple tuple : mappingNode.getValue())
    {
        K keyObj;
        Node keyNode = tuple.getKeyNode();
        if (Serialization.isSimpleType(keyType))
        {
            if (keyType != Object.class)
            {
                keyNode.setTag(keyTag);
            }
            keyObj = (K) this.constructor.constructObject(keyNode);
        }
        else if (this.serialization.isStringSerializable(keyType))
        {
            keyNode.setTag(Tag.STR);
            keyObj = this.serialization.deserializeFromString(keyType, this.constructor.constructObject(keyNode).toString());
        }
        else
        {
            throw new DeserializationException(type, this, "Can't deserialize given node to key: (" + type.getName() + ") -> " + keyNode);
        }

        Node valueNode = tuple.getValueNode();
        if (type != Object.class)
        {
            valueNode.setTag(typeTag);
        }
        map.put(keyObj, (T) this.constructor.constructObject(valueNode));
    }
}
 
Example 14
Source File: AbstractUserAgentAnalyzerDirect.java    From yauaa with Apache License 2.0 4 votes vote down vote up
private synchronized void loadYaml(Yaml yaml, InputStream yamlStream, String filename) {
    Node loadedYaml;
    try {
        loadedYaml = yaml.compose(new UnicodeReader(yamlStream));
    } catch (Exception e) {
        throw new InvalidParserConfigurationException("Parse error in the file " + filename + ": " + e.getMessage(), e);
    }

    if (loadedYaml == null) {
        LOG.warn("The file {} is empty", filename);
        return;
    }

    // Get and check top level config
    requireNodeInstanceOf(MappingNode.class, loadedYaml, filename, "File must be a Map");

    MappingNode rootNode = (MappingNode) loadedYaml;

    NodeTuple configNodeTuple = null;
    for (NodeTuple tuple : rootNode.getValue()) {
        String name = getKeyAsString(tuple, filename);
        if ("config".equals(name)) {
            configNodeTuple = tuple;
            break;
        }
        if ("version".equals(name)) {
            // Check the version information from the Yaml files
            assertSameVersion(tuple, filename);
            return;
        }
    }

    require(configNodeTuple != null, loadedYaml, filename, "The top level entry MUST be 'config'.");

    SequenceNode configNode = getValueAsSequenceNode(configNodeTuple, filename);
    List<Node> configList = configNode.getValue();

    for (Node configEntry : configList) {
        requireNodeInstanceOf(MappingNode.class, configEntry, filename, "The entry MUST be a mapping");
        NodeTuple entry = getExactlyOneNodeTuple((MappingNode) configEntry, filename);
        MappingNode actualEntry = getValueAsMappingNode(entry, filename);
        String entryType = getKeyAsString(entry, filename);
        switch (entryType) {
            case "lookup":
                loadYamlLookup(actualEntry, filename);
                break;
            case "set":
                loadYamlLookupSets(actualEntry, filename);
                break;
            case "matcher":
                loadYamlMatcher(actualEntry, filename);
                break;
            case "test":
                if (loadTests) {
                    loadYamlTestcase(actualEntry, filename);
                }
                break;
            default:
                throw new InvalidParserConfigurationException(
                    "Yaml config.(" + filename + ":" + actualEntry.getStartMark().getLine() + "): " +
                        "Found unexpected config entry: " + entryType + ", allowed are 'lookup', 'set', 'matcher' and 'test'");
        }
    }
}
 
Example 15
Source File: YamlUtils.java    From yauaa with Apache License 2.0 4 votes vote down vote up
public static NodeTuple getExactlyOneNodeTuple(MappingNode mappingNode, String filename) {
    List<NodeTuple> nodeTupleList = mappingNode.getValue();
    require(nodeTupleList.size() == 1, mappingNode, filename,
        "There must be exactly 1 value in the list");
    return nodeTupleList.get(0);
}
 
Example 16
Source File: BundleCacher.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Fix for https://aptana.lighthouseapp.com/projects/35272/tickets/1658 Sets the prefix triggers for
 * CommandElements and subclasses. Fixes an issue where "[def]" isn't treated as an array of strings with
 * "def" as an item in it (and would instead think it's a string of "[def]").
 */
protected void setPrefixTriggers(Node node, CommandElement be)
{
	MappingNode mapNode = (MappingNode) node;
	List<NodeTuple> tuples = mapNode.getValue();
	for (NodeTuple tuple : tuples)
	{
		ScalarNode keyNode = (ScalarNode) tuple.getKeyNode();
		String key = keyNode.getValue();
		if ("customProperties".equals(key)) //$NON-NLS-1$
		{
			Node customPropertiesValueNode = tuple.getValueNode();
			if (customPropertiesValueNode instanceof MappingNode)
			{
				MappingNode custompropertiesNode = (MappingNode) customPropertiesValueNode;
				for (NodeTuple propTuple : custompropertiesNode.getValue())
				{
					ScalarNode propKeyNode = (ScalarNode) propTuple.getKeyNode();
					if ("prefix_values".equals(propKeyNode.getValue())) //$NON-NLS-1$
					{
						SequenceNode prefixValuesNode = (SequenceNode) propTuple.getValueNode();
						List<String> values = new ArrayList<String>();
						for (Node prefixValue : prefixValuesNode.getValue())
						{
							if (prefixValue instanceof ScalarNode)
							{
								ScalarNode blah = (ScalarNode) prefixValue;
								values.add(blah.getValue());
							}
							else
							{
								IdeLog.logWarning(ScriptingActivator.getDefault(),
										"Expected a flattened array for trigger, but got nested arrays."); //$NON-NLS-1$
							}
						}
						be.setTrigger(TriggerType.PREFIX.getName(),
								values.toArray(new String[values.size()]));
					}
				}
			}
		}
	}
}
 
Example 17
Source File: VersionedYamlDoc.java    From onedev with MIT License 4 votes vote down vote up
public VersionedYamlDoc(MappingNode wrapped) {
	super(wrapped.getTag(), wrapped.getValue(), wrapped.getFlowStyle());
}
 
Example 18
Source File: Serializer.java    From snake-yaml with Apache License 2.0 4 votes vote down vote up
private void serializeNode(Node node, Node parent) throws IOException {
    if (node.getNodeId() == NodeId.anchor) {
        node = ((AnchorNode) node).getRealNode();
    }
    String tAlias = this.anchors.get(node);
    if (this.serializedNodes.contains(node)) {
        this.emitter.emit(new AliasEvent(tAlias, null, null));
    } else {
        this.serializedNodes.add(node);
        switch (node.getNodeId()) {
        case scalar:
            ScalarNode scalarNode = (ScalarNode) node;
            Tag detectedTag = this.resolver.resolve(NodeId.scalar, scalarNode.getValue(), true);
            Tag defaultTag = this.resolver.resolve(NodeId.scalar, scalarNode.getValue(), false);
            ImplicitTuple tuple = new ImplicitTuple(node.getTag().equals(detectedTag), node
                    .getTag().equals(defaultTag));
            ScalarEvent event = new ScalarEvent(tAlias, node.getTag().getValue(), tuple,
                    scalarNode.getValue(), null, null, scalarNode.getStyle());
            this.emitter.emit(event);
            break;
        case sequence:
            SequenceNode seqNode = (SequenceNode) node;
            boolean implicitS = node.getTag().equals(this.resolver.resolve(NodeId.sequence,
                    null, true));
            this.emitter.emit(new SequenceStartEvent(tAlias, node.getTag().getValue(),
                    implicitS, null, null, seqNode.getFlowStyle()));
            List<Node> list = seqNode.getValue();
            for (Node item : list) {
                serializeNode(item, node);
            }
            this.emitter.emit(new SequenceEndEvent(null, null));
            break;
        default:// instance of MappingNode
            Tag implicitTag = this.resolver.resolve(NodeId.mapping, null, true);
            boolean implicitM = node.getTag().equals(implicitTag);
            this.emitter.emit(new MappingStartEvent(tAlias, node.getTag().getValue(),
                    implicitM, null, null, ((CollectionNode) node).getFlowStyle()));
            MappingNode mnode = (MappingNode) node;
            List<NodeTuple> map = mnode.getValue();
            for (NodeTuple row : map) {
                Node key = row.getKeyNode();
                Node value = row.getValueNode();
                serializeNode(key, mnode);
                serializeNode(value, mnode);
            }
            this.emitter.emit(new MappingEndEvent(null, null));
        }
    }
}
 
Example 19
Source File: SafeConstructor.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Does merge for supplied mapping node.
 * 
 * @param node
 *            where to merge
 * @param isPreffered
 *            true if keys of node should take precedence over others...
 * @param key2index
 *            maps already merged keys to index from values
 * @param values
 *            collects merged NodeTuple
 * @return list of the merged NodeTuple (to be set as value for the
 *         MappingNode)
 */
private List<NodeTuple> mergeNode(MappingNode node, boolean isPreffered,
        Map<Object, Integer> key2index, List<NodeTuple> values) {
    List<NodeTuple> nodeValue = node.getValue();
    // reversed for http://code.google.com/p/snakeyaml/issues/detail?id=139
    Collections.reverse(nodeValue);
    for (Iterator<NodeTuple> iter = nodeValue.iterator(); iter.hasNext();) {
        final NodeTuple nodeTuple = iter.next();
        final Node keyNode = nodeTuple.getKeyNode();
        final Node valueNode = nodeTuple.getValueNode();
        if (keyNode.getTag().equals(Tag.MERGE)) {
            iter.remove();
            switch (valueNode.getNodeId()) {
            case mapping:
                MappingNode mn = (MappingNode) valueNode;
                mergeNode(mn, false, key2index, values);
                break;
            case sequence:
                SequenceNode sn = (SequenceNode) valueNode;
                List<Node> vals = sn.getValue();
                for (Node subnode : vals) {
                    if (!(subnode instanceof MappingNode)) {
                        throw new ConstructorException("while constructing a mapping",
                                node.getStartMark(),
                                "expected a mapping for merging, but found "
                                        + subnode.getNodeId(), subnode.getStartMark());
                    }
                    MappingNode mnode = (MappingNode) subnode;
                    mergeNode(mnode, false, key2index, values);
                }
                break;
            default:
                throw new ConstructorException("while constructing a mapping",
                        node.getStartMark(),
                        "expected a mapping or list of mappings for merging, but found "
                                + valueNode.getNodeId(), valueNode.getStartMark());
            }
        } else {
            // we need to construct keys to avoid duplications
            Object key = constructObject(keyNode);
            if (!key2index.containsKey(key)) { // 1st time merging key
                values.add(nodeTuple);
                // keep track where tuple for the key is
                key2index.put(key, values.size() - 1);
            } else if (isPreffered) { // there is value for the key, but we
                                      // need to override it
                // change value for the key using saved position
                values.set(key2index.get(key), nodeTuple);
            }
        }
    }
    return values;
}
 
Example 20
Source File: Serializer.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
private void serializeNode(Node node, Node parent) throws IOException {
    if (node.getNodeId() == NodeId.anchor) {
        node = ((AnchorNode) node).getRealNode();
    }
    String tAlias = this.anchors.get(node);
    if (this.serializedNodes.contains(node)) {
        this.emitter.emit(new AliasEvent(tAlias, null, null));
    } else {
        this.serializedNodes.add(node);
        switch (node.getNodeId()) {
        case scalar:
            ScalarNode scalarNode = (ScalarNode) node;
            Tag detectedTag = this.resolver.resolve(NodeId.scalar, scalarNode.getValue(), true);
            Tag defaultTag = this.resolver.resolve(NodeId.scalar, scalarNode.getValue(), false);
            ImplicitTuple tuple = new ImplicitTuple(node.getTag().equals(detectedTag), node
                    .getTag().equals(defaultTag));
            ScalarEvent event = new ScalarEvent(tAlias, node.getTag().getValue(), tuple,
                    scalarNode.getValue(), null, null, scalarNode.getStyle());
            this.emitter.emit(event);
            break;
        case sequence:
            SequenceNode seqNode = (SequenceNode) node;
            boolean implicitS = (node.getTag().equals(this.resolver.resolve(NodeId.sequence,
                    null, true)));
            this.emitter.emit(new SequenceStartEvent(tAlias, node.getTag().getValue(),
                    implicitS, null, null, seqNode.getFlowStyle()));
            int indexCounter = 0;
            List<Node> list = seqNode.getValue();
            for (Node item : list) {
                serializeNode(item, node);
                indexCounter++;
            }
            this.emitter.emit(new SequenceEndEvent(null, null));
            break;
        default:// instance of MappingNode
            Tag implicitTag = this.resolver.resolve(NodeId.mapping, null, true);
            boolean implicitM = (node.getTag().equals(implicitTag));
            this.emitter.emit(new MappingStartEvent(tAlias, node.getTag().getValue(),
                    implicitM, null, null, ((CollectionNode) node).getFlowStyle()));
            MappingNode mnode = (MappingNode) node;
            List<NodeTuple> map = mnode.getValue();
            for (NodeTuple row : map) {
                Node key = row.getKeyNode();
                Node value = row.getValueNode();
                serializeNode(key, mnode);
                serializeNode(value, mnode);
            }
            this.emitter.emit(new MappingEndEvent(null, null));
        }
    }
}