org.yaml.snakeyaml.events.ScalarEvent Java Examples

The following examples show how to use org.yaml.snakeyaml.events.ScalarEvent. 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: ParserImplTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
public void testGetEvent2() {
    String data = "american:\n  - Boston Red Sox";
    StreamReader reader = new StreamReader(data);
    Parser parser = new ParserImpl(reader);
    Mark dummyMark = new Mark("dummy", 0, 0, 0, "", 0);
    LinkedList<Event> etalonEvents = new LinkedList<Event>();
    etalonEvents.add(new StreamStartEvent(dummyMark, dummyMark));
    etalonEvents.add(new DocumentStartEvent(dummyMark, dummyMark, false, null, null));
    etalonEvents
            .add(new MappingStartEvent(null, null, true, dummyMark, dummyMark, Boolean.TRUE));
    etalonEvents.add(new ScalarEvent(null, null, new ImplicitTuple(true, false), "american",
            dummyMark, dummyMark, (char) 0));
    etalonEvents.add(new SequenceStartEvent(null, null, true, dummyMark, dummyMark,
            Boolean.FALSE));
    etalonEvents.add(new ScalarEvent(null, null, new ImplicitTuple(true, false),
            "Boston Red Sox", dummyMark, dummyMark, (char) 0));
    etalonEvents.add(new SequenceEndEvent(dummyMark, dummyMark));
    etalonEvents.add(new MappingEndEvent(dummyMark, dummyMark));
    etalonEvents.add(new DocumentEndEvent(dummyMark, dummyMark, false));
    etalonEvents.add(new StreamEndEvent(dummyMark, dummyMark));
    check(etalonEvents, parser);
}
 
Example #2
Source File: Emitter.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
private Character chooseScalarStyle() {
    ScalarEvent ev = (ScalarEvent) event;
    if (analysis == null) {
        analysis = analyzeScalar(ev.getValue());
    }
    if (ev.getStyle() != null && ev.getStyle() == '"' || this.canonical) {
        return '"';
    }
    if (ev.getStyle() == null && ev.getImplicit().canOmitTagInPlainScalar()) {
        if (!(simpleKeyContext && (analysis.empty || analysis.multiline))
                && ((flowLevel != 0 && analysis.allowFlowPlain) || (flowLevel == 0 && analysis.allowBlockPlain))) {
            return null;
        }
    }
    if (ev.getStyle() != null && (ev.getStyle() == '|' || ev.getStyle() == '>')) {
        if (flowLevel == 0 && !simpleKeyContext && analysis.allowBlock) {
            return ev.getStyle();
        }
    }
    if (ev.getStyle() == null || ev.getStyle() == '\'') {
        if (analysis.allowSingleQuoted && !(simpleKeyContext && analysis.multiline)) {
            return '\'';
        }
    }
    return '"';
}
 
Example #3
Source File: ParserImplTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
public void testGetEvent() {
    String data = "string: abcd";
    StreamReader reader = new StreamReader(data);
    Parser parser = new ParserImpl(reader);
    Mark dummyMark = new Mark("dummy", 0, 0, 0, "", 0);
    LinkedList<Event> etalonEvents = new LinkedList<Event>();
    etalonEvents.add(new StreamStartEvent(dummyMark, dummyMark));
    etalonEvents.add(new DocumentStartEvent(dummyMark, dummyMark, false, null, null));
    etalonEvents.add(new MappingStartEvent(null, null, true, dummyMark, dummyMark,
            Boolean.FALSE));
    etalonEvents.add(new ScalarEvent(null, null, new ImplicitTuple(true, false), "string",
            dummyMark, dummyMark, (char) 0));
    etalonEvents.add(new ScalarEvent(null, null, new ImplicitTuple(true, false), "abcd",
            dummyMark, dummyMark, (char) 0));
    etalonEvents.add(new MappingEndEvent(dummyMark, dummyMark));
    etalonEvents.add(new DocumentEndEvent(dummyMark, dummyMark, false));
    etalonEvents.add(new StreamEndEvent(dummyMark, dummyMark));
    check(etalonEvents, parser);
}
 
