Configures logging from xml file.
@param configFile
@throws IOException
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);
        }
    }
777545
public static void writeConfiguration(Configuration cfg, File file) throws IOException {
		try (FileWriter fwrt = new FileWriter(file);
			PrintWriter out = new PrintWriter(fwrt)) {
			for (String key : cfg.keySet()) {
				String value = cfg.getString(key, null);
				out.print(key);
				out.print(": ");
				out.println(value);
			}
		}
	}
16097
public final Configuration getConfig(final File configFile, final InputStream configData)
            throws IOException {
        final Configuration configuration = this.context.getBean(Configuration.class);
        configuration.setConfigurationFile(configFile);
        MapfishPrintConstructor.setConfigurationUnderConstruction(configuration);

        final Configuration config =
                this.yaml.load(new InputStreamReader(configData, "UTF-8"));
        if (this.doValidation) {
            final List<Throwable> validate = config.validate();
            if (!validate.isEmpty()) {
                StringBuilder errors = new StringBuilder();
                for (Throwable throwable: validate) {
                    errors.append("\n\t* ").append(throwable.getMessage());
                    LOGGER.error("Configuration Error found", throwable);
                }
                throw new Error(errors.toString(), validate.get(0));
            }
        }
        return config;
    }
1329962
public void configLogger()
    {
        Map<String, Level> logLevels = new HashMap<String, Level>();
        logLevels.put("trace", Level.TRACE);
        logLevels.put("debug", Level.DEBUG);
        logLevels.put("info", Level.INFO);
        logLevels.put("warning", Level.WARNING);
        logLevels.put("error", Level.ERROR);

        if( this.get("logging_log_type", "file").equals("file") ){

            DateFormat dateFormat = new SimpleDateFormat(this.get("logging_current_date_format","yyyy-MM-dd"));
            Date date = new Date();
            String logFileName = (this.get("logging_file_format", "current_date").equals("current_date")) ? dateFormat.format(date) + ".log" : this.get("logging_file_format", "current_date") + ".log";
            Configurator.defaultConfig()
                .writer(new FileWriter(this.get("logging_file_path", "src/main/java/resources/") + logFileName, (this.get("logging_buffered", "false").equals("true")) ? true : false, (this.get("logging_append", "true").equals("true")) ? true : false))
                .level((logLevels.containsKey(this.get("logging_level","debug"))) ? logLevels.get(this.get("logging_level","debug")) : Level.INFO)
                .activate();

        }else if( this.get("logging_log_type", "file").equals("both") ){

            DateFormat dateFormat = new SimpleDateFormat(this.get("logging_current_date_format","yyyy-MM-dd"));
            Date date = new Date();
            String logFileName = (this.get("logging_file_format", "current_date").equals("current_date")) ? dateFormat.format(date) + ".log" : this.get("logging_file_format", "current_date") + ".log";
            Configurator.defaultConfig()
                .writer(new ConsoleWriter())
                .addWriter(new FileWriter(this.get("logging_file_path", "src/main/java/resources/") + logFileName))
                .level((logLevels.containsKey(this.get("logging_level","debug"))) ? logLevels.get(this.get("logging_level","debug")) : Level.INFO)
                .activate();

        }else{

            Configurator.defaultConfig()
                .writer(new ConsoleWriter())
                .level((logLevels.containsKey(this.get("logging_level","debug"))) ? logLevels.get(this.get("logging_level","debug")) : Level.INFO)
                .activate();

        }
    }
160710
protected function loadConfiguration($configFile = false)
    {
        if ($configFile === false) {
            return;
        }
        echo "\nLoad configuration";

        $configuration = require $configFile;

        foreach ($configuration as $name => $value) {
            if ($this->module->canSetProperty($name) == true) {
                $this->module->$name = $value;
            } else {
                throw new InvalidConfigException("Invalid configuration. Unknown configuration option '{$name}'");
            }
        }
        $this->module->loadComponents();
    }
