Search in sources :

Example 1 with YAMLParser

use of com.fasterxml.jackson.dataformat.yaml.YAMLParser in project polaris-java by polarismesh.

the class ConfigAPIFactory method loadConfig.

/**
 * 通过配置文件加载配置对象
 *
 * @param configStream 配置文件流
 * @return 配置对象
 * @throws PolarisException 文件加载异常
 */
public static Configuration loadConfig(InputStream configStream) throws PolarisException {
    YAMLFactory yamlFactory = new YAMLFactory();
    ObjectMapper mapper = new ObjectMapper();
    try {
        YAMLParser yamlParser = yamlFactory.createParser(configStream);
        final JsonNode node = mapper.readTree(yamlParser);
        TreeTraversingParser treeTraversingParser = new TreeTraversingParser(node);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper.readValue(treeTraversingParser, ConfigurationImpl.class);
    } catch (Exception e) {
        throw new PolarisException(ErrorCode.INVALID_CONFIG, "fail to load config from stream", e);
    }
}
Also used : PolarisException(com.tencent.polaris.api.exception.PolarisException) TreeTraversingParser(com.fasterxml.jackson.databind.node.TreeTraversingParser) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) YAMLParser(com.fasterxml.jackson.dataformat.yaml.YAMLParser) JsonNode(com.fasterxml.jackson.databind.JsonNode) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) PolarisException(com.tencent.polaris.api.exception.PolarisException)

Example 2 with YAMLParser

use of com.fasterxml.jackson.dataformat.yaml.YAMLParser in project atlas by osmlab.

the class StandardConfiguration method readConfigurationMapFromYAML.

@SuppressWarnings("unchecked")
private Optional<Map<String, Object>> readConfigurationMapFromYAML(final byte[] readBytes) {
    final ByteArrayInputStream read = new ByteArrayInputStream(readBytes);
    logger.info("Attempting to load configuration as YAML.");
    try {
        final ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
        final SimpleModule simpleModule = new SimpleModule();
        simpleModule.addDeserializer(Map.class, new ConfigurationDeserializer());
        objectMapper.registerModule(simpleModule);
        final YAMLParser parser = new YAMLFactory().createParser(read);
        final Map<String, Object> readConfig = objectMapper.readValue(parser, Map.class);
        logger.info("Success! Loaded YAML configuration.");
        return Optional.of(readConfig);
    } catch (final Exception yamlReadException) {
        logger.warn("Unable to parse config file as YAML");
        return Optional.empty();
    } finally {
        IOUtils.closeQuietly(read);
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) YAMLParser(com.fasterxml.jackson.dataformat.yaml.YAMLParser) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) SimpleModule(com.fasterxml.jackson.databind.module.SimpleModule) CoreException(org.openstreetmap.atlas.exception.CoreException)

Example 3 with YAMLParser

use of com.fasterxml.jackson.dataformat.yaml.YAMLParser in project strimzi by strimzi.

the class TestUtils method configMapFromYaml.

