Java Code Examples for org.yaml.snakeyaml.nodes.ScalarNode

The following examples show how to use org.yaml.snakeyaml.nodes.ScalarNode. These examples are extracted from open source projects. 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 Project: snake-yaml   Source File: FragmentComposer.java    License: 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 2
Source Project: AuTe-Framework   Source File: AutotesterAnchorGenerator.java    License: 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 3
Source Project: onedev   Source File: XmlBuildSpecMigrator.java    License: 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 4
Source Project: onedev   Source File: XmlBuildSpecMigrator.java    License: 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 Project: java   Source File: Yaml.java    License: 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 6
Source Project: orion.server   Source File: BaseRepresenter.java    License: 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 Project: orion.server   Source File: BaseRepresenter.java    License: 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 8
Source Project: snake-yaml   Source File: SafeConstructor.java    License: 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 9
Source Project: snake-yaml   Source File: LongUriTest.java    License: 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 10
Source Project: onedev   Source File: Representer.java    License: 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 11
Source Project: onedev   Source File: Representer.java    License: 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 12
private static Node findNode(MappingNode root, List<String> paths) {
    if (paths.isEmpty())
        return root;

    String path = paths.get(0);
    if (path.startsWith("/")) {
        path = path.substring(1, path.length());
    }

    final List<String> next = paths.subList(1, paths.size());
    // ~1 is use to escape /
    if (path.contains("~1")) {
        path = path.replaceAll("~1", "/");
    }

    for (NodeTuple child : root.getValue()) {
        if (child.getKeyNode() instanceof ScalarNode) {
            ScalarNode scalar = (ScalarNode) child.getKeyNode();

            if (scalar.getValue().equals(path)) {
                return findNode(child, next);
            }
        }
    }

    return root;
}
 
Example 13
Source Project: onedev   Source File: XmlBuildSpecMigrator.java    License: MIT License 5 votes vote down vote up
private static Node migrateChoiceProvider(Element choiceProviderElement) {
	List<NodeTuple> tuples = new ArrayList<>();
	String classTag = getClassTag(choiceProviderElement.attributeValue("class"));

	Element scriptNameElement = choiceProviderElement.element("scriptName");
	if (scriptNameElement != null) {
		tuples.add(new NodeTuple(
				new ScalarNode(Tag.STR, "scriptName"), 
				new ScalarNode(Tag.STR, scriptNameElement.getText().trim())));
	}
	Element choicesElement = choiceProviderElement.element("choices");
	if (choicesElement != null) {
		List<Node> choiceNodes = new ArrayList<>();
		for (Element choiceElement: choicesElement.elements()) {
			List<NodeTuple> choiceTuples = new ArrayList<>();
			choiceTuples.add(new NodeTuple(
					new ScalarNode(Tag.STR, "value"), 
					new ScalarNode(Tag.STR, choiceElement.elementText("value").trim())));
			choiceTuples.add(new NodeTuple(
					new ScalarNode(Tag.STR, "color"), 
					new ScalarNode(Tag.STR, choiceElement.elementText("color").trim())));
			choiceNodes.add(new MappingNode(Tag.MAP, choiceTuples, FlowStyle.BLOCK));
		}
		tuples.add(new NodeTuple(
				new ScalarNode(Tag.STR, "choices"), 
				new SequenceNode(Tag.SEQ, choiceNodes, FlowStyle.BLOCK)));
	}
	
	return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
 
Example 14
Source Project: onedev   Source File: XmlBuildSpecMigrator.java    License: MIT License 5 votes vote down vote up
private static Node migrateShowCondition(Element showConditionElement) {
	List<NodeTuple> tuples = new ArrayList<>();
	tuples.add(new NodeTuple(
			new ScalarNode(Tag.STR, "inputName"), 
			new ScalarNode(Tag.STR, showConditionElement.elementText("inputName").trim())));
	tuples.add(new NodeTuple(
			new ScalarNode(Tag.STR, "valueMatcher"), 
			migrateValueMatcher(showConditionElement.element("valueMatcher"))));
	return new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK);
}
 
