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,17 @@
# 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.
# SCIs that should be added when running tests
org.apache.jasper.servlet.JasperInitializer

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<jaspic-providers xmlns="http://tomcat.apache.org/xml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://tomcat.apache.org/xml jaspic-providers.xsd"
version="1.0">
</jaspic-providers>

View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<jaspic-providers xmlns="http://tomcat.apache.org/xml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://tomcat.apache.org/xml jaspic-providers.xsd"
version="1.0">
<provider className="a" layer="b" appContext="c" description="d">
<property name="e" value="f"/>
<property name="g" value="h"/>
</provider>
</jaspic-providers>

View File

@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<jaspic-providers xmlns="http://tomcat.apache.org/xml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://tomcat.apache.org/xml jaspic-providers.xsd"
version="1.0">
<provider className="a" description="d"/>
</jaspic-providers>

BIN
test/deployment/broken.war Normal file

Binary file not shown.

BIN
test/deployment/context.jar Normal file

Binary file not shown.

BIN
test/deployment/context.war Normal file

Binary file not shown.

View File

@@ -0,0 +1,17 @@
<!--
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.
-->
<Context sessionCookieName="XML_CONTEXT" />

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,17 @@
<!--
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.
-->
<Context sessionCookieName="DIR_CONTEXT" />

View File

@@ -0,0 +1,22 @@
<!--
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.
-->
<!-- dirContext -->
<html>
<body>
<p>Directory based web application with a context.xml file.</p>
</body>
</html>

View File

@@ -0,0 +1,22 @@
<!--
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.
-->
<!-- dirNoContext -->
<html>
<body>
<p>Directory based web application with no context.xml file.</p>
</body>
</html>

Binary file not shown.

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
}
}

File diff suppressed because it is too large Load Diff

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" }));
}
}

File diff suppressed because it is too large Load Diff

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");
}
}
}

Some files were not shown because too many files have changed in this diff Show More