org.yaml.snakeyaml.constructor.SafeConstructor Java Examples

The following examples show how to use org.yaml.snakeyaml.constructor.SafeConstructor. 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: KubeConfig.java    From java with Apache License 2.0 7 votes vote down vote up
/** Load a Kubernetes config from a Reader */
public static KubeConfig loadKubeConfig(Reader input) {
  Yaml yaml = new Yaml(new SafeConstructor());
  Object config = yaml.load(input);
  Map<String, Object> configMap = (Map<String, Object>) config;

  String currentContext = (String) configMap.get("current-context");
  ArrayList<Object> contexts = (ArrayList<Object>) configMap.get("contexts");
  ArrayList<Object> clusters = (ArrayList<Object>) configMap.get("clusters");
  ArrayList<Object> users = (ArrayList<Object>) configMap.get("users");
  Object preferences = configMap.get("preferences");

  KubeConfig kubeConfig = new KubeConfig(contexts, clusters, users);
  kubeConfig.setContext(currentContext);
  kubeConfig.setPreferences(preferences);

  return kubeConfig;
}
 
Example #2
Source File: BenchmarkConfig.java    From yahoo-streaming-benchmark with Apache License 2.0 6 votes vote down vote up
private static ParameterTool yamlToParameters(String yamlFile) throws FileNotFoundException {
  // load yaml file
  Yaml yml = new Yaml(new SafeConstructor());
  Map<String, String> ymlMap = (Map) yml.load(new FileInputStream(yamlFile));

  String kafkaZookeeperConnect = getZookeeperServers(ymlMap, String.valueOf(ymlMap.get("kafka.zookeeper.path")));
  String akkaZookeeperQuorum = getZookeeperServers(ymlMap, "");

  // We need to add these values as "parameters"
  // -- This is a bit of a hack but the Kafka consumers and producers
  //    expect these values to be there
  ymlMap.put("zookeeper.connect", kafkaZookeeperConnect); // set ZK connect for Kafka
  ymlMap.put("bootstrap.servers", getKafkaBrokers(ymlMap));
  ymlMap.put("akka.zookeeper.quorum", akkaZookeeperQuorum);
  ymlMap.put("auto.offset.reset", "latest");
  ymlMap.put("group.id", UUID.randomUUID().toString());

  // Convert everything to strings
  for (Map.Entry e : ymlMap.entrySet()) {
    {
      e.setValue(e.getValue().toString());
    }
  }
  return ParameterTool.fromMap(ymlMap);
}
 
Example #3
Source File: ConfigUtilsTests.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testCreateOverrides() throws IOException {
  final Properties overrideProperties = createOverrideProperties(
      Pair.create("heron.statemgr.connection.string", "zookeeper:2181"),
      Pair.create("heron.kubernetes.scheduler.uri", "http://127.0.0.1:8001")
  );

  final String overridesPath = ConfigUtils.createOverrideConfiguration(overrideProperties);
  try (Reader reader = Files.newBufferedReader(Paths.get(overridesPath))) {
    final Map<String, Object> overrides =
        (Map<String, Object>) new Yaml(new SafeConstructor()).load(reader);
    assertEquals(overrides.size(), overrideProperties.size());
    for (String key : overrides.keySet()) {
      assertEquals(overrides.get(key), overrideProperties.getProperty(key));
    }
  }
}
 
Example #4
Source File: GlobalApplicationOptions.java    From halyard with Apache License 2.0 6 votes vote down vote up
public static GlobalApplicationOptions getInstance() {
  if (GlobalApplicationOptions.options == null) {
    Yaml yamlParser = new Yaml(new SafeConstructor());
    ObjectMapper objectMapper = new ObjectMapper();

    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES, false);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    try {
      GlobalApplicationOptions.options =
          objectMapper.convertValue(
              yamlParser.load(FileUtils.openInputStream(new File(CONFIG_PATH))),
              GlobalApplicationOptions.class);
    } catch (IOException e) {
      GlobalApplicationOptions.options = new GlobalApplicationOptions();
    }
  }
  return GlobalApplicationOptions.options;
}
 
