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

The following examples show how to use com.fasterxml.jackson.dataformat.yaml.YAMLGenerator. 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: Directory.java    From pegasus with Apache License 2.0 7 votes vote down vote up
public static void main(String[] args) {
    ObjectMapper mapper =
            new ObjectMapper(
                    new YAMLFactory().configure(YAMLGenerator.Feature.INDENT_ARRAYS, true));
    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);
    /*SimpleModule module = new SimpleModule();
    module.addDeserializer(FileServer.class, new FileServerDeserializer());
    mapper.registerModule(module);
    */
    String test =
            "  type: sharedScratch\n"
                    + "  path: /tmp/workflows/scratch\n"
                    + "  freeSize: 1GB\n"
                    + "  totalSize: 122GB\n"
                    + "  fileServers:\n"
                    + "    - operation: all\n"
                    + "      url: file:///tmp/workflows/scratch\n";
    Directory dir = null;
    try {
        dir = mapper.readValue(test, Directory.class);
        System.out.println(dir);
        System.out.println(mapper.writeValueAsString(dir));
    } catch (IOException ex) {
        Logger.getLogger(FileServer.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example #2
Source File: MetadataTest.java    From pegasus with Apache License 2.0 6 votes vote down vote up
@Test
public void serializationWithOnlyChecksum() throws IOException {
    ObjectMapper mapper =
            new ObjectMapper(
                    new YAMLFactory().configure(YAMLGenerator.Feature.INDENT_ARRAYS, true));
    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);

    // metadata serialization can only be tested by being enclosed in a ReplicaLocation
    // object as we don't have writeStartObject in the serializer implementatio of Metadata
    ReplicaLocation rl = new ReplicaLocation();
    rl.setLFN("test");

    Metadata m = new Metadata();
    rl.addMetadata(Metadata.CHECKSUM_TYPE_KEY, "sha256");
    rl.addMetadata(Metadata.CHECKSUM_VALUE_KEY, "sdasdsadas2020");

    String expected =
            "---\n" + "lfn: \"test\"\n" + "checksum:\n" + "  sha256: \"sdasdsadas2020\"\n";

    String actual = mapper.writeValueAsString(rl);
    // System.out.println(actual);
    assertEquals(expected, actual);
}
 
Example #3
Source File: MetadataTest.java    From pegasus with Apache License 2.0 6 votes vote down vote up
@Test
public void serializationWithNoMetadata() throws IOException {
    ObjectMapper mapper =
            new ObjectMapper(
                    new YAMLFactory().configure(YAMLGenerator.Feature.INDENT_ARRAYS, true));
    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);

    // metadata serialization can only be tested by being enclosed in a ReplicaLocation
    // object as we don't have writeStartObject in the serializer implementatio of Metadata
    ReplicaLocation rl = new ReplicaLocation();
    rl.setLFN("test");

    String expected = "---\n" + "lfn: \"test\"\n";

    String actual = mapper.writeValueAsString(rl);

    assertEquals(expected, actual);
}
 
Example #4
Source File: SerializerUtils.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
public static String toYamlString(OpenAPI openAPI) {
    if (openAPI == null) {
        return null;
    }
    SimpleModule module = createModule();
    try {
        ObjectMapper yamlMapper = Yaml.mapper().copy();
        // there is an unfortunate YAML condition where user inputs should be treated as strings (e.g. "1234_1234"), but in yaml this is a valid number and
        // removing quotes forcibly by default means we are potentially doing a data conversion resulting in an unexpected change to the user's YAML outputs.
        // We may allow for property-based enable/disable, retaining the default of enabled for backward compatibility.
        if (minimizeYamlQuotes) {
            ((YAMLFactory) yamlMapper.getFactory()).enable(YAMLGenerator.Feature.MINIMIZE_QUOTES);
        } else {
            ((YAMLFactory) yamlMapper.getFactory()).disable(YAMLGenerator.Feature.MINIMIZE_QUOTES);
        }
        return yamlMapper.registerModule(module)
                .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
                .writeValueAsString(openAPI)
                .replace("\r\n", "\n");
    } catch (JsonProcessingException e) {
        LOGGER.warn("Can not create yaml content", e);
    }
    return null;
}
 