Example #4
Source File: Emitter.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
private Character chooseScalarStyle() {
    ScalarEvent ev = (ScalarEvent) event;
    if (analysis == null) {
        analysis = analyzeScalar(ev.getValue());
    }
    if (ev.getStyle() != null && ev.getStyle() == '"' || this.canonical) {
        return '"';
    }
    if (ev.getStyle() == null && ev.getImplicit().canOmitTagInPlainScalar()) {
        if (!(simpleKeyContext && (analysis.empty || analysis.multiline))
                && ((flowLevel != 0 && analysis.allowFlowPlain) || (flowLevel == 0 && analysis.allowBlockPlain))) {
            return null;
        }
    }
    if (ev.getStyle() != null && (ev.getStyle() == '|' || ev.getStyle() == '>')) {
        if (flowLevel == 0 && !simpleKeyContext && analysis.allowBlock) {
            return ev.getStyle();
        }
    }
    if (ev.getStyle() == null || ev.getStyle() == '\'') {
        if (analysis.allowSingleQuoted && !(simpleKeyContext && analysis.multiline)) {
            return '\'';
        }
    }
    return '"';
}
 
Example #5
Source File: Emitter.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
private void expectNode(boolean root, boolean mapping, boolean simpleKey) throws IOException {
    rootContext = root;
    mappingContext = mapping;
    simpleKeyContext = simpleKey;
    if (event instanceof AliasEvent) {
        expectAlias();
    } else if (event instanceof ScalarEvent || event instanceof CollectionStartEvent) {
        processAnchor("&");
        processTag();
        if (event instanceof ScalarEvent) {
            expectScalar();
        } else if (event instanceof SequenceStartEvent) {
            if (flowLevel != 0 || canonical || ((SequenceStartEvent) event).getFlowStyle()
                    || checkEmptySequence()) {
                expectFlowSequence();
            } else {
                expectBlockSequence();
            }
        } else {// MappingStartEvent
            if (flowLevel != 0 || canonical || ((MappingStartEvent) event).getFlowStyle()
                    || checkEmptyMapping()) {
                expectFlowMapping();
            } else {
                expectBlockMapping();
            }
        }
    } else {
        throw new EmitterException("expected NodeEvent, but got " + event);
    }
}
 
Example #6
Source File: ScalarEventTagTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testDump() {
    Yaml yaml = new Yaml();
    Node intNode = yaml.represent(7);
    assertEquals("tag:yaml.org,2002:int", intNode.getTag().toString());
    // System.out.println(intNode);
    List<Event> intEvents = yaml.serialize(intNode);
    String tag = ((ScalarEvent) intEvents.get(2)).getTag();
    assertEquals("Without the tag emitter would not know how to emit '7'",
            "tag:yaml.org,2002:int", tag);
    //
    Node strNode = yaml.represent("7");
    assertEquals("tag:yaml.org,2002:str", strNode.getTag().toString());
    // System.out.println(strNode);
}
 
Example #7
Source File: ScalarEventTagTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testLoad() {
    Yaml yaml = new Yaml();
    Iterable<Event> parsed = yaml.parse(new StringReader("5"));
    List<Event> events = new ArrayList<Event>(5);
    for (Event event : parsed) {
        events.add(event);
        // System.out.println(event);
    }
    String tag = ((ScalarEvent) events.get(2)).getTag();
    assertNull("The tag should not be specified: " + tag, tag);
}
 
