Set config by environment
@param {object} defaultConfig - default config
@param {string} server - server type ('ne' or local)
332304
function setConfig(defaultConfig, server) {
    if (server === 'ne') {
        defaultConfig.captureTimeout = 100000;

        defaultConfig.customLaunchers = {
            'IE8': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'internet explorer',
                version: '8'
            },
            'IE9': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'internet explorer',
                version: '9'
            },
            'IE10': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'internet explorer',
                version: '10'
            },
            'IE11': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'internet explorer',
                version: '11'
            },
            'Edge': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'MicrosoftEdge'
            },
            'Chrome-WebDriver': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'chrome'
            },
            'Firefox-WebDriver': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'firefox'
            },
            'Safari-WebDriver': {
                base: 'WebDriver',
                config: webdriverConfig,
                browserName: 'safari'
            }
        };

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        defaultConfig.browsers = [
            'IE8',
            'IE9',
            'IE10',
            'IE11',
            'Edge',
            'Chrome-WebDriver',
            'Firefox-WebDriver'
            // 'Safari-WebDriver' // active only when safari test is needed
        ];

        defaultConfig.webpack.module.preLoaders = [{
            test: /\.js$/,
            include: path.resolve('./src/js'),
            loader: 'istanbul-instrumenter'
        }];

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        defaultConfig.reporters = [
            'dots',
            'coverage',
            'junit'
        ];

        // optionally, configure the reporter
        defaultConfig.coverageReporter = {
            dir: 'report/coverage/',
            reporters: [
                {
                    type: 'html',
                    subdir: function(browser) {
                        return 'report-html/' + browser;
                    }
                },
                {
                    type: 'cobertura',
                    subdir: function(browser) {
                        return 'report-cobertura/' + browser;
                    },
                    file: 'cobertura.txt'
                }
            ]
        };

        defaultConfig.junitReporter = {
            outputDir: 'report/junit',
            suite: ''
        };
    } else {
        defaultConfig.captureTimeout = 60000;

        defaultConfig.reporters = [
            'karmaSimpleReporter'
        ];

        defaultConfig.specReporter = {
            suppressPassed: true,
            suppressSkipped: true,
            suppressErrorSummary: true
        };

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        defaultConfig.browsers = [
            'ChromeHeadless'
        ];
    }
}
1351163
function setConfig (options) {
  Object.keys(options).forEach((option) => {
    if (config[option] !== undefined) {
      config[option] = options[option]
    }
  })
}
346251
function setDefaultSettings(settings) {
  if (!settings)
    throw new Error('Settings must be an object.')

  // Default settings for each project type.
  switch (settings.projectType) {
    case 'cli':
    case 'node-app':
    case 'node-lib':
      settings.platforms ??= ['node']
      break

    case 'lib':
      settings.platforms ??= ['browser', 'node']
      break

    case 'react-spa':
      settings.platforms ??= ['browser']
      settings.jsx ??= true
      settings.react ??= true
      break

    case 'web-lib':
      settings.platforms ??= ['browser']
      break
  }

  // Default supported browsers inferred by the platform.
  if (settings.platforms.includes('browsers')) {
    settings.browsers ??= [
      '>= 0.5%',
      'not ie 11',
      'not op_mini all',
    ]
  }

  // Default supported NodeJS inferred by the platform.
  if (settings.platforms.includes('node'))
    settings.node ??= '8.9'
}
418657
function ( conf ) {
    serverConfig = sqsUtil.copy( conf.server );

    serverConfig.siteurl = serverConfig.siteurl.replace( rSlash, "" );
    serverConfig.port = (serverConfig.port || 5050);
    serverConfig.webroot = process.cwd();
    serverConfig.protocol = serverConfig.siteurl.match( rProtocol )[ 0 ];
    serverConfig.siteData = {};

    // Set config for middleware
    sqsWare.set( "siteurl", serverConfig.siteurl );

    if ( serverConfig.password ) {
        sqsWare.set( "sitepassword", serverConfig.password );
    }

    if ( serverConfig.sandbox ) {
        sqsWare.set( "sandboxmode", true );
    }

    if ( serverConfig.fulldata !== undefined ) {
        sqsWare.set( "fulldata", serverConfig.fulldata );
    }

    sqsTemplate.setConfig( "server", serverConfig );
}
212745
public function setSail()
    {
        $env = new Environment($_SERVER);
        if (!count($this->registry->getAll())) {
            $config = $env->fetchConfig($this->configFolder, $this->environment);
            $this->setConfig($config);
        }
        $request = ServerRequestFactory::fromGlobals($_SERVER, $_GET, $_POST, $_COOKIE, $_FILES);
        $response = new Response();
        $dispatcher = new Dispatcher($request, $response, $env);
        $dispatcher->fireCannons();
    }