Example #5
Source File: NotificationsTest.java    From pegasus with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotificationsSerialization() throws IOException {
    ObjectMapper mapper =
            new ObjectMapper(
                    new YAMLFactory().configure(YAMLGenerator.Feature.INDENT_ARRAYS, true));
    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);

    Notifications n = new Notifications();
    n.add(new Invoke(Invoke.WHEN.start, "/bin/date"));
    n.add(new Invoke(Invoke.WHEN.end, "/bin/echo \"Finished\""));

    String expected =
            "---\n"
                    + "shell:\n"
                    + " -\n"
                    + "  _on: \"start\"\n"
                    + "  cmd: \"/bin/date\"\n"
                    + "  _on: \"end\"\n"
                    + "  cmd: \"/bin/echo \\\"Finished\\\"\"\n"
                    + "";
    String actual = mapper.writeValueAsString(n);
    System.out.println(actual);
    assertEquals(expected, actual);
}
 
Example #6
Source File: YamlParser.java    From elasticsearch-migration with Apache License 2.0 6 votes vote down vote up
private ObjectMapper createYamlMapper() {
    final YAMLFactory yamlFactory = new YAMLFactory();
    yamlFactory.configure(YAMLGenerator.Feature.WRITE_DOC_START_MARKER, false);
    yamlFactory.configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false);
    yamlFactory.configure(YAMLGenerator.Feature.LITERAL_BLOCK_STYLE, true);

    final ObjectMapper yamlMapper = new ObjectMapper(yamlFactory);
    yamlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    yamlMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);
    yamlMapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);
    yamlMapper.configure(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS, true);
    yamlMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
    yamlMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    yamlMapper.setSerializationInclusion(JsonInclude.Include.NON_ABSENT);

    yamlMapper.registerModule(new Jdk8Module());
    yamlMapper.registerModule(new JavaTimeModule());

    return yamlMapper;
}
 
Example #7
Source File: NotificationsTest.java    From pegasus with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotificationsDeserialization() throws IOException {
    ObjectMapper mapper =
            new ObjectMapper(
                    new YAMLFactory().configure(YAMLGenerator.Feature.INDENT_ARRAYS, true));
    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);

    String test = // "hooks:\n"
            "  shell:\n"
                    + "    - _on: start\n"
                    + "      cmd: /bin/date\n"
                    + "    - _on: end\n"
                    + "      cmd: /bin/echo \"Finished\"\n";

    Notifications n = mapper.readValue(test, Notifications.class);
    assertNotNull(n);
    assertTrue(n.contains(new Invoke(Invoke.WHEN.start, "/bin/date")));
    assertTrue(n.contains(new Invoke(Invoke.WHEN.end, "/bin/echo \"Finished\"")));
}
 
Example #8
Source File: SingularityRunnerBaseModule.java    From Singularity with Apache License 2.0 6 votes vote down vote up
@Provides
@Singleton
@Named(YAML)
public ObjectMapper providesYamlMapper() {
  final YAMLFactory yamlFactory = new YAMLFactory();
  yamlFactory.disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER);

  final ObjectMapper mapper = new ObjectMapper(yamlFactory);
  mapper.setSerializationInclusion(JsonInclude.Include.NON_ABSENT);
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  mapper.registerModule(new GuavaModule());
  mapper.registerModule(new ProtobufModule());
  mapper.registerModule(new Jdk8Module());

  return mapper;
}
 