Example #8
Source File: LowLevelApiTest.java    From snake-yaml with 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 #9
Source File: EmitterTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testWriteSupplementaryUnicode() throws IOException {
    DumperOptions options = new DumperOptions();
    String burger = new String(Character.toChars(0x1f354));
    String halfBurger = "\uD83C";
    StringWriter output = new StringWriter();
    Emitter emitter = new Emitter(output, options);

    emitter.emit(new StreamStartEvent(null, null));
    emitter.emit(new DocumentStartEvent(null, null, false, null, null));
    emitter.emit(new ScalarEvent(null, null, new ImplicitTuple(true, false), burger
            + halfBurger, null, null, '"'));
    String expected = "! \"\\U0001f354\\ud83c\"";
    assertEquals(expected, output.toString());
}
 
Example #10
Source File: Emitter.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
private void processScalar() throws IOException {
    ScalarEvent ev = (ScalarEvent) event;
    if (analysis == null) {
        analysis = analyzeScalar(ev.getValue());
    }
    if (style == null) {
        style = chooseScalarStyle();
    }
    boolean split = !simpleKeyContext && splitLines;
    if (style == null) {
        writePlain(analysis.scalar, split);
    } else {
        switch (style) {
        case '"':
            writeDoubleQuoted(analysis.scalar, split);
            break;
        case '\'':
            writeSingleQuoted(analysis.scalar, split);
            break;
        case '>':
            writeFolded(analysis.scalar, split);
            break;
        case '|':
            writeLiteral(analysis.scalar);
            break;
        default:
            throw new YAMLException("Unexpected style: " + style);
        }
    }
    analysis = null;
    style = null;
}
 
Example #11
Source File: Emitter.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
private boolean checkSimpleKey() {
    int length = 0;
    if (event instanceof NodeEvent && ((NodeEvent) event).getAnchor() != null) {
        if (preparedAnchor == null) {
            preparedAnchor = prepareAnchor(((NodeEvent) event).getAnchor());
        }
        length += preparedAnchor.length();
    }
    String tag = null;
    if (event instanceof ScalarEvent) {
        tag = ((ScalarEvent) event).getTag();
    } else if (event instanceof CollectionStartEvent) {
        tag = ((CollectionStartEvent) event).getTag();
    }
    if (tag != null) {
        if (preparedTag == null) {
            preparedTag = prepareTag(tag);
        }
        length += preparedTag.length();
    }
    if (event instanceof ScalarEvent) {
        if (analysis == null) {
            analysis = analyzeScalar(((ScalarEvent) event).getValue());
        }
        length += analysis.scalar.length();
    }
    return length < 128 && (event instanceof AliasEvent
            || (event instanceof ScalarEvent && !analysis.empty && !analysis.multiline)
            || checkEmptySequence() || checkEmptyMapping());
}
 
Example #12
Source File: PyStructureTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
private void compareEvents(List<Event> events1, List<Event> events2, boolean full) {
    assertEquals(events1.size(), events2.size());
    Iterator<Event> iter1 = events1.iterator();
    Iterator<Event> iter2 = events2.iterator();
    while (iter1.hasNext()) {
        Event event1 = iter1.next();
        Event event2 = iter2.next();
        assertEquals(event1.getClass(), event2.getClass());
        if (event1 instanceof AliasEvent && full) {
            assertEquals(((AliasEvent) event1).getAnchor(), ((AliasEvent) event2).getAnchor());
        }
        if (event1 instanceof CollectionStartEvent) {
            String tag1 = ((CollectionStartEvent) event1).getTag();
            String tag2 = ((CollectionStartEvent) event1).getTag();
            if (tag1 != null && !"!".equals(tag1) && tag2 != null && !"!".equals(tag1)) {
                assertEquals(tag1, tag2);
            }
        }
        if (event1 instanceof ScalarEvent) {
            ScalarEvent scalar1 = (ScalarEvent) event1;
            ScalarEvent scalar2 = (ScalarEvent) event2;
            if (scalar1.getImplicit().bothFalse() && scalar2.getImplicit().bothFalse()) {
                assertEquals(scalar1.getTag(), scalar2.getTag());
            }
            assertEquals(scalar1.getValue(), scalar2.getValue());
        }
    }
}
 
