Various cleanups of StringUtil and TypeUtil (#10082)

* Various cleanups of StringUtil and TypeUtil

Removed deprecated and unused methods
Moved charset handling to MimeTypes
resolve IDE warnings

* updates from review
This commit is contained in:
Greg Wilkins 2023-07-12 10:31:28 +02:00 committed by GitHub
parent bd80297f7e
commit 0ee0716d33
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
30 changed files with 249 additions and 454 deletions

View File

@ -28,7 +28,6 @@ import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.util.Attributes;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.TypeUtil;
/**
* Implementation of the HTTP "Digest" authentication defined in RFC 2617.
@ -231,7 +230,7 @@ public class DigestAuthentication extends AbstractAuthentication
private String toHexString(byte[] bytes)
{
return TypeUtil.toHexString(bytes).toLowerCase(Locale.ENGLISH);
return StringUtil.toHexString(bytes).toLowerCase(Locale.ENGLISH);
}
}
}

View File

@ -16,8 +16,10 @@ package org.eclipse.jetty.http;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
@ -40,11 +42,18 @@ public class MimeTypes
{
static final Logger LOG = LoggerFactory.getLogger(MimeTypes.class);
private static final Set<Locale> KNOWN_LOCALES = Set.copyOf(Arrays.asList(Locale.getAvailableLocales()));
public static boolean isKnownLocale(Locale locale)
{
return KNOWN_LOCALES.contains(locale);
}
public static final String ISO_8859_1 = StandardCharsets.ISO_8859_1.name().toLowerCase();
public static final String UTF8 = StandardCharsets.UTF_8.name().toLowerCase();
public static final String UTF16 = StandardCharsets.UTF_16.name().toLowerCase();
private static final Index<String> CHARSETS = new Index.Builder<String>()
.caseSensitive(false)
.with("utf-8", UTF8)
.with("utf8", UTF8)
.with("utf-16", UTF16)
.with("utf16", UTF16)
.with("iso-8859-1", ISO_8859_1)
.with("iso_8859_1", ISO_8859_1)
.build();
/** Enumeration of predefined MimeTypes. This is not exhaustive */
public enum Type
@ -115,9 +124,9 @@ public class MimeTypes
private final boolean _assumedCharset;
private final HttpField _field;
Type(String s)
Type(String name)
{
_string = s;
_string = name;
_base = this;
_charset = null;
_charsetString = null;
@ -125,20 +134,20 @@ public class MimeTypes
_field = new PreEncodedHttpField(HttpHeader.CONTENT_TYPE, _string);
}
Type(String s, Type base)
Type(String name, Type base)
{
_string = s;
_string = name;
_base = base;
int i = s.indexOf(";charset=");
_charset = Charset.forName(s.substring(i + 9));
int i = name.indexOf(";charset=");
_charset = Charset.forName(name.substring(i + 9));
_charsetString = _charset.toString().toLowerCase(Locale.ENGLISH);
_assumedCharset = false;
_field = new PreEncodedHttpField(HttpHeader.CONTENT_TYPE, _string);
}
Type(String s, Charset cs)
Type(String name, Charset cs)
{
_string = s;
_string = name;
_base = this;
_charset = cs;
_charsetString = _charset == null ? null : _charset.toString().toLowerCase(Locale.ENGLISH);
@ -156,9 +165,9 @@ public class MimeTypes
return _charsetString;
}
public boolean is(String s)
public boolean is(String type)
{
return _string.equalsIgnoreCase(s);
return _string.equalsIgnoreCase(type);
}
public String asString()
@ -235,6 +244,62 @@ public class MimeTypes
return null;
}
public static boolean isKnownLocale(Locale locale)
{
return KNOWN_LOCALES.contains(locale);
}
/**
* Convert alternate charset names (eg utf8) to normalized
* name (eg UTF-8).
*
* @param charsetName the charset to normalize
* @return the normalized charset (or null if normalized version not found)
*/
public static String normalizeCharset(String charsetName)
{
String n = CHARSETS.get(charsetName);
return (n == null) ? charsetName : n;
}
/**
* Convert alternate charset names (eg utf8) to normalized
* name (eg UTF-8).
*
* @param charsetName the charset to normalize
* @param offset the offset in the charset
* @param length the length of the charset in the input param
* @return the normalized charset (or null if not found)
*/
public static String normalizeCharset(String charsetName, int offset, int length)
{
String n = CHARSETS.get(charsetName, offset, length);
return (n == null) ? charsetName.substring(offset, offset + length) : n;
}
/**
* @param charsetName The name of the charset
* @return The {@link Charset} for the normalized name
* @throws UnsupportedEncodingException Thrown if the charset is not known to the JVM.
*/
public static Charset getKnownCharset(String charsetName) throws UnsupportedEncodingException
{
// check encoding is supported
if (StandardCharsets.UTF_8.name().equalsIgnoreCase(charsetName))
return StandardCharsets.UTF_8;
charsetName = normalizeCharset(charsetName);
if (StandardCharsets.UTF_8.name().equalsIgnoreCase(charsetName))
return StandardCharsets.UTF_8;
try
{
return Charset.forName(charsetName);
}
catch (UnsupportedCharsetException e)
{
throw new UnsupportedEncodingException(e.getMessage());
}
}
protected final Map<String, String> _mimeMap = new HashMap<>();
protected final Map<String, String> _inferredEncodings = new HashMap<>();
protected final Map<String, String> _assumedEncodings = new HashMap<>();
@ -625,7 +690,7 @@ public class MimeTypes
case 10:
if (!quote && (';' == b || ' ' == b) ||
(quote && '"' == b))
return StringUtil.normalizeCharset(value, start, i - start);
return normalizeCharset(value, start, i - start);
break;
default:
throw new IllegalStateException();
@ -633,7 +698,7 @@ public class MimeTypes
}
if (state == 10)
return StringUtil.normalizeCharset(value, start, i - start);
return normalizeCharset(value, start, i - start);
return null;
}

View File