Example #9
Source File: GridGatewayTest.java    From pegasus with Apache License 2.0 6 votes vote down vote up
@Test
public void testGridGatewaySerialization() throws IOException {
    GridGateway gw = new GridGateway();
    gw.setArchitecture(SysInfo.Architecture.x86_64);
    gw.setIdleNodes(3);
    gw.setTotalNodes(40);
    gw.setContact("smarty.isi.edu/jobmanager-pbs");
    gw.setJobType(GridGateway.JOB_TYPE.compute);
    gw.setScheduler(GridGateway.SCHEDULER_TYPE.pbs);
    ObjectMapper mapper =
            new ObjectMapper(
                    new YAMLFactory().configure(YAMLGenerator.Feature.INDENT_ARRAYS, true));
    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);
    String expected =
            "---\n"
                    + "type: \"gt2\"\n"
                    + "contact: \"smarty.isi.edu/jobmanager-pbs\"\n"
                    + "scheduler: \"pbs\"\n"
                    + "jobtype: \"compute\"\n"
                    + "idleNodes: 3\n"
                    + "totalNodes: 40\n";
    String actual = mapper.writeValueAsString(gw);
    assertEquals(expected, actual);
}
 
Example #10
Source File: FileServerTest.java    From pegasus with Apache License 2.0 6 votes vote down vote up
@Test
public void testFileServerSerialization() throws IOException {
    ObjectMapper mapper =
            new ObjectMapper(
                    new YAMLFactory().configure(YAMLGenerator.Feature.INDENT_ARRAYS, true));
    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);

    FileServer fs = new FileServer();
    fs.setSupportedOperation(FileServerType.OPERATION.get);
    PegasusURL url = new PegasusURL("http://test.isi.edu/shared/data/scratch");
    fs.setURLPrefix(url.getURLPrefix());
    fs.setProtocol(url.getProtocol());
    fs.setMountPoint(url.getPath());

    String expected =
            "---\n"
                    + "operation: \"get\"\n"
                    + "url: \"http://test.isi.edu/shared/data/scratch\"\n";
    String actual = mapper.writeValueAsString(fs);
    System.err.println(actual);
    assertEquals(expected, actual);
}
 
Example #11
Source File: TransformationCatalogEntryTest.java    From pegasus with Apache License 2.0 5 votes vote down vote up
@Test
public void serializeBaseEntryWithMetadataAndChecksum() throws IOException {
    ObjectMapper mapper =
            new ObjectMapper(
                    new YAMLFactory().configure(YAMLGenerator.Feature.INDENT_ARRAYS, true));
    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);

    TransformationCatalogEntry entry = new TransformationCatalogEntry("example", "keg", "1.0");
    entry.addProfile(new Profile(Profiles.NAMESPACES.metadata.toString(), "user", "vahi"));
    entry.addProfile(
            new Profile(
                    Profiles.NAMESPACES.metadata.toString(),
                    Metadata.CHECKSUM_TYPE_KEY,
                    "sha256"));
    entry.addProfile(
            new Profile(
                    Profiles.NAMESPACES.metadata.toString(),
                    Metadata.CHECKSUM_VALUE_KEY,
                    "dsadsadsa093232"));

    String expected =
            "---\n"
                    + "namespace: \"example\"\n"
                    + "name: \"keg\"\n"
                    + "version: \"1.0\"\n"
                    + "checksum:\n"
                    + "  sha256: \"dsadsadsa093232\"\n"
                    + "metadata:\n"
                    + "  user: \"vahi\"\n";
    String actual = mapper.writeValueAsString(entry);
    // System.err.println(actual);
    assertEquals(expected, actual);
}
 