Example #13
Source File: Emitter.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private void processScalar() throws IOException {
    ScalarEvent ev = (ScalarEvent) event;
    if (analysis == null) {
        analysis = analyzeScalar(ev.getValue());
    }
    if (style == null) {
        style = chooseScalarStyle();
    }
    // TODO the next line should be removed
    style = options.calculateScalarStyle(analysis, ScalarStyle.createStyle(style)).getChar();
    boolean split = !simpleKeyContext;
    if (style == null) {
        writePlain(analysis.scalar, split);
    } else {
        switch (style) {
        case '"':
            writeDoubleQuoted(analysis.scalar, split);
            break;
        case '\'':
            writeSingleQuoted(analysis.scalar, split);
            break;
        case '>':
            writeFolded(analysis.scalar);
            break;
        case '|':
            writeLiteral(analysis.scalar);
            break;
        default:
            throw new YAMLException("Unexpected style: " + style);
        }
    }
    analysis = null;
    style = null;
}
 
Example #14
Source File: Emitter.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
private boolean checkSimpleKey() {
    int length = 0;
    if (event instanceof NodeEvent && ((NodeEvent) event).getAnchor() != null) {
        if (preparedAnchor == null) {
            preparedAnchor = prepareAnchor(((NodeEvent) event).getAnchor());
        }
        length += preparedAnchor.length();
    }
    String tag = null;
    if (event instanceof ScalarEvent) {
        tag = ((ScalarEvent) event).getTag();
    } else if (event instanceof CollectionStartEvent) {
        tag = ((CollectionStartEvent) event).getTag();
    }
    if (tag != null) {
        if (preparedTag == null) {
            preparedTag = prepareTag(tag);
        }
        length += preparedTag.length();
    }
    if (event instanceof ScalarEvent) {
        if (analysis == null) {
            analysis = analyzeScalar(((ScalarEvent) event).getValue());
        }
        length += analysis.scalar.length();
    }
    return (length < 128 && (event instanceof AliasEvent
            || (event instanceof ScalarEvent && !analysis.empty && !analysis.multiline)
            || checkEmptySequence() || checkEmptyMapping()));
}
 
Example #15
Source File: Emitter.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
private void expectNode(boolean root, boolean mapping, boolean simpleKey) throws IOException {
    rootContext = root;
    mappingContext = mapping;
    simpleKeyContext = simpleKey;
    if (event instanceof AliasEvent) {
        expectAlias();
    } else if (event instanceof ScalarEvent || event instanceof CollectionStartEvent) {
        processAnchor("&");
        processTag();
        if (event instanceof ScalarEvent) {
            expectScalar();
        } else if (event instanceof SequenceStartEvent) {
            if (flowLevel != 0 || canonical || ((SequenceStartEvent) event).getFlowStyle()
                    || checkEmptySequence()) {
                expectFlowSequence();
            } else {
                expectBlockSequence();
            }
        } else {// MappingStartEvent
            if (flowLevel != 0 || canonical || ((MappingStartEvent) event).getFlowStyle()
                    || checkEmptyMapping()) {
                expectFlowMapping();
            } else {
                expectBlockMapping();
            }
        }
    } else {
        throw new EmitterException("expected NodeEvent, but got " + event);
    }
}
 
