Consume all the whitespace we find (WS)

@param buffer
@return true if we did consume something, false otherwise
196697
public static int consumeWS(final Buffer buffer) throws SipParseException {
        try {
            boolean done = false;
            int count = 0;
            while (buffer.hasReadableBytes() && !done) {
                if (isNext(buffer, SP) || isNext(buffer, HTAB)) {
                    buffer.readByte();
                    ++count;
                } else {
                    done = true;
                }
            }
            return count;
        } catch (final IOException e) {
            throw new SipParseException(buffer.getReaderIndex(), UNABLE_TO_READ_FROM_STREAM, e);
        }
    }
308776
private void scribbleWhiteSpace(WsByteBuffer buffer, int start, int stop) {
        if (buffer.hasArray()) {
            // buffer has a backing array so directly update that
            final byte[] data = buffer.array();
            final int offset = buffer.arrayOffset();
            int myStart = start + offset;
            int myStop = stop + offset;
            for (int i = myStart; i < myStop; i++) {
                data[i] = BNFHeaders.SPACE;
            }
        } else {
            // overlay whitespace into the buffer
            byte[] localWhitespace = whitespace;
            if (null == localWhitespace) {
                localWhitespace = getWhiteSpace();
            }
            buffer.position(start);
            int len = stop - start;
            while (len > 0) {
                if (localWhitespace.length >= len) {
                    buffer.put(localWhitespace, 0, len);
                    break; // out of while
                }
                int partial = localWhitespace.length;
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Scribbling " + partial + " bytes of whitespace");
                }
                buffer.put(localWhitespace, 0, partial);
                len -= partial;
            }
        }
    }
604565
public static boolean isWhiteSpace(String s)
  {

    if(null != s)
    {
      int n = s.length();
  
      for (int i = 0; i < n; i++)
      {
        if (!isWhiteSpace(s.charAt(i)))
          return false;
      }
    }

    return true;
  }
920572
function consumeWhitespace(remaining) {
  var match = remaining.match(/^\s+/);

  if (match) {
    var consumed = match[0];
    remaining = remaining.substring(consumed.length);
  }

  return remaining;
}
1091234
public int skipWhitespace() {
        try {
            int readChar = 20;
            char c = SPACE;
            while (Character.isWhitespace(c)) {
                reader.mark(1);
                readChar = reader.read();
                c = (char) readChar;
            }
            reader.reset();
            return readChar;
        } catch (IOException ioe) {
            throw new JsonException("An IO exception occurred while reading the JSON payload", ioe);
        }
    }
877399
private void removeBuffer(W buffer) {
        createdBufs.decrementAndGet();
        if (bufferMonitor.remove(buffer) == null) {
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.WARNING,
                    "Attempt to remove unknown buffer from pool.",
                    new Throwable());
            } else {
                logger.warning("Attempt to remove unknown buffer from pool.");
            }
        }
    }
1236614
@Nullable
  @CheckReturnValue
  public static String trimLeadingWhitespaces (@Nullable final String s)
  {
    final int n = getLeadingWhitespaceCount (s);
    return n == 0 ? s : s.substring (n, s.length ());
  }
963298
private boolean tryWhitespace() throws SAXException, IOException {
        char c;
        c = readCh();
        if (isWhitespace(c)) {
            skipWhitespace();
            return true;
        } else {
            unread(c);
            return false;
        }
    }
1336843
private final State onPayload(final Buffer buffer) {
        if (contentLength == 0) {
            return State.DONE;
        }

        if (buffer.getReadableBytes() >= contentLength) {
            try {
                payload = buffer.readBytes(contentLength);
            } catch (final IOException e) {
                throw new RuntimeException("Unable to read from stream due to IOException", e);
            }
            return State.DONE;
        }

        return State.GET_PAYLOAD;
    }
