Java Code Examples for org.yaml.snakeyaml.Yaml

The following examples show how to use org.yaml.snakeyaml.Yaml. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * From a yaml file
 *
 * @param yamlPolicyFile File location for the chaincode endorsement policy specification.
 * @throws IOException
 * @throws ChaincodeEndorsementPolicyParseException
 * @deprecated use {@link #fromYamlFile(Path)}
 */

public void fromYamlFile(File yamlPolicyFile) throws IOException, ChaincodeEndorsementPolicyParseException {
    final Yaml yaml = new Yaml(new SafeConstructor());
    final Map<?, ?> load = (Map<?, ?>) yaml.load(new FileInputStream(yamlPolicyFile));

    Map<?, ?> mp = (Map<?, ?>) load.get("policy");

    if (null == mp) {
        throw new ChaincodeEndorsementPolicyParseException("The policy file has no policy section");
    }

    IndexedHashMap<String, MSPPrincipal> identities = parseIdentities((Map<?, ?>) load.get("identities"));

    SignaturePolicy sp = parsePolicy(identities, mp);

    policyBytes = Policies.SignaturePolicyEnvelope.newBuilder()
            .setVersion(0)
            .addAllIdentities(identities.values())
            .setRule(sp)
            .build().toByteArray();
}
 
Example 2
Source Project: snake-yaml   Source File: ReadOnlyPropertiesTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testBean2() {
    IncompleteBean bean = new IncompleteBean();
    bean.setName("lunch");
    DumperOptions options = new DumperOptions();
    options.setAllowReadOnlyProperties(true);
    Yaml yaml = new Yaml(options);
    String output = yaml.dumpAsMap(bean);
    // System.out.println(output);
    assertEquals("id: 10\nname: lunch\n", output);
    //
    Yaml loader = new Yaml();
    try {
        loader.loadAs(output, IncompleteBean.class);
        fail("Setter is missing.");
    } catch (YAMLException e) {
        String message = e.getMessage();
        assertTrue(
                message,
                message.contains("Unable to find property 'id' on class: org.yaml.snakeyaml.issues.issue47.IncompleteBean"));
    }
}
 
Example 3
Source Project: jstorm   Source File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
public static Map LoadYaml(String confPath) {
    Map conf = new HashMap();
    
    Yaml yaml = new Yaml();
    
    try {
        InputStream stream = new FileInputStream(confPath);
        
        conf = (Map) yaml.load(stream);
        if (conf == null || conf.isEmpty() == true) {
            throw new RuntimeException("Failed to read config file");
        }
        
    } catch (FileNotFoundException e) {
        System.out.println("No such file " + confPath);
        throw new RuntimeException("No config file");
    } catch (Exception e1) {
        e1.printStackTrace();
        throw new RuntimeException("Failed to read config file");
    }
    
    return conf;
}
 
Example 4
public void testABProperty() {
    SuperSaverAccount supersaver = new SuperSaverAccount();
    GeneralAccount generalAccount = new GeneralAccount();

    CustomerAB_Property customerAB_property = new CustomerAB_Property();
    ArrayList<Account> all = new ArrayList<Account>();
    all.add(supersaver);
    all.add(generalAccount);
    ArrayList<GeneralAccount> general = new ArrayList<GeneralAccount>();
    general.add(generalAccount);
    general.add(supersaver);

    customerAB_property.acc = generalAccount;
    customerAB_property.bGeneral = general;

    Constructor constructor = new Constructor();
    Representer representer = new Representer();

    Yaml yaml = new Yaml(constructor, representer);
    String dump = yaml.dump(customerAB_property);
    // System.out.println(dump);
    CustomerAB_Property parsed = (CustomerAB_Property) yaml.load(dump);
    assertNotNull(parsed);
}
 
Example 5
Source Project: snake-yaml   Source File: TypeSafeListTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testLoadList() {
    String output = Util.getLocalResource("examples/list-bean-1.yaml");
    // System.out.println(output);
    Yaml beanLoader = new Yaml();
    ListBean1 parsed = beanLoader.loadAs(output, ListBean1.class);
    assertNotNull(parsed);
    List<String> list2 = parsed.getChildren();
    assertEquals(2, list2.size());
    assertEquals("aaa", list2.get(0));
    assertEquals("bbb", list2.get(1));
    List<Developer> developers = parsed.getDevelopers();
    assertEquals(2, developers.size());
    assertEquals("Developer must be recognised.", Developer.class, developers.get(0).getClass());
    Developer fred = developers.get(0);
    assertEquals("Fred", fred.getName());
    assertEquals("creator", fred.getRole());
}
 
Example 6
Source Project: NFVO   Source File: CSARParser.java    License: Apache License 2.0 6 votes vote down vote up
private BaseNfvImage getImage(
    VNFPackage vnfPackage,
    VirtualNetworkFunctionDescriptor virtualNetworkFunctionDescriptor,
    String projectId)
    throws NotFoundException, PluginException, VimException, IncompatibleVNFPackage,
        BadRequestException, IOException, AlreadyExistingException, BadFormatException,
        InterruptedException, EntityUnreachableException, ExecutionException {

  Map<String, Object> metadata;

  Yaml yaml = new Yaml();
  metadata = yaml.loadAs(new String(this.vnfMetadata.toByteArray()), Map.class);
  // Get configuration for NFVImage
  vnfPackage = vnfPackageManagement.handleMetadata(metadata, vnfPackage, new HashMap<>());

  return vnfPackageManagement.handleImage(
      vnfPackage, virtualNetworkFunctionDescriptor, metadata, projectId);
}
 
Example 7
Source Project: snake-yaml   Source File: ArrayInGenericCollectionTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testArrayAsListValueWithTypeDespriptor() {
    Yaml yaml2dump = new Yaml();
    yaml2dump.setBeanAccess(BeanAccess.FIELD);
    B data = createB();
    String dump = yaml2dump.dump(data);
    // System.out.println(dump);

    TypeDescription aTypeDescr = new TypeDescription(B.class);
    aTypeDescr.putListPropertyType("meta", String[].class);

    Constructor c = new Constructor();
    c.addTypeDescription(aTypeDescr);
    Yaml yaml2load = new Yaml(c);
    yaml2load.setBeanAccess(BeanAccess.FIELD);

    B loaded = (B) yaml2load.load(dump);

    Assert.assertArrayEquals(data.meta.toArray(), loaded.meta.toArray());
}
 
Example 8
private static Map<String, Object> loadPubspecInfo(@NotNull String yamlContents) {
  final Yaml yaml = new Yaml(new SafeConstructor(), new Representer(), new DumperOptions(), new Resolver() {
    @Override
    protected void addImplicitResolvers() {
      this.addImplicitResolver(Tag.BOOL, BOOL, "yYnNtTfFoO");
      this.addImplicitResolver(Tag.NULL, NULL, "~nN\u0000");
      this.addImplicitResolver(Tag.NULL, EMPTY, null);
      this.addImplicitResolver(new Tag("tag:yaml.org,2002:value"), VALUE, "=");
      this.addImplicitResolver(Tag.MERGE, MERGE, "<");
    }
  });

  try {
    //noinspection unchecked
    return (Map)yaml.load(yamlContents);
  }
  catch (Exception e) {
    return null;
  }
}
 
Example 9
Source Project: thorntail   Source File: ConfigViewFactory.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void loadProjectStages(InputStream inputStream) {
    Yaml yaml = newYaml(System.getenv());
    Iterable<Object> docs = yaml.loadAll(inputStream);

    for (Object item : docs) {
        Map<String, Map<String, String>> doc = (Map<String, Map<String, String>>) item;

        String name = DEFAULT;
        if (doc.get(PROJECT_PREFIX) != null) {
            name = doc.get(PROJECT_PREFIX).get(STAGE);
            doc.remove(PROJECT_PREFIX);
        }
        ConfigNode node = MapConfigNodeFactory.load(doc);

        if (name.equals(DEFAULT)) {
            this.configView.withDefaults(node);
        } else {
            this.configView.register(name, node);
        }
    }
}
 
Example 10
/**
	 * Work with a flexible document definition from a configuration file.
	 *
 	 * @param location
	 * @throws FileNotFoundException 
	 */
	public void add(String location) throws FileNotFoundException {

		// Find the file in question on the filesystem.
		InputStream input = new FileInputStream(new File(location));

		LOG.info("Found flex config: " + location);
		Yaml yaml = new Yaml(new Constructor(GOlrConfig.class));
		GOlrConfig config = (GOlrConfig) yaml.load(input);
		LOG.info("Dumping flex loader YAML: \n" + yaml.dump(config));

		//searchable_extension = config.searchable_extension;
		
		// Plonk them all in to our bookkeeping.
		for( GOlrField field : config.fields ){
			addFieldToBook(config.id, field);
			fields.add(field);
		}
//		for( GOlrDynamicField field : config.dynamic ){
//			addFieldToBook(field);
//			dynamic_fields.add(field);
//		}
	}
 
Example 11
Source Project: skywalking   Source File: ProfileSnapshotExporterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void init() throws IOException {
    CoreModule coreModule = Mockito.spy(CoreModule.class);
    StorageModule storageModule = Mockito.spy(StorageModule.class);
    Whitebox.setInternalState(coreModule, "loadedProvider", moduleProvider);
    Whitebox.setInternalState(storageModule, "loadedProvider", moduleProvider);
    Mockito.when(moduleManager.find(CoreModule.NAME)).thenReturn(coreModule);
    Mockito.when(moduleManager.find(StorageModule.NAME)).thenReturn(storageModule);
    final ProfileTaskQueryService taskQueryService = new ProfileTaskQueryService(moduleManager, coreModuleConfig);

    Mockito.when(moduleProvider.getService(IComponentLibraryCatalogService.class))
           .thenReturn(new ComponentLibraryCatalogService());
    Mockito.when(moduleProvider.getService(ProfileTaskQueryService.class)).thenReturn(taskQueryService);
    Mockito.when(moduleProvider.getService(TraceQueryService.class))
           .thenReturn(new TraceQueryService(moduleManager));

    try (final Reader reader = ResourceUtils.read("profile.yml");) {
        exportedData = new Yaml().loadAs(reader, ExportedData.class);
    }
    Mockito.when(moduleProvider.getService(IProfileThreadSnapshotQueryDAO.class))
           .thenReturn(new ProfileExportSnapshotDAO(exportedData));
    Mockito.when(moduleProvider.getService(ITraceQueryDAO.class)).thenReturn(new ProfileTraceDAO(exportedData));
}
 
Example 12
Source Project: snake-yaml   Source File: SafeRepresenterTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testStyle2() {
    List<Integer> list = new ArrayList<Integer>();
    list.add(new Integer(1));
    list.add(new Integer(1));
    Map<String, Object> map = new LinkedHashMap<String, Object>();
    map.put("age", 5);
    map.put("name", "Ubuntu");
    map.put("list", list);
    DumperOptions options = new DumperOptions();
    options.setDefaultScalarStyle(DumperOptions.ScalarStyle.SINGLE_QUOTED);
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW);
    Yaml yaml = new Yaml(options);
    String output = yaml.dump(map);
    assertEquals("{'age': !!int '5', 'name': 'Ubuntu', 'list': [!!int '1', !!int '1']}\n",
            output);
}
 
