Java Code Examples for org.yaml.snakeyaml.Yaml#loadAs()

The following examples show how to use org.yaml.snakeyaml.Yaml#loadAs() . 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: CSARParser.java    From NFVO with 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 2
Source File: PropertyHolder.java    From framework with Apache License 2.0 6 votes vote down vote up
/**
 * Description: <br>
 * 
 * @author 王伟<br>
 * @taskId <br>
 * @param inputStream
 * @param map
 * @throws IOException <br>
 */
@SuppressWarnings("unchecked")
private static void loadYml(final InputStream inputStream, final Map<String, String> map) throws IOException {
    try {

        Yaml yaml = new Yaml();
        HashMap<String, Object> value = yaml.loadAs(inputStream, HashMap.class);
        if (MapUtils.isNotEmpty(value)) {
            for (Entry<String, Object> entry : value.entrySet()) {
                transfer(entry.getKey(), entry.getValue(), map);
            }
        }
    }
    finally {
        IOUtils.closeQuietly(inputStream);
    }
}
 
Example 3
Source File: DocumentResourceAccess.java    From sureness with Apache License 2.0 6 votes vote down vote up
/**
 * 从配置文件里读取resource配置信息
 * @return 配置实体对象
 * @throws IOException 文件不存在或者读取文件异常时
 */
public static DocumentResourceEntity loadConfig() throws IOException {
    Yaml yaml = new Yaml();
    InputStream inputStream = DocumentResourceAccess.class.getClassLoader().getResourceAsStream(yamlFileName);
    if (inputStream == null) {
        File yamlFile = new File(yamlFileName);
        if (yamlFile.exists()) {
            try (FileInputStream fileInputStream = new FileInputStream(yamlFile)) {
                return yaml.loadAs(fileInputStream, DocumentResourceEntity.class);
            } catch (IOException e) {
                throw new IOException(e);
            }
        }
    }
    if (inputStream == null) {
        throw new FileNotFoundException("sureness file: " + DEFAULT_FILE_NAME + " not found, " +
                "please create the file if you need config resource");
    }
    return yaml.loadAs(inputStream, DocumentResourceEntity.class);
}
 
