Creates a new NetworkConfig instance configured with details supplied in a JSON file.

@param configFile The file containing the network configuration
@return A new NetworkConfig instance
@throws InvalidArgumentException
@throws IOException
189575
public static NetworkConfig fromJsonFile(File configFile) throws InvalidArgumentException, IOException, NetworkConfigurationException {
        return fromFile(configFile, true);
    }
1360515
public static boolean configure (File configFile) {
		boolean goOn = true;

		if (!configFile.exists ()) {
			LogHelperDebug.printError ("File " + configFile.getAbsolutePath () + " does not exist", false);
			goOn = false;
		}

		DocumentBuilderFactory documentBuilderFactory = null;
		DocumentBuilder documentBuilder = null;
		if (goOn) {
			documentBuilderFactory = DocumentBuilderFactory.newInstance ();

			try {
				documentBuilder = documentBuilderFactory.newDocumentBuilder ();
			} catch (ParserConfigurationException ex) {
				LogHelperDebug.printError (ex.getMessage (), ex, false);
				goOn = false;
			}
		}

		Document configDocument = null;
		if (goOn) {
			try {
				configDocument = documentBuilder.parse (configFile);
			} catch (SAXException ex) {
				LogHelperDebug.printError (ex.getMessage (), ex, false);
				goOn = false;
			} catch (IOException ex) {
				LogHelperDebug.printError (ex.getMessage (), ex, false);
				goOn = false;
			}
		}

		NodeList configNodeList = null;
		if (goOn) {
			configNodeList = configDocument.getElementsByTagName ("log-helper");
			if (configNodeList == null) {
				LogHelperDebug.printError ("configNodeList is null", false);
				goOn = false;
			} else if (configNodeList.getLength () < 1) {
				LogHelperDebug.printError ("configNodeList is empty", false);
				goOn = false;
			}
		}

		Node configNode = null;
		if (goOn) {
			configNode = configNodeList.item (0);
			if (configNode == null) {
				LogHelperDebug.printError ("configNode is null", false);
				goOn = false;
			}
		}

		boolean success = false;
		if (goOn) {
			success = configure (configNode);
		}

		return success;
	}
501160
public GatewayConfigDocument parse(final File configFile) throws Exception {
        long time = 0;
        if (LOGGER.isDebugEnabled()) {
            time = System.currentTimeMillis();
        }

        // For errors and logging (KG-1379) we need to report the real config file name,
        // which is not always 'gateway-config.xml'.
        String configFileName = configFile.getName();

        // Validate the gateway-config
        GatewayConfigDocument config = null;
        XmlOptions parseOptions = new XmlOptions();
        parseOptions.setLoadLineNumbers();
        parseOptions.setLoadLineNumbers(XmlOptions.LOAD_LINE_NUMBERS_END_ELEMENT);
        parseOptions.setLoadStripWhitespace();
        parseOptions.setLoadStripComments();

        File translatedConfigFile;
        try {
            translatedConfigFile = getTranslatedConfigFile(configFile);
        } catch (Exception e) {
            Throwable rootCause = getRootCause(e);
            if (rootCause == null) {
                rootCause = e;
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.error("Error upgrading XML: " + rootCause, rootCause);

            } else {
                LOGGER.error("Error upgrading XML: " + rootCause);
            }

            // If it's not an IllegalArgumentException, wrap it in a
            // GatewayConfigParserException
            if (e instanceof IllegalArgumentException) {
                throw e;

            } else {
                throw new GatewayConfigParserException(e.getMessage());
            }
        }

        List<String> xmlParseErrors = new ArrayList<>();
        try {
            config = GatewayConfigDocument.Factory.parse(new FileInputStream(translatedConfigFile), parseOptions);

        } catch (Exception e) {
            // track the parse error so that we don't make the 2nd pass through the file
            xmlParseErrors.add("Invalid XML: " + getRootCause(e).getMessage());
        }

        if (xmlParseErrors.isEmpty()) {
            // The properties used in parameter substitution are now proper XMLBeans
            // and should be injected after an initial parse
            GatewayConfigDocument.GatewayConfig gatewayConfig = config.getGatewayConfig();
            PropertiesType properties = gatewayConfig.getProperties();
            Map<String, String> propertiesMap = new HashMap<>();
            if (properties != null) {
                for (PropertyType propertyType : properties.getPropertyArray()) {
                    propertiesMap.put(propertyType.getName(), propertyType.getValue());
                }
            }

            // make a second pass through the file now, injecting the properties and performing XSL translations
            InputStream xmlInjectedIn = new PipedInputStream();
            OutputStream xmlInjectedOut = new PipedOutputStream((PipedInputStream) xmlInjectedIn);
            ExecutorService xmlInjectedExecutor = Executors.newSingleThreadExecutor();
            Future<Boolean> xmlInjectedFuture = xmlInjectedExecutor.submit(new XMLParameterInjector(new FileInputStream(
                    translatedConfigFile), xmlInjectedOut, propertiesMap, configuration, xmlParseErrors));

            // trace injected xml
            if (LOGGER.isTraceEnabled()) {
                xmlInjectedIn = bufferToTraceLog(xmlInjectedIn,
                        "Gateway config file '" + configFileName + "' post parameter injection", LOGGER);
            }

            // Pass gateway-config through the pre-parse transformer
            InputStream xmlTransformedIn = new PipedInputStream();
            OutputStream xmlTransformedOut = new PipedOutputStream((PipedInputStream) xmlTransformedIn);
            ExecutorService xmlTransformedExecutor = Executors.newSingleThreadExecutor();
            Future<Boolean> xmlTransformedFuture = xmlTransformedExecutor.submit(
                    new XSLTransformer(xmlInjectedIn, xmlTransformedOut, GATEWAY_CONFIG_ANNOTATE_TYPES_XSL));

            // trace transformed xml
            if (LOGGER.isTraceEnabled()) {
                xmlTransformedIn = bufferToTraceLog(xmlTransformedIn,
                        "Gateway config file '" + configFileName + "' post XSL transformation", LOGGER);
            }

            try {
                config = GatewayConfigDocument.Factory.parse(xmlTransformedIn, parseOptions);
            } catch (Exception e) {
                // If parsing with previous namespace was also unsuccessful,
                // process errors top down, failing fast, for user level errors
               try {
                    if (xmlInjectedFuture.get()) {
                        if (xmlTransformedFuture.get()) {
                            throw e;
                        }
                    }
                } catch (Exception n) {
                    xmlParseErrors.add("Invalid XML: " + getRootCause(n).getMessage());
                }
            } finally {
                xmlInjectedFuture.cancel(true);
                xmlInjectedExecutor.shutdownNow();
                xmlTransformedFuture.cancel(true);
                xmlTransformedExecutor.shutdownNow();
            }
        }

        validateGatewayConfig(config, xmlParseErrors);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("parsed " + " gateway config file '" + configFileName + "' in [" + (System.currentTimeMillis() - time) +
                    " ms]");
        }

        return config;
    }