Example #12
Source File: HttpCallIT.java    From digdag with Apache License 2.0 5 votes vote down vote up
private String formatYaml(Config value)
{
    try {
        StringWriter writer = new StringWriter();
        try (YAMLGenerator out = new YAMLFactory().createGenerator(writer)) {
            objectMapper().writeValue(out, value);
        }
        return writer.toString();
    }
    catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #13
Source File: YamlMapper.java    From digdag with Apache License 2.0 5 votes vote down vote up
@Inject
public YamlMapper(ObjectMapper mapper)
{
    this.yaml = new YAMLFactory()
        .configure(YAMLGenerator.Feature.WRITE_DOC_START_MARKER, false);
    this.mapper = mapper;
}
 
Example #14
Source File: YamlMapper.java    From digdag with Apache License 2.0 5 votes vote down vote up
public <T> void writeFile(File file, T value)
    throws IOException
{
    file.getParentFile().mkdirs();
    // TODO use yaml if file path ends with dig or yml, otherwise use json?
    try (YAMLGenerator out = yaml.createGenerator(new FileOutputStream(file))) {
        // TODO write to a String first, then write to file. to not create partially-written broken file
        mapper.writeValue(out, value);
    }
}
 
Example #15
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 #16
Source File: SiteCatalogEntry.java    From pegasus with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    ObjectMapper mapper =
            new ObjectMapper(
                    new YAMLFactory().configure(YAMLGenerator.Feature.INDENT_ARRAYS, true));
    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);

    String test =
            "name: condor_pool\n"
                    + "arch: x86_64\n"
                    + "os.type: linux\n"
                    + "grids:\n"
                    + "  - type: gt5\n"
                    + "    contact: smarty.isi.edu/jobmanager-pbs\n"
                    + "    scheduler: pbs\n"
                    + "    jobtype: auxillary\n"
                    + "  - type: gt5\n"
                    + "    contact: smarty.isi/edu/jobmanager-pbs\n"
                    + "    scheduler: pbs\n"
                    + "    jobtype: compute\n"
                    + "directories:\n"
                    + "  - type: sharedScratch\n"
                    + "    path: /lustre\n"
                    + "    fileServers:\n"
                    + "      - operation: all\n"
                    + "        url: gsiftp://smarty.isi.edu/lustre\n"
                    + "profiles:\n"
                    + "  env:\n"
                    + "    PATH: /usr/bin:/bin\n"
                    + "  pegasus:\n"
                    + "    clusters.num: 1\n"
                    + "  x-ext: true";
    try {
        SiteCatalogEntry site = mapper.readValue(test, SiteCatalogEntry.class);
        System.out.println(site);
        System.out.println(mapper.writeValueAsString(site));
    } catch (IOException ex) {
        Logger.getLogger(FileServer.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example #17
Source File: DirectoryTest.java    From pegasus with Apache License 2.0 5 votes vote down vote up
@Test
public void testDirectorySerialization() throws IOException {
    ObjectMapper mapper =
            new ObjectMapper(
                    new YAMLFactory().configure(YAMLGenerator.Feature.INDENT_ARRAYS, true));
    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);

    Directory dir = new Directory();
    dir.setType(Directory.TYPE.shared_scratch);
    dir.setInternalMountPoint(
            new InternalMountPoint("/mount/workflows/scratch", "122GB", "1GB"));
    FileServer fs = new FileServer();
    fs.setSupportedOperation(FileServerType.OPERATION.get);
    PegasusURL url = new PegasusURL("/tmp/workflows/scratch");
    fs.setURLPrefix(url.getURLPrefix());
    fs.setProtocol(url.getProtocol());
    fs.setMountPoint(url.getPath());
    dir.addFileServer(fs);

    String expected =
            "---\n"
                    + "type: \"sharedScratch\"\n"
                    + "path: \"/mount/workflows/scratch\"\n"
                    + "freeSize: \"1GB\"\n"
                    + "totalSize: \"122GB\"\n"
                    + "fileServers:\n"
                    + " -\n"
                    + "  operation: \"get\"\n"
                    + "  url: \"file:///tmp/workflows/scratch\"\n";
    String actual = mapper.writeValueAsString(dir);
    // System.err.println(actual);
    assertEquals(expected, actual);
}
 
Example #18
Source File: TransformationCatalogEntryTest.java    From pegasus with Apache License 2.0 5 votes vote down vote up
@Test
public void serializeBaseEntryWithProfilesAndHooks() throws IOException {
    ObjectMapper mapper =
            new ObjectMapper(
                    new YAMLFactory().configure(YAMLGenerator.Feature.INDENT_ARRAYS, true));
    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);

    TransformationCatalogEntry entry = new TransformationCatalogEntry("example", "keg", "1.0");
    entry.addProfile(
            new Profile(Profiles.NAMESPACES.env.toString(), "JAVA_HOME", "/opt/java/1.6"));

    entry.addNotification(new Invoke(Invoke.WHEN.end, "echo Test"));

    String expected =
            "---\n"
                    + "namespace: \"example\"\n"
                    + "name: \"keg\"\n"
                    + "version: \"1.0\"\n"
                    + "hooks:\n"
                    + "  shell:\n"
                    + "   -\n"
                    + "    _on: \"end\"\n"
                    + "    cmd: \"echo Test\"\n"
                    + "profiles:\n"
                    + "  env:\n"
                    + "    JAVA_HOME: \"/opt/java/1.6\"\n"
                    + "";
    String actual = mapper.writeValueAsString(entry);
    // System.err.println(actual);
    assertEquals(expected, actual);
}
 
