////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////
// Ensure that the supplied request has a correct ContentLength field set.
484286
func fillInContentLength(req *http.Request) (err error) {
	body := req.Body
	if body == nil {
		req.ContentLength = 0
		return
	}

	// Make a copy.
	contents, err := ioutil.ReadAll(req.Body)
	if err != nil {
		err = fmt.Errorf("ReadAll: %v", err)
		return
	}

	req.Body.Close()

	// Fill in the content length and restore the body.
	req.ContentLength = int64(len(contents))
	req.Body = ioutil.NopCloser(bytes.NewReader(contents))

	return
}
851031
public long contentLengthSent()
  {
    OutHttpApp stream = _responseStream;
    
    // stream can be null for duplex (websocket)
    if (stream != null) {
      return stream.contentLength();
    }
    else {
      return Math.max(_contentLengthOut, 0);
    }
  }
698387
protected int getContentLength(boolean update) {            
      if (update){
              contentLength = (int) this.getFileSize(update);
              return contentLength;
      } else {
              if (contentLength==-1){
                      contentLength = (int) this.getFileSize(update);
              return contentLength;
              }
              else {
                      return contentLength;
              }
      }
  }
846554
def check_content_length(status, headers, env)
      headers.each { |key, value|
        if key.downcase == 'content-length'
          ## There must not be a <tt>Content-Length</tt> header when the
          ## +Status+ is 1xx, 204 or 304.
          assert("Content-Length header found in #{status} response, not allowed") {
            not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
          }

          bytes = 0
          string_body = true

          if @body.respond_to?(:to_ary)
            @body.each { |part|
              unless part.kind_of?(String)
                string_body = false
                break
              end

              bytes += Rack::Utils.bytesize(part)
            }

            if env["REQUEST_METHOD"] == "HEAD"
              assert("Response body was given for HEAD request, but should be empty") {
                bytes == 0
              }
            else
              if string_body
                assert("Content-Length header was #{value}, but should be #{bytes}") {
                  value == bytes.to_s
                }
              end
            end
          end

          return
        end
      }
    end
46994
function ChecksumError(cause, actual, expected) {
    this.code = 'ChecksumError';
    if (expected === undefined) {
        expected = actual;
        actual = cause;
        cause = undefined;
    }
    assert.optionalObject(cause);
    assert.string(actual);
    assert.string(expected);

    var args = [];
    if (cause) args.push(cause);
    args = args.concat('content-md5 expected to be %s, but was %s',
        expected, actual);
    WError.apply(this, args);
}
1188343
public static boolean isMultipartContent(HttpServletRequest request) {
		if (!"post".equals(request.getMethod().toLowerCase())) {
			return false;
		}

		String contentType = request.getContentType();
		if (contentType == null) {
			return false;
		}
		if (contentType.toLowerCase().startsWith(MULTIPART)) {
			return true;
		}

		return false;
	}
218709
def _init_length(self, request_method):
        
        length = self.headers.get('content-length')

        if length is not None:
            if self.chunked:
                # This Response will fail with an IncompleteRead if it can't be
                # received as chunked. This method falls back to attempt reading
                # the response before raising an exception.
                log.warning("Received response with both Content-Length and "
                            "Transfer-Encoding set. This is expressly forbidden "
                            "by RFC 7230 sec 3.3.2. Ignoring Content-Length and "
                            "attempting to process response as Transfer-Encoding: "
                            "chunked.")
                return None

            try:
                # RFC 7230 section 3.3.2 specifies multiple content lengths can
                # be sent in a single Content-Length header
                # (e.g. Content-Length: 42, 42). This line ensures the values
                # are all valid ints and that as long as the `set` length is 1,
                # all values are the same. Otherwise, the header is invalid.
                lengths = set([int(val) for val in length.split(',')])
                if len(lengths) > 1:
                    raise InvalidHeader("Content-Length contained multiple "
                                        "unmatching values (%s)" % length)
                length = lengths.pop()
            except ValueError:
                length = None
            else:
                if length < 0:
                    length = None

        # Convert status to int for comparison
        # In some cases, httplib returns a status of "_UNKNOWN"
        try:
            status = int(self.status)
        except ValueError:
            status = 0

        # Check for responses that shouldn't include a body
        if status in (204, 304) or 100 <= status < 200 or request_method == 'HEAD':
            length = 0

        return length