Example 13
Source Project: cdep   Source File: TestCDep.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void sqlite() throws Exception {
  CDepYml config = new CDepYml();
  System.out.printf(new Yaml().dump(config));
  File yaml = new File(".test-files/firebase/cdep.yml");
  yaml.getParentFile().mkdirs();
  Files.write("builders: [cmake, cmakeExamples]\n"
          + "dependencies:\n"
          + "- compile: com.github.jomof:sqlite:3.16.2-rev45\n",
      yaml, StandardCharsets.UTF_8);
  String result1 = main("show", "manifest", "-wf", yaml.getParent());
  yaml.delete();
  Files.write(result1, yaml, StandardCharsets.UTF_8);
  System.out.print(result1);
  String result = main("-wf", yaml.getParent());
  System.out.printf(result);
}
 
Example 14
public void testAB_asMapValue() {
    SuperSaverAccount supersaver = new SuperSaverAccount();
    GeneralAccount generalAccount = new GeneralAccount();

    CustomerAB_MapValue customerAB_mapValue = new CustomerAB_MapValue();
    ArrayList<Account> all = new ArrayList<Account>();
    all.add(supersaver);
    all.add(generalAccount);
    Map<String, GeneralAccount> generalMap = new HashMap<String, GeneralAccount>();
    generalMap.put(generalAccount.name, generalAccount);
    generalMap.put(supersaver.name, supersaver);

    customerAB_mapValue.aAll = all;
    customerAB_mapValue.bGeneralMap = generalMap;

    Yaml yaml = new Yaml();
    String dump = yaml.dump(customerAB_mapValue);
    // System.out.println(dump);
    CustomerAB_MapValue parsed = (CustomerAB_MapValue) yaml.load(dump);
    assertNotNull(parsed);
}
 
