org.yaml.snakeyaml.representer.Representer Java Examples

The following examples show how to use org.yaml.snakeyaml.representer.Representer. 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
Source File: ConfigViewFactory.java    From thorntail with Apache License 2.0 7 votes vote down vote up
private static Yaml newYaml(Map<String, String> environment) {
    return new Yaml(new EnvironmentConstructor(environment),
                    new Representer(),
                    new DumperOptions(),
                    new Resolver() {
                        @Override
                        public Tag resolve(NodeId kind, String value, boolean implicit) {
                            if (value != null) {
                                if (value.startsWith("${env.")) {
                                    return new Tag("!env");
                                }
                                if (value.equalsIgnoreCase("on") ||
                                        value.equalsIgnoreCase("off") ||
                                        value.equalsIgnoreCase("yes") ||
                                        value.equalsIgnoreCase("no")) {
                                    return Tag.STR;
                                }
                            }
                            return super.resolve(kind, value, implicit);
                        }
                    });
}
 
Example #2
Source File: YamlDataSetProducer.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
public Yaml createYamlReader() {
    return new Yaml(new Constructor(), new Representer(), new DumperOptions(), new Resolver() {
        @Override
        protected void addImplicitResolvers() {
            // Intentionally left TIMESTAMP as string to let DBUnit deal with the conversion
            addImplicitResolver(Tag.BOOL, BOOL, "yYnNtTfFoO");
            addImplicitResolver(Tag.INT, INT, "-+0123456789");
            addImplicitResolver(Tag.FLOAT, FLOAT, "-+0123456789.");
            addImplicitResolver(Tag.MERGE, MERGE, "<");
            addImplicitResolver(Tag.NULL, NULL, "~nN\0");
            addImplicitResolver(Tag.NULL, EMPTY, null);
            addImplicitResolver(Tag.VALUE, VALUE, "=");
            addImplicitResolver(Tag.YAML, YAML, "!&*");
        }
    });
}
 
Example #3
Source File: DefaultPackageReader.java    From spring-cloud-skipper with Apache License 2.0 6 votes vote down vote up
private PackageMetadata loadPackageMetadata(File file) {
	// The Representer will not try to set the value in the YAML on the
	// Java object if it isn't present on the object
	Representer representer = new Representer();
	representer.getPropertyUtils().setSkipMissingProperties(true);
	Yaml yaml = new Yaml(new Constructor(PackageMetadata.class), representer);
	String fileContents = null;
	try {
		fileContents = FileUtils.readFileToString(file);
	}
	catch (IOException e) {
		throw new SkipperException("Error reading yaml file", e);
	}
	PackageMetadata pkgMetadata = (PackageMetadata) yaml.load(fileContents);
	return pkgMetadata;
}
 
Example #4
Source File: YamlConfiguration.java    From CloudNet with Apache License 2.0 6 votes vote down vote up
@Override
protected Yaml initialValue() {
    Representer representer = new Representer() {
        {
            representers.put(Configuration.class, new Represent() {
                @Override
                public Node representData(Object data) {
                    return represent(((Configuration) data).self);
                }
            });
        }
    };

    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);

    return new Yaml(new Constructor(), representer, options);
}
 
Example #5
Source File: ContainerDataYaml.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Read the yaml content, and return containerData.
 *
 * @throws IOException
 */
public static ContainerData readContainer(InputStream input)
    throws IOException {

  ContainerData containerData;
  PropertyUtils propertyUtils = new PropertyUtils();
  propertyUtils.setBeanAccess(BeanAccess.FIELD);
  propertyUtils.setAllowReadOnlyProperties(true);

  Representer representer = new ContainerDataRepresenter();
  representer.setPropertyUtils(propertyUtils);

  Constructor containerDataConstructor = new ContainerDataConstructor();

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

  containerData = (ContainerData)
      yaml.load(input);

  return containerData;
}
 
