View Javadoc

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