Example #19
Source File: YamlMapper.java    From digdag with Apache License 2.0 5 votes vote down vote up
public <T> String toYaml(T value)
{
    try {
        StringWriter writer = new StringWriter();
        try (YAMLGenerator out = yaml.createGenerator(writer)) {
            mapper.writeValue(out, value);
        }
        return writer.toString();
    }
    catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #20
Source File: TransformationCatalogEntryTest.java    From pegasus with Apache License 2.0 5 votes vote down vote up
@Test
public void serializeEntryWithContainerReference() throws IOException {
    ObjectMapper mapper =
            new ObjectMapper(
                    new YAMLFactory().configure(YAMLGenerator.Feature.INDENT_ARRAYS, true));
    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);

    TransformationCatalogEntry entry = new TransformationCatalogEntry("example", "keg", "1.0");
    entry.setPhysicalTransformation("/usr/bin/keg");
    entry.setResourceId("isi");
    entry.setContainer(new Container("centos-pegasus"));

    String expected =
            "---\n"
                    + "namespace: \"example\"\n"
                    + "name: \"keg\"\n"
                    + "version: \"1.0\"\n"
                    + "sites:\n"
                    + " -\n"
                    + "  name: \"isi\"\n"
                    + "  type: \"installed\"\n"
                    + "  pfn: \"/usr/bin/keg\"\n"
                    + "  arch: \"x86_64\"\n"
                    + "  os.type: \"linux\"\n"
                    + "  container: \"centos-pegasus\"\n";
    String actual = mapper.writeValueAsString(entry);
    // System.err.println(actual);
    assertEquals(expected, actual);
}
 
Example #21
Source File: ContainerTest.java    From pegasus with Apache License 2.0 5 votes vote down vote up
@Test
public void serializeContainer() throws IOException {
    ObjectMapper mapper =
            new ObjectMapper(
                    new YAMLFactory().configure(YAMLGenerator.Feature.INDENT_ARRAYS, true));
    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);
    Container c = new Container();
    c.setName("centos-pegasus");
    c.setImageSite("dockerhub");
    c.setImageURL("docker:///rynge/montage:latest");
    c.setType(Container.TYPE.docker);
    c.addMountPoint("/Volumes/Work/lfs1:/shared-data/:ro");
    c.addMountPoint("/Volumes/Work/lfs12:/shared-data1/:ro");
    c.addProfile(new Profile(Profiles.NAMESPACES.env.toString(), "JAVA_HOME", "/opt/java/1.6"));

    String expected =
            "---\n"
                    + "name: \"centos-pegasus\"\n"
                    + "type: \"docker\"\n"
                    + "image: \"docker:///rynge/montage:latest\"\n"
                    + "image.site: \"dockerhub\"\n"
                    + "mounts:\n"
                    + " - \"/Volumes/Work/lfs1:/shared-data/:ro\"\n"
                    + " - \"/Volumes/Work/lfs12:/shared-data1/:ro\"\n"
                    + "profiles:\n"
                    + "  env:\n"
                    + "    JAVA_HOME: \"/opt/java/1.6\"\n";

    String actual = mapper.writeValueAsString(c);
    assertEquals(expected, actual);
}
 