320104
function listRequest (path, options = {}, cb) {
  if (typeof options === 'function') {
    cb = options;
    options = {};
  }
  // serialise options
  let opts = [];
  for (let k in options) {
    // The whole URL *minus* the scheme and "://" (for whatever benighted reason) has to be at most
    // 4096 characters long. Taking the extra bloat that `encodeURIComponent()` adds we truncate the
    // query to 2000 chars. We could be more precise and regenerate the URL until we reach as close
    // as possible to 4096, but frankly if you're searching for a string longer than 2000 characters
    // you're probably doing something wrong.
    if (k === 'query') {
      if (options.query.length > 2000) options.query = options.query.substr(0, 2000);
      opts.push(`query=${encodeURIComponent(options.query)}`);
    }
    else if (k === 'filter') {
      let filts = [];
      for (let f in options.filter) {
        if (Array.isArray(options.filter[f])) {
          options.filter[f].forEach(val => {
            filts.push(`${f}:${val}`);
          });
        }
        else {
          filts.push(`${f}:${options.filter[f]}`);
        }
      }
      opts.push(`filter=${filts.join(',')}`);
    }
    else if (k === 'facet' && options.facet) opts.push('facet=t');
    else opts.push(`${k}=${options[k]}`);
  }
  if (opts.length) path += `?${opts.join('&')}`;
  return GET(path, (err, msg) => {
    if (err) return cb(err);
    let objects = msg.items;
    delete msg.items;
    let nextOffset = 0
      , isDone = false
      , nextOptions
    ;
    // /types is a list but it does not behave like the other lists
    // Once again the science.ai League of JStice saves the day papering over inconsistency!
    if (msg['items-per-page'] && msg.query) {
      nextOffset = msg.query['start-index'] + msg['items-per-page'];
      if (nextOffset > msg['total-results']) isDone = true;
      nextOptions = assign({}, options, { offset: nextOffset });
    }
    else {
      isDone = true;
      nextOptions = assign({}, options);
    }
    cb(null, objects, nextOptions, isDone, msg);
  });
}
669335
function validateObjectAttributeHTTPInput( $http, $base, $contentObjectAttribute )
    {
        $classAttribute = $contentObjectAttribute->contentClassAttribute();
        $useSeconds = ( $classAttribute->attribute( self::USE_SECONDS_FIELD ) == 1 );

        if ( $http->hasPostVariable( $base . '_datetime_year_' . $contentObjectAttribute->attribute( 'id' ) ) and
             $http->hasPostVariable( $base . '_datetime_month_' . $contentObjectAttribute->attribute( 'id' ) ) and
             $http->hasPostVariable( $base . '_datetime_day_' . $contentObjectAttribute->attribute( 'id' ) ) and
             $http->hasPostVariable( $base . '_datetime_hour_' . $contentObjectAttribute->attribute( 'id' ) ) and
             $http->hasPostVariable( $base . '_datetime_minute_' . $contentObjectAttribute->attribute( 'id' ) ) and
             ( !$useSeconds or $http->hasPostVariable( $base . '_datetime_second_' . $contentObjectAttribute->attribute( 'id' ) ) ) )
        {
            $year   = $http->postVariable( $base . '_datetime_year_' . $contentObjectAttribute->attribute( 'id' ) );
            $month  = $http->postVariable( $base . '_datetime_month_' . $contentObjectAttribute->attribute( 'id' ) );
            $day    = $http->postVariable( $base . '_datetime_day_' . $contentObjectAttribute->attribute( 'id' ) );
            $hour   = $http->postVariable( $base . '_datetime_hour_' . $contentObjectAttribute->attribute( 'id' ) );
            $minute = $http->postVariable( $base . '_datetime_minute_' . $contentObjectAttribute->attribute( 'id' ) );
            $second = $useSeconds ? $http->postVariable( $base . '_datetime_second_' . $contentObjectAttribute->attribute( 'id' ) ) : 0;

            if ( $year == '' or
                 $month == '' or
                 $day == '' or
                 $hour == '' or
                 $minute == '' or
                 ( $useSeconds and $second == '' ) )
            {
                if ( !( $year == '' and
                        $month == '' and
                        $day == '' and
                        $hour == '' and
                        $minute == '' and
                        ( !$useSeconds or $second == '' ) ) or
                     ( !$classAttribute->attribute( 'is_information_collector' ) and
                       $contentObjectAttribute->validateIsRequired() ) )
                {
                    $contentObjectAttribute->setValidationError( ezpI18n::tr( 'kernel/classes/datatypes',
                                                                         'Missing datetime input.' ) );
                    return eZInputValidator::STATE_INVALID;
                }
                else
                    return eZInputValidator::STATE_ACCEPTED;
            }
            else
            {
                return $this->validateDateTimeHTTPInput( $day, $month, $year, $hour, $minute, $second, $contentObjectAttribute );
            }
        }
        else if ( !$classAttribute->attribute( 'is_information_collector' ) and $contentObjectAttribute->validateIsRequired() )
        {
            $contentObjectAttribute->setValidationError( ezpI18n::tr( 'kernel/classes/datatypes', 'Missing datetime input.' ) );
            return eZInputValidator::STATE_INVALID;
        }
        else
            return eZInputValidator::STATE_ACCEPTED;
    }
