Tries to efficiently allocate the response string if the "Content-Length"
header is set.
433713
private String readResponseStream(InputStream responseStream, HttpURLConnection connection)
            throws IOException {
        LOGGER.debug("Reading response stream");
        InputStream decodedStream = responseStream;
        if (compression == Compression.LZF && "lzf".equals(connection.getHeaderField("Content-Encoding"))) {
            LOGGER.debug("Decoding lzf");
            decodedStream = new LZFInputStream(responseStream);
        }

        int contentLength = connection.getContentLength();

        if (contentLength == 0) {
            return "";
        } else {
            return new String(ByteStreams.toByteArray(decodedStream), UTF_8);
        }
    }
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);
    }
1014260
public static long getDownContentSize(HttpHeaders resHeaders) {
    String contentRange = resHeaders.get(HttpHeaderNames.CONTENT_RANGE);
    if (contentRange != null) {
      Pattern pattern = Pattern.compile("^[^\\d]*(\\d+)-(\\d+)/.*$");
      Matcher matcher = pattern.matcher(contentRange);
      if (matcher.find()) {
        long startSize = Long.parseLong(matcher.group(1));
        long endSize = Long.parseLong(matcher.group(2));
        return endSize - startSize + 1;
      }
    } else {
      String contentLength = resHeaders.get(HttpHeaderNames.CONTENT_LENGTH);
      if (contentLength != null) {
        return Long.valueOf(resHeaders.get(HttpHeaderNames.CONTENT_LENGTH));
      }
    }
    return 0;
  }
58783
def _getsize_from_header(self, header):
        
        # By default, assumes that information are in a standard HTTP header
        for key in self._SIZE_KEYS:
            try:
                return int(header.pop(key))
            except KeyError:
                continue
        else:
            raise UnsupportedOperation('getsize')
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");
    }
884552
def SafeReadBytes(self, length):
        
        data = self.ReadBytes(length)
        if len(data) < length:
            raise ValueError("Not enough data available")
        else:
            return data
90742
@Override
  public void setHeader(String key, String value)
  {
    int tail;

    if (_headerSize > 0) {
      tail = (_headerValues[_headerSize - 1].offset()
              + _headerValues[_headerSize - 1].length());
    }
    else {
      tail = 0;
    }

    int keyLength = key.length();
    int valueLength = value.length();
    char []headerBuffer = _headerBuffer;
    
    for (int i = keyLength - 1; i >= 0; i--) {
      headerBuffer[tail + i] = key.charAt(i);
    }

    _headerKeys[_headerSize].init(headerBuffer, tail, keyLength);

    tail += keyLength;

    for (int i = valueLength - 1; i >= 0; i--) {
      headerBuffer[tail + i] = value.charAt(i);
    }

    _headerValues[_headerSize].init(headerBuffer, tail, valueLength);
    _headerSize++;
    // XXX: size
  }
587611
private function populateResponseHeaders()
	{
		$done = FALSE;
		$line = NULL;
		$header = '';
		$buffer = NULL;

		// When using a file stream.
		if ( $this->resourceType === static::RESOURCE_TYPE_FILE ) {
			$done = \feof( $this->resource );
		}

		// Read the headers from the resource.
		while ( !$done )
		{
			$buffer = $this->readFromResource( 1 );
			// Update stream
			$this->content .= $buffer;
			$header = \strstr( $this->content, "\r\n\r\n", TRUE );
			// When you reach the end of the header, then exit the loop.
			if ( $buffer === '' || $header !== FALSE )
			{
				break;
			}
		}

		// Update cursor position.
		$this->position += \strlen( $this->content );
		// Parse header.
		if ( strlen(trim($header)) > 0 )
		{
			// Set header
			$this->wrapperData = explode( "\r\n", $header );
		}
	}