Example 15
Source Project: justtestlah   Source File: TestDataParserTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPrimitiveTypes() throws IOException {
  TestDataObjectRegistry testDataObjectRegistry = new TestDataObjectRegistry();
  testDataObjectRegistry.register(TestEntity2.class, "testEntity2");
  target.setYamlParser(new Yaml());
  target.setTestDataObjectRegistry(testDataObjectRegistry);
  Pair<Object, String> result =
      target.parse(new ClassPathResource("valid/TestEntity2/test-456.yaml", this.getClass()));
  assertThat(result.getRight()).as("check entity name").isEqualTo("test-456");
  Object element = result.getLeft();
  assertThat(element.getClass()).as("check type of element").isEqualTo(TestEntity2.class);
  TestEntity2 entity2 = (TestEntity2) element;
  assertThat(entity2.getStringValue()).as("check String value").isEqualTo("000");
  assertThat(entity2.getIntValue()).as("check int value").isEqualTo(1);
  assertThat(entity2.getDoubleValue()).as("check double value").isEqualTo(2.0);
  assertThat(entity2.isBooleanValue()).as("check boolean value").isEqualTo(true);
}
 
Example 16
Source Project: sofa-lookout   Source File: DefaultScrapeManager.java    License: Apache License 2.0 6 votes vote down vote up
public List<ScrapeConfig> loadConfigFile(File file) throws FileNotFoundException {
    Preconditions.checkArgument(file.exists() && file.isFile(), "invalid file:" + file.getPath());
    // 该文件是否过期
    Long lastModifiedTime = fileFreshMarker.get(file.getAbsolutePath());
    if (lastModifiedTime != null && file.lastModified() == lastModifiedTime) {
        return Collections.emptyList();
    }
    //read yaml
    Yaml yaml = new Yaml();
    Map<String, Object> configsMap = yaml.load(new FileInputStream(file));
    //resolve
    List<ScrapeConfig> scrapeConfigs = jobConfigResolver.resolve(file.getName(), file.lastModified(), configsMap);
    if (scrapeConfigs != null) {
        fileFreshMarker.put(file.getAbsolutePath(), file.lastModified());
    }
    return scrapeConfigs;
}
 