951811
def prepare_content_length(self, body):
        """"""
        if body is not None:
            length = super_len(body)
            if length:
                # If length exists, set it. Otherwise, we fallback
                # to Transfer-Encoding: chunked.
                self.headers['Content-Length'] = builtin_str(length)
        elif self.method not in ('GET', 'HEAD') and self.headers.get('Content-Length') is None:
            # Set Content-Length to 0 for methods that can have a body
            # but don't provide one. (i.e. not GET or HEAD)
            self.headers['Content-Length'] = '0'
1309423
function _getUTF8Length(content) {
    var result = encodeURI(content).toString().replace(/\%[0-9a-fA-F]{2}/g, 'a');
    return result.length + (result.length != content ? 3 : 0);
  }
310873
function addContentType(req) {
    var httpRequest = req.httpRequest;
    if (httpRequest.method === 'GET' || httpRequest.method === 'HEAD') {
      // Content-Type is not set in GET/HEAD requests
      delete httpRequest.headers['Content-Type'];
      return;
    }

    if (!httpRequest.headers['Content-Type']) { // always have a Content-Type
      httpRequest.headers['Content-Type'] = 'application/octet-stream';
    }

    var contentType = httpRequest.headers['Content-Type'];
    if (AWS.util.isBrowser()) {
      if (typeof httpRequest.body === 'string' && !contentType.match(/;\s*charset=/)) {
        var charset = '; charset=UTF-8';
        httpRequest.headers['Content-Type'] += charset;
      } else {
        var replaceFn = function(_, prefix, charsetName) {
          return prefix + charsetName.toUpperCase();
        };

        httpRequest.headers['Content-Type'] =
          contentType.replace(/(;\s*charset=)(.+)$/, replaceFn);
      }
    }
  }
622422
function urlencoded (options) {
  var opts = options || {}

  // notice because option default will flip in next major
  if (opts.extended === undefined) {
    deprecate('undefined extended: provide extended option')
  }

  var extended = opts.extended !== false
  var inflate = opts.inflate !== false
  var limit = typeof opts.limit !== 'number'
    ? bytes.parse(opts.limit || '100kb')
    : opts.limit
  var type = opts.type || 'application/x-www-form-urlencoded'
  var verify = opts.verify || false

  if (verify !== false && typeof verify !== 'function') {
    throw new TypeError('option verify must be function')
  }

  // create the appropriate query parser
  var queryparse = extended
    ? extendedparser(opts)
    : simpleparser(opts)

  // create the appropriate type checking function
  var shouldParse = typeof type !== 'function'
    ? typeChecker(type)
    : type

  function parse (body) {
    return body.length
      ? queryparse(body)
      : {}
  }

  return function urlencodedParser (req, res, next) {
    if (req._body) {
      debug('body already parsed')
      next()
      return
    }

    req.body = req.body || {}

    // skip requests without bodies
    if (!typeis.hasBody(req)) {
      debug('skip empty body')
      next()
      return
    }

    debug('content-type %j', req.headers['content-type'])

    // determine if request should be parsed
    if (!shouldParse(req)) {
      debug('skip parsing')
      next()
      return
    }

    // assert charset
    var charset = getCharset(req) || 'utf-8'
    if (charset !== 'utf-8') {
      debug('invalid charset')
      next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
        charset: charset
      }))
      return
    }

    // read
    read(req, res, next, parse, debug, {
      debug: debug,
      encoding: charset,
      inflate: inflate,
      limit: limit,
      verify: verify
    })
  }
}
393626
function checkFieldLength(parsed, field, length) {
  length = length || transactionFields[field].options.length;
  if (parsed.transactions[field] && parsed.transactions[field].toString().length > length) {
    console.log(parsed.transactions);
    console.log(field, parsed.transactions[field]);
  }
}
1121335
public int getSolverLength() {
    // Attribute name alias, creation date, Id length,
    int length = 4 + 8 + 4;

    // Id,
    if (this.identifier != null) {
      try {
        length += this.identifier.getBytes("UTF-16BE").length;
      } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("Unable to encode UTF16 strings.", e);
      }
    }

    // Data length
    length += 4;
    // Data
    if (this.data != null) {
      length += this.data.length;
    }

    return length;
  }
71694
function validateContentType(cb) {
        if (!_.isUndefined(kontx.args.meta) && !_.isUndefined(kontx.args.meta.type)) {
            db.contentTypes.getById(kontx.args.meta.type.toString()).then(
                function(contentType) {
                    cb(null, contentType);
                },
                function() {
                    cb(createError(400, messages.invalid_content_type));
                });
        } else {
            cb(createError(400, messages.invalid_content_type));
        }

    }
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;
    }