Example 15
Source Project: onedev   Source File: XmlBuildSpecMigrator.java    License: MIT License 5 votes vote down vote up
private static Node migrateCache(Element cacheElement) {
	List<NodeTuple> tuples = new ArrayList<>();
	tuples.add(new NodeTuple(
			new ScalarNode(Tag.STR, "key"), 
			new ScalarNode(Tag.STR, cacheElement.elementText("key").trim())));
	tuples.add(new NodeTuple(
			new ScalarNode(Tag.STR, "path"), 
			new ScalarNode(Tag.STR, cacheElement.elementText("path").trim())));
	return new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK);
}
 
Example 16
Source Project: onedev   Source File: XmlBuildSpecMigrator.java    License: MIT License 5 votes vote down vote up
private static Node migrateTrigger(Element triggerElement) {
	List<NodeTuple> tuples = new ArrayList<>();
	String classTag = getClassTag(triggerElement.getName());

	List<Node> paramSupplyNodes = migrateParamSupplies(triggerElement.element("params").elements());
	if (!paramSupplyNodes.isEmpty()) {
		tuples.add(new NodeTuple(
				new ScalarNode(Tag.STR, "params"), 
				new SequenceNode(Tag.SEQ, paramSupplyNodes, FlowStyle.BLOCK)));
	}
	
	Element branchesElement = triggerElement.element("branches");
	if (branchesElement != null) {
		tuples.add(new NodeTuple(
				new ScalarNode(Tag.STR, "branches"), 
				new ScalarNode(Tag.STR, branchesElement.getText().trim())));
	}
	
	Element pathsElement = triggerElement.element("paths");
	if (pathsElement != null) {
		tuples.add(new NodeTuple(
				new ScalarNode(Tag.STR, "paths"), 
				new ScalarNode(Tag.STR, pathsElement.getText().trim())));
	}
	
	Element tagsElement = triggerElement.element("tags");
	if (tagsElement != null) {
		tuples.add(new NodeTuple(
				new ScalarNode(Tag.STR, "tags"), 
				new ScalarNode(Tag.STR, tagsElement.getText().trim())));
	}
	
	return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
 
Example 17
Source Project: onedev   Source File: XmlBuildSpecMigrator.java    License: MIT License 5 votes vote down vote up
private static Node migrateReport(Element reportElement) {
	List<NodeTuple> tuples = new ArrayList<>();
	String classTag = getClassTag(reportElement.getName());
	tuples.add(new NodeTuple(
			new ScalarNode(Tag.STR, "filePatterns"), 
			new ScalarNode(Tag.STR, reportElement.elementText("filePatterns").trim())));
	tuples.add(new NodeTuple(
			new ScalarNode(Tag.STR, "reportName"), 
			new ScalarNode(Tag.STR, reportElement.elementText("reportName").trim())));
	tuples.add(new NodeTuple(
			new ScalarNode(Tag.STR, "startPage"), 
			new ScalarNode(Tag.STR, reportElement.elementText("startPage").trim())));
	return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
 
Example 18
Source Project: APICloud-Studio   Source File: BundleCacher.java    License: 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 19
Source Project: APICloud-Studio   Source File: BundleCacher.java    License: 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 20
Source Project: onedev   Source File: XmlBuildSpecMigrator.java    License: MIT License 5 votes vote down vote up
private static List<Node> migrateFieldSupplies(List<Element> fieldSupplyElements) {
	List<Node> fieldSupplyNodes = new ArrayList<>();
	for (Element fieldSupplyElement: fieldSupplyElements) {
		List<NodeTuple> tuples = new ArrayList<>();
		tuples.add(new NodeTuple(
				new ScalarNode(Tag.STR, "name"), 
				new ScalarNode(Tag.STR, fieldSupplyElement.elementText("name").trim())));
		tuples.add(new NodeTuple(
				new ScalarNode(Tag.STR, "secret"), 
				new ScalarNode(Tag.STR, fieldSupplyElement.elementText("secret").trim())));
		
		Element valueProviderElement = fieldSupplyElement.element("valueProvider");
		String classTag = getClassTag(valueProviderElement.attributeValue("class"));
		List<NodeTuple> valueProviderTuples = new ArrayList<>();
		Element scriptNameElement = valueProviderElement.element("scriptName");
		if (scriptNameElement != null) {
			valueProviderTuples.add(new NodeTuple(
					new ScalarNode(Tag.STR, "scriptName"), 
					new ScalarNode(Tag.STR, scriptNameElement.getText().trim())));
		}
		Element valueElement = valueProviderElement.element("value");
		if (valueElement != null) {
			List<Node> valueItemNodes = new ArrayList<>();
			for (Element valueItemElement: valueElement.elements()) 
				valueItemNodes.add(new ScalarNode(Tag.STR, valueItemElement.getText().trim()));
			valueProviderTuples.add(new NodeTuple(
					new ScalarNode(Tag.STR, "value"), 
					new SequenceNode(Tag.SEQ, valueItemNodes, FlowStyle.BLOCK)));
		}
		
		tuples.add(new NodeTuple(
				new ScalarNode(Tag.STR, "valueProvider"), 
				new MappingNode(new Tag(classTag), valueProviderTuples, FlowStyle.BLOCK)));
		fieldSupplyNodes.add(new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK));
	}
	return fieldSupplyNodes;
}
 
Example 21
Source Project: onedev   Source File: VersionedYamlDoc.java    License: MIT License 5 votes vote down vote up
private String getVersion() {
	for (NodeTuple tuple: getValue()) {
		ScalarNode keyNode = (ScalarNode) tuple.getKeyNode();
		if (keyNode.getValue().equals("version")) 
			return ((ScalarNode)tuple.getValueNode()).getValue();
	}
	throw new OneException("Unable to find version");
}
 
Example 22
Source Project: onedev   Source File: VersionedYamlDoc.java    License: MIT License 5 votes vote down vote up
private void removeVersion() {
	for (Iterator<NodeTuple> it = getValue().iterator(); it.hasNext();) {
		ScalarNode keyNode = (ScalarNode) it.next().getKeyNode();
		if (keyNode.getValue().equals("version")) 
			it.remove();
	}
}
 
Example 23
Source Project: sql-layer   Source File: YamlTester.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Object construct(Node node) {
    if(!(node instanceof ScalarNode)) {
        fail("The value of the UTF8Bytes tag must be a scalar");
    }
    try {
        return ((ScalarNode)node).getValue().getBytes("UTF-8");
    }
    catch (UnsupportedEncodingException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 24
Source Project: java   Source File: Yaml.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Object constructObject(Node node) {
  if (node.getType() == IntOrString.class) {
    return constructIntOrString((ScalarNode) node);
  }
  if (node.getType() == byte[].class) {
    return constructByteArray((ScalarNode) node);
  }

  if (node.getType() == org.joda.time.DateTime.class) {
    return constructDateTime((ScalarNode) node);
  }

  return super.constructObject(node);
}
 
Example 25
Source Project: java   Source File: Yaml.java    License: Apache License 2.0 5 votes vote down vote up
private IntOrString constructIntOrString(ScalarNode node) {
  try {
    return new IntOrString(Integer.parseInt(node.getValue()));
  } catch (NumberFormatException err) {
    return new IntOrString(node.getValue());
  }
}
 
Example 26
Source Project: api-compiler   Source File: NodeConverterUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static SequenceNode expectList(YamlReaderHelper config, FieldDescriptor field, Node node) {
  if (isEmpty(node)) {
    return new SequenceNode(Tag.SEQ, ImmutableList.<Node>of(), false);
  } else if (node instanceof ScalarNode) {
    // Allow a singleton as a list.
    return new SequenceNode(Tag.SEQ, ImmutableList.<Node>of(node), false);
  } else if (node instanceof SequenceNode) {
    return (SequenceNode) node;
  } else {
    config.error(node, "Expected a list for field '%s', found '%s'.",
        field.getFullName(), node.getNodeId());
    return new SequenceNode(Tag.SEQ, ImmutableList.<Node>of(), false);
  }
}
 
Example 27
Source Project: java   Source File: Yaml.java    License: Apache License 2.0 5 votes vote down vote up
private Object constructDateTime(ScalarNode node) {
  if (node.getValue() == null || "null".equalsIgnoreCase(node.getValue())) {
    return null;
  } else {
    return new DateTime(node.getValue(), DateTimeZone.UTC);
  }
}
 
Example 28
Source Project: orion.server   Source File: Representer.java    License: 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 29
Source Project: orion.server   Source File: BaseRepresenter.java    License: 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 Project: Diorite   Source File: YamlStringSerializerImpl.java    License: 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);
}