/*
This is a helper utility specifically to reload environment variables if java
language worker is started in standby mode by the functions runtime and
should not be used for other purposes
176575
public void setEnv(Map<String, String> newSettings) throws Exception {
		if (newSettings == null || newSettings.isEmpty()) {
			return;
		}
		
		// Update Environment variables in the JVM
		try {			
			Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
			Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
			theEnvironmentField.setAccessible(true);
			Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
			env.clear();
			env.putAll(newSettings);
			Field theCaseInsensitiveEnvironmentField = processEnvironmentClass
					.getDeclaredField("theCaseInsensitiveEnvironment");
			theCaseInsensitiveEnvironmentField.setAccessible(true);
			Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
			cienv.clear();
			cienv.putAll(newSettings);
			WorkerLogManager.getSystemLogger().log(Level.INFO,
					"Finished resetting environment variables in the JVM");
		} catch (NoSuchFieldException e) {
			Class[] classes = Collections.class.getDeclaredClasses();
			Map<String, String> env = System.getenv();
			for (Class cl : classes) {
				if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
					Field field = cl.getDeclaredField("m");
					field.setAccessible(true);
					Object obj = field.get(env);
					Map<String, String> map = (Map<String, String>) obj;
					map.clear();
					map.putAll(newSettings);
				}
			}
		}
	}
1134483
public static synchronized void initializeEnvironment()
  {
    if (_isStaticInit)
      return;

    _isStaticInit = true;

    ClassLoader systemLoader = ClassLoader.getSystemClassLoader();

    Thread thread = Thread.currentThread();
    ClassLoader oldLoader = thread.getContextClassLoader();
    try {
      thread.setContextClassLoader(systemLoader);
      
      if ("1.8.".compareTo(System.getProperty("java.runtime.version")) > 0)
        throw new ConfigException("Baratine requires JDK 1.8 or later");

      // #2281
      // PolicyImpl.init();

      //EnvironmentStream.setStdout(System.out);
      //EnvironmentStream.setStderr(System.err);

      /*
      try {
        Vfs.initJNI();
      } catch (Throwable e) {
      }
      */
      
      Properties props = System.getProperties();

      ClassLoader envClassLoader
        = EnvironmentClassLoader.class.getClassLoader();

      /*
      boolean isGlobalLoadableJndi = false;
      try {
        Class<?> cl = Class.forName("com.caucho.v5.naming.InitialContextFactoryImpl",
                                    false,
                                    systemLoader);

        isGlobalLoadableJndi = (cl != null);
      } catch (Exception e) {
        log().log(Level.FINER, e.toString(), e);
      }
      
      // #3486
      String namingPkgs = (String) props.get("java.naming.factory.url.pkgs");
      if (namingPkgs == null)
        namingPkgs = "com.caucho.v5.naming";
      else
        namingPkgs = namingPkgs + ":" + "com.caucho.v5.naming";
      props.put("java.naming.factory.url.pkgs", namingPkgs);

      if (isGlobalLoadableJndi) {
        // These properties require the server to be at the system loader

        if (props.get("java.naming.factory.initial") == null) {
          props.put("java.naming.factory.initial",
                    "com.caucho.v5.naming.InitialContextFactoryImpl");
        }
      }
      */

      /*
      boolean isGlobalLoadableJmx = false;
      try {
        Class<?> cl = Class.forName("com.caucho.v5.jmx.MBeanServerBuilderImpl",
                                    false,
                                    systemLoader);

        isGlobalLoadableJmx = (cl != null);
      } catch (Exception e) {
        log().log(Level.FINER, e.toString(), e);
      }
      
      if (isGlobalLoadableJmx) {
        // props.put("java.naming.factory.url.pkgs", "com.caucho.naming");

        EnvironmentProperties.enableEnvironmentSystemProperties(true);

        String oldBuilder = props.getProperty("javax.management.builder.initial");
        if (oldBuilder == null) {
          oldBuilder = "com.caucho.v5.jmx.MBeanServerBuilderImpl";
          props.put("javax.management.builder.initial", oldBuilder);
        }

        Object value = ManagementFactory.getPlatformMBeanServer();
      }
      */
    } catch (Throwable e) {
      log().log(Level.FINE, e.toString(), e);
    } finally {
      thread.setContextClassLoader(oldLoader);
      
      _isInitComplete = true;
    }
  }
