Get a handler that calls Jenkins API to stream console output.

@param {Function} cb: callback for argument handling
@return Jenkins API handler function
762501
function _console(cb) {
  return function (name, buildNumber, args) {

    if (!args) {
      args = buildNumber;
      buildNumber = null;
    }

    function jenkinsCb(jenkins) {
      // console does not trigger any build, interval is set to 0 (no-pending delay time)
      var interval = 0;

      var stream = jenkins.streamJobConsole(name, buildNumber, interval, cli.exit);
      stream.pipe(process.stdout, { end: false });
    }
    cb(args, jenkinsCb);
  };
}
475856
function responseHandler(params, cb) {

  return function handleResponse(err, httpResponse, body) {
    body = body || "{}";
    httpResponse = httpResponse || {};

    //The response should be JSON. If it is a string, then the response should be parsed.
    if (_.isString(body)) {
      try {
        body = JSON.parse(body);
      } catch (e) {
        log.logger.error("FH-MBAAS-CLIENT: Invalid Response Body ", {body: body});
      }
    }

    log.logger.debug("FH-MBAAS-CLIENT:  Request Finish ", {
      err: err,
      httpResponse: httpResponse.statusCode,
      body: body
    });

    // provide defaults
    if (httpResponse && httpResponse.statusCode >= 400) {
      err = err || {};
      err.httpCode = httpResponse.statusCode;
      err.message = "Unexpected Status Code " + httpResponse.statusCode;
    }

    //There is a specific error message if an environment is unreachable
    if (httpResponse && httpResponse.statusCode === 503) {
      err = {
        httpCode: 503,
        message: CONSTANTS.ERROR_MESSAGES.ENVIRONMENT_UNREACHABLE.replace('{{ENVLABEL}}', params.envLabel || "")
      };
    }

    // MbaaS unavailable
    if (err && err.code !== undefined && (err.code === "ENOTFOUND" || err.code === "ETIMEDOUT")) {
      err = {
        httpCode: httpResponse.statusCode || 500,
        message: "MBaaS environment is not reachable. Please make the environment available or delete it. Environment Label - " + params.envLabel || ""
      };
    }

    if (err) {
      cb(err || body || "Unexpected Status Code " + httpResponse.statusCode);
    } else {
      cb(undefined, body);
    }
  };
}
849096
function handleErrorCallback(cb) {
  return function(err) {
    if (err) {
      logger.error(err);
      return cb(err);
    }
    return cb.apply(this, arguments);
  };
}
485821
function runCommand(name, args, options, cb, stdoutHandler, stderrHandler) {
	//if we dont actually have stdout and stderr, try to get the cb
	//if there was no callback passed, used a default

	options = options || { cwd : cwd, env: env };
	var child = spawn(name, args, options);
	if (cb) {
		var out = null;
		var err = null;
		//we need to wait for process.exit, stdout.end, and stderr.end before
		//we return
		var waiting = 3;
		var returnArgs = [];

		var fire = function(index, arg) {
			if (arg != null) {
				returnArgs[index] = arg;
			}
			if (--waiting === 0) {
				cb.apply(undefined, returnArgs);
			}
		};
		//buffer stdout and stderr to pass to the completion callback
		if (!stdoutHandler) {
			out = '';
			stdoutHandler = function(data) {
				out += data;
			};
		}
		if (!stderrHandler) {
			err = '';
			stderrHandler = function(data) {
				err += data;
			};
		}
		child.stdout.setEncoding('utf8');
		child.stdout.on('data', stdoutHandler); 
		child.stdout.on('end', function() {fire(1, out); });
				
		child.stderr.setEncoding('utf8');
		child.stderr.on('data', stderrHandler);
		child.stderr.on('end', function() {fire(2, err); });

		child.on('exit', function(code) {
			fire(0, code);
		});
	}

	return child;

}
811920
function makeAsync(cb) {
    return function () {
        var args = arguments;
        process.nextTick(function () {
            cb.apply(null, args);
        });
    };
}
476607
function executeCallback(cb, arg) {
    var r = cb(arg)
    if(r !== undefined && !isLikeAFuture(r) )
        throw Error("Value returned from then or catch ("+r+") is *not* a Future. Callback: "+cb.toString())

    return r
}
332859
function executor(cb) {
  return function (args) {
    function resultCb(result) {

      var computers = result.computer;

      if (_.isEmpty(computers)) {
        console.log(text.__('No executor found'));
      } else {

        var data = Jenkins.executorSummary(computers);

        _.keys(data).forEach(function (computer) {
          console.log('+ %s | %s', computer, data[computer].summary);
          data[computer].executors.forEach(function (executor) {
            if (!executor.idle) {
              console.log('  - %s | %s%%s', executor.name, executor.progress, (executor.stuck) ? text.__(' stuck!') : '');
            }
          });
        });

      }
    }
    function jenkinsCb(jenkins) {
      jenkins.computer(cli.exitCb(null, resultCb));
    }
    cb(args, jenkinsCb);
  };
}
883603
function(nameOrDir, cb) {
    var errorPrefix, onError, onSuccess;

    // Strip any leading slash
    if (nameOrDir && nameOrDir.substr(0, 1) === '/') {
      nameOrDir = nameOrDir.substr(1);
    }

    // Check for errors. Note this feature requires jQuery at the moment
    errorPrefix = 'SocketStream Error: The ss.load.code() command ';
    if (!jQuery) {
      return console.error(errorPrefix + 'requires jQuery to be present');
    }
    if (!nameOrDir) {
      return console.error(errorPrefix + 'requires a directory to load. Specify it as the first argument. '+
        'E.g. The ss.load.code(\'/mail\',cb) will load code in /client/code/mail');
    }
    if (!cb) {
      return console.error(errorPrefix + 'requires a callback. Specify it as the last argument');
    }

    // If we've loaded this module or package before, callback right away
    if (async.loaded[nameOrDir]) {
      return cb();
    }

    // Else, register callback and use EE to prevent multiple reqs for the same mod/package to the server before the first responds
    async.loading.once(nameOrDir, cb);

    // Retrieve module or directory of modules from the server if this is the first request
    if (async.loading.listeners(nameOrDir).length === 1) {
      onError = function() {
        console.error('SocketStream Error: Could not asynchronously load ' + nameOrDir);
        return console.log(arguments);
      };
      onSuccess = function() {
        async.loaded[nameOrDir] = true;
        return async.loading.emit(nameOrDir);
      };

      // Send request to server
      return $.ajax({
        url: '/assets/ondemand/' + nameOrDir,
        type: 'GET',
        cache: false,
        dataType: 'script',
        success: onSuccess,
        error: onError
      });
    }
  }
