com.fasterxml.jackson.dataformat.yaml.YAMLMapper Java Examples

The following examples show how to use com.fasterxml.jackson.dataformat.yaml.YAMLMapper. 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: JsonSchemaPreProcessor.java    From liiklus with MIT License 6 votes vote down vote up
public JsonSchemaPreProcessor(URL schemaURL, JsonPointer eventTypePointer, boolean allowDeprecatedProperties) {
    this.eventTypePointer = eventTypePointer;

    var jsonSchemaFactoryBuilder = JsonSchemaFactory.builder(JsonSchemaFactory.getInstance());

    var jsonMetaSchemaBuilder = JsonMetaSchema.builder(JsonMetaSchema.getDraftV4().getUri(), JsonMetaSchema.getDraftV4());
    if (!allowDeprecatedProperties) {
        jsonMetaSchemaBuilder.addKeyword(new DeprecatedKeyword());
    }

    jsonSchemaFactoryBuilder.addMetaSchema(jsonMetaSchemaBuilder.build());

    this.jsonSchemaFactory = jsonSchemaFactoryBuilder
            .urlFetcher(url -> new ByteArrayInputStream(JSON_MAPPER.writeValueAsBytes(new YAMLMapper().readTree(url))))
            .build();

    this.schema = jsonSchemaFactory.getSchema(schemaURL);
}
 
Example #2
Source File: PackageMetadataService.java    From spring-cloud-skipper with Apache License 2.0 6 votes vote down vote up
protected List<PackageMetadata> deserializeFromIndexFiles(List<File> indexFiles) {
	List<PackageMetadata> packageMetadataList = new ArrayList<>();
	YAMLMapper yamlMapper = new YAMLMapper();
	yamlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	for (File indexFile : indexFiles) {
		try {
			MappingIterator<PackageMetadata> it = yamlMapper.readerFor(PackageMetadata.class).readValues(indexFile);
			while (it.hasNextValue()) {
				PackageMetadata packageMetadata = it.next();
				packageMetadataList.add(packageMetadata);
			}
		}
		catch (IOException e) {
			throw new IllegalArgumentException("Can't parse Release manifest YAML", e);
		}
	}
	return packageMetadataList;
}
 
Example #3
Source File: FileLibraryResolver.java    From Arend with Apache License 2.0 6 votes vote down vote up
private FileLoadableHeaderLibrary getLibrary(Path headerFile) {
  try {
    LibraryConfig config = new YAMLMapper().readValue(headerFile.toFile(), LibraryConfig.class);
    if (config.getName() == null) {
      Path parent = headerFile.getParent();
      Path fileName = parent == null ? null : parent.getFileName();
      if (fileName != null) {
        config.setName(fileName.toString());
      } else {
        return null;
      }
    }
    if (config.getSourcesDir() == null) {
      config.setSourcesDir(headerFile.getParent().toString());
    }
    return new FileLoadableHeaderLibrary(config, headerFile, myTypecheckerState);
  } catch (IOException e) {
    myErrorReporter.report(new LibraryIOError(headerFile.toString(), "Failed to read header file", e.getLocalizedMessage()));
    return null;
  }
}
 
Example #4
Source File: PodlockParser.java    From hub-detect with Apache License 2.0 6 votes vote down vote up
public DependencyGraph extractDependencyGraph(final String podLockText) throws IOException {
    final LazyExternalIdDependencyGraphBuilder lazyBuilder = new LazyExternalIdDependencyGraphBuilder();
    final YAMLMapper mapper = new YAMLMapper();
    final PodfileLock podfileLock = mapper.readValue(podLockText, PodfileLock.class);

    final Map<DependencyId, Forge> forgeOverrides = createForgeOverrideMap(podfileLock);

    for (final Pod pod : podfileLock.pods) {
        logger.trace(String.format("Processing pod %s", pod.name));
        processPod(pod, forgeOverrides, lazyBuilder);
    }

    for (final Pod dependency : podfileLock.dependencies) {
        logger.trace(String.format("Processing pod dependency from pod lock file %s", dependency.name));
        final String podText = dependency.name;
        final Optional<DependencyId> dependencyId = parseDependencyId(podText);
        if (dependencyId.isPresent()) {
            lazyBuilder.addChildToRoot(dependencyId.get());
        }
    }
    logger.trace("Attempting to build the dependency graph.");
    final DependencyGraph dependencyGraph = lazyBuilder.build();
    logger.trace("Completed the dependency graph.");
    return dependencyGraph;
}
 