Example #6
Source File: Yaml.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Create Yaml instance. It is safe to create a few instances and use them
 * in different Threads.
 * 
 * @param constructor
 *            BaseConstructor to construct incoming documents
 * @param representer
 *            Representer to emit outgoing objects
 * @param dumperOptions
 *            DumperOptions to configure outgoing objects
 * @param resolver
 *            Resolver to detect implicit type
 */
public Yaml(BaseConstructor constructor, Representer representer, DumperOptions dumperOptions,
        Resolver resolver) {
    if (!constructor.isExplicitPropertyUtils()) {
        constructor.setPropertyUtils(representer.getPropertyUtils());
    } else if (!representer.isExplicitPropertyUtils()) {
        representer.setPropertyUtils(constructor.getPropertyUtils());
    }
    this.constructor = constructor;
    representer.setDefaultFlowStyle(dumperOptions.getDefaultFlowStyle());
    representer.setDefaultScalarStyle(dumperOptions.getDefaultScalarStyle());
    representer.getPropertyUtils().setAllowReadOnlyProperties(
            dumperOptions.isAllowReadOnlyProperties());
    representer.setTimeZone(dumperOptions.getTimeZone());
    this.representer = representer;
    this.dumperOptions = dumperOptions;
    this.resolver = resolver;
    this.name = "Yaml:" + System.identityHashCode(this);
}
 
Example #7
Source File: YamlConfigLoader.java    From digdag with Apache License 2.0 6 votes vote down vote up
ObjectNode loadParameterizedInclude(Path path, Config params)
    throws IOException
{
    String content;
    try (InputStream in = Files.newInputStream(path)) {
        content = CharStreams.toString(new InputStreamReader(in, StandardCharsets.UTF_8));
    }

    Yaml yaml = new Yaml(new YamlParameterizedConstructor(), new Representer(), new DumperOptions(), new YamlTagResolver());
    ObjectNode object = normalizeValidateObjectNode(yaml.load(content));

    Path includeDir = path.toAbsolutePath().getParent();
    if (includeDir == null) {
        throw new FileNotFoundException("Loading file named '/' is invalid");
    }

    return new ParameterizeContext(includeDir, params).evalObjectRecursive(object);
}
 
Example #8
Source File: GenerateTestPlanCommand.java    From testgrid with Apache License 2.0 6 votes vote down vote up
/**
 * Build the testgrid.yaml bean by reading the testgrid.yaml portions
 * in each infra/deployment/scenario repositories. The paths to repos
 * are read from the {@link JobConfigFile}.
 *
 * @param jobConfigFile the job-config.yaml bean
 * @return the built testgrid.yaml bean
 */
private TestgridYaml buildTestgridYamlContent(JobConfigFile jobConfigFile) {
    String testgridYamlContent = getTestgridYamlFor(Paths.get(testgridYamlLocation)).trim();

    if (testgridYamlContent.isEmpty()) {
        logger.error("Testgrid.yaml content is empty. job-config.yaml content: " + jobConfigFile.toString());
        throw new TestGridRuntimeException("Could not find testgrid.yaml content. It is either empty or the path "
                + "could not be resolved via the job-config.yaml at: " + this.jobConfigFilePath);
    }

    Representer representer = new Representer();
    representer.getPropertyUtils().setSkipMissingProperties(true); // Skip missing properties in testgrid.yaml
    TestgridYaml testgridYaml = new Yaml(new Constructor(TestgridYaml.class), representer)
            .loadAs(testgridYamlContent, TestgridYaml.class);
    validateDeploymentConfigName(testgridYaml);
    insertJobConfigFilePropertiesTo(testgridYaml, jobConfigFile);

    if (logger.isDebugEnabled()) {
        logger.debug("The testgrid.yaml content for this product build: " + testgridYamlContent);
    }
    return testgridYaml;
}
 