@ -22,7 +22,6 @@ import org.eclipse.jetty.http.compression.HuffmanDecoder;
import org.eclipse.jetty.http.compression.HuffmanEncoder;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.TypeUtil;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@ -65,7 +64,7 @@ public class HuffmanTest
@MethodSource("data")
public void testDecode(String specSection, String hex, String expected) throws Exception
{
byte[] encoded = TypeUtil.fromHexString(hex);
byte[] encoded = StringUtil.fromHexString(hex);
HuffmanDecoder huffmanDecoder = new HuffmanDecoder();
huffmanDecoder.setLength(encoded.length);
String decoded = huffmanDecoder.decode(ByteBuffer.wrap(encoded));
@ -80,7 +79,8 @@ public class HuffmanTest
int pos = BufferUtil.flipToFill(buf);
HuffmanEncoder.encode(buf, expected);
BufferUtil.flipToFlush(buf, pos);
String encoded = TypeUtil.toHexString(BufferUtil.toArray(buf)).toLowerCase(Locale.ENGLISH);
byte[] b = BufferUtil.toArray(buf);
String encoded = StringUtil.toHexString(b).toLowerCase(Locale.ENGLISH);
assertEquals(hex, encoded, specSection);
assertEquals(hex.length() / 2, HuffmanEncoder.octetsNeeded(expected));
}

View File

@ -17,7 +17,7 @@ import java.nio.ByteBuffer;
import org.eclipse.jetty.http.compression.NBitIntegerDecoder;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.StringUtil;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
@ -32,7 +32,7 @@ public class NBitIntegerParserTest
NBitIntegerDecoder decoder = new NBitIntegerDecoder();
String encoded = "FFBA09";
byte[] bytes = TypeUtil.fromHexString(encoded);
byte[] bytes = StringUtil.fromHexString(encoded);
bytes[0] = (byte)(bytes[0] | 0x80); // set the first bit so it is a section acknowledgement.
ByteBuffer buffer1 = BufferUtil.toBuffer(bytes, 0, 2);
ByteBuffer buffer2 = BufferUtil.toBuffer(bytes, 2, 1);

View File

