Java Code Examples for org.yaml.snakeyaml.nodes.Node#getNodeId()

The following examples show how to use org.yaml.snakeyaml.nodes.Node#getNodeId() . 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: ConfigurationRepresenter.java    From ServerListPlus with GNU General Public License v3.0 6 votes vote down vote up
@Override // Skip null values for configuration generating
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object value, Tag customTag) {
    if (value != null) {
        NodeTuple tuple = super.representJavaBeanProperty(javaBean, property, value, customTag);
        Node valueNode = tuple.getValueNode();

        // Avoid using tags for enums
        if (customTag == null && valueNode.getNodeId() == NodeId.scalar && value instanceof Enum<?>) {
            valueNode.setTag(Tag.STR);
        }

        return tuple;
    } else {
        return null;
    }
}
 
Example 2
Source File: IgnoreTagsExampleTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
public Object construct(Node node) {
    if (node.getTag().startsWith("!KnownTag")) {
        return original.construct(node);
    } else {
        switch (node.getNodeId()) {
        case scalar:
            return yamlConstructors.get(Tag.STR).construct(node);
        case sequence:
            return yamlConstructors.get(Tag.SEQ).construct(node);
        case mapping:
            return yamlConstructors.get(Tag.MAP).construct(node);
        default:
            throw new YAMLException("Unexpected node");
        }
    }
}
 
Example 3
Source File: Representer.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Represent one JavaBean property.
 * 
 * @param javaBean
 *            - the instance to be represented
 * @param property
 *            - the property of the instance
 * @param propertyValue
 *            - value to be represented
 * @param customTag
 *            - user defined Tag
 * @return NodeTuple to be used in a MappingNode. Return null to skip the
 *         property
 */
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property,
        Object propertyValue, Tag customTag) {
    ScalarNode nodeKey = (ScalarNode) representData(property.getName());
    // the first occurrence of the node must keep the tag
    boolean hasAlias = this.representedObjects.containsKey(propertyValue);

    Node nodeValue = representData(propertyValue);

    if (propertyValue != null && !hasAlias) {
        NodeId nodeId = nodeValue.getNodeId();
        if (customTag == null) {
            if (nodeId == NodeId.scalar) {
                if (propertyValue instanceof Enum<?>) {
                    nodeValue.setTag(Tag.STR);
                }
            } else {
                if (nodeId == NodeId.mapping) {
                    if (property.getType() == propertyValue.getClass()) {
                        if (!(propertyValue instanceof Map<?, ?>)) {
                            if (!nodeValue.getTag().equals(Tag.SET)) {
                                nodeValue.setTag(Tag.MAP);
                            }
                        }
                    }
                }
                checkGlobalTag(property, nodeValue, propertyValue);
            }
        }
    }

    return new NodeTuple(nodeKey, nodeValue);
}
 
Example 4
Source File: SafeConstructor.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
public Object construct(Node node) {
    // Note: we do not check for duplicate keys, because it's too
    // CPU-expensive.
    Map<Object, Object> omap = new LinkedHashMap<Object, Object>();
    if (!(node instanceof SequenceNode)) {
        throw new ConstructorException("while constructing an ordered map",
                node.getStartMark(), "expected a sequence, but found " + node.getNodeId(),
                node.getStartMark());
    }
    SequenceNode snode = (SequenceNode) node;
    for (Node subnode : snode.getValue()) {
        if (!(subnode instanceof MappingNode)) {
            throw new ConstructorException("while constructing an ordered map",
                    node.getStartMark(), "expected a mapping of length 1, but found "
                            + subnode.getNodeId(), subnode.getStartMark());
        }
        MappingNode mnode = (MappingNode) subnode;
        if (mnode.getValue().size() != 1) {
            throw new ConstructorException("while constructing an ordered map",
                    node.getStartMark(), "expected a single mapping item, but found "
                            + mnode.getValue().size() + " items", mnode.getStartMark());
        }
        Node keyNode = mnode.getValue().get(0).getKeyNode();
        Node valueNode = mnode.getValue().get(0).getValueNode();
        Object key = constructObject(keyNode);
        Object value = constructObject(valueNode);
        omap.put(key, value);
    }
    return omap;
}
 
