parse a configuration stream (external file or resources)
160356
public static List<Specification> parseInputSpecification(InputStream in) {
        List<Specification> monitorables = new ArrayList<>();
        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode metrics = mapper.readTree(in).path("metrics");
            for (JsonNode node : metrics) {
                monitorables.add(specificationAdapter.fromJson(node));
            }
        } catch (Exception e) {
            logger.error(String.format("Unexpected JSON format%n%s", e.getMessage()));
        }
        return monitorables;
    }
579836
function readFromLocalConfig(parent){
    return readFile(config_file(parent), "utf8")
        .then(function(contents){
            return JSON.parse(contents);
        })
        .catch(function(){
            return {
                data: {},
                installed: [],
            };
        });
}
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());
        }
    }
905380
def load_config(filename=None):
    
    try:
        with _config_stream(filename) as handle:
            filename = handle.name
            return deserialize_config(handle.read())
    except (OSError, toml.TomlDecodeError, UnicodeDecodeError) as exc:
        raise ConfigError(
            'Error loading configuration from {}'.format(filename)) from exc
1171416
def parse(config_path):
    
    config_path = os.path.expanduser(config_path)

    # Read the configuration file
    config_file = ConfigParser.RawConfigParser()
    config_file.SECTCRE = re.compile(r"\[ *(?P<header>.*) *\]")
    config_file.optionxform = lambda option: option
    config_file.read(config_path)

    #
    # Handle [global]
    #
    if 'global' in config_file.sections():
        global_config = __parse_options(
            config_file,
            'global',
            [
                {
                    'key': 'aws_access_key_id',
                    'option': 'aws-access-key-id',
                    'required': False,
                    'type': 'str'
                },
                {
                    'key': 'aws_secret_access_key',
                    'option': 'aws-secret-access-key-id',
                    'required': False,
                    'type': 'str'
                },
                {
                    'key': 'region',
                    'option': 'region',
                    'required': False,
                    'type': 'str'
                },
                {
                    'key': 'check_interval',
                    'option': 'check-interval',
                    'required': False,
                    'type': 'int'
                },
                {
                    'key': 'circuit_breaker_url',
                    'option': 'circuit-breaker-url',
                    'required': False,
                    'type': 'str'
                },
                {
                    'key': 'circuit_breaker_timeout',
                    'option': 'circuit-breaker-timeout',
                    'required': False,
                    'type': 'float'
                },
            ])

    #
    # Handle [logging]
    #
    if 'logging' in config_file.sections():
        logging_config = __parse_options(
            config_file,
            'logging',
            [
                {
                    'key': 'log_level',
                    'option': 'log-level',
                    'required': False,
                    'type': 'str'
                },
                {
                    'key': 'log_file',
                    'option': 'log-file',
                    'required': False,
                    'type': 'str'
                },
                {
                    'key': 'log_config_file',
                    'option': 'log-config-file',
                    'required': False,
                    'type': 'str'
                }
            ])

    if 'default_options' in config_file.sections():
        # nothing is required in defaults, so we set required to False
        default_config_options = deepcopy(TABLE_CONFIG_OPTIONS)
        for item in default_config_options:
            item['required'] = False
        default_options = __parse_options(
            config_file, 'default_options', default_config_options)
        # if we've got a default set required to be false for table parsing
        for item in TABLE_CONFIG_OPTIONS:
            if item['key'] in default_options:
                item['required'] = False
    else:
        default_options = {}

    #
    # Handle [table: ]
    #
    table_config = {'tables': ordereddict()}

    # Find the first table definition
    found_table = False
    for current_section in config_file.sections():
        if current_section.rsplit(':', 1)[0] != 'table':
            continue

        found_table = True
        current_table_name = current_section.rsplit(':', 1)[1].strip()
        table_config['tables'][current_table_name] = \
            dict(default_options.items() + __parse_options(
                config_file, current_section, TABLE_CONFIG_OPTIONS).items())

    if not found_table:
        print('Could not find a [table: <table_name>] section in {0}'.format(
            config_path))
        sys.exit(1)

    # Find gsi definitions - this allows gsi's to be defined before the table
    # definitions we don't worry about parsing everything twice here
    for current_section in config_file.sections():
        try:
            header1, gsi_key, header2, table_key = current_section.split(' ')
        except ValueError:
            continue

        if header1 != 'gsi:':
            continue

        if table_key not in table_config['tables']:
            print('No table configuration matching {0} found.'.format(
                table_key))
            sys.exit(1)

        if 'gsis' not in table_config['tables'][table_key]:
            table_config['tables'][table_key]['gsis'] = {}

        table_config['tables'][table_key]['gsis'][gsi_key] = \
            ordereddict(default_options.items() + __parse_options(
                config_file, current_section, TABLE_CONFIG_OPTIONS).items())

    return ordereddict(
        global_config.items() +
        logging_config.items() +
        table_config.items())
