org.yaml.snakeyaml.constructor.Constructor Java Examples

The following examples show how to use org.yaml.snakeyaml.constructor.Constructor. 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: 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 #2
Source File: ToscaTest.java    From NFVO with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void testVNFDTemplate() throws FileNotFoundException {

  InputStream vnfdFile =
      new FileInputStream(new File("src/main/resources/Testing/testVNFDTemplate.yaml"));

  Constructor constructor = new Constructor(VNFDTemplate.class);
  TypeDescription typeDescription = new TypeDescription(VNFDTemplate.class);
  constructor.addTypeDescription(typeDescription);

  Yaml yaml = new Yaml(constructor);
  VNFDTemplate vnfdInput = yaml.loadAs(vnfdFile, VNFDTemplate.class);

  System.out.println(vnfdInput.toString());
}
 
Example #3
Source File: ConfigManager.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
	 * 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 #4
Source File: StarterConfigure.java    From ClashForMagisk with GNU General Public License v3.0 6 votes vote down vote up
static StarterConfigure loadFromFile(File file) throws IOException {
    FileInputStream inputStream = new FileInputStream(file);
    Constructor constructor = new Constructor(StarterConfigure.class);

    constructor.setPropertyUtils(new PropertyUtils() {
        {
            setSkipMissingProperties(true);
        }
    });

    StarterConfigure result = new Yaml(constructor).loadAs(inputStream, StarterConfigure.class);

    inputStream.close();

    return result;
}
 
Example #5
Source File: PerlTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void testJavaBean() {
    Constructor c = new CustomBeanConstructor();
    Yaml yaml = new Yaml(c);
    String input = Util.getLocalResource("issues/issue56-1.yaml");
    int counter = 0;
    for (Object obj : yaml.loadAll(input)) {
        // System.out.println(obj);
        Map<String, Object> map = (Map<String, Object>) obj;
        Integer oid = (Integer) map.get("oid");
        assertTrue(oid > 10000);
        counter++;
    }
    assertEquals(4, counter);
    assertEquals(55, CodeBean.counter);
}
 
Example #6
Source File: ToscaTest.java    From NFVO with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void testGetNodesFromVNFDTemplate() throws FileNotFoundException, NotFoundException {

  InputStream vnfdFile =
      new FileInputStream(new File("src/main/resources/Testing/testVNFDTemplate.yaml"));

  Constructor constructor = new Constructor(VNFDTemplate.class);
  TypeDescription typeDescription = new TypeDescription(VNFDTemplate.class);
  constructor.addTypeDescription(typeDescription);

  Yaml yaml = new Yaml(constructor);
  VNFDTemplate vnfdInput = yaml.loadAs(vnfdFile, VNFDTemplate.class);

  System.out.println(vnfdInput.getTopology_template().getVDUNodes());
  System.out.println(vnfdInput.getTopology_template().getCPNodes());
  System.out.println(vnfdInput.getTopology_template().getVNFNodes());
}
 
Example #7
Source File: ToscaTest.java    From NFVO with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void testVNFDServerIperf() throws NotFoundException, FileNotFoundException {

  InputStream vnfdFile =
      new FileInputStream(new File("src/main/resources/Testing/vnfd_server_iperf.yaml"));

  Constructor constructor = new Constructor(VNFDTemplate.class);
  TypeDescription typeDescription = new TypeDescription(VNFDTemplate.class);
  constructor.addTypeDescription(typeDescription);

  Yaml yaml = new Yaml(constructor);
  VNFDTemplate vnfdInput = yaml.loadAs(vnfdFile, VNFDTemplate.class);

  TOSCAParser parser = new TOSCAParser();

  VirtualNetworkFunctionDescriptor vnfd = parser.parseVNFDTemplate(vnfdInput);
  Gson gson = new Gson();
  System.out.println(gson.toJson(vnfd));
}
 
Example #8
Source File: GodScreen.java    From xibalba with MIT License 6 votes vote down vote up
private void updateAbilitiesGroup() {
  abilityGroup.clear();

  abilityGroup.addActor(new Label("Abilities", Main.skin));
  abilityGroup.addActor(new Label("", Main.skin));

  GodData godData = godDataList.get(godSelected);

  Constructor constructor = new Constructor(Ability.class);
  constructor.addTypeDescription(new TypeDescription(Charm.class, "!Charm"));
  Yaml yaml = new Yaml(constructor);
  godData.abilities.forEach((String ability) -> {
    Ability details = (Ability) yaml.load(Main.abilitiesData.get(ability));

    abilityGroup.addActor(
        new Label(
            createAbilityText(details), Main.skin)
    );
  });
}
 
