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

The following examples show how to use org.yaml.snakeyaml.nodes.Node. 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: Kettle   Source File: YamlConstructor.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public Object construct(Node node) {
    if (node.isTwoStepsConstruction()) {
        throw new YAMLException("Unexpected referential mapping structure. Node: " + node);
    }

    Map<?, ?> raw = (Map<?, ?>) super.construct(node);

    if (raw.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) {
        Map<String, Object> typed = new LinkedHashMap<String, Object>(raw.size());
        for (Map.Entry<?, ?> entry : raw.entrySet()) {
            typed.put(entry.getKey().toString(), entry.getValue());
        }

        try {
            return ConfigurationSerialization.deserializeObject(typed);
        } catch (IllegalArgumentException ex) {
            throw new YAMLException("Could not deserialize object", ex);
        }
    }

    return raw;
}
 
Example 2
Source Project: onedev   Source File: BaseConstructor.java    License: MIT License 6 votes vote down vote up
public BaseConstructor() {
    constructedObjects = new HashMap<Node, Object>();
    recursiveObjects = new HashSet<Node>();
    maps2fill = new ArrayList<RecursiveTuple<Map<Object, Object>, RecursiveTuple<Object, Object>>>();
    sets2fill = new ArrayList<RecursiveTuple<Set<Object>, Object>>();
    typeDefinitions = new HashMap<Class<? extends Object>, TypeDescription>();
    typeTags = new HashMap<Tag, Class<? extends Object>>();

    rootTag = null;
    explicitPropertyUtils = false;

    typeDefinitions.put(SortedMap.class, new TypeDescription(SortedMap.class, Tag.OMAP,
            TreeMap.class));
    typeDefinitions.put(SortedSet.class, new TypeDescription(SortedSet.class, Tag.SET,
            TreeSet.class));
}
 
Example 3
Source Project: orion.server   Source File: CompactConstructor.java    License: 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 4
Source Project: snake-yaml   Source File: BaseConstructor.java    License: Apache License 2.0 6 votes vote down vote up
protected void constructSet2ndStep(MappingNode node, Set<Object> set) {
    List<NodeTuple> nodeValue = (List<NodeTuple>) node.getValue();
    for (NodeTuple tuple : nodeValue) {
        Node keyNode = tuple.getKeyNode();
        Object key = constructObject(keyNode);
        if (key != null) {
            try {
                key.hashCode();// check circular dependencies
            } catch (Exception e) {
                throw new ConstructorException("while constructing a Set", node.getStartMark(),
                        "found unacceptable key " + key, tuple.getKeyNode().getStartMark(), e);
            }
        }
        if (keyNode.isTwoStepsConstruction()) {
            /*
             * if keyObject is created it 2 steps we should postpone putting
             * it into the set because it may have different hash after
             * initialization compared to clean just created one. And set of
             * course does not observe value hashCode changes.
             */
            sets2fill.add(0, new RecursiveTuple<Set<Object>, Object>(set, key));
        } else {
            set.add(key);
        }
    }
}
 
Example 5
Source Project: onedev   Source File: BaseConstructor.java    License: MIT License 6 votes vote down vote up
/**
 * Get the constructor to construct the Node. For implicit tags if the
 * runtime class is known a dedicated Construct implementation is used.
 * Otherwise the constructor is chosen by the tag.
 *
 * @param node {@link Node} to construct an instance from
 * @return {@link Construct} implementation for the specified node
 */
protected Construct getConstructor(Node node) {
    if (node.useClassConstructor()) {
        return yamlClassConstructors.get(node.getNodeId());
    } else {
        Construct constructor = yamlConstructors.get(node.getTag());
        if (constructor == null) {
            for (String prefix : yamlMultiConstructors.keySet()) {
                if (node.getTag().startsWith(prefix)) {
                    return yamlMultiConstructors.get(prefix);
                }
            }
            return yamlConstructors.get(null);
        }
        return constructor;
    }
}
 
Example 6
Source Project: onedev   Source File: BaseConstructor.java    License: MIT License 6 votes vote down vote up
protected void constructSet2ndStep(MappingNode node, Set<Object> set) {
    List<NodeTuple> nodeValue = node.getValue();
    for (NodeTuple tuple : nodeValue) {
        Node keyNode = tuple.getKeyNode();
        Object key = constructObject(keyNode);
        if (key != null) {
            try {
                key.hashCode();// check circular dependencies
            } catch (Exception e) {
                throw new ConstructorException("while constructing a Set", node.getStartMark(),
                        "found unacceptable key " + key, tuple.getKeyNode().getStartMark(), e);
            }
        }
        if (keyNode.isTwoStepsConstruction()) {
            /*
             * if keyObject is created it 2 steps we should postpone putting
             * it into the set because it may have different hash after
             * initialization compared to clean just created one. And set of
             * course does not observe value hashCode changes.
             */
            sets2fill.add(0, new RecursiveTuple<Set<Object>, Object>(set, key));
        } else {
            set.add(key);
        }
    }
}
 