348992
def read(config_file, configspec, server_mode=False, default_section='default_settings', list_values=True):
    '''
    
    '''
#    configspec = ConfigObj(path.join(path.abspath(path.dirname(__file__)), configspec),
#                           encoding='UTF8',
#                           interpolation='Template',
#                           list_values=False,
#                           _inspec=True)
    config = ConfigObj(config_file,
                       configspec=path.join(path.abspath(path.dirname(__file__)),
                                            configspec),
                                            list_values=list_values)
    validation = config.validate(validate.Validator(), preserve_errors=True)

    if validation == True:
        config = dict(config)
        for section in config:
            if section != default_section:
                if server_mode: # When it's a servers config file, retrieve the correct fqdn
                    config[section]['availability'] = True
                    if config[section]['custom_fqdn'] == None:
                        config[section]['custom_fqdn'] = socket.getfqdn()
                for option in config[section]:  # retrieve default configuration for missing values
                    if config[section][option] == None:
                        config[section][option] = config[default_section][option]

        del(config[default_section])

        return config
    else:
        raise ConfiguratorException(config_file, validation)
1019432
def from_stream(cls, f, **kwargs):
        """"""
        lines = lines_from_stream(f)
        if 'meta' not in kwargs:
            kwargs['meta'] = {'from': 'stream'}
        kwargs['meta']['filepath'] = f.name if hasattr(f, 'name') else None
        return cls(lines, **kwargs)
759499
def read_config(path=None, final=False):
    """"""
    try:
        with open(config_path(path, final=final), 'r') as configfile:
            return yaml.safe_load(configfile) or {}
    except FileNotFoundError:
        return {}
617981
def parse_config_file(path: str, final: bool = True) -> None:
    
    return options.parse_config_file(path, final=final)
148759
@SuppressWarnings("unchecked")
    @Override
    public T readConfig(InputStream fileAsStream) throws ConfigurationException {
        InputStreamReader streamReader = new InputStreamReader(fileAsStream);
        try {
            YamlReader reader = new YamlReader(streamReader);
            reader.getConfig().setClassTag(clazz.getSimpleName(), clazz);
            return (T) reader.read();
        } catch (YamlException e) {
            throw new ConfigurationException("Configuration Exception", "CONF_002", e);
        }
    }
701544
static ConfigurationStream resolveConfigFileAsStream(String configFilePath) throws ConfigurationException {
        InputStream fileStream;
        String fileExtention;
        
        if (configFilePath != null) {
            if (new File(configFilePath).isDirectory()) {
                String path = scanConfigFile(configFilePath);
                fileStream = getFileAsStream(new File(path));
                fileExtention = FilenameUtils.getExtension(path);
            } else {
                fileStream = getFileAsStream(configFilePath);
                fileExtention = FilenameUtils.getExtension(configFilePath);
            }
        } else if (hasEnvironmentVariable(ENVIRONMENT_CONFIG_VARIABLE_NAME)) {
            fileStream = getFileAsStream(getEnvironemtVariableConfigFilePath());
            fileExtention = FilenameUtils.getExtension(getEnvironemtVariableConfigFilePath().toFile().getName());
        } else if (hasSystemPropertyVariable(SYSTEM_PROPERTY_CONFIG_VARIABLE_NAME)) {
            fileStream = getFileAsStream(getSystemPropertyConfigFilePath());
            fileExtention = FilenameUtils.getExtension(getSystemPropertyConfigFilePath().toFile().getName());
        } else if (getClasspathResourceAsStream(CONFIG_FILE_NAME + "." + YML_EXTENTION) != null) {
            fileStream = getClasspathResourceAsStream(CONFIG_FILE_NAME + "." + YML_EXTENTION);
            fileExtention = YML_EXTENTION;
        } else if (getClasspathResourceAsStream(CONFIG_FILE_NAME + "." + YAML_EXTENTION) != null) {
            fileStream = getClasspathResourceAsStream(CONFIG_FILE_NAME + "." + YAML_EXTENTION);
            fileExtention = YAML_EXTENTION;
        } else if (getClasspathResourceAsStream(CONFIG_FILE_NAME + "." + XML_EXTENTION) != null) {
            fileStream = getClasspathResourceAsStream(CONFIG_FILE_NAME + "." + XML_EXTENTION);
            fileExtention = XML_EXTENTION;
        } else {

            String defaultConfigDir = System.getProperty("user.dir");
            String defaultConfigPath = scanConfigFile(defaultConfigDir);
            fileExtention = FilenameUtils.getExtension(defaultConfigPath);
            fileStream = getFileAsStream(new File(defaultConfigPath));
        }
        ConfigurationStream config = new ConfigurationStream();
        config.setExtention(fileExtention);
        config.setInputStream(fileStream);
        return config;
    }
