Begin sending the contents of this L{File} (or a subset of the
        contents, based on the 'range' header) to the given request.
348494
def render_GET(self, request):
        
        request.setHeader(b'accept-ranges', b'bytes')

        producer = self.makeProducer(request, self.fileObject)

        if request.method == b'HEAD':
            return b''

        def done(ign):
            producer.stopProducing()

        request.notifyFinish().addCallbacks(done, done)
        producer.start()
        # and make sure the connection doesn't get closed
        return server.NOT_DONE_YET
33584
public function send()
    {
        deprecationWarning('Response::send() will be removed in 4.0.0');

        if ($this->hasHeader('Location') && $this->_status === 200) {
            $this->statusCode(302);
        }

        $this->_setContent();
        $this->sendHeaders();

        if ($this->_file) {
            $this->_sendFile($this->_file, $this->_fileRange);
            $this->_file = null;
            $this->_fileRange = [];
        } else {
            $this->_sendContent($this->body());
        }

        if (function_exists('fastcgi_finish_request')) {
            fastcgi_finish_request();
        }
    }
1238449
public static void send(MailAccount mailAccount, Collection<String> tos, String subject, String content, boolean isHtml, File... files) {
		Mail.create(mailAccount)//
				.setTos(tos.toArray(new String[tos.size()]))//
				.setTitle(subject)//
				.setContent(content)//
				.setHtml(isHtml)//
				.setFiles(files)//
				.send();
	}
1168616
@Override
    public void prepare ( CommonServerMessageBlockRequest next ) {
        if ( isReceived() && ( next instanceof RequestWithFileId ) ) {
            ( (RequestWithFileId) next ).setFileId(this.fileId);
        }
        super.prepare(next);
    }
1219017
private void adjustRequest(GetObjectRequest req) {
        long[] range = req.getRange();
        long lastByte = range[1];
        long totalBytesToDownload = lastByte - this.origStartingByte + 1;

        if (dstfile.exists()) {
            if (!FileLocks.lock(dstfile)) {
                throw new FileLockException("Fail to lock " + dstfile
                                            + " for range adjustment");
            }
            try {
                expectedFileLength = dstfile.length();
                long startingByte = this.origStartingByte + expectedFileLength;
                LOG.info("Adjusting request range from " + Arrays.toString(range)
                         + " to "
                         + Arrays.toString(new long[] {startingByte, lastByte})
                         + " for file " + dstfile);
                req.setRange(startingByte, lastByte);
                totalBytesToDownload = lastByte - startingByte + 1;
            } finally {
                FileLocks.unlock(dstfile);
            }
        }

        if (totalBytesToDownload < 0) {
            throw new IllegalArgumentException(
                "Unable to determine the range for download operation. lastByte="
                + lastByte + ", origStartingByte=" + origStartingByte
                + ", expectedFileLength=" + expectedFileLength
                + ", totalBytesToDownload=" + totalBytesToDownload);
        }
    }
643803
def send_file(from, message, file)
      if from.length > 20
        raise UsernameTooLong, "Username #{from} is `#{from.length} characters long. Limit is 20'"
      end

      response = self.class.post(@api.send_file_config[:url],
        :query => { :auth_token => @token },
        :body  => file_body(
          {
            :room_id        => room_id,
            :from           => from,
            :message        => message,
          }.send(@api.send_config[:body_format]), file
        ),
        :headers => file_body_headers(@api.headers)
      )

      ErrorHandler.response_code_to_exception_for :room, room_id, response
      true
    end
932340
def send_header(self, keyword, value):
        """"""
        if self.request_version != 'HTTP/0.9':
            self.wfile.write("%s: %s\r\n" % (keyword, value))

        if keyword.lower() == 'connection':
            if value.lower() == 'close':
                self.close_connection = 1
            elif value.lower() == 'keep-alive':
                self.close_connection = 0
