Class ByteChunk

  • All Implemented Interfaces:
    java.io.Serializable, java.lang.Cloneable

    public final class ByteChunk
    extends AbstractChunk
    This class is used to represent a chunk of bytes, and utilities to manipulate byte[].

    The buffer can be modified and used for both input and output.

    There are 2 modes: The chunk can be associated with a sink - ByteInputChannel or ByteOutputChannel, which will be used when the buffer is empty (on input) or filled (on output). For output, it can also grow. This operating mode is selected by calling setLimit() or allocate(initial, limit) with limit != -1.

    Various search and append method are defined - similar with String and StringBuffer, but operating on bytes.

    This is important because it allows processing the http headers directly on the received bytes, without converting to chars and Strings until the strings are needed. In addition, the charset is determined later, from headers or user code.

    In a server it is very important to be able to operate on the original byte[] without converting everything to chars. Some protocols are ASCII only, and some allow different non-UNICODE encodings. The encoding is not known beforehand, and can even change during the execution of the protocol. ( for example a multipart message may have parts with different encoding )

    For HTTP, it is not very clear how the encoding of RequestURI and mime values can be determined, but it is a great advantage to be able to parse the request without converting to string.

    See Also:
    Serialized Form
    • Constructor Summary

      Constructors 
      Constructor Description
      ByteChunk()
      Creates a new, uninitialized ByteChunk object.
      ByteChunk​(int initial)
      Creates a ByteChunk with the specified initial buffer size.
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods 
      Modifier and Type Method Description
      void allocate​(int initial, int limit)
      Allocates a buffer with the specified initial size and optional limit.
      void append​(byte b)
      Appends a single byte to this chunk.
      void append​(byte[] src, int off, int len)
      Add data to the buffer.
      void append​(java.nio.ByteBuffer from)
      Add data to the buffer.
      void append​(ByteChunk src)
      Appends the contents of another ByteChunk.
      ByteChunk clone()  
      static byte[] convertToBytes​(java.lang.String value)
      Convert specified String to a byte array.
      boolean equals​(byte[] b2, int off2, int len2)
      Compares this chunk to a byte array region.
      boolean equals​(char[] c2, int off2, int len2)
      Compares the message bytes to the specified char array.
      boolean equals​(java.lang.Object obj)
      boolean equals​(java.lang.String s)
      Compares the message bytes to the specified String object.
      boolean equals​(ByteChunk bb)
      Compares this chunk to another ByteChunk.
      boolean equals​(CharChunk cc)
      Compares this chunk to a CharChunk.
      boolean equalsIgnoreCase​(byte[] b2, int off2, int len2)
      Compares this chunk to a byte array region, ignoring case.
      boolean equalsIgnoreCase​(java.lang.String s)
      Compares the message bytes to the specified String object.
      static int findByte​(byte[] bytes, int start, int end, byte b)
      Returns the first instance of the given byte in the byte array between the specified start and end.
      static int findBytes​(byte[] bytes, int start, int end, byte[] b)
      Returns the first instance of the given bytes in the byte array between the specified start and end.
      void flushBuffer()
      Send the buffer to the sink.
      byte[] getBuffer()
      Returns the underlying byte array.
      protected int getBufferElement​(int index)
      Returns the element at the specified index in the buffer.
      byte[] getBytes()
      Returns the underlying byte array.
      java.nio.charset.Charset getCharset()
      Returns the character set for this chunk.
      long getLong()
      Parses the byte chunk content as a long integer.
      static int indexOf​(byte[] bytes, int start, int end, char s)
      Returns the first instance of the given character in the given byte array between the specified start and end.
      int indexOf​(char c, int starting)
      Returns the first instance of the given character in this ByteChunk starting at the specified byte.
      void makeSpace​(int count)
      Make space for len bytes.
      void recycle()
      Resets the chunk to an uninitialized state.
      void setByteInputChannel​(ByteChunk.ByteInputChannel in)
      When the buffer is empty, read the data from the input channel.
      void setByteOutputChannel​(ByteChunk.ByteOutputChannel out)
      When the buffer is full, write the data to the output channel.
      void setBytes​(byte[] b, int off, int len)
      Sets the buffer to the specified sub array of bytes.
      void setCharset​(java.nio.charset.Charset charset)
      Sets the character set for this chunk.
      boolean startsWith​(java.lang.String s, int pos)
      Returns true if the buffer starts with the specified string when tested in a case-sensitive manner.
      boolean startsWithIgnoreCase​(java.lang.String s, int pos)
      Returns true if the buffer starts with the specified string when tested in a case-insensitive manner.
      int subtract()
      Reads and removes the next byte from this chunk.
      int subtract​(byte[] dest, int off, int len)
      Reads bytes into the specified array.
      int subtract​(java.nio.ByteBuffer to)
      Transfers bytes from the buffer to the specified ByteBuffer.
      byte subtractB()
      Deprecated.
      Use subtract() instead.
      java.lang.String toString()  
      java.lang.String toString​(java.nio.charset.CodingErrorAction malformedInputAction, java.nio.charset.CodingErrorAction unmappableCharacterAction)
      Converts the byte chunk to a String using the configured charset.
      java.lang.String toStringInternal()
      Deprecated.
      Unused.
      java.lang.String toStringInternal​(java.nio.charset.CodingErrorAction malformedInputAction, java.nio.charset.CodingErrorAction unmappableCharacterAction)
      Converts the current content of the byte buffer to a String using the configured character set.
      • Methods inherited from class java.lang.Object

        finalize, getClass, notify, notifyAll, wait, wait, wait
    • Field Detail

      • DEFAULT_CHARSET

        public static final java.nio.charset.Charset DEFAULT_CHARSET
        Default encoding used to convert to strings. It should be UTF8, as most standards seem to converge, but the servlet API requires 8859_1, and this object is used mostly for servlets.
    • Constructor Detail

      • ByteChunk

        public ByteChunk()
        Creates a new, uninitialized ByteChunk object.
      • ByteChunk

        public ByteChunk​(int initial)
        Creates a ByteChunk with the specified initial buffer size.
        Parameters:
        initial - initial buffer size
    • Method Detail

      • clone

        public ByteChunk clone()
                        throws java.lang.CloneNotSupportedException
        Overrides:
        clone in class java.lang.Object
        Throws:
        java.lang.CloneNotSupportedException
      • recycle

        public void recycle()
        Description copied from class: AbstractChunk
        Resets the chunk to an uninitialized state.
        Overrides:
        recycle in class AbstractChunk
      • allocate

        public void allocate​(int initial,
                             int limit)
        Allocates a buffer with the specified initial size and optional limit.
        Parameters:
        initial - initial size
        limit - maximum size or -1 for unlimited
      • setBytes

        public void setBytes​(byte[] b,
                             int off,
                             int len)
        Sets the buffer to the specified sub array of bytes.
        Parameters:
        b - the ascii bytes
        off - the start offset of the bytes
        len - the length of the bytes
      • setCharset

        public void setCharset​(java.nio.charset.Charset charset)
        Sets the character set for this chunk.
        Parameters:
        charset - the character set
      • getCharset

        public java.nio.charset.Charset getCharset()
        Returns the character set for this chunk.
        Returns:
        the character set
      • getBytes

        public byte[] getBytes()
        Returns the underlying byte array.
        Returns:
        the buffer
      • getBuffer

        public byte[] getBuffer()
        Returns the underlying byte array.
        Returns:
        the buffer
      • setByteInputChannel

        public void setByteInputChannel​(ByteChunk.ByteInputChannel in)
        When the buffer is empty, read the data from the input channel.
        Parameters:
        in - The input channel
      • setByteOutputChannel

        public void setByteOutputChannel​(ByteChunk.ByteOutputChannel out)
        When the buffer is full, write the data to the output channel. Also used when large amount of data is appended. If not set, the buffer will grow to the limit.
        Parameters:
        out - The output channel
      • append

        public void append​(byte b)
                    throws java.io.IOException
        Appends a single byte to this chunk.
        Parameters:
        b - the byte to append
        Throws:
        java.io.IOException - if writing fails
      • append

        public void append​(ByteChunk src)
                    throws java.io.IOException
        Appends the contents of another ByteChunk.
        Parameters:
        src - the source chunk
        Throws:
        java.io.IOException - if writing fails
      • append

        public void append​(byte[] src,
                           int off,
                           int len)
                    throws java.io.IOException
        Add data to the buffer.
        Parameters:
        src - Bytes array
        off - Offset
        len - Length
        Throws:
        java.io.IOException - Writing overflow data to the output channel failed
      • append

        public void append​(java.nio.ByteBuffer from)
                    throws java.io.IOException
        Add data to the buffer.
        Parameters:
        from - the ByteBuffer with the data
        Throws:
        java.io.IOException - Writing overflow data to the output channel failed
      • subtract

        public int subtract()
                     throws java.io.IOException
        Reads and removes the next byte from this chunk.
        Returns:
        the byte value (0-255) or -1 if end of data
        Throws:
        java.io.IOException - if reading from input channel fails
      • subtractB

        @Deprecated
        public byte subtractB()
                       throws java.io.IOException
        Deprecated.
        Use subtract() instead. This method cannot distinguish between EOF (-1) and the legitimate byte value 0xFF because it returns byte.
        Reads and removes the next byte from this chunk.
        Returns:
        the byte value or -1 if end of data
        Throws:
        java.io.IOException - if reading from input channel fails
      • subtract

        public int subtract​(byte[] dest,
                            int off,
                            int len)
                     throws java.io.IOException
        Reads bytes into the specified array.
        Parameters:
        dest - destination array
        off - offset
        len - maximum length
        Returns:
        number of bytes read or -1 if end of data
        Throws:
        java.io.IOException - if reading from input channel fails
      • subtract

        public int subtract​(java.nio.ByteBuffer to)
                     throws java.io.IOException
        Transfers bytes from the buffer to the specified ByteBuffer. After the operation the position of the ByteBuffer will be returned to the one before the operation, the limit will be the position incremented by the number of the transferred bytes.
        Parameters:
        to - the ByteBuffer into which bytes are to be written.
        Returns:
        an integer specifying the actual number of bytes read, or -1 if the end of the stream is reached
        Throws:
        java.io.IOException - if an input or output exception has occurred
      • flushBuffer

        public void flushBuffer()
                         throws java.io.IOException
        Send the buffer to the sink. Called by append() when the limit is reached. You can also call it explicitly to force the data to be written.
        Throws:
        java.io.IOException - Writing overflow data to the output channel failed
      • makeSpace

        public void makeSpace​(int count)
        Make space for len bytes. If len is small, allocate a reserve space too. Never grow bigger than the limit or AbstractChunk.ARRAY_MAX_SIZE.
        Parameters:
        count - The size
      • toString

        public java.lang.String toString()
        Overrides:
        toString in class java.lang.Object
      • toString

        public java.lang.String toString​(java.nio.charset.CodingErrorAction malformedInputAction,
                                         java.nio.charset.CodingErrorAction unmappableCharacterAction)
                                  throws java.nio.charset.CharacterCodingException
        Converts the byte chunk to a String using the configured charset.
        Parameters:
        malformedInputAction - action for malformed input
        unmappableCharacterAction - action for unmappable characters
        Returns:
        the string representation
        Throws:
        java.nio.charset.CharacterCodingException - if conversion fails
      • toStringInternal

        @Deprecated
        public java.lang.String toStringInternal()
        Deprecated.
        Unused. This method will be removed in Tomcat 11 onwards.
        Converts the current content of the byte buffer to a String using the configured character set.
        Returns:
        The result of converting the bytes to a String
      • toStringInternal

        public java.lang.String toStringInternal​(java.nio.charset.CodingErrorAction malformedInputAction,
                                                 java.nio.charset.CodingErrorAction unmappableCharacterAction)
                                          throws java.nio.charset.CharacterCodingException
        Converts the current content of the byte buffer to a String using the configured character set.
        Parameters:
        malformedInputAction - Action to take if the input is malformed
        unmappableCharacterAction - Action to take if a byte sequence can't be mapped to a character
        Returns:
        The result of converting the bytes to a String
        Throws:
        java.nio.charset.CharacterCodingException - If an error occurs during the conversion
      • getLong

        public long getLong()
        Parses the byte chunk content as a long integer.
        Returns:
        the parsed long value
      • equals

        public boolean equals​(java.lang.String s)
        Compares the message bytes to the specified String object.

        NOTE: This only works for characters in the range 0-127.

        Parameters:
        s - the String to compare
        Returns:
        true if the comparison succeeded, false otherwise
      • equalsIgnoreCase

        public boolean equalsIgnoreCase​(java.lang.String s)
        Compares the message bytes to the specified String object.

        NOTE: This only works for characters in the range 0-255.

        Parameters:
        s - the String to compare
        Returns:
        true if the comparison succeeded, false otherwise
      • equals

        public boolean equals​(ByteChunk bb)
        Compares this chunk to another ByteChunk.
        Parameters:
        bb - the ByteChunk to compare
        Returns:
        true if equal
      • equals

        public boolean equals​(byte[] b2,
                              int off2,
                              int len2)
        Compares this chunk to a byte array region.
        Parameters:
        b2 - the byte array
        off2 - offset
        len2 - length
        Returns:
        true if equal
      • equalsIgnoreCase

        public boolean equalsIgnoreCase​(byte[] b2,
                                        int off2,
                                        int len2)
        Compares this chunk to a byte array region, ignoring case.
        Parameters:
        b2 - the byte array
        off2 - offset
        len2 - length
        Returns:
        true if equal
      • equals

        public boolean equals​(CharChunk cc)
        Compares this chunk to a CharChunk.
        Parameters:
        cc - the CharChunk to compare
        Returns:
        true if equal
      • equals

        public boolean equals​(char[] c2,
                              int off2,
                              int len2)
        Compares the message bytes to the specified char array.

        NOTE: This only works for characters in the range 0-127.

        Parameters:
        c2 - the array to compare to
        off2 - offset
        len2 - length
        Returns:
        true if the comparison succeeded, false otherwise
      • startsWith

        public boolean startsWith​(java.lang.String s,
                                  int pos)
        Returns true if the buffer starts with the specified string when tested in a case-sensitive manner.

        NOTE: This only works for characters in the range 0-127.

        Parameters:
        s - the string
        pos - The position
        Returns:
        true if the start matches
      • startsWithIgnoreCase

        public boolean startsWithIgnoreCase​(java.lang.String s,
                                            int pos)
        Returns true if the buffer starts with the specified string when tested in a case-insensitive manner.

        NOTE: This only works for characters in the range 0-255.

        Parameters:
        s - the string
        pos - The position
        Returns:
        true if the start matches
      • getBufferElement

        protected int getBufferElement​(int index)
        Description copied from class: AbstractChunk
        Returns the element at the specified index in the buffer.
        Specified by:
        getBufferElement in class AbstractChunk
        Parameters:
        index - the element location in the buffer
        Returns:
        the element
      • indexOf

        public int indexOf​(char c,
                           int starting)
        Returns the first instance of the given character in this ByteChunk starting at the specified byte. If the character is not found, -1 is returned.

        NOTE: This only works for characters in the range 0-127.

        Parameters:
        c - The character
        starting - The start position
        Returns:
        The position of the first instance of the character or -1 if the character is not found.
      • indexOf

        public static int indexOf​(byte[] bytes,
                                  int start,
                                  int end,
                                  char s)
        Returns the first instance of the given character in the given byte array between the specified start and end.

        NOTE: This only works for characters in the range 0-127.

        Parameters:
        bytes - The array to search
        start - The point to start searching from in the array
        end - The point to stop searching in the array
        s - The character to search for
        Returns:
        The position of the first instance of the character or -1 if the character is not found.
      • findByte

        public static int findByte​(byte[] bytes,
                                   int start,
                                   int end,
                                   byte b)
        Returns the first instance of the given byte in the byte array between the specified start and end.
        Parameters:
        bytes - The byte array to search
        start - The point to start searching from in the byte array
        end - The point to stop searching in the byte array
        b - The byte to search for
        Returns:
        The position of the first instance of the byte or -1 if the byte is not found.
      • findBytes

        public static int findBytes​(byte[] bytes,
                                    int start,
                                    int end,
                                    byte[] b)
        Returns the first instance of the given bytes in the byte array between the specified start and end.
        Parameters:
        bytes - The byte array to search
        start - The point to start searching from in the byte array
        end - The point to stop searching in the byte array
        b - The array of bytes to search for
        Returns:
        The position of the first instance of the byte or -1 if the byte is not found.
      • convertToBytes

        public static byte[] convertToBytes​(java.lang.String value)
        Convert specified String to a byte array. This ONLY WORKS for ascii, UTF chars will be truncated.
        Parameters:
        value - to convert to byte array
        Returns:
        the byte array value