Default implementation OK HTTP response on GET file request
@param {Object} req HTTP request
@param {Object} res HTTP response
@param {string} content File content
@param {string} fileExt File extension
551649
function httpOk(req, res, content, fileExt) {
    res.writeHead(200, {
        'Content-Type': Mine.getType(fileExt),
    });
    res.write(content, 'binary');
    res.end();
}
137510
def _handle_response(self, response, data):
        
        # Content-Type headers can include additional parameters(RFC 1521), so
        # we split on ; to match against only the type/subtype
        if data and response.get('content-type', '').split(';')[0] in (
            'application/json', 
            'application/x-javascript',
            'text/javascript',
            'text/x-javascript',
            'text/x-json'
        ):
            return json.loads(data)
        else:
            return data
138849
function () {
                // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
                var status = _xhr.status === 1223 ? 204 : _xhr.status;
                var body = null;
                // HTTP 204 means no content
                if (status !== 204) {
                    // responseText is the old-school way of retrieving response (supported by IE8 & 9)
                    // response/responseType properties were introduced in ResourceLoader Level2 spec
                    // (supported by IE10)
                    body = (typeof _xhr.response === 'undefined') ? _xhr.responseText : _xhr.response;
                    // Implicitly strip a potential XSSI prefix.
                    if (typeof body === 'string') {
                        body = body.replace(XSSI_PREFIX, '');
                    }
                }
                // fix status code when it is 0 (0 status is undocumented).
                // Occurs when accessing file resources or on Android 4.1 stock browser
                // while retrieving files from application cache.
                if (status === 0) {
                    status = body ? 200 : 0;
                }
                var headers = Headers.fromResponseHeaderString(_xhr.getAllResponseHeaders());
                // IE 9 does not provide the way to get URL of response
                var url = getResponseURL(_xhr) || req.url;
                var statusText = _xhr.statusText || 'OK';
                var responseOptions = new ResponseOptions({ body: body, status: status, headers: headers, statusText: statusText, url: url });
                if (baseResponseOptions != null) {
                    responseOptions = baseResponseOptions.merge(responseOptions);
                }
                var response = new Response(responseOptions);
                response.ok = isSuccess(status);
                if (response.ok) {
                    responseObserver.next(response);
                    // TODO(gdi2290): defer complete if array buffer until done
                    responseObserver.complete();
                    return;
                }
                responseObserver.error(response);
            }
388177
function respondWithFile(req, res, path, ifNoFile) {
  ifNoFile = ifNoFile || function() {};
  // We use `documentRoot` as the root wherein we seek files.
  var realpath = protectedPath(req.server.documentRoot, path);
  fs.stat(realpath, function(err, stats) {
    if (err) return ifNoFile();

    if (stats.isDirectory()) {
      realpath = p.join(realpath, 'index.html');
    }
    res.mime(p.extname(realpath).slice(1));

    // Cache management (compare timestamps at second-level precision).
    var lastModified = Math.floor(stats.mtime / 1000);
    var since = req.headers['if-modified-since'];
    if (since && (lastModified <= Math.floor(new Date(since) / 1000))) {
      res.statusCode = 304; // not modified.
      res.end();
      return;
    }
    res.setHeader('Last-Modified', stats.mtime.toUTCString());

    // Connect the output of the file to the network!
    var raw = fs.createReadStream(realpath);
    raw.on('error', function(err) {
      log(err.stack, 'error');
      res.statusCode = 404;
      res.end('Not Found\n');
    });
    raw.pipe(res.compressed());
  });
}
7963
@Override
    public void service(HttpServletRequest req, HttpServletResponse res) 
        throws ServletException, IOException
    {
    	String sourceFileName = req.getParameter("source");
    	String styleSheetFileName = req.getParameter("stylesheet");
    	FileReader sourceFileReader = new FileReader(sourceFileName);
    	FileReader stylesheetFileReader = new FileReader(styleSheetFileName);
    	
    	ServletOutputStream outStream = res.getOutputStream();
    	
        try {
            StreamSource source = new StreamSource(sourceFileReader);

            Result result = new StreamResult(outStream);

            TransformerFactory tFact = TransformerFactory.newInstance();
            StreamSource streamTransformer = new StreamSource(stylesheetFileReader);
            
            Transformer transformer = tFact.newTransformer(streamTransformer);

            transformer.transform(source, result);
        } catch (TransformerConfigurationException ex)    {
            ex.printStackTrace();
        } catch (TransformerException ex) {
            ex.printStackTrace();
        }                    
    	
    	super.service(req, res);
    }
