load configuration.
1. initialize the server config
2. register global resource (global resource initialize)

@param  globalConfig
@return JcsegServer
@throws CloneNotSupportedException
@throws JcsegException
439803
public JcsegServer initFromGlobalConfig(JSONObject globalConfig) 
            throws CloneNotSupportedException, JcsegException
    {
        /*
         * parse and initialize the server according to the global config
        */
        if ( globalConfig.has("server_config") ) {
            JSONObject serverSetting = globalConfig.getJSONObject("server_config");
            if ( serverSetting.has("host") ) {
                config.setHost(serverSetting.getString("host"));
            }
            if ( serverSetting.has("port") ) {
                config.setPort(serverSetting.getInt("port"));
            }
            if ( serverSetting.has("charset") ) {
                config.setCharset(serverSetting.getString("charset")); 
            }
            if ( serverSetting.has("max_thread_pool_size") ) {
                config.setMaxThreadPoolSize(serverSetting.getInt("max_thread_pool_size"));
            }
            if ( serverSetting.has("thread_idle_timeout") ) {
                config.setThreadIdleTimeout(serverSetting.getInt("thread_idle_timeout"));
            }
            if ( serverSetting.has("http_output_buffer_size") ) {
                config.setOutputBufferSize(serverSetting.getInt("http_output_buffer_size"));
            }
            if ( serverSetting.has("http_request_header_size") ) {
                config.setRequestHeaderSize(serverSetting.getInt("http_request_header_size"));
            }
            if ( serverSetting.has("http_response_header_size") ) {
                config.setResponseHeaderSize(serverSetting.getInt("http_connection_idle_timeout"));
            }
        }

        //create a global JcsegTaskConfig and initialize from the global_setting
        JcsegTaskConfig globalJcsegTaskConfig = new JcsegTaskConfig(false);
        if ( globalConfig.has("jcseg_global_config") ) {
            JSONObject globalSetting = globalConfig.getJSONObject("jcseg_global_config");
            resetJcsegTaskConfig(globalJcsegTaskConfig, globalSetting);
        }
        
        /*
         * create the dictionaries according to the definition of dict 
         * and we will make a copy of the globalSetting for dictionary load
         * 
         * reset the max length to pass the dictionary words length limitation
        */
        JcsegTaskConfig dictLoadConfig = globalJcsegTaskConfig.clone();
        dictLoadConfig.setMaxLength(100);
        if ( globalConfig.has("jcseg_dict") ) {
            JSONObject dictSetting = globalConfig.getJSONObject("jcseg_dict");
            String[] dictNames = JSONObject.getNames(dictSetting);
            for ( String name : dictNames ) {
                JSONObject dicJson = dictSetting.getJSONObject(name);
                if ( ! dicJson.has("path") ) {
                    throw new JcsegException("Missing path for dict instance " + name);
                }
                
                String[] lexPath = null;
                if ( ! dicJson.isNull("path") ) {
                    //process the lexPath
                    JSONArray path = dicJson.getJSONArray("path");
                    List<String> dicPath = new ArrayList<String>();
                    for ( int i = 0; i < path.length(); i++ ) {
                        String filePath = path.get(i).toString();
                        if ( filePath.indexOf("{jar.dir}") > -1 ) {
                            filePath = filePath.replace("{jar.dir}", Util.getJarHome(this));
                        }
                        dicPath.add(filePath);
                    }
                    
                    lexPath = new String[dicPath.size()];
                    dicPath.toArray(lexPath);
                    dicPath.clear(); dicPath = null;
                }
                
                boolean loadpos = dicJson.has("loadpos") 
                        ? dicJson.getBoolean("loadpos") : true;
                boolean loadpinyin = dicJson.has("loadpinyin") 
                        ? dicJson.getBoolean("loadpinyin") : true;
                boolean loadsyn = dicJson.has("loadsyn") 
                        ? dicJson.getBoolean("loadsyn") : true;
                boolean loadentity = dicJson.has("loadentity") 
                        ? dicJson.getBoolean("loadentity") : true;
                boolean autoload = dicJson.has("autoload") 
                        ? dicJson.getBoolean("autoload") : false;
                int polltime = dicJson.has("polltime") 
                        ? dicJson.getInt("polltime") : 300;
                        
                dictLoadConfig.setLoadCJKPinyin(loadpinyin);
                dictLoadConfig.setLoadCJKPos(loadpos);
                dictLoadConfig.setLoadCJKSyn(loadsyn);
                dictLoadConfig.setLoadEntity(loadentity);
                dictLoadConfig.setAutoload(autoload);
                dictLoadConfig.setPollTime(polltime);
                dictLoadConfig.setLexiconPath(lexPath);
                
                //create and register the global dictionary resource
                ADictionary dic = DictionaryFactory.createDefaultDictionary(dictLoadConfig);
                resourcePool.addDict(name, dic);
            }
        }
        
        dictLoadConfig = null;
        
        /*
         * create the JcsegTaskConfig instance according to the definition config
        */
        if ( globalConfig.has("jcseg_config") ) {
            JSONObject configSetting = globalConfig.getJSONObject("jcseg_config");
            String[] configNames = JSONObject.getNames(configSetting);
            for ( String name : configNames ) {
                JSONObject configJson = configSetting.getJSONObject(name);
                
                //clone the globalJcsegTaskConfig
                //and do the override working by local defination
                JcsegTaskConfig config = globalJcsegTaskConfig.clone();
                if ( configJson.length() > 0 ) {
                    resetJcsegTaskConfig(config, configJson);
                }
                
                //register the global resource
                resourcePool.addConfig(name, config);
            }
        }
        
        /*
         * create the tokenizer instance according the definition of tokenizer
        */
        if ( globalConfig.has("jcseg_tokenizer") ) {
            JSONObject tokenizerSetting = globalConfig.getJSONObject("jcseg_tokenizer");
            String[] tokenizerNames = JSONObject.getNames(tokenizerSetting);
            for ( String name : tokenizerNames ) {
                JSONObject tokenizerJson = tokenizerSetting.getJSONObject(name);
                
                int algorithm = tokenizerJson.has("algorithm") 
                        ? tokenizerJson.getInt("algorithm") : JcsegTaskConfig.COMPLEX_MODE;
                
                if ( ! tokenizerJson.has("dict") ) {
                    throw new JcsegException("Missing dict setting for tokenizer " + name);
                }
                if ( ! tokenizerJson.has("config") ) {
                    throw new JcsegException("Missing config setting for tokenizer " + name);
                }
                
                ADictionary dic = resourcePool.getDict(tokenizerJson.getString("dict"));
                JcsegTaskConfig config = resourcePool.getConfig(tokenizerJson.getString("config"));
                if ( dic == null ) {
                    throw new JcsegException("Unknow dict instance " 
                        + tokenizerJson.getString("dict") + " for tokenizer " + name);
                }
                
                if ( config == null ) {
                    throw new JcsegException("Unknow config instance " 
                        + tokenizerJson.getString("config") + " for tokenizer " + name);
                }
                
                resourcePool.addTokenizerEntry(name, new JcsegTokenizerEntry(algorithm, config, dic));
            }
        }
        
        //now, initialize the server
        init();
        
        return this;
    }