Example #16
Source File: Emitter.java    From Diorite with MIT License 5 votes vote down vote up
boolean checkSimpleKey()
{
    int length = 0;
    if ((this.event instanceof NodeEvent) && (((NodeEvent) this.event).getAnchor() != null))
    {
        if (this.preparedAnchor == null)
        {
            this.preparedAnchor = prepareAnchor(((NodeEvent) this.event).getAnchor());
        }
        length += this.preparedAnchor.length();
    }
    String tag = null;
    if (this.event instanceof ScalarEvent)
    {
        tag = ((ScalarEvent) this.event).getTag();
    }
    else if (this.event instanceof CollectionStartEvent)
    {
        tag = ((CollectionStartEvent) this.event).getTag();
    }
    if (tag != null)
    {
        if (this.preparedTag == null)
        {
            this.preparedTag = this.prepareTag(tag);
        }
        length += this.preparedTag.length();
    }
    if (this.event instanceof ScalarEvent)
    {
        if (this.analysis == null)
        {
            this.analysis = this.analyzeScalar(((ScalarEvent) this.event).getValue());
        }
        length += this.analysis.scalar.length();
    }
    return (length < SMALL_LENGTH) && ((this.event instanceof AliasEvent) ||
                                       ((this.event instanceof ScalarEvent) && ! ((this.analysis == null) || this.analysis.empty) &&
                                        ! this.analysis.multiline) || this.checkEmptySequence() || this.checkEmptyMapping());
}
 
Example #17
Source File: IndexYamlAbsoluteUrlRewriterSupport.java    From nexus-repository-helm with Eclipse Public License 1.0 5 votes vote down vote up
protected void updateUrls(final InputStream is,
                          final OutputStream os)
{
  try (Reader reader = new InputStreamReader(is);
       Writer writer = new OutputStreamWriter(os)) {
    Yaml yaml = new Yaml();
    Emitter emitter = new Emitter(writer, new DumperOptions());
    boolean rewrite = false;
    for (Event event : yaml.parse(reader)) {
      if (event instanceof ScalarEvent) {
        ScalarEvent scalarEvent = (ScalarEvent) event;
        if (rewrite) {
          event = maybeSetAbsoluteUrlAsRelative(scalarEvent);
        }
        else if (URLS.equals(scalarEvent.getValue())) {
          rewrite = true;
        }
      }
      else if (event instanceof CollectionStartEvent) {
        // NOOP
      }
      else if (event instanceof CollectionEndEvent) {
        rewrite = false;
      }
      emitter.emit(event);
    }
  }
  catch (IOException ex) {
    log.error("Error rewriting urls in index.yaml", ex);
  }
}
 
Example #18
Source File: Serializer.java    From Diorite with MIT License 4 votes vote down vote up
private void serializeNode(Node node, @Nullable Node parent, LinkedList<String> commentPath, boolean mappingScalar) throws IOException
{
    if (node.getNodeId() == NodeId.anchor)
    {
        node = ((AnchorNode) node).getRealNode();
    }
    String tAlias = this.anchors.get(node);
    if (this.serializedNodes.contains(node))
    {
        this.emitter.emit(new AliasEvent(tAlias, null, null));
    }
    else
    {
        this.serializedNodes.add(node);
        switch (node.getNodeId())
        {
            case scalar:
                ScalarNode scalarNode = (ScalarNode) node;
                Tag detectedTag = this.resolver.resolve(NodeId.scalar, scalarNode.getValue(), true);
                Tag defaultTag = this.resolver.resolve(NodeId.scalar, scalarNode.getValue(), false);
                String[] pathNodes = commentPath.toArray(new String[commentPath.size()]);
                String comment;
                if (this.checkCommentsSet(pathNodes))
                {
                    comment = this.comments.getComment(pathNodes);
                }
                else
                {
                    comment = null;
                }
                ImplicitTuple tuple = new ImplicitTupleExtension(node.getTag().equals(detectedTag), node.getTag().equals(defaultTag), comment);
                ScalarEvent event = new ScalarEvent(tAlias, node.getTag().getValue(), tuple, scalarNode.getValue(), null, null, scalarNode.getStyle());
                this.emitter.emit(event);
                break;
            case sequence:
                SequenceNode seqNode = (SequenceNode) node;
                boolean implicitS = node.getTag().equals(this.resolver.resolve(NodeId.sequence, null, true));
                this.emitter.emit(new SequenceStartEvent(tAlias, node.getTag().getValue(), implicitS, null, null, seqNode.getFlowStyle()));
                List<Node> list = seqNode.getValue();
                for (Node item : list)
                {
                    this.serializeNode(item, node, commentPath, false);
                }
                this.emitter.emit(new SequenceEndEvent(null, null));
                break;
            default:// instance of MappingNode
                Tag implicitTag = this.resolver.resolve(NodeId.mapping, null, true);
                boolean implicitM = node.getTag().equals(implicitTag);
                this.emitter.emit(new MappingStartEvent(tAlias, node.getTag().getValue(), implicitM, null, null, ((CollectionNode) node).getFlowStyle()));
                MappingNode mnode = (MappingNode) node;
                List<NodeTuple> map = mnode.getValue();
                for (NodeTuple row : map)
                {
                    Node key = row.getKeyNode();
                    Node value = row.getValueNode();
                    if (key instanceof ScalarNode)
                    {
                        commentPath.add(((ScalarNode) key).getValue());
                    }
                    this.serializeNode(key, mnode, commentPath, true);
                    this.serializeNode(value, mnode, commentPath, false);
                    if (key instanceof ScalarNode)
                    {
                        commentPath.removeLast();
                    }
                }
                this.emitter.emit(new MappingEndEvent(null, null));
        }
    }
}
 
