org.yaml.snakeyaml.nodes.ScalarNode Java Examples

The following examples show how to use org.yaml.snakeyaml.nodes.ScalarNode. 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: SafeConstructor.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
public Object construct(Node node) {
    ScalarNode scalar = (ScalarNode) node;
    try {
        return nf.parse(scalar.getValue());
    } catch (ParseException e) {
        String lowerCaseValue = scalar.getValue().toLowerCase();
        if (lowerCaseValue.contains("inf") || lowerCaseValue.contains("nan")) {
            /*
             * Non-finites such as (+/-)infinity and NaN are not
             * parseable by NumberFormat when these `Double` values are
             * dumped by snakeyaml. Delegate to the `Tag.FLOAT`
             * constructor when for this expected failure cause.
             */
            return (Number) yamlConstructors.get(Tag.FLOAT).construct(node);
        } else {
            throw new IllegalArgumentException("Unable to parse as Number: "
                    + scalar.getValue());
        }
    }
}
 
Example #3
Source File: BaseRepresenter.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
protected Node representMapping(Tag tag, Map<?, ?> mapping, Boolean flowStyle) {
    List<NodeTuple> value = new ArrayList<NodeTuple>(mapping.size());
    MappingNode node = new MappingNode(tag, value, flowStyle);
    representedObjects.put(objectToRepresent, node);
    boolean bestStyle = true;
    for (Map.Entry<?, ?> entry : mapping.entrySet()) {
        Node nodeKey = representData(entry.getKey());
        Node nodeValue = representData(entry.getValue());
        if (!((nodeKey instanceof ScalarNode && ((ScalarNode) nodeKey).getStyle() == null))) {
            bestStyle = false;
        }
        if (!((nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null))) {
            bestStyle = false;
        }
        value.add(new NodeTuple(nodeKey, nodeValue));
    }
    if (flowStyle == null) {
        if (defaultFlowStyle != FlowStyle.AUTO) {
            node.setFlowStyle(defaultFlowStyle.getStyleBoolean());
        } else {
            node.setFlowStyle(bestStyle);
        }
    }
    return node;
}
 