Example 4
Source File: CredentialLoaderTestUtil.java    From ebay-oauth-java-client with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static Map<String, Map<String, String>> loadUserCredentials() {
    String runtimeParam = getRuntimeParam("usercred_yaml");
    Map<String, Map<String, String>> values = new HashMap<>();

    if (runtimeParam != null && !runtimeParam.trim().isEmpty()) {
        isUserCredentialsLoaded = true;
        return new Yaml().load(runtimeParam);
    } else {
        //TODO: Create the file ebay-config.yaml using the ebay-config-sample.yaml before running these tests
        Yaml yaml = new Yaml();
        try {
            values = (Map<String, Map<String, String>>) yaml.loadAs(new FileInputStream("src/test/resources/test-config.yaml"), Map.class);
            isUserCredentialsLoaded = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    return values;
}
 
Example 5
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 6
Source File: Settings.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * Read configuration from a file into a new {@link Settings} object.
 *
 * @param stream an input stream containing a Gremlin Server YAML configuration
 */
public static Settings read(final InputStream stream) {
    Objects.requireNonNull(stream);

    final Constructor constructor = new Constructor(Settings.class);
    final TypeDescription settingsDescription = new TypeDescription(Settings.class);
    settingsDescription.putListPropertyType("hosts", String.class);
    settingsDescription.putListPropertyType("serializers", SerializerSettings.class);
    constructor.addTypeDescription(settingsDescription);

    final Yaml yaml = new Yaml(constructor);
    return yaml.loadAs(stream, Settings.class);
}
 
Example 7
Source File: NumberBeanTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testNumberAsDoubleNaN() throws Exception {
    NumberBean number = new NumberBean();
    number.number = Double.NaN;

    Yaml yaml = new Yaml();
    String dump = yaml.dump(number);
    NumberBean loaded = yaml.loadAs(dump, NumberBean.class);
    assertEquals(Double.NaN, loaded.number.doubleValue());
}
 
Example 8
Source File: TypeSafeMap2Test.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testLoadMap() {
    String output = Util.getLocalResource("examples/map-bean-12.yaml");
    // System.out.println(output);
    Yaml beanLoader = new Yaml();
    MapBean2 parsed = beanLoader.loadAs(output, MapBean2.class);
    assertNotNull(parsed);
    Map<Developer2, Color> data = parsed.getData();
    assertEquals(2, data.size());
    Iterator<Developer2> iter = data.keySet().iterator();
    Developer2 first = iter.next();
    assertEquals("Andy", first.getName());
    assertEquals("tester", first.getRole());
    assertEquals(Color.BLACK, data.get(first));
    Developer2 second = iter.next();
    assertEquals("Lisa", second.getName());
    assertEquals("owner", second.getRole());
    assertEquals(Color.RED, data.get(second));
    //
    Map<Color, Developer2> developers = parsed.getDevelopers();
    assertEquals(2, developers.size());
    Iterator<Color> iter2 = developers.keySet().iterator();
    Color firstColor = iter2.next();
    assertEquals(Color.WHITE, firstColor);
    Developer2 dev1 = developers.get(firstColor);
    assertEquals("Fred", dev1.getName());
    assertEquals("creator", dev1.getRole());
    Color secondColor = iter2.next();
    assertEquals(Color.BLACK, secondColor);
    Developer2 dev2 = developers.get(secondColor);
    assertEquals("John", dev2.getName());
    assertEquals("committer", dev2.getRole());
}
 
Example 9
Source File: InfinityFloatBeanTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testInfinityFloatBean() throws Exception {

        InfinityFloatBean bean = new InfinityFloatBean();
        bean.infinityFloat = Float.POSITIVE_INFINITY;
        bean.infinityFloatObject = Float.POSITIVE_INFINITY;

        Yaml yaml = new Yaml();
        String yamled = yaml.dump(bean);
        InfinityFloatBean loadedBean = yaml.loadAs(yamled, InfinityFloatBean.class);
        assertEquals(Float.POSITIVE_INFINITY, loadedBean.infinityFloat);
        assertEquals(Float.POSITIVE_INFINITY, loadedBean.infinityFloatObject);
    }
 
Example 10
Source File: DogFoodBeanTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testBigDecimalNoRootTag() {
    DogFoodBean input = new DogFoodBean();
    input.setDecimal(new BigDecimal("5.123"));
    Yaml yaml = new Yaml();
    String text = yaml.dumpAsMap(input);
    // System.out.println(text);
    assertEquals("decimal: 5.123\n", text);
    Yaml loader = new Yaml();
    DogFoodBean output = loader.loadAs(text, DogFoodBean.class);
    assertEquals(input.getDecimal(), output.getDecimal());
}
 
Example 11
Source File: Info.java    From gateplugin-LearningFramework with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Load from directory.
 * @param directory directory to load from
 * @return Info instance
 */
public static Info load(URL directory) {
  CustomClassLoaderConstructor constr = 
          new CustomClassLoaderConstructor(Info.class.getClassLoader());
  Yaml yaml = new Yaml(constr);
  Object obj;
  URL infoFile = newURL(directory,FILENAME_INFO);
  try (InputStream is = infoFile.openStream()) {
    obj = yaml.loadAs(new InputStreamReader(is,"UTF-8"),Info.class);
  } catch (IOException ex) {
    throw new GateRuntimeException("Could not load info file "+infoFile,ex);
  }    
  Info info = (Info)obj;    
  return info;
}
 
Example 12
Source File: ReadOnlyPropertiesTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testBean1() {
    IncompleteBean bean = new IncompleteBean();
    bean.setName("lunch");
    Yaml yaml = new Yaml();
    String output = yaml.dumpAsMap(bean);
    // System.out.println(output);
    assertEquals("name: lunch\n", output);
    //
    Yaml loader = new Yaml();
    IncompleteBean parsed = loader.loadAs(output, IncompleteBean.class);
    assertEquals(bean.getName(), parsed.getName());
}
 
Example 13
Source File: TriangleBeanTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testClassNotFound() {
    String output = "name: Bean25\nshape: !!org.yaml.snakeyaml.javabeans.Triangle777\n  name: Triangle25\n";
    Yaml beanLoader = new Yaml();
    try {
        beanLoader.loadAs(output, TriangleBean.class);
        fail("Class not found expected.");
    } catch (Exception e) {
        assertTrue(
                e.getMessage(),
                e.getMessage().contains(
                        "Class not found: org.yaml.snakeyaml.javabeans.Triangle777"));
    }
}
 
Example 14
Source File: BirdTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testHome() throws IntrospectionException {
    Bird bird = new Bird();
    bird.setName("Eagle");
    Nest home = new Nest();
    home = new Nest();
    home.setHeight(3);
    bird.setHome(home);
    Yaml yaml = new Yaml();
    String output = yaml.dumpAsMap(bird);
    Bird parsed;
    String javaVendor = System.getProperty("java.vm.name");
    Yaml loader = new Yaml();
    if (GenericsBugDetector.isProperIntrospection()) {
        // no global tags
        System.out.println("java.vm.name: " + javaVendor);
        assertEquals("no global tags must be emitted.", "home:\n  height: 3\nname: Eagle\n",
                output);
        parsed = loader.loadAs(output, Bird.class);

    } else {
        // with global tags
        System.out
                .println("JDK requires global tags for JavaBean properties with Java Generics. java.vm.name: "
                        + javaVendor);
        assertEquals("global tags are inevitable here.",
                "home: !!org.yaml.snakeyaml.generics.Nest\n  height: 3\nname: Eagle\n", output);
        parsed = loader.loadAs(output, Bird.class);
    }
    assertEquals(bird.getName(), parsed.getName());
    assertEquals(bird.getHome().getHeight(), parsed.getHome().getHeight());
}
 
Example 15
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 16
Source File: YamlLoadAsIssueTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
@Test
public void ignoreImplicitTag() {
    Yaml yaml = yaml();
    Car car = yaml.loadAs(reader(), Car.class);
    assertNotNull(car);
    assertEquals("12-XP-F4", car.getPlate());
    ArrayList<Wheel> wheels = new ArrayList<Wheel>(car.getWheels());
    assertEquals(4, wheels.size());
    for (int i = 0; i < wheels.size(); i++) {
        assertEquals(wheels.get(i).getId(), Integer.valueOf(i + 1));
    }
}
 
Example 17
Source File: DatanodeIdYaml.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Read datanode.id from file.
 */
public static DatanodeDetails readDatanodeIdFile(File path)
    throws IOException {
  DatanodeDetails datanodeDetails;
  try (FileInputStream inputFileStream = new FileInputStream(path)) {
    Yaml yaml = new Yaml();
    DatanodeDetailsYaml datanodeDetailsYaml;
    try {
      datanodeDetailsYaml =
          yaml.loadAs(inputFileStream, DatanodeDetailsYaml.class);
    } catch (Exception e) {
      throw new IOException("Unable to parse yaml file.", e);
    }

    DatanodeDetails.Builder builder = DatanodeDetails.newBuilder();
    builder.setUuid(datanodeDetailsYaml.getUuid())
        .setIpAddress(datanodeDetailsYaml.getIpAddress())
        .setHostName(datanodeDetailsYaml.getHostName())
        .setCertSerialId(datanodeDetailsYaml.getCertSerialId());

    if (!MapUtils.isEmpty(datanodeDetailsYaml.getPortDetails())) {
      for (Map.Entry<String, Integer> portEntry :
          datanodeDetailsYaml.getPortDetails().entrySet()) {
        builder.addPort(DatanodeDetails.newPort(
            DatanodeDetails.Port.Name.valueOf(portEntry.getKey()),
            portEntry.getValue()));
      }
    }
    datanodeDetails = builder.build();
  }

  return datanodeDetails;
}
 
Example 18
Source File: TriangleBeanTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
/**
 * Runtime class has less priority then an explicit tag
 */
public void testClassAndTag() {
    String output = "name: !!whatever Bean25\nshape: !!org.yaml.snakeyaml.javabeans.Triangle\n  name: Triangle25\n";
    Yaml beanLoader = new Yaml();
    try {
        beanLoader.loadAs(output, TriangleBean.class);
        fail("Runtime class has less priority then an explicit tag");
    } catch (Exception e) {
        assertTrue(e.getMessage(), e.getMessage().contains("Class not found: whatever"));
    }
}
 
Example 19
Source File: ValidatorsTest.java    From rdflint with MIT License 4 votes vote down vote up
private void executeValidatorTest(Path f, String rootPath) {
  Yaml yaml = new Yaml();
  final String conf = f.toString() + "/rdflint-config.yml";
  final String suppress = f.toString() + "/rdflint-suppress.yml";
  final String expect = f.toString() + "/expected-problems.yml";
  final String[] target = f.toString().substring(rootPath.length()).split("/");
  final String targetClass = target[0];
  final String targetDataset = target[1];
  final String assertPrefix = "[" + targetClass + "/" + targetDataset + "] ";
  assertTrue(assertPrefix + conf + " not found.", new File(conf).exists());
  assertTrue(assertPrefix + expect + "not found", new File(expect).exists());

  try {
    // load rdflint-config.yml
    RdfLintParameters params = ConfigurationLoader.loadConfig(conf);
    if (new File(suppress).exists()) {
      params.setSuppressPath(suppress);
    }

    // load expected-problems.yml
    @SuppressWarnings("unchecked")
    LinkedHashMap<String, List<LinkedHashMap<String, Object>>> expectedYaml = yaml.loadAs(
        new InputStreamReader(
            Files.newInputStream(Paths.get(new File(expect).getCanonicalPath())),
            StandardCharsets.UTF_8),
        (Class<LinkedHashMap<String, List<LinkedHashMap<String, Object>>>>)
            (Class<?>) LinkedHashMap.class
    );
    final LinkedHashMap<String, List<LinkedHashMap<String, Object>>> expected
        = expectedYaml == null ? new LinkedHashMap<>() : expectedYaml;

    // append validator
    RdfValidator v = (RdfValidator) Class
        .forName("com.github.imas.rdflint.validator.impl." + targetClass)
        .newInstance();
    ValidationRunner runner = new ValidationRunner();
    runner.appendRdfValidator(v);

    // linter process
    LintProblemSet problems = runner.execute(params, f.toString());

    // valid errors
    assertThat(assertPrefix + "problem fileset unmatched",
        problems.getProblemSet().keySet().toArray(),
        is(arrayContainingInAnyOrder(expected.keySet().toArray())));

    problems.getProblemSet().forEach((fn, lst) -> {
      String[] targetProblems = lst.stream().map(p -> {
        LinkedHashMap<String, Object> issue = new LinkedHashMap<>();
        issue.put("key", p.getKey());
        if (p.getLocation() != null) {
          if (p.getLocation().getTriple() != null) {
            issue.put("subject", p.getLocation().getTriple().getSubject().toString());
            issue.put("predicate", p.getLocation().getTriple().getPredicate().toString());
          } else if (p.getLocation().getNode() != null) {
            issue.put("node", p.getLocation().getNode().toString());
          } else if (p.getLocation().getBeginCol() > 0) {
            issue.put("line", String.valueOf(p.getLocation().getBeginLine()));
            issue.put("column", String.valueOf(p.getLocation().getBeginCol()));
          } else if (p.getLocation().getBeginLine() > 0) {
            issue.put("line", String.valueOf(p.getLocation().getBeginLine()));
          }
        }
        return this.createKeySortedMapString(issue);
      }).toArray(String[]::new);
      String[] expectedProblems = expected.get(fn).stream()
          .map(this::createKeySortedMapString).toArray(String[]::new);
      assertThat(assertPrefix + "problem list unmatched @ " + fn,
          targetProblems,
          is(arrayContainingInAnyOrder(expectedProblems)));
    });
  } catch (IOException
      | InstantiationException | IllegalAccessException | ClassNotFoundException e) {
    fail(assertPrefix + "fail on " + e.getMessage());
  }
}
 
Example 20
Source File: NodeSchemaLoader.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
/**
 * Load network topology layer schemas from a YAML configuration file.
 * @param schemaFile as inputStream
 * @return all valid node schemas defined in schema file
 * @throws IllegalArgumentException xml file content is logically invalid
 */
private NodeSchemaLoadResult loadSchemaFromYaml(InputStream schemaFile) {
  LOG.info("Loading network topology layer schema file {}", schemaFile);
  NodeSchemaLoadResult finalSchema;

  try {
    Yaml yaml = new Yaml();
    NodeSchema nodeTree;

    nodeTree = yaml.loadAs(schemaFile, NodeSchema.class);

    List<NodeSchema> schemaList = new ArrayList<>();
    if (nodeTree.getType() != LayerType.ROOT) {
      throw new IllegalArgumentException("First layer is not a ROOT node."
          + " schema file.");
    }
    schemaList.add(nodeTree);
    if (nodeTree.getSublayer() != null) {
      nodeTree = nodeTree.getSublayer().get(0);
    }

    while (nodeTree != null) {
      if (nodeTree.getType() == LayerType.LEAF_NODE
              && nodeTree.getSublayer() != null) {
        throw new IllegalArgumentException("Leaf node in the middle of path."
            + " schema file.");
      }
      if (nodeTree.getType() == LayerType.ROOT) {
        throw new IllegalArgumentException("Multiple root nodes are defined."
            + " schema file.");
      }
      schemaList.add(nodeTree);
      if (nodeTree.getSublayer() != null) {
        nodeTree = nodeTree.getSublayer().get(0);
      } else {
        break;
      }
    }
    finalSchema = new NodeSchemaLoadResult(schemaList, true);
  } catch (Exception e) {
    throw new IllegalArgumentException("Fail to load network topology node"
        + " schema file: " + schemaFile + " , error:"
        + e.getMessage(), e);
  }

  return finalSchema;
}