Example #19
Source File: Emitter.java    From Diorite with MIT License 4 votes vote down vote up
void expectNode(boolean root, boolean mapping, boolean simpleKey, @Nullable Integer lastIndent) throws IOException
{
    this.rootContext = root;
    this.mappingContext = mapping;
    this.simpleKeyContext = simpleKey;
    if (this.event instanceof AliasEvent)
    {
        this.expectAlias();
    }
    else if ((this.event instanceof ScalarEvent) || (this.event instanceof CollectionStartEvent))
    {
        this.processAnchor("&");
        this.processTag();
        if (this.event instanceof ScalarEvent)
        {
            this.expectScalar(lastIndent);
        }
        else if (this.event instanceof SequenceStartEvent)
        {
            if ((this.flowLevel != 0) || this.canonical || ((SequenceStartEvent) this.event).getFlowStyle()
                || this.checkEmptySequence())
            {
                this.expectFlowSequence();
            }
            else
            {
                this.expectBlockSequence();
            }
        }
        else
        {// MappingStartEvent
            if ((this.flowLevel != 0) || this.canonical || ((MappingStartEvent) this.event).getFlowStyle() || this.checkEmptyMapping())
            {
                this.expectFlowMapping();
            }
            else
            {
                this.expectBlockMapping();
            }
        }
    }
    else
    {
        throw new EmitterException("expected NodeEvent, but got " + this.event);
    }
}
 
Example #20
Source File: JodaTimeFlowStylesTest.java    From snake-yaml with Apache License 2.0 4 votes vote down vote up
/**
 * @see <a href="http://code.google.com/p/snakeyaml/issues/detail?id=128"></a>
 */