899862
public static function fromJson($configFilePath)
    {
        $configArray = json_decode(file_get_contents($configFilePath), true);
        if (!is_array($configArray)) {
            throw new \RuntimeException(sprintf(
                'File \'%s\' must be valid JSON',
                $configFilePath
            ));
        }

        return new static($configArray, $configFilePath);
    }
801351
private function configure($configFile) {
    if (!file_exists($configFile)) {
      throw new ConfigurationException('Configuration file '.$configFile.' not found');
    }
    $config = parse_ini_file($configFile, true);

    // default settings
    if (isset($config[self::ROOT_SECTION_NAME])) {
      $rootConfig = $config[self::ROOT_SECTION_NAME];
      self::$defaultLevel = isset($rootConfig['level']) ?
              constant('Monolog\Logger::'.strtoupper($rootConfig['level'])) :
              self::$defaultLevel;
      self::$logTarget = isset($rootConfig['target']) ?
              $rootConfig['target'] : WCMF_BASE.self::$logTarget;
    }

    // log levels
    self::$levels = isset($config[self::LOGGER_SECTION_NAME]) ?
            $config[self::LOGGER_SECTION_NAME] : [];
    foreach (self::$levels as $key => $val) {
      self::$levels[$key] = constant('Monolog\Logger::'.strtoupper($val));
    }
  }
961964
private void createDefaultConfigurationFile() throws IOException
    {
        
        File configFile = new File(configFilePath);
        
        if (configFile.exists()) {
            //seems a problem with access rights, report error
            throw new IOException();
        }
        else {
            //create the default file
            
            //create config dir if not exists yet
            File parentDir = configFile.getParentFile();
            if (!parentDir.exists())
                parentDir.mkdirs();
            
            //create config file
            configFile.createNewFile();
            
            Properties config = new Properties();
            
            fillDefaultProperties(config);
            
            OutputStream fileOutput = new FileOutputStream(configFile);
            config.store(fileOutput, automaticFileMsg);
        }
        
    }
739154
def get_config(self, configfile):
        
        with open(configfile) as config_file:
            config = json.load(config_file)
        return config