Example #5
Source File: ConfigUtilsTests.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testApplyEmptyOverrides() throws IOException {
  final Properties overrideProperties = createOverrideProperties(
      Pair.create("heron.statemgr.connection.string", "zookeeper:2181"),
      Pair.create("heron.kubernetes.scheduler.uri", "http://127.0.0.1:8001")
  );

  final String overridesPath = ConfigUtils.createOverrideConfiguration(overrideProperties);

  ConfigUtils.applyOverrides(Paths.get(overridesPath), new HashMap<>());

  final Map<String, String> overrides = new HashMap<>();
  for (String key : overrideProperties.stringPropertyNames()) {
    overrides.put(key, overrideProperties.getProperty(key));
  }

  try (Reader reader = Files.newBufferedReader(Paths.get(overridesPath))) {
    final Map<String, Object> newOverrides =
        (Map<String, Object>) new Yaml(new SafeConstructor()).load(reader);
    assertEquals(newOverrides, overrides);
  }
}
 
Example #6
Source File: ConfigReader.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
/**
 * Load config from the given YAML stream
 *
 * @param inputStream the name of YAML stream to read
 *
 * @return Map, contains the key value pairs of config
 */
@SuppressWarnings("unchecked") // yaml.load API returns raw Map
public static Map<String, Object> loadStream(InputStream inputStream) {
  LOG.fine("Reading config stream");

  Yaml yaml = new Yaml(new SafeConstructor());
  Map<Object, Object> propsYaml = (Map<Object, Object>) yaml.load(inputStream);
  LOG.fine("Successfully read config");

  Map<String, Object> typedMap = new HashMap<>();
  for (Object key: propsYaml.keySet()) {
    typedMap.put(key.toString(), propsYaml.get(key));
  }

  return typedMap;
}
 
Example #7
Source File: ParamVerify.java    From jenkins-plugin with Apache License 2.0 6 votes vote down vote up
public static FormValidation doCheckJsonyaml(@QueryParameter String value)
        throws IOException, ServletException {
    if (value.length() == 0)
        return FormValidation.error("You must set a block of JSON or YAML");
    try {
        ModelNode.fromJSONString(value);
    } catch (Throwable t) {
        try {
            Yaml yaml = new Yaml(new SafeConstructor());
            Map<String, Object> map = (Map<String, Object>) yaml
                    .load(value);
            JSONObject jsonObj = JSONObject.fromObject(map);
            ModelNode.fromJSONString(jsonObj.toString());
        } catch (Throwable t2) {
            return FormValidation
                    .error("Valid JSON or YAML must be specified");
        }
    }
    return FormValidation.ok();
}
 
Example #8
Source File: LifecycleChaincodeEndorsementPolicy.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
public static LifecycleChaincodeEndorsementPolicy fromSignaturePolicyYamlFile(Path yamlPolicyFile) throws IOException, ChaincodeEndorsementPolicyParseException {
    final Yaml yaml = new Yaml(new SafeConstructor());
    final Map<?, ?> load = (Map<?, ?>) yaml.load(new FileInputStream(yamlPolicyFile.toFile()));

    Map<?, ?> mp = (Map<?, ?>) load.get("policy");

    if (null == mp) {
        throw new ChaincodeEndorsementPolicyParseException("The policy file has no policy section");
    }

    IndexedHashMap<String, MSPPrincipal> identities = parseIdentities((Map<?, ?>) load.get("identities"));

    SignaturePolicy sp = parsePolicy(identities, mp);

    return new LifecycleChaincodeEndorsementPolicy(Policy.ApplicationPolicy.newBuilder()
            .setSignaturePolicy(Policies.SignaturePolicyEnvelope.newBuilder()
                    .setVersion(0)
                    .addAllIdentities(identities.values())
                    .setRule(sp)
                    .build()).build().toByteString());
}
 
Example #9
Source File: IOpenShiftApiObjHandler.java    From jenkins-plugin with Apache License 2.0 6 votes vote down vote up
default ModelNode hydrateJsonYaml(String jsonyaml, TaskListener listener) {
    // construct json/yaml node
    ModelNode resources = null;
    try {
        resources = ModelNode.fromJSONString(jsonyaml);
    } catch (Exception e) {
        Yaml yaml = new Yaml(new SafeConstructor());
        Map<String, Object> map = (Map<String, Object>) yaml.load(jsonyaml);
        JSONObject jsonObj = JSONObject.fromObject(map);
        try {
            resources = ModelNode.fromJSONString(jsonObj.toString());
        } catch (Throwable t) {
            if (listener != null)
                t.printStackTrace(listener.getLogger());
        }
    }
    return resources;
}
 
