You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@tomcat.apache.org by re...@apache.org on 2026/10/18 16:14:18 UTC

(tomcat) branch 10.1.x updated (f5c38da8dd -> 66af02be76)

This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a change to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git


    from f5c38da8dd Remove stray raw path entry added to the WebSocket template match map when a programmatic registration duplicates an annotated POJO template path
     new ba38d8490d Correct equals() implementations in method expression classes
     new 21021ff89e Pin serialVersionUID in EL expression classes
     new a2cfa7250a Fix broken tests.
     new a760ac19d7 Surface EL arithmetic and comparison errors as ELException
     new 1d1c7f3aaf Report accurate result type for EL concatenation expressions
     new 377c490db1 Pass empty array for empty EL function varargs
     new b6d261e9e5 Reject multiple parameter sets for EL constructor and static calls
     new 875c8630e8 Correct the EL empty operator for empty primitive arrays
     new 873da9c550 Resolve imported identifiers in AstIdentifier.getType()
     new 3022bb57b1 Coerce strings correctly for the EL unary minus operator
     new 8a1ac3c5e9 Report inaccessible methods in BeanELResolver as MethodNotFoundException
     new ddb7764886 Accept zero varargs elements in EL method expression calls
     new 833197d84e Evaluate each expression once for EL method references
     new 8d83eeaaea Reduce the cost of parsing EL expressions with long tokens
     new bede36c6eb Coerce EL stream predicate results in the match operations
     new 9217b7c7ba Accept null results from EL stream comparator lambdas
     new b2b49f9855 Follow the EL specification for substream with a negative start
     new fdcd59beb0 Correct the method call check in AstValue.getValueReference
     new 0c9270778b Fix bad merge
     new 66af02be76 Compatibility

The 20 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 java/jakarta/el/BeanELResolver.java                |   8 +
 java/jakarta/el/LocalStrings.properties            |   2 +
 java/org/apache/el/LocalStrings.properties         |   6 +
 java/org/apache/el/MethodExpressionImpl.java       |  13 +-
 java/org/apache/el/MethodExpressionLiteral.java    |   8 +-
 java/org/apache/el/ValueExpressionImpl.java        |   2 +
 java/org/apache/el/lang/ELArithmetic.java          |  86 +++++++---
 java/org/apache/el/lang/ELSupport.java             |  50 ++++--
 java/org/apache/el/parser/AstAbstractEmpty.java    |   3 +-
 java/org/apache/el/parser/AstConcatenation.java    |  24 +++
 java/org/apache/el/parser/AstFunction.java         |  26 ++-
 java/org/apache/el/parser/AstIdentifier.java       |  23 ++-
 java/org/apache/el/parser/AstNegative.java         |  15 +-
 java/org/apache/el/parser/AstValue.java            |  15 +-
 java/org/apache/el/parser/SimpleCharStream.java    |  14 +-
 java/org/apache/el/stream/Stream.java              |  52 ++++--
 test/jakarta/el/TestBeanELResolver.java            |  58 +++++++
 test/org/apache/el/TestELEvaluation.java           |  18 +-
 test/org/apache/el/TestMethodExpressionImpl.java   | 139 ++++++++++++++-
 test/org/apache/el/TestValueExpressionImpl.java    |  53 ++++++
 .../el/{TesterBeanJ.java => TesterBeanK.java}      |  35 ++--
 .../el/{TesterBeanD.java => TesterBeanM.java}      |  26 ++-
 test/org/apache/el/TesterFunctions.java            |  10 ++
 test/org/apache/el/lang/TestELArithmetic.java      | 104 +++++++++++
 test/org/apache/el/lang/TestELSupport.java         |  81 +++++++++
 .../org/apache/el/parser/TestAstConcatenation.java |  55 ++++++
 test/org/apache/el/parser/TestAstEmpty.java        |  29 ++++
 test/org/apache/el/parser/TestAstFunction.java     |  74 ++++++++
 test/org/apache/el/parser/TestAstIdentifier.java   |  95 ++++++++++
 test/org/apache/el/parser/TestAstNegative.java     | 111 ++++++++++++
 test/org/apache/el/parser/TestAstNotEmpty.java     |  19 ++
 .../apache/el/stream/TestCollectionOperations.java | 191 +++++++++++++++++++++
 test/org/apache/el/util/TestReflectionUtil.java    |  18 +-
 33 files changed, 1329 insertions(+), 134 deletions(-)
 copy test/org/apache/el/{TesterBeanJ.java => TesterBeanK.java} (61%)
 copy test/org/apache/el/{TesterBeanD.java => TesterBeanM.java} (67%)
 create mode 100644 test/org/apache/el/parser/TestAstNegative.java


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 10/20: Coerce strings correctly for the EL unary minus operator

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 3022bb57b186c8f0b715f5469620364af90b2534
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 15:03:23 2026 +0200

    Coerce strings correctly for the EL unary minus operator
    
    The String case of AstNegative parsed its operand by calling
    Long.parseLong() and Double.parseDouble() directly, bypassing the
    shared numeric coercion. Two consequences.
    
    An empty string operand threw an uncaught NumberFormatException.
    Every other numeric conversion path in the EL implementation coerces
    the empty string to zero, including the binary operators, so a common
    pattern such as a unary minus applied to an empty request parameter
    reported a raw NumberFormatException to the container instead of
    evaluating to zero. The null case already returned zero; the empty
    string now matches it.
    
    Any string that cannot be parsed, e.g. text or an integer literal too
    large for a long, leaked the raw unchecked NumberFormatException. The
    Jakarta EL API requires conversion failures to surface as an
    ELException, as ELSupport.coerceToNumber() does for the same parse
    failures. The parse calls are now wrapped, producing an ELException
    with the standard conversion message and the NumberFormatException as
    the cause. The result types and values for all operands that
    previously evaluated successfully are unchanged.
    
    Adds a test class for the node covering the null, empty, valid and
    invalid string operands, including the exception type and cause. The
    four failure-mode tests throw the raw NumberFormatException against
    the previous implementation.
---
 java/org/apache/el/parser/AstNegative.java     |  15 +++-
 test/org/apache/el/parser/TestAstNegative.java | 111 +++++++++++++++++++++++++
 2 files changed, 123 insertions(+), 3 deletions(-)

diff --git a/java/org/apache/el/parser/AstNegative.java b/java/org/apache/el/parser/AstNegative.java
index 2eb41a20c5..877eed6528 100644
--- a/java/org/apache/el/parser/AstNegative.java
+++ b/java/org/apache/el/parser/AstNegative.java
@@ -24,6 +24,7 @@ import jakarta.el.ELException;
 
 import org.apache.el.lang.ELSupport;
 import org.apache.el.lang.EvaluationContext;