239672
public void init(Path configFile) {
        String abspath = configFile.toAbsolutePath().toString();
        System.out.println("initialize user dictionary:" + abspath);
        synchronized (WordDictionary.class) {
            if (loadedPath.contains(abspath))
                return;
            
            DirectoryStream<Path> stream;
            try {
                stream = Files.newDirectoryStream(configFile, String.format(Locale.getDefault(), "*%s", USER_DICT_SUFFIX));
                for (Path path: stream){
                    System.err.println(String.format(Locale.getDefault(), "loading dict %s", path.toString()));
                    singleton.loadUserDict(path);
                }
                loadedPath.add(abspath);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                // e.printStackTrace();
                System.err.println(String.format(Locale.getDefault(), "%s: load user dict failure!", configFile.toString()));
            }
        }
    }
42738
public static void configureFiles(Iterable<File> files)
	{
		for (File file : files)
		{
			if (file != null && file.exists() && file.canRead())
			{
				setup(file);
				return;
			}
		}

		System.out.println("(No suitable log config file found)");
	}
924383
synchronized public static void loadAdapters(String configFile) {

    InputStream is = CpoClassLoader.getResourceAsStream(configFile);
    if (is == null) {
      logger.info("Resource Not Found: " + configFile);
      try {
        is = new FileInputStream(configFile);
      } catch (FileNotFoundException fnfe) {
        logger.info("File Not Found: " + configFile);
        is = null;
      }
    }

    try {
      CpoConfigDocument configDoc;
      if (is == null) {
        configDoc = CpoConfigDocument.Factory.parse(configFile);
      } else {
        configDoc = CpoConfigDocument.Factory.parse(is);
      }

      String errMsg = XmlBeansHelper.validateXml(configDoc);
      if (errMsg != null) {
        logger.error("Invalid CPO Config file: " + configFile + ":" + errMsg);
      } else {
        logger.info("Processing Config File: " + configFile);
        // Moving the clear to here to make sure we get a good file before we just blow away all the adapters.
        // We are doing a load clear all the caches first, in case the load gets called more than once.
        CpoMetaDescriptor.clearAllInstances();
        clearCpoAdapterFactoryCache();

        CtCpoConfig cpoConfig = configDoc.getCpoConfig();

        // Set the default context.
        if (cpoConfig.isSetDefaultConfig()) {
          defaultContext = cpoConfig.getDefaultConfig();
        } else {
          // make the first listed config the default.
          defaultContext = cpoConfig.getDataConfigArray(0).getName();
        }

        for (CtMetaDescriptor metaDescriptor : cpoConfig.getMetaConfigArray()) {
          boolean caseSensitive = true;
          if (metaDescriptor.isSetCaseSensitive()) {
            caseSensitive = metaDescriptor.getCaseSensitive();
          }

          // this will create and cache, so we don't need the return
          CpoMetaDescriptor.getInstance(metaDescriptor.getName(), metaDescriptor.getMetaXmlArray(), caseSensitive);
        }

        // now lets loop through all the adapters and get them cached.
        for (CtDataSourceConfig dataSourceConfig : cpoConfig.getDataConfigArray()) {
          CpoAdapterFactory cpoAdapterFactory = makeCpoAdapterFactory(dataSourceConfig);
          if (cpoAdapterFactory != null) {
            addCpoAdapterFactory(dataSourceConfig.getName(), cpoAdapterFactory);
          }
        }
      }
    } catch (IOException ioe) {
      logger.error("Error reading " + configFile + ": ", ioe);
    } catch (XmlException xe) {
      logger.error("Error processing " + configFile + ": Invalid XML");
    } catch (CpoException ce) {
      logger.error("Error processing " + configFile + ": ", ce);
    }
  }
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;
        }
    }
273373
private void loadConfigFile(String configFile) {
    try (InputStream is = new FileInputStream(configFile)) {
      mProperties.load(is);
    } catch (Exception e) {
      LOG.error("Error loading metrics configuration file.", e);
    }
  }