Example #10
Source File: Parser.java    From hangout with MIT License 6 votes vote down vote up
private void initialize(InputStream regexYaml) {
  Yaml yaml = new Yaml(new SafeConstructor());
  @SuppressWarnings("unchecked")
  Map<String,List<Map<String,String>>> regexConfig = (Map<String,List<Map<String,String>>>) yaml.load(regexYaml);

  List<Map<String,String>> uaParserConfigs = regexConfig.get("user_agent_parsers");
  if (uaParserConfigs == null) {
    throw new IllegalArgumentException("user_agent_parsers is missing from yaml");
  }
  uaParser = UserAgentParser.fromList(uaParserConfigs);

  List<Map<String,String>> osParserConfigs = regexConfig.get("os_parsers");
  if (osParserConfigs == null) {
    throw new IllegalArgumentException("os_parsers is missing from yaml");
  }
  osParser = OSParser.fromList(osParserConfigs);

  List<Map<String,String>> deviceParserConfigs = regexConfig.get("device_parsers");
  if (deviceParserConfigs == null) {
    throw new IllegalArgumentException("device_parsers is missing from yaml");
  }
  deviceParser = DeviceParser.fromList(deviceParserConfigs);
}
 
Example #11
Source File: ChaincodeEndorsementPolicy.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
public static ChaincodeEndorsementPolicy fromYamlFile(Path yamlPolicyFile) throws IOException, ChaincodeEndorsementPolicyParseException {
    final Yaml yaml = new Yaml(new SafeConstructor());
    final Map<?, ?> load = (Map<?, ?>) yaml.load(new FileInputStream(yamlPolicyFile.toFile()));

    Map<?, ?> mp = (Map<?, ?>) load.get("policy");

    if (null == mp) {
        throw new ChaincodeEndorsementPolicyParseException("The policy file has no policy section");
    }

    IndexedHashMap<String, MSPPrincipal> identities = parseIdentities((Map<?, ?>) load.get("identities"));

    SignaturePolicy sp = parsePolicy(identities, mp);

    ChaincodeEndorsementPolicy chaincodeEndorsementPolicy = new ChaincodeEndorsementPolicy();

    chaincodeEndorsementPolicy.policyBytes = Policies.SignaturePolicyEnvelope.newBuilder()
            .setVersion(0)
            .addAllIdentities(identities.values())
            .setRule(sp)
            .build().toByteArray();

    return chaincodeEndorsementPolicy;
}
 