public void testLoadBeanWithBlockFlow() {
    MyBean bean = new MyBean();
    bean.setId("id123");
    DateTime etalon = new DateTime(timestamp, DateTimeZone.UTC);
    bean.setDate(etalon);
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(FlowStyle.BLOCK);
    Yaml dumper = new Yaml(new JodaTimeRepresenter(), options);
    // compare Nodes with flow style AUTO and flow style BLOCK
    Node node1 = dumper.represent(bean);
    DumperOptions options2 = new DumperOptions();
    options2.setDefaultFlowStyle(FlowStyle.AUTO);
    Yaml dumper2 = new Yaml(new JodaTimeRepresenter(), options2);
    Node node2 = dumper2.represent(bean);
    assertEquals(node2.toString(), node1.toString());
    // compare Events with flow style AUTO and flow style BLOCK
    List<Event> events1 = dumper.serialize(node1);
    List<Event> events2 = dumper2.serialize(node2);
    assertEquals(events2.size(), events1.size());
    int i = 0;
    for (Event etalonEvent : events2) {
        assertEquals(etalonEvent, events1.get(i++));
        if (etalonEvent instanceof ScalarEvent) {
            ScalarEvent scalar = (ScalarEvent) etalonEvent;
            if (scalar.getValue().equals("2001-09-09T01:46:40Z")) {
                assertTrue(scalar.getImplicit().canOmitTagInPlainScalar());
                assertFalse(scalar.getImplicit().canOmitTagInNonPlainScalar());
            }
        }
    }
    // Nodes and Events are the same. Only emitter may influence the output.
    String doc1 = dumper.dump(bean);
    // System.out.println(doc1);
    /*
     * 'date' must be used only with the explicit '!!timestamp' tag.
     * Implicit tag will not work because 'date' is the JavaBean property
     * and in this case the empty constructor of the class will be used.
     * Since this constructor does not exist for JodaTime an exception will
     * be thrown.
     */
    assertEquals("!!examples.jodatime.MyBean\ndate: 2001-09-09T01:46:40Z\nid: id123\n", doc1);
    /*
     * provided JodaTimeContructor will be ignored because 'date' is a
     * JavaBean property and its class gets more priority then the implicit
     * '!!timestamp' tag.
     */
    Yaml loader = new Yaml(new JodaTimeImplicitContructor());
    try {
        loader.load(doc1);
    } catch (Exception e) {
        assertTrue(
                "The error must indicate that JodaTime cannot be created from the scalar value.",
                e.getMessage()
                        .contains(
                                "No String constructor found. Exception=org.joda.time.DateTime.<init>(java.lang.String)"));
    }
    // we have to provide a special way to create JodaTime instances from
    // scalars
    Yaml loader2 = new Yaml(new JodaPropertyConstructor());
    MyBean parsed = (MyBean) loader2.load(doc1);
    assertEquals(etalon, parsed.getDate());
}
 
Example #21
Source File: Serializer.java    From snake-yaml with Apache License 2.0 4 votes vote down vote up
private void serializeNode(Node node, Node parent) throws IOException {
    if (node.getNodeId() == NodeId.anchor) {
        node = ((AnchorNode) node).getRealNode();
    }
    String tAlias = this.anchors.get(node);
    if (this.serializedNodes.contains(node)) {
        this.emitter.emit(new AliasEvent(tAlias, null, null));
    } else {
        this.serializedNodes.add(node);
        switch (node.getNodeId()) {
        case scalar:
            ScalarNode scalarNode = (ScalarNode) node;
            Tag detectedTag = this.resolver.resolve(NodeId.scalar, scalarNode.getValue(), true);
            Tag defaultTag = this.resolver.resolve(NodeId.scalar, scalarNode.getValue(), false);
            ImplicitTuple tuple = new ImplicitTuple(node.getTag().equals(detectedTag), node
                    .getTag().equals(defaultTag));
            ScalarEvent event = new ScalarEvent(tAlias, node.getTag().getValue(), tuple,
                    scalarNode.getValue(), null, null, scalarNode.getStyle());
            this.emitter.emit(event);
            break;
        case sequence:
            SequenceNode seqNode = (SequenceNode) node;
            boolean implicitS = node.getTag().equals(this.resolver.resolve(NodeId.sequence,
                    null, true));
            this.emitter.emit(new SequenceStartEvent(tAlias, node.getTag().getValue(),
                    implicitS, null, null, seqNode.getFlowStyle()));
            List<Node> list = seqNode.getValue();
            for (Node item : list) {
                serializeNode(item, node);
            }
            this.emitter.emit(new SequenceEndEvent(null, null));
            break;
        default:// instance of MappingNode
            Tag implicitTag = this.resolver.resolve(NodeId.mapping, null, true);
            boolean implicitM = node.getTag().equals(implicitTag);
            this.emitter.emit(new MappingStartEvent(tAlias, node.getTag().getValue(),
                    implicitM, null, null, ((CollectionNode) node).getFlowStyle()));
            MappingNode mnode = (MappingNode) node;
            List<NodeTuple> map = mnode.getValue();
            for (NodeTuple row : map) {
                Node key = row.getKeyNode();
                Node value = row.getValueNode();
                serializeNode(key, mnode);
                serializeNode(value, mnode);
            }
            this.emitter.emit(new MappingEndEvent(null, null));
        }
    }
}
 
