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.issue46;
17  
18  import java.io.File;
19  import java.util.HashMap;
20  import java.util.Map;
21  
22  import junit.framework.TestCase;
23  
24  import org.yaml.snakeyaml.Yaml;
25  import org.yaml.snakeyaml.nodes.Node;
26  import org.yaml.snakeyaml.nodes.Tag;
27  import org.yaml.snakeyaml.representer.Represent;
28  import org.yaml.snakeyaml.representer.Representer;
29  
30  /**
31   * Issue 46: Dump a java.io.File object
32   */
33  public class FileTest extends TestCase {
34      @SuppressWarnings("unchecked")
35      public void test() {
36          File file = new File("src/test/resources/examples/list-bean-1.yaml");
37          assertTrue(file.exists());
38          Yaml yaml = new Yaml(new MyRepresenter());
39          Map<String, File> map = new HashMap<String, File>();
40          map.put("one", file);
41          String output = yaml.dump(map);
42          // System.out.println(output);
43          assertTrue(output, output.startsWith("{one: !!java.io.File '"));
44          assertTrue(output, output.endsWith("list-bean-1.yaml'}\n"));
45          Map<String, File> parsed = (Map<String, File>) yaml.load(output);
46          File file2 = parsed.get("one");
47          assertTrue(file2.getAbsolutePath(), file2.getAbsolutePath().endsWith("list-bean-1.yaml"));
48      }
49  
50      public class MyRepresenter extends Representer {
51          public MyRepresenter() {
52              this.representers.put(File.class, new FileRepresenter());
53          }
54  
55          public class FileRepresenter implements Represent {
56              public Node representData(Object data) {
57                  File file = (File) data;
58                  Node scalar = representScalar(new Tag("!!java.io.File"), file.getAbsolutePath());
59                  return scalar;
60              }
61          }
62      }
63  }