564854
public void read_config(InputStream in) throws Exception {

        JsonFactory f = new MappingJsonFactory();
        JsonParser jp = f.createJsonParser(in);

        JsonToken current;

        current = jp.nextToken();
        if (current != JsonToken.START_OBJECT) {
            logger.warn("read_config: Error:  START_OBJECT not found : quiting.");
            return;
        }
        current = jp.nextToken();
        String fieldName = jp.getCurrentName();
        current = jp.nextToken();
        if (fieldName.equals("config")) {
            if (current != JsonToken.START_OBJECT) {
                logger.warn("read_config: Error:  START_OBJECT not found after config : quiting.");
                return;
            }
            current = jp.nextToken();
            String fieldName2 = jp.getCurrentName();
            if (fieldName2.equals("metric_groups")) {
                current = jp.nextToken();
                if (current != JsonToken.START_ARRAY) {
                  logger.warn("read_config: Error:  START_ARRAY not found after metric_groups : quiting.");
                  return;
                }

                current = jp.nextToken();
                while (current != JsonToken.END_ARRAY) {
                    if (current != JsonToken.START_OBJECT) {
                        logger.warn("read_config: Error:  START_OBJECT not found after metric_groups START_ARRAY : quiting.");
                        return;
                    }
                    current = jp.nextToken();
                    JsonNode node1 = jp.readValueAsTree();
                    String node1string = write_tostring(node1);
                    metricgroupMap.put(node1.get("name").asText(),node1string);
                    current = jp.nextToken();
                }

                current = jp.nextToken();
                String fieldName3 = jp.getCurrentName();

                if (fieldName3.equals("dashboards")) {
                    current = jp.nextToken();
                    if (current != JsonToken.START_ARRAY) {
                        logger.warn("read_config: Error:  START_ARRAY not found after dashboards : quiting.");
                        return;
                    }
                    current = jp.nextToken();
                    while (current != JsonToken.END_ARRAY) {
                        if (current != JsonToken.START_OBJECT) {
                            logger.warn("read_config: Error:  START_OBJECT not found after dashboards START_ARRAY : quiting.");
                            return;
                        }
                        current = jp.nextToken();
                        JsonNode node = jp.readValueAsTree();
                        String nodestring = write_tostring(node);
                        dashMap.put(node.get("name").asText(),nodestring);
                        current = jp.nextToken();

                    }
                    if(jp.nextToken() != JsonToken.END_OBJECT) {
                        logger.warn("read_config: Error:  END_OBJECT expected, not found (1): quiting.");
                        return;
                    }
                    if(jp.nextToken() != JsonToken.END_OBJECT) {
                        logger.warn("read_config: Error:  END_OBJECT expected, not found (2): quiting.");
                        return;
                    }
                } else {
                    logger.warn("read_config: Error:  Expected dashboards : quiting.");
                    return;
                }
            } else {
                logger.warn("read_config: Error:  Expected metric_groups : quiting.");
                return;
            }
        }
    }
449429
def _read_config(cls):
        

        cls._config_parser = configparser.ConfigParser()
        cls._config_parser.read(cls._default_attribute_values_configuration_file_path)
1245981
def parse_yaml_file(self, path):
        """"""
        with open(path, 'r') as fp:
            data = yaml.safe_load(fp)

        if not data:
            return {}

        def traverse(namespace, d):
            cfg = {}
            for key, val in d.items():
                if isinstance(d[key], dict):
                    cfg.update(traverse(namespace + [key], d[key]))
                else:
                    if not isinstance(val, str):
                        # All values should be double-quoted strings so they
                        # parse as strings; anything else is a configuration
                        # error at parse-time
                        raise ConfigurationError(
                            'Invalid value %r in file %s: values must be double-quoted strings' % (
                                val, path
                            )
                        )

                    cfg['_'.join(namespace + [key]).upper()] = val

            return cfg

        return traverse([], data)
1128325
def parse_config(config_file):
    """"""
    try:
        with open(config_file, 'r') as f:
            return yaml.load(f)
    except IOError:
        print "Configuration file {} not found or not readable.".format(config_file)
        raise
185469
def from_file(cls, config_path=None, *args, **kwargs):
        

        config_reader = kaptan.Kaptan()

        config = {}

        if config_path:
            if not os.path.exists(config_path):
                raise exc.CihaiException(
                    '{0} does not exist.'.format(os.path.abspath(config_path))
                )
            if not any(
                config_path.endswith(ext) for ext in ('json', 'yml', 'yaml', 'ini')
            ):
                raise exc.CihaiException(
                    '{0} does not have a yaml,yml,json,ini extend.'.format(
                        os.path.abspath(config_path)
                    )
                )
            else:
                custom_config = config_reader.import_config(config_path).get()
                config = merge_dict(config, custom_config)

        return cls(config)
520308
def parseconf (self, filename):
        """"""
        with open(filename) as fd:
            # yet another config format, sigh
            for line in fd:
                line = line.strip()
                if not line or line.startswith("#"):
                    # ignore empty lines and comments
                    continue
                split = line.split(None, 1)
                if len(split) == 1:
                    self[split[0]] = True
                else:
                    self[split[0]] = split[1]