Example 17
Source Project: snake-yaml   Source File: CalendarTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Daylight Saving Time is not taken into account
 */
public void testDumpDstIgnored() {
    CalendarBean bean = new CalendarBean();
    bean.setName("lunch");
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date(1000000000000L));
    cal.setTimeZone(TimeZone.getTimeZone("GMT-8:00"));
    bean.setCalendar(cal);
    Yaml yaml = new Yaml();
    String output = yaml.dumpAsMap(bean);
    // System.out.println(output);
    assertEquals("calendar: 2001-09-08T17:46:40-8:00\nname: lunch\n", output);
    //
    Yaml loader = new Yaml();
    CalendarBean parsed = loader.loadAs(output, CalendarBean.class);
    assertEquals(bean.getCalendar(), parsed.getCalendar());
}
 
Example 18
Source Project: helix   Source File: Workflow.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Helper function to parse workflow from a generic {@link Reader}
 */
private static Workflow parse(Reader reader) throws Exception {
  Yaml yaml = new Yaml(new Constructor(WorkflowBean.class));
  WorkflowBean wf = (WorkflowBean) yaml.load(reader);
  Builder workflowBuilder = new Builder(wf.name);

  if (wf != null && wf.jobs != null) {
    for (JobBean job : wf.jobs) {
      if (job.name == null) {
        throw new IllegalArgumentException("A job must have a name.");
      }
      JobConfig.Builder jobConfigBuilder = JobConfig.Builder.from(job);
      jobConfigBuilder.setWorkflow(wf.name);
      workflowBuilder.addJob(job.name, jobConfigBuilder);
      if (job.parents != null) {
        for (String parent : job.parents) {
          workflowBuilder.addParentChildDependency(parent, job.name);
        }
      }
    }
  }

  workflowBuilder.setWorkflowConfig(WorkflowConfig.Builder.from(wf).build());

  return workflowBuilder.build();
}
 