623323
void updateContentSize(long frameLength, boolean last) {
        if(contentLengthRemaining != -1) {
            contentLengthRemaining -= frameLength;
            if(contentLengthRemaining < 0) {
                UndertowLogger.REQUEST_IO_LOGGER.debugf("Closing stream %s on %s as data length exceeds content size", streamId, getFramedChannel());
                getFramedChannel().sendRstStream(streamId, Http2Channel.ERROR_PROTOCOL_ERROR);
            } else if(last && contentLengthRemaining != 0) {
                UndertowLogger.REQUEST_IO_LOGGER.debugf("Closing stream %s on %s as data length was less than content size", streamId, getFramedChannel());
                getFramedChannel().sendRstStream(streamId, Http2Channel.ERROR_PROTOCOL_ERROR);
            }
        }
    }
408688
function httpOk(response,isHead,body) {
  response.setHeader(HTTP_CONTENT_TYPE,MIME_TYPE_JAVASCRIPT);
  response.setHeader(HTTP_CONTENT_LENGTH,body.length);
  response.statusCode = HTTP_OK;
  if (isHead) response.end();
  else response.end(body);
}
1197345
private static void setContentLength(HttpRequest req, HttpHeaders headers, int contentLength) {
        // https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.4
        // prohibits to send message body for below cases.
        // and in those cases, content should be empty.
        if (req.method() == HttpMethod.HEAD || ArmeriaHttpUtil.isContentAlwaysEmpty(headers.status())) {
            return;
        }
        headers.setInt(HttpHeaderNames.CONTENT_LENGTH, contentLength);
    }
1217947
public static void downloadDataToSink( CResponse response, ByteSink byteSink )
    {
        InputStream is = null;
        ByteSinkStream bss = null;
        boolean success = false;
        try {

            long contentLength = response.getContentLength();
            if ( contentLength >= 0 ) {
                // content length is known: inform any listener
                byteSink.setExpectedLength( contentLength );
            }

            long current = 0;
            is = response.openStream();
            bss = byteSink.openStream();

            byte[] buffer = new byte[ 8 * 1024 ];
            int len;
            while ( ( len = is.read( buffer ) ) != -1 ) {
                current += len;
                bss.write( buffer, 0, len );
            }

            if ( contentLength < 0 ) {
                // content length was unknown; inform listener operation is terminated
                byteSink.setExpectedLength( current );
            }

            bss.flush();
            bss.close();
            bss = null;

            success = true;

        } catch ( IOException ex ) {
            throw new CStorageException( ex.getMessage(), ex );
        } finally {
            if ( bss != null && !success ) {
                bss.abort();
            }

            PcsUtils.closeQuietly( is );
            PcsUtils.closeQuietly( bss );
        }
    }
1027804
@Override
	public long getSize() throws IOException {
		if (length < 0) {
			try {
				if (activeMethod != null) {
					length = activeMethod.getResponseContentLength();
				} else {
					acquireLength();
				}
			} catch (URISyntaxException e) {
				throw new IOException(e);
			}
		}
		return length;
	}
733721
protected long getContentLength(HttpServletRequest request) {
		if (useServlet31) {
			return request.getContentLengthLong();
		}
		String contentLengthHeader = request.getHeader(HttpHeaders.CONTENT_LENGTH);
		if (contentLengthHeader != null) {
			try {
				return Long.parseLong(contentLengthHeader);
			}
			catch (NumberFormatException e) {
			}
		}
		return request.getContentLength();
	}
1156517
def request_length(self):
        
        remainder = self.stop_at - self.offset
        return self.chunk_size if remainder > self.chunk_size else remainder
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
471895
function _setResponseBody(body) {
    verifyRequestSent(this);
    verifyHeadersReceived(this);
    verifyResponseBodyType(body);

    var chunkSize = this.chunkSize || 10;
    var index = 0;
    this.responseText = "";

    do {
      if (this.async) {
        this._readyStateChange(FakeXMLHttpRequest.LOADING);
      }

      this.responseText += body.substring(index, index + chunkSize);
      index += chunkSize;
    } while (index < body.length);

    var type = this.getResponseHeader("Content-Type");

    if (this.responseText && (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) {
      try {
        this.responseXML = parseXML(this.responseText);
      } catch (e) {
        // Unable to parse XML - no biggie
      }
    }

    if (this.async) {
      this._readyStateChange(FakeXMLHttpRequest.DONE);
    } else {
      this.readyState = FakeXMLHttpRequest.DONE;
    }
  }