1129687
def write(url, content, **args):
    """"""
    relay = urlparse.urlparse(args.pop('relay', 'lmtp://localhot'))
    try:
        smtplib_SMTPS = functools.partial(smtplib.SMTP_SSL,
                                          keyfile=args.pop('keyfile', None),
                                          certfile=args.pop('certfile', None))
    except AttributeError:
        def smtplib_SMTPS():
            raise ValueError(relay.geturl())
    filename = args.pop('filename', '')
    content_type, encoding = mimetypes.guess_type(filename)
    content_type = args.pop('content_type', content_type)
    encoding = args.pop('content_encoding', encoding)
    maintype, subtype = content_type.split('/')
    content = content_types.get(content_types).format(content, **args)
    content = content_encodings.get(encoding).encode(content)
    message = {
        'application': application.MIMEApplication,
        'text': text.MIMEText}[maintype](content, subtype)
    if filename:
        message.set_param('filename', ('UTF-8', '', filename.decode('UTF-8')))
    if encoding:
        message['Content-Encoding'] = encoding
    message['To'] = urllib.unquote(url.path)
    for name, value in urlparse.parse_qsl(url.query):
        message[name.replace('_', '-')] = value
    if message['From'] is None:
        username = os.environ.get('USERNAME')
        username = os.environ.get('LOGNAME', username)
        username = os.environ.get('USER', username)
        message['From'] = '{}@{}'.format(username, socket.getfqdn())

    # ``mailto`` scheme allow for a body param. We don't.
    del message['body']

    # Send the email.
    client = {'smtp': smtplib.SMTP,
              'lmtp': smtplib.LMTP,
              'smtps': smtplib_SMTPS}[relay.scheme]()
    client.connect(''.join([relay.hostname, relay.path]), relay.port)
    if relay.username and relay.password:
        client.login(relay.username, relay.password)
    client.sendmail(message['From'], [message['To']], message.as_string())
    client.quit()
1265038
protected void sendData(HttpServletRequest request, HttpServletResponse response, String pathInContext, Resource resource) throws IOException
    {
        long resLength = resource.length();

        boolean include = request.getAttribute(Dispatcher.__INCLUDE_REQUEST_URI) != null;

        // Get the output stream (or writer)
        OutputStream out = null;
        try
        {
            out = response.getOutputStream();
        }
        catch (IllegalStateException e)
        {
            out = new WriterOutputStream(response.getWriter());
        }

        // see if there are any range headers
        Enumeration reqRanges = include ? null : request.getHeaders(HttpFields.__Range);

        if (reqRanges == null || !reqRanges.hasMoreElements())
        {
            // if there were no ranges, send entire entity
            Resource data = resource;
            if (!include)
            {
                // look for a gziped content.
                if (_minGzipLength > 0)
                {
                    String accept = request.getHeader(HttpFields.__AcceptEncoding);
                    if (accept != null && resLength > _minGzipLength && !pathInContext.endsWith(".gz"))
                    {
                        Resource gz = getResource(pathInContext + ".gz");
                        if (gz.exists() && accept.indexOf("gzip") >= 0 && request.getAttribute(Dispatcher.__INCLUDE_REQUEST_URI) == null)
                        {
                            response.setHeader(HttpFields.__ContentEncoding, "gzip");
                            data = gz;
                            resLength = data.length();
                        }
                    }
                }
                writeHeaders(response, resource, resLength);
            }

            data.writeTo(out, 0, resLength);
            return;
        }

        // Parse the satisfiable ranges
        List ranges = InclusiveByteRange.satisfiableRanges(reqRanges, resLength);

        // if there are no satisfiable ranges, send 416 response
        if (ranges == null || ranges.size() == 0)
        {
            writeHeaders(response, resource, resLength);
            response.setStatus(HttpResponse.__416_Requested_Range_Not_Satisfiable);
            response.setHeader(HttpFields.__ContentRange, InclusiveByteRange.to416HeaderRangeString(resLength));
            resource.writeTo(out, 0, resLength);
            return;
        }

        // if there is only a single valid range (must be satisfiable
        // since were here now), send that range with a 216 response
        if (ranges.size() == 1)
        {
            InclusiveByteRange singleSatisfiableRange = (InclusiveByteRange) ranges.get(0);
            long singleLength = singleSatisfiableRange.getSize(resLength);
            writeHeaders(response, resource, singleLength);
            response.setStatus(HttpResponse.__206_Partial_Content);
            response.setHeader(HttpFields.__ContentRange, singleSatisfiableRange.toHeaderRangeString(resLength));
            resource.writeTo(out, singleSatisfiableRange.getFirst(resLength), singleLength);
            return;
        }

        // multiple non-overlapping valid ranges cause a multipart
        // 216 response which does not require an overall
        // content-length header
        //
        writeHeaders(response, resource, -1);
        ResourceCache.ResourceMetaData metaData = _httpContext.getResourceMetaData(resource);
        String encoding = metaData.getMimeType();
        MultiPartResponse multi = new MultiPartResponse(response.getOutputStream());
        response.setStatus(HttpResponse.__206_Partial_Content);

        // If the request has a "Request-Range" header then we need to
        // send an old style multipart/x-byteranges Content-Type. This
        // keeps Netscape and acrobat happy. This is what Apache does.
        String ctp;
        if (request.getHeader(HttpFields.__RequestRange) != null)
            ctp = "multipart/x-byteranges; boundary=";
        else
            ctp = "multipart/byteranges; boundary=";
        response.setContentType(ctp + multi.getBoundary());

        InputStream in = (resource instanceof CachedResource) ? null : resource.getInputStream();
        long pos = 0;

        for (int i = 0; i < ranges.size(); i++)
        {
            InclusiveByteRange ibr = (InclusiveByteRange) ranges.get(i);
            String header = HttpFields.__ContentRange + ": " + ibr.toHeaderRangeString(resLength);
            multi.startPart(encoding, new String[]
            { header});

            long start = ibr.getFirst(resLength);
            long size = ibr.getSize(resLength);
            if (in != null)
            {
                // Handle non cached resource
                if (start < pos)
                {
                    in.close();
                    in = resource.getInputStream();
                    pos = 0;
                }
                if (pos < start)
                {
                    in.skip(start - pos);
                    pos = start;
                }
                IO.copy(in, out, size);
                pos += size;
            }
            else
                // Handle cached resource
                (resource).writeTo(out, start, size);

        }
        if (in != null)
            in.close();
        multi.close();

        return;
    }
