This commit is contained in:
2024-11-30 19:03:49 +08:00
commit 1e6763c160
3806 changed files with 737676 additions and 0 deletions

View File

@@ -0,0 +1,392 @@
/*
* 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 javax.el;
import org.junit.Assert;
import org.junit.Test;
public class TestArrayELResolver {
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testGetType01() {
ArrayELResolver resolver = new ArrayELResolver();
resolver.getType(null, new Object(), new Object());
}
/**
* Tests that a valid property is not resolved if base is not an array.
*/
@Test
public void testGetType02() {
doNegativeTest(new Object(), new Object(), MethodUnderTest.GET_TYPE,
true);
}
/**
* Tests that a valid property is resolved.
*/
@Test
public void testGetType03() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
Class<?> result = resolver.getType(context, base, Integer.valueOf(0));
Assert.assertEquals(base.getClass().getComponentType(), result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that the key is out of bounds and exception will be thrown.
*/
@Test(expected = PropertyNotFoundException.class)
public void testGetType04() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
resolver.getType(context, base, Integer.valueOf(1));
}
/**
* Tests that a result is returned even when a coercion cannot be performed.
*/
@Test
public void testGetType05() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
Class<?> result = resolver.getType(context, base, "index");
Assert.assertEquals(base.getClass().getComponentType(), result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testGetValue01() {
ArrayELResolver resolver = new ArrayELResolver();
resolver.getValue(null, new Object(), new Object());
}
/**
* Tests that a valid property is not resolved if base is not an array.
*/
@Test
public void testGetValue02() {
doNegativeTest(new Object(), new Object(), MethodUnderTest.GET_VALUE,
true);
}
/**
* Tests that a valid property is resolved.
*/
@Test
public void testGetValue03() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
Object result = resolver.getValue(context, base, Integer.valueOf(0));
Assert.assertEquals("element", result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests a coercion cannot be performed as the key is not integer.
*/
@Test(expected = IllegalArgumentException.class)
public void testGetValue04() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
resolver.getValue(context, base, "key");
}
/**
* Tests that the key is out of bounds and null will be returned.
*/
@Test
public void testGetValue05() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
Object result = resolver.getValue(context, base, Integer.valueOf(1));
Assert.assertNull(result);
Assert.assertTrue(context.isPropertyResolved());
result = resolver.getValue(context, base, Integer.valueOf(-1));
Assert.assertNull(result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testSetValue01() {
ArrayELResolver resolver = new ArrayELResolver();
resolver.setValue(null, new Object(), new Object(), new Object());
}
/**
* Tests that a valid property is not set if base is not an array.
*/
@Test
public void testSetValue02() {
doNegativeTest(new Object(), new Object(), MethodUnderTest.SET_VALUE,
false);
}
/**
* Tests that an exception is thrown when readOnly is true.
*/
@Test(expected = PropertyNotWritableException.class)
public void testSetValue03() {
ArrayELResolver resolver = new ArrayELResolver(true);
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
resolver.setValue(context, new String[] {}, new Object(), new Object());
}
/**
* Tests that a valid property is set.
*/
@Test
public void testSetValue04() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
resolver.setValue(context, base, Integer.valueOf(0), "new-element");
Assert.assertEquals("new-element",
resolver.getValue(context, base, Integer.valueOf(0)));
Assert.assertTrue(context.isPropertyResolved());
resolver.setValue(context, base, Integer.valueOf(0), null);
Assert.assertEquals(null,
resolver.getValue(context, base, Integer.valueOf(0)));
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests a coercion cannot be performed as the key is not integer.
*/
@Test(expected = IllegalArgumentException.class)
public void testSetValue05() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
resolver.setValue(context, base, "key", "new-element");
}
/**
* Tests that the key is out of bounds and exception will be thrown.
*/
@Test(expected = PropertyNotFoundException.class)
public void testSetValue06() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
resolver.setValue(context, base, Integer.valueOf(1), "new-element");
}
/**
* Tests that an exception will be thrown if the value is not from the
* corresponding type.
*/
@Test(expected = ClassCastException.class)
public void testSetValue07() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
resolver.setValue(context, base, Integer.valueOf(0), Integer.valueOf(1));
}
/**
* Tests setting arrays of primitives.
* https://bz.apache.org/bugzilla/show_bug.cgi?id=55691
*/
@Test
public void testSetValue08() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
int[] base = new int[] { 1, 2, 3 };
resolver.setValue(context, base, Integer.valueOf(1), Integer.valueOf(4));
Assert.assertEquals(Integer.valueOf(base[1]), Integer.valueOf(4));
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testIsReadOnly01() {
ArrayELResolver resolver = new ArrayELResolver();
resolver.isReadOnly(null, new Object(), new Object());
}
/**
* Tests that the propertyResolved is false if base is not an array.
*/
@Test
public void testIsReadOnly02() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
boolean result = resolver.isReadOnly(context, new Object(),
new Object());
Assert.assertFalse(result);
Assert.assertFalse(context.isPropertyResolved());
resolver = new ArrayELResolver(true);
result = resolver.isReadOnly(context, new Object(), new Object());
Assert.assertTrue(result);
Assert.assertFalse(context.isPropertyResolved());
}
/**
* Tests that if the ArrayELResolver is constructed with readOnly the method
* will return always true, otherwise false.
*/
@Test
public void testIsReadOnly03() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
boolean result = resolver.isReadOnly(context, base, Integer.valueOf(0));
Assert.assertFalse(result);
Assert.assertTrue(context.isPropertyResolved());
resolver = new ArrayELResolver(true);
result = resolver.isReadOnly(context, base, Integer.valueOf(0));
Assert.assertTrue(result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that the key is out of bounds and exception will be thrown.
*/
@Test(expected = PropertyNotFoundException.class)
public void testIsReadOnly04() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
resolver.isReadOnly(context, base, Integer.valueOf(1));
}
/**
* Tests that a result is returned even when a coercion cannot be performed.
*/
@Test
public void testIsReadOnly05() {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
String[] base = new String[] { "element" };
boolean result = resolver.isReadOnly(context, base, "key");
Assert.assertFalse(result);
Assert.assertTrue(context.isPropertyResolved());
resolver = new ArrayELResolver(true);
result = resolver.isReadOnly(context, base, "key");
Assert.assertTrue(result);
Assert.assertTrue(context.isPropertyResolved());
}
private void doNegativeTest(Object base, Object trigger,
MethodUnderTest method, boolean checkResult) {
ArrayELResolver resolver = new ArrayELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
Object result = null;
switch (method) {
case GET_VALUE: {
result = resolver.getValue(context, base, trigger);
break;
}
case SET_VALUE: {
resolver.setValue(context, base, trigger, new Object());
break;
}
case GET_TYPE: {
result = resolver.getType(context, base, trigger);
break;
}
default: {
// Should never happen
Assert.fail("Missing case for method");
}
}
if (checkResult) {
Assert.assertNull(result);
}
Assert.assertFalse(context.isPropertyResolved());
}
private enum MethodUnderTest {
GET_VALUE, SET_VALUE, GET_TYPE
}
}

View File

@@ -0,0 +1,988 @@
/*
* 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 javax.el;
import java.beans.FeatureDescriptor;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.Iterator;
import org.junit.Assert;
import org.junit.Test;
import org.apache.jasper.el.ELContextImpl;
public class TestBeanELResolver {
private static final String METHOD01_NAME = "toString";
private static final String METHOD02_NAME = "<init>";
private static final String METHOD03_NAME = "nonExistingMethod";
private static final String BEAN_NAME = "test";
private static final String PROPERTY01_NAME = "valueA";
private static final String PROPERTY02_NAME = "valueB";
private static final String PROPERTY03_NAME = "name";
private static final String PROPERTY_VALUE = "test1";
@Test
public void testBug53421() {
ExpressionFactory factory = ExpressionFactory.newInstance();
ELContext context = new ELContextImpl(factory);
Bean bean = new Bean();
ValueExpression varBean =
factory.createValueExpression(bean, Bean.class);
context.getVariableMapper().setVariable("bean", varBean);
ValueExpression ve = factory.createValueExpression(
context, "${bean.valueA}", String.class);
Exception e = null;
try {
ve.getValue(context);
} catch (PropertyNotFoundException pnfe) {
e = pnfe;
}
Assert.assertTrue("Wrong exception type",
e instanceof PropertyNotFoundException);
String type = Bean.class.getName();
String msg = e.getMessage();
Assert.assertTrue("No reference to type [" + type +
"] where property cannot be found in [" + msg + "]",
msg.contains(type));
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testGetType01() {
BeanELResolver resolver = new BeanELResolver();
resolver.getType(null, new Object(), new Object());
}
/**
* Tests that a valid property is not resolved if base is null.
*/
@Test
public void testGetType02() {
doNegativeTest(null, new Object(), MethodUnderTest.GET_TYPE, true);
}
/**
* Tests that a valid property is resolved.
*/
@Test
public void testGetType03() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Class<?> result = resolver.getType(context, new Bean(), PROPERTY01_NAME);
Assert.assertEquals(String.class, result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that an exception will be thrown when the property does not exist.
*/
@Test(expected = PropertyNotFoundException.class)
public void testGetType04() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
resolver.getType(context, new Bean(), PROPERTY02_NAME);
}
/**
* Tests that an exception will be thrown when a coercion cannot be
* performed.
*/
@Test(expected = PropertyNotFoundException.class)
public void testGetType05() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
resolver.getType(context, new Bean(), new Object());
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testGetValue01() {
BeanELResolver resolver = new BeanELResolver();
resolver.getValue(null, new Object(), new Object());
}
/**
* Tests that a valid property is not resolved if base is null.
*/
@Test
public void testGetValue02() {
doNegativeTest(null, new Object(), MethodUnderTest.GET_VALUE, true);
}
/**
* Tests that a valid property is resolved.
*/
@Test
public void testGetValue03() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.getValue(context, new TesterBean(BEAN_NAME), PROPERTY03_NAME);
Assert.assertEquals(BEAN_NAME, result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that an exception will be thrown when the property does not exist.
*/
@Test(expected = PropertyNotFoundException.class)
public void testGetValue04() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
resolver.getValue(context, new Bean(), PROPERTY02_NAME);
}
/**
* Tests that an exception will be thrown when a coercion cannot be
* performed.
*/
@Test(expected = PropertyNotFoundException.class)
public void testGetValue05() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
resolver.getValue(context, new Bean(), new Object());
}
/**
* Tests that an exception will be thrown when the property is not readable.
*/
@Test(expected = PropertyNotFoundException.class)
public void testGetValue06() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
resolver.getValue(context, new Bean(), PROPERTY01_NAME);
}
/**
* Tests that getter method throws exception which should be propagated.
*/
@Test(expected = ELException.class)
public void testGetValue07() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
resolver.getValue(context, new TesterBean(BEAN_NAME), PROPERTY01_NAME);
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testSetValue01() {
BeanELResolver resolver = new BeanELResolver();
resolver.setValue(null, new Object(), new Object(), new Object());
}
/**
* Tests that a valid property is not resolved if base is null.
*/
@Test
public void testSetValue02() {
doNegativeTest(null, new Object(), MethodUnderTest.SET_VALUE, true);
}
/**
* Tests that an exception is thrown when readOnly is true.
*/
@Test(expected = PropertyNotWritableException.class)
public void testSetValue03() {
BeanELResolver resolver = new BeanELResolver(true);
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
resolver.setValue(context, new Bean(), new Object(), new Object());
}
/**
* Tests that a valid property is resolved.
*/
@Test
public void testSetValue04() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
TesterBean bean = new TesterBean(BEAN_NAME);
resolver.setValue(context, bean, PROPERTY03_NAME, PROPERTY_VALUE);
Assert.assertEquals(PROPERTY_VALUE, resolver.getValue(context, bean, PROPERTY03_NAME));
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that an exception will be thrown when a coercion cannot be
* performed.
*/
@Test(expected = PropertyNotFoundException.class)
public void testSetValue05() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
resolver.setValue(context, new Bean(), new Object(), PROPERTY_VALUE);
}
/**
* Tests that an exception will be thrown when the property does not exist.
*/
@Test(expected = PropertyNotFoundException.class)
public void testSetValue06() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
resolver.setValue(context, new Bean(), PROPERTY02_NAME, PROPERTY_VALUE);
}
/**
* Tests that an exception will be thrown when the property does not have
* setter method.
*/
@Test(expected = PropertyNotWritableException.class)
public void testSetValue07() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
resolver.setValue(context, new TesterBean(BEAN_NAME), PROPERTY01_NAME, PROPERTY_VALUE);
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testIsReadOnly01() {
BeanELResolver resolver = new BeanELResolver();
resolver.isReadOnly(null, new Object(), new Object());
}
/**
* Tests that the propertyResolved is false if base is null.
*/
@Test
public void testIsReadOnly02() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
resolver.isReadOnly(context, null, new Object());
Assert.assertFalse(context.isPropertyResolved());
resolver = new BeanELResolver(true);
resolver.isReadOnly(context, null, new Object());
Assert.assertFalse(context.isPropertyResolved());
}
/**
* Tests that if the BeanELResolver is constructed with readOnly the method
* will return always true.
*/
@Test
public void testIsReadOnly03() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
boolean result = resolver.isReadOnly(context, new TesterBean(BEAN_NAME), PROPERTY03_NAME);
Assert.assertFalse(result);
Assert.assertTrue(context.isPropertyResolved());
resolver = new BeanELResolver(true);
result = resolver.isReadOnly(context, new TesterBean(BEAN_NAME), PROPERTY03_NAME);
Assert.assertTrue(result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that an exception is thrown when a coercion cannot be performed.
*/
@Test(expected = PropertyNotFoundException.class)
public void testIsReadOnly04() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
resolver.isReadOnly(context, new TesterBean(BEAN_NAME), Integer.valueOf(0));
}
/**
* Tests that an exception will be thrown when the property does not exist.
*/
@Test(expected = PropertyNotFoundException.class)
public void testIsReadOnly05() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
resolver.isReadOnly(context, new Bean(), PROPERTY02_NAME);
}
/**
* Tests that true will be returned when the property does not have setter
* method.
*/
@Test
public void testIsReadOnly06() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
boolean result = resolver.isReadOnly(context, new TesterBean(BEAN_NAME), PROPERTY01_NAME);
Assert.assertTrue(result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that a valid FeatureDescriptors are not returned if base is not
* Map.
*/
@Test
public void testGetFeatureDescriptors01() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Iterator<FeatureDescriptor> result = resolver.getFeatureDescriptors(context, null);
Assert.assertNull(result);
}
/**
* Tests that a valid FeatureDescriptors are returned.
*/
@Test
public void testGetFeatureDescriptors02() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Iterator<FeatureDescriptor> result = resolver.getFeatureDescriptors(context, new Bean());
while (result.hasNext()) {
PropertyDescriptor featureDescriptor = (PropertyDescriptor) result.next();
Assert.assertEquals(featureDescriptor.getPropertyType(),
featureDescriptor.getValue(ELResolver.TYPE));
Assert.assertEquals(Boolean.TRUE,
featureDescriptor.getValue(ELResolver.RESOLVABLE_AT_DESIGN_TIME));
}
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testInvoke01() {
BeanELResolver resolver = new BeanELResolver();
resolver.invoke(null, new Object(), new Object(), new Class<?>[0], new Object[0]);
}
/**
* Tests that a valid property is not resolved if base is null.
*/
@Test
public void testInvoke02() {
doNegativeTest(null, new Object(), MethodUnderTest.INVOKE, true);
}
/**
* Tests a method invocation.
*/
@Test
public void testInvoke03() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), METHOD01_NAME,
new Class<?>[] {}, new Object[] {});
Assert.assertEquals(BEAN_NAME, result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that the method name cannot be coerced to String.
*/
@Test
public void testInvoke04() {
doNegativeTest(new Bean(), null, MethodUnderTest.INVOKE, true);
}
/**
* Tests that a call to &lt;init&gt; as a method name will throw an exception.
*/
@Test(expected = MethodNotFoundException.class)
public void testInvoke05() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
resolver.invoke(context, new TesterBean(BEAN_NAME), METHOD02_NAME, new Class<?>[] {},
new Object[] {});
}
/**
* Tests that a call to a non existing method will throw an exception.
*/
@Test(expected = MethodNotFoundException.class)
public void testInvoke06() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
resolver.invoke(context, new TesterBean(BEAN_NAME), METHOD03_NAME, new Class<?>[] {},
new Object[] {});
}
@Test
public void testInvokeVarargsCoerce01() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] {}, new String[] {});
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargsCoerce02() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
null, null);
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargsCoerce03() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
null, new String[] {});
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargsCoerce04() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] {}, null);
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargsCoerce05() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { null }, new String[] { null });
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargsCoerce06() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
null, new String[] { null });
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargsCoerce07() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { null }, null);
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargsCoerce08() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { String.class }, new String[] { "true" });
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargsCoerce09() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { String.class, String.class }, new Object[] { "true", null });
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargsCoerce10() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { String.class, String[].class }, new Object[] { "true", null });
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargsCoerce11() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { String.class }, new Object[] { "10" });
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargsCoerce12() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { String[].class }, new String[] { "10" });
Assert.assertEquals(BEAN_NAME, result);
}
// Ambiguous because the Strings coerce to both Boolean and Integer hence
// both varargs methods match.
@Test(expected=MethodNotFoundException.class)
public void testInvokeVarargsCoerce13() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { String.class, String.class }, new String[] { "10", "11" });
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargsCoerce14() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { String.class, String.class }, new String[] { "true", null });
Assert.assertEquals(BEAN_NAME, result);
}
@Test(expected=MethodNotFoundException.class)
public void testInvokeVarargsCoerce15() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { String.class, String.class }, new Object[] { "true", new ArrayList<>() });
Assert.assertEquals(BEAN_NAME, result);
}
// Ambiguous because the Strings coerce to both Boolean and Integer hence
// both varargs methods match.
@Test(expected=MethodNotFoundException.class)
public void testInvokeVarargsCoerce16() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { String.class, String.class, String.class },
new Object[] { "10", "11", "12" });
Assert.assertEquals(BEAN_NAME, result);
}
@Test(expected=MethodNotFoundException.class)
public void testInvokeVarargsCoerce17() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { String.class, String.class },
new Object[] { "10", "11", "12" });
Assert.assertEquals(BEAN_NAME, result);
}
@Test(expected=MethodNotFoundException.class)
public void testInvokeVarargsCoerce18() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { String.class, String.class, String.class, String.class },
new Object[] { "10", "11", "12" });
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargsCoerce19() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { String.class, String.class, String.class, String.class },
new Object[] { "true", "10", "11", "12" });
Assert.assertEquals(BEAN_NAME, result);
}
@Test(expected=MethodNotFoundException.class)
public void testInvokeVarargsCoerce20() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { String.class, String.class, String.class },
new Object[] { "true", "10", "11", "12" });
Assert.assertEquals(BEAN_NAME, result);
}
@Test(expected=MethodNotFoundException.class)
public void testInvokeVarargsCoerce21() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { String.class, String.class, String.class, String.class, String.class },
new Object[] { "true", "10", "11", "12" });
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargs01() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] {}, new Object[] {});
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargs02() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
null, null);
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargs03() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
null, new Object[] {});
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargs04() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] {}, null);
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargs05() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { null }, new Object[] { null });
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargs06() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
null, new Object[] { null });
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargs07() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { null }, null);
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargs08() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { Boolean.class }, new Object[] { Boolean.TRUE });
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargs09() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { Boolean.class, Integer.class }, new Object[] { Boolean.TRUE, null });
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargs10() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { Boolean.class, Integer[].class }, new Object[] { Boolean.TRUE, null });
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargs11() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { Integer.class }, new Object[] { Integer.valueOf(10) });
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargs12() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { Integer[].class }, new Object[] { Integer.valueOf(10) });
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargs13() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { Integer.class, Integer.class }, new Object[] { Integer.valueOf(10), Integer.valueOf(11) });
Assert.assertEquals(BEAN_NAME, result);
}
// Note: The coercion rules are that a null of any type can be coerced to a
// null of *any* other type so this works.
@Test
public void testInvokeVarargs14() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { Boolean.class, ArrayList.class }, new Object[] { Boolean.TRUE, null });
Assert.assertEquals(BEAN_NAME, result);
}
@Test(expected=MethodNotFoundException.class)
public void testInvokeVarargs15() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { Boolean.class, ArrayList.class }, new Object[] { Boolean.TRUE, new ArrayList<>() });
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargs16() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { Integer.class, Integer.class, Integer.class },
new Object[] { Integer.valueOf(10), Integer.valueOf(11), Integer.valueOf(12) });
Assert.assertEquals(BEAN_NAME, result);
}
@Test(expected=MethodNotFoundException.class)
public void testInvokeVarargs17() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { Integer.class, Integer.class },
new Object[] { Integer.valueOf(10), Integer.valueOf(11), Integer.valueOf(12) });
Assert.assertEquals(BEAN_NAME, result);
}
@Test(expected=MethodNotFoundException.class)
public void testInvokeVarargs18() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { Integer.class, Integer.class, Integer.class, Integer.class },
new Object[] { Integer.valueOf(10), Integer.valueOf(11), Integer.valueOf(12) });
Assert.assertEquals(BEAN_NAME, result);
}
@Test
public void testInvokeVarargs19() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { Boolean.class, Integer.class, Integer.class, Integer.class },
new Object[] { Boolean.TRUE, Integer.valueOf(10), Integer.valueOf(11), Integer.valueOf(12) });
Assert.assertEquals(BEAN_NAME, result);
}
@Test(expected=MethodNotFoundException.class)
public void testInvokeVarargs20() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { Boolean.class, Integer.class, Integer.class },
new Object[] { Boolean.TRUE, Integer.valueOf(10), Integer.valueOf(11), Integer.valueOf(12) });
Assert.assertEquals(BEAN_NAME, result);
}
@Test(expected=MethodNotFoundException.class)
public void testInvokeVarargs21() {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.invoke(context, new TesterBean(BEAN_NAME), "getNameVarargs",
new Class<?>[] { Boolean.class, Integer.class, Integer.class, Integer.class, Integer.class },
new Object[] { Boolean.TRUE, Integer.valueOf(10), Integer.valueOf(11), Integer.valueOf(12) });
Assert.assertEquals(BEAN_NAME, result);
}
private static class Bean {
@SuppressWarnings("unused")
public void setValueA(String valueA) {
// NOOP
}
}
private void doNegativeTest(Object base, Object trigger, MethodUnderTest method,
boolean checkResult) {
BeanELResolver resolver = new BeanELResolver();
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
Object result = null;
switch (method) {
case GET_VALUE: {
result = resolver.getValue(context, base, trigger);
break;
}
case SET_VALUE: {
resolver.setValue(context, base, trigger, new Object());
break;
}
case GET_TYPE: {
result = resolver.getType(context, base, trigger);
break;
}
case INVOKE: {
result = resolver.invoke(context, base, trigger, new Class<?>[0], new Object[0]);
break;
}
default: {
// Should never happen
Assert.fail("Missing case for method");
}
}
if (checkResult) {
Assert.assertNull(result);
}
Assert.assertFalse(context.isPropertyResolved());
}
private enum MethodUnderTest {
GET_VALUE, SET_VALUE, GET_TYPE, INVOKE
}
}