667102
protected void setupLogback() {

        // Check for Logback config file System Property
        // http://logback.qos.ch/manual/configuration.html
        //     -Dlogback.configurationFile=logback_prod.xml
        if (System.getProperty(LOGBACK_CONFIGURATION_FILE_PROPERTY) != null) {
            // Logback already configured
            return;
        }

        // Check for a logback configuration file declared in Fathom settings
        URL configFileUrl = settings.getFileUrl(LOGBACK_CONFIGURATION_FILE_PROPERTY, "classpath:conf/logback.xml");

        if (configFileUrl == null) {
            throw new FathomException("Failed to find Logback config file '{}'",
                    settings.getString(LOGBACK_CONFIGURATION_FILE_PROPERTY, "classpath:conf/logback.xml"));
        }

        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

        try (InputStream is = configFileUrl.openStream()) {
            JoranConfigurator configurator = new JoranConfigurator();
            configurator.setContext(context);
            context.reset();
            configurator.doConfigure(is);
            log.info("Configured Logback from '{}'", configFileUrl);
        } catch (IOException | JoranException je) {
            // StatusPrinter will handle this
        }

        StatusPrinter.printInCaseOfErrorsOrWarnings(context);
    }
881095
private static void setupLogging(Config config) throws IOException {
    String systemConfigFilename = Context.systemConfigFile(config);

    SystemConfig systemConfig = SystemConfig.newBuilder(true)
        .putAll(systemConfigFilename, true)
        .build();

    // Init the logging setting and redirect the stdout and stderr to logging
    // For now we just set the logging level as INFO; later we may accept an argument to set it.
    Level loggingLevel = Level.INFO;
    if (Context.verbose(config).booleanValue()) {
      loggingLevel = Level.FINE;
    }
    // TODO(mfu): The folder creation may be duplicated with heron-executor in future
    // TODO(mfu): Remove the creation in future if feasible
    String loggingDir = systemConfig.getHeronLoggingDirectory();
    if (!FileUtils.isDirectoryExists(loggingDir)) {
      FileUtils.createDirectory(loggingDir);
    }

    // Log to file
    LoggingHelper.loggerInit(loggingLevel, true);

    // TODO(mfu): Pass the scheduler id from cmd
    String processId =
        String.format("%s-%s-%s", "heron", Context.topologyName(config), "scheduler");
    LoggingHelper.addLoggingHandler(
        LoggingHelper.getFileHandler(processId, loggingDir, true,
            systemConfig.getHeronLoggingMaximumSize(),
            systemConfig.getHeronLoggingMaximumFiles()));

    LOG.info("Logging setup done.");
  }
737964
public void storeSettingsToFile(File file) throws IOException {
    FileOutputStream fos = new FileOutputStream(file);
    this.conf.writeXml(fos);
    fos.close();
  }
710627
public synchronized void storeConfiguration() throws IOException
    {
        OutputStream out = new FileOutputStream(configFilePath);
        configuration.store(out, configFilePath);
    }
1272992
private void parseLoggerConfig(final Node node,
			final ConfigSettings config, final ConfigurationKeys logPath,
			final ConfigurationKeys logLevel)
	{

		String name, value;
		Level level;
		Node nnode;
		NodeList list = node.getChildNodes();

		int length = list.getLength();
		for (int i = 0; i < length; i++) {
			nnode = list.item(i);

			name = nnode.getNodeName().toUpperCase();
			if (name.equals(KEY_LOG_PATH)) {

				value = nnode.getChildNodes().item(0).getNodeValue();
				value = value.substring(1, value.length() - 1);
				config.setConfigParameter(logPath, value);

			}
			else if (name.equals(KEY_LOG_LEVEL)) {

				level = Level.valueOf(nnode.getChildNodes().item(0)
						.getNodeValue());
				config.setConfigParameter(logLevel, level);
			}
		}
	}
45037
@Override
    public void configFields(Configuration conf, String[] fields) throws IOException {
        if (null != fields) {
            super.configFields(conf, fields);
            for (int i = 0; i < fields.length; i++) {
                if(fields[i].trim().equals("")) continue;
                if (!XML11Char.isXML11ValidName(fields[i])) {
                    fields[i] = XMLUtil.getValidName(fields[i]);
                }
            }
        } else {
            throw new IOException("Fields not defined");
        }
    }