Example 7
public static int getLine(JsonNode error, Node yamlTree) {
    String path = getInstancePointer(error);

    if (path == null || path.isEmpty())
        return 1;

    path = path.substring(1, path.length());
    String[] strings = path.split("/");

    if (yamlTree instanceof MappingNode) {
        MappingNode mn = (MappingNode) yamlTree;

        Node findNode = findNode(mn, Arrays.asList(strings));
        if (findNode != null) {
            return findNode.getStartMark().getLine() + 1;
        }
    }

    return 1;
}
 
Example 8
Source Project: orion.server   Source File: BaseConstructor.java    License: Eclipse Public License 1.0 6 votes vote down vote up
protected void constructSet2ndStep(MappingNode node, Set<Object> set) {
    List<NodeTuple> nodeValue = (List<NodeTuple>) node.getValue();
    for (NodeTuple tuple : nodeValue) {
        Node keyNode = tuple.getKeyNode();
        Object key = constructObject(keyNode);
        if (key != null) {
            try {
                key.hashCode();// check circular dependencies
            } catch (Exception e) {
                throw new ConstructorException("while constructing a Set", node.getStartMark(),
                        "found unacceptable key " + key, tuple.getKeyNode().getStartMark(), e);
            }
        }
        if (keyNode.isTwoStepsConstruction()) {
            /*
             * if keyObject is created it 2 steps we should postpone putting
             * it into the set because it may have different hash after
             * initialization compared to clean just created one. And set of
             * course does not observe value hashCode changes.
             */
            sets2fill.add(0, new RecursiveTuple<Set<Object>, Object>(set, key));
        } else {
            set.add(key);
        }
    }
}
 
Example 9
Source Project: snake-yaml   Source File: BaseRepresenter.java    License: Apache License 2.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 10
Source Project: orion.server   Source File: BaseConstructor.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Construct object from the specified Node. Return existing instance if the
 * node is already constructed.
 * 
 * @param node
 *            Node to be constructed
 * @return Java instance
 */
protected Object constructObject(Node node) {
    if (constructedObjects.containsKey(node)) {
        return constructedObjects.get(node);
    }
    if (recursiveObjects.contains(node)) {
        throw new ConstructorException(null, null, "found unconstructable recursive node",
                node.getStartMark());
    }
    recursiveObjects.add(node);
    Construct constructor = getConstructor(node);
    Object data = constructor.construct(node);
    constructedObjects.put(node, data);
    recursiveObjects.remove(node);
    if (node.isTwoStepsConstruction()) {
        constructor.construct2ndStep(node, data);
    }
    return data;
}
 
Example 11
@Override
public Object construct(final Node node) {
    if (node.isTwoStepsConstruction()) {
        throw new YAMLException("Unexpected referential mapping structure. Node: " + node);
    }

    final Map<?, ?> raw = (Map<?, ?>) super.construct(node);

    if (raw.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) {
        final Map<String, Object> typed = new LinkedHashMap<>(raw.size());
        for (final Map.Entry<?, ?> entry : raw.entrySet()) {
            typed.put(entry.getKey().toString(), entry.getValue());
        }

        try {
            return ConfigurationSerialization.deserializeObject(typed);
        } catch (final IllegalArgumentException ex) {
            throw new YAMLException("Could not deserialize object", ex);
        }
    }

    return raw;
}
 
Example 12
Source Project: hadoop-ozone   Source File: ContainerDataYaml.java    License: Apache License 2.0 5 votes vote down vote up
public Object construct(Node node) {
  MappingNode mnode = (MappingNode) node;
  Map<Object, Object> nodes = constructMapping(mnode);

  //Needed this, as TAG.INT type is by default converted to Long.
  long layOutVersion = (long) nodes.get(OzoneConsts.LAYOUTVERSION);
  ChunkLayOutVersion layoutVersion =
      ChunkLayOutVersion.getChunkLayOutVersion((int) layOutVersion);

  long size = (long) nodes.get(OzoneConsts.MAX_SIZE);

  String originPipelineId = (String) nodes.get(
      OzoneConsts.ORIGIN_PIPELINE_ID);
  String originNodeId = (String) nodes.get(OzoneConsts.ORIGIN_NODE_ID);

  //When a new field is added, it needs to be added here.
  KeyValueContainerData kvData = new KeyValueContainerData(
      (long) nodes.get(OzoneConsts.CONTAINER_ID), layoutVersion, size,
      originPipelineId, originNodeId);

  kvData.setContainerDBType((String)nodes.get(
      OzoneConsts.CONTAINER_DB_TYPE));
  kvData.setMetadataPath((String) nodes.get(
      OzoneConsts.METADATA_PATH));
  kvData.setChunksPath((String) nodes.get(OzoneConsts.CHUNKS_PATH));
  Map<String, String> meta = (Map) nodes.get(OzoneConsts.METADATA);
  kvData.setMetadata(meta);
  kvData.setChecksum((String) nodes.get(OzoneConsts.CHECKSUM));
  Long timestamp = (Long) nodes.get(OzoneConsts.DATA_SCAN_TIMESTAMP);
  kvData.setDataScanTimestamp(timestamp);
  String state = (String) nodes.get(OzoneConsts.STATE);
  kvData
      .setState(ContainerProtos.ContainerDataProto.State.valueOf(state));
  return kvData;
}
 