public static ConfigMap configMapFromYaml(String yamlPath, String name) {
    try {
        YAMLFactory yaml = new YAMLFactory();
        ObjectMapper mapper = new ObjectMapper(yaml);
        YAMLParser yamlParser = yaml.createParser(new File(yamlPath));
        List<ConfigMap> list = mapper.readValues(yamlParser, new TypeReference<ConfigMap>() {
        }).readAll();
        Optional<ConfigMap> cmOpt = list.stream().filter(cm -> "ConfigMap".equals(cm.getKind()) && name.equals(cm.getMetadata().getName())).findFirst();
        if (cmOpt.isPresent()) {
            return cmOpt.get();
        } else {
            LOGGER.warn("ConfigMap {} not found in file {}", name, yamlPath);
            return null;
        }
    } catch (InvalidFormatException e) {
        throw new IllegalArgumentException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : VertxException(io.vertx.core.VertxException) CoreMatchers.is(org.hamcrest.CoreMatchers.is) YAMLGenerator(com.fasterxml.jackson.dataformat.yaml.YAMLGenerator) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) BooleanSupplier(java.util.function.BooleanSupplier) YAMLMapper(com.fasterxml.jackson.dataformat.yaml.YAMLMapper) Arrays.asList(java.util.Arrays.asList) Duration(java.time.Duration) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) Collector(java.util.stream.Collector) TypeReference(com.fasterxml.jackson.core.type.TypeReference) PrintWriter(java.io.PrintWriter) Set(java.util.Set) Reader(java.io.Reader) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Writer(java.io.Writer) Optional(java.util.Optional) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) InvalidFormatException(com.fasterxml.jackson.databind.exc.InvalidFormatException) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) OwnerReference(io.fabric8.kubernetes.api.model.OwnerReference) Function(java.util.function.Function) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) HashSet(java.util.HashSet) Charset(java.nio.charset.Charset) YAMLParser(com.fasterxml.jackson.dataformat.yaml.YAMLParser) StringTokenizer(java.util.StringTokenizer) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) OutputStreamWriter(java.io.OutputStreamWriter) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Files(java.nio.file.Files) BufferedWriter(java.io.BufferedWriter) StringWriter(java.io.StringWriter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) FileOutputStream(java.io.FileOutputStream) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) UnknownHostException(java.net.UnknownHostException) File(java.io.File) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) AbstractMap(java.util.AbstractMap) Paths(java.nio.file.Paths) JsonInclude(com.fasterxml.jackson.annotation.JsonInclude) SerializationFeature(com.fasterxml.jackson.databind.SerializationFeature) BufferedReader(java.io.BufferedReader) LogManager(org.apache.logging.log4j.LogManager) Collections(java.util.Collections) InputStream(java.io.InputStream) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) YAMLParser(com.fasterxml.jackson.dataformat.yaml.YAMLParser) IOException(java.io.IOException) InvalidFormatException(com.fasterxml.jackson.databind.exc.InvalidFormatException) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) TypeReference(com.fasterxml.jackson.core.type.TypeReference) File(java.io.File) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 4 with YAMLParser

use of com.fasterxml.jackson.dataformat.yaml.YAMLParser in project strimzi-kafka-operator by strimzi.

the class TestUtils method configMapFromYaml.

public static ConfigMap configMapFromYaml(String yamlPath, String name) {
    try {
        YAMLFactory yaml = new YAMLFactory();
        ObjectMapper mapper = new ObjectMapper(yaml);
        YAMLParser yamlParser = yaml.createParser(new File(yamlPath));
        List<ConfigMap> list = mapper.readValues(yamlParser, new TypeReference<ConfigMap>() {
        }).readAll();
        Optional<ConfigMap> cmOpt = list.stream().filter(cm -> "ConfigMap".equals(cm.getKind()) && name.equals(cm.getMetadata().getName())).findFirst();
        if (cmOpt.isPresent()) {
            return cmOpt.get();
        } else {
            LOGGER.warn("ConfigMap {} not found in file {}", name, yamlPath);
            return null;
        }
    } catch (InvalidFormatException e) {
        throw new IllegalArgumentException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : VertxException(io.vertx.core.VertxException) CoreMatchers.is(org.hamcrest.CoreMatchers.is) YAMLGenerator(com.fasterxml.jackson.dataformat.yaml.YAMLGenerator) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) BooleanSupplier(java.util.function.BooleanSupplier) YAMLMapper(com.fasterxml.jackson.dataformat.yaml.YAMLMapper) Arrays.asList(java.util.Arrays.asList) Duration(java.time.Duration) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) Collector(java.util.stream.Collector) TypeReference(com.fasterxml.jackson.core.type.TypeReference) PrintWriter(java.io.PrintWriter) Set(java.util.Set) Reader(java.io.Reader) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Writer(java.io.Writer) Optional(java.util.Optional) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) InvalidFormatException(com.fasterxml.jackson.databind.exc.InvalidFormatException) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) OwnerReference(io.fabric8.kubernetes.api.model.OwnerReference) Function(java.util.function.Function) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) HashSet(java.util.HashSet) Charset(java.nio.charset.Charset) YAMLParser(com.fasterxml.jackson.dataformat.yaml.YAMLParser) StringTokenizer(java.util.StringTokenizer) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) OutputStreamWriter(java.io.OutputStreamWriter) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Files(java.nio.file.Files) BufferedWriter(java.io.BufferedWriter) StringWriter(java.io.StringWriter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) FileOutputStream(java.io.FileOutputStream) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) UnknownHostException(java.net.UnknownHostException) File(java.io.File) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) AbstractMap(java.util.AbstractMap) Paths(java.nio.file.Paths) JsonInclude(com.fasterxml.jackson.annotation.JsonInclude) SerializationFeature(com.fasterxml.jackson.databind.SerializationFeature) BufferedReader(java.io.BufferedReader) LogManager(org.apache.logging.log4j.LogManager) Collections(java.util.Collections) InputStream(java.io.InputStream) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) YAMLParser(com.fasterxml.jackson.dataformat.yaml.YAMLParser) IOException(java.io.IOException) InvalidFormatException(com.fasterxml.jackson.databind.exc.InvalidFormatException) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) TypeReference(com.fasterxml.jackson.core.type.TypeReference) File(java.io.File) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 5 with YAMLParser

