1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package examples;
18
19 import java.math.BigDecimal;
20 import java.util.Map;
21 import java.util.regex.Pattern;
22
23 import junit.framework.TestCase;
24
25 import org.yaml.snakeyaml.Yaml;
26 import org.yaml.snakeyaml.constructor.AbstractConstruct;
27 import org.yaml.snakeyaml.constructor.SafeConstructor;
28 import org.yaml.snakeyaml.nodes.Node;
29 import org.yaml.snakeyaml.nodes.ScalarNode;
30 import org.yaml.snakeyaml.nodes.Tag;
31
32
33
34
35
36 public class CustomImplicitResolverTest extends TestCase {
37 private final Tag CUSTOM_TAG = new Tag("!BigDecimalDividedBy100");
38 private final Pattern CUSTOM_PATTERN = Pattern.compile("\\d+%");
39
40 @SuppressWarnings("unchecked")
41 public void testImplicit() {
42 Yaml yaml = new Yaml(new BigConstructor());
43 yaml.addImplicitResolver(CUSTOM_TAG, CUSTOM_PATTERN, "-0123456789");
44 Map<String, Object> obj = (Map<String, Object>) yaml.load("bar: 50%");
45 assertEquals("0.5", obj.get("bar").toString());
46 assertEquals(BigDecimal.class, obj.get("bar").getClass());
47 }
48
49 public void testImplicitFailure() {
50 Yaml yaml = new Yaml(new BigConstructor());
51 yaml.addImplicitResolver(CUSTOM_TAG, Pattern.compile("\\d+%"), "-0123456789");
52 try {
53 yaml.load("bar: !!float 50%");
54 fail("Both implicit and explicit are present.");
55 } catch (NumberFormatException e) {
56 assertEquals("For input string: \"50%\"", e.getMessage());
57 }
58 }
59
60 class BigConstructor extends SafeConstructor {
61 public BigConstructor() {
62 this.yamlConstructors.put(CUSTOM_TAG, new ConstructBig());
63 }
64
65 private class ConstructBig extends AbstractConstruct {
66 public Object construct(Node node) {
67 String val = (String) constructScalar((ScalarNode) node);
68 return new BigDecimal(val.substring(0, val.length() - 1))
69 .divide(new BigDecimal(100));
70 }
71 }
72 }
73 }