Example 13
Source Project: Diorite   Source File: AbstractRepresent.java    License: MIT License 5 votes vote down vote up
public final Node representString(String data)
{
    Tag tag = Tag.STR;
    Character style = null;
    if (StreamReader.NON_PRINTABLE.matcher(data).find())
    {
        tag = Tag.BINARY;
        char[] binary;
        try
        {
            binary = Base64Coder.encode(data.getBytes("UTF-8"));
        }
        catch (UnsupportedEncodingException e)
        {
            throw new YAMLException(e);
        }
        data = String.valueOf(binary);
        style = '|';
    }
    // if no other scalar style is explicitly set, use literal style for
    // multiline scalars
    if ((this.getDefaultScalarStyle() == null) && Representer.MULTILINE_PATTERN.matcher(data).find())
    {
        style = '|';
    }
    return this.representer.representScalar(tag, data, style);
}
 
Example 14
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(TemplateElement.class);
	String path = getPath(node);
	TemplateElement be = new LazyTemplateElement(path);
	Construct mappingConstruct = yamlClassConstructors.get(NodeId.mapping);
	mappingConstruct.construct2ndStep(node, be);
	be.setPath(path);
	setPrefixTriggers(node, be);
	return be;
}
 
Example 15
Source Project: skript-yaml   Source File: SkriptYamlConstructor.java    License: MIT License 5 votes vote down vote up
@Override
public Object construct(Node node) {
	final Map<Object, Object> values = constructMapping((MappingNode) node);
	String type = (String) values.get("type");
	String data = (String) values.get("data");
	if (type == null || data == null)
		return null;

	return new SkriptClass(type, data).deserialize();
}
 
Example 16
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)
{
	String val = (String) constructScalar((ScalarNode) node);
	// Handle when regexp is using // syntax. Lop the slashes off the ends.
	if (val != null && val.length() > 2 && val.charAt(0) == '/')
	{
		val = val.substring(1, val.length() - 1);
	}
	return RubyRegexp.newRegexp(ScriptingEngine.getInstance().getScriptingContainer().getProvider()
			.getRuntime(), val, RegexpOptions.NULL_OPTIONS);
}
 
Example 17
@Override
protected Class<?> getClassForNode(Node node) {
    try {
        return super.getClassForNode(node);
    } catch (YAMLException e) {
        core.getLogger().log(WARN, "Unknown configuration: {} -> {}", node.getTag().getValue(),
                Throwables.getRootCause(e).getMessage());
        return UnknownConf.class;
    }
}
 
Example 18
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 19
Source Project: Diorite   Source File: Representer.java    License: MIT License 5 votes vote down vote up
private void resetTag(Class<?> type, Node node)
{
    Tag tag = node.getTag();
    if (tag.matches(type))
    {
        if (Enum.class.isAssignableFrom(type))
        {
            node.setTag(Tag.STR);
        }
        else
        {
            node.setTag(Tag.MAP);
        }
    }
}
 
Example 20
Source Project: snake-yaml   Source File: Yaml.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Serialize the representation tree into Events.
 * 
 * @see <a href="http://yaml.org/spec/1.1/#id859333">Processing Overview</a>
 * @param data
 *            representation tree
 * @return Event list
 */
public List<Event> serialize(Node data) {
    SilentEmitter emitter = new SilentEmitter();
    Serializer serializer = new Serializer(emitter, resolver, dumperOptions, null);
    try {
        serializer.open();
        serializer.serialize(data);
        serializer.close();
    } catch (IOException e) {
        throw new YAMLException(e);
    }
    return emitter.getEvents();
}
 
Example 21
Source Project: snake-yaml   Source File: Composer.java    License: Apache License 2.0 5 votes vote down vote up
private Node composeDocument() {
    // Drop the DOCUMENT-START event.
    parser.getEvent();
    // Compose the root node.
    Node node = composeNode(null);
    // Drop the DOCUMENT-END event.
    parser.getEvent();
    this.anchors.clear();
    recursiveNodes.clear();
    return node;
}
 