View File

@@ -0,0 +1,122 @@
/*
* 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 javax.el;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class TestBeanELResolverVarargsInvocation {
public static class Foo {
public String joinDelimited(String delim, String... strings) {
StringBuilder result = new StringBuilder();
if (strings != null) {
for (String s : strings) {
if (delim != null && result.length() > 0) {
result.append(delim);
}
result.append(s);
}
}
return result.toString();
}
public String join(String... strings) {
return joinDelimited(null, strings);
}
}
private Foo foo;
private ELContext elContext;
private BeanELResolver beanELResolver;
@Before
public void setup() {
foo = new Foo();
beanELResolver = new BeanELResolver();
elContext = new ELContext() {
private VariableMapper variableMapper = new VariableMapper() {
private Map<String, ValueExpression> vars = new HashMap<>();
@Override
public ValueExpression setVariable(String arg0,
ValueExpression arg1) {
if (arg1 == null) {
return vars.remove(arg0);
} else {
return vars.put(arg0, arg1);
}
}
@Override
public ValueExpression resolveVariable(String arg0) {
return vars.get(arg0);
}
};
private FunctionMapper functionMapper = new FunctionMapper() {
@Override
public Method resolveFunction(String arg0, String arg1) {
return null;
}
};
@Override
public VariableMapper getVariableMapper() {
return variableMapper;
}
@Override
public FunctionMapper getFunctionMapper() {
return functionMapper;
}
@Override
public ELResolver getELResolver() {
return beanELResolver;
}
};
}
/**
* Tests varargs that come after an opening argument.
*/
@Test
public void testJoinDelimited() {
Assert.assertEquals(foo.joinDelimited("-", "foo", "bar", "baz"),
beanELResolver.invoke(elContext, foo, "joinDelimited", null,
new Object[] { "-", "foo", "bar", "baz" }));
}
/**
* Tests varargs that constitute a method's only parameters, as well as
* bogus results due to improper matching of ANY vararg method, and
* depending on the order in which reflected methods are encountered.
*/
@Test
public void testJoin() {
Assert.assertEquals(foo.join("foo", "bar", "baz"),
beanELResolver.invoke(elContext, foo, "join", null,
new Object[] { "foo", "bar", "baz" }));
}
}

View File