1074509
public void collectVariables(EnvVars env, Run build, TaskListener listener) {
        EnvVars buildParameters = Utils.extractBuildParameters(build, listener);
        if (buildParameters != null) {
            env.putAll(buildParameters);
        }
        addAllWithFilter(envVars, env, filter.getPatternFilter());
        Map<String, String> sysEnv = new HashMap<>();
        Properties systemProperties = System.getProperties();
        Enumeration<?> enumeration = systemProperties.propertyNames();
        while (enumeration.hasMoreElements()) {
            String propertyKey = (String) enumeration.nextElement();
            sysEnv.put(propertyKey, systemProperties.getProperty(propertyKey));
        }
        addAllWithFilter(sysVars, sysEnv, filter.getPatternFilter());
    }
1230040
public static int startServer(String settings, PrintStream err) {
        try {
            String portfile = Util.extractStringOption("portfile", settings);
            // The log file collects more javac server specific log information.
            String logfile = Util.extractStringOption("logfile", settings);
            // The stdouterr file collects all the System.out and System.err writes to disk.
            String stdouterrfile = Util.extractStringOption("stdouterrfile", settings);
            // We could perhaps use System.setOut and setErr here.
            // But for the moment we rely on the client to spawn a shell where stdout
            // and stderr are redirected already.
            // The pool size is a limit the number of concurrent compiler threads used.
            // The server might use less than these to avoid memory problems.
            int poolsize = Util.extractIntOption("poolsize", settings);
            if (poolsize <= 0) {
                // If not set, default to the number of cores.
                poolsize = Runtime.getRuntime().availableProcessors();
            }

            // How many seconds of inactivity will the server accept before quitting?
            int keepalive = Util.extractIntOption("keepalive", settings);
            if (keepalive <= 0) {
                keepalive = 120;
            }
            // The port file is locked and the server port and cookie is written into it.
            PortFile portFile = getPortFile(portfile);
            JavacServer s;

            synchronized (portFile) {
                portFile.lock();
                portFile.getValues();
                if (portFile.containsPortInfo()) {
                    err.println("Javac server not started because portfile exists!");
                    portFile.unlock();
                    return -1;
                }
                s = new JavacServer(poolsize, logfile);
                portFile.setValues(s.getPort(), s.getCookie());
                portFile.unlock();
            }

            // Run the server. Will delete the port file when shutting down.
            // It will shut down automatically when no new requests have come in
            // during the last 125 seconds.
            s.run(portFile, err, keepalive);
            // The run loop for the server has exited.
            return 0;
        } catch (Exception e) {
            e.printStackTrace(err);
            return -1;
        }
    }
41750
public static function onWorkerStart() {
		Yesf::app()->loadEnvConfig();
		Yesf::loadProjectConfig();
		Logger::init();
		Response::init();
		Response::initInWorker();
		Utils::setRDAlias();
		Utils::setCacheAlias();
		Pool::init();
	}
705765
async def Runtime(args, env):
    ''
    r = _Runtime(args, env)
    await r._init_cache()
    return r
1028574
static boolean hasEnvironmentVariable(String variable) {
        final String value = System.getenv(variable);
        if (value != null) {
            return true;
        }
        return false;
    }
759817
function resetTernServer() {
    // If a server is already created just reset the analysis data 
    if (ternServer) {
        ternServer.reset();
        Infer.resetGuessing();
        // tell the main thread we're ready to start processing again
        self.postMessage({type: MessageIds.TERN_WORKER_READY});
    }
}
654126
public void reload() throws IOException, InterruptedException, ReactorException {
        queue.save();
        executeReactor(null, loadTasks());

        // Ensure we reached the final initialization state. Log the error otherwise
        if (initLevel != InitMilestone.COMPLETED) {
            LOGGER.log(SEVERE, "Jenkins initialization has not reached the COMPLETED initialization milestone after the configuration reload. " +
                            "Current state: {0}. " +
                            "It may cause undefined incorrect behavior in Jenkins plugin relying on this state. " +
                            "It is likely an issue with the Initialization task graph. " +
                            "Example: usage of @Initializer(after = InitMilestone.COMPLETED) in a plugin (JENKINS-37759). " +
                            "Please create a bug in Jenkins bugtracker.",
                    initLevel);
        }

        User.reload();
        queue.load();
        WebApp.get(servletContext).setApp(this);
    }
842969
function setLoading(value) {
    if (ctrl.loading !== value) {
      ctrl.loading = value;
    }

    // Always refresh the hidden variable as something else might have changed
    ctrl.hidden = shouldHide();
  }
