callback to return response to client
168642
function (res_obj, data, conn) {

		// check if we should return empty response
		if (typeof res_obj === 'undefined') {
			SR.REST.reply(res, {});
			return true;
		}

		// check for special case processing (SR_REDIRECT)
		if (res_obj[SR.Tags.UPDATE] === 'SR_REDIRECT' && res_obj[SR.Tags.PARA] && res_obj[SR.Tags.PARA].url) {

			var url = res_obj[SR.Tags.PARA].url;
			LOG.warn('redirecting to: ' + url, l_name);

			/*
			res.writeHead(302, {
				'Location': url
			});
			res.end();
			*/

			// redirect by page 
			// TODO: merge with same code in FB.js
			var page =
				'<html><body><script>\n' +
				'if (navigator.appName.indexOf("Microsoft") != -1)\n' +
				'    window.top.location.href="' + url + '";\n' +
				'else\n' +
				'	 top.location.href="' + url + '";\n' +
				'</script></body></html>\n';

			res.writeHead(200, {
				'Content-Type': 'text/html'
			});
			res.end(page);

			return true;
		}
		
		// check for special case processing (SR_HTML)
		if (res_obj[SR.Tags.UPDATE] === 'SR_HTML' && res_obj[SR.Tags.PARA].page) {
			res.writeHead(200, {
				'Content-Type': 'text/html'
			});
			res.end(res_obj[SR.Tags.PARA].page);
			return true;
		}

		// check for special case processing (SR_DOWNLOAD)
		if (res_obj[SR.Tags.UPDATE] === 'SR_DOWNLOAD' && res_obj[SR.Tags.PARA].data && res_obj[SR.Tags.PARA].filename) {

			var filename = res_obj[SR.Tags.PARA].filename;
			LOG.warn('allow client to download file: ' + filename, l_name);

			var data = res_obj[SR.Tags.PARA].data;
			res.writeHead(200, {
				'Content-Type': 'application/octet-stream',
				'Content-Disposition': 'attachment; filename=' + filename,
				'Content-Length': data.length
			});
			res.end(data);
			return true;
		}

		// check for special case processing (SR_RESOURCE)
		if (res_obj[SR.Tags.UPDATE] === 'SR_RESOURCE' && res_obj[SR.Tags.PARA].address) {

			var file = res_obj[SR.Tags.PARA].address;
						
			// check if resource exists & its states
			SR.fs.stat(file, function (err, stats) {
										
				var resHeader = typeof res_obj[SR.Tags.PARA].header === 'object' ? res_obj[SR.Tags.PARA].header : {};
				
				if (err) {			
					LOG.error(err, l_name);
					res.writeHead(404, resHeader);
					res.end();
					return;
				}
				
				var extFilename = file.match(/[\W\w]*\.([\W\w]*)/)[1];
				if (typeof extFilename === 'string')
					extFilename = extFilename.toLowerCase();
				
				// default to 200 status
				var resStatus = 200;
				resHeader['Accept-Ranges'] = 'bytes';
				resHeader['Cache-Control'] = 'no-cache';
				resHeader['Content-Length'] = stats.size;
				
				if (l_extList[extFilename]) {
					resHeader['Content-Type'] = l_extList[extFilename];
				};
				
				var start = undefined;
				var end = undefined;
				
				// check if request range exists (e.g., streaming media such as webm/mp4) to return 206 status
				// see: https://delog.wordpress.com/2011/04/25/stream-webm-file-to-chrome-using-node-js/						
				if (req.headers.range) {
					var range = req.headers.range.split(/bytes=([0-9]*)-([0-9]*)/);
					resStatus = 206;
					
					start = parseInt(range[1] || 0);
					end = parseInt(range[2] || stats.size - 1);
					
					if (start > end) {
						LOG.error('stream file start > end. start: ' + start + ' end: ' + end, l_name);
						var resHeader = typeof res_obj[SR.Tags.PARA].header === 'object' ? res_obj[SR.Tags.PARA].header : {};
						res.writeHead(404, resHeader);
						res.end();
						return;  // abnormal if we've reached here
					}
					
					LOG.debug('requesting bytes ' + start + ' to ' + end + ' for file: ' + file, l_name);
							 
					resHeader['Connection'] = 'close';
					resHeader['Content-Length'] = end - start + 1;
					resHeader['Content-Range'] = 'bytes ' + start + '-' + end + '/' + stats.size;
					resHeader['Transfer-Encoding'] = 'chunked';
				} 
				// otherwise assume it's a regular file
				else if (l_directExt.hasOwnProperty(extFilename)) {
					// NOTE: code below will cause the file be downloaded in a "Save As.." format
					// (instead of being displayed directly), we only want this behavior for certain file types (such as .zip)				
					var filename = file.replace(/^.*[\\\/]/, '')
					LOG.warn('requesting a file: ' + filename, l_name);
					resHeader['Content-Disposition'] = 'attachment; filename=' + filename;
				}
				
				LOG.sys('SR_RESOURCE header:', l_name);
				LOG.sys(resHeader);
				res.writeHead(resStatus, resHeader);

				// start streaming
				SR.fs.createReadStream(file, {
					flags: 'r',
					start: start,
					end: end
				}).pipe(res);			
			});
			
			return true;
		}

		var origin = _getOrigin(req);

		// send back via res object if hadn't responded yet
		if (res.headersSent === false) {
			// NOTE: cookie may be undefined;
			SR.REST.reply(res, data, {
				origin: origin,
				cookie: cookie
			});
		}
		else {
			LOG.error('HTTP request has already responded (cannot respond twice)', l_name);
			LOG.stack();
		}

		return true;
	}