Example 5
Source File: SafeConstructor.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
public Object construct(Node node) {
    // Note: we do not check for duplicate keys, because it's too
    // CPU-expensive.
    if (!(node instanceof SequenceNode)) {
        throw new ConstructorException("while constructing pairs", node.getStartMark(),
                "expected a sequence, but found " + node.getNodeId(), node.getStartMark());
    }
    SequenceNode snode = (SequenceNode) node;
    List<Object[]> pairs = new ArrayList<Object[]>(snode.getValue().size());
    for (Node subnode : snode.getValue()) {
        if (!(subnode instanceof MappingNode)) {
            throw new ConstructorException("while constructingpairs", node.getStartMark(),
                    "expected a mapping of length 1, but found " + subnode.getNodeId(),
                    subnode.getStartMark());
        }
        MappingNode mnode = (MappingNode) subnode;
        if (mnode.getValue().size() != 1) {
            throw new ConstructorException("while constructing pairs", node.getStartMark(),
                    "expected a single mapping item, but found " + mnode.getValue().size()
                            + " items", mnode.getStartMark());
        }
        Node keyNode = mnode.getValue().get(0).getKeyNode();
        Node valueNode = mnode.getValue().get(0).getValueNode();
        Object key = constructObject(keyNode);
        Object value = constructObject(valueNode);
        pairs.add(new Object[] { key, value });
    }
    return pairs;
}
 
Example 6
Source File: ManifestParser.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
private void addChild(NodeTuple tuple, ManifestParseTree parent) throws ParserException {
	ManifestParseTree keyNode = new ManifestParseTree();
	Node tupleKeyNode = tuple.getKeyNode();
	int lineNumber = tupleKeyNode.getStartMark().getLine() + 1;
	if (tupleKeyNode.getNodeId() != NodeId.scalar) {
		throw new ParserException(NLS.bind(ManifestConstants.UNSUPPORTED_TOKEN_ERROR, lineNumber), lineNumber);
	}
	keyNode.setLabel(((ScalarNode) tupleKeyNode).getValue());
	keyNode.setLineNumber(lineNumber);
	keyNode.setParent(parent);
	parent.getChildren().add(keyNode);
	addChild(tuple.getValueNode(), keyNode);
}
 
Example 7
Source File: Representer.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
/**
 * Represent one JavaBean property.
 *
 * @param javaBean
 *            - the instance to be represented
 * @param property
 *            - the property of the instance
 * @param propertyValue
 *            - value to be represented
 * @param customTag
 *            - user defined Tag
 * @return NodeTuple to be used in a MappingNode. Return null to skip the
 *         property
 */
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property,
        Object propertyValue, Tag customTag) {
    ScalarNode nodeKey = (ScalarNode) representData(property.getName());
    // the first occurrence of the node must keep the tag
    boolean hasAlias = this.representedObjects.containsKey(propertyValue);

    Node nodeValue = representData(propertyValue);

    if (propertyValue != null && !hasAlias) {
        NodeId nodeId = nodeValue.getNodeId();
        if (customTag == null) {
            if (nodeId == NodeId.scalar) {
                if (propertyValue instanceof Enum<?>) {
                    nodeValue.setTag(Tag.STR);
                }
            } else {
                if (nodeId == NodeId.mapping) {
                    if (property.getType() == propertyValue.getClass()) {
                        if (!(propertyValue instanceof Map<?, ?>)) {
                            if (!nodeValue.getTag().equals(Tag.SET)) {
                                nodeValue.setTag(Tag.MAP);
                            }
                        }
                    }
                }
                checkGlobalTag(property, nodeValue, propertyValue);
            }
        }
    }

    return new NodeTuple(nodeKey, nodeValue);
}
 