707045
function envVars(config) {
  const configuration = Object.assign({}, config);
  if (process.env.AMQP_URL && !configuration.host) {
    configuration.host = process.env.AMQP_URL;
  }

  if (process.env.LOCAL_QUEUE && !configuration.consumerSuffix) {
    configuration.consumerSuffix = process.env.LOCAL_QUEUE;
  }

  if (process.env.AMQP_DEBUG && !configuration.transport) {
    configuration.transport = console;
  }

  return configuration;
}
568387
function setConfig(config) {
  let oldConfig = getConfig();  // to check if the file exists.
  if (!oldConfig) return false;
  if (typeof config !== 'object' || !config) return false;
  let configData = '';
  try {
    configData = JSON.stringify(config, null, 1);
  } catch (e) {
    console.warn(`thorin-env: failed to serialize configuration`, e);
    return false;
  }
  try {
    fs.writeFileSync(PERSIST_FILE, configData, {encoding: 'utf8'});
  } catch (e) {
    console.warn(`thorin-env: failed to persist new config in .thorin file`);
    console.debug(e);
    return false;
  }
  return true;
}
1245780
public static void setDefaultEnvironment(String environment) {
    System.setProperty("pelzer.environment", environment);
    Logging.getLogger(EnvironmentManager.class);
    PropertyManager.setDefaultEnvironment(environment);
  }
1145228
function Config (config, defaultConfig) {
  validateConfig(config);
  deepAssign(this, defaultConfig || Config.defaults);

  if (config) {
    deepAssign(this, config);
  }
}
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;
    }
1271571
def init_config(self, app):
        
        app.config.setdefault(
            'OAISERVER_BASE_TEMPLATE',
            app.config.get('BASE_TEMPLATE',
                           'invenio_oaiserver/base.html'))

        app.config.setdefault(
            'OAISERVER_REPOSITORY_NAME',
            app.config.get('THEME_SITENAME',
                           'Invenio-OAIServer'))

        # warn user if ID_PREFIX is not set
        if 'OAISERVER_ID_PREFIX' not in app.config:
            import socket
            import warnings

            app.config.setdefault(
                'OAISERVER_ID_PREFIX',
                'oai:{0}:recid/'.format(socket.gethostname()))
            warnings.warn(
                """Please specify the OAISERVER_ID_PREFIX configuration.default value is: {0}""".format(
                    app.config.get('OAISERVER_ID_PREFIX')))

        for k in dir(config):
            if k.startswith('OAISERVER_'):
                app.config.setdefault(k, getattr(config, k))
