This is an automated email from the ASF dual-hosted git repository. markt pushed a commit to branch main in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit c114c309a368527d45d5c4cde210c4541802c3d7 Author: Mark Thomas <ma...@apache.org> AuthorDate: Wed Jun 7 17:54:00 2023 +0100 Code clean-up - formatting. No functional change. --- java/org/apache/tomcat/util/buf/AbstractChunk.java | 14 +- java/org/apache/tomcat/util/buf/Ascii.java | 19 +- java/org/apache/tomcat/util/buf/Asn1Parser.java | 15 +- java/org/apache/tomcat/util/buf/Asn1Writer.java | 5 +- java/org/apache/tomcat/util/buf/B2CConverter.java | 26 +- .../apache/tomcat/util/buf/ByteBufferHolder.java | 7 +- .../apache/tomcat/util/buf/ByteBufferUtils.java | 28 +- java/org/apache/tomcat/util/buf/ByteChunk.java | 140 ++++----- java/org/apache/tomcat/util/buf/C2BConverter.java | 5 +- java/org/apache/tomcat/util/buf/CharChunk.java | 82 +++-- java/org/apache/tomcat/util/buf/CharsetCache.java | 9 +- java/org/apache/tomcat/util/buf/CharsetHolder.java | 31 +- java/org/apache/tomcat/util/buf/HexUtils.java | 29 +- java/org/apache/tomcat/util/buf/MessageBytes.java | 338 +++++++++++---------- java/org/apache/tomcat/util/buf/StringCache.java | 102 +++---- java/org/apache/tomcat/util/buf/StringUtils.java | 13 +- java/org/apache/tomcat/util/buf/UDecoder.java | 167 +++++----- java/org/apache/tomcat/util/buf/UEncoder.java | 160 +++++----- java/org/apache/tomcat/util/buf/UriUtil.java | 61 ++-- java/org/apache/tomcat/util/buf/Utf8Encoder.java | 3 +- 20 files changed, 590 insertions(+), 664 deletions(-) diff --git a/java/org/apache/tomcat/util/buf/AbstractChunk.java b/java/org/apache/tomcat/util/buf/AbstractChunk.java index 75d5b58bf1..3e06362f5f 100644 --- a/java/org/apache/tomcat/util/buf/AbstractChunk.java +++ b/java/org/apache/tomcat/util/buf/AbstractChunk.java @@ -29,10 +29,9 @@ public abstract class AbstractChunk implements Cloneable, Serializable { protected static final StringManager sm = StringManager.getManager(AbstractChunk.class); /* - * JVMs may limit the maximum array size to slightly less than - * Integer.MAX_VALUE. On markt's desktop the limit is MAX_VALUE - 2. - * Comments in the JRE source code for ArrayList and other classes indicate - * that it may be as low as MAX_VALUE - 8 on some systems. + * JVMs may limit the maximum array size to slightly less than Integer.MAX_VALUE. On markt's desktop the limit is + * MAX_VALUE - 2. Comments in the JRE source code for ArrayList and other classes indicate that it may be as low as + * MAX_VALUE - 8 on some systems. */ public static final int ARRAY_MAX_SIZE = Integer.MAX_VALUE - 8; @@ -48,10 +47,9 @@ public abstract class AbstractChunk implements Cloneable, Serializable { /** - * Maximum amount of data in this buffer. If -1 or not set, the buffer will - * grow to {{@link #ARRAY_MAX_SIZE}. Can be smaller than the current buffer - * size ( which will not shrink ). When the limit is reached, the buffer - * will be flushed (if out is set) or throw exception. + * Maximum amount of data in this buffer. If -1 or not set, the buffer will grow to {{@link #ARRAY_MAX_SIZE}. Can be + * smaller than the current buffer size ( which will not shrink ). When the limit is reached, the buffer will be + * flushed (if out is set) or throw exception. * * @param limit The new limit */ diff --git a/java/org/apache/tomcat/util/buf/Ascii.java b/java/org/apache/tomcat/util/buf/Ascii.java index daf9310a71..2c6d1eefcf 100644 --- a/java/org/apache/tomcat/util/buf/Ascii.java +++ b/java/org/apache/tomcat/util/buf/Ascii.java @@ -40,13 +40,13 @@ public final class Ascii { */ static { for (int i = 0; i < 256; i++) { - toLower[i] = (byte)i; + toLower[i] = (byte) i; } for (int lc = 'a'; lc <= 'z'; lc++) { int uc = lc + 'A' - 'a'; - toLower[uc] = (byte)lc; + toLower[uc] = (byte) lc; } for (int d = '0'; d <= '9'; d++) { @@ -56,7 +56,9 @@ public final class Ascii { /** * Returns the lower case equivalent of the specified ASCII character. + * * @param c The char + * * @return the lower case equivalent char */ public static int toLower(int c) { @@ -65,6 +67,7 @@ public final class Ascii { /** * @return <code>true</code> if the specified ASCII character is a digit. + * * @param c The char */ private static boolean isDigit(int c) { @@ -73,15 +76,16 @@ public final class Ascii { /** * Parses an unsigned long from the specified subarray of bytes. - * @param b the bytes to parse + * + * @param b the bytes to parse * @param off the start offset of the bytes * @param len the length of the bytes + * * @return the long value + * * @exception NumberFormatException if the long format was invalid */ - public static long parseLong(byte[] b, int off, int len) - throws NumberFormatException - { + public static long parseLong(byte[] b, int off, int len) throws NumberFormatException { int c; if (b == null || len <= 0 || !isDigit(c = b[off++])) { @@ -90,8 +94,7 @@ public final class Ascii { long n = c - '0'; while (--len > 0) { - if (isDigit(c = b[off++]) && - (n < OVERFLOW_LIMIT || (n == OVERFLOW_LIMIT && (c - '0') < 8))) { + if (isDigit(c = b[off++]) && (n < OVERFLOW_LIMIT || (n == OVERFLOW_LIMIT && (c - '0') < 8))) { n = n * 10 + c - '0'; } else { throw new NumberFormatException(); diff --git a/java/org/apache/tomcat/util/buf/Asn1Parser.java b/java/org/apache/tomcat/util/buf/Asn1Parser.java index 9c5bb276b2..e32e71886f 100644 --- a/java/org/apache/tomcat/util/buf/Asn1Parser.java +++ b/java/org/apache/tomcat/util/buf/Asn1Parser.java @@ -21,11 +21,10 @@ import java.math.BigInteger; import org.apache.tomcat.util.res.StringManager; /** - * This is a very basic ASN.1 parser that provides the limited functionality - * required by Tomcat. It is a long way from a complete parser. + * This is a very basic ASN.1 parser that provides the limited functionality required by Tomcat. It is a long way from a + * complete parser. * <p> - * TODO: Consider extending this parser and refactoring the SpnegoTokenFixer to - * use it. + * TODO: Consider extending this parser and refactoring the SpnegoTokenFixer to use it. */ public class Asn1Parser { @@ -54,8 +53,8 @@ public class Asn1Parser { public void parseTag(int tag) { int value = next(); if (value != tag) { - throw new IllegalArgumentException(sm.getString("asn1Parser.tagMismatch", - Integer.valueOf(tag), Integer.valueOf(value))); + throw new IllegalArgumentException( + sm.getString("asn1Parser.tagMismatch", Integer.valueOf(tag), Integer.valueOf(value))); } } @@ -63,8 +62,8 @@ public class Asn1Parser { public void parseFullLength() { int len = parseLength(); if (len + pos != source.length) { - throw new IllegalArgumentException(sm.getString("asn1Parser.lengthInvalid", - Integer.valueOf(len), Integer.valueOf(source.length - pos))); + throw new IllegalArgumentException(sm.getString("asn1Parser.lengthInvalid", Integer.valueOf(len), + Integer.valueOf(source.length - pos))); } } diff --git a/java/org/apache/tomcat/util/buf/Asn1Writer.java b/java/org/apache/tomcat/util/buf/Asn1Writer.java index f485517e09..57b36c3847 100644 --- a/java/org/apache/tomcat/util/buf/Asn1Writer.java +++ b/java/org/apache/tomcat/util/buf/Asn1Writer.java @@ -62,14 +62,13 @@ public class Asn1Writer { int dataSize = data.length; // How many bytes to write the length? int lengthSize = 1; - if (dataSize >127) { + if (dataSize > 127) { // 1 byte we have is now used to record how many bytes we need to // record a length > 127 // Result is lengthSize = 1 + number of bytes to record length do { lengthSize++; - } - while ((dataSize >> (lengthSize * 8)) > 0); + } while ((dataSize >> (lengthSize * 8)) > 0); } // 1 for tag + lengthSize + dataSize diff --git a/java/org/apache/tomcat/util/buf/B2CConverter.java b/java/org/apache/tomcat/util/buf/B2CConverter.java index c7fd4b67b7..935e89310b 100644 --- a/java/org/apache/tomcat/util/buf/B2CConverter.java +++ b/java/org/apache/tomcat/util/buf/B2CConverter.java @@ -48,8 +48,7 @@ public class B2CConverter { * * @return The Charset corresponding to the requested encoding * - * @throws UnsupportedEncodingException If the requested Charset is not - * available + * @throws UnsupportedEncodingException If the requested Charset is not available */ public static Charset getCharset(String enc) throws UnsupportedEncodingException { @@ -60,8 +59,7 @@ public class B2CConverter { if (charset == null) { // Pre-population of the cache means this must be invalid - throw new UnsupportedEncodingException( - sm.getString("b2cConverter.unknownEncoding", lowerCaseEnc)); + throw new UnsupportedEncodingException(sm.getString("b2cConverter.unknownEncoding", lowerCaseEnc)); } return charset; } @@ -105,14 +103,13 @@ public class B2CConverter { /** * Convert the given bytes to characters. * - * @param bc byte input - * @param cc char output - * @param endOfInput Is this all of the available data + * @param bc byte input + * @param cc char output + * @param endOfInput Is this all of the available data * * @throws IOException If the conversion can not be completed */ - public void convert(ByteChunk bc, CharChunk cc, boolean endOfInput) - throws IOException { + public void convert(ByteChunk bc, CharChunk cc, boolean endOfInput) throws IOException { if ((bb == null) || (bb.array() != bc.getBuffer())) { // Create a new byte buffer if anything changed bb = ByteBuffer.wrap(bc.getBuffer(), bc.getStart(), bc.getLength()); @@ -123,8 +120,7 @@ public class B2CConverter { } if ((cb == null) || (cb.array() != cc.getBuffer())) { // Create a new char buffer if anything changed - cb = CharBuffer.wrap(cc.getBuffer(), cc.getEnd(), - cc.getBuffer().length - cc.getEnd()); + cb = CharBuffer.wrap(cc.getBuffer(), cc.getEnd(), cc.getBuffer().length - cc.getEnd()); } else { // Initialize the char buffer cb.limit(cc.getBuffer().length); @@ -174,10 +170,10 @@ public class B2CConverter { /** * Convert the given bytes to characters. * - * @param bc byte input - * @param cc char output - * @param ic byte input channel - * @param endOfInput Is this all of the available data + * @param bc byte input + * @param cc char output + * @param ic byte input channel + * @param endOfInput Is this all of the available data * * @throws IOException If the conversion can not be completed */ diff --git a/java/org/apache/tomcat/util/buf/ByteBufferHolder.java b/java/org/apache/tomcat/util/buf/ByteBufferHolder.java index d12419612c..f50dded35d 100644 --- a/java/org/apache/tomcat/util/buf/ByteBufferHolder.java +++ b/java/org/apache/tomcat/util/buf/ByteBufferHolder.java @@ -20,8 +20,7 @@ import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicBoolean; /** - * Simple wrapper for a {@link ByteBuffer} that remembers if the buffer has been - * flipped or not. + * Simple wrapper for a {@link ByteBuffer} that remembers if the buffer has been flipped or not. */ public class ByteBufferHolder { @@ -29,8 +28,8 @@ public class ByteBufferHolder { private final AtomicBoolean flipped; public ByteBufferHolder(ByteBuffer buf, boolean flipped) { - this.buf = buf; - this.flipped = new AtomicBoolean(flipped); + this.buf = buf; + this.flipped = new AtomicBoolean(flipped); } diff --git a/java/org/apache/tomcat/util/buf/ByteBufferUtils.java b/java/org/apache/tomcat/util/buf/ByteBufferUtils.java index de7d0e7961..db1f68287d 100644 --- a/java/org/apache/tomcat/util/buf/ByteBufferUtils.java +++ b/java/org/apache/tomcat/util/buf/ByteBufferUtils.java @@ -48,9 +48,8 @@ public class ByteBufferUtils { unsafeLocal = theUnsafe.get(null); invokeCleanerMethodLocal = clazz.getMethod("invokeCleaner", ByteBuffer.class); invokeCleanerMethodLocal.invoke(unsafeLocal, tempBuffer); - } catch (IllegalAccessException | IllegalArgumentException - | InvocationTargetException | NoSuchMethodException | SecurityException - | ClassNotFoundException | NoSuchFieldException e) { + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | + SecurityException | ClassNotFoundException | NoSuchFieldException e) { log.warn(sm.getString("byteBufferUtils.cleaner"), e); unsafeLocal = null; invokeCleanerMethodLocal = null; @@ -67,15 +66,14 @@ public class ByteBufferUtils { /** - * Expands buffer to the given size unless it is already as big or bigger. - * Buffers are assumed to be in 'write to' mode since there would be no need - * to expand a buffer while it was in 'read from' mode. + * Expands buffer to the given size unless it is already as big or bigger. Buffers are assumed to be in 'write to' + * mode since there would be no need to expand a buffer while it was in 'read from' mode. * - * @param in Buffer to expand - * @param newSize The size t which the buffer should be expanded - * @return The expanded buffer with any data from the input buffer - * copied in to it or the original buffer if there was no - * need for expansion + * @param in Buffer to expand + * @param newSize The size t which the buffer should be expanded + * + * @return The expanded buffer with any data from the input buffer copied in to it or the original buffer if there + * was no need for expansion */ public static ByteBuffer expand(ByteBuffer in, int newSize) { if (in.capacity() >= newSize) { @@ -106,8 +104,8 @@ public class ByteBufferUtils { if (cleanMethod != null) { try { cleanMethod.invoke(cleanerMethod.invoke(buf)); - } catch (IllegalAccessException | IllegalArgumentException - | InvocationTargetException | SecurityException e) { + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | + SecurityException e) { if (log.isDebugEnabled()) { log.debug(sm.getString("byteBufferUtils.cleaner"), e); } @@ -115,8 +113,8 @@ public class ByteBufferUtils { } else if (invokeCleanerMethod != null) { try { invokeCleanerMethod.invoke(unsafe, buf); - } catch (IllegalAccessException | IllegalArgumentException - | InvocationTargetException | SecurityException e) { + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | + SecurityException e) { if (log.isDebugEnabled()) { log.debug(sm.getString("byteBufferUtils.cleaner"), e); } diff --git a/java/org/apache/tomcat/util/buf/ByteChunk.java b/java/org/apache/tomcat/util/buf/ByteChunk.java index 40607bb084..101f9c0eaa 100644 --- a/java/org/apache/tomcat/util/buf/ByteChunk.java +++ b/java/org/apache/tomcat/util/buf/ByteChunk.java @@ -42,23 +42,19 @@ import java.nio.charset.StandardCharsets; // inside this way it could provide the search/etc on ByteBuffer, as a helper. /** - * This class is used to represent a chunk of bytes, and utilities to manipulate - * byte[]. + * This class is used to represent a chunk of bytes, and utilities to manipulate byte[]. * <p> * The buffer can be modified and used for both input and output. * <p> - * 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 + * 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. * <p> - * Various search and append method are defined - similar with String and - * StringBuffer, but operating on bytes. + * Various search and append method are defined - similar with String and StringBuffer, but operating on bytes. * <p> - * 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. + * 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. * * @author d...@sun.com * @author James Todd [go...@sun.com] @@ -70,9 +66,7 @@ public final class ByteChunk extends AbstractChunk { private static final long serialVersionUID = 1L; /** - * Input interface, used when the buffer is empty. - * - * Same as java.nio.channels.ReadableByteChannel + * Input interface, used when the buffer is empty. Same as java.nio.channels.ReadableByteChannel */ public interface ByteInputChannel { @@ -87,30 +81,28 @@ public final class ByteChunk extends AbstractChunk { } /** - * When we need more space we'll either grow the buffer ( up to the limit ) - * or send it to a channel. - * - * Same as java.nio.channel.WritableByteChannel. + * When we need more space we'll either grow the buffer ( up to the limit ) or send it to a channel. Same as + * java.nio.channel.WritableByteChannel. */ public interface ByteOutputChannel { /** - * Send the bytes ( usually the internal conversion buffer ). Expect 8k - * output if the buffer is full. + * Send the bytes ( usually the internal conversion buffer ). Expect 8k output if the buffer is full. * * @param buf bytes that will be written * @param off offset in the bytes array * @param len length that will be written + * * @throws IOException If an I/O occurs while writing the bytes */ void realWriteBytes(byte buf[], int off, int len) throws IOException; /** - * Send the bytes ( usually the internal conversion buffer ). Expect 8k - * output if the buffer is full. + * Send the bytes ( usually the internal conversion buffer ). Expect 8k output if the buffer is full. * * @param from bytes that will be written + * * @throws IOException If an I/O occurs while writing the bytes */ void realWriteBytes(ByteBuffer from) throws IOException; @@ -119,9 +111,8 @@ public final class ByteChunk extends AbstractChunk { // -------------------- /** - * 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. + * 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. */ public static final Charset DEFAULT_CHARSET = StandardCharsets.ISO_8859_1; @@ -189,7 +180,7 @@ public final class ByteChunk extends AbstractChunk { /** * Sets the buffer to the specified subarray of bytes. * - * @param b the ascii bytes + * @param b the ascii bytes * @param off the start offset of the bytes * @param len the length of the bytes */ @@ -242,9 +233,8 @@ public final class ByteChunk extends AbstractChunk { /** - * 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. + * 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. * * @param out The output channel */ @@ -278,6 +268,7 @@ public final class ByteChunk extends AbstractChunk { * @param src Bytes array * @param off Offset * @param len Length + * * @throws IOException Writing overflow data to the output channel failed */ public void append(byte src[], int off, int len) throws IOException { @@ -330,6 +321,7 @@ public final class ByteChunk extends AbstractChunk { * Add data to the buffer. * * @param from the ByteBuffer with the data + * * @throws IOException Writing overflow data to the output channel failed */ public void append(ByteBuffer from) throws IOException { @@ -419,14 +411,14 @@ public final class ByteChunk extends AbstractChunk { /** - * 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. + * 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. * * @param to the ByteBuffer into which bytes are to be written. - * @return an integer specifying the actual number of bytes read, or -1 if - * the end of the stream is reached + * + * @return an integer specifying the actual number of bytes read, or -1 if the end of the stream is reached + * * @throws IOException if an input or output exception has occurred */ public int subtract(ByteBuffer to) throws IOException { @@ -457,16 +449,16 @@ public final class ByteChunk extends AbstractChunk { /** - * 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. + * 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 IOException Writing overflow data to the output channel failed */ public void flushBuffer() throws IOException { // assert out!=null if (out == null) { - throw new BufferOverflowException(sm.getString( - "chunk.overflow", Integer.valueOf(getLimit()), Integer.valueOf(buff.length))); + throw new BufferOverflowException( + sm.getString("chunk.overflow", Integer.valueOf(getLimit()), Integer.valueOf(buff.length))); } out.realWriteBytes(buff, start, end - start); end = start; @@ -474,8 +466,8 @@ public final class ByteChunk extends AbstractChunk { /** - * Make space for len bytes. If len is small, allocate a reserve space too. - * Never grow bigger than the limit or {@link AbstractChunk#ARRAY_MAX_SIZE}. + * Make space for len bytes. If len is small, allocate a reserve space too. Never grow bigger than the limit or + * {@link AbstractChunk#ARRAY_MAX_SIZE}. * * @param count The size */ @@ -570,8 +562,8 @@ public final class ByteChunk extends AbstractChunk { * Compares the message bytes to the specified String object. * * @param s the String to compare - * @return <code>true</code> if the comparison succeeded, <code>false</code> - * otherwise + * + * @return <code>true</code> if the comparison succeeded, <code>false</code> otherwise */ public boolean equals(String s) { // XXX ENCODING - this only works if encoding is UTF8-compat @@ -596,8 +588,8 @@ public final class ByteChunk extends AbstractChunk { * Compares the message bytes to the specified String object. * * @param s the String to compare - * @return <code>true</code> if the comparison succeeded, <code>false</code> - * otherwise + * + * @return <code>true</code> if the comparison succeeded, <code>false</code> otherwise */ public boolean equalsIgnoreCase(String s) { byte[] b = buff; @@ -670,10 +662,9 @@ public final class ByteChunk extends AbstractChunk { /** - * Returns true if the buffer starts with the specified string when tested - * in a case sensitive manner. + * Returns true if the buffer starts with the specified string when tested in a case sensitive manner. * - * @param s the string + * @param s the string * @param pos The position * * @return <code>true</code> if the start matches @@ -695,10 +686,9 @@ public final class ByteChunk extends AbstractChunk { /** - * Returns true if the buffer starts with the specified string when tested - * in a case insensitive manner. + * Returns true if the buffer starts with the specified string when tested in a case insensitive manner. * - * @param s the string + * @param s the string * @param pos The position * * @return <code>true</code> if the start matches @@ -726,16 +716,15 @@ public final class ByteChunk extends AbstractChunk { /** - * 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. + * 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. * <p> * NOTE: This only works for characters in the range 0-127. * - * @param c The character + * @param c The character * @param starting The start position - * @return The position of the first instance of the character or -1 if the - * character is not found. + * + * @return The position of the first instance of the character or -1 if the character is not found. */ public int indexOf(char c, int starting) { int ret = indexOf(buff, start + starting, end, c); @@ -744,17 +733,16 @@ public final class ByteChunk extends AbstractChunk { /** - * Returns the first instance of the given character in the given byte array - * between the specified start and end. + * Returns the first instance of the given character in the given byte array between the specified start and end. * <p> * NOTE: This only works for characters in the range 0-127. * * @param bytes The array to search * @param start The point to start searching from in the array - * @param end The point to stop searching in the array - * @param s The character to search for - * @return The position of the first instance of the character or -1 if the - * character is not found. + * @param end The point to stop searching in the array + * @param s The character to search for + * + * @return The position of the first instance of the character or -1 if the character is not found. */ public static int indexOf(byte bytes[], int start, int end, char s) { int offset = start; @@ -771,15 +759,14 @@ public final class ByteChunk extends AbstractChunk { /** - * Returns the first instance of the given byte in the byte array between - * the specified start and end. + * Returns the first instance of the given byte in the byte array between the specified start and end. * * @param bytes The byte array to search * @param start The point to start searching from in the byte array - * @param end The point to stop searching in the byte array - * @param b The byte to search for - * @return The position of the first instance of the byte or -1 if the byte - * is not found. + * @param end The point to stop searching in the byte array + * @param b The byte to search for + * + * @return The position of the first instance of the byte or -1 if the byte is not found. */ public static int findByte(byte bytes[], int start, int end, byte b) { int offset = start; @@ -794,15 +781,14 @@ public final class ByteChunk extends AbstractChunk { /** - * Returns the first instance of any of the given bytes in the byte array - * between the specified start and end. + * Returns the first instance of any of the given bytes in the byte array between the specified start and end. * * @param bytes The byte array to search * @param start The point to start searching from in the byte array - * @param end The point to stop searching in the byte array - * @param b The array of bytes to search for - * @return The position of the first instance of the byte or -1 if the byte - * is not found. + * @param end The point to stop searching in the byte array + * @param b The array of bytes to search for + * + * @return The position of the first instance of the byte or -1 if the byte is not found. */ public static int findBytes(byte bytes[], int start, int end, byte b[]) { int offset = start; @@ -819,10 +805,10 @@ public final class ByteChunk extends AbstractChunk { /** - * Convert specified String to a byte array. This ONLY WORKS for ascii, UTF - * chars will be truncated. + * Convert specified String to a byte array. This ONLY WORKS for ascii, UTF chars will be truncated. * * @param value to convert to byte array + * * @return the byte array value */ public static byte[] convertToBytes(String value) { diff --git a/java/org/apache/tomcat/util/buf/C2BConverter.java b/java/org/apache/tomcat/util/buf/C2BConverter.java index 4b27f6c980..5cff0f3a78 100644 --- a/java/org/apache/tomcat/util/buf/C2BConverter.java +++ b/java/org/apache/tomcat/util/buf/C2BConverter.java @@ -40,8 +40,7 @@ public final class C2BConverter { public C2BConverter(Charset charset) { encoder = charset.newEncoder(); - encoder.onUnmappableCharacter(CodingErrorAction.REPLACE) - .onMalformedInput(CodingErrorAction.REPLACE); + encoder.onUnmappableCharacter(CodingErrorAction.REPLACE).onMalformedInput(CodingErrorAction.REPLACE); char[] left = new char[4]; leftovers = CharBuffer.wrap(left); } @@ -63,6 +62,7 @@ public final class C2BConverter { * * @param cc char input * @param bc byte output + * * @throws IOException An encoding error occurred */ public void convert(CharChunk cc, ByteChunk bc) throws IOException { @@ -127,6 +127,7 @@ public final class C2BConverter { * * @param cc char input * @param bc byte output + * * @throws IOException An encoding error occurred */ public void convert(CharBuffer cc, ByteBuffer bc) throws IOException { diff --git a/java/org/apache/tomcat/util/buf/CharChunk.java b/java/org/apache/tomcat/util/buf/CharChunk.java index 411f79b5a9..b0b4745768 100644 --- a/java/org/apache/tomcat/util/buf/CharChunk.java +++ b/java/org/apache/tomcat/util/buf/CharChunk.java @@ -19,9 +19,8 @@ package org.apache.tomcat.util.buf; import java.io.IOException; /** - * Utilities to manipulate char chunks. While String is the easiest way to - * manipulate chars ( search, substrings, etc), it is known to not be the most - * efficient solution - Strings are designed as immutable and secure objects. + * Utilities to manipulate char chunks. While String is the easiest way to manipulate chars ( search, substrings, etc), + * it is known to not be the most efficient solution - Strings are designed as immutable and secure objects. * * @author d...@sun.com * @author James Todd [go...@sun.com] @@ -48,18 +47,17 @@ public final class CharChunk extends AbstractChunk implements CharSequence { } /** - * When we need more space we'll either grow the buffer ( up to the limit ) - * or send it to a channel. + * When we need more space we'll either grow the buffer ( up to the limit ) or send it to a channel. */ public interface CharOutputChannel { /** - * Send the bytes ( usually the internal conversion buffer ). Expect 8k - * output if the buffer is full. + * Send the bytes ( usually the internal conversion buffer ). Expect 8k output if the buffer is full. * * @param buf characters that will be written * @param off offset in the characters array * @param len length that will be written + * * @throws IOException If an I/O occurs while writing the characters */ void realWriteChars(char buf[], int off, int len) throws IOException; @@ -112,7 +110,7 @@ public final class CharChunk extends AbstractChunk implements CharSequence { /** * Sets the buffer to the specified subarray of characters. * - * @param c the characters + * @param c the characters * @param off the start offset of the characters * @param len the length of the characters */ @@ -152,9 +150,8 @@ public final class CharChunk extends AbstractChunk implements CharSequence { /** - * 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. + * 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. * * @param out The output channel */ @@ -188,6 +185,7 @@ public final class CharChunk extends AbstractChunk implements CharSequence { * @param src Char array * @param off Offset * @param len Length + * * @throws IOException Writing overflow data to the output channel failed */ public void append(char src[], int off, int len) throws IOException { @@ -223,9 +221,8 @@ public final class CharChunk extends AbstractChunk implements CharSequence { if (len + end < 2 * limit) { /* - * If the request length exceeds the size of the output buffer, - * flush the output buffer and then write the data directly. We - * can't avoid 2 writes, but we can write more on the second + * If the request length exceeds the size of the output buffer, flush the output buffer and then write the + * data directly. We can't avoid 2 writes, but we can write more on the second */ int avail = limit - end; System.arraycopy(src, off, buff, end, avail); @@ -250,6 +247,7 @@ public final class CharChunk extends AbstractChunk implements CharSequence { * Append a string to the buffer. * * @param s The string + * * @throws IOException Writing overflow data to the output channel failed */ public void append(String s) throws IOException { @@ -260,9 +258,10 @@ public final class CharChunk extends AbstractChunk implements CharSequence { /** * Append a string to the buffer. * - * @param s The string + * @param s The string * @param off Offset * @param len Length + * * @throws IOException Writing overflow data to the output channel failed */ public void append(String s, int off, int len) throws IOException { @@ -327,16 +326,16 @@ public final class CharChunk extends AbstractChunk implements CharSequence { /** - * 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. + * 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 IOException Writing overflow data to the output channel failed */ public void flushBuffer() throws IOException { // assert out!=null if (out == null) { - throw new IOException(sm.getString("chunk.overflow", - Integer.valueOf(getLimit()), Integer.valueOf(buff.length))); + throw new IOException( + sm.getString("chunk.overflow", Integer.valueOf(getLimit()), Integer.valueOf(buff.length))); } out.realWriteChars(buff, start, end - start); end = start; @@ -344,8 +343,8 @@ public final class CharChunk extends AbstractChunk implements CharSequence { /** - * Make space for len chars. If len is small, allocate a reserve space too. - * Never grow bigger than the limit or {@link AbstractChunk#ARRAY_MAX_SIZE}. + * Make space for len chars. If len is small, allocate a reserve space too. Never grow bigger than the limit or + * {@link AbstractChunk#ARRAY_MAX_SIZE}. * * @param count The size */ @@ -426,8 +425,8 @@ public final class CharChunk extends AbstractChunk implements CharSequence { * Compares the message bytes to the specified String object. * * @param s the String to compare - * @return <code>true</code> if the comparison succeeded, <code>false</code> - * otherwise + * + * @return <code>true</code> if the comparison succeeded, <code>false</code> otherwise */ public boolean equals(String s) { char[] c = buff; @@ -449,8 +448,8 @@ public final class CharChunk extends AbstractChunk implements CharSequence { * Compares the message bytes to the specified String object. * * @param s the String to compare - * @return <code>true</code> if the comparison succeeded, <code>false</code> - * otherwise + * + * @return <code>true</code> if the comparison succeeded, <code>false</code> otherwise */ public boolean equalsIgnoreCase(String s) { char[] c = buff; @@ -496,8 +495,8 @@ public final class CharChunk extends AbstractChunk implements CharSequence { /** - * @return <code>true</code> if the message bytes starts with the specified - * string. + * @return <code>true</code> if the message bytes starts with the specified string. + * * @param s The string */ public boolean startsWith(String s) { @@ -519,7 +518,7 @@ public final class CharChunk extends AbstractChunk implements CharSequence { /** * Returns true if the buffer starts with the specified string. * - * @param s the string + * @param s the string * @param pos The position * * @return <code>true</code> if the start matches @@ -541,8 +540,8 @@ public final class CharChunk extends AbstractChunk implements CharSequence { /** - * @return <code>true</code> if the message bytes end with the specified - * string. + * @return <code>true</code> if the message bytes end with the specified string. + * * @param s The string */ public boolean endsWith(String s) { @@ -573,14 +572,13 @@ public final class CharChunk extends AbstractChunk implements CharSequence { /** - * Returns the first instance of the given character in this CharChunk - * starting at the specified char. If the character is not found, -1 is - * returned. <br> + * Returns the first instance of the given character in this CharChunk starting at the specified char. If the + * character is not found, -1 is returned. <br> * - * @param c The character + * @param c The character * @param starting The start position - * @return The position of the first instance of the character or -1 if the - * character is not found. + * + * @return The position of the first instance of the character or -1 if the character is not found. */ public int indexOf(char c, int starting) { int ret = indexOf(buff, start + starting, end, c); @@ -589,15 +587,15 @@ public final class CharChunk extends AbstractChunk implements CharSequence { /** - * Returns the first instance of the given character in the given char array - * between the specified start and end. <br> + * Returns the first instance of the given character in the given char array between the specified start and end. + * <br> * * @param chars The array to search * @param start The point to start searching from in the array - * @param end The point to stop searching in the array - * @param s The character to search for - * @return The position of the first instance of the character or -1 if the - * character is not found. + * @param end The point to stop searching in the array + * @param s The character to search for + * + * @return The position of the first instance of the character or -1 if the character is not found. */ public static int indexOf(char chars[], int start, int end, char s) { int offset = start; diff --git a/java/org/apache/tomcat/util/buf/CharsetCache.java b/java/org/apache/tomcat/util/buf/CharsetCache.java index b26033bb1f..7de8f79c42 100644 --- a/java/org/apache/tomcat/util/buf/CharsetCache.java +++ b/java/org/apache/tomcat/util/buf/CharsetCache.java @@ -29,7 +29,7 @@ public class CharsetCache { static final String[] INITIAL_CHARSETS = new String[] { "iso-8859-1", "utf-8" }; /* - * Note: Package private to enable testing without reflection + * Note: Package private to enable testing without reflection */ static final String[] LAZY_CHARSETS = new String[] { // Initial set from Oracle JDK 8 u192 @@ -158,9 +158,9 @@ public class CharsetCache { "gb18030-2022" // If you add and entry to this list, ensure you run // TestCharsetUtil#testIsAcsiiSupersetAll() - }; + }; - private static final Charset DUMMY_CHARSET = new DummyCharset("Dummy", null); + private static final Charset DUMMY_CHARSET = new DummyCharset("Dummy", null); private ConcurrentMap<String,Charset> cache = new ConcurrentHashMap<>(); @@ -209,8 +209,7 @@ public class CharsetCache { /* - * Placeholder Charset implementation for entries that will be loaded lazily - * into the cache. + * Placeholder Charset implementation for entries that will be loaded lazily into the cache. */ private static class DummyCharset extends Charset { diff --git a/java/org/apache/tomcat/util/buf/CharsetHolder.java b/java/org/apache/tomcat/util/buf/CharsetHolder.java index f1f0d7996d..a94b8e00cb 100755 --- a/java/org/apache/tomcat/util/buf/CharsetHolder.java +++ b/java/org/apache/tomcat/util/buf/CharsetHolder.java @@ -21,15 +21,13 @@ import java.nio.charset.Charset; /** * Represents a character encoding to be used for a request or response. - * - * <p>Historically the Servlet API has used Strings for this information with - * lazy conversion to Charset. Sometimes the API required that an invalid name - * triggered an exception. Sometimes the invalid name was treated as if it had - * never been set. This resulted in classes storing both the String - * and, if the name was valid, the Charset with validation and conversion logic - * spread throughout those classes. - * - * <p>This class is an attempt to encapsulate that behaviour. + * <p> + * Historically the Servlet API has used Strings for this information with lazy conversion to Charset. Sometimes the API + * required that an invalid name triggered an exception. Sometimes the invalid name was treated as if it had never been + * set. This resulted in classes storing both the String and, if the name was valid, the Charset with validation and + * conversion logic spread throughout those classes. + * <p> + * This class is an attempt to encapsulate that behaviour. */ public class CharsetHolder { @@ -76,9 +74,8 @@ public class CharsetHolder { /** - * Returns the Charset, {@code null} if no Charset has been specified, or - * {@code null} if the holder was created using the name of a Charset that - * the JRE does not recognise. + * Returns the Charset, {@code null} if no Charset has been specified, or {@code null} if the holder was created + * using the name of a Charset that the JRE does not recognise. * * @return The Charset or {@code null} it is not set or invalid */ @@ -92,8 +89,8 @@ public class CharsetHolder { * * @return The validated Charset or {@code null} if is not set * - * @throws UnsupportedEncodingException if the holder was created using the - * name of a Charset that the JRE does not recognise + * @throws UnsupportedEncodingException if the holder was created using the name of a Charset that the JRE does not + * recognise */ public Charset getValidatedCharset() throws UnsupportedEncodingException { validate(); @@ -102,11 +99,9 @@ public class CharsetHolder { /** - * Throws an exception if the instance holds a name that without a matching - * Charset. + * Throws an exception if the instance holds a name that without a matching Charset. * - * @throws UnsupportedEncodingException if the holder contains a name - * without a matching Charset + * @throws UnsupportedEncodingException if the holder contains a name without a matching Charset */ public void validate() throws UnsupportedEncodingException { if (name != null && charset == null) { diff --git a/java/org/apache/tomcat/util/buf/HexUtils.java b/java/org/apache/tomcat/util/buf/HexUtils.java index e4aafdf551..76bb7e0dff 100644 --- a/java/org/apache/tomcat/util/buf/HexUtils.java +++ b/java/org/apache/tomcat/util/buf/HexUtils.java @@ -19,9 +19,8 @@ package org.apache.tomcat.util.buf; import org.apache.tomcat.util.res.StringManager; /** - * Tables useful when converting byte arrays to and from strings of hexadecimal - * digits. - * Code from Ajp11, from Apache's JServ. + * Tables useful when converting byte arrays to and from strings of hexadecimal digits. Code from Ajp11, from Apache's + * JServ. * * @author Craig R. McClanahan */ @@ -32,23 +31,19 @@ public final class HexUtils { // -------------------------------------------------------------- Constants /** - * Table for HEX to DEC byte translation. + * Table for HEX to DEC byte translation. */ - private static final int[] DEC = { - 00, 01, 02, 03, 04, 05, 06, 07, 8, 9, -1, -1, -1, -1, -1, -1, - -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, 10, 11, 12, 13, 14, 15, - }; + private static final int[] DEC = { 00, 01, 02, 03, 04, 05, 06, 07, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, + 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, 10, 11, 12, 13, 14, 15, }; /** * Table for DEC to HEX byte translation. */ private static final byte[] HEX = - { (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', - (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'a', (byte) 'b', - (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f' }; + { (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', + (byte) '8', (byte) '9', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f' }; /** @@ -96,9 +91,7 @@ public final class HexUtils { StringBuilder sb = new StringBuilder(bytes.length << 1); for (byte aByte : bytes) { - sb.append(hex[(aByte & 0xf0) >> 4]) - .append(hex[(aByte & 0x0f)]) - ; + sb.append(hex[(aByte & 0xf0) >> 4]).append(hex[(aByte & 0x0f)]); } return sb.toString(); @@ -118,8 +111,8 @@ public final class HexUtils { char[] inputChars = input.toCharArray(); byte[] result = new byte[input.length() >> 1]; for (int i = 0; i < result.length; i++) { - int upperNibble = getDec(inputChars[2*i]); - int lowerNibble = getDec(inputChars[2*i + 1]); + int upperNibble = getDec(inputChars[2 * i]); + int lowerNibble = getDec(inputChars[2 * i + 1]); if (upperNibble < 0 || lowerNibble < 0) { // Non hex character throw new IllegalArgumentException(sm.getString("hexUtils.fromHex.nonHex")); diff --git a/java/org/apache/tomcat/util/buf/MessageBytes.java b/java/org/apache/tomcat/util/buf/MessageBytes.java index 78f1f114d0..0aacbd83d6 100644 --- a/java/org/apache/tomcat/util/buf/MessageBytes.java +++ b/java/org/apache/tomcat/util/buf/MessageBytes.java @@ -27,12 +27,11 @@ import java.nio.charset.CodingErrorAction; import java.util.Locale; /** - * This class is used to represent a subarray of bytes in an HTTP message. - * It represents all request/response elements. The byte/char conversions are - * delayed and cached. Everything is recyclable. + * This class is used to represent a subarray of bytes in an HTTP message. It represents all request/response elements. + * The byte/char conversions are delayed and cached. Everything is recyclable. * <p> - * The object can represent a byte[], a char[], or a (sub) String. All - * operations can be made in case sensitive mode or not. + * The object can represent a byte[], a char[], or a (sub) String. All operations can be made in case sensitive mode or + * not. * * @author d...@eng.sun.com * @author James Todd [go...@eng.sun.com] @@ -47,44 +46,40 @@ public final class MessageBytes implements Cloneable, Serializable { public static final int T_NULL = 0; /** - * getType() is T_STR if the the object used to create the MessageBytes - * was a String. + * getType() is T_STR if the the object used to create the MessageBytes was a String. */ - public static final int T_STR = 1; + public static final int T_STR = 1; /** - * getType() is T_BYTES if the the object used to create the MessageBytes - * was a byte[]. + * getType() is T_BYTES if the the object used to create the MessageBytes was a byte[]. */ public static final int T_BYTES = 2; /** - * getType() is T_CHARS if the the object used to create the MessageBytes - * was a char[]. + * getType() is T_CHARS if the the object used to create the MessageBytes was a char[]. */ public static final int T_CHARS = 3; public static final char[] EMPTY_CHAR_ARRAY = new char[0]; - private int hashCode=0; + private int hashCode = 0; // did we compute the hashcode ? - private boolean hasHashCode=false; + private boolean hasHashCode = false; // Internal objects to represent array + offset, and specific methods - private final ByteChunk byteC=new ByteChunk(); - private final CharChunk charC=new CharChunk(); + private final ByteChunk byteC = new ByteChunk(); + private final CharChunk charC = new CharChunk(); // String private String strValue; /** - * Creates a new, uninitialized MessageBytes object. - * Use static newInstance() in order to allow - * future hooks. + * Creates a new, uninitialized MessageBytes object. Use static newInstance() in order to allow future hooks. */ private MessageBytes() { } /** * Construct a new MessageBytes instance. + * * @return the instance */ public static MessageBytes newInstance() { @@ -104,50 +99,51 @@ public final class MessageBytes implements Cloneable, Serializable { * Resets the message bytes to an uninitialized (NULL) state. */ public void recycle() { - type=T_NULL; + type = T_NULL; byteC.recycle(); charC.recycle(); - strValue=null; + strValue = null; - hasHashCode=false; - hasLongValue=false; + hasHashCode = false; + hasLongValue = false; } /** * Sets the content to the specified subarray of bytes. * - * @param b the bytes + * @param b the bytes * @param off the start offset of the bytes * @param len the length of the bytes */ public void setBytes(byte[] b, int off, int len) { - byteC.setBytes( b, off, len ); - type=T_BYTES; - hasHashCode=false; - hasLongValue=false; + byteC.setBytes(b, off, len); + type = T_BYTES; + hasHashCode = false; + hasLongValue = false; } /** * Sets the content to be a char[] * - * @param c the chars + * @param c the chars * @param off the start offset of the chars * @param len the length of the chars */ - public void setChars( char[] c, int off, int len ) { - charC.setChars( c, off, len ); - type=T_CHARS; - hasHashCode=false; - hasLongValue=false; + public void setChars(char[] c, int off, int len) { + charC.setChars(c, off, len); + type = T_CHARS; + hasHashCode = false; + hasLongValue = false; } /** * Set the content to be a string + * * @param s The string */ - public void setString( String s ) { + public void setString(String s) { strValue = s; hasHashCode = false; hasLongValue = false; @@ -162,6 +158,7 @@ public final class MessageBytes implements Cloneable, Serializable { /** * Compute the string value. + * * @return the string */ @Override @@ -184,10 +181,10 @@ public final class MessageBytes implements Cloneable, Serializable { return strValue; } - //---------------------------------------- + // ---------------------------------------- /** - * Return the type of the original content. Can be - * T_STR, T_BYTES, T_CHARS or T_NULL + * Return the type of the original content. Can be T_STR, T_BYTES, T_CHARS or T_NULL + * * @return the type */ public int getType() { @@ -195,8 +192,9 @@ public final class MessageBytes implements Cloneable, Serializable { } /** - * Returns the byte chunk, representing the byte[] and offset/length. - * Valid only if T_BYTES or after a conversion was made. + * Returns the byte chunk, representing the byte[] and offset/length. Valid only if T_BYTES or after a conversion + * was made. + * * @return the byte chunk */ public ByteChunk getByteChunk() { @@ -204,8 +202,9 @@ public final class MessageBytes implements Cloneable, Serializable { } /** - * Returns the char chunk, representing the char[] and offset/length. - * Valid only if T_CHARS or after a conversion was made. + * Returns the char chunk, representing the char[] and offset/length. Valid only if T_CHARS or after a conversion + * was made. + * * @return the char chunk */ public CharChunk getCharChunk() { @@ -213,8 +212,8 @@ public final class MessageBytes implements Cloneable, Serializable { } /** - * Returns the string value. - * Valid only if T_STR or after a conversion was made. + * Returns the string value. Valid only if T_STR or after a conversion was made. + * * @return the string */ public String getString() { @@ -230,6 +229,7 @@ public final class MessageBytes implements Cloneable, Serializable { /** * Set the Charset used for string<->byte conversions. + * * @param charset The charset */ public void setCharset(Charset charset) { @@ -279,9 +279,8 @@ public final class MessageBytes implements Cloneable, Serializable { /** * Convert to char[] and fill the CharChunk. * <p> - * Note: The conversion from bytes is not optimised - it converts to String - * first. However, Tomcat doesn't call this method to convert from - * bytes so there is no benefit from optimising that path. + * Note: The conversion from bytes is not optimised - it converts to String first. However, Tomcat doesn't call this + * method to convert from bytes so there is no benefit from optimising that path. */ public void toChars() { switch (type) { @@ -306,22 +305,22 @@ public final class MessageBytes implements Cloneable, Serializable { /** * Returns the length of the original buffer. * <p> - * Note: The length in bytes may be different from the length - * in chars. + * Note: The length in bytes may be different from the length in chars. + * * @return the length */ public int getLength() { - if(type==T_BYTES) { + if (type == T_BYTES) { return byteC.getLength(); } - if(type==T_CHARS) { + if (type == T_CHARS) { return charC.getLength(); } - if(type==T_STR) { + if (type == T_STR) { return strValue.length(); } toString(); - if( strValue==null ) { + if (strValue == null) { return 0; } return strValue.length(); @@ -331,43 +330,47 @@ public final class MessageBytes implements Cloneable, Serializable { /** * Compares the message bytes to the specified String object. + * * @param s the String to compare + * * @return <code>true</code> if the comparison succeeded, <code>false</code> otherwise */ public boolean equals(String s) { switch (type) { - case T_STR: - if (strValue == null) { - return s == null; - } - return strValue.equals( s ); - case T_CHARS: - return charC.equals( s ); - case T_BYTES: - return byteC.equals( s ); - default: - return false; + case T_STR: + if (strValue == null) { + return s == null; + } + return strValue.equals(s); + case T_CHARS: + return charC.equals(s); + case T_BYTES: + return byteC.equals(s); + default: + return false; } } /** * Compares the message bytes to the specified String object. + * * @param s the String to compare + * * @return <code>true</code> if the comparison succeeded, <code>false</code> otherwise */ public boolean equalsIgnoreCase(String s) { switch (type) { - case T_STR: - if (strValue == null) { - return s == null; - } - return strValue.equalsIgnoreCase( s ); - case T_CHARS: - return charC.equalsIgnoreCase( s ); - case T_BYTES: - return byteC.equalsIgnoreCase( s ); - default: - return false; + case T_STR: + if (strValue == null) { + return s == null; + } + return strValue.equalsIgnoreCase(s); + case T_CHARS: + return charC.equalsIgnoreCase(s); + case T_BYTES: + return byteC.equalsIgnoreCase(s); + default: + return false; } } @@ -381,31 +384,30 @@ public final class MessageBytes implements Cloneable, Serializable { public boolean equals(MessageBytes mb) { switch (type) { - case T_STR: - return mb.equals( strValue ); + case T_STR: + return mb.equals(strValue); } - if( mb.type != T_CHARS && - mb.type!= T_BYTES ) { + if (mb.type != T_CHARS && mb.type != T_BYTES) { // it's a string or int/date string value - return equals( mb.toString() ); + return equals(mb.toString()); } // mb is either CHARS or BYTES. // this is either CHARS or BYTES // Deal with the 4 cases ( in fact 3, one is symmetric) - if( mb.type == T_CHARS && type==T_CHARS ) { - return charC.equals( mb.charC ); + if (mb.type == T_CHARS && type == T_CHARS) { + return charC.equals(mb.charC); } - if( mb.type==T_BYTES && type== T_BYTES ) { - return byteC.equals( mb.byteC ); + if (mb.type == T_BYTES && type == T_BYTES) { + return byteC.equals(mb.byteC); } - if( mb.type== T_CHARS && type== T_BYTES ) { - return byteC.equals( mb.charC ); + if (mb.type == T_CHARS && type == T_BYTES) { + return byteC.equals(mb.charC); } - if( mb.type== T_BYTES && type== T_CHARS ) { - return mb.byteC.equals( charC ); + if (mb.type == T_BYTES && type == T_CHARS) { + return mb.byteC.equals(charC); } // can't happen return true; @@ -414,66 +416,66 @@ public final class MessageBytes implements Cloneable, Serializable { /** * @return <code>true</code> if the message bytes starts with the specified string. - * @param s the string + * + * @param s the string * @param pos The start position */ public boolean startsWithIgnoreCase(String s, int pos) { switch (type) { - case T_STR: - if( strValue==null ) { - return false; - } - if( strValue.length() < pos + s.length() ) { - return false; - } - - for( int i=0; i<s.length(); i++ ) { - if( Ascii.toLower( s.charAt( i ) ) != - Ascii.toLower( strValue.charAt( pos + i ))) { + case T_STR: + if (strValue == null) { return false; } - } - return true; - case T_CHARS: - return charC.startsWithIgnoreCase( s, pos ); - case T_BYTES: - return byteC.startsWithIgnoreCase( s, pos ); - default: - return false; + if (strValue.length() < pos + s.length()) { + return false; + } + + for (int i = 0; i < s.length(); i++) { + if (Ascii.toLower(s.charAt(i)) != Ascii.toLower(strValue.charAt(pos + i))) { + return false; + } + } + return true; + case T_CHARS: + return charC.startsWithIgnoreCase(s, pos); + case T_BYTES: + return byteC.startsWithIgnoreCase(s, pos); + default: + return false; } } - // -------------------- Hash code -------------------- + // -------------------- Hash code -------------------- @Override - public int hashCode() { - if( hasHashCode ) { + public int hashCode() { + if (hasHashCode) { return hashCode; } int code = 0; - code=hash(); - hashCode=code; - hasHashCode=true; + code = hash(); + hashCode = code; + hasHashCode = true; return code; } // normal hash. private int hash() { - int code=0; + int code = 0; switch (type) { - case T_STR: - // We need to use the same hash function - for (int i = 0; i < strValue.length(); i++) { - code = code * 37 + strValue.charAt( i ); - } - return code; - case T_CHARS: - return charC.hash(); - case T_BYTES: - return byteC.hash(); - default: - return 0; + case T_STR: + // We need to use the same hash function + for (int i = 0; i < strValue.length(); i++) { + code = code * 37 + strValue.charAt(i); + } + return code; + case T_CHARS: + return charC.hash(); + case T_BYTES: + return byteC.hash(); + default: + return 0; } } @@ -481,47 +483,48 @@ public final class MessageBytes implements Cloneable, Serializable { // round of tune-up public int indexOf(String s, int starting) { toString(); - return strValue.indexOf( s, starting ); + return strValue.indexOf(s, starting); } // Inefficient initial implementation. Will be replaced on the next // round of tune-up public int indexOf(String s) { - return indexOf( s, 0 ); + return indexOf(s, 0); } public int indexOfIgnoreCase(String s, int starting) { toString(); - String upper=strValue.toUpperCase(Locale.ENGLISH); - String sU=s.toUpperCase(Locale.ENGLISH); - return upper.indexOf( sU, starting ); + String upper = strValue.toUpperCase(Locale.ENGLISH); + String sU = s.toUpperCase(Locale.ENGLISH); + return upper.indexOf(sU, starting); } /** * Copy the src into this MessageBytes, allocating more space if needed. + * * @param src The source + * * @throws IOException Writing overflow data to the output channel failed */ - public void duplicate( MessageBytes src ) throws IOException - { - switch( src.getType() ) { - case MessageBytes.T_BYTES: - type=T_BYTES; - ByteChunk bc=src.getByteChunk(); - byteC.allocate( 2 * bc.getLength(), -1 ); - byteC.append( bc ); - break; - case MessageBytes.T_CHARS: - type=T_CHARS; - CharChunk cc=src.getCharChunk(); - charC.allocate( 2 * cc.getLength(), -1 ); - charC.append( cc ); - break; - case MessageBytes.T_STR: - type=T_STR; - String sc=src.getString(); - this.setString( sc ); - break; + public void duplicate(MessageBytes src) throws IOException { + switch (src.getType()) { + case MessageBytes.T_BYTES: + type = T_BYTES; + ByteChunk bc = src.getByteChunk(); + byteC.allocate(2 * bc.getLength(), -1); + byteC.append(bc); + break; + case MessageBytes.T_CHARS: + type = T_CHARS; + CharChunk cc = src.getCharChunk(); + charC.allocate(2 * cc.getLength(), -1); + charC.append(cc); + break; + case MessageBytes.T_STR: + type = T_STR; + String sc = src.getString(); + this.setString(sc); + break; } setCharset(src.getCharset()); } @@ -530,10 +533,11 @@ public final class MessageBytes implements Cloneable, Serializable { // efficient long // XXX used only for headers - shouldn't be stored here. private long longValue; - private boolean hasLongValue=false; + private boolean hasLongValue = false; /** * Set the buffer to the representation of a long. + * * @param l The long */ public void setLong(long l) { @@ -568,42 +572,44 @@ public final class MessageBytes implements Cloneable, Serializable { start++; end--; } - longValue=l; - hasHashCode=false; - hasLongValue=true; - type=T_BYTES; + longValue = l; + hasHashCode = false; + hasLongValue = true; + type = T_BYTES; } // Used for headers conversion /** * Convert the buffer to a long, cache the value. + * * @return the long value */ public long getLong() { - if( hasLongValue ) { + if (hasLongValue) { return longValue; } switch (type) { - case T_BYTES: - longValue=byteC.getLong(); - break; - default: - longValue=Long.parseLong(toString()); + case T_BYTES: + longValue = byteC.getLong(); + break; + default: + longValue = Long.parseLong(toString()); } - hasLongValue=true; + hasLongValue = true; return longValue; - } + } // -------------------- Future may be different -------------------- - private static final MessageBytesFactory factory=new MessageBytesFactory(); + private static final MessageBytesFactory factory = new MessageBytesFactory(); private static class MessageBytesFactory { protected MessageBytesFactory() { } + public MessageBytes newInstance() { return new MessageBytes(); } diff --git a/java/org/apache/tomcat/util/buf/StringCache.java b/java/org/apache/tomcat/util/buf/StringCache.java index 483748970c..d39de93cfa 100644 --- a/java/org/apache/tomcat/util/buf/StringCache.java +++ b/java/org/apache/tomcat/util/buf/StringCache.java @@ -52,19 +52,17 @@ public class StringCache { Integer.getInteger("tomcat.util.buf.StringCache.trainThreshold", 20000).intValue(); - protected static int cacheSize = - Integer.getInteger("tomcat.util.buf.StringCache.cacheSize", 200).intValue(); + protected static int cacheSize = Integer.getInteger("tomcat.util.buf.StringCache.cacheSize", 200).intValue(); protected static final int maxStringSize = Integer.getInteger("tomcat.util.buf.StringCache.maxStringSize", 128).intValue(); - /** + /** * Statistics hash map for byte chunk. */ - protected static final HashMap<ByteEntry,int[]> bcStats = - new HashMap<>(cacheSize); + protected static final HashMap<ByteEntry,int[]> bcStats = new HashMap<>(cacheSize); /** @@ -82,8 +80,7 @@ public class StringCache { /** * Statistics hash map for char chunk. */ - protected static final HashMap<CharEntry,int[]> ccStats = - new HashMap<>(cacheSize); + protected static final HashMap<CharEntry,int[]> ccStats = new HashMap<>(cacheSize); /** @@ -231,8 +228,7 @@ public class StringCache { if (bcCount > trainThreshold) { long t1 = System.currentTimeMillis(); // Sort the entries according to occurrence - TreeMap<Integer,ArrayList<ByteEntry>> tempMap = - new TreeMap<>(); + TreeMap<Integer,ArrayList<ByteEntry>> tempMap = new TreeMap<>(); for (Entry<ByteEntry,int[]> item : bcStats.entrySet()) { ByteEntry entry = item.getKey(); int[] countA = item.getValue(); @@ -255,15 +251,12 @@ public class StringCache { ArrayList<ByteEntry> list = tempMap.get(key); for (int i = 0; i < list.size() && n < size; i++) { ByteEntry entry = list.get(i); - tempChunk.setBytes(entry.name, 0, - entry.name.length); - int insertPos = findClosest(tempChunk, - tempbcCache, n); + tempChunk.setBytes(entry.name, 0, entry.name.length); + int insertPos = findClosest(tempChunk, tempbcCache, n); if (insertPos == n) { tempbcCache[n + 1] = entry; } else { - System.arraycopy(tempbcCache, insertPos + 1, - tempbcCache, insertPos + 2, + System.arraycopy(tempbcCache, insertPos + 1, tempbcCache, insertPos + 2, n - insertPos - 1); tempbcCache[insertPos + 1] = entry; } @@ -276,8 +269,7 @@ public class StringCache { bcCache = tempbcCache; if (log.isDebugEnabled()) { long t2 = System.currentTimeMillis(); - log.debug("ByteCache generation time: " + - (t2 - t1) + "ms"); + log.debug("ByteCache generation time: " + (t2 - t1) + "ms"); } } else { bcCount++; @@ -290,8 +282,7 @@ public class StringCache { int start = bc.getStart(); // Create byte array and copy bytes entry.name = new byte[bc.getLength()]; - System.arraycopy(bc.getBuffer(), start, entry.name, - 0, end - start); + System.arraycopy(bc.getBuffer(), start, entry.name, 0, end - start); // Set encoding entry.charset = bc.getCharset(); // Initialize occurrence count to one @@ -342,8 +333,7 @@ public class StringCache { if (ccCount > trainThreshold) { long t1 = System.currentTimeMillis(); // Sort the entries according to occurrence - TreeMap<Integer,ArrayList<CharEntry>> tempMap = - new TreeMap<>(); + TreeMap<Integer,ArrayList<CharEntry>> tempMap = new TreeMap<>(); for (Entry<CharEntry,int[]> item : ccStats.entrySet()) { CharEntry entry = item.getKey(); int[] countA = item.getValue(); @@ -367,15 +357,12 @@ public class StringCache { ArrayList<CharEntry> list = tempMap.get(key); for (int i = 0; i < list.size() && n < size; i++) { CharEntry entry = list.get(i); - tempChunk.setChars(entry.name, 0, - entry.name.length); - int insertPos = findClosest(tempChunk, - tempccCache, n); + tempChunk.setChars(entry.name, 0, entry.name.length); + int insertPos = findClosest(tempChunk, tempccCache, n); if (insertPos == n) { tempccCache[n + 1] = entry; } else { - System.arraycopy(tempccCache, insertPos + 1, - tempccCache, insertPos + 2, + System.arraycopy(tempccCache, insertPos + 1, tempccCache, insertPos + 2, n - insertPos - 1); tempccCache[insertPos + 1] = entry; } @@ -388,8 +375,7 @@ public class StringCache { ccCache = tempccCache; if (log.isDebugEnabled()) { long t2 = System.currentTimeMillis(); - log.debug("CharCache generation time: " + - (t2 - t1) + "ms"); + log.debug("CharCache generation time: " + (t2 - t1) + "ms"); } } else { ccCount++; @@ -402,8 +388,7 @@ public class StringCache { int start = cc.getStart(); // Create char array and copy chars entry.name = new char[cc.getLength()]; - System.arraycopy(cc.getBuffer(), start, entry.name, - 0, end - start); + System.arraycopy(cc.getBuffer(), start, entry.name, 0, end - start); // Initialize occurrence count to one count = new int[1]; count[0] = 1; @@ -436,8 +421,10 @@ public class StringCache { /** * Compare given byte chunk with byte array. - * @param name The name to compare + * + * @param name The name to compare * @param compareTo The compared to data + * * @return -1, 0 or +1 if inferior, equal, or superior to the String. */ protected static final int compare(ByteChunk name, byte[] compareTo) { @@ -470,15 +457,15 @@ public class StringCache { /** - * Find an entry given its name in the cache and return the associated - * String. + * Find an entry given its name in the cache and return the associated String. + * * @param name The name to find + * * @return the corresponding value */ protected static final String find(ByteChunk name) { int pos = findClosest(name, bcCache, bcCache.length); - if ((pos < 0) || (compare(name, bcCache[pos].name) != 0) - || !(name.getCharset().equals(bcCache[pos].charset))) { + if ((pos < 0) || (compare(name, bcCache[pos].name) != 0) || !(name.getCharset().equals(bcCache[pos].charset))) { return null; } else { return bcCache[pos].value; @@ -487,16 +474,16 @@ public class StringCache { /** - * Find an entry given its name in a sorted array of map elements. - * This will return the index for the closest inferior or equal item in the - * given array. - * @param name The name to find + * Find an entry given its name in a sorted array of map elements. This will return the index for the closest + * inferior or equal item in the given array. + * + * @param name The name to find * @param array The array in which to look - * @param len The effective length of the array + * @param len The effective length of the array + * * @return the position of the best match */ - protected static final int findClosest(ByteChunk name, ByteEntry[] array, - int len) { + protected static final int findClosest(ByteChunk name, ByteEntry[] array, int len) { int a = 0; int b = len - 1; @@ -539,8 +526,10 @@ public class StringCache { /** * Compare given char chunk with char array. - * @param name The name to compare + * + * @param name The name to compare * @param compareTo The compared to data + * * @return -1, 0 or +1 if inferior, equal, or superior to the String. */ protected static final int compare(CharChunk name, char[] compareTo) { @@ -573,9 +562,10 @@ public class StringCache { /** - * Find an entry given its name in the cache and return the associated - * String. + * Find an entry given its name in the cache and return the associated String. + * * @param name The name to find + * * @return the corresponding value */ protected static final String find(CharChunk name) { @@ -589,16 +579,16 @@ public class StringCache { /** - * Find an entry given its name in a sorted array of map elements. - * This will return the index for the closest inferior or equal item in the - * given array. - * @param name The name to find + * Find an entry given its name in a sorted array of map elements. This will return the index for the closest + * inferior or equal item in the given array. + * + * @param name The name to find * @param array The array in which to look - * @param len The effective length of the array + * @param len The effective length of the array + * * @return the position of the best match */ - protected static final int findClosest(CharChunk name, CharEntry[] array, - int len) { + protected static final int findClosest(CharChunk name, CharEntry[] array, int len) { int a = 0; int b = len - 1; @@ -608,7 +598,7 @@ public class StringCache { return -1; } - if (compare(name, array[0].name) < 0 ) { + if (compare(name, array[0].name) < 0) { return -1; } if (b == 0) { @@ -652,10 +642,12 @@ public class StringCache { public String toString() { return value; } + @Override public int hashCode() { return value.hashCode(); } + @Override public boolean equals(Object obj) { if (obj instanceof ByteEntry) { @@ -679,10 +671,12 @@ public class StringCache { public String toString() { return value; } + @Override public int hashCode() { return value.hashCode(); } + @Override public boolean equals(Object obj) { if (obj instanceof CharEntry) { diff --git a/java/org/apache/tomcat/util/buf/StringUtils.java b/java/org/apache/tomcat/util/buf/StringUtils.java index 2a9eeb0622..a50535295a 100644 --- a/java/org/apache/tomcat/util/buf/StringUtils.java +++ b/java/org/apache/tomcat/util/buf/StringUtils.java @@ -21,10 +21,9 @@ import java.util.Collection; import java.util.function.Function; /** - * Utility methods to build a separated list from a given set (not - * java.util.Set) of inputs and return that list as a string or append it to an - * existing StringBuilder. If the given set is null or empty, an empty string - * will be returned. + * Utility methods to build a separated list from a given set (not java.util.Set) of inputs and return that list as a + * string or append it to an existing StringBuilder. If the given set is null or empty, an empty string will be + * returned. */ public final class StringUtils { @@ -73,8 +72,7 @@ public final class StringUtils { } - public static <T> void join(T[] array, char separator, Function<T,String> function, - StringBuilder sb) { + public static <T> void join(T[] array, char separator, Function<T,String> function, StringBuilder sb) { if (array == null) { return; } @@ -82,8 +80,7 @@ public final class StringUtils { } - public static <T> void join(Iterable<T> iterable, char separator, Function<T,String> function, - StringBuilder sb) { + public static <T> void join(Iterable<T> iterable, char separator, Function<T,String> function, StringBuilder sb) { if (iterable == null) { return; } diff --git a/java/org/apache/tomcat/util/buf/UDecoder.java b/java/org/apache/tomcat/util/buf/UDecoder.java index b411244071..fd73d41f1f 100644 --- a/java/org/apache/tomcat/util/buf/UDecoder.java +++ b/java/org/apache/tomcat/util/buf/UDecoder.java @@ -26,12 +26,10 @@ import java.nio.charset.StandardCharsets; import org.apache.tomcat.util.res.StringManager; /** - * All URL decoding happens here. This way we can reuse, review, optimize - * without adding complexity to the buffers. + * All URL decoding happens here. This way we can reuse, review, optimize without adding complexity to the buffers. The + * conversion will modify the original buffer. * - * The conversion will modify the original buffer. - * - * @author Costin Manolache + * @author Costin Manolache */ public final class UDecoder { @@ -39,6 +37,7 @@ public final class UDecoder { private static class DecodeException extends CharConversionException { private static final long serialVersionUID = 1L; + DecodeException(String s) { super(s); } @@ -54,22 +53,18 @@ public final class UDecoder { private static final IOException EXCEPTION_EOF = new DecodeException(sm.getString("uDecoder.eof")); /** %xx with not-hex digit */ - private static final IOException EXCEPTION_NOT_HEX_DIGIT = new DecodeException( - "isHexDigit"); + private static final IOException EXCEPTION_NOT_HEX_DIGIT = new DecodeException("isHexDigit"); /** %-encoded slash is forbidden in resource path */ - private static final IOException EXCEPTION_SLASH = new DecodeException( - "noSlash"); + private static final IOException EXCEPTION_SLASH = new DecodeException("noSlash"); /** - * URLDecode, will modify the source. Assumes source bytes are encoded using - * a superset of US-ASCII as per RFC 7230. "%2f" will be rejected unless the - * input is a query string. + * URLDecode, will modify the source. Assumes source bytes are encoded using a superset of US-ASCII as per RFC 7230. + * "%2f" will be rejected unless the input is a query string. * * @param mb The URL encoded bytes - * @param query {@code true} if this is a query string. For a query string - * '+' will be decoded to ' ' + * @param query {@code true} if this is a query string. For a query string '+' will be decoded to ' ' * * @throws IOException Invalid %xx URL encoding */ @@ -83,14 +78,12 @@ public final class UDecoder { /** - * URLDecode, will modify the source. Assumes source bytes are encoded using - * a superset of US-ASCII as per RFC 7230. + * URLDecode, will modify the source. Assumes source bytes are encoded using a superset of US-ASCII as per RFC 7230. + * + * @param mb The URL encoded bytes + * @param encodedSolidusHandling How should the %2f sequence handled by the decoder? For query strings this + * parameter will be ignored and the %2f sequence will be decoded * - * @param mb The URL encoded bytes - * @param encodedSolidusHandling How should the %2f sequence handled by - * the decoder? For query strings this - * parameter will be ignored and the - * %2f sequence will be decoded * @throws IOException Invalid %xx URL encoding */ public void convert(ByteChunk mb, EncodedSolidusHandling encodedSolidusHandling) throws IOException { @@ -98,79 +91,80 @@ public final class UDecoder { } - private void convert(ByteChunk mb, boolean query, EncodedSolidusHandling encodedSolidusHandling) throws IOException { + private void convert(ByteChunk mb, boolean query, EncodedSolidusHandling encodedSolidusHandling) + throws IOException { - int start=mb.getOffset(); - byte buff[]=mb.getBytes(); - int end=mb.getEnd(); + int start = mb.getOffset(); + byte buff[] = mb.getBytes(); + int end = mb.getEnd(); - int idx= ByteChunk.findByte( buff, start, end, (byte) '%' ); - int idx2=-1; - if( query ) { - idx2= ByteChunk.findByte( buff, start, (idx >= 0 ? idx : end), (byte) '+' ); + int idx = ByteChunk.findByte(buff, start, end, (byte) '%'); + int idx2 = -1; + if (query) { + idx2 = ByteChunk.findByte(buff, start, (idx >= 0 ? idx : end), (byte) '+'); } - if( idx<0 && idx2<0 ) { + if (idx < 0 && idx2 < 0) { return; } // idx will be the smallest positive index ( first % or + ) - if( (idx2 >= 0 && idx2 < idx) || idx < 0 ) { - idx=idx2; + if ((idx2 >= 0 && idx2 < idx) || idx < 0) { + idx = idx2; } - for( int j=idx; j<end; j++, idx++ ) { - if( buff[ j ] == '+' && query) { - buff[idx]= (byte)' ' ; - } else if( buff[ j ] != '%' ) { - buff[idx]= buff[j]; + for (int j = idx; j < end; j++, idx++) { + if (buff[j] == '+' && query) { + buff[idx] = (byte) ' '; + } else if (buff[j] != '%') { + buff[idx] = buff[j]; } else { // read next 2 digits - if( j+2 >= end ) { + if (j + 2 >= end) { throw EXCEPTION_EOF; } - byte b1= buff[j+1]; - byte b2=buff[j+2]; - if( !isHexDigit( b1 ) || ! isHexDigit(b2 )) { + byte b1 = buff[j + 1]; + byte b2 = buff[j + 2]; + if (!isHexDigit(b1) || !isHexDigit(b2)) { throw EXCEPTION_NOT_HEX_DIGIT; } - j+=2; - int res=x2c( b1, b2 ); + j += 2; + int res = x2c(b1, b2); if (res == '/') { switch (encodedSolidusHandling) { - case DECODE: { - buff[idx]=(byte)res; - break; - } - case REJECT: { - throw EXCEPTION_SLASH; - } - case PASS_THROUGH: { - buff[idx++] = buff[j-2]; - buff[idx++] = buff[j-1]; - buff[idx] = buff[j]; - } + case DECODE: { + buff[idx] = (byte) res; + break; + } + case REJECT: { + throw EXCEPTION_SLASH; + } + case PASS_THROUGH: { + buff[idx++] = buff[j - 2]; + buff[idx++] = buff[j - 1]; + buff[idx] = buff[j]; + } } } else { - buff[idx]=(byte)res; + buff[idx] = (byte) res; } } } - mb.setEnd( idx ); + mb.setEnd(idx); } // -------------------- Additional methods -------------------- /** - * Decode and return the specified URL-encoded String. It is assumed the - * string is not a query string. + * Decode and return the specified URL-encoded String. It is assumed the string is not a query string. * - * @param str The url-encoded string + * @param str The url-encoded string * @param charset The character encoding to use; if null, UTF-8 is used. + * * @return the decoded string - * @exception IllegalArgumentException if a '%' character is not followed - * by a valid 2-digit hexadecimal number + * + * @exception IllegalArgumentException if a '%' character is not followed by a valid 2-digit hexadecimal number */ public static String URLDecode(String str, Charset charset) { if (str == null) { @@ -191,16 +185,13 @@ public final class UDecoder { * * Potential complications: * - * - The source String may be partially decoded so it is not valid to - * assume that the source String is ASCII. + * - The source String may be partially decoded so it is not valid to assume that the source String is ASCII. * - * - Have to process as characters since there is no guarantee that the - * byte sequence for '%' is going to be the same in all character - * sets. + * - Have to process as characters since there is no guarantee that the byte sequence for '%' is going to be the + * same in all character sets. * - * - We don't know how many '%nn' sequences are required for a single - * character. It varies between character sets and some use a variable - * length. + * - We don't know how many '%nn' sequences are required for a single character. It varies between character + * sets and some use a variable length. */ // This isn't perfect but it is a reasonable guess for the size of the @@ -219,16 +210,14 @@ public final class UDecoder { if (c == '%') { osw.flush(); if (ix + 2 > len) { - throw new IllegalArgumentException( - sm.getString("uDecoder.urlDecode.missingDigit", str)); + throw new IllegalArgumentException(sm.getString("uDecoder.urlDecode.missingDigit", str)); } char c1 = sourceChars[ix++]; char c2 = sourceChars[ix++]; if (isHexDigit(c1) && isHexDigit(c2)) { baos.write(x2c(c1, c2)); } else { - throw new IllegalArgumentException( - sm.getString("uDecoder.urlDecode.missingDigit", str)); + throw new IllegalArgumentException(sm.getString("uDecoder.urlDecode.missingDigit", str)); } } else { osw.append(c); @@ -238,35 +227,29 @@ public final class UDecoder { return baos.toString(charset.name()); } catch (IOException ioe) { - throw new IllegalArgumentException( - sm.getString("uDecoder.urlDecode.conversionError", str, charset.name()), ioe); + throw new IllegalArgumentException(sm.getString("uDecoder.urlDecode.conversionError", str, charset.name()), + ioe); } } - private static boolean isHexDigit( int c ) { - return ( ( c>='0' && c<='9' ) || - ( c>='a' && c<='f' ) || - ( c>='A' && c<='F' )); + private static boolean isHexDigit(int c) { + return ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')); } - private static int x2c( byte b1, byte b2 ) { - int digit= (b1>='A') ? ( (b1 & 0xDF)-'A') + 10 : - (b1 -'0'); - digit*=16; - digit +=(b2>='A') ? ( (b2 & 0xDF)-'A') + 10 : - (b2 -'0'); + private static int x2c(byte b1, byte b2) { + int digit = (b1 >= 'A') ? ((b1 & 0xDF) - 'A') + 10 : (b1 - '0'); + digit *= 16; + digit += (b2 >= 'A') ? ((b2 & 0xDF) - 'A') + 10 : (b2 - '0'); return digit; } - private static int x2c( char b1, char b2 ) { - int digit= (b1>='A') ? ( (b1 & 0xDF)-'A') + 10 : - (b1 -'0'); - digit*=16; - digit +=(b2>='A') ? ( (b2 & 0xDF)-'A') + 10 : - (b2 -'0'); + private static int x2c(char b1, char b2) { + int digit = (b1 >= 'A') ? ((b1 & 0xDF) - 'A') + 10 : (b1 - '0'); + digit *= 16; + digit += (b2 >= 'A') ? ((b2 & 0xDF) - 'A') + 10 : (b2 - '0'); return digit; } } diff --git a/java/org/apache/tomcat/util/buf/UEncoder.java b/java/org/apache/tomcat/util/buf/UEncoder.java index e84fd238d2..6f2855f009 100644 --- a/java/org/apache/tomcat/util/buf/UEncoder.java +++ b/java/org/apache/tomcat/util/buf/UEncoder.java @@ -21,20 +21,18 @@ import java.nio.charset.StandardCharsets; import java.util.BitSet; /** - * Efficient implementation of a UTF-8 encoder. - * This class is not thread safe - you need one encoder per thread. - * The encoder will save and recycle the internal objects, avoiding - * garbage. - * - * You can add extra characters that you want preserved, for example - * while encoding a URL you can add "/". + * Efficient implementation of a UTF-8 encoder. This class is not thread safe - you need one encoder per thread. The + * encoder will save and recycle the internal objects, avoiding garbage. You can add extra characters that you want + * preserved, for example while encoding a URL you can add "/". * * @author Costin Manolache */ public final class UEncoder { public enum SafeCharsSet { - WITH_SLASH("/"), DEFAULT(""); + WITH_SLASH("/"), + DEFAULT(""); + private final BitSet safeChars; private BitSet getSafeChars() { @@ -51,11 +49,11 @@ public final class UEncoder { // Not static - the set may differ ( it's better than adding // an extra check for "/", "+", etc - private BitSet safeChars=null; - private C2BConverter c2b=null; - private ByteChunk bb=null; - private CharChunk cb=null; - private CharChunk output=null; + private BitSet safeChars = null; + private C2BConverter c2b = null; + private ByteChunk bb = null; + private CharChunk cb = null; + private CharChunk output = null; /** * Create a UEncoder with an unmodifiable safe character set. @@ -66,76 +64,74 @@ public final class UEncoder { this.safeChars = safeCharsSet.getSafeChars(); } - /** - * URL Encode string, using a specified encoding. - * - * @param s string to be encoded - * @param start the beginning index, inclusive - * @param end the ending index, exclusive - * - * @return A new CharChunk contained the URL encoded string - * - * @throws IOException If an I/O error occurs - */ - public CharChunk encodeURL(String s, int start, int end) - throws IOException { - if (c2b == null) { - bb = new ByteChunk(8); // small enough. - cb = new CharChunk(2); // small enough. - output = new CharChunk(64); // small enough. - c2b = new C2BConverter(StandardCharsets.UTF_8); - } else { - bb.recycle(); - cb.recycle(); - output.recycle(); - } - - for (int i = start; i < end; i++) { - char c = s.charAt(i); - if (safeChars.get(c)) { - output.append(c); - } else { - cb.append(c); - c2b.convert(cb, bb); - - // "surrogate" - UTF is _not_ 16 bit, but 21 !!!! - // ( while UCS is 31 ). Amazing... - if (c >= 0xD800 && c <= 0xDBFF) { - if ((i+1) < end) { - char d = s.charAt(i+1); - if (d >= 0xDC00 && d <= 0xDFFF) { - cb.append(d); - c2b.convert(cb, bb); - i++; - } - } - } - - urlEncode(output, bb); - cb.recycle(); - bb.recycle(); - } - } - - return output; - } - - protected void urlEncode(CharChunk out, ByteChunk bb) - throws IOException { - byte[] bytes = bb.getBuffer(); - for (int j = bb.getStart(); j < bb.getEnd(); j++) { - out.append('%'); - char ch = Character.forDigit((bytes[j] >> 4) & 0xF, 16); - out.append(ch); - ch = Character.forDigit(bytes[j] & 0xF, 16); - out.append(ch); - } - } + /** + * URL Encode string, using a specified encoding. + * + * @param s string to be encoded + * @param start the beginning index, inclusive + * @param end the ending index, exclusive + * + * @return A new CharChunk contained the URL encoded string + * + * @throws IOException If an I/O error occurs + */ + public CharChunk encodeURL(String s, int start, int end) throws IOException { + if (c2b == null) { + bb = new ByteChunk(8); // small enough. + cb = new CharChunk(2); // small enough. + output = new CharChunk(64); // small enough. + c2b = new C2BConverter(StandardCharsets.UTF_8); + } else { + bb.recycle(); + cb.recycle(); + output.recycle(); + } + + for (int i = start; i < end; i++) { + char c = s.charAt(i); + if (safeChars.get(c)) { + output.append(c); + } else { + cb.append(c); + c2b.convert(cb, bb); + + // "surrogate" - UTF is _not_ 16 bit, but 21 !!!! + // ( while UCS is 31 ). Amazing... + if (c >= 0xD800 && c <= 0xDBFF) { + if ((i + 1) < end) { + char d = s.charAt(i + 1); + if (d >= 0xDC00 && d <= 0xDFFF) { + cb.append(d); + c2b.convert(cb, bb); + i++; + } + } + } + + urlEncode(output, bb); + cb.recycle(); + bb.recycle(); + } + } + + return output; + } + + protected void urlEncode(CharChunk out, ByteChunk bb) throws IOException { + byte[] bytes = bb.getBuffer(); + for (int j = bb.getStart(); j < bb.getEnd(); j++) { + out.append('%'); + char ch = Character.forDigit((bytes[j] >> 4) & 0xF, 16); + out.append(ch); + ch = Character.forDigit(bytes[j] & 0xF, 16); + out.append(ch); + } + } // -------------------- Internal implementation -------------------- private static BitSet initialSafeChars() { - BitSet initialSafeChars=new BitSet(128); + BitSet initialSafeChars = new BitSet(128); int i; for (i = 'a'; i <= 'z'; i++) { initialSafeChars.set(i); @@ -146,7 +142,7 @@ public final class UEncoder { for (i = '0'; i <= '9'; i++) { initialSafeChars.set(i); } - //safe + // safe initialSafeChars.set('$'); initialSafeChars.set('-'); initialSafeChars.set('_'); @@ -154,8 +150,8 @@ public final class UEncoder { // Dangerous: someone may treat this as " " // RFC1738 does allow it, it's not reserved - // initialSafeChars.set('+'); - //extra + // initialSafeChars.set('+'); + // extra initialSafeChars.set('!'); initialSafeChars.set('*'); initialSafeChars.set('\''); diff --git a/java/org/apache/tomcat/util/buf/UriUtil.java b/java/org/apache/tomcat/util/buf/UriUtil.java index 818566abae..0ba60103a1 100644 --- a/java/org/apache/tomcat/util/buf/UriUtil.java +++ b/java/org/apache/tomcat/util/buf/UriUtil.java @@ -30,7 +30,7 @@ import java.util.regex.Pattern; public final class UriUtil { private static final char[] HEX = - {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; + { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private static final Pattern PATTERN_EXCLAMATION_MARK = Pattern.compile("!/"); private static final Pattern PATTERN_ASTERISK = Pattern.compile("\\*/"); @@ -70,8 +70,7 @@ public final class UriUtil { /** - * Determine if the character is allowed in the scheme of a URI. - * See RFC 2396, Section 3.1 + * Determine if the character is allowed in the scheme of a URI. See RFC 2396, Section 3.1 * * @param c The character to test * @@ -92,11 +91,11 @@ public final class UriUtil { */ public static boolean hasScheme(CharSequence uri) { int len = uri.length(); - for(int i=0; i < len ; i++) { + for (int i = 0; i < len; i++) { char c = uri.charAt(i); - if(c == ':') { + if (c == ':') { return i > 0; - } else if(!UriUtil.isSchemeChar(c)) { + } else if (!UriUtil.isSchemeChar(c)) { return false; } } @@ -150,20 +149,16 @@ public final class UriUtil { /* - * When testing on markt's desktop each iteration was taking ~1420ns when - * using String.replaceAll(). + * When testing on markt's desktop each iteration was taking ~1420ns when using String.replaceAll(). * - * Switching the implementation to use pre-compiled patterns and - * Pattern.matcher(input).replaceAll(replacement) reduced this by ~10%. + * Switching the implementation to use pre-compiled patterns and Pattern.matcher(input).replaceAll(replacement) + * reduced this by ~10%. * - * Note: Given the very small absolute time of a single iteration, even for - * a web application with 1000 JARs this is only going to add ~3ms. - * It is therefore unlikely that further optimisation will be - * necessary. + * Note: Given the very small absolute time of a single iteration, even for a web application with 1000 JARs this is + * only going to add ~3ms. It is therefore unlikely that further optimisation will be necessary. */ /* - * Pulled out into a separate method in case we need to handle other unusual - * sequences in the future. + * Pulled out into a separate method in case we need to handle other unusual sequences in the future. */ private static String makeSafeForJarUrl(String input) { // Since "!/" has a special meaning in a JAR URL, make sure that the @@ -179,8 +174,7 @@ public final class UriUtil { /** - * Convert a URL of the form <code>war:file:...</code> to - * <code>jar:file:...</code>. + * Convert a URL of the form <code>war:file:...</code> to <code>jar:file:...</code>. * * @param warUrl The WAR URL to convert * @@ -212,13 +206,11 @@ public final class UriUtil { /** - * Does the provided path start with <code>file:/</code> or - * <code><protocol>://</code>. + * Does the provided path start with <code>file:/</code> or <code><protocol>://</code>. * * @param path The path to test * - * @return {@code true} if the supplied path starts with once of the - * recognised sequences. + * @return {@code true} if the supplied path starts with once of the recognised sequences. */ public static boolean isAbsoluteURI(String path) { // Special case as only a single / @@ -247,29 +239,24 @@ public final class UriUtil { /** - * Replicates the behaviour of {@link URI#resolve(String)} and adds support - * for URIs of the form {@code jar:file:/... }. + * Replicates the behaviour of {@link URI#resolve(String)} and adds support for URIs of the form + * {@code jar:file:/... }. * - * @param base The base URI to resolve against - * @param target The path to resolve + * @param base The base URI to resolve against + * @param target The path to resolve * - * @return The resulting URI as per {@link URI#resolve(String)} + * @return The resulting URI as per {@link URI#resolve(String)} * - * @throws MalformedURLException - * If the base URI cannot be converted to a URL - * @throws URISyntaxException - * If the resulting URL cannot be converted to a URI + * @throws MalformedURLException If the base URI cannot be converted to a URL + * @throws URISyntaxException If the resulting URL cannot be converted to a URI */ public static URI resolve(URI base, String target) throws MalformedURLException, URISyntaxException { if (base.getScheme().equals("jar")) { /* - * Previously used: - * new URL(base.toURL(), target).toURI() - * This delegated the work to the jar stream handler which correctly - * resolved the target against the base. + * Previously used: new URL(base.toURL(), target).toURI() This delegated the work to the jar stream handler + * which correctly resolved the target against the base. * - * Deprecation of all the URL constructors mean a different approach - * is required. + * Deprecation of all the URL constructors mean a different approach is required. */ URI fileUri = new URI(base.getSchemeSpecificPart()); URI fileUriResolved = fileUri.resolve(target); diff --git a/java/org/apache/tomcat/util/buf/Utf8Encoder.java b/java/org/apache/tomcat/util/buf/Utf8Encoder.java index e3795b2ec0..b6fea536df 100644 --- a/java/org/apache/tomcat/util/buf/Utf8Encoder.java +++ b/java/org/apache/tomcat/util/buf/Utf8Encoder.java @@ -23,8 +23,7 @@ import java.nio.charset.CoderResult; import java.nio.charset.StandardCharsets; /** - * Encodes characters as bytes using UTF-8. Extracted from Apache Harmony with - * some minor bug fixes applied. + * Encodes characters as bytes using UTF-8. Extracted from Apache Harmony with some minor bug fixes applied. */ public class Utf8Encoder extends CharsetEncoder { --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org For additional commands, e-mail: dev-h...@tomcat.apache.org