@ -19,7 +19,6 @@ import org.eclipse.jetty.http.compression.NBitIntegerDecoder;
import org.eclipse.jetty.http.compression.NBitIntegerEncoder;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.TypeUtil;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ -85,7 +84,8 @@ public class NBitIntegerTest
buf.put((byte)0x00);
NBitIntegerEncoder.encode(buf, n, i);
BufferUtil.flipToFlush(buf, p);
String r = TypeUtil.toHexString(BufferUtil.toArray(buf));
byte[] b = BufferUtil.toArray(buf);
String r = StringUtil.toHexString(b);
assertEquals(expected, r);
assertEquals(expected.length() / 2, NBitIntegerEncoder.octetsNeeded(n, i));
@ -125,7 +125,7 @@ public class NBitIntegerTest
public void testDecode(int n, int expected, String encoded)
{
ByteBuffer buf = ByteBuffer.wrap(TypeUtil.fromHexString(encoded));
ByteBuffer buf = ByteBuffer.wrap(StringUtil.fromHexString(encoded));
_decoder.setPrefix(n);
assertEquals(expected, _decoder.decodeInt(buf));
}
@ -140,7 +140,8 @@ public class NBitIntegerTest
NBitIntegerEncoder.encode(buf, 5, 10);
BufferUtil.flipToFlush(buf, p);
String r = TypeUtil.toHexString(BufferUtil.toArray(buf));
byte[] b = BufferUtil.toArray(buf);
String r = StringUtil.toHexString(b);
assertEquals("77Ea", r);
}
@ -148,7 +149,7 @@ public class NBitIntegerTest
@Test
public void testDecodeExampleD11()
{
ByteBuffer buf = ByteBuffer.wrap(TypeUtil.fromHexString("77EaFF"));
ByteBuffer buf = ByteBuffer.wrap(StringUtil.fromHexString("77EaFF"));
buf.position(1);
_decoder.setPrefix(5);
assertEquals(10, _decoder.decodeInt(buf));
@ -171,7 +172,7 @@ public class NBitIntegerTest
@Test
public void testDecodeExampleD12()
{
ByteBuffer buf = ByteBuffer.wrap(TypeUtil.fromHexString("881f9a0aff"));
ByteBuffer buf = ByteBuffer.wrap(StringUtil.fromHexString("881f9a0aff"));
buf.position(1);
_decoder.setPrefix(5);
assertEquals(1337, _decoder.decodeInt(buf));
@ -187,7 +188,8 @@ public class NBitIntegerTest
NBitIntegerEncoder.encode(buf, 8, 42);
BufferUtil.flipToFlush(buf, p);
String r = TypeUtil.toHexString(BufferUtil.toArray(buf));
byte[] b = BufferUtil.toArray(buf);
String r = StringUtil.toHexString(b);
assertEquals("88Ff2a", r);
}
@ -195,7 +197,7 @@ public class NBitIntegerTest
@Test
public void testDecodeExampleD13()
{
ByteBuffer buf = ByteBuffer.wrap(TypeUtil.fromHexString("882aFf"));
ByteBuffer buf = ByteBuffer.wrap(StringUtil.fromHexString("882aFf"));
buf.position(1);
_decoder.setPrefix(8);
assertEquals(42, _decoder.decodeInt(buf));

View File

@ -17,7 +17,7 @@ import java.nio.ByteBuffer;
import org.eclipse.jetty.http3.qpack.internal.parser.EncoderInstructionParser;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.StringUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -42,42 +42,42 @@ public class EncoderInstructionParserTest
{
// Example from the spec, section acknowledgement instruction with stream id 4.
String encoded = "84";
ByteBuffer buffer = BufferUtil.toBuffer(TypeUtil.fromHexString(encoded));
ByteBuffer buffer = BufferUtil.toBuffer(StringUtil.fromHexString(encoded));
_instructionParser.parse(buffer);
assertThat(_handler.sectionAcknowledgements.poll(), is(4L));
assertTrue(_handler.isEmpty());
// 1111 1110 == FE is largest value we can do without continuation should be stream ID 126.
encoded = "FE";
buffer = BufferUtil.toBuffer(TypeUtil.fromHexString(encoded));
buffer = BufferUtil.toBuffer(StringUtil.fromHexString(encoded));
_instructionParser.parse(buffer);
assertThat(_handler.sectionAcknowledgements.poll(), is(126L));
assertTrue(_handler.isEmpty());
// 1111 1111 0000 0000 == FF00 is next value, stream id 127.
encoded = "FF00";
buffer = BufferUtil.toBuffer(TypeUtil.fromHexString(encoded));
buffer = BufferUtil.toBuffer(StringUtil.fromHexString(encoded));
_instructionParser.parse(buffer);
assertThat(_handler.sectionAcknowledgements.poll(), is(127L));
assertTrue(_handler.isEmpty());
// 1111 1111 0000 0001 == FF01 is next value, stream id 128.
encoded = "FF01";
buffer = BufferUtil.toBuffer(TypeUtil.fromHexString(encoded));
buffer = BufferUtil.toBuffer(StringUtil.fromHexString(encoded));
_instructionParser.parse(buffer);
assertThat(_handler.sectionAcknowledgements.poll(), is(128L));
assertTrue(_handler.isEmpty());
// FFBA09 contains section ack with stream ID of 1337, this contains an octet with continuation bit.
encoded = "FFBA09";
buffer = BufferUtil.toBuffer(TypeUtil.fromHexString(encoded));
buffer = BufferUtil.toBuffer(StringUtil.fromHexString(encoded));
_instructionParser.parse(buffer);
assertThat(_handler.sectionAcknowledgements.poll(), is(1337L));
assertTrue(_handler.isEmpty());
// Test with continuation.
encoded = "FFBA09";
byte[] bytes = TypeUtil.fromHexString(encoded);
byte[] bytes = StringUtil.fromHexString(encoded);
for (int i = 0; i < 10; i++)
{
ByteBuffer buffer1 = BufferUtil.toBuffer(bytes, 0, 2);

View File

@ -23,7 +23,7 @@ import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.http.MetaData;
import org.eclipse.jetty.io.ByteBufferPool;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.StringUtil;
import org.hamcrest.Matcher;
import static org.hamcrest.MatcherAssert.assertThat;
@ -71,7 +71,7 @@ public class QpackTestUtil
public static ByteBuffer hexToBuffer(String hexString)
{
hexString = hexString.replaceAll("\\s+", "");
return ByteBuffer.wrap(TypeUtil.fromHexString(hexString));
return ByteBuffer.wrap(StringUtil.fromHexString(hexString));
}
public static String toHexString(Instruction instruction)

View File

@ -41,6 +41,7 @@ import javax.security.auth.login.LoginException;
import org.eclipse.jetty.security.UserPrincipal;
import org.eclipse.jetty.security.jaas.callback.ObjectCallback;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.security.Credential;
import org.slf4j.Logger;
@ -750,7 +751,7 @@ public class LdapLoginModule extends AbstractLoginModule
private static String hexToBase64(String src)
{
byte[] bytes = TypeUtil.fromHexString(src);
byte[] bytes = StringUtil.fromHexString(src);
return Base64.getEncoder().encodeToString(bytes);
}
}

View File

@ -22,7 +22,7 @@ import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.logging.StacklessLogging;
import org.eclipse.jetty.server.handler.DumpHandler;
import org.eclipse.jetty.toolchain.test.Net;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.StringUtil;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.params.ParameterizedTest;
@ -138,7 +138,7 @@ public class ProxyConnectionTest
"Connection: close\n" +
"\n";
String response = p.sendRequestWaitingForResponse(TypeUtil.fromHexString(proxy), http.getBytes(StandardCharsets.US_ASCII));
String response = p.sendRequestWaitingForResponse(StringUtil.fromHexString(proxy), http.getBytes(StandardCharsets.US_ASCII));
assertThat(response, Matchers.containsString("HTTP/1.1 200"));
assertThat(response, Matchers.containsString("pathInContext=/path"));
@ -171,7 +171,7 @@ public class ProxyConnectionTest
"Connection: close\n" +
"\n";
String response = p.sendRequestWaitingForResponse(TypeUtil.fromHexString(proxy), http.getBytes(StandardCharsets.US_ASCII));
String response = p.sendRequestWaitingForResponse(StringUtil.fromHexString(proxy), http.getBytes(StandardCharsets.US_ASCII));
assertThat(response, Matchers.containsString("HTTP/1.1 200"));
assertThat(response, Matchers.containsString("pathInContext=/path"));
@ -261,7 +261,7 @@ public class ProxyConnectionTest
"Connection: close\n" +
"\n";
String response = p.sendRequestWaitingForResponse(TypeUtil.fromHexString(proxy), http.getBytes(StandardCharsets.US_ASCII));
String response = p.sendRequestWaitingForResponse(StringUtil.fromHexString(proxy), http.getBytes(StandardCharsets.US_ASCII));
assertThat(response, Matchers.containsString("HTTP/1.1 200"));
assertThat(response, Matchers.containsString("pathInContext=/path"));
@ -302,7 +302,7 @@ public class ProxyConnectionTest
"Connection: close\n" +
"\n";
String response = p.sendRequestWaitingForResponse(TypeUtil.fromHexString(proxy), http.getBytes(StandardCharsets.US_ASCII));
String response = p.sendRequestWaitingForResponse(StringUtil.fromHexString(proxy), http.getBytes(StandardCharsets.US_ASCII));
assertThat(response, Matchers.is(Matchers.nullValue()));
}

View File

@ -25,7 +25,7 @@ import java.util.ArrayList;
import java.util.Collections;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.StringUtil;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@ -42,7 +42,7 @@ public class ProxyCustomizerTest
try (Socket socket = new Socket(server.getURI().getHost(), server.getURI().getPort()))
{
OutputStream output = socket.getOutputStream();
output.write(TypeUtil.fromHexString(proxyAsHexString));
output.write(StringUtil.fromHexString(proxyAsHexString));
output.write(rawHttp.getBytes(StandardCharsets.UTF_8));
output.flush();
socket.shutdownOutput();

View File

@ -26,7 +26,7 @@ import java.util.Arrays;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.server.internal.HttpConnection;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.StringUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
@ -192,7 +192,7 @@ public class ProxyProtocolTest
"Host: localhost\r\n" +
"\r\n";
OutputStream output = socket.getOutputStream();
output.write(TypeUtil.fromHexString(proxy));
output.write(StringUtil.fromHexString(proxy));
output.write(request1.getBytes(StandardCharsets.UTF_8));
output.flush();
@ -270,7 +270,7 @@ public class ProxyProtocolTest
"Host: localhost\r\n" +
"\r\n";
OutputStream output = socket.getOutputStream();
output.write(TypeUtil.fromHexString(proxy));
output.write(StringUtil.fromHexString(proxy));
output.write(request1.getBytes(StandardCharsets.UTF_8));
output.flush();

View File

@ -1313,7 +1313,7 @@ public class BufferUtil
else if (b == '\t')
buf.append("\\t");
else
buf.append("\\x").append(TypeUtil.toHexString(b));
buf.append("\\x").append(StringUtil.toHexString(b));
}
/**
@ -1351,7 +1351,8 @@ public class BufferUtil
{
if (buffer == null)
return "null";
return TypeUtil.toHexString(toArray(buffer));
byte[] b = toArray(buffer);
return StringUtil.toHexString(b);
}
private static final int[] decDivisors =

View File

@ -24,7 +24,7 @@ import java.util.stream.IntStream;
/**
* Fast String Utilities.
*
* <p>
* These string utilities provide both convenience methods and
* performance improvements over most standard library versions. The
* main aim of the optimizations is to avoid object creation unless
@ -32,52 +32,9 @@ import java.util.stream.IntStream;
*/
public class StringUtil
{
public static final String ALL_INTERFACES = "0.0.0.0";
public static final String CRLF = "\r\n";
public static final String DEFAULT_DELIMS = ",;";
public static final String __ISO_8859_1 = "iso-8859-1";
public static final String __UTF8 = "utf-8";
public static final String __UTF16 = "utf-16";
private static final Index<String> CHARSETS = new Index.Builder<String>()
.caseSensitive(false)
.with("utf-8", __UTF8)
.with("utf8", __UTF8)
.with("utf-16", __UTF16)
.with("utf16", __UTF16)
.with("iso-8859-1", __ISO_8859_1)
.with("iso_8859_1", __ISO_8859_1)
.build();
/**
* Convert alternate charset names (eg utf8) to normalized
* name (eg UTF-8).
*
* @param s the charset to normalize
* @return the normalized charset (or null if normalized version not found)
*/
public static String normalizeCharset(String s)
{
String n = CHARSETS.get(s);
return (n == null) ? s : n;
}
/**
* Convert alternate charset names (eg utf8) to normalized
* name (eg UTF-8).
*
* @param s the charset to normalize
* @param offset the offset in the charset
* @param length the length of the charset in the input param
* @return the normalized charset (or null if not found)
*/
public static String normalizeCharset(String s, int offset, int length)
{
String n = CHARSETS.get(s, offset, length);
return (n == null) ? s.substring(offset, offset + length) : n;
}
// @checkstyle-disable-check : IllegalTokenTextCheck
private static final char[] LOWERCASES =
{
@ -144,28 +101,6 @@ public class StringUtil
return (c > 0) ? (byte)LOWERCASES[c] : c;
}
/**
* fast upper case conversion. Only works on ascii (not unicode)
*
* @param c the char to convert
* @return a upper case version of c
*/
public static char asciiToUpperCase(char c)
{
return (c < 0x80) ? UPPERCASES[c] : c;
}
/**
* fast upper case conversion. Only works on ascii (not unicode)
*
* @param c the byte to convert
* @return a upper case version of c
*/
public static byte asciiToUpperCase(byte c)
{
return (c > 0) ? (byte)UPPERCASES[c] : c;
}
/**
* fast lower case conversion. Only works on ascii (not unicode)
*
@ -196,6 +131,7 @@ public class StringUtil
}
while (i-- > 0)
{
assert c != null;
if (c[i] <= 127)
c[i] = LOWERCASES[c[i]];
}
@ -233,6 +169,7 @@ public class StringUtil
}
while (i-- > 0)
{
assert c != null;
if (c[i] <= 127)
c[i] = UPPERCASES[c[i]];
}
@ -474,15 +411,12 @@ public class StringUtil
int offset,
int length)
{
synchronized (buf)
int end = offset + length;
for (int i = offset; i < end; i++)
{
int end = offset + length;
for (int i = offset; i < end; i++)
{
if (i >= s.length())
break;
buf.append(s.charAt(i));
}
if (i >= s.length())
break;
buf.append(s.charAt(i));
}
}
@ -506,21 +440,6 @@ public class StringUtil
buf.append((char)c);
}
/**
* Append 2 digits (zero padded) to the StringBuffer
*
* @param buf the buffer to append to
* @param i the value to append
*/
public static void append2digits(StringBuffer buf, int i)
{
if (i < 100)
{
buf.append((char)(i / 10 + '0'));
buf.append((char)(i % 10 + '0'));
}
}
/**
* Append 2 digits (zero padded) to the StringBuilder
*
@ -536,22 +455,6 @@ public class StringUtil
}
}
/**
* Generate a string from another string repeated n times.
*
* @param s the string to use
* @param n the number of times this string should be appended
*/
public static String stringFrom(String s, int n)
{
StringBuilder stringBuilder = new StringBuilder(s.length() * n);
for (int i = 0; i < n; i++)
{
stringBuilder.append(s);
}
return stringBuilder.toString();
}
/**
* Return a non null string.
*
@ -752,11 +655,6 @@ public class StringUtil
return false;
}
public static boolean isUTF8(String charset)
{
return __UTF8.equalsIgnoreCase(charset) || __UTF8.equalsIgnoreCase(normalizeCharset(charset));
}
public static boolean isHex(String str, int offset, int length)
{
if (offset + length > str.length())
@ -835,15 +733,15 @@ public class StringUtil
public static String printable(byte[] b)
{
StringBuilder buf = new StringBuilder();
for (int i = 0; i < b.length; i++)
for (byte value : b)
{
char c = (char)b[i];
char c = (char)value;
if (Character.isWhitespace(c) || c > ' ' && c < 0x7f)
buf.append(c);
else
{
buf.append("0x");
TypeUtil.toHex(b[i], buf);
TypeUtil.toHex(value, buf);
}
}
return buf.toString();
@ -908,42 +806,6 @@ public class StringUtil
throw new NumberFormatException(string);
}
/**
* Convert String to an long. Parses up to the first non-numeric character. If no number is found an IllegalArgumentException is thrown
*
* @param string A String containing an integer.
* @return an int
*/
public static long toLong(String string)
{
long val = 0;
boolean started = false;
boolean minus = false;
for (int i = 0; i < string.length(); i++)
{
char b = string.charAt(i);
if (b <= ' ')
{
if (started)
break;
}
else if (b >= '0' && b <= '9')
{
val = val * 10L + (b - '0');
started = true;
}
else if (b == '-' && !started)
{
minus = true;
}
else
break;
}
if (started)
return minus ? (-val) : val;
throw new NumberFormatException(string);
}
/**
* Truncate a string to a max size.
*
@ -1010,7 +872,7 @@ public class StringUtil
throw new IllegalArgumentException();
List<String> list = new ArrayList<>();
csvSplit(list, s, off, len);
return list.toArray(new String[list.size()]);
return list.toArray(new String[0]);
}
enum CsvSplitState
@ -1048,95 +910,91 @@ public class StringUtil
switch (state)
{
case PRE_DATA:
if (Character.isWhitespace(ch))
continue;
case PRE_DATA ->
{
if ('"' == ch)
{
state = CsvSplitState.QUOTE;
continue;
}
if (',' == ch)
else if (',' == ch)
{
list.add("");
continue;
}
state = CsvSplitState.DATA;
out.append(ch);
continue;
case DATA:
else if (!Character.isWhitespace(ch))
{
state = CsvSplitState.DATA;
out.append(ch);
}
}
case DATA ->
{
if (Character.isWhitespace(ch))
{
last = out.length();
out.append(ch);
state = CsvSplitState.WHITE;
continue;
}
if (',' == ch)
else if (',' == ch)
{
list.add(out.toString());
out.setLength(0);
state = CsvSplitState.PRE_DATA;
continue;
}
out.append(ch);
continue;
case WHITE:
else
{
out.append(ch);
}
}
case WHITE ->
{
if (Character.isWhitespace(ch))
{
out.append(ch);
continue;
}
if (',' == ch)
else if (',' == ch)
{
out.setLength(last);
list.add(out.toString());
out.setLength(0);
state = CsvSplitState.PRE_DATA;
continue;
}
state = CsvSplitState.DATA;
out.append(ch);
last = -1;
continue;
case QUOTE:
else
{
state = CsvSplitState.DATA;
out.append(ch);
last = -1;
}
}
case QUOTE ->
{
if ('\\' == ch)
{
state = CsvSplitState.SLOSH;
continue;
}
if ('"' == ch)
else if ('"' == ch)
{
list.add(out.toString());
out.setLength(0);
state = CsvSplitState.POST_DATA;
continue;
}
out.append(ch);
continue;
case SLOSH:
else
{
out.append(ch);
}
}
case SLOSH ->
{
out.append(ch);
state = CsvSplitState.QUOTE;
continue;
case POST_DATA:
}
case POST_DATA ->
{
if (',' == ch)
{
state = CsvSplitState.PRE_DATA;
continue;
}
continue;
default:
throw new IllegalStateException(state.toString());
}
default -> throw new IllegalStateException(state.toString());
}
}
switch (state)
@ -1202,26 +1060,18 @@ public class StringUtil
char c = html.charAt(i);
switch (c)
{
case '&':
out.append("&amp;");
break;
case '<':
out.append("&lt;");
break;
case '>':
out.append("&gt;");
break;
case '\'':
out.append("&apos;");
break;
case '"':
out.append("&quot;");
break;
default:
case '&' -> out.append("&amp;");
case '<' -> out.append("&lt;");
case '>' -> out.append("&gt;");
case '\'' -> out.append("&apos;");
case '"' -> out.append("&quot;");
default ->
{
if (Character.isISOControl(c) && !Character.isWhitespace(c))
out.append('?');
else
out.append(c);
}
}
}
return out.toString();

View File

@ -111,33 +111,6 @@ public class TypeUtil
name2Class.put("java.lang.String", java.lang.String.class);
}
private static final HashMap<Class<?>, String> class2Name = new HashMap<>();
static
{
class2Name.put(java.lang.Boolean.TYPE, "boolean");
class2Name.put(java.lang.Byte.TYPE, "byte");
class2Name.put(java.lang.Character.TYPE, "char");
class2Name.put(java.lang.Double.TYPE, "double");
class2Name.put(java.lang.Float.TYPE, "float");
class2Name.put(java.lang.Integer.TYPE, "int");
class2Name.put(java.lang.Long.TYPE, "long");
class2Name.put(java.lang.Short.TYPE, "short");
class2Name.put(java.lang.Void.TYPE, "void");
class2Name.put(java.lang.Boolean.class, "java.lang.Boolean");
class2Name.put(java.lang.Byte.class, "java.lang.Byte");
class2Name.put(java.lang.Character.class, "java.lang.Character");
class2Name.put(java.lang.Double.class, "java.lang.Double");
class2Name.put(java.lang.Float.class, "java.lang.Float");
class2Name.put(java.lang.Integer.class, "java.lang.Integer");
class2Name.put(java.lang.Long.class, "java.lang.Long");
class2Name.put(java.lang.Short.class, "java.lang.Short");
class2Name.put(null, "void");
class2Name.put(java.lang.String.class, "java.lang.String");
}
private static final HashMap<Class<?>, Function<String, Object>> class2Value = new HashMap<>();
static
@ -209,17 +182,6 @@ public class TypeUtil
return name2Class.get(name);
}
/**
* Canonical name for a type.
*
* @param type A class , which may be a primitive TYPE field.
* @return Canonical name.
*/
public static String toName(Class<?> type)
{
return class2Name.get(type);
}
public static String toShortName(Class<?> type)
{
StringBuilder b = new StringBuilder();
@ -413,20 +375,6 @@ public class TypeUtil
return value;
}
/**
* @deprecated use {@link StringUtil#fromHexString(String)} instead
*/
@Deprecated
public static byte[] parseBytes(String s, int base)
{
byte[] bytes = new byte[s.length() / 2];
for (int i = 0; i < s.length(); i += 2)
{
bytes[i / 2] = (byte)TypeUtil.parseInt(s, i, 2, base);
}
return bytes;
}
public static String toString(byte[] bytes, int base)
{
StringBuilder buf = new StringBuilder();
@ -542,42 +490,6 @@ public class TypeUtil
toHex((int)value, buf);
}
/**
* @deprecated use {@link StringUtil#toHexString(byte)} instead
*/
@Deprecated
public static String toHexString(byte b)
{
return StringUtil.toHexString(b);
}
/**
* @deprecated use {@link StringUtil#toHexString(byte[])} instead
*/
@Deprecated
public static String toHexString(byte[] b)
{
return StringUtil.toHexString(b);
}
/**
* @deprecated use {@link StringUtil#toHexString(byte[], int, int)} instead
*/
@Deprecated
public static String toHexString(byte[] b, int offset, int length)
{
return StringUtil.toHexString(b, offset, length);
}
/**
* @deprecated use {@link StringUtil#fromHexString(String)}
*/
@Deprecated
public static byte[] fromHexString(String s)
{
return StringUtil.fromHexString(s);
}
public static void dump(Class<?> c)
{
System.err.println("Dump: " + c);
@ -603,7 +515,7 @@ public class TypeUtil
if (o == null)
return false;
if (o instanceof Boolean)
return ((Boolean)o).booleanValue();
return (Boolean)o;
return Boolean.parseBoolean(o.toString());
}
@ -616,7 +528,7 @@ public class TypeUtil
if (o == null)
return false;
if (o instanceof Boolean)
return !((Boolean)o).booleanValue();
return !(Boolean)o;
return "false".equalsIgnoreCase(o.toString());
}
@ -731,7 +643,7 @@ public class TypeUtil
}
Optional<ResolvedModule> resolvedModule = configuration.findModule(module.getName());
if ((resolvedModule == null) || !resolvedModule.isPresent())
if (resolvedModule.isEmpty())
{
return null;
}
@ -743,12 +655,7 @@ public class TypeUtil
}
Optional<URI> location = moduleReference.location();
if (location.isPresent())
{
return location.get();
}
return null;
return location.orElse(null);
}
public static <T> Iterator<T> concat(Iterator<T> i1, Iterator<T> i2)
@ -807,7 +714,7 @@ public class TypeUtil
/**
* Utility to create a stream which provides the same functionality as {@link ServiceLoader#stream()}.
* However this also guards the case in which {@link Iterator#hasNext()} throws. Any exceptions
* However, this also guards the case in which {@link Iterator#hasNext()} throws. Any exceptions
* from the underlying iterator will be cached until the {@link ServiceLoader.Provider#get()} is called.
* @param serviceLoader the ServiceLoader instance to use.
* @param <T> the type of the service to load.

View File

@ -13,12 +13,11 @@
package org.eclipse.jetty.util;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.hamcrest.MatcherAssert.assertThat;
@ -26,6 +25,7 @@ import static org.hamcrest.Matchers.arrayContaining;
import static org.hamcrest.Matchers.emptyArray;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@ -100,28 +100,24 @@ public class StringUtilTest
assertEquals(StringUtil.replace(s, "\u0690bc", "xyz"), " xyz ");
}
public static Stream<String[]> replaceFirstArgs()
public static Stream<Arguments> replaceFirstArgs()
{
List<String[]> data = new ArrayList<>();
return Stream.of(
// no match
Arguments.of("abc", "z", "foo", "abc"),
// [original, target, replacement, expected]
// matches at start of string
Arguments.of("abc", "a", "foo", "foobc"),
Arguments.of("abcabcabc", "a", "foo", "foobcabcabc"),
// no match
data.add(new String[]{"abc", "z", "foo", "abc"});
// matches in middle of string
Arguments.of("abc", "b", "foo", "afooc"),
Arguments.of("abcabcabc", "b", "foo", "afoocabcabc"),
Arguments.of("abcabcabc", "cab", "X", "abXcabc"),
// matches at start of string
data.add(new String[]{"abc", "a", "foo", "foobc"});
data.add(new String[]{"abcabcabc", "a", "foo", "foobcabcabc"});
// matches in middle of string
data.add(new String[]{"abc", "b", "foo", "afooc"});
data.add(new String[]{"abcabcabc", "b", "foo", "afoocabcabc"});
data.add(new String[]{"abcabcabc", "cab", "X", "abXcabc"});
// matches at end of string
data.add(new String[]{"abc", "c", "foo", "abfoo"});
return data.stream();
// matches at end of string
Arguments.of("abc", "c", "foo", "abfoo")
);
}
@ParameterizedTest
@ -136,7 +132,7 @@ public class StringUtilTest
public void testNonNull()
{
String nn = "non empty string";
assertTrue(nn == StringUtil.nonNull(nn));
assertThat(StringUtil.nonNull(nn), sameInstance(nn));
assertEquals("", StringUtil.nonNull(null));
}

View File

@ -165,10 +165,10 @@ public class URLEncodedTest
{
String[][] charsets = new String[][]
{
{StringUtil.__UTF8, null, "%30"},
{StringUtil.__ISO_8859_1, StringUtil.__ISO_8859_1, "%30"},
{StringUtil.__UTF8, StringUtil.__UTF8, "%30"},
{StringUtil.__UTF16, StringUtil.__UTF16, "%00%30"},
{StandardCharsets.UTF_8.name(), null, "%30"},
{StandardCharsets.ISO_8859_1.name(), StandardCharsets.ISO_8859_1.name(), "%30"},
{StandardCharsets.UTF_8.name(), StandardCharsets.UTF_8.name(), "%30"},
{StandardCharsets.UTF_16.name(), StandardCharsets.UTF_16.name(), "%00%30"},
};
// Note: "%30" -> decode -> "0"
@ -218,12 +218,12 @@ public class URLEncodedTest
public void testCharsetViaSystemProperty()
throws Exception
{
try (ByteArrayInputStream in3 = new ByteArrayInputStream("name=libell%E9".getBytes(StringUtil.__ISO_8859_1)))
try (ByteArrayInputStream in3 = new ByteArrayInputStream("name=libell%E9".getBytes(StandardCharsets.ISO_8859_1)))
{
MultiMap<String> m3 = new MultiMap<>();
Charset nullCharset = null; // use the one from the system property
UrlEncoded.decodeTo(in3, m3, nullCharset, -1, -1);
assertEquals("libell\u00E9", m3.getString("name"), "stream name");
assertEquals("libellé", m3.getString("name"), "stream name");
}
}
@ -238,7 +238,7 @@ public class URLEncodedTest
UrlEncoded.decodeTo("text=%E0%B8%9F%E0%B8%AB%E0%B8%81%E0%B8%A7%E0%B8%94%E0%B8%B2%E0%B9%88%E0%B8%81%E0%B8%9F%E0%B8%A7%E0%B8%AB%E0%B8%AA%E0%B8%94%E0%B8%B2%E0%B9%88%E0%B8%AB%E0%B8%9F%E0%B8%81%E0%B8%A7%E0%B8%94%E0%B8%AA%E0%B8%B2%E0%B8%9F%E0%B8%81%E0%B8%AB%E0%B8%A3%E0%B8%94%E0%B9%89%E0%B8%9F%E0%B8%AB%E0%B8%99%E0%B8%81%E0%B8%A3%E0%B8%94%E0%B8%B5&Action=Submit", urlEncoded, UrlEncoded.ENCODING);
String hex = "E0B89FE0B8ABE0B881E0B8A7E0B894E0B8B2E0B988E0B881E0B89FE0B8A7E0B8ABE0B8AAE0B894E0B8B2E0B988E0B8ABE0B89FE0B881E0B8A7E0B894E0B8AAE0B8B2E0B89FE0B881E0B8ABE0B8A3E0B894E0B989E0B89FE0B8ABE0B899E0B881E0B8A3E0B894E0B8B5";
String expected = new String(TypeUtil.fromHexString(hex), "utf-8");
String expected = new String(StringUtil.fromHexString(hex), UTF_8);
assertEquals(expected, urlEncoded.getString("text"));
}

View File

@ -20,7 +20,6 @@ import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;
import java.security.Principal;
import java.util.AbstractList;
import java.util.ArrayList;
@ -737,21 +736,8 @@ public class ServletApiRequest implements HttpServletRequest
{
if (_inputState != ServletContextRequest.INPUT_NONE)
return;
MimeTypes.getKnownCharset(encoding);
_characterEncoding = encoding;
// check encoding is supported
if (!StringUtil.isUTF8(encoding))
{
try
{
Charset.forName(encoding);
}
catch (UnsupportedCharsetException e)
{
throw new UnsupportedEncodingException(e.getMessage());
}
}
}
@Override
@ -1049,7 +1035,7 @@ public class ServletApiRequest implements HttpServletRequest
String encoding = getCharacterEncoding();
if (encoding == null)
encoding = StringUtil.__ISO_8859_1;
encoding = MimeTypes.ISO_8859_1;
if (_reader == null || !encoding.equalsIgnoreCase(_readerEncoding))
{

View File

@ -37,6 +37,7 @@ import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.session.ManagedSession;
@ -300,9 +301,9 @@ public class ServletApiResponse implements HttpServletResponse
writer.reopen();
else
{
if (StringUtil.__ISO_8859_1.equalsIgnoreCase(encoding))
if (MimeTypes.ISO_8859_1.equalsIgnoreCase(encoding))
getServletResponseInfo().setWriter(writer = new ResponseWriter(new Iso88591HttpWriter(getServletChannel().getHttpOutput()), locale, encoding));
else if (StringUtil.__UTF8.equalsIgnoreCase(encoding))
else if (MimeTypes.UTF8.equalsIgnoreCase(encoding))
getServletResponseInfo().setWriter(writer = new ResponseWriter(new Utf8HttpWriter(getServletChannel().getHttpOutput()), locale, encoding));
else
getServletResponseInfo().setWriter(writer = new ResponseWriter(new EncodingHttpWriter(getServletChannel().getHttpOutput(), encoding), locale, encoding));

View File

@ -38,7 +38,6 @@ import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.server.handler.ContextResponse;
import org.eclipse.jetty.session.ManagedSession;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.StringUtil;
/**
* A core response wrapper that carries the servlet related response state,
@ -423,7 +422,7 @@ public class ServletContextResponse extends ContextResponse implements ServletCo
}
// Fallback to last resort iso-8859-1.
encoding = StringUtil.__ISO_8859_1;
encoding = MimeTypes.ISO_8859_1;
if (setContentType)
setCharacterEncoding(encoding, EncodingFrom.DEFAULT);
return encoding;
@ -463,7 +462,7 @@ public class ServletContextResponse extends ContextResponse implements ServletCo
else
{
_encodingFrom = from;
_characterEncoding = HttpGenerator.__STRICT ? encoding : StringUtil.normalizeCharset(encoding);
_characterEncoding = HttpGenerator.__STRICT ? encoding : MimeTypes.normalizeCharset(encoding);
if (_mimeType != null)
{
_contentType = _mimeType.getBaseType().asString() + ";charset=" + _characterEncoding;

View File

@ -35,7 +35,7 @@ import org.eclipse.jetty.server.handler.gzip.GzipHandler;
import org.eclipse.jetty.toolchain.test.IO;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.StringUtil;
import org.junit.jupiter.api.extension.ExtendWith;
import static java.nio.charset.StandardCharsets.UTF_8;
@ -81,7 +81,8 @@ public abstract class AbstractGzipTest
metadata.uncompressedContent = uncompressedStream.toByteArray();
metadata.uncompressedSize = metadata.uncompressedContent.length;
// Odd toUpperCase is because TypeUtil.toHexString is mixed case results!??
metadata.uncompressedSha1Sum = TypeUtil.toHexString(digest.digest()).toUpperCase(Locale.ENGLISH);
byte[] b = digest.digest();
metadata.uncompressedSha1Sum = StringUtil.toHexString(b).toUpperCase(Locale.ENGLISH);
return metadata;
}
}

View File

@ -44,7 +44,6 @@ import org.eclipse.jetty.ee10.websocket.jakarta.tests.LocalServer;
import org.eclipse.jetty.ee10.websocket.jakarta.tests.WSEndpointTracker;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.websocket.core.CloseStatus;
import org.eclipse.jetty.websocket.core.Frame;
import org.eclipse.jetty.websocket.core.OpCode;
@ -224,7 +223,7 @@ public class TextStreamTest
writer.flush();
// Lots of data after we have stopped reading and onMessage exits.
final String largePayload = StringUtil.stringFrom("x", serverInputBufferSize * 2);
final String largePayload = "x".repeat(serverInputBufferSize * 2);
writer.write(largePayload);
writer.close();

View File

@ -20,9 +20,9 @@ import jakarta.websocket.OnError;
import jakarta.websocket.OnMessage;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.toolchain.test.StackUtils;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -34,7 +34,7 @@ public class InputStreamSocket
@OnMessage
public String onInputStream(InputStream stream) throws IOException
{
return IO.toString(stream, StringUtil.__UTF8);
return IO.toString(stream, MimeTypes.UTF8);
}
@OnError

View File

@ -25,7 +25,6 @@ import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;
import java.security.Principal;
import java.util.AbstractList;
import java.util.ArrayList;
@ -1058,7 +1057,7 @@ public class Request implements HttpServletRequest
String encoding = getCharacterEncoding();
if (encoding == null)
encoding = StringUtil.__ISO_8859_1;
encoding = MimeTypes.ISO_8859_1;
if (_reader == null || !encoding.equalsIgnoreCase(_readerEncoding))
{
@ -1747,20 +1746,8 @@ public class Request implements HttpServletRequest
if (_inputState != INPUT_NONE)
return;
MimeTypes.getKnownCharset(encoding);
_characterEncoding = encoding;
// check encoding is supported
if (!StringUtil.isUTF8(encoding))
{
try
{
Charset.forName(encoding);
}
catch (UnsupportedCharsetException e)
{
throw new UnsupportedEncodingException(e.getMessage());
}
}
}
/*

View File

@ -815,7 +815,7 @@ public class Response implements HttpServletResponse
}
// Fallback to last resort iso-8859-1.
encoding = StringUtil.__ISO_8859_1;
encoding = MimeTypes.ISO_8859_1;
if (setContentType)
setCharacterEncoding(encoding, EncodingFrom.DEFAULT);
return encoding;
@ -865,9 +865,9 @@ public class Response implements HttpServletResponse
_writer.reopen();
else
{
if (StringUtil.__ISO_8859_1.equalsIgnoreCase(encoding))
if (MimeTypes.ISO_8859_1.equalsIgnoreCase(encoding))
_writer = new ResponseWriter(new Iso88591HttpWriter(_out), locale, encoding);
else if (StringUtil.__UTF8.equalsIgnoreCase(encoding))
else if (MimeTypes.UTF8.equalsIgnoreCase(encoding))
_writer = new ResponseWriter(new Utf8HttpWriter(_out), locale, encoding);
else
_writer = new ResponseWriter(new EncodingHttpWriter(_out, encoding), locale, encoding);
@ -1020,7 +1020,7 @@ public class Response implements HttpServletResponse
else
{
_encodingFrom = from;
_characterEncoding = HttpGenerator.__STRICT ? encoding : StringUtil.normalizeCharset(encoding);
_characterEncoding = HttpGenerator.__STRICT ? encoding : MimeTypes.normalizeCharset(encoding);
if (_mimeType != null)
{
_contentType = _mimeType.getBaseType().asString() + ";charset=" + _characterEncoding;

View File

@ -17,10 +17,10 @@ import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.Utf8StringBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
@ -93,7 +93,7 @@ public class HttpWriterTest
@Test
public void testUTF16() throws Exception
{
HttpWriter writer = new EncodingHttpWriter(_httpOut, StringUtil.__UTF16);
HttpWriter writer = new EncodingHttpWriter(_httpOut, MimeTypes.UTF16);
writer.write("How now \uFF22rown cow");
assertArrayEquals("How now \uFF22rown cow".getBytes(StandardCharsets.UTF_16), BufferUtil.toArray(_bytes));
}
@ -104,7 +104,8 @@ public class HttpWriterTest
HttpWriter writer = new Utf8HttpWriter(_httpOut);
String data = "xxx\uD801\uDC00xxx";
writer.write(data);
assertEquals("787878F0909080787878", TypeUtil.toHexString(BufferUtil.toArray(_bytes)));
byte[] b = BufferUtil.toArray(_bytes);
assertEquals("787878F0909080787878", StringUtil.toHexString(b));
assertArrayEquals(data.getBytes(StandardCharsets.UTF_8), BufferUtil.toArray(_bytes));
assertEquals(3 + 4 + 3, _bytes.remaining());

View File

@ -55,7 +55,7 @@ import org.eclipse.jetty.toolchain.test.FS;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.resource.FileSystemPool;
import org.eclipse.jetty.util.resource.ResourceFactory;
import org.junit.jupiter.api.AfterEach;
@ -2092,11 +2092,11 @@ public class DefaultServletTest
context.addAliasCheck(new AllowedResourceAliasChecker(context.getCoreContextHandler()));
// Create file with UTF-8 NFC format
String filename = "swedish-" + new String(TypeUtil.fromHexString("C3A5"), UTF_8) + ".txt";
String filename = "swedish-" + new String(StringUtil.fromHexString("C3A5"), UTF_8) + ".txt";
createFile(docRoot.resolve(filename), "hi a-with-circle");
// Using filesystem, attempt to access via NFD format
Path nfdPath = docRoot.resolve("swedish-a" + new String(TypeUtil.fromHexString("CC8A"), UTF_8) + ".txt");
Path nfdPath = docRoot.resolve("swedish-a" + new String(StringUtil.fromHexString("CC8A"), UTF_8) + ".txt");
boolean filesystemSupportsNFDAccess = Files.exists(nfdPath);
// Make requests
@ -2132,11 +2132,11 @@ public class DefaultServletTest
context.addAliasCheck(new AllowedResourceAliasChecker(context.getCoreContextHandler()));
// Create file with UTF-8 NFD format
String filename = "swedish-a" + new String(TypeUtil.fromHexString("CC8A"), UTF_8) + ".txt";
String filename = "swedish-a" + new String(StringUtil.fromHexString("CC8A"), UTF_8) + ".txt";
createFile(docRoot.resolve(filename), "hi a-with-circle");
// Using filesystem, attempt to access via NFC format
Path nfcPath = docRoot.resolve("swedish-" + new String(TypeUtil.fromHexString("C3A5"), UTF_8) + ".txt");
Path nfcPath = docRoot.resolve("swedish-" + new String(StringUtil.fromHexString("C3A5"), UTF_8) + ".txt");
boolean filesystemSupportsNFCAccess = Files.exists(nfcPath);
String rawResponse;

View File

@ -65,7 +65,7 @@ import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.toolchain.test.MavenPaths;
import org.eclipse.jetty.util.MultiMap;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.UrlEncoded;
import org.eclipse.jetty.util.component.LifeCycle;
import org.hamcrest.Matcher;
@ -1178,7 +1178,7 @@ public class DispatcherTest
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
byte[] cp1251Bytes = TypeUtil.fromHexString("d2e5ecefe5f0e0f2f3f0e0");
byte[] cp1251Bytes = StringUtil.fromHexString("d2e5ecefe5f0e0f2f3f0e0");
String expectedCP1251String = new String(cp1251Bytes, "cp1251");
assertEquals("/context/ForwardServlet", request.getAttribute(Dispatcher.FORWARD_REQUEST_URI));

View File

@ -35,7 +35,7 @@ import org.eclipse.jetty.server.handler.gzip.GzipHandler;
import org.eclipse.jetty.toolchain.test.IO;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.StringUtil;
import org.junit.jupiter.api.extension.ExtendWith;
import static java.nio.charset.StandardCharsets.UTF_8;
@ -81,7 +81,8 @@ public abstract class AbstractGzipTest
metadata.uncompressedContent = uncompressedStream.toByteArray();
metadata.uncompressedSize = metadata.uncompressedContent.length;
// Odd toUpperCase is because TypeUtil.toHexString is mixed case results!??
metadata.uncompressedSha1Sum = TypeUtil.toHexString(digest.digest()).toUpperCase(Locale.ENGLISH);
byte[] b = digest.digest();
metadata.uncompressedSha1Sum = StringUtil.toHexString(b).toUpperCase(Locale.ENGLISH);
return metadata;
}
}

View File

@ -44,7 +44,6 @@ import org.eclipse.jetty.ee9.websocket.jakarta.tests.LocalServer;
import org.eclipse.jetty.ee9.websocket.jakarta.tests.WSEndpointTracker;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.websocket.core.CloseStatus;
import org.eclipse.jetty.websocket.core.Frame;
import org.eclipse.jetty.websocket.core.OpCode;
@ -224,7 +223,7 @@ public class TextStreamTest
writer.flush();
// Lots of data after we have stopped reading and onMessage exits.
final String largePayload = StringUtil.stringFrom("x", serverInputBufferSize * 2);
final String largePayload = "x".repeat(serverInputBufferSize * 2);
writer.write(largePayload);
writer.close();

View File

@ -20,9 +20,9 @@ import jakarta.websocket.OnError;
import jakarta.websocket.OnMessage;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.toolchain.test.StackUtils;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -34,7 +34,7 @@ public class InputStreamSocket
@OnMessage
public String onInputStream(InputStream stream) throws IOException
{
return IO.toString(stream, StringUtil.__UTF8);
return IO.toString(stream, MimeTypes.UTF8);
}
@OnError