1232103
protected void setDefaults() {
    // map.put("tsd.network.port", ""); // does not have a default, required
    // map.put("tsd.http.cachedir", ""); // does not have a default, required
    // map.put("tsd.http.staticroot", ""); // does not have a default, required
    default_map.put("tsd.mode", "rw");
    default_map.put("tsd.no_diediedie", "false");
    default_map.put("tsd.network.bind", "0.0.0.0");
    default_map.put("tsd.network.worker_threads", "");
    default_map.put("tsd.network.async_io", "true");
    default_map.put("tsd.network.tcp_no_delay", "true");
    default_map.put("tsd.network.keep_alive", "true");
    default_map.put("tsd.network.reuse_address", "true");
    default_map.put("tsd.core.authentication.enable", "false");
    default_map.put("tsd.core.authentication.plugin", "");
    default_map.put("tsd.core.auto_create_metrics", "false");
    default_map.put("tsd.core.auto_create_tagks", "true");
    default_map.put("tsd.core.auto_create_tagvs", "true");
    default_map.put("tsd.core.connections.limit", "0");
    default_map.put("tsd.core.enable_api", "true");
    default_map.put("tsd.core.enable_ui", "true");
    default_map.put("tsd.core.meta.enable_realtime_ts", "false");
    default_map.put("tsd.core.meta.enable_realtime_uid", "false");
    default_map.put("tsd.core.meta.enable_tsuid_incrementing", "false");
    default_map.put("tsd.core.meta.enable_tsuid_tracking", "false");
    default_map.put("tsd.core.meta.cache.enable", "false");
    default_map.put("tsd.core.plugin_path", "");
    default_map.put("tsd.core.socket.timeout", "0");
    default_map.put("tsd.core.tree.enable_processing", "false");
    default_map.put("tsd.core.preload_uid_cache", "false");
    default_map.put("tsd.core.preload_uid_cache.max_entries", "300000");
    default_map.put("tsd.core.storage_exception_handler.enable", "false");
    default_map.put("tsd.core.uid.random_metrics", "false");
    default_map.put("tsd.core.bulk.allow_out_of_order_timestamps", "false");
    default_map.put("tsd.query.filter.expansion_limit", "4096");
    default_map.put("tsd.query.skip_unresolved_tagvs", "false");
    default_map.put("tsd.query.allow_simultaneous_duplicates", "true");
    default_map.put("tsd.query.enable_fuzzy_filter", "true");
    default_map.put("tsd.query.limits.bytes.default", "0");
    default_map.put("tsd.query.limits.bytes.allow_override", "false");
    default_map.put("tsd.query.limits.data_points.default", "0");
    default_map.put("tsd.query.limits.data_points.allow_override", "false");
    default_map.put("tsd.query.limits.overrides.interval", "60000");
    default_map.put("tsd.query.multi_get.enable", "false");
    default_map.put("tsd.query.multi_get.limit", "131072");
    default_map.put("tsd.query.multi_get.batch_size", "1024");
    default_map.put("tsd.query.multi_get.concurrent", "20");
    default_map.put("tsd.query.multi_get.get_all_salts", "false");
    default_map.put("tsd.rpc.telnet.return_errors", "true");
    // Rollup related settings
    default_map.put("tsd.rollups.enable", "false");
    default_map.put("tsd.rollups.tag_raw", "false");
    default_map.put("tsd.rollups.agg_tag_key", "_aggregate");
    default_map.put("tsd.rollups.raw_agg_tag_value", "RAW");
    default_map.put("tsd.rollups.block_derived", "true");
    default_map.put("tsd.rtpublisher.enable", "false");
    default_map.put("tsd.rtpublisher.plugin", "");
    default_map.put("tsd.search.enable", "false");
    default_map.put("tsd.search.plugin", "");
    default_map.put("tsd.stats.canonical", "false");
    default_map.put("tsd.startup.enable", "false");
    default_map.put("tsd.startup.plugin", "");
    default_map.put("tsd.storage.hbase.scanner.maxNumRows", "128");
    default_map.put("tsd.storage.fix_duplicates", "false");
    default_map.put("tsd.storage.flush_interval", "1000");
    default_map.put("tsd.storage.hbase.data_table", "tsdb");
    default_map.put("tsd.storage.hbase.uid_table", "tsdb-uid");
    default_map.put("tsd.storage.hbase.tree_table", "tsdb-tree");
    default_map.put("tsd.storage.hbase.meta_table", "tsdb-meta");
    default_map.put("tsd.storage.hbase.zk_quorum", "localhost");
    default_map.put("tsd.storage.hbase.zk_basedir", "/hbase");
    default_map.put("tsd.storage.hbase.prefetch_meta", "false");
    default_map.put("tsd.storage.enable_appends", "false");
    default_map.put("tsd.storage.repair_appends", "false");
    default_map.put("tsd.storage.enable_compaction", "true");
    default_map.put("tsd.storage.compaction.flush_interval", "10");
    default_map.put("tsd.storage.compaction.min_flush_threshold", "100");
    default_map.put("tsd.storage.compaction.max_concurrent_flushes", "10000");
    default_map.put("tsd.storage.compaction.flush_speed", "2");
    default_map.put("tsd.timeseriesfilter.enable", "false");
    default_map.put("tsd.uid.use_mode", "false");
    default_map.put("tsd.uid.lru.enable", "false");
    default_map.put("tsd.uid.lru.name.size", "5000000");
    default_map.put("tsd.uid.lru.id.size", "5000000");
    default_map.put("tsd.uidfilter.enable", "false");
    default_map.put("tsd.core.stats_with_port", "false");
    default_map.put("tsd.http.show_stack_trace", "true");
    default_map.put("tsd.http.query.allow_delete", "false");
    default_map.put("tsd.http.header_tag", "");
    default_map.put("tsd.http.request.enable_chunked", "false");
    default_map.put("tsd.http.request.max_chunk", "4096");
    default_map.put("tsd.http.request.cors_domains", "");
    default_map.put("tsd.http.request.cors_headers", "Authorization, "
      + "Content-Type, Accept, Origin, User-Agent, DNT, Cache-Control, "
      + "X-Mx-ReqToken, Keep-Alive, X-Requested-With, If-Modified-Since");
    default_map.put("tsd.query.timeout", "0");
    default_map.put("tsd.storage.use_otsdb_timestamp", "false");
    default_map.put("tsd.storage.use_max_value", "true");
    default_map.put("tsd.storage.get_date_tiered_compaction_start", "0");

    for (Map.Entry<String, String> entry : default_map.entrySet()) {
      if (!properties.containsKey(entry.getKey()))
        properties.put(entry.getKey(), entry.getValue());
    }

    loadStaticVariables();
  }