1294200
function (err, data) {
      debug(`${service}.${method} response:`, err || {
        status: data && data.status,
        size: data && JSON.stringify(data).length
      });
      if (err) return next(err.cause || err);

      res.data = data;

      if (!data) {
        debug(`No content returned for '${req.url}'`);
        res.status(statusCodes.noContent);
      } else if (method === 'create') {
        res.status(statusCodes.created);
      }

      return next();
    }
1205820
function checkResponse(err, data, response) {
		var results, accessToken, accessSecret;

		if (err) {
			return callback(err);
		}

		// Check if we got a for url encoded response
		if (/oauth_token/.test(data)) {
			results = require('querystring').parse(data);
			accessToken= results['oauth_token'];
			accessSecret = results['oauth_token_secret'];

			delete results['oauth_token'];
			delete results['oauth_token_secret'];

			return callback(null, accessToken, accessSecret);
		}

		// We didn't so parse the body as an XML response
		responseParser.parse(data,
			{ format: this.format, logger: this.logger }, getTokens);
		function getTokens(err, tokenResponse) {
			var accessToken, accessSecret;

			if (err) {
				return callback(err);
			}

			accessToken = tokenResponse.oauth_access_token.oauth_token;
			accessSecret = tokenResponse.oauth_access_token.oauth_token_secret;

			return callback(null, accessToken, accessSecret);
		}
   }
11530
function (fn) {
            return function (response) {
                fn(response.status === "success" ? true : false, response.message, response.data);
            };
        }
142276
function(callback)
    {
        var params = util.extend({count:1}, this.params);        
        this.api.doRequest("GET", this.path, params, function(err, res) {
            if (err)
            {
                return callback(err);
            }                    
            callback(null, res.count);
        });
    }
576483
function requestHandler (method) {
  return function (req, res, next) {
    method.call(this, req, responseHandler(res, next));
  }.bind(this);
}
856952
function _getResponseStatus(handler, req, callback) {
        // Number
        if (!_(handler.reply.status).isFunction()) {
            return callback(handler.reply.status || 0);
        }

        // Synch function
        return callback(handler.reply.status(req) || 0);
    }
