Parse and validate a gateway configuration file.

@param configFile the configuration file
@return GatewayConfig the parsed gateway configuration
@throws Exception when a problem occurs
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;
    }
1144098
public static function readConfigFile($file = self::DEFAULT_CONFIG_FILE)
    {
        if (!is_string($file)) {
            throw new InvalidArgumentException('The config file path must be a string, type passed "'.gettype($file).'".');
        }

        $baseDir = realpath(dirname($file));
        $searchDirs = array(
            $baseDir.'/',
            $baseDir.'/../',
            $baseDir.'/../../',
            $baseDir.'/config/',
            $baseDir.'/../config/',
            $baseDir.'/../../config/'
        );

        $filename = basename($file);

        $configFile = null;
        foreach ($searchDirs as $dir) {
            if (realpath($dir.$filename) and is_readable($dir.$filename)) {
                $configFile = realpath($dir.$filename);
                break;
            }
        }

        if (is_null($configFile) and $file !== self::DEFAULT_CONFIG_FILE) {
            throw new InvalidArgumentException('The config file "'.$file.'" cannot be found or read.');
        }

        if (!$configFile) {
            return static::$config;
        }

        // Try to parse the contents
        try {
            $yaml = Yaml\Yaml::parse(file_get_contents($configFile));
        } catch (Yaml\Exception\ParseException $e) {
            throw new Exception('Unable to parse the config file: '.$e->getMessage());
        }

        return static::$config = $yaml;
    }
654115
func ParseConfigFile(path string) (*Config, error) {
	path, err := filepath.Abs(path)
	if err != nil {
		return nil, err
	}

	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	config, err := ParseConfig(f)
	if err != nil {
		return nil, err
	}

	return config, nil
}
270333
private void getPfile() throws ConfigException {
    if (pfile != null) {
      return;
    }

    String pfileUri = System.getProperty(pfilePname);

    if (pfileUri == null) {
      throw new ConfigException("No property with name \"" +
                                        pfilePname + "\"");
    }

    try {
/*
      URI uri;
      uri = new URI(pfileUri);

      String scheme = uri.getScheme();

      if ((scheme == null) || (scheme.equals("file"))) {
        */
      String path = pfileUri;
      File f = new File(path);
      if (!f.exists()) {
        throw new ConfigException("No configuration pfile at " + path);
      }

      if (!f.isFile()) {
        throw new ConfigException(path + " is not a file");
      }

      final Util.PropertiesPropertyFetcher ppf =
              new Util.PropertiesPropertyFetcher(System.getProperties());

        synchronized (pfileLock) {
          if (pfile != null) {
            // Someone beat us to it
            return;
          }

          pfile = new Properties();
          pfile.load(new FileReader(f));

          /* Do any property replacement on values */
          Set pfileNames = pfile.keySet();

          for (Object o: pfileNames) {
            pfile.put(o, Util.propertyReplace(pfile.getProperty((String)o),
                                              ppf));
          }

          configBase = pfile.getProperty(configBasePname);

          URI uri = new URI(configBase);
          String scheme = uri.getScheme();

          if ((scheme == null) || (scheme.equals("file"))) {
            configBase = uri.getPath();
            configBaseIsFile = true;
          } else if (httpSchemes.contains(scheme)) {
            configBaseIsHttp = true;
          } else {
            throw new ConfigException("Unsupported scheme in " + uri);
          }
        }

/*        return;
      }

      throw new ConfigException("Unsupported configuration pfile: " + uri);
      */
    } catch (ConfigException ce) {
      throw ce;
    } catch (Throwable t) {
      throw new ConfigException(t);
    }
  }
743568
public static Configuration newConfig(@NotNull File configFile) {
		return new Configuration(OneOrOther.<File, Path>ofOne(configFile), false);
	}
880916
protected function fetchConfig($configFile)
    {
        if (is_string($configFile) && ! is_readable($configFile)) {
            $configFile = [];
        }

        return ConfigFactory::create($configFile);
    }
490284
public static ClientInterface getConfigRestClientUtil(String elasticSearch,String configFile){
		ElasticSearch elasticSearchSink = getElasticSearchSink( elasticSearch);
		return elasticSearchSink.getConfigRestClientUtil(configFile);
	}
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;
        }
    }
1023455
public void validateUpdateFile(Long configId, String fileName) {

        //
        // config
        //
        Config config = valideConfigExist(configId);

        //
        // value
        //
        try {

            if (!config.getName().equals(fileName)) {
                throw new Exception();
            }

        } catch (Exception e) {

            throw new FieldException("value", "conf.file.name.not.equal", e);
        }

    }