Example #22
Source File: ContainerTest.java    From pegasus with Apache License 2.0 5 votes vote down vote up
@Test
public void serializeContainerChecksum() throws IOException {
    ObjectMapper mapper =
            new ObjectMapper(
                    new YAMLFactory().configure(YAMLGenerator.Feature.INDENT_ARRAYS, true));
    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);
    Container c = new Container();
    c.setName("centos-pegasus");
    c.setImageSite("dockerhub");
    c.setImageURL("docker:///rynge/montage:latest");
    c.setType(Container.TYPE.docker);
    c.addProfile(
            new Profile(
                    Profiles.NAMESPACES.metadata.toString(),
                    Metadata.CHECKSUM_TYPE_KEY,
                    "sha256"));
    c.addProfile(
            new Profile(
                    Profiles.NAMESPACES.metadata.toString(),
                    Metadata.CHECKSUM_VALUE_KEY,
                    "dsadsadsa093232"));
    String expected =
            "---\n"
                    + "name: \"centos-pegasus\"\n"
                    + "type: \"docker\"\n"
                    + "image: \"docker:///rynge/montage:latest\"\n"
                    + "image.site: \"dockerhub\"\n"
                    + "checksum:\n"
                    + "  sha256: \"dsadsadsa093232\"\n";

    String actual = mapper.writeValueAsString(c);
    // System.err.println(actual);
    assertEquals(expected, actual);
}
 
Example #23
Source File: MetadataTest.java    From pegasus with Apache License 2.0 5 votes vote down vote up
@Test
public void serializationWithOnlyMetadata() throws IOException {
    ObjectMapper mapper =
            new ObjectMapper(
                    new YAMLFactory().configure(YAMLGenerator.Feature.INDENT_ARRAYS, true));
    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);

    // metadata serialization can only be tested by being enclosed in a ReplicaLocation
    // object as we don't have writeStartObject in the serializer implementatio of Metadata
    ReplicaLocation rl = new ReplicaLocation();
    rl.setLFN("test");

    Metadata m = new Metadata();
    rl.addMetadata("user", "vahi");
    rl.addMetadata("year", "2020");

    String expected =
            "---\n"
                    + "lfn: \"test\"\n"
                    + "metadata:\n"
                    + "  year: \"2020\"\n"
                    + "  user: \"vahi\"\n";

    String actual = mapper.writeValueAsString(rl);

    assertEquals(expected, actual);
}
 
Example #24
Source File: MetadataTest.java    From pegasus with Apache License 2.0 5 votes vote down vote up
@Test
public void serializationWithBothChecksumAndMetadata() throws IOException {
    ObjectMapper mapper =
            new ObjectMapper(
                    new YAMLFactory().configure(YAMLGenerator.Feature.INDENT_ARRAYS, true));
    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);

    // metadata serialization can only be tested by being enclosed in a ReplicaLocation
    // object as we don't have writeStartObject in the serializer implementatio of Metadata
    ReplicaLocation rl = new ReplicaLocation();
    rl.setLFN("test");

    Metadata m = new Metadata();
    rl.addMetadata("user", "vahi");
    rl.addMetadata("year", "2020");
    rl.addMetadata(Metadata.CHECKSUM_TYPE_KEY, "sha256");
    rl.addMetadata(Metadata.CHECKSUM_VALUE_KEY, "sdasdsadas2020");

    String expected =
            "---\n"
                    + "lfn: \"test\"\n"
                    + "checksum:\n"
                    + "  sha256: \"sdasdsadas2020\"\n"
                    + "metadata:\n"
                    + "  year: \"2020\"\n"
                    + "  user: \"vahi\"\n";

    String actual = mapper.writeValueAsString(rl);
    // System.out.println(actual);
    assertEquals(expected, actual);
}
 