Example #9
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 #10
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 #11
Source File: ToscaTest.java    From NFVO with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void testGettingVDUNodes() throws FileNotFoundException {

  InputStream cpFile =
      new FileInputStream(new File("src/main/resources/Testing/testTopologyTemplate.yaml"));

  Constructor constructor = new Constructor(TopologyTemplate.class);
  TypeDescription typeDescription = new TypeDescription(TopologyTemplate.class);
  constructor.addTypeDescription(typeDescription);

  Yaml yaml = new Yaml(constructor);
  TopologyTemplate cpInput = yaml.loadAs(cpFile, TopologyTemplate.class);

  List<VDUNodeTemplate> vduNodes = cpInput.getVDUNodes();

  for (VDUNodeTemplate n : vduNodes) {
    System.out.println(n.toString());
  }
}
 
Example #12
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 #13
Source File: Human_WithArrayOfChildrenTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
public void testChildrenArray() {
    Constructor constructor = new Constructor(Human_WithArrayOfChildren.class);
    TypeDescription HumanWithChildrenArrayDescription = new TypeDescription(
            Human_WithArrayOfChildren.class);
    HumanWithChildrenArrayDescription.putListPropertyType("children",
            Human_WithArrayOfChildren.class);
    constructor.addTypeDescription(HumanWithChildrenArrayDescription);
    Human_WithArrayOfChildren son = createSon();
    Yaml yaml = new Yaml(constructor);
    String output = yaml.dump(son);
    // System.out.println(output);
    String etalon = Util.getLocalResource("recursive/with-childrenArray.yaml");
    assertEquals(etalon, output);
    //
    Human_WithArrayOfChildren son2 = (Human_WithArrayOfChildren) yaml.load(output);
    checkSon(son2);
}
 
Example #14
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 #15
Source File: ToscaTest.java    From NFVO with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void testCreatingVNFDInstance() throws FileNotFoundException, NotFoundException {

  InputStream vnfdFile =
      new FileInputStream(new File("src/main/resources/Testing/testVNFDTemplate.yaml"));

  Constructor constructor = new Constructor(VNFDTemplate.class);
  TypeDescription typeDescription = new TypeDescription(VNFDTemplate.class);
  constructor.addTypeDescription(typeDescription);

  Yaml yaml = new Yaml(constructor);
  VNFDTemplate vnfdInput = yaml.loadAs(vnfdFile, VNFDTemplate.class);

  TOSCAParser parser = new TOSCAParser();

  VirtualNetworkFunctionDescriptor vnfd = parser.parseVNFDTemplate(vnfdInput);

  Gson gson = new Gson();
  System.out.println(gson.toJson(vnfd));
}
 
Example #16
Source File: ToscaTest.java    From NFVO with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void testMultipleVLs() throws FileNotFoundException, NotFoundException {

  InputStream nsdFile =
      new FileInputStream(new File("src/main/resources/Testing/tosca-ns-example.yaml"));

  Constructor constructor = new Constructor(NSDTemplate.class);
  TypeDescription typeDescription = new TypeDescription(NSDTemplate.class);
  constructor.addTypeDescription(typeDescription);

  Yaml yaml = new Yaml(constructor);
  NSDTemplate nsdInput = yaml.loadAs(nsdFile, NSDTemplate.class);

  TOSCAParser parser = new TOSCAParser();

  NetworkServiceDescriptor nsd = parser.parseNSDTemplate(nsdInput);

  Gson gson = new Gson();
  System.out.println(gson.toJson(nsd));
}
 