761068
public static void loadExternalSpringConfig(RuntimeSpringConfiguration config, final GrailsApplication application) {
        if (springGroovyResourcesBeanBuilder == null) {
            try {
                Class<?> groovySpringResourcesClass = null;
                try {
                    groovySpringResourcesClass = ClassUtils.forName(SPRING_RESOURCES_CLASS,
                        application.getClassLoader());
                }
                catch (ClassNotFoundException e) {
                    // ignore
                }
                if (groovySpringResourcesClass != null) {
                    reloadSpringResourcesConfig(config, application, groovySpringResourcesClass);
                }
            }
            catch (Exception ex) {
                LOG.error("[RuntimeConfiguration] Unable to load beans from resources.groovy", ex);
            }
        }
        else {
            if (!springGroovyResourcesBeanBuilder.getSpringConfig().equals(config)) {
                springGroovyResourcesBeanBuilder.registerBeans(config);
            }
        }
    }
254940
public function init($config, $global)
    {
        //~ Comment
        $this->author  = $global['comment']['author'];
        $this->version = $global['comment']['version'];

        //~ Class
        $this->classname = $config['class']['classname'];
        $this->namespace = $config['class']['namespace'];

        //~ Cache
        $this->cacheName   = $config['cache']['name'];
        $this->cachePrefix = $config['cache']['prefix'];

        //~ Db
        $this->dbTable  = $config['db']['table'];
        $this->dbPrefix = $config['db']['prefix'];

        //~ Joins
        $this->joinList = (isset($config['joins']) ? $config['joins'] : array());

        return $this;
    }