Example 8
Source File: Representer.java    From onedev with MIT License 5 votes vote down vote up
/**
 * Represent one JavaBean property.
 *
 * @param javaBean
 *            - the instance to be represented
 * @param property
 *            - the property of the instance
 * @param propertyValue
 *            - value to be represented
 * @param customTag
 *            - user defined Tag
 * @return NodeTuple to be used in a MappingNode. Return null to skip the
 *         property
 */
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property,
        Object propertyValue, Tag customTag) {
    ScalarNode nodeKey = (ScalarNode) representData(property.getName());
    // the first occurrence of the node must keep the tag
    boolean hasAlias = this.representedObjects.containsKey(propertyValue);

    Node nodeValue = representData(propertyValue);

    if (propertyValue != null && !hasAlias) {
        NodeId nodeId = nodeValue.getNodeId();
        if (customTag == null) {
            if (nodeId == NodeId.scalar) {
                if (property.getType() == propertyValue.getClass()) {
                    if (propertyValue instanceof Enum<?>) {
                        nodeValue.setTag(Tag.STR);
                    }
                }
            } else {
                if (nodeId == NodeId.mapping) {
                    if (property.getType() == propertyValue.getClass()) {
                        if (!(propertyValue instanceof Map<?, ?>)) {
                            if (!nodeValue.getTag().equals(Tag.SET)) {
                                nodeValue.setTag(Tag.MAP);
                            }
                        }
                    }
                }
                checkGlobalTag(property, nodeValue, propertyValue);
            }
        }
    }

    return new NodeTuple(nodeKey, nodeValue);
}
 
Example 9
Source File: SafeConstructor.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public Object construct(Node node) {
    // Note: we do not check for duplicate keys, because it's too
    // CPU-expensive.
    Map<Object, Object> omap = new LinkedHashMap<Object, Object>();
    if (!(node instanceof SequenceNode)) {
        throw new ConstructorException("while constructing an ordered map",
                node.getStartMark(), "expected a sequence, but found " + node.getNodeId(),
                node.getStartMark());
    }
    SequenceNode snode = (SequenceNode) node;
    for (Node subnode : snode.getValue()) {
        if (!(subnode instanceof MappingNode)) {
            throw new ConstructorException("while constructing an ordered map",
                    node.getStartMark(), "expected a mapping of length 1, but found "
                            + subnode.getNodeId(), subnode.getStartMark());
        }
        MappingNode mnode = (MappingNode) subnode;
        if (mnode.getValue().size() != 1) {
            throw new ConstructorException("while constructing an ordered map",
                    node.getStartMark(), "expected a single mapping item, but found "
                            + mnode.getValue().size() + " items", mnode.getStartMark());
        }
        Node keyNode = mnode.getValue().get(0).getKeyNode();
        Node valueNode = mnode.getValue().get(0).getValueNode();
        Object key = constructObject(keyNode);
        Object value = constructObject(valueNode);
        omap.put(key, value);
    }
    return omap;
}
 
Example 10
Source File: SafeConstructor.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public Object construct(Node node) {
    // Note: we do not check for duplicate keys, because it's too
    // CPU-expensive.
    if (!(node instanceof SequenceNode)) {
        throw new ConstructorException("while constructing pairs", node.getStartMark(),
                "expected a sequence, but found " + node.getNodeId(), node.getStartMark());
    }
    SequenceNode snode = (SequenceNode) node;
    List<Object[]> pairs = new ArrayList<Object[]>(snode.getValue().size());
    for (Node subnode : snode.getValue()) {
        if (!(subnode instanceof MappingNode)) {
            throw new ConstructorException("while constructingpairs", node.getStartMark(),
                    "expected a mapping of length 1, but found " + subnode.getNodeId(),
                    subnode.getStartMark());
        }
        MappingNode mnode = (MappingNode) subnode;
        if (mnode.getValue().size() != 1) {
            throw new ConstructorException("while constructing pairs", node.getStartMark(),
                    "expected a single mapping item, but found " + mnode.getValue().size()
                            + " items", mnode.getStartMark());
        }
        Node keyNode = mnode.getValue().get(0).getKeyNode();
        Node valueNode = mnode.getValue().get(0).getValueNode();
        Object key = constructObject(keyNode);
        Object value = constructObject(valueNode);
        pairs.add(new Object[] { key, value });
    }
    return pairs;
}
 