581890
function(res) {
    res.setEncoding('utf8');
    var data = "";
    res.on('data', function(chunk) {
      data+=chunk;
    });

    res.on('end', function() {
      // Get HTTP Statuscode and act according to situation
      var code = res.statusCode;
      try { // try to parse JSON
        var answer = JSON.parse(data);
      } catch (e) {
        var err = {};
        err.http_code = 500;
        err.message = "No valid JSON received: "+data;
        callback(err, null);
        return;
      }
      if(code >= 200 && code <= 206) { // request was successful
        callback(null, answer);
      } else if (code >= 300 && code <= 307) { // server send redirect
        // we do not follow anything the server wants us to follow right now, since this should never be the case.
        // instead let's raise an error.
        var err = new Object();
        err.http_code = 500;
        err.message = "Redirects not supported by pastyclient-node"
        callback(err, null);
      } else if (code >= 400 && code <= 418) { // client error
        if(typeof(answer.error) == "object") {
          var err = answer.error;
        } else if(answer.code != undefined && answer.message != undefined) { // New RestError, temporary support both 
          var err = answer;
          err.http_code = code;
        } else {
          var err = new Object();
          err.http_code = code;
          err.message = "Resource not found";
        }
        callback(err, null);
      } else if (code >= 500 && code <= 505) { // server error
        if(typeof(answer.error) == "object") {
          var err = answer.error;
        } else {
          var err = new Object();
          err.http_code = code;
          err.message = "Internal Server Error";
        }
        callback(err, null);
      } else {
        // Not existant HTTP code. Raise error.
        var err = new Object();
        err.http_code = 500;
        err.message = "HTTP Status Code "+code+" is not supported by pastyclient-node"
        callback(err, null);
      }
    });
  }
1123042
function makeRequest () {
    request = self.request.apply(null, args);
    requestMiddleware.use(request);
    request.on("response", function (response) {
      var contentEncoding, gzipper;

      //Only cache successful responses
      if (response.statusCode >= 200 && response.statusCode < 300) {
        response.on('error', function (error) {
          self.handleError(error);
        });
        fs.writeFile(self.cacheDirectory + key + ".json", JSON.stringify(response.headers), function (error) {
          if (error) self.handleError(error);
        });

        responseWriter = fs.createWriteStream(self.cacheDirectory + key);

        responseWriter.on('error', function (error) {
          self.handleError(error);
        });

        contentEncoding = response.headers['content-encoding'] || '';
        contentEncoding = contentEncoding.trim().toLowerCase();

        if (contentEncoding === 'gzip') {
          response.on('error', function (error) {
            responseWriter.end();
          });
          response.pipe(responseWriter);
        } else {
          gzipper = zlib.createGzip();
          response.on('error', function (error) {
            gzipper.end();
          });
          gzipper.on('error', function (error) {
            self.handleError(error);
            responseWriter.end();
          });
          responseWriter.on('error', function (error) {
            response.unpipe(gzipper);
            gzipper.end();
          });
          response.pipe(gzipper).pipe(responseWriter);
        }
      }
    });
    self.emit("request", args[0]);
  }
161230
function(data) {
    var h, headerArray, headers, i, l, len, o;
    headers = {};
    headerArray = data.getAllResponseHeaders().split('\r');
    for (l = 0, len = headerArray.length; l < len; l++) {
      i = headerArray[l];
      h = i.match(/^([^:]*?):(.*)$/);
      if (!h) {
        h = [];
      }
      h.shift();
      if (h[0] !== void 0 && h[1] !== void 0) {
        headers[h[0].trim()] = h[1].trim();
      }
    }
    o = {};
    o.content = {};
    o.content.data = data.responseText;
    o.headers = headers;
    o.request = {};
    o.request.url = this.invocationUrl;
    o.status = data.status;
    return o;
  }
