Java com.fasterxml.jackson.dataformat.yaml.YAMLFactory 代码实例

・13 分钟阅读

以下是展示如何使用com.fasterxml.jackson.dataformat.yaml.YAMLFactory的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


/**
 * Create the ProfileWriter with the proejct name and the 
 * fig configuration. 
 * 
 * See {@link http://www.fig.sh/yml.html} for further information on the config format. 
 * 
 * @param projectName The project name, to use as variable prefix
 * @param config The fig yaml configuration as input stream
 * @throws IOException
 */
public ConfigurationWriter(String projectName, InputStream config) throws IOException {
        this.projectName = projectName;
        YAMLFactory yamlFactory = new YAMLFactory();
        ObjectMapper mapper = new ObjectMapper();
        fig = mapper.readValue(yamlFactory.createParser(config), Fig.class);
}
 

实例 2


@BeforeClass
public static void setUpBeforeClass() throws Exception {
  ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
  cfg = mapper.readValue(Thread.currentThread().getContextClassLoader().getResource("myriad-config-test-default.yml"),
      MyriadConfiguration.class);
}
 

实例 3


public T getConfig(){
    try {
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        LOGGER.info(String.format("Loading config from: %s", configFileName));
        return mapper.readValue(this.getClass().getClassLoader().getResourceAsStream(configFileName), configClass);
    }
    catch(Exception e){
        throw new RuntimeException(e);
    }
}
 

实例 4


public SimpleHttpClientExample(String configFile) {
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        try {
            UrsusHttpClientConfiguration ursusHttpClientConfiguration =
                    mapper.readValue(open(configFile), UrsusHttpClientConfiguration.class);
            HttpClient httpClient = new UrsusHttpClientBuilder().build("example", ursusHttpClientConfiguration);
            HttpResponse httpResponse = httpClient.execute(new HttpGet("http://localhost:8080/hello"));
            // Convert to POJO
            Hello hello = new ObjectMapper().readValue(httpResponse.getEntity().getContent(), Hello.class);
            System.out.println("Name is: " + hello.getName());
        } catch (IOException e) {
            throw new RuntimeException("Error parsing config file: " + e);
        }
    }
 

实例 5