Example #25
Source File: HttpCallOperatorFactory.java    From digdag with Apache License 2.0 5 votes vote down vote up
@Inject
public HttpCallOperatorFactory(ConfigFactory cf,
        Config systemConfig, @Environment Map<String, String> env)
{
    super(systemConfig, env);
    this.cf = cf;
    this.mapper = new ObjectMapper();
    this.yaml = new YAMLFactory()
        .configure(YAMLGenerator.Feature.WRITE_DOC_START_MARKER, false);
    this.projectLoader = new ProjectArchiveLoader(
            new ConfigLoaderManager(
                cf,
                new YamlConfigLoader()));
    this.maxResponseContentSize = systemConfig.get("config.http_call.max_response_content_size", int.class, 64 * 1024);
}
 
Example #26
Source File: YamlSourceLoader.java    From camel-k-runtime with Apache License 2.0 5 votes vote down vote up
public YamlSourceLoader() {
    YAMLFactory yamlFactory = new YAMLFactory()
        .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true)
        .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false);

    this.mapper = new ObjectMapper(yamlFactory)
        .registerModule(new YamlModule())
        .setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
        .setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE)
        .enable(MapperFeature.USE_GETTERS_AS_SETTERS)
        .disable(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS)
        .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
        .enable(SerializationFeature.INDENT_OUTPUT);
}
 
Example #27
Source File: SwaggerYamlGenerator.java    From TypeScript-Microservices with MIT License 5 votes vote down vote up
@Override
public void processSwagger(Swagger swagger) {
    try {
        final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()
                .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true)
                .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true));
        configureMapper(mapper);
        String swaggerString = mapper.writeValueAsString(swagger);
        String outputFile = outputFolder + File.separator + this.outputFile;
        FileUtils.writeStringToFile(new File(outputFile), swaggerString);
        LOGGER.debug("wrote file to " + outputFile);
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
}
 
Example #28
Source File: RuleToYamlConverter.java    From yare with MIT License 5 votes vote down vote up
public static ObjectMapper createObjectMapper() {
    YAMLFactory yamlFactory = new YAMLFactory();
    yamlFactory.disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER);
    ObjectMapper objectMapper = new ObjectMapper(yamlFactory);
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
    return objectMapper;
}
 
Example #29
Source File: TestJsonYamlDictionaryStructureLoader.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testYamlSerialize() throws Exception {
    // Disabled USE_NATIVE_OBJECT_ID because YAMLFactory write reference like '*N1' on default
    ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory().disable(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID).disable(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID));


    String file = Paths.get(getBaseDir(), "src", "test", "resources", "native.json").toString();
    JsonYamlDictionary dictionary = new JsonYamlDictionaryStructureLoader().getDictionary(new FileInputStream(file));
    String jsonStr = objectMapper.writerFor(JsonYamlDictionary.class).withDefaultPrettyPrinter().writeValueAsString(dictionary);


    System.out.println(testNativeDictionary(new JsonYamlDictionaryStructureLoader().convert(new JsonYamlDictionaryStructureLoader().getDictionary(new ByteArrayInputStream(jsonStr.getBytes())))));
    System.out.println(jsonStr);
}
 
Example #30
Source File: YamlHelper.java    From funktion-connectors with Apache License 2.0 5 votes vote down vote up
public static ObjectMapper createYamlMapper() {
    ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()
            .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true)
            .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true)
            .configure(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID, false)
            .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false)
    );
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY).
            enable(SerializationFeature.INDENT_OUTPUT).
            disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS).
            disable(SerializationFeature.WRITE_NULL_MAP_VALUES);
    return objectMapper;

}