@@ -0,0 +1,615 @@
/*
* 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 javax.el;
import org.junit.Assert;
import org.junit.Test;
public class TestBeanNameELResolver {
private static final String BEAN01_NAME = "bean01";
private static final TesterBean BEAN01 = new TesterBean(BEAN01_NAME);
private static final String BEAN02_NAME = "bean02";
private static final TesterBean BEAN02 = new TesterBean(BEAN02_NAME);
private static final String BEAN99_NAME = "bean99";
private static final TesterBean BEAN99 = new TesterBean(BEAN99_NAME);
/**
* Creates the resolver that is used for the test. All the tests use a
* resolver with the same configuration.
*/
private BeanNameELResolver createBeanNameELResolver() {
return createBeanNameELResolver(true);
}
private BeanNameELResolver createBeanNameELResolver(boolean allowCreate) {
TesterBeanNameResolver beanNameResolver = new TesterBeanNameResolver();
beanNameResolver.setBeanValue(BEAN01_NAME, BEAN01);
beanNameResolver.setBeanValue(BEAN02_NAME, BEAN02);
beanNameResolver.setAllowCreate(allowCreate);
BeanNameELResolver beanNameELResolver =
new BeanNameELResolver(beanNameResolver);
return beanNameELResolver;
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected=NullPointerException.class)
public void testGetValue01() {
BeanNameELResolver resolver = createBeanNameELResolver();
resolver.getValue(null, new Object(), new Object());
}
/**
* Tests that a valid bean is resolved.
*/
@Test
public void testGetValue02() {
BeanNameELResolver resolver = createBeanNameELResolver();
ELContext context =
new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.getValue(context, null, BEAN01_NAME);
Assert.assertEquals(BEAN01, result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that a valid bean is not resolved if base is non-null.
*/
@Test
public void testGetValue03() {
BeanNameELResolver resolver = createBeanNameELResolver();
ELContext context =
new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.getValue(context, new Object(), BEAN01_NAME);
Assert.assertNull(result);
Assert.assertFalse(context.isPropertyResolved());
}
/**
* Tests that a valid bean is not resolved if property is not a String even
* if it can be coerced to a valid bean name.
*/
@Test
public void testGetValue04() {
BeanNameELResolver resolver = createBeanNameELResolver();
ELContext context =
new StandardELContext(ELManager.getExpressionFactory());
Object property = new Object() {
@Override
public String toString() {
return BEAN01_NAME;
}
};
Object result = resolver.getValue(context, null, property);
Assert.assertNull(result);
Assert.assertFalse(context.isPropertyResolved());
}
/**
* Beans that don't exist shouldn't return anything
*/
@Test
public void testGetValue05() {
BeanNameELResolver resolver = createBeanNameELResolver();
ELContext context =
new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.getValue(context, null, BEAN99_NAME);
Assert.assertNull(result);
Assert.assertFalse(context.isPropertyResolved());
}
/**
* Exception during resolution should be wrapped and re-thrown.
*/
@Test
public void testGetValue06() {
doThrowableTest(TesterBeanNameResolver.EXCEPTION_TRIGGER_NAME,
MethodUnderTest.GET_VALUE);
}
/**
* Throwable during resolution should be wrapped and re-thrown.
*/
@Test
public void testGetValue07() {
doThrowableTest(TesterBeanNameResolver.THROWABLE_TRIGGER_NAME,
MethodUnderTest.GET_VALUE);
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected=NullPointerException.class)
public void testSetValue01() {
BeanNameELResolver resolver = createBeanNameELResolver();
resolver.setValue(null, new Object(), new Object(), new Object());
}
/**
* Test replace with create enabled.
*/
@Test
public void testSetValue02() {
doSetValueCreateReplaceTest(true, BEAN01_NAME);
}
/**
* Test replace with create disabled.
*/
@Test
public void testSetValue03() {
doSetValueCreateReplaceTest(false, BEAN01_NAME);
}
/**
* Test create with create enabled.
*/
@Test
public void testSetValue04() {
doSetValueCreateReplaceTest(true, BEAN99_NAME);
}
/**
* Test create with create disabled.
*/
@Test
public void testSetValue05() {
doSetValueCreateReplaceTest(false, BEAN99_NAME);
}
/**
* Test replacing a read-only bean with create enabled.
*/
@Test(expected=PropertyNotWritableException.class)
public void testSetValue06() {
doSetValueCreateReplaceTest(true,
TesterBeanNameResolver.READ_ONLY_NAME);
}
/**
* Test replacing a read-only bean with create disable.
*/
@Test(expected=PropertyNotWritableException.class)
public void testSetValue07() {
doSetValueCreateReplaceTest(false,
TesterBeanNameResolver.READ_ONLY_NAME);
}
/**
* Exception during resolution should be wrapped and re-thrown.
*/
@Test
public void testSetValue08() {
doThrowableTest(TesterBeanNameResolver.EXCEPTION_TRIGGER_NAME,
MethodUnderTest.SET_VALUE);
}
/**
* Throwable during resolution should be wrapped and re-thrown.
*/
@Test
public void testSetValue09() {
doThrowableTest(TesterBeanNameResolver.THROWABLE_TRIGGER_NAME,
MethodUnderTest.SET_VALUE);
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected=NullPointerException.class)
public void testGetType01() {
BeanNameELResolver resolver = createBeanNameELResolver();
resolver.getType(null, new Object(), new Object());
}
/**
* Tests that a valid bean is resolved.
*/
@Test
public void testGetType02() {
BeanNameELResolver resolver = createBeanNameELResolver();
ELContext context =
new StandardELContext(ELManager.getExpressionFactory());
Class<?> result = resolver.getType(context, null, BEAN01_NAME);
Assert.assertEquals(BEAN01.getClass(), result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that a valid bean is not resolved if base is non-null.
*/
@Test
public void testGetType03() {
BeanNameELResolver resolver = createBeanNameELResolver();
ELContext context =
new StandardELContext(ELManager.getExpressionFactory());
Class<?> result = resolver.getType(context, new Object(), BEAN01_NAME);
Assert.assertNull(result);
Assert.assertFalse(context.isPropertyResolved());
}
/**
* Tests that a valid bean is not resolved if property is not a String even
* if it can be coerced to a valid bean name.
*/
@Test
public void testGetType04() {
BeanNameELResolver resolver = createBeanNameELResolver();
ELContext context =
new StandardELContext(ELManager.getExpressionFactory());
Object property = new Object() {
@Override
public String toString() {
return BEAN01_NAME;
}
};
Class<?> result = resolver.getType(context, null, property);
Assert.assertNull(result);
Assert.assertFalse(context.isPropertyResolved());
}
/**
* Beans that don't exist shouldn't return anything
*/
@Test
public void testGetType05() {
BeanNameELResolver resolver = createBeanNameELResolver();
ELContext context =
new StandardELContext(ELManager.getExpressionFactory());
Class<?> result = resolver.getType(context, null, BEAN99_NAME);
Assert.assertNull(result);
Assert.assertFalse(context.isPropertyResolved());
}
/**
* Exception during resolution should be wrapped and re-thrown.
*/
@Test
public void testGetType06() {
doThrowableTest(TesterBeanNameResolver.EXCEPTION_TRIGGER_NAME,
MethodUnderTest.GET_TYPE);
}
/**
* Throwable during resolution should be wrapped and re-thrown.
*/
@Test
public void testGetType07() {
doThrowableTest(TesterBeanNameResolver.THROWABLE_TRIGGER_NAME,
MethodUnderTest.GET_TYPE);
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected=NullPointerException.class)
public void testIsReadOnly01() {
BeanNameELResolver resolver = createBeanNameELResolver();
resolver.isReadOnly(null, new Object(), new Object());
}
/**
* Tests that a writable bean is reported as writable.
*/
@Test
public void testIsReadOnly02() {
BeanNameELResolver resolver = createBeanNameELResolver();
ELContext context =
new StandardELContext(ELManager.getExpressionFactory());
boolean result = resolver.isReadOnly(context, null, BEAN01_NAME);
Assert.assertFalse(result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that a read-only bean is reported as not writable.
*/
@Test
public void testIsReadOnly03() {
BeanNameELResolver resolver = createBeanNameELResolver();
ELContext context =
new StandardELContext(ELManager.getExpressionFactory());
boolean result = resolver.isReadOnly(context, null,
TesterBeanNameResolver.READ_ONLY_NAME);
Assert.assertTrue(result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that a valid bean is not resolved if base is non-null.
*/
@Test
public void testIsReadOnly04() {
BeanNameELResolver resolver = createBeanNameELResolver();
ELContext context =
new StandardELContext(ELManager.getExpressionFactory());
resolver.isReadOnly(context, new Object(), BEAN01_NAME);
Assert.assertFalse(context.isPropertyResolved());
}
/**
* Tests that a valid bean is not resolved if property is not a String even
* if it can be coerced to a valid bean name.
*/
@Test
public void testIsReadOnly05() {
BeanNameELResolver resolver = createBeanNameELResolver();
ELContext context =
new StandardELContext(ELManager.getExpressionFactory());
Object property = new Object() {
@Override
public String toString() {
return BEAN01_NAME;
}
};
resolver.isReadOnly(context, null, property);
Assert.assertFalse(context.isPropertyResolved());
}
/**
* Beans that don't exist should not resolve
*/
@Test
public void testIsReadOnly06() {
BeanNameELResolver resolver = createBeanNameELResolver();
ELContext context =
new StandardELContext(ELManager.getExpressionFactory());
resolver.isReadOnly(context, null, BEAN99_NAME);
Assert.assertFalse(context.isPropertyResolved());
}
/**
* Exception during resolution should be wrapped and re-thrown.
*/
@Test
public void testIsReadOnly07() {
doThrowableTest(TesterBeanNameResolver.EXCEPTION_TRIGGER_NAME,
MethodUnderTest.IS_READ_ONLY);
}
/**
* Throwable during resolution should be wrapped and re-thrown.
*/
@Test
public void testIsReadOnly08() {
doThrowableTest(TesterBeanNameResolver.THROWABLE_TRIGGER_NAME,
MethodUnderTest.IS_READ_ONLY);
}
/**
* Confirm it returns null for 'valid' input.
*/
public void testGetFeatureDescriptors01() {
BeanNameELResolver resolver = createBeanNameELResolver();
ELContext context =
new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.getFeatureDescriptors(context, null);
Assert.assertNull(result);
Assert.assertFalse(context.isPropertyResolved());
}
/**
* Confirm it returns null for invalid input.
*/
public void testGetFeatureDescriptors02() {
BeanNameELResolver resolver = createBeanNameELResolver();
Object result = resolver.getFeatureDescriptors(null, new Object());
Assert.assertNull(result);
}
/**
* Confirm it returns String.class for 'valid' input.
*/
public void testGetCommonPropertyType01() {
BeanNameELResolver resolver = createBeanNameELResolver();
ELContext context =
new StandardELContext(ELManager.getExpressionFactory());
Object result = resolver.getCommonPropertyType(context, null);
Assert.assertNull(result);
Assert.assertFalse(context.isPropertyResolved());
}
/**
* Confirm it returns String.class for invalid input.
*/
public void testGetCommonPropertyType02() {
BeanNameELResolver resolver = createBeanNameELResolver();
Object result = resolver.getCommonPropertyType(null, new Object());
Assert.assertNull(result);
}
private void doThrowableTest(String trigger, MethodUnderTest method) {
BeanNameELResolver resolver = createBeanNameELResolver();
ELContext context =
new StandardELContext(ELManager.getExpressionFactory());
ELException elException = null;
try {
switch (method) {
case GET_VALUE: {
resolver.getValue(context, null, trigger);
break;
}
case SET_VALUE: {
resolver.setValue(context, null, trigger, new Object());
break;
}
case GET_TYPE: {
resolver.getType(context, null, trigger);
break;
}
case IS_READ_ONLY: {
resolver.isReadOnly(context, null, trigger);
break;
}
default: {
// Should never happen
Assert.fail("Missing case for method");
}
}
} catch (ELException e) {
elException = e;
}
Assert.assertFalse(context.isPropertyResolved());
Assert.assertNotNull(elException);
Throwable cause = elException.getCause();
Assert.assertNotNull(cause);
}
/**
* Tests adding/replacing beans beans
*/
private void doSetValueCreateReplaceTest(boolean canCreate,
String beanName) {
BeanNameELResolver resolver = createBeanNameELResolver(canCreate);
ELContext context =
new StandardELContext(ELManager.getExpressionFactory());
// Get bean one to be sure it has been replaced when testing replace
Object bean = resolver.getValue(context, null, BEAN01_NAME);
Assert.assertTrue(context.isPropertyResolved());
Assert.assertEquals(BEAN01, bean);
// Reset context
context.setPropertyResolved(false);
// Replace BEAN01
resolver.setValue(context, null, beanName, BEAN99);
if (canCreate || BEAN01_NAME.equals(beanName)) {
Assert.assertTrue(context.isPropertyResolved());
// Obtain BEAN01 again
context.setPropertyResolved(false);
bean = resolver.getValue(context, null, beanName);
Assert.assertTrue(context.isPropertyResolved());
Assert.assertEquals(BEAN99, bean);
} else {
Assert.assertFalse(context.isPropertyResolved());
// Obtain BEAN01 again
context.setPropertyResolved(false);
bean = resolver.getValue(context, null, BEAN01_NAME);
Assert.assertTrue(context.isPropertyResolved());
Assert.assertEquals(BEAN01, bean);
}
}
private enum MethodUnderTest {
GET_VALUE,
SET_VALUE,
GET_TYPE,
IS_READ_ONLY
}
}

View File

@@ -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 javax.el;
import javax.servlet.http.HttpServletResponse;
import org.junit.Assert;
import org.junit.Test;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.tomcat.util.buf.ByteChunk;
public class TestCompositeELResolver extends TomcatBaseTest {
@Test
public void testBug50408() throws Exception {
getTomcatInstanceTestWebapp(true, true);
int rc = getUrl("http://localhost:" + getPort() +
"/test/bug5nnnn/bug50408.jsp", new ByteChunk(), null);
Assert.assertEquals(HttpServletResponse.SC_OK, rc);
}
}

View File

@@ -0,0 +1,175 @@
/*
* 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 javax.el;
import java.util.List;
import javax.el.TesterEvaluationListener.Pair;
import org.junit.Assert;
import org.junit.Test;
public class TestELContext {
/**
* Tests that a null key results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testGetContext() {
ELContext elContext = new TesterELContext();
elContext.getContext(null);
}
/**
* Tests that a null key results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testPutContext01() {
ELContext elContext = new TesterELContext();
elContext.putContext(null, new Object());
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testPutContext02() {
ELContext elContext = new TesterELContext();
elContext.putContext(Object.class, null);
}
/**
* Tests that the context object will be added to the map with context
* objects. The key is used as unique identifier of the context object in
* the map.
*/
@Test
public void testPutContext03() {
ELContext elContext = new TesterELContext();
Assert.assertNull(elContext.getContext(String.class));
elContext.putContext(String.class, "test");
Assert.assertEquals("test", elContext.getContext(String.class));
elContext.putContext(String.class, "test1");
Assert.assertEquals("test1", elContext.getContext(String.class));
}
/**
* Tests that propertyResolved will be set to true and the corresponding
* listeners will be notified.
*/
@Test
public void testSetPropertyResolved() {
ELContext elContext = new TesterELContext();
TesterEvaluationListener listener = new TesterEvaluationListener();
elContext.addEvaluationListener(listener);
TesterBean bean = new TesterBean("test");
elContext.setPropertyResolved(bean, "name");
Assert.assertTrue(elContext.isPropertyResolved());
List<Pair> events = listener.getResolvedProperties();
Assert.assertEquals(1, events.size());
Pair p = events.get(0);
Assert.assertEquals(bean, p.getBase());
Assert.assertEquals("name", p.getProperty());
}
/**
* Tests that the corresponding listeners will be notified.
*/
@Test
public void testNotifyBeforeEvaluation() {
ELContext elContext = new TesterELContext();
TesterEvaluationListener listener = new TesterEvaluationListener();
elContext.addEvaluationListener(listener);
elContext.notifyBeforeEvaluation("before");
List<String> events = listener.getBeforeEvaluationExpressions();
Assert.assertEquals(1, events.size());
Assert.assertEquals("before", events.get(0));
}
/**
* Tests that the corresponding listeners will be notified.
*/
@Test
public void testNotifyAfterEvaluation() {
ELContext elContext = new TesterELContext();
TesterEvaluationListener listener = new TesterEvaluationListener();
elContext.addEvaluationListener(listener);
elContext.notifyAfterEvaluation("after");
List<String> events = listener.getAfterEvaluationExpressions();
Assert.assertEquals(1, events.size());
Assert.assertEquals("after", events.get(0));
}
/**
* Tests not compatible object and type.
*/
@Test(expected = ELException.class)
public void testConvertToType01() {
ELContext elContext = new TesterELContext();
elContext.convertToType("test", Integer.class);
}
/**
* Tests that if there is no ELResolver the standard coercions will be
* invoked.
*/
@Test
public void testConvertToType02() {
ELContext elContext = new TesterELContext();
boolean originalPropertyResolved = false;
elContext.setPropertyResolved(originalPropertyResolved);
Object result = elContext.convertToType("test", String.class);
Assert.assertEquals("test", result);
Assert.assertTrue(originalPropertyResolved == elContext
.isPropertyResolved());
}
/**
* Tests that if there is ELResolver it will handle the conversion. If this
* resolver cannot return a result the standard coercions will be invoked.
*/
@Test
public void testConvertToType03() {
ELContext elContext = new TesterELContext(new TesterELResolverOne());
boolean originalPropertyResolved = false;
elContext.setPropertyResolved(originalPropertyResolved);
Object result = elContext.convertToType("1", String.class);
Assert.assertEquals("ONE", result);
Assert.assertTrue(originalPropertyResolved == elContext
.isPropertyResolved());
result = elContext.convertToType("test", String.class);
Assert.assertEquals("test", result);
Assert.assertTrue(originalPropertyResolved == elContext
.isPropertyResolved());
}
}

View File

@@ -0,0 +1,211 @@
/*
* 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 javax.el;
import org.junit.Assert;
import org.junit.Test;
public class TestELProcessor {
@Test
public void testDefineBean01() {
ELProcessor elp = new ELProcessor();
elp.defineBean("bean01", new TesterBean("name01"));
Assert.assertEquals("name01", elp.eval("bean01.name"));
}
@Test(expected=ELException.class)
public void testEval01() {
ELProcessor elp = new ELProcessor();
elp.eval("${1+1}");
}
@Test(expected=ELException.class)
public void testEval02() {
ELProcessor elp = new ELProcessor();
elp.eval("#{1+1}");
}
@Test
public void testEval03() {
ELProcessor elp = new ELProcessor();
// Note \ is escaped as \\ in Java source code
String result = (String) elp.eval("'\\\\'");
Assert.assertEquals("\\", result);
}
@Test
public void testDefineFunctionMethod01() throws Exception {
ELProcessor elp = new ELProcessor();
elp.defineFunction("fn", "toBoolean",
Boolean.class.getMethod("valueOf", String.class));
Assert.assertEquals(Boolean.valueOf(true),
elp.eval("fn:toBoolean(true)"));
}
@Test
public void testDefineFunctionName01() throws Exception {
ELProcessor elp = new ELProcessor();
// java.lang should be automatically imported so no need for full class
// name
elp.defineFunction("fn", "toBoolean", "Boolean", "valueOf");
Assert.assertEquals(Boolean.valueOf(true),
elp.eval("fn:toBoolean(true)"));
}
@Test
public void testDefineFunctionName02() throws Exception {
ELProcessor elp = new ELProcessor();
elp.defineFunction("fn", "test", "java.lang.Integer", "Integer valueOf(int)");
Assert.assertEquals(Integer.valueOf(1), elp.eval("fn:test(1)"));
}
@Test
public void testDefineFunctionName03() throws Exception {
TesterFunctions.resetCallList();
ELProcessor elp = new ELProcessor();
elp.defineFunction("fn", "test", "javax.el.TesterFunctions", "void doIt()");
elp.eval("fn:test()");
Assert.assertEquals("A", TesterFunctions.getCallList());
}
@Test
public void testDefineFunctionName04() throws Exception {
TesterFunctions.resetCallList();
ELProcessor elp = new ELProcessor();
elp.defineFunction("fn", "test", "javax.el.TesterFunctions", "void doIt(int)");
elp.eval("fn:test(5)");
Assert.assertEquals("B", TesterFunctions.getCallList());
}
@Test
public void testDefineFunctionName05() throws Exception {
TesterFunctions.resetCallList();
ELProcessor elp = new ELProcessor();
elp.defineFunction("fn", "test", "javax.el.TesterFunctions", "void doIt(Integer)");
elp.eval("fn:test(null)");
Assert.assertEquals("C", TesterFunctions.getCallList());
}
@Test
public void testDefineFunctionName06() throws Exception {
TesterFunctions.resetCallList();
ELProcessor elp = new ELProcessor();
elp.defineFunction("", "", "javax.el.TesterFunctions", "void doIt(int)");
elp.eval("doIt(5)");
Assert.assertEquals("B", TesterFunctions.getCallList());
}
@Test
public void testDefineFunctionName07() throws Exception {
TesterFunctions.resetCallList();
ELProcessor elp = new ELProcessor();
elp.defineFunction("fn", "", "javax.el.TesterFunctions", "void doIt(int)");
elp.eval("fn:doIt(5)");
Assert.assertEquals("B", TesterFunctions.getCallList());
}
@Test
public void testDefineFunctionName08() throws Exception {
TesterFunctions.resetCallList();
ELProcessor elp = new ELProcessor();
elp.defineFunction("fn", "", "javax.el.TesterFunctions", "void doIt(int[])");
elp.eval("fn:doIt([5].stream().toArray())");
Assert.assertEquals("D", TesterFunctions.getCallList());
}
@Test
public void testDefineFunctionName09() throws Exception {
TesterFunctions.resetCallList();
ELProcessor elp = new ELProcessor();
elp.defineFunction("fn", "", "javax.el.TesterFunctions", "void doIt(int[][])");
elp.eval("fn:doIt([[5].stream().toArray()].stream().toArray())");
Assert.assertEquals("E", TesterFunctions.getCallList());
}
@Test
public void testDefineFunctionName10() throws Exception {
TesterFunctions.resetCallList();
ELProcessor elp = new ELProcessor();
elp.defineFunction("fn", "test1", "java.lang.Integer", "Integer valueOf(int)");
elp.defineFunction("fn", "test2", "javax.el.TesterFunctions", "void doIt(Integer[])");
elp.eval("fn:test2([fn:test1(1), fn:test1(2)].stream().toArray())");
Assert.assertEquals("F", TesterFunctions.getCallList());
}
@Test
public void testDefineFunctionName11() throws Exception {
TesterFunctions.resetCallList();
ELProcessor elp = new ELProcessor();
elp.defineFunction("fn", "test1", "java.lang.Integer", "Integer valueOf(int)");
elp.defineFunction("fn", "test2", "javax.el.TesterFunctions", "void doIt(Integer[][])");
elp.eval("fn:test2([[fn:test1(1), fn:test1(2)].stream().toArray()].stream().toArray())");
Assert.assertEquals("G", TesterFunctions.getCallList());
}
@Test
public void testDefineFunctionName12() throws Exception {
TesterFunctions.resetCallList();
ELProcessor elp = new ELProcessor();
elp.defineFunction("fn", "test", "javax.el.TesterFunctions", "void doIt(long...)");
elp.eval("fn:test(1,2)");
Assert.assertEquals("H", TesterFunctions.getCallList());
}
@Test
public void testDefineFunctionName13() throws Exception {
TesterFunctions.resetCallList();
ELProcessor elp = new ELProcessor();
elp.defineFunction("fn", "test", "javax.el.TesterFunctions", "void doIt(Object...)");
elp.eval("fn:test(null, null)");
Assert.assertEquals("I", TesterFunctions.getCallList());
}
@Test
public void testPrimitiveArray01() {
ELProcessor elp = new ELProcessor();
TesterBean bean01= new TesterBean("bean01");
elp.defineBean("bean01", bean01);
elp.defineBean("bean02", new TesterBean("bean02"));
Object result = elp.eval("bean02.setValueC(bean01.valueB);bean02.valueC");
Integer[] resultArray = (Integer[]) result;
Assert.assertEquals(bean01.getValueB().length, resultArray.length);
for (int i = 0; i < resultArray.length; i++) {
Assert.assertEquals(bean01.getValueB()[i], resultArray[i].intValue());
}
}
}

View File

@@ -0,0 +1,143 @@
/*
* 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 javax.el;
import org.junit.Assert;
import org.junit.Test;
public class TestELResolver {
@Test
public void testConvertToType01() {
ELContext context = new TesterELContext();
ValueExpression ve =
ELManager.getExpressionFactory().createValueExpression(
context, "1", String.class);
String result = (String) ve.getValue(context);
Assert.assertEquals("1", result);
}
@Test
public void testConvertToType02() {
ELContext context = new TesterELContext(new TesterELResolverOne());
ValueExpression ve =
ELManager.getExpressionFactory().createValueExpression(
context, "1", String.class);
String result = (String) ve.getValue(context);
Assert.assertEquals("ONE", result);
}
@Test
public void testConvertToType03() {
ELContext context = new TesterELContext(new TesterELResolverOne());
ValueExpression ve =
ELManager.getExpressionFactory().createValueExpression(
context, "2", String.class);
String result = (String) ve.getValue(context);
Assert.assertEquals("2", result);
}
@Test
public void testConvertToType04() {
CompositeELResolver resolver = new CompositeELResolver();
ELContext context = new TesterELContext(resolver);
ValueExpression ve =
ELManager.getExpressionFactory().createValueExpression(
context, "2", String.class);
String result = (String) ve.getValue(context);
Assert.assertEquals("2", result);
}
@Test
public void testConvertToType05() {
CompositeELResolver resolver = new CompositeELResolver();
resolver.add(new TesterELResolverOne());
resolver.add(new TesterELResolverTwo());
ELContext context = new TesterELContext(resolver);
ValueExpression ve =
ELManager.getExpressionFactory().createValueExpression(
context, "1", String.class);
String result = (String) ve.getValue(context);
Assert.assertEquals("ONE", result);
}
@Test
public void testConvertToType06() {
CompositeELResolver resolver = new CompositeELResolver();
resolver.add(new TesterELResolverOne());
resolver.add(new TesterELResolverTwo());
ELContext context = new TesterELContext(resolver);
ValueExpression ve =
ELManager.getExpressionFactory().createValueExpression(
context, "2", String.class);
String result = (String) ve.getValue(context);
Assert.assertEquals("TWO", result);
}
@Test
public void testConvertToType07() {
CompositeELResolver resolver = new CompositeELResolver();
resolver.add(new TesterELResolverOne());
resolver.add(new TesterELResolverTwo());
ELContext context = new TesterELContext(resolver);
ValueExpression ve =
ELManager.getExpressionFactory().createValueExpression(
context, "3", String.class);
String result = (String) ve.getValue(context);
Assert.assertEquals("3", result);
}
// https://bz.apache.org/bugzilla/show_bug.cgi?id=57802
@Test
public void testDefaultConvertToType() {
ELContext context = new TesterELContext(new StaticFieldELResolver());
ValueExpression ve = ELManager.getExpressionFactory().createValueExpression(
context, "${!Boolean.FALSE}", Boolean.class);
Boolean result = (Boolean) ve.getValue(context);
Assert.assertEquals(Boolean.TRUE, result);
}
}

View File

@@ -0,0 +1,134 @@
/*
* 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 javax.el;
import java.util.List;
import javax.el.TesterEvaluationListener.Pair;
import org.junit.Assert;
import org.junit.Test;
public class TestEvaluationListener {
@Test
public void testPropertyResolved01() {
ELContext context = new TesterELContext();
ELResolver resolver = new BeanELResolver();
TesterBean bean = new TesterBean("test");
TesterEvaluationListener listener = new TesterEvaluationListener();
context.addEvaluationListener(listener);
Object result = resolver.getValue(context, bean, "name");
Assert.assertTrue(context.isPropertyResolved());
Assert.assertEquals("test", result);
List<Pair> events = listener.getResolvedProperties();
Assert.assertEquals(1, events.size());
Pair p = events.get(0);
Assert.assertEquals(bean, p.getBase());
Assert.assertEquals("name", p.getProperty());
}
@Test
public void testPropertyResolved02() {
ELContext context = new TesterELContext();
ELResolver resolver = new BeanELResolver();
TesterBean bean = new TesterBean("test");
TesterEvaluationListener listener = new TesterEvaluationListener();
context.addEvaluationListener(listener);
Exception exception = null;
try {
resolver.getValue(context, bean, "foo");
} catch (PropertyNotFoundException e) {
exception = e;
}
Assert.assertNotNull(exception);
// Still expect the property to be resolved and the listener to fire
// since the vent is at the time of resolution. The EL spec could be a
// lot clear on this.
Assert.assertTrue(context.isPropertyResolved());
List<Pair> events = listener.getResolvedProperties();
Assert.assertEquals(1, events.size());
Pair p = events.get(0);
Assert.assertEquals(bean, p.getBase());
Assert.assertEquals("foo", p.getProperty());
}
@Test
public void testEvaluation01() {
ExpressionFactory factory = ELManager.getExpressionFactory();
ELContext context = new TesterELContext();
String expression = "${1 + 1}";
ValueExpression ve =
factory.createValueExpression(context, expression, int.class);
TesterEvaluationListener listener = new TesterEvaluationListener();
context.addEvaluationListener(listener);
Object result = ve.getValue(context);
// Check the result
Assert.assertEquals(Integer.valueOf(2), result);
List<String> before = listener.getBeforeEvaluationExpressions();
Assert.assertEquals(1, before.size());
Assert.assertEquals(expression, before.get(0));
List<String> after = listener.getAfterEvaluationExpressions();
Assert.assertEquals(1, after.size());
Assert.assertEquals(expression, after.get(0));
}
@Test
public void testEvaluation02() {
ExpressionFactory factory = ELManager.getExpressionFactory();
ELContext context = new TesterELContext(new CompositeELResolver());
String expression = "${foo.bar + 1}";
ValueExpression ve =
factory.createValueExpression(context, expression, int.class);
TesterEvaluationListener listener = new TesterEvaluationListener();
context.addEvaluationListener(listener);
Exception e = null;
try {
ve.getValue(context);
} catch (PropertyNotFoundException pnfe) {
e = pnfe;
}
Assert.assertNotNull(e);
List<String> before = listener.getBeforeEvaluationExpressions();
Assert.assertEquals(1, before.size());
Assert.assertEquals(expression, before.get(0));
List<String> after = listener.getAfterEvaluationExpressions();
Assert.assertEquals(0, after.size());
}
}

View File

@@ -0,0 +1,273 @@
/*
* 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 javax.el;
import java.util.ArrayList;
import org.junit.Assert;
import org.junit.Test;
import org.apache.tomcat.util.res.StringManager;
public class TestImportHandler {
/**
* java.lang should be imported by default
*/
@Test
public void testResolveClass01() {
ImportHandler handler = new ImportHandler();
Class<?> result = handler.resolveClass("String");
Assert.assertEquals(String.class, result);
}
/**
* Resolve an unknown class
*/
@Test
public void testResolveClass02() {
ImportHandler handler = new ImportHandler();
Class<?> result = handler.resolveClass("Foo");
Assert.assertNull(result);
}
/**
* Conflict on resolution.
*/
@Test
public void testResolveClass03() {
ImportHandler handler = new ImportHandler();
handler.importPackage("org.apache.tomcat.util");
handler.importPackage("org.apache.jasper.runtime");
for (int i = 1; i <= 3; i++) {
try {
Class<?> clazz = handler.resolveClass("ExceptionUtils");
Assert.fail("Expected ELException but got [" + clazz.getName()
+ "] on iteration " + i);
} catch (ELException ex) {
// Expected
}
}
}
/**
* Multiple package imports with a single match.
* https://bz.apache.org/bugzilla/show_bug.cgi?id=57113
*/
@Test
public void testResolveClass04() {
ImportHandler handler = new ImportHandler();
handler.importPackage("java.util");
handler.importPackage("java.net");
Class<?> clazz = handler.resolveClass("ArrayList");
Assert.assertEquals(ArrayList.class, clazz);
}
/**
* Attempting to resolve something that isn't a simple class name
* https://bz.apache.org/bugzilla/show_bug.cgi?id=57132
*/
@Test
public void testResolveClass05() {
ImportHandler handler = new ImportHandler();
handler.importPackage("java.nio");
Class<?> clazz = handler.resolveClass("charset.StandardCharsets");
Assert.assertNull(clazz);
}
/**
* Attempting to resolve something that isn't a simple class name
* https://bz.apache.org/bugzilla/show_bug.cgi?id=57132
*/
@Test
public void testResolveClass06() {
ImportHandler handler = new ImportHandler();
handler.importPackage("java.nio");
Class<?> clazz = handler.resolveClass(null);
Assert.assertNull(clazz);
}
/**
* Import a valid class.
*/
@Test
public void testImportClass01() {
ImportHandler handler = new ImportHandler();
handler.importClass("org.apache.tomcat.util.res.StringManager");
Class<?> result = handler.resolveClass("StringManager");
Assert.assertEquals(StringManager.class, result);
}
/**
* Import an invalid class.
*/
@Test
public void testImportClass02() {
ImportHandler handler = new ImportHandler();
handler.importClass("org.apache.tomcat.util.res.StringManagerX");
Class<?> result = handler.resolveClass("StringManagerX");
Assert.assertNull(result);
}
/**
* Import conflicting classes
*/
@Test
public void testImportClass03() {
ImportHandler handler = new ImportHandler();
handler.importClass("org.apache.tomcat.util.ExceptionUtils");
for (int i = 1; i <= 3; i++) {
try {
handler.importClass("org.apache.jasper.util.ExceptionUtils");
Assert.fail("Expected ELException but got none on iteration "
+ i);
} catch (ELException ex) {
// Expected
}
}
}
/**
* Import duplicate classes (i.e. the same class twice).
*/
@Test
public void testImportClass04() {
ImportHandler handler = new ImportHandler();
handler.importClass("org.apache.tomcat.util.res.StringManager");
handler.importClass("org.apache.tomcat.util.res.StringManager");
Class<?> result = handler.resolveClass("StringManager");
Assert.assertEquals(StringManager.class, result);
}
/**
* Import an invalid package.
*/
@Test
public void testImportPackage01_57574() {
ImportHandler handler = new ImportHandler();
handler.importPackage("org.apache.tomcat.foo");
// No exception is expected
}
/**
* Import a valid static field.
*/
@Test
public void testImportStatic01() {
ImportHandler handler = new ImportHandler();
handler.importStatic("org.apache.tomcat.util.scan.Constants.Package");
Class<?> result = handler.resolveStatic("Package");
Assert.assertEquals(org.apache.tomcat.util.scan.Constants.class, result);
}
/**
* Import an invalid static field - does not exist.
*/
@Test(expected=ELException.class)
public void testImportStatic02() {
ImportHandler handler = new ImportHandler();
handler.importStatic("org.apache.tomcat.util.buf.Constants.PackageXX");
}
/**
* Import an invalid static field - non-public.
*/
@Test
public void testImportStatic03() {
ImportHandler handler = new ImportHandler();
handler.importStatic("org.apache.tomcat.util.buf.Ascii.toLower");
Class<?> result = handler.resolveStatic("toLower");
Assert.assertEquals(org.apache.tomcat.util.buf.Ascii.class, result);
}
/**
* Import an invalid static field - conflict.
*/
@Test
public void testImportStatic04() {
ImportHandler handler = new ImportHandler();
handler.importStatic("org.apache.tomcat.util.buf.Constants.Package");
for (int i = 1; i <= 3; i++) {
try {
handler.importStatic("org.apache.tomcat.util.scan.Constants.Package");
Assert.fail("Expected ELException but got none on iteration "
+ i);
} catch (ELException ex) {
// Expected
}
}
}
/**
* Package imports with conflicts due to non-public classes should not
* conflict.
*/
@Test
public void testBug57135() {
ImportHandler importHandler = new ImportHandler();
importHandler.importPackage("util.a");
importHandler.importPackage("util.b");
importHandler.resolveClass("Foo");
}
}

View File

@@ -0,0 +1,179 @@
/*
* 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 javax.el;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.URI;
import java.net.URL;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import org.apache.tomcat.util.compat.JreCompat;
public class TestImportHandlerStandardPackages {
@Test
public void testClassListsAreComplete() throws Exception {
// Use reflection to get hold of the internal Map
Class<?> clazz = ImportHandler.class;
Field f = clazz.getDeclaredField("standardPackages");
f.setAccessible(true);
Object obj = f.get(null);
Assert.assertTrue("Not Map", obj instanceof Map);
@SuppressWarnings("unchecked")
Map<String,Set<String>> standardPackageName = (Map<String, Set<String>>) obj;
for (Map.Entry<String,Set<String>> entry : standardPackageName.entrySet()) {
checkPackageClassList(entry.getKey(), entry.getValue());
}
}
private void checkPackageClassList(String packageName, Set<String> classNames) throws Exception {
if ("java.lang".equals(packageName)) {
// The code below is designed to run on Java 9 so skip this check
// if running on Java 8. The test has previously been run with Java
// 9 (and later) so it is not necessary that this is executed on
// every test run. The intention is that it will catch new classes
// when the tests are run on a newer JRE.
// The latest version of the JRE where this test is known to pass is
// - OpenJDK 14 EA 27
if (!JreCompat.isJre9Available()) {
return;
}
for (String fileName : getJavaBaseClasses()) {
if (!fileName.startsWith("java/lang/") || // Class not in java.lang
fileName.lastIndexOf('/') != 9 || // Class no in sub-package
!fileName.endsWith(".class")) { // Exclude non-class resources
continue;
}
// Extract class name
String className = fileName.substring(10, fileName.length() - 6);
Class<?> clazz = Class.forName("java.lang." + className);
if (!Modifier.isPublic(clazz.getModifiers())) {
// Exclude non-public classes
continue;
}
className = className.replace('$', '.');
if (classNames.contains(className)) {
// Already listed
continue;
}
// Skip public inner classes of non-public classes
if (className.startsWith("FdLibm.") ||
className.startsWith("LiveStackFrame.") ||
className.startsWith("WeakPairMap.")) {
continue;
}
// Anything left at this point is an error
Assert.fail(fileName);
}
} else {
// When this test runs, the class loader will be loading resources
// from a directory for each of these packages.
ClassLoader cl = Thread.currentThread().getContextClassLoader();
String path = packageName.replace('.', '/');
Enumeration<URL> resources = cl.getResources(path);
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
URI uri = resource.toURI();
// Gump includes some JARs on classpath - skip them
if (!"file".equals(uri.getScheme())) {
continue;
}
File dir = new File(uri);
String[] files = dir.list();
Assert.assertNotNull(files);
for (String file : files) {
if (!file.endsWith(".class")) {
// Skip non-class resoucres
continue;
}
if (file.startsWith("Test")) {
// Skip test resources
continue;
}
if (file.matches(".*\\$[0-9]?\\.class")) {
// Skip anonymous inner classes
continue;
}
String name = file.substring(0, file.length() - 6);
name = name.replace('$', '.');
if (classNames.contains(name)) {
// Skip classes already known
continue;
}
File f = new File (dir, file);
if (!f.isFile()) {
// Skip directories
continue;
}
Class<?> clazz = Class.forName(packageName + "." + name);
if (!Modifier.isPublic(clazz.getModifiers())) {
// Skip non-public classes
continue;
}
// There should be nothing left unless we missed something
Assert.fail(packageName + "." + name);
}
}
}
}
private static String[] getJavaBaseClasses() throws Exception {
// While this code is only used on Java 9 and later, it needs to compile
// with Java 8 so use reflection for now.
Class<?> clazzModuleFinder = Class.forName("java.lang.module.ModuleFinder");
Class<?> clazzModuleReference = Class.forName("java.lang.module.ModuleReference");
Class<?> clazzOptional = Class.forName("java.util.Optional");
Class<?> clazzModuleReader = Class.forName("java.lang.module.ModuleReader");
Class<?> clazzStream = Class.forName("java.util.stream.Stream");
// Returns ModuleFinder
Object mf = clazzModuleFinder.getMethod("ofSystem").invoke(null);
// Returns Optional containing a ModuleReference
Object optMRef = clazzModuleFinder.getMethod("find", String.class).invoke(mf, "java.base");
// Extract the ModuleReference
Object mRef = clazzOptional.getMethod("get").invoke(optMRef);
// Returns ModuleReader
Object mr = clazzModuleReference.getMethod("open").invoke(mRef);
// Returns a Stream of class names
Object stream = clazzModuleReader.getMethod("list").invoke(mr);
// Convert to an array
Object[] names = (Object[]) clazzStream.getMethod("toArray").invoke(stream);
// Cast
String [] result = new String[names.length];
for (int i = 0; i < names.length; i++) {
result[i] = (String) names[i];
}
return result;
}
}

View File

@@ -0,0 +1,388 @@
/*
* 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 javax.el;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
public class TestListELResolver {
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testGetValue01() {
ListELResolver resolver = new ListELResolver();
resolver.getValue(null, new Object(), new Object());
}
/**
* Tests that a valid property is not resolved if base is not List.
*/
@Test
public void testGetValue02() {
doNegativeTest(new Object(), new Object(), MethodUnderTest.GET_VALUE,
true);
}
/**
* Tests that a valid property is resolved.
*/
@Test
public void testGetValue03() {
ListELResolver resolver = new ListELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
List<String> list = new ArrayList<>();
list.add("key");
Object result = resolver.getValue(context, list, Integer.valueOf(0));
Assert.assertEquals("key", result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests a coercion cannot be performed as the key is not integer.
*/
@Test(expected = IllegalArgumentException.class)
public void testGetValue04() {
ListELResolver resolver = new ListELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
List<String> list = new ArrayList<>();
list.add("key");
resolver.getValue(context, list, "key");
}
/**
* Tests that the key is out of bounds and null will be returned.
*/
@Test
public void testGetValue05() {
ListELResolver resolver = new ListELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
List<String> list = new ArrayList<>();
list.add("key");
Object result = resolver.getValue(context, list, Integer.valueOf(1));
Assert.assertNull(result);
Assert.assertTrue(context.isPropertyResolved());
result = resolver.getValue(context, list, Integer.valueOf(-1));
Assert.assertNull(result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testGetType01() {
ListELResolver resolver = new ListELResolver();
resolver.getType(null, new Object(), new Object());
}
/**
* Tests that a valid property is not resolved if base is not List.
*/
@Test
public void testGetType02() {
doNegativeTest(new Object(), new Object(), MethodUnderTest.GET_TYPE,
true);
}
/**
* Tests that a valid property is resolved.
*/
@Test
public void testGetType03() {
ListELResolver resolver = new ListELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
List<String> list = new ArrayList<>();
list.add("key");
Class<?> result = resolver.getType(context, list, Integer.valueOf(0));
Assert.assertEquals(Object.class, result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that the key is out of bounds and exception will be thrown.
*/
@Test(expected = PropertyNotFoundException.class)
public void testGetType04() {
ListELResolver resolver = new ListELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
List<String> list = new ArrayList<>();
list.add("key");
resolver.getType(context, list, Integer.valueOf(1));
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testSetValue01() {
ListELResolver resolver = new ListELResolver();
resolver.setValue(null, new Object(), new Object(), new Object());
}
/**
* Tests that a valid property is not set if base is not List.
*/
@Test
public void testSetValue02() {
doNegativeTest(new Object(), new Object(), MethodUnderTest.SET_VALUE,
false);
}
/**
* Tests that an exception is thrown when readOnly is true.
*/
@Test(expected = PropertyNotWritableException.class)
public void testSetValue03() {
ListELResolver resolver = new ListELResolver(true);
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
resolver.setValue(context, new ArrayList<>(), new Object(),
new Object());
}
/**
* Tests that a valid property is set.
*/
@Test
public void testSetValue04() {
ListELResolver resolver = new ListELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
List<String> list = new ArrayList<>();
list.add("value");
resolver.setValue(context, list, Integer.valueOf(0), "value");
Assert.assertEquals("value",
resolver.getValue(context, list, Integer.valueOf(0)));
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that an exception is thrown when the list is not modifiable.
*/
@Test(expected = PropertyNotWritableException.class)
public void testSetValue05() {
ListELResolver resolver = new ListELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
List<Object> list = Collections.unmodifiableList(new ArrayList<>());
resolver.setValue(context, list, Integer.valueOf(0), "value");
}
/**
* Tests a coercion cannot be performed as the key is not integer.
*/
@Test(expected = IllegalArgumentException.class)
public void testSetValue06() {
ListELResolver resolver = new ListELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
List<String> list = new ArrayList<>();
list.add("key");
resolver.setValue(context, list, "key", "value");
}
/**
* Tests that the key is out of bounds and exception will be thrown.
*/
@Test(expected = PropertyNotFoundException.class)
public void testSetValue07() {
ListELResolver resolver = new ListELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
List<String> list = new ArrayList<>();
list.add("key");
resolver.setValue(context, list, Integer.valueOf(1), "value");
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testIsReadOnly01() {
ListELResolver resolver = new ListELResolver();
resolver.isReadOnly(null, new Object(), new Object());
}
/**
* Tests that the propertyResolved is false if base is not List.
*/
@Test
public void testIsReadOnly02() {
ListELResolver resolver = new ListELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
boolean result = resolver.isReadOnly(context, new Object(),
new Object());
Assert.assertFalse(result);
Assert.assertFalse(context.isPropertyResolved());
resolver = new ListELResolver(true);
result = resolver.isReadOnly(context, new Object(), new Object());
Assert.assertTrue(result);
Assert.assertFalse(context.isPropertyResolved());
}
/**
* Tests that if the ListELResolver is constructed with readOnly the method
* will return always true, otherwise false.
*/
@Test
public void testIsReadOnly03() {
ListELResolver resolver = new ListELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
List<String> list = new ArrayList<>();
list.add("key");
boolean result = resolver.isReadOnly(context, list, Integer.valueOf(0));
Assert.assertFalse(result);
Assert.assertTrue(context.isPropertyResolved());
resolver = new ListELResolver(true);
result = resolver.isReadOnly(context, list, Integer.valueOf(0));
Assert.assertTrue(result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that the readOnly is true always when the map is not modifiable.
*/
@Test
public void testIsReadOnly04() {
ListELResolver resolver = new ListELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
List<String> list = new ArrayList<>();
list.add("key");
List<String> unmodifiableList = Collections.unmodifiableList(list);
boolean result = resolver.isReadOnly(context, unmodifiableList,
Integer.valueOf(0));
Assert.assertTrue(result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that the key is out of bounds and exception will be thrown.
*/
@Test(expected = PropertyNotFoundException.class)
public void testIsReadOnly05() {
ListELResolver resolver = new ListELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
List<String> list = new ArrayList<>();
list.add("key");
resolver.isReadOnly(context, list, Integer.valueOf(1));
}
/**
* Tests that a result is returned even when a coercion cannot be performed.
*/
@Test
public void testIsReadOnly06() {
ListELResolver resolver = new ListELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
List<String> list = new ArrayList<>();
list.add("key");
boolean result = resolver.isReadOnly(context, list, "key");
Assert.assertFalse(result);
Assert.assertTrue(context.isPropertyResolved());
resolver = new ListELResolver(true);
result = resolver.isReadOnly(context, list, "key");
Assert.assertTrue(result);
Assert.assertTrue(context.isPropertyResolved());
}
private void doNegativeTest(Object base, Object trigger,
MethodUnderTest method, boolean checkResult) {
ListELResolver resolver = new ListELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
Object result = null;
switch (method) {
case GET_VALUE: {
result = resolver.getValue(context, base, trigger);
break;
}
case SET_VALUE: {
resolver.setValue(context, base, trigger, new Object());
break;
}
case GET_TYPE: {
result = resolver.getType(context, base, trigger);
break;
}
default: {
// Should never happen
Assert.fail("Missing case for method");
}
}
if (checkResult) {
Assert.assertNull(result);
}
Assert.assertFalse(context.isPropertyResolved());
}
private enum MethodUnderTest {
GET_VALUE, SET_VALUE, GET_TYPE
}
}

View File

@@ -0,0 +1,318 @@
/*
* 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 javax.el;
import java.beans.FeatureDescriptor;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
public class TestMapELResolver {
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testGetType01() {
MapELResolver mapELResolver = new MapELResolver();
mapELResolver.getType(null, new Object(), new Object());
}
/**
* Tests that a valid property is not resolved if base is not Map.
*/
@Test
public void testGetType02() {
doNegativeTest(new Object(), new Object(), MethodUnderTest.GET_TYPE,
true);
}
/**
* Tests that a valid property is resolved.
*/
@Test
public void testGetType03() {
MapELResolver mapELResolver = new MapELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
Class<?> result = mapELResolver.getType(context, new HashMap<>(),
"test");
Assert.assertEquals(Object.class, result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testGetValue01() {
MapELResolver mapELResolver = new MapELResolver();
mapELResolver.getValue(null, new Object(), new Object());
}
/**
* Tests that a valid property is not resolved if base is not Map.
*/
@Test
public void testGetValue02() {
doNegativeTest(new Object(), new Object(), MethodUnderTest.GET_VALUE,
true);
}
/**
* Tests that a valid property is resolved.
*/
@Test
public void testGetValue03() {
MapELResolver mapELResolver = new MapELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
Map<String, String> map = new HashMap<>();
map.put("key", "value");
Object result = mapELResolver.getValue(context, map, "key");
Assert.assertEquals("value", result);
Assert.assertTrue(context.isPropertyResolved());
result = mapELResolver.getValue(context, map, "unknown-key");
Assert.assertNull(result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testSetValue01() {
MapELResolver mapELResolver = new MapELResolver();
mapELResolver.setValue(null, new Object(), new Object(), new Object());
}
/**
* Tests that a valid property is not set if base is not Map.
*/
@Test
public void testSetValue02() {
doNegativeTest(new Object(), new Object(), MethodUnderTest.SET_VALUE,
false);
}
/**
* Tests that an exception is thrown when readOnly is true.
*/
@Test(expected = PropertyNotWritableException.class)
public void testSetValue03() {
MapELResolver mapELResolver = new MapELResolver(true);
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
mapELResolver.setValue(context, new HashMap<>(), new Object(),
new Object());
}
/**
* Tests that a valid property is set.
*/
@Test
public void testSetValue04() {
MapELResolver mapELResolver = new MapELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
Map<String, String> map = new HashMap<>();
mapELResolver.setValue(context, map, "key", "value");
Assert.assertEquals("value",
mapELResolver.getValue(context, map, "key"));
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that an exception is thrown when the map is not modifiable.
*/
@Test(expected = PropertyNotWritableException.class)
public void testSetValue05() {
MapELResolver mapELResolver = new MapELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
Map<Object, Object> map = Collections.unmodifiableMap(new HashMap<>());
mapELResolver.setValue(context, map, "key", "value");
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testIsReadOnly01() {
MapELResolver mapELResolver = new MapELResolver();
mapELResolver.isReadOnly(null, new Object(), new Object());
}
/**
* Tests that the propertyResolved is false if base is not Map.
*/
@Test
public void testIsReadOnly02() {
MapELResolver mapELResolver = new MapELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
boolean result = mapELResolver.isReadOnly(context, new Object(),
new Object());
Assert.assertFalse(result);
Assert.assertFalse(context.isPropertyResolved());
mapELResolver = new MapELResolver(true);
result = mapELResolver.isReadOnly(context, new Object(), new Object());
Assert.assertTrue(result);
Assert.assertFalse(context.isPropertyResolved());
}
/**
* Tests that if the MapELResolver is constructed with readOnly the method
* will return always true, otherwise false.
*/
@Test
public void testIsReadOnly03() {
MapELResolver mapELResolver = new MapELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
boolean result = mapELResolver.isReadOnly(context, new HashMap<>(),
new Object());
Assert.assertFalse(result);
Assert.assertTrue(context.isPropertyResolved());
mapELResolver = new MapELResolver(true);
result = mapELResolver.isReadOnly(context, new HashMap<>(),
new Object());
Assert.assertTrue(result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that the readOnly is true always when the map is not modifiable.
*/
@Test
public void testIsReadOnly04() {
MapELResolver mapELResolver = new MapELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
Map<Object, Object> map = Collections.unmodifiableMap(new HashMap<>());
boolean result = mapELResolver.isReadOnly(context, map, new Object());
Assert.assertTrue(result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that a valid FeatureDescriptors are not returned if base is not
* Map.
*/
@Test
public void testGetFeatureDescriptors01() {
MapELResolver mapELResolver = new MapELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
Iterator<FeatureDescriptor> result = mapELResolver
.getFeatureDescriptors(context, new Object());
Assert.assertNull(result);
}
/**
* Tests that a valid FeatureDescriptors are returned.
*/
@Test
public void testGetFeatureDescriptors02() {
MapELResolver mapELResolver = new MapELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
Map<String, String> map = new HashMap<>();
map.put("key", "value");
Iterator<FeatureDescriptor> result = mapELResolver
.getFeatureDescriptors(context, map);
while (result.hasNext()) {
FeatureDescriptor featureDescriptor = result.next();
Assert.assertEquals("key", featureDescriptor.getDisplayName());
Assert.assertEquals("key", featureDescriptor.getName());
Assert.assertEquals("", featureDescriptor.getShortDescription());
Assert.assertFalse(featureDescriptor.isExpert());
Assert.assertFalse(featureDescriptor.isHidden());
Assert.assertTrue(featureDescriptor.isPreferred());
Assert.assertEquals("key".getClass(),
featureDescriptor.getValue(ELResolver.TYPE));
Assert.assertEquals(Boolean.TRUE, featureDescriptor
.getValue(ELResolver.RESOLVABLE_AT_DESIGN_TIME));
}
}
private void doNegativeTest(Object base, Object trigger,
MethodUnderTest method, boolean checkResult) {
MapELResolver resolver = new MapELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
Object result = null;
switch (method) {
case GET_VALUE: {
result = resolver.getValue(context, base, trigger);
break;
}
case SET_VALUE: {
resolver.setValue(context, base, trigger, new Object());
break;
}
case GET_TYPE: {
result = resolver.getType(context, base, trigger);
break;
}
default: {
// Should never happen
Assert.fail("Missing case for method");
}
}
if (checkResult) {
Assert.assertNull(result);
}
Assert.assertFalse(context.isPropertyResolved());
}
private enum MethodUnderTest {
GET_VALUE, SET_VALUE, GET_TYPE
}
}

View File

@@ -0,0 +1,327 @@
/*
* 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 javax.el;
import java.beans.FeatureDescriptor;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.ListResourceBundle;
import java.util.ResourceBundle;
import org.junit.Assert;
import org.junit.Test;
import org.apache.jasper.el.ELContextImpl;
public class TestResourceBundleELResolver {
@Test
public void bug53001() {
ExpressionFactory factory = ExpressionFactory.newInstance();
ELContext context = new ELContextImpl(factory);
ResourceBundle rb = new TesterResourceBundle();
ValueExpression var = factory.createValueExpression(rb,
ResourceBundle.class);
context.getVariableMapper().setVariable("rb", var);
ValueExpression ve = factory.createValueExpression(context,
"${rb.keys}", String.class);
MethodExpression me = factory.createMethodExpression(context,
"${rb.getKeys()}", Enumeration.class, null);
// Ensure we are specification compliant
String result1 = (String) ve.getValue(context);
Assert.assertEquals("???keys???", result1);
// Check that the method expression does return the keys
Object result2 = me.invoke(context, null);
Assert.assertTrue(result2 instanceof Enumeration);
@SuppressWarnings("unchecked")
Enumeration<String> e = (Enumeration<String>) result2;
Assert.assertTrue(e.hasMoreElements());
String element = e.nextElement();
if ("key1".equals(element)) {
Assert.assertEquals("key1", element);
Assert.assertTrue(e.hasMoreElements());
Assert.assertEquals("key2", e.nextElement());
Assert.assertFalse(e.hasMoreElements());
} else {
Assert.assertEquals("key2", element);
Assert.assertTrue(e.hasMoreElements());
Assert.assertEquals("key1", e.nextElement());
Assert.assertFalse(e.hasMoreElements());
}
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testGetValue01() {
ResourceBundleELResolver resolver = new ResourceBundleELResolver();
resolver.getValue(null, new Object(), new Object());
}
/**
* Tests that a valid property is not resolved if base is not
* ResourceBundle.
*/
@Test
public void testGetValue02() {
doNegativeTest(new Object(), new Object(), MethodUnderTest.GET_VALUE,
true);
}
/**
* Tests that a valid property is resolved.
*/
@Test
public void testGetValue03() {
ResourceBundleELResolver resolver = new ResourceBundleELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
ResourceBundle resourceBundle = new TesterResourceBundle();
Object result = resolver.getValue(context, resourceBundle, "key1");
Assert.assertEquals("value1", result);
Assert.assertTrue(context.isPropertyResolved());
result = resolver.getValue(context, resourceBundle, "unknown-key");
Assert.assertEquals("???unknown-key???", result);
Assert.assertTrue(context.isPropertyResolved());
result = resolver.getValue(context, resourceBundle, null);
Assert.assertNull(result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testGetType01() {
ResourceBundleELResolver resolver = new ResourceBundleELResolver();
resolver.getType(null, new Object(), new Object());
}
/**
* Tests that a valid property is not resolved if base is not
* ResourceBundle.
*/
@Test
public void testGetType02() {
doNegativeTest(new Object(), new Object(), MethodUnderTest.GET_TYPE,
true);
}
/**
* Tests that null will be returned when base is ResourceBundle. Checks that
* the propertyResolved is true.
*/
@Test
public void testGetType03() {
ResourceBundleELResolver resolver = new ResourceBundleELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
ResourceBundle resourceBundle = new TesterResourceBundle();
Class<?> result = resolver.getType(context, resourceBundle, "key1");
Assert.assertNull(result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testSetValue01() {
ResourceBundleELResolver resolver = new ResourceBundleELResolver();
resolver.setValue(null, new Object(), new Object(), new Object());
}
/**
* Tests that a valid property is not set if base is not ResourceBundle.
*/
@Test
public void testSetValue02() {
doNegativeTest(new Object(), new Object(), MethodUnderTest.SET_VALUE,
false);
}
/**
* Tests that an exception is thrown because the resolver is read only.
*/
@Test(expected = PropertyNotWritableException.class)
public void testSetValue03() {
ResourceBundleELResolver resolver = new ResourceBundleELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
ResourceBundle resourceBundle = new TesterResourceBundle();
resolver.setValue(context, resourceBundle, new Object(), new Object());
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testIsReadOnly01() {
ResourceBundleELResolver resolver = new ResourceBundleELResolver();
resolver.isReadOnly(null, new Object(), new Object());
}
/**
* Tests that the propertyResolved is false and readOnly is false if base is
* not ResourceBundle.
*/
@Test
public void testIsReadOnly02() {
ResourceBundleELResolver resolver = new ResourceBundleELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
boolean result = resolver.isReadOnly(context, new Object(),
new Object());
Assert.assertFalse(result);
Assert.assertFalse(context.isPropertyResolved());
}
/**
* Tests that the readOnly is true always when the base is ResourceBundle.
*/
@Test
public void testIsReadOnly03() {
ResourceBundleELResolver resolver = new ResourceBundleELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
ResourceBundle resourceBundle = new TesterResourceBundle();
boolean result = resolver.isReadOnly(context, resourceBundle,
new Object());
Assert.assertTrue(result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that a valid FeatureDescriptors are not returned if base is not
* ResourceBundle.
*/
@Test
public void testGetFeatureDescriptors01() {
ResourceBundleELResolver resolver = new ResourceBundleELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
Iterator<FeatureDescriptor> result = resolver.getFeatureDescriptors(
context, new Object());
Assert.assertNull(result);
}
/**
* Tests that a valid FeatureDescriptors are returned.
*/
@Test
public void testGetFeatureDescriptors02() {
ResourceBundleELResolver resolver = new ResourceBundleELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
ResourceBundle resourceBundle = new TesterResourceBundle(
new Object[][] { { "key", "value" } });
Iterator<FeatureDescriptor> result = resolver.getFeatureDescriptors(
context, resourceBundle);
while (result.hasNext()) {
FeatureDescriptor featureDescriptor = result.next();
Assert.assertEquals("key", featureDescriptor.getDisplayName());
Assert.assertEquals("key", featureDescriptor.getName());
Assert.assertEquals("", featureDescriptor.getShortDescription());
Assert.assertFalse(featureDescriptor.isExpert());
Assert.assertFalse(featureDescriptor.isHidden());
Assert.assertTrue(featureDescriptor.isPreferred());
Assert.assertEquals(String.class,
featureDescriptor.getValue(ELResolver.TYPE));
Assert.assertEquals(Boolean.TRUE, featureDescriptor
.getValue(ELResolver.RESOLVABLE_AT_DESIGN_TIME));
}
}
private static class TesterResourceBundle extends ListResourceBundle {
public TesterResourceBundle() {
this(new Object[][] { { "key1", "value1" }, { "key2", "value2" } });
}
public TesterResourceBundle(Object[][] contents) {
this.contents = contents;
}
@Override
protected Object[][] getContents() {
return contents;
}
private Object[][] contents;
}
private void doNegativeTest(Object base, Object trigger,
MethodUnderTest method, boolean checkResult) {
ResourceBundleELResolver resolver = new ResourceBundleELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
Object result = null;
switch (method) {
case GET_VALUE: {
result = resolver.getValue(context, base, trigger);
break;
}
case SET_VALUE: {
resolver.setValue(context, base, trigger, new Object());
break;
}
case GET_TYPE: {
result = resolver.getType(context, base, trigger);
break;
}
default: {
// Should never happen
Assert.fail("Missing case for method");
}
}
if (checkResult) {
Assert.assertNull(result);
}
Assert.assertFalse(context.isPropertyResolved());
}
private enum MethodUnderTest {
GET_VALUE, SET_VALUE, GET_TYPE
}
}

View File

@@ -0,0 +1,489 @@
/*
* 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 javax.el;
import org.junit.Assert;
import org.junit.Test;
public class TestStaticFieldELResolver {
private static final String PROPERTY01_NAME = "publicStaticString";
private static final String PROPERTY01_VALUE = "publicStaticStringNewValue";
private static final String PROPERTY02_NAME = "nonExistingString";
private static final String PROPERTY03_NAME = "publicString";
private static final String PROPERTY04_NAME = "privateStaticString";
private static final String PROPERTY05_NAME = "privateString";
private static final String METHOD01_NAME = "<init>";
private static final String METHOD02_NAME = "getPublicStaticString";
private static final String METHOD03_NAME = "setPrivateString";
private static final String METHOD04_NAME = "printPublicStaticString";
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testGetValue01() {
StaticFieldELResolver resolver = new StaticFieldELResolver();
resolver.getValue(null, new Object(), new Object());
}
/**
* Tests that a valid property is resolved.
*/
@Test
public void testGetValue02() {
StaticFieldELResolver resolver = new StaticFieldELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
Object result = resolver.getValue(context, new ELClass(
TesterClass.class), PROPERTY01_NAME);
Assert.assertEquals(PROPERTY01_NAME, result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that a valid property is not resolved if base is not ELCLass.
*/
@Test
public void testGetValue03() {
doNegativeTest(new Object(), PROPERTY01_NAME, MethodUnderTest.GET_VALUE);
}
/**
* Tests that non String property is not resolved.
*/
@Test
public void testGetValue04() {
doNegativeTest(new ELClass(TesterClass.class), new Object(),
MethodUnderTest.GET_VALUE);
}
/**
* Property doesn't exist
*/
@Test
public void testGetValue05() {
doThrowableTest(PROPERTY02_NAME, MethodUnderTest.GET_VALUE, true);
}
/**
* Property is not static
*/
@Test
public void testGetValue06() {
doThrowableTest(PROPERTY03_NAME, MethodUnderTest.GET_VALUE, false);
}
/**
* Property is not public
*/
@Test
public void testGetValue07() {
doThrowableTest(PROPERTY04_NAME, MethodUnderTest.GET_VALUE, true);
}
/**
* Property is neither public nor static
*/
@Test
public void testGetValue08() {
doThrowableTest(PROPERTY05_NAME, MethodUnderTest.GET_VALUE, true);
}
/**
* Tests that a valid property of Enum is resolved.
*/
@Test
public void testGetValue09() {
StaticFieldELResolver resolver = new StaticFieldELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
Object result = resolver.getValue(context, new ELClass(
MethodUnderTest.class), MethodUnderTest.GET_TYPE.toString());
Assert.assertEquals(MethodUnderTest.GET_TYPE, result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testSetValue01() {
StaticFieldELResolver resolver = new StaticFieldELResolver();
resolver.setValue(null, new Object(), new Object(), new Object());
}
/**
* Tests that cannot write to a static field.
*/
@Test(expected = PropertyNotWritableException.class)
public void testSetValue02() {
StaticFieldELResolver resolver = new StaticFieldELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
resolver.setValue(context, new ELClass(TesterClass.class),
PROPERTY01_NAME, PROPERTY01_VALUE);
}
/**
* Tests that the operation is not invoked if base is not ELCLass.
*/
@Test
public void testSetValue03() {
doNegativeTest(new Object(), PROPERTY01_NAME, MethodUnderTest.SET_VALUE);
}
/**
* Tests that the operation is no invoked when the property is not String.
*/
@Test
public void testSetValue04() {
doNegativeTest(new ELClass(TesterClass.class), new Object(),
MethodUnderTest.SET_VALUE);
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testIsReadOnly01() {
StaticFieldELResolver resolver = new StaticFieldELResolver();
resolver.isReadOnly(null, new Object(), new Object());
}
/**
* Tests that the propertyResolved is true when base is ELCLass and the
* property is String.
*/
@Test
public void testIsReadOnly02() {
StaticFieldELResolver resolver = new StaticFieldELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
boolean result = resolver.isReadOnly(context, new ELClass(
TesterClass.class), PROPERTY01_NAME);
Assert.assertTrue(result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that the propertyResolved is false if base is not ELCLass.
*/
@Test
public void testIsReadOnly03() {
StaticFieldELResolver resolver = new StaticFieldELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
boolean result = resolver.isReadOnly(context, new Object(),
PROPERTY01_NAME);
Assert.assertTrue(result);
Assert.assertFalse(context.isPropertyResolved());
}
/**
* Tests that the propertyResolved is false when the property is not String.
*/
@Test
public void testIsReadOnly04() {
StaticFieldELResolver resolver = new StaticFieldELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
boolean result = resolver.isReadOnly(context, new ELClass(
TesterClass.class), new Object());
Assert.assertTrue(result);
Assert.assertFalse(context.isPropertyResolved());
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testGetType01() {
StaticFieldELResolver resolver = new StaticFieldELResolver();
resolver.getType(null, new Object(), new Object());
}
/**
* Tests that a valid property is resolved.
*/
@Test
public void testGetType02() {
StaticFieldELResolver resolver = new StaticFieldELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
Class<?> result = resolver.getType(context, new ELClass(
TesterClass.class), PROPERTY01_NAME);
Assert.assertEquals(PROPERTY01_NAME.getClass(), result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that a valid property is not resolved if base is not ELCLass.
*/
@Test
public void testGetType03() {
doNegativeTest(new Object(), PROPERTY01_NAME, MethodUnderTest.GET_TYPE);
}
/**
* Tests that non String property is not resolved.
*/
@Test
public void testGetType04() {
doNegativeTest(new ELClass(TesterClass.class), new Object(),
MethodUnderTest.GET_TYPE);
}
/**
* Property doesn't exist
*/
@Test
public void testGetType05() {
doThrowableTest(PROPERTY02_NAME, MethodUnderTest.GET_TYPE, true);
}
/**
* Property is not static
*/
@Test
public void testGetType06() {
doThrowableTest(PROPERTY03_NAME, MethodUnderTest.GET_TYPE, false);
}
/**
* Property is not public
*/
@Test
public void testGetType07() {
doThrowableTest(PROPERTY04_NAME, MethodUnderTest.GET_TYPE, true);
}
/**
* Property is neither public nor static
*/
@Test
public void testGetType08() {
doThrowableTest(PROPERTY05_NAME, MethodUnderTest.GET_TYPE, true);
}
/**
* Tests that a valid property of Enum is resolved.
*/
@Test
public void testGetType09() {
StaticFieldELResolver resolver = new StaticFieldELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
Class<?> result = resolver.getType(context, new ELClass(
MethodUnderTest.class), MethodUnderTest.GET_TYPE.toString());
Assert.assertEquals(MethodUnderTest.GET_TYPE.getClass(), result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that a null context results in an NPE as per EL Javadoc.
*/
@Test(expected = NullPointerException.class)
public void testInvoke01() {
StaticFieldELResolver resolver = new StaticFieldELResolver();
resolver.invoke(null, new Object(), new Object(), new Class<?>[] {},
new Object[] {});
}
/**
* Tests a constructor invocation.
*/
@Test
public void testInvoke02() {
StaticFieldELResolver resolver = new StaticFieldELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
Object result = resolver.invoke(context,
new ELClass(TesterClass.class), METHOD01_NAME, null, null);
Assert.assertEquals(TesterClass.class, result.getClass());
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests a method invocation.
*/
@Test
public void testInvoke03() {
StaticFieldELResolver resolver = new StaticFieldELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
Object result = resolver.invoke(context,
new ELClass(TesterClass.class), METHOD02_NAME,
new Class<?>[] {}, new Object[] {});
Assert.assertEquals(PROPERTY01_NAME, result);
Assert.assertTrue(context.isPropertyResolved());
}
/**
* Tests that a valid method is not resolved if base is not ELCLass.
*/
@Test
public void testInvoke04() {
doNegativeTest(new Object(), METHOD02_NAME, MethodUnderTest.INVOKE);
}
/**
* Tests that non String method name is not resolved.
*/
@Test
public void testInvoke05() {
doNegativeTest(new ELClass(TesterClass.class), new Object(),
MethodUnderTest.INVOKE);
}
/**
* Tests that a private constructor invocation will fail.
*/
@Test
public void testInvoke06() {
doThrowableTest(METHOD01_NAME, MethodUnderTest.INVOKE, false);
}
/**
* Tests that a non static method invocation will fail.
*/
@Test
public void testInvoke07() {
doThrowableTest(METHOD03_NAME, MethodUnderTest.INVOKE, false);
}
/**
* Tests a void method invocation.
*/
@Test
public void testInvoke08() {
StaticFieldELResolver resolver = new StaticFieldELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
Object result = resolver.invoke(context,
new ELClass(TesterClass.class), METHOD04_NAME,
new Class<?>[] {}, new Object[] {});
Assert.assertNull(result);
Assert.assertTrue(context.isPropertyResolved());
}
private void doNegativeTest(Object elClass, Object trigger,
MethodUnderTest method) {
StaticFieldELResolver resolver = new StaticFieldELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
Object result = null;
switch (method) {
case GET_VALUE: {
result = resolver.getValue(context, elClass, trigger);
break;
}
case SET_VALUE: {
resolver.setValue(context, elClass, trigger, PROPERTY01_VALUE);
result = resolver.getValue(context, elClass, trigger);
break;
}
case GET_TYPE: {
result = resolver.getType(context, elClass, trigger);
break;
}
case INVOKE: {
result = resolver.invoke(context, elClass, trigger,
new Class<?>[] { String.class }, new Object[] { "test" });
break;
}
default: {
// Should never happen
Assert.fail("Missing case for method");
}
}
Assert.assertNull(result);
Assert.assertFalse(context.isPropertyResolved());
}
private void doThrowableTest(String trigger, MethodUnderTest method,
boolean checkCause) {
StaticFieldELResolver resolver = new StaticFieldELResolver();
ELContext context = new StandardELContext(
ELManager.getExpressionFactory());
ELException exception = null;
try {
switch (method) {
case GET_VALUE: {
resolver.getValue(context, new ELClass(TesterClass.class),
trigger);
break;
}
case GET_TYPE: {
resolver.getType(context, new ELClass(TesterClass.class),
trigger);
break;
}
case INVOKE: {
resolver.invoke(context, new ELClass(TesterClass.class),
trigger, new Class<?>[] { String.class },
new Object[] { "test" });
break;
}
default: {
// Should never happen
Assert.fail("Missing case for method");
}
}
} catch (PropertyNotFoundException | MethodNotFoundException e) {
exception = e;
}
Assert.assertTrue(context.isPropertyResolved());
Assert.assertNotNull(exception);
if (checkCause) {
// Can't be null due to assertion above
Throwable cause = exception.getCause();
Assert.assertNotNull(cause);
}
}
private enum MethodUnderTest {
GET_VALUE, SET_VALUE, GET_TYPE, INVOKE
}
}

View File

@@ -0,0 +1,56 @@
/*
* 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 javax.el;
import java.util.Date;
import org.junit.Assert;
import org.junit.Test;
public class TestUtil {
@Test
public void test01() {
ELProcessor processor = new ELProcessor();
processor.defineBean("sb", new StringBuilder());
Assert.assertEquals("a", processor.eval("sb.append('a'); sb.toString()"));
}
@Test
public void test02() {
ELProcessor processor = new ELProcessor();
processor.getELManager().importClass("java.util.Date");
Date result = (Date) processor.eval("Date(86400)");
Assert.assertEquals(86400, result.getTime());
}
@Test
public void testBug56425a() {
ELProcessor processor = new ELProcessor();
processor.defineBean("string", "a-b-c-d");
Assert.assertEquals("a_b_c_d", processor.eval("string.replace(\"-\",\"_\")"));
}
@Test
public void testBug56425b() {
ELProcessor processor = new ELProcessor();
processor.defineBean("string", "Not used. Any value is fine here");
Assert.assertEquals("5", processor.eval("string.valueOf(5)"));
}
}

View File

@@ -0,0 +1,65 @@
/*
* 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 javax.el;
public class TesterBean {
private String name;
private Integer[] valueC;
public TesterBean(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getNameVarargs(@SuppressWarnings("unused") Integer... someNumbers) {
return name;
}
public String getNameVarargs(@SuppressWarnings("unused") Boolean someBoolean,
@SuppressWarnings("unused") Integer... someNumbers) {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return getName();
}
public String getValueA() throws Exception {
throw new Exception();
}
public int[] getValueB() {
return new int[] {1,2,3,4,5};
}
public void setValueC(Integer[] values) {
valueC = values;
}
public Integer[] getValueC() {
return valueC;
}
}

View File

@@ -0,0 +1,83 @@
/*
* 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 javax.el;
import java.util.HashMap;
import java.util.Map;
public class TesterBeanNameResolver extends BeanNameResolver {
public static final String EXCEPTION_TRIGGER_NAME = "exception";
public static final String THROWABLE_TRIGGER_NAME = "throwable";
public static final String READ_ONLY_NAME = "readonly";
private Map<String,Object> beans = new HashMap<>();
private boolean allowCreate = true;
public TesterBeanNameResolver() {
beans.put(EXCEPTION_TRIGGER_NAME, new Object());
beans.put(THROWABLE_TRIGGER_NAME, new Object());
beans.put(READ_ONLY_NAME, new Object());
}
@Override
public void setBeanValue(String beanName, Object value)
throws PropertyNotWritableException {
checkTriggers(beanName);
if (allowCreate || beans.containsKey(beanName)) {
beans.put(beanName, value);
}
}
@Override
public boolean isNameResolved(String beanName) {
return beans.containsKey(beanName);
}
@Override
public Object getBean(String beanName) {
checkTriggers(beanName);
return beans.get(beanName);
}
@Override
public boolean canCreateBean(String beanName) {
checkTriggers(beanName);
return allowCreate;
}
public void setAllowCreate(boolean allowCreate) {
this.allowCreate = allowCreate;
}
@Override
public boolean isReadOnly(String beanName) {
checkTriggers(beanName);
return READ_ONLY_NAME.equals(beanName);
}
private void checkTriggers(String beanName) {
if (EXCEPTION_TRIGGER_NAME.equals(beanName)) {
throw new RuntimeException();
}
if (THROWABLE_TRIGGER_NAME.equals(beanName)) {
throw new Error();
}
}
}

View File

@@ -0,0 +1,47 @@
/*
* 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 javax.el;
public class TesterClass {
public static final String publicStaticString = "publicStaticString";
public String publicString = "publicString";
@SuppressWarnings("unused") // Used in TestStaticFieldELResolver
private static String privateStaticString = "privateStaticString";
@SuppressWarnings("unused") // Used in TestStaticFieldELResolver
private String privateString = "privateString";
public TesterClass() {
}
@SuppressWarnings("unused") // Used in TestStaticFieldELResolver
private TesterClass(String privateString) {
this.privateString = privateString;
}
public static String getPublicStaticString() {
return publicStaticString;
}
public static void printPublicStaticString() {
System.out.println(publicStaticString);
}
public void setPrivateString(String privateString) {
this.privateString = privateString;
}
}

View File

@@ -0,0 +1,45 @@
/*
* 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 javax.el;
public class TesterELContext extends ELContext {
private final ELResolver resolver;
public TesterELContext() {
this(null);
}
public TesterELContext(ELResolver resolver) {
this.resolver = resolver;
}
@Override
public ELResolver getELResolver() {
return resolver;
}
@Override
public FunctionMapper getFunctionMapper() {
return null;
}
@Override
public VariableMapper getVariableMapper() {
return null;
}
}

View File

@@ -0,0 +1,29 @@
/*
* 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 javax.el;
public class TesterELResolverOne extends TypeConverter {
@Override
public Object convertToType(ELContext context, Object obj, Class<?> type) {
if ("1".equals(obj) && type == String.class) {
context.setPropertyResolved(obj, type);
return "ONE";
}
return null;
}
}

View File

@@ -0,0 +1,29 @@
/*
* 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 javax.el;
public class TesterELResolverTwo extends TypeConverter {
@Override
public Object convertToType(ELContext context, Object obj, Class<?> type) {
if ("2".equals(obj) && type == String.class) {
context.setPropertyResolved(obj, type);
return "TWO";
}
return null;
}
}

View File

@@ -0,0 +1,80 @@
/*
* 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 javax.el;
import java.util.ArrayList;
import java.util.List;
public class TesterEvaluationListener extends EvaluationListener {
private final List<Pair> resolvedProperties = new ArrayList<>();
private final List<String> beforeEvaluationExpressions = new ArrayList<>();
private final List<String> afterEvaluationExpressions = new ArrayList<>();
@Override
public void propertyResolved(ELContext context, Object base,
Object property) {
resolvedProperties.add(new Pair(base, property));
}
@Override
public void beforeEvaluation(ELContext context, String expression) {
beforeEvaluationExpressions.add(expression);
}
@Override
public void afterEvaluation(ELContext context, String expression) {
afterEvaluationExpressions.add(expression);
}
public List<Pair> getResolvedProperties() {
return resolvedProperties;
}
public List<String> getBeforeEvaluationExpressions() {
return beforeEvaluationExpressions;
}
public List<String> getAfterEvaluationExpressions() {
return afterEvaluationExpressions;
}
public static class Pair {
private final Object base;
private final Object property;
public Pair(Object base, Object property) {
this.base = base;
this.property = property;
}
public Object getBase() {
return base;
}
public Object getProperty() {
return property;
}
}
}

View File

@@ -0,0 +1,66 @@
/*
* 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 javax.el;
public class TesterFunctions {
private static StringBuilder calls = new StringBuilder();
public static String getCallList() {
return calls.toString();
}
public static void resetCallList() {
calls = new StringBuilder();
}
public static void doIt() {
calls.append('A');
}
public static void doIt(@SuppressWarnings("unused") int a) {
calls.append('B');
}
public static void doIt(@SuppressWarnings("unused") Integer a) {
calls.append('C');
}
public static void doIt(@SuppressWarnings("unused") int[] a) {
calls.append('D');
}
public static void doIt(@SuppressWarnings("unused") int[][] a) {
calls.append('E');
}
public static void doIt(@SuppressWarnings("unused") Integer[] a) {
calls.append('F');
}
public static void doIt(@SuppressWarnings("unused") Integer[][] a) {
calls.append('G');
}
public static void doIt(@SuppressWarnings("unused") long... a) {
calls.append('H');
}
public static void doIt(@SuppressWarnings("unused") Object... a) {
calls.append('I');
}
}

View File

@@ -0,0 +1,49 @@
/*
* 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 javax.el;
import org.junit.Test;
public class TesterImportHandlerPerformance {
/*
* This test is looking at the cost of looking up a class when the standard
* JSP package imports are present:
* - java.lang
* - javax.servlet
* - javax.servlet.http
* - javax.servlet.jsp
*
* Before optimisation, this test took ~4.6s on markt's desktop
* After optimisation, this test took ~0.05s on markt's desktop
*/
@Test
public void testBug62453() throws Exception {
long totalTime = 0;
for (int i = 0; i < 100000; i++) {
ImportHandler ih = new ImportHandler();
ih.importPackage("javax.servlet");
ih.importPackage("javax.servlet.http");
ih.importPackage("javax.servlet.jsp");
long start = System.nanoTime();
ih.resolveClass("unknown");
long end = System.nanoTime();
totalTime += (end -start);
}
System.out.println("Time taken: " + totalTime + "ns");
}
}

View File

@@ -0,0 +1,108 @@
/*
* 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 javax.servlet.annotation;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Assert;
import org.junit.Test;
import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.tomcat.util.buf.ByteChunk;
public class TestServletSecurity extends TomcatBaseTest {
@Test
public void testFooThenFooBar() throws Exception {
doTestFooAndFooBar(true);
}
@Test
public void testFooBarThenFoo() throws Exception {
doTestFooAndFooBar(false);
}
public void doTestFooAndFooBar(boolean fooFirst) throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
Tomcat.addServlet(ctx, "Foo", Foo.class.getName());
ctx.addServletMappingDecoded("/foo/*", "Foo");
Tomcat.addServlet(ctx, "FooBar", FooBar.class.getName());
ctx.addServletMappingDecoded("/foo/bar/*", "FooBar");
tomcat.start();
ByteChunk bc = new ByteChunk();
int rc;
if (fooFirst) {
rc = getUrl("http://localhost:" + getPort() + "/foo", bc, null, null);
} else {
rc = getUrl("http://localhost:" + getPort() + "/foo/bar", bc, null, null);
}
bc.recycle();
Assert.assertEquals(403, rc);
if (fooFirst) {
rc = getUrl("http://localhost:" + getPort() + "/foo/bar", bc, null, null);
} else {
rc = getUrl("http://localhost:" + getPort() + "/foo", bc, null, null);
}
Assert.assertEquals(403, rc);
}
@ServletSecurity(@HttpConstraint(ServletSecurity.EmptyRoleSemantic.DENY))
public static class Foo extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().print("OK: Foo");
}
}
public static class FooBar extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().print("OK: FooBar");
}
}
}

View File

@@ -0,0 +1,247 @@
/*
* 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 javax.servlet.annotation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.tomcat.util.buf.ByteChunk;
@RunWith(Parameterized.class)
public class TestServletSecurityMappings extends TomcatBaseTest {
@Parameters(name="{0}, {1}, {2}, {3}")
public static Collection<Object[]> inputs() {
List<Object[]> result = new ArrayList<>();
result.add(new Object[] { Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE });
result.add(new Object[] { Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE });
result.add(new Object[] { Boolean.FALSE, Boolean.FALSE, Boolean.TRUE , Boolean.FALSE });
result.add(new Object[] { Boolean.FALSE, Boolean.FALSE, Boolean.TRUE, Boolean.TRUE });
result.add(new Object[] { Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, Boolean.FALSE });
result.add(new Object[] { Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, Boolean.TRUE });
result.add(new Object[] { Boolean.FALSE, Boolean.TRUE, Boolean.TRUE , Boolean.FALSE });
result.add(new Object[] { Boolean.FALSE, Boolean.TRUE, Boolean.TRUE, Boolean.TRUE });
result.add(new Object[] { Boolean.TRUE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE });
result.add(new Object[] { Boolean.TRUE, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE });
result.add(new Object[] { Boolean.TRUE, Boolean.FALSE, Boolean.TRUE , Boolean.FALSE });
result.add(new Object[] { Boolean.TRUE, Boolean.FALSE, Boolean.TRUE, Boolean.TRUE });
result.add(new Object[] { Boolean.TRUE, Boolean.TRUE, Boolean.FALSE, Boolean.FALSE });
result.add(new Object[] { Boolean.TRUE, Boolean.TRUE, Boolean.FALSE, Boolean.TRUE });
result.add(new Object[] { Boolean.TRUE, Boolean.TRUE, Boolean.TRUE , Boolean.FALSE });
result.add(new Object[] { Boolean.TRUE, Boolean.TRUE, Boolean.TRUE, Boolean.TRUE });
return result;
}
@Parameter(0)
public boolean redirectContextRoot;
@Parameter(1)
public boolean secureRoot;
@Parameter(2)
public boolean secureDefault;
@Parameter(3)
public boolean secureFoo;
@Test
public void doTestSecurityAnnotationsAddServlet() throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("/test", null);
ctx.setMapperContextRootRedirectEnabled(redirectContextRoot);
ServletContainerInitializer sci = new SCI(secureRoot, secureDefault, secureFoo);
ctx.addServletContainerInitializer(sci, null);
tomcat.start();
ByteChunk bc = new ByteChunk();
int rc;
// Foo
rc = getUrl("http://localhost:" + getPort() + "/test/foo", bc, false);
if (secureFoo || secureDefault) {
Assert.assertEquals(403, rc);
} else {
Assert.assertEquals(200, rc);
}
bc.recycle();
// Default
rc = getUrl("http://localhost:" + getPort() + "/test/something", bc, false);
if (secureDefault) {
Assert.assertEquals(403, rc);
} else {
Assert.assertEquals(200, rc);
}
bc.recycle();
// Root
rc = getUrl("http://localhost:" + getPort() + "/test", bc, false);
if (redirectContextRoot) {
Assert.assertEquals(302, rc);
} else {
if (secureRoot || secureDefault) {
Assert.assertEquals(403, rc);
} else {
Assert.assertEquals(200, rc);
}
}
}
public static class SCI implements ServletContainerInitializer {
private final boolean secureRoot;
private final boolean secureDefault;
private final boolean secureFoo;
public SCI(boolean secureRoot, boolean secureDefault, boolean secureFoo) {
this.secureRoot = secureRoot;
this.secureDefault = secureDefault;
this.secureFoo = secureFoo;
}
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx)
throws ServletException {
ServletRegistration.Dynamic sr;
if (secureRoot) {
sr = ctx.addServlet("Root", SecureRoot.class.getName());
} else {
sr =ctx.addServlet("Root", Root.class.getName());
}
sr.addMapping("");
if (secureDefault) {
sr = ctx.addServlet("Default", SecureDefault.class.getName());
} else {
sr = ctx.addServlet("Default", Default.class.getName());
}
sr.addMapping("/");
if (secureFoo) {
sr = ctx.addServlet("Foo", SecureFoo.class.getName());
} else {
sr = ctx.addServlet("Foo", Foo.class.getName());
}
sr.addMapping("/foo");
}
}
@ServletSecurity(@HttpConstraint(ServletSecurity.EmptyRoleSemantic.DENY))
public static class SecureRoot extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().print("OK");
}
}
public static class Root extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().print("OK");
}
}
@ServletSecurity(@HttpConstraint(ServletSecurity.EmptyRoleSemantic.DENY))
public static class SecureDefault extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().print("OK");
}
}
public static class Default extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().print("OK");
}
}
@ServletSecurity(@HttpConstraint(ServletSecurity.EmptyRoleSemantic.DENY))
public static class SecureFoo extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().print("OK");
}
}
public static class Foo extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().print("OK");
}
}
}

View File

@@ -0,0 +1,153 @@
/*
* 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 javax.servlet.http;
import java.util.BitSet;
import org.junit.Assert;
import org.junit.Test;
/**
* Basic tests for Cookie in default configuration.
*/
public class TestCookie {
public static final BitSet CHAR; // <any US-ASCII character (octets 0 - 127)>
public static final BitSet CTL; // <any US-ASCII control character (octets 0 - 31) and DEL (127)>
public static final BitSet SEPARATORS;
public static final BitSet TOKEN; // 1*<any CHAR except CTLs or separators>
static {
CHAR = new BitSet(256);
CHAR.set(0, 128);
CTL = new BitSet(256);
CTL.set(0, 32);
CTL.set(127);
SEPARATORS = new BitSet(256);
for (char ch : "()<>@,;:\\\"/[]?={} \t".toCharArray()) {
SEPARATORS.set(ch);
}
TOKEN = new BitSet(256);
TOKEN.or(CHAR); // any CHAR
TOKEN.andNot(CTL); // except CTLs
TOKEN.andNot(SEPARATORS); // or separators
}
@Test
public void testDefaults() {
Cookie cookie = new Cookie("foo", null);
Assert.assertEquals("foo", cookie.getName());
Assert.assertNull(cookie.getValue());
Assert.assertEquals(0, cookie.getVersion());
Assert.assertEquals(-1, cookie.getMaxAge());
}
@Test
public void testInitialValue() {
Cookie cookie = new Cookie("foo", "bar");
Assert.assertEquals("foo", cookie.getName());
Assert.assertEquals("bar", cookie.getValue());
Assert.assertEquals(0, cookie.getVersion());
}
@Test
public void defaultImpliesNetscape() {
// $Foo is allowed by Netscape but not by RFC2109
Cookie cookie = new Cookie("$Foo", null);
Assert.assertEquals("$Foo", cookie.getName());
}
@Test
public void tokenVersion() {
Cookie cookie = new Cookie("Version", null);
Assert.assertEquals("Version", cookie.getName());
}
@Test
public void attributeVersion() {
Cookie cookie = new Cookie("Comment", null);
Assert.assertEquals("Comment", cookie.getName());
}
@Test
public void attributeDiscard() {
Cookie cookie = new Cookie("Discard", null);
Assert.assertEquals("Discard", cookie.getName());
}
@Test
public void attributeExpires() {
Cookie cookie = new Cookie("Expires", null);
Assert.assertEquals("Expires", cookie.getName());
}
@Test
public void attributeMaxAge() {
Cookie cookie = new Cookie("Max-Age", null);
Assert.assertEquals("Max-Age", cookie.getName());
}
@Test
public void attributeDomain() {
Cookie cookie = new Cookie("Domain", null);
Assert.assertEquals("Domain", cookie.getName());
}
@Test
public void attributePath() {
Cookie cookie = new Cookie("Path", null);
Assert.assertEquals("Path", cookie.getName());
}
@Test
public void attributeSecure() {
Cookie cookie = new Cookie("Secure", null);
Assert.assertEquals("Secure", cookie.getName());
}
@Test
public void attributeHttpOnly() {
Cookie cookie = new Cookie("HttpOnly", null);
Assert.assertEquals("HttpOnly", cookie.getName());
}
@Test
public void strictNamingImpliesRFC2109() {
// Needs to be something RFC6265 allows, but strict naming does not.
@SuppressWarnings("unused")
Cookie cookie = new Cookie("$Foo", null);
}
public static void checkCharInName(CookieNameValidator validator, BitSet allowed) {
for (char ch = 0; ch < allowed.size(); ch++) {
boolean expected = allowed.get(ch);
String name = "X" + ch + "X";
try {
validator.validate(name);
if (!expected) {
Assert.fail(String.format("Char %d should not be allowed", Integer.valueOf(ch)));
}
} catch (IllegalArgumentException e) {
if (expected) {
Assert.fail(String.format("Char %d should be allowed", Integer.valueOf(ch)));
}
}
}
}
}

View File

@@ -0,0 +1,40 @@
/*
* 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 javax.servlet.http;
import org.junit.Test;
/**
* Basic tests for Cookie in default configuration.
*/
public class TestCookieRFC2109Validator {
static {
System.setProperty("org.apache.tomcat.util.http.ServerCookie.FWD_SLASH_IS_SEPARATOR", "true");
}
private RFC2109Validator validator = new RFC2109Validator();
@Test
public void actualCharactersAllowedInName() {
TestCookie.checkCharInName(validator, TestCookie.TOKEN);
}
@Test(expected = IllegalArgumentException.class)
public void leadingDollar() {
validator.validate("$Version");
}
}

View File

@@ -0,0 +1,40 @@
/*
* 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 javax.servlet.http;
import org.junit.Test;
/**
* Basic tests for Cookie in default configuration.
*/
public class TestCookieRFC6265Validator {
static {
System.setProperty("org.apache.tomcat.util.http.ServerCookie.FWD_SLASH_IS_SEPARATOR", "true");
}
private RFC6265Validator validator = new RFC6265Validator();
@Test
public void actualCharactersAllowedInName() {
TestCookie.checkCharInName(validator, TestCookie.TOKEN);
}
@Test
public void leadingDollar() {
validator.validate("$Version");
}
}

View File

@@ -0,0 +1,44 @@
/*
* 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 javax.servlet.http;
import org.junit.Assert;
import org.junit.Test;
/**
* Basic tests for Cookie in STRICT_SERVLET_COMPLIANCE configuration.
*/
public class TestCookieStrict {
static {
System.setProperty("org.apache.tomcat.util.http.ServerCookie.STRICT_NAMING", "true");
}
@Test
public void testDefaults() {
Cookie cookie = new Cookie("strict", null);
Assert.assertEquals("strict", cookie.getName());
Assert.assertNull(cookie.getValue());
Assert.assertEquals(0, cookie.getVersion());
Assert.assertEquals(-1, cookie.getMaxAge());
}
@Test(expected = IllegalArgumentException.class)
public void strictNamingImpliesRFC2109() {
@SuppressWarnings("unused")
Cookie cookie = new Cookie("@Foo", null);
}
}

View File

@@ -0,0 +1,207 @@
/*
* 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 javax.servlet.http;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import org.junit.Assert;
import org.junit.Test;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.collections.CaseInsensitiveKeyMap;
public class TestHttpServlet extends TomcatBaseTest {
@Test
public void testBug53454() throws Exception {
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
StandardContext ctx = (StandardContext) tomcat.addContext("", null);
// Map the test Servlet
LargeBodyServlet largeBodyServlet = new LargeBodyServlet();
Tomcat.addServlet(ctx, "largeBodyServlet", largeBodyServlet);
ctx.addServletMappingDecoded("/", "largeBodyServlet");
tomcat.start();
Map<String,List<String>> resHeaders= new HashMap<>();
int rc = headUrl("http://localhost:" + getPort() + "/", new ByteChunk(),
resHeaders);
Assert.assertEquals(HttpServletResponse.SC_OK, rc);
Assert.assertEquals(LargeBodyServlet.RESPONSE_LENGTH,
resHeaders.get("Content-Length").get(0));
}
private static class LargeBodyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String RESPONSE_LENGTH = "12345678901";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setHeader("content-length", RESPONSE_LENGTH);
}
}
/*
* Verifies that the same Content-Length is returned for both GET and HEAD
* operations when a Servlet includes content from another Servlet
*/
@Test
public void testBug57602() throws Exception {
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
StandardContext ctx = (StandardContext) tomcat.addContext("", null);
Bug57602ServletOuter outer = new Bug57602ServletOuter();
Tomcat.addServlet(ctx, "Bug57602ServletOuter", outer);
ctx.addServletMappingDecoded("/outer", "Bug57602ServletOuter");
Bug57602ServletInner inner = new Bug57602ServletInner();
Tomcat.addServlet(ctx, "Bug57602ServletInner", inner);
ctx.addServletMappingDecoded("/inner", "Bug57602ServletInner");
tomcat.start();
Map<String,List<String>> resHeaders= new CaseInsensitiveKeyMap<>();
String path = "http://localhost:" + getPort() + "/outer";
ByteChunk out = new ByteChunk();
int rc = getUrl(path, out, resHeaders);
Assert.assertEquals(HttpServletResponse.SC_OK, rc);
String length = getSingleHeader("Content-Length", resHeaders);
Assert.assertEquals(Long.parseLong(length), out.getLength());
out.recycle();
rc = headUrl(path, out, resHeaders);
Assert.assertEquals(HttpServletResponse.SC_OK, rc);
Assert.assertEquals(0, out.getLength());
Assert.assertEquals(length, resHeaders.get("Content-Length").get(0));
tomcat.stop();
}
@Test
public void testChunkingWithHead() throws Exception {
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
StandardContext ctx = (StandardContext) tomcat.addContext("", null);
ChunkingServlet s = new ChunkingServlet();
Tomcat.addServlet(ctx, "ChunkingServlet", s);
ctx.addServletMappingDecoded("/chunking", "ChunkingServlet");
tomcat.start();
Map<String,List<String>> getHeaders = new CaseInsensitiveKeyMap<>();
String path = "http://localhost:" + getPort() + "/chunking";
ByteChunk out = new ByteChunk();
int rc = getUrl(path, out, getHeaders);
Assert.assertEquals(HttpServletResponse.SC_OK, rc);
out.recycle();
Map<String,List<String>> headHeaders = new HashMap<>();
rc = headUrl(path, out, headHeaders);
Assert.assertEquals(HttpServletResponse.SC_OK, rc);
// Headers should be the same (apart from Date)
Assert.assertEquals(getHeaders.size(), headHeaders.size());
for (Map.Entry<String, List<String>> getHeader : getHeaders.entrySet()) {
String headerName = getHeader.getKey();
if ("date".equalsIgnoreCase(headerName)) {
continue;
}
Assert.assertTrue(headerName, headHeaders.containsKey(headerName));
List<String> getValues = getHeader.getValue();
List<String> headValues = headHeaders.get(headerName);
Assert.assertEquals(getValues.size(), headValues.size());
for (String value : getValues) {
Assert.assertTrue(headValues.contains(value));
}
}
tomcat.stop();
}
private static class Bug57602ServletOuter extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/plain");
resp.setCharacterEncoding("UTF-8");
PrintWriter pw = resp.getWriter();
pw.println("Header");
req.getRequestDispatcher("/inner").include(req, resp);
pw.println("Footer");
}
}
private static class Bug57602ServletInner extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/plain");
resp.setCharacterEncoding("UTF-8");
PrintWriter pw = resp.getWriter();
pw.println("Included");
}
}
private static class ChunkingServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/plain");
resp.setCharacterEncoding("UTF-8");
PrintWriter pw = resp.getWriter();
// Trigger chunking
pw.write(new char[8192 * 16]);
pw.println("Data");
}
}
}

View File

@@ -0,0 +1,366 @@
/*
* 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 javax.servlet.http;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.apache.catalina.Context;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.descriptor.web.ErrorPage;
/**
* These tests evolved out of a discussion in the Jakarta Servlet project
* regarding the intended behaviour in various error scenarios. Async requests
* and/or async error pages added additional complexity.
*/
@RunWith(Parameterized.class)
public class TestHttpServletResponseSendError extends TomcatBaseTest {
/*
* Implementation notes:
* Original Request
* - async
* - error in original thread / new thread
* - error before / after startAsync
* - error before / after complete / dispatch
* Error page
* - sync
* - async
* - complete
* - dispatch
*/
private enum AsyncErrorPoint {
/*
* Thread A is the container thread the processes the original request.
* Thread B is the async thread (may or may not be a container thread)
* that is started by the async processing.
*/
THREAD_A_BEFORE_START_ASYNC,
THREAD_A_AFTER_START_ASYNC,
THREAD_A_AFTER_START_RUNNABLE,
THREAD_B_BEFORE_COMPLETE
/*
* If the error is triggered after Thread B completes async processing
* there is essentially a race condition between thread B making the
* change and the container checking to see if the error flag has been
* set. We can't easily control the execution order here so we don't
* test it.
*/
}
@Parameterized.Parameters(name = "{index}: async[{0}], throw[{1}], dispatch[{2}], errorPoint[{3}], useStart[{4}]")
public static Collection<Object[]> parameters() {
List<Object[]> parameterSets = new ArrayList<>();
for (Boolean async : booleans) {
for (Boolean throwException : booleans) {
if (async.booleanValue()) {
for (Boolean useDispatch : booleans) {
for (AsyncErrorPoint errorPoint : AsyncErrorPoint.values()) {
for (Boolean useStart : booleans) {
if (throwException.booleanValue() && !useStart.booleanValue() &&
errorPoint == AsyncErrorPoint.THREAD_B_BEFORE_COMPLETE) {
// Skip this combination as exceptions that occur on application
// managed threads are not visible to the container.
continue;
}
parameterSets.add(new Object[] { async, throwException, useDispatch,
errorPoint, useStart} );
}
}
}
} else {
// Ignore the async specific parameters
parameterSets.add(new Object[] { async, throwException, Boolean.FALSE,
AsyncErrorPoint.THREAD_A_AFTER_START_ASYNC, Boolean.FALSE} );
}
}
}
return parameterSets;
}
@Parameter(0)
public boolean async;
@Parameter(1)
public boolean throwException;
@Parameter(2)
public boolean useDispatch;
@Parameter(3)
public AsyncErrorPoint errorPoint;
@Parameter(4)
public boolean useStart;
@Test
public void testSendError() throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
if (async) {
Wrapper w = Tomcat.addServlet(ctx, "target",
new TesterAsyncServlet(throwException, useDispatch, errorPoint, useStart));
w.setAsyncSupported(true);
} else {
Tomcat.addServlet(ctx, "target", new TesterServlet(throwException));
}
ctx.addServletMappingDecoded("/target", "target");
Tomcat.addServlet(ctx, "dispatch", new TesterDispatchServlet());
ctx.addServletMappingDecoded("/dispatch", "dispatch");
Tomcat.addServlet(ctx, "error599", new ErrorServletStatic599());
ctx.addServletMappingDecoded("/error599", "error599");
Tomcat.addServlet(ctx, "errorException", new ErrorServletStaticException());
ctx.addServletMappingDecoded("/errorException", "errorException");
ErrorPage ep1 = new ErrorPage();
ep1.setErrorCode(599);
ep1.setLocation("/error599");
ctx.addErrorPage(ep1);
ErrorPage ep2 = new ErrorPage();
ep2.setExceptionType(SendErrorException.class.getName());
ep2.setLocation("/errorException");
ctx.addErrorPage(ep2);
tomcat.start();
ByteChunk bc = new ByteChunk();
int rc;
rc = getUrl("http://localhost:" + getPort() + "/target", bc, null, null);
String body = bc.toString();
if (throwException) {
Assert.assertEquals(500, rc);
Assert.assertEquals("FAIL-Exception", body);
} else {
Assert.assertEquals(599, rc);
Assert.assertEquals("FAIL-599", body);
}
}
public static class TesterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final boolean throwException;
public TesterServlet(boolean throwException) {
this.throwException = throwException;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (throwException) {
throw new SendErrorException();
} else {
// Custom 5xx code so we can detect if the correct error is
// reported
resp.sendError(599);
}
}
}
public static class TesterAsyncServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final boolean throwException;
private final boolean useDispatch;
private final AsyncErrorPoint errorPoint;
private final boolean useStart;
public TesterAsyncServlet(boolean throwException, boolean useDispatch, AsyncErrorPoint errorPoint,
boolean useStart) {
this.throwException = throwException;
this.useDispatch = useDispatch;
this.errorPoint = errorPoint;
this.useStart = useStart;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (errorPoint == AsyncErrorPoint.THREAD_A_BEFORE_START_ASYNC) {
doError(resp);
}
AsyncContext ac = req.startAsync();
ac.setTimeout(2000);
if (errorPoint == AsyncErrorPoint.THREAD_A_AFTER_START_ASYNC) {
doError(resp);
}
AsyncRunnable r = new AsyncRunnable(ac, throwException, useDispatch, errorPoint);
if (useStart) {
ac.start(r);
} else {
Thread t = new Thread(r);
t.start();
}
if (errorPoint == AsyncErrorPoint.THREAD_A_AFTER_START_RUNNABLE) {
doError(resp);
}
}
private void doError(HttpServletResponse resp) throws IOException {
if (throwException) {
throw new SendErrorException();
} else {
resp.sendError(599);
}
}
}
public static class AsyncRunnable implements Runnable {
private final AsyncContext ac;
private final boolean throwException;
private final boolean useDispatch;
private final AsyncErrorPoint errorPoint;
public AsyncRunnable(AsyncContext ac, boolean throwException, boolean useDispatch,
AsyncErrorPoint errorPoint) {
this.ac = ac;
this.throwException = throwException;
this.useDispatch = useDispatch;
this.errorPoint = errorPoint;
}
@Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
/*
if (errorPoint == AsyncErrorPoint.THREAD_B_AFTER_COMPLETE) {
if (useDispatch) {
ac.complete();
} else {
ac.dispatch("/dispatch");
}
}
*/
if (throwException) {
throw new SendErrorException();
} else {
// Custom 5xx code so we can detect if the correct error is
// reported
try {
((HttpServletResponse) ac.getResponse()).sendError(599);
} catch (IOException e) {
e.printStackTrace();
}
}
if (errorPoint == AsyncErrorPoint.THREAD_B_BEFORE_COMPLETE) {
if (useDispatch) {
ac.dispatch("/dispatch");
} else {
ac.complete();
}
}
}
}
public static class TesterDispatchServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/plain");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().write("DISPATCH");
}
}
public static class SendErrorException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
public static class ErrorServletStatic599 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/plain");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().write("FAIL-599");
}
}
public static class ErrorServletStaticException extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/plain");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().write("FAIL-Exception");
}
}
}

View File

@@ -0,0 +1,37 @@
/*
* 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 javax.servlet.jsp;
import org.junit.Assert;
import org.junit.Test;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.tomcat.util.buf.ByteChunk;
public class TestPageContext extends TomcatBaseTest {
@Test
public void testBug49196() throws Exception {
getTomcatInstanceTestWebapp(false, true);
ByteChunk res = getUrl("http://localhost:" + getPort() +
"/test/bug49nnn/bug49196.jsp");
String result = res.toString();
Assert.assertTrue(result.contains("OK"));
}
}

View File

@@ -0,0 +1,195 @@
/*
* 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 javax.servlet.jsp;
import java.io.IOException;
import java.util.Enumeration;
import javax.el.ELContext;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpSession;
public class TesterPageContext extends PageContext {
@Override
public void initialize(Servlet servlet, ServletRequest request,
ServletResponse response, String errorPageURL,
boolean needsSession, int bufferSize, boolean autoFlush)
throws IOException, IllegalStateException, IllegalArgumentException {
// NO-OP
}
@Override
public void release() {
// NO-OP
}
@Override
public HttpSession getSession() {
// NO-OP
return null;
}
@Override
public Object getPage() {
// NO-OP
return null;
}
@Override
public ServletRequest getRequest() {
// NO-OP
return null;
}
@Override
public ServletResponse getResponse() {
// NO-OP
return null;
}
@Override
public Exception getException() {
// NO-OP
return null;
}
@Override
public ServletConfig getServletConfig() {
// NO-OP
return null;
}
@Override
public ServletContext getServletContext() {
// NO-OP
return null;
}
@Override
public void forward(String relativeUrlPath) throws ServletException,
IOException {
// NO-OP
}
@Override
public void include(String relativeUrlPath) throws ServletException,
IOException {
// NO-OP
}
@Override
public void include(String relativeUrlPath, boolean flush)
throws ServletException, IOException {
// NO-OP
}
@Override
public void handlePageException(Exception e) throws ServletException,
IOException {
// NO-OP
}
@Override
public void handlePageException(Throwable t) throws ServletException,
IOException {
// NO-OP
}
@Override
public void setAttribute(String name, Object value) {
// NO-OP
}
@Override
public void setAttribute(String name, Object value, int scope) {
// NO-OP
}
@Override
public Object getAttribute(String name) {
// NO-OP
return null;
}
@Override
public Object getAttribute(String name, int scope) {
// NO-OP
return null;
}
@Override
public Object findAttribute(String name) {
// NO-OP
return null;
}
@Override
public void removeAttribute(String name) {
// NO-OP
}
@Override
public void removeAttribute(String name, int scope) {
// NO-OP
}
@Override
public int getAttributesScope(String name) {
// NO-OP
return 0;
}
@Override
public Enumeration<String> getAttributeNamesInScope(int scope) {
// NO-OP
return null;
}
@Override
public JspWriter getOut() {
// NO-OP
return null;
}
@Override
@Deprecated
public javax.servlet.jsp.el.ExpressionEvaluator getExpressionEvaluator() {
// NO-OP
return null;
}
@Override
public ELContext getELContext() {
// NO-OP
return null;
}
@Override
@Deprecated
public javax.servlet.jsp.el.VariableResolver getVariableResolver() {
// NO-OP
return null;
}
}

View File

@@ -0,0 +1,39 @@
/*
* 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 javax.servlet.jsp.el;
import org.junit.Assert;
import org.junit.Test;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.tomcat.util.buf.ByteChunk;
public class TestScopedAttributeELResolver extends TomcatBaseTest {
@Test
public void testBug49196() throws Exception {
getTomcatInstanceTestWebapp(true, true);
ByteChunk res = getUrl("http://localhost:" + getPort() +
"/test/bug6nnnn/bug62453.jsp");
String result = res.toString();
Assert.assertTrue(result, result.contains("<div>foo: OK</div>"));
Assert.assertTrue(result, result.contains("<div>bar: </div>"));
Assert.assertTrue(result, result.contains("<div>baz: </div>"));
}
}

View File

@@ -0,0 +1,47 @@
/*
* 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 javax.servlet.jsp.el;
import javax.el.ELContext;
import javax.el.ELManager;
import javax.el.ELResolver;
import javax.el.StandardELContext;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.TesterPageContext;
import org.junit.Test;
public class TestScopedAttributeELResolverPerformance {
/*
* With the caching of NotFound responses this test takes ~20ms. Without the
* caching it takes ~6s.
*/
@Test
public void testGetValuePerformance() throws Exception {
ELContext context = new StandardELContext(ELManager.getExpressionFactory());
context.putContext(JspContext.class, new TesterPageContext());
ELResolver resolver = new ScopedAttributeELResolver();
for (int i = 0; i < 100000; i++) {
resolver.getValue(context, null, "unknown");
}
}
}

View File

@@ -0,0 +1,132 @@
/*
* 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 javax.servlet.resources;
import java.io.File;
import org.junit.Assert;
import org.junit.Test;
import org.apache.tomcat.util.descriptor.DigesterFactory;
import org.apache.tomcat.util.descriptor.XmlErrorHandler;
import org.apache.tomcat.util.descriptor.XmlIdentifiers;
import org.apache.tomcat.util.descriptor.web.WebRuleSet;
import org.apache.tomcat.util.descriptor.web.WebXml;
import org.apache.tomcat.util.digester.Digester;
public class TestSchemaValidation {
@Test
public void testWebapp() throws Exception {
XmlErrorHandler handler = new XmlErrorHandler();
Digester digester = DigesterFactory.newDigester(
true, true, new WebRuleSet(false), true);
digester.setErrorHandler(handler);
digester.push(new WebXml());
WebXml desc = (WebXml) digester.parse(
new File("test/webapp/WEB-INF/web.xml"));
Assert.assertEquals("3.1", desc.getVersion());
Assert.assertEquals(0, handler.getErrors().size());
Assert.assertEquals(0, handler.getWarnings().size());
}
@Test
public void testWebapp_2_2() throws Exception {
XmlErrorHandler handler = new XmlErrorHandler();
Digester digester = DigesterFactory.newDigester(
true, true, new WebRuleSet(false), true);
digester.setErrorHandler(handler);
digester.push(new WebXml());
WebXml desc = (WebXml) digester.parse(
new File("test/webapp-2.2/WEB-INF/web.xml"));
Assert.assertEquals("2.2", desc.getVersion());
Assert.assertEquals(XmlIdentifiers.WEB_22_PUBLIC, desc.getPublicId());
Assert.assertEquals(0, handler.getErrors().size());
Assert.assertEquals(0, handler.getWarnings().size());
}
@Test
public void testWebapp_2_3() throws Exception {
XmlErrorHandler handler = new XmlErrorHandler();
Digester digester = DigesterFactory.newDigester(
true, true, new WebRuleSet(false), true);
digester.setErrorHandler(handler);
digester.push(new WebXml());
WebXml desc = (WebXml) digester.parse(
new File("test/webapp-2.3/WEB-INF/web.xml"));
Assert.assertEquals("2.3", desc.getVersion());
Assert.assertEquals(XmlIdentifiers.WEB_23_PUBLIC, desc.getPublicId());
Assert.assertEquals(0, handler.getErrors().size());
Assert.assertEquals(0, handler.getWarnings().size());
}
@Test
public void testWebapp_2_4() throws Exception {
XmlErrorHandler handler = new XmlErrorHandler();
Digester digester = DigesterFactory.newDigester(
true, true, new WebRuleSet(false), true);
digester.setErrorHandler(handler);
digester.push(new WebXml());
WebXml desc = (WebXml) digester.parse(
new File("test/webapp-2.4/WEB-INF/web.xml"));
Assert.assertEquals("2.4", desc.getVersion());
Assert.assertEquals(0, handler.getErrors().size());
Assert.assertEquals(0, handler.getWarnings().size());
}
@Test
public void testWebapp_2_5() throws Exception {
XmlErrorHandler handler = new XmlErrorHandler();
Digester digester = DigesterFactory.newDigester(
true, true, new WebRuleSet(false), true);
digester.setErrorHandler(handler);
digester.push(new WebXml());
WebXml desc = (WebXml) digester.parse(
new File("test/webapp-2.5/WEB-INF/web.xml"));
Assert.assertEquals("2.5", desc.getVersion());
Assert.assertEquals(0, handler.getErrors().size());
Assert.assertEquals(0, handler.getWarnings().size());
}
@Test
public void testWebapp_3_0() throws Exception {
XmlErrorHandler handler = new XmlErrorHandler();
Digester digester = DigesterFactory.newDigester(
true, true, new WebRuleSet(false), true);
digester.setErrorHandler(handler);
digester.push(new WebXml());
WebXml desc = (WebXml) digester.parse(
new File("test/webapp-3.0/WEB-INF/web.xml"));
Assert.assertEquals("3.0", desc.getVersion());
Assert.assertEquals(0, handler.getErrors().size());
Assert.assertEquals(0, handler.getWarnings().size());
}
@Test
public void testWebapp_3_1() throws Exception {
XmlErrorHandler handler = new XmlErrorHandler();
Digester digester = DigesterFactory.newDigester(
true, true, new WebRuleSet(false), true);
digester.setErrorHandler(handler);
digester.push(new WebXml());
WebXml desc = (WebXml) digester.parse(
new File("test/webapp-3.1/WEB-INF/web.xml"));
Assert.assertEquals("3.1", desc.getVersion());
Assert.assertEquals(0, handler.getErrors().size());
Assert.assertEquals(0, handler.getWarnings().size());
}
}