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; }
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; }
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()); } } }
public static final <T> void addSerializer(ExtensibleRepresenter representer, Class<T> type, Function<T, String> function) { representer.addRepresenter(type, new Represent() { @SuppressWarnings("unchecked") @Override public Node representData(Object data) { String txt = function.apply((T) data); if (txt == null) { return new ScalarNode(Tag.NULL, "null", null, null, null); } return new ScalarNode(Tag.STR, txt, null, null, null); } }); }
@Test public void notNullMapProperty() { bean.setMapProperty(ImmutableMap.<String, Long> builder().put("first", 1L).put("second", 2L).build()); Property property = new MethodProperty(getPropertyDescriptor("mapProperty")); NodeTuple nodeTuple = representer.representJavaBeanProperty(bean, property, bean.getMapProperty(), null); assertThat(nodeTuple, is(notNullValue())); assertThat(nodeTuple.getKeyNode(), is(instanceOf(ScalarNode.class))); assertThat(((ScalarNode) nodeTuple.getKeyNode()).getValue(), is("map-property")); assertThat(nodeTuple.getValueNode(), is(instanceOf(MappingNode.class))); assertThat(((MappingNode) nodeTuple.getValueNode()).getValue().size(), is(2)); assertThat(((MappingNode) nodeTuple.getValueNode()).getValue().get(0), is(instanceOf(NodeTuple.class))); assertThat(((ScalarNode) ((MappingNode) nodeTuple.getValueNode()).getValue().get(0).getKeyNode()).getValue(), is("first")); assertThat(((ScalarNode) ((MappingNode) nodeTuple.getValueNode()).getValue().get(0).getValueNode()).getValue(), is("1")); assertThat(((ScalarNode) ((MappingNode) nodeTuple.getValueNode()).getValue().get(1).getKeyNode()).getValue(), is("second")); assertThat(((ScalarNode) ((MappingNode) nodeTuple.getValueNode()).getValue().get(1).getValueNode()).getValue(), is("2")); }
@Override public Set<String> getKeys() { if (this.node instanceof MappingNode) { List<NodeTuple> tuples = ((MappingNode) this.node).getValue(); Set<String> result = new LinkedHashSet<>(tuples.size()); for (NodeTuple tuple : tuples) { Node keyNode = tuple.getKeyNode(); if (keyNode instanceof ScalarNode) { result.add(((ScalarNode) keyNode).getValue()); } } return result; } return Collections.emptySet(); }
@Nullable private Node getNode(MappingNode node, String key, boolean remove) { for (Iterator<NodeTuple> iterator = node.getValue().iterator(); iterator.hasNext(); ) { NodeTuple tuple = iterator.next(); Node keyNode = tuple.getKeyNode(); if (! (keyNode instanceof ScalarNode)) { return null; } if (key.equals(((ScalarNode) keyNode).getValue())) { if (remove) { iterator.remove(); } return tuple.getValueNode(); } } return null; }
protected Node composeScalarNode(String anchor) { ScalarEvent ev = (ScalarEvent) parser.getEvent(); String tag = ev.getTag(); boolean resolved = false; Tag nodeTag; if (tag == null || tag.equals("!")) { nodeTag = resolver.resolve(NodeId.scalar, ev.getValue(), ev.getImplicit() .canOmitTagInPlainScalar()); resolved = true; } else { nodeTag = new Tag(tag); } Node node = new ScalarNode(nodeTag, resolved, ev.getValue(), ev.getStartMark(), ev.getEndMark(), ev.getStyle()); if (anchor != null) { anchors.put(anchor, node); } return node; }
/** * 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()); }
@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"); }
private static Node getNode(final MappingNode node, final String key, final boolean remove) { for (final Iterator<NodeTuple> it = node.getValue().iterator(); it.hasNext(); ) { final NodeTuple nodeTuple = it.next(); final Node keyNode = nodeTuple.getKeyNode(); if (keyNode instanceof ScalarNode) { if (key.equals(((ScalarNode) keyNode).getValue())) { if (remove) { it.remove(); } return nodeTuple.getValueNode(); } } } return null; }
protected Node composeScalarNode(String anchor) { ScalarEvent ev = (ScalarEvent) parser.getEvent(); String tag = ev.getTag(); boolean resolved = false; Tag nodeTag; if (tag == null || tag.equals("!")) { nodeTag = resolver.resolve(NodeId.scalar, ev.getValue(), ev.getImplicit().canOmitTagInPlainScalar()); resolved = true; } else { nodeTag = new Tag(tag); } Node node = new ScalarNode(nodeTag, resolved, ev.getValue(), ev.getStartMark(), ev.getEndMark(), ev.getStyle()); if (anchor != null) { anchors.put(anchor, node); } return node; }
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 yamlConstructors.get(Tag.FLOAT).construct(node); } else { throw new IllegalArgumentException( "Unable to parse as Number: " + scalar.getValue()); } } }
@Override public Object construct(Node node) { if(!(node instanceof MappingNode)) { fail("The value of the !select-engine tag must be a map" + "\nGot: " + node); } String matchingKey = null; Object result = null; for(NodeTuple tuple : ((MappingNode)node).getValue()) { Node keyNode = tuple.getKeyNode(); if(!(keyNode instanceof ScalarNode)) { fail("The key in a !select-engine map must be a scalar" + "\nGot: " + constructObject(keyNode)); } String key = ((ScalarNode)keyNode).getValue(); if(IT_ENGINE.equals(key) || (matchingKey == null && ALL_ENGINE.equals(key))) { matchingKey = key; result = constructObject(tuple.getValueNode()); } } if(matchingKey != null) { LOG.debug("Select engine: '{}' => '{}'", matchingKey, result); return result; } else { LOG.debug("Select engine: no match"); return null; } }
private void validateKeys(MappingNode node) { Map<String, Long> keyCounts = node.getValue().stream() .map(NodeTuple::getKeyNode) .filter(n -> n instanceof ScalarNode) .map(ScalarNode.class::cast) .filter(n -> !"!include".equals(n.getTag().getValue())) // exclude !include tag .collect(Collectors.groupingBy(ScalarNode::getValue, Collectors.counting())); List<String> duplicatedKeys = keyCounts.entrySet().stream() .filter(it -> it.getValue() > 1) .map(Map.Entry<String, Long>::getKey) .collect(Collectors.toList()); if (!duplicatedKeys.isEmpty()) { throw new DuplicateKeyYAMLException(duplicatedKeys); } }
@Override public Object construct(final Node node) { if (!(node instanceof ScalarNode)) { throw new YAMLException(format("Only strings must be tagged as %s, this is %s", PLANOUT_TAG, node.getClass().getSimpleName())); } final Object value = constructScalar((ScalarNode)node); if (value == null) { return null; } if (!(value instanceof String)) { throw new YAMLException(format("Only strings must be tagged as %s, this is %s", PLANOUT_TAG, value.getClass())); } try { return PlanoutDSLCompiler.dsl_to_json((String)value); } catch (ValidationException e) { throw new YAMLException(format("Failed to compile PlanOut DSL (annotated with %s)", PLANOUT_TAG), e); } }
private Node composeScalarNode(String anchor) { ScalarEvent ev = (ScalarEvent) parser.getEvent(); String tag = ev.getTag(); boolean resolved = false; Tag nodeTag; if (tag == null || tag.equals("!")) { nodeTag = resolver.resolve(NodeId.scalar, ev.getValue(), ev.getImplicit() .canOmitTagInPlainScalar()); resolved = true; } else { nodeTag = new Tag(tag); } Node node = new ScalarNode(nodeTag, resolved, ev.getValue(), ev.getStartMark(), ev.getEndMark(), ev.getStyle()); if (anchor != null) { anchors.put(anchor, node); } return node; }
protected Node representSequence(Tag tag, Iterable<? extends Object> 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; }
protected Node representMapping(Tag tag, Map<? extends Object, Object> 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<? extends Object, Object> 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; }
@Test public void SlotRepresentationTest() { Rack rack = rackService.findRack( RACK_1 ); SlotConnectionRepresenter representer = new SlotConnectionRepresenter(); Node node = representer.represent( rack ); System.out.println( "Node :" + node.getTag() + ":" ); assertEquals( SlotConnectionRepresenter.RACK_TAG, node.getTag().toString() ); assertEquals( rack.getName(), ( ( ScalarNode ) node ).getValue() ); Slot slot = rack.getSlots().get( 0 ); Node node1 = representer.represent( slot ); System.out.println( "Node :" + node1.getTag() + ":" ); assertEquals( SlotConnectionRepresenter.SLOT_TAG, node1.getTag().toString() ); assertEquals( rack.getName() + SlotConnectionRepresenter.SLOT_DELIMITER + slot.getNumber(), ( ( ScalarNode ) node1 ).getValue() ); }
@Override public void onScalar(ScalarNode node, TupleType tupleType) { if (schemaTuple != null && node instanceof IncludeResolver.IncludeScalarNode) { final String includeName = ((IncludeResolver.IncludeScalarNode) node).getIncludeName(); if (includeName.endsWith(".json")) { try { @SuppressWarnings("unchecked") final Map<String, Object> json = mapper.readValue(node.getValue(), Map.class); if (json.containsKey("$schema") && !json.containsKey("id")) { json.put("id", protocol + ":/" + includeName); super.onScalar(new ScalarNode(node.getTag(), node.isResolved(), mapper.writeValueAsString(json), node.getStartMark(), node.getEndMark(), node.getStyle()), tupleType); return; } } catch (IOException e) { log.warn("Line {}: Could not parse json file '{}' as schema. Relative $refs inside might not work: {}", node.getStartMark().getLine() + 1, includeName, e.getMessage()); } } } super.onScalar(node, tupleType); }
@Override public void typeCheck(Node node) throws ConfigTypeErrorException { if (!(node instanceof ScalarNode)) { throw new ConfigTypeErrorException(node, String.format("Expected %s, found %s", this.toString(), node.getNodeId())); } String value = YamlUtils.getValue((ScalarNode)node); if (value != null) { if (!value.equalsIgnoreCase("true") && !value.equalsIgnoreCase("false")) { throw new ConfigTypeErrorException(node, String.format("Expected %s, found %s", this.toString(), value)); } } }
@SuppressWarnings("rawtypes") private Object toEnum(Node node) { if (!(node instanceof ScalarNode)) { throw new ConfigTypeErrorException(node, format("Expected %s, found %s", this.toString(), node.getNodeId())); } ScalarNode sNode = (ScalarNode)node; Map<String,Enum> names = enumNames(sNode); String configName = YamlUtils.getValue(sNode); if (names.containsKey(configName)) { return names.get(configName); } Enum value = valueOf(node, configName); if (value == null) { throw new ConfigTypeErrorException(sNode, errorMessage(configName)); } return value; }
protected Node representSequence(final Tag tag, final Iterable<?> sequence, final 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; }
protected Node representMapping(final Tag tag, final Map<?, ?> mapping, final 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; }