View Javadoc

1   /**
2    * Copyright (c) 2008-2012, 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 org.yaml.snakeyaml.issues.issue133;
17  
18  import java.awt.Point;
19  
20  import junit.framework.TestCase;
21  
22  import org.yaml.snakeyaml.Yaml;
23  import org.yaml.snakeyaml.introspector.Property;
24  import org.yaml.snakeyaml.nodes.NodeTuple;
25  import org.yaml.snakeyaml.nodes.Tag;
26  import org.yaml.snakeyaml.representer.Representer;
27  
28  /**
29   * to test http://code.google.com/p/snakeyaml/issues/detail?id=133
30   */
31  public class StackOverflowTest extends TestCase {
32      public void testDumpRecursiveObject() {
33          try {
34              Yaml yaml = new Yaml();
35              // by default it must fail with StackOverflow
36              yaml.dump(new Point());
37              fail("getLocation() is recursive.");
38          } catch (Throwable e) {
39              assertNull("StackOverflow has no message: " + e.getMessage(), e.getMessage());
40          }
41      }
42  
43      /**
44       * Since Point.getLocation() creates a new instance of Point class,
45       * SnakeYAML will fail to dump an instance of Point if 'getLocation()' is
46       * also included.
47       * 
48       * Since Point is not really a JavaBean, we can safely skip the recursive
49       * property when we dump the instance of Point.
50       */
51      private class PointRepresenter extends Representer {
52  
53          @Override
54          protected NodeTuple representJavaBeanProperty(Object javaBean, Property property,
55                  Object propertyValue, Tag customTag) {
56              if (javaBean instanceof Point && "location".equals(property.getName())) {
57                  return null;
58              } else {
59                  return super
60                          .representJavaBeanProperty(javaBean, property, propertyValue, customTag);
61              }
62          }
63      }
64  
65      public void testDump() {
66          Yaml yaml = new Yaml(new PointRepresenter());
67          String output = yaml.dump(new Point());
68          assertEquals("!!java.awt.Point {x: 0, y: 0}\n", output);
69      }
70  }