Set headers for content length, and, if available, md5.
@throws IOException
177324
public static void setVerificationHeaders(HttpServletResponse response, File file)
  throws IOException {
    response.setHeader(TransferFsImage.CONTENT_LENGTH,
        String.valueOf(file.length()));
    MD5Hash hash = MD5FileUtils.readStoredMd5ForFile(file);
    if (hash != null) {
      response.setHeader(TransferFsImage.MD5_HEADER, hash.toString());
    }
  }
1209052
private void writeHeader() throws IOException {
    /* Write out the header */
    if (passwordBased) {
      macOutputStream.write(AES256JNCryptor.VERSION);
      macOutputStream.write(AES256Ciphertext.FLAG_PASSWORD);
      macOutputStream.write(encryptionSalt);
      macOutputStream.write(hmacSalt);
      macOutputStream.write(iv);
    } else {
      macOutputStream.write(AES256JNCryptor.VERSION);
      macOutputStream.write(0);
      macOutputStream.write(iv);
    }
  }
400798
private function prepareDefaultHeaders()
    {
        // Set a default content-disposition header if one was no provided
        if (!$this->hasHeader('Content-Disposition')) {
            $this->headers['Content-Disposition'] = sprintf(
                'form-data; name="%s"; filename="%s"',
                $this->name,
                basename($this->filename)
            );
        }

        // Set a default Content-Type if one was not supplied
        if (!$this->hasHeader('Content-Type')) {
            $this->headers['Content-Type'] = Mimetypes::getInstance()
                ->fromFilename($this->filename) ?: 'text/plain';
        }
    }
1132239
public static MD5Hash digest(InputStream in) throws IOException {
    final byte[] buffer = new byte[4*1024]; 
    int fileLength = 0;

    final MessageDigest digester = DIGESTER_FACTORY.get();
    for(int n; (n = in.read(buffer)) != -1; ) {
      digester.update(buffer, 0, n);
      fileLength += n;
    }

    return new MD5Hash(digester.digest(), fileLength);
  }
285608
private static void setContentTypeHeader(HttpResponse response, File file) {
        String contentType = StringKit.mimeType(file.getName());
        if (null == contentType) {
            contentType = URLConnection.guessContentTypeFromName(file.getName());
        }
        response.headers().set(HttpConst.CONTENT_TYPE, contentType);
    }
1083593
private function setHeaders()
    {
        /*Execution Time unlimited*/
        set_time_limit(0);

        $fileSize = filesize($this->filePath);

        if ($fileSize === false) {
            throw new \Exception('Invalid path exception');
        }

        $_mimeType = $this->getMimeType();

        ob_start();
        header('Content-Description: File Transfer');
        header('Content-Type: '.$_mimeType);
        //header("Content-type: ".mime_content_type($value));
        header('Content-Disposition: attachment; filename='.rawurlencode(basename($this->filePath)));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: '.$fileSize);
        ob_clean();
        ob_end_flush();
        readfile($this->filePath);
    }
728681
public void writeHeaders(HttpResponse response,Resource resource, long count)
        throws IOException
    {
        ResourceCache.ResourceMetaData metaData =
            (ResourceCache.ResourceMetaData)resource.getAssociate();

        response.setContentType(metaData.getMimeType());
        if (count != -1)
        {
            if (count==resource.length())
                response.setField(HttpFields.__ContentLength,metaData.getLength());
            else
                response.setContentLength((int)count);
        }

        response.setField(HttpFields.__LastModified,metaData.getLastModified());
        
        if (_acceptRanges && response.getHttpRequest().getDotVersion()>0)
            response.setField(HttpFields.__AcceptRanges,"bytes");
    }
31200
public HttpServerExchange setResponseContentLength(long length) {
        if (length == -1) {
            responseHeaders.remove(Headers.CONTENT_LENGTH);
        } else {
            responseHeaders.put(Headers.CONTENT_LENGTH, Long.toString(length));
        }
        return this;
    }
421960
def header_length(bytearray):
    """"""
    groups_of_3, leftover = divmod(len(bytearray), 3)
    # 4 bytes out for each 3 bytes (or nonzero fraction thereof) in.
    n = groups_of_3 * 4
    if leftover:
        n += 4
    return n
317431
public void setMaxHeaderTableSize(ByteBuf out, long maxHeaderTableSize) throws Http2Exception {
        if (maxHeaderTableSize < MIN_HEADER_TABLE_SIZE || maxHeaderTableSize > MAX_HEADER_TABLE_SIZE) {
            throw connectionError(PROTOCOL_ERROR, "Header Table Size must be >= %d and <= %d but was %d",
                    MIN_HEADER_TABLE_SIZE, MAX_HEADER_TABLE_SIZE, maxHeaderTableSize);
        }
        if (this.maxHeaderTableSize == maxHeaderTableSize) {
            return;
        }
        this.maxHeaderTableSize = maxHeaderTableSize;
        ensureCapacity(0);
        // Casting to integer is safe as we verified the maxHeaderTableSize is a valid unsigned int.
        encodeInteger(out, 0x20, 5, maxHeaderTableSize);
    }