+import org.apache.el.util.MessageFactory;
 
 public final class AstNegative extends SimpleNode {
 
@@ -52,10 +53,18 @@ public final class AstNegative extends SimpleNode {
             return ((BigInteger) obj).negate();
         }
         if (obj instanceof String) {
-            if (ELSupport.isStringFloat((String) obj)) {
-                return Double.valueOf(-Double.parseDouble((String) obj));
+            String s = (String) obj;
+            if (s.isEmpty()) {
+                return Long.valueOf(0);
+            }
+            try {
+                if (ELSupport.isStringFloat(s)) {
+                    return Double.valueOf(-Double.parseDouble(s));
+                }
+                return Long.valueOf(-Long.parseLong(s));
+            } catch (NumberFormatException nfe) {
+                throw new ELException(MessageFactory.get("error.convert", s, String.class, Number.class), nfe);
             }
-            return Long.valueOf(-Long.parseLong((String) obj));
         }
         if (obj instanceof Long) {
             return Long.valueOf(-((Long) obj).longValue());
diff --git a/test/org/apache/el/parser/TestAstNegative.java b/test/org/apache/el/parser/TestAstNegative.java
new file mode 100644
index 0000000000..311ff29ff6
--- /dev/null
+++ b/test/org/apache/el/parser/TestAstNegative.java
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.el.parser;
+
+import jakarta.el.ELException;
+import jakarta.el.ELProcessor;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class TestAstNegative {
+
+    @Test
+    public void testNull() {
+        ELProcessor processor = new ELProcessor();
+        Assert.assertEquals(Long.valueOf(0), processor.eval("-null"));
+    }
+
+
+    @Test
+    public void testEmptyString() {
+        // An empty string coerces to zero. This is consistent with the
+        // coercion used by the binary operators, e.g. 5 - '' is 5.
+        ELProcessor processor = new ELProcessor();
+        Object result = processor.eval("-''");
+        Assert.assertEquals(Long.class, result.getClass());
+        Assert.assertEquals(Long.valueOf(0), result);
+    }
+
+
+    @Test
+    public void testIntegerString() {
+        ELProcessor processor = new ELProcessor();
+        Assert.assertEquals(Long.valueOf(-12), processor.eval("-'12'"));
+    }
+
+
+    @Test
+    public void testFloatingPointString() {
+        ELProcessor processor = new ELProcessor();
+        Object result = processor.eval("-'1.5'");
+        Assert.assertEquals(Double.class, result.getClass());
+        Assert.assertEquals(Double.valueOf(-1.5), result);
+    }
+
+
+    @Test
+    public void testNonNumericString() {
+        // A string that cannot be parsed as a number must produce an
+        // ELException, not the raw NumberFormatException from parsing
+        ELProcessor processor = new ELProcessor();
+        try {
+            processor.eval("-'abc'");
+            Assert.fail("An ELException was expected");
+        } catch (ELException e) {
+            // Expected
+            Assert.assertTrue("Unexpected cause: " + e.getCause(),
+                    e.getCause() instanceof NumberFormatException);
+        }
+    }
+
+
+    @Test
+    public void testInvalidFloatingPointString() {
+        ELProcessor processor = new ELProcessor();
+        try {
+            processor.eval("-'1.5.5'");
+            Assert.fail("An ELException was expected");
+        } catch (ELException e) {
+            // Expected
+        }
+    }
+
+
+    @Test
+    public void testOverflowString() {
+        // A string that is too large for a long cannot be negated as a long.
+        // The unary minus of a string is specified in terms of
+        // Long.parseLong()/Double.parseDouble(), so this is a conversion
+        // failure rather than a change of result type.
+        ELProcessor processor = new ELProcessor();
+        try {
+            processor.eval("-'99999999999999999999999999'");
+            Assert.fail("An ELException was expected");
+        } catch (ELException e) {
+            // Expected
+        }
+    }
+
+
+    @Test
+    public void testNumericLiteral() {
+        ELProcessor processor = new ELProcessor();
+        Assert.assertEquals(Long.valueOf(-12), processor.eval("-12"));
+        Assert.assertEquals(Double.valueOf(-1.5), processor.eval("-1.5"));
+    }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 09/20: Resolve imported identifiers in AstIdentifier.getType()

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 873da9c55045cb96aa2d14a92e58c56667b55352
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 14:55:25 2026 +0200

    Resolve imported identifiers in AstIdentifier.getType()
    
    AstIdentifier evaluated an identifier that no resolver handled by
    falling back to the ImportHandler: a name matching an imported class
    yielded an ELClass and a name matching a statically imported field
    yielded the field value. getType() had no equivalent fallback, so for
    these expressions getValue() succeeded while getType() reported
    PropertyNotFoundException. Since ValueExpression.getType() is the API
    used to determine the result type before evaluating, the gap made
    import-resolved identifiers unusable for any client that inspects the
    type first.
    
    Mirror the fallback in getType(). A class import reports ELClass rather
    than Class, since that is the type of the value getValue() returns and
    ELClass is not itself a Class, which keeps the reported type assignable
    from the value. A static field import reports the declared type of the
    field, matching how a bean property of the same type is reported. The
    check stays behind the resolver so a resolver that handles the name
    still takes precedence, as it does when getting the value, and a name
    that resolves nothing continues to report PropertyNotFoundException.
    
    Adds tests for both import kinds, for the resolver precedence and for
    the unchanged error for unresolvable names. The import tests fail
    against the previous implementation.
---
 java/org/apache/el/parser/AstIdentifier.java     | 23 +++++-
 test/org/apache/el/parser/TestAstIdentifier.java | 95 ++++++++++++++++++++++++
 2 files changed, 115 insertions(+), 3 deletions(-)

diff --git a/java/org/apache/el/parser/AstIdentifier.java b/java/org/apache/el/parser/AstIdentifier.java
index a02b10d105..3de3a3560a 100644
--- a/java/org/apache/el/parser/AstIdentifier.java
+++ b/java/org/apache/el/parser/AstIdentifier.java
@@ -50,10 +50,27 @@ public final class AstIdentifier extends SimpleNode {
         }
         ctx.setPropertyResolved(false);
         Class<?> result = ctx.getELResolver().getType(ctx, null, this.image);
-        if (!ctx.isPropertyResolved()) {
-            throw new PropertyNotFoundException(MessageFactory.get("error.resolver.unhandled.null", this.image));
+        if (ctx.isPropertyResolved()) {
+            return result;
         }
-        return result;
+
+        // Import
+        Object imported = ctx.getImportHandler().resolveClass(this.image);
+        if (imported != null) {
+            // getValue() returns an ELClass for an imported class
+            return ELClass.class;
+        }
+        imported = ctx.getImportHandler().resolveStatic(this.image);
+        if (imported != null) {
+            // getValue() returns the value of a statically imported field
+            try {
+                return ((Class<?>) imported).getField(this.image).getType();
+            } catch (IllegalArgumentException | NoSuchFieldException | SecurityException e) {
+                throw new ELException(e);
+            }
+        }
+
+        throw new PropertyNotFoundException(MessageFactory.get("error.resolver.unhandled.null", this.image));
     }
 
 
diff --git a/test/org/apache/el/parser/TestAstIdentifier.java b/test/org/apache/el/parser/TestAstIdentifier.java
index b9dfec5df5..fb4e4487a6 100644
--- a/test/org/apache/el/parser/TestAstIdentifier.java
+++ b/test/org/apache/el/parser/TestAstIdentifier.java
@@ -16,10 +16,13 @@
  */
 package org.apache.el.parser;
 
+import jakarta.el.ELClass;
 import jakarta.el.ELContext;
 import jakarta.el.ELException;
 import jakarta.el.ELProcessor;
+import jakarta.el.ELResolver;
 import jakarta.el.ExpressionFactory;
+import jakarta.el.PropertyNotFoundException;
 import jakarta.el.ValueExpression;
 
 import org.junit.Assert;
@@ -52,6 +55,98 @@ public class TestAstIdentifier {
     }
 
 
+    @Test
+    public void testImport03() {
+        // getType() must resolve an imported class, just as getValue() does
+        ELProcessor processor = new ELProcessor();
+        ELContext context = processor.getELManager().getELContext();
+        ValueExpression ve = processor.getELManager().getExpressionFactory().createValueExpression(context,
+                "${Integer}", Object.class);
+        Assert.assertNotNull(ve.getValue(context));
+        Assert.assertEquals(ELClass.class, ve.getType(context));
+    }
+
+
+    @Test
+    public void testImport04() {
+        // getType() must resolve a statically imported field, just as
+        // getValue() does. The declared type of the field is reported, in the
+        // same way as for a bean property.
+        ELProcessor processor = new ELProcessor();
+        processor.getELManager().getELContext().getImportHandler().importStatic(
+                "java.lang.Integer.MAX_VALUE");
+        ELContext context = processor.getELManager().getELContext();
+        ValueExpression ve = processor.getELManager().getExpressionFactory().createValueExpression(context,
+                "${MAX_VALUE}", Object.class);
+        Assert.assertEquals(Integer.valueOf(Integer.MAX_VALUE), ve.getValue(context));
+        Assert.assertEquals(Integer.TYPE, ve.getType(context));
+    }
+
+
+    @Test
+    public void testImport05() {
+        // The resolver chain must take precedence over the import fallback in
+        // getType(), just as it does in getValue(). "Integer" is resolvable
+        // both ways: by the custom resolver and via the default class import.
+        ELProcessor processor = new ELProcessor();
+        processor.getELManager().addELResolver(new ELResolver() {
+            @Override
+            public Object getValue(ELContext context, Object base, Object property) {
+                if (base == null && "Integer".equals(property)) {
+                    context.setPropertyResolved(null, property);
+                    return "resolved";
+                }
+                return null;
+            }
+
+            @Override
+            public Class<?> getType(ELContext context, Object base, Object property) {
+                if (base == null && "Integer".equals(property)) {
+                    context.setPropertyResolved(null, property);
+                    return String.class;
+                }
+                return null;
+            }
+
+            @Override
+            public void setValue(ELContext context, Object base, Object property, Object value) {
+            }
+
+            @Override
+            public boolean isReadOnly(ELContext context, Object base, Object property) {
+                return false;
+            }
+
+            @Override
+            public Class<?> getCommonPropertyType(ELContext context, Object base) {
+                return null;
+            }
+        });
+        ELContext context = processor.getELManager().getELContext();
+        ValueExpression ve = processor.getELManager().getExpressionFactory().createValueExpression(context,
+                "${Integer}", Object.class);
+        Assert.assertEquals("resolved", ve.getValue(context));
+        Assert.assertEquals(String.class, ve.getType(context));
+    }
+
+
+    @Test
+    public void testUnresolvedGetType() {
+        // A name that getValue() cannot resolve must continue to report a
+        // PropertyNotFoundException from getType()
+        ELProcessor processor = new ELProcessor();
+        ELContext context = processor.getELManager().getELContext();
+        ValueExpression ve = processor.getELManager().getExpressionFactory().createValueExpression(context,
+                "${unresolvedName}", Object.class);
+        try {
+            ve.getType(context);
+            Assert.fail("A PropertyNotFoundException was expected");
+        } catch (PropertyNotFoundException e) {
+            // Expected
+        }
+    }
+
+
     @Test
     public void testIdentifierStart() {
         /*


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 20/20: Compatibility

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 66af02be769d91328442056586aa1f92712541b2
Author: remm <re...@apache.org>
AuthorDate: Sun Oct 18 18:13:57 2026 +0200

    Compatibility
---
 java/org/apache/el/MethodExpressionImpl.java    | 2 --
 java/org/apache/el/MethodExpressionLiteral.java | 2 --
 java/org/apache/el/ValueExpressionImpl.java     | 2 --
 test/org/apache/el/TestValueExpressionImpl.java | 6 +++---
 4 files changed, 3 insertions(+), 9 deletions(-)

diff --git a/java/org/apache/el/MethodExpressionImpl.java b/java/org/apache/el/MethodExpressionImpl.java
index 00c1ee7fcb..4de8495706 100644
--- a/java/org/apache/el/MethodExpressionImpl.java
+++ b/java/org/apache/el/MethodExpressionImpl.java
@@ -20,7 +20,6 @@ import java.io.Externalizable;
 import java.io.IOException;
 import java.io.ObjectInput;
 import java.io.ObjectOutput;
-import java.io.Serial;
 
 import jakarta.el.ELContext;
 import jakarta.el.ELException;
@@ -68,7 +67,6 @@ import org.apache.el.util.ReflectionUtil;
  */
 public final class MethodExpressionImpl extends MethodExpression implements Externalizable {
 
-    @Serial
     private static final long serialVersionUID = 1L;
 
     private Class<?> expectedType;
diff --git a/java/org/apache/el/MethodExpressionLiteral.java b/java/org/apache/el/MethodExpressionLiteral.java
index 182ae8e02f..c9fe57bd51 100644
--- a/java/org/apache/el/MethodExpressionLiteral.java
+++ b/java/org/apache/el/MethodExpressionLiteral.java
@@ -20,7 +20,6 @@ import java.io.Externalizable;
 import java.io.IOException;
 import java.io.ObjectInput;
 import java.io.ObjectOutput;
-import java.io.Serial;
 import java.lang.annotation.Annotation;
 
 import jakarta.el.ELContext;
@@ -38,7 +37,6 @@ import org.apache.el.util.ReflectionUtil;
  */
 public class MethodExpressionLiteral extends MethodExpression implements Externalizable {
 
-    @Serial
     private static final long serialVersionUID = 1L;
 
     private static final Annotation[] EMPTY_ANNOTATION_ARRAY = new Annotation[0];
diff --git a/java/org/apache/el/ValueExpressionImpl.java b/java/org/apache/el/ValueExpressionImpl.java
index a6a46c3321..2bd002a1c2 100644
--- a/java/org/apache/el/ValueExpressionImpl.java
+++ b/java/org/apache/el/ValueExpressionImpl.java
@@ -20,7 +20,6 @@ import java.io.Externalizable;
 import java.io.IOException;
 import java.io.ObjectInput;
 import java.io.ObjectOutput;
-import java.io.Serial;
 
 import jakarta.el.ELContext;
 import jakarta.el.ELException;
@@ -75,7 +74,6 @@ import org.apache.el.util.ReflectionUtil;
  */
 public final class ValueExpressionImpl extends ValueExpression implements Externalizable {
 
-    @Serial
     private static final long serialVersionUID = 1L;
 
     private Class<?> expectedType;
diff --git a/test/org/apache/el/TestValueExpressionImpl.java b/test/org/apache/el/TestValueExpressionImpl.java
index 1df77e220f..cec9a2edc8 100644
--- a/test/org/apache/el/TestValueExpressionImpl.java
+++ b/test/org/apache/el/TestValueExpressionImpl.java
@@ -88,7 +88,7 @@ public class TestValueExpressionImpl {
     @Test
     public void testGetValueReferenceMethodCall() {
         ExpressionFactory factory = ExpressionFactory.newInstance();
-        ELContext context = new ELContextImpl();
+        ELContext context = new ELContextImpl(factory);
 
         TesterBeanM beanM = new TesterBeanM();
         ValueExpression var = factory.createValueExpression(beanM, TesterBeanM.class);
@@ -104,7 +104,7 @@ public class TestValueExpressionImpl {
     @Test
     public void testGetValueReferenceMethodCallResult() {
         ExpressionFactory factory = ExpressionFactory.newInstance();
-        ELContext context = new ELContextImpl();
+        ELContext context = new ELContextImpl(factory);
 
         TesterBeanM beanM = new TesterBeanM();
         ValueExpression var = factory.createValueExpression(beanM, TesterBeanM.class);
@@ -124,7 +124,7 @@ public class TestValueExpressionImpl {
     @Test
     public void testGetValueReferencePropertyThenMethodCall() {
         ExpressionFactory factory = ExpressionFactory.newInstance();
-        ELContext context = new ELContextImpl();
+        ELContext context = new ELContextImpl(factory);
 
         TesterBeanM beanM = new TesterBeanM();
         ValueExpression var = factory.createValueExpression(beanM, TesterBeanM.class);


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 07/20: Reject multiple parameter sets for EL constructor and static calls

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit b6d261e9e565da2774f73cbc42a0024911eb1ebc
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 14:25:17 2026 +0200

    Reject multiple parameter sets for EL constructor and static calls
    
    When an unprefixed function call resolved through the import handler,
    to a class (constructor invocation) or a static import (static method
    invocation), AstFunction evaluated only the first set of method
    parameters and silently discarded any additional sets. Expressions
    such as ${Integer(1000)(2000)} and, with String.valueOf statically
    imported, ${valueOf('a')('b')} quietly ignored the trailing sets and
    returned the single-set result.
    
    The other two resolution paths in the same method already reject extra
    sets: the declared-function path raises
    error.function.tooManyMethodParameterSets and the lambda path raises
    error.lambda.tooManyMethodParameterSets after consuming one set per
    nested lambda. Only the lambda path supports chained parameter sets,
    since only a lambda can return something callable.
    
    Apply the same rule as the declared-function path to the constructor
    and static method dispatch, merging the two branches so the check runs
    once before invocation. The check sits inside the resolution guard so
    names that resolve to neither a class nor a static method continue to
    report the existing function-not-found error.
    
    Adds tests for both resolved paths and a test pinning the unchanged
    error for unresolved names.
---
 java/org/apache/el/parser/AstFunction.java     | 17 +++++++---
 test/org/apache/el/parser/TestAstFunction.java | 46 ++++++++++++++++++++++++++
 2 files changed, 58 insertions(+), 5 deletions(-)

diff --git a/java/org/apache/el/parser/AstFunction.java b/java/org/apache/el/parser/AstFunction.java
index 1c2e5e61ba..a94c294528 100644
--- a/java/org/apache/el/parser/AstFunction.java
+++ b/java/org/apache/el/parser/AstFunction.java
@@ -130,13 +130,20 @@ public final class AstFunction extends SimpleNode {
 
             // Call to a constructor or a static method
             obj = ctx.getImportHandler().resolveClass(this.localName);
-            if (obj != null) {
-                return ctx.getELResolver().invoke(ctx, new ELClass((Class<?>) obj), "<init>", null,
-                        ((AstMethodParameters) this.children[0]).getParameters(ctx));
+            String methodName = "<init>";
+            if (obj == null) {
+                obj = ctx.getImportHandler().resolveStatic(this.localName);
+                methodName = this.localName;
             }
-            obj = ctx.getImportHandler().resolveStatic(this.localName);
             if (obj != null) {
-                return ctx.getELResolver().invoke(ctx, new ELClass((Class<?>) obj), this.localName, null,
+                // The result of a constructor or static method call is not
+                // treated as a lambda expression so there must be just a single
+                // set of method parameters
+                if (this.jjtGetNumChildren() != 1) {
+                    throw new ELException(MessageFactory.get("error.function.tooManyMethodParameterSets",
+                            getOutputName()));
+                }
+                return ctx.getELResolver().invoke(ctx, new ELClass((Class<?>) obj), methodName, null,
                         ((AstMethodParameters) this.children[0]).getParameters(ctx));
             }
         }
diff --git a/test/org/apache/el/parser/TestAstFunction.java b/test/org/apache/el/parser/TestAstFunction.java
index e0ae0f6be8..2137afe565 100644
--- a/test/org/apache/el/parser/TestAstFunction.java
+++ b/test/org/apache/el/parser/TestAstFunction.java
@@ -17,6 +17,7 @@
 package org.apache.el.parser;
 
 import jakarta.el.ELContext;
+import jakarta.el.ELException;
 import jakarta.el.ELProcessor;
 import jakarta.el.ExpressionFactory;
 import jakarta.el.StandardELContext;
@@ -43,6 +44,51 @@ public class TestAstFunction {
         Assert.assertEquals(Integer.valueOf(1000), result);
     }
 
+    @Test
+    public void testImportConstructorTooManyParameterSets() {
+        // resolveClass path: the result of a constructor call is not treated as
+        // a lambda so only a single set of method parameters is valid. The extra
+        // set must be rejected rather than silently ignored.
+        ELProcessor processor = new ELProcessor();
+        try {
+            processor.getValue("Integer(1000)(2000)", Object.class);
+            Assert.fail("An ELException was expected");
+        } catch (ELException e) {
+            // Expected
+        }
+    }
+
+    @Test
+    public void testImportStaticTooManyParameterSets() {
+        // resolveStatic path: the result of a static method call is not treated
+        // as a lambda so only a single set of method parameters is valid. The
+        // extra set must be rejected rather than silently ignored.
+        ELProcessor processor = new ELProcessor();
+        processor.getELManager().getELContext().getImportHandler().importStatic("java.lang.String.valueOf");
+        try {
+            processor.getValue("valueOf('a')('b')", Object.class);
+            Assert.fail("An ELException was expected");
+        } catch (ELException e) {
+            // Expected
+        }
+    }
+
+    @Test
+    public void testUnresolvedNameTooManyParameterSets() {
+        // A name that resolves to neither a class nor a static method must still
+        // report the "function not found" error, not the too-many-parameters
+        // error. This pins the placement of the parameter-set check so that it
+        // cannot be hoisted above the resolution.
+        ELProcessor processor = new ELProcessor();
+        try {
+            processor.getValue("unknown(1)(2)", Object.class);
+            Assert.fail("An ELException was expected");
+        } catch (ELException e) {
+            Assert.assertTrue("Unexpected message: " + e.getMessage(),
+                    e.getMessage().contains("not found"));
+        }
+    }
+
     @Test
     public void testVarargMethod() throws NoSuchMethodException, SecurityException {
         ExpressionFactory factory = ExpressionFactory.newInstance();


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 16/20: Accept null results from EL stream comparator lambdas

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 9217b7c7ba3b1ffd822201c393be2ec12ff0974a
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 16:42:19 2026 +0200

    Accept null results from EL stream comparator lambdas
    
    The max, min and sorted stream operations evaluated their comparator
    lambda and coerced the result to a number with the boxed integer type
    as the target. That coercion returns null for a null value, so a
    comparator lambda that returned null triggered a null pointer
    exception when the coerced result was unboxed.
    
    The Jakarta EL specification types the comparator as a function to the
    primitive int, and the coercion to a primitive numeric type maps null
    and the empty string to zero. Coerce to the primitive type instead. A
    null comparator result now means that the two elements compare as
    equal, which for sorted leaves a stable sort in its input order and
    for max and min leaves the current element, while results that cannot
    be coerced at all continue to be reported as an ELException. The
    handling of non-null numeric results, including the truncation of
    fractional values, is unchanged.
    
    Adds tests for a null comparator result on the three operations and a
    test that a non-coercible comparator result is reported as an
    ELException. The null result tests report the null pointer exception
    against the previous implementation.
---
 java/org/apache/el/stream/Stream.java              | 10 ++--
 .../apache/el/stream/TestCollectionOperations.java | 59 ++++++++++++++++++++++
 2 files changed, 66 insertions(+), 3 deletions(-)

diff --git a/java/org/apache/el/stream/Stream.java b/java/org/apache/el/stream/Stream.java
index d4a5d23926..f7c80cb279 100644
--- a/java/org/apache/el/stream/Stream.java
+++ b/java/org/apache/el/stream/Stream.java
@@ -621,9 +621,11 @@ public class Stream {
 
         while (iterator.hasNext()) {
             Object obj = iterator.next();
-            if (isMax && ELSupport.coerceToNumber(null, le.invoke(obj, result), Integer.class).intValue() > 0) {
+            // Coerce to the primitive type so that a null comparator result
+            // coerces to zero rather than producing a NullPointerException
+            if (isMax && ELSupport.coerceToNumber(null, le.invoke(obj, result), Integer.TYPE).intValue() > 0) {
                 result = obj;
-            } else if (!isMax && ELSupport.coerceToNumber(null, le.invoke(obj, result), Integer.class).intValue() < 0) {
+            } else if (!isMax && ELSupport.coerceToNumber(null, le.invoke(obj, result), Integer.TYPE).intValue() < 0) {
                 result = obj;
             }
         }
@@ -646,7 +648,9 @@ public class Stream {
 
         @Override
         public int compare(Object o1, Object o2) {
-            return ELSupport.coerceToNumber(null, le.invoke(o1, o2), Integer.class).intValue();
+            // Coerce to the primitive type so that a null comparator result
+            // coerces to zero rather than producing a NullPointerException
+            return ELSupport.coerceToNumber(null, le.invoke(o1, o2), Integer.TYPE).intValue();
         }
     }
 
diff --git a/test/org/apache/el/stream/TestCollectionOperations.java b/test/org/apache/el/stream/TestCollectionOperations.java
index 688e098e24..c271c9250a 100644
--- a/test/org/apache/el/stream/TestCollectionOperations.java
+++ b/test/org/apache/el/stream/TestCollectionOperations.java
@@ -213,6 +213,23 @@ public class TestCollectionOperations {
     }
 
 
+    @Test
+    public void testSortedLambdaExpression02() {
+        // A comparator that returns null coerces to zero, treating all
+        // elements as equal. The sort is stable, so the order is unchanged.
+        ELProcessor processor = new ELProcessor();
+        Object result = processor.getValue(
+                "[3, 1, 2].stream().sorted((x,y)->null).toList()",
+                List.class);
+        List<Long> expected = new ArrayList<>(3);
+        expected.add(3L);
+        expected.add(1L);
+        expected.add(2L);
+
+        Assert.assertEquals(expected, result);
+    }
+
+
     @Test
     public void testForEach01() {
         ELProcessor processor = new ELProcessor();
@@ -433,6 +450,34 @@ public class TestCollectionOperations {
 
         Assert.assertEquals(bean03, ((Optional) result).get());
     }
+
+
+    @Test
+    public void testMaxLambda03() {
+        // A comparator that returns null coerces to zero, treating all
+        // elements as equal. The first element is retained.
+        ELProcessor processor = new ELProcessor();
+
+        Object result = processor.getValue(
+                "[1, 2, 3].stream().max((x,y)->null)",
+                Object.class);
+
+        Assert.assertEquals(1L, ((Optional) result).get());
+    }
+
+
+    @Test(expected=ELException.class)
+    public void testMaxLambda04() {
+        // A comparator result that cannot be coerced to a number is reported
+        // as an ELException
+        ELProcessor processor = new ELProcessor();
+
+        processor.getValue(
+                "[1, 2, 3].stream().max((x,y)->'abc')",
+                Object.class);
+    }
+
+
     @Test
     public void testMin01() {
         ELProcessor processor = new ELProcessor();
@@ -493,6 +538,20 @@ public class TestCollectionOperations {
     }
 
 
+    @Test
+    public void testMinLambda02() {
+        // A comparator that returns null coerces to zero, treating all
+        // elements as equal. The first element is retained.
+        ELProcessor processor = new ELProcessor();
+
+        Object result = processor.getValue(
+                "[1, 2, 3].stream().min((x,y)->null)",
+                Object.class);
+
+        Assert.assertEquals(1L, ((Optional) result).get());
+    }
+
+
     @Test
     public void testAverage01() {
         ELProcessor processor = new ELProcessor();


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 11/20: Report inaccessible methods in BeanELResolver as MethodNotFoundException

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 8a1ac3c5e9e80682424edf99a7cd623fe83257b2
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 15:17:41 2026 +0200

    Report inaccessible methods in BeanELResolver as MethodNotFoundException
    
    When a method call in an EL value expression was resolved by
    BeanELResolver, the search for a matching method could legitimately
    complete without finding an accessible method. A method with a
    matching name and signature exists but is treated as not found when
    the class that defines it is not public and the method is not exposed
    via a public interface or a public super class. The resolver then used
    the null result to build the call parameters, producing a raw
    NullPointerException. A valid expression such as calling a public
    method on a package-private bean reported an unexpected container
    error rather than the exception the EL API requires.
    
    Check for the null result and report a MethodNotFoundException with a
    message naming the method and the class. This matches how the sibling
    static method invocation in StaticFieldELResolver and the constructor
    lookup in Util already handle the same situation. The method
    expression path in org.apache.el already reported this case as a
    MethodNotFoundException and required no change.
    
    Adds tests for the no-argument and argument paths of a method that is
    only accessible on a non-public class, and for the unchanged case of a
    method exposed via a public interface. The first two report the raw
    NullPointerException against the previous implementation.
---
 java/jakarta/el/BeanELResolver.java     |  8 +++++
 java/jakarta/el/LocalStrings.properties |  2 ++
 test/jakarta/el/TestBeanELResolver.java | 58 +++++++++++++++++++++++++++++++++
 3 files changed, 68 insertions(+)

diff --git a/java/jakarta/el/BeanELResolver.java b/java/jakarta/el/BeanELResolver.java
index 0d8ad14558..69b45c6662 100644
--- a/java/jakarta/el/BeanELResolver.java
+++ b/java/jakarta/el/BeanELResolver.java
@@ -150,6 +150,14 @@ public class BeanELResolver extends ELResolver {
         // Find the matching method
         Method matchingMethod = Util.findMethod(context, base.getClass(), base, methodName, paramTypes, params);
 
+        // Util.findMethod() returns null when no accessible method was found,
+        // e.g. when the method exists but is not publicly accessible because
+        // the class that defines it is not public.
+        if (matchingMethod == null) {
+            throw new MethodNotFoundException(
+                    Util.message(context, "beanELResolver.methodNotFound", methodName, base.getClass().getName()));
+        }
+
         Object[] parameters =
                 Util.buildParameters(context, matchingMethod.getParameterTypes(), matchingMethod.isVarArgs(), params);
 
diff --git a/java/jakarta/el/LocalStrings.properties b/java/jakarta/el/LocalStrings.properties
index 525f92b919..a1b85ad2e0 100644
--- a/java/jakarta/el/LocalStrings.properties
+++ b/java/jakarta/el/LocalStrings.properties
@@ -16,6 +16,8 @@
 # Do not edit this file directly.
 # To edit translations see: https://tomcat.apache.org/getinvolved.html#Translations
 
+beanELResolver.methodNotFound=No matching public method named [{0}] found on class [{1}]
+
 beanNameELResolver.beanReadOnly=The bean name [{0}] is read-only
 
 elProcessor.defineFunctionInvalidClass=The class [{0}] is not public
diff --git a/test/jakarta/el/TestBeanELResolver.java b/test/jakarta/el/TestBeanELResolver.java
index 69ea92aaf1..6f58e2ac13 100644
--- a/test/jakarta/el/TestBeanELResolver.java
+++ b/test/jakarta/el/TestBeanELResolver.java
@@ -453,6 +453,48 @@ public class TestBeanELResolver {
         resolver.invoke(context, new TesterBean(BEAN_NAME), METHOD03_NAME, new Class<?>[] {}, new Object[] {});
     }
 
+    /**
+     * Tests that a call to a public method on a non-public class, where the
+     * method is not exposed via a public interface or super class, throws a
+     * MethodNotFoundException rather than producing a NullPointerException
+     * from the use of the null result of the method search.
+     */
+    @Test(expected = MethodNotFoundException.class)
+    public void testInvokeNonPublicClass01() {
+        BeanELResolver resolver = new BeanELResolver();
+        ELContext context = new StandardELContext(ELManager.getExpressionFactory());
+
+        resolver.invoke(context, new NonPublicBean(), "getName", new Class<?>[] {}, new Object[] {});
+    }
+
+    /**
+     * Tests the same behaviour as testInvokeNonPublicClass01() for a method
+     * with parameters, which is resolved via the slower, broader logic.
+     */
+    @Test(expected = MethodNotFoundException.class)
+    public void testInvokeNonPublicClass02() {
+        BeanELResolver resolver = new BeanELResolver();
+        ELContext context = new StandardELContext(ELManager.getExpressionFactory());
+
+        resolver.invoke(context, new NonPublicBean(), "echo", new Class<?>[] { String.class },
+                new Object[] { "value" });
+    }
+
+    /**
+     * Tests that a public method on a non-public class is invoked normally
+     * when it is exposed via a public interface.
+     */
+    @Test
+    public void testInvokeNonPublicClass03() {
+        BeanELResolver resolver = new BeanELResolver();
+        ELContext context = new StandardELContext(ELManager.getExpressionFactory());
+
+        Object result = resolver.invoke(context, new Bean(), "getValueC", new Class<?>[] {}, new Object[] {});
+
+        Assert.assertEquals("Default", result);
+        Assert.assertTrue(context.isPropertyResolved());
+    }
+
     @Test
     public void testInvokeVarargsCoerce01() {
         BeanELResolver resolver = new BeanELResolver();
@@ -968,6 +1010,22 @@ public class TestBeanELResolver {
     }
 
 
+    /*
+     * Deliberately not public. The methods are only accessible via this class
+     * so, for the purposes of the EL, they are not accessible at all.
+     */
+    private static class NonPublicBean {
+
+        public String getName() {
+            return BEAN_NAME;
+        }
+
+        public String echo(String value) {
+            return value;
+        }
+    }
+
+
     public interface MyInterface {
         default String getValueC() {
             return "Default";


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 13/20: Evaluate each expression once for EL method references

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 833197d84e9a21e8d5dc95ab3a87b8486719e544
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 16:01:40 2026 +0200

    Evaluate each expression once for EL method references
    
    When building a method reference, AstValue resolved the method from the
    base and the parameter values, then constructed the method information
    by calling getMethodInfo, which re-ran the whole resolution: it walked
    the base property chain again, re-evaluated the parameter expressions
    and looked the method up again. Expressions with side effects, such as
    a method call as an argument, were therefore evaluated twice per
    reference, and the reported method information and annotations could
    come from a different evaluation than the base and the parameters of
    the reference. The resolution in getMethodInfo also ran without the
    values, while the reference itself resolved with them, so an expression
    whose arguments required coercion or were null reported a method not
    found error, even though invoking the very same expression succeeded.
    
    Construct the method information from the method that the reference
    already resolved. The base, the coerced parameters, the method
    information and the annotations now all come from a single evaluation,
    consistent with how the same expression is invoked.
    
    Adds a test that counts the evaluations of the base chain getter and of
    a method call used as an argument, and asserts the base, the parameters
    and the method information all come from that single evaluation. The
    test reports two evaluations of each against the previous
    implementation.
---
 java/org/apache/el/parser/AstValue.java          |  6 ++-
 test/org/apache/el/TestMethodExpressionImpl.java | 35 ++++++++++++++++
 test/org/apache/el/TesterBeanK.java              | 51 ++++++++++++++++++++++++
 3 files changed, 91 insertions(+), 1 deletion(-)

diff --git a/java/org/apache/el/parser/AstValue.java b/java/org/apache/el/parser/AstValue.java
index 55013fab88..68d4df7181 100644
--- a/java/org/apache/el/parser/AstValue.java
+++ b/java/org/apache/el/parser/AstValue.java
@@ -265,7 +265,11 @@ public final class AstValue extends SimpleNode {
         // Handle varArgs and any coercion required
         values = convertArgs(ctx, values, m);
 
-        return new MethodReference(t.base, getMethodInfo(ctx, types), m.getAnnotations(), values);
+        // The method information is taken from the method resolved above, so
+        // that the base chain and the parameters are evaluated only once
+        MethodInfo mi = new MethodInfo(m.getName(), m.getReturnType(), m.getParameterTypes());
+
+        return new MethodReference(t.base, mi, m.getAnnotations(), values);
     }
 
 
diff --git a/test/org/apache/el/TestMethodExpressionImpl.java b/test/org/apache/el/TestMethodExpressionImpl.java
index 50844b14b1..76bab3122d 100644
--- a/test/org/apache/el/TestMethodExpressionImpl.java
+++ b/test/org/apache/el/TestMethodExpressionImpl.java
@@ -24,6 +24,7 @@ import jakarta.el.ExpressionFactory;
 import jakarta.el.MethodExpression;
 import jakarta.el.MethodInfo;
 import jakarta.el.MethodNotFoundException;
+import jakarta.el.MethodReference;
 import jakarta.el.ValueExpression;
 
 import org.junit.Assert;
@@ -752,6 +753,40 @@ public class TestMethodExpressionImpl {
     }
 
 
+    @Test
+    public void testGetReference01() {
+        // Building a method reference must evaluate the base chain and the
+        // parameters exactly once
+        ELProcessor elp = new ELProcessor();
+        TesterBeanK bean = new TesterBeanK();
+        TesterBeanK child = new TesterBeanK();
+        bean.setChild(child);
+        elp.defineBean("beanK", bean);
+        ELContext elpContext = elp.getELManager().getELContext();
+
+        MethodExpression me = elp.getELManager().getExpressionFactory().createMethodExpression(elpContext,
+                "${beanK.child.format(beanK.next())}", String.class, null);
+
+        MethodReference ref = me.getMethodReference(elpContext);
+
+        Assert.assertEquals(1, bean.baseCalls);
+        Assert.assertEquals(1, bean.argCalls);
+        Assert.assertEquals("format", ref.getMethodInfo().getName());
+        // The base, parameters and method information must all come from the
+        // single evaluation
+        Assert.assertSame(child, ref.getBase());
+        Assert.assertArrayEquals(new Object[] { Integer.valueOf(1) }, ref.getEvaluatedParameters());
+
+        // Invoke must also evaluate each exactly once
+        bean.baseCalls = 0;
+        bean.argCalls = 0;
+
+        Assert.assertEquals("formatted-1", me.invoke(elpContext, null));
+        Assert.assertEquals(1, bean.baseCalls);
+        Assert.assertEquals(1, bean.argCalls);
+    }
+
+
     @Test
     public void testGetMethodInfo01() throws Exception {
         MethodExpression me = factory.createMethodExpression(context, "#{beanA.setName('New value')}", null, null);
diff --git a/test/org/apache/el/TesterBeanK.java b/test/org/apache/el/TesterBeanK.java
new file mode 100644
index 0000000000..a65d4b7aa2
--- /dev/null
+++ b/test/org/apache/el/TesterBeanK.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.el;
+
+/*
+ * Counts how often the getter used for the base chain and the method used as
+ * a parameter are evaluated.
+ */
+public class TesterBeanK {
+
+    public int baseCalls = 0;
+    public int argCalls = 0;
+
+    private TesterBeanK child;
+
+
+    public TesterBeanK getChild() {
+        baseCalls++;
+        return child;
+    }
+
+
+    public void setChild(TesterBeanK child) {
+        this.child = child;
+    }
+
+
+    public int next() {
+        argCalls++;
+        return argCalls;
+    }
+
+
+    public String format(int value) {
+        return "formatted-" + value;
+    }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 08/20: Correct the EL empty operator for empty primitive arrays

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 875c8630e84a3ba316efe79ad6eaeb5fc5a6f0df
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 14:34:04 2026 +0200

    Correct the EL empty operator for empty primitive arrays
    
    The EL specification defines the empty operator as true when the
    operand evaluates to an empty array. AstAbstractEmpty tested arrays
    with instanceof Object[] and Array.length, which only matches object
    arrays. A one-dimensional primitive array, such as an int[0] returned
    by a bean property, is not an instance of Object[], so empty evaluated
    to false and not empty to true, silently inverting the spec result.
    Other array handling in the EL implementation (the stream resolver and
    ELSupport) already uses the primitive-array-correct reflective checks.
    
    Test array-ness with Class.isArray() and length with
    java.lang.reflect.Array.getLength() instead. The null disjunct
    precedes this test and short-circuits, so no additional null guard is
    required. Multi-dimensional behaviour is unchanged: an empty outer
    array is empty and a non-empty outer array with empty inner arrays is
    not, consistent with the previous treatment of equivalent object
    arrays.
    
    Adds tests to TestAstEmpty and TestAstNotEmpty covering empty and
    filled primitive arrays plus an empty object array as a regression
    guard for the original path. The primitive-array tests fail against
    the previous implementation.
---
 java/org/apache/el/parser/AstAbstractEmpty.java |  3 ++-
 test/org/apache/el/parser/TestAstEmpty.java     | 29 +++++++++++++++++++++++++
 test/org/apache/el/parser/TestAstNotEmpty.java  | 19 ++++++++++++++++
 3 files changed, 50 insertions(+), 1 deletion(-)

diff --git a/java/org/apache/el/parser/AstAbstractEmpty.java b/java/org/apache/el/parser/AstAbstractEmpty.java
index e3c38dcf3f..c798b94412 100644
--- a/java/org/apache/el/parser/AstAbstractEmpty.java
+++ b/java/org/apache/el/parser/AstAbstractEmpty.java
@@ -17,6 +17,7 @@
 /* Generated By:JJTree: Do not edit this line. AstAbstractEmpty.java */
 package org.apache.el.parser;
 
+import java.lang.reflect.Array;
 import java.util.Collection;
 import java.util.Map;
 
@@ -53,7 +54,7 @@ public abstract class AstAbstractEmpty extends SimpleNode {
     public Object getValue(EvaluationContext ctx) throws ELException {
         Object obj = this.children[0].getValue(ctx);
         if (obj == null || obj instanceof String && ((String) obj).isEmpty() ||
-                obj instanceof Object[] && ((Object[]) obj).length == 0 ||
+                obj.getClass().isArray() && Array.getLength(obj) == 0 ||
                 obj instanceof Collection<?> && ((Collection<?>) obj).isEmpty() ||
                 obj instanceof Map<?,?> && ((Map<?,?>) obj).isEmpty()) {
             return RETURN_EMPTY;
diff --git a/test/org/apache/el/parser/TestAstEmpty.java b/test/org/apache/el/parser/TestAstEmpty.java
index 1523967189..c90f7fe29e 100644
--- a/test/org/apache/el/parser/TestAstEmpty.java
+++ b/test/org/apache/el/parser/TestAstEmpty.java
@@ -37,4 +37,33 @@ public class TestAstEmpty {
         Boolean result = processor.eval("empty ''");
         Assert.assertEquals(Boolean.TRUE, result);
     }
+
+    @Test
+    public void test03() {
+        // An array with no elements is empty. This includes primitive arrays.
+        ELProcessor processor = new ELProcessor();
+        processor.defineBean("arr", new int[0]);
+        Boolean result = processor.eval("empty arr");
+        Assert.assertEquals(Boolean.TRUE, result);
+    }
+
+
+
+    @Test
+    public void test04() {
+        ELProcessor processor = new ELProcessor();
+        processor.defineBean("arr", new int[] { 1, 2 });
+        Boolean result = processor.eval("empty arr");
+        Assert.assertEquals(Boolean.FALSE, result);
+    }
+
+
+
+    @Test
+    public void test05() {
+        ELProcessor processor = new ELProcessor();
+        processor.defineBean("arr", new Object[0]);
+        Boolean result = processor.eval("empty arr");
+        Assert.assertEquals(Boolean.TRUE, result);
+    }
 }
diff --git a/test/org/apache/el/parser/TestAstNotEmpty.java b/test/org/apache/el/parser/TestAstNotEmpty.java
index dceca6bb1c..8e6c9e9973 100644
--- a/test/org/apache/el/parser/TestAstNotEmpty.java
+++ b/test/org/apache/el/parser/TestAstNotEmpty.java
@@ -37,4 +37,23 @@ public class TestAstNotEmpty {
         Boolean result = processor.eval("not empty ''");
         Assert.assertEquals(Boolean.FALSE, result);
     }
+
+
+    @Test
+    public void test03() {
+        // An array with no elements is empty. This includes primitive arrays.
+        ELProcessor processor = new ELProcessor();
+        processor.defineBean("arr", new int[0]);
+        Boolean result = processor.eval("not empty arr");
+        Assert.assertEquals(Boolean.FALSE, result);
+    }
+
+
+    @Test
+    public void test04() {
+        ELProcessor processor = new ELProcessor();
+        processor.defineBean("arr", new int[] { 1, 2 });
+        Boolean result = processor.eval("not empty arr");
+        Assert.assertEquals(Boolean.TRUE, result);
+    }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 12/20: Accept zero varargs elements in EL method expression calls

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit ddb7764886ab0b33dad32417d4597b030052d18e
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 15:40:28 2026 +0200

    Accept zero varargs elements in EL method expression calls
    
    The argument count check in AstValue.convertArgs, which prepares the
    arguments for a method expression invocation, rejected calls that
    supplied exactly the fixed parameters of a varargs method. A varargs
    method with N parameters accepts N minus 1 arguments, the final
    parameter being supplied by zero or more arguments, but the guard
    required N. Such calls were reported as IllegalArgumentException even
    though the same call written directly in the expression, and the same
    call through the value expression mechanism, both worked. The two
    invocation mechanisms disagreed on valid Java arity.
    
    Reduce the required count by one for varargs methods and report the
    true minimum in the too-few-parameters message. Building the trailing
    varargs array already handles the zero-element case for every
    component type.
    
    Two existing tests relied on the incorrect arity. testBug60844
    asserted the rejected error for a call with one value of the wrong
    type against a method whose minimum arity is one; that call is now
    valid by arity and fails in the argument coercion with an ELException,
    as it would via the value expression mechanism, so the test now uses a
    genuinely too-few call and still pins the reported error.
    testStaticMethodOnInstance asserted the rejection of a call with only
    the format string; the call is valid and the test now asserts the
    correct result. Adds tests for calls with zero and one varargs
    elements.
---
 java/org/apache/el/parser/AstValue.java          |  7 +++--
 test/org/apache/el/TestMethodExpressionImpl.java | 35 ++++++++++++++++++++++--
 test/org/apache/el/util/TestReflectionUtil.java  | 18 ++++++------
 3 files changed, 46 insertions(+), 14 deletions(-)

diff --git a/java/org/apache/el/parser/AstValue.java b/java/org/apache/el/parser/AstValue.java
index e0e53e7eeb..55013fab88 100644
--- a/java/org/apache/el/parser/AstValue.java
+++ b/java/org/apache/el/parser/AstValue.java
@@ -278,7 +278,10 @@ public final class AstValue extends SimpleNode {
 
         int paramCount = types.length;
 
-        if (m.isVarArgs() && paramCount > 1 && (src == null || paramCount > src.length) ||
+        // For a varargs method, the final parameter may be supplied by zero or
+        // more arguments so the minimum number of arguments is one less than
+        // the number of parameters.
+        if (m.isVarArgs() && paramCount > 1 && (src == null || paramCount - 1 > src.length) ||
                 !m.isVarArgs() && (src == null || src.length != paramCount)) {
             String srcCount = null;
             if (src != null) {
@@ -287,7 +290,7 @@ public final class AstValue extends SimpleNode {
             String msg;
             if (m.isVarArgs()) {
                 msg = MessageFactory.get("error.invoke.tooFewParams", m.getName(), srcCount,
-                        Integer.toString(paramCount));
+                        Integer.toString(paramCount - 1));
             } else {
                 msg = MessageFactory.get("error.invoke.wrongParams", m.getName(), srcCount,
                         Integer.toString(paramCount));
diff --git a/test/org/apache/el/TestMethodExpressionImpl.java b/test/org/apache/el/TestMethodExpressionImpl.java
index 0701725a81..50844b14b1 100644
--- a/test/org/apache/el/TestMethodExpressionImpl.java
+++ b/test/org/apache/el/TestMethodExpressionImpl.java
@@ -492,9 +492,13 @@ public class TestMethodExpressionImpl {
 
     @Test(expected = IllegalArgumentException.class)
     public void testBug60844() {
+        // Fewer parameter values than the minimum required by a varargs
+        // method (here, the fixed parameters only). A single value would be
+        // a valid number of arguments for this method, so the call below
+        // with no values is the too-few-parameters case.
         MethodExpression me2 = factory.createMethodExpression(context, "${beanC.sayHello}", null,
-                new Class[] { TesterBeanA.class, TesterBeanB.class });
-        me2.invoke(context, new Object[] { new Object() });
+                new Class[] { TesterBeanA.class });
+        me2.invoke(context, new Object[] { });
     }
 
 
@@ -721,6 +725,33 @@ public class TestMethodExpressionImpl {
     }
 
 
+    @Test
+    public void testVarArgsZeroVarArgsElements() {
+        // A call that supplies only the fixed parameters of a varargs method
+        // is valid Java. The method expression mechanism must accept it, as
+        // the value expression mechanism already does.
+        context.getVariableMapper().setVariable("beanH",
+                factory.createValueExpression(new TesterBeanH(), TesterBeanH.class));
+
+        MethodExpression me = factory.createMethodExpression(context, "${beanH.doTest}", String.class,
+                new Class<?>[] { String.class });
+
+        Assert.assertEquals("String-VString", me.invoke(context, new Object[] { "apple" }));
+    }
+
+
+    @Test
+    public void testVarArgsOneVarArgsElement() {
+        context.getVariableMapper().setVariable("beanH",
+                factory.createValueExpression(new TesterBeanH(), TesterBeanH.class));
+
+        MethodExpression me = factory.createMethodExpression(context, "${beanH.doTest}", String.class,
+                new Class<?>[] { String.class, String.class });
+
+        Assert.assertEquals("String-VString", me.invoke(context, new Object[] { "apple", "apple" }));
+    }
+
+
     @Test
     public void testGetMethodInfo01() throws Exception {
         MethodExpression me = factory.createMethodExpression(context, "#{beanA.setName('New value')}", null, null);
diff --git a/test/org/apache/el/util/TestReflectionUtil.java b/test/org/apache/el/util/TestReflectionUtil.java
index 4362fc255e..ee194ea7da 100644
--- a/test/org/apache/el/util/TestReflectionUtil.java
+++ b/test/org/apache/el/util/TestReflectionUtil.java
@@ -72,16 +72,14 @@ public class TestReflectionUtil {
         ExpressionFactory factory = ExpressionFactory.newInstance();
         ELContext context = new ELContextImpl(factory);
 
-        MethodExpression methodExpression = factory.createMethodExpression(context, "${\"1\".format(2)}", String.class, new Class<?>[] {});
+        MethodExpression methodExpression = factory.createMethodExpression(context, "${\"1\".format(2)}", String.class,
+                new Class<?>[] {});
 
-        try {
-            methodExpression.invoke(context, null);
-        } catch (IllegalArgumentException iae) {
-            // Ensure correct IllegalArgumentException is thrown
-            String msg = iae.getMessage();
-            Assert.assertTrue(msg, msg.contains("[format]"));
-            return;
-        }
-        Assert.fail("No exception");
+        // The static method format(String,Object...) must be resolvable and
+        // invocable when called on an instance. The single argument is the
+        // format string. No varargs elements are provided which is valid.
+        Object result = methodExpression.invoke(context, null);
+
+        Assert.assertEquals("2", result);
     }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 18/20: Correct the method call check in AstValue.getValueReference

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit fdcd59beb0f92b3b527057a6d9ab420ec3cbebfa
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 17:05:30 2026 +0200

    Correct the method call check in AstValue.getValueReference
    
    The value reference of an expression is null unless the expression is a
    reference to a property of a base object. To tell a method call from a
    property reference, getValueReference checked whether the third child
    of the value node was the parameter list. The parameter list is the
    last child of a value node, which is only the third child when the
    expression is a single method call. Two shapes were therefore
    misclassified. A property of the result of a method call, such as
    ${bean.select('x').name}, reported no value reference although it is a
    reference to the name property of the object the method call returns.
    A method call on the result of a property, such as
    ${bean.target.select('x')}, reported a value reference for the property
    and the name of the method, and even evaluated the property along the
    way, although a method call must not produce a value reference at all.
    
    Use the class's own check for the presence of a parameter list, the
    same one the evaluation of the node uses, in place of the positional
    guess. Method calls are now recognised before the base is resolved, so
    they return null without evaluating anything.
    
    Adds tests for a method call, for a property of the result of a method
    call and for a method call on the result of a property, along with a
    test bean that provides such a method. Two of the three report the
    wrong result against the previous implementation.
---
 java/org/apache/el/parser/AstValue.java         |  2 +-
 test/org/apache/el/TestValueExpressionImpl.java | 53 +++++++++++++++++++++++++
 test/org/apache/el/TesterBeanM.java             | 38 ++++++++++++++++++
 3 files changed, 92 insertions(+), 1 deletion(-)

diff --git a/java/org/apache/el/parser/AstValue.java b/java/org/apache/el/parser/AstValue.java
index 68d4df7181..52e96b5031 100644
--- a/java/org/apache/el/parser/AstValue.java
+++ b/java/org/apache/el/parser/AstValue.java
@@ -451,7 +451,7 @@ public final class AstValue extends SimpleNode {
     @Override
     public ValueReference getValueReference(EvaluationContext ctx) {
         // Check this is a reference to a base and a property
-        if (this.children.length > 2 && this.jjtGetChild(2) instanceof AstMethodParameters) {
+        if (isParametersProvided()) {
             // This is a method call
             return null;
         }
diff --git a/test/org/apache/el/TestValueExpressionImpl.java b/test/org/apache/el/TestValueExpressionImpl.java
index 928400e3c8..1df77e220f 100644
--- a/test/org/apache/el/TestValueExpressionImpl.java
+++ b/test/org/apache/el/TestValueExpressionImpl.java
@@ -85,6 +85,59 @@ public class TestValueExpressionImpl {
         Assert.assertEquals("name", vr.getProperty());
     }
 
+    @Test
+    public void testGetValueReferenceMethodCall() {
+        ExpressionFactory factory = ExpressionFactory.newInstance();
+        ELContext context = new ELContextImpl();
+
+        TesterBeanM beanM = new TesterBeanM();
+        ValueExpression var = factory.createValueExpression(beanM, TesterBeanM.class);
+        context.getVariableMapper().setVariable("beanM", var);
+
+        ValueExpression ve = factory.createValueExpression(context, "${beanM.select('Tomcat')}", String.class);
+
+        // A method call is not a reference to a base and a property
+        ValueReference vr = ve.getValueReference(context);
+        Assert.assertNull(vr);
+    }
+
+    @Test
+    public void testGetValueReferenceMethodCallResult() {
+        ExpressionFactory factory = ExpressionFactory.newInstance();
+        ELContext context = new ELContextImpl();
+
+        TesterBeanM beanM = new TesterBeanM();
+        ValueExpression var = factory.createValueExpression(beanM, TesterBeanM.class);
+        context.getVariableMapper().setVariable("beanM", var);
+
+        ValueExpression ve = factory.createValueExpression(context, "${beanM.select('Tomcat').name}", String.class);
+
+        // The result of the method call is the base of the property
+        // reference, so this is a reference to a base and a property
+        ValueReference vr = ve.getValueReference(context);
+        Assert.assertNotNull(vr);
+
+        Assert.assertEquals(beanM.getTarget(), vr.getBase());
+        Assert.assertEquals("name", vr.getProperty());
+    }
+
+    @Test
+    public void testGetValueReferencePropertyThenMethodCall() {
+        ExpressionFactory factory = ExpressionFactory.newInstance();
+        ELContext context = new ELContextImpl();
+
+        TesterBeanM beanM = new TesterBeanM();
+        ValueExpression var = factory.createValueExpression(beanM, TesterBeanM.class);
+        context.getVariableMapper().setVariable("beanM", var);
+
+        ValueExpression ve = factory.createValueExpression(context, "${beanM.target.select('Tomcat')}", String.class);
+
+        // A method call is not a reference to a base and a property, even
+        // when the base of the method call is itself a property
+        ValueReference vr = ve.getValueReference(context);
+        Assert.assertNull(vr);
+    }
+
     @Test
     public void testBug49345() {
         ExpressionFactory factory = ExpressionFactory.newInstance();
diff --git a/test/org/apache/el/TesterBeanM.java b/test/org/apache/el/TesterBeanM.java
new file mode 100644
index 0000000000..285fbe18ff
--- /dev/null
+++ b/test/org/apache/el/TesterBeanM.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.el;
+
+/*
+ * Provides a method that takes a parameter and returns a bean, for tests of
+ * the value reference of expressions that combine method calls and property
+ * references.
+ */
+public class TesterBeanM {
+
+    private final TesterBeanB target = new TesterBeanB();
+
+
+    public TesterBeanB getTarget() {
+        return target;
+    }
+
+
+    public TesterBeanB select(String name) {
+        target.setName(name);
+        return target;
+    }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 03/20: Fix broken tests.

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit a2cfa7250a23ddadc8a6284fc56186ba809f83b7
Author: Mark Thomas <ma...@apache.org>
AuthorDate: Fri Jul 4 18:21:38 2025 +0100

    Fix broken tests.
    
    If obj0 != obj1 and either is null, the algorithm for relational
    operators terminates before reaching the Comparable section. So these
    objects should not not null if processing gets as far as the Comparable
    section.
---
 java/org/apache/el/LocalStrings.properties |  1 +
 java/org/apache/el/lang/ELSupport.java     | 26 ++++++++++++++------------
 test/org/apache/el/TestELEvaluation.java   | 18 +++++++++++-------
 3 files changed, 26 insertions(+), 19 deletions(-)

diff --git a/java/org/apache/el/LocalStrings.properties b/java/org/apache/el/LocalStrings.properties
index f11270f5e8..3915106e60 100644
--- a/java/org/apache/el/LocalStrings.properties
+++ b/java/org/apache/el/LocalStrings.properties
@@ -20,6 +20,7 @@ elSupport.coerce.nonAbstract=Unable to coerce a LambdaExpression to the function
 
 error.cannotSetVariables=Cannot set variables on factory
 error.compare=Cannot compare [{0}] to [{1}]
+error.compare.null=Unable to compare null with non-null object
 error.context.null=ELContext was null
 error.convert=Cannot convert [{0}] of type [{1}] to [{2}]
 error.fnMapper.method=Function [{0}] not found
diff --git a/java/org/apache/el/lang/ELSupport.java b/java/org/apache/el/lang/ELSupport.java
index 73df04c372..b92d290f79 100644
--- a/java/org/apache/el/lang/ELSupport.java
+++ b/java/org/apache/el/lang/ELSupport.java
@@ -28,6 +28,7 @@ import java.security.AccessController;
 import java.security.PrivilegedAction;
 import java.util.Collections;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 import java.util.function.Supplier;
 
@@ -66,21 +67,19 @@ public class ELSupport {
      * If the objects are identical, or they are equal according to {@link #equals(ELContext, Object, Object)} then
      * return 0.
      * <p>
+     * If either object is null, error
+     * <p>
      * If either object is a BigDecimal, then coerce both to BigDecimal first. Similarly for Double(Float), BigInteger,
      * and Long(Integer, Char, Short, Byte).
      * <p>
-     * Otherwise, check that the first object is an instance of Comparable, and compare against the second object. If
-     * that is null, return 1, otherwise return the result of comparing against the second object.
+     * If either object is TemporalAccessor, Clock, java.util.Date or java.sql.Timestamp, coerce both to Instant and
+     * then compare.
+     * <p>
+     * If the first object is an instance of Comparable, return the result of comparing against the second object.
      * <p>
-     * Similarly, if the second object is Comparable, if the first is null, return -1, else return the result of
-     * comparing against the first object.
+     * If the second object is an instance of Comparable, return -1 * the result of comparing against the first object.
      * <p>
-     * A null object is considered as:
-     * <ul>
-     * <li>ZERO when compared with Numbers</li>
-     * <li>the empty string for String compares</li>
-     * <li>Otherwise null is considered to be lower than anything else.</li>
-     * </ul>
+     * Otherwise, error.
      *
      * @param ctx  the context in which this comparison is taking place
      * @param obj0 first object
@@ -96,6 +95,9 @@ public class ELSupport {
         if (obj0 == obj1 || equals(ctx, obj0, obj1)) {
             return 0;
         }
+        Objects.requireNonNull(obj0, MessageFactory.get("error.compare.null"));
+        Objects.requireNonNull(obj1, MessageFactory.get("error.compare.null"));
+
         if (isBigDecimalOp(obj0, obj1)) {
             BigDecimal bd0 = (BigDecimal) coerceToNumber(ctx, obj0, BigDecimal.class);
             BigDecimal bd1 = (BigDecimal) coerceToNumber(ctx, obj1, BigDecimal.class);
@@ -122,12 +124,12 @@ public class ELSupport {
         if (obj0 instanceof Comparable<?>) {
             @SuppressWarnings("unchecked") // checked above
             final Comparable<Object> comparable = (Comparable<Object>) obj0;
-            return (obj1 != null) ? comparable.compareTo(obj1) : 1;
+            return comparable.compareTo(obj1);
         }
         if (obj1 instanceof Comparable<?>) {
             @SuppressWarnings("unchecked") // checked above
             final Comparable<Object> comparable = (Comparable<Object>) obj1;
-            return (obj0 != null) ? -comparable.compareTo(obj0) : -1;
+            return -comparable.compareTo(obj0);
         }
         throw new ELException(MessageFactory.get("error.compare", obj0, obj1));
     }
diff --git a/test/org/apache/el/TestELEvaluation.java b/test/org/apache/el/TestELEvaluation.java
index fb560b1569..89b76696eb 100644
--- a/test/org/apache/el/TestELEvaluation.java
+++ b/test/org/apache/el/TestELEvaluation.java
@@ -160,24 +160,28 @@ public class TestELEvaluation {
     private void compareBoth(String msg, int expected, Object o1, Object o2) {
         int i1 = ELSupport.compare(null, o1, o2);
         int i2 = ELSupport.compare(null, o2, o1);
-        Assert.assertEquals(msg, expected, i1);
-        Assert.assertEquals(msg, expected, -i2);
+        if (expected == -1) {
+            Assert.assertTrue(msg, i1 < 0);
+            Assert.assertTrue(msg, i2 > 0);
+        } else if (expected == 0) {
+            Assert.assertTrue(msg, i1 == 0);
+            Assert.assertTrue(msg, i2 == 0);
+        } else {
+            Assert.assertTrue(msg, i1 > 0);
+            Assert.assertTrue(msg, i2 < 0);
+         }
     }
 
     @Test
     public void testElSupportCompare() {
         compareBoth("Nulls should compare equal", 0, null, null);
-        compareBoth("Null should compare equal to \"\"", 0, "", null);
-        compareBoth("Null should be less than File()", -1, null, new File(""));
-        compareBoth("Null should be less than Date()", -1, null, new Date());
         compareBoth("Date(0) should be less than Date(1)", -1, new Date(0), new Date(1));
         try {
             compareBoth("Should not compare", 0, new Date(), new File(""));
             Assert.fail("Expecting ClassCastException");
-        } catch (ClassCastException expected) {
+        } catch (ELException expected) {
             // Expected
         }
-        Assert.assertTrue(null == null);
     }
 
     /**


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 15/20: Coerce EL stream predicate results in the match operations

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit bede36c6ebdb7b725155189ab0593a7f5581dcba
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 16:29:15 2026 +0200

    Coerce EL stream predicate results in the match operations
    
    The anyMatch, allMatch and noneMatch stream operations treated the
    result of each predicate evaluation as an already boxed boolean by
    casting it. A predicate returning null produced a raw
    NullPointerException when the loop next inspected the result, and a
    predicate returning any other non-boolean type, such as a number,
    produced a ClassCastException. The filter operation, which takes the
    same predicate type, instead coerced the result: null and the empty
    string meant false, a convertible string was honoured, and anything
    else was reported as an ELException. The Jakarta EL specification
    types the predicate as a function to boolean and defines a coercion
    for producing a boolean from an arbitrary value, which is what the
    filter operation applies.
    
    Coerce the predicate results in the three match operations with the
    same coercion used by filter, so the predicate-consuming operations
    agree on what a predicate result means and invalid results are
    reported as conversion errors rather than as unexpected runtime
    exceptions. The short-circuit behaviour of the three operations is
    unchanged.
    
    Adds tests for a null predicate result and for a non-boolean predicate
    result on the three operations. The null result tests report the raw
    NullPointerException against the previous implementation.
---
 java/org/apache/el/stream/Stream.java              |  6 +--
 .../apache/el/stream/TestCollectionOperations.java | 59 ++++++++++++++++++++++
 2 files changed, 62 insertions(+), 3 deletions(-)

diff --git a/java/org/apache/el/stream/Stream.java b/java/org/apache/el/stream/Stream.java
index a045179dcb..d4a5d23926 100644
--- a/java/org/apache/el/stream/Stream.java
+++ b/java/org/apache/el/stream/Stream.java
@@ -514,7 +514,7 @@ public class Stream {
         Boolean match = Boolean.FALSE;
 
         while (!match.booleanValue() && iterator.hasNext()) {
-            match = (Boolean) le.invoke(iterator.next());
+            match = ELSupport.coerceToBoolean(null, le.invoke(iterator.next()), true);
         }
 
         return new Optional(match);
@@ -535,7 +535,7 @@ public class Stream {
         Boolean match = Boolean.TRUE;
 
         while (match.booleanValue() && iterator.hasNext()) {
-            match = (Boolean) le.invoke(iterator.next());
+            match = ELSupport.coerceToBoolean(null, le.invoke(iterator.next()), true);
         }
 
         return new Optional(match);
@@ -556,7 +556,7 @@ public class Stream {
         Boolean match = Boolean.FALSE;
 
         while (!match.booleanValue() && iterator.hasNext()) {
-            match = (Boolean) le.invoke(iterator.next());
+            match = ELSupport.coerceToBoolean(null, le.invoke(iterator.next()), true);
         }
 
         return new Optional(Boolean.valueOf(!match.booleanValue()));
diff --git a/test/org/apache/el/stream/TestCollectionOperations.java b/test/org/apache/el/stream/TestCollectionOperations.java
index 1d33a6c5ab..688e098e24 100644
--- a/test/org/apache/el/stream/TestCollectionOperations.java
+++ b/test/org/apache/el/stream/TestCollectionOperations.java
@@ -751,6 +751,65 @@ public class TestCollectionOperations {
     }
 
 
+    @Test(expected=ELException.class)
+    public void testAnyMatch04() {
+        // A predicate that returns a non-boolean must be coerced, producing an
+        // ELException, as for filter()
+        ELProcessor processor = new ELProcessor();
+
+        processor.getValue(
+                "[1,2,3].stream().anyMatch(x->x)",
+                Object.class);
+    }
+
+
+    @Test
+    public void testAnyMatch05() {
+        // A null predicate result is coerced to false, as for filter()
+        ELProcessor processor = new ELProcessor();
+
+        Optional result = (Optional) processor.getValue(
+                "[1,2,3].stream().anyMatch(x->null)",
+                Object.class);
+
+        Assert.assertEquals(Boolean.FALSE, result.get());
+    }
+
+
+    @Test(expected=ELException.class)
+    public void testAllMatch05() {
+        ELProcessor processor = new ELProcessor();
+
+        processor.getValue(
+                "[1,2,3].stream().allMatch(x->x)",
+                Object.class);
+    }
+
+
+    @Test
+    public void testAllMatch06() {
+        ELProcessor processor = new ELProcessor();
+
+        Optional result = (Optional) processor.getValue(
+                "[1,2,3].stream().allMatch(x->null)",
+                Object.class);
+
+        Assert.assertEquals(Boolean.FALSE, result.get());
+    }
+
+
+    @Test
+    public void testNoneMatch05() {
+        ELProcessor processor = new ELProcessor();
+
+        Optional result = (Optional) processor.getValue(
+                "[1,2,3].stream().noneMatch(x->null)",
+                Object.class);
+
+        Assert.assertEquals(Boolean.TRUE, result.get());
+    }
+
+
     @Test
     public void testFindFirst01() {
         ELProcessor processor = new ELProcessor();


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 05/20: Report accurate result type for EL concatenation expressions

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 1d1c7f3aaf81c928fa0883bc7c578f0107722b7a
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 13:45:34 2026 +0200

    Report accurate result type for EL concatenation expressions
    
    AstConcatenation (the += operator) merges Maps, Sets and Lists
    in-place when the operand types match and only falls back to string
    concatenation otherwise, but getType() unconditionally reported
    String.class. Applications calling ValueExpression.getType() on a
    merge expression such as ${m1 += m2} were told the result was a
    String while getValue() returned the merged Map.
    
    getType() now evaluates both operands and mirrors the branch
    structure of getValue(), returning the left operand's concrete class
    for the merge branches and String.class for the string concatenation
    path. Unlike getValue() it performs no putAll()/addAll() mutations;
    evaluating the operands is required to determine the type, consistent
    with AstChoice, AstElvis, AstNullCoalescing and AstAssign getType()
    implementations and with the documented ValueExpression.getType()
    contract.
    
    Adds regression tests for the Map, Set and List merge branches and
    for the unchanged string path.
---
 java/org/apache/el/parser/AstConcatenation.java    | 19 ++++++++
 .../org/apache/el/parser/TestAstConcatenation.java | 51 ++++++++++++++++++++++
 2 files changed, 70 insertions(+)

diff --git a/java/org/apache/el/parser/AstConcatenation.java b/java/org/apache/el/parser/AstConcatenation.java
index ae83893170..9caf78705f 100644
--- a/java/org/apache/el/parser/AstConcatenation.java
+++ b/java/org/apache/el/parser/AstConcatenation.java
@@ -40,6 +40,25 @@ public class AstConcatenation extends SimpleNode {
 
     @Override
     public Class<?> getType(EvaluationContext ctx) throws ELException {
+        // Mirror the getValue type determination, but without performing any
+        // merging. The operands must be evaluated to determine the result type.
+        Object obj0 = this.children[0].getValue(ctx);
+        Object obj1 = this.children[1].getValue(ctx);
+
+        if (obj0 != null) {
+            if (obj0 instanceof Map<?, ?> && obj1 instanceof Map<?, ?>) {
+                // Maps are merged
+                return obj0.getClass();
+            } else if (obj0 instanceof Set<?> && obj1 instanceof Collection<?>) {
+                // If obj0 is a Set then merge
+                return obj0.getClass();
+            } else if (obj0 instanceof List<?> && obj1 instanceof Collection<?>) {
+                // If obj0 is a List then concatenate
+                return obj0.getClass();
+            }
+        }
+
+        // Otherwise the values are coerced to string and concatenated
         return String.class;
     }
 }
diff --git a/test/org/apache/el/parser/TestAstConcatenation.java b/test/org/apache/el/parser/TestAstConcatenation.java
index 68c51a8782..be2921cbcc 100644
--- a/test/org/apache/el/parser/TestAstConcatenation.java
+++ b/test/org/apache/el/parser/TestAstConcatenation.java
@@ -119,4 +119,55 @@ public class TestAstConcatenation {
         Assert.assertEquals(String.class, ve.getType(context));
         Assert.assertEquals("a3", ve.getValue(context));
     }
+
+    @Test
+    public void testGetTypeMapMerge() {
+        // The merge branches of += produce the left operand, not a string, so
+        // getType() must not report String for them.
+        ELProcessor processor = new ELProcessor();
+        ELContext context = processor.getELManager().getELContext();
+        ExpressionFactory factory = ELManager.getExpressionFactory();
+
+        ValueExpression ve = factory.createValueExpression(
+                context, "${{'a':'1'} += {'b':'2'}}", Object.class);
+
+        Assert.assertTrue(Map.class.isAssignableFrom(ve.getType(context)));
+    }
+
+    @Test
+    public void testGetTypeSetMerge() {
+        ELProcessor processor = new ELProcessor();
+        ELContext context = processor.getELManager().getELContext();
+        ExpressionFactory factory = ELManager.getExpressionFactory();
+
+        ValueExpression ve = factory.createValueExpression(
+                context, "${{'a','b'} += ['c']}", Object.class);
+
+        Assert.assertTrue(Set.class.isAssignableFrom(ve.getType(context)));
+    }
+
+    @Test
+    public void testGetTypeListMerge() {
+        ELProcessor processor = new ELProcessor();
+        ELContext context = processor.getELManager().getELContext();
+        ExpressionFactory factory = ELManager.getExpressionFactory();
+
+        ValueExpression ve = factory.createValueExpression(
+                context, "${['a','b'] += ['c']}", Object.class);
+
+        Assert.assertTrue(List.class.isAssignableFrom(ve.getType(context)));
+    }
+
+    @Test
+    public void testGetTypeStringConcatenation() {
+        // Non-collection operands still take the string concatenation path.
+        ELProcessor processor = new ELProcessor();
+        ELContext context = processor.getELManager().getELContext();
+        ExpressionFactory factory = ELManager.getExpressionFactory();
+
+        ValueExpression ve = factory.createValueExpression(
+                context, "${1 += 2}", Object.class);
+
+        Assert.assertEquals(String.class, ve.getType(context));
+    }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 19/20: Fix bad merge

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 0c9270778b61aa48cecc6f1d88b0fb8372ae4618
Author: remm <re...@apache.org>
AuthorDate: Sun Oct 18 18:02:58 2026 +0200

    Fix bad merge
---
 java/org/apache/el/parser/AstConcatenation.java     | 5 +++++
 test/org/apache/el/parser/TestAstConcatenation.java | 4 ++++
 2 files changed, 9 insertions(+)

diff --git a/java/org/apache/el/parser/AstConcatenation.java b/java/org/apache/el/parser/AstConcatenation.java
index 9caf78705f..a24ba2f9ab 100644
--- a/java/org/apache/el/parser/AstConcatenation.java
+++ b/java/org/apache/el/parser/AstConcatenation.java
@@ -17,6 +17,11 @@
 /* Generated By:JJTree: Do not edit this line. AstConcatenation.java Version 4.3 */
 package org.apache.el.parser;
 
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
 import jakarta.el.ELException;
 
 import org.apache.el.lang.ELSupport;
diff --git a/test/org/apache/el/parser/TestAstConcatenation.java b/test/org/apache/el/parser/TestAstConcatenation.java
index be2921cbcc..993408ef63 100644
--- a/test/org/apache/el/parser/TestAstConcatenation.java
+++ b/test/org/apache/el/parser/TestAstConcatenation.java
@@ -16,6 +16,10 @@
  */
 package org.apache.el.parser;
 
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
 import jakarta.el.ELContext;
 import jakarta.el.ELManager;
 import jakarta.el.ELProcessor;


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 06/20: Pass empty array for empty EL function varargs

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 377c490db184bf48d51c21fe0e62d0bb399b3d93
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 14:05:30 2026 +0200

    Pass empty array for empty EL function varargs
    
    The Jakarta EL varargs function support intended to match Java
    varargs semantics. Two call shapes did not. A varargs-only function
    called with no arguments received a null array because AstFunction
    built the reflective argument array as new Object[] { null }. A mixed
    fixed and varargs function called with only the fixed arguments
    received a length-1 varargs array holding a spurious element, because
    the varargs slot was initialised to new Object[] { null } which the
    subsequent coercion converted to e.g. String[]{ "" } for String
    components or a null element otherwise. Plain Java always passes an
    empty array in both cases.
    
    Pass an empty array of the varargs parameter's exact component type
    instead: built with Array.newInstance() for the zero-argument case,
    which is required because reflection rejects an Object[] argument for
    a typed varargs parameter such as String... (the array previously held
    a null element so the mismatch never surfaced), and as an empty Object[]
    that the existing coercion converts to the component type for the
    mixed case.
    
    This makes functions behave like direct Java calls, e.g. a format
    function on String.format(String,Object...) now raises the same
    MissingFormatArgumentException that String.format("%s") does, rather
    than rendering a phantom null element. The existing BZ 60431 tests
    still pass; they could not detect the deviation because the spurious
    element was invisible to their string concatenation assertions.
    
    Adds tester methods and tests that report varargs array length, so a
    null array (-1) and a spurious element (length 1) are now distinguishable
    from the correct empty array (length 0).
---
 java/org/apache/el/parser/AstFunction.java     |  9 +++++++--
 test/org/apache/el/TesterFunctions.java        | 10 +++++++++
 test/org/apache/el/parser/TestAstFunction.java | 28 ++++++++++++++++++++++++++
 3 files changed, 45 insertions(+), 2 deletions(-)

diff --git a/java/org/apache/el/parser/AstFunction.java b/java/org/apache/el/parser/AstFunction.java
index 7bfa0e5d3a..1c2e5e61ba 100644
--- a/java/org/apache/el/parser/AstFunction.java
+++ b/java/org/apache/el/parser/AstFunction.java
@@ -17,6 +17,7 @@
 /* Generated By:JJTree: Do not edit this line. AstFunction.java */
 package org.apache.el.parser;
 
+import java.lang.reflect.Array;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 
@@ -156,14 +157,18 @@ public final class AstFunction extends SimpleNode {
         int inputParameterCount = parameters.jjtGetNumChildren();
         int methodParameterCount = paramTypes.length;
         if (inputParameterCount == 0 && methodParameterCount == 1 && m.isVarArgs()) {
-            params = new Object[] { null };
+            // Java semantics: an empty array of the varargs component type is
+            // passed when no varargs elements are supplied
+            params = new Object[] { Array.newInstance(paramTypes[0].getComponentType(), 0) };
         } else if (inputParameterCount > 0) {
             params = new Object[methodParameterCount];
             try {
                 for (int i = 0; i < methodParameterCount; i++) {
                     if (m.isVarArgs() && i == methodParameterCount - 1) {
                         if (inputParameterCount < methodParameterCount) {
-                            params[i] = new Object[] { null };
+                            // Java semantics: an empty array is passed when no
+                            // varargs elements are supplied
+                            params[i] = new Object[0];
                         } else if (inputParameterCount == methodParameterCount &&
                                 isArray(parameters.jjtGetChild(i).getValue(ctx))) {
                             params[i] = parameters.jjtGetChild(i).getValue(ctx);
diff --git a/test/org/apache/el/TesterFunctions.java b/test/org/apache/el/TesterFunctions.java
index 904fba0c89..c7f1994f5a 100644
--- a/test/org/apache/el/TesterFunctions.java
+++ b/test/org/apache/el/TesterFunctions.java
@@ -44,6 +44,16 @@ public class TesterFunctions {
         return result.toString();
     }
 
+    public static int varargsLength(String... inputs) {
+        // Distinguishes a null varargs array from an empty one
+        return inputs == null ? -1 : inputs.length;
+    }
+
+    public static int varargsLength2(String prefix, String... inputs) {
+        // Distinguishes a null varargs array from an empty one
+        return inputs == null ? -1 : inputs.length;
+    }
+
     public static String[] toArray(String a, String b) {
         return new String[] { a, b };
     }
diff --git a/test/org/apache/el/parser/TestAstFunction.java b/test/org/apache/el/parser/TestAstFunction.java
index 4b3a6572bd..e0ae0f6be8 100644
--- a/test/org/apache/el/parser/TestAstFunction.java
+++ b/test/org/apache/el/parser/TestAstFunction.java
@@ -24,6 +24,8 @@ import jakarta.el.StandardELContext;
 import org.junit.Assert;
 import org.junit.Test;
 
+import org.apache.el.TesterFunctions;
+
 public class TestAstFunction {
 
     @Test
@@ -59,4 +61,30 @@ public class TestAstFunction {
         result = factory.createValueExpression(context, "${fn:format('%s','one')}", String.class).getValue(context);
         Assert.assertEquals("one", result);
     }
+
+    @Test
+    public void testVarargMethodEmptyVarargs01() throws NoSuchMethodException {
+        // Java passes an empty array, never null, to a varargs method that is
+        // called with no arguments
+        ExpressionFactory factory = ExpressionFactory.newInstance();
+        ELContext context = new StandardELContext(factory);
+        context.getFunctionMapper().mapFunction("fn", "count",
+                TesterFunctions.class.getMethod("varargsLength", String[].class));
+
+        Object result = factory.createValueExpression(context, "${fn:count()}", Integer.class).getValue(context);
+        Assert.assertEquals(Integer.valueOf(0), result);
+    }
+
+    @Test
+    public void testVarargMethodEmptyVarargs02() throws NoSuchMethodException {
+        // Java passes an empty array, never null, to the varargs parameter of a
+        // mixed fixed and varargs method that is called with no varargs elements
+        ExpressionFactory factory = ExpressionFactory.newInstance();
+        ELContext context = new StandardELContext(factory);
+        context.getFunctionMapper().mapFunction("fn", "count2",
+                TesterFunctions.class.getMethod("varargsLength2", String.class, String[].class));
+
+        Object result = factory.createValueExpression(context, "${fn:count2('x')}", Integer.class).getValue(context);
+        Assert.assertEquals(Integer.valueOf(0), result);
+    }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 01/20: Correct equals() implementations in method expression classes

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit ba38d8490dc4cc5005015fb421fccd37e9a8c850
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 12:45:43 2026 +0200

    Correct equals() implementations in method expression classes
    
    MethodExpressionImpl.equals() and MethodExpressionLiteral.equals()
    previously decided equality by comparing only the hashCode() of the
    expression string. Distinct expressions whose expression strings
    happened to have colliding 32-bit hash codes were therefore reported
    as equal, violating the equals() contract and the documented
    jakarta.el.Expression "identical parsed representation" semantics.
    
    MethodExpressionImpl now mirrors ValueExpressionImpl: equals() uses
    the hash code only as a fast path filter and then compares the parsed
    AST nodes (SimpleNode provides semantic equals()/hashCode() based on
    node type, image and children), with hashCode() derived from the
    parsed node so the equals()/hashCode() contract holds, including for
    expressions that differ only in whitespace. MethodExpressionLiteral
    now compares the literal expression string directly.
    
    Adds unit tests covering identical expressions, whitespace variants,
    different expressions and the classic "Aa"/"BB" string hash-collision
    pair for both classes.
---
 java/org/apache/el/MethodExpressionImpl.java     | 11 +++-
 java/org/apache/el/MethodExpressionLiteral.java  |  6 ++-
 test/org/apache/el/TestMethodExpressionImpl.java | 69 ++++++++++++++++++++++++
 3 files changed, 83 insertions(+), 3 deletions(-)

diff --git a/java/org/apache/el/MethodExpressionImpl.java b/java/org/apache/el/MethodExpressionImpl.java
index 8e0b7ed897..190e281aef 100644
--- a/java/org/apache/el/MethodExpressionImpl.java
+++ b/java/org/apache/el/MethodExpressionImpl.java
@@ -128,7 +128,14 @@ public final class MethodExpressionImpl extends MethodExpression implements Exte
      */
     @Override
     public boolean equals(Object obj) {
-        return (obj instanceof MethodExpressionImpl && obj.hashCode() == this.hashCode());
+        if (!(obj instanceof MethodExpressionImpl)) {
+            return false;
+        }
+        if (obj.hashCode() != this.hashCode()) {
+            return false;
+        }
+
+        return this.getNode().equals(((MethodExpressionImpl) obj).getNode());
     }
 
     /**
@@ -207,7 +214,7 @@ public final class MethodExpressionImpl extends MethodExpression implements Exte
      */
     @Override
     public int hashCode() {
-        return this.expr.hashCode();
+        return this.getNode().hashCode();
     }
 
     /**
diff --git a/java/org/apache/el/MethodExpressionLiteral.java b/java/org/apache/el/MethodExpressionLiteral.java
index 8e8f68eda7..09846c7b99 100644
--- a/java/org/apache/el/MethodExpressionLiteral.java
+++ b/java/org/apache/el/MethodExpressionLiteral.java
@@ -111,7 +111,11 @@ public class MethodExpressionLiteral extends MethodExpression implements Externa
 
     @Override
     public boolean equals(Object obj) {
-        return (obj instanceof MethodExpressionLiteral && this.hashCode() == obj.hashCode());
+        if (!(obj instanceof MethodExpressionLiteral)) {
+            return false;
+        }
+
+        return this.expr.equals(((MethodExpressionLiteral) obj).expr);
     }
 
     @Override
diff --git a/test/org/apache/el/TestMethodExpressionImpl.java b/test/org/apache/el/TestMethodExpressionImpl.java
index f9af586722..0701725a81 100644
--- a/test/org/apache/el/TestMethodExpressionImpl.java
+++ b/test/org/apache/el/TestMethodExpressionImpl.java
@@ -744,4 +744,73 @@ public class TestMethodExpressionImpl {
         Assert.assertEquals(1, mi.getParamTypes().length);
         Assert.assertEquals(String.class, mi.getParamTypes()[0]);
     }
+
+
+    @Test
+    public void testEqualsHashCodeSameExpression() {
+        MethodExpression me1 = factory.createMethodExpression(context, "${beanB.getName}", String.class,
+                new Class<?>[] {});
+        MethodExpression me2 = factory.createMethodExpression(context, "${beanB.getName}", String.class,
+                new Class<?>[] {});
+
+        Assert.assertEquals(me1, me2);
+        Assert.assertEquals(me1.hashCode(), me2.hashCode());
+    }
+
+
+    @Test
+    public void testEqualsHashCodeWhitespaceVariants() {
+        MethodExpression me1 = factory.createMethodExpression(context, "${beanB.getName}", String.class,
+                new Class<?>[] {});
+        MethodExpression me2 = factory.createMethodExpression(context, "${ beanB.getName }", String.class,
+                new Class<?>[] {});
+
+        Assert.assertEquals(me1, me2);
+        Assert.assertEquals(me1.hashCode(), me2.hashCode());
+    }
+
+
+    @Test
+    public void testNotEqualsDifferentExpression() {
+        MethodExpression me1 = factory.createMethodExpression(context, "${beanB.getName}", String.class,
+                new Class<?>[] {});
+        MethodExpression me2 = factory.createMethodExpression(context, "${beanBB.getName}", String.class,
+                new Class<?>[] {});
+
+        Assert.assertNotEquals(me1, me2);
+    }
+
+
+    @Test
+    public void testNotEqualsHashCollidingExpressions() {
+        // "Aa" and "BB" are a well known pair of strings with the same hash code
+        Assert.assertEquals("Aa".hashCode(), "BB".hashCode());
+
+        MethodExpression me1 = factory.createMethodExpression(context, "${Aa}", String.class, new Class<?>[] {});
+        MethodExpression me2 = factory.createMethodExpression(context, "${BB}", String.class, new Class<?>[] {});
+
+        Assert.assertNotEquals(me1, me2);
+    }
+
+
+    @Test
+    public void testEqualsHashCodeSameLiteral() {
+        MethodExpression me1 = factory.createMethodExpression(context, "'Aa'", String.class, new Class<?>[] {});
+        MethodExpression me2 = factory.createMethodExpression(context, "'Aa'", String.class, new Class<?>[] {});
+
+        Assert.assertEquals(me1, me2);
+        Assert.assertEquals(me1.hashCode(), me2.hashCode());
+    }
+
+
+    @Test
+    public void testNotEqualsHashCollidingLiterals() {
+        // "Aa" and "BB" are a well known pair of strings with the same hash code
+        Assert.assertEquals("'Aa'".hashCode(), "'BB'".hashCode());
+
+        MethodExpression me1 = factory.createMethodExpression(context, "'Aa'", String.class, new Class<?>[] {});
+        MethodExpression me2 = factory.createMethodExpression(context, "'BB'", String.class, new Class<?>[] {});
+
+        Assert.assertNotEquals(me1, me2);
+    }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 02/20: Pin serialVersionUID in EL expression classes

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 21021ff89ed40364f3825fa48c07ac4eee768dd8
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 13:00:33 2026 +0200

    Pin serialVersionUID in EL expression classes
    
    MethodExpressionImpl, ValueExpressionImpl and MethodExpressionLiteral
    are Externalizable classes that, per the jakarta.el Expression
    contract, are intended to be serialized to preserve expression state
    across the application lifetime. Unlike their sibling classes
    (ValueExpressionLiteral, FunctionMapperImpl, VariableMapperImpl, all
    of which are reachable in the same serialized streams and all of
    which have long pinned a serialVersionUID), these three relied on the
    JVM-computed default UID, which changes whenever the class structure
    changes, making cross-version deserialization fragile.
    
    Add @Serial private static final long serialVersionUID = 1L to each
    class, aligning them with the existing package convention. Verified
    that same-version serialization round-trips of all four expression
    classes continue to work and that the EL testsuite passes unchanged.
---
 java/org/apache/el/MethodExpressionImpl.java    | 4 ++++
 java/org/apache/el/MethodExpressionLiteral.java | 4 ++++
 java/org/apache/el/ValueExpressionImpl.java     | 4 ++++
 3 files changed, 12 insertions(+)

diff --git a/java/org/apache/el/MethodExpressionImpl.java b/java/org/apache/el/MethodExpressionImpl.java
index 190e281aef..00c1ee7fcb 100644
--- a/java/org/apache/el/MethodExpressionImpl.java
+++ b/java/org/apache/el/MethodExpressionImpl.java
@@ -20,6 +20,7 @@ import java.io.Externalizable;
 import java.io.IOException;
 import java.io.ObjectInput;
 import java.io.ObjectOutput;
+import java.io.Serial;
 
 import jakarta.el.ELContext;
 import jakarta.el.ELException;
@@ -67,6 +68,9 @@ import org.apache.el.util.ReflectionUtil;
  */
 public final class MethodExpressionImpl extends MethodExpression implements Externalizable {
 
+    @Serial
+    private static final long serialVersionUID = 1L;
+
     private Class<?> expectedType;
 
     private String expr;
diff --git a/java/org/apache/el/MethodExpressionLiteral.java b/java/org/apache/el/MethodExpressionLiteral.java
index 09846c7b99..182ae8e02f 100644
--- a/java/org/apache/el/MethodExpressionLiteral.java
+++ b/java/org/apache/el/MethodExpressionLiteral.java
@@ -20,6 +20,7 @@ import java.io.Externalizable;
 import java.io.IOException;
 import java.io.ObjectInput;
 import java.io.ObjectOutput;
+import java.io.Serial;
 import java.lang.annotation.Annotation;
 
 import jakarta.el.ELContext;
@@ -37,6 +38,9 @@ import org.apache.el.util.ReflectionUtil;
  */
 public class MethodExpressionLiteral extends MethodExpression implements Externalizable {
 
+    @Serial
+    private static final long serialVersionUID = 1L;
+
     private static final Annotation[] EMPTY_ANNOTATION_ARRAY = new Annotation[0];
     private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
 
diff --git a/java/org/apache/el/ValueExpressionImpl.java b/java/org/apache/el/ValueExpressionImpl.java
index 67fc44aca1..a6a46c3321 100644
--- a/java/org/apache/el/ValueExpressionImpl.java
+++ b/java/org/apache/el/ValueExpressionImpl.java
@@ -20,6 +20,7 @@ import java.io.Externalizable;
 import java.io.IOException;
 import java.io.ObjectInput;
 import java.io.ObjectOutput;
+import java.io.Serial;
 
 import jakarta.el.ELContext;
 import jakarta.el.ELException;
@@ -74,6 +75,9 @@ import org.apache.el.util.ReflectionUtil;
  */
 public final class ValueExpressionImpl extends ValueExpression implements Externalizable {
 
+    @Serial
+    private static final long serialVersionUID = 1L;
+
     private Class<?> expectedType;
 
     private String expr;


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 04/20: Surface EL arithmetic and comparison errors as ELException

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit a760ac19d7ef593db2910cda98f5a024a8a136cb
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 13:33:29 2026 +0200

    Surface EL arithmetic and comparison errors as ELException
    
    The Jakarta EL specification requires errors during arithmetic and
    comparison operator evaluation to surface as ELException, and the
    public API (ValueExpression.getValue(), ELProcessor.eval(),
    ExpressionFactory.coerceToType() etc.) only declares ELException.
    Several failure modes were instead leaking raw JDK runtime exceptions
    to callers:
    
    - coercing a non-numeric string during arithmetic leaked the
      NumberFormatException from Long.valueOf(), Double.valueOf(),
      new BigDecimal(String) and new BigInteger(String)
    - coercing NaN or Infinity for a BigDecimal operand leaked the
      NumberFormatException from new BigDecimal(double)
    - coercing a Number with an odd toString() representation for a
      BigInteger operand leaked a NumberFormatException
    - integer/BigInteger modulo by zero and BigDecimal/BigInteger
      division by zero leaked the ArithmeticException
    - BigDecimal addition and subtraction of extreme exponents leaked
      the ArithmeticException declared by BigDecimal.add()/subtract(),
      reachable from plain EL literals such as ${1e999999999 + 1}
    - comparing mutually non-comparable Comparable implementations
      leaked the ClassCastException from compareTo()
    - coercing an extreme BigDecimal to BigInteger leaked the
      ArithmeticException from BigDecimal.toBigInteger() through the
      public coercion API
    
    ELArithmetic.coerce() now wraps any NumberFormatException as an
    ELException using the existing error.convert message. The static
    add/subtract/divide/mod methods wrap ArithmeticException as an
    ELException using new error.add/error.subtract/error.divide/error.mod
    messages. ELSupport.coerceToNumber() wraps the BigDecimal and
    BigInteger coercion failures, and ELSupport.compare() wraps the
    ClassCastException from the two Comparable branches as the existing
    error.compare ELException. The original exception is preserved as
    the cause in every case so applications that were catching the raw
    types can still inspect it via getCause().
    
    Spec-defined outcomes such as 1 / 0 returning Infinity and successful
    coercions are unchanged. Adds regression tests covering all of the
    above failure modes.
---
 java/org/apache/el/LocalStrings.properties    |   5 ++
 java/org/apache/el/lang/ELArithmetic.java     |  86 +++++++++++++++------
 java/org/apache/el/lang/ELSupport.java        |  28 +++++--
 test/org/apache/el/lang/TestELArithmetic.java | 104 ++++++++++++++++++++++++++
 test/org/apache/el/lang/TestELSupport.java    |  81 ++++++++++++++++++++
 5 files changed, 274 insertions(+), 30 deletions(-)

diff --git a/java/org/apache/el/LocalStrings.properties b/java/org/apache/el/LocalStrings.properties
index 3915106e60..4085b91edf 100644
--- a/java/org/apache/el/LocalStrings.properties
+++ b/java/org/apache/el/LocalStrings.properties
@@ -19,10 +19,13 @@
 elSupport.coerce.nonAbstract=Unable to coerce a LambdaExpression to the functional interface [{0}] because the method [{1}] is not abstract
 
 error.cannotSetVariables=Cannot set variables on factory
+error.add=Cannot add [{0}] to [{1}]
+error.convert=Cannot convert [{0}] of type [{1}] to [{2}]
 error.compare=Cannot compare [{0}] to [{1}]
 error.compare.null=Unable to compare null with non-null object
 error.context.null=ELContext was null
 error.convert=Cannot convert [{0}] of type [{1}] to [{2}]
+error.divide=Cannot divide [{0}] by [{1}]
 error.fnMapper.method=Function [{0}] not found
 error.fnMapper.null=Expression uses functions, but no FunctionMapper was provided
 error.fnMapper.paramcount=Function [{0}] specifies [{1}] params, but [{2}] were declared
@@ -40,6 +43,7 @@ error.method.ambiguous=Unable to find unambiguous method: {0}.{1}({2})
 error.method.notfound=Method not found: {0}.{1}({2})
 error.method.nullParms=Parameter types cannot be null
 error.mixed=Expression cannot contain both ''#{...}'' and ''${...}'' : [{0}]
+error.mod=Cannot compute [{0}] modulo [{1}]
 error.noFunctionMapperTarget=FunctionMapper target cannot be null
 error.noVariableMapperTarget=VariableMapper target cannot be null
 error.null=Expression cannot be null
@@ -48,6 +52,7 @@ error.nullMethod=Method cannot be null
 error.parseFail=Failed to parse the expression [{0}]
 error.resolver.unhandled=ELResolver did not handle type: [{0}] with property of [{1}]
 error.resolver.unhandled.null=ELResolver cannot handle a null base Object with identifier [{0}]
+error.subtract=Cannot subtract [{1}] from [{0}]
 error.syntax.set=Illegal Syntax for Set Operation
 error.unreachable.base=Target Unreachable, identifier [{0}] resolved to null
 error.unreachable.property=Target Unreachable, [{0}] returned null
diff --git a/java/org/apache/el/lang/ELArithmetic.java b/java/org/apache/el/lang/ELArithmetic.java
index 481155d7e3..3ec9bdf102 100644
--- a/java/org/apache/el/lang/ELArithmetic.java
+++ b/java/org/apache/el/lang/ELArithmetic.java
@@ -303,7 +303,11 @@ public abstract class ELArithmetic {
      *
      * @param obj0 The first operand
      * @param obj1 The second operand
+     *
      * @return The result of the addition
+     *
+     * @throws ELException if the operands cannot be coerced to numbers or if the addition cannot be computed, for
+     *                     example overflow with extreme BigDecimal values
      */
     public static Number add(final Object obj0, final Object obj1) {
         final ELArithmetic delegate = findDelegate(obj0, obj1);
@@ -311,10 +315,14 @@ public abstract class ELArithmetic {
             return Long.valueOf(0);
         }
 
-        Number num0 = delegate.coerce(obj0);
-        Number num1 = delegate.coerce(obj1);
+        try {
+            Number num0 = delegate.coerce(obj0);
+            Number num1 = delegate.coerce(obj1);
 
-        return delegate.add(num0, num1);
+            return delegate.add(num0, num1);
+        } catch (ArithmeticException ae) {
+            throw new ELException(MessageFactory.get("error.add", obj0, obj1), ae);
+        }
     }
 
     /**
@@ -322,7 +330,11 @@ public abstract class ELArithmetic {
      *
      * @param obj0 The dividend
      * @param obj1 The divisor
+     *
      * @return The result of the modulo operation
+     *
+     * @throws ELException if the operands cannot be coerced to numbers or if the modulo cannot be computed, for
+     *                     example division by zero with integer operands
      */
     public static Number mod(final Object obj0, final Object obj1) {
         if (obj0 == null && obj1 == null) {
@@ -340,10 +352,14 @@ public abstract class ELArithmetic {
             delegate = LONG;
         }
 
-        Number num0 = delegate.coerce(obj0);
-        Number num1 = delegate.coerce(obj1);
+        try {
+            Number num0 = delegate.coerce(obj0);
+            Number num1 = delegate.coerce(obj1);
 
-        return delegate.mod(num0, num1);
+            return delegate.mod(num0, num1);
+        } catch (ArithmeticException ae) {
+            throw new ELException(MessageFactory.get("error.mod", obj0, obj1), ae);
+        }
     }
 
     /**
@@ -351,7 +367,11 @@ public abstract class ELArithmetic {
      *
      * @param obj0 The minuend
      * @param obj1 The subtrahend
+     *
      * @return The result of the subtraction
+     *
+     * @throws ELException if the operands cannot be coerced to numbers or if the subtraction cannot be computed, for
+     *                     example overflow with extreme BigDecimal values
      */
     public static Number subtract(final Object obj0, final Object obj1) {
         final ELArithmetic delegate = findDelegate(obj0, obj1);
@@ -359,10 +379,14 @@ public abstract class ELArithmetic {
             return Long.valueOf(0);
         }
 
-        Number num0 = delegate.coerce(obj0);
-        Number num1 = delegate.coerce(obj1);
+        try {
+            Number num0 = delegate.coerce(obj0);
+            Number num1 = delegate.coerce(obj1);
 
-        return delegate.subtract(num0, num1);
+            return delegate.subtract(num0, num1);
+        } catch (ArithmeticException ae) {
+            throw new ELException(MessageFactory.get("error.subtract", obj0, obj1), ae);
+        }
     }
 
     /**
@@ -370,7 +394,11 @@ public abstract class ELArithmetic {
      *
      * @param obj0 The dividend
      * @param obj1 The divisor
+     *
      * @return The result of the division
+     *
+     * @throws ELException if the operands cannot be coerced to numbers or if the division cannot be computed, for
+     *                     example division by zero with BigDecimal or BigInteger operands
      */
     public static Number divide(final Object obj0, final Object obj1) {
         if (obj0 == null && obj1 == null) {
@@ -386,10 +414,14 @@ public abstract class ELArithmetic {
             delegate = DOUBLE;
         }
 
-        Number num0 = delegate.coerce(obj0);
-        Number num1 = delegate.coerce(obj1);
+        try {
+            Number num0 = delegate.coerce(obj0);
+            Number num1 = delegate.coerce(obj1);
 
-        return delegate.divide(num0, num1);
+            return delegate.divide(num0, num1);
+        } catch (ArithmeticException ae) {
+            throw new ELException(MessageFactory.get("error.divide", obj0, obj1), ae);
+        }
     }
 
     /**
@@ -507,21 +539,27 @@ public abstract class ELArithmetic {
      * Coerce an object to a number.
      *
      * @param obj The object to coerce
+     *
      * @return The coerced number
+     *
+     * @throws ELException if the object cannot be coerced to a number
      */
     protected final Number coerce(final Object obj) {
-
-        if (isNumber(obj)) {
-            return coerce((Number) obj);
-        }
-        if (obj == null || "".equals(obj)) {
-            return coerce(ZERO);
-        }
-        if (obj instanceof String) {
-            return coerce((String) obj);
-        }
-        if (obj instanceof Character) {
-            return coerce(Short.valueOf((short) ((Character) obj).charValue()));
+        try {
+            if (isNumber(obj)) {
+                return coerce((Number) obj);
+            }
+            if (obj == null || "".equals(obj)) {
+                return coerce(ZERO);
+            }
+            if (obj instanceof String) {
+                return coerce((String) obj);
+            }
+            if (obj instanceof Character) {
+                return coerce(Short.valueOf((short) ((Character) obj).charValue()));
+            }
+        } catch (NumberFormatException nfe) {
+            throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), "Number"), nfe);
         }
 
         throw new ELException(MessageFactory.get("error.convert", obj, obj.getClass(), "Number"));
diff --git a/java/org/apache/el/lang/ELSupport.java b/java/org/apache/el/lang/ELSupport.java
index b92d290f79..8e412a33ed 100644
--- a/java/org/apache/el/lang/ELSupport.java
+++ b/java/org/apache/el/lang/ELSupport.java
@@ -87,8 +87,8 @@ public class ELSupport {
      *
      * @return -1, 0, or 1 if this object is less than, equal to, or greater than val.
      *
-     * @throws ELException          if neither object is Comparable
-     * @throws ClassCastException   if the objects are not mutually comparable
+     * @throws ELException          if the objects cannot be compared, including because they are not mutually
+     *                              comparable
      * @throws NullPointerException if either object is null
      */
     public static int compare(final ELContext ctx, final Object obj0, final Object obj1) throws ELException {
@@ -124,12 +124,20 @@ public class ELSupport {
         if (obj0 instanceof Comparable<?>) {
             @SuppressWarnings("unchecked") // checked above
             final Comparable<Object> comparable = (Comparable<Object>) obj0;
-            return comparable.compareTo(obj1);
+            try {
+                return comparable.compareTo(obj1);
+            } catch (ClassCastException cce) {
+                throw new ELException(MessageFactory.get("error.compare", obj0, obj1), cce);
+            }
         }
         if (obj1 instanceof Comparable<?>) {
             @SuppressWarnings("unchecked") // checked above
             final Comparable<Object> comparable = (Comparable<Object>) obj1;
-            return -comparable.compareTo(obj0);
+            try {
+                return -comparable.compareTo(obj0);
+            } catch (ClassCastException cce) {
+                throw new ELException(MessageFactory.get("error.compare", obj0, obj1), cce);
+            }
         }
         throw new ELException(MessageFactory.get("error.compare", obj0, obj1));
     }
@@ -341,7 +349,11 @@ public class ELSupport {
         }
         if (BigInteger.class.equals(type)) {
             if (number instanceof BigDecimal) {
-                return ((BigDecimal) number).toBigInteger();
+                try {
+                    return ((BigDecimal) number).toBigInteger();
+                } catch (ArithmeticException ae) {
+                    throw new ELException(MessageFactory.get("error.convert", number, number.getClass(), type), ae);
+                }
             }
             if (number instanceof BigInteger) {
                 return number;
@@ -355,7 +367,11 @@ public class ELSupport {
             if (number instanceof BigInteger) {
                 return new BigDecimal((BigInteger) number);
             }
-            return new BigDecimal(number.doubleValue());
+            try {
+                return new BigDecimal(number.doubleValue());
+            } catch (NumberFormatException nfe) {
+                throw new ELException(MessageFactory.get("error.convert", number, number.getClass(), type), nfe);
+            }
         }
         if (Byte.TYPE == type || Byte.class.equals(type)) {
             return Byte.valueOf(number.byteValue());
diff --git a/test/org/apache/el/lang/TestELArithmetic.java b/test/org/apache/el/lang/TestELArithmetic.java
index fd9ec2c029..e5aa355feb 100644
--- a/test/org/apache/el/lang/TestELArithmetic.java
+++ b/test/org/apache/el/lang/TestELArithmetic.java
@@ -19,6 +19,7 @@ package org.apache.el.lang;
 import java.math.BigDecimal;
 import java.math.BigInteger;
 
+import jakarta.el.ELException;
 import jakarta.el.ELProcessor;
 
 import org.junit.Assert;
@@ -145,4 +146,107 @@ public class TestELArithmetic {
     public void testBug47371doubleString2() throws Exception {
         Assert.assertEquals(Double.valueOf(2), ELArithmetic.add("1.", "1"));
     }
+
+    @Test
+    public void testNonNumericStringCoercedThrowsELException() {
+        // A non-numeric String coerced during arithmetic must surface as ELException,
+        // not as a raw NumberFormatException (the delegate String coercions use
+        // Long.valueOf/Double.valueOf/new BigDecimal/new BigInteger).
+        Object[] badOperands = { "abc", "1E", "0x1f", "1.2.3" };
+        for (Object operand : badOperands) {
+            assertELException("add", () -> ELArithmetic.add(operand, Long.valueOf(1)));
+            assertELException("subtract", () -> ELArithmetic.subtract(Long.valueOf(1), operand));
+            assertELException("multiply", () -> ELArithmetic.multiply(operand, Long.valueOf(1)));
+        }
+    }
+
+    @Test
+    public void testIntegerModByZeroThrowsELException() {
+        // Cast to Object to select the static Object-based method
+        assertELException("mod", () -> ELArithmetic.mod((Object) Long.valueOf(1), (Object) Long.valueOf(0)));
+    }
+
+    @Test
+    public void testBigIntegerModByZeroThrowsELException() {
+        assertELException("mod",
+                () -> ELArithmetic.mod((Object) BigInteger.valueOf(1), (Object) BigInteger.valueOf(0)));
+    }
+
+    @Test
+    public void testBigDecimalDivByZeroThrowsELException() {
+        assertELException("divide", () -> ELArithmetic.divide((Object) BigDecimal.ONE, (Object) BigDecimal.ZERO));
+    }
+
+    @Test
+    public void testBigIntegerDivByZeroThrowsELException() {
+        assertELException("divide",
+                () -> ELArithmetic.divide((Object) BigInteger.ONE, (Object) BigInteger.ZERO));
+    }
+
+    @Test
+    public void testNonFiniteNumberWithBigDecimalThrowsELException() {
+        // The BigDecimal delegate Number coercion uses new BigDecimal(double) which
+        // rejects NaN and Infinity. The failure must surface as ELException.
+        assertELException("add", () -> ELArithmetic.add((Object) BigDecimal.ONE, (Object) Double.NaN));
+        assertELException("add",
+                () -> ELArithmetic.add((Object) BigDecimal.ONE, (Object) Double.POSITIVE_INFINITY));
+        assertELException("divide",
+                () -> ELArithmetic.divide((Object) BigDecimal.ONE, (Object) Double.NEGATIVE_INFINITY));
+    }
+
+    @Test
+    public void testOddNumberToStringCoercionThrowsELException() {
+        // The BigInteger delegate Number coercion uses new BigInteger(toString()). The
+        // failure must surface as ELException.
+        assertELException("add",
+                () -> ELArithmetic.add((Object) new TesterNumberOddToString(), (Object) BigInteger.ONE));
+    }
+
+    @Test
+    public void testBigDecimalOverflowThrowsELException() {
+        // BigDecimal.add()/subtract() declare ArithmeticException for overflow with
+        // extreme exponents. The failure must surface as ELException.
+        BigDecimal extreme = new BigDecimal("1e999999999");
+        assertELException("add", () -> ELArithmetic.add((Object) extreme, (Object) Long.valueOf(1)));
+        assertELException("subtract", () -> ELArithmetic.subtract((Object) extreme, (Object) Long.valueOf(1)));
+    }
+
+    private static class TesterNumberOddToString extends Number {
+
+        private static final long serialVersionUID = 1L;
+
+        @Override
+        public int intValue() {
+            return 1;
+        }
+
+        @Override
+        public long longValue() {
+            return 1L;
+        }
+
+        @Override
+        public float floatValue() {
+            return 1.5f;
+        }
+
+        @Override
+        public double doubleValue() {
+            return 1.5;
+        }
+
+        @Override
+        public String toString() {
+            return "1.5";
+        }
+    }
+
+    private static void assertELException(String op, Runnable runnable) {
+        try {
+            runnable.run();
+            Assert.fail(op + " with an invalid operand should throw ELException");
+        } catch (ELException e) {
+            // Expected
+        }
+    }
 }
diff --git a/test/org/apache/el/lang/TestELSupport.java b/test/org/apache/el/lang/TestELSupport.java
index 58dd776b68..38a485bf76 100644
--- a/test/org/apache/el/lang/TestELSupport.java
+++ b/test/org/apache/el/lang/TestELSupport.java
@@ -244,6 +244,87 @@ public class TestELSupport {
         Assert.assertNull("Result: " + result, result);
     }
 
+    @Test
+    public void testCompareNonMutuallyComparable01() {
+        // The ClassCastException raised by obj0's compareTo() must be wrapped
+        try {
+            ELSupport.compare(null, new TesterComparableA(), new TesterComparableB());
+            Assert.fail("An ELException was expected");
+        } catch (ELException e) {
+            Assert.assertTrue("Unexpected cause: " + e.getCause(), e.getCause() instanceof ClassCastException);
+        }
+    }
+
+    @Test
+    public void testCompareNonMutuallyComparable02() {
+        // obj0 is not Comparable, so obj1's compareTo() is used. The resulting
+        // ClassCastException must be wrapped
+        try {
+            ELSupport.compare(null, new Object(), new TesterComparableB());
+            Assert.fail("An ELException was expected");
+        } catch (ELException e) {
+            Assert.assertTrue("Unexpected cause: " + e.getCause(), e.getCause() instanceof ClassCastException);
+        }
+    }
+
+    @Test
+    public void testCompareBigDecimalWithNonFiniteThrowsELException() {
+        // Coercing NaN to BigDecimal uses new BigDecimal(double) which rejects the
+        // value. The failure must surface as ELException.
+        try {
+            ELSupport.compare(null, BigDecimal.ONE, Double.NaN);
+            Assert.fail("An ELException was expected");
+        } catch (ELException e) {
+            Assert.assertTrue("Unexpected cause: " + e.getCause(), e.getCause() instanceof NumberFormatException);
+        }
+    }
+
+    @Test
+    public void testEqualsBigDecimalWithNonFiniteThrowsELException() {
+        try {
+            ELSupport.equals(null, BigDecimal.ONE, Double.NaN);
+            Assert.fail("An ELException was expected");
+        } catch (ELException e) {
+            Assert.assertTrue("Unexpected cause: " + e.getCause(), e.getCause() instanceof NumberFormatException);
+        }
+    }
+
+    @Test
+    public void testCoerceToTypeNonFiniteToBigDecimalThrowsELException() {
+        try {
+            ELSupport.coerceToType(null, Double.POSITIVE_INFINITY, BigDecimal.class);
+            Assert.fail("An ELException was expected");
+        } catch (ELException e) {
+            Assert.assertTrue("Unexpected cause: " + e.getCause(), e.getCause() instanceof NumberFormatException);
+        }
+    }
+
+    @Test
+    public void testCoerceToTypeExtremeBigDecimalToBigIntegerThrowsELException() {
+        // BigDecimal.toBigInteger() declares ArithmeticException for overflow with
+        // extreme exponents. The failure must surface as ELException.
+        try {
+            ELSupport.coerceToType(null, new BigDecimal("1e999999999"), BigInteger.class);
+            Assert.fail("An ELException was expected");
+        } catch (ELException e) {
+            Assert.assertTrue("Unexpected cause: " + e.getCause(), e.getCause() instanceof ArithmeticException);
+        }
+    }
+
+    private static class TesterComparableA implements Comparable<TesterComparableA> {
+        @Override
+        public int compareTo(TesterComparableA o) {
+            return 0;
+        }
+    }
+
+    private static class TesterComparableB implements Comparable<TesterComparableB> {
+        @Override
+        public int compareTo(TesterComparableB o) {
+            return 0;
+        }
+    }
+
     private static void testIsSame(Object value) {
         Assert.assertEquals(value, ELSupport.coerceToNumber(null, value, value.getClass()));
     }


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 17/20: Follow the EL specification for substream with a negative start

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit b2b49f985536441f9373ad278cb3acf7dfb9989b
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 16:56:58 2026 +0200

    Follow the EL specification for substream with a negative start
    
    The two argument form of the substream stream operation worked with
    absolute positions: it consumed elements until the read position
    reached the start position and then emitted elements until the read
    position reached the end position. For a start greater than zero that
    matches the specification, because the number of elements emitted is
    the end position minus the start position. For a start that is less
    than or equal to zero it did not. The specification skips elements only
    when the start is greater than zero and always includes the next
    (end minus start) elements, so substream(-2, 3) of five elements had to
    include all five but returned only the first three, and substream(-2,
    0) returned nothing where the specification includes two elements.
    
    Skip the greater of the start and zero elements, and include the next
    end minus start elements. The count is calculated as a long because the
    single argument form requests the rest of the stream by passing an end
    of the largest int value, and that minus a negative start does not fit
    in an int. The behaviour for a start that is greater than or equal to
    zero, which covers the limit operation that delegates to this one, is
    unchanged.
    
    Adds tests for a negative start on both forms, with a positive and a
    zero end, and for a source with fewer elements than the number to
    skip. The two tests with the negative start and an end report the
    truncated results against the previous implementation.
---
 java/org/apache/el/stream/Stream.java              | 36 +++++++----
 .../apache/el/stream/TestCollectionOperations.java | 73 ++++++++++++++++++++++
 2 files changed, 96 insertions(+), 13 deletions(-)

diff --git a/java/org/apache/el/stream/Stream.java b/java/org/apache/el/stream/Stream.java
index f7c80cb279..98dca68cea 100644
--- a/java/org/apache/el/stream/Stream.java
+++ b/java/org/apache/el/stream/Stream.java
@@ -291,10 +291,11 @@ public class Stream {
 
 
     /**
-     * Returns a stream consisting of the elements of this stream from the
-     * specified start position to the end.
+     * Returns a stream consisting of the elements of this stream after
+     * skipping the first {@code start} elements. No elements are skipped if
+     * {@code start} is less than or equal to zero.
      *
-     * @param start the start position (inclusive)
+     * @param start the number of elements to skip
      * @return the new substream
      */
     public Stream substream(final Number start) {
@@ -302,10 +303,12 @@ public class Stream {
     }
 
     /**
-     * Returns a stream consisting of the elements of this stream from the
-     * specified start position up to, but not including, the specified end position.
+     * Returns a stream consisting of the elements of this stream, skipping
+     * the first {@code start} elements and including the next
+     * {@code end - start} elements. No elements are skipped if {@code start}
+     * is less than or equal to zero.
      *
-     * @param start the start position (inclusive)
+     * @param start the number of elements to skip
      * @param end the end position (exclusive)
      * @return the new substream
      */
@@ -313,18 +316,25 @@ public class Stream {
 
         Iterator<Object> downStream = new OpIterator() {
 
-            private final int startPos = start.intValue();
-            private final int endPos = end.intValue();
-            private int itemCount = 0;
+            // The specification counts the elements to include from the
+            // position at which the start elements were skipped, so a start
+            // that is less than or equal to zero, which skips no elements,
+            // includes end minus start elements. The count is calculated as
+            // a long because the single argument form passes an end of
+            // Integer.MAX_VALUE.
+            private final int skipCount = Math.max(start.intValue(), 0);
+            private final long includeCount = (long) end.intValue() - start.intValue();
+            private int skipped = 0;
+            private long included = 0;
 
             @Override
             protected void findNext() {
-                while (itemCount < startPos && iterator.hasNext()) {
+                while (skipped < skipCount && iterator.hasNext()) {
                     iterator.next();
-                    itemCount++;
+                    skipped++;
                 }
-                if (itemCount < endPos && iterator.hasNext()) {
-                    itemCount++;
+                if (skipped == skipCount && included < includeCount && iterator.hasNext()) {
+                    included++;
                     next = iterator.next();
                     foundNext = true;
                 }
diff --git a/test/org/apache/el/stream/TestCollectionOperations.java b/test/org/apache/el/stream/TestCollectionOperations.java
index c271c9250a..19689f27d2 100644
--- a/test/org/apache/el/stream/TestCollectionOperations.java
+++ b/test/org/apache/el/stream/TestCollectionOperations.java
@@ -324,6 +324,79 @@ public class TestCollectionOperations {
     }
 
 
+    @Test
+    public void testSubstreamStart02() {
+        // A start that is less than or equal to zero skips no elements
+        ELProcessor processor = new ELProcessor();
+
+        Object result = processor.getValue(
+                "[1, 2, 3, 4, 5].stream().substream(-2).toList()",
+                Object.class);
+
+        List<Long> expected = new ArrayList<>(5);
+        expected.add(1L);
+        expected.add(2L);
+        expected.add(3L);
+        expected.add(4L);
+        expected.add(5L);
+
+        Assert.assertEquals(expected, result);
+    }
+
+
+    @Test
+    public void testSubstreamStartEnd02() {
+        // A start that is less than or equal to zero skips no elements and
+        // the number of elements included is end minus start
+        ELProcessor processor = new ELProcessor();
+
+        Object result = processor.getValue(
+                "[1, 2, 3, 4, 5].stream().substream(-2,3).toList()",
+                Object.class);
+
+        List<Long> expected = new ArrayList<>(5);
+        expected.add(1L);
+        expected.add(2L);
+        expected.add(3L);
+        expected.add(4L);
+        expected.add(5L);
+
+        Assert.assertEquals(expected, result);
+    }
+
+
+    @Test
+    public void testSubstreamStartEnd03() {
+        // The zero end position still includes end minus start elements when
+        // the start is negative
+        ELProcessor processor = new ELProcessor();
+
+        Object result = processor.getValue(
+                "[1, 2, 3, 4, 5].stream().substream(-2,0).toList()",
+                Object.class);
+
+        List<Long> expected = new ArrayList<>(2);
+        expected.add(1L);
+        expected.add(2L);
+
+        Assert.assertEquals(expected, result);
+    }
+
+
+    @Test
+    public void testSubstreamStartEnd04() {
+        // A source with fewer elements than the number to skip includes
+        // nothing
+        ELProcessor processor = new ELProcessor();
+
+        Object result = processor.getValue(
+                "[1].stream().substream(2,3).toList()",
+                Object.class);
+
+        Assert.assertEquals(new ArrayList<Long>(), result);
+    }
+
+
     @Test
     public void testToArray01() {
         ELProcessor processor = new ELProcessor();


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


(tomcat) 14/20: Reduce the cost of parsing EL expressions with long tokens

Posted by re...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 10.1.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 8d83eeaaea24e709571960d3a9f2c6e6c07f272d
Author: opencode <re...@apache.org>
AuthorDate: Sun Oct 18 16:20:23 2026 +0200

    Reduce the cost of parsing EL expressions with long tokens
    
    The character stream used by the EL parser grew its buffer by a fixed
    2048 characters on each expansion, copying the existing contents on
    every expansion. Reading a single token larger than the initial buffer,
    such as a long string literal, therefore required one expansion per
    2048 characters read and copied everything read so far on each of
    those expansions. The total cost grew quadratically with the token
    length: a one megabyte string literal took around 640ms to parse and a
    ten megabyte one over thirty seconds.
    
    Grow the buffer in proportion to its current size, doubling it, so the
    number of expansions and the total copy cost grow linearly with the
    input. The arithmetic that relocates the current token uses the
    previous buffer size throughout and is unaffected. Parsing the same
    expressions now takes a few tens of milliseconds with identical
    results, including the error positions reported for invalid
    expressions.
---
 java/org/apache/el/parser/SimpleCharStream.java | 14 ++++++++++----
 1 file changed, 10 insertions(+), 4 deletions(-)

diff --git a/java/org/apache/el/parser/SimpleCharStream.java b/java/org/apache/el/parser/SimpleCharStream.java
index d68f7c54cb..1a84886078 100644
--- a/java/org/apache/el/parser/SimpleCharStream.java
+++ b/java/org/apache/el/parser/SimpleCharStream.java
@@ -58,9 +58,15 @@ public class SimpleCharStream {
 
 
     protected void ExpandBuff(boolean wrapAround) {
-        char[] newbuffer = new char[bufsize + 2048];
-        int newbufline[] = new int[bufsize + 2048];
-        int newbufcolumn[] = new int[bufsize + 2048];
+        // Grow the buffer geometrically. Growing by a fixed amount, as was
+        // done previously, makes the total cost of reading a single token
+        // that is larger than the initial buffer quadratic, since the entire
+        // contents of the buffer are copied on every expansion.
+        int newbufsize = (int) Math.min((long) bufsize * 2, Integer.MAX_VALUE);
+
+        char[] newbuffer = new char[newbufsize];
+        int newbufline[] = new int[newbufsize];
+        int newbufcolumn[] = new int[newbufsize];
 
         try {
             if (wrapAround) {
@@ -93,7 +99,7 @@ public class SimpleCharStream {
             throw new Error(t.getMessage());
         }
 
-        bufsize += 2048;
+        bufsize = newbufsize;
         available = bufsize;
         tokenBegin = 0;
     }


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org