590346
public static void initJMXBean(JawrApplicationConfigManager appConfigMgr, ServletContext servletContext,
			String resourceType, String mBeanPrefix) {

		try {

			MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

			if (mbs != null) {

				ObjectName jawrConfigMgrObjName = JmxUtils.getMBeanObjectName(servletContext, resourceType,
						mBeanPrefix);

				// register the jawrApplicationConfigManager if it's not already
				// done
				ObjectName appJawrMgrObjectName = JmxUtils.getAppJawrConfigMBeanObjectName(servletContext, mBeanPrefix);
				if (!mbs.isRegistered(appJawrMgrObjectName)) {
					mbs.registerMBean(appConfigMgr, appJawrMgrObjectName);
				}

				if (mbs.isRegistered(jawrConfigMgrObjName)) {
					LOGGER.warn("The MBean '" + jawrConfigMgrObjName.getCanonicalName()
							+ "' already exists. It will be unregisterd and registered with the new JawrConfigManagerMBean.");
					mbs.unregisterMBean(jawrConfigMgrObjName);
				}
				JawrConfigManagerMBean configMgr = appConfigMgr.getConfigMgr(resourceType);
				mbs.registerMBean(configMgr, jawrConfigMgrObjName);
			}

		} catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException
				| InstanceNotFoundException e) {
			LOGGER.error("Unable to instanciate the Jawr MBean for resource type '" + resourceType + "'", e);
		}

	}
1252127
private function initServerGlobal()
    {

        $entryUrl = $this->config['entryUrl'];
        $entryFile = $this->config['entryScript'] ?: basename($entryUrl);
        $entryScript = $this->config['entryScript'] ?: parse_url($entryUrl, PHP_URL_PATH);
        $_SERVER = array_merge($_SERVER, [
            'SCRIPT_FILENAME' => $entryFile,
            'SCRIPT_NAME' => $entryScript,
            'SERVER_NAME' => parse_url($entryUrl, PHP_URL_HOST),
            'SERVER_PORT' => parse_url($entryUrl, PHP_URL_PORT) ?: '80',
            'HTTPS' => parse_url($entryUrl, PHP_URL_SCHEME) === 'https'
        ]);
    }
561897
@Override
    protected synchronized void loadConfiguration() throws IOException {
        final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        final TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() {};
        namespaces = mapper.readValue(new File(configPath), typeRef);
    }
982277
public static ConsistentHashFactory pickConsistentHashFactory(GlobalConfiguration globalConfiguration, Configuration configuration) {
      ConsistentHashFactory factory = configuration.clustering().hash().consistentHashFactory();
      if (factory == null) {
         CacheMode cacheMode = configuration.clustering().cacheMode();
         if (cacheMode.isClustered()) {
            if (cacheMode.isDistributed()) {
               if (globalConfiguration.transport().hasTopologyInfo()) {
                  factory = new TopologyAwareSyncConsistentHashFactory();
               } else {
                  factory = new SyncConsistentHashFactory();
               }
            } else if (cacheMode.isReplicated() || cacheMode.isInvalidation()) {
               factory = new SyncReplicatedConsistentHashFactory();
            } else if (cacheMode.isScattered()) {
               factory = new ScatteredConsistentHashFactory();
            } else {
               throw new CacheException("Unexpected cache mode: " + cacheMode);
            }
         }
      }
      return factory;
   }
127593
public static ConformanceConfig loadGlobalConformance(Class<?> clazz) {
    ConformanceConfig.Builder builder = ConformanceConfig.newBuilder();
    if (resourceExists(clazz, "global_conformance.binarypb")) {
      try {
        builder.mergeFrom(clazz.getResourceAsStream("global_conformance.binarypb"));
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
    return builder.build();
  }
327847
public static Config loadConfig(ClassLoader classLoader, String configResource,
            boolean useSystemEnvironment) {
        return loadConfig(ConfigParseOptions.defaults(),
                ConfigResolveOptions.defaults().setUseSystemEnvironment(useSystemEnvironment),
                classLoader, configResource);
    }
1042504
public OStorageConfiguration load() throws OSerializationException {
    final byte[] record = storage.readRecord(CONFIG_RID, null, false, null).buffer;

    if (record == null)
      throw new OStorageException("Cannot load database's configuration. The database seems to be corrupted.");

    fromStream(record);
    return this;
  }
544523
public static ServerParams load(String[] args) throws ConfigurationException {
        if (INSTANCE != null) {
            logger.warn("Configuration is loaded already. Use ServerParams.getInstance() method. ");
            return INSTANCE;
        }

        INSTANCE = new ServerParams();
        INSTANCE.parseConfigFile(getConfigUrl());
        INSTANCE.parseCommandLineArgs(args);
        INSTANCE.parseOverrideFile();
        INSTANCE.printConfig();
        
        // TODO: Delete the next line when ServerConfig is phased out.
        copyParamsToServerConfig();
        return INSTANCE;
    }
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);
    }