Example #5
Source File: ClassWithInterfaceFieldsRegistry.java    From istio-java-api with Apache License 2.0 6 votes vote down vote up
Object deserialize(JsonNode node, String fieldName, Class targetClass, DeserializationContext ctxt) throws IOException {
    final String type = getFieldClassFQN(targetClass, valueType);
    try {
        // load class of the field
        final Class<?> fieldClass = Thread.currentThread().getContextClassLoader().loadClass(type);
        // create a map type matching the type of the field from the mapping information
        final YAMLMapper codec = (YAMLMapper) ctxt.getParser().getCodec();
        MapType mapType = codec.getTypeFactory().constructMapType(Map.class, String.class, fieldClass);
        // get a parser taking the current value as root
        final JsonParser traverse = node.get(fieldName).traverse(codec);
        // and use it to deserialize the subtree as the map type we just created
        return codec.readValue(traverse, mapType);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Unsupported type '" + type + "' for field '" + fieldName +
                "' on '" + targetClass.getName() + "' class. Full type was " + this, e);
    }
}
 
Example #6
Source File: ConfigFileWriterTest.java    From streamline with Apache License 2.0 6 votes vote down vote up
@Test
public void writeYamlConfigToFile() throws Exception {
  Map<String, String> configuration = createDummyConfiguration();

  File destPath = Files.createTempFile("config", "yaml").toFile();
  destPath.deleteOnExit();

  writer.writeConfigToFile(ConfigFileType.YAML, configuration, destPath);
  assertTrue(destPath.exists());
  try (InputStream is = new FileInputStream(destPath)) {
    String content = IOUtils.toString(is);
    System.out.println("Test print: yaml content - " + content);

    ObjectMapper mapper = new YAMLMapper();
    Map<String, Object> readConfig = mapper.readValue(content, Map.class);

    assertEquals(configuration, readConfig);
  }
}
 
