Java Code Examples for org.yaml.snakeyaml.nodes.NodeTuple#getValueNode()

The following examples show how to use org.yaml.snakeyaml.nodes.NodeTuple#getValueNode() . 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: AutotesterAnchorGenerator.java    From AuTe-Framework with Apache License 2.0 6 votes vote down vote up
@Override
public String nextAnchor(Node node) {
    if (node instanceof MappingNode) {
        NodeTuple idNode = ((MappingNode) node).getValue()
                .stream()
                .filter(nodeTuple -> nodeTuple.getKeyNode() instanceof ScalarNode)
                .filter(nodeTuple -> "id".equals(((ScalarNode) nodeTuple.getKeyNode()).getValue()))
                .findAny()
                .orElse(null);
        if (idNode != null && idNode.getValueNode() instanceof ScalarNode) {
            String idValue = ((ScalarNode) idNode.getValueNode()).getValue();
            if (idValue != null) {
                return "objId" + idValue;
            }
        }
    }
    return "id" + (lastAnchorId++);
}
 
Example 2
Source File: YamlDeserializationData.java    From Diorite with MIT License 6 votes vote down vote up
@Nullable
private Node getNode(MappingNode node, String key, boolean remove)
{
    for (Iterator<NodeTuple> iterator = node.getValue().iterator(); iterator.hasNext(); )
    {
        NodeTuple tuple = iterator.next();
        Node keyNode = tuple.getKeyNode();
        if (! (keyNode instanceof ScalarNode))
        {
            return null;
        }
        if (key.equals(((ScalarNode) keyNode).getValue()))
        {
            if (remove)
            {
                iterator.remove();
            }
            return tuple.getValueNode();
        }
    }
    return null;
}
 
Example 3
Source File: UniqueKeyTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
@Override
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) {
            key.hashCode();// check circular dependencies
        }
        Object value = constructObject(valueNode);
        Object old = mapping.put(key, value);
        if (old != null) {
            throw new YAMLException("The key is not unique " + key);
        }
    }
}
 
Example 4
Source File: CompactConstructor.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
@Override
public void construct2ndStep(Node node, Object object) {
    // Compact Object Notation may contain only one entry
    MappingNode mnode = (MappingNode) node;
    NodeTuple nodeTuple = mnode.getValue().iterator().next();

    Node valueNode = nodeTuple.getValueNode();

    if (valueNode instanceof MappingNode) {
        valueNode.setType(object.getClass());
        constructJavaBean2ndStep((MappingNode) valueNode, object);
    } else {
        // value is a list
        applySequence(object, constructSequence((SequenceNode) valueNode));
    }
}
 
Example 5
Source File: CompactConstructor.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void construct2ndStep(Node node, Object object) {
    // Compact Object Notation may contain only one entry
    MappingNode mnode = (MappingNode) node;
    NodeTuple nodeTuple = mnode.getValue().iterator().next();

    Node valueNode = nodeTuple.getValueNode();

    if (valueNode instanceof MappingNode) {
        valueNode.setType(object.getClass());
        constructJavaBean2ndStep((MappingNode) valueNode, object);
    } else {
        // value is a list
        applySequence(object, constructSequence((SequenceNode) valueNode));
    }
}
 
Example 6
Source File: JsonReconcilingStrategy.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 6 votes vote down vote up
protected List<Position> calculatePositions(MappingNode mapping) {
    List<Position> positions = new ArrayList<>();
    int start;
    int end = -1;

    for (NodeTuple tuple : mapping.getValue()) {
        start = tuple.getKeyNode().getStartMark().getLine();
        end = tuple.getValueNode().getEndMark().getLine();

        if ((end - start) > 0) {
            try {
                int startOffset = document.getLineOffset(start);
                int endOffset = document.getLineOffset(end);

                positions.add(new Position(startOffset, (endOffset - startOffset)));
            } catch (BadLocationException e) {
            }
        }

        if (tuple.getValueNode() instanceof MappingNode) {
            positions.addAll(calculatePositions((MappingNode) tuple.getValueNode()));
        }
    }

    return positions;
}
 
Example 7
Source File: Representer.java    From onedev with MIT License 5 votes vote down vote up
/**
 * Tag logic:
 * - explicit root tag is set in serializer
 * - if there is a predefined class tag it is used
 * - a global tag with class name is always used as tag. The JavaBean parent
 * of the specified JavaBean may set another tag (tag:yaml.org,2002:map)
 * when the property class is the same as runtime class
 *
 * @param properties
 *            JavaBean getters
 * @param javaBean
 *            instance for Node
 * @return Node to get serialized
 */
protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
    List<NodeTuple> value = new ArrayList<NodeTuple>(properties.size());
    Tag tag;
    Tag customTag = classTags.get(javaBean.getClass());
    tag = customTag != null ? customTag : new Tag("!" + javaBean.getClass().getSimpleName());
    // flow style will be chosen by BaseRepresenter
    MappingNode node = new MappingNode(tag, value, FlowStyle.AUTO);
    representedObjects.put(javaBean, node);
    DumperOptions.FlowStyle bestStyle = FlowStyle.FLOW;
    for (Property property : properties) {
        Object memberValue = property.get(javaBean);
        Tag customPropertyTag = memberValue == null ? null
                : classTags.get(memberValue.getClass());
        NodeTuple tuple = representJavaBeanProperty(javaBean, property, memberValue,
                customPropertyTag);
        if (tuple == null) {
            continue;
        }
        if (!((ScalarNode) tuple.getKeyNode()).isPlain()) {
            bestStyle = FlowStyle.BLOCK;
        }
        Node nodeValue = tuple.getValueNode();
        if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).isPlain())) {
            bestStyle = FlowStyle.BLOCK;
        }
        value.add(tuple);
    }
    if (defaultFlowStyle != FlowStyle.AUTO) {
        node.setFlowStyle(defaultFlowStyle);
    } else {
        node.setFlowStyle(bestStyle);
    }
    return node;
}
 
Example 8
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 9
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 10
Source File: Representer.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Tag logic:<br/>
 * - explicit root tag is set in serializer <br/>
 * - if there is a predefined class tag it is used<br/>
 * - a global tag with class name is always used as tag. The JavaBean parent
 * of the specified JavaBean may set another tag (tag:yaml.org,2002:map)
 * when the property class is the same as runtime class
 * 
 * @param properties
 *            JavaBean getters
 * @param javaBean
 *            instance for Node
 * @return Node to get serialized
 */
protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
    List<NodeTuple> value = new ArrayList<NodeTuple>(properties.size());
    Tag tag;
    Tag customTag = classTags.get(javaBean.getClass());
    tag = customTag != null ? customTag : new Tag(javaBean.getClass());
    // flow style will be chosen by BaseRepresenter
    MappingNode node = new MappingNode(tag, value, null);
    representedObjects.put(javaBean, node);
    boolean bestStyle = true;
    for (Property property : properties) {
        Object memberValue = property.get(javaBean);
        Tag customPropertyTag = memberValue == null ? null : classTags.get(memberValue
                .getClass());
        NodeTuple tuple = representJavaBeanProperty(javaBean, property, memberValue,
                customPropertyTag);
        if (tuple == null) {
            continue;
        }
        if (((ScalarNode) tuple.getKeyNode()).getStyle() != null) {
            bestStyle = false;
        }
        Node nodeValue = tuple.getValueNode();
        if (!((nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null))) {
            bestStyle = false;
        }
        value.add(tuple);
    }
    if (defaultFlowStyle != FlowStyle.AUTO) {
        node.setFlowStyle(defaultFlowStyle.getStyleBoolean());
    } else {
        node.setFlowStyle(bestStyle);
    }
    return node;
}
 
Example 11
Source File: BuildSpec.java    From onedev with MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
private void migrate1(VersionedYamlDoc doc, Stack<Integer> versions) {
	for (NodeTuple specTuple: doc.getValue()) {
		if (((ScalarNode)specTuple.getKeyNode()).getValue().equals("jobs")) {
			SequenceNode jobsNode = (SequenceNode) specTuple.getValueNode();
			for (Node jobsNodeItem: jobsNode.getValue()) {
				MappingNode jobNode = (MappingNode) jobsNodeItem;
				for (Iterator<NodeTuple> itJobTuple = jobNode.getValue().iterator(); itJobTuple.hasNext();) {
					NodeTuple jobTuple = itJobTuple.next();
					String jobTupleKey = ((ScalarNode)jobTuple.getKeyNode()).getValue();
					if (jobTupleKey.equals("submoduleCredentials")) {
						itJobTuple.remove();
					} else if (jobTupleKey.equals("projectDependencies")) {
						SequenceNode projectDependenciesNode = (SequenceNode) jobTuple.getValueNode();
						for (Node projectDependenciesItem: projectDependenciesNode.getValue()) {
							MappingNode projectDependencyNode = (MappingNode) projectDependenciesItem;
							for (Iterator<NodeTuple> itProjectDependencyTuple = projectDependencyNode.getValue().iterator(); 
									itProjectDependencyTuple.hasNext();) {
								NodeTuple projectDependencyTuple = itProjectDependencyTuple.next();
								if (((ScalarNode)projectDependencyTuple.getKeyNode()).getValue().equals("authentication"))
									itProjectDependencyTuple.remove();
							}								
						}
					}
				}
				NodeTuple cloneCredentialTuple = new NodeTuple(
						new ScalarNode(Tag.STR, "cloneCredential"), 
						new MappingNode(new Tag("!DefaultCredential"), Lists.newArrayList(), FlowStyle.BLOCK));
				jobNode.getValue().add(cloneCredentialTuple);
			}
		}
	}
}
 
Example 12
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 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: 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 15
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 16
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 17
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 18
Source File: ValidationUtil.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 4 votes vote down vote up
private static Node findNode(NodeTuple child, List<String> paths) {
    if (child.getValueNode() instanceof MappingNode) {
        return findNode((MappingNode) child.getValueNode(), paths);
    }
    return child.getKeyNode();
}
 
Example 19
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 20
Source File: YamlUtils.java    From yauaa with Apache License 2.0 4 votes vote down vote up
public static SequenceNode getValueAsSequenceNode(NodeTuple tuple, String filename) {
    Node valueNode = tuple.getValueNode();
    requireNodeInstanceOf(SequenceNode.class, valueNode, filename,
        "The value should be a sequence but it is a " + valueNode.getNodeId().name());
    return ((SequenceNode)valueNode);
}