1102625
function onRequest (request, sender, sendResponse) {
  // Show the page action for the tab that the sender (content script) was on.
  chrome.pageAction.show(sender.tab.id)

  var files = request.files

  if (request.action === 'load') {
    var rules = []
    for (var file in files) {
      var regex
      var isKnownFile =
      prevFiles[sender.tab.id] && prevFiles[sender.tab.id][file]
      if (isKnownFile) {
        if (prevFiles[sender.tab.id][file] === files[file]) {
          // We can skip this rule if the timestamp hasn't change.
          continue
        }
        regex = '^([^\\?]*)\\?' + prevFiles[sender.tab.id][file] + '$'
      } else {
        regex = '^([^\\?]*)$'
      }
      var actions = [
        new chrome.declarativeWebRequest.RedirectByRegEx({
          from: regex,
          to: '$1?' + files[file]
        })
      ]
      if (!isKnownFile) { // is new file
        actions.push(
          new chrome.declarativeWebRequest.RemoveResponseHeader(
            {name: 'Cache-Control'}))
        actions.push(
          new chrome.declarativeWebRequest.AddResponseHeader(
            {name: 'Cache-Control', value: 'no-cache'}))
      }
      rules.push({
        conditions: [
          new chrome.declarativeWebRequest.RequestMatcher({
            url: { pathSuffix: file }
          })
        ],
        actions: actions
      })
    }
    prevFiles[sender.tab.id] = files
    chrome.declarativeWebRequest.onRequest.addRules(rules, function (callback) {
      // We reply back only when new rules are set.
      sendResponse({})
    })
  }
// Return nothing to let the connection be cleaned up.
}
139882
private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content)
            throws IOException {
        // Validate the requested file ------------------------------------------------------------

        // Get requested file by path info.
        String requestedFile = request.getPathInfo();
        if (logger.isDebugEnabled()) {
            logger.debug("Requested path:" + requestedFile);
        }

        // Check if file is actually supplied to the request URL.
        if (requestedFile == null) {
            logger.debug("No file requested, return 404.");
            // Do your thing if the file is not supplied to the request URL.
            // Throw an exception, or send 404, or show default/warning page, or just ignore it.
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        Configuration rootConfiguration = (Configuration) request.getServletContext().getAttribute(Configuration.class.getName());
        Configuration runtimeConfiguration = rootConfiguration.subset("runtime-settings");

        String basePath = runtimeConfiguration.getString("cache-path");
        int bufferSize = runtimeConfiguration.getInteger("cache-buffer-size", DEFAULT_BUFFER_SIZE);
        long expireTime = runtimeConfiguration.getLong("cache-expire-time", DEFAULT_EXPIRE_TIME);

        // URL-decode the file name (might contain spaces and on) and prepare file object.
        String fDecodedPath = URLDecoder.decode(requestedFile, "UTF-8");
        File file = new File(basePath, fDecodedPath);

        // Check if file actually exists in filesystem.
        if (!file.exists()) {
            logger.debug("Requested file not found, return 404.");
            // Do your thing if the file appears to be non-existing.
            // Throw an exception, or send 404, or show default/warning page, or just ignore it.
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // Prepare some variables. The ETag is an unique identifier of the file.
        String fileName = file.getName();
        long length = file.length();
        long lastModified = file.lastModified();
        String eTag = fileName + "_" + length + "_" + lastModified;
        long expires = System.currentTimeMillis() + expireTime;

        // Validate request headers for caching ---------------------------------------------------
        // If-None-Match header should contain "*" or ETag. If so, then return 304.
        String ifNoneMatch = request.getHeader("If-None-Match");
        if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
            logger.debug("IfNoneMatch/Etag not matching, return 304.");
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            response.setHeader("ETag", eTag); // Required in 304.
            response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
            return;
        }

        // If-Modified-Since header should be greater than LastModified. If so, then return 304.
        // This header is ignored if any If-None-Match header is specified.
        long ifModifiedSince = request.getDateHeader("If-Modified-Since");
        if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
            logger.debug("IfModifiedSince not matching, return 304.");
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            response.setHeader("ETag", eTag); // Required in 304.
            response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
            return;
        }

        // Validate request headers for resume ----------------------------------------------------
        // If-Match header should contain "*" or ETag. If not, then return 412.
        String ifMatch = request.getHeader("If-Match");
        if (ifMatch != null && !matches(ifMatch, eTag)) {
            logger.debug("ifMatch not matching, return 412.");
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }

        // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
        long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
        if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
            logger.debug("ifUnmodifiedSince not matching, return 412.");
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }

        // Prepare and initialize response --------------------------------------------------------
        // Get content type by file name and content disposition.
        String contentType = getServletContext().getMimeType(fileName);
        String disposition = "inline";

        // If content type is unknown, then set the default value.
        // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
        // To add new content types, add new mime-mapping entry in web.xml.
        if (contentType == null) {
            contentType = "application/octet-stream";
        }

        // If content type is text, expand content type with the one and right character encoding.
        if (contentType.startsWith("text")) {
            contentType += ";charset=UTF-8";
        } // Else, expect for images, determine content disposition. If content type is supported by
        // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
        else if (!contentType.startsWith("image")) {
            String accept = request.getHeader("Accept");
            disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
        }

        // Initialize response.
        response.reset();
        response.setBufferSize(bufferSize);
        response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("ETag", eTag);
        response.setDateHeader("Last-Modified", lastModified);
        response.setDateHeader("Expires", expires);

        // Send requested file (part(s)) to client ------------------------------------------------
        // Prepare streams.
        FileInputStream input = null;
        OutputStream output = null;

        if (content) {
            logger.debug("Content requested,streaming.");
            // Open streams.
            input = new FileInputStream(file);
            output = response.getOutputStream();
            long streamed = stream(input, output, bufferSize);
            if (logger.isDebugEnabled()) {
                logger.debug("Bytes streamed:" + streamed);
            }
        }

    }
