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.constructor;
17  
18  import junit.framework.TestCase;
19  
20  import org.yaml.snakeyaml.Yaml;
21  
22  public class FilterClassesConstructorTest extends TestCase {
23  
24      public void testGetClassForName() {
25          Yaml yaml = new Yaml(new FilterConstructor(true));
26          String input = "!!org.yaml.snakeyaml.constructor.FilterClassesConstructorTest$FilteredBean {name: Andrey, number: 543}";
27          try {
28              yaml.load(input);
29              fail("Filter is expected.");
30          } catch (Exception e) {
31              assertTrue(e.getMessage().contains("Filter is applied."));
32          }
33          yaml = new Yaml(new FilterConstructor(false));
34          FilteredBean s = (FilteredBean) yaml.load(input);
35          assertEquals("Andrey", s.getName());
36      }
37  
38      class FilterConstructor extends Constructor {
39          private boolean filter;
40  
41          public FilterConstructor(boolean f) {
42              filter = f;
43          }
44  
45          @Override
46          protected Class<?> getClassForName(String name) throws ClassNotFoundException {
47              if (filter && name.startsWith("org.yaml")) {
48                  throw new RuntimeException("Filter is applied.");
49              }
50              return super.getClassForName(name);
51          }
52      }
53  
54      public static class FilteredBean {
55          private String name;
56          private int number;
57  
58          public String getName() {
59              return name;
60          }
61  
62          public void setName(String name) {
63              this.name = name;
64          }
65  
66          public int getNumber() {
67              return number;
68          }
69  
70          public void setNumber(int number) {
71              this.number = number;
72          }
73      }
74  }