diff --git a/src/main/java/com/hubspot/jinjava/el/ext/JinjavaListELResolver.java b/src/main/java/com/hubspot/jinjava/el/ext/JinjavaListELResolver.java index 975286eba..cea4ac484 100644 --- a/src/main/java/com/hubspot/jinjava/el/ext/JinjavaListELResolver.java +++ b/src/main/java/com/hubspot/jinjava/el/ext/JinjavaListELResolver.java @@ -64,10 +64,13 @@ private static boolean isResolvable(Object base) { * if property cannot be coerced to an integer. */ private static int toIndex(Object property) { - int index = 0; + int index; if (property instanceof Number) { index = ((Number) property).intValue(); } else if (property instanceof String) { + if (!isNumeric((String) property)) { + throw new IllegalArgumentException("Cannot parse list index: " + property); + } try { // ListELResolver uses valueOf, but findbugs complains. index = Integer.parseInt((String) property); @@ -92,4 +95,17 @@ public void setValue(ELContext context, Object base, Object property, Object val super.setValue(context, base, property, value); } catch (IllegalArgumentException ignored) {} } + + public static boolean isNumeric(final CharSequence cs) { + if (cs == null || cs.length() == 0) { + return false; + } + final int sz = cs.length(); + for (int i = 0; i < sz; i++) { + if (!Character.isDigit(cs.charAt(i)) && cs.charAt(i) != '-') { + return false; + } + } + return true; + } } diff --git a/src/test/java/com/hubspot/jinjava/el/ExpressionResolverPerformanceTest.java b/src/test/java/com/hubspot/jinjava/el/ExpressionResolverPerformanceTest.java index d9049ada3..8338a351c 100644 --- a/src/test/java/com/hubspot/jinjava/el/ExpressionResolverPerformanceTest.java +++ b/src/test/java/com/hubspot/jinjava/el/ExpressionResolverPerformanceTest.java @@ -40,9 +40,7 @@ public void startTimer() { } public void stopTimer() { - System.out.println( - String.format("%d msec", System.currentTimeMillis() - startTime) - ); + System.out.printf("%d msec%n", System.currentTimeMillis() - startTime); } public void testMapResolver(int iterations) {