Example 11
Source File: BeanConstructor.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
@Override
public Object construct(Node node) {
    if (node.getNodeId() == NodeId.scalar) {
        ScalarNode n = (ScalarNode) node;
        String value = n.getValue();
        int i = 3;
        if (value.length() != 0) {
            i = Integer.parseInt(value);
        }
        return new BeanHolder(new Bean1(i));
    } else {
        return new BeanHolder();
    }
}
 
Example 12
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 13
Source File: Yamls.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private static void findTextOfYamlAtPath(YamlExtract result, int pathIndex, Object ...path) {
    if (pathIndex>=path.length) {
        // we're done
        return;
    }
    
    Object pathItem = path[pathIndex];
    Node node = result.focus;
    
    if (node.getNodeId()==NodeId.mapping && pathItem instanceof String) {
        // find key
        Iterator<NodeTuple> ti = ((MappingNode)node).getValue().iterator();
        while (ti.hasNext()) {
            NodeTuple t = ti.next();
            Node key = t.getKeyNode();
            if (key.getNodeId()==NodeId.scalar) {
                if (pathItem.equals( ((ScalarNode)key).getValue() )) {
                    result.key = key;
                    result.focus = t.getValueNode();
                    if (pathIndex+1<path.length) {
                        // there are more path items, so the key here is a previous node
                        result.prev = key;
                    } else {
                        result.focusTuple = t;
                    }
                    findTextOfYamlAtPath(result, pathIndex+1, path);
                    if (result.next==null) {
                        if (ti.hasNext()) result.next = ti.next().getKeyNode();
                    }
                    return;
                } else {
                    result.prev = t.getValueNode();
                }
            } else {
                throw new IllegalStateException("Key "+key+" is not a scalar, searching for "+pathItem+" at depth "+pathIndex+" of "+Arrays.asList(path));
            }
        }
        throw new IllegalStateException("Did not find "+pathItem+" in "+node+" at depth "+pathIndex+" of "+Arrays.asList(path));
        
    } else if (node.getNodeId()==NodeId.sequence && pathItem instanceof Number) {
        // find list item
        List<Node> nl = ((SequenceNode)node).getValue();
        int i = ((Number)pathItem).intValue();
        if (i>=nl.size()) 
            throw new IllegalStateException("Index "+i+" is out of bounds in "+node+", searching for "+pathItem+" at depth "+pathIndex+" of "+Arrays.asList(path));
        if (i>0) result.prev = nl.get(i-1);
        result.key = null;
        result.focus = nl.get(i);
        findTextOfYamlAtPath(result, pathIndex+1, path);
        if (result.next==null) {
            if (nl.size()>i+1) result.next = nl.get(i+1);
        }
        return;
        
    } else {
        throw new IllegalStateException("Node "+node+" does not match selector "+pathItem+" at depth "+pathIndex+" of "+Arrays.asList(path));
    }
    
    // unreachable
}
 
Example 14
Source File: Representer.java    From Diorite with MIT License 4 votes vote down vote up
/**
 * Represent one JavaBean property.
 *
 * @param javaBean
 *         - the instance to be represented
 * @param property
 *         - the property of the instance
 * @param propertyValue
 *         - value to be represented
 * @param customTag
 *         - user defined Tag
 *
 * @return NodeTuple to be used in a MappingNode. Return null to skip the property
 */