182971
protected static Properties loadConfig(File file) {
    InputStream is = null;
    try {
      is = new FileInputStream(file);
      return loadConfig(file.getAbsolutePath(), is);     
    } catch (Exception ex) {
      throw new IllegalArgumentException("Failed to load configuration from [" + file.getAbsolutePath() + "]");
    }finally {
      if(is!=null) try { is.close(); } catch (Exception ex) { /* No Op */ }
    }
  }
906828
static void generateConfigFile(String configFilePath) throws ConfigurationException {
        String fileExtention = FilenameUtils.getExtension(configFilePath);
        ConfigProvider<Configuration> provider = getProviderByFileExtention(fileExtention);
        if (!AuditUtil.isFileExists(configFilePath)) {
            provider.generateConfig(Configuration.DEFAULT, configFilePath);
        }
    }
287922
public static function getInstance($configFile='config.yml')
    {
        static $instance = null;
        if (null === $instance) {
            $instance = new static();
        }

        $configuration = Yaml::parse(file_get_contents($configFile));
        $instance->setParams($configuration);

        return $instance;
    }
518541
public static final void xmlConfig(File configFile) throws IOException
    {
        try
        {
            JAXBContext jaxbCtx = JAXBContext.newInstance("org.vesalainen.util.jaxb");
            Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();
            JavaLoggingConfig javaLoggingConfig = (JavaLoggingConfig) unmarshaller.unmarshal(configFile);
            Map<String,String> expressionMap = new HashMap<>();
            Properties properties = javaLoggingConfig.getProperties();
            if (properties != null)
            {
                for (Element element : properties.getAny())
                {
                    String property = element.getTagName();
                    String expression = element.getTextContent();
                    expressionMap.put(property, expression);
                }
            }
            ExpressionParser ep = new ExpressionParser(expressionMap);
            for (LoggerType loggerType : javaLoggingConfig.getLogger())
            {
                String name = ep.replace(loggerType.getName());
                JavaLogging javaLogging = getLogger(name);
                Logger logger = javaLogging.getLogger();
                String lev = ep.replace(loggerType.getLevel());
                Level level = lev != null ? BaseLogging.parseLevel(lev) : null;
                if (level != null)
                {
                    logger.setLevel(level);
                }
                logger.setUseParentHandlers(parseBoolean(ep.replace(loggerType.getUseParentHandlers())));
                String resourceBundleString = ep.replace(loggerType.getResourceBundle());
                if (resourceBundleString != null)
                {
                    Locale locale;
                    String languageTag = ep.replace(loggerType.getLocale());
                    if (languageTag != null)
                    {
                        locale = Locale.forLanguageTag(languageTag);
                    }
                    else
                    {
                        locale = Locale.getDefault();
                    }
                    ResourceBundle resourceBundle = ResourceBundle.getBundle(resourceBundleString, locale);
                    logger.setResourceBundle(resourceBundle);
                }
                logger.setFilter(getInstance(ep.replace(loggerType.getFilter())));
                for (ConsoleHandlerType consoleHandlerType : loggerType.getConsoleHandler())
                {
                    logger.addHandler(createConsoleHandler(ep, consoleHandlerType, level));
                }
                for (FileHandlerType fileHandlerType : loggerType.getFileHandler())
                {
                    logger.addHandler(createFileHandler(ep, fileHandlerType, level));
                }
                for (MemoryHandlerType memoryHandlerType : loggerType.getMemoryHandler())
                {
                    logger.addHandler(createMemoryHandler(ep, memoryHandlerType, level));
                }
                for (SocketHandlerType socketHandlerType : loggerType.getSocketHandler())
                {
                    logger.addHandler(createSocketHandler(ep, socketHandlerType, level));
                }
            }
        }
        catch (JAXBException ex)
        {
            throw new RuntimeException(ex);
        }
    }
39955
static Config loadOvercastConfigFromFile(String file) {

        if (file == null) {
            return ConfigFactory.empty();
        }

        File f = new File(file);
        if (!f.exists()) {
            logger.warn("File {} not found.", f.getAbsolutePath());
            return ConfigFactory.empty();
        }

        logger.info("Loading from file {}", f.getAbsolutePath());
        return ConfigFactory.parseFile(f);
    }
1298368
public static function getConfigurationByConfigFile($configFile)
    {
        if (file_exists($configFile) === false) {
            $message = 'Configuration file "%s" not found or accessible.';
            $message = sprintf($message, $configFile);
            throw new \RuntimeException($message, 1415381521);
        }

        $config = Yaml::parse($configFile);
        $configuration = new Configuration($config);

        return $configuration;
    }
89296
public static ConfigDocument parseFile(File file, ConfigParseOptions options) {
        return Parseable.newFile(file, options).parseConfigDocument();
    }
739154
def get_config(self, configfile):
        
        with open(configfile) as config_file:
            config = json.load(config_file)
        return config