1044089
private boolean readMessage(ByteBuffer buffer) {

    // logger.finest("readMessage: " + bytesRead + " bytes read, remaining=" +
    // remainingBytes.length + ", state=" + state.toString() + ", recurse=" +
    // recurse);

    buffer.position(0);
    int bytesWeHaveBeenReading = 0;

    switch (state) {
      case SERVICELIST:
        StringBuilder builder = new StringBuilder();
        builder.append(buffer.asCharBuffer());
        parseServiceList(builder.toString());
        buffer.position(0);// reset position!
        bytesWeHaveBeenReading = buffer.limit(); // bytesWeHaveBeenreading = all
        // bytes in buffer!
        break;

      case HANDSHAKE:
        if (buffer.limit() >= 6) {
          byte[] dst = new byte[6];
          buffer.position(0);// read from start!
          buffer.get(dst);
          buffer.position(0);// reset position!
          bytesWeHaveBeenReading = 6; // 6 bytes will be removed from buffer
          String handShake = new String(dst);
          if (!handShake.equals("STP/1\n")) {
            close();
            connectionHandler.onException(
                new CommunicationException("Expected STP/1, got: " + handShake));
          }
          setState(State.EMPTY);
          connectionHandler.onHandshake(true);
        }
        break;

      case EMPTY: // read 4 byte header: STP/0
        if (buffer.limit() >= 4) {
          byte[] headerPrefix = new byte[4];
          buffer.get(headerPrefix);
          buffer.position(0);
          bytesWeHaveBeenReading = 4;
          ByteString incomingPrefix = ByteString.copyFrom(headerPrefix);
          if (stpPrefix.equals(incomingPrefix)) {
            setState(State.STP);
            /*
            if(buffer.hasRemaining()){
                buffer.compact();
                readMessage(buffer, buffer.position(), true);
            } else {
                buffer.clear();
            }
            */
          } else {
            close();
            connectionHandler.onException(
                new CommunicationException("Expected empty header"));
          }
        }
        break;

      case STP:
        // Try to read size
        buffer.position(0);
        if (buffer.limit() <= 0) {
          logger.finest("STP: Empty buffer");
          break;
        }
        int messageSize = readRawVarint32(buffer);// read part of buffer
        bytesWeHaveBeenReading = buffer.position();
        buffer.position(0);

        // If we got size, read more, if not just leave it!
        if (buffer.limit() >= bytesWeHaveBeenReading + messageSize) {
          buffer.position(bytesWeHaveBeenReading);

          // Read type and Payload!
          int messageType = buffer.get();
          bytesWeHaveBeenReading += 1;

          byte[] payload = new byte[--messageSize];
          buffer.get(payload);
          buffer.position(0);

          bytesWeHaveBeenReading += messageSize; // 32 bits = 4 bytes :-)

          setState(State.EMPTY);

          try {
            processMessage(messageType, payload);
          } catch (IOException e) {
            close();
            connectionHandler.onException(new CommunicationException(
                "Error while processing the message: " + e.getMessage()));
          }
        } else {
          // 4 + messageSize because of the int at the beginning
          logger.finest(String.format("Tried to read a message and expected %d bytes, but got %d",
                                      (4 + messageSize), buffer.limit()));

          buffer.position(0);
          bytesWeHaveBeenReading = 0;
        }
        break;

    }

    // Pop number of read bytes from
    if (bytesWeHaveBeenReading > 0) {

      // Pop X bytes, and keep message for the rest
      int rest = buffer.limit() - bytesWeHaveBeenReading;
      if (rest <= 0) {
        buffer.clear();
        buffer.limit(0);
      } else {
        byte[] temp = new byte[rest];

        buffer.position(bytesWeHaveBeenReading);
        buffer.get(temp, 0, rest);

        buffer.clear();
        buffer.limit(rest);
        buffer.position(0);
        buffer.put(temp, 0, rest);
        buffer.position(0);// set position back to start!
      }

      logger.finest(String.format("Did read message of %d bytes, new buffer size is %d",
                                  bytesWeHaveBeenReading, buffer.limit()));

      return true; // We did read a message :-)
    } else {
      if (buffer.limit() > 0) {
        logger.finest("Did NOT read message from buffer of size " + buffer.limit());
      } else {
        logger.finest("No messages in empty buffer");
      }
      return false;
    }
  }
548177
public static Buffer consumePort(final Buffer buffer) throws IOException {
        int count = 0;
        final int index = buffer.getReaderIndex();
        boolean done = false;
        while (!done && buffer.hasReadableBytes()) {
            if (isDigit(buffer.readByte())) {
                ++count;
            } else {
                done = true;
            }
        }

        buffer.setReaderIndex(index);
        if (count != 0) {
            return buffer.readBytes(count);
        }

        return null;
    }
