This is an automated email from the ASF dual-hosted git repository. markt pushed a commit to branch 8.5.x in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit 4fa51315990cf8a8f843aa0b1f3d34bd2deb54d1 Author: Mark Thomas <ma...@apache.org> AuthorDate: Wed Jun 7 17:59:53 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 | 42 +-- .../apache/tomcat/util/buf/ByteBufferHolder.java | 7 +- .../apache/tomcat/util/buf/ByteBufferUtils.java | 35 +-- 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 | 81 +++-- java/org/apache/tomcat/util/buf/CharsetCache.java | 9 +- java/org/apache/tomcat/util/buf/HexUtils.java | 32 +- java/org/apache/tomcat/util/buf/MessageBytes.java | 341 ++++++++++---------- java/org/apache/tomcat/util/buf/StringCache.java | 102 +++--- java/org/apache/tomcat/util/buf/StringUtils.java | 21 +- java/org/apache/tomcat/util/buf/UDecoder.java | 344 ++++++++++----------- java/org/apache/tomcat/util/buf/UEncoder.java | 160 +++++----- java/org/apache/tomcat/util/buf/UriUtil.java | 61 ++-- java/org/apache/tomcat/util/buf/Utf8Decoder.java | 53 ++-- java/org/apache/tomcat/util/buf/Utf8Encoder.java | 3 +- 20 files changed, 700 insertions(+), 789 deletions(-) diff --git a/java/org/apache/tomcat/util/buf/AbstractChunk.java b/java/org/apache/tomcat/util/buf/AbstractChunk.java index 1573fd4473..7bd7001181 100644 --- a/java/org/apache/tomcat/util/buf/AbstractChunk.java +++ b/java/org/apache/tomcat/util/buf/AbstractChunk.java @@ -26,10 +26,9 @@ public abstract class AbstractChunk implements Cloneable, Serializable { private static final long serialVersionUID = 1L; /* - * 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; @@ -45,10 +44,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 9d72234759..923ed66f9a 100644 --- a/java/org/apache/tomcat/util/buf/B2CConverter.java +++ b/java/org/apache/tomcat/util/buf/B2CConverter.java @@ -34,8 +34,7 @@ import org.apache.tomcat.util.res.StringManager; */ public class B2CConverter { - private static final StringManager sm = - StringManager.getManager(Constants.Package); + private static final StringManager sm = StringManager.getManager(Constants.Package); private static final CharsetCache charsetCache = new CharsetCache(); @@ -50,11 +49,9 @@ 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 { + public static Charset getCharset(String enc) throws UnsupportedEncodingException { // Encoding names should all be ASCII String lowerCaseEnc = enc.toLowerCase(Locale.ENGLISH); @@ -65,26 +62,23 @@ public class B2CConverter { /** * Only to be used when it is known that the encoding name is in lower case. - * @param lowerCaseEnc The name of the encoding for the required charset in - * lower case + * + * @param lowerCaseEnc The name of the encoding for the required charset in lower case * * @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 * * @deprecated Will be removed in Tomcat 9.0.x */ @Deprecated - public static Charset getCharsetLower(String lowerCaseEnc) - throws UnsupportedEncodingException { + public static Charset getCharsetLower(String lowerCaseEnc) throws UnsupportedEncodingException { Charset charset = charsetCache.getCharset(lowerCaseEnc); 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; } @@ -135,14 +129,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()); @@ -153,8 +146,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); @@ -204,10 +196,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 093723055a..8a991d8fab 100644 --- a/java/org/apache/tomcat/util/buf/ByteBufferUtils.java +++ b/java/org/apache/tomcat/util/buf/ByteBufferUtils.java @@ -28,8 +28,7 @@ import org.apache.tomcat.util.res.StringManager; public class ByteBufferUtils { - private static final StringManager sm = - StringManager.getManager(Constants.Package); + private static final StringManager sm = StringManager.getManager(Constants.Package); private static final Log log = LogFactory.getLog(ByteBufferUtils.class); private static final Object unsafe; @@ -51,9 +50,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; @@ -65,8 +63,8 @@ public class ByteBufferUtils { Object cleanerObject = cleanerMethodLocal.invoke(tempBuffer); cleanMethodLocal = cleanerObject.getClass().getMethod("clean"); cleanMethodLocal.invoke(cleanerObject); - } catch (NoSuchMethodException | SecurityException | IllegalAccessException | - IllegalArgumentException | InvocationTargetException e) { + } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | + InvocationTargetException e) { log.warn(sm.getString("byteBufferUtils.cleaner"), e); cleanerMethodLocal = null; cleanMethodLocal = null; @@ -84,15 +82,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) { @@ -123,8 +120,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); } @@ -132,8 +129,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 007330a250..a1a65cfdbc 100644 --- a/java/org/apache/tomcat/util/buf/ByteChunk.java +++ b/java/org/apache/tomcat/util/buf/ByteChunk.java @@ -44,23 +44,19 @@ import org.apache.tomcat.util.res.StringManager; // 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] @@ -72,9 +68,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 { @@ -89,30 +83,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; @@ -123,9 +115,8 @@ public final class ByteChunk extends AbstractChunk { private static final StringManager sm = StringManager.getManager(ByteChunk.class); /** - * 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; @@ -193,7 +184,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 */ @@ -246,9 +237,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 */ @@ -282,6 +272,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 { @@ -334,6 +325,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 { @@ -424,14 +416,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 substract(ByteBuffer to) throws IOException { @@ -462,16 +454,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; @@ -479,8 +471,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 */ @@ -575,8 +567,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 @@ -601,8 +593,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; @@ -675,10 +667,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 @@ -700,10 +691,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 @@ -731,16 +721,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); @@ -749,17 +738,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; @@ -776,15 +764,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; @@ -799,15 +786,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; @@ -824,10 +810,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 e5062defb7..8082c09300 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 e6fd9559e1..9b78408c24 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,8 +326,8 @@ 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 */ @@ -343,8 +342,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 */ @@ -425,8 +424,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; @@ -448,8 +447,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; @@ -495,8 +494,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) { @@ -518,7 +517,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 @@ -540,8 +539,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) { @@ -572,14 +571,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); @@ -588,15 +586,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; @@ -653,8 +651,7 @@ public final class CharChunk extends AbstractChunk implements CharSequence { * * @param optimizedWrite Ignored * - * @deprecated Unused code. This is now a NO-OP and will be removed without - * replacement in Tomcat 10. + * @deprecated Unused code. This is now a NO-OP and will be removed without replacement in Tomcat 10. */ @Deprecated public void setOptimizedWrite(boolean optimizedWrite) { 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/HexUtils.java b/java/org/apache/tomcat/util/buf/HexUtils.java index 379217f856..794658e351 100644 --- a/java/org/apache/tomcat/util/buf/HexUtils.java +++ b/java/org/apache/tomcat/util/buf/HexUtils.java @@ -19,37 +19,31 @@ 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 */ public final class HexUtils { - private static final StringManager sm = - StringManager.getManager(Constants.Package); + private static final StringManager sm = StringManager.getManager(Constants.Package); // -------------------------------------------------------------- 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' }; /** @@ -97,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(); @@ -119,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 9203d1049b..76ebee4c1b 100644 --- a/java/org/apache/tomcat/util/buf/MessageBytes.java +++ b/java/org/apache/tomcat/util/buf/MessageBytes.java @@ -26,12 +26,11 @@ import java.util.Locale; import org.apache.tomcat.util.res.StringManager; /** - * 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] @@ -48,44 +47,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() { @@ -105,50 +100,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; @@ -163,6 +159,7 @@ public final class MessageBytes implements Cloneable, Serializable { /** * Compute the string value. + * * @return the string */ @Override @@ -185,10 +182,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() { @@ -196,8 +193,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() { @@ -205,8 +203,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() { @@ -214,8 +213,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() { @@ -231,6 +230,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,8 +279,7 @@ public final class MessageBytes implements Cloneable, Serializable { /** * Simple conversion of chars to bytes. * - * @throws IllegalArgumentException if any of the characters to convert are - * above code point 0xFF. + * @throws IllegalArgumentException if any of the characters to convert are above code point 0xFF. */ private void toBytesSimple(char[] chars, int start, int len) { byte[] bytes = new byte[len]; @@ -302,9 +301,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) { @@ -329,22 +327,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(); @@ -354,43 +352,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; } } @@ -404,31 +406,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; @@ -437,66 +438,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; } } @@ -504,47 +505,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()); } @@ -553,10 +555,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) { @@ -591,42 +594,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 an 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 d922a3e75a..3ba1e6eebf 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(); @@ -261,15 +257,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; } @@ -282,8 +275,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++; @@ -296,8 +288,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 @@ -348,8 +339,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(); @@ -378,15 +368,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; } @@ -399,8 +386,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++; @@ -413,8 +399,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; @@ -447,8 +432,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) { @@ -481,15 +468,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; @@ -498,16 +485,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; @@ -550,8 +537,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) { @@ -584,9 +573,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) { @@ -600,16 +590,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; @@ -619,7 +609,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) { @@ -663,10 +653,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) { @@ -690,10 +682,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 9c9a6b2ef0..6e207da874 100644 --- a/java/org/apache/tomcat/util/buf/StringUtils.java +++ b/java/org/apache/tomcat/util/buf/StringUtils.java @@ -20,10 +20,9 @@ import java.util.Arrays; import java.util.Collection; /** - * 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 { @@ -68,13 +67,16 @@ public final class StringUtils { public static void join(Iterable<String> iterable, char separator, StringBuilder sb) { - join(iterable, separator, - new Function<String>() {@Override public String apply(String t) { return t; }}, sb); + join(iterable, separator, new Function<String>() { + @Override + public String apply(String t) { + return t; + } + }, sb); } - public static <T> void join(T[] array, char separator, Function<T> function, - StringBuilder sb) { + public static <T> void join(T[] array, char separator, Function<T> function, StringBuilder sb) { if (array == null) { return; } @@ -82,8 +84,7 @@ public final class StringUtils { } - public static <T> void join(Iterable<T> iterable, char separator, Function<T> function, - StringBuilder sb) { + public static <T> void join(Iterable<T> iterable, char separator, Function<T> 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 c647ccb397..bf738ed7f8 100644 --- a/java/org/apache/tomcat/util/buf/UDecoder.java +++ b/java/org/apache/tomcat/util/buf/UDecoder.java @@ -29,12 +29,10 @@ import org.apache.juli.logging.LogFactory; 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 { @@ -43,11 +41,12 @@ public final class UDecoder { private static final Log log = LogFactory.getLog(UDecoder.class); @Deprecated - public static final boolean ALLOW_ENCODED_SLASH = - Boolean.parseBoolean(System.getProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "false")); + public static final boolean ALLOW_ENCODED_SLASH = Boolean + .parseBoolean(System.getProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "false")); private static class DecodeException extends CharConversionException { private static final long serialVersionUID = 1L; + DecodeException(String s) { super(s); } @@ -63,22 +62,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 */ @@ -92,14 +87,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. - * - * @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 + * 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 + * * @throws IOException Invalid %xx URL encoding */ public void convert(ByteChunk mb, EncodedSolidusHandling encodedSolidusHandling) throws IOException { @@ -107,66 +100,67 @@ 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); } @@ -177,63 +171,62 @@ public final class UDecoder { * <p> * <b>WARNING:</b> This method assumes US-ASCII encoding. * - * @param mb The URL encoded chars + * @param mb The URL encoded chars * @param query <code>true</code> if this is a query string + * * @throws IOException Invalid %xx URL encoding * * @deprecated Unused. Will be removed in Tomcat 10 */ @Deprecated - public void convert( CharChunk mb, boolean query ) - throws IOException - { - // log( "Converting a char chunk "); - int start=mb.getOffset(); - char buff[]=mb.getBuffer(); - int cend=mb.getEnd(); - - int idx= CharChunk.indexOf( buff, start, cend, '%' ); - int idx2=-1; - if( query ) { - idx2= CharChunk.indexOf( buff, start, (idx >= 0 ? idx : cend), '+' ); + public void convert(CharChunk mb, boolean query) throws IOException { + // log( "Converting a char chunk "); + int start = mb.getOffset(); + char buff[] = mb.getBuffer(); + int cend = mb.getEnd(); + + int idx = CharChunk.indexOf(buff, start, cend, '%'); + int idx2 = -1; + if (query) { + idx2 = CharChunk.indexOf(buff, start, (idx >= 0 ? idx : cend), '+'); } - 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; } final boolean noSlash = !(ALLOW_ENCODED_SLASH || query); - for( int j=idx; j<cend; j++, idx++ ) { - if( buff[ j ] == '+' && query ) { - buff[idx]=( ' ' ); - } else if( buff[ j ] != '%' ) { - buff[idx]=buff[j]; + for (int j = idx; j < cend; j++, idx++) { + if (buff[j] == '+' && query) { + buff[idx] = (' '); + } else if (buff[j] != '%') { + buff[idx] = buff[j]; } else { // read next 2 digits - if( j+2 >= cend ) { + if (j + 2 >= cend) { // invalid throw EXCEPTION_EOF; } - char b1= buff[j+1]; - char b2=buff[j+2]; - if( !isHexDigit( b1 ) || ! isHexDigit(b2 )) { + char b1 = buff[j + 1]; + char 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 (noSlash && (res == '/')) { throw EXCEPTION_SLASH; } - buff[idx]=(char)res; + buff[idx] = (char) res; } } - mb.setEnd( idx ); + mb.setEnd(idx); } /** @@ -241,37 +234,36 @@ public final class UDecoder { * <p> * <b>WARNING:</b> This method assumes US-ASCII encoding. * - * @param mb The URL encoded String, bytes or chars + * @param mb The URL encoded String, bytes or chars * @param query <code>true</code> if this is a query string + * * @throws IOException Invalid %xx URL encoding * * @deprecated Unused. Will be removed in Tomcat 10 */ @Deprecated - public void convert(MessageBytes mb, boolean query) - throws IOException - { + public void convert(MessageBytes mb, boolean query) throws IOException { switch (mb.getType()) { - case MessageBytes.T_STR: - String strValue=mb.toString(); - if( strValue==null ) { - return; - } - try { - mb.setString( convert( strValue, query )); - } catch (RuntimeException ex) { - throw new DecodeException(ex.getMessage()); - } - break; - case MessageBytes.T_CHARS: - CharChunk charC=mb.getCharChunk(); - convert( charC, query ); - break; - case MessageBytes.T_BYTES: - ByteChunk bytesC=mb.getByteChunk(); - convert( bytesC, query ); - break; + case MessageBytes.T_STR: + String strValue = mb.toString(); + if (strValue == null) { + return; + } + try { + mb.setString(convert(strValue, query)); + } catch (RuntimeException ex) { + throw new DecodeException(ex.getMessage()); + } + break; + case MessageBytes.T_CHARS: + CharChunk charC = mb.getCharChunk(); + convert(charC, query); + break; + case MessageBytes.T_BYTES: + ByteChunk bytesC = mb.getByteChunk(); + convert(bytesC, query); + break; } } @@ -282,32 +274,32 @@ public final class UDecoder { * <p> * FIXME: this is inefficient. * - * @param str The URL encoded string + * @param str The URL encoded string * @param query <code>true</code> if this is a query string + * * @return the decoded string * * @deprecated Unused. Will be removed in Tomcat 10 */ @Deprecated - public String convert(String str, boolean query) - { + public String convert(String str, boolean query) { if (str == null) { - return null; + return null; } - if( (!query || str.indexOf( '+' ) < 0) && str.indexOf( '%' ) < 0 ) { + if ((!query || str.indexOf('+') < 0) && str.indexOf('%') < 0) { return str; } final boolean noSlash = !(ALLOW_ENCODED_SLASH || query); - StringBuilder dec = new StringBuilder(); // decoded string output + StringBuilder dec = new StringBuilder(); // decoded string output int strPos = 0; int strLen = str.length(); dec.ensureCapacity(str.length()); while (strPos < strLen) { - int laPos; // lookahead position + int laPos; // lookahead position // look ahead to next URLencoded metacharacter, if any for (laPos = strPos; laPos < strLen; laPos++) { @@ -319,7 +311,7 @@ public final class UDecoder { // if there were non-metacharacters, copy them all as a block if (laPos > strPos) { - dec.append(str.substring(strPos,laPos)); + dec.append(str.substring(strPos, laPos)); strPos = laPos; } @@ -337,9 +329,8 @@ public final class UDecoder { } else if (metaChar == '%') { // We throw the original exception - the super will deal with // it - // try { - char res = (char) Integer.parseInt( - str.substring(strPos + 1, strPos + 3), 16); + // try { + char res = (char) Integer.parseInt(str.substring(strPos + 1, strPos + 3), 16); if (noSlash && (res == '/')) { throw new IllegalArgumentException(sm.getString("uDecoder.noSlash")); } @@ -353,15 +344,14 @@ public final class UDecoder { /** - * Decode and return the specified URL-encoded String. - * When the byte array is converted to a string, ISO-885901 is used. This - * may be different than some other servers. It is assumed the string is not - * a query string. + * Decode and return the specified URL-encoded String. When the byte array is converted to a string, ISO-885901 is + * used. This may be different than some other servers. It is assumed the string is not a query string. * * @param str The url-encoded string + * * @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 * * @deprecated Unused. This will be removed in Tomcat 10 onwards */ @@ -372,15 +362,15 @@ public final class UDecoder { /** - * 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 enc The encoding to use; if null, ISO-885901 is used. If - * an unsupported encoding is specified null will be returned + * @param enc The encoding to use; if null, ISO-885901 is used. If an unsupported encoding is specified null will be + * returned + * * @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 * * @deprecated This method will be removed in Tomcat 9 */ @@ -391,15 +381,14 @@ public final class UDecoder { /** - * 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 charset The character encoding to use; if null, ISO-8859-1 is used. * - * @param str The url-encoded string - * @param charset The character encoding to use; if null, ISO-8859-1 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) { return URLDecode(str, charset, false); @@ -409,13 +398,14 @@ public final class UDecoder { /** * Decode and return the specified URL-encoded String. * - * @param str The url-encoded string - * @param enc The encoding to use; if null, ISO-8859-1 is used. If - * an unsupported encoding is specified null will be returned + * @param str The url-encoded string + * @param enc The encoding to use; if null, ISO-8859-1 is used. If an unsupported encoding is specified null + * will be returned * @param isQuery Is this a query string being processed + * * @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 * * @deprecated This method will be removed in Tomcat 9 */ @@ -440,13 +430,14 @@ public final class UDecoder { /** * Decode and return the specified URL-encoded byte array. * - * @param bytes The url-encoded byte array - * @param enc The encoding to use; if null, ISO-8859-1 is used. If - * an unsupported encoding is specified null will be returned + * @param bytes The url-encoded byte array + * @param enc The encoding to use; if null, ISO-8859-1 is used. If an unsupported encoding is specified null + * will be returned * @param isQuery Is this a query string being processed + * * @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 * * @deprecated This method will be removed in Tomcat 9 */ @@ -476,16 +467,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 @@ -504,16 +492,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 if (c == '+' && isQuery) { osw.append(' '); @@ -525,35 +511,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 e8194c06ec..6b9fc75dbe 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 an 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 an 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 63c933ac0f..9ff2be23ec 100644 --- a/java/org/apache/tomcat/util/buf/UriUtil.java +++ b/java/org/apache/tomcat/util/buf/UriUtil.java @@ -29,7 +29,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_CARET = 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; } } @@ -138,20 +137,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 @@ -168,8 +163,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 * @@ -198,13 +192,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 / @@ -233,29 +225,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/Utf8Decoder.java b/java/org/apache/tomcat/util/buf/Utf8Decoder.java index 932e88c764..e637ca3f82 100644 --- a/java/org/apache/tomcat/util/buf/Utf8Decoder.java +++ b/java/org/apache/tomcat/util/buf/Utf8Decoder.java @@ -23,11 +23,9 @@ import java.nio.charset.CoderResult; import java.nio.charset.StandardCharsets; /** - * Decodes bytes to UTF-8. Extracted from Apache Harmony and modified to reject - * code points from U+D800 to U+DFFF as per RFC3629. The standard Java decoder - * does not reject these. It has also been modified to reject code points - * greater than U+10FFFF which the standard Java decoder rejects but the harmony - * one does not. + * Decodes bytes to UTF-8. Extracted from Apache Harmony and modified to reject code points from U+D800 to U+DFFF as per + * RFC3629. The standard Java decoder does not reject these. It has also been modified to reject code points greater + * than U+10FFFF which the standard Java decoder rejects but the harmony one does not. */ public class Utf8Decoder extends CharsetDecoder { @@ -39,32 +37,30 @@ public class Utf8Decoder extends CharsetDecoder { // ------------------------------------------------------------------- // 0 1 2 3 Value // ------------------------------------------------------------------- - // oxxxxxxx 00000000 00000000 0xxxxxxx - // 11oyyyyy 1oxxxxxx 00000000 00000yyy yyxxxxxx - // 111ozzzz 1oyyyyyy 1oxxxxxx 00000000 zzzzyyyy yyxxxxxx + // oxxxxxxx 00000000 00000000 0xxxxxxx + // 11oyyyyy 1oxxxxxx 00000000 00000yyy yyxxxxxx + // 111ozzzz 1oyyyyyy 1oxxxxxx 00000000 zzzzyyyy yyxxxxxx // 1111ouuu 1ouuzzzz 1oyyyyyy 1oxxxxxx 000uuuuu zzzzyyyy yyxxxxxx private static final int remainingBytes[] = { // 1owwwwww - -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, -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, -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, -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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 11oyyyyy - -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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 111ozzzz 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 1111ouuu 3, 3, 3, 3, 3, -1, -1, -1, // > 11110111 - -1, -1, -1, -1, -1, -1, -1, -1}; - private static final int remainingNumbers[] = {0, // 0 1 2 3 + -1, -1, -1, -1, -1, -1, -1, -1 }; + private static final int remainingNumbers[] = { 0, // 0 1 2 3 4224, // (01o00000b << 6)+(1o000000b) 401536, // (011o0000b << 12)+(1o000000b << 6)+(1o000000b) 29892736 // (0111o000b << 18)+(1o000000b << 12)+(1o000000b << // 6)+(1o000000b) }; - private static final int lowerEncodingLimit[] = {-1, 0x80, 0x800, 0x10000}; + private static final int lowerEncodingLimit[] = { -1, 0x80, 0x800, 0x10000 }; public Utf8Decoder() { @@ -173,8 +169,7 @@ public class Utf8Decoder extends CharsetDecoder { int tailAvailable = inIndexLimit - inIndex - 1; if (tailAvailable > 0) { // First byte C2..DF, second byte 80..BF - if (jchar > 0x41 && jchar < 0x60 && - (bArr[inIndex + 1] & 0xC0) != 0x80) { + if (jchar > 0x41 && jchar < 0x60 && (bArr[inIndex + 1] & 0xC0) != 0x80) { in.position(inIndex - in.arrayOffset()); out.position(outIndex - out.arrayOffset()); return CoderResult.malformedForLength(1); @@ -186,8 +181,7 @@ public class Utf8Decoder extends CharsetDecoder { return CoderResult.malformedForLength(1); } // First byte E1..EC, second byte 80..BF - if (jchar > 0x60 && jchar < 0x6D && - (bArr[inIndex + 1] & 0xC0) != 0x80) { + if (jchar > 0x60 && jchar < 0x6D && (bArr[inIndex + 1] & 0xC0) != 0x80) { in.position(inIndex - in.arrayOffset()); out.position(outIndex - out.arrayOffset()); return CoderResult.malformedForLength(1); @@ -199,30 +193,25 @@ public class Utf8Decoder extends CharsetDecoder { return CoderResult.malformedForLength(1); } // First byte EE..EF, second byte 80..BF - if (jchar > 0x6D && jchar < 0x70 && - (bArr[inIndex + 1] & 0xC0) != 0x80) { + if (jchar > 0x6D && jchar < 0x70 && (bArr[inIndex + 1] & 0xC0) != 0x80) { in.position(inIndex - in.arrayOffset()); out.position(outIndex - out.arrayOffset()); return CoderResult.malformedForLength(1); } // First byte F0, second byte 90..BF - if (jchar == 0x70 && - ((bArr[inIndex + 1] & 0xFF) < 0x90 || - (bArr[inIndex + 1] & 0xFF) > 0xBF)) { + if (jchar == 0x70 && ((bArr[inIndex + 1] & 0xFF) < 0x90 || (bArr[inIndex + 1] & 0xFF) > 0xBF)) { in.position(inIndex - in.arrayOffset()); out.position(outIndex - out.arrayOffset()); return CoderResult.malformedForLength(1); } // First byte F1..F3, second byte 80..BF - if (jchar > 0x70 && jchar < 0x74 && - (bArr[inIndex + 1] & 0xC0) != 0x80) { + if (jchar > 0x70 && jchar < 0x74 && (bArr[inIndex + 1] & 0xC0) != 0x80) { in.position(inIndex - in.arrayOffset()); out.position(outIndex - out.arrayOffset()); return CoderResult.malformedForLength(1); } // First byte F4, second byte 80..8F - if (jchar == 0x74 && - (bArr[inIndex + 1] & 0xF0) != 0x80) { + if (jchar == 0x74 && (bArr[inIndex + 1] & 0xF0) != 0x80) { in.position(inIndex - in.arrayOffset()); out.position(outIndex - out.arrayOffset()); return CoderResult.malformedForLength(1); @@ -292,8 +281,6 @@ public class Utf8Decoder extends CharsetDecoder { } in.position(inIndex - in.arrayOffset()); out.position(outIndex - out.arrayOffset()); - return (outRemaining == 0 && inIndex < inIndexLimit) ? - CoderResult.OVERFLOW : - CoderResult.UNDERFLOW; + return (outRemaining == 0 && inIndex < inIndexLimit) ? CoderResult.OVERFLOW : CoderResult.UNDERFLOW; } } 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