Example #22
Source File: Serializer.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
private void serializeNode(Node node, Node parent) throws IOException {
    if (node.getNodeId() == NodeId.anchor) {
        node = ((AnchorNode) node).getRealNode();
    }
    String tAlias = this.anchors.get(node);
    if (this.serializedNodes.contains(node)) {
        this.emitter.emit(new AliasEvent(tAlias, null, null));
    } else {
        this.serializedNodes.add(node);
        switch (node.getNodeId()) {
        case scalar:
            ScalarNode scalarNode = (ScalarNode) node;
            Tag detectedTag = this.resolver.resolve(NodeId.scalar, scalarNode.getValue(), true);
            Tag defaultTag = this.resolver.resolve(NodeId.scalar, scalarNode.getValue(), false);
            ImplicitTuple tuple = new ImplicitTuple(node.getTag().equals(detectedTag), node
                    .getTag().equals(defaultTag));
            ScalarEvent event = new ScalarEvent(tAlias, node.getTag().getValue(), tuple,
                    scalarNode.getValue(), null, null, scalarNode.getStyle());
            this.emitter.emit(event);
            break;
        case sequence:
            SequenceNode seqNode = (SequenceNode) node;
            boolean implicitS = (node.getTag().equals(this.resolver.resolve(NodeId.sequence,
                    null, true)));
            this.emitter.emit(new SequenceStartEvent(tAlias, node.getTag().getValue(),
                    implicitS, null, null, seqNode.getFlowStyle()));
            int indexCounter = 0;
            List<Node> list = seqNode.getValue();
            for (Node item : list) {
                serializeNode(item, node);
                indexCounter++;
            }
            this.emitter.emit(new SequenceEndEvent(null, null));
            break;
        default:// instance of MappingNode
            Tag implicitTag = this.resolver.resolve(NodeId.mapping, null, true);
            boolean implicitM = (node.getTag().equals(implicitTag));
            this.emitter.emit(new MappingStartEvent(tAlias, node.getTag().getValue(),
                    implicitM, null, null, ((CollectionNode) node).getFlowStyle()));
            MappingNode mnode = (MappingNode) node;
            List<NodeTuple> map = mnode.getValue();
            for (NodeTuple row : map) {
                Node key = row.getKeyNode();
                Node value = row.getValueNode();
                serializeNode(key, mnode);
                serializeNode(value, mnode);
            }
            this.emitter.emit(new MappingEndEvent(null, null));
        }
    }
}
 
Example #23
Source File: ParserImpl.java    From snake-yaml with Apache License 2.0 2 votes vote down vote up
/**
 * <pre>
 * block_mapping     ::= BLOCK-MAPPING_START
 *           ((KEY block_node_or_indentless_sequence?)?
 *           (VALUE block_node_or_indentless_sequence?)?)*
 *           BLOCK-END
 * </pre>
 */
private Event processEmptyScalar(Mark mark) {
    return new ScalarEvent(null, null, new ImplicitTuple(true, false), "", mark, mark, (char) 0);
}
 
Example #24
Source File: ParserImpl.java    From orion.server with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * <pre>
 * block_mapping     ::= BLOCK-MAPPING_START
 *           ((KEY block_node_or_indentless_sequence?)?
 *           (VALUE block_node_or_indentless_sequence?)?)*
 *           BLOCK-END
 * </pre>
 */
private Event processEmptyScalar(Mark mark) {
    return new ScalarEvent(null, null, new ImplicitTuple(true, false), "", mark, mark, (char) 0);
}