Example #17
Source File: YAMLToJavaDeserialisationUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenLoadYAMLDocumentWithTypeDescription_thenLoadCorrectJavaObjectWithCorrectGenericType() {
    Constructor constructor = new Constructor(Customer.class);
    TypeDescription customTypeDescription = new TypeDescription(Customer.class);
    customTypeDescription.addPropertyParameters("contactDetails", Contact.class);
    constructor.addTypeDescription(customTypeDescription);
    Yaml yaml = new Yaml(constructor);
    InputStream inputStream = this.getClass()
        .getClassLoader()
        .getResourceAsStream("yaml/customer_with_contact_details.yaml");
    Customer customer = yaml.load(inputStream);
    assertNotNull(customer);
    assertEquals("John", customer.getFirstName());
    assertEquals("Doe", customer.getLastName());
    assertEquals(31, customer.getAge());
    assertNotNull(customer.getContactDetails());
    assertEquals(2, customer.getContactDetails().size());
    assertEquals("mobile", customer.getContactDetails()
        .get(0)
        .getType());
    assertEquals("landline", customer.getContactDetails()
        .get(1)
        .getType());
}
 
Example #18
Source File: ToscaTest.java    From NFVO with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void testNSDIperfASTemplate() throws FileNotFoundException, NotFoundException {

  InputStream nsdFile =
      new FileInputStream(new File("src/main/resources/Testing/testNSDIperfAutoscaling.yaml"));

  Constructor constructor = new Constructor(NSDTemplate.class);
  TypeDescription typeDescription = new TypeDescription(NSDTemplate.class);
  constructor.addTypeDescription(typeDescription);

  Yaml yaml = new Yaml(constructor);
  NSDTemplate nsdInput = yaml.loadAs(nsdFile, NSDTemplate.class);

  TOSCAParser parser = new TOSCAParser();

  NetworkServiceDescriptor nsd = parser.parseNSDTemplate(nsdInput);

  Gson gson = new Gson();
  System.out.println(gson.toJson(nsd));
}
 
Example #19
Source File: Workflow.java    From helix with 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 #20
Source File: AbstractBeanTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
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());
    }
 
Example #21
Source File: TypeSafePriorityTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
/**
 * explicit TypeDescription is more important then runtime class (which may
 * be an interface)
 */
public void testLoadList2() {
    String output = Util.getLocalResource("examples/list-bean-3.yaml");
    // System.out.println(output);
    TypeDescription descr = new TypeDescription(ListBean.class);
    descr.putListPropertyType("developers", Developer.class);
    Yaml beanLoader = new Yaml(new Constructor(descr));
    ListBean parsed = beanLoader.loadAs(output, ListBean.class);
    assertNotNull(parsed);
    List<Human> developers = parsed.getDevelopers();
    assertEquals(2, developers.size());
    assertEquals("Committer must be recognised.", Developer.class, developers.get(0).getClass());
    Developer fred = (Developer) developers.get(0);
    assertEquals("Fred", fred.getName());
    assertEquals("creator", fred.getRole());
    Developer john = (Developer) developers.get(1);
    assertEquals("John", john.getName());
    assertEquals("committer", john.getRole());
}
 
Example #22
Source File: ToscaTest.java    From NFVO with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void testGettingCPNodes() throws FileNotFoundException {

  InputStream cpFile =
      new FileInputStream(new File("src/main/resources/Testing/testTopologyTemplate.yaml"));

  Constructor constructor = new Constructor(TopologyTemplate.class);
  TypeDescription typeDescription = new TypeDescription(TopologyTemplate.class);
  constructor.addTypeDescription(typeDescription);

  Yaml yaml = new Yaml(constructor);
  TopologyTemplate cpInput = yaml.loadAs(cpFile, TopologyTemplate.class);

  List<CPNodeTemplate> cpNodes = cpInput.getCPNodes();

  for (CPNodeTemplate n : cpNodes) {
    System.out.println(n.toString());
  }
}
 