785968
public static Config load(final String... resources) {
        final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
        try (final InputStream resourceAsStream = findResource("jjs-config-utils.js")) {
            engine.eval(new InputStreamReader(resourceAsStream));
            loadResources(engine, resources);
        } catch (final ScriptException se) {
            throw new IllegalArgumentException("unable to execute main javascript.", se);
        } catch (final Exception ex) {
            if (ex instanceof IllegalArgumentException) {
                throw (IllegalArgumentException) ex;
            }
            throw new IllegalArgumentException("unable to load main resource ", ex);
        }
        return loadFromObject(engine.get("config"));
    }
1120932
def _load_config(self):
        
        # load the global config
        with open(self.config_global_path, "r") as f_config:
            config = ordered_yaml_load(f_config)
        self.config_global = config

        # Load the local config
        if self.config_global_local_path:
            config = ordered_yaml_load(open(self.config_global_local_path, "r"))
            self.config_global_local = config

        self.config = merge_config(
            OrderedDict(
                [
                    ("global_config", self.config_global),
                    ("global_local", self.config_global_local),
                ]
            )
        )
703101
public ServerBase build()
  {
    EnvLoader.init();
    
    SystemManager systemManager = createSystemManager();
    
    Thread thread = Thread.currentThread();
    ClassLoader oldLoader = thread.getContextClassLoader();
    
    boolean isValid = false;
    try {
      thread.setContextClassLoader(systemManager.getClassLoader());
      
      Vfs.setPwd(getRootDirectory());
      
      if (! isEmbedded()) {
        logCopyright();
      }

      preConfigureInit();
      
      configureRootDirectory();
      
      _serverSelf = initNetwork();
      Objects.requireNonNull(_serverSelf);
      
      addServices(_serverSelf);

      initHttpSystem(systemManager, _serverSelf);
      
      ServerBase server = build(systemManager,
                                _serverSelf);

      init(server);
      
      isValid = true;
      
      systemManager.start();
      
      return server;
    } catch (RuntimeException e) {
      throw e;
    } catch (Exception e) {
      throw ConfigException.wrap(e);
    } finally {
      thread.setContextClassLoader(oldLoader);
      
      if (! isValid) {
        systemManager.shutdown(ShutdownModeAmp.IMMEDIATE);
      }
    }
  }
574900
@SuppressWarnings("unchecked")
    public static ServerConfig load(String[] args) throws ConfigurationException {
    	if(config != null) {
    		logger.warn("Configuration is loaded already. Use ServerConfig.getInstance() method. ");
    		return config;
    	}

        try {
            URL url = getConfigUrl();
            logger.info("Trying to load settings from: " + url);

            InputStream input = null;
            try {
                input = url.openStream();
            } catch (IOException e) {
                throw new AssertionError(e);
            }

            Yaml yaml = new Yaml();
            LinkedHashMap<String, ?> dataColl = (LinkedHashMap<String, ?>)yaml.load(input);
            config = new ServerConfig();
            setParams(dataColl);
                       
            logger.info("Ok. Configuration loaded.");

        } catch (ConfigurationException e) {
            logger.warn(e.getMessage() + " -- Ignoring.");
        } catch (YAMLException e) {
            logger.warn(e.getMessage() + " -- Ignoring.");
        }

        if (config == null) {
            logger.info("Initializing configuration by default settings.");
            config = new ServerConfig();
        }

        try {
            if (args != null && args.length > 0) {
                logger.info("Parsing the command line arguments...");
                parseCommandLineArgs(args);
                logger.info("Ok. Arguments parsed.");
            }
        } catch (ConfigurationException e) {
            logger.error("Fatal configuration error", e);
            System.err.println(e.getMessage() + "\nFatal configuration error. Unable to start server.  See log for stacktrace.");
            throw e;
        }

        //overrides with params from the file
        if (!Utils.isEmpty(config.param_override_filename)) {
            try {
                InputStream overrideFile = new FileInputStream(config.param_override_filename);
                Yaml yaml = new Yaml();
                LinkedHashMap<String, ?> overrideColl = (LinkedHashMap<String, ?>)yaml.load(overrideFile);
                setParams(overrideColl);
            } catch (Exception e) {
                logger.warn(e.getMessage() + " -- Ignoring.");
            }       
        }
        return config;
    }
1092930
private final static void loadConfig() {
		try {
			conf = Configurations.loadConfig(configFilePath);
		} catch (ConfigurationException e) {
			terminate();
			throw new InitializationException(INIT_FAILED, e);
		}
	}