785892
public static function config($configFile = null)
    {
        if (!$configFile && self::$config) {
            return self::$config;
        }

        if (self::$config && self::$lock) {
            return self::$config;
        }

        if ($configFile === null) {
            $configFile = getcwd() . DIRECTORY_SEPARATOR . 'codeception.yml';
        }

        if (is_dir($configFile)) {
            $configFile = $configFile . DIRECTORY_SEPARATOR . 'codeception.yml';
        }

        $dir = realpath(dirname($configFile));
        self::$dir = $dir;

        $configDistFile = $dir . DIRECTORY_SEPARATOR . 'codeception.dist.yml';

        if (!(file_exists($configDistFile) || file_exists($configFile))) {
            throw new ConfigurationException("Configuration file could not be found.\nRun `bootstrap` to initialize Codeception.", 404);
        }

        // Preload config to retrieve params such that they are applied to codeception config file below
        $tempConfig = self::$defaultConfig;

        $distConfigContents = "";
        if (file_exists($configDistFile)) {
            $distConfigContents = file_get_contents($configDistFile);
            $tempConfig = self::mergeConfigs($tempConfig, self::getConfFromContents($distConfigContents, $configDistFile));
        }

        $configContents = "";
        if (file_exists($configFile)) {
            $configContents = file_get_contents($configFile);
            $tempConfig = self::mergeConfigs($tempConfig, self::getConfFromContents($configContents, $configFile));
        }
        self::prepareParams($tempConfig);

        // load config using params
        $config = self::mergeConfigs(self::$defaultConfig, self::getConfFromContents($distConfigContents, $configDistFile));
        $config = self::mergeConfigs($config, self::getConfFromContents($configContents, $configFile));

        if ($config == self::$defaultConfig) {
            throw new ConfigurationException("Configuration file is invalid");
        }

        // we check for the "extends" key in the yml file
        if (isset($config['extends'])) {
            // and now we search for the file
            $presetFilePath = codecept_absolute_path($config['extends']);
            if (file_exists($presetFilePath)) {
                // and merge it with our configuration file
                $config = self::mergeConfigs(self::getConfFromFile($presetFilePath), $config);
            }
        }

        self::$config = $config;

        // compatibility with suites created by Codeception < 2.3.0
        if (!isset($config['paths']['output']) and isset($config['paths']['log'])) {
            $config['paths']['output'] = $config['paths']['log'];
        }

        if (isset(self::$config['actor'])) {
            self::$config['actor_suffix'] = self::$config['actor']; // old compatibility
        }

        if (!isset($config['paths']['support']) and isset($config['paths']['helpers'])) {
            $config['paths']['support'] = $config['paths']['helpers'];
        }

        if (!isset($config['paths']['output'])) {
            throw new ConfigurationException('Output path is not defined by key "paths: output"');
        }

        self::$outputDir = $config['paths']['output'];

        // fill up includes with wildcard expansions
        $config['include'] = self::expandWildcardedIncludes($config['include']);

        // config without tests, for inclusion of other configs
        if (count($config['include'])) {
            self::$config = $config;
            if (!isset($config['paths']['tests'])) {
                 return $config;
            }
        }

        if (!isset($config['paths']['tests'])) {
            throw new ConfigurationException(
                'Tests directory is not defined in Codeception config by key "paths: tests:"'
            );
        }

        if (!isset($config['paths']['data'])) {
            throw new ConfigurationException('Data path is not defined Codeception config by key "paths: data"');
        }

        if (!isset($config['paths']['support'])) {
            throw new ConfigurationException('Helpers path is not defined by key "paths: support"');
        }

        self::$dataDir = $config['paths']['data'];
        self::$supportDir = $config['paths']['support'];
        self::$testsDir = $config['paths']['tests'];

        if (isset($config['paths']['envs'])) {
            self::$envsDir = $config['paths']['envs'];
        }

        Autoload::addNamespace(self::$config['namespace'], self::supportDir());
        self::loadBootstrap($config['settings']['bootstrap']);
        self::loadSuites();

        return $config;
    }
1233200
public static Config loadConfig(File configFile, boolean useSystemEnvironment) {
        return loadConfig(ConfigParseOptions.defaults(),
                ConfigResolveOptions.defaults().setUseSystemEnvironment(useSystemEnvironment),
                configFile);
    }
683980
public void generateConfig(File configFile, ContainerRoot model) throws IOException {
        StringBuilder buffer = new StringBuilder();
        buffer.append(OSHelper.read(this.getClass().getClassLoader().getResourceAsStream("base.cfg")));
        buffer.append("\n");
        HashMap<String, Backend> backends = new HashMap<String, Backend>();
        for (ContainerNode node : model.getNodes()) {
            for (ComponentInstance instance : node.getComponents()) {
                if (instance.getTypeDefinition().getDictionaryType() != null
                        && instance.getTypeDefinition().getDictionaryType().findAttributesByID("http_port") != null
                        && instance.getStarted()
                        && !instance.getName().equals(context.getInstanceName())) {

                    if (!backends.containsKey(instance.getTypeDefinition().getName())) {
                        Backend backend = new Backend();
                        backends.put(instance.getTypeDefinition().getName(), backend);
                    }
                    Backend backend = backends.get(instance.getTypeDefinition().getName());
                    backend.setName(instance.getTypeDefinition().getName());
                    Server s = new Server();
                    s.setIp("127.0.0.1");
                    s.setName(instance.getName());
                    s.setPort(instance.getDictionary().findValuesByID("http_port").getValue());
                    backend.getServers().add(s);
                }
            }
        }

        if (backends.size() > 0) {
            buffer.append("default_backend ");
            String firstKey = backends.keySet().iterator().next();
            buffer.append(backends.get(firstKey).getName());
            buffer.append("\n");
        }
        for (String key : backends.keySet()) {
            buffer.append("\n");
            buffer.append(backends.get(key));
            buffer.append("\n");
        }
        FileWriter writer = new FileWriter(configFile);
        writer.write(buffer.toString());
        writer.close();
    }