Example #9
Source File: YAMLProcessor.java    From skript-yaml with MIT License 6 votes vote down vote up
public YAMLProcessor(File file, boolean writeDefaults, YAMLFormat format) {
	super(new LinkedHashMap<String, Object>(), writeDefaults);
	this.format = format;

	DumperOptions options = new FancyDumperOptions();
	options.setIndent(4);
	options.setDefaultFlowStyle(format.getStyle());
	options.setTimeZone(TimeZone.getDefault());

	//Representer representer = new SkriptYamlRepresenter();
	Representer representer = SkriptYaml.getInstance().getRepresenter();
	representer.setDefaultFlowStyle(format.getStyle());

	//yaml = new Yaml(new SkriptYamlConstructor(), representer, options);
	yaml = new Yaml(SkriptYaml.getInstance().getConstructor(), representer, options);
	
	this.file = file;
}
 
Example #10
Source File: TestUtils.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
/**
 * Create master key file.
 *
 * @param file                   file instance
 * @param masterKeyConfiguration master key configuration
 */
public static void createMasterKeyFile(File file, MasterKeyConfiguration masterKeyConfiguration) {
    try {
        file.createNewFile();
        file.deleteOnExit();
        FileWriter fileWriter = new FileWriter(file);

        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);

        Representer representer = new Representer();
        representer.addClassTag(MasterKeyConfiguration.class, Tag.MAP);
        Yaml yaml = new Yaml(representer, options);

        yaml.setBeanAccess(BeanAccess.FIELD);
        yaml.dump(masterKeyConfiguration, fileWriter);
    } catch (IOException e) {
        Assert.fail("Failed to create temp password file");
    }
}
 
Example #11
Source File: ChronixSparkLoader.java    From chronix.spark with 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 #12
Source File: YamlFactory.java    From waggle-dance with Apache License 2.0 6 votes vote down vote up
public static Yaml newYaml() {
  PropertyUtils propertyUtils = new AdvancedPropertyUtils();
  propertyUtils.setSkipMissingProperties(true);

  Constructor constructor = new Constructor(Federations.class);
  TypeDescription federationDescription = new TypeDescription(Federations.class);
  federationDescription.putListPropertyType("federatedMetaStores", FederatedMetaStore.class);
  constructor.addTypeDescription(federationDescription);
  constructor.setPropertyUtils(propertyUtils);

  Representer representer = new AdvancedRepresenter();
  representer.setPropertyUtils(new FieldOrderPropertyUtils());
  representer.addClassTag(Federations.class, Tag.MAP);
  representer.addClassTag(AbstractMetaStore.class, Tag.MAP);
  representer.addClassTag(WaggleDanceConfiguration.class, Tag.MAP);
  representer.addClassTag(YamlStorageConfiguration.class, Tag.MAP);
  representer.addClassTag(GraphiteConfiguration.class, Tag.MAP);

  DumperOptions dumperOptions = new DumperOptions();
  dumperOptions.setIndent(2);
  dumperOptions.setDefaultFlowStyle(FlowStyle.BLOCK);

  return new Yaml(constructor, representer, dumperOptions);
}
 
Example #13
Source File: YamlTranslator.java    From mdw with Apache License 2.0 6 votes vote down vote up
protected Representer getRepresenter() {
    return new Representer() {
        @Override
        protected Set<Property> getProperties(Class<? extends Object> type) throws IntrospectionException {
            Set<Property> props = super.getProperties(type);
            Property toRemove = null;
            for (Property prop : props) {
                if (prop.getName().equals("metaClass")) {
                    toRemove = prop;
                    break;
                }
            }
            if (toRemove != null)
                props.remove(toRemove);
            return props;
        }
    };
}
 
Example #14
Source File: ContainerDataYaml.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Given a ContainerType this method returns a Yaml representation of
 * the container properties.
 *
 * @param containerType type of container
 * @return Yamal representation of container properties
 *
 * @throws StorageContainerException if the type is unrecognized
 */