311160
def send(self):
        """"""
        self._file.write(self.as_bytes())
        self._file.write(b'\r\n')
164337
def send_head(self):
        
        path = self.translate_path(self.path)
        f = None
        to_render = False
        if os.path.isdir(path):
            if not self.path.endswith('/'):
                # redirect browser - doing basically what apache does
                self.send_response(301)
                self.send_header("Location", self.path + "/")
                self.end_headers()
                return None
        else:
            # check if URL corresponds to a template to render
            if path.endswith("/"):
                index = path[:-1]
            else:
                index = path
            for ext in '.html', '.htm':
                if os.path.exists(index + ext):
                    to_render = True
                    realpath = index + ext
                    break
        if os.path.isdir(path):
            # if dir, check for existence of index.htm*
            for index in "index.html", "index.htm":
                index = os.path.join(path, index)
                if os.path.exists(index):
                    realpath = index
                    to_render = True
                    break
            else:
                return self.list_directory(path)
        # deny if URL directly requests for *.html file, allow if dir
        file_extension = os.path.splitext(path)[1]
        if file_extension in ('.html', '.htm') and not os.path.isdir(path):
            self.send_error(404, "File not found")
            return None
        if to_render:
            path = realpath
        ctype = self.guess_type(path)
        try:
            f = open(path, 'rb')
        except IOError:
            self.send_error(404, "File not found")
            return None
        fs = os.fstat(f.fileno())
        if to_render:
            stream, length = self.gen_response_stream(f)
        else:
            length = fs[6]
        self.send_response(200)
        self.send_header("Content-type", ctype)
        self.send_header("Content-Length", str(length))
        self.send_header("Last-Modified", self.date_time_string(
            fs.st_mtime))
        self.end_headers()
        if to_render:
            return stream
        return f