Example 22
Source Project: snake-yaml   Source File: LowLevelApiTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testLowLevel() {
    List<Object> list = new ArrayList<Object>();
    list.add(1);
    list.add("abc");
    Map<String, String> map = new HashMap<String, String>();
    map.put("name", "Tolstoy");
    map.put("book", "War and People");
    list.add(map);
    Yaml yaml = new Yaml();
    String etalon = yaml.dump(list);
    // System.out.println(etalon);
    //
    Node node = yaml.represent(list);
    // System.out.println(node);
    assertEquals(
            "Representation tree from an object and from its YAML document must be the same.",
            yaml.compose(new StringReader(etalon)).toString(), node.toString());
    //
    List<Event> events = yaml.serialize(node);
    int i = 0;
    for (Event etalonEvent : yaml.parse(new StringReader(etalon))) {
        Event ev1 = events.get(i++);
        assertEquals(etalonEvent.getClass(), ev1.getClass());
        if (etalonEvent instanceof ScalarEvent) {
            ScalarEvent scalar1 = (ScalarEvent) etalonEvent;
            ScalarEvent scalar2 = (ScalarEvent) ev1;
            assertEquals(scalar1.getAnchor(), scalar2.getAnchor());
            assertEquals(scalar1.getValue(), scalar2.getValue());
        }
    }
    assertEquals(i, events.size());
}
 
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
protected Object constructObject(Node node) {
    if (recursing)
        return super.constructObject(node);
    else {
        recursing = true;
        Object o = super.constructObject(node);
        recursing = false;
        return new LinedObject(o, node.getStartMark());
    }
}
 
Example 24
Source Project: thunderstorm   Source File: Homography.java    License: GNU General Public License v3.0 5 votes vote down vote up
public Node representData(Object data) {
    List<Double> sequence = new ArrayList<Double>(9);
    TransformationMatrix mat = (TransformationMatrix) data;
    for (int r = 0; r < 3; r++) {
        for (int c = 0; c < 3; c++) {
            sequence.add(mat.matrix.getEntry(r, c));
        }
    }
    return representSequence(new Tag("!homography"), sequence, null);
}
 
Example 25
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 26
Source Project: snake-yaml   Source File: BaseRepresenter.java    License: 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 27
Source Project: onedev   Source File: VersionedYamlDoc.java    License: MIT License 5 votes vote down vote up
@Override
protected Class<?> getClassForNode(Node node) {
	Class<?> type = node.getType();
	if (type.getAnnotation(Editable.class) != null && !ClassUtils.isConcrete(type)) {
		ImplementationRegistry registry = OneDev.getInstance(ImplementationRegistry.class);
		for (Class<?> implementationClass: registry.getImplementations(node.getType())) {
			String implementationTag = new Tag("!" + implementationClass.getSimpleName()).getValue();
			if (implementationTag.equals(node.getTag().getValue()))
				return implementationClass;
		}
	}
	
	return super.getClassForNode(node);
}
 
Example 28
Source Project: onedev   Source File: BuildSpec.java    License: 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 29
Source Project: digdag   Source File: YamlParameterizedConstructor.java    License: Apache License 2.0 5 votes vote down vote up
private String validateScalar(Node node)
{
    if (node.isTwoStepsConstruction()) {
        throw new TagException("'"+node.getTag()+"' cannot be recursive.",
                node.getStartMark());
    }
    if (!node.getNodeId().equals(NodeId.scalar)) {
        throw new TagException("'"+node.getTag()+"' must be a string.",
                node.getStartMark());
    }
    return ((ScalarNode) node).getValue().toString();
}
 
Example 30
Source Project: deploymentmanager-autogen   Source File: SoyDirectives.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SoyValue applyForJava(SoyValue value, List<SoyValue> args) {
  Preconditions.checkArgument(
      value instanceof PrimitiveData || value instanceof SanitizedContent,
      "|yamlprimitive directive only supports primitive types");
  Node node;
  if (value instanceof BooleanData) {
    node = representer.represent(value.booleanValue());
  } else if (value instanceof FloatData) {
    node = representer.represent(value.floatValue());
  } else if (value instanceof IntegerData) {
    node = representer.represent(value.integerValue());
  } else {
    node = representer.represent(value.coerceToString());
  }
  int indent = args.get(0).integerValue();
  StringWriter writer = new StringWriter();
  Serializer serializer = new Serializer(
      new Emitter(writer, dumperOptions), resolver, dumperOptions, null);
  try {
    serializer.open();
    serializer.serialize(node);
    serializer.close();
    return StringData.forValue(indentLines(writer.toString().trim(), indent));
  } catch (IOException e) {
    // Should not happen.
    throw new RuntimeException(e);
  }
}