Example 19
@Test
public void testSave() throws IOException, ConfigurationException
{
    // save the YAMLConfiguration as a String...
    final StringWriter sw = new StringWriter();
    yamlConfiguration.write(sw);
    final String output = sw.toString();

    // ..and then try parsing it back as using SnakeYAML
    final Map parsed = new Yaml().loadAs(output, Map.class);
    assertEquals(6, parsed.entrySet().size());
    assertEquals("value1", parsed.get("key1"));

    final Map key2 = (Map) parsed.get("key2");
    assertEquals("value23", key2.get("key3"));

    final List<String> key5 =
            (List<String>) ((Map) parsed.get("key4")).get("key5");
    assertEquals(2, key5.size());
    assertEquals("col1", key5.get(0));
    assertEquals("col2", key5.get(1));
}
 
Example 20
Source Project: chronix.spark   Source File: ChronixSparkLoader.java    License: Apache License 2.0 6 votes vote down vote up
public ChronixSparkLoader() {
    Representer representer = new Representer();
    representer.getPropertyUtils().setSkipMissingProperties(true);

    Constructor constructor = new Constructor(YamlConfiguration.class);

    TypeDescription typeDescription = new TypeDescription(ChronixYAMLConfiguration.class);
    typeDescription.putMapPropertyType("configurations", Object.class, ChronixYAMLConfiguration.IndividualConfiguration.class);
    constructor.addTypeDescription(typeDescription);

    Yaml yaml = new Yaml(constructor, representer);
    yaml.setBeanAccess(BeanAccess.FIELD);

    InputStream in = this.getClass().getClassLoader().getResourceAsStream("test_config.yml");
    chronixYAMLConfiguration = yaml.loadAs(in, ChronixYAMLConfiguration.class);
}
 
Example 21
Source Project: snake-yaml   Source File: HumanTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testBeanRing() {
    Human man1 = new Human();
    man1.setName("Man 1");
    Human man2 = new Human();
    man2.setName("Man 2");
    Human man3 = new Human();
    man3.setName("Man 3");
    man1.setBankAccountOwner(man2);
    man2.setBankAccountOwner(man3);
    man3.setBankAccountOwner(man1);
    //
    Yaml yaml = new Yaml();
    String output = yaml.dump(man1);
    // System.out.println(output);
    String etalon = Util.getLocalResource("recursive/beanring-3.yaml");
    assertEquals(etalon, output);
    //
    Human loadedMan1 = (Human) yaml.load(output);
    assertNotNull(loadedMan1);
    assertEquals("Man 1", loadedMan1.getName());
    Human loadedMan2 = loadedMan1.getBankAccountOwner();
    Human loadedMan3 = loadedMan2.getBankAccountOwner();
    assertSame(loadedMan1, loadedMan3.getBankAccountOwner());
}
 
Example 22
Source Project: cloudbreak   Source File: CliProfileReaderService.java    License: Apache License 2.0 6 votes vote down vote up
Map<String, String> read() throws IOException {
    String userHome = System.getProperty("user.home");
    Path cbProfileLocation = Paths.get(userHome, ".dp", "config");
    if (!Files.exists(cbProfileLocation)) {
        LOGGER.info("Could not find cb profile file at location {}, falling back to application.yml", cbProfileLocation);
        return Map.of();
    }

    byte[] encoded = Files.readAllBytes(Paths.get(userHome, ".dp", "config"));
    String profileString = new String(encoded, Charset.defaultCharset());

    Yaml yaml = new Yaml();
    Map<String, Object> profiles = yaml.load(profileString);

    return (Map<String, String>) profiles.get(profile);
}
 
Example 23
Source Project: leaf-snowflake   Source File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
public static Map loadDefinedConf(String confFile)
{
	File file = new File(confFile);
	if ( !file.exists())
	{
		return LoadConf.findAndReadYaml(confFile,true,false);
	}
	Yaml yaml = new Yaml();
	Map ret;
	try {
		ret = (Map) yaml.load(new FileReader(file));
	}
	catch (FileNotFoundException e)
	{
		ret = null;
	}
	if (ret == null)
		ret = new HashMap();
	return ret;

}
 