1345259
function(cb_) {
    common.log.out('Hash generation: ' + base_name + '.tar.gz.sha1sum');
    var sha1sum = require('child_process').spawn('sha1sum', 
      [base_name + '.tar.gz'], {
      cwd: out_path
    });
    var out = fs.createWriteStream(path.join(out_path, 
                                             base_name + '.tar.gz.sha1sum'));
    sha1sum.stdout.on('data', function(data) {
      out.write(data);
    });
    sha1sum.stderr.on('data', function(data) {
      console.log('stderr: ' + data);
    });
    sha1sum.on('close', function(code) {
      out.end();
      if(code !== 0) {
        return cb_(common.err('`sha1sum` failed with code: ' + code,
                              'auto_updater:failed_sha1sum'));

      }
      return cb_();
    });
  }
1265679
function load(opts, cb) {
  if(typeof opts === 'function') {
    cb = opts;
    opts = null;
  }

  var args = opts && opts.args ? opts.args : null
    , defaults = path.normalize(path.join(__dirname, 'command'));
  opts = opts || argv(args);

  if(opts.commands === undefined) {
    opts.commands = [defaults];
  }else if(Array.isArray(opts.commands) && opts.defaults) {
    opts.commands.unshift(defaults);
  }

  function onConfigError(err) {
    //console.dir(err);
    console.error(err.message);
    if(process.env.NODE_ENV !== Constants.TEST) {
      process.exit(1);
    }
  }

  this.conf.once('error', onConfigError.bind(this));

  function onConfigLoad() {
    // if we loaded ok we are done with fatal config errors
    // config set/rewrite need to catch errors now
    this.conf.removeAllListeners('error');

    this.emit('config', this.conf);

    opts.conf = this.conf;

    // spawning the daemon process
    if(this.conf.get(ConfigKey.DAEMONIZE) && !this._daemonized) {
      var pid = daemon(
        path.join(__dirname, 'daemonize.js'), this.conf, opts.args);
      if(cb) cb(pid);
      return;
    }

    this.log.notice('cwd: %s', process.cwd());

    // pass configured timeout to script manager
    ScriptManager.timeout = this.conf.get(ConfigKey.LUA_TIME_LIMIT);

    // spawn now, makes first script executions faster
    // later this should be configurable - allow disabling all
    // scripting
    ScriptManager.spawn();

    // load commands
    return loader(opts, onCommandLoad);
  }

  function onCommandLoad(err, commands) {
    if(err) return cb(err);
    this.execs = commands;
    this.emit('ready', this.execs);

    // inject command list so the script manager
    // can detect write commands
    ScriptManager.commands = commands;

    // loading from rdb files breaks the tests
    if(process.env.NODE_ENV === Constants.TEST) {
      return cb();
    }
    Persistence.load(this.state.store, this.state.conf, onDatabaseLoad);
  }

  function onDatabaseLoad(err, time, diff, version) {
    // load errors are thrown, will cause
    // the process to exit
    if(err) throw err;
    if(err !== false) {
      this.log.notice('db loaded from disk: %s seconds (v%s)', time, version);
      this.emit('database', time, diff, version);
    }
    cb();
  }

  onConfigLoad = onConfigLoad.bind(this);
  onCommandLoad = onCommandLoad.bind(this);
  onDatabaseLoad = onDatabaseLoad.bind(this);

  // load config
  this.conf.load(opts, onConfigLoad);
}
800216
function(cb) {
          var opts = {
            url: uri + 'user/stream',
            method: 'GET',
            qs: qs,
            json: true
          };
          request(opts,function(e,r,b) {
            if (e) cb(e)
            else {
              if (r.statusCode==200) cb(null, b)
              else {
                cb({statusCode:r.statusCode,error:b.error})
              }
            }
          });
        }
