org.yaml.snakeyaml.nodes.Node Java Examples
The following examples show how to use
org.yaml.snakeyaml.nodes.Node.
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: BaseConstructor.java From onedev with MIT License | 6 votes |
/** * 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 #2
Source File: BaseRepresenter.java From snake-yaml with Apache License 2.0 | 6 votes |
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 #3
Source File: YamlConstructor.java From FastAsyncWorldedit with GNU General Public License v3.0 | 6 votes |
@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 #4
Source File: ValidationUtil.java From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 | 6 votes |
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 #5
Source File: YamlConstructor.java From Kettle with GNU General Public License v3.0 | 6 votes |
@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 #6
Source File: BaseConstructor.java From snake-yaml with Apache License 2.0 | 6 votes |
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 #7
Source File: BaseConstructor.java From onedev with MIT License | 6 votes |
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 #8
Source File: CompactConstructor.java From orion.server with Eclipse Public License 1.0 | 6 votes |
@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 #9
Source File: BaseConstructor.java From onedev with MIT License | 6 votes |
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 #10
Source File: BaseConstructor.java From orion.server with Eclipse Public License 1.0 | 6 votes |
/** * 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
Source File: BaseConstructor.java From orion.server with Eclipse Public License 1.0 | 6 votes |
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 #12
Source File: BaseConstructor.java From orion.server with Eclipse Public License 1.0 | 5 votes |
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 #13
Source File: LowLevelApiTest.java From snake-yaml with Apache License 2.0 | 5 votes |
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 #14
Source File: YamlParameterizedConstructor.java From digdag with Apache License 2.0 | 5 votes |
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 #15
Source File: BundleCacher.java From APICloud-Studio with GNU General Public License v3.0 | 5 votes |
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 #16
Source File: Composer.java From snake-yaml with Apache License 2.0 | 5 votes |
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 #17
Source File: Representer.java From snake-yaml with Apache License 2.0 | 5 votes |
/** * Represent one JavaBean property. * * @param javaBean * - the instance to be represented * @param property * - the property of the instance * @param propertyValue * - value to be represented * @param customTag * - user defined Tag * @return NodeTuple to be used in a MappingNode. Return null to skip the * property */ protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) { ScalarNode nodeKey = (ScalarNode) representData(property.getName()); // the first occurrence of the node must keep the tag boolean hasAlias = this.representedObjects.containsKey(propertyValue); Node nodeValue = representData(propertyValue); if (propertyValue != null && !hasAlias) { NodeId nodeId = nodeValue.getNodeId(); if (customTag == null) { if (nodeId == NodeId.scalar) { if (propertyValue instanceof Enum<?>) { nodeValue.setTag(Tag.STR); } } else { if (nodeId == NodeId.mapping) { if (property.getType() == propertyValue.getClass()) { if (!(propertyValue instanceof Map<?, ?>)) { if (!nodeValue.getTag().equals(Tag.SET)) { nodeValue.setTag(Tag.MAP); } } } } checkGlobalTag(property, nodeValue, propertyValue); } } } return new NodeTuple(nodeKey, nodeValue); }
Example #18
Source File: SkriptYamlConstructor.java From skript-yaml with MIT License | 5 votes |
@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 #19
Source File: YamlDeserializationData.java From Diorite with MIT License | 5 votes |
@Override public <T, C extends Collection<T>> void getAsCollection(String key, Class<T> type, C collection) { Node node = this.getNode(this.node, key); if (node == null) { throw new DeserializationException(type, this, "Can't find valid value for key: " + key); } if (node instanceof SequenceNode) { SequenceNode sequenceNode = (SequenceNode) node; for (Node nodeValue : sequenceNode.getValue()) { collection.add(this.deserializeSpecial(type, nodeValue, null)); } } else if (node instanceof MappingNode) { MappingNode mappingNode = (MappingNode) node; for (NodeTuple tuple : mappingNode.getValue()) { collection.add(this.deserializeSpecial(type, tuple.getValueNode(), null)); } } else { throw new DeserializationException(type, this, "Can't find valid value for key: " + key); } }
Example #20
Source File: SafeConstructor.java From orion.server with Eclipse Public License 1.0 | 5 votes |
public Object construct(Node node) { SequenceNode seqNode = (SequenceNode) node; if (node.isTwoStepsConstruction()) { return createDefaultList((seqNode.getValue()).size()); } else { return constructSequence(seqNode); } }
Example #21
Source File: YamlTester.java From sql-layer with GNU Affero General Public License v3.0 | 5 votes |
@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 #22
Source File: BundleCacher.java From APICloud-Studio with GNU General Public License v3.0 | 5 votes |
public Object construct(Node node) { node.setType(ProjectTemplateElement.class); String path = getPath(node); ProjectTemplateElement be = new ProjectTemplateElement(path); Construct mappingConstruct = yamlClassConstructors.get(NodeId.mapping); mappingConstruct.construct2ndStep(node, be); be.setPath(path); return be; }
Example #23
Source File: YamlUtils.java From configuration-as-code-plugin with MIT License | 5 votes |
/** * Load configuration-as-code model from a snakeyaml Node */ private static Mapping loadFrom(Node node) { final ModelConstructor constructor = new ModelConstructor(); constructor.setComposer(new Composer(null, null) { @Override public Node getSingleNode() { return node; } }); return (Mapping) constructor.getSingleData(Mapping.class); }
Example #24
Source File: ValidationUtil.java From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 | 5 votes |
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 #25
Source File: ContainerDataYaml.java From hadoop-ozone with Apache License 2.0 | 5 votes |
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 #26
Source File: YamlUtils.java From configuration-as-code-plugin with MIT License | 5 votes |
/** * Load configuration-as-code model from a set of Yaml sources, merging documents */ public static Mapping loadFrom(List<YamlSource> sources, ConfigurationContext context) throws ConfiguratorException { if (sources.isEmpty()) return Mapping.EMPTY; final Node merged = merge(sources, context); if (merged == null) { LOGGER.warning("configuration-as-code yaml source returned an empty document."); return Mapping.EMPTY; } return loadFrom(merged); }
Example #27
Source File: BaseRepresenter.java From snake-yaml with Apache License 2.0 | 5 votes |
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 #28
Source File: SafeRepresenter.java From snake-yaml with Apache License 2.0 | 5 votes |
public Node representData(Object data) { String value; if (Boolean.TRUE.equals(data)) { value = "true"; } else { value = "false"; } return representScalar(Tag.BOOL, value); }
Example #29
Source File: VersionedYamlDoc.java From onedev with MIT License | 5 votes |
@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 #30
Source File: BuildSpec.java From onedev with MIT License | 5 votes |
@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); } } } }