1215194
public void reloadPlugin() {
        sendConsoleMessage(Level.INFO, "Starting up!");
        sendConsoleMessage(Level.INFO, "Loading the Configuration");
        config = new ConfigurationManager(serverCaller);
        mainConfig = config.loadFile(serverCaller.getDataFolder(), "config.yml");
        if (!mainConfig.has("System.Setup")) {
            initializeConfig();
        }
        if (!getMainConfig().has("System.Database.Prefix")) {
            getMainConfig().setValue("System.Database.Prefix", "cc3_");
        }

        languageManager = new LanguageManager(serverCaller, serverCaller.getDataFolder(), "lang.yml");
        loadLanguage();
        serverCaller.setCommandPrefix(languageManager.getString("command_prefix"));
        commandManager.setCurrentLevel(1);
        initialiseDatabase();
        updateDatabase();
        initializeCurrency();
        sendConsoleMessage(Level.INFO, getLanguageManager().getString("loading_default_settings"));
        loadDefaultSettings();
        sendConsoleMessage(Level.INFO, getLanguageManager().getString("default_settings_loaded"));
        startUp();
        sendConsoleMessage(Level.INFO, getLanguageManager().getString("ready"));

    }
225803
private void startWorker() {
    JobServiceFactory serviceFactory = new JobServiceFactory() {

      private boolean first = true;

      public JobService connect() {
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            setStatus("Connecting...");
          }
        });
        JobService service = first ? MainWindow.this.connect()
            : reconnect();
        if (service == null) {
          setVisible(false);
          throw new RuntimeException("Unable to connect");
        }
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            setStatus("Connected");
          }
        });
        first = false;
        return service;
      }
//
//      public JobService connect() {
//        try {
//          SwingUtilities.invokeAndWait(task);
//        } catch (Exception e) {
//          logger.warn("Exception thrown trying to reconnect", e);
//          throw new RuntimeException(e);
//        }
//        if (task.service == null) {
//          throw new RuntimeException("No service.");
//        }
//        return task.service;
//      }

    };

    int availableCpus = Runtime.getRuntime().availableProcessors();
    if (options.numberOfCpus < 0) {
      options.numberOfCpus = pref.getInt("maxCpus", 0);
    }
    if (options.numberOfCpus <= 0 || options.numberOfCpus > availableCpus) {
      options.numberOfCpus = availableCpus;
    }

    if (worker != null) {
      setStatus("Shutting down worker...");
      worker.shutdown();
      try {
        workerThread.join();
      } catch (InterruptedException e) {
      }
      progressPanel.clear();
    }

    setStatus("Starting worker...");

    CourtesyMonitor courtesyMonitor = (powerMonitor != null) ? powerMonitor
        : new UnconditionalCourtesyMonitor();
    ThreadFactory threadFactory = new BackgroundThreadFactory();
    worker = new ThreadServiceWorker(serviceFactory, threadFactory,
        getProgressPanel(), courtesyMonitor);
    worker.setMaxWorkers(options.numberOfCpus);

    boolean cacheClassDefinitions = pref.getBoolean("cacheClassDefinitions", true);
    if (cacheClassDefinitions) {
      setStatus("Preparing data source...");
      EmbeddedDataSource ds = null;
      try {
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        ds = new EmbeddedDataSource();
        ds.setConnectionAttributes("create=true");
        ds.setDatabaseName("classes");
        worker.setDataSource(ds);
      } catch (ClassNotFoundException e) {
        logger.error("Could not locate database driver.", e);
      } catch (SQLException e) {
        logger.error("Error occurred while initializing data source.", e);
      }
    }

    onPreferencesChanged();

    workerThread = new Thread(worker);
    workerThread.start();

  }
748114
function reserveWorker(workerType, callback) {
        var debug = false,
            execArgv = process.execArgv.filter(function (arg) {
                if (arg.indexOf('--debug-brk') === 0) {
                    debug = '--debug-brk';
                } else if (arg.indexOf('--debug') === 0) {
                    debug = '--debug';
                } else if (arg.indexOf('--inspect-brk') === 0) {
                    debug = '--inspect-brk';
                } else if (arg.indexOf('--inspect') === 0) {
                    debug = '--inspect';
                } else {
                    return true;
                }

                return false;
            });
        // http://stackoverflow.com/questions/16840623/how-to-debug-node-js-child-forked-process
        // For some reason --debug-brk is given here..
        if (debug) {
            logger.info('Main process is in debug mode [', debug, ']');
            execArgv.push(debug + '=' + debugPort.toString());
            logger.info('Child debug port: ' + debugPort.toString());
            debugPort += 2;
        }

        logger.debug('execArgv for main process', process.execArgv);
        logger.debug('execArgv for new child process', execArgv);

        if (Object.keys(_workers || {}).length < gmeConfig.server.maxWorkers) {
            var childProcess = Child.fork(SIMPLE_WORKER_JS, [], {execArgv: execArgv});

            _workers[childProcess.pid] = {
                childProcess: childProcess,
                state: CONSTANTS.workerStates.initializing,
                type: workerType,
                cb: null
            };

            logger.debug('workerPid forked ' + childProcess.pid);
            childProcess.on('message', function (msg) {
                messageHandling(msg);

                // FIXME: Do we really need the "initialize" in addition to "initialized"?
                // FIXME: Why couldn't the worker start the initializing at spawn? (It can load the gmeConfig itself)
                if (msg.type === CONSTANTS.msgTypes.initialized && typeof callback === 'function') {
                    callback();
                    callback = null;
                }
            });

            childProcess.on('exit', function (code, signal) {
                logger.debug('worker has exited: ' + childProcess.pid);
                // When killing child-process the code is undefined and the signal SIGINT.
                if (code !== 0 && signal !== 'SIGINT') {
                    logger.warn('worker ' + childProcess.pid + ' has exited abnormally with code ' + code +
                        ', signal', signal);
                    if (typeof callback === 'function') {
                        callback(new Error('worker ' + childProcess.pid + ' exited abnormally with code ' + code));
                    }
                } else {
                    logger.debug('worker ' + childProcess.pid + ' was terminated.');
                }

                delete _workers[childProcess.pid];
                reserveWorkerIfNecessary(workerType);
            });
        } else if (typeof callback === 'function') {
            callback();
        }
    }