Example 24
Source Project: multiapps   Source File: YamlUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static Map<String, Object> convertYamlToMap(String yaml) throws ParsingException {
    try {
        return new Yaml(new YamlTaggedObjectsConstructor()).load(yaml);
    } catch (Exception e) {
        throw new ParsingException(e, constructParsingExceptionMessage(e, yaml));
    }
}
 
Example 25
@POST
public String executeCommit(String commands){
    try{
        Commit commit = new Commit();
        commit.modifications = new ArrayList<Modification>();
        Yaml yaml = CloudMLCmds.INSTANCE.getYaml();

        Object obj =  yaml.load(commands);

        if(obj instanceof Modification){
            commit.modifications.add((Modification) obj);
        }
        else if(obj instanceof Collection){
            for(Object sobj : (Collection) obj){
                if(sobj instanceof Modification){
                    commit.modifications.add((Modification)sobj);
                }
                else
                    return "Invalid command format";
            }
        }
        else
            return "Invalid command format";

        coord.process(commit, RestDaemon.commonStub);
        return "Command succeeded without return values";
    }
    catch(Exception e){
        e.printStackTrace();
        return "Sorry, I failed. "+ e;
    }
    
}
 
Example 26
Source Project: rpcx-java   Source File: YamlTest.java    License: Apache License 2.0 5 votes vote down vote up
private String dump() {
    DumperOptions options = new DumperOptions();
    options.setPrettyFlow(true);
    Yaml yaml = new Yaml(options);
    RpcxConfig config = new RpcxConfig();
    config.setConsumerPackage("com.test.consumer");
    config.setFilterPackage("com.test.filter");
    return yaml.dump(config);
}
 
Example 27
Source Project: Jupiter   Source File: PluginBase.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void reloadConfig() {
    this.config = new Config(this.configFile);
    InputStream configStream = this.getResource("config.yml");
    if (configStream != null) {
        DumperOptions dumperOptions = new DumperOptions();
        dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        Yaml yaml = new Yaml(dumperOptions);
        try {
            this.config.setDefault(yaml.loadAs(Utils.readFile(this.configFile), LinkedHashMap.class));
        } catch (IOException e) {
            Server.getInstance().getLogger().logException(e);
        }
    }
}
 
Example 28
Source Project: snake-yaml   Source File: ConstructEmptyBeanTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * global tag is ignored
 */
public void testEmptyBean2() {
    Yaml beanLoader = new Yaml();
    EmptyBean bean = beanLoader.loadAs("!!Bla-bla-bla {}", EmptyBean.class);
    assertNotNull(bean);
    assertNull(bean.getFirstName());
    assertEquals(5, bean.getHatSize());
}
 
Example 29
Source Project: snake-yaml   Source File: DiceExampleTest.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void testImplicitResolverWithNull() {
    Yaml yaml = new Yaml(new DiceConstructor(), new DiceRepresenter());
    // the tag may start with anything
    yaml.addImplicitResolver(new Tag("!dice"), Pattern.compile("\\d+d\\d+"), null);
    // dump
    Map<String, Dice> treasure = new HashMap<String, Dice>();
    treasure.put("treasure", new Dice(10, 20));
    String output = yaml.dump(treasure);
    assertEquals("{treasure: 10d20}\n", output);
    // load
    Object data = yaml.load("{damage: 5d10}");
    Map<String, Dice> map = (Map<String, Dice>) data;
    assertEquals(new Dice(5, 10), map.get("damage"));
}
 
Example 30
Source Project: snake-yaml   Source File: EmitterMultiLineTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testWriteMultiLineLiteralWithStripChomping() {
    String source = "a: 1\nb: |-\n  mama\n  mila\n  ramu\n";
    // System.out.println("Source:\n" + source);
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(FlowStyle.BLOCK);
    Yaml yaml = new Yaml(options);
    @SuppressWarnings("unchecked")
    Map<String, Object> parsed = (Map<String, Object>) yaml.load(source);
    String value = (String) parsed.get("b");
    // System.out.println(value);
    assertEquals("mama\nmila\nramu", value);
    String dumped = yaml.dump(parsed);
    // System.out.println(dumped);
    assertEquals(source, dumped);
}