482585
protected boolean parseOctetContent(ByteBuffer buffer) {

        // Starts With
        if (_partialBoundary > 0) {
            int partial = _delimiterSearch.startsWith(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining(), _partialBoundary);
            if (partial > 0) {
                if (partial == _delimiterSearch.getLength()) {
                    buffer.position(buffer.position() + _delimiterSearch.getLength() - _partialBoundary);
                    setState(State.DELIMITER);
                    _partialBoundary = 0;

                    if (LOG.isDebugEnabled())
                        LOG.debug("Content={}, Last={} {}", BufferUtils.toDetailString(BufferUtils.EMPTY_BUFFER), true, this);

                    return _handler.content(BufferUtils.EMPTY_BUFFER, true);
                }

                _partialBoundary = partial;
                BufferUtils.clear(buffer);
                return false;
            } else {
                // output up to _partialBoundary of the search pattern
                ByteBuffer content = _patternBuffer.slice();
                if (_state == State.FIRST_OCTETS) {
                    setState(State.OCTETS);
                    content.position(2);
                }
                content.limit(_partialBoundary);
                _partialBoundary = 0;

                if (LOG.isDebugEnabled())
                    LOG.debug("Content={}, Last={} {}", BufferUtils.toDetailString(content), false, this);

                if (_handler.content(content, false))
                    return true;
            }
        }

        // Contains
        int delimiter = _delimiterSearch.match(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining());
        if (delimiter >= 0) {
            ByteBuffer content = buffer.slice();
            content.limit(delimiter - buffer.arrayOffset() - buffer.position());

            buffer.position(delimiter - buffer.arrayOffset() + _delimiterSearch.getLength());
            setState(State.DELIMITER);

            if (LOG.isDebugEnabled())
                LOG.debug("Content={}, Last={} {}", BufferUtils.toDetailString(content), true, this);

            return _handler.content(content, true);
        }

        // Ends With
        _partialBoundary = _delimiterSearch.endsWith(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining());
        if (_partialBoundary > 0) {
            ByteBuffer content = buffer.slice();
            content.limit(content.limit() - _partialBoundary);

            if (LOG.isDebugEnabled())
                LOG.debug("Content={}, Last={} {}", BufferUtils.toDetailString(content), false, this);

            BufferUtils.clear(buffer);
            return _handler.content(content, false);
        }

        // There is normal content with no delimiter
        ByteBuffer content = buffer.slice();

        if (LOG.isDebugEnabled())
            LOG.debug("Content={}, Last={} {}", BufferUtils.toDetailString(content), false, this);

        BufferUtils.clear(buffer);
        return _handler.content(content, false);
    }
891966
protected boolean populateBuffer (Buffer buffer)
    {
        if (_abuf == null) {
            _abuf = ByteBuffer.allocateDirect(getBufferSize()).order(ByteOrder.nativeOrder());
        }
        _abuf.clear();
        int read = 0;
        try {
            read = Math.max(populateBuffer(_abuf), 0);
        } catch (IOException e) {
            log.warning("Error reading audio stream [error=" + e + "].");
        }
        if (read <= 0) {
            return false;
        }
        _abuf.rewind().limit(read);
        buffer.setData(getFormat(), _abuf, getFrequency());
        return true;
    }
397963
private boolean isWhitespace(Chars data){
        char chars[] = data.array();
        int end = data.offset()+data.length();
        for(int i=data.offset(); i<end; i++){
            if(!XMLChar.isSpace(chars[i]))
                return false;
        }
        return true;
    }
1145319
public static void clearToFill(ByteBuffer buffer) {
        if (buffer != null) {
            buffer.position(0);
            buffer.limit(buffer.capacity());
        }
    }