1150788
@Override
  public T loadInBackground() {
    Cursor cursor = null;
    try {
      CancellationSignal cancellationSignal = initCancellationSignal();
      cursor = loadCursorInBackground();
      cancellationSignal.throwIfCanceled();
      final T result = mCursorTransformation.apply(cursor, cancellationSignal);
      Preconditions.checkNotNull(result, "Function passed to this loader should never return null.");

      synchronized (pendingLoadResults) {
        pendingLoadResults.add(new Pair<>(result, cursor));
      }

      return result;
    } catch (OperationCanceledException ex) {
      releaseCursor(cursor);
      throw ex;
    } catch (Throwable t) {
      throw new RuntimeException("Error occurred when running loader: " + this, t);
    } finally {
      destroyCancellationSignal();
    }
  }
1325922
function WorkerFn(root) {
  var timers = {};

  root.onmessage = function (event) {
    switch (event.data.type) {
      case 'ping':
        root.postMessage({ type: 'pong' });
        break;

      case 'set_timeout':
        timers[event.data.id] = setTimeout(function () {
          root.postMessage({ type: 'tick', id: event.data.id });
        }, event.data.delay);
        break;

      case 'clear_timeout':
        clearTimeout(timers[event.data.id]);
        break;

      case 'set_interval':
        timers[event.data.id] = setInterval(function () {
          root.postMessage({ type: 'tick', id: event.data.id });
        }, event.data.interval);
        break;

      case 'clear_interval':
        clearInterval(timers[event.data.id]);
        break;
    }
  };
}
529858
public void checkServerState(final AsyncCallback<Boolean> callback, final String standBy, final String success) {

        // :read-attribute(name=process-type)
        final ModelNode operation = new ModelNode();
        operation.get(OP).set(READ_ATTRIBUTE_OPERATION);
        operation.get(NAME).set("server-state");
        operation.get(ADDRESS).setEmptyList();

        dispatchAsync.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {

            @Override
            public void onSuccess(DMRResponse result) {

                ModelNode response = result.get();

                if (response.isFailure()) {
                    callback.onFailure(new RuntimeException("Failed to poll server state"));
                } else {
                    // TODO: only works when this response changes the reload state
                    String outcome = response.get(RESULT).asString();
                    boolean keepRunning = !outcome.equalsIgnoreCase("running");//reloadState.isStaleModel();

                    if (!keepRunning) {

                        // clear state
                        reloadState.reset();

                        Console.info(Console.MESSAGES.successful(success));

                        // clear reload state
                        eventBus.fireEvent(new ReloadEvent());
                    }

                    callback.onSuccess(keepRunning);
                }
            }

            @Override
            public void onFailure(Throwable caught) {
                Console.getMessageCenter().notify(new Message(standBy, caught.getMessage(), Message.Severity.Warning));
            }
        });
    }
984285
function startWorkerPoolServer(options, listenCallback)
{
	var workerPool = createWorkerPool();
	var server = createServer(options);
	var logConnection = getOption(options, 'logConnection', true);
	var port = getOption(options, 'port', 0);

	server.on('client', (client) => {
		
		client.on('RGST', (msg) => {
			workerPool.addClient(client);
		});
		
		client.on('error', (e) => {
			workerPool.deleteClient(client);
		});
		
		client.on('close', () => {
			workerPool.deleteClient(client);
		});
	});
	
	server.listen({port: port}, () => {
		if ( logConnection )
		{
			console.log('LISTEN ' + port);
		}
		if ( listenCallback )
		{
			listenCallback(server);
		}
	});
	
	return workerPool;
}