605307
private void addExtraHeaders(final ByteBuffer bb,
    final Object... extraHeaders) {
    for (Object o : extraHeaders) {
      if (o instanceof Integer) {
        bb.putInt((Integer) o);
      } else if (o instanceof byte[]) {
        bb.put((byte[]) o);
      } else if (o instanceof Long) {
        bb.putLong((Long) o);
      } else if (o instanceof Short) {
        bb.putShort((Short) o);
      } else {
        assert false : "Unhandled extra header type:  " + o.getClass();
      }
    }
466674
@Override
    public void setLimitOnNumberOfHeaders(int size) {
        if (0 >= size) {
            throw new IllegalArgumentException("Invalid limit on number headers: " + size);
        }
        this.limitNumHeaders = size;
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Limit on number of headers now: " + this.limitNumHeaders);
        }
    }
363508
@Override
    public int getHeaderLength() {
        try {
            final byte b = this.headers.getByte(0);
            // length is encoded as the number of 32-bit words, so to get number of bytes we must multiply by 4
            return (b & 0x0F) * 4;
        } catch (final IOException e) {
            throw new RuntimeException("unable to get the header length of the IP packet due to IOException", e);
        }
    }
974797
void parseNextResponse() throws IOException {
    contentId++;

    // Extract the outer headers.
    String line;
    while ((line = readLine()) != null && !line.equals("")) {
      // Do nothing.
    }

    // Extract the status code.
    String statusLine = readLine();
    String[] statusParts = statusLine.split(" ");
    int statusCode = Integer.parseInt(statusParts[1]);

    // Extract and store the inner headers.
    // TODO(rmistry): Handle inner headers that span multiple lines. More details here:
    // http://tools.ietf.org/html/rfc2616#section-2.2
    List<String> headerNames = new ArrayList<String>();
    List<String> headerValues = new ArrayList<String>();
    long contentLength = -1L;
    while ((line = readLine()) != null && !line.equals("")) {
      String[] headerParts = line.split(": ", 2);
      String headerName = headerParts[0];
      String headerValue = headerParts[1];
      headerNames.add(headerName);
      headerValues.add(headerValue);
      if ("Content-Length".equalsIgnoreCase(headerName.trim())) {
          contentLength = Long.parseLong(headerValue);
      }
    }

    InputStream body;
    if (contentLength == -1) {
      // This isn't very efficient, but most respectable servers should set the Content-Length
      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      while ((line = readRawLine()) != null && !line.startsWith(boundary)) {
        // Convert characters back to bytes:
        buffer.write(line.getBytes("ISO-8859-1"));
      }

      // Remove CRLF that separates body from boundary token
      body = trimCrlf(buffer.toByteArray());

      // Remove CRLF from the boundary token (to match readLine)
      line = trimCrlf(line);
    } else {
      body = new FilterInputStream(ByteStreams.limit(inputStream, contentLength)) {
        @Override
        public void close() {
          // Don't allow the parser to close the underlying stream
        }
      };
    }

    HttpResponse response =
        getFakeResponse(statusCode, body, headerNames, headerValues);

    parseAndCallback(requestInfos.get(contentId - 1), statusCode, response);

    // Consume any bytes that were not consumed by the parser
    while (body.skip(contentLength) > 0 || body.read() != -1) {
    }

    if (contentLength != -1) {
      line = readLine();
    } else {
      // The line was already read
    }
    // Consume any blank lines that follow the response (not included in Content-Length)
    while ((line != null) && (line.length() == 0)) {
      line = readLine();
    }

    checkForFinalBoundary(line);
  }
1026185
def fill_all_headers(self, req):
        """"""
        url = urlsplit(req.url)

        content_type, __ = mimetypes.guess_type(url.path)
        if content_type is None:
            content_type = self.DEFAULT_TYPE
            logger.warn("can not determine mime-type for {0}".format(url.path))
        if self._expires is None:
            # sign with url, no content-type for url
            req.headers.setdefault("content-type", content_type)

        if (
            req.body is not None
            and req.headers.get("content-md5") is None
            and self._allow_empty_md5 is False
        ):
            logger.debug("calculating content-md5")
            content, content_md5 = utils.cal_content_md5(req.body)
            req.body = content
            req.headers["content-md5"] = content_md5
            logger.debug("new content-md5 is: {0}".format(content_md5))
        else:
            logger.debug("skip content-md5 calculation")

        if self._expires is None:
            req.headers.setdefault(
                "date",
                time.strftime(self.DATE_FMT, time.gmtime())
            )
        return req