Example #23
Source File: ObjectMapItem.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
private Object loadYaml(File omapfile) throws IOException {
    FileReader reader = new FileReader(omapfile);
    try {
        Constructor constructor = new Constructor();
        PropertyUtils putils = new PropertyUtils();
        putils.setSkipMissingProperties(true);
        constructor.setPropertyUtils(putils);
        Yaml yaml = new Yaml(constructor);
        return yaml.load(reader);
    } catch (Throwable t) {
        throw new RuntimeException("Error loading yaml from: " + omapfile.getAbsolutePath() + "\n" + t.getMessage(), t);
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example #24
Source File: DotCiPlugin.java    From DotCi with MIT License 6 votes vote down vote up
@Override
public void start() throws Exception {
    File configsDir = new File(Jenkins.getInstance().getRootDir(), "pluginConfigs");
    File dotciPluginYml = new File(configsDir, "dotci.yml");

    if (dotciPluginYml.exists()) {
        LOGGER.info("Configuring dotci plugin from " + dotciPluginYml.getAbsolutePath());
        try (InputStream in = new BufferedInputStream(new FileInputStream(dotciPluginYml))) {
            Constructor constructor = new Constructor(SetupConfig.class);
            Yaml yaml = new Yaml(constructor);
            SetupConfig configuration = (SetupConfig) yaml.load(in);
            configuration.save();
        }
    } else {
        LOGGER.info(dotciPluginYml.getAbsolutePath() + " file not found.");
    }
}
 
Example #25
Source File: HumanTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void testChildrenSetAsRoot() {
    String etalon = Util.getLocalResource("recursive/with-children-as-set.yaml");

    Constructor constructor = new Constructor();
    TypeDescription humanDescription = new TypeDescription(Human.class);
    humanDescription.putMapPropertyType("children", Human.class, Object.class);
    constructor.addTypeDescription(humanDescription);

    Yaml yaml = new Yaml(constructor);
    Set<Human> children2 = (Set<Human>) yaml.load(etalon);
    assertNotNull(children2);
    assertEquals(2, children2.size());

    Human firstChild = children2.iterator().next();

    Human father2 = firstChild.getFather();
    assertEquals("Father", father2.getName());
    assertEquals("Mother", firstChild.getMother().getName());
    assertSame(father2, father2.getBankAccountOwner());
    assertSame(father2.getPartner(), firstChild.getMother());
    assertSame(father2, firstChild.getMother().getPartner());

    assertSame(father2.getPartner().getChildren(), children2);

    for (Object child : children2) {
        // check if type descriptor was correct
        assertSame(Human.class, child.getClass());
    }

    validateSet(children2);
}
 
Example #26
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 #27
Source File: Yamls.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private static Yaml newYaml() {
    return new Yaml(
            BrooklynSystemProperties.YAML_TYPE_INSTANTIATION.isEnabled()
                    ? new Constructor() // allows instantiation of arbitrary Java types
                    : new SafeConstructor() // allows instantiation of limited set of types only
    );
}
 
Example #28
Source File: ArrayInGenericCollectionTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testNoTags() {
    Yaml yaml2dump = new Yaml();
    yaml2dump.setBeanAccess(BeanAccess.FIELD);
    B data = createB();
    String dump = yaml2dump.dumpAs(data, Tag.MAP, FlowStyle.AUTO);
    // System.out.println(dump);
    assertEquals("meta:\n- [whatever]\n- [something, something else]\n", dump);
    //
    Constructor constr = new Constructor(B.class);
    Yaml yaml2load = new Yaml(constr);
    yaml2load.setBeanAccess(BeanAccess.FIELD);
    B loaded = (B) yaml2load.load(dump);

    Assert.assertArrayEquals(data.meta.toArray(), loaded.meta.toArray());
}
 
Example #29
Source File: KaramelFile.java    From karamel with Apache License 2.0 5 votes vote down vote up
public KaramelFile(String fileContent) throws MetadataParseException {
  Yaml yaml = new Yaml(new Constructor(KaramelFileYamlRep.class));
  KaramelFileYamlRep file = null;
  try {
    file = (KaramelFileYamlRep) yaml.load(fileContent);
  } catch (YAMLException ex) {
    throw new MetadataParseException(ex.getMessage());
  }
  dependencies = new ArrayList<>();
  dependencies.addAll(file.getDependencies());
}
 
Example #30
Source File: CompactConstructor.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
protected Object createInstance(ScalarNode node, CompactData data) throws Exception {
    Class<?> clazz = getClassForName(data.getPrefix());
    Class<?>[] args = new Class[data.getArguments().size()];
    for (int i = 0; i < args.length; i++) {
        // assume all the arguments are Strings
        args[i] = String.class;
    }
    java.lang.reflect.Constructor<?> c = clazz.getDeclaredConstructor(args);
    c.setAccessible(true);
    return c.newInstance(data.getArguments().toArray());

}