1180105
function setDefaults ({ headers={}, overrideHeaders=false, ...rest }) {
  return {
    ...DEFAULTS,
    headers: overrideHeaders ? headers : { ...DEFAULT_HEADERS, ...headers },
    ...rest,
  }
}
425670
function setConfig(newConf, isClearPrevious) {
    checkIsObject(newConf);
    config = isClearPrevious ? Immutable.fromJS(newConf) : config.merge(newConf);
}
1239430
function set(key, value) {
  let config = getGlobalConfig();
  if (key && typeof key === 'string' && typeof value !== 'undefined') {
    config = _.set(config, key, value);
  } else if (_.isObject(key)) {
    config = _.merge(config, key);
  } else if (typeof value !== 'undefined') {
    config = _.merge(config, value);
  }
  // update config meta
  config.meta = config.meta || {};
  config.meta.updated_at = Math.round(+new Date() / 1000);
  // write to .serverlessrc file
  writeFileAtomic.sync(serverlessrcPath, JSON.stringify(config, null, 2));
  return config;
}
1211609
function initWebServer(settings) {

    let server = {
        app:       null,
        server:    null,
        io:        null,
        settings:  settings
    };
    adapter.subscribeForeignObjects('system.config');

    settings.ttl = parseInt(settings.ttl, 10) || 3600;
    if (!settings.whiteListEnabled && settings.whiteListSettings) delete settings.whiteListSettings;

    settings.defaultUser = settings.defaultUser || 'system.user.admin';
    if (!settings.defaultUser.match(/^system\.user\./)) settings.defaultUser = 'system.user.' + settings.defaultUser;

    if (settings.port) {
        if (settings.secure) {
            if (!settings.certificates) {
                return null;
            }
        }
        server.app = express();

        server.app.disable('x-powered-by');
        // enable use of i-frames together with HTTPS
        server.app.get('/*', (req, res, next) => {
            res.header('X-Frame-Options' , 'SAMEORIGIN');
            next(); // http://expressjs.com/guide.html#passing-route control
        });

        if (settings.auth) {

            initAuth(server, settings);

            let autoLogonOrRedirectToLogin = (req, res, next, redirect) => {
                if (!settings.whiteListSettings) {
                    if (/\.css(\?.*)?$/.test(req.originalUrl)) {
                        return res.status(200).send('');
                    } else
					if (/\.js(\?.*)?$/.test(req.originalUrl)) {
						// return always valid js file for js, because if cache is active it leads to errors
                        const parts = req.originalUrl.split('/');
                        parts.shift();
                        const ref = parts.join('/');
						// if request for web/lib, ignore it, because no redirect information
						if (parts[0] === 'lib') return res.status(200).send('');
						return res.status(200).send('document.location="/login/index.html?href=" + encodeURI(location.href.replace(location.origin, ""));');
					} else {
						return res.redirect(redirect);
					}
				}
                let remoteIp = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
                let whiteListIp = server.io.getWhiteListIpForAddress(remoteIp, settings.whiteListSettings);
				adapter.log.silly('whiteListIp ' + whiteListIp);
                if (!whiteListIp || settings.whiteListSettings[whiteListIp].user === 'auth') {
                    if (/\.css(\?.*)?$/.test(req.originalUrl)) {
                        return res.status(200).send('');
                    } else if (/\.js(\?.*)?$/.test(req.originalUrl)) {
						// return always valid js file for js, because if cache is active it leads to errors
						let parts = req.originalUrl.split('/');
                        parts.shift();
                        const ref = parts.join('/');
						if (parts[0] === 'lib') return res.status(200).send('');
                        return res.status(200).send('document.location="/login/index.html?href=" + encodeURI(location.href.replace(location.origin, ""));');
					} else {
						return res.redirect(redirect);
					}
				}
                req.logIn(settings.whiteListSettings[whiteListIp].user, err => {
					return next(err);
                });
            };

            server.app.post('/login', (req, res, next) => {
                let redirect = '/';
                let parts;
                if (req.body.origin) {
                    parts = req.body.origin.split('=');
                    if (parts[1]) redirect = decodeURIComponent(parts[1]);
                }
                if (req.body && req.body.username && settings.addUserName && redirect.indexOf('?') === -1) {
                    parts = redirect.split('#');
                    parts[0] += '?' + req.body.username;
                    redirect = parts.join('#');
                }
                passport.authenticate('local', {
                    successRedirect: redirect,
                    failureRedirect: '/login/index.html' + req.body.origin + (req.body.origin ? '&error' : '?error'),
                    failureFlash: 'Invalid username or password.'
                })(req, res, next);
            });

            server.app.get('/logout', (req, res) => {
                req.logout();
                res.redirect('/login/index.html');
            });

            // route middleware to make sure a user is logged in
            server.app.use((req, res, next) => {
				// if cache.manifest got back not 200 it makes an error
                if (req.isAuthenticated() ||
                    /web\.\d+\/login-bg\.png(\?.*)?$/.test(req.originalUrl) ||
                    /cache\.manifest(\?.*)?$/.test(req.originalUrl) ||
                    /^\/login\//.test(req.originalUrl) ||
                    /\.ico(\?.*)?$/.test(req.originalUrl)
                ) {
                    return next();
                } else {
                    autoLogonOrRedirectToLogin(req, res, next, '/login/index.html?href=' + encodeURIComponent(req.originalUrl));
                }
            });
        } else {
            server.app.get('/login', (req, res) => {
                res.redirect('/');
            });
            server.app.get('/logout', (req, res) => {
                res.redirect('/');
            });

            if (settings.whiteListEnabled) {
                initAuth(server, settings);
                server.app.use((req, res, next) => {
                    let remoteIp = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
                    let whiteListIp = server.io.getWhiteListIpForAddress(remoteIp, settings.whiteListSettings);
                    adapter.log.silly('whiteListIp ' + whiteListIp);
                    if (whiteListIp) {
                       req.logIn(settings.whiteListSettings[whiteListIp].user, err => {
                            return next(err);
                        });
                    } else {
                        req.logIn(settings.defaultUser, err => {
                            return next(err);
                        });
                    }
                });
            }
        }

        // Init read from states
        server.app.get('/state/*', (req, res) => {
            try {
                const fileName = req.url.split('/', 3)[2].split('?', 2);
                adapter.getForeignObject(fileName[0], (err, obj) => {
                    let contentType = 'text/plain';
                    if (obj && obj.common.type === 'file')  {
                        contentType = mime.lookup(fileName[0]);
                    }
                    adapter.getBinaryState(fileName[0], {user: req.user ? 'system.user.' + req.user : settings.defaultUser}, (err, obj) => {
                        if (!err && obj !== null && obj !== undefined) {
                            if (obj && typeof obj === 'object' && obj.val !== undefined && obj.ack !== undefined) {
                                res.set('Content-Type', 'application/json');
                            } else {
                                res.set('Content-Type', contentType || 'text/plain');
                            }
                            res.status(200).send(obj);
                        } else {
                            res.status(404).send('404 Not found. File ' + fileName[0] + ' not found');
                        }
                    });
                });
            } catch (e) {
                res.status(500).send('500. Error' + e);
            }
        });

        server.app.get('*/_socket/info.js', (req, res) => {
            res.set('Content-Type', 'application/javascript');
            res.status(200).send(getInfoJs(settings));
        });

        // Enable CORS
        if (settings.socketio) {
            server.app.use((req, res, next) => {
                res.header('Access-Control-Allow-Origin', '*');
                res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
                res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, *');

                // intercept OPTIONS method
                if ('OPTIONS' === req.method) {
                    res.status(200).send(200);
                } else {
                    next();
                }
            });
        }

        let appOptions = {};
        if (settings.cache) appOptions.maxAge = 30758400000;

        server.server = LE.createServer(server.app, settings, settings.certificates, settings.leConfig, adapter.log);
        server.server.__server = server;
    } else {
        adapter.log.error('port missing');
        adapter.terminate ? adapter.terminate(1): process.exit(1);
    }

    if (server.server) {
        settings.port = parseInt(settings.port, 10);
        adapter.getPort(settings.port, port => {
            port = parseInt(port, 10);
            if (port !== settings.port && !settings.findNextPort) {
                adapter.log.error('port ' + settings.port + ' already in use');
                adapter.terminate ? adapter.terminate(1): process.exit(1);
            }
            server.server.listen(port, (!settings.bind || settings.bind === '0.0.0.0') ? undefined : settings.bind || undefined);
            adapter.log.info('http' + (settings.secure ? 's' : '') + ' server listening on port ' + port);
        });
    }

    // activate extensions
    for (let e in extensions) {
        if (!extensions.hasOwnProperty(e)) continue;
        try {
            // for debug purposes try to load file in current directory "/lib/file.js" (elsewise node.js cannot debug it)
            let parts = extensions[e].path.split('/');
            parts.shift();
            let extAPI;
            if (fs.existsSync(__dirname + '/' + parts.join('/'))) {
                extAPI = require(__dirname + '/' + parts.join('/'));
            } else {
                extAPI = require(utils.appName + '.' + extensions[e].path);
            }

            extensions[e].obj = new extAPI(server.server, {secure: settings.secure, port: settings.port}, adapter, extensions[e].config, server.app);
            adapter.log.info('Connect extension "' + extensions[e].path + '"');
        } catch (err) {
            adapter.log.error('Cannot start extension "' + e + '": ' + err);
        }
    }

    // Activate integrated simple API
    if (settings.simpleapi) {
        let SimpleAPI = require(utils.appName + '.simple-api/lib/simpleapi.js');

        server.api = new SimpleAPI(server.server, {secure: settings.secure, port: settings.port}, adapter);
    }

    // Activate integrated socket
    if (ownSocket) {
        let IOSocket = require(utils.appName + '.socketio/lib/socket.js');
        let socketSettings = JSON.parse(JSON.stringify(settings));
        // Authentication checked by server itself
        socketSettings.auth             = settings.auth;
        socketSettings.secret           = secret;
        socketSettings.store            = store;
        socketSettings.ttl              = settings.ttl || 3600;
        socketSettings.forceWebSockets  = settings.forceWebSockets || false;
        server.io = new IOSocket(server.server, socketSettings, adapter);
    }

    if (server.app) {
        // deliver web files from objectDB
        server.app.use('/', (req, res) => {

            let url = decodeURI(req.url);
            // remove all ../
            // important: Linux does not normalize "\" but fs.readFile accepts it as '/'
            url = path.normalize(url.replace(/\\/g, '/')).replace(/\\/g, '/');
            // remove '////' at start and let only one
            if (url[0] === '/' && url[1] === '/') {
                let i = 2;
                while (url[i] === '/') i++;
                url = url.substring(i - 1);
            }
            if ((url[0] === '.' && url[1] === '.') || (url[0] === '/' && url[1] === '.' && url[2] === '.')) {
                res.status(404).send('Not found');
                return;
            }

            if (server.api && server.api.checkRequest(url)) {
                server.api.restApi(req, res);
                return;
            }

            if (url === '/' || url === '/index.html') {
                getListOfAllAdapters((err, data) => {
                    if (err) {
                        res.status(500).send('500. Error' + e);
                    } else {
                        res
                            .set('Content-Type', 'text/html')
                            .status(200)
                            .send(data);
                    }
                });
                return;
            }

            // add index.html
            url = url.replace(/\/($|\?|#)/, '/index.html$1');

            if (url.match(/^\/adapter\//)) {
                // add .admin to adapter name
                url = url.replace(/^\/adapter\/([a-zA-Z0-9-_]+)\//, '/$1.admin/');
            }

            if (url.match(/^\/lib\//)) {
                url = '/' + adapter.name + url;
            }
            if (url.match(/^\/admin\//)) {
                url = '/' + adapter.name + url;
            }
            url = url.split('/');
            // Skip first /
            url.shift();
            // Get ID
            let id = url.shift();
            let versionPrefix = url[0];
            url = url.join('/');
            let pos = url.indexOf('?');
            let noFileCache;
            if (pos !== -1) {
                url = url.substring(0, pos);
                // disable file cache if request like /vis/files/picture.png?noCache
                noFileCache = true;
            }

            // get adapter name
            if (webByVersion[id]) {
                if (!versionPrefix || !versionPrefix.match(/^\d+\.\d+.\d+$/)) {
                    // redirect to version
                    res.set('location', '/' + id + '/' + webByVersion[id] + '/' + url);
                    res.status(301).send();
                    return;
                }
            }

            if (settings.cache && cache[id + '/' + url] && !noFileCache) {
                res.contentType(cache[id + '/' + url].mimeType);
                res.status(200).send(cache[id + '/' + url].buffer);
            } else {
                if (id === 'login' && url === 'index.html') {
                    loginPage = loginPage || prepareLoginTemplate();
                    let buffer = loginPage;

                    if (buffer === null || buffer === undefined) {
                        res.contentType('text/html');
                        res.status(200).send('File ' + url + ' not found', 404);
                    } else {
                        // Store file in cache
                        if (settings.cache) {
                            cache[id + '/' + url] = {buffer: buffer.toString(), mimeType: 'text/html'};
                        }
                        res.contentType('text/html');
                        res.status(200).send(buffer.toString());
                    }
                } else {
                    // special solution for socket.io
                    if (socketIoFile !== false && url.match(/\/socket\.io\.js(\?.*)?$/)) {
                        if (socketIoFile) {
                            res.contentType('text/javascript');
                            res.status(200).send(socketIoFile);
                            return
                        } else {
                            try {
                                const dir = require.resolve('socket.io-client');
                                const fileDir = path.join(path.dirname(dir), '../dist/');
                                if (fs.existsSync(fileDir + 'socket.io.min.js')) {
                                    socketIoFile = fs.readFileSync(fileDir + 'socket.io.min.js');
                                } else {
                                    socketIoFile = fs.readFileSync(fileDir + 'socket.io.js');
                                }
                            } catch (e) {
                                socketIoFile = false;
                            }
                            if (socketIoFile) {
                                res.contentType('text/javascript');
                                res.status(200).send(socketIoFile);
                                return
                            }
                        }
                    }
                    
                    adapter.readFile(id, webByVersion[id] ? url.substring(versionPrefix.length + 1) : url , {user: req.user ? 'system.user.' + req.user : settings.defaultUser, noFileCache: noFileCache}, (err, buffer, mimeType) => {
                        if (buffer === null || buffer === undefined || err) {
                            res.contentType('text/html');
                            res.status(404).send('File ' + url + ' not found: ' + err);
                        } else {
                            mimeType = mimeType || mime.lookup(url) || 'text/javascript';

                            // Store file in cache
                            if (settings.cache) {
                                cache[id + '/' + url] = {
                                    buffer: buffer,
                                    mimeType: mimeType
                                };
                            }

                            res.contentType(mimeType);
                            res.status(200).send(buffer);
                        }
                    });
                }
            }
        });
    }

    if (server.server) {
        return server;
    } else {
        return null;
    }
}
1174425
def set_server(self, server_pos, key, value):
        """"""
        self.servers.set_server(server_pos, key, value)