Update AbstractXContentParser to support parsers that don't provide text characters (#129005)

This commit is contained in:
Mike Pellegrini 2025-06-06 09:17:41 -04:00 committed by GitHub
parent 523ba41fd1
commit 5ee6dfadfe
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 52 additions and 2 deletions

View file

@ -0,0 +1,6 @@
pr: 129005
summary: Update AbstractXContentParser to support parsers that don't provide text
characters
area: Infra/Core
type: bug
issues: []

View file

@ -87,7 +87,13 @@ public abstract class AbstractXContentParser implements XContentParser {
public boolean isBooleanValue() throws IOException {
return switch (currentToken()) {
case VALUE_BOOLEAN -> true;
case VALUE_STRING -> Booleans.isBoolean(textCharacters(), textOffset(), textLength());
case VALUE_STRING -> {
if (hasTextCharacters()) {
yield Booleans.isBoolean(textCharacters(), textOffset(), textLength());
} else {
yield Booleans.isBoolean(text());
}
}
default -> false;
};
}
@ -96,7 +102,11 @@ public abstract class AbstractXContentParser implements XContentParser {
public boolean booleanValue() throws IOException {
Token token = currentToken();
if (token == Token.VALUE_STRING) {
if (hasTextCharacters()) {
return Booleans.parseBoolean(textCharacters(), textOffset(), textLength(), false /* irrelevant */);
} else {
return Booleans.parseBoolean(text(), false /* irrelevant */);
}
}
return doBooleanValue();
}

View file

@ -97,6 +97,40 @@ public class MapXContentParserTests extends ESTestCase {
}
}
public void testParseBooleanStringValue() throws IOException {
try (
XContentParser parser = new MapXContentParser(
xContentRegistry(),
LoggingDeprecationHandler.INSTANCE,
Map.of("bool_key", "true"),
randomFrom(XContentType.values())
)
) {
assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
assertEquals(XContentParser.Token.VALUE_STRING, parser.nextToken());
assertTrue(parser.isBooleanValue());
assertTrue(parser.booleanValue());
assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
}
try (
XContentParser parser = new MapXContentParser(
xContentRegistry(),
LoggingDeprecationHandler.INSTANCE,
Map.of("bool_key", "false"),
randomFrom(XContentType.values())
)
) {
assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
assertEquals(XContentParser.Token.VALUE_STRING, parser.nextToken());
assertTrue(parser.isBooleanValue());
assertFalse(parser.booleanValue());
assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
}
}
private void compareTokens(CheckedConsumer<XContentBuilder, IOException> consumer) throws IOException {
for (XContentType xContentType : EnumSet.allOf(XContentType.class)) {
logger.info("--> testing with xcontent type: {}", xContentType);