public static Yaml getYamlForContainerType(ContainerType containerType)
    throws StorageContainerException {
  PropertyUtils propertyUtils = new PropertyUtils();
  propertyUtils.setBeanAccess(BeanAccess.FIELD);
  propertyUtils.setAllowReadOnlyProperties(true);

  switch (containerType) {
  case KeyValueContainer:
    Representer representer = new ContainerDataRepresenter();
    representer.setPropertyUtils(propertyUtils);
    representer.addClassTag(
        KeyValueContainerData.class,
        KeyValueContainerData.KEYVALUE_YAML_TAG);

    Constructor keyValueDataConstructor = new ContainerDataConstructor();

    return new Yaml(keyValueDataConstructor, representer);
  default:
    throw new StorageContainerException("Unrecognized container Type " +
        "format " + containerType, ContainerProtos.Result
        .UNKNOWN_CONTAINER_TYPE);
  }
}
 
Example #15
Source File: FlutterUtils.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #16
Source File: FlutterUtils.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #17
Source File: LongTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
public void testLongRepresenter() {
    DumperOptions options = new DumperOptions();
    options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED);
    Representer repr = new Representer();
    repr.addClassTag(Long.class, new Tag("!!java.lang.Long"));
    Yaml yaml = new Yaml(repr, options);

    Foo foo = new Foo();
    String output = yaml.dump(foo);
    // System.out.println(output);
    Foo foo2 = (Foo) yaml.load(output);
    assertEquals(new Long(42L), foo2.getBar());
}
 
Example #18
Source File: SingleQuoteTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
private void checkQuotes(boolean isBlock, String expectation) {
    DumperOptions options = new DumperOptions();
    options.setIndent(4);
    if (isBlock) {
        options.setDefaultFlowStyle(FlowStyle.BLOCK);
    }
    Representer representer = new Representer();

    Yaml yaml = new Yaml(new SafeConstructor(), representer, options);

    LinkedHashMap<String, Object> lvl1 = new LinkedHashMap<String, Object>();
    lvl1.put("steak:cow", "11");
    LinkedHashMap<String, Object> root = new LinkedHashMap<String, Object>();
    root.put("cows", lvl1);
    String output = yaml.dump(root);
    assertEquals(expectation + "\n", output);

    // parse the value back
    @SuppressWarnings("unchecked")
    Map<String, Object> cows = (Map<String, Object>) yaml.load(output);
    @SuppressWarnings("unchecked")
    Map<String, String> cow = (Map<String, String>) cows.get("cows");
    assertEquals("11", cow.get("steak:cow"));
}
 
Example #19
Source File: PropOrderInfluenceWhenAliasedInGenericCollectionTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
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 #20
Source File: RubyTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
public void testEmitWithTags2WithoutTagForParentJavabean() {
    TestObject result = parseObject(Util.getLocalResource("ruby/ruby1.yaml"));
    DumperOptions options = new DumperOptions();
    options.setExplicitStart(true);
    Representer repr = new Representer();
    repr.addClassTag(Sub1.class, new Tag("!ruby/object:Test::Module::Sub1"));
    repr.addClassTag(Sub2.class, new Tag("!ruby/object:Test::Module::Sub2"));
    Yaml yaml2 = new Yaml(repr, options);
    String output = yaml2.dump(result);
    // System.out.println(output);
    assertTrue("Tags must be present.",
            output.startsWith("--- !!org.yaml.snakeyaml.ruby.TestObject"));
    assertTrue("Tags must be present: " + output,
            output.contains("!ruby/object:Test::Module::Sub1"));
    assertTrue("Tags must be present.", output.contains("!ruby/object:Test::Module::Sub2"));
    // parse back.
    TestObject result2 = parseObject(output);
    assertEquals(0, result2.getSub1().getAtt2());
    assertEquals("MyString", result2.getSub2().getAtt1());
    assertEquals(1, result2.getSub2().getAtt2().size());
    assertEquals(12345, result2.getSub2().getAtt3());
}
 