871428
function (url, cb) {

            var request = new XMLHttpRequest();

            request.onload = function () {
                if (this.status >= 200 && this.status < 400) {
                    cb(this.response);
                }
                else {
                    Logger.log(Logger.LEVEL_SEVERE, "sever error: " + this.status);
                    cb(null);
                }
            };

            request.onerror = function (e) {
                Logger.log(Logger.LEVEL_SEVERE, "connection error: " + e);
                cb(null);
            };

            request.open("get", url, true);

            request.send();
        }
342375
function runServer(cb) {
  function onStdOut(data) {
    const time = new Date().toTimeString();
    const match = data.toString('utf8').match(RUNNING_REGEXP);

    process.stdout.write(time.replace(/.*(\d{2}:\d{2}:\d{2}).*/, '[$1] '));
    process.stdout.write(data);

    if (match) {
      server.stdout.removeListener('data', onStdOut);
      server.stdout.on('data', x => process.stdout.write(x));
      if (cb) {
        cb(null, match[1]);
      }
    }
  }

  if (server) {
    server.kill('SIGTERM');
  }

  server = cp.spawn('node', [serverPath], {
    env: Object.assign({ NODE_ENV: 'development' }, process.env),
    silent: false,
  });

  server.stdout.on('data', onStdOut);
  server.stderr.on('data', x => process.stderr.write(x));
}
151983
function (callback) {
                var self = this;
                flow()
                    .seq(function (cb) {
                        self.$handlers.stop(function () {
                            // ignore errors during stop
                            cb();
                        });
                    })
                    .seq(function (cb) {
                        self.$authenticationService.stop(function () {
                            cb();
                        });
                    })
                    .seq(function (cb) {
                        self.$filters.stop(function () {
                            // ignore errors during stop
                            cb();
                        });
                    })
                    .seq(function (cb) {
                        self.$endPoints.shutdown(function () {
                            // ignore errors during shutdown
                            cb();
                        });
                    })
                    .exec(function (err) {
                        callback && callback(err);

                        process.stdin.end();
                    });
            }