Example #7
Source File: TestUtils.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
public static String changeDeploymentNamespaceUpgrade(File deploymentFile, String namespace) {
    YAMLMapper mapper = new YAMLMapper();
    try {
        JsonNode node = mapper.readTree(deploymentFile);
        // Change the docker org of the images in the 050-deployment.yaml
        ObjectNode containerNode = (ObjectNode) node.at("/spec/template/spec/containers").get(0);
        for (JsonNode envVar : containerNode.get("env")) {
            String varName = envVar.get("name").textValue();
            if (varName.matches("STRIMZI_NAMESPACE")) {
                // Replace all the default images with ones from the $DOCKER_ORG org and with the $DOCKER_TAG tag
                ((ObjectNode) envVar).remove("valueFrom");
                ((ObjectNode) envVar).put("value", namespace);
            }
            if (varName.matches("STRIMZI_LOG_LEVEL")) {
                ((ObjectNode) envVar).put("value", "DEBUG");
            }
        }
        return mapper.writeValueAsString(node);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #8
Source File: PodlockParser.java    From synopsys-detect with Apache License 2.0 6 votes vote down vote up
public DependencyGraph extractDependencyGraph(final String podLockText) throws IOException, MissingExternalIdException {
    final LazyExternalIdDependencyGraphBuilder lazyBuilder = new LazyExternalIdDependencyGraphBuilder();
    final YAMLMapper mapper = new YAMLMapper();
    final PodfileLock podfileLock = mapper.readValue(podLockText, PodfileLock.class);

    final Map<DependencyId, Forge> forgeOverrides = createForgeOverrideMap(podfileLock);

    for (final Pod pod : podfileLock.getPods()) {
        logger.trace(String.format("Processing pod %s", pod.getName()));
        processPod(pod, forgeOverrides, lazyBuilder);
    }

    for (final Pod dependency : podfileLock.getDependencies()) {
        logger.trace(String.format("Processing pod dependency from pod lock file %s", dependency.getName()));
        final String podText = dependency.getName();
        final Optional<DependencyId> dependencyId = parseDependencyId(podText);
        dependencyId.ifPresent(lazyBuilder::addChildToRoot);
    }
    logger.trace("Attempting to build the dependency graph.");
    final DependencyGraph dependencyGraph = lazyBuilder.build();
    logger.trace("Completed the dependency graph.");
    return dependencyGraph;
}
 
Example #9
Source File: StackTraceElementYamlMixInTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testFromYamlWithSimpleModule() throws Exception {
    final ObjectMapper mapper = new YAMLMapper();
    final SimpleModule module = new SimpleModule();
    module.addDeserializer(StackTraceElement.class, new Log4jStackTraceElementDeserializer());
    mapper.registerModule(module);
    final StackTraceElement expected = new StackTraceElement("package.SomeClass", "someMethod", "SomeClass.java",
            123);
    final StackTraceElement actual = mapper.readValue(
            "---\nclass: package.SomeClass\nmethod: someMethod\nfile: SomeClass.java\nline: 123\n...",
            StackTraceElement.class);
    Assert.assertEquals(expected, actual);
}
 
Example #10
Source File: TestWorkflowProcess.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
private static void printAsYaml(JsonNode node) {
    try {
        String yaml = new YAMLMapper().writeValueAsString(node);
        System.out.println("YAML DATA");
        System.out.println(yaml);
    } catch (JsonProcessingException e) {
        System.err.println("Error writing JsonNode to YAML");
    }
}
 
Example #11
Source File: Braindump.java    From pegasus with Apache License 2.0 5 votes vote down vote up
/**
 * Writes out the braindump.txt file for a workflow in the submit directory. The braindump.txt
 * file is used for passing to the tailstatd daemon that monitors the state of execution of the
 * workflow.
 *
 * @param entries the Map containing the entries going into the braindump file.
 * @return the absolute path to the braindump file.txt written in the directory.
 * @throws IOException in case of error while writing out file.
 */
protected File writeOutBraindumpFile(Map<String, String> entries) throws IOException {
    File f = new File(mSubmitFileDir, BRAINDUMP_FILE);
    YAMLMapper mapper = new YAMLMapper();
    mapper.configure(Feature.WRITE_DOC_START_MARKER, false);
    // SPLIT_LINES feature needs to be disabled until Perl code is deprecated.
    mapper.configure(Feature.SPLIT_LINES, false);
    SequenceWriter writer = mapper.writerWithDefaultPrettyPrinter().writeValues(f);
    writer.write(entries);

    return f;
}
 
Example #12
Source File: StackTraceElementYamlMixInTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testFromYamlWithLog4jModule() throws Exception {
    final ObjectMapper mapper = new YAMLMapper();
    final boolean encodeThreadContextAsList = false;
    final SimpleModule module = new Log4jYamlModule(encodeThreadContextAsList, true, false);
    module.addDeserializer(StackTraceElement.class, new Log4jStackTraceElementDeserializer());
    mapper.registerModule(module);
    final StackTraceElement expected = new StackTraceElement("package.SomeClass", "someMethod", "SomeClass.java",
            123);
    final StackTraceElement actual = mapper.readValue(
            "---\nclass: package.SomeClass\nmethod: someMethod\nfile: SomeClass.java\nline: 123\n...",
            StackTraceElement.class);
    Assert.assertEquals(expected, actual);
}
 
Example #13
Source File: SwaggerWsdlHelper.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * Transforms a jsonNode to a prettified json or yaml string depending on the api definition type
 *
 * @param jsonNode   jsonNode to prettify
 * @param apiVersion apiVersion to determine the definition type
 * @return prettified swagger definition as yaml or json string
 */
private static String jsonNodeToString(JsonNode jsonNode, ApiVersionBean apiVersion) {
    String prettifiedSwaggerDefinition = null;
    try {
        if (apiVersion.getDefinitionType() == ApiDefinitionType.SwaggerJSON) {
            prettifiedSwaggerDefinition = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
        } else if (apiVersion.getDefinitionType() == ApiDefinitionType.SwaggerYAML) {
            prettifiedSwaggerDefinition = new YAMLMapper().writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
        }
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return prettifiedSwaggerDefinition;
}
 
Example #14
Source File: CommonUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Converts JSON to YAML.
 *
 * @param json json representation
 * @return json file as a yaml document
 * @throws IOException If an error occurs while converting JSON to YAML
 */
public static String jsonToYaml(String json) throws IOException {

    ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory()
            .enable(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER));
    JsonNode jsonNodeTree = yamlReader.readTree(json);
    YAMLMapper yamlMapper = new YAMLMapper()
            .disable(YAMLGenerator.Feature.SPLIT_LINES)
            .enable(YAMLGenerator.Feature.INDENT_ARRAYS)
            .disable(YAMLGenerator.Feature.LITERAL_BLOCK_STYLE)
            .disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER)
            .enable(YAMLGenerator.Feature.MINIMIZE_QUOTES)
            .enable(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS);
    return yamlMapper.writeValueAsString(jsonNodeTree);
}
 
Example #15
Source File: YamlConverter.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Convert json to yaml
 * @param jsonReader the reader of json
 * @return the text of yaml
 */
public static String convertJsonToYaml(Reader jsonReader) {
    try (Reader reader = jsonReader) {
        JsonNode json = new ObjectMapper().readTree(reader);

        return new YAMLMapper().writeValueAsString(json);
    } catch (IOException e) {
        throw new YamlRuntimeException(e);
    }
}
 
Example #16
Source File: PluginHelper.java    From fess with Apache License 2.0 5 votes vote down vote up
protected List<Artifact> loadArtifactsFromRepository(final String url) {
    final String content = getRepositoryContent(url);
    final ObjectMapper objectMapper = new YAMLMapper();
    try {
        @SuppressWarnings("unchecked")
        final List<Map<?, ?>> result = objectMapper.readValue(content, List.class);
        if (result != null) {
            return result.stream().map(o -> new Artifact((String) o.get("name"), (String) o.get("version"), (String) o.get("url")))
                    .collect(Collectors.toList());
        }
        return Collections.emptyList();
    } catch (final Exception e) {
        throw new PluginException("Failed to access " + url, e);
    }
}
 
Example #17
Source File: CommonG.java    From bdt with Apache License 2.0 5 votes vote down vote up
/**
 * Method to convert one json to yaml file - backup&restore functionality
 * <p>
 * File will be placed on path /target/test-classes
 */
public String asYaml(String jsonStringFile) throws IOException {

    InputStream stream = getClass().getClassLoader().getResourceAsStream(jsonStringFile);

    Writer writer = new StringWriter();
    char[] buffer = new char[1024];
    Reader reader;

    if (stream == null) {
        this.getLogger().error("File does not exist: {}", jsonStringFile);
        throw new FileNotFoundException("ERR! File not found: " + jsonStringFile);
    }

    try {
        reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } catch (Exception readerexception) {
        this.getLogger().error(readerexception.getMessage());
    } finally {
        try {
            stream.close();
        } catch (Exception closeException) {
            this.getLogger().error(closeException.getMessage());
        }
    }
    String text = writer.toString();

    String std = text.replace("\r", "").replace("\n", ""); // make sure we have unix style text regardless of the input

    // parse JSON
    JsonNode jsonNodeTree = new ObjectMapper().readTree(std);
    // save it as YAML
    String jsonAsYaml = new YAMLMapper().writeValueAsString(jsonNodeTree);
    return jsonAsYaml;
}
 
Example #18
Source File: OpenAPIHolderImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public OpenAPIHolderImpl(HttpClient client, FileSystem fs, OpenAPILoaderOptions options) {
  absolutePaths = new ConcurrentHashMap<>();
  externalSolvingRefs = new ConcurrentHashMap<>();
  this.client = client;
  this.fs = fs;
  this.options = options;
  this.router = SchemaRouter.create(client, fs, options.toSchemaRouterOptions());
  this.parser = Draft7SchemaParser.create(this.router);
  this.yamlMapper = new YAMLMapper();
  this.openapiSchema = parser.parseFromString(OpenAPI3Utils.openapiSchemaJson);
}
 
Example #19
Source File: QuestPackage.java    From BetonQuest-Editor with GNU General Public License v3.0 5 votes vote down vote up
public void printObjectivesYaml(OutputStream out) throws IOException {
	YAMLFactory yf = new YAMLFactory();
	YAMLMapper mapper = new YAMLMapper();
	ObjectNode root = mapper.createObjectNode();
	for (Objective objective : objectives) {
		root.put(objective.getId().get(), objective.getInstruction().get());
	}
	yf.createGenerator(out).setCodec(mapper).writeObject(root);
}
 
Example #20
Source File: KafkaUser.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    YAMLMapper mapper = new YAMLMapper();
    try {
        return mapper.writeValueAsString(this);
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #21
Source File: StreamControllerTests.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
private SpringCloudDeployerApplicationSpec parseSpec(String yamlString) throws IOException {
	YAMLMapper mapper = new YAMLMapper();
	mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	MappingIterator<SpringCloudDeployerApplicationManifest> it = mapper
			.readerFor(SpringCloudDeployerApplicationManifest.class).readValues(yamlString);
	return it.next().getSpec();
}
 
Example #22
Source File: TestUtils.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public static String getContent(File file, Function<JsonNode, String> edit) {
    YAMLMapper mapper = new YAMLMapper();
    try {
        JsonNode node = mapper.readTree(file);
        return edit.apply(node);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #23
Source File: TestUtils.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
/**
 * Changes the {@code subject} of the RoleBinding in the given YAML resource to be the
 * {@code strimzi-cluster-operator} {@code ServiceAccount} in the given namespace.
 * @param roleBindingFile
 * @param namespace
 * @return role
 */
public static String changeRoleBindingSubject(File roleBindingFile, String namespace) {
    YAMLMapper mapper = new YAMLMapper();
    try {
        JsonNode node = mapper.readTree(roleBindingFile);
        ArrayNode subjects = (ArrayNode) node.get("subjects");
        ObjectNode subject = (ObjectNode) subjects.get(0);
        subject.put("kind", "ServiceAccount")
                .put("name", "strimzi-cluster-operator")
                .put("namespace", namespace);
        return mapper.writeValueAsString(node);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #24
Source File: TestUtils.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public static <T> String toYamlString(T instance) {
    ObjectMapper mapper = new YAMLMapper()
            .disable(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID)
            .setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    try {
        return mapper.writeValueAsString(instance);
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #25
Source File: TopicCrd.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public static void main(String[] a) throws IOException {
    YAMLMapper m = new YAMLMapper();
    TopicCrd x = new TopicCrd();
    x.name = "my-topic";
    x.partitions = 12;
    x.replicas = new HashMap<>();
    for (int i = 0; i < 12; i++) {
        x.replicas.put(i, asList((i + 1) % 7, (i + 2) % 7, (i + 3) % 7));
    }
    System.out.println(m.writeValueAsString(x));

    new CrdGenerator(m).generate(TopicCrd.class, new OutputStreamWriter(System.out));
}
 
Example #26
Source File: CrdGeneratorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void generateHelmMetadataLabels() throws IOException {
    Map<String, String> labels = new LinkedHashMap<>();
    labels.put("app", "{{ template \"strimzi.name\" . }}");
    labels.put("chart", "{{ template \"strimzi.chart\" . }}");
    labels.put("component", "%plural%.%group%-crd");
    labels.put("release", "{{ .Release.Name }}");
    labels.put("heritage", "{{ .Release.Service }}");
    CrdGenerator crdGenerator = new CrdGenerator(new YAMLMapper().configure(YAMLGenerator.Feature.WRITE_DOC_START_MARKER, false), labels);
    StringWriter w = new StringWriter();
    crdGenerator.generate(ExampleCrd.class, w);
    String s = w.toString();
    assertEquals(CrdTestUtils.readResource("simpleTestHelmMetadata.yaml"), s);
}
 
Example #27
Source File: CrdGeneratorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void simpleTestWithSubresources() throws IOException, URISyntaxException {
    CrdGenerator crdGenerator = new CrdGenerator(new YAMLMapper().configure(YAMLGenerator.Feature.WRITE_DOC_START_MARKER, false));
    StringWriter w = new StringWriter();
    crdGenerator.generate(ExampleWithSubresourcesCrd.class, w);
    String s = w.toString();
    assertEquals(CrdTestUtils.readResource("simpleTestWithSubresources.yaml"), s);
}
 
Example #28
Source File: ExamplesTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
private void validateTemplate(JsonNode rootNode) throws JsonProcessingException {
    JsonNode parameters = rootNode.get("parameters");
    Map<String, Object> params = new HashMap<>();
    for (JsonNode parameter : parameters) {
        String name = parameter.get("name").asText();
        Object value;
        JsonNode valueNode = parameter.get("value");
        switch (valueNode.getNodeType()) {
            case NULL:
                value = null;
                break;
            case NUMBER:
            case BOOLEAN:
                value = valueNode.toString();
                break;
            case STRING:
                value = valueNode.asText();
                break;
            default:
                throw new RuntimeException("Unsupported JSON type " + valueNode.getNodeType());
        }
        params.put(name, value);
    }
    for (JsonNode object : rootNode.get("objects")) {
        String s = new YAMLMapper().enable(YAMLGenerator.Feature.MINIMIZE_QUOTES).enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(object);
        Matcher matcher = PARAMETER_PATTERN.matcher(s);
        StringBuilder sb = new StringBuilder();
        int last = 0;
        while (matcher.find()) {
            sb.append(s, last, matcher.start());
            String paramName = matcher.group(1);
            sb.append(params.get(paramName));
            last = matcher.end();
        }
        sb.append(s.substring(last));
        String yamlContent = sb.toString();
        validate(yamlContent);
    }
}
 
Example #29
Source File: ExamplesTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
private void validate(File f) {
    try {
        ObjectMapper mapper = new YAMLMapper();
        final String content = TestUtils.readFile(f);
        JsonNode rootNode = mapper.readTree(content);
        String resourceKind = getKind(rootNode);
        if ("Template".equals(resourceKind)) {
            validateTemplate(rootNode);
        } else {
            validate(content);
        }
    } catch (Exception | AssertionError e) {
        throw new AssertionError("Invalid example yaml in " + f.getPath() + ": " + e.getMessage(), e);
    }
}
 
Example #30
Source File: CrdGeneratorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void simpleTest() throws IOException, URISyntaxException {
    CrdGenerator crdGenerator = new CrdGenerator(new YAMLMapper().configure(YAMLGenerator.Feature.WRITE_DOC_START_MARKER, false));
    StringWriter w = new StringWriter();
    crdGenerator.generate(ExampleCrd.class, w);
    String s = w.toString();
    assertEquals(CrdTestUtils.readResource("simpleTest.yaml"), s);
}