use of com.fasterxml.jackson.dataformat.yaml.YAMLParser in project pancm_project by xuwujing.

the class TransferUtils method yml2Properties.

public static Map<String, String> yml2Properties(String path) {
    final String DOT = ".";
    Map<String, String> map = new HashMap<>();
    try {
        YAMLFactory yamlFactory = new YAMLFactory();
        YAMLParser parser = yamlFactory.createParser(new InputStreamReader(new FileInputStream(path), Charset.forName(ENCODING)));
        String key = "";
        String value = null;
        JsonToken token = parser.nextToken();
        while (token != null) {
            if (JsonToken.START_OBJECT.equals(token)) {
            // do nothing
            } else if (JsonToken.FIELD_NAME.equals(token)) {
                if (key.length() > 0) {
                    key = key + DOT;
                }
                key = key + parser.getCurrentName();
                token = parser.nextToken();
                if (JsonToken.START_OBJECT.equals(token)) {
                    continue;
                }
                value = parser.getText();
                map.put(key, value);
                int dotOffset = key.lastIndexOf(DOT);
                if (dotOffset > 0) {
                    key = key.substring(0, dotOffset);
                }
                value = null;
            } else if (JsonToken.END_OBJECT.equals(token)) {
                int dotOffset = key.lastIndexOf(DOT);
                if (dotOffset > 0) {
                    key = key.substring(0, dotOffset);
                } else {
                    key = "";
                }
            }
            token = parser.nextToken();
        }
        parser.close();
        System.out.println(map);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return map;
}
Also used : InputStreamReader(java.io.InputStreamReader) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) YAMLParser(com.fasterxml.jackson.dataformat.yaml.YAMLParser) JsonToken(com.fasterxml.jackson.core.JsonToken) FileInputStream(java.io.FileInputStream)

Aggregations

YAMLFactory (com.fasterxml.jackson.dataformat.yaml.YAMLFactory)6 YAMLParser (com.fasterxml.jackson.dataformat.yaml.YAMLParser)6 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)5 TypeReference (com.fasterxml.jackson.core.type.TypeReference)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)3 IOException (java.io.IOException)3 InputStreamReader (java.io.InputStreamReader)3 JsonInclude (com.fasterxml.jackson.annotation.JsonInclude)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 DeserializationFeature (com.fasterxml.jackson.databind.DeserializationFeature)2 JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)2 SerializationFeature (com.fasterxml.jackson.databind.SerializationFeature)2 InvalidFormatException (com.fasterxml.jackson.databind.exc.InvalidFormatException)2 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)2 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)2 YAMLGenerator (com.fasterxml.jackson.dataformat.yaml.YAMLGenerator)2 YAMLMapper (com.fasterxml.jackson.dataformat.yaml.YAMLMapper)2 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)2 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)2 OwnerReference (io.fabric8.kubernetes.api.model.OwnerReference)2