653202
function desiredResponse (context) {
  const callback = context.task.callbackManager.callbacks[context.executionName]
  return callback ? callback.eventName : COMPLETE
}
775746
function() {
        // Send request
        var sendRequest = function() {
          debug('Calling: %s, retry: %s', entry.name, attempts - 1);
          // Make request and handle response or error
          return makeRequest(
            that,
            entry.method,
            url,
            payload,
            query
          ).then(function(res) {
            // If request was successful, accept the result
            debug('Success calling: %s, (%s retries)',
              entry.name, attempts - 1);
            if (monitor) {
              var d = process.hrtime(start);
              monitor.measure([entry.name, 'success'], d[0] * 1000 + d[1] / 1000000);
              monitor.count([entry.name, 'success']);
            }
            if (!_.includes(res.headers['content-type'], 'application/json') || !res.body) {
              debug('Empty response from server: call: %s, method: %s', entry.name, entry.method);
              return undefined;
            }
            return res.body;
          }, function(err) {
            // If we got a response we read the error code from the response
            var res = err.response;
            if (res) {
              // Decide if we should retry
              if (attempts <= that._options.retries &&
                  res.status >= 500 &&  // Check if it's a 5xx error
                  res.status < 600) {
                debug('Error calling: %s now retrying, info: %j',
                  entry.name, res.body);
                return retryRequest();
              }
              // If not retrying, construct error object and reject
              debug('Error calling: %s NOT retrying!, info: %j',
                entry.name, res.body);
              var message = 'Unknown Server Error';
              if (res.status === 401) {
                message = 'Authentication Error';
              }
              if (res.status === 500) {
                message = 'Internal Server Error';
              }
              err = new Error(res.body.message || message);
              err.body = res.body;
              err.code = res.body.code || 'UnknownError';
              err.statusCode = res.status;
              if (monitor) {
                var d = process.hrtime(start);

                var state = 'client-error';
                if (res.statusCode >= 500) {
                  state = 'server-error';
                }
                monitor.measure([entry.name, state], d[0] * 1000 + d[1] / 1000000);
                monitor.count([entry.name, state]);
              }
              throw err;
            }

            // Decide if we should retry
            if (attempts <= that._options.retries) {
              debug('Request error calling %s (retrying), err: %s, JSON: %s',
                entry.name, err, err);
              return retryRequest();
            }
            debug('Request error calling %s NOT retrying!, err: %s, JSON: %s',
              entry.name, err, err);
            if (monitor) {
              var d = process.hrtime(start);
              monitor.measure([entry.name, 'connection-error'], d[0] * 1000 + d[1] / 1000000);
              monitor.count([entry.name, 'connection-error']);
            }
            throw err;
          });
        };

        // Increment attempt count, but track how many we had before.
        attempts += 1;

        // If this is the first retry, ie we haven't retried yet, we make the
        // request immediately
        if (attempts === 1) {
          return sendRequest();
        } else {
          var delay;
          // First request is attempt = 1, so attempt = 2 is the first retry
          // we subtract one to get exponents: 1, 2, 3, 4, 5, ...
          delay = Math.pow(2, attempts - 1) * that._options.delayFactor;
          // Apply randomization factor
          var rf = that._options.randomizationFactor;
          delay *= Math.random() * 2 * rf + 1 - rf;
          // Always limit with a maximum delay
          delay = Math.min(delay, that._options.maxDelay);
          // Sleep then send the request
          return new Promise(function(accept) {
            setTimeout(accept, delay);
          }).then(function() {
            return sendRequest();
          });
        }
      }
698965
function getResponse( clbk ) {
	if ( typeof clbk !== 'function' ) {
		throw new TypeError( 'getResponse()::invalid input argument. Callback must be a function.' );
	}
	/**
	* FUNCTION: onResponse( error, response, body )
	*	Response handler.
	*
	* @private
	* @param {Object} error - error object
	* @param {Object} response - response object
	* @param {String} body - response body
	*/
	return function onResponse( error, response, body ) {
		var data;
		if ( error ) {
			clbk({
				'status': 502,
				'message': 'Request error. Unable to obtain data.'
			});
			return;
		}
		if ( !body ) {
			clbk({
				'status': 404,
				'message': 'No data returned. Empty body. Ensure all query parameters are correct.'
			});
			return;
		}
		try {
			data = JSON.parse( body );
		} catch ( err ) {
			clbk({
				'status': 502,
				'message': 'Unsupported data format. Response body cannot be parsed as JSON.'
			});
			return;
		}
		if ( Array.isArray( data ) && !data.length ) {
			clbk({
				'status': 404,
				'message': 'No data returned. Empty data array. Ensure all query parameters are correct.'
			});
			return;
		}
		clbk( null, data );
	}; // end FUNCTION onResponse()
}
751889
function returnResponse(res, Handler, data, perfInstance) {
        var content = React.renderToString(React.createElement(Handler, { data: data })),
            html = '<!DOCTYPE html>' + content;
        options.log && log(options.log, 'perf', perfInstance());
        res.end(html);
    }