1279439
private boolean parseLine(ByteBuffer buffer) {
        boolean handle = false;

        // Process headers
        while (_state.ordinal() < State.HEADER.ordinal() && buffer.hasRemaining() && !handle) {
            // process each character
            HttpTokens.Token t = next(buffer);
            if (t == null)
                break;

            if (_maxHeaderBytes > 0 && ++_headerBytes > _maxHeaderBytes) {
                if (_state == State.URI) {
                    LOG.warn("URI is too large >" + _maxHeaderBytes);
                    throw new BadMessageException(HttpStatus.URI_TOO_LONG_414);
                } else {
                    if (_requestHandler != null)
                        LOG.warn("request is too large >" + _maxHeaderBytes);
                    else
                        LOG.warn("response is too large >" + _maxHeaderBytes);
                    throw new BadMessageException(HttpStatus.REQUEST_HEADER_FIELDS_TOO_LARGE_431);
                }
            }

            switch (_state) {
                case METHOD:
                    switch (t.getType()) {
                        case SPACE:
                            _length = _string.length();
                            _methodString = takeString();

                            if (_compliances.contains(HttpComplianceSection.METHOD_CASE_SENSITIVE)) {
                                HttpMethod method = HttpMethod.CACHE.get(_methodString);
                                if (method != null)
                                    _methodString = method.asString();
                            } else {
                                HttpMethod method = HttpMethod.INSENSITIVE_CACHE.get(_methodString);

                                if (method != null) {
                                    if (!method.asString().equals(_methodString))
                                        handleViolation(HttpComplianceSection.METHOD_CASE_SENSITIVE, _methodString);
                                    _methodString = method.asString();
                                }
                            }

                            setState(State.SPACE1);
                            break;

                        case LF:
                            throw new BadMessageException("No URI");

                        case ALPHA:
                        case DIGIT:
                        case TCHAR:
                            _string.append(t.getChar());
                            break;

                        default:
                            throw new IllegalCharacterException(_state, t, buffer);
                    }
                    break;

                case RESPONSE_VERSION:
                    switch (t.getType()) {
                        case SPACE:
                            _length = _string.length();
                            String version = takeString();
                            _version = HttpVersion.CACHE.get(version);
                            checkVersion();
                            setState(State.SPACE1);
                            break;

                        case ALPHA:
                        case DIGIT:
                        case TCHAR:
                        case VCHAR:
                        case COLON:
                            _string.append(t.getChar());
                            break;
                        default:
                            throw new IllegalCharacterException(_state, t, buffer);
                    }
                    break;

                case SPACE1:
                    switch (t.getType()) {
                        case SPACE:
                            break;

                        case ALPHA:
                        case DIGIT:
                        case TCHAR:
                        case VCHAR:
                        case COLON:
                            if (_responseHandler != null) {
                                if (t.getType() != HttpTokens.Type.DIGIT)
                                    throw new IllegalCharacterException(_state, t, buffer);
                                setState(State.STATUS);
                                setResponseStatus(t.getByte() - '0');
                            } else {
                                _uri.reset();
                                setState(State.URI);
                                // quick scan for space or EoBuffer
                                if (buffer.hasArray()) {
                                    byte[] array = buffer.array();
                                    int p = buffer.arrayOffset() + buffer.position();
                                    int l = buffer.arrayOffset() + buffer.limit();
                                    int i = p;
                                    while (i < l && array[i] > HttpTokens.SPACE)
                                        i++;

                                    int len = i - p;
                                    _headerBytes += len;

                                    if (_maxHeaderBytes > 0 && ++_headerBytes > _maxHeaderBytes) {
                                        LOG.warn("URI is too large >" + _maxHeaderBytes);
                                        throw new BadMessageException(HttpStatus.URI_TOO_LONG_414);
                                    }
                                    _uri.append(array, p - 1, len + 1);
                                    buffer.position(i - buffer.arrayOffset());
                                } else
                                    _uri.append(t.getByte());
                            }
                            break;

                        default:
                            throw new BadMessageException(HttpStatus.BAD_REQUEST_400, _requestHandler != null ? "No URI" : "No Status");
                    }
                    break;

                case STATUS:
                    switch (t.getType()) {
                        case SPACE:
                            setState(State.SPACE2);
                            break;

                        case DIGIT:
                            _responseStatus = _responseStatus * 10 + (t.getByte() - '0');
                            if (_responseStatus >= 1000)
                                throw new BadMessageException("Bad status");
                            break;

                        case LF:
                            setState(State.HEADER);
                            handle = _responseHandler.startResponse(_version, _responseStatus, null) || handle;
                            break;

                        default:
                            throw new IllegalCharacterException(_state, t, buffer);
                    }
                    break;

                case URI:
                    switch (t.getType()) {
                        case SPACE:
                            setState(State.SPACE2);
                            break;

                        case LF:
                            // HTTP/0.9
                            if (complianceViolation(HttpComplianceSection.NO_HTTP_0_9, "No request version"))
                                throw new BadMessageException("HTTP/0.9 not supported");
                            handle = _requestHandler.startRequest(_methodString, _uri.toString(), HttpVersion.HTTP_0_9);
                            setState(State.END);
                            BufferUtils.clear(buffer);
                            handle = handleHeaderContentMessage() || handle;
                            break;

                        case ALPHA:
                        case DIGIT:
                        case TCHAR:
                        case VCHAR:
                        case COLON:
                        case OTEXT:
                            _uri.append(t.getByte());
                            break;

                        default:
                            throw new IllegalCharacterException(_state, t, buffer);
                    }
                    break;

                case SPACE2:
                    switch (t.getType()) {
                        case SPACE:
                            break;

                        case ALPHA:
                        case DIGIT:
                        case TCHAR:
                        case VCHAR:
                        case COLON:
                            _string.setLength(0);
                            _string.append(t.getChar());
                            if (_responseHandler != null) {
                                _length = 1;
                                setState(State.REASON);
                            } else {
                                setState(State.REQUEST_VERSION);

                                // try quick look ahead for HTTP Version
                                HttpVersion version;
                                if (buffer.position() > 0 && buffer.hasArray())
                                    version = HttpVersion.lookAheadGet(buffer.array(), buffer.arrayOffset() + buffer.position() - 1, buffer.arrayOffset() + buffer.limit());
                                else
                                    version = HttpVersion.CACHE.getBest(buffer, 0, buffer.remaining());

                                if (version != null) {
                                    int pos = buffer.position() + version.asString().length() - 1;
                                    if (pos < buffer.limit()) {
                                        byte n = buffer.get(pos);
                                        if (n == HttpTokens.CARRIAGE_RETURN) {
                                            _cr = true;
                                            _version = version;
                                            checkVersion();
                                            _string.setLength(0);
                                            buffer.position(pos + 1);
                                        } else if (n == HttpTokens.LINE_FEED) {
                                            _version = version;
                                            checkVersion();
                                            _string.setLength(0);
                                            buffer.position(pos);
                                        }
                                    }
                                }
                            }
                            break;

                        case LF:
                            if (_responseHandler != null) {
                                setState(State.HEADER);
                                handle = _responseHandler.startResponse(_version, _responseStatus, null) || handle;
                            } else {
                                // HTTP/0.9
                                if (complianceViolation(HttpComplianceSection.NO_HTTP_0_9, "No request version"))
                                    throw new BadMessageException("HTTP/0.9 not supported");

                                handle = _requestHandler.startRequest(_methodString, _uri.toString(), HttpVersion.HTTP_0_9);
                                setState(State.END);
                                BufferUtils.clear(buffer);
                                handle = handleHeaderContentMessage() || handle;
                            }
                            break;

                        default:
                            throw new IllegalCharacterException(_state, t, buffer);
                    }
                    break;

                case REQUEST_VERSION:
                    switch (t.getType()) {
                        case LF:
                            if (_version == null) {
                                _length = _string.length();
                                _version = HttpVersion.CACHE.get(takeString());
                            }
                            checkVersion();

                            // Should we try to cache header fields?
                            if (_fieldCache == null && _version.getVersion() >= HttpVersion.HTTP_1_1.getVersion() && _handler.getHeaderCacheSize() > 0) {
                                int header_cache = _handler.getHeaderCacheSize();
                                _fieldCache = new ArrayTernaryTrie<>(header_cache);
                            }

                            setState(State.HEADER);

                            handle = _requestHandler.startRequest(_methodString, _uri.toString(), _version) || handle;
                            continue;

                        case ALPHA:
                        case DIGIT:
                        case TCHAR:
                        case VCHAR:
                        case COLON:
                            _string.append(t.getChar());
                            break;

                        default:
                            throw new IllegalCharacterException(_state, t, buffer);
                    }
                    break;

                case REASON:
                    switch (t.getType()) {
                        case LF:
                            String reason = takeString();
                            setState(State.HEADER);
                            handle = _responseHandler.startResponse(_version, _responseStatus, reason) || handle;
                            continue;

                        case ALPHA:
                        case DIGIT:
                        case TCHAR:
                        case VCHAR:
                        case COLON:
                        case OTEXT: // TODO should this be UTF8
                            _string.append(t.getChar());
                            _length = _string.length();
                            break;

                        case SPACE:
                        case HTAB:
                            _string.append(t.getChar());
                            break;

                        default:
                            throw new IllegalCharacterException(_state, t, buffer);
                    }
                    break;

                default:
                    throw new IllegalStateException(_state.toString());
            }
        }

        return handle;
    }
877668
public static boolean containsWhitespace(final CharSequence seq) {
        if (isEmpty(seq)) {
            return false;
        }
        final int strLen = seq.length();
        for (int i = 0; i < strLen; i++) {
            if (CharUtils.isWhitespace(seq.charAt(i))) {
                return true;
            }
        }
        return false;
    }