load yaml stream as sequence of policy documents

@throws IOException
510894
private <T> void load(YamlSourceLoader<T> loader, YamlPolicyCreator<T> creator)
            throws IOException
    {
        int index = 1;
        try (final YamlSourceLoader<T> loader1 = loader) {
            for (T yamlDoc : loader1.loadAll()) {
                String ident = identity + "[" + index + "]";
                if (null == yamlDoc) {
                    continue;
                }
                try {
                    Policy yamlPolicy = creator.createYamlPolicy(
                            yamlDoc,
                            identity + "[" + index + "]",
                            index
                    );
                    all.add(yamlPolicy);
                    ruleSet.addAll(yamlPolicy.getRuleSet().getRules());
                } catch (AclPolicySyntaxException e) {
                    validationError(ident, e.getMessage());
                    logger.debug(
                            "ERROR parsing a policy in file: " +
                            identity +
                            "[" +
                            index +
                            "]. Reason: " +
                            e.getMessage(), e
                    );
                }
                index++;
            }

        }
    }
1351705
def load_yaml(stream, **kwargs):
    
    # if there's an error parsing the yaml, and you pass yaml.load a string,
    # it will print lines of context, but will print "<string>" instead of a
    # filename; if you pass a stream, it will print the filename, but no lines
    # of context.
    # Get the best of both worlds, by passing it a string, then replacing
    # "<string>" with the filename if there's an error...
    content = stream.read()
    try:
        return yaml.load(content) or {}
    except Exception, e:
        if stream.name and stream.name != '<string>':
            for mark_name in 'context_mark', 'problem_mark':
                mark = getattr(e, mark_name, None)
                if mark is None:
                    continue
                if getattr(mark, 'name') == '<string>':
                    mark.name = stream.name
        raise e
1249093
def include_yaml(self, node):
        '''
        
        '''
        filename = self.construct_scalar(node)
        if not filename.startswith('/'):
            if self._root is None:
                raise Exception('!include_yaml %s is a relative path, '
                                'but stream lacks path' % filename)
            filename = os.path.join(self._root, self.construct_scalar(node))
        with self.open(filename, 'r') as fin:
            return yaml.load(fin, Loader)
1008952
protected function loadRolesFromPolicyFiles()
    {
        $roles = array();

        $yamlPathsAndFilenames = Files::readDirectoryRecursively(__DIR__ . '/../../../../../Packages', 'yaml', true);
        $configurationPathsAndFilenames = array_filter($yamlPathsAndFilenames,
            function ($pathAndFileName) {
                if (basename($pathAndFileName) === 'Policy.yaml') {
                    return true;
                } else {
                    return false;
                }
            }
        );

        $yamlSource = new \Neos\Flow\Configuration\Source\YamlSource();
        foreach ($configurationPathsAndFilenames as $pathAndFilename) {
            if (preg_match('%Packages/[^/]+/([^/]+)/Configuration/(?:Development/|Production/)?[^/]+%', $pathAndFilename, $matches) === 0) {
                continue;
            };
            $packageKey = $matches[1];
            $configuration = $yamlSource->load(substr($pathAndFilename, 0, -5));
            if (isset($configuration['roles']) && is_array($configuration['roles'])) {
                foreach ($configuration['roles'] as $roleIdentifier => $parentRoles) {
                    $roles[$packageKey . ':' . $roleIdentifier] = true;
                }
            }
        }

        return array_keys($roles);
    }
528143
@SuppressWarnings("unchecked")
    public static Map<String, Object> readYaml(File targetFile) throws IOException
    {
        Map<String, Object> configObject = null;
        Yaml yaml = new Yaml();

        InputStream inputStream = null;
        InputStreamReader steamReader = null;

        try
        {
            inputStream = new FileInputStream(targetFile);
            steamReader = new InputStreamReader(inputStream, "UTF-8");
            configObject = (Map<String, Object>) yaml.load(steamReader);
        }
        catch (ScannerException ex)
        {
            // ScannerException/IOException are occured.
            // throw IOException because handling is same.
            throw new IOException(ex);
        }
        finally
        {
            IOUtils.closeQuietly(inputStream);
        }

        return configObject;
    }