532696
private ContentChunk buildContentChunk() throws IOException {
    int blockSize;
    if (isMediaLengthKnown()) {
      // We know exactly what the blockSize will be because we know the media content length.
      blockSize = (int) Math.min(chunkSize, getMediaContentLength() - totalBytesServerReceived);
    } else {
      // Use the chunkSize as the blockSize because we do know what what it is yet.
      blockSize = chunkSize;
    }

    AbstractInputStreamContent contentChunk;
    int actualBlockSize = blockSize;
    if (isMediaLengthKnown()) {
      // Mark the current position in case we need to retry the request.
      contentInputStream.mark(blockSize);

      InputStream limitInputStream = ByteStreams.limit(contentInputStream, blockSize);
      contentChunk = new InputStreamContent(
          mediaContent.getType(), limitInputStream).setRetrySupported(true)
          .setLength(blockSize).setCloseInputStream(false);
      mediaContentLengthStr = String.valueOf(getMediaContentLength());
    } else {
      // If the media content length is not known we implement a custom buffered input stream that
      // enables us to detect the length of the media content when the last chunk is sent. We
      // accomplish this by always trying to read an extra byte further than the end of the current
      // chunk.
      int actualBytesRead;
      int bytesAllowedToRead;

      // amount of bytes which need to be copied from last chunk buffer
      int copyBytes = 0;
      if (currentRequestContentBuffer == null) {
        bytesAllowedToRead = cachedByte == null ? blockSize + 1 : blockSize;
        currentRequestContentBuffer = new byte[blockSize + 1];
        if (cachedByte != null) {
          currentRequestContentBuffer[0] = cachedByte;
        }
      } else {
        // currentRequestContentBuffer is not null that means one of the following:
        // 1. This is a request to recover from a server error (e.g. 503)
        // or
        // 2. The server received less bytes than the amount of bytes the client had sent. For
        // example, the client sends bytes 100-199, but the server returns back status code 308,
        // and its "Range" header is "bytes=0-150".
        // In that case, the new request will be constructed from the previous request's byte buffer
        // plus new bytes from the stream.
        copyBytes = (int) (totalBytesClientSent - totalBytesServerReceived);
        // shift copyBytes bytes to the beginning - those are the bytes which weren't received by
        // the server in the last chunk.
        System.arraycopy(currentRequestContentBuffer, currentChunkLength - copyBytes,
            currentRequestContentBuffer, 0, copyBytes);
        if (cachedByte != null) {
          // add the last cached byte to the buffer
          currentRequestContentBuffer[copyBytes] = cachedByte;
        }

        bytesAllowedToRead = blockSize - copyBytes;
      }

      actualBytesRead = ByteStreams.read(
          contentInputStream, currentRequestContentBuffer, blockSize + 1 - bytesAllowedToRead,
          bytesAllowedToRead);

      if (actualBytesRead < bytesAllowedToRead) {
        actualBlockSize = copyBytes + Math.max(0, actualBytesRead);
        if (cachedByte != null) {
          actualBlockSize++;
          cachedByte = null;
        }

        if (mediaContentLengthStr.equals("*")) {
          // At this point we know we reached the media content length because we either read less
          // than the specified chunk size or there is no more data left to be read.
          mediaContentLengthStr = String.valueOf(totalBytesServerReceived + actualBlockSize);
        }
      } else {
        cachedByte = currentRequestContentBuffer[blockSize];
      }

      contentChunk = new ByteArrayContent(
          mediaContent.getType(), currentRequestContentBuffer, 0, actualBlockSize);
      totalBytesClientSent = totalBytesServerReceived + actualBlockSize;
    }

    currentChunkLength = actualBlockSize;

    String contentRange;
    if (actualBlockSize == 0) {
      // No bytes to upload. Either zero content media being uploaded, or a server failure on the
      // last write, even though the write actually succeeded. Either way,
      // mediaContentLengthStr will contain the actual media length.
      contentRange = "bytes */" + mediaContentLengthStr;
    } else {
      contentRange = "bytes " + totalBytesServerReceived + "-"
              + (totalBytesServerReceived + actualBlockSize - 1) + "/" + mediaContentLengthStr;
    }
    return new ContentChunk(contentChunk, contentRange);
  }
1181282
protected void readLength() throws IOException {
        int len = incomingBuffer.getInt();
        if(LOGGER.isTraceEnabled()){
            LOGGER.trace("Read length in client - " + len);
        }
        if (len < 0 || len >= DirectoryConnection.packetLen) {
            throw new IOException("Packet len" + len + " is out of range!");
        }
        incomingBuffer = ByteBuffer.allocate(len);
    }