Example #4
Source File: XmlBuildSpecMigrator.java    From onedev with MIT License 6 votes vote down vote up
private static Node migrateDefaultValueProvider(Element defaultValueProviderElement) {
	List<NodeTuple> tuples = new ArrayList<>();
	String classTag = getClassTag(defaultValueProviderElement.attributeValue("class"));
	Element scriptNameElement = defaultValueProviderElement.element("scriptName");
	if (scriptNameElement != null) {
		tuples.add(new NodeTuple(
				new ScalarNode(Tag.STR, "scriptName"), 
				new ScalarNode(Tag.STR, scriptNameElement.getText().trim())));
	}
	Element valueElement = defaultValueProviderElement.element("value");
	if (valueElement != null) {
		tuples.add(new NodeTuple(
				new ScalarNode(Tag.STR, "value"), 
				new ScalarNode(Tag.STR, valueElement.getText().trim())));
	}
	
	return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
 
Example #5
Source File: XmlBuildSpecMigrator.java    From onedev with MIT License 6 votes vote down vote up
private static Node migrateDefaultMultiValueProvider(Element defaultMultiValueProviderElement) {
	List<NodeTuple> tuples = new ArrayList<>();
	String classTag = getClassTag(defaultMultiValueProviderElement.attributeValue("class"));
	Element scriptNameElement = defaultMultiValueProviderElement.element("scriptName");
	if (scriptNameElement != null) {
		tuples.add(new NodeTuple(
				new ScalarNode(Tag.STR, "scriptName"), 
				new ScalarNode(Tag.STR, scriptNameElement.getText().trim())));
	}
	Element valueElement = defaultMultiValueProviderElement.element("value");
	if (valueElement != null) {
		List<Node> valueItemNodes = new ArrayList<>();
		for (Element valueItemElement: valueElement.elements())
			valueItemNodes.add(new ScalarNode(Tag.STR, valueItemElement.getText().trim()));
		tuples.add(new NodeTuple(
				new ScalarNode(Tag.STR, "value"), 
				new SequenceNode(Tag.SEQ, valueItemNodes, FlowStyle.BLOCK)));
	}
	
	return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
 
Example #6
Source File: BaseRepresenter.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
protected Node representSequence(Tag tag, Iterable<?> sequence, Boolean flowStyle) {
    int size = 10;// default for ArrayList
    if (sequence instanceof List<?>) {
        size = ((List<?>) sequence).size();
    }
    List<Node> value = new ArrayList<Node>(size);
    SequenceNode node = new SequenceNode(tag, value, flowStyle);
    representedObjects.put(objectToRepresent, node);
    boolean bestStyle = true;
    for (Object item : sequence) {
        Node nodeItem = representData(item);
        if (!((nodeItem instanceof ScalarNode && ((ScalarNode) nodeItem).getStyle() == null))) {
            bestStyle = false;
        }
        value.add(nodeItem);
    }
    if (flowStyle == null) {
        if (defaultFlowStyle != FlowStyle.AUTO) {
            node.setFlowStyle(defaultFlowStyle.getStyleBoolean());
        } else {
            node.setFlowStyle(bestStyle);
        }
    }
    return node;
}
 
Example #7
Source File: LongUriTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
/**
 * Try loading a tag with a very long escaped URI section (over 256 bytes'
 * worth).
 */
public void testLongURIEscape() {
    Yaml loader = new Yaml();
    // Create a long escaped string by exponential growth...
    String longEscURI = "%41"; // capital A...
    for (int i = 0; i < 10; ++i) {
        longEscURI = longEscURI + longEscURI;
    }
    assertEquals(1024 * 3, longEscURI.length());
    String yaml = "!" + longEscURI + " www";

    Node node = loader.compose(new StringReader(yaml));
    ScalarNode scalar = (ScalarNode) node;
    String etalon = "!";
    for (int i = 0; i < 1024; i++) {
        etalon += "A";
    }
    assertEquals(1025, etalon.length());
    assertEquals(etalon, scalar.getTag().toString());
}
 
Example #8
Source File: Yaml.java    From java with Apache License 2.0 6 votes vote down vote up
@Override
protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
  MappingNode node = super.representJavaBean(properties, javaBean);
  // Always set the tag to MAP so that SnakeYaml doesn't print out the class name as a tag.
  node.setTag(Tag.MAP);
  // Sort the output of our map so that we put certain keys, such as apiVersion, first.
  Collections.sort(
      node.getValue(),
      new Comparator<NodeTuple>() {
        @Override
        public int compare(NodeTuple a, NodeTuple b) {
          String nameA = ((ScalarNode) a.getKeyNode()).getValue();
          String nameB = ((ScalarNode) b.getKeyNode()).getValue();
          int intCompare =
              Integer.compare(getPropertyPosition(nameA), getPropertyPosition(nameB));
          if (intCompare != 0) {
            return intCompare;
          } else {
            return nameA.compareTo(nameB);
          }
        }
      });
  return node;
}
 
Example #9
Source File: FragmentComposer.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
@Override
public Node getSingleNode() {
    Node node = super.getSingleNode();
    if (!MappingNode.class.isAssignableFrom(node.getClass())) {
        throw new RuntimeException(
                "Document is not structured as expected.  Root element should be a map!");
    }
    MappingNode root = (MappingNode) node;
    for (NodeTuple tuple : root.getValue()) {
        Node keyNode = tuple.getKeyNode();
        if (ScalarNode.class.isAssignableFrom(keyNode.getClass())) {
            if (((ScalarNode) keyNode).getValue().equals(nodeName)) {
                return tuple.getValueNode();
            }
        }
    }
    throw new RuntimeException("Did not find key \"" + nodeName + "\" in document-level map");
}
 
Example #10
Source File: CompactConstructor.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
protected Object createInstance(ScalarNode node, CompactData data) throws Exception {
    Class<?> clazz = getClassForName(data.getPrefix());
    Class<?>[] args = new Class[data.getArguments().size()];
    for (int i = 0; i < args.length; i++) {
        // assume all the arguments are Strings
        args[i] = String.class;
    }
    java.lang.reflect.Constructor<?> c = clazz.getDeclaredConstructor(args);
    c.setAccessible(true);
    return c.newInstance(data.getArguments().toArray());

}
 
Example #11
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 #12
Source File: Representer.java    From snake-yaml with Apache License 2.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 #13
Source File: SafeConstructor.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public Object construct(Node node) {
    String value = constructScalar((ScalarNode) node).toString().replaceAll("_", "");
    int sign = +1;
    char first = value.charAt(0);
    if (first == '-') {
        sign = -1;
        value = value.substring(1);
    } else if (first == '+') {
        value = value.substring(1);
    }
    int base = 10;
    if ("0".equals(value)) {
        return Integer.valueOf(0);
    } else if (value.startsWith("0b")) {
        value = value.substring(2);
        base = 2;
    } else if (value.startsWith("0x")) {
        value = value.substring(2);
        base = 16;
    } else if (value.startsWith("0")) {
        value = value.substring(1);
        base = 8;
    } else if (value.indexOf(':') != -1) {
        String[] digits = value.split(":");
        int bes = 1;
        int val = 0;
        for (int i = 0, j = digits.length; i < j; i++) {
            val += Long.parseLong(digits[j - i - 1]) * bes;
            bes *= 60;
        }
        return createNumber(sign, String.valueOf(val), 10);
    } else {
        return createNumber(sign, value, 10);
    }
    return createNumber(sign, value, base);
}
 
Example #14
Source File: YamlUtils.java    From yauaa with Apache License 2.0 5 votes vote down vote up
public static List<String> getStringValues(Node sequenceNode, String filename) {
    requireNodeInstanceOf(SequenceNode.class, sequenceNode, filename,
        "The provided node must be a sequence but it is a " + sequenceNode.getNodeId().name());

    List<Node> valueNodes = ((SequenceNode)sequenceNode).getValue();
    List<String> values = new ArrayList<>(valueNodes.size());
    for (Node node: valueNodes) {
        requireNodeInstanceOf(ScalarNode.class, node, filename,
            "The value should be a string but it is a " + node.getNodeId().name());
        values.add(((ScalarNode)node).getValue());
    }
    return values;
}
 
Example #15
Source File: BaseRepresenter.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
protected Node representScalar(Tag tag, String value, Character style) {
    if (style == null) {
        style = this.defaultScalarStyle;
    }
    Node node = new ScalarNode(tag, value, null, null, style);
    return node;
}
 
Example #16
Source File: CompactConstructor.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
protected Object constructCompactFormat(ScalarNode node, CompactData data) {
    try {
        Object obj = createInstance(node, data);
        Map<String, Object> properties = new HashMap<String, Object>(data.getProperties());
        setProperties(obj, properties);
        return obj;
    } catch (Exception e) {
        throw new YAMLException(e);
    }
}
 
Example #17
Source File: DiceExampleTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public Object construct(Node node) {
    String val = (String) constructScalar((ScalarNode) node);
    int position = val.indexOf('d');
    Integer a = new Integer(val.substring(0, position));
    Integer b = new Integer(val.substring(position + 1));
    return new Dice(a, b);
}
 
Example #18
Source File: YamlComposeTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testComposeFromReader() {
    Yaml yaml = new Yaml();
    MappingNode node = (MappingNode) yaml.compose(new StringReader("abc: 56"));
    ScalarNode node1 = (ScalarNode) node.getValue().get(0).getKeyNode();
    assertEquals("abc", node1.getValue());
    ScalarNode node2 = (ScalarNode) node.getValue().get(0).getValueNode();
    assertEquals("56", node2.getValue());
}
 
Example #19
Source File: FlexibleScalarStyleTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public Node representData(Object data) {
    ScalarNode node = (ScalarNode) super.representData(data);
    if (node.getStyle() == null) {
        // if Plain scalar style
        if (node.getValue().length() < 25) {
            return node;
        } else {
            // Folded scalar style
            return new ScalarNode(node.getTag(), node.getValue(), node.getStartMark(),
                    node.getEndMark(), '>');
        }
    } else {
        return node;
    }
}
 
Example #20
Source File: BooleanEnumTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public Object construct(Node node) {
    if (node.getType().equals(BooleanEnum.class)) {
        String val = (String) constructScalar((ScalarNode) node);
        if ("true".equals(val)) {
            return BooleanEnum.TRUE;
        } else if ("false".equals(val)) {
            return BooleanEnum.FALSE;
        } else
            return BooleanEnum.UNKNOWN;
    }
    return super.construct(node);
}
 
Example #21
Source File: BeanConstructor.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
@Override
public Object construct(Node node) {
    ScalarNode snode = (ScalarNode) node;
    if (snode.getValue().length() == 0) {
        return new Bean1();
    } else {
        return new Bean1(new Integer(snode.getValue()));
    }
}
 
Example #22
Source File: SerializerTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testSerializerIsNotOpened2() throws IOException {
    try {
        serializer.serialize(new ScalarNode(new Tag("!foo"), "bar", null, null, (char) 0));
        fail();
    } catch (RuntimeException e) {
        assertEquals("serializer is not opened", e.getMessage());
    }
}
 
Example #23
Source File: AdvancedRepresenterTest.java    From waggle-dance with Apache License 2.0 5 votes vote down vote up
@Test
public void notNullCollectionProperty() {
  bean.setCollectionProperty(ImmutableList.<String>builder().add("1").add("2").build());
  Property property = new MethodProperty(getPropertyDescriptor("collectionProperty"));
  NodeTuple nodeTuple = representer.representJavaBeanProperty(bean, property, bean.getCollectionProperty(), null);
  assertThat(nodeTuple, is(notNullValue()));
  assertThat(nodeTuple.getKeyNode(), is(instanceOf(ScalarNode.class)));
  assertThat(((ScalarNode) nodeTuple.getKeyNode()).getValue(), is("collection-property"));
  assertThat(nodeTuple.getValueNode(), is(instanceOf(SequenceNode.class)));
  assertThat(((SequenceNode) nodeTuple.getValueNode()).getValue().size(), is(2));
  assertThat(((SequenceNode) nodeTuple.getValueNode()).getValue().get(0), is(instanceOf(ScalarNode.class)));
  assertThat(((ScalarNode) ((SequenceNode) nodeTuple.getValueNode()).getValue().get(0)).getValue(), is("1"));
  assertThat(((SequenceNode) nodeTuple.getValueNode()).getValue().get(1), is(instanceOf(ScalarNode.class)));
  assertThat(((ScalarNode) ((SequenceNode) nodeTuple.getValueNode()).getValue().get(1)).getValue(), is("2"));
}
 
Example #24
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 #25
Source File: JsonReference.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns true if the argument can be identified as a JSON reference node.
 * 
 * @param tuple
 * @return true if a reference node
 */
public static boolean isReference(NodeTuple tuple) {
    if (tuple.getKeyNode().getNodeId() == NodeId.scalar) {
        String value = ((ScalarNode) tuple.getKeyNode()).getValue();

        return JsonReference.PROPERTY.equals(value) && tuple.getValueNode().getNodeId() == NodeId.scalar;
    }
    return false;
}
 
Example #26
Source File: SafeConstructor.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
public Object construct(Node node) {
    ScalarNode scalar = (ScalarNode) node;
    try {
        return nf.parse(scalar.getValue());
    } catch (ParseException e) {
        throw new IllegalArgumentException("Unable to parse as Number: "
                + scalar.getValue());
    }
}
 
Example #27
Source File: SafeConstructor.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
public Object construct(Node node) {
    String value = constructScalar((ScalarNode) node).toString().replaceAll("_", "");
    int sign = +1;
    char first = value.charAt(0);
    if (first == '-') {
        sign = -1;
        value = value.substring(1);
    } else if (first == '+') {
        value = value.substring(1);
    }
    int base = 10;
    if ("0".equals(value)) {
        return Integer.valueOf(0);
    } else if (value.startsWith("0b")) {
        value = value.substring(2);
        base = 2;
    } else if (value.startsWith("0x")) {
        value = value.substring(2);
        base = 16;
    } else if (value.startsWith("0")) {
        value = value.substring(1);
        base = 8;
    } else if (value.indexOf(':') != -1) {
        String[] digits = value.split(":");
        int bes = 1;
        int val = 0;
        for (int i = 0, j = digits.length; i < j; i++) {
            val += (Long.parseLong(digits[(j - i) - 1]) * bes);
            bes *= 60;
        }
        return createNumber(sign, String.valueOf(val), 10);
    } else {
        return createNumber(sign, value, 10);
    }
    return createNumber(sign, value, base);
}
 
Example #28
Source File: YamlStringSerializerImpl.java    From Diorite with MIT License 5 votes vote down vote up
@Override
public Object construct(Node node)
{
    while (node instanceof AnchorNode)
    {
        node = ((AnchorNode) node).getRealNode();
    }
    if (node instanceof ScalarNode)
    {
        return this.stringSerializer.deserialize(((ScalarNode) node).getValue());
    }
    throw new RuntimeException("Can't deserialize simple string from yaml node: " + node);
}
 
Example #29
Source File: BaseRepresenter.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
protected Node representScalar(Tag tag, String value, Character style) {
    if (style == null) {
        style = this.defaultScalarStyle;
    }
    Node node = new ScalarNode(tag, value, null, null, style);
    return node;
}
 
Example #30
Source File: JsonReferenceFactory.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 5 votes vote down vote up
public JsonReference create(ScalarNode node) {
    if (node == null) {
        return new JsonReference(null, null, false, false, false, node);
    }

    return doCreate(node.getValue(), node);
}