Example #21
Source File: RubyTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
public void testEmitWithTags() {
    TestObject result = parseObject(Util.getLocalResource("ruby/ruby1.yaml"));
    DumperOptions options = new DumperOptions();
    options.setExplicitStart(true);
    Representer repr = new Representer();
    repr.addClassTag(TestObject.class, new Tag("!ruby/object:Test::Module::Object"));
    repr.addClassTag(Sub1.class, new Tag("!ruby/object:Test::Module::Sub1"));
    repr.addClassTag(Sub2.class, new Tag("!ruby/object:Test::Module::Sub2"));
    Yaml yaml2 = new Yaml(repr, options);
    String output = yaml2.dump(result);
    // System.out.println(output);
    assertTrue("Tags must be present.",
            output.startsWith("--- !ruby/object:Test::Module::Object"));
    assertTrue("Tags must be present: " + output,
            output.contains("!ruby/object:Test::Module::Sub1"));
    assertTrue("Tags must be present.", output.contains("!ruby/object:Test::Module::Sub2"));
    // parse back.
    TestObject result2 = parseObject(output);
    assertEquals(0, result2.getSub1().getAtt2());
    assertEquals("MyString", result2.getSub2().getAtt1());
    assertEquals(1, result2.getSub2().getAtt2().size());
    assertEquals(12345, result2.getSub2().getAtt3());
}
 
Example #22
Source File: Yaml.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
/**
 * Create Yaml instance. It is safe to create a few instances and use them
 * in different Threads.
 * 
 * @param constructor
 *            BaseConstructor to construct incoming documents
 * @param representer
 *            Representer to emit outgoing objects
 * @param dumperOptions
 *            DumperOptions to configure outgoing objects
 * @param resolver
 *            Resolver to detect implicit type
 */
public Yaml(BaseConstructor constructor, Representer representer, DumperOptions dumperOptions,
        Resolver resolver) {
    if (!constructor.isExplicitPropertyUtils()) {
        constructor.setPropertyUtils(representer.getPropertyUtils());
    } else if (!representer.isExplicitPropertyUtils()) {
        representer.setPropertyUtils(constructor.getPropertyUtils());
    }
    this.constructor = constructor;
    representer.setDefaultFlowStyle(dumperOptions.getDefaultFlowStyle());
    representer.setDefaultScalarStyle(dumperOptions.getDefaultScalarStyle());
    representer.getPropertyUtils().setAllowReadOnlyProperties(
            dumperOptions.isAllowReadOnlyProperties());
    representer.setTimeZone(dumperOptions.getTimeZone());
    this.representer = representer;
    this.dumperOptions = dumperOptions;
    this.resolver = resolver;
    this.name = "Yaml:" + System.identityHashCode(this);
}
 
Example #23
Source File: YamlConfigLoader.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
public static MxisdConfig loadFromFile(String path) throws IOException {
    File f = new File(path).getAbsoluteFile();
    log.info("Reading config from {}", f.toString());
    Representer rep = new Representer();
    rep.getPropertyUtils().setBeanAccess(BeanAccess.FIELD);
    rep.getPropertyUtils().setAllowReadOnlyProperties(true);
    rep.getPropertyUtils().setSkipMissingProperties(true);
    Yaml yaml = new Yaml(new Constructor(MxisdConfig.class), rep);
    try (FileInputStream is = new FileInputStream(f)) {
        MxisdConfig raw = yaml.load(is);
        log.debug("Read config in memory from {}", path);

        // SnakeYaml set objects to null when there is no value set in the config, even a full sub-tree.
        // This is problematic for default config values and objects, to avoid NPEs.
        // Therefore, we'll use Gson to re-parse the data in a way that avoids us checking the whole config for nulls.
        MxisdConfig cfg = GsonUtil.get().fromJson(GsonUtil.get().toJson(raw), MxisdConfig.class);

        log.info("Loaded config from {}", path);
        return cfg;
    } catch (ParserException t) {
        throw new ConfigurationException(t.getMessage(), "Could not parse YAML config file - Please check indentation and that the configuration options exist");
    }
}
 