255951
public static FrameworkProjectConfig create(
            final String name,
            final File propertyFile,
            final IFilesystemFramework filesystemFramework
    )
    {
        return new FrameworkProjectConfig(name, propertyFile, filesystemFramework);
    }
125791
public void resetFromFile(String configFile) throws IOException
    {
        IStringBuffer isb = new IStringBuffer();
        String line = null;
        BufferedReader reader = new BufferedReader(new FileReader(configFile));
        while ( (line = reader.readLine()) != null ) {
            line = line.trim();
            if (line.equals("")) continue;
            if (line.charAt(0) == '#') continue;
            
            isb.append(line).append('\n');
            line = null;    //let gc do its work
        }
        
        globalConfig = new JSONObject(isb.toString());
        
        //let gc do its work
        isb = null;
        reader.close();
        reader = null;
    }
104247
protected function preloadConfiguration($configFile)
    {
        try {
            Configuration::config($configFile);
        } catch (ConfigurationException $e) {
            if ($e->getCode() == 404) {
                throw new ConfigurationException("Your configuration file `{$configFile}` could not be found.", 405);
            }
            throw $e;
        }
    }
14077
public function setOnDiskConfiguration(?string $configFile = null): ConfigurationBuilder
    {
        $this->configFile = $configFile;

        if ($this->configFile) {
            if (file_exists($path = getcwd() . '/' . $this->configFile)) {
                $this->configFile = $path;
            }

            if (!file_exists($this->configFile)) {
                throw new \InvalidArgumentException('The specified config file is not a valid file.');
            }

            $info = pathinfo($this->configFile);

            $fileExt = strtolower($info['extension']);

            switch ($fileExt) {
                case 'xml':
                    $diskConfig = $this->loadXmlFile($this->configFile);
                    break;

                case 'yml':
                case 'yaml':
                    $diskConfig = Yaml::parse(file_get_contents($this->configFile));
                    break;

                default:
                    throw new \InvalidArgumentException(
                        sprintf(
                            'The specified config file should end in .xml or .yml/.yaml. Unrecognized extension [%s]',
                            $fileExt
                        )
                    );
            }

            $this->configParams = array_merge($this->configParams, $diskConfig);
        }

        return $this;
    }
7283
private static synchronized void initializeLog4JSubSystem(String configFile)
    {
        LoggerFactory.getBootLogger().info("Initializing Log4J using file: '" + configFile + "'");
        if(configFile == null || "".equals(configFile.trim()))
        {
            // no configuration available
            LoggerFactory.getBootLogger().warn("No log4j configuration file specified");
        }
        else
        {
            // try resource look in classpath
            URL url = ClassHelper.getResource(configFile);
            LoggerFactory.getBootLogger().info("Initializing Log4J : resource from config file:" + url);
            if (url != null)
            {
                PropertyConfigurator.configure(url);
            }
            // if file is not in classpath try ordinary filesystem lookup
            else
            {
                PropertyConfigurator.configure(configFile);
            }
        }
        log4jConfigured = true;
    }
531653
private static NetworkConfig load(JsonObject jsonConfig) throws InvalidArgumentException, NetworkConfigurationException {

        // Sanity check
        if (jsonConfig == null) {
            throw new InvalidArgumentException("config must be specified");
        }

        return new NetworkConfig(jsonConfig);
    }
258168
private static ChaincodeCollectionConfiguration fromFile(File configFile, boolean isJson) throws InvalidArgumentException, IOException, ChaincodeCollectionConfigurationException {

        // Sanity check
        if (configFile == null) {
            throw new InvalidArgumentException("configFile must be specified");
        }

        if (logger.isTraceEnabled()) {
            logger.trace(format("ChaincodeCollectionConfiguration.fromFile: %s  isJson = %b", configFile.getAbsolutePath(), isJson));
        }

        // Json file
        try (InputStream stream = new FileInputStream(configFile)) {
            return isJson ? fromJsonStream(stream) : fromYamlStream(stream);
        }

    }