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) { e.printStackTrace(); } PackageMetadata pkgMetadata = (PackageMetadata) yaml.load(fileContents); return pkgMetadata; }
@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); }
/** * 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); }
/** * 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 loadingConfig * LoadingConfig to control load behavior * @param resolver * Resolver to detect implicit type */ public Yaml(BaseConstructor constructor, Representer representer, DumperOptions dumperOptions, LoaderOptions loadingConfig, Resolver resolver) { if (!constructor.isExplicitPropertyUtils()) { constructor.setPropertyUtils(representer.getPropertyUtils()); } else if (!representer.isExplicitPropertyUtils()) { representer.setPropertyUtils(constructor.getPropertyUtils()); } this.constructor = constructor; this.constructor.setAllowDuplicateKeys(loadingConfig.isAllowDuplicateKeys()); if (dumperOptions.getIndent() <= dumperOptions.getIndicatorIndent()) { throw new YAMLException("Indicator indent must be smaller then indent."); } representer.setDefaultFlowStyle(dumperOptions.getDefaultFlowStyle()); representer.setDefaultScalarStyle(dumperOptions.getDefaultScalarStyle()); representer.getPropertyUtils() .setAllowReadOnlyProperties(dumperOptions.isAllowReadOnlyProperties()); representer.setTimeZone(dumperOptions.getTimeZone()); this.representer = representer; this.dumperOptions = dumperOptions; this.loadingConfig = loadingConfig; this.resolver = resolver; this.name = "Yaml:" + System.identityHashCode(this); }
private void dumpConfiguration(Path configFilePath) { try (FileWriter fileWriter = new FileWriter(configFilePath.toFile())) { DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); Representer representer = new Representer() { @Override protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,Tag customTag) { // if value of property is null, ignore it. if (propertyValue == null) { return null; } else { return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); } } }; representer.addClassTag(Configuration.class, Tag.MAP); Yaml yaml = new Yaml(representer, options); yaml.dump(configuration, fileWriter); } catch (IOException e) { throw new RuntimeException("Failed to dump configuration in file " + configFilePath, e); } }
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); }
/** * use wrapper with local tag */ public void testLocalTag() { JavaBeanWithStaticState bean = new JavaBeanWithStaticState(); bean.setName("Bahrack"); bean.setAge(-47); JavaBeanWithStaticState.setType("Type3"); JavaBeanWithStaticState.color = "Violet"; Representer repr = new Representer(); repr.addClassTag(Wrapper.class, new Tag("!mybean")); Yaml yaml = new Yaml(repr); String output = yaml.dump(new Wrapper(bean)); // System.out.println(output); assertEquals("!mybean {age: -47, color: Violet, name: Bahrack, type: Type3}\n", output); // parse back to instance Constructor constr = new Constructor(); TypeDescription description = new TypeDescription(Wrapper.class, new Tag("!mybean")); constr.addTypeDescription(description); yaml = new Yaml(constr); Wrapper wrapper = (Wrapper) yaml.load(output); JavaBeanWithStaticState bean2 = wrapper.createBean(); assertEquals(-47, bean2.getAge()); assertEquals("Bahrack", bean2.getName()); }
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()); }
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()); }
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); }
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")); }
public void testErrorMessage() throws Exception { BeanA1 b = new BeanA1(); b.setId(2l); b.setName("name1"); Constructor c = new Constructor(); Representer r = new Representer(); PropertyUtils pu = new PropertyUtils(); c.setPropertyUtils(pu); r.setPropertyUtils(pu); pu.getProperties(BeanA1.class, BeanAccess.FIELD); Yaml yaml = new Yaml(c, r); // yaml.setBeanAccess(BeanAccess.FIELD); String dump = yaml.dump(b); BeanA1 b2 = (BeanA1) yaml.load(dump); assertEquals(b.getId(), b2.getId()); assertEquals(b.getName(), b2.getName()); }
public void testDumpClassTag() { Car car = new Car(); car.setPlate("12-XP-F4"); List<Wheel> wheels = new ArrayList<Wheel>(); for (int i = 1; i < 6; i++) { Wheel wheel = new Wheel(); wheel.setId(i); wheels.add(wheel); } car.setWheels(wheels); Representer representer = new Representer(); representer.addClassTag(Car.class, new Tag("!car")); representer.addClassTag(Wheel.class, Tag.MAP); Yaml yaml = new Yaml(representer); String output = yaml.dump(car); assertEquals(Util.getLocalResource("constructor/car-without-tags.yaml"), output); }
public void testLoadClassTag() { Constructor constructor = new Constructor(); constructor.addTypeDescription(new TypeDescription(Car.class, "!car")); Yaml yaml = new Yaml(constructor); Car car = (Car) yaml.load(Util.getLocalResource("constructor/car-without-tags.yaml")); assertEquals("12-XP-F4", car.getPlate()); List<Wheel> wheels = car.getWheels(); assertNotNull(wheels); assertEquals(5, wheels.size()); Wheel w1 = wheels.get(0); assertEquals(1, w1.getId()); // String carYaml1 = new Yaml().dump(car); assertTrue(carYaml1.startsWith("!!org.yaml.snakeyaml.constructor.Car")); // Representer representer = new Representer(); representer.addClassTag(Car.class, new Tag("!car")); yaml = new Yaml(representer); String carYaml2 = yaml.dump(car); assertEquals(Util.getLocalResource("constructor/car-without-tags.yaml"), carYaml2); }
private static void configYamlFormat(final ToolBelt belt, final AppConfig config) { DumperOptions dumperOptions = new DumperOptions(); dumperOptions.setDefaultFlowStyle( "BLOCK".equalsIgnoreCase(config.getString("RD_YAML_FLOW", "BLOCK")) ? DumperOptions.FlowStyle.BLOCK : DumperOptions.FlowStyle.FLOW ); dumperOptions.setPrettyFlow(config.getBool("RD_YAML_PRETTY", true)); Representer representer = new Representer(); representer.addClassTag(JobItem.class, Tag.MAP); representer.addClassTag(ScheduledJobItem.class, Tag.MAP); representer.addClassTag(DateInfo.class, Tag.MAP); representer.addClassTag(Execution.class, Tag.MAP); belt.formatter(new YamlFormatter(representer, dumperOptions)); belt.channels().infoEnabled(false); belt.channels().warningEnabled(false); belt.channels().errorEnabled(false); }
@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 ); }
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, "!&*"); } }); }
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; } }; }
private static Yaml newYaml() { return new Yaml(new Constructor(), new Representer(), new DumperOptions(), new Resolver() { @Override public Tag resolve(NodeId kind, String value, boolean implicit) { if (value != null) { if (value.equalsIgnoreCase("on") || value.equalsIgnoreCase("off") || value.equalsIgnoreCase("yes") || value.equalsIgnoreCase("no")) { return Tag.STR; } } return super.resolve(kind, value, implicit); } }); }
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); }
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); }
public void testWithBlockStyle() throws Exception { Map<String, Map<String, Object>> rootMap = new HashMap<String, Map<String, Object>>(); Map<String, Object> enclosedMap = new HashMap<String, Object>(); enclosedMap.put("world", "test"); rootMap.put("test", enclosedMap); DumperOptions yamlOptions = new DumperOptions(); yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); Representer yamlRepresenter = new Representer(); yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); Yaml yaml = new Yaml(yamlRepresenter, yamlOptions); String output = yaml.dump(rootMap); assertEquals("test:\n world: test\n", output); }
private Properties loadYamlFile ( final File configFile ) throws ManipulationException { Properties result = new Properties( ); Representer representer = new Representer(); representer.getPropertyUtils().setSkipMissingProperties(true); Yaml yaml = new Yaml( representer); try { YamlFile yf = yaml.loadAs( new FileInputStream( configFile ), YamlFile.class); result.putAll( yf.getPme() ); } catch ( FileNotFoundException e ) { throw new ManipulationException( "Unable to load yaml file.", e); } return result; }
/** * 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(final BaseConstructor constructor, final Representer representer, final DumperOptions dumperOptions, final 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); }
public void save() throws IOException { FileWriter writer = new FileWriter(getConfigFile()); DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(FlowStyle.AUTO); options.setIndent(4); Representer representer = new Representer(); representer.getPropertyUtils().setBeanAccess(BeanAccess.DEFAULT); new Yaml(options).dump(this, writer); }
private YamlConfigLoader(@NotNull Builder builder, final DumperOptions options, boolean doComments) { super(builder, new CommentHandler[] {CommentHandlers.HASH}); this.commentsEnabled = doComments; // TODO fix broken comment instrumenter D: this.options = options; representer = new Representer(); representer.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); this.yaml = new ThreadLocal<Yaml>() { @Override protected Yaml initialValue() { return new Yaml(representer, options); } }; }