@Test
public void test_complete_serialization_yaml() throws IOException {
    CompleteGrain expected = newCompleteBuilderWithSampleValues().build();
    assertEquals(28, expected.size());
    ObjectMapper mapper = JacksonTools.newGrainsObjectMapper(new YAMLFactory());
    String data = mapper.writeValueAsString(expected);
    assertEquals(
        "---|a: true|b: 1|c: 2|d: 2|e: 3|f: 1|g: 1.0|h: -1.0|i: 10|j: 'a'|k: 'hello'|l: '1bd31d66-eda2-43" +
            "95-a2a7-510bd581e3ab'|m: 'http://nullschool.net'|o: 'green'|p:|  id: 1|q:|- 1|- 2|r:|- id: 1" +
            "|- id: 2|s:|- 2|- 3|t:|- id: 2|- id: 3|u:|- 'a'|- 'b'|v:|- id: 4|- id: 5|w:|  a: 1|  b: 2|x:" +
            "|  a:|    id: 6|  b:|    id: 7|y:|- 'x'|- 'y'|z:|  1:|    id: 8|  2:|    id: 9|za:|  a:|  - " +
            "- id: 1|    - id: 2|zb:|- - 'a'|  - 'b'|- - 'c'|  - 'd'|",
        data.replace('"', ''').replace('n', '|'));  // replace quotes and line breaks for sanity
    CompleteGrain actual = mapper.readValue(data, CompleteGrain.class);
    assertEquals(expected, actual);
    assertEquals(
        BasicToolsTest.asTypeHierarchy(expected),
        BasicToolsTest.asTypeHierarchy(actual));
}
 

实例 6


public static ObjectMapper getStatelessMapper() {
  if (statelessMapper == null) {
    statelessMapper = new ObjectMapper(new YAMLFactory());
    statelessMapper.addMixIn(ObjectMeta.class, ObjectMetaMixIn.class);
    statelessMapper.addMixIn(ReplicationController.class, StatelessReplicationControllerMixIn.class);
  }
  return statelessMapper;
}
 

实例 7


public ConstrettoConfigurationFactory(Class<T> klass, Validator validator, ObjectMapper mapper,
                                      String propertyPrefix, ConfigurationContextResolver tagResolver) {
    super(klass, validator, mapper, propertyPrefix);
    this.tagResolver = tagResolver;
    this.mapper = mapper;
    this.yamlFactory = new YAMLFactory();
}
 

实例 8


/**
 * Load.
 * 
 * @param is
 *            the is
 * @return the config
 */
public static Config load(final InputStream is) {
        final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        try {
                return Config.decorate((ObjectNode) mapper.readTree(is));
        } catch (final JsonProcessingException e) {
                LOG.log(Level.WARNING, "Couldn't parse Yaml file", e);
        } catch (final IOException e) {
                LOG.log(Level.WARNING, "Couldn't read Yaml file", e);
        }
        return null;
}
 

实例 9


private Config loadUrl(URL url) {
    try {
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        return mapper.readValue(url, Config.class);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 

实例 10


@BeforeClass
public static void init() throws IOException {
  // load DataCite account username and password from the properties file
  ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
  InputStream dc = FileUtils.classpathStream("testdb.yaml");
  dbCfg = mapper.readValue(dc, ServiceConfig.class);
  // populate HashMap from basisOfRecord vocabulary, with lowercase keys (used in basisOfRecord validation)
  Map<String, String> basisOfRecords = Maps.newHashMap();
  basisOfRecords.put("preservedspecimen", "Preserved Specimen");
  basisOfRecords.put("fossilspecimen", "Fossil Specimen");
  basisOfRecords.put("livingspecimen", "Living Specimen");
  basisOfRecords.put("humanobservation", "Human Observation");
  basisOfRecords.put("machineobservation", "Machine Observation");
  basisOfRecords.put("materialsample", "Material Sample");
  basisOfRecords.put("occurrence", "Occurrence");
  when(
    mockVocabulariesManager.getI18nVocab(Constants.VOCAB_URI_BASIS_OF_RECORDS, Locale.ENGLISH.getLanguage(), false))
    .thenReturn(basisOfRecords);
}
 

实例 11


private static UserConfigFile loadUserFile() throws IOException {
    java.io.File file = Paths.get(System.getProperty("user.home"), ".opencga", "opencga.yml").toFile();
    if (file.exists()) {
        return new ObjectMapper(new YAMLFactory()).readValue(file, UserConfigFile.class);
    } else {
        return new UserConfigFile();
    }
}
 

实例 12


@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_NULL);
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  mapper.registerModule(new GuavaModule());
  mapper.registerModule(new ProtobufModule());
  return mapper;
}
 

实例 13


@Inject
public BuildLauncher(BuildStateService buildStateService,
                     BuildService buildService,
                     AsyncHttpClient asyncHttpClient,
                     BlazarConfiguration configuration,
                     Map<String, GitHub> gitHubByHost,
                     EventBus eventBus,
                     ObjectMapper objectMapper,
                     YAMLFactory yamlFactory) {
  this.buildStateService = buildStateService;
  this.buildService = buildService;
  this.asyncHttpClient = asyncHttpClient;
  this.singularityConfiguration = configuration.getSingularityConfiguration();
  this.gitHubByHost = gitHubByHost;
  this.objectMapper = objectMapper;
  this.yamlFactory = yamlFactory;
  eventBus.register(this);
}
 

实例 14


@Test
public void testDebugger() throws Exception {
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        InputStream yaml = getClass().getResourceAsStream(
                        "/yaml/templateDebugger.yml");
        TemplateDebugger debugger = mapper.readValue(yaml,
                        TemplateDebugger.class);
        assertNotNull(debugger);
        String rendered = debugger.render();
        assertNotNull(rendered);
        InputStream gold = getClass().getResourceAsStream("/configurations/templateDebugger.rendered");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Utils.copy(gold, baos);
        String expected = baos.toString();
        assertEquals(expected, rendered);
}
 

实例 15


/**
 * Creates an instance of the {@link CroquetRestBuilder} given the command line args.
 * @param settingsClass the Class of the Settings class.
 * @param args the command line args.
 * @return an instance of the {@link CroquetRestBuilder}.
 * @param <S> the type of the settings class.
 */
public static <S extends RestSettings> CroquetRestBuilder<S> create(final Class<S> settingsClass, final String[] args) {
    if (args.length < 1) {
        System.err.println("Configuration YAML file not provided");
        System.exit(-1);
    }
    // parse the arguments and configuration file here
    final String filename = args[0];
    final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    final S configuration;
    try {
        configuration = mapper.readValue(new File(filename), settingsClass);
        configuration.initialize();
    } catch (final JsonParseException e) {
        LOG.error("JsonParseException: {}", e.getMessage());
        throw errorAndDie(filename, e.getMessage());
    } catch (final JsonMappingException e) {
        LOG.error("JsonMappingException: {}", e.getMessage());
        throw errorAndDie(filename, e.getMessage());
    } catch (final IOException e) {
        LOG.error("IOException: {}", e.getMessage());
        throw errorAndDie(filename, e.getMessage());
    }
    new CroquetLoggingFactory().configureLogging(configuration.getLoggingSettings());
    return new CroquetRestBuilder<S>(settingsClass, configuration);
}
 
讨论
淘淘あ西西 profile image