674221
function sendCommand(js,cb){
    if(!js) return stream.log('send command got no command!',js);
    var id = ++stream.inc;
    if(!js.id) js.id = 0;// default input id.

    var start = Date.now();
    var timeCallback = function(err,js){
      js.basetime = Date.now()-start;// decorate performance time.
      if(cb) cb(err,js)
    }

    if(js.timeout == undefined) js.timeout = 10000;
    else if(js.timeout < 0) {
      js.timeout = 60000;// 60 seconds max timeout
    } else if(js.timeout > 60000){
      js.timeout = 60000; 
    }
    
    var timeout = js.timeout;
    setTimeout(function(){
      if(stream.callbacks[id]) {
        // make reply js
        js.type = "reply";
        js.err = "base timeout in "+timeout+" ms";
        js.timeout = timeout;
        js.timeerror = true;
        js.from = js.to;
        delete js.to;
        timeCallback(true,js);
      }
    },timeout);

    stream.callbacks[id] = {id:js.id,cb:timeCallback};
    js.id = id;

    if(stream.inc > maxId) stream.inc = 1;

    js.type = "command";
    toBoard.write(js);
  
    return js;
  }
1293525
function downloadFile(cb) {
      if(task.file_path) {
        // Download the file
        var stream = fs.createWriteStream(path);

        // Store error if statusCode !== 200
        var err;
        stream.on("finish", function() {
          cb(err);
        });

        var urlToDownload = url.parse(task.file_path, false, true);

        // deny queries to ElasticSearch and other vulnerable services
        if(task.config.forbiddenPorts && task.config.forbiddenPorts.indexOf(urlToDownload.port) !== -1) {
          stream.end();
          return fs.unlink(path, function() {
            cb(new Error('Trying to access forbidden port: ' + urlToDownload.port));
          });
        }

        var req = request(urlToDownload.protocol + "//" + urlToDownload.host)
          .get(urlToDownload.path);

        // Warning, Black magic.
        // Streaming and checking for status code is no easy task...
        // Hours spent optimizing: 22
        req.end(function() {}).req.once('response', function(res) {
          if(res.statusCode !== 200) {
            if(res.statusCode === 410) {
              err = new Error('410 Gone');
              err.skip = true;
            }
            else {
              err = new Error('Error downloading file, got status ' + res.statusCode);
            }

            stream.end();
            this.abort();
          }
        });
        req.pipe(stream);
      }
      else {
        cb(null);
      }
    }
90953
function Channel_connect(cb) {
  cb = utils.callOnce(cb)

  var websocket = new WebSocket(this._url, [this._protocol])

  websocket.addEventListener("open",    onOpen)
  websocket.addEventListener("message", onMessage)
  websocket.addEventListener("close",   onClose)
  websocket.addEventListener("error",   onError)

  var channel = this

  //-----------------------------------
  function onOpen() {
    channel._websocket = websocket

    cb(null)
  }

  //-----------------------------------
  function onMessage(event) {
    if (!channel._websocket) return

    var message = JSON.parse(event.data)

    channel.emit("message", message)
  }

  //-----------------------------------
  function onClose() {
    if (!channel._websocket) return

    channel._websocket = null

    channel.emit("close")
    cb(new Error("closed"))
  }

  //-----------------------------------
  function onError() {
    channel.emit("error", new Error("undisclosed error"))
  }

}