Example #12
Source File: ChaincodeEndorsementPolicy.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * From a yaml file
 *
 * @param yamlPolicyFile File location for the chaincode endorsement policy specification.
 * @throws IOException
 * @throws ChaincodeEndorsementPolicyParseException
 * @deprecated use {@link #fromYamlFile(Path)}
 */

public void fromYamlFile(File yamlPolicyFile) throws IOException, ChaincodeEndorsementPolicyParseException {
    final Yaml yaml = new Yaml(new SafeConstructor());
    final Map<?, ?> load = (Map<?, ?>) yaml.load(new FileInputStream(yamlPolicyFile));

    Map<?, ?> mp = (Map<?, ?>) load.get("policy");

    if (null == mp) {
        throw new ChaincodeEndorsementPolicyParseException("The policy file has no policy section");
    }

    IndexedHashMap<String, MSPPrincipal> identities = parseIdentities((Map<?, ?>) load.get("identities"));

    SignaturePolicy sp = parsePolicy(identities, mp);

    policyBytes = Policies.SignaturePolicyEnvelope.newBuilder()
            .setVersion(0)
            .addAllIdentities(identities.values())
            .setRule(sp)
            .build().toByteArray();
}
 
Example #13
Source File: YAMLParameterFileParser.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<Parameter> parseParams(InputStream fileContent) throws IOException {
	Yaml yaml = new Yaml(new SafeConstructor());
	@SuppressWarnings("unchecked")
	Map<String, Object> parse = yaml.load(new InputStreamReader(fileContent, Charsets.UTF_8));

	Collection<Parameter> parameters = new ArrayList<>();
	for (Map.Entry<String, Object> entry : parse.entrySet()) {
		Object value = entry.getValue();
		if (value instanceof Collection) {
			String val = Joiner.on(",").join((Collection) value);
			parameters.add(new Parameter().withParameterKey(entry.getKey()).withParameterValue(val));
		} else {
			parameters.add(new Parameter().withParameterKey(entry.getKey()).withParameterValue(value.toString()));
		}
	}
	return parameters;
}
 
Example #14
Source File: FlutterUtils.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static Map<String, Object> loadPubspecInfo(@NotNull String yamlContents) {
  final Yaml yaml = new Yaml(new SafeConstructor(), new Representer(), new DumperOptions(), new Resolver() {
    @Override
    protected void addImplicitResolvers() {
      this.addImplicitResolver(Tag.BOOL, BOOL, "yYnNtTfFoO");
      this.addImplicitResolver(Tag.NULL, NULL, "~nN\u0000");
      this.addImplicitResolver(Tag.NULL, EMPTY, null);
      this.addImplicitResolver(new Tag("tag:yaml.org,2002:value"), VALUE, "=");
      this.addImplicitResolver(Tag.MERGE, MERGE, "<");
    }
  });

  try {
    //noinspection unchecked
    return (Map)yaml.load(yamlContents);
  }
  catch (Exception e) {
    return null;
  }
}
 
Example #15
Source File: Parser.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
private void initialize(InputStream regexYaml) {
  Yaml yaml = new Yaml(new SafeConstructor());
  Map<String,List> regexConfig = (Map<String,List>) yaml.load(regexYaml);

  List<Map> uaParserConfigs = regexConfig.get("user_agent_parsers");
  if (uaParserConfigs == null) {
    throw new IllegalArgumentException("user_agent_parsers is missing from yaml");
  }
  uaParser = UserAgentParser.fromList(uaParserConfigs);

  List<Map> osParserConfigs = regexConfig.get("os_parsers");
  if (osParserConfigs == null) {
    throw new IllegalArgumentException("os_parsers is missing from yaml");
  }
  osParser = OSParser.fromList(osParserConfigs);

  List<Map> deviceParserConfigs = regexConfig.get("device_parsers");
  if (deviceParserConfigs == null) {
    throw new IllegalArgumentException("device_parsers is missing from yaml");
  }
  deviceParser = DeviceParser.fromList(deviceParserConfigs);
}
 
Example #16
Source File: Parser.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
private void initialize(InputStream regexYaml) {
  Yaml yaml = new Yaml(new SafeConstructor());
  Map<String,List> regexConfig = (Map<String,List>) yaml.load(regexYaml);

  List<Map> uaParserConfigs = regexConfig.get("user_agent_parsers");
  if (uaParserConfigs == null) {
    throw new IllegalArgumentException("user_agent_parsers is missing from yaml");
  }
  uaParser = UserAgentParser.fromList(uaParserConfigs);

  List<Map> osParserConfigs = regexConfig.get("os_parsers");
  if (osParserConfigs == null) {
    throw new IllegalArgumentException("os_parsers is missing from yaml");
  }
  osParser = OSParser.fromList(osParserConfigs);

  List<Map> deviceParserConfigs = regexConfig.get("device_parsers");
  if (deviceParserConfigs == null) {
    throw new IllegalArgumentException("device_parsers is missing from yaml");
  }
  deviceParser = DeviceParser.fromList(deviceParserConfigs);
}
 
Example #17
Source File: Parser.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
private void initialize(InputStream regexYaml) {
  Yaml yaml = new Yaml(new SafeConstructor());
  Map<String,List> regexConfig = (Map<String,List>) yaml.load(regexYaml);

  List<Map> uaParserConfigs = regexConfig.get("user_agent_parsers");
  if (uaParserConfigs == null) {
    throw new IllegalArgumentException("user_agent_parsers is missing from yaml");
  }
  uaParser = UserAgentParser.fromList(uaParserConfigs);

  List<Map> osParserConfigs = regexConfig.get("os_parsers");
  if (osParserConfigs == null) {
    throw new IllegalArgumentException("os_parsers is missing from yaml");
  }
  osParser = OSParser.fromList(osParserConfigs);

  List<Map> deviceParserConfigs = regexConfig.get("device_parsers");
  if (deviceParserConfigs == null) {
    throw new IllegalArgumentException("device_parsers is missing from yaml");
  }
  deviceParser = DeviceParser.fromList(deviceParserConfigs);
}
 
Example #18
Source File: Parser.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
private void initialize(InputStream regexYaml) {
  Yaml yaml = new Yaml(new SafeConstructor());
  Map<String,List> regexConfig = (Map<String,List>) yaml.load(regexYaml);

  List<Map> uaParserConfigs = regexConfig.get("user_agent_parsers");
  if (uaParserConfigs == null) {
    throw new IllegalArgumentException("user_agent_parsers is missing from yaml");
  }
  uaParser = UserAgentParser.fromList(uaParserConfigs);

  List<Map> osParserConfigs = regexConfig.get("os_parsers");
  if (osParserConfigs == null) {
    throw new IllegalArgumentException("os_parsers is missing from yaml");
  }
  osParser = OSParser.fromList(osParserConfigs);

  List<Map> deviceParserConfigs = regexConfig.get("device_parsers");
  if (deviceParserConfigs == null) {
    throw new IllegalArgumentException("device_parsers is missing from yaml");
  }
  deviceParser = DeviceParser.fromList(deviceParserConfigs);
}
 
Example #19
Source File: IntegrationSpecificationITCase.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldServeOpenApiSpecificationInYamlFormat() throws IOException {
    final MultiValueMap<Object, Object> data = specification("/io/syndesis/server/runtime/test-swagger.yaml");

    final ResponseEntity<Integration> integrationResponse = post("/api/v1/apis/generator", data, Integration.class, tokenRule.validToken(), HttpStatus.OK,
        MULTIPART);

    final Integration integration = integrationResponse.getBody();
    final String integrationId = KeyGenerator.createKey();
    dataManager.create(integration.builder()
        .id(integrationId)
        .build());

    final ResponseEntity<ByteArrayResource> specificationResponse = get("/api/v1/integrations/" + integrationId + "/specification",
        ByteArrayResource.class);

    assertThat(specificationResponse.getHeaders().getContentType()).isEqualTo(MediaType.valueOf("application/vnd.oai.openapi"));
    final String givenYaml = getResourceAsText("io/syndesis/server/runtime/test-swagger.yaml");
    final String receivedJson = new String(specificationResponse.getBody().getByteArray(), StandardCharsets.UTF_8);

    final Object givenYamlObject = new Yaml(new SafeConstructor()).load(givenYaml);
    final String givenJson = JsonUtils.toString(givenYamlObject);

    assertThatJson(receivedJson).whenIgnoringPaths("$..operationId").isEqualTo(givenJson);
}
 
Example #20
Source File: Parser.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
private void initialize(InputStream regexYaml) {
  Yaml yaml = new Yaml(new SafeConstructor());
  Map<String,List> regexConfig = (Map<String,List>) yaml.load(regexYaml);

  List<Map> uaParserConfigs = regexConfig.get("user_agent_parsers");
  if (uaParserConfigs == null) {
    throw new IllegalArgumentException("user_agent_parsers is missing from yaml");
  }
  uaParser = UserAgentParser.fromList(uaParserConfigs);

  List<Map> osParserConfigs = regexConfig.get("os_parsers");
  if (osParserConfigs == null) {
    throw new IllegalArgumentException("os_parsers is missing from yaml");
  }
  osParser = OSParser.fromList(osParserConfigs);

  List<Map> deviceParserConfigs = regexConfig.get("device_parsers");
  if (deviceParserConfigs == null) {
    throw new IllegalArgumentException("device_parsers is missing from yaml");
  }
  deviceParser = DeviceParser.fromList(deviceParserConfigs);
}
 
Example #21
Source File: FlutterUtils.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static Map<String, Object> loadPubspecInfo(@NotNull String yamlContents) {
  final Yaml yaml = new Yaml(new SafeConstructor(), new Representer(), new DumperOptions(), new Resolver() {
    @Override
    protected void addImplicitResolvers() {
      this.addImplicitResolver(Tag.BOOL, BOOL, "yYnNtTfFoO");
      this.addImplicitResolver(Tag.NULL, NULL, "~nN\u0000");
      this.addImplicitResolver(Tag.NULL, EMPTY, null);
      this.addImplicitResolver(new Tag("tag:yaml.org,2002:value"), VALUE, "=");
      this.addImplicitResolver(Tag.MERGE, MERGE, "<");
    }
  });

  try {
    //noinspection unchecked
    return (Map)yaml.load(yamlContents);
  }
  catch (Exception e) {
    return null;
  }
}
 
Example #22
Source File: Parser.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
private void initialize(InputStream regexYaml) {
  Yaml yaml = new Yaml(new SafeConstructor());
  Map<String,List> regexConfig = (Map<String,List>) yaml.load(regexYaml);

  List<Map> uaParserConfigs = regexConfig.get("user_agent_parsers");
  if (uaParserConfigs == null) {
    throw new IllegalArgumentException("user_agent_parsers is missing from yaml");
  }
  uaParser = UserAgentParser.fromList(uaParserConfigs);

  List<Map> osParserConfigs = regexConfig.get("os_parsers");
  if (osParserConfigs == null) {
    throw new IllegalArgumentException("os_parsers is missing from yaml");
  }
  osParser = OSParser.fromList(osParserConfigs);

  List<Map> deviceParserConfigs = regexConfig.get("device_parsers");
  if (deviceParserConfigs == null) {
    throw new IllegalArgumentException("device_parsers is missing from yaml");
  }
  deviceParser = DeviceParser.fromList(deviceParserConfigs);
}
 
Example #23
Source File: Parser.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
private void initialize(InputStream regexYaml) {
  Yaml yaml = new Yaml(new SafeConstructor());
  Map<String,List> regexConfig = (Map<String,List>) yaml.load(regexYaml);

  List<Map> uaParserConfigs = regexConfig.get("user_agent_parsers");
  if (uaParserConfigs == null) {
    throw new IllegalArgumentException("user_agent_parsers is missing from yaml");
  }
  uaParser = UserAgentParser.fromList(uaParserConfigs);

  List<Map> osParserConfigs = regexConfig.get("os_parsers");
  if (osParserConfigs == null) {
    throw new IllegalArgumentException("os_parsers is missing from yaml");
  }
  osParser = OSParser.fromList(osParserConfigs);

  List<Map> deviceParserConfigs = regexConfig.get("device_parsers");
  if (deviceParserConfigs == null) {
    throw new IllegalArgumentException("device_parsers is missing from yaml");
  }
  deviceParser = DeviceParser.fromList(deviceParserConfigs);
}
 
Example #24
Source File: Parser.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
private void initialize(InputStream regexYaml) {
  Yaml yaml = new Yaml(new SafeConstructor());
  Map<String,List> regexConfig = (Map<String,List>) yaml.load(regexYaml);

  List<Map> uaParserConfigs = regexConfig.get("user_agent_parsers");
  if (uaParserConfigs == null) {
    throw new IllegalArgumentException("user_agent_parsers is missing from yaml");
  }
  uaParser = UserAgentParser.fromList(uaParserConfigs);

  List<Map> osParserConfigs = regexConfig.get("os_parsers");
  if (osParserConfigs == null) {
    throw new IllegalArgumentException("os_parsers is missing from yaml");
  }
  osParser = OSParser.fromList(osParserConfigs);

  List<Map> deviceParserConfigs = regexConfig.get("device_parsers");
  if (deviceParserConfigs == null) {
    throw new IllegalArgumentException("device_parsers is missing from yaml");
  }
  deviceParser = DeviceParser.fromList(deviceParserConfigs);
}
 
Example #25
Source File: SingleQuoteTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
private void checkQuotes(boolean isBlock, String expectation) {
    DumperOptions options = new DumperOptions();
    options.setIndent(4);
    if (isBlock) {
        options.setDefaultFlowStyle(FlowStyle.BLOCK);
    }
    Representer representer = new Representer();

    Yaml yaml = new Yaml(new SafeConstructor(), representer, options);

    LinkedHashMap<String, Object> lvl1 = new LinkedHashMap<String, Object>();
    lvl1.put("steak:cow", "11");
    LinkedHashMap<String, Object> root = new LinkedHashMap<String, Object>();
    root.put("cows", lvl1);
    String output = yaml.dump(root);
    assertEquals(expectation + "\n", output);

    // parse the value back
    @SuppressWarnings("unchecked")
    Map<String, Object> cows = (Map<String, Object>) yaml.load(output);
    @SuppressWarnings("unchecked")
    Map<String, String> cow = (Map<String, String>) cows.get("cows");
    assertEquals("11", cow.get("steak:cow"));
}
 
Example #26
Source File: PyRecursiveTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testListSafeConstructor() {
    List value = new ArrayList();
    value.add(value);
    value.add("test");
    value.add(new Integer(1));

    Yaml yaml = new Yaml(new SafeConstructor());
    String output1 = yaml.dump(value);
    assertEquals("&id001\n- *id001\n- test\n- 1\n", output1);
    List value2 = (List) yaml.load(output1);
    assertEquals(3, value2.size());
    assertEquals(value.size(), value2.size());
    assertSame(value2, value2.get(0));
    // we expect self-reference as 1st element of the list
    // let's remove self-reference and check other "simple" members of the
    // list. otherwise assertEquals will lead us to StackOverflow
    value.remove(0);
    value2.remove(0);
    assertEquals(value, value2);
}
 
Example #27
Source File: YamlLoader.java    From digdag with Apache License 2.0 5 votes vote down vote up
public ObjectNode loadString(String content)
    throws IOException
{
    // here doesn't use jackson-dataformat-yaml so that snakeyaml calls Resolver
    // and Composer. See also YamlTagResolver.
    Yaml yaml = new Yaml(new SafeConstructor(), new Representer(), new DumperOptions(), new YamlTagResolver());
    ObjectNode object = normalizeValidateObjectNode(yaml.load(content));
    return object;
}
 
Example #28
Source File: Yamls.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private static Yaml newYaml() {
    return new Yaml(
            BrooklynSystemProperties.YAML_TYPE_INSTANTIATION.isEnabled()
                    ? new Constructor() // allows instantiation of arbitrary Java types
                    : new SafeConstructor() // allows instantiation of limited set of types only
    );
}
 
Example #29
Source File: ConfigUtilsTests.java    From incubator-heron with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testApplyOverrides() throws IOException {
  final Properties overrideProperties = createOverrideProperties(
      Pair.create("heron.statemgr.connection.string", "zookeeper:2181"),
      Pair.create("heron.kubernetes.scheduler.uri", "http://127.0.0.1:8001")
  );

  final String overridesPath = ConfigUtils.createOverrideConfiguration(overrideProperties);

  final Map<String, String> overrides = createOverrides(
      Pair.create("my.override.key", "my.override.value")
  );

  ConfigUtils.applyOverrides(Paths.get(overridesPath), overrides);

  final Map<String, String> combinedOverrides = new HashMap<>();
  combinedOverrides.putAll(overrides);
  for (String key : overrideProperties.stringPropertyNames()) {
    combinedOverrides.put(key, overrideProperties.getProperty(key));
  }

  try (Reader reader = Files.newBufferedReader(Paths.get(overridesPath))) {
    final Map<String, Object> newOverrides =
        (Map<String, Object>) new Yaml(new SafeConstructor()).load(reader);
    assertEquals(newOverrides, combinedOverrides);
  }
}
 
Example #30
Source File: Autogen.java    From deploymentmanager-autogen with Apache License 2.0 5 votes vote down vote up
private static String toYaml(Map<String, Object> message) {
  DumperOptions dumperOptions = new DumperOptions();
  dumperOptions.setDefaultFlowStyle(FlowStyle.BLOCK);
  dumperOptions.setWidth(3000);  // No auto line breaking on a field.
  return new Yaml(new SafeConstructor(), new Representer(), dumperOptions)
      .dump(message)
      .trim();
}