Example #24
Source File: MissingPropertyTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
/**
 * A new method setSkipMissingProperties(boolean) was added to configure
 * whether missing properties should throw a YAMLException (the default) or
 * simply show a warning. The default is false.
 */
public void testSkipMissingProperties() throws Exception {
    Representer representer = new Representer();
    representer.getPropertyUtils().setSkipMissingProperties(true);
    yaml = new Yaml(new Constructor(), representer);
    String doc = "goodbye: 10\nhello: 5\nfizz: [1]";
    TestBean bean = yaml.loadAs(doc, TestBean.class);
    assertNotNull(bean);
    assertEquals(5, bean.hello);
}
 
Example #25
Source File: YamlPropertySourceLoader.java    From canal with Apache License 2.0 5 votes vote down vote up
@Override
protected Yaml createYaml() {
    return new Yaml(new StrictMapAppenderConstructor(), new Representer(), new DumperOptions(), new Resolver() {

        @Override
        public void addImplicitResolver(Tag tag, Pattern regexp, String first) {
            if (tag == Tag.TIMESTAMP) {
                return;
            }
            super.addImplicitResolver(tag, regexp, first);
        }
    });
}
 
Example #26
Source File: PropOrderInfluenceWhenAliasedInGenericCollectionTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testABPropertyWithCustomTag() {
    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();

    Tag generalAccountTag = new Tag("!GA");
    constructor
            .addTypeDescription(new TypeDescription(GeneralAccount.class, generalAccountTag));
    representer.addClassTag(GeneralAccount.class, generalAccountTag);

    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 #27
Source File: YamlConfigLoader.java    From digdag with Apache License 2.0 5 votes vote down vote up
public ConfigElement loadString(String content)
    throws IOException
{
    // here doesn't use jackson-dataformat-yaml so that snakeyaml calls Resolver
    // and Composer. See also YamlTagResolver.
    Yaml yaml = new Yaml(new StrictSafeConstructor(), new Representer(), new DumperOptions(), new YamlTagResolver());
    ObjectNode object = normalizeValidateObjectNode(yaml.load(content));
    return ConfigElement.of(object);
}
 
Example #28
Source File: PropertyUtilsSharingTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testYamlDefaults() {
    Yaml yaml1 = new Yaml();
    assertSame(yaml1.constructor.getPropertyUtils(), yaml1.representer.getPropertyUtils());

    Yaml yaml2 = new Yaml(new Constructor());
    assertSame(yaml2.constructor.getPropertyUtils(), yaml2.representer.getPropertyUtils());

    Yaml yaml3 = new Yaml(new Representer());
    assertSame(yaml3.constructor.getPropertyUtils(), yaml3.representer.getPropertyUtils());
}
 
Example #29
Source File: CustomResolverTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testResolverToDump() {
    Map<Object, Object> map = new HashMap<Object, Object>();
    map.put("1.0", "2009-01-01");
    Yaml yaml = new Yaml(new Constructor(), new Representer(), new DumperOptions(),
            new CustomResolver());
    String output = yaml.dump(map);
    assertEquals("{1.0: 2009-01-01}\n", output);
    assertEquals("Float and Date must be escaped.", "{'1.0': '2009-01-01'}\n",
            new Yaml().dump(map));
}
 
Example #30
Source File: CustomResolverTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void testResolverToLoad() {
    Yaml yaml = new Yaml(new Constructor(), new Representer(), new DumperOptions(),
            new CustomResolver());
    Map<Object, Object> map = (Map<Object, Object>) yaml.load("1.0: 2009-01-01");
    assertEquals(1, map.size());
    assertEquals("2009-01-01", map.get("1.0"));
    // the default Resolver shall create Date and Double from the same YAML
    // document
    Yaml yaml2 = new Yaml();
    Map<Object, Object> map2 = (Map<Object, Object>) yaml2.load("1.0: 2009-01-01");
    assertEquals(1, map2.size());
    assertFalse(map2.containsKey("1.0"));
    assertTrue(map2.toString(), map2.containsKey(new Double(1.0)));
}