688568
function sendFile(params) {
    const p = params;
    
    checkParams(params);
    
    fs.lstat(p.name, (error, stat) => {
        if (error)
            return sendError(error, params);
        
        const isGzip = isGZIP(p.request) && p.gzip;
        const time = stat.mtime.toUTCString();
        const length = stat.size;
        const range = getRange(p.request, length);
        
        if (range)
            assign(p, {
                range,
                status: RANGE
            });
        
        assign(p, {
            time
        });
        
        if (!isGzip)
            p.length = length;
        
        setHeader(params);
        
        const options = {
            gzip    : isGzip,
            range,
        };
        
        files.pipe(p.name, p.response, options).catch((error) => {
            sendError(error, params);
        });
    });
}
672848
public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException {
    NameNode.getNameNodeMetrics().numFileDataServletDoGet.inc();
    final UnixUserGroupInformation ugi = getUGI(request);
    final ClientProtocol nnproxy = createNameNodeProxy(ugi);

    try {
      final String path = request.getPathInfo() != null
        ? request.getPathInfo() : "/";
      FileStatus info = nnproxy.getFileInfo(path);
      if ((info != null) && !info.isDir()) {
        response.sendRedirect(createUri(info, ugi, nnproxy,
              request).toURL().toString());
      } else if (info == null){
        response.sendError(400, "cat: File not found " + path);
      } else {
        response.sendError(400, "cat: " + path + ": is a directory");
      }
    } catch (URISyntaxException e) {
      response.getWriter().println(e.toString());
    } catch (IOException e) {
      response.sendError(400, e.getMessage());
    }
  }
1141781
public static void sendText(Collection<String> tos, String subject, String content, File... files) {
		send(tos, subject, content, false, files);
	}
819224
def add_range(self, start, part_len, total_len):
        
        content_range = 'bytes {0}-{1}/{2}'.format(start,
                                                   start + part_len - 1,
                                                   total_len)

        self.statusline = '206 Partial Content'
        self.replace_header('Content-Range', content_range)
        self.replace_header('Content-Length', str(part_len))
        self.replace_header('Accept-Ranges', 'bytes')
        return self