740171
function callEntityMethod(req, res, next) {
  var payload = req.payload;
  var method = req.serversideMethod;

  if (req.hasCallback) {

    debug('Transforming callback function');
    payload[req.clientCallbackIndex] = function(err) {
      if (err) {
        return next(err);
      }

      var values = Array.prototype.slice.call(arguments).slice(1);

      debug('Callback function called. Values are:', values);

      res.entityResponse = values;

      next();
    };
  }

  debug('Calling ' + req.path + ' with arguments:', payload);

  var context = {
    req: req,
    xhr: true,
    setCookie: res.cookie.bind(res),
    clearCookie: res.clearCookie.bind(res)
  };

  var ret;

  // Calls the requested serverside method.
  // Applies the payload, and provides a context for validation purposes.
  // Caches errors in the method's scope, and sends it to the next error handler.
  try {
    ret = method.apply(context, payload);
  } catch(err) {
    return next(err);
  }

  if (util.isPromise(ret)) {
    ret.then(function(resolved) {
      res.entityResponse = [resolved];
      next();
    })
    .catch(function(err) {
      next(err);
    });
  }

  // If the request is not expecting the response from the entity,
  // send a generic 'Ok' response.
  else if (!req.hasCallback) {
    res.entityResponse = [ret];
    debug('Not asynchronous. Returning value: ', res.entityResponse);
    next();
  }
}
763324
def _request_callback(self, request_id):
        """"""
        def callback(future):
            # Remove the future from the client requests map
            self._client_request_futures.pop(request_id, None)

            if future.cancelled():
                future.set_exception(JsonRpcRequestCancelled())

            message = {
                'jsonrpc': JSONRPC_VERSION,
                'id': request_id,
            }

            try:
                message['result'] = future.result()
            except JsonRpcException as e:
                log.exception("Failed to handle request %s", request_id)
                message['error'] = e.to_dict()
            except Exception:  # pylint: disable=broad-except
                log.exception("Failed to handle request %s", request_id)
                message['error'] = JsonRpcInternalError.of(sys.exc_info()).to_dict()

            self._consumer(message)

        return callback
734429
function responseHandler (res, next) {
  return function (err, message) {
    if (err || !message) {
      next(err);
    } else {
      res.send(message);
    }
  }
}
1006067
def _client_request_callback(self, request: Request):
        ''''''
        self._item_session = self._new_item_session(request)
        self._item_session.request = request

        if self._cookie_jar:
            self._cookie_jar.add_cookie_header(request)

        verdict, reason = self._fetch_rule.check_subsequent_web_request(self._item_session)
        self._file_writer_session.process_request(request)

        if verdict:
            _logger.info(__(
                _('Fetching ‘{url}’.'),
                url=request.url_info.url
            ))

        return verdict
80696
function (result) {

      // don't send a second response
      if (responseHasBeenSent) {
        console.warn('JSON-RPC2 response has already been sent.')
        return
      }
      // notifications should not send error responses (JSON-RPC2 specs)
      if (!isMethodCall) {
        logNotificationResponseWarning(result, requestMessage)
        callback()
        return
      }

      // result should not be undefined
      if (result === undefined) {
        console.warn('JSON-RPC2 response from method ' + methodName + ' should return a result. (JSON-RPC2 spec)')
        result = ''
      }

      var rpcMessage = {
        jsonrpc: '2.0',
        result: result,
        id: id
      }

      callback(rpcMessage)
      responseHasBeenSent = true

    }
59887
function onResponse(httpCode, headers, body, callback) {
  var resp = {
    _HTTP: {
      status: httpCode
    },
    headers: headers
  };
  var i;
  var pieces;

  if(typeof body === 'string') {
    try {
      //JSON decode
      resp.body = (body.length > 0 && decodeJSON) ? JSON.parse(body) : body;
    }
    catch(e) {
      //failed to decode - likely not JSON
      resp.body = body;
    }
  }

  //will likely only happen in node due to httpOnly cookies
  if(headers['set-cookie']) {
    resp.cookies = {};

    for(i in headers['set-cookie']) {
      if(headers['set-cookie'].hasOwnProperty(i)) {
        pieces = headers['set-cookie'][i].split(';')[0].split('=');
        resp.cookies[pieces[0]] = pieces[1];
        pieces = null;
      }
    }
  }

  if(resp._HTTP.status >= 400) {
    observers._notify('error', resp);
  }

  if(typeof callback === 'function') {
    callback(resp, (resp._HTTP.status < 400));
  }
}