1374568
function(method, url, headers, data, callback) {

		var r = new XMLHttpRequest();
		var error = this.error;

		// Binary?
		var binary = false;
		if (method === 'blob') {
			binary = method;
			method = 'GET';
		}

		method = method.toUpperCase();

		// Xhr.responseType 'json' is not supported in any of the vendors yet.
		r.onload = function(e) {
			var json = r.response;
			try {
				json = JSON.parse(r.responseText);
			}
			catch (_e) {
				if (r.status === 401) {
					json = error('access_denied', r.statusText);
				}
			}

			var headers = headersToJSON(r.getAllResponseHeaders());
			headers.statusCode = r.status;

			callback(json || (method === 'GET' ? error('empty_response', 'Could not get resource') : {}), headers);
		};

		r.onerror = function(e) {
			var json = r.responseText;
			try {
				json = JSON.parse(r.responseText);
			}
			catch (_e) {}

			callback(json || error('access_denied', 'Could not get resource'));
		};

		var x;

		// Should we add the query to the URL?
		if (method === 'GET' || method === 'DELETE') {
			data = null;
		}
		else if (data && typeof (data) !== 'string' && !(data instanceof FormData) && !(data instanceof File) && !(data instanceof Blob)) {
			// Loop through and add formData
			var f = new FormData();
			for (x in data) if (data.hasOwnProperty(x)) {
				if (data[x] instanceof HTMLInputElement) {
					if ('files' in data[x] && data[x].files.length > 0) {
						f.append(x, data[x].files[0]);
					}
				}
				else if (data[x] instanceof Blob) {
					f.append(x, data[x], data.name);
				}
				else {
					f.append(x, data[x]);
				}
			}

			data = f;
		}

		// Open the path, async
		r.open(method, url, true);

		if (binary) {
			if ('responseType' in r) {
				r.responseType = binary;
			}
			else {
				r.overrideMimeType('text/plain; charset=x-user-defined');
			}
		}

		// Set any bespoke headers
		if (headers) {
			for (x in headers) {
				r.setRequestHeader(x, headers[x]);
			}
		}

		r.send(data);

		return r;

		// Headers are returned as a string
		function headersToJSON(s) {
			var r = {};
			var reg = /([a-z\-]+):\s?(.*);?/gi;
			var m;
			while ((m = reg.exec(s))) {
				r[m[1]] = m[2];
			}

			return r;
		}
	}
1032855
function sendFile (req, res, next, file) {
  if (file instanceof Buffer) {
    setContentType(req, res, ["application/octet-stream", "*/*"]);

    // `file` is the file's contents
    util.debug("Sending raw buffer data");
    res.send(file);
    return;
  }

  if (typeof file === "string" || file instanceof String) {
    setContentType(req, res, ["application/octet-stream", "*/*"]);

    // `file` is the file's contents as as string
    util.debug("Sending raw string data");
    res.send(file);
    return;
  }

  // `file` is a file info object
  fs.exists(file.path || "", (exists) => {
    if (exists) {
      let isAttachment = _.some(res.swagger.headers, (header, name) => {
        return name.toLowerCase() === "content-disposition";
      });

      if (isAttachment) {
        // Get the filename from the "Content-Disposition" header,
        // or fallback to the request path
        let fileName = /filename\=\"(.+)\"/.exec(res.get("content-disposition"));
        fileName = fileName ? fileName[1] : req.path;

        util.debug('Sending "%s" as an attachment named "%s"', file.path, fileName);
        res.download(file.path, fileName);
      }
      else {
        util.debug('Sending "%s" contents', file.path);
        res.sendFile(file.path, { lastModified: false });
      }
    }
    else {
      // Throw an HTTP 410 (Gone)
      util.debug('Unable to find the file: "%s".  Sending an HTTP 410 (Gone)', file.path);
      next(ono({ status: 410 }, "%s no longer exists", file.path || req.path));
    }
  });
}
1197672
async function handleGenericFile(req, res, fileExtension) {
    const nodeFilePath = `.${req.url}`;

    // check if the file is in the cache
    if (compiledFiles[nodeFilePath]) {
        res.end(compiledFiles[nodeFilePath]);
        return;
    }

    // the file is not in the cache
    // watch the file if necessary
    // compile the file and return the compiled source
    if (await fs.exists(nodeFilePath)) {
        watchFile(nodeFilePath, watchFiles);
        const source = await fs.readFile(nodeFilePath);
        compiledFiles[nodeFilePath] = source;
        res.end(source);
        return;
    }

    //TODO this code is repeated multiple times
    // if SPA is enabled, return the contents to index.html
    // if SPA is not enabled, return a 404 error
    if (!disableSpa) {
        const indexFileContents = (await fs.readFile(`./index.html`)).toString();
        const modifiedIndexFileContents = modifyHTML(indexFileContents, 'index.html', watchFiles, webSocketPort);
        const directoryPath = req.url.slice(0, req.url.lastIndexOf('/')) || '/';
        res.end(modifyHTML(modifiedIndexFileContents, directoryPath, watchFiles, webSocketPort));
        return;
    }
    else {
        res.statusCode = 404;
        res.end();
        return;
    }
}
806486
@Override
	protected boolean copyRequestedContentToResponse(String requestedPath, HttpServletResponse response,
			String contentType) throws IOException {

		boolean copyDone = false;
		if (isValidRequestedPath(requestedPath)) {

			try {
				writeContent(requestedPath, null, response);
				response.setContentType(contentType);
				copyDone = true;
			} catch (ResourceNotFoundException e) {
				// Nothing to do here
			}
		}

		return copyDone;
	}