1089387
public void readResources(String path) throws IOException {
		Enumeration<URL> resources =
				getClass().getClassLoader().getResources(path);

		if (!resources.hasMoreElements()) {
			throw new IllegalArgumentException(String.format("File %s was not found on classpath", path));
		}

		Yaml yaml = new Yaml();
		while (resources.hasMoreElements()) {
			appendData(yaml.loadAs(resources.nextElement().openStream(), Data.class));
		}
	}
1286062
def load_yaml(self):
        '''
        
        '''
        env = self.state.document.settings.env
        relpath, abspath = env.relfn2path(directives.path(self.arguments[0]))

        env.note_dependency(relpath)

        encoding = self.options.get('encoding', env.config.source_encoding)
        with io.open(abspath, 'rt', encoding=encoding) as stream:
            spec = yaml.load(stream, _YamlOrderedLoader)
        self.spec = spec
        self.paths = spec[self.path_path]
        self.definitions = spec[self.models_path]
        self.openapi_version = spec.get('swagger', None) or spec['openapi']
        self.options.setdefault('uri', 'file://%s' % abspath)
798581
def load(self):
        """"""
        try:
            merged_configfile = self.get_merged_config()
            self.yamldocs = yaml.load(merged_configfile, Loader=Loader)

            # Strip out the top level 'None's we get from concatenation.
            # Functionally not required, but makes dumps cleaner.
            self.yamldocs = [x for x in self.yamldocs if x]
            self.logdebug('parsed_rules:\n%s\n' % pretty(self.yamldocs))

        except (yaml.scanner.ScannerError, yaml.parser.ParserError):
            self.raise_and_log_error(ConfigError, 'error parsing config.')
795046
def load_tokens
      if File.exists?(TOKEN_PATH)
        f = File.open(TOKEN_PATH, 'r')
        tokens = YAML::load(f)
        f.close
        tokens
      end
    end
368341
private void load() throws IOException
   {
      if (PrivilegedFileHelper.exists(storage))
      {
         InputStream in = PrivilegedFileHelper.fileInputStream(storage);
         try
         {
            Properties props = new Properties();
            log.debug("loading namespace mappings...");
            props.load(in);

            // read mappings from properties
            Iterator<Object> iter = props.keySet().iterator();
            while (iter.hasNext())
            {
               String prefix = (String)iter.next();
               String uri = props.getProperty(prefix);
               log.debug(prefix + " -> " + uri);
               prefixToURI.put(prefix, uri);
               uriToPrefix.put(uri, prefix);
            }
            prefixCount = props.size();
            log.debug("namespace mappings loaded.");
         }
         finally
         {
            in.close();
         }
      }
   }
262955
@Override
    protected synchronized void loadConfiguration() throws IOException {
        LOGGER.info("Loading list of allowed external content locations from {}", configPath);
        try (final Stream<String> stream = Files.lines(Paths.get(configPath))) {
            allowedList = stream.map(line -> normalizePath(line.trim().toLowerCase()))
                    .filter(line -> isAllowanceValid(line))
                    .collect(Collectors.toList());
        }
    }
1298726
function readSync(filename, options = undefined) {
  const {encoding, flag, ...opts} = normalizeOptions(options)

  if (!isNumber(filename)) {
    filename = normalizePathSync(base, filename)

    opts.filename = filename
  }

  const content = fs.readFileSync(filename, {encoding, flag})

  return yaml.load(content, opts)
}
22503
function loadYamlFile (file) {
  try {
    return yaml.load(fs.readFileSync(file, 'utf8'))
  } catch (e) {
    if (!/ENOENT:\s+no such file or directory/.test(e)) {
      console.log('Error Loading ' + file + ':', e)
      throw e
    }
  }
}
875479
def load_all(stream):
    
    loader = YAMLDictLoader(stream)
    try:
        while loader.check_data():
            yield loader.get_data()
    finally:
        loader.dispose()
41185
public void fromFile(File policyFile) throws IOException {
        InputStream is = new FileInputStream(policyFile);
        policyBytes = IOUtils.toByteArray(is);
    }
530728
public static YamlConfiguration loadYamlConfiguration(File file) throws DeployerConfigurationException {
        try {
            try (Reader reader = new BufferedReader(new FileReader(file))) {
                return doLoadYamlConfiguration(reader);
            }
        } catch (Exception e) {
            throw new DeployerConfigurationException("Failed to load YAML configuration at " + file, e);
        }
    }
1191378
def generate_yaml_file(filename, contents):
    """"""
    with open(filename, 'w') as file:
        file.write(yaml.dump(contents, default_flow_style=False))