@Nullable
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, @Nullable Object propertyValue, @Nullable Tag customTag)
{
    ScalarNode nodeKey = (ScalarNode) this.representData(property.getName());
    // the first occurrence of the node must keep the tag
    boolean hasAlias = this.representedObjects.containsKey(propertyValue);

    Node nodeValue = this.representData(propertyValue);

    if ((propertyValue != null) && ! hasAlias)
    {
        NodeId nodeId = nodeValue.getNodeId();
        if (customTag == null)
        {
            if (nodeId == NodeId.scalar)
            {
                if (propertyValue instanceof Enum<?>)
                {
                    nodeValue.setTag(Tag.STR);
                }
            }
            else
            {
                if (nodeId == NodeId.mapping)
                {
                    if (property.getType() == propertyValue.getClass())
                    {
                        if (! (propertyValue instanceof Map<?, ?>))
                        {
                            if (! nodeValue.getTag().equals(Tag.SET))
                            {
                                nodeValue.setTag(Tag.MAP);
                            }
                        }
                    }
                }
                this.checkGlobalTag(property, nodeValue, propertyValue);
            }
        }
    }

    return new NodeTuple(nodeKey, nodeValue);
}
 
Example 15
Source File: Serializer.java    From Diorite with MIT License 4 votes vote down vote up
private void serializeNode(Node node, @Nullable Node parent, LinkedList<String> commentPath, boolean mappingScalar) 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);
                String[] pathNodes = commentPath.toArray(new String[commentPath.size()]);
                String comment;
                if (this.checkCommentsSet(pathNodes))
                {
                    comment = this.comments.getComment(pathNodes);
                }
                else
                {
                    comment = null;
                }
                ImplicitTuple tuple = new ImplicitTupleExtension(node.getTag().equals(detectedTag), node.getTag().equals(defaultTag), comment);
                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)
                {
                    this.serializeNode(item, node, commentPath, false);
                }
                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();
                    if (key instanceof ScalarNode)
                    {
                        commentPath.add(((ScalarNode) key).getValue());
                    }
                    this.serializeNode(key, mnode, commentPath, true);
                    this.serializeNode(value, mnode, commentPath, false);
                    if (key instanceof ScalarNode)
                    {
                        commentPath.removeLast();
                    }
                }
                this.emitter.emit(new MappingEndEvent(null, null));
        }
    }
}
 
Example 16
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 17
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 18
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));
        }
    }
}
 
Example 19
Source File: YamlUtils.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
private static void merge(Node root, Node node, String source) throws ConfiguratorException {
    if (root.getNodeId() != node.getNodeId()) {
        // means one of those yaml file doesn't conform to JCasC schema
        throw new ConfiguratorException(
                String.format("Found incompatible configuration elements %s %s", source, node.getStartMark()));
    }

    switch (root.getNodeId()) {
        case sequence:
            SequenceNode seq = (SequenceNode) root;
            SequenceNode seq2 = (SequenceNode) node;
            seq.getValue().addAll(seq2.getValue());
            return;
        case mapping:
            MappingNode map = (MappingNode) root;
            MappingNode map2 = (MappingNode) node;
            // merge common entries
            final Iterator<NodeTuple> it = map2.getValue().iterator();
            while (it.hasNext()) {
                NodeTuple t2 = it.next();
                for (NodeTuple tuple : map.getValue()) {

                    final Node key = tuple.getKeyNode();
                    final Node key2 = t2.getKeyNode();
                    if (key.getNodeId() == NodeId.scalar) {
                        // We dont support merge for more complex cases (yet)
                        if (((ScalarNode) key).getValue().equals(((ScalarNode) key2).getValue())) {
                            merge(tuple.getValueNode(), t2.getValueNode(), source);
                            it.remove();
                        }
                    } else {
                        throw new ConfiguratorException(
                                String.format("Found unmergeable configuration keys %s %s)", source, node.getEndMark()));
                    }
                }
            }
            // .. and add others
            map.getValue().addAll(map2.getValue());
            return;
        default:
            throw new ConfiguratorException(
                    String.format("Found conflicting configuration at %s %s", source, node.getStartMark()));
    }

}