Skip to content

Commit 8a29c1e

Browse files
fvladartembilan
authored andcommitted
Optimise maybeIndex() in JsonPropertyAccessor
The `NumberFormatException` flow control is costly operation * Use `Character.isDigit()` check iterating through property String instead of `NumberFormatException` flow control **Cherry-pick to `6.1.x`, `6.0.x` & `5.5.x`**
1 parent 8315b11 commit 8a29c1e

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

spring-integration-core/src/main/java/org/springframework/integration/json/JsonPropertyAccessor.java

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2013-2022 the original author or authors.
2+
* Copyright 2013-2023 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -31,6 +31,7 @@
3131
import org.springframework.expression.TypedValue;
3232
import org.springframework.lang.Nullable;
3333
import org.springframework.util.Assert;
34+
import org.springframework.util.StringUtils;
3435

3536
/**
3637
* A SpEL {@link PropertyAccessor} that knows how to read properties from JSON objects.
@@ -41,6 +42,7 @@
4142
* @author Paul Martin
4243
* @author Gary Russell
4344
* @author Pierre Lakreb
45+
* @author Vladislav Fefelov
4446
*
4547
* @since 3.0
4648
*/
@@ -109,6 +111,9 @@ else if (target instanceof String) {
109111
* Return an integer if the String property name can be parsed as an int, or null otherwise.
110112
*/
111113
private static Integer maybeIndex(String name) {
114+
if (!isNumeric(name)) {
115+
return null;
116+
}
112117
try {
113118
return Integer.valueOf(name);
114119
}
@@ -139,6 +144,22 @@ public void write(EvaluationContext context, Object target, String name, Object
139144
throw new UnsupportedOperationException("Write is not supported");
140145
}
141146

147+
/**
148+
* Check if the string is a numeric representation (all digits) or not.
149+
*/
150+
private static boolean isNumeric(String str) {
151+
if (!StringUtils.hasLength(str)) {
152+
return false;
153+
}
154+
int length = str.length();
155+
for (int i = 0; i < length; i++) {
156+
if (!Character.isDigit(str.charAt(i))) {
157+
return false;
158+
}
159+
}
160+
return true;
161+
}
162+
142163
private static TypedValue typedValue(JsonNode json) throws AccessException {
143164
if (json == null) {
144165
return TypedValue.NULL;

0 commit comments

Comments
 (0)