1 /** 2 * Copyright (c) 2008, http://www.snakeyaml.org 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package examples; 17 18 import java.math.BigDecimal; 19 import java.util.regex.Pattern; 20 21 import junit.framework.TestCase; 22 23 import org.yaml.snakeyaml.Yaml; 24 import org.yaml.snakeyaml.constructor.Constructor; 25 import org.yaml.snakeyaml.nodes.Node; 26 import org.yaml.snakeyaml.nodes.NodeId; 27 import org.yaml.snakeyaml.nodes.ScalarNode; 28 29 /** 30 * http://code.google.com/p/snakeyaml/issues/detail?id=75 31 */ 32 public class CustomBeanResolverTest extends TestCase { 33 private final Pattern CUSTOM_PATTERN = Pattern.compile("\\d+%"); 34 35 public void testOnlyBigDecimal() { 36 Yaml yaml = new Yaml(new BigBeanConstructor()); 37 Foo foo = (Foo) yaml.load("bar: 50\nbaz: 35%\nbas: 1250"); 38 assertEquals(50.0, foo.bar); 39 assertEquals("0.35", foo.baz.toString()); 40 assertEquals("1250", foo.bas); 41 } 42 43 public void testPrimitive() { 44 Yaml yaml = new Yaml(new BigBeanConstructor()); 45 Foo foo = (Foo) yaml.load("bar: 50%\nbaz: 35%\nbas: 1250%\nbaw: 35"); 46 assertEquals(0.5, foo.bar); 47 assertEquals("0.35", foo.baz.toString()); 48 assertEquals("1250%", foo.bas); 49 assertEquals("35", foo.baw.toString()); 50 } 51 52 class BigBeanConstructor extends Constructor { 53 public BigBeanConstructor() { 54 super(Foo.class); 55 yamlClassConstructors.put(NodeId.scalar, new ConstructBig()); 56 } 57 58 private class ConstructBig extends ConstructScalar { 59 public Object construct(Node node) { 60 if (node.getType().equals(BigDecimal.class)) { 61 String val = (String) constructScalar((ScalarNode) node); 62 if (CUSTOM_PATTERN.matcher(val).matches()) { 63 return new BigDecimal(val.substring(0, val.length() - 1)) 64 .divide(new BigDecimal(100)); 65 } 66 } else if (node.getType().isAssignableFrom(double.class)) { 67 String val = (String) constructScalar((ScalarNode) node); 68 if (CUSTOM_PATTERN.matcher(val).matches()) { 69 return new Double(val.substring(0, val.length() - 1)) / 100; 70 } 71 } 72 return super.construct(node); 73 } 74 } 75 } 76 77 public static class Foo { 78 public double bar = 0; 79 public BigDecimal baz; 80 public BigDecimal baw; 81 public String bas; 82 } 83 } 84