11736
public void service(HttpServletRequest req, HttpServletResponse res) 
        throws ServletException, IOException
    {
        String regex = this.getProperty(REGEX);
        String server = req.getServerName();
        if (regex != null)
        	if (server != null)
        {
        	String match = null;
        	if (regex.indexOf('/') != -1)
        	{
        	    match = regex.substring(regex.indexOf('/'));
        	    regex = regex.substring(0, regex.indexOf('/'));
        	}
        	if (server.matches(regex))
	        {
        		String target = this.getProperty(REGEX_TARGET);
        		if (target != null)
        		{
        	        if (logger != null)
        	        	logger.info("Redirect " + server + " to " + target);
                    String requestPath = req.getServletPath();
        	        if ((match == null) || (requestPath.matches(match)))
        	        	res.sendRedirect(target);
        	        else
        	        {
        	            boolean fileFound = sendResourceFile(req, res);
        	            if (!fileFound)
        	                res.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
        	        }
                    return;
        		}
	        }
        }
    	super.service(req, res);
    }
605475
function processFileResponse(req, res, next) {
  var fileDetails = req.appformsResultPayload.data;
  if (fileDetails.stream) {
    var headers = {};
    headers["Content-Type"] = fileDetails.type;//Setting the file content type. Mime types are set by the file handler.
    headers["Content-Disposition"] = "attachment; filename=" + fileDetails.name;
    res.writeHead(200, headers);
    fileDetails.stream.pipe(res);
    fileDetails.stream.resume(); //Unpausing the stream as it was paused by the file handler
  } else {
    return next('Error getting submitted file - result: ' + JSON.stringify(fileDetails));
  }
}
465187
function (req, res) {
		LOG.warn('handle_request');

		// attach custom res methods (borrowed from express)
		res = UTIL.mixin(res, response);

		LOG.sys('HTTP req received, header', 'SR.REST');
		LOG.sys(req.headers, 'SR.REST');
		
		var content_type = req.headers['content-type'];

		// NOTE: multi-part needs to be handled first, because req.on('data') will not be able to process correctly
		if (typeof content_type === 'string' && content_type.startsWith('multipart/form-data; boundary=')) { 
			LOG.warn('parsing form request...', 'SR.REST');
			route(req, res);
			return;
		}
		
		// temp buffer for incoming request
		var data = '';
		var JSONobj = undefined;
		
		req.on('data', function (chunk) {
			data += chunk;
		});

		req.on('end', function () {
			
			var JSONobj = undefined;
			
			try {
				if (data !== '') {
						
					if (content_type.startsWith('application/x-www-form-urlencoded')) {
						JSONobj = qs.parse(data);
					} else if (content_type.startsWith('application/json')) {
						JSONobj = UTIL.convertJSON(decodeURIComponent(data));
					} else if (content_type.startsWith('application/sdp')) {
						JSONobj = data;
					} else {
						var msg = 'content type not known: ' + content_type;
						LOG.warn(msg, 'SR.REST');
						SR.REST.reply(res, msg);
						//res.writeHead(200, {'Content-Type': 'text/plain'});
						//res.end(msg);
						return;
					}
				}
			} catch (e) {
				var msg = 'JSON parsing error for data: ' + data + '\n content_type: ' + content_type;
				LOG.error(msg, 'SR.REST');
				//res.writeHead(200, {'Content-Type': 'text/plain'});
				//res.end(msg);
				SR.REST.reply(res, msg);
				return;
			}

			route(req, res, JSONobj);
		})
	}
54583
function postExec (req, res) {
  let cmd = req.body.cmd;
  let connection = res.locals.connection;
  let parts = myutil.split(cmd);
  parts[0] = parts[0].toLowerCase();
  let commandName = parts[0].toLowerCase();

  // must be in our white list to be allowed in read only mode
  if (req.app.locals.redisReadOnly) {
    if (!isReadOnlyCommand(commandName, connection)) {
      return res.send('ERROR: Command not read-only');
    }
  }

  let args = parts.slice(1);
  args.push(function (err, results) {
      if (err) {
          return res.send(err.message);
      }
      return res.send(JSON.stringify(results));
  });
  // check if command is valid is done by ioredis if called with
  // 'connection.call(command, ...)' and our callback called to handle it
  // but throws Error if called via 'connection[commandName].apply(connection, ...)'
  connection.call(commandName, ...args);
}
529851
function reqrtn(req, res) {
    if (req && req._headers) {
        throw new Error('Received response object where request object was expected');
    }
    this.req = req;
    this.res = res;
    this.data = {
    //localHostIpArray:['localhost','127.0.0.1','::1']
    };
    this.isClientInputLoaded = false;
}