A function to log request into file
@param  {Object} req  Request
@param  {Object} res  Response
768661
function logRequest(req, res) {
		var responseTime = Math.round(req.duration),
			shouldLogRequest = requestLogger && req && req.url && req.url !== '/arrowPing.json',
			shouldADILog = options && options.adiLogging && adiLogger && req && req.url && isWhitelisted(req.url),
			time = new Date().getTime(),
			uri = (req.route && req.route.path) || req.path || (req.url && req.url.split('?')[0]),
			localPort = getPort(req);

		if (shouldLogRequest && req.log && req.logname && (req.logmetadata === undefined || req.logmetadata)) {
			requestLogger.info({
				req_id: req.requestId,
				req: req,
				res: res,
				route: req.route,
				name: req._logname,
				logname: req.logname,
				response_time: responseTime
			});

			const result = {
				url: req.url,
				req_headers: req.headers,
				status: res.status,
				req_id: req.requestId,
				name: req._logname,
				logname: req.logname,
				response_time: responseTime
			};
			fs.writeFile(req.logname + '.metadata', JSON.stringify(result));
		} else if (shouldLogRequest) {
			requestLogger.info({
				req_id: req.requestId,
				response_time: responseTime,
				route: req.route,
				req: req,
				res: res
			});
		}

		if (shouldADILog) {
			adiLogger.info({
				type: 'transaction',
				time: time,
				path: uri,
				protocol: req.protocol,
				protocolSrc: localPort,
				duration: responseTime,
				status: getStatus(res),
				serviceContexts: [
					{
						service: '',
						monitor: '',
						client: null,
						org: null,
						app: options.name,
						method: '',
						status: '',
						duration: ''
					}
				],
				customMsgAtts: {},
				correlationId: getCorrelationId(req),
				legs: [
					{
						uri: uri,
						status: res.statusCode,
						statusText: '',
						method: req.method,
						vhost: null,
						wafStatus: 0,
						bytesSent: parseInt(res.get('Content-Length'), 10) || null,
						bytesReceived: parseInt(req.get('Content-Length'), 10) || null,
						remoteName: '',
						remoteAddr: '',
						localAddr: '',
						remotePort: '',
						localPort: '',
						sslsubject: null,
						leg: 0,
						timestamp: time,
						duration: responseTime,
						serviceName: uri,
						subject: null,
						operation: req.method + ' - ' + uri,
						type: req.protocol,
						finalStatus: ''
					}
				]
			});
		}
		if (req.cleanStream) {
			req.cleanStream();
			req.cleanStream = null;
		}
	}
1261327
function logHttpResponse (uniqueId, res) {
    // require log client
    if (!logClient) {
        return
    }
    // log response
    logClient.log('httpResponse', {
        httpRequestId: uniqueId.id,
        httpResponseBody: res.body,
        httpResponseHeader: res.rawHeaders,
        httpResponseCreateTime: microTimestamp(),
        httpResponseStatusCode: res.statusCode,

    })
}
1216514
def save_response_to_file(self, response, filename):
        
        try:
            last_response = self.get_last_response()
            with open(filename, 'w') as f:
                f.write(last_response.content)
        except OSError, e:
            return False
        return True
866191
function performCleanup(requester, filesToCache, notifyBack) {
        var currentRequester = requester || "";
        function filterFilesAndNotify(files, filesToCacheArr, notifyBackToBrackets) {
            files.forEach(function (file) {
                var fileExt = path.extname(path.basename(file));
                if (filesToCacheArr.indexOf(fileExt) < 0) {
                    var fileFullPath = updateDir + '/' + file;
                    try {
                        fs.removeSync(fileFullPath);
                    } catch (e) {
                        console.log("AutoUpdate : Exception occured in removing ", fileFullPath, e);
                    }
                }
            });
            if (notifyBackToBrackets) {
                postMessageToBrackets(MessageIds.NOTIFY_SAFE_TO_DOWNLOAD, currentRequester);
            }
        }

        fs.stat(updateDir)
            .then(function (stats) {
                if (stats) {
                    if (filesToCache) {
                        fs.readdir(updateDir)
                            .then(function (files) {
                                filterFilesAndNotify(files, filesToCache, notifyBack);
                            })
                            .catch(function (err) {
                                console.log("AutoUpdate : Error in Reading Update Dir for Cleanup : " + err.toString());
                                postMessageToBrackets(MessageIds.SHOW_ERROR_MESSAGE,
                                                      currentRequester, nodeErrorMessages.UPDATEDIR_READ_FAILED);
                            });
                    } else {
                        fs.remove(updateDir)
                            .then(function () {
                                console.log('AutoUpdate : Update Directory in AppData Cleaned: Complete');
                            })
                            .catch(function (err) {
                                console.log("AutoUpdate : Error in Cleaning Update Dir : " + err.toString());
                                postMessageToBrackets(MessageIds.SHOW_ERROR_MESSAGE,
                                                      currentRequester, nodeErrorMessages.UPDATEDIR_CLEAN_FAILED);
                            });
                    }
                }
            })
            .catch(function (err) {
                console.log("AutoUpdate : Error in Reading Update Dir stats for Cleanup : " + err.toString());
                postMessageToBrackets(MessageIds.SHOW_ERROR_MESSAGE,
                                      currentRequester, nodeErrorMessages.UPDATEDIR_CLEAN_FAILED);
            });
    }
1203618
function handlePost(req, res) {
  var length = parseInt(req.headers['content-length'], 10);
  if (length <= 0) {
    res.end();
    return;
  }

  var filename = req.headers['x-filename'] || 'save-trace.wtf-trace';
  var writable = fs.createWriteStream(filename, {flags: 'w'});

  req.on('data', function(chunk) {
    writable.write(chunk);
  });

  req.on('end', function() {
    console.log(filename);
    writable.end();
    res.end();
  });
}
239435
function(req, res, router) {
    res.send = function() {
      router.sendFn.apply(res, arguments);
    };
    res.sendImage = function() {
      router.sendImageFn.apply(res, arguments);
    };
    res.render = function(file, context){
      if (typeof router.engine === 'string') {
        var engine = require(router.engine)

        router.fs.readFile(router.view + '/' + file + '.' + router.engine, function (err, data) {
          var _html = engine.render(data.toString(), context)
          res.send(_html)
        })
      } else {
        var engine = require(router.engine.eng)

        router.fs.readFile(router.view + '/' + file + '.' + router.engine.ext, function (err, data) {
          var _html = engine.render(data.toString(), context)
          res.send(_html)
        })
      }
    };
  }
838732
function makeRequest(params) {
    params.retryStrategy = loggingRetryStrategy;
    return q
      .nfcall(request, params)
      .then(function (result) {
        var response = result[0];
        var body = result[1];

        if (response.statusCode !== 200) {
          throw new Error('HTTP error (' + response.statusCode + ')');
        }

        return body;
      })
      .fail(function (error) {
        throw new WrapperError([
          params.method,
          params.url,
          'failed.'
        ].join(' '), error);
      });
  }
1152295
function(req, res) {
        if (req.headers.accept == 'application/json') {
            res.header('Content-Type', 'application/json');
            res.status(200).json({
                data: {
                    ontologyTxt: req.rawOntology,
                    mimeType: req.mimeType
                },
                requestDelay: req.requestDelay,
                serverTime: new Date().getTime()
            });
        } else {
            res.header('Content-Type', req.mimeType);
            res.status(200).send(req.rawOntology);
        }
    }
1198280
function requestHandler(req, res, next) {
  const start = Date.now();
  let source;

  return Promise.try(() => {
    source = core.getPublicSource(req.params.src);
    return source.getHandler().getInfoAsync().then(info => [info, infoHeaders]);
  }).spread((data, dataHeaders) => {
    core.setResponseHeaders(res, source, dataHeaders);

    if (req.query && req.query.format) {
      const escapedText = JSON.stringify(data, null, ' ').replace(/&/g, '&amp;').replace(/</g, '&lt;');
      res.send(`<pre>${escapedText}</pre>`);
    } else {
      res.json(data);
    }

    const mx = util.format('req.%s.info', req.params.src);
    core.metrics.endTiming(mx, start);
  }).catch(err => core.reportRequestError(err, res)).catch(next);
}
177475
function deleteFile(req, res) {
		var rest = req.params["0"];
		var file = fileUtil.getFile(req, rest);
		fileUtil.withStatsAndETag(file.path, function(error, stats, etag) {
			var callback = function(error) {
				if (error) {
					return writeError(500, res, error);
				}
				sendStatus(204, res);
			};
			var ifMatchHeader = req.headers['if-match'];
			if (error && error.code === 'ENOENT') {
				return sendStatus(204, res);
			} else if (error) {
				writeError(500, res, error);
			} else if (ifMatchHeader && ifMatchHeader !== etag) {
				return sendStatus(412, res);
			} else if (stats.isDirectory()) {
				fileUtil.rumRuff(file.path, callback);
			} else {
				fs.unlink(file.path, callback);
			}
		});
	}
400675
function decompressResponse (res) {
  var encoding = lowercase(res.headers['content-encoding']);
  var isCompressed = ['gzip', 'compress', 'deflate'].indexOf(encoding) >= 0;

  if (isCompressed) {
    // The response is compressed, so add decompression middleware to the stream
    res.pipe(zlib.createUnzip());

    // Remove the content-encoding header, to prevent double-decoding
    delete res.headers['content-encoding'];
  }
}
693686
function writeHttpResponse(path, res) {
    var responseStr = fs.readFileSync(path).toString();
    var response = JSON.parse(responseStr);
    var encoding = 'utf8';
    var contentType = response.contentType;

    var actualResponse = {};

    if(response.headers) {
      _.assign(actualResponse, response.headers);
    }

    if (response.contentType) {
      actualResponse['Content-Type'] = response.contentType;
    }

    if ('location' in response) {
      actualResponse['Location'] = response.location;
    }

    res.writeHead(response.statusCode, actualResponse);

    var data = response.data;
    if( contentType == 'image/jpeg' || contentType == 'image/jpg' || contentType == 'image/png' || contentType == 'image/gif' ) {
      data = new Buffer(data, 'base64');
    }
    else if (typeof data !== 'string') {
      data = JSON.stringify(data);
    } else if (response.isBase64) {
      data = new Buffer(data, 'base64');
    }

    res.write(data);
    res.end();
  }
626672
function logResponse(data, isRejection) {
	        data = data || {};
	        // examine the data object
	        if (data instanceof Error) {
	          // log the Error object
	          _this.defaults.error('FAILED: ' + (data.message || 'Unknown Error'), data);
	          return DSUtils.Promise.reject(data);
	        } else if ((typeof data === 'undefined' ? 'undefined' : _typeof(data)) === 'object') {
	          var str = start.toUTCString() + ' - ' + config.method + ' ' + config.url + ' - ' + data.status + ' ' + (new Date().getTime() - start.getTime()) + 'ms';
	
	          if (data.status >= 200 && data.status < 300 && !isRejection) {
	            if (_this.defaults.log) {
	              _this.defaults.log(str, data);
	            }
	            return data;
	          } else {
	            if (_this.defaults.error) {
	              _this.defaults.error('FAILED: ' + str, data);
	            }
	            return DSUtils.Promise.reject(data);
	          }
	        } else {
	          // unknown type for 'data' that is not an Object or Error
	          _this.defaults.error('FAILED', data);
	          return DSUtils.Promise.reject(data);
	        }
	      }
469838
function(req, res, next) {
        var initialTime = req.query.time,
            receivedReqTime = new Date().getTime(),
            filename = req.params.filename,
            absolutePathToFile = ontoDir + '/' + filename,
            extension = path.extname(absolutePathToFile),
            contentType = mime.contentType(extension);

        if(contentType) {
            req.mimeType = contentType.replace(/;.*/g, '');
        } else {
            req.mimeType = contentType;
        }

        req.requestDelay =  receivedReqTime - initialTime;

        fs.readFile(absolutePathToFile, function(err, data) {
            if(err) {
                res.status(500).send(err.toString());
            } else {
                req.rawOntology = data.toString().replace(/(&)([a-z0-9]+)(;)/gi, '$2:');
                next();
            };
        });
    }
90564
function fileUploaded( error, response ) {
  this.debug( 'File Uploaded' );
  console.log( require( 'util' ).inspect( error || response, { showHidden: false, colors: true, depth: 4 } ) );
}
763619
function log_event(req, code, message, elapsed) {
  return {
    code:           code,
    message:        message,
    elapsed:        elapsed,
    request:        req,
    url:            req.originalUrl || req.url,
    method:         req.method,
    headers:        req.headers,
    httpVersion:    req.httpVersion,
    remoteAddress:  req.connection.remoteAddress
  };
}
793124
function logRequest(err, res) {
    if (res) {
      let ms = new Date() - res.requestStartTime;

      var time = ms < 1000 ? `${ms}ms` : `${(ms/1000).toFixed(2)}s`;

      logRoute(`${res.req.method} ${res.statusCode} (${time}): ${res.req.originalUrl}`);
    }
  }