mirror of
https://github.com/apache/struts.git
synced 2026-08-08 16:16:58 +00:00
Compare commits
145 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8dface4fcb | |||
| 1348971d40 | |||
| dd6d206d78 | |||
| e2b644a4fb | |||
| 13cfba86f8 | |||
| d84d59f53c | |||
| 3651f55869 | |||
| 7ffa750c68 | |||
| 313876aa3c | |||
| 9d7a9f81db | |||
| fe98223724 | |||
| 1de94b2092 | |||
| 706bb560e4 | |||
| 12d4feaf8f | |||
| d88a8382d4 | |||
| 73809eae54 | |||
| 5b4b554d11 | |||
| fcbd29b7f9 | |||
| 220896a0cf | |||
| 632f19eab3 | |||
| 50a145152d | |||
| f7b191f782 | |||
| 4ae1a6a26d | |||
| 79e598f360 | |||
| 9216e8e22c | |||
| 651eac2c57 | |||
| a50af87644 | |||
| 9e01fbd2dd | |||
| d4dd3386cc | |||
| 0999fba8c4 | |||
| 3ac6835c5c | |||
| b0dd7c1c0d | |||
| a63beef1f8 | |||
| e74e5539dd | |||
| 2226fcc168 | |||
| 865b8a20df | |||
| 3c6956116e | |||
| bb9ce7582b | |||
| 11d373f8b4 | |||
| b23bfd42d2 | |||
| f94b681050 | |||
| fb38a919c9 | |||
| e25c826167 | |||
| 4815744eaf | |||
| f5a7776854 | |||
| f45d2752bb | |||
| 0262574095 | |||
| 30cb56a414 | |||
| 63dc85fd7a | |||
| 5b0ec3400d | |||
| d460d71498 | |||
| 53f64cdecf | |||
| aff4d46835 | |||
| a15c12a051 | |||
| e62155c460 | |||
| f7f4fbd47f | |||
| 2d81439553 | |||
| 7afe35cb96 | |||
| fdd1054070 | |||
| 32e88d1a2e | |||
| 6403de4516 | |||
| 13c517fc3c | |||
| 7242a87165 | |||
| 0323795d67 | |||
| 71267a9b4b | |||
| 5524c579d2 | |||
| 873ca8fa20 | |||
| 8988d57644 | |||
| 2e7cf63964 | |||
| 3eb68be674 | |||
| c9f279ec2e | |||
| 881e1b2580 | |||
| cb0ac7c440 | |||
| 96c38b27e4 | |||
| e9108f0feb | |||
| 3653f6e9e1 | |||
| 5a2323a19f | |||
| ea09a8828b | |||
| 17fe42c0f7 | |||
| 87fa5bddf2 | |||
| 45161e88f9 | |||
| 4456620b51 | |||
| f4a8f42ca4 | |||
| a6f8895c90 | |||
| 46dbdbe018 | |||
| 6f176cc5a7 | |||
| db085dbeef | |||
| c3205888b4 | |||
| ce9789c4c9 | |||
| b431755332 | |||
| c694c6fdfb | |||
| 1d49a06272 | |||
| 264e03b7ed | |||
| 2f99110189 | |||
| d33930f3bd | |||
| 360927931c | |||
| bff033e6a3 | |||
| 536d2db4b8 | |||
| 32c8f6f811 | |||
| 06e5dfc2ab | |||
| fe630db5f2 | |||
| b75c0ba5e1 | |||
| 8ab102209f | |||
| d7a7c909ea | |||
| 24e151143e | |||
| c5272d2a0d | |||
| 11de8810e4 | |||
| 75dc4c00d2 | |||
| 415ce3e165 | |||
| fe6257b995 | |||
| 3b81a9edaa | |||
| 478a9b8f1c | |||
| 12c3d23bdf | |||
| 8293add6aa | |||
| ecb7beef38 | |||
| bac0f2953c | |||
| 7bca98205d | |||
| 567fae9dfc | |||
| f4d7dbe88e | |||
| 289782c583 | |||
| 1e33df947a | |||
| de1a42d34a | |||
| b816cc1374 | |||
| b802baa4a9 | |||
| daac47ee62 | |||
| b1709c5208 | |||
| daf6f6f749 | |||
| 029892d656 | |||
| 65fb0d4a44 | |||
| 58d87025e9 | |||
| 83c0f1cd1e | |||
| eacc002334 | |||
| 45effc3822 | |||
| bad9a49060 | |||
| a75eddb515 | |||
| 6e87474f9a | |||
| 9fcbd912bc | |||
| fbc780e779 | |||
| 6eb83016e3 | |||
| 3ec7fa9d80 | |||
| f9806ee4e1 | |||
| d175836757 | |||
| e55ad3fb45 | |||
| 6efaf900d4 | |||
| b3bad5ea44 |
@@ -62,3 +62,4 @@ bundles/target
|
||||
plugins/target
|
||||
target
|
||||
plugins/testng/test-output
|
||||
test-output
|
||||
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
/*
|
||||
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.
|
||||
*/
|
||||
|
||||
import java.net.*;
|
||||
import java.io.*;
|
||||
import java.nio.channels.*;
|
||||
import java.util.Properties;
|
||||
|
||||
public class MavenWrapperDownloader {
|
||||
|
||||
/**
|
||||
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
|
||||
*/
|
||||
private static final String DEFAULT_DOWNLOAD_URL =
|
||||
"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.0/maven-wrapper-0.4.0.jar";
|
||||
|
||||
/**
|
||||
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
|
||||
* use instead of the default one.
|
||||
*/
|
||||
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
|
||||
".mvn/wrapper/maven-wrapper.properties";
|
||||
|
||||
/**
|
||||
* Path where the maven-wrapper.jar will be saved to.
|
||||
*/
|
||||
private static final String MAVEN_WRAPPER_JAR_PATH =
|
||||
".mvn/wrapper/maven-wrapper.jar";
|
||||
|
||||
/**
|
||||
* Name of the property which should be used to override the default download url for the wrapper.
|
||||
*/
|
||||
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
|
||||
|
||||
public static void main(String args[]) {
|
||||
System.out.println("- Downloader started");
|
||||
File baseDirectory = new File(args[0]);
|
||||
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
|
||||
|
||||
// If the maven-wrapper.properties exists, read it and check if it contains a custom
|
||||
// wrapperUrl parameter.
|
||||
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
|
||||
String url = DEFAULT_DOWNLOAD_URL;
|
||||
if(mavenWrapperPropertyFile.exists()) {
|
||||
FileInputStream mavenWrapperPropertyFileInputStream = null;
|
||||
try {
|
||||
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
|
||||
Properties mavenWrapperProperties = new Properties();
|
||||
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
|
||||
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
|
||||
} catch (IOException e) {
|
||||
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
|
||||
} finally {
|
||||
try {
|
||||
if(mavenWrapperPropertyFileInputStream != null) {
|
||||
mavenWrapperPropertyFileInputStream.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// Ignore ...
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("- Downloading from: : " + url);
|
||||
|
||||
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
|
||||
if(!outputFile.getParentFile().exists()) {
|
||||
if(!outputFile.getParentFile().mkdirs()) {
|
||||
System.out.println(
|
||||
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
|
||||
}
|
||||
}
|
||||
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
|
||||
try {
|
||||
downloadFileFromURL(url, outputFile);
|
||||
System.out.println("Done");
|
||||
System.exit(0);
|
||||
} catch (Throwable e) {
|
||||
System.out.println("- Error downloading");
|
||||
e.printStackTrace();
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
|
||||
URL website = new URL(urlString);
|
||||
ReadableByteChannel rbc;
|
||||
rbc = Channels.newChannel(website.openStream());
|
||||
FileOutputStream fos = new FileOutputStream(destination);
|
||||
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
|
||||
fos.close();
|
||||
rbc.close();
|
||||
}
|
||||
|
||||
}
|
||||
BIN
Binary file not shown.
+1
@@ -0,0 +1 @@
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip
|
||||
+11
-3
@@ -1,15 +1,23 @@
|
||||
dist: trusty
|
||||
language: java
|
||||
sudo: false
|
||||
|
||||
jdk:
|
||||
- openjdk7
|
||||
- oraclejdk8
|
||||
- oraclejdk9
|
||||
- oraclejdk11
|
||||
|
||||
install: true
|
||||
script: mvn test -DskipAssembly
|
||||
script: mvn test -DskipAssembly -B
|
||||
|
||||
after_success:
|
||||
- mvn clean cobertura:cobertura org.eluder.coveralls:coveralls-maven-plugin:report com.updateimpact:updateimpact-maven-plugin:submit -Ptravis-coveralls,update-impact -DskipAssembly
|
||||
# TODO delete following if statement after fix of https://github.com/cobertura/cobertura/issues/271
|
||||
- if [ "$TRAVIS_JDK_VERSION" == "openjdk8" ] || [ "$TRAVIS_JDK_VERSION" == "oraclejdk8" ]; then
|
||||
mvn cobertura:cobertura org.eluder.coveralls:coveralls-maven-plugin:report com.updateimpact:updateimpact-maven-plugin:submit -Ptravis-coveralls,update-impact -DskipAssembly -B;
|
||||
else
|
||||
echo "Not reporting coverage for $TRAVIS_JDK_VERSION due to incompatibility or to save performance";
|
||||
fi;
|
||||
|
||||
env:
|
||||
global:
|
||||
@@ -18,4 +26,4 @@ env:
|
||||
cache:
|
||||
directories:
|
||||
- $HOME/.m2
|
||||
|
||||
|
||||
|
||||
Vendored
+29
@@ -0,0 +1,29 @@
|
||||
#!groovy
|
||||
pipeline {
|
||||
agent {
|
||||
label 'ubuntu'
|
||||
}
|
||||
options {
|
||||
buildDiscarder logRotator(daysToKeepStr: '14', numToKeepStr: '10')
|
||||
timeout(80)
|
||||
disableConcurrentBuilds()
|
||||
}
|
||||
tools {
|
||||
jdk 'JDK 1.7 (latest)'
|
||||
maven 'Maven 3 (latest)'
|
||||
}
|
||||
triggers {
|
||||
pollSCM 'H/15 * * * *'
|
||||
}
|
||||
environment {
|
||||
MAVEN_OPTS = '-Xmx1024m -XX:MaxPermSize=256m'
|
||||
}
|
||||
stages {
|
||||
stage('Build') {
|
||||
steps {
|
||||
sh 'mvn --version'
|
||||
sh 'mvn clean source:jar javadoc:jar install deploy -DskipWiki -Dhttps.protocols=TLSv1,TLSv1.1,TLSv1.2'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -24,7 +24,7 @@
|
||||
<parent>
|
||||
<groupId>org.apache.struts</groupId>
|
||||
<artifactId>struts2-parent</artifactId>
|
||||
<version>2.5.16</version>
|
||||
<version>2.5.21</version>
|
||||
</parent>
|
||||
<artifactId>struts2-apps</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
@@ -24,12 +24,12 @@
|
||||
<parent>
|
||||
<groupId>org.apache.struts</groupId>
|
||||
<artifactId>struts2-apps</artifactId>
|
||||
<version>2.5.16</version>
|
||||
<version>2.5.21</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>struts2-rest-showcase</artifactId>
|
||||
<packaging>war</packaging>
|
||||
<version>2.5.16</version>
|
||||
<version>2.5.21</version>
|
||||
<name>Struts 2 Rest Showcase Webapp</name>
|
||||
<description>Struts 2 Rest Showcase Example</description>
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
<parent>
|
||||
<groupId>org.apache.struts</groupId>
|
||||
<artifactId>struts2-apps</artifactId>
|
||||
<version>2.5.16</version>
|
||||
<version>2.5.21</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>struts2-showcase</artifactId>
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
</action>
|
||||
|
||||
<action name="doMultipleUploadUsingList" class="org.apache.struts2.showcase.fileupload.MultipleFileUploadUsingListAction" method="upload">
|
||||
<result name="input">/WEB-INF/fileupload/multipleUploadUsingList.jsp</result>
|
||||
<result>/WEB-INF/fileupload/multiple-success.jsp</result>
|
||||
</action>
|
||||
|
||||
@@ -49,6 +50,7 @@
|
||||
</action>
|
||||
|
||||
<action name="doMultipleUploadUsingArray" class="org.apache.struts2.showcase.fileupload.MultipleFileUploadUsingArrayAction" method="upload">
|
||||
<result name="input">/WEB-INF/fileupload/multipleUploadUsingArray.jsp</result>
|
||||
<result>/WEB-INF/fileupload/multiple-success.jsp</result>
|
||||
</action>
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@
|
||||
<interceptor-ref name="defaultStack"/>
|
||||
<interceptor-ref name="token"/>
|
||||
<result name="invalid.token">/WEB-INF/token/doublePost.jsp</result>
|
||||
<result name="success" type="redirect">/WEB-INF/token/transferDone.jsp</result>
|
||||
<result name="success">/WEB-INF/token/transferDone.jsp</result>
|
||||
</action>
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@
|
||||
<interceptor-ref name="defaultStack"/>
|
||||
<interceptor-ref name="tokenSession"/>
|
||||
<result name="invalid.token">/WEB-INF/token/doublePost.jsp</result>
|
||||
<result name="success" type="redirect">/WEB-INF/token/transferDone.jsp</result>
|
||||
<result name="success">/WEB-INF/token/transferDone.jsp</result>
|
||||
</action>
|
||||
|
||||
|
||||
|
||||
@@ -34,28 +34,28 @@
|
||||
|
||||
<package name="validation" extends="json-default" namespace="/validation">
|
||||
<action name="index">
|
||||
<result>/WEB-INF/validation/index.jsp</result>
|
||||
<result>index.jsp</result>
|
||||
</action>
|
||||
|
||||
<action name="quizBasic" class="org.apache.struts2.showcase.validation.QuizAction">
|
||||
<result name="input">quiz-basic.jsp</result>
|
||||
<result>quiz-success.jsp</result>
|
||||
<result name="input">/WEB-INF/validation/quiz-basic.jsp</result>
|
||||
<result>/WEB-INF/validation/quiz-success.jsp</result>
|
||||
</action>
|
||||
|
||||
<action name="quizClient" class="org.apache.struts2.showcase.validation.QuizAction">
|
||||
<result name="input">quiz-client.jsp</result>
|
||||
<result>quiz-success.jsp</result>
|
||||
<result name="input">/WEB-INF/validation/quiz-client.jsp</result>
|
||||
<result>/WEB-INF/validation/quiz-success.jsp</result>
|
||||
</action>
|
||||
|
||||
<action name="quizClientCss" class="org.apache.struts2.showcase.validation.QuizAction">
|
||||
<result name="input">quiz-client-css.jsp</result>
|
||||
<result>quiz-success.jsp</result>
|
||||
<result name="input">/WEB-INF/validation/quiz-client-css.jsp</result>
|
||||
<result>/WEB-INF/validation/quiz-success.jsp</result>
|
||||
</action>
|
||||
|
||||
<action name="quizAjax" class="org.apache.struts2.showcase.validation.QuizAction">
|
||||
<interceptor-ref name="jsonValidationWorkflowStack"/>
|
||||
<result name="input">quiz-ajax.jsp</result>
|
||||
<result>quiz-success.jsp</result>
|
||||
<result name="input">/WEB-INF/validation/quiz-ajax.jsp</result>
|
||||
<result>/WEB-INF/validation/quiz-success.jsp</result>
|
||||
</action>
|
||||
|
||||
<!-- =========================================== -->
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
-->
|
||||
<%@ page
|
||||
language="java"
|
||||
contentType="text/html; charset=UTF-8"
|
||||
pageEncoding="UTF-8"%>
|
||||
<%@ taglib prefix="s" uri="/struts-tags" %>
|
||||
<html>
|
||||
<head>
|
||||
<title>Struts2 Showcase - Fileupload sample - Multiple fileupload</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="page-header">
|
||||
<h1>Fileupload sample - Multiple fileupload</h1>
|
||||
</div>
|
||||
|
||||
<div class="container-fluid">
|
||||
<s:iterator var="counter" begin="1" end="3">
|
||||
<!-- Mechanism for display to work with upload both as an array and list in a single JSP (a bit ugly).
|
||||
Note: Output "index" doesn't always match if the input is "sparse". -->
|
||||
<s:if test="%{#counter <= upload.length}">
|
||||
<s:set var="displayContent" value="true" />
|
||||
</s:if>
|
||||
<s:elseif test="%{#counter <= upload.size}">
|
||||
<s:set var="displayContent" value="true" />
|
||||
</s:elseif>
|
||||
<s:else>
|
||||
<s:set var="displayContent" value="false" />
|
||||
</s:else>
|
||||
<s:if test="%{#displayContent == true}">
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
<b>File (<s:property value="#counter" />):</b>
|
||||
<ul>
|
||||
<li>ContentType: <s:property value="uploadContentType[#counter - 1]" /></li>
|
||||
<li>FileName: <s:property value="uploadFileName[#counter -1]" /></li>
|
||||
<li>File: <s:property value="upload[#counter - 1]" /></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</s:if>
|
||||
</s:iterator>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -18,6 +18,7 @@
|
||||
* under the License.
|
||||
*/
|
||||
-->
|
||||
<%@page import="org.apache.struts2.showcase.hangman.HangmanConstants" %>
|
||||
<%@taglib prefix="s" uri="/struts-tags" %>
|
||||
<html>
|
||||
<head>
|
||||
@@ -635,5 +636,18 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<br>
|
||||
<br>
|
||||
<p>
|
||||
A secondary test for this JSP visually verifies expression access to a public constant.
|
||||
A direct access to the same public constant via scriptlet provides secondary verification.
|
||||
</p>
|
||||
<br>
|
||||
<div>
|
||||
Test public static (constant) access (expression). Value: <s:property default="unavailable" value="@org.apache.struts2.showcase.hangman.HangmanConstants@HANGMAN_SESSION_KEY" />
|
||||
</div>
|
||||
<div>
|
||||
Test public static (constant) access (scriptlet). Value: <%=org.apache.struts2.showcase.hangman.HangmanConstants.HANGMAN_SESSION_KEY%>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -50,7 +50,7 @@
|
||||
|
||||
<@s.form action="transfer4">
|
||||
<@s.token/>
|
||||
<@s.textfield label="Amount" name="amount" required="true" value="400"/>
|
||||
<@s.textfield label="Amount" name="amount" required=true value="400"/>
|
||||
<@s.submit value="Transfer money" cssClass="btn btn-primary"/>
|
||||
</@s.form>
|
||||
</div>
|
||||
|
||||
+2
-2
@@ -24,7 +24,7 @@
|
||||
<parent>
|
||||
<groupId>org.apache.struts</groupId>
|
||||
<artifactId>struts2-parent</artifactId>
|
||||
<version>2.5.16</version>
|
||||
<version>2.5.21</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>struts2-assembly</artifactId>
|
||||
@@ -111,7 +111,7 @@
|
||||
<id>make-assembly</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>attached</goal>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
http://struts.apache.org/getting-started/
|
||||
http://struts.apache.org/security/
|
||||
http://struts.apache.org/core-developers/
|
||||
http://struts.apache.org/tag-developers/
|
||||
http://struts.apache.org/maven-archetypes/
|
||||
http://struts.apache.org/plugins/
|
||||
https://struts.apache.org/getting-started/
|
||||
https://struts.apache.org/security/
|
||||
https://struts.apache.org/core-developers/
|
||||
https://struts.apache.org/tag-developers/
|
||||
https://struts.apache.org/maven-archetypes/
|
||||
https://struts.apache.org/plugins/
|
||||
|
||||
+3
-3
@@ -30,7 +30,7 @@
|
||||
</parent>
|
||||
|
||||
<artifactId>struts2-bom</artifactId>
|
||||
<version>2.5.16</version>
|
||||
<version>2.5.21</version>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<name>Struts 2 Bill of Materials</name>
|
||||
@@ -45,7 +45,7 @@
|
||||
</licenses>
|
||||
|
||||
<properties>
|
||||
<struts-version.version>2.5.16</struts-version.version>
|
||||
<struts-version.version>2.5.21</struts-version.version>
|
||||
<maven.site.skip>true</maven.site.skip>
|
||||
<maven.site.deploy.skip>true</maven.site.deploy.skip>
|
||||
</properties>
|
||||
@@ -181,6 +181,6 @@
|
||||
</dependencyManagement>
|
||||
|
||||
<scm>
|
||||
<tag>STRUTS_2_5_16</tag>
|
||||
<tag>STRUTS_2_5_21</tag>
|
||||
</scm>
|
||||
</project>
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
<parent>
|
||||
<groupId>org.apache.struts</groupId>
|
||||
<artifactId>struts2-osgi-bundles</artifactId>
|
||||
<version>2.5.16</version>
|
||||
<version>2.5.21</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>struts2-osgi-admin-bundle</artifactId>
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
<parent>
|
||||
<groupId>org.apache.struts</groupId>
|
||||
<artifactId>struts2-osgi-bundles</artifactId>
|
||||
<version>2.5.16</version>
|
||||
<version>2.5.21</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>struts2-osgi-demo-bundle</artifactId>
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@
|
||||
<parent>
|
||||
<groupId>org.apache.struts</groupId>
|
||||
<artifactId>struts2-parent</artifactId>
|
||||
<version>2.5.16</version>
|
||||
<version>2.5.21</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>struts2-osgi-bundles</artifactId>
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@
|
||||
<parent>
|
||||
<groupId>org.apache.struts</groupId>
|
||||
<artifactId>struts2-parent</artifactId>
|
||||
<version>2.5.16</version>
|
||||
<version>2.5.21</version>
|
||||
</parent>
|
||||
<artifactId>struts2-core</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
@@ -201,13 +201,10 @@ public class ActionChainResult implements Result {
|
||||
* @param invocation the DefaultActionInvocation calling the action call stack
|
||||
*/
|
||||
public void execute(ActionInvocation invocation) throws Exception {
|
||||
// if the finalNamespace wasn't explicitly defined, assume the current one
|
||||
if (this.namespace == null) {
|
||||
this.namespace = invocation.getProxy().getNamespace();
|
||||
}
|
||||
|
||||
ValueStack stack = ActionContext.getContext().getValueStack();
|
||||
String finalNamespace = TextParseUtil.translateVariables(namespace, stack);
|
||||
String finalNamespace = this.namespace != null
|
||||
? TextParseUtil.translateVariables(namespace, stack)
|
||||
: invocation.getProxy().getNamespace();
|
||||
String finalActionName = TextParseUtil.translateVariables(actionName, stack);
|
||||
String finalMethodName = this.methodName != null
|
||||
? TextParseUtil.translateVariables(this.methodName, stack)
|
||||
|
||||
@@ -27,6 +27,7 @@ import com.opensymphony.xwork2.test.StubConfigurationProvider;
|
||||
import com.opensymphony.xwork2.util.XWorkTestCaseHelper;
|
||||
import com.opensymphony.xwork2.util.location.LocatableProperties;
|
||||
import junit.framework.TestCase;
|
||||
import org.apache.commons.lang3.ClassUtils;
|
||||
|
||||
/**
|
||||
* Base JUnit TestCase to extend for XWork specific JUnit tests. Uses
|
||||
@@ -78,16 +79,20 @@ public abstract class XWorkTestCase extends TestCase {
|
||||
@Override
|
||||
public void register(ContainerBuilder builder,
|
||||
LocatableProperties props) throws ConfigurationException {
|
||||
builder.factory(type, name, new Factory() {
|
||||
public Object create(Context context) throws Exception {
|
||||
return impl;
|
||||
}
|
||||
if (impl instanceof String || ClassUtils.isPrimitiveOrWrapper(impl.getClass())) {
|
||||
props.setProperty(name, "" + impl);
|
||||
} else {
|
||||
builder.factory(type, name, new Factory() {
|
||||
public Object create(Context context) throws Exception {
|
||||
return impl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class type() {
|
||||
return impl.getClass();
|
||||
}
|
||||
}, Scope.SINGLETON);
|
||||
@Override
|
||||
public Class type() {
|
||||
return impl.getClass();
|
||||
}
|
||||
}, Scope.SINGLETON);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+1
@@ -226,6 +226,7 @@ public class XWorkConfigurationProvider implements ConfigurationProvider {
|
||||
props.setProperty(XWorkConstants.ENABLE_OGNL_EXPRESSION_CACHE, Boolean.TRUE.toString());
|
||||
props.setProperty(XWorkConstants.ENABLE_OGNL_EVAL_EXPRESSION, Boolean.FALSE.toString());
|
||||
props.setProperty(XWorkConstants.RELOAD_XML_CONFIGURATION, Boolean.FALSE.toString());
|
||||
props.setProperty(StrutsConstants.STRUTS_ALLOW_STATIC_METHOD_ACCESS, Boolean.FALSE.toString());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+35
-14
@@ -93,12 +93,12 @@ public class XmlConfigurationProvider implements ConfigurationProvider {
|
||||
private String configFileName;
|
||||
private ObjectFactory objectFactory;
|
||||
|
||||
private Set<String> loadedFileUrls = new HashSet<>();
|
||||
private final Set<String> loadedFileUrls = new HashSet<>();
|
||||
private boolean errorIfMissing;
|
||||
private Map<String, String> dtdMappings;
|
||||
private Configuration configuration;
|
||||
private boolean throwExceptionOnDuplicateBeans = true;
|
||||
private Map<String, Element> declaredPackages = new HashMap<>();
|
||||
private final Map<String, Element> declaredPackages = new HashMap<>();
|
||||
|
||||
private FileManager fileManager;
|
||||
private ValueSubstitutor valueSubstitutor;
|
||||
@@ -874,15 +874,24 @@ public class XmlConfigurationProvider implements ConfigurationProvider {
|
||||
if (allowedMethodsEls.getLength() > 0) {
|
||||
// user defined 'allowed-methods' so used them whatever Strict DMI was enabled or not
|
||||
allowedMethods = new HashSet<>(packageContext.getGlobalAllowedMethods());
|
||||
|
||||
if (allowedMethodsEls.getLength() > 0) {
|
||||
Node n = allowedMethodsEls.item(0).getFirstChild();
|
||||
if (n != null) {
|
||||
String s = n.getNodeValue().trim();
|
||||
if (s.length() > 0) {
|
||||
allowedMethods.addAll(TextParseUtil.commaDelimitedStringToSet(s));
|
||||
// Fix for WW-5029 (concatenate all possible text node children)
|
||||
final Node allowedMethodsNode = allowedMethodsEls.item(0);
|
||||
if (allowedMethodsNode != null) {
|
||||
final NodeList allowedMethodsChildren = allowedMethodsNode.getChildNodes();
|
||||
final StringBuilder allowedMethodsSB = new StringBuilder();
|
||||
for (int i = 0; i < allowedMethodsChildren.getLength(); i++) {
|
||||
Node allowedMethodsChildNode = allowedMethodsChildren.item(i);
|
||||
if (allowedMethodsChildNode != null && allowedMethodsChildNode.getNodeType() == Node.TEXT_NODE) {
|
||||
String childNodeValue = allowedMethodsChildNode.getNodeValue();
|
||||
childNodeValue = (childNodeValue != null ? childNodeValue.trim() : "");
|
||||
if (childNodeValue.length() > 0) {
|
||||
allowedMethodsSB.append(childNodeValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (allowedMethodsSB.length() > 0) {
|
||||
allowedMethods.addAll(TextParseUtil.commaDelimitedStringToSet(allowedMethodsSB.toString()));
|
||||
}
|
||||
}
|
||||
} else if (packageContext.isStrictMethodInvocation()) {
|
||||
// user enabled Strict DMI but didn't defined action specific 'allowed-methods' so we use 'global-allowed-methods' only
|
||||
@@ -937,11 +946,23 @@ public class XmlConfigurationProvider implements ConfigurationProvider {
|
||||
|
||||
if (globalAllowedMethodsElms.getLength() > 0) {
|
||||
Set<String> globalAllowedMethods = new HashSet<>();
|
||||
Node n = globalAllowedMethodsElms.item(0).getFirstChild();
|
||||
if (n != null) {
|
||||
String s = n.getNodeValue().trim();
|
||||
if (s.length() > 0) {
|
||||
globalAllowedMethods = TextParseUtil.commaDelimitedStringToSet(s);
|
||||
// Fix for WW-5029 (concatenate all possible text node children)
|
||||
Node globaAllowedMethodsNode = globalAllowedMethodsElms.item(0);
|
||||
if (globaAllowedMethodsNode != null) {
|
||||
NodeList globaAllowedMethodsChildren = globaAllowedMethodsNode.getChildNodes();
|
||||
final StringBuilder globalAllowedMethodsSB = new StringBuilder();
|
||||
for (int i = 0; i < globaAllowedMethodsChildren.getLength(); i++) {
|
||||
Node globalAllowedMethodsChildNode = globaAllowedMethodsChildren.item(i);
|
||||
if (globalAllowedMethodsChildNode != null && globalAllowedMethodsChildNode.getNodeType() == Node.TEXT_NODE) {
|
||||
String childNodeValue = globalAllowedMethodsChildNode.getNodeValue();
|
||||
childNodeValue = (childNodeValue != null ? childNodeValue.trim() : "");
|
||||
if (childNodeValue.length() > 0) {
|
||||
globalAllowedMethodsSB.append(childNodeValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (globalAllowedMethodsSB.length() > 0) {
|
||||
globalAllowedMethods.addAll(TextParseUtil.commaDelimitedStringToSet(globalAllowedMethodsSB.toString()));
|
||||
}
|
||||
}
|
||||
packageContext.addGlobalAllowedMethods(globalAllowedMethods);
|
||||
|
||||
@@ -21,7 +21,6 @@ package com.opensymphony.xwork2.conversion.impl;
|
||||
import com.opensymphony.xwork2.conversion.ObjectTypeDeterminer;
|
||||
import com.opensymphony.xwork2.conversion.TypeConverter;
|
||||
import com.opensymphony.xwork2.inject.Inject;
|
||||
import com.opensymphony.xwork2.util.XWorkList;
|
||||
|
||||
import java.lang.reflect.Member;
|
||||
import java.util.Collection;
|
||||
|
||||
+1
-2
@@ -16,13 +16,12 @@
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package com.opensymphony.xwork2.util;
|
||||
package com.opensymphony.xwork2.conversion.impl;
|
||||
|
||||
import com.opensymphony.xwork2.ActionContext;
|
||||
import com.opensymphony.xwork2.ObjectFactory;
|
||||
import com.opensymphony.xwork2.XWorkException;
|
||||
import com.opensymphony.xwork2.conversion.TypeConverter;
|
||||
import com.opensymphony.xwork2.conversion.impl.XWorkConverter;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
@@ -164,7 +164,8 @@ class ContainerImpl implements Container {
|
||||
public FieldInjector(ContainerImpl container, Field field, String name)
|
||||
throws MissingDependencyException {
|
||||
this.field = field;
|
||||
if (!field.isAccessible()) {
|
||||
if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()))
|
||||
&& !field.isAccessible()) {
|
||||
SecurityManager sm = System.getSecurityManager();
|
||||
try {
|
||||
if (sm != null) {
|
||||
@@ -256,7 +257,8 @@ class ContainerImpl implements Container {
|
||||
|
||||
public MethodInjector(ContainerImpl container, Method method, String name) throws MissingDependencyException {
|
||||
this.method = method;
|
||||
if (!method.isAccessible()) {
|
||||
if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
|
||||
&& !method.isAccessible()) {
|
||||
SecurityManager sm = System.getSecurityManager();
|
||||
try {
|
||||
if (sm != null) {
|
||||
@@ -306,7 +308,8 @@ class ContainerImpl implements Container {
|
||||
this.implementation = implementation;
|
||||
|
||||
constructor = findConstructorIn(implementation);
|
||||
if (!constructor.isAccessible()) {
|
||||
if ((!Modifier.isPublic(constructor.getModifiers()) || !Modifier.isPublic(constructor.getDeclaringClass().getModifiers()))
|
||||
&& !constructor.isAccessible()) {
|
||||
SecurityManager sm = System.getSecurityManager();
|
||||
try {
|
||||
if (sm != null) {
|
||||
|
||||
@@ -23,7 +23,7 @@ package com.opensymphony.xwork2.ognl;
|
||||
*/
|
||||
public class ErrorMessageBuilder {
|
||||
|
||||
private StringBuilder message = new StringBuilder();
|
||||
private final StringBuilder message = new StringBuilder();
|
||||
|
||||
public static ErrorMessageBuilder create() {
|
||||
return new ErrorMessageBuilder();
|
||||
|
||||
@@ -24,7 +24,7 @@ import java.util.Map;
|
||||
|
||||
public class OgnlNullHandlerWrapper implements ognl.NullHandler {
|
||||
|
||||
private NullHandler wrapped;
|
||||
private final NullHandler wrapped;
|
||||
|
||||
public OgnlNullHandlerWrapper(NullHandler target) {
|
||||
this.wrapped = target;
|
||||
|
||||
@@ -28,7 +28,7 @@ import java.util.Map;
|
||||
*/
|
||||
public class OgnlTypeConverterWrapper implements ognl.TypeConverter {
|
||||
|
||||
private TypeConverter typeConverter;
|
||||
private final TypeConverter typeConverter;
|
||||
|
||||
public OgnlTypeConverterWrapper(TypeConverter converter) {
|
||||
if (converter == null) {
|
||||
|
||||
@@ -54,48 +54,64 @@ public class OgnlUtil {
|
||||
|
||||
private static final Logger LOG = LogManager.getLogger(OgnlUtil.class);
|
||||
|
||||
private ConcurrentMap<String, Object> expressions = new ConcurrentHashMap<>();
|
||||
private final ConcurrentMap<String, Object> expressions = new ConcurrentHashMap<>();
|
||||
private final ConcurrentMap<Class, BeanInfo> beanInfoCache = new ConcurrentHashMap<>();
|
||||
private TypeConverter defaultConverter;
|
||||
|
||||
private boolean devMode = false;
|
||||
private boolean devMode;
|
||||
private boolean enableExpressionCache = true;
|
||||
private boolean enableEvalExpression;
|
||||
|
||||
private Set<Class<?>> excludedClasses = Collections.emptySet();
|
||||
private Set<Pattern> excludedPackageNamePatterns = Collections.emptySet();
|
||||
private Set<String> excludedPackageNames = Collections.emptySet();
|
||||
private Set<Class<?>> excludedClasses;
|
||||
private Set<Pattern> excludedPackageNamePatterns;
|
||||
private Set<String> excludedPackageNames;
|
||||
|
||||
private Container container;
|
||||
private boolean allowStaticMethodAccess;
|
||||
private boolean disallowProxyMemberAccess;
|
||||
|
||||
public OgnlUtil() {
|
||||
excludedClasses = new HashSet<>();
|
||||
excludedPackageNamePatterns = new HashSet<>();
|
||||
excludedPackageNames = new HashSet<>();
|
||||
excludedClasses = Collections.unmodifiableSet(excludedClasses);
|
||||
excludedPackageNamePatterns = Collections.unmodifiableSet(excludedPackageNamePatterns);
|
||||
excludedPackageNames = Collections.unmodifiableSet(excludedPackageNames);
|
||||
}
|
||||
|
||||
@Inject
|
||||
public void setXWorkConverter(XWorkConverter conv) {
|
||||
protected void setXWorkConverter(XWorkConverter conv) {
|
||||
this.defaultConverter = new OgnlTypeConverterWrapper(conv);
|
||||
}
|
||||
|
||||
@Inject(XWorkConstants.DEV_MODE)
|
||||
public void setDevMode(String mode) {
|
||||
protected void setDevMode(String mode) {
|
||||
this.devMode = BooleanUtils.toBoolean(mode);
|
||||
}
|
||||
|
||||
@Inject(XWorkConstants.ENABLE_OGNL_EXPRESSION_CACHE)
|
||||
public void setEnableExpressionCache(String cache) {
|
||||
protected void setEnableExpressionCache(String cache) {
|
||||
enableExpressionCache = BooleanUtils.toBoolean(cache);
|
||||
}
|
||||
|
||||
@Inject(value = XWorkConstants.ENABLE_OGNL_EVAL_EXPRESSION, required = false)
|
||||
public void setEnableEvalExpression(String evalExpression) {
|
||||
enableEvalExpression = "true".equals(evalExpression);
|
||||
if(enableEvalExpression){
|
||||
protected void setEnableEvalExpression(String evalExpression) {
|
||||
this.enableEvalExpression = BooleanUtils.toBoolean(evalExpression);
|
||||
if (this.enableEvalExpression) {
|
||||
LOG.warn("Enabling OGNL expression evaluation may introduce security risks " +
|
||||
"(see http://struts.apache.org/release/2.3.x/docs/s2-013.html for further details)");
|
||||
}
|
||||
}
|
||||
|
||||
@Inject(value = XWorkConstants.OGNL_EXCLUDED_CLASSES, required = false)
|
||||
public void setExcludedClasses(String commaDelimitedClasses) {
|
||||
protected void setExcludedClasses(String commaDelimitedClasses) {
|
||||
Set<Class<?>> excludedClasses = new HashSet<>();
|
||||
excludedClasses.addAll(this.excludedClasses);
|
||||
excludedClasses.addAll(parseExcludedClasses(commaDelimitedClasses));
|
||||
this.excludedClasses = Collections.unmodifiableSet(excludedClasses);
|
||||
}
|
||||
|
||||
private Set<Class<?>> parseExcludedClasses(String commaDelimitedClasses) {
|
||||
Set<String> classNames = TextParseUtil.commaDelimitedStringToSet(commaDelimitedClasses);
|
||||
Set<Class<?>> classes = new HashSet<>();
|
||||
|
||||
@@ -107,11 +123,18 @@ public class OgnlUtil {
|
||||
}
|
||||
}
|
||||
|
||||
excludedClasses = Collections.unmodifiableSet(classes);
|
||||
return classes;
|
||||
}
|
||||
|
||||
@Inject(value = XWorkConstants.OGNL_EXCLUDED_PACKAGE_NAME_PATTERNS, required = false)
|
||||
public void setExcludedPackageNamePatterns(String commaDelimitedPackagePatterns) {
|
||||
protected void setExcludedPackageNamePatterns(String commaDelimitedPackagePatterns) {
|
||||
Set<Pattern> excludedPackageNamePatterns = new HashSet<>();
|
||||
excludedPackageNamePatterns.addAll(this.excludedPackageNamePatterns);
|
||||
excludedPackageNamePatterns.addAll(parseExcludedPackageNamePatterns(commaDelimitedPackagePatterns));
|
||||
this.excludedPackageNamePatterns = Collections.unmodifiableSet(excludedPackageNamePatterns);
|
||||
}
|
||||
|
||||
private Set<Pattern> parseExcludedPackageNamePatterns(String commaDelimitedPackagePatterns) {
|
||||
Set<String> packagePatterns = TextParseUtil.commaDelimitedStringToSet(commaDelimitedPackagePatterns);
|
||||
Set<Pattern> packageNamePatterns = new HashSet<>();
|
||||
|
||||
@@ -119,12 +142,19 @@ public class OgnlUtil {
|
||||
packageNamePatterns.add(Pattern.compile(pattern));
|
||||
}
|
||||
|
||||
excludedPackageNamePatterns = Collections.unmodifiableSet(packageNamePatterns);
|
||||
return packageNamePatterns;
|
||||
}
|
||||
|
||||
@Inject(value = XWorkConstants.OGNL_EXCLUDED_PACKAGE_NAMES, required = false)
|
||||
public void setExcludedPackageNames(String commaDelimitedPackageNames) {
|
||||
excludedPackageNames = Collections.unmodifiableSet(TextParseUtil.commaDelimitedStringToSet(commaDelimitedPackageNames));
|
||||
protected void setExcludedPackageNames(String commaDelimitedPackageNames) {
|
||||
Set<String> excludedPackageNames = new HashSet<>();
|
||||
excludedPackageNames.addAll(this.excludedPackageNames);
|
||||
excludedPackageNames.addAll(parseExcludedPackageNames(commaDelimitedPackageNames));
|
||||
this.excludedPackageNames = Collections.unmodifiableSet(excludedPackageNames);
|
||||
}
|
||||
|
||||
private Set<String> parseExcludedPackageNames(String commaDelimitedPackageNames) {
|
||||
return TextParseUtil.commaDelimitedStringToSet(commaDelimitedPackageNames);
|
||||
}
|
||||
|
||||
public Set<Class<?>> getExcludedClasses() {
|
||||
@@ -140,24 +170,112 @@ public class OgnlUtil {
|
||||
}
|
||||
|
||||
@Inject
|
||||
public void setContainer(Container container) {
|
||||
protected void setContainer(Container container) {
|
||||
this.container = container;
|
||||
}
|
||||
|
||||
@Inject(value = XWorkConstants.ALLOW_STATIC_METHOD_ACCESS, required = false)
|
||||
public void setAllowStaticMethodAccess(String allowStaticMethodAccess) {
|
||||
this.allowStaticMethodAccess = Boolean.parseBoolean(allowStaticMethodAccess);
|
||||
protected void setAllowStaticMethodAccess(String allowStaticMethodAccess) {
|
||||
this.allowStaticMethodAccess = BooleanUtils.toBoolean(allowStaticMethodAccess);
|
||||
}
|
||||
|
||||
@Inject(value = StrutsConstants.STRUTS_DISALLOW_PROXY_MEMBER_ACCESS, required = false)
|
||||
public void setDisallowProxyMemberAccess(String disallowProxyMemberAccess) {
|
||||
protected void setDisallowProxyMemberAccess(String disallowProxyMemberAccess) {
|
||||
this.disallowProxyMemberAccess = Boolean.parseBoolean(disallowProxyMemberAccess);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param maxLength Injects the Struts OGNL maximum expression length.
|
||||
*/
|
||||
@Inject(value = StrutsConstants.STRUTS_OGNL_EXPRESSION_MAX_LENGTH, required = false)
|
||||
protected void applyExpressionMaxLength(String maxLength) {
|
||||
try {
|
||||
if (maxLength == null || maxLength.isEmpty()) {
|
||||
// user is going to disable this functionality
|
||||
Ognl.applyExpressionMaxLength(null);
|
||||
} else {
|
||||
Ognl.applyExpressionMaxLength(Integer.parseInt(maxLength));
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
LOG.warn("Unable to set OGNL Expression Max Length {}.", maxLength); // Help configuration debugging.
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isDisallowProxyMemberAccess() {
|
||||
return disallowProxyMemberAccess;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience mechanism to clear the OGNL Runtime Cache via OgnlUtil. May be utilized
|
||||
* by applications that generate many unique OGNL expressions over time.
|
||||
*
|
||||
* Note: This call affects the global OGNL cache, see ({@link ognl.OgnlRuntime#clearCache()} for details.
|
||||
*
|
||||
* Warning: Frequent calling if this method may negatively impact performance, but may be required
|
||||
* to avoid memory exhaustion (resource leak) with too many OGNL expressions being cached.
|
||||
*
|
||||
* @since 2.5.21
|
||||
*/
|
||||
public static void clearRuntimeCache() {
|
||||
OgnlRuntime.clearCache();
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide a mechanism to clear the OGNL expression cache. May be utilized by applications
|
||||
* that generate many unique OGNL expressions over time.
|
||||
*
|
||||
* Note: This call affects the current OgnlUtil instance. For Struts this is often a Singleton
|
||||
* instance so it can be "effectively global".
|
||||
*
|
||||
* Warning: Frequent calling if this method may negatively impact performance, but may be required
|
||||
* to avoid memory exhaustion (resource leak) with too many OGNL expressions being cached.
|
||||
*
|
||||
* @since 2.5.21
|
||||
*/
|
||||
public void clearExpressionCache() {
|
||||
expressions.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the size of the expression cache (current number of elements).
|
||||
*
|
||||
* @return current number of elements in the expression cache.
|
||||
*
|
||||
* @since 2.5.21
|
||||
*/
|
||||
public int expressionCacheSize() {
|
||||
return expressions.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide a mechanism to clear the BeanInfo cache. May be utilized by applications
|
||||
* that request BeanInfo and/or PropertyDescriptors for many unique classes or objects over time
|
||||
* (especially dynamic objects).
|
||||
*
|
||||
* Note: This call affects the current OgnlUtil instance. For Struts this is often a Singleton
|
||||
* instance so it can be "effectively global".
|
||||
*
|
||||
* Warning: Frequent calling if this method may negatively impact performance, but may be required
|
||||
* to avoid memory exhaustion (resource leak) with too many BeanInfo elements being cached.
|
||||
*
|
||||
* @since 2.5.21
|
||||
*/
|
||||
public void clearBeanInfoCache() {
|
||||
beanInfoCache.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the size of the BeanInfo cache (current number of elements).
|
||||
*
|
||||
* @return current number of elements in the BeanInfo cache.
|
||||
*
|
||||
* @since 2.5.21
|
||||
*/
|
||||
public int beanInfoCacheSize() {
|
||||
return beanInfoCache.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the object's properties using the default type converter, defaulting to not throw
|
||||
* exceptions for problems setting the properties.
|
||||
@@ -404,7 +522,7 @@ public class OgnlUtil {
|
||||
|
||||
final T exec = task.execute(tree);
|
||||
// if cache is enabled and it's a valid expression, puts it in
|
||||
if(enableExpressionCache) {
|
||||
if (enableExpressionCache) {
|
||||
expressions.putIfAbsent(expression, tree);
|
||||
}
|
||||
return exec;
|
||||
@@ -425,7 +543,7 @@ public class OgnlUtil {
|
||||
|
||||
final T exec = task.execute(tree);
|
||||
// if cache is enabled and it's a valid expression, puts it in
|
||||
if(enableExpressionCache) {
|
||||
if (enableExpressionCache) {
|
||||
expressions.putIfAbsent(expression, tree);
|
||||
}
|
||||
return exec;
|
||||
@@ -641,8 +759,7 @@ public class OgnlUtil {
|
||||
*/
|
||||
public BeanInfo getBeanInfo(Class clazz) throws IntrospectionException {
|
||||
synchronized (beanInfoCache) {
|
||||
BeanInfo beanInfo;
|
||||
beanInfo = beanInfoCache.get(clazz);
|
||||
BeanInfo beanInfo = beanInfoCache.get(clazz);
|
||||
if (beanInfo == null) {
|
||||
beanInfo = Introspector.getBeanInfo(clazz, Object.class);
|
||||
beanInfoCache.putIfAbsent(clazz, beanInfo);
|
||||
@@ -656,6 +773,9 @@ public class OgnlUtil {
|
||||
setValue(name, context, o, value);
|
||||
} catch (OgnlException e) {
|
||||
Throwable reason = e.getReason();
|
||||
if (reason instanceof SecurityException) {
|
||||
LOG.warn("Could not evaluate this expression due to security constraints: [{}]", name, e);
|
||||
}
|
||||
String msg = "Caught OgnlException while setting property '" + name + "' on type '" + o.getClass().getName() + "'.";
|
||||
Throwable exception = (reason == null) ? e : reason;
|
||||
|
||||
|
||||
@@ -82,7 +82,7 @@ public class OgnlValueStack implements Serializable, ValueStack, ClearableValueS
|
||||
}
|
||||
|
||||
@Inject
|
||||
public void setOgnlUtil(OgnlUtil ognlUtil) {
|
||||
protected void setOgnlUtil(OgnlUtil ognlUtil) {
|
||||
this.ognlUtil = ognlUtil;
|
||||
securityMemberAccess.setExcludedClasses(ognlUtil.getExcludedClasses());
|
||||
securityMemberAccess.setExcludedPackageNamePatterns(ognlUtil.getExcludedPackageNamePatterns());
|
||||
@@ -102,12 +102,12 @@ public class OgnlValueStack implements Serializable, ValueStack, ClearableValueS
|
||||
}
|
||||
|
||||
@Inject(XWorkConstants.DEV_MODE)
|
||||
public void setDevMode(String mode) {
|
||||
protected void setDevMode(String mode) {
|
||||
this.devMode = BooleanUtils.toBoolean(mode);
|
||||
}
|
||||
|
||||
@Inject(value = "logMissingProperties", required = false)
|
||||
public void setLogMissingProperties(String logMissingProperties) {
|
||||
protected void setLogMissingProperties(String logMissingProperties) {
|
||||
this.logMissingProperties = BooleanUtils.toBoolean(logMissingProperties);
|
||||
}
|
||||
|
||||
@@ -157,8 +157,6 @@ public class OgnlValueStack implements Serializable, ValueStack, ClearableValueS
|
||||
setValue(expr, value, devMode);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
/**
|
||||
* @see com.opensymphony.xwork2.util.ValueStack#setValue(java.lang.String, java.lang.Object)
|
||||
*/
|
||||
@@ -184,7 +182,7 @@ public class OgnlValueStack implements Serializable, ValueStack, ClearableValueS
|
||||
|
||||
private void trySetValue(String expr, Object value, boolean throwExceptionOnFailure, Map<String, Object> context) throws OgnlException {
|
||||
context.put(XWorkConverter.CONVERSION_PROPERTY_FULLNAME, expr);
|
||||
context.put(REPORT_ERRORS_ON_NO_PROP, (throwExceptionOnFailure) ? Boolean.TRUE : Boolean.FALSE);
|
||||
context.put(REPORT_ERRORS_ON_NO_PROP, throwExceptionOnFailure || logMissingProperties ? Boolean.TRUE : Boolean.FALSE);
|
||||
ognlUtil.setValue(expr, context, root, value);
|
||||
}
|
||||
|
||||
@@ -206,6 +204,9 @@ public class OgnlValueStack implements Serializable, ValueStack, ClearableValueS
|
||||
}
|
||||
|
||||
protected void handleOgnlException(String expr, Object value, boolean throwExceptionOnFailure, OgnlException e) {
|
||||
if (e != null && e.getReason() instanceof SecurityException) {
|
||||
LOG.warn("Could not evaluate this expression due to security constraints: [{}]", expr, e);
|
||||
}
|
||||
boolean shouldLog = shouldLogMissingPropertyWarning(e);
|
||||
String msg = null;
|
||||
if (throwExceptionOnFailure || shouldLog) {
|
||||
@@ -248,7 +249,7 @@ public class OgnlValueStack implements Serializable, ValueStack, ClearableValueS
|
||||
}
|
||||
|
||||
protected void setupExceptionOnFailure(boolean throwExceptionOnFailure) {
|
||||
if (throwExceptionOnFailure) {
|
||||
if (throwExceptionOnFailure || logMissingProperties) {
|
||||
context.put(THROW_EXCEPTION_ON_FAILURE, true);
|
||||
}
|
||||
}
|
||||
@@ -328,7 +329,12 @@ public class OgnlValueStack implements Serializable, ValueStack, ClearableValueS
|
||||
}
|
||||
|
||||
protected Object handleOgnlException(String expr, boolean throwExceptionOnFailure, OgnlException e) {
|
||||
Object ret = findInContext(expr);
|
||||
Object ret = null;
|
||||
if (e != null && e.getReason() instanceof SecurityException) {
|
||||
LOG.warn("Could not evaluate this expression due to security constraints: [{}]", expr, e);
|
||||
} else {
|
||||
ret = findInContext(expr);
|
||||
}
|
||||
if (ret == null) {
|
||||
if (shouldLogMissingPropertyWarning(e)) {
|
||||
LOG.warn("Could not find property [{}]!", expr, e);
|
||||
@@ -341,8 +347,9 @@ public class OgnlValueStack implements Serializable, ValueStack, ClearableValueS
|
||||
}
|
||||
|
||||
protected boolean shouldLogMissingPropertyWarning(OgnlException e) {
|
||||
return (e instanceof NoSuchPropertyException || e instanceof MethodFailedException)
|
||||
&& devMode && logMissingProperties;
|
||||
return (e instanceof NoSuchPropertyException ||
|
||||
(e instanceof MethodFailedException && e.getReason() instanceof NoSuchMethodException))
|
||||
&& logMissingProperties;
|
||||
}
|
||||
|
||||
private Object tryFindValue(String expr, Class asType) throws OgnlException {
|
||||
@@ -379,7 +386,7 @@ public class OgnlValueStack implements Serializable, ValueStack, ClearableValueS
|
||||
* @param e The thrown exception.
|
||||
*/
|
||||
private void logLookupFailure(String expr, Exception e) {
|
||||
if (devMode && LOG.isWarnEnabled()) {
|
||||
if (devMode) {
|
||||
LOG.warn("Caught an exception while evaluating expression '{}' against value stack", expr, e);
|
||||
LOG.warn("NOTE: Previous warning message was issued due to devMode set to true.");
|
||||
} else {
|
||||
@@ -475,7 +482,7 @@ public class OgnlValueStack implements Serializable, ValueStack, ClearableValueS
|
||||
}
|
||||
|
||||
@Inject
|
||||
public void setXWorkConverter(final XWorkConverter converter) {
|
||||
protected void setXWorkConverter(final XWorkConverter converter) {
|
||||
this.converter = converter;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
package com.opensymphony.xwork2.ognl;
|
||||
|
||||
import com.opensymphony.xwork2.ActionContext;
|
||||
import com.opensymphony.xwork2.XWorkConstants;
|
||||
import com.opensymphony.xwork2.TextProvider;
|
||||
import com.opensymphony.xwork2.conversion.NullHandler;
|
||||
import com.opensymphony.xwork2.conversion.impl.XWorkConverter;
|
||||
@@ -32,6 +33,8 @@ import ognl.MethodAccessor;
|
||||
import ognl.OgnlRuntime;
|
||||
import ognl.PropertyAccessor;
|
||||
import org.apache.commons.lang3.BooleanUtils;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
@@ -41,24 +44,26 @@ import java.util.Set;
|
||||
*/
|
||||
public class OgnlValueStackFactory implements ValueStackFactory {
|
||||
|
||||
private static final Logger LOG = LogManager.getLogger(OgnlValueStackFactory.class);
|
||||
|
||||
protected XWorkConverter xworkConverter;
|
||||
protected CompoundRootAccessor compoundRootAccessor;
|
||||
protected TextProvider textProvider;
|
||||
protected Container container;
|
||||
protected boolean allowStaticMethodAccess;
|
||||
private boolean allowStaticMethodAccess;
|
||||
|
||||
@Inject
|
||||
public void setXWorkConverter(XWorkConverter converter) {
|
||||
protected void setXWorkConverter(XWorkConverter converter) {
|
||||
this.xworkConverter = converter;
|
||||
}
|
||||
|
||||
@Inject("system")
|
||||
public void setTextProvider(TextProvider textProvider) {
|
||||
protected void setTextProvider(TextProvider textProvider) {
|
||||
this.textProvider = textProvider;
|
||||
}
|
||||
|
||||
@Inject(value="allowStaticMethodAccess", required=false)
|
||||
public void setAllowStaticMethodAccess(String allowStaticMethodAccess) {
|
||||
@Inject(value = XWorkConstants.ALLOW_STATIC_METHOD_ACCESS, required = false)
|
||||
protected void setAllowStaticMethodAccess(String allowStaticMethodAccess) {
|
||||
this.allowStaticMethodAccess = BooleanUtils.toBoolean(allowStaticMethodAccess);
|
||||
}
|
||||
|
||||
@@ -77,7 +82,7 @@ public class OgnlValueStackFactory implements ValueStackFactory {
|
||||
}
|
||||
|
||||
@Inject
|
||||
public void setContainer(Container container) throws ClassNotFoundException {
|
||||
protected void setContainer(Container container) throws ClassNotFoundException {
|
||||
Set<String> names = container.getInstanceNames(PropertyAccessor.class);
|
||||
for (String name : names) {
|
||||
Class cls = Class.forName(name);
|
||||
|
||||
@@ -46,9 +46,16 @@ public class SecurityMemberAccess extends DefaultMemberAccess {
|
||||
private Set<String> excludedPackageNames = Collections.emptySet();
|
||||
private boolean disallowProxyMemberAccess;
|
||||
|
||||
public SecurityMemberAccess(boolean method) {
|
||||
/**
|
||||
* SecurityMemberAccess
|
||||
* - access decisions based on whether member is static (or not)
|
||||
* - block or allow access to properties (configurable-after-construction)
|
||||
*
|
||||
* @param allowStaticMethodAccess
|
||||
*/
|
||||
public SecurityMemberAccess(boolean allowStaticMethodAccess) {
|
||||
super(false);
|
||||
allowStaticMethodAccess = method;
|
||||
this.allowStaticMethodAccess = allowStaticMethodAccess;
|
||||
}
|
||||
|
||||
public boolean getAllowStaticMethodAccess() {
|
||||
@@ -59,28 +66,30 @@ public class SecurityMemberAccess extends DefaultMemberAccess {
|
||||
public boolean isAccessible(Map context, Object target, Member member, String propertyName) {
|
||||
LOG.debug("Checking access for [target: {}, member: {}, property: {}]", target, member, propertyName);
|
||||
|
||||
final Class memberClass = member.getDeclaringClass();
|
||||
Class targetClass = (target != null ? target.getClass() : memberClass); // Note: target,propertyName may be null (static field checks OGNL 3.1.19+)
|
||||
|
||||
if (checkEnumAccess(target, member)) {
|
||||
LOG.trace("Allowing access to enum: {}", target);
|
||||
LOG.trace("Allowing access to enum: target class [{}] of target [{}], member [{}]", targetClass, target, member);
|
||||
return true;
|
||||
}
|
||||
|
||||
Class targetClass = target.getClass();
|
||||
Class memberClass = member.getDeclaringClass();
|
||||
|
||||
if (Modifier.isStatic(member.getModifiers()) && allowStaticMethodAccess) {
|
||||
LOG.debug("Support for accessing static methods [target: {}, member: {}, property: {}] is deprecated!", target, member, propertyName);
|
||||
if (!isClassExcluded(member.getDeclaringClass())) {
|
||||
targetClass = member.getDeclaringClass();
|
||||
LOG.debug("Support for accessing static methods [target: {}, targetClass: {}, member: {}, property: {}] is deprecated!",
|
||||
target, targetClass, member, propertyName);
|
||||
if (!isClassExcluded(memberClass)) {
|
||||
targetClass = memberClass;
|
||||
}
|
||||
}
|
||||
|
||||
if (isPackageExcluded(targetClass.getPackage(), memberClass.getPackage())) {
|
||||
LOG.warn("Package of target [{}] or package of member [{}] are excluded!", target, member);
|
||||
LOG.warn("Package [{}] of target class [{}] of target [{}] or package [{}] of member [{}] are excluded!", targetClass.getPackage(), targetClass,
|
||||
target, memberClass.getPackage(), member);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isClassExcluded(targetClass)) {
|
||||
LOG.warn("Target class [{}] is excluded!", target);
|
||||
LOG.warn("Target class [{}] of target [{}] is excluded!", targetClass, target);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -90,7 +99,7 @@ public class SecurityMemberAccess extends DefaultMemberAccess {
|
||||
}
|
||||
|
||||
if (disallowProxyMemberAccess && ProxyUtil.isProxyMember(member, target)) {
|
||||
LOG.warn("Access to proxy [{}] is blocked!", member);
|
||||
LOG.warn("Access to proxy is blocked! Target class [{}] of target [{}], member [{}]", targetClass, target, member);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -133,8 +142,8 @@ public class SecurityMemberAccess extends DefaultMemberAccess {
|
||||
LOG.warn("The use of the default (unnamed) package is discouraged!");
|
||||
}
|
||||
|
||||
final String targetPackageName = targetPackage == null ? "" : targetPackage.getName();
|
||||
final String memberPackageName = memberPackage == null ? "" : memberPackage.getName();
|
||||
String targetPackageName = targetPackage == null ? "" : targetPackage.getName();
|
||||
String memberPackageName = memberPackage == null ? "" : memberPackage.getName();
|
||||
|
||||
for (Pattern pattern : excludedPackageNamePatterns) {
|
||||
if (pattern.matcher(targetPackageName).matches() || pattern.matcher(memberPackageName).matches()) {
|
||||
@@ -142,9 +151,11 @@ public class SecurityMemberAccess extends DefaultMemberAccess {
|
||||
}
|
||||
}
|
||||
|
||||
targetPackageName = targetPackageName + ".";
|
||||
memberPackageName = memberPackageName + ".";
|
||||
|
||||
for (String packageName: excludedPackageNames) {
|
||||
if (targetPackageName.startsWith(packageName) || targetPackageName.equals(packageName)
|
||||
|| memberPackageName.startsWith(packageName) || memberPackageName.equals(packageName)) {
|
||||
if (targetPackageName.startsWith(packageName) || memberPackageName.startsWith(packageName)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ import java.util.Map;
|
||||
*/
|
||||
public class XWorkTypeConverterWrapper implements TypeConverter {
|
||||
|
||||
private ognl.TypeConverter typeConverter;
|
||||
private final ognl.TypeConverter typeConverter;
|
||||
|
||||
public XWorkTypeConverterWrapper(ognl.TypeConverter conv) {
|
||||
this.typeConverter = conv;
|
||||
|
||||
+18
-14
@@ -63,10 +63,10 @@ public class CompoundRootAccessor implements PropertyAccessor, MethodAccessor, C
|
||||
private final static Logger LOG = LogManager.getLogger(CompoundRootAccessor.class);
|
||||
private final static Class[] EMPTY_CLASS_ARRAY = new Class[0];
|
||||
private static Map<MethodCall, Boolean> invalidMethods = new ConcurrentHashMap<>();
|
||||
private boolean devMode = false;
|
||||
private boolean devMode;
|
||||
|
||||
@Inject(XWorkConstants.DEV_MODE)
|
||||
public void setDevMode(String mode) {
|
||||
protected void setDevMode(String mode) {
|
||||
this.devMode = BooleanUtils.toBoolean(mode);
|
||||
}
|
||||
|
||||
@@ -217,13 +217,14 @@ public class CompoundRootAccessor implements PropertyAccessor, MethodAccessor, C
|
||||
return null;
|
||||
}
|
||||
|
||||
Throwable reason = null;
|
||||
Class[] argTypes = getArgTypes(objects);
|
||||
for (Object o : root) {
|
||||
if (o == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Class clazz = o.getClass();
|
||||
Class[] argTypes = getArgTypes(objects);
|
||||
|
||||
MethodCall mc = null;
|
||||
|
||||
@@ -233,24 +234,27 @@ public class CompoundRootAccessor implements PropertyAccessor, MethodAccessor, C
|
||||
|
||||
if ((argTypes == null) || !invalidMethods.containsKey(mc)) {
|
||||
try {
|
||||
Object value = OgnlRuntime.callMethod((OgnlContext) context, o, name, objects);
|
||||
|
||||
if (value != null) {
|
||||
return value;
|
||||
}
|
||||
return OgnlRuntime.callMethod((OgnlContext) context, o, name, objects);
|
||||
} catch (OgnlException e) {
|
||||
// try the next one
|
||||
Throwable reason = e.getReason();
|
||||
reason = e.getReason();
|
||||
|
||||
if (!context.containsKey(OgnlValueStack.THROW_EXCEPTION_ON_FAILURE) && (mc != null) && (reason != null) && (reason.getClass() == NoSuchMethodException.class)) {
|
||||
invalidMethods.put(mc, Boolean.TRUE);
|
||||
} else if (reason != null) {
|
||||
throw new MethodFailedException(o, name, e.getReason());
|
||||
if (reason != null && !(reason instanceof NoSuchMethodException)) {
|
||||
// method has found but thrown an exception
|
||||
break;
|
||||
}
|
||||
|
||||
if ((mc != null) && (reason != null)) {
|
||||
invalidMethods.put(mc, Boolean.TRUE);
|
||||
}
|
||||
// continue and try the next one
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (context.containsKey(OgnlValueStack.THROW_EXCEPTION_ON_FAILURE)) {
|
||||
throw new MethodFailedException(target, name, reason);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -48,7 +48,7 @@ public class XWorkCollectionPropertyAccessor extends SetPropertyAccessor {
|
||||
//use a basic object Ognl property accessor here
|
||||
//to access properties of the objects in the Set
|
||||
//so that nothing is put in the context to screw things up
|
||||
private ObjectPropertyAccessor _accessor = new ObjectPropertyAccessor();
|
||||
private final ObjectPropertyAccessor _accessor = new ObjectPropertyAccessor();
|
||||
|
||||
private XWorkConverter xworkConverter;
|
||||
private ObjectFactory objectFactory;
|
||||
|
||||
+1
-1
@@ -30,7 +30,7 @@ import java.util.Map;
|
||||
*/
|
||||
public class XWorkEnumerationAccessor extends EnumerationPropertyAccessor {
|
||||
|
||||
ObjectPropertyAccessor opa = new ObjectPropertyAccessor();
|
||||
private final ObjectPropertyAccessor opa = new ObjectPropertyAccessor();
|
||||
|
||||
@Override
|
||||
public void setProperty(Map context, Object target, Object name, Object value) throws OgnlException {
|
||||
|
||||
+1
-1
@@ -30,7 +30,7 @@ import java.util.Map;
|
||||
*/
|
||||
public class XWorkIteratorPropertyAccessor extends IteratorPropertyAccessor {
|
||||
|
||||
ObjectPropertyAccessor opa = new ObjectPropertyAccessor();
|
||||
private final ObjectPropertyAccessor opa = new ObjectPropertyAccessor();
|
||||
|
||||
@Override
|
||||
public void setProperty(Map context, Object target, Object name, Object value) throws OgnlException {
|
||||
|
||||
+35
-10
@@ -25,6 +25,7 @@ import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
@@ -44,39 +45,62 @@ public class DefaultAcceptedPatternsChecker implements AcceptedPatternsChecker {
|
||||
}
|
||||
|
||||
@Inject(value = XWorkConstants.OVERRIDE_ACCEPTED_PATTERNS, required = false)
|
||||
public void setOverrideAcceptedPatterns(String acceptablePatterns) {
|
||||
protected void setOverrideAcceptedPatterns(String acceptablePatterns) {
|
||||
LOG.warn("Overriding accepted patterns [{}] with [{}], be aware that this affects all instances and safety of your application!",
|
||||
XWorkConstants.OVERRIDE_ACCEPTED_PATTERNS, acceptablePatterns);
|
||||
acceptedPatterns, acceptablePatterns);
|
||||
acceptedPatterns = new HashSet<>();
|
||||
for (String pattern : TextParseUtil.commaDelimitedStringToSet(acceptablePatterns)) {
|
||||
acceptedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE));
|
||||
try {
|
||||
for (String pattern : TextParseUtil.commaDelimitedStringToSet(acceptablePatterns)) {
|
||||
acceptedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE));
|
||||
}
|
||||
} finally {
|
||||
acceptedPatterns = Collections.unmodifiableSet(acceptedPatterns);
|
||||
}
|
||||
}
|
||||
|
||||
@Inject(value = XWorkConstants.ADDITIONAL_ACCEPTED_PATTERNS, required = false)
|
||||
public void setAdditionalAcceptedPatterns(String acceptablePatterns) {
|
||||
protected void setAdditionalAcceptedPatterns(String acceptablePatterns) {
|
||||
LOG.warn("Adding additional global patterns [{}] to accepted patterns!", acceptablePatterns);
|
||||
for (String pattern : TextParseUtil.commaDelimitedStringToSet(acceptablePatterns)) {
|
||||
acceptedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE));
|
||||
acceptedPatterns = new HashSet<>(acceptedPatterns); // Make mutable before adding
|
||||
try {
|
||||
for (String pattern : TextParseUtil.commaDelimitedStringToSet(acceptablePatterns)) {
|
||||
acceptedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE));
|
||||
}
|
||||
} finally {
|
||||
acceptedPatterns = Collections.unmodifiableSet(acceptedPatterns);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAcceptedPatterns(String commaDelimitedPatterns) {
|
||||
setAcceptedPatterns(TextParseUtil.commaDelimitedStringToSet(commaDelimitedPatterns));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAcceptedPatterns(String[] additionalPatterns) {
|
||||
setAcceptedPatterns(new HashSet<>(Arrays.asList(additionalPatterns)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAcceptedPatterns(Set<String> patterns) {
|
||||
LOG.trace("Sets accepted patterns [{}]", patterns);
|
||||
if (acceptedPatterns == null) {
|
||||
// Limit unwanted log entries (for 1st call, acceptedPatterns null)
|
||||
LOG.debug("Sets accepted patterns to [{}], note this impacts the safety of your application!", patterns);
|
||||
} else {
|
||||
LOG.warn("Replacing accepted patterns [{}] with [{}], be aware that this affects all instances and safety of your application!",
|
||||
acceptedPatterns, patterns);
|
||||
}
|
||||
acceptedPatterns = new HashSet<>(patterns.size());
|
||||
for (String pattern : patterns) {
|
||||
acceptedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE));
|
||||
try {
|
||||
for (String pattern : patterns) {
|
||||
acceptedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE));
|
||||
}
|
||||
} finally {
|
||||
acceptedPatterns = Collections.unmodifiableSet(acceptedPatterns);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public IsAccepted isAccepted(String value) {
|
||||
for (Pattern acceptedPattern : acceptedPatterns) {
|
||||
if (acceptedPattern.matcher(value).matches()) {
|
||||
@@ -87,6 +111,7 @@ public class DefaultAcceptedPatternsChecker implements AcceptedPatternsChecker {
|
||||
return IsAccepted.no(acceptedPatterns.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Pattern> getAcceptedPatterns() {
|
||||
return acceptedPatterns;
|
||||
}
|
||||
|
||||
+43
-13
@@ -27,6 +27,7 @@ import org.apache.logging.log4j.Logger;
|
||||
import org.apache.struts2.StrutsConstants;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
@@ -47,47 +48,75 @@ public class DefaultExcludedPatternsChecker implements ExcludedPatternsChecker {
|
||||
}
|
||||
|
||||
@Inject(value = XWorkConstants.OVERRIDE_EXCLUDED_PATTERNS, required = false)
|
||||
public void setOverrideExcludePatterns(String excludePatterns) {
|
||||
LOG.warn("Overriding excluded patterns [{}] with [{}], be aware that this affects all instances and safety of your application!",
|
||||
XWorkConstants.OVERRIDE_EXCLUDED_PATTERNS, excludePatterns);
|
||||
excludedPatterns = new HashSet<Pattern>();
|
||||
for (String pattern : TextParseUtil.commaDelimitedStringToSet(excludePatterns)) {
|
||||
excludedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE));
|
||||
protected void setOverrideExcludePatterns(String excludePatterns) {
|
||||
if (excludedPatterns != null && excludedPatterns.size() > 0) {
|
||||
LOG.warn("Overriding excluded patterns [{}] with [{}], be aware that this affects all instances and safety of your application!",
|
||||
excludedPatterns, excludePatterns);
|
||||
} else {
|
||||
// Limit unwanted log entries (when excludedPatterns null/empty - usually 1st call)
|
||||
LOG.debug("Overriding excluded patterns with [{}]", excludePatterns);
|
||||
}
|
||||
excludedPatterns = new HashSet<>();
|
||||
try {
|
||||
for (String pattern : TextParseUtil.commaDelimitedStringToSet(excludePatterns)) {
|
||||
excludedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE));
|
||||
}
|
||||
} finally {
|
||||
excludedPatterns = Collections.unmodifiableSet(excludedPatterns);
|
||||
}
|
||||
}
|
||||
|
||||
@Inject(value = XWorkConstants.ADDITIONAL_EXCLUDED_PATTERNS, required = false)
|
||||
public void setAdditionalExcludePatterns(String excludePatterns) {
|
||||
LOG.debug("Adding additional global patterns [{}] to excluded patterns!", excludePatterns);
|
||||
for (String pattern : TextParseUtil.commaDelimitedStringToSet(excludePatterns)) {
|
||||
excludedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE));
|
||||
excludedPatterns = new HashSet<>(excludedPatterns); // Make mutable before adding
|
||||
try {
|
||||
for (String pattern : TextParseUtil.commaDelimitedStringToSet(excludePatterns)) {
|
||||
excludedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE));
|
||||
}
|
||||
} finally {
|
||||
excludedPatterns = Collections.unmodifiableSet(excludedPatterns);
|
||||
}
|
||||
}
|
||||
|
||||
@Inject(StrutsConstants.STRUTS_ENABLE_DYNAMIC_METHOD_INVOCATION)
|
||||
public void setDynamicMethodInvocation(String dmiValue) {
|
||||
if (!BooleanUtils.toBoolean(dmiValue)) {
|
||||
protected void setDynamicMethodInvocation(String dmiValue) {
|
||||
if (BooleanUtils.toBoolean(dmiValue) == false) {
|
||||
LOG.debug("DMI is disabled, adding DMI related excluded patterns");
|
||||
setAdditionalExcludePatterns("^(action|method):.*");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setExcludedPatterns(String commaDelimitedPatterns) {
|
||||
setExcludedPatterns(TextParseUtil.commaDelimitedStringToSet(commaDelimitedPatterns));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setExcludedPatterns(String[] patterns) {
|
||||
setExcludedPatterns(new HashSet<>(Arrays.asList(patterns)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setExcludedPatterns(Set<String> patterns) {
|
||||
LOG.trace("Sets excluded patterns [{}]", patterns);
|
||||
if (excludedPatterns != null && excludedPatterns.size() > 0) {
|
||||
LOG.warn("Replacing excluded patterns [{}] with [{}], be aware that this affects all instances and safety of your application!",
|
||||
excludedPatterns, patterns);
|
||||
} else {
|
||||
// Limit unwanted log entries (when excludedPatterns null/empty - usually 1st call)
|
||||
LOG.debug("Sets excluded patterns to [{}]", patterns);
|
||||
}
|
||||
excludedPatterns = new HashSet<>(patterns.size());
|
||||
for (String pattern : patterns) {
|
||||
excludedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE));
|
||||
try {
|
||||
for (String pattern : patterns) {
|
||||
excludedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE));
|
||||
}
|
||||
} finally {
|
||||
excludedPatterns = Collections.unmodifiableSet(excludedPatterns);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public IsExcluded isExcluded(String value) {
|
||||
for (Pattern excludedPattern : excludedPatterns) {
|
||||
if (excludedPattern.matcher(value).matches()) {
|
||||
@@ -98,6 +127,7 @@ public class DefaultExcludedPatternsChecker implements ExcludedPatternsChecker {
|
||||
return IsExcluded.no(excludedPatterns);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Pattern> getExcludedPatterns() {
|
||||
return excludedPatterns;
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ abstract class AbstractLocalizedTextProvider implements LocalizedTextProvider {
|
||||
public static final String STRUTS_MESSAGES_BUNDLE = "org/apache/struts2/struts-messages";
|
||||
|
||||
private static final String TOMCAT_RESOURCE_ENTRIES_FIELD = "resourceEntries";
|
||||
private final String RELOADED = "com.opensymphony.xwork2.util.LocalizedTextProvider.reloaded";
|
||||
private static final String RELOADED = "com.opensymphony.xwork2.util.LocalizedTextProvider.reloaded";
|
||||
|
||||
protected final ConcurrentMap<String, ResourceBundle> bundlesMap = new ConcurrentHashMap<>();
|
||||
protected boolean devMode = false;
|
||||
@@ -225,10 +225,45 @@ abstract class AbstractLocalizedTextProvider implements LocalizedTextProvider {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bundleName Removes the bundle from any cached "misses"
|
||||
* Clear a specific bundle from the <code>bundlesMap</code>
|
||||
*
|
||||
* Warning: This method <b>may be ineffective</b> due to the way the <code>bundlesMap</code>
|
||||
* is used in combination with locale. Descendants should use the method
|
||||
* {@link #clearBundle(java.lang.String, java.util.Locale)} instead.
|
||||
*
|
||||
* @param bundleName The bundle to remove from the bundle map
|
||||
*/
|
||||
public void clearBundle(final String bundleName) {
|
||||
bundlesMap.remove(getCurrentThreadContextClassLoader().hashCode() + bundleName);
|
||||
final ResourceBundle removedBundle = bundlesMap.remove(getCurrentThreadContextClassLoader().hashCode() + bundleName);
|
||||
LOG.debug("Clearing resource bundle [{}], result: [{}].", bundleName, Boolean.valueOf(removedBundle != null));
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear a specific bundle + locale combination from the <code>bundlesMap</code>.
|
||||
* Intended for descendants to use clear a bundle + locale combination.
|
||||
*
|
||||
* @param bundleName The bundle (combined with locale) to remove from the bundle map
|
||||
* @param locale Provides the locale to combine with the bundle to get the key
|
||||
*/
|
||||
protected void clearBundle(final String bundleName, Locale locale) {
|
||||
final String key = createMissesKey(String.valueOf(getCurrentThreadContextClassLoader().hashCode()), bundleName, locale);
|
||||
final ResourceBundle removedBundle = bundlesMap.remove(key);
|
||||
LOG.debug("Clearing resource bundle [{}], locale [{}], result: [{}].", bundleName, locale, Boolean.valueOf(removedBundle != null));
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the <code>missingBundles</code> contents. This allows descendants to
|
||||
* clear the <b>"missing bundles cache"</b> when desired (or needed).
|
||||
*
|
||||
* Note: This method may be used when the <code>bundlesMap</code> state has changed
|
||||
* in such a way that bundles that were previously "missing" may now be available
|
||||
* (e.g. after calling {@link #addDefaultResourceBundle(java.lang.String)} when the
|
||||
* {@link AbstractLocalizedTextProvider} has already been used for failed bundle
|
||||
* lookups of a given key, or some transitory state made a bundle lookup fail.
|
||||
*/
|
||||
protected void clearMissingBundlesCache() {
|
||||
missingBundles.clear();
|
||||
LOG.debug("Cleared the missing bundles cache.");
|
||||
}
|
||||
|
||||
protected void reloadBundles() {
|
||||
|
||||
@@ -27,6 +27,7 @@ import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Vector;
|
||||
import java.util.zip.ZipEntry;
|
||||
@@ -77,11 +78,7 @@ public class ClassPathFinder {
|
||||
*/
|
||||
public Vector<String> findMatches() {
|
||||
Vector<String> matches = new Vector<>();
|
||||
URLClassLoader cl = getURLClassLoader();
|
||||
if (cl == null ) {
|
||||
throw new XWorkException("unable to attain an URLClassLoader") ;
|
||||
}
|
||||
URL[] parentUrls = cl.getURLs();
|
||||
URL[] parentUrls = getClassLoaderURLs();
|
||||
compiledPattern = patternMatcher.compilePattern(pattern);
|
||||
for (URL url : parentUrls) {
|
||||
if (!"file".equals(url.getProtocol())) {
|
||||
@@ -173,20 +170,24 @@ public class ClassPathFinder {
|
||||
this.patternMatcher = patternMatcher;
|
||||
}
|
||||
|
||||
private URLClassLoader getURLClassLoader() {
|
||||
URLClassLoader ucl = null;
|
||||
private URL[] getClassLoaderURLs() {
|
||||
URL[] urls;
|
||||
ClassLoader loader = Thread.currentThread().getContextClassLoader();
|
||||
|
||||
if(! (loader instanceof URLClassLoader)) {
|
||||
|
||||
if (!(loader instanceof URLClassLoader)) {
|
||||
loader = ClassPathFinder.class.getClassLoader();
|
||||
if (loader instanceof URLClassLoader) {
|
||||
ucl = (URLClassLoader) loader ;
|
||||
}
|
||||
|
||||
if (loader instanceof URLClassLoader) {
|
||||
urls = ((URLClassLoader) loader).getURLs();
|
||||
} else { //jdk9 or later
|
||||
try {
|
||||
urls = Collections.list(loader.getResources("")).toArray(new URL[0]);
|
||||
} catch (IOException e) {
|
||||
throw new XWorkException("unable to get ClassLoader URLs", e);
|
||||
}
|
||||
}
|
||||
else {
|
||||
ucl = (URLClassLoader) loader;
|
||||
}
|
||||
|
||||
return ucl ;
|
||||
|
||||
return urls;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,13 +82,14 @@ public class ProxyUtil {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the given member is a proxy member of a proxy object.
|
||||
* Check whether the given member is a proxy member of a proxy object or is a static proxy member.
|
||||
* @param member the member to check
|
||||
* @param object the object to check
|
||||
*/
|
||||
public static boolean isProxyMember(Member member, Object object) {
|
||||
if (!isProxy(object))
|
||||
if (!Modifier.isStatic(member.getModifiers()) && !isProxy(object)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Boolean flag = isProxyMemberCache.get(member);
|
||||
if (flag != null) {
|
||||
|
||||
@@ -40,7 +40,8 @@ public class DefaultFileManager implements FileManager {
|
||||
private static final Pattern JAR_PATTERN = Pattern.compile("^(jar:|wsjar:|zip:|vfsfile:|code-source:)?(file:)?(.*?)(\\!/|\\.jar/)(.*)");
|
||||
private static final int JAR_FILE_PATH = 3;
|
||||
|
||||
protected static Map<String, Revision> files = Collections.synchronizedMap(new HashMap<String, Revision>());
|
||||
protected static final Map<String, Revision> files = Collections.synchronizedMap(new HashMap<String, Revision>());
|
||||
private static final List<URL> lazyMonitoredFilesCache = Collections.synchronizedList(new ArrayList<URL>());
|
||||
|
||||
protected boolean reloadingConfigs = false;
|
||||
|
||||
@@ -48,6 +49,16 @@ public class DefaultFileManager implements FileManager {
|
||||
}
|
||||
|
||||
public void setReloadingConfigs(boolean reloadingConfigs) {
|
||||
if (reloadingConfigs && !this.reloadingConfigs) {
|
||||
//starting monitoring cached not-monitored files (lazy monitoring on demand because of performance)
|
||||
this.reloadingConfigs = true;
|
||||
synchronized (lazyMonitoredFilesCache) {
|
||||
for (URL fileUrl : lazyMonitoredFilesCache) {
|
||||
monitorFile(fileUrl);
|
||||
}
|
||||
lazyMonitoredFilesCache.clear();
|
||||
}
|
||||
}
|
||||
this.reloadingConfigs = reloadingConfigs;
|
||||
}
|
||||
|
||||
@@ -88,6 +99,12 @@ public class DefaultFileManager implements FileManager {
|
||||
|
||||
public void monitorFile(URL fileUrl) {
|
||||
String fileName = fileUrl.toString();
|
||||
if (!reloadingConfigs) {
|
||||
//reserve file for monitoring on demand because of performance
|
||||
files.remove(fileName);
|
||||
lazyMonitoredFilesCache.add(fileUrl);
|
||||
return;
|
||||
}
|
||||
Revision revision;
|
||||
LOG.debug("Creating revision for URL: {}", fileName);
|
||||
if (isJarURL(fileUrl)) {
|
||||
|
||||
@@ -37,9 +37,7 @@ public class JarEntryRevision extends Revision {
|
||||
private long lastModified;
|
||||
|
||||
public static Revision build(URL fileUrl, FileManager fileManager) {
|
||||
StrutsJarURLConnection conn = null;
|
||||
try {
|
||||
conn = StrutsJarURLConnection.openConnection(fileUrl);
|
||||
try (StrutsJarURLConnection conn = StrutsJarURLConnection.openConnection(fileUrl)) {
|
||||
conn.setUseCaches(false);
|
||||
URL url = fileManager.normalizeToFileProtocol(fileUrl);
|
||||
if (url != null) {
|
||||
@@ -51,14 +49,6 @@ public class JarEntryRevision extends Revision {
|
||||
LOG.warn("Could not create JarEntryRevision for [{}]!", fileUrl, e);
|
||||
return null;
|
||||
}
|
||||
finally {
|
||||
if(null != conn) {
|
||||
try {
|
||||
conn.getInputStream().close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private JarEntryRevision(URL jarFileURL, long lastModified) {
|
||||
@@ -70,21 +60,12 @@ public class JarEntryRevision extends Revision {
|
||||
}
|
||||
|
||||
public boolean needsReloading() {
|
||||
StrutsJarURLConnection conn = null;
|
||||
long lastLastModified = lastModified;
|
||||
try {
|
||||
conn = StrutsJarURLConnection.openConnection(jarFileURL);
|
||||
try (StrutsJarURLConnection conn = StrutsJarURLConnection.openConnection(jarFileURL)) {
|
||||
conn.setUseCaches(false);
|
||||
lastLastModified = conn.getJarEntry().getTime();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
finally {
|
||||
if(null != conn) {
|
||||
try {
|
||||
conn.getInputStream().close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
LOG.warn("Could not check if needsReloading for [{}]!", jarFileURL, e);
|
||||
}
|
||||
|
||||
return lastModified < lastLastModified;
|
||||
|
||||
@@ -44,7 +44,7 @@ import java.util.jar.JarFile;
|
||||
* While {@link JarURLConnection#parseSpecs(URL)} is private, then we had to extend {@link URLConnection} instead
|
||||
* @since 2.5.15
|
||||
*/
|
||||
class StrutsJarURLConnection extends URLConnection {
|
||||
class StrutsJarURLConnection extends URLConnection implements AutoCloseable {
|
||||
private static final String FILE_URL_PREFIX = "file:";
|
||||
|
||||
private JarURLConnection jarURLConnection;
|
||||
@@ -123,8 +123,8 @@ class StrutsJarURLConnection extends URLConnection {
|
||||
Path tmpFile = Files.createTempFile("jar_cache", null);
|
||||
try {
|
||||
Files.copy(in, tmpFile, StandardCopyOption.REPLACE_EXISTING);
|
||||
JarFile jarFile = new JarFile(tmpFile.toFile(), true, JarFile.OPEN_READ);
|
||||
tmpFile.toFile().deleteOnExit();
|
||||
JarFile jarFile = new JarFile(tmpFile.toFile(), true, JarFile.OPEN_READ
|
||||
| JarFile.OPEN_DELETE);
|
||||
return jarFile;
|
||||
} catch (Throwable thr) {
|
||||
try {
|
||||
@@ -171,6 +171,20 @@ class StrutsJarURLConnection extends URLConnection {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Exception {
|
||||
try {
|
||||
getInputStream().close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
if (jarURLConnection == null) {
|
||||
try {
|
||||
jarFile.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static StrutsJarURLConnection openConnection(URL url) throws IOException {
|
||||
return new StrutsJarURLConnection(url);
|
||||
}
|
||||
|
||||
@@ -41,12 +41,15 @@ public final class StrutsConstants {
|
||||
/** The URL extension to use to determine if the request is meant for a Struts action */
|
||||
public static final String STRUTS_ACTION_EXTENSION = "struts.action.extension";
|
||||
|
||||
/** Comma separated list of patterns (java.util.regex.Pattern) to be excluded from Struts2-processing */
|
||||
public static final String STRUTS_ACTION_EXCLUDE_PATTERN = "struts.action.excludePattern";
|
||||
/** Comma separated list of patterns (java.util.regex.Pattern) to be excluded from Struts2-processing */
|
||||
public static final String STRUTS_ACTION_EXCLUDE_PATTERN = "struts.action.excludePattern";
|
||||
|
||||
/** Whether to use the alterative syntax for the tags or not */
|
||||
/** Whether to use the alternative syntax for the tags or not */
|
||||
public static final String STRUTS_TAG_ALTSYNTAX = "struts.tag.altSyntax";
|
||||
|
||||
/** Whether to use the response encoding (JSP page encoding) for s:include tag processing (false - use STRUTS_I18N_ENCODING - by default) */
|
||||
public static final String STRUTS_TAG_INCLUDETAG_USERESPONSEENCODING = "struts.tag.includetag.useResponseEncoding";
|
||||
|
||||
/** The HTTP port used by Struts URLs */
|
||||
public static final String STRUTS_URL_HTTP_PORT = "struts.url.http.port";
|
||||
|
||||
@@ -56,7 +59,7 @@ public final class StrutsConstants {
|
||||
/** The default includeParams method to generate Struts URLs */
|
||||
public static final String STRUTS_URL_INCLUDEPARAMS = "struts.url.includeParams";
|
||||
|
||||
public static final String STRUTS_URL_RENDERER = "struts.urlRenderer";
|
||||
public static final String STRUTS_URL_RENDERER = "struts.urlRenderer";
|
||||
|
||||
/** The com.opensymphony.xwork2.ObjectFactory implementation class */
|
||||
public static final String STRUTS_OBJECTFACTORY = "struts.objectFactory";
|
||||
@@ -91,7 +94,7 @@ public final class StrutsConstants {
|
||||
/** The org.apache.struts2.views.freemarker.FreemarkerManager implementation class */
|
||||
public static final String STRUTS_FREEMARKER_MANAGER_CLASSNAME = "struts.freemarker.manager.classname";
|
||||
|
||||
/** Update freemarker templates cache in seconds*/
|
||||
/** Update freemarker templates cache in seconds */
|
||||
public static final String STRUTS_FREEMARKER_TEMPLATES_CACHE_UPDATE_DELAY = "struts.freemarker.templatesCache.updateDelay";
|
||||
|
||||
/** Cache model instances at BeanWrapper level */
|
||||
@@ -220,12 +223,12 @@ public final class StrutsConstants {
|
||||
public static final String STRUTS_LOCALE_PROVIDER_FACTORY = "struts.localeProviderFactory";
|
||||
|
||||
/** The name of the parameter to create when mapping an id (used by some action mappers) */
|
||||
public static final String STRUTS_ID_PARAMETER_NAME = "struts.mapper.idParameterName";
|
||||
|
||||
/** The name of the parameter to determine whether static method access will be allowed in OGNL expressions or not */
|
||||
public static final String STRUTS_ALLOW_STATIC_METHOD_ACCESS = "struts.ognl.allowStaticMethodAccess";
|
||||
public static final String STRUTS_ID_PARAMETER_NAME = "struts.mapper.idParameterName";
|
||||
|
||||
/** The com.opensymphony.xwork2.validator.ActionValidatorManager implementation class */
|
||||
/** The name of the parameter to determine whether static method access will be allowed in OGNL expressions or not */
|
||||
public static final String STRUTS_ALLOW_STATIC_METHOD_ACCESS = "struts.ognl.allowStaticMethodAccess";
|
||||
|
||||
/** The com.opensymphony.xwork2.validator.ActionValidatorManager implementation class */
|
||||
public static final String STRUTS_ACTIONVALIDATORMANAGER = "struts.actionValidatorManager";
|
||||
|
||||
/** The {@link com.opensymphony.xwork2.util.ValueStackFactory} implementation class */
|
||||
@@ -236,7 +239,7 @@ public final class StrutsConstants {
|
||||
|
||||
/** The {@link com.opensymphony.xwork2.util.reflection.ReflectionContextFactory} implementation class */
|
||||
public static final String STRUTS_REFLECTIONCONTEXTFACTORY = "struts.reflectionContextFactory";
|
||||
|
||||
|
||||
/** The {@link com.opensymphony.xwork2.util.PatternMatcher} implementation class */
|
||||
public static final String STRUTS_PATTERNMATCHER = "struts.patternMatcher";
|
||||
|
||||
@@ -246,32 +249,35 @@ public final class StrutsConstants {
|
||||
/** The {@link com.opensymphony.xwork2.UnknownHandlerManager} implementation class */
|
||||
public static final String STRUTS_UNKNOWN_HANDLER_MANAGER = "struts.unknownHandlerManager";
|
||||
|
||||
/** Throw RuntimeException when a property is not found, or the evaluation of the espression fails*/
|
||||
/** Throw RuntimeException when a property is not found, or the evaluation of the expression fails */
|
||||
public static final String STRUTS_EL_THROW_EXCEPTION = "struts.el.throwExceptionOnFailure";
|
||||
|
||||
/** Logs properties that are not found (very verbose) **/
|
||||
/** Logs properties that are not found (very verbose) */
|
||||
public static final String STRUTS_LOG_MISSING_PROPERTIES = "struts.ognl.logMissingProperties";
|
||||
|
||||
/** Enables caching of parsed OGNL expressions **/
|
||||
/** Enables caching of parsed OGNL expressions */
|
||||
public static final String STRUTS_ENABLE_OGNL_EXPRESSION_CACHE = "struts.ognl.enableExpressionCache";
|
||||
|
||||
/** Enables evaluation of OGNL expressions **/
|
||||
/** Enables evaluation of OGNL expressions */
|
||||
public static final String STRUTS_ENABLE_OGNL_EVAL_EXPRESSION = "struts.ognl.enableOGNLEvalExpression";
|
||||
|
||||
/** Disables {@link org.apache.struts2.dispatcher.StrutsRequestWrapper} request attribute value stack lookup (JSTL accessibility) **/
|
||||
/** The maximum length of an expression (OGNL) */
|
||||
public static final String STRUTS_OGNL_EXPRESSION_MAX_LENGTH = "struts.ognl.expressionMaxLength";
|
||||
|
||||
/** Disables {@link org.apache.struts2.dispatcher.StrutsRequestWrapper} request attribute value stack lookup (JSTL accessibility) */
|
||||
public static final String STRUTS_DISABLE_REQUEST_ATTRIBUTE_VALUE_STACK_LOOKUP = "struts.disableRequestAttributeValueStackLookup";
|
||||
|
||||
/** The{@link org.apache.struts2.views.util.UrlHelper} implementation class **/
|
||||
/** The{@link org.apache.struts2.views.util.UrlHelper} implementation class */
|
||||
public static final String STRUTS_URL_HELPER = "struts.view.urlHelper";
|
||||
|
||||
/** {@link com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter} **/
|
||||
/** {@link com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter} */
|
||||
public static final String STRUTS_CONVERTER_COLLECTION = "struts.converter.collection";
|
||||
public static final String STRUTS_CONVERTER_ARRAY = "struts.converter.array";
|
||||
public static final String STRUTS_CONVERTER_DATE = "struts.converter.date";
|
||||
public static final String STRUTS_CONVERTER_NUMBER = "struts.converter.number";
|
||||
public static final String STRUTS_CONVERTER_STRING = "struts.converter.string";
|
||||
|
||||
/** Enable handling exceptions by Dispatcher - true by default **/
|
||||
/** Enable handling exceptions by Dispatcher - true by default */
|
||||
public static final String STRUTS_HANDLE_EXCEPTION = "struts.handle.exception";
|
||||
|
||||
public static final String STRUTS_CONVERTER_PROPERTIES_PROCESSOR = "struts.converter.properties.processor";
|
||||
@@ -282,37 +288,42 @@ public final class StrutsConstants {
|
||||
|
||||
public static final String STRUTS_EXPRESSION_PARSER = "struts.expression.parser";
|
||||
|
||||
/** actions names' whitelist **/
|
||||
/** Namespace names' whitelist */
|
||||
public static final String STRUTS_ALLOWED_NAMESPACE_NAMES = "struts.allowed.namespace.names";
|
||||
/** Default namespace name to use when namespace didn't match the whitelist */
|
||||
public static final String STRUTS_DEFAULT_NAMESPACE_NAME = "struts.default.namespace.name";
|
||||
|
||||
/** Action names' whitelist */
|
||||
public static final String STRUTS_ALLOWED_ACTION_NAMES = "struts.allowed.action.names";
|
||||
/** default action name to use when action didn't match the whitelist **/
|
||||
/** Default action name to use when action didn't match the whitelist */
|
||||
public static final String STRUTS_DEFAULT_ACTION_NAME = "struts.default.action.name";
|
||||
|
||||
/** methods names' whitelist **/
|
||||
/** Method names' whitelist */
|
||||
public static final String STRUTS_ALLOWED_METHOD_NAMES = "struts.allowed.method.names";
|
||||
/** default method name to use when method didn't match the whitelist **/
|
||||
/** Default method name to use when method didn't match the whitelist */
|
||||
public static final String STRUTS_DEFAULT_METHOD_NAME = "struts.default.method.name";
|
||||
|
||||
/** enables action: prefix **/
|
||||
/** Enables action: prefix */
|
||||
public static final String STRUTS_MAPPER_ACTION_PREFIX_ENABLED = "struts.mapper.action.prefix.enabled";
|
||||
|
||||
/** enables access to actions in other namespaces than current with action: prefix **/
|
||||
/** Enables access to actions in other namespaces than current with action: prefix */
|
||||
public static final String STRUTS_MAPPER_ACTION_PREFIX_CROSSNAMESPACES = "struts.mapper.action.prefix.crossNamespaces";
|
||||
|
||||
public static final String DEFAULT_TEMPLATE_TYPE_CONFIG_KEY = "struts.ui.templateSuffix";
|
||||
|
||||
/** Allows override default DispatcherErrorHandler **/
|
||||
/** Allows override default DispatcherErrorHandler */
|
||||
public static final String STRUTS_DISPATCHER_ERROR_HANDLER = "struts.dispatcher.errorHandler";
|
||||
|
||||
/** Comma delimited set of excluded classes and package names which cannot be accessed via expressions **/
|
||||
/** Comma delimited set of excluded classes and package names which cannot be accessed via expressions */
|
||||
public static final String STRUTS_EXCLUDED_CLASSES = "struts.excludedClasses";
|
||||
public static final String STRUTS_EXCLUDED_PACKAGE_NAME_PATTERNS = "struts.excludedPackageNamePatterns";
|
||||
public static final String STRUTS_EXCLUDED_PACKAGE_NAMES = "struts.excludedPackageNames";
|
||||
|
||||
/** Dedicated services to check if passed string is excluded/accepted **/
|
||||
/** Dedicated services to check if passed string is excluded/accepted */
|
||||
public static final String STRUTS_EXCLUDED_PATTERNS_CHECKER = "struts.excludedPatterns.checker";
|
||||
public static final String STRUTS_ACCEPTED_PATTERNS_CHECKER = "struts.acceptedPatterns.checker";
|
||||
|
||||
/** Constant is used to override framework's default excluded patterns **/
|
||||
/** Constant is used to override framework's default excluded patterns */
|
||||
public static final String STRUTS_OVERRIDE_EXCLUDED_PATTERNS = "struts.override.excludedPatterns";
|
||||
public static final String STRUTS_OVERRIDE_ACCEPTED_PATTERNS = "struts.override.acceptedPatterns";
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ package org.apache.struts2.components;
|
||||
|
||||
import com.opensymphony.xwork2.inject.Inject;
|
||||
import com.opensymphony.xwork2.util.ValueStack;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.struts2.RequestUtils;
|
||||
@@ -35,6 +36,7 @@ import javax.servlet.ServletRequest;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpServletResponseWrapper;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.*;
|
||||
@@ -90,17 +92,19 @@ public class Include extends Component {
|
||||
|
||||
private static final Logger LOG = LogManager.getLogger(Include.class);
|
||||
|
||||
private static String systemEncoding = System.getProperty("file.encoding");
|
||||
private static final String systemEncoding = System.getProperty("file.encoding");
|
||||
|
||||
protected String value;
|
||||
private HttpServletRequest req;
|
||||
private HttpServletResponse res;
|
||||
private static String defaultEncoding;
|
||||
private String defaultEncoding; // Made non-static (during WW-4971 fix)
|
||||
private boolean useResponseEncoding; // Added with WW-4971 fix (allows switch between usage of response or default encoding)
|
||||
|
||||
public Include(ValueStack stack, HttpServletRequest req, HttpServletResponse res) {
|
||||
super(stack);
|
||||
this.req = req;
|
||||
this.res = res;
|
||||
useResponseEncoding = false; // By default use defaultEncoding (vs. response/page encoding)
|
||||
}
|
||||
|
||||
@Inject(StrutsConstants.STRUTS_I18N_ENCODING)
|
||||
@@ -108,9 +112,25 @@ public class Include extends Component {
|
||||
defaultEncoding = encoding;
|
||||
}
|
||||
|
||||
@Inject(value = StrutsConstants.STRUTS_TAG_INCLUDETAG_USERESPONSEENCODING, required=false)
|
||||
public void setUseResponseEncoding(String useEncoding) {
|
||||
useResponseEncoding = Boolean.parseBoolean(useEncoding);
|
||||
}
|
||||
|
||||
public boolean end(Writer writer, String body) {
|
||||
String page = findString(value, "value", "You must specify the URL to include. Example: /foo.jsp");
|
||||
StringBuilder urlBuf = new StringBuilder();
|
||||
String encodingForInclude;
|
||||
|
||||
if (useResponseEncoding) {
|
||||
encodingForInclude = res.getCharacterEncoding(); // Use response (page) encoding
|
||||
if (encodingForInclude == null || encodingForInclude.length() == 0) {
|
||||
encodingForInclude = defaultEncoding; // Revert to defaultEncoding when response (page) encoding is invalid
|
||||
}
|
||||
}
|
||||
else {
|
||||
encodingForInclude = defaultEncoding; // Use default encoding (when useResponseEncoding is false)
|
||||
}
|
||||
|
||||
// Add URL
|
||||
urlBuf.append(page);
|
||||
@@ -147,7 +167,7 @@ public class Include extends Component {
|
||||
|
||||
// Include
|
||||
try {
|
||||
include(result, writer, req, res, defaultEncoding);
|
||||
include(result, writer, req, res, encodingForInclude);
|
||||
} catch (ServletException | IOException e) {
|
||||
LOG.warn("Exception thrown during include of {}", result, e);
|
||||
}
|
||||
@@ -209,7 +229,7 @@ public class Include extends Component {
|
||||
}
|
||||
|
||||
public void addParameter(String key, Object value) {
|
||||
// don't use the default implementation of addParameter,
|
||||
// Don't use the default implementation of addParameter,
|
||||
// instead, include tag requires that each parameter be a list of objects,
|
||||
// just like the HTTP servlet interfaces are (String[])
|
||||
if (value != null) {
|
||||
@@ -256,7 +276,7 @@ public class Include extends Component {
|
||||
// Use given encoding
|
||||
pageResponse.getContent().writeTo(writer, encoding);
|
||||
} else {
|
||||
//use the platform specific encoding
|
||||
// Use the platform specific encoding
|
||||
pageResponse.getContent().writeTo(writer, systemEncoding);
|
||||
}
|
||||
}
|
||||
@@ -349,9 +369,9 @@ public class Include extends Component {
|
||||
* @throws IOException
|
||||
*/
|
||||
public FastByteArrayOutputStream getContent() throws IOException {
|
||||
//if we are using a writer, we need to flush the
|
||||
//data to the underlying outputstream.
|
||||
//most containers do this - but it seems Jetty 4.0.5 doesn't
|
||||
// If we are using a writer, we need to flush the
|
||||
// data to the underlying outputstream.
|
||||
// Most containers do this - but it seems Jetty 4.0.5 doesn't
|
||||
if (pagePrintWriter != null) {
|
||||
pagePrintWriter.flush();
|
||||
}
|
||||
|
||||
@@ -140,4 +140,19 @@ public class OptGroup extends Component {
|
||||
public void setListValue(String listValue) {
|
||||
internalUiBean.setListValue(listValue);
|
||||
}
|
||||
|
||||
@StrutsTagAttribute(description = "Property of list objects to get css class from")
|
||||
public void setListCssClass(String listCssClass) {
|
||||
internalUiBean.setListCssClass(listCssClass);
|
||||
}
|
||||
|
||||
@StrutsTagAttribute(description = "Property of list objects to get css style from")
|
||||
public void setListCssStyle(String listCssStyle) {
|
||||
internalUiBean.setListCssStyle(listCssStyle);
|
||||
}
|
||||
|
||||
@StrutsTagAttribute(description = "Property of list objects to get title from")
|
||||
public void setListTitle(String listTitle) {
|
||||
internalUiBean.setListTitle(listTitle);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,6 +83,7 @@ import com.opensymphony.xwork2.util.ValueStack;
|
||||
public class Set extends ContextBean {
|
||||
protected String scope;
|
||||
protected String value;
|
||||
protected boolean trimBody = true;
|
||||
|
||||
public Set(ValueStack stack) {
|
||||
super(stack);
|
||||
@@ -136,6 +137,11 @@ public class Set extends ContextBean {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@StrutsTagAttribute(description="Set to false to prevent the default whitespace-trim of this tag's body content", type="Boolean", defaultValue="true")
|
||||
public void setTrimBody(boolean trimBody) {
|
||||
this.trimBody = trimBody;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean usesBody() {
|
||||
return true;
|
||||
|
||||
@@ -97,6 +97,10 @@ public class DefaultDispatcherErrorHandler implements DispatcherErrorHandler {
|
||||
response.sendError(code, e.getMessage());
|
||||
} catch (IOException e1) {
|
||||
// we're already sending an error, not much else we can do if more stuff breaks
|
||||
LOG.warn("Unable to send error response, code: {};", code, e1);
|
||||
} catch (IllegalStateException ise) {
|
||||
// Log illegalstate instead of passing unrecoverable exception to calling thread
|
||||
LOG.warn("Unable to send error response, code: {}; isCommited: {};", code, response.isCommitted(), ise);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,6 +126,10 @@ public class DefaultDispatcherErrorHandler implements DispatcherErrorHandler {
|
||||
response.sendError(code, "Unable to show problem report:\n" + exp + "\n\n" + LocationUtils.getLocation(exp));
|
||||
} catch (IOException ex) {
|
||||
// we're already sending an error, not much else we can do if more stuff breaks
|
||||
LOG.warn("Unable to send error response, code: {};", code, ex);
|
||||
} catch (IllegalStateException ise) {
|
||||
// Log illegalstate instead of passing unrecoverable exception to calling thread
|
||||
LOG.warn("Unable to send error response, code: {}; isCommited: {};", code, response.isCommitted(), ise);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,7 +218,15 @@ public class DefaultStaticContentLoader implements StaticContentLoader {
|
||||
}
|
||||
}
|
||||
|
||||
response.sendError(HttpServletResponse.SC_NOT_FOUND);
|
||||
try {
|
||||
response.sendError(HttpServletResponse.SC_NOT_FOUND);
|
||||
} catch (IOException e1) {
|
||||
// we're already sending an error, not much else we can do if more stuff breaks
|
||||
LOG.warn("Unable to send error response, code: {};", HttpServletResponse.SC_NOT_FOUND, e1);
|
||||
} catch (IllegalStateException ise) {
|
||||
// Log illegalstate instead of passing unrecoverable exception to calling thread
|
||||
LOG.warn("Unable to send error response, code: {}; isCommited: {};", HttpServletResponse.SC_NOT_FOUND, response.isCommitted(), ise);
|
||||
}
|
||||
}
|
||||
|
||||
protected void process(InputStream is, String path, HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
|
||||
@@ -85,7 +85,7 @@ public class Dispatcher {
|
||||
*/
|
||||
public static final String REQUEST_POST_METHOD = "POST";
|
||||
|
||||
public static final String MULTIPART_FORM_DATA_REGEX = "^multipart/form-data(; boundary=[0-9a-zA-Z'()+_,\\-./:=?]{1,70})?(;charset=[a-zA-Z\\-0-9]{3,14})?";
|
||||
public static final String MULTIPART_FORM_DATA_REGEX = "^multipart/form-data(?:\\s*;\\s*boundary=[0-9a-zA-Z'()+_,\\-./:=?]{1,70})?(?:\\s*;\\s*charset=[a-zA-Z\\-0-9]{3,14})?";
|
||||
|
||||
/**
|
||||
* Provide a thread local instance.
|
||||
@@ -582,8 +582,10 @@ public class Dispatcher {
|
||||
logConfigurationException(request, e);
|
||||
sendError(request, response, HttpServletResponse.SC_NOT_FOUND, e);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
if (handleException || devMode) {
|
||||
if (devMode) {
|
||||
LOG.debug("Dispatcher serviceAction failed", e);
|
||||
}
|
||||
sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
|
||||
} else {
|
||||
throw new ServletException(e);
|
||||
|
||||
@@ -197,5 +197,28 @@ public class HttpParameters implements Map<String, Parameter>, Cloneable {
|
||||
|
||||
return new HttpParameters(parameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Alternate Builder method which avoids wrapping any parameters that are already
|
||||
* a {@link Parameter} element within another {@link Parameter} wrapper.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public HttpParameters buildNoNestedWrapping() {
|
||||
Map<String, Parameter> parameters = (parent == null)
|
||||
? new HashMap<String, Parameter>()
|
||||
: new HashMap<>(parent.parameters);
|
||||
|
||||
for (Map.Entry<String, Object> entry : requestParameterMap.entrySet()) {
|
||||
String name = entry.getKey();
|
||||
Object value = entry.getValue();
|
||||
Parameter parameterValue = (value instanceof Parameter)
|
||||
? (Parameter) value
|
||||
: new Parameter.Request(name, value);
|
||||
parameters.put(name, parameterValue);
|
||||
}
|
||||
|
||||
return new HttpParameters(parameters);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,7 +31,6 @@ import org.apache.logging.log4j.Logger;
|
||||
import org.apache.struts2.RequestUtils;
|
||||
import org.apache.struts2.ServletActionContext;
|
||||
import org.apache.struts2.StrutsConstants;
|
||||
import org.apache.struts2.StrutsException;
|
||||
import org.apache.struts2.util.PrefixTrie;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
@@ -117,6 +116,10 @@ public class DefaultActionMapper implements ActionMapper {
|
||||
protected boolean allowSlashesInActionNames = false;
|
||||
protected boolean alwaysSelectFullNamespace = false;
|
||||
protected PrefixTrie prefixTrie = null;
|
||||
|
||||
protected Pattern allowedNamespaceNames = Pattern.compile("[a-zA-Z0-9._/\\-]*");
|
||||
protected String defaultNamespaceName = "/";
|
||||
|
||||
protected Pattern allowedActionNames = Pattern.compile("[a-zA-Z0-9._!/\\-]*");
|
||||
protected String defaultActionName = "index";
|
||||
|
||||
@@ -202,6 +205,16 @@ public class DefaultActionMapper implements ActionMapper {
|
||||
this.alwaysSelectFullNamespace = BooleanUtils.toBoolean(alwaysSelectFullNamespace);
|
||||
}
|
||||
|
||||
@Inject(value = StrutsConstants.STRUTS_ALLOWED_NAMESPACE_NAMES, required = false)
|
||||
public void setAllowedNamespaceNames(String allowedNamespaceNames) {
|
||||
this.allowedNamespaceNames = Pattern.compile(allowedNamespaceNames);
|
||||
}
|
||||
|
||||
@Inject(value = StrutsConstants.STRUTS_DEFAULT_NAMESPACE_NAME, required = false)
|
||||
public void setDefaultNamespaceName(String defaultNamespaceName) {
|
||||
this.defaultNamespaceName = defaultNamespaceName;
|
||||
}
|
||||
|
||||
@Inject(value = StrutsConstants.STRUTS_ALLOWED_ACTION_NAMES, required = false)
|
||||
public void setAllowedActionNames(String allowedActionNames) {
|
||||
this.allowedActionNames = Pattern.compile(allowedActionNames);
|
||||
@@ -389,10 +402,28 @@ public class DefaultActionMapper implements ActionMapper {
|
||||
}
|
||||
}
|
||||
|
||||
mapping.setNamespace(namespace);
|
||||
mapping.setNamespace(cleanupNamespaceName(namespace));
|
||||
mapping.setName(cleanupActionName(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks namespace name against allowed pattern if not matched returns default namespace
|
||||
*
|
||||
* @param rawNamespace name extracted from URI
|
||||
* @return safe namespace name
|
||||
*/
|
||||
protected String cleanupNamespaceName(final String rawNamespace) {
|
||||
if (allowedNamespaceNames.matcher(rawNamespace).matches()) {
|
||||
return rawNamespace;
|
||||
} else {
|
||||
LOG.warn(
|
||||
"{} did not match allowed namespace names {} - default namespace {} will be used!",
|
||||
rawNamespace, allowedNamespaceNames, defaultNamespaceName
|
||||
);
|
||||
return defaultNamespaceName;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks action name against allowed pattern if not matched returns default action name
|
||||
*
|
||||
|
||||
+8
-8
@@ -74,6 +74,8 @@ import java.util.Map;
|
||||
public class ActionMappingParametersInterceptor extends ParametersInterceptor {
|
||||
|
||||
/**
|
||||
* Get the parameter map from ActionMapping associated with the provided ActionContext.
|
||||
*
|
||||
* @param ac The action context
|
||||
* @return the parameters from the action mapping in the context. If none found, returns an empty map.
|
||||
*/
|
||||
@@ -81,27 +83,25 @@ public class ActionMappingParametersInterceptor extends ParametersInterceptor {
|
||||
protected HttpParameters retrieveParameters(ActionContext ac) {
|
||||
ActionMapping mapping = (ActionMapping) ac.get(ServletActionContext.ACTION_MAPPING);
|
||||
if (mapping != null) {
|
||||
return HttpParameters.create(mapping.getParams()).build();
|
||||
return HttpParameters.create(mapping.getParams()).buildNoNestedWrapping();
|
||||
} else {
|
||||
return HttpParameters.create().build();
|
||||
return HttpParameters.create().buildNoNestedWrapping();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the parameters into context's ParameterMap
|
||||
* Adds the parameters into the current ActionContext's parameter map.
|
||||
*
|
||||
* Note: The method should avoid re-wrapping values which are already of type Parameter.
|
||||
*
|
||||
* @param ac The action context
|
||||
* @param newParams The parameter map to apply
|
||||
* <p>
|
||||
* In this class this is a no-op, since the parameters were fetched from the same location.
|
||||
* In subclasses both retrieveParameters() and addParametersToContext() should be overridden.
|
||||
* </p>
|
||||
*/
|
||||
@Override
|
||||
protected void addParametersToContext(ActionContext ac, Map<String, ?> newParams) {
|
||||
HttpParameters previousParams = ac.getParameters();
|
||||
HttpParameters.Builder combinedParams = HttpParameters.create().withParent(previousParams).withExtraParams(newParams);
|
||||
|
||||
ac.setParameters(combinedParams.build());
|
||||
ac.setParameters(combinedParams.buildNoNestedWrapping());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -261,6 +261,7 @@ public class I18nInterceptor extends AbstractInterceptor {
|
||||
super(invocation);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Locale find() {
|
||||
Locale requestOnlyLocale = super.find();
|
||||
|
||||
@@ -281,15 +282,13 @@ public class I18nInterceptor extends AbstractInterceptor {
|
||||
|
||||
@Override
|
||||
public Locale store(ActionInvocation invocation, Locale locale) {
|
||||
HttpSession session = ServletActionContext.getRequest().getSession(false);
|
||||
Map<String, Object> session = invocation.getInvocationContext().getSession();
|
||||
|
||||
if (session != null) {
|
||||
String sessionId = session.getId();
|
||||
String sessionId = ServletActionContext.getRequest().getSession().getId();
|
||||
synchronized (sessionId.intern()) {
|
||||
invocation.getInvocationContext().getSession().put(attributeName, locale);
|
||||
session.put(attributeName, locale);
|
||||
}
|
||||
} else {
|
||||
LOG.debug("session creation avoided as it doesn't exist already");
|
||||
}
|
||||
|
||||
return locale;
|
||||
|
||||
@@ -29,7 +29,7 @@ import java.util.Map;
|
||||
/**
|
||||
* Just as the CheckboxInterceptor checks that if only the hidden field is present, so too does this interceptor. If
|
||||
* the "__multiselect_" request parameter is present and its visible counterpart is not, set a new request parameter to an
|
||||
* empty Sting.
|
||||
* empty String.
|
||||
*/
|
||||
public class MultiselectInterceptor extends AbstractInterceptor {
|
||||
private static final long serialVersionUID = 1L;
|
||||
@@ -37,7 +37,7 @@ public class MultiselectInterceptor extends AbstractInterceptor {
|
||||
/**
|
||||
* Just as the CheckboxInterceptor checks that if only the hidden field is present, so too does this interceptor.
|
||||
* If the "__multiselect_" request parameter is present and its visible counterpart is not, set a new request parameter
|
||||
* to an empty Sting.
|
||||
* to an empty String.
|
||||
*
|
||||
* @param ai ActionInvocation
|
||||
* @return the result of the action
|
||||
|
||||
+28
-4
@@ -112,6 +112,20 @@ public class TokenSessionStoreInterceptor extends TokenInterceptor {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles processing of invalid tokens. If a previously stored invocation is
|
||||
* available, the method will attempt to return and render its result. Otherwise
|
||||
* it will return INVALID_TOKEN_CODE.
|
||||
*
|
||||
* Note: Because a stored (previously completed) invocation's PageContext will be closed,
|
||||
* this method must replace the stored PageContext with the current invocation's one (or a null).
|
||||
* See {@link org.apache.struts2.util.InvocationSessionStore#loadInvocation(String key, String token)} for details.
|
||||
*
|
||||
* @param invocation
|
||||
*
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
@Override
|
||||
protected String handleInvalidToken(ActionInvocation invocation) throws Exception {
|
||||
ActionContext ac = invocation.getInvocationContext();
|
||||
@@ -126,11 +140,11 @@ public class TokenSessionStoreInterceptor extends TokenInterceptor {
|
||||
params.remove(tokenName);
|
||||
params.remove(TokenHelper.TOKEN_NAME_FIELD);
|
||||
|
||||
String sessionTokenName = TokenHelper.buildTokenSessionAttributeName(tokenName);
|
||||
String sessionTokenName = TokenHelper.buildTokenSessionAttributeName(tokenName);
|
||||
ActionInvocation savedInvocation = InvocationSessionStore.loadInvocation(sessionTokenName, token);
|
||||
|
||||
if (savedInvocation != null) {
|
||||
// set the valuestack to the request scope
|
||||
// set the savedInvocation's valuestack to the request scope
|
||||
ValueStack stack = savedInvocation.getStack();
|
||||
request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack);
|
||||
|
||||
@@ -153,13 +167,23 @@ public class TokenSessionStoreInterceptor extends TokenInterceptor {
|
||||
return INVALID_TOKEN_CODE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles processing of valid tokens. Stores the current invocation for
|
||||
* later use by {@link handleInvalidToken}.
|
||||
* See {@link org.apache.struts2.util.InvocationSessionStore#storeInvocation(String key, String token, ActionInvocation invocation)} for details.
|
||||
*
|
||||
* @param invocation
|
||||
*
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
@Override
|
||||
protected String handleValidToken(ActionInvocation invocation) throws Exception {
|
||||
// we know the token name and token must be there
|
||||
String key = TokenHelper.getTokenName();
|
||||
String token = TokenHelper.getToken(key);
|
||||
String sessionTokenName = TokenHelper.buildTokenSessionAttributeName(key);
|
||||
InvocationSessionStore.storeInvocation(sessionTokenName, token, invocation);
|
||||
String sessionTokenName = TokenHelper.buildTokenSessionAttributeName(key);
|
||||
InvocationSessionStore.storeInvocation(sessionTokenName, token, invocation);
|
||||
|
||||
return invocation.invoke();
|
||||
}
|
||||
|
||||
@@ -134,6 +134,7 @@ public class PostbackResult extends StrutsResultSupport {
|
||||
|
||||
if (actionName != null) {
|
||||
actionName = conditionalParse(actionName, invocation);
|
||||
parseLocation = false;
|
||||
if (namespace == null) {
|
||||
namespace = invocation.getProxy().getNamespace();
|
||||
} else {
|
||||
|
||||
@@ -159,6 +159,7 @@ public class ServletActionRedirectResult extends ServletRedirectResult implement
|
||||
*/
|
||||
public void execute(ActionInvocation invocation) throws Exception {
|
||||
actionName = conditionalParse(actionName, invocation);
|
||||
parseLocation = false;
|
||||
if (namespace == null) {
|
||||
namespace = invocation.getProxy().getNamespace();
|
||||
} else {
|
||||
|
||||
@@ -250,13 +250,24 @@ public class ServletRedirectResult extends StrutsResultSupport implements Reflec
|
||||
* @throws IOException in case of IO errors
|
||||
*/
|
||||
protected void sendRedirect(HttpServletResponse response, String finalLocation) throws IOException {
|
||||
if (SC_FOUND == statusCode) {
|
||||
response.sendRedirect(finalLocation);
|
||||
} else {
|
||||
response.setStatus(statusCode);
|
||||
response.setHeader("Location", finalLocation);
|
||||
response.getWriter().write(finalLocation);
|
||||
response.getWriter().close();
|
||||
try {
|
||||
if (SC_FOUND == statusCode) {
|
||||
response.sendRedirect(finalLocation);
|
||||
} else {
|
||||
response.setStatus(statusCode);
|
||||
response.setHeader("Location", finalLocation);
|
||||
try {
|
||||
response.getWriter().write(finalLocation);
|
||||
} finally {
|
||||
response.getWriter().close();
|
||||
}
|
||||
}
|
||||
} catch (IOException ioe) {
|
||||
LOG.warn("Unable to redirect to: {}, code: {}; {}", finalLocation, statusCode, ioe);
|
||||
throw ioe; // Re-throw required to preserve existing default behaviour (no stacktrace in above warn for this reason)
|
||||
} catch (IllegalStateException ise) {
|
||||
LOG.warn("Unable to redirect to: {}, code: {}; isCommited: {}; {}", finalLocation, statusCode, response.isCommitted(), ise);
|
||||
throw ise; // Re-throw required to preserve existing default behaviour (no stacktrace in above warn for this reason)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -122,6 +122,8 @@ public abstract class StrutsResultSupport implements Result, StrutsStatics {
|
||||
/** use UTF-8 as this is the recommended encoding by W3C to avoid incompatibilities. */
|
||||
public static final String DEFAULT_URL_ENCODING = "UTF-8";
|
||||
|
||||
protected boolean parseLocation = true;
|
||||
|
||||
private boolean parse;
|
||||
private boolean encode;
|
||||
private String location;
|
||||
@@ -200,7 +202,7 @@ public abstract class StrutsResultSupport implements Result, StrutsStatics {
|
||||
* @throws Exception if an error occurs while executing the result.
|
||||
*/
|
||||
public void execute(ActionInvocation invocation) throws Exception {
|
||||
lastFinalLocation = conditionalParse(location, invocation);
|
||||
lastFinalLocation = parseLocation ? conditionalParse(location, invocation) : location;
|
||||
doExecute(lastFinalLocation, invocation);
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,9 @@
|
||||
*/
|
||||
package org.apache.struts2.util;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import javax.servlet.jsp.JspWriter;
|
||||
import java.io.*;
|
||||
import java.nio.ByteBuffer;
|
||||
@@ -35,6 +38,9 @@ import java.util.LinkedList;
|
||||
*
|
||||
*/
|
||||
public class FastByteArrayOutputStream extends OutputStream {
|
||||
|
||||
private static final Logger LOG = LogManager.getLogger(FastByteArrayOutputStream.class);
|
||||
|
||||
private static final int DEFAULT_BLOCK_SIZE = 8192;
|
||||
|
||||
private LinkedList<byte[]> buffers;
|
||||
@@ -144,7 +150,7 @@ public class FastByteArrayOutputStream extends OutputStream {
|
||||
// Append bytes to current buffer
|
||||
// Previous data maybe partially decoded, this part will appended to previous
|
||||
in.put(bytes, 0, length);
|
||||
// To begin of data
|
||||
// To begin processing of data
|
||||
in.flip();
|
||||
decodeAndWriteBuffered(writer, in, out, decoder, endOfInput);
|
||||
}
|
||||
@@ -158,7 +164,7 @@ public class FastByteArrayOutputStream extends OutputStream {
|
||||
if (in.hasRemaining()) {
|
||||
// Move remaining to top of buffer
|
||||
in.compact();
|
||||
if (result.isOverflow() && !result.isError() && !result.isMalformed()) {
|
||||
if (result.isOverflow() && !result.isError()) { // isError covers isMalformed and isUnmappable
|
||||
// Not all buffer chars decoded, spin it again
|
||||
// Set to begin
|
||||
in.flip();
|
||||
@@ -167,16 +173,24 @@ public class FastByteArrayOutputStream extends OutputStream {
|
||||
// Clean up buffer
|
||||
in.clear();
|
||||
}
|
||||
} while (in.hasRemaining() && result.isOverflow() && !result.isError() && !result.isMalformed());
|
||||
} while (in.hasRemaining() && result.isOverflow() && !result.isError()); // isError covers isMalformed and isUnmappable
|
||||
|
||||
if (result.isError()) {
|
||||
if (LOG.isWarnEnabled()) {
|
||||
// Provide a log warning when the decoding fails (prior to 2.5.19 it failed silently).
|
||||
// Note: Set FastByteArrayOutputStream's Logger level to error or higher to suppress this log warning.
|
||||
LOG.warn("Buffer decoding-in-to-out [{}] failed, coderResult [{}]", decoder.charset().name(), result.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static CoderResult decodeAndWrite(Writer writer, ByteBuffer in, CharBuffer out, CharsetDecoder decoder, boolean endOfInput) throws IOException {
|
||||
CoderResult result = decoder.decode(in, out, endOfInput);
|
||||
// To begin of decoded data
|
||||
// To begin processing of decoded data
|
||||
out.flip();
|
||||
// Output
|
||||
writer.write(out.toString());
|
||||
// clear output to avoid infinitive loops, see WW-4383
|
||||
// Clear output to avoid infinite loops, see WW-4383
|
||||
out.clear();
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ package org.apache.struts2.util;
|
||||
|
||||
import com.opensymphony.xwork2.ActionContext;
|
||||
import com.opensymphony.xwork2.ActionInvocation;
|
||||
import org.apache.struts2.ServletActionContext;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.HashMap;
|
||||
@@ -55,11 +56,20 @@ public class InvocationSessionStore {
|
||||
return null;
|
||||
}
|
||||
|
||||
ActionInvocation savedInvocation = null;
|
||||
if (invocationContext.invocation != null) {
|
||||
savedInvocation = invocationContext.invocation;
|
||||
ActionContext.setContext(savedInvocation.getInvocationContext());
|
||||
ActionContext.getContext().setValueStack(savedInvocation.getStack());
|
||||
final ActionInvocation savedInvocation = invocationContext.invocation;
|
||||
if (savedInvocation != null) {
|
||||
// WW-5026 - Preserve the previous PageContext (even if null) and restore it to the
|
||||
// ActionContext after loading the savedInvocation context. The saved context's PageContext
|
||||
// would already be closed at this point (causing failures if used for output).
|
||||
final ActionContext savedActionContext = savedInvocation.getInvocationContext();
|
||||
final ActionContext previousActionContext = ActionContext.getContext();
|
||||
ActionContext.setContext(savedActionContext);
|
||||
savedActionContext.setValueStack(savedInvocation.getStack());
|
||||
if (previousActionContext != null) {
|
||||
savedActionContext.put(ServletActionContext.PAGE_CONTEXT, previousActionContext.get(ServletActionContext.PAGE_CONTEXT));
|
||||
} else {
|
||||
savedActionContext.put(ServletActionContext.PAGE_CONTEXT, null);
|
||||
}
|
||||
}
|
||||
|
||||
return savedInvocation;
|
||||
|
||||
@@ -81,7 +81,7 @@ public class JBossFileManager extends DefaultFileManager {
|
||||
|
||||
@Override
|
||||
public void monitorFile(URL fileUrl) {
|
||||
if (isJBossUrl(fileUrl)) {
|
||||
if (reloadingConfigs && isJBossUrl(fileUrl)) {
|
||||
String fileName = fileUrl.toString();
|
||||
LOG.debug("Creating revision for URL: {}", fileName);
|
||||
URL normalizedUrl = normalizeToFileProtocol(fileUrl);
|
||||
|
||||
@@ -35,6 +35,7 @@ public class SetTag extends ContextBeanTag {
|
||||
|
||||
protected String scope;
|
||||
protected String value;
|
||||
protected boolean trimBody = true;
|
||||
|
||||
public Component getBean(ValueStack stack, HttpServletRequest req, HttpServletResponse res) {
|
||||
return new Set(stack);
|
||||
@@ -59,4 +60,17 @@ public class SetTag extends ContextBeanTag {
|
||||
public void setValue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public void setTrimBody(boolean trimBody) {
|
||||
this.trimBody = trimBody;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getBody() {
|
||||
if (trimBody) {
|
||||
return super.getBody();
|
||||
} else {
|
||||
return (bodyContent == null ? "" : bodyContent.getString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,12 +23,16 @@ import ognl.OgnlException;
|
||||
|
||||
import com.opensymphony.xwork2.inject.Inject;
|
||||
import com.opensymphony.xwork2.ognl.OgnlUtil;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
/**
|
||||
* FIXME: remove?
|
||||
*/
|
||||
public class OgnlTool {
|
||||
|
||||
private static final Logger LOG = LogManager.getLogger(OgnlTool.class);
|
||||
|
||||
private OgnlUtil ognlUtil;
|
||||
|
||||
public OgnlTool() {
|
||||
@@ -43,6 +47,9 @@ public class OgnlTool {
|
||||
try {
|
||||
return Ognl.getValue(ognlUtil.compile(expr), context);
|
||||
} catch (OgnlException e) {
|
||||
if (e.getReason() instanceof SecurityException) {
|
||||
LOG.warn("Could not evaluate this expression due to security constraints: [{}]", expr, e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +36,9 @@ public class OptGroupTag extends ComponentTagSupport {
|
||||
protected String disabled;
|
||||
protected String listKey;
|
||||
protected String listValue;
|
||||
protected String listCssClass;
|
||||
protected String listCssStyle;
|
||||
protected String listTitle;
|
||||
|
||||
public Component getBean(ValueStack stack, HttpServletRequest req, HttpServletResponse res) {
|
||||
return new OptGroup(stack, req, res);
|
||||
@@ -50,6 +53,9 @@ public class OptGroupTag extends ComponentTagSupport {
|
||||
optGroup.setDisabled(disabled);
|
||||
optGroup.setListKey(listKey);
|
||||
optGroup.setListValue(listValue);
|
||||
optGroup.setListCssClass(listCssClass);
|
||||
optGroup.setListCssStyle(listCssStyle);
|
||||
optGroup.setListTitle(listTitle);
|
||||
}
|
||||
|
||||
public void setList(String list) {
|
||||
@@ -71,4 +77,16 @@ public class OptGroupTag extends ComponentTagSupport {
|
||||
public void setListValue(String listValue) {
|
||||
this.listValue = listValue;
|
||||
}
|
||||
|
||||
public void setListCssClass(String listCssClass) {
|
||||
this.listCssClass = listCssClass;
|
||||
}
|
||||
|
||||
public void setListCssStyle(String listCssStyle) {
|
||||
this.listCssStyle = listCssStyle;
|
||||
}
|
||||
|
||||
public void setListTitle(String listTitle) {
|
||||
this.listTitle = listTitle;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -219,4 +219,8 @@ struts.ognl.enableExpressionCache=true
|
||||
### Indicates if Dispatcher should handle unexpected exceptions by calling sendError()
|
||||
### or simply rethrow it as a ServletException to allow future processing by other frameworks like Spring Security
|
||||
struts.handle.exception=true
|
||||
|
||||
### applies maximum length allowed on OGNL expressions for security enhancement
|
||||
struts.ognl.expressionMaxLength=200
|
||||
|
||||
### END SNIPPET: complete_file
|
||||
|
||||
@@ -45,12 +45,7 @@
|
||||
java.lang.ClassLoader,
|
||||
java.lang.Shutdown,
|
||||
java.lang.ProcessBuilder,
|
||||
ognl.OgnlContext,
|
||||
ognl.ClassResolver,
|
||||
ognl.TypeConverter,
|
||||
ognl.MemberAccess,
|
||||
ognl.DefaultMemberAccess,
|
||||
com.opensymphony.xwork2.ognl.SecurityMemberAccess,
|
||||
sun.misc.Unsafe,
|
||||
com.opensymphony.xwork2.ActionContext" />
|
||||
|
||||
<!-- this must be valid regex, each '.' in package name must be escaped! -->
|
||||
@@ -60,15 +55,25 @@
|
||||
<!-- this is simpler version of the above used with string comparison -->
|
||||
<constant name="struts.excludedPackageNames"
|
||||
value="
|
||||
java.lang.,
|
||||
ognl.,
|
||||
javax,
|
||||
java.io.,
|
||||
java.net.,
|
||||
java.nio.,
|
||||
javax.,
|
||||
freemarker.core.,
|
||||
freemarker.template.,
|
||||
freemarker.ext.jsp.,
|
||||
freemarker.ext.rhino.,
|
||||
freemarker.ext.beans.,
|
||||
sun.misc.,
|
||||
sun.reflect.,
|
||||
javassist." />
|
||||
javassist.,
|
||||
org.apache.velocity.,
|
||||
org.objectweb.asm.,
|
||||
org.springframework.context.,
|
||||
com.opensymphony.xwork2.inject.,
|
||||
com.opensymphony.xwork2.ognl.,
|
||||
com.opensymphony.xwork2.security.,
|
||||
com.opensymphony.xwork2.util." />
|
||||
|
||||
<bean class="com.opensymphony.xwork2.ObjectFactory" name="struts"/>
|
||||
<bean type="com.opensymphony.xwork2.factory.ResultFactory" name="struts" class="org.apache.struts2.factory.StrutsResultFactory" />
|
||||
|
||||
@@ -21,27 +21,47 @@
|
||||
<#if parameters.optGroupInternalListUiBeanList??>
|
||||
<#assign optGroupInternalListUiBeans=parameters.optGroupInternalListUiBeanList />
|
||||
<#list optGroupInternalListUiBeans as optGroupInternalListUiBean>
|
||||
<optgroup
|
||||
<optgroup<#rt>
|
||||
<#if optGroupInternalListUiBean.parameters.label?has_content>
|
||||
label="${optGroupInternalListUiBean.parameters.label}"
|
||||
label="${optGroupInternalListUiBean.parameters.label}"<#rt>
|
||||
</#if>
|
||||
<#if optGroupInternalListUiBean.parameters.disabled!false>
|
||||
disabled="disabled"
|
||||
disabled="disabled"<#rt>
|
||||
</#if>
|
||||
<#include "/${parameters.templateDir}/${parameters.expandTheme}/dynamic-attributes.ftl" />
|
||||
>
|
||||
|
||||
<#list optGroupInternalListUiBean.parameters.list as optGroupBean>
|
||||
<#assign trash=stack.push(optGroupBean) />
|
||||
<#assign tmpKey=stack.findValue(optGroupInternalListUiBean.parameters.listKey) />
|
||||
<#assign tmpValue=stack.findValue(optGroupInternalListUiBean.parameters.listValue) />
|
||||
<#assign tmpKeyStr = tmpKey.toString() />
|
||||
<option value="${tmpKeyStr?html}"
|
||||
<#if tag.contains(parameters.nameValue, tmpKey) == true>
|
||||
selected="selected"
|
||||
<#assign optGroupItemCssClass = ''/>
|
||||
<#if optGroupInternalListUiBean.parameters.listCssClass??>
|
||||
<#assign optGroupItemCssClass= stack.findString(optGroupInternalListUiBean.parameters.listCssClass)!''/>
|
||||
</#if>
|
||||
>${tmpValue?html}
|
||||
</option>
|
||||
<#assign optGroupItemCssStyle = ''/>
|
||||
<#if optGroupInternalListUiBean.parameters.listCssStyle??>
|
||||
<#assign optGroupItemCssStyle= stack.findString(optGroupInternalListUiBean.parameters.listCssStyle)!''/>
|
||||
</#if>
|
||||
<#assign optGroupItemTitle = ''/>
|
||||
<#if optGroupInternalListUiBean.parameters.listTitle??>
|
||||
<#assign optGroupItemTitle= stack.findString(optGroupInternalListUiBean.parameters.listTitle)!''/>
|
||||
</#if>
|
||||
<option value="${tmpKeyStr?html}"<#rt>
|
||||
<#if tag.contains(parameters.nameValue, tmpKey) == true>
|
||||
selected="selected"<#rt>
|
||||
</#if>
|
||||
<#if optGroupItemCssClass?has_content>
|
||||
class="${optGroupItemCssClass?html}"<#rt/>
|
||||
</#if>
|
||||
<#if optGroupItemCssStyle?has_content>
|
||||
style="${optGroupItemCssStyle?html}"<#rt/>
|
||||
</#if>
|
||||
<#if optGroupItemTitle?has_content>
|
||||
title="${optGroupItemTitle?html}"<#rt/>
|
||||
</#if>
|
||||
>${tmpValue?html}<#t>
|
||||
</option><#lt>
|
||||
<#assign trash=stack.pop() />
|
||||
</#list>
|
||||
</optgroup>
|
||||
|
||||
@@ -29,9 +29,12 @@
|
||||
<#if parameters.listValueKey??>
|
||||
<#-- checks the valueStack for the 'valueKey.' The valueKey is then looked-up in the locale
|
||||
file for it's localized value. This is then used as a label -->
|
||||
<#assign itemValue = stack.findString(parameters.listValueKey)/>
|
||||
<#-- FIXME: find a better way to get the value than a call to @s.text -->
|
||||
<#assign itemValue><@s.text name="${itemValue}"/></#assign>
|
||||
<#assign valueKey = stack.findString(parameters.listValueKey)!''/>
|
||||
<#if valueKey?has_content>
|
||||
<#assign itemValue = struts.getText(valueKey) />
|
||||
<#else>
|
||||
<#assign itemValue = parameters.listValueKey />
|
||||
</#if>
|
||||
<#elseif parameters.listValue??>
|
||||
<#assign itemValue = stack.findString(parameters.listValue)/>
|
||||
<#else>
|
||||
|
||||
@@ -70,8 +70,8 @@
|
||||
<#if parameters.listValueKey??>
|
||||
<#-- checks the valueStack for the 'valueKey.' The valueKey is then looked-up in the locale file for it's
|
||||
localized value. This is then used as a label -->
|
||||
<#assign valueKey = stack.findString(parameters.listValueKey) />
|
||||
<#if valueKey??>
|
||||
<#assign valueKey = stack.findString(parameters.listValueKey)!'' />
|
||||
<#if valueKey?has_content>
|
||||
<#assign itemValue = struts.getText(valueKey) />
|
||||
<#else>
|
||||
<#assign itemValue = parameters.listValueKey />
|
||||
|
||||
@@ -57,6 +57,22 @@ Please do not edit it directly.
|
||||
<td align="left" valign="top">String</td>
|
||||
<td align="left" valign="top">Set the list attribute.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="left" valign="top">listCssClass</td>
|
||||
<td align="left" valign="top">false</td>
|
||||
<td align="left" valign="top"></td>
|
||||
<td align="left" valign="top">false</td>
|
||||
<td align="left" valign="top">String</td>
|
||||
<td align="left" valign="top">Property of list objects to get css class from</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="left" valign="top">listCssStyle</td>
|
||||
<td align="left" valign="top">false</td>
|
||||
<td align="left" valign="top"></td>
|
||||
<td align="left" valign="top">false</td>
|
||||
<td align="left" valign="top">String</td>
|
||||
<td align="left" valign="top">Property of list objects to get css style from</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="left" valign="top">listKey</td>
|
||||
<td align="left" valign="top">false</td>
|
||||
@@ -65,6 +81,14 @@ Please do not edit it directly.
|
||||
<td align="left" valign="top">String</td>
|
||||
<td align="left" valign="top">Set the listKey attribute.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="left" valign="top">listTitle</td>
|
||||
<td align="left" valign="top">false</td>
|
||||
<td align="left" valign="top"></td>
|
||||
<td align="left" valign="top">false</td>
|
||||
<td align="left" valign="top">String</td>
|
||||
<td align="left" valign="top">Property of list objects to get title from</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="left" valign="top">listValue</td>
|
||||
<td align="left" valign="top">false</td>
|
||||
|
||||
@@ -41,6 +41,14 @@ Please do not edit it directly.
|
||||
<td align="left" valign="top">String</td>
|
||||
<td align="left" valign="top">The scope in which to assign the variable. Can be <b>application</b>, <b>session</b>, <b>request</b>, <b>page</b>, or <b>action</b>.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="left" valign="top">trimBody</td>
|
||||
<td align="left" valign="top">false</td>
|
||||
<td align="left" valign="top">true</td>
|
||||
<td align="left" valign="top">false</td>
|
||||
<td align="left" valign="top">Boolean</td>
|
||||
<td align="left" valign="top">Set to false to prevent the default whitespace-trim of this tag's body content</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="left" valign="top">value</td>
|
||||
<td align="left" valign="top">false</td>
|
||||
|
||||
+34
-20
@@ -18,31 +18,45 @@
|
||||
*/
|
||||
package com.opensymphony.xwork2.config.providers;
|
||||
|
||||
import org.apache.struts2.StrutsInternalTestCase;
|
||||
import static org.hamcrest.core.Is.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import org.apache.commons.lang3.SystemUtils;
|
||||
import org.apache.struts2.StrutsInternalTestCase;
|
||||
|
||||
public class EnvsValueSubstitutorTest extends StrutsInternalTestCase {
|
||||
|
||||
public void testSimpleValue() throws Exception {
|
||||
// given
|
||||
String expected = System.getenv("USER");
|
||||
ValueSubstitutor substitutor = new EnvsValueSubstitutor();
|
||||
private ValueSubstitutor substitutor;
|
||||
|
||||
// when
|
||||
String actual = substitutor.substitute("${env.USER}");
|
||||
|
||||
// then
|
||||
assertEquals(expected, actual);
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
substitutor = new EnvsValueSubstitutor();
|
||||
}
|
||||
|
||||
public void testNoSubstitution() throws Exception {
|
||||
// given
|
||||
ValueSubstitutor substitutor = new EnvsValueSubstitutor();
|
||||
|
||||
// when
|
||||
String actual = substitutor.substitute("val1");
|
||||
|
||||
// then
|
||||
assertEquals("val1", actual);
|
||||
public void testEnvSimpleValue() {
|
||||
if (SystemUtils.IS_OS_WINDOWS) {
|
||||
assertThat(substitutor.substitute("${env.USERNAME}"), is(System.getenv("USERNAME")));
|
||||
} else {
|
||||
assertThat(substitutor.substitute("${env.USER}"), is(System.getenv("USER")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void testEnvSimpleDefaultValue() {
|
||||
final String defaultValue = "defaultValue";
|
||||
assertThat(substitutor.substitute("${env.UNKNOWN:" + defaultValue + "}"), is(defaultValue));
|
||||
}
|
||||
|
||||
public void testSystemSimpleValue() {
|
||||
final String key = "sysPropKey";
|
||||
final String value = "sysPropValue";
|
||||
System.setProperty(key, value);
|
||||
|
||||
assertThat(substitutor.substitute("${" + key + "}"), is(value));
|
||||
}
|
||||
|
||||
public void testNoSubstitution() {
|
||||
final String value = "val1";
|
||||
assertThat(substitutor.substitute(value), is(value));
|
||||
}
|
||||
}
|
||||
|
||||
+25
-12
@@ -18,29 +18,42 @@
|
||||
*/
|
||||
package com.opensymphony.xwork2.config.providers;
|
||||
|
||||
import com.opensymphony.xwork2.config.ConfigurationException;
|
||||
import com.opensymphony.xwork2.config.ConfigurationProvider;
|
||||
import org.apache.commons.lang3.SystemUtils;
|
||||
import org.apache.struts2.StrutsConstants;
|
||||
|
||||
public class XmlConfigurationProviderEnvsSubstitutionTest extends ConfigurationTestBase {
|
||||
|
||||
public void testSubstitution() throws ConfigurationException {
|
||||
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-envs-substitution.xml";
|
||||
ConfigurationProvider provider = buildConfigurationProvider(filename);
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
|
||||
configurationManager.addContainerProvider(provider);
|
||||
configurationManager.addContainerProvider(buildConfigurationProvider(
|
||||
"com/opensymphony/xwork2/config/providers/xwork-test-envs-substitution.xml"));
|
||||
configurationManager.reload();
|
||||
configuration = configurationManager.getConfiguration();
|
||||
container = configuration.getContainer();
|
||||
}
|
||||
|
||||
String foo = container.getInstance(String.class, "foo");
|
||||
assertEquals("bar", foo);
|
||||
public void testSubstitution() {
|
||||
assertEquals("bar", container.getInstance(String.class, "foo"));
|
||||
|
||||
String user = container.getInstance(String.class, "user");
|
||||
assertEquals(System.getenv("USER"), user);
|
||||
String user;
|
||||
if (SystemUtils.IS_OS_WINDOWS) {
|
||||
user = container.getInstance(String.class, "username");
|
||||
assertEquals(System.getenv("USERNAME"), user);
|
||||
} else {
|
||||
user = container.getInstance(String.class, "user");
|
||||
assertEquals(System.getenv("USER"), user);
|
||||
}
|
||||
|
||||
String home = container.getInstance(String.class, "home");
|
||||
assertEquals("Current HOME = " + System.getenv("HOME"), home);
|
||||
String home;
|
||||
if (SystemUtils.IS_OS_WINDOWS) {
|
||||
home = container.getInstance(String.class, "homedrive.homepath");
|
||||
assertEquals("Current HOMEDRIVE.HOMEPATH = " + System.getenv("HOMEDRIVE") + System.getenv("HOMEPATH"), home);
|
||||
} else {
|
||||
home = container.getInstance(String.class, "home");
|
||||
assertEquals("Current HOME = " + System.getenv("HOME"), home);
|
||||
}
|
||||
|
||||
String os = container.getInstance(String.class, "os");
|
||||
assertEquals("Current OS = " + System.getProperty("os.name"), os);
|
||||
|
||||
+889
-10
@@ -23,18 +23,35 @@ import com.opensymphony.xwork2.ObjectFactory;
|
||||
import com.opensymphony.xwork2.config.ConfigurationProvider;
|
||||
import com.opensymphony.xwork2.config.RuntimeConfiguration;
|
||||
import com.opensymphony.xwork2.config.entities.PackageConfig;
|
||||
import com.opensymphony.xwork2.config.entities.ResultConfig;
|
||||
import com.opensymphony.xwork2.config.entities.ResultTypeConfig;
|
||||
import com.opensymphony.xwork2.config.impl.MockConfiguration;
|
||||
import com.opensymphony.xwork2.util.ClassLoaderUtil;
|
||||
import com.sun.org.apache.xerces.internal.dom.ElementImpl;
|
||||
import org.w3c.dom.Document;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.apache.struts2.result.ServletDispatcherResult;
|
||||
import org.w3c.dom.Attr;
|
||||
import org.w3c.dom.DOMException;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
import org.w3c.dom.TypeInfo;
|
||||
import org.w3c.dom.UserDataHandler;
|
||||
|
||||
|
||||
public class XmlConfigurationProviderTest extends ConfigurationTestBase {
|
||||
@@ -78,12 +95,14 @@ public class XmlConfigurationProviderTest extends ConfigurationTestBase {
|
||||
}
|
||||
|
||||
public void testNeedsReload() throws Exception {
|
||||
container.getInstance(FileManagerFactory.class).setReloadingConfigs("true");
|
||||
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-actions.xml";
|
||||
ConfigurationProvider provider = buildConfigurationProvider(filename);
|
||||
container.getInstance(FileManagerFactory.class).setReloadingConfigs("true");
|
||||
ConfigurationProvider provider = new XmlConfigurationProvider(filename, true);
|
||||
container.inject(provider);
|
||||
provider.init(configuration);
|
||||
provider.loadPackages();
|
||||
container.getInstance(FileManagerFactory.class).getFileManager().setReloadingConfigs(true);
|
||||
|
||||
assertTrue(!provider.needsReload()); // Revision exists and timestamp didn't change
|
||||
assertFalse(provider.needsReload()); // Revision exists and timestamp didn't change
|
||||
|
||||
File file = new File(getClass().getResource("/" + filename).toURI());
|
||||
assertTrue("not exists: " + file.toString(), file.exists());
|
||||
@@ -92,6 +111,54 @@ public class XmlConfigurationProviderTest extends ConfigurationTestBase {
|
||||
assertTrue(provider.needsReload());
|
||||
}
|
||||
|
||||
public void testReload() throws Exception {
|
||||
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-reload.xml";
|
||||
ConfigurationProvider provider = new XmlConfigurationProvider(filename, true);
|
||||
loadConfigurationProviders(provider);
|
||||
|
||||
assertFalse(provider.needsReload()); // Revision exists and timestamp didn't change
|
||||
|
||||
File file = new File(getClass().getResource("/" + filename).toURI());
|
||||
assertTrue("not exists: " + file.toString(), file.exists());
|
||||
|
||||
Path configPath = Paths.get(file.getAbsolutePath());
|
||||
String content = new String(Files.readAllBytes(configPath));
|
||||
content = content.replaceAll("<constant name=\"struts.configuration.xml.reload\" value=\"true\" />",
|
||||
"<constant name=\"struts.configuration.xml.reload\" value=\"false\" />");
|
||||
Files.write(configPath, content.getBytes()); // user demand: stop reloading configs
|
||||
|
||||
try {
|
||||
assertTrue(provider.needsReload()); // config file has changed in previous lines
|
||||
|
||||
configurationManager.reload();
|
||||
|
||||
changeFileTime(file);
|
||||
assertFalse(provider.needsReload()); // user already has stopped reloading configs
|
||||
} finally {
|
||||
content = content.replaceAll("<constant name=\"struts.configuration.xml.reload\" value=\"false\" />",
|
||||
"<constant name=\"struts.configuration.xml.reload\" value=\"true\" />");
|
||||
Files.write(configPath, content.getBytes());
|
||||
}
|
||||
}
|
||||
|
||||
public void testNeedsReloadNotReloadingConfigs() throws Exception {
|
||||
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-actions.xml";
|
||||
buildConfigurationProvider(filename);
|
||||
ConfigurationProvider provider = new XmlConfigurationProvider(filename, true);
|
||||
container.getInstance(FileManagerFactory.class).getFileManager().setReloadingConfigs(false);
|
||||
container.inject(provider);
|
||||
provider.init(configuration);
|
||||
provider.loadPackages();
|
||||
|
||||
assertFalse(provider.needsReload()); // Revision exists and timestamp didn't change
|
||||
|
||||
File file = new File(getClass().getResource("/" + filename).toURI());
|
||||
assertTrue("not exists: " + file.toString(), file.exists());
|
||||
changeFileTime(file);
|
||||
|
||||
assertFalse(provider.needsReload());
|
||||
}
|
||||
|
||||
public void testInheritence() throws Exception {
|
||||
final String filename = "com/opensymphony/xwork2/config/providers/xwork-include-parent.xml";
|
||||
ConfigurationProvider provider = buildConfigurationProvider(filename);
|
||||
@@ -155,10 +222,13 @@ public class XmlConfigurationProviderTest extends ConfigurationTestBase {
|
||||
|
||||
public void testEmptySpaces() throws Exception {
|
||||
final String filename = "com/opensymphony/xwork2/config/providers/xwork- test.xml";
|
||||
ConfigurationProvider provider = new XmlConfigurationProvider(filename, true);
|
||||
container.inject(provider);
|
||||
provider.init(configuration);
|
||||
provider.loadPackages();
|
||||
container.getInstance(FileManagerFactory.class).getFileManager().setReloadingConfigs(true);
|
||||
|
||||
ConfigurationProvider provider = buildConfigurationProvider(filename);
|
||||
assertTrue(!provider.needsReload());
|
||||
assertFalse(provider.needsReload());
|
||||
|
||||
URI uri = ClassLoaderUtil.getResource(filename, ConfigurationProvider.class).toURI();
|
||||
|
||||
@@ -170,8 +240,28 @@ public class XmlConfigurationProviderTest extends ConfigurationTestBase {
|
||||
assertTrue(provider.needsReload());
|
||||
}
|
||||
|
||||
public void testEmptySpacesNotReloadingConfigs() throws Exception {
|
||||
final String filename = "com/opensymphony/xwork2/config/providers/xwork- test.xml";
|
||||
buildConfigurationProvider(filename);
|
||||
ConfigurationProvider provider = new XmlConfigurationProvider(filename, true);
|
||||
container.getInstance(FileManagerFactory.class).getFileManager().setReloadingConfigs(false);
|
||||
container.inject(provider);
|
||||
provider.init(configuration);
|
||||
provider.loadPackages();
|
||||
|
||||
assertFalse(provider.needsReload());
|
||||
|
||||
URI uri = ClassLoaderUtil.getResource(filename, ConfigurationProvider.class).toURI();
|
||||
|
||||
File file = new File(uri);
|
||||
|
||||
assertTrue(file.exists());
|
||||
changeFileTime(file);
|
||||
|
||||
assertFalse(provider.needsReload());
|
||||
}
|
||||
|
||||
public void testConfigsInJarFiles() throws Exception {
|
||||
container.getInstance(FileManagerFactory.class).getFileManager().setReloadingConfigs(true);
|
||||
testProvider("xwork-jar.xml");
|
||||
testProvider("xwork-zip.xml");
|
||||
testProvider("xwork - jar.xml");
|
||||
@@ -185,7 +275,8 @@ public class XmlConfigurationProviderTest extends ConfigurationTestBase {
|
||||
|
||||
private void testProvider(String configFile) throws Exception {
|
||||
ConfigurationProvider provider = buildConfigurationProvider(configFile);
|
||||
assertTrue(!provider.needsReload());
|
||||
container.getInstance(FileManagerFactory.class).getFileManager().setReloadingConfigs(true);
|
||||
assertFalse(provider.needsReload());
|
||||
|
||||
String fullPath = ClassLoaderUtil.getResource(configFile, ConfigurationProvider.class).toString();
|
||||
|
||||
@@ -197,9 +288,9 @@ public class XmlConfigurationProviderTest extends ConfigurationTestBase {
|
||||
File file = new File(jar);
|
||||
|
||||
assertTrue("File [" + file + "] doesn't exist!", file.exists());
|
||||
file.setLastModified(System.currentTimeMillis());
|
||||
changeFileTime(file);
|
||||
|
||||
assertTrue(!provider.needsReload());
|
||||
assertFalse(provider.needsReload());
|
||||
}
|
||||
|
||||
public void testIncludeWithWildcard() throws Exception {
|
||||
@@ -217,4 +308,792 @@ public class XmlConfigurationProviderTest extends ConfigurationTestBase {
|
||||
assertTrue(loadedFileNames.contains("xwork-test-beans.xml"));
|
||||
assertTrue(loadedFileNames.contains("xwork-test-default.xml"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test buildAllowedMethods() to ensure consistent results for processing
|
||||
* <allowed-methods/> in <action/> XML configuration elements.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public void testBuildAllowedMethods() throws Exception {
|
||||
// Test introduced with WW-5029 fix.
|
||||
// Set up test using two mock DOM Elements:
|
||||
// 1) A mock "action" Element with a single "allowed-methods" child Element that contains a single
|
||||
// TEXT_NODE Node. This simulates a typical result from a SAX parser parsing the allowed-methods
|
||||
// tag body.
|
||||
// 2) A mock "action" Element with a single "allowed-methods" child Element that contains multiple
|
||||
// TEXT_NODE Nodes. This simulates an unusal result from a SAX parser parsing the allowed-methods
|
||||
// tag body (as reported with WW-5029).
|
||||
final String fakeBodyString = "allowedMethod1,allowedMethod2,allowedMethod3";
|
||||
PackageConfig.Builder testPackageConfigBuilder = new PackageConfig.Builder("allowedMethodsPackage");
|
||||
List<String> singleStringList = new ArrayList(1);
|
||||
List<String> multipleStringList = new ArrayList(4);
|
||||
singleStringList.add(fakeBodyString);
|
||||
multipleStringList.add("allowedMethod1,");
|
||||
multipleStringList.add("allowed");
|
||||
multipleStringList.add("Method2,");
|
||||
multipleStringList.add("allowedMethod3");
|
||||
NodeList mockNodeListSingleChild = new MockNodeList(singleStringList);
|
||||
NodeList mockNodeListMultipleChild = new MockNodeList(multipleStringList);
|
||||
Element mockSingleChildAllowedMethodsElement = new MockElement("allowed-methods", fakeBodyString,
|
||||
"allowed-methods", fakeBodyString, Node.TEXT_NODE, mockNodeListSingleChild, null);
|
||||
Element mockMultipleChildAllowedMethodsElement = new MockElement("allowed-methods", fakeBodyString,
|
||||
"allowed-methods", fakeBodyString, Node.TEXT_NODE, mockNodeListMultipleChild, null);
|
||||
MockNodeList mockActionElementChildrenSingle = new MockNodeList();
|
||||
mockActionElementChildrenSingle.addToNodeList(mockSingleChildAllowedMethodsElement);
|
||||
MockNodeList mockActionElementChildrenMultiple = new MockNodeList();
|
||||
mockActionElementChildrenMultiple.addToNodeList(mockMultipleChildAllowedMethodsElement);
|
||||
Element mockActionElementSingle = new MockElement("action", "fakeBody", "action", "fakeValue",
|
||||
Node.TEXT_NODE, mockActionElementChildrenSingle, null);
|
||||
Element mockActionElementMultiple = new MockElement("action", "fakeBody", "action", "fakeValue",
|
||||
Node.TEXT_NODE, mockActionElementChildrenMultiple, null);
|
||||
// Attempt the method using both types of Elements (single child and multiple child) and confirm
|
||||
// the result is the same for both. Also confirm the results are as expected.
|
||||
XmlConfigurationProvider prov = new XmlConfigurationProvider("com/opensymphony/xwork2/config/providers/xwork- test.xml", false);
|
||||
Set<String> singleChildResult = prov.buildAllowedMethods(mockActionElementSingle, testPackageConfigBuilder);
|
||||
Set<String> multipleChildResult = prov.buildAllowedMethods(mockActionElementMultiple, testPackageConfigBuilder);
|
||||
assertNotNull("singleChildResult is null ?", singleChildResult);
|
||||
assertNotNull("multipleChildResult is null ?", multipleChildResult);
|
||||
assertEquals("singleChildResult not equal to multipleChildResult ?", singleChildResult, multipleChildResult);
|
||||
// Since both Sets are equal, only need to test one to confirm contents are correct
|
||||
assertEquals("result Sets not of length 3 ?", 3, multipleChildResult.size());
|
||||
assertTrue("allowedMethod1 not present ?", multipleChildResult.contains("allowedMethod1"));
|
||||
assertTrue("allowedMethod2 not present ?", multipleChildResult.contains("allowedMethod2"));
|
||||
assertTrue("allowedMethod3 not present ?", multipleChildResult.contains("allowedMethod3"));
|
||||
assertFalse("noSuchMethod is present ?", multipleChildResult.contains("noSuchMethod"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test loadGlobalAllowedMethods() to ensure consistent results for processing
|
||||
* <global-allowed-methods/> in <package/> XML configuration elements.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public void testLoadGlobalAllowedMethods() throws Exception {
|
||||
// Test introduced with WW-5029 fix.
|
||||
// Set up test using two mock DOM Elements:
|
||||
// 1) A mock "package" Element with a single "global-allowed-methods" child Element that contains a single
|
||||
// TEXT_NODE Node. This simulates a typical result from a SAX parser parsing the global-allowed-methods
|
||||
// tag body.
|
||||
// 2) A mock "package" Element with a single "global-allowed-methods" child Element that contains multiple
|
||||
// TEXT_NODE Nodes. This simulates an unusal result from a SAX parser parsing the global-allowed-methods
|
||||
// tag body (as reported with WW-5029).
|
||||
final String fakeBodyString = "allowedMethod1,allowedMethod2,allowedMethod3";
|
||||
PackageConfig.Builder testPackageConfigBuilder = new PackageConfig.Builder("globalAllowedMethodsPackage");
|
||||
List<String> singleStringList = new ArrayList(1);
|
||||
List<String> multipleStringList = new ArrayList(4);
|
||||
singleStringList.add(fakeBodyString);
|
||||
multipleStringList.add("allowedMethod4,");
|
||||
multipleStringList.add("allowed");
|
||||
multipleStringList.add("Method5,");
|
||||
multipleStringList.add("allowedMethod6");
|
||||
NodeList mockNodeListSingleChild = new MockNodeList(singleStringList);
|
||||
NodeList mockNodeListMultipleChild = new MockNodeList(multipleStringList);
|
||||
Element mockSingleChildAllowedMethodsElement = new MockElement("global-allowed-methods", fakeBodyString,
|
||||
"global-allowed-methods", fakeBodyString, Node.TEXT_NODE, mockNodeListSingleChild, null);
|
||||
Element mockMultipleChildAllowedMethodsElement = new MockElement("global-allowed-methods", fakeBodyString,
|
||||
"global-allowed-methods", fakeBodyString, Node.TEXT_NODE, mockNodeListMultipleChild, null);
|
||||
MockNodeList mockPackageElementChildrenSingle = new MockNodeList();
|
||||
mockPackageElementChildrenSingle.addToNodeList(mockSingleChildAllowedMethodsElement);
|
||||
MockNodeList mockPackageElementChildrenMultiple = new MockNodeList();
|
||||
mockPackageElementChildrenMultiple.addToNodeList(mockMultipleChildAllowedMethodsElement);
|
||||
Element mockPackageElementSingle = new MockElement("package", "fakeBody", "package", "fakeValue",
|
||||
Node.TEXT_NODE, mockPackageElementChildrenSingle, null);
|
||||
Element mockPackageElementMultiple = new MockElement("package", "fakeBody", "package", "fakeValue",
|
||||
Node.TEXT_NODE, mockPackageElementChildrenMultiple, null);
|
||||
// Attempt the method using the single child Element and confirm the result is as expected.
|
||||
XmlConfigurationProvider prov = new XmlConfigurationProvider("com/opensymphony/xwork2/config/providers/xwork- test.xml", false);
|
||||
prov.loadGlobalAllowedMethods(testPackageConfigBuilder, mockPackageElementSingle);
|
||||
Set<String> currentGlobalResult = testPackageConfigBuilder.getGlobalAllowedMethods();
|
||||
assertNotNull("currentGlobalResult is null ?", currentGlobalResult);
|
||||
assertEquals("currentGlobalResult Sets not of length 3 ?", 3, currentGlobalResult.size());
|
||||
assertTrue("allowedMethod1 not present ?", currentGlobalResult.contains("allowedMethod1"));
|
||||
assertTrue("allowedMethod2 not present ?", currentGlobalResult.contains("allowedMethod2"));
|
||||
assertTrue("allowedMethod3 not present ?", currentGlobalResult.contains("allowedMethod3"));
|
||||
assertFalse("noSuchMethod is present ?", currentGlobalResult.contains("noSuchMethod"));
|
||||
// Attempt the method using the multiple child Element and confirm the result is as expected.
|
||||
prov.loadGlobalAllowedMethods(testPackageConfigBuilder, mockPackageElementMultiple);
|
||||
currentGlobalResult = testPackageConfigBuilder.getGlobalAllowedMethods();
|
||||
assertNotNull("currentGlobalResult is null ?", currentGlobalResult);
|
||||
assertEquals("currentGlobalResult Sets not of length 6 ?", 6, currentGlobalResult.size());
|
||||
assertTrue("allowedMethod4 not present ?", currentGlobalResult.contains("allowedMethod4"));
|
||||
assertTrue("allowedMethod5 not present ?", currentGlobalResult.contains("allowedMethod5"));
|
||||
assertTrue("allowedMethod6 not present ?", currentGlobalResult.contains("allowedMethod6"));
|
||||
assertFalse("noSuchMethod is present ?", currentGlobalResult.contains("snoSUchMethod"));
|
||||
// Confirm the previously added elements are still present
|
||||
assertTrue("allowedMethod1 not present ?", currentGlobalResult.contains("allowedMethod1"));
|
||||
assertTrue("allowedMethod2 not present ?", currentGlobalResult.contains("allowedMethod2"));
|
||||
assertTrue("allowedMethod3 not present ?", currentGlobalResult.contains("allowedMethod3"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test buildResults() to ensure consistent results for processing
|
||||
* <result/> in <action/> XML configuration elements.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public void testBuildResults() throws Exception {
|
||||
// Set up test using two mock DOM Elements:
|
||||
// 1) A mock "action" Element with a two "result" child Elements that each contains a single
|
||||
// TEXT_NODE Node. This simulates a typical result from a SAX parser parsing the result
|
||||
// tag body.
|
||||
// 2) A mock "action" Element with two "result" child Elements that each contain multiple
|
||||
// TEXT_NODE Nodes. This simulates an unusal result from a SAX parser parsing the result
|
||||
// tag body.
|
||||
final String fakeBodyString = "/SomePath/SomePath/SomePath/SomeJSP.jsp";
|
||||
final String fakeBodyString2 = "/SomePath2/SomePath2/SomePath2/SomeJSP2.jsp";
|
||||
final String resultParam = "nonNullDefaultParam";
|
||||
PackageConfig.Builder testPackageConfigBuilder = new PackageConfig.Builder("resultsPackage");
|
||||
ResultTypeConfig.Builder resultTypeConfigBuilder = new ResultTypeConfig.Builder("dispatcher", (String) ServletDispatcherResult.class.getName());
|
||||
resultTypeConfigBuilder.defaultResultParam(resultParam);
|
||||
ResultTypeConfig resultTypeConfig = resultTypeConfigBuilder.build();
|
||||
testPackageConfigBuilder.addResultTypeConfig(resultTypeConfig);
|
||||
List<String> singleStringList = new ArrayList(1);
|
||||
List<String> singleStringList2 = new ArrayList(1);
|
||||
List<String> multipleStringList = new ArrayList(4);
|
||||
List<String> multipleStringList2 = new ArrayList(4);
|
||||
singleStringList.add(fakeBodyString);
|
||||
singleStringList2.add(fakeBodyString2);
|
||||
multipleStringList.add("/SomePath");
|
||||
multipleStringList.add("/SomePath/");
|
||||
multipleStringList.add("SomePath/");
|
||||
multipleStringList.add("SomeJSP.jsp");
|
||||
multipleStringList2.add("/SomePath2");
|
||||
multipleStringList2.add("/SomePath2/");
|
||||
multipleStringList2.add("SomePath2/");
|
||||
multipleStringList2.add("SomeJSP2.jsp");
|
||||
NodeList mockNodeListSingleChild = new MockNodeList(singleStringList);
|
||||
NodeList mockNodeListSingleChild2 = new MockNodeList(singleStringList2);
|
||||
NodeList mockNodeListMultipleChild = new MockNodeList(multipleStringList);
|
||||
NodeList mockNodeListMultipleChild2 = new MockNodeList(multipleStringList2);
|
||||
Element mockSingleChildResultElement = new MockElement("result", fakeBodyString,
|
||||
"result", fakeBodyString, Node.TEXT_NODE, mockNodeListSingleChild, null);
|
||||
mockSingleChildResultElement.setAttribute("name", "input");
|
||||
mockSingleChildResultElement.setAttribute("type", "dispatcher");
|
||||
Element mockSingleChildResultElement2 = new MockElement("result", fakeBodyString2,
|
||||
"result", fakeBodyString2, Node.TEXT_NODE, mockNodeListSingleChild2, null);
|
||||
mockSingleChildResultElement2.setAttribute("name", "success");
|
||||
mockSingleChildResultElement2.setAttribute("type", "dispatcher");
|
||||
Element mockMultipleChildAllowedMethodsElement = new MockElement("result", fakeBodyString,
|
||||
"result", fakeBodyString, Node.TEXT_NODE, mockNodeListMultipleChild, null);
|
||||
mockMultipleChildAllowedMethodsElement.setAttribute("name", "input");
|
||||
mockMultipleChildAllowedMethodsElement.setAttribute("type", "dispatcher");
|
||||
Element mockMultipleChildAllowedMethodsElement2 = new MockElement("result", fakeBodyString2,
|
||||
"result", fakeBodyString2, Node.TEXT_NODE, mockNodeListMultipleChild2, null);
|
||||
mockMultipleChildAllowedMethodsElement2.setAttribute("name", "success");
|
||||
mockMultipleChildAllowedMethodsElement2.setAttribute("type", "dispatcher");
|
||||
MockNodeList mockActionElementChildrenSingle = new MockNodeList();
|
||||
mockActionElementChildrenSingle.addToNodeList(mockSingleChildResultElement);
|
||||
mockActionElementChildrenSingle.addToNodeList(mockSingleChildResultElement2);
|
||||
MockNodeList mockActionElementChildrenMultiple = new MockNodeList();
|
||||
mockActionElementChildrenMultiple.addToNodeList(mockMultipleChildAllowedMethodsElement);
|
||||
mockActionElementChildrenMultiple.addToNodeList(mockMultipleChildAllowedMethodsElement2);
|
||||
Element mockActionElementSingle = new MockElement("action", "fakeBody", "action", "fakeValue",
|
||||
Node.TEXT_NODE, mockActionElementChildrenSingle, null);
|
||||
Element mockActionElementMultiple = new MockElement("action", "fakeBody", "action", "fakeValue",
|
||||
Node.TEXT_NODE, mockActionElementChildrenMultiple, null);
|
||||
// Attempt the method using both types of Elements (single child and multiple child) and confirm
|
||||
// the result is the same for both. Also confirm the results are as expected.
|
||||
XmlConfigurationProvider prov = new XmlConfigurationProvider("com/opensymphony/xwork2/config/providers/xwork- test.xml", false);
|
||||
Map<String, ResultConfig> singleChildResult = prov.buildResults(mockActionElementSingle, testPackageConfigBuilder);
|
||||
Map<String, ResultConfig> multipleChildResult = prov.buildResults(mockActionElementMultiple, testPackageConfigBuilder);
|
||||
assertNotNull("singleChildResult is null ?", singleChildResult);
|
||||
assertNotNull("multipleChildResult is null ?", multipleChildResult);
|
||||
assertEquals("singleChildResult not equal to multipleChildResult ?", singleChildResult, multipleChildResult);
|
||||
// Since both Maps are equal, only need to test one to confirm the contents of ONE are correct.contents are correct
|
||||
// The multipleChildResult (constructed from the multiple child TEXT_NODES) will be checked for correctness.
|
||||
assertEquals("result Maps not of size 2 ?", 2, multipleChildResult.size());
|
||||
ResultConfig inputResult = multipleChildResult.get("input");
|
||||
ResultConfig successResult = multipleChildResult.get("success");
|
||||
assertNotNull("inputResult (multipleChildResult) is null ?", inputResult);
|
||||
assertNotNull("successResult (multipleChildResult) is null ?", successResult);
|
||||
Map<String, String> inputResultParams = inputResult.getParams();
|
||||
Map<String, String> successResultParams = successResult.getParams();
|
||||
assertNotNull("inputResultParams (multipleChildResult) is null ?", inputResultParams);
|
||||
assertNotNull("successResultParams (multipleChildResult) is null ?", successResultParams);
|
||||
assertEquals("inputResult (multipleChildResult) resultParam value not equal to fakeBodyString ?",
|
||||
fakeBodyString, inputResultParams.get(resultParam));
|
||||
assertEquals("successResult (multipleChildResult) resultParam value not equal to fakeBodyString2 ?",
|
||||
fakeBodyString2, successResultParams.get(resultParam));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test loadGlobalResults() to ensure consistent results for processing
|
||||
* <global-results/> in <package/> XML configuration elements.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public void testLoadGlobalResults() throws Exception {
|
||||
// Set up test using two mock DOM Elements:
|
||||
// 1) A mock "package" Element containing a mock "global-results" Element with a two "result"
|
||||
// child Elements that each contains a single TEXT_NODE Node. This simulates a typical result
|
||||
// from a SAX parser parsing the result tag body.
|
||||
// 2) A mock "package" Element containing a mock "global-results" Element with two "result"
|
||||
// child Elements that each contain multiple TEXT_NODE Nodes. This simulates an unusal result
|
||||
// from a SAX parser parsing the result tag body.
|
||||
final String fakeBodyString = "/SomePath/SomePath/SomePath/SomeJSP.jsp";
|
||||
final String fakeBodyString2 = "/SomePath2/SomePath2/SomePath2/SomeJSP2.jsp";
|
||||
final String resultParam = "nonNullDefaultParam";
|
||||
PackageConfig.Builder testPackageConfigBuilder = new PackageConfig.Builder("resultsPackage");
|
||||
ResultTypeConfig.Builder resultTypeConfigBuilder = new ResultTypeConfig.Builder("dispatcher", (String) ServletDispatcherResult.class.getName());
|
||||
resultTypeConfigBuilder.defaultResultParam(resultParam);
|
||||
ResultTypeConfig resultTypeConfig = resultTypeConfigBuilder.build();
|
||||
testPackageConfigBuilder.addResultTypeConfig(resultTypeConfig);
|
||||
List<String> singleStringList = new ArrayList(1);
|
||||
List<String> singleStringList2 = new ArrayList(1);
|
||||
List<String> multipleStringList = new ArrayList(4);
|
||||
List<String> multipleStringList2 = new ArrayList(4);
|
||||
singleStringList.add(fakeBodyString);
|
||||
singleStringList2.add(fakeBodyString2);
|
||||
multipleStringList.add("/SomePath");
|
||||
multipleStringList.add("/SomePath/");
|
||||
multipleStringList.add("SomePath/");
|
||||
multipleStringList.add("SomeJSP.jsp");
|
||||
multipleStringList2.add("/SomePath2");
|
||||
multipleStringList2.add("/SomePath2/");
|
||||
multipleStringList2.add("SomePath2/");
|
||||
multipleStringList2.add("SomeJSP2.jsp");
|
||||
NodeList mockNodeListSingleChild = new MockNodeList(singleStringList);
|
||||
NodeList mockNodeListSingleChild2 = new MockNodeList(singleStringList2);
|
||||
NodeList mockNodeListMultipleChild = new MockNodeList(multipleStringList);
|
||||
NodeList mockNodeListMultipleChild2 = new MockNodeList(multipleStringList2);
|
||||
Element mockSingleChildResultElement = new MockElement("result", fakeBodyString,
|
||||
"result", fakeBodyString, Node.TEXT_NODE, mockNodeListSingleChild, null);
|
||||
mockSingleChildResultElement.setAttribute("name", "input");
|
||||
mockSingleChildResultElement.setAttribute("type", "dispatcher");
|
||||
Element mockSingleChildResultElement2 = new MockElement("result", fakeBodyString2,
|
||||
"result", fakeBodyString2, Node.TEXT_NODE, mockNodeListSingleChild2, null);
|
||||
mockSingleChildResultElement2.setAttribute("name", "success");
|
||||
mockSingleChildResultElement2.setAttribute("type", "dispatcher");
|
||||
Element mockMultipleChildAllowedMethodsElement = new MockElement("result", fakeBodyString,
|
||||
"result", fakeBodyString, Node.TEXT_NODE, mockNodeListMultipleChild, null);
|
||||
mockMultipleChildAllowedMethodsElement.setAttribute("name", "input2");
|
||||
mockMultipleChildAllowedMethodsElement.setAttribute("type", "dispatcher");
|
||||
Element mockMultipleChildAllowedMethodsElement2 = new MockElement("result", fakeBodyString,
|
||||
"result", fakeBodyString2, Node.TEXT_NODE, mockNodeListMultipleChild2, null);
|
||||
mockMultipleChildAllowedMethodsElement2.setAttribute("name", "success2");
|
||||
mockMultipleChildAllowedMethodsElement2.setAttribute("type", "dispatcher");
|
||||
MockNodeList mockGlobalResultsElementChildrenSingle = new MockNodeList();
|
||||
mockGlobalResultsElementChildrenSingle.addToNodeList(mockSingleChildResultElement);
|
||||
mockGlobalResultsElementChildrenSingle.addToNodeList(mockSingleChildResultElement2);
|
||||
MockNodeList mockGlobalResultsElementChildrenMultiple = new MockNodeList();
|
||||
mockGlobalResultsElementChildrenMultiple.addToNodeList(mockMultipleChildAllowedMethodsElement);
|
||||
mockGlobalResultsElementChildrenMultiple.addToNodeList(mockMultipleChildAllowedMethodsElement2);
|
||||
Element mockGlobalResultsElementSingle = new MockElement("global-results", "fakeBody", "global-results", "fakeValue",
|
||||
Node.TEXT_NODE, mockGlobalResultsElementChildrenSingle, null);
|
||||
Element mockGlobalResultsGlobalResultsElementMultiple = new MockElement("global-results", "fakeBody", "global-results", "fakeValue",
|
||||
Node.TEXT_NODE, mockGlobalResultsElementChildrenMultiple, null);
|
||||
MockNodeList mockPackageElementChildrenSingle = new MockNodeList();
|
||||
mockPackageElementChildrenSingle.addToNodeList(mockGlobalResultsElementSingle);
|
||||
MockNodeList mockPackageElementChildrenMultiple = new MockNodeList();
|
||||
mockPackageElementChildrenMultiple.addToNodeList(mockGlobalResultsGlobalResultsElementMultiple);
|
||||
Element mockPackageElementSingle = new MockElement("package", "fakeBody", "package", "fakeValue",
|
||||
Node.TEXT_NODE, mockPackageElementChildrenSingle, null);
|
||||
Element mockPackageElementMultiple = new MockElement("package", "fakeBody", "package", "fakeValue",
|
||||
Node.TEXT_NODE, mockPackageElementChildrenMultiple, null);
|
||||
// Attempt the global laod method using single child Elements first, and confirm the results are as expected.
|
||||
XmlConfigurationProvider prov = new XmlConfigurationProvider("com/opensymphony/xwork2/config/providers/xwork- test.xml", false);
|
||||
prov.loadGlobalResults(testPackageConfigBuilder, mockPackageElementSingle);
|
||||
PackageConfig testPackageConfig = testPackageConfigBuilder.build();
|
||||
Map<String, ResultConfig> currentGlobalResults = testPackageConfig.getAllGlobalResults();
|
||||
assertNotNull("currentGlobalResults is null ?", currentGlobalResults);
|
||||
assertEquals("currentGlobalResults size not 2 ?", 2, currentGlobalResults.size());
|
||||
ResultConfig inputResult = currentGlobalResults.get("input");
|
||||
ResultConfig successResult = currentGlobalResults.get("success");
|
||||
assertNotNull("inputResult (currentGlobalResults - single) is null ?", inputResult);
|
||||
assertNotNull("successResult (currentGlobalResults - single) is null ?", successResult);
|
||||
Map<String, String> inputResultParams = inputResult.getParams();
|
||||
Map<String, String> successResultParams = successResult.getParams();
|
||||
assertNotNull("inputResultParams (currentGlobalResults - single) is null ?", inputResultParams);
|
||||
assertNotNull("successResultParams (currentGlobalResults - single) is null ?", successResultParams);
|
||||
assertEquals("inputResult (currentGlobalResults - single) resultParam value not equal to fakeBodyString ?",
|
||||
fakeBodyString, inputResultParams.get(resultParam));
|
||||
assertEquals("successResult (currentGlobalResults - single) resultParam value not equal to fakeBodyString2 ?",
|
||||
fakeBodyString2, successResultParams.get(resultParam));
|
||||
// Attempt the global laod method using mutliple child Elements next, and confirm the results are as expected.
|
||||
prov.loadGlobalResults(testPackageConfigBuilder, mockPackageElementMultiple);
|
||||
testPackageConfig = testPackageConfigBuilder.build();
|
||||
currentGlobalResults = testPackageConfig.getAllGlobalResults();
|
||||
assertNotNull("currentGlobalResults is null ?", currentGlobalResults);
|
||||
assertEquals("currentGlobalResults size not 4 ?", 4, currentGlobalResults.size());
|
||||
ResultConfig inputResult2 = currentGlobalResults.get("input2");
|
||||
ResultConfig successResult2 = currentGlobalResults.get("success2");
|
||||
assertNotNull("inputResult2 (currentGlobalResults - multiple) is null ?", inputResult2);
|
||||
assertNotNull("successResult2 (currentGlobalResults - multiple) is null ?", successResult2);
|
||||
Map<String, String> inputResultParams2 = inputResult2.getParams();
|
||||
Map<String, String> successResultParams2 = successResult2.getParams();
|
||||
assertNotNull("inputResultParams2 (currentGlobalResults - multiple) is null ?", inputResultParams2);
|
||||
assertNotNull("successResultParams2 (currentGlobalResults - multiple) is null ?", successResultParams2);
|
||||
assertEquals("inputResult2 (currentGlobalResults - multiple) resultParam value not equal to fakeBodyString ?",
|
||||
fakeBodyString, inputResultParams2.get(resultParam));
|
||||
assertEquals("successResult2 (currentGlobalResults - multiple) resultParam value not equal to fakeBodyString2 ?",
|
||||
fakeBodyString2, successResultParams2.get(resultParam));
|
||||
// Confirm the previous global results are still present
|
||||
inputResult = currentGlobalResults.get("input");
|
||||
successResult = currentGlobalResults.get("success");
|
||||
assertNotNull("inputResult (currentGlobalResults - single) is null ?", inputResult);
|
||||
assertNotNull("successResult (currentGlobalResults - single) is null ?", successResult);
|
||||
inputResultParams = inputResult.getParams();
|
||||
successResultParams = successResult.getParams();
|
||||
assertNotNull("inputResultParams (currentGlobalResults - single) is null ?", inputResultParams);
|
||||
assertNotNull("successResultParams (currentGlobalResults - single) is null ?", successResultParams);
|
||||
assertEquals("inputResult (currentGlobalResults - single) resultParam value not equal to fakeBodyString ?",
|
||||
fakeBodyString, inputResultParams.get(resultParam));
|
||||
assertEquals("successResult (currentGlobalResults - single) resultParam value not equal to fakeBodyString2 ?",
|
||||
fakeBodyString2, successResultParams.get(resultParam));
|
||||
inputResult = currentGlobalResults.get("input");
|
||||
successResult = currentGlobalResults.get("success");
|
||||
assertNotNull("inputResult (currentGlobalResults - single) is null ?", inputResult);
|
||||
assertNotNull("successResult (currentGlobalResults - single) is null ?", successResult);
|
||||
inputResultParams = inputResult.getParams();
|
||||
successResultParams = successResult.getParams();
|
||||
assertNotNull("inputResultParams (currentGlobalResults - single) is null ?", inputResultParams);
|
||||
assertNotNull("successResultParams (currentGlobalResults - single) is null ?", successResultParams);
|
||||
assertEquals("inputResult (currentGlobalResults - single) resultParam value not equal to fakeBodyString ?",
|
||||
fakeBodyString, inputResultParams.get(resultParam));
|
||||
assertEquals("successResult (currentGlobalResults - single) resultParam value not equal to fakeBodyString2 ?",
|
||||
fakeBodyString2, successResultParams.get(resultParam));
|
||||
}
|
||||
|
||||
/**
|
||||
* Mock NodeList.
|
||||
*
|
||||
* Provides minimal functionality to permit limited mock DOM testing.
|
||||
*/
|
||||
protected class MockNodeList implements org.w3c.dom.NodeList {
|
||||
List<Node> nodeList;
|
||||
|
||||
public MockNodeList() {
|
||||
this.nodeList = new ArrayList(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Produces TEXT_NODE Nodes based on the input List of Strings. Node names
|
||||
* follow a simple pattern "nodeX" where X is the index.
|
||||
*
|
||||
* @param stringList
|
||||
*/
|
||||
public MockNodeList(List<String> stringList) {
|
||||
if (stringList != null) {
|
||||
final int nodeListLength = stringList.size();
|
||||
this.nodeList = new ArrayList(nodeListLength);
|
||||
for (int index = 0; index < nodeListLength; index++) {
|
||||
this.nodeList.add(new MockNode("node" + index, stringList.get(index), Node.TEXT_NODE, null, null));
|
||||
}
|
||||
} else {
|
||||
this.nodeList = new ArrayList(0);
|
||||
}
|
||||
}
|
||||
|
||||
public MockNodeList(NodeList nodeList) {
|
||||
if (nodeList != null) {
|
||||
final int nodeListLength = nodeList.getLength();
|
||||
this.nodeList = new ArrayList(nodeListLength);
|
||||
for (int index = 0; index < nodeListLength; index++) {
|
||||
this.nodeList.add(nodeList.item(index));
|
||||
}
|
||||
} else {
|
||||
this.nodeList = new ArrayList(0);
|
||||
}
|
||||
}
|
||||
|
||||
public void addToNodeList(List<Node> nodeList) {
|
||||
if (nodeList != null) {
|
||||
final int nodeListLength = nodeList.size();
|
||||
for (int index = 0; index < nodeListLength; index++) {
|
||||
this.nodeList.add(nodeList.get(index));
|
||||
}
|
||||
} else {
|
||||
this.nodeList = new ArrayList(0);
|
||||
}
|
||||
}
|
||||
|
||||
public void addToNodeList(Node node) {
|
||||
nodeList.add(node);
|
||||
}
|
||||
|
||||
public void setParentForListNodes(Node parentNode) {
|
||||
if (nodeList != null) {
|
||||
final int nodeListLength = nodeList.size();
|
||||
for (int index = 0; index < nodeListLength; index++) {
|
||||
Node node = nodeList.get(index);
|
||||
if (node instanceof MockNode) {
|
||||
MockNode mockNode = (MockNode) node;
|
||||
mockNode.setParentNode(parentNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Node item(int index) {
|
||||
return (nodeList != null ? nodeList.get(index) : null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getLength() {
|
||||
return (nodeList != null ? nodeList.size() : 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* MockNode
|
||||
*
|
||||
* Provides minimal functionality to permit limited mock DOM testing.
|
||||
*/
|
||||
protected class MockNode implements org.w3c.dom.Node {
|
||||
final private String nodeName;
|
||||
private String nodeValue;
|
||||
final private short nodeType;
|
||||
private Node parentNode;
|
||||
final private NodeList childNodes;
|
||||
|
||||
public MockNode(String nodeName, String nodeValue, short nodeType, NodeList childNodes, Node parentNode) {
|
||||
this.nodeName = nodeName;
|
||||
this.nodeValue = nodeValue;
|
||||
this.nodeType = nodeType;
|
||||
this.childNodes = childNodes;
|
||||
this.parentNode = parentNode;
|
||||
|
||||
if (childNodes instanceof MockNodeList) {
|
||||
MockNodeList mockNodeList = (MockNodeList) childNodes;
|
||||
mockNodeList.setParentForListNodes(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getNodeName() {
|
||||
return nodeName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getNodeValue() throws DOMException {
|
||||
return nodeValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setNodeValue(String nodeValue) throws DOMException {
|
||||
this.nodeValue = nodeValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public short getNodeType() {
|
||||
return nodeType;
|
||||
}
|
||||
|
||||
public void setParentNode(Node parentNode) {
|
||||
this.parentNode = parentNode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Node getParentNode() {
|
||||
return parentNode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public NodeList getChildNodes() {
|
||||
return childNodes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Node getFirstChild() {
|
||||
if (childNodes != null) {
|
||||
return childNodes.item(0);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Node getLastChild() {
|
||||
if (childNodes != null) {
|
||||
return childNodes.item(childNodes.getLength());
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Node getPreviousSibling() {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Node getNextSibling() {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public NamedNodeMap getAttributes() {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Document getOwnerDocument() {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Node insertBefore(Node newChild, Node refChild) throws DOMException {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Node replaceChild(Node newChild, Node oldChild) throws DOMException {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Node removeChild(Node oldChild) throws DOMException {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Node appendChild(Node newChild) throws DOMException {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasChildNodes() {
|
||||
return (childNodes != null ? childNodes.getLength() > 0 : false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Node cloneNode(boolean deep) {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void normalize() {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSupported(String feature, String version) {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getNamespaceURI() {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPrefix() {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPrefix(String prefix) throws DOMException {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLocalName() {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasAttributes() {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBaseURI() {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public short compareDocumentPosition(Node other) throws DOMException {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTextContent() throws DOMException {
|
||||
return nodeValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTextContent(String textContent) throws DOMException {
|
||||
setNodeValue(textContent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSameNode(Node other) {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String lookupPrefix(String namespaceURI) {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDefaultNamespace(String namespaceURI) {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String lookupNamespaceURI(String prefix) {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEqualNode(Node arg) {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getFeature(String feature, String version) {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object setUserData(String key, Object data, UserDataHandler handler) {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getUserData(String key) {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mock Element.
|
||||
*
|
||||
* Provides minimal functionality to permit limited mock DOM testing.
|
||||
*/
|
||||
protected class MockElement extends MockNode implements org.w3c.dom.Element {
|
||||
final private String tagName;
|
||||
final private String tagBody;
|
||||
final private Map<String, String> attributes;
|
||||
|
||||
public MockElement(String tagName, String tagBody,
|
||||
String nodeName, String nodeValue, short nodeType, NodeList childNodes, Node parentNode) {
|
||||
super(nodeName, nodeValue, nodeType, childNodes, parentNode);
|
||||
this.tagName = nodeName;
|
||||
this.tagBody = nodeValue;
|
||||
attributes = new HashMap<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTagName() {
|
||||
return tagName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAttribute(String name) {
|
||||
return attributes.get(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAttribute(String name, String value) throws DOMException {
|
||||
attributes.put(name, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeAttribute(String name) throws DOMException {
|
||||
attributes.remove(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Attr getAttributeNode(String name) {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Attr setAttributeNode(Attr newAttr) throws DOMException {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Attr removeAttributeNode(Attr oldAttr) throws DOMException {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public NodeList getElementsByTagName(String name) {
|
||||
if (name != null) {
|
||||
final NodeList tempChildren = getChildNodes();
|
||||
final MockNodeList result = new MockNodeList();
|
||||
if (tempChildren != null) {
|
||||
final int nodeListLength = tempChildren.getLength();
|
||||
for (int index = 0; index < nodeListLength; index++) {
|
||||
Node node = tempChildren.item(index);
|
||||
if (node instanceof Element) {
|
||||
Element element = (Element) node;
|
||||
if (name.equals(element.getTagName())) {
|
||||
result.addToNodeList(element);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
} else {
|
||||
return new MockNodeList((NodeList) null);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAttributeNS(String namespaceURI, String localName) throws DOMException {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeAttributeNS(String namespaceURI, String localName) throws DOMException {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Attr getAttributeNodeNS(String namespaceURI, String localName) throws DOMException {
|
||||
return null; // Sufficient for Result processing
|
||||
}
|
||||
|
||||
@Override
|
||||
public Attr setAttributeNodeNS(Attr newAttr) throws DOMException {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public NodeList getElementsByTagNameNS(String namespaceURI, String localName) throws DOMException {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasAttribute(String name) {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasAttributeNS(String namespaceURI, String localName) throws DOMException {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeInfo getSchemaTypeInfo() {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setIdAttribute(String name, boolean isId) throws DOMException {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setIdAttributeNS(String namespaceURI, String localName, boolean isId) throws DOMException {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setIdAttributeNode(Attr idAttr, boolean isId) throws DOMException {
|
||||
throw new UnsupportedOperationException("No mock support.");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package com.opensymphony.xwork2.util;
|
||||
package com.opensymphony.xwork2.conversion.impl;
|
||||
|
||||
import com.opensymphony.xwork2.XWorkTestCase;
|
||||
|
||||
@@ -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 com.opensymphony.xwork2.ognl;
|
||||
|
||||
import org.apache.struts2.StrutsInternalTestCase;
|
||||
|
||||
public class OgnlUtilStrutsTest extends StrutsInternalTestCase {
|
||||
|
||||
private OgnlUtil ognlUtil;
|
||||
|
||||
@Override
|
||||
public void setUp() throws Exception {
|
||||
super.setUp();
|
||||
ognlUtil = container.getInstance(OgnlUtil.class);
|
||||
}
|
||||
|
||||
public void testDefaultExcludes() {
|
||||
ognlUtil.setExcludedClasses("");
|
||||
ognlUtil.setExcludedPackageNames("");
|
||||
ognlUtil.setExcludedPackageNamePatterns("");
|
||||
assertTrue(ognlUtil.getExcludedClasses().size() > 0);
|
||||
assertTrue(ognlUtil.getExcludedPackageNames().size() > 0);
|
||||
|
||||
try {
|
||||
ognlUtil.getExcludedClasses().clear();
|
||||
} catch (Exception ex){
|
||||
assertTrue(ex instanceof UnsupportedOperationException);
|
||||
}
|
||||
try {
|
||||
ognlUtil.getExcludedPackageNames().clear();
|
||||
} catch (Exception ex){
|
||||
assertTrue(ex instanceof UnsupportedOperationException);
|
||||
}
|
||||
try {
|
||||
ognlUtil.getExcludedPackageNamePatterns().clear();
|
||||
} catch (Exception ex){
|
||||
assertTrue(ex instanceof UnsupportedOperationException);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,20 +19,39 @@
|
||||
package com.opensymphony.xwork2.ognl;
|
||||
|
||||
import com.opensymphony.xwork2.ActionContext;
|
||||
import com.opensymphony.xwork2.XWorkConstants;
|
||||
import com.opensymphony.xwork2.XWorkException;
|
||||
import com.opensymphony.xwork2.XWorkTestCase;
|
||||
import com.opensymphony.xwork2.config.ConfigurationException;
|
||||
import com.opensymphony.xwork2.conversion.impl.XWorkConverter;
|
||||
import com.opensymphony.xwork2.inject.ContainerBuilder;
|
||||
import com.opensymphony.xwork2.interceptor.ChainingInterceptor;
|
||||
import com.opensymphony.xwork2.test.StubConfigurationProvider;
|
||||
import com.opensymphony.xwork2.test.User;
|
||||
import com.opensymphony.xwork2.util.*;
|
||||
import com.opensymphony.xwork2.util.location.LocatableProperties;
|
||||
import com.opensymphony.xwork2.util.reflection.ReflectionContextState;
|
||||
import java.beans.IntrospectionException;
|
||||
import ognl.*;
|
||||
import org.apache.struts2.StrutsConstants;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.text.DateFormat;
|
||||
import java.util.*;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class OgnlUtilTest extends XWorkTestCase {
|
||||
|
||||
|
||||
// Fields for static field access test
|
||||
public static final String STATIC_FINAL_PUBLIC_ATTRIBUTE = "Static_Final_Public_Attribute";
|
||||
static final String STATIC_FINAL_PACKAGE_ATTRIBUTE = "Static_Final_Package_Attribute";
|
||||
protected static final String STATIC_FINAL_PROTECTED_ATTRIBUTE = "Static_Final_Protected_Attribute";
|
||||
private static final String STATIC_FINAL_PRIVATE_ATTRIBUTE = "Static_Final_Private_Attribute";
|
||||
public static String STATIC_PUBLIC_ATTRIBUTE = "Static_Public_Attribute";
|
||||
static String STATIC_PACKAGE_ATTRIBUTE = "Static_Package_Attribute";
|
||||
protected static String STATIC_PROTECTED_ATTRIBUTE = "Static_Protected_Attribute";
|
||||
private static String STATIC_PRIVATE_ATTRIBUTE = "Static_Private_Attribute";
|
||||
|
||||
private OgnlUtil ognlUtil;
|
||||
|
||||
@Override
|
||||
@@ -41,7 +60,7 @@ public class OgnlUtilTest extends XWorkTestCase {
|
||||
ognlUtil = container.getInstance(OgnlUtil.class);
|
||||
}
|
||||
|
||||
public void testCanSetADependentObject() throws Exception {
|
||||
public void testCanSetADependentObject() {
|
||||
String dogName = "fido";
|
||||
|
||||
OgnlRuntime.setNullHandler(Owner.class, new NullHandler() {
|
||||
@@ -95,6 +114,84 @@ public class OgnlUtilTest extends XWorkTestCase {
|
||||
assertSame(expr0, expr2);
|
||||
}
|
||||
|
||||
public void testClearExpressionCache() throws OgnlException {
|
||||
ognlUtil.setEnableExpressionCache("true");
|
||||
// Test that the expression cache is functioning as expected.
|
||||
Object expr0 = ognlUtil.compile("test");
|
||||
Object expr1 = ognlUtil.compile("test");
|
||||
Object expr2 = ognlUtil.compile("test");
|
||||
// Cache in effect, so expr0, expr1, expr2 should be the same.
|
||||
assertSame(expr0, expr1);
|
||||
assertSame(expr0, expr2);
|
||||
assertTrue("Expression cache empty before clear ?", ognlUtil.expressionCacheSize() > 0);
|
||||
// Clear the Epxression cache and confirm subsequent requests are new.
|
||||
ognlUtil.clearExpressionCache();
|
||||
assertTrue("Expression cache not empty after clear ?", ognlUtil.expressionCacheSize() == 0);
|
||||
Object expr3 = ognlUtil.compile("test");
|
||||
Object expr4 = ognlUtil.compile("test");
|
||||
Object expr5 = ognlUtil.compile("test");
|
||||
// Cache cleared, expr3 should be a new instance.
|
||||
assertNotSame(expr0, expr3);
|
||||
// Cache still in effect, so expr3, expr4, expr5 should be the same.
|
||||
assertSame(expr3, expr4);
|
||||
assertSame(expr3, expr5);
|
||||
assertTrue("Expression cache empty after usage ?", ognlUtil.expressionCacheSize() > 0);
|
||||
}
|
||||
|
||||
public void testClearBeanInfoCache() throws IntrospectionException {
|
||||
final TestBean1 testBean1 = new TestBean1();
|
||||
final TestBean2 testBean2 = new TestBean2();
|
||||
// Test that the BeanInfo cache is functioning as expected.
|
||||
Object beanInfo1_1 = ognlUtil.getBeanInfo(testBean1);
|
||||
Object beanInfo1_2 = ognlUtil.getBeanInfo(testBean1);
|
||||
Object beanInfo1_3 = ognlUtil.getBeanInfo(testBean1);
|
||||
// Cache in effect, so beanInfo1_1, beanInfo1_2, beanInfo1_3 should be the same.
|
||||
assertSame(beanInfo1_1, beanInfo1_2);
|
||||
assertSame(beanInfo1_1, beanInfo1_3);
|
||||
Object beanInfo2_1 = ognlUtil.getBeanInfo(testBean2);
|
||||
Object beanInfo2_2 = ognlUtil.getBeanInfo(testBean2);
|
||||
Object beanInfo2_3 = ognlUtil.getBeanInfo(testBean2);
|
||||
// Cache in effect, so beanInfo2_1, beanInfo2_2, beanInfo2_3 should be the same.
|
||||
assertSame(beanInfo2_1, beanInfo2_2);
|
||||
assertSame(beanInfo2_1, beanInfo2_3);
|
||||
// BeanInfo for TestBean1 and TestBean2 should always be different.
|
||||
assertNotSame(beanInfo1_1, beanInfo2_1);
|
||||
assertTrue("BeanInfo cache empty before clear ?", ognlUtil.beanInfoCacheSize() > 0);
|
||||
// Clear the BeanInfo cache and confirm subsequent requests are new.
|
||||
ognlUtil.clearBeanInfoCache();
|
||||
assertTrue("BeanInfo cache not empty after clear ?", ognlUtil.beanInfoCacheSize() == 0);
|
||||
Object beanInfo1_4 = ognlUtil.getBeanInfo(testBean1);
|
||||
Object beanInfo1_5 = ognlUtil.getBeanInfo(testBean1);
|
||||
Object beanInfo1_6 = ognlUtil.getBeanInfo(testBean1);
|
||||
// Cache in effect, so beanInfo1_4, beanInfo1_5, beanInfo1_6 should be the same.
|
||||
assertSame(beanInfo1_4, beanInfo1_5);
|
||||
assertSame(beanInfo1_4, beanInfo1_6);
|
||||
// Cache was cleared in-between, so beanInfo1_1/beanInfo1_2/beanInfo1_3 should differ
|
||||
// from beanInfo1_4/beanInfo1_5/beanInfo1_6.
|
||||
assertNotSame(beanInfo1_1, beanInfo1_4);
|
||||
assertNotSame(beanInfo1_2, beanInfo1_5);
|
||||
assertNotSame(beanInfo1_3, beanInfo1_6);
|
||||
Object beanInfo2_4 = ognlUtil.getBeanInfo(testBean2);
|
||||
Object beanInfo2_5 = ognlUtil.getBeanInfo(testBean2);
|
||||
Object beanInfo2_6 = ognlUtil.getBeanInfo(testBean2);
|
||||
// Cache in effect, so beanInfo2_4, beanInfo2_5, beanInfo2_6 should be the same.
|
||||
assertSame(beanInfo2_4, beanInfo2_5);
|
||||
assertSame(beanInfo2_4, beanInfo2_6);
|
||||
// Cache was cleared in-between, so beanInfo2_1/beanInfo2_2/beanInfo2_3 should differ
|
||||
// from beanInfo2_4/beanInfo2_5/beanInfo2_6.
|
||||
assertNotSame(beanInfo2_1, beanInfo2_4);
|
||||
assertNotSame(beanInfo2_2, beanInfo2_5);
|
||||
assertNotSame(beanInfo2_3, beanInfo2_6);
|
||||
// BeanInfo for TestBean1 and TestBean2 should always be different.
|
||||
assertNotSame(beanInfo1_4, beanInfo2_4);
|
||||
assertTrue("BeanInfo cache empty after usage ?", ognlUtil.beanInfoCacheSize() > 0);
|
||||
}
|
||||
|
||||
public void testClearRuntimeCache() {
|
||||
// Confirm that no exceptions or failures arise when calling the convenience global clear method.
|
||||
OgnlUtil.clearRuntimeCache();
|
||||
}
|
||||
|
||||
public void testCacheDisabled() throws OgnlException {
|
||||
ognlUtil.setEnableExpressionCache("false");
|
||||
Object expr0 = ognlUtil.compile("test");
|
||||
@@ -363,24 +460,19 @@ public class OgnlUtilTest extends XWorkTestCase {
|
||||
Map props = new HashMap();
|
||||
props.put("birthday", "02/12/1982");
|
||||
// US style test
|
||||
context.put(ActionContext.LOCALE, Locale.US);
|
||||
ognlUtil.setProperties(props, foo, context);
|
||||
|
||||
Calendar cal = Calendar.getInstance();
|
||||
Calendar cal = Calendar.getInstance(Locale.US);
|
||||
cal.clear();
|
||||
cal.set(Calendar.MONTH, Calendar.FEBRUARY);
|
||||
cal.set(Calendar.DAY_OF_MONTH, 12);
|
||||
cal.set(Calendar.YEAR, 1982);
|
||||
|
||||
assertEquals(cal.getTime(), foo.getBirthday());
|
||||
|
||||
//UK style test
|
||||
props.put("event", "18/10/2006 14:23:45");
|
||||
props.put("meeting", "09/09/2006 14:30");
|
||||
context.put(ActionContext.LOCALE, Locale.UK);
|
||||
|
||||
ognlUtil.setProperties(props, foo, context);
|
||||
|
||||
cal = Calendar.getInstance();
|
||||
//UK style test
|
||||
cal = Calendar.getInstance(Locale.UK);
|
||||
cal.clear();
|
||||
cal.set(Calendar.MONTH, Calendar.OCTOBER);
|
||||
cal.set(Calendar.DAY_OF_MONTH, 18);
|
||||
@@ -388,24 +480,39 @@ public class OgnlUtilTest extends XWorkTestCase {
|
||||
cal.set(Calendar.HOUR_OF_DAY, 14);
|
||||
cal.set(Calendar.MINUTE, 23);
|
||||
cal.set(Calendar.SECOND, 45);
|
||||
|
||||
assertEquals(cal.getTime(), foo.getEvent());
|
||||
|
||||
cal = Calendar.getInstance();
|
||||
|
||||
Date eventTime = cal.getTime();
|
||||
String formatted = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, Locale.UK)
|
||||
.format(eventTime);
|
||||
props.put("event", formatted);
|
||||
|
||||
cal = Calendar.getInstance(Locale.UK);
|
||||
cal.clear();
|
||||
cal.set(Calendar.MONTH, Calendar.SEPTEMBER);
|
||||
cal.set(Calendar.DAY_OF_MONTH, 9);
|
||||
cal.set(Calendar.YEAR, 2006);
|
||||
cal.set(Calendar.HOUR_OF_DAY, 14);
|
||||
cal.set(Calendar.MINUTE, 30);
|
||||
|
||||
assertEquals(cal.getTime(), foo.getMeeting());
|
||||
|
||||
Date meetingTime = cal.getTime();
|
||||
formatted = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, Locale.UK)
|
||||
.format(meetingTime);
|
||||
props.put("meeting", formatted);
|
||||
|
||||
context.put(ActionContext.LOCALE, Locale.UK);
|
||||
|
||||
ognlUtil.setProperties(props, foo, context);
|
||||
|
||||
assertEquals(eventTime, foo.getEvent());
|
||||
|
||||
assertEquals(meetingTime, foo.getMeeting());
|
||||
|
||||
//test RFC 3339 date format for JSON
|
||||
props.put("event", "1996-12-19T16:39:57Z");
|
||||
context.put(ActionContext.LOCALE, Locale.US);
|
||||
ognlUtil.setProperties(props, foo, context);
|
||||
|
||||
cal = Calendar.getInstance();
|
||||
cal = Calendar.getInstance(Locale.US);
|
||||
cal.clear();
|
||||
cal.set(Calendar.MONTH, Calendar.DECEMBER);
|
||||
cal.set(Calendar.DAY_OF_MONTH, 19);
|
||||
@@ -418,6 +525,7 @@ public class OgnlUtilTest extends XWorkTestCase {
|
||||
|
||||
//test setting a calendar property
|
||||
props.put("calendar", "1996-12-19T16:39:57Z");
|
||||
context.put(ActionContext.LOCALE, Locale.US);
|
||||
ognlUtil.setProperties(props, foo, context);
|
||||
assertEquals(cal, foo.getCalendar());
|
||||
}
|
||||
@@ -636,7 +744,7 @@ public class OgnlUtilTest extends XWorkTestCase {
|
||||
|
||||
try {
|
||||
stack.setValue("1234", foo);
|
||||
fail("non-valid expression: 1114778947765");
|
||||
fail("non-valid expression: 1234");
|
||||
}
|
||||
catch(RuntimeException ex) {
|
||||
;
|
||||
@@ -648,6 +756,126 @@ public class OgnlUtilTest extends XWorkTestCase {
|
||||
stack.setValue("1234", foo);
|
||||
}
|
||||
|
||||
public void testStackValueDevModeChange() throws Exception {
|
||||
|
||||
try {
|
||||
reloadTestContainerConfiguration(false, false); // Set dev mode false
|
||||
}
|
||||
catch (Exception ex) {
|
||||
fail("Unable to reload container configuration - exception: " + ex);
|
||||
}
|
||||
|
||||
ValueStack stack = ActionContext.getContext().getValueStack();
|
||||
Map stackContext = stack.getContext();
|
||||
stackContext.put(ReflectionContextState.CREATE_NULL_OBJECTS, Boolean.FALSE);
|
||||
stackContext.put(ReflectionContextState.DENY_METHOD_EXECUTION, Boolean.TRUE);
|
||||
stackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
|
||||
|
||||
String[] foo = new String[]{"asdf"};
|
||||
|
||||
// With dev mode false, the following set values should not cause failures
|
||||
stack.setValue("list.1114778947765", foo);
|
||||
stack.setValue("1114778947765", foo);
|
||||
stack.setValue("1234", foo);
|
||||
|
||||
try {
|
||||
reloadTestContainerConfiguration(true, false); // Set dev mode true
|
||||
}
|
||||
catch (Exception ex) {
|
||||
fail("Unable to reload container configuration - exception: " + ex);
|
||||
}
|
||||
|
||||
// Repeat stack/context set after retrieving updated stack
|
||||
stack = ActionContext.getContext().getValueStack();
|
||||
stackContext = stack.getContext();
|
||||
stackContext.put(ReflectionContextState.CREATE_NULL_OBJECTS, Boolean.FALSE);
|
||||
stackContext.put(ReflectionContextState.DENY_METHOD_EXECUTION, Boolean.TRUE);
|
||||
stackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
|
||||
|
||||
try {
|
||||
stack.setValue("list.1114778947765", foo);
|
||||
fail("non-valid expression: list.1114778947765");
|
||||
}
|
||||
catch(RuntimeException ex) {
|
||||
// Expected with dev mode true
|
||||
}
|
||||
try {
|
||||
stack.setValue("1114778947765", foo);
|
||||
fail("non-valid expression: 1114778947765");
|
||||
}
|
||||
catch(RuntimeException ex) {
|
||||
// Expected with dev mode true
|
||||
}
|
||||
try {
|
||||
stack.setValue("1234", foo);
|
||||
fail("non-valid expression: 1234");
|
||||
}
|
||||
catch(RuntimeException ex) {
|
||||
// Expected with dev mode true
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void testDevModeChange() throws Exception {
|
||||
|
||||
try {
|
||||
reloadTestContainerConfiguration(false, false); // Set dev mode false
|
||||
}
|
||||
catch (Exception ex) {
|
||||
fail("Unable to reload container configuration - exception: " + ex);
|
||||
}
|
||||
|
||||
ValueStack stack = ActionContext.getContext().getValueStack();
|
||||
Map stackContext = stack.getContext();
|
||||
stackContext.put(ReflectionContextState.CREATE_NULL_OBJECTS, Boolean.FALSE);
|
||||
stackContext.put(ReflectionContextState.DENY_METHOD_EXECUTION, Boolean.TRUE);
|
||||
stackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
|
||||
|
||||
String[] foo = new String[]{"asdf"};
|
||||
|
||||
// With dev mode false, the following set values should not cause failures
|
||||
stack.setValue("list.1114778947765", foo);
|
||||
stack.setValue("1114778947765", foo);
|
||||
stack.setValue("1234", foo);
|
||||
|
||||
try {
|
||||
reloadTestContainerConfiguration(true, false); // Set dev mode true
|
||||
}
|
||||
catch (Exception ex) {
|
||||
fail("Unable to reload container configuration - exception: " + ex);
|
||||
}
|
||||
|
||||
// Repeat stack/context set after retrieving updated stack
|
||||
stack = ActionContext.getContext().getValueStack();
|
||||
stackContext = stack.getContext();
|
||||
stackContext.put(ReflectionContextState.CREATE_NULL_OBJECTS, Boolean.FALSE);
|
||||
stackContext.put(ReflectionContextState.DENY_METHOD_EXECUTION, Boolean.TRUE);
|
||||
stackContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
|
||||
|
||||
try {
|
||||
stack.setValue("list.1114778947765", foo);
|
||||
fail("non-valid expression: list.1114778947765");
|
||||
}
|
||||
catch(RuntimeException ex) {
|
||||
// Expected with dev mode true
|
||||
}
|
||||
try {
|
||||
stack.setValue("1114778947765", foo);
|
||||
fail("non-valid expression: 1114778947765");
|
||||
}
|
||||
catch(RuntimeException ex) {
|
||||
// Expected with dev mode true
|
||||
}
|
||||
try {
|
||||
stack.setValue("1234", foo);
|
||||
fail("non-valid expression: 1234");
|
||||
}
|
||||
catch(RuntimeException ex) {
|
||||
// Expected with dev mode true
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void testAvoidCallingMethodsOnObjectClass() throws Exception {
|
||||
Foo foo = new Foo();
|
||||
|
||||
@@ -803,6 +1031,334 @@ public class OgnlUtilTest extends XWorkTestCase {
|
||||
assertEquals(expected.getMessage(), "It isn't a simple method which can be called!");
|
||||
}
|
||||
|
||||
public void testXworkTestCaseOgnlUtilExclusions() throws Exception {
|
||||
internalTestInitialEmptyOgnlUtilExclusions(ognlUtil);
|
||||
internalTestOgnlUtilExclusionsImmutable(ognlUtil);
|
||||
}
|
||||
|
||||
public void testDefaultOgnlUtilExclusions() throws Exception {
|
||||
OgnlUtil basicOgnlUtil = new OgnlUtil();
|
||||
|
||||
internalTestInitialEmptyOgnlUtilExclusions(basicOgnlUtil);
|
||||
internalTestOgnlUtilExclusionsImmutable(basicOgnlUtil);
|
||||
}
|
||||
|
||||
public void testOgnlUtilExcludedAdditivity() throws Exception {
|
||||
Set<Class<?>> excludedClasses;
|
||||
Set<Pattern> excludedPackageNamePatterns;
|
||||
Iterator<Pattern> excludedPackageNamePatternsIterator;
|
||||
Set<String> excludedPackageNames;
|
||||
Set<String> patternStrings = new HashSet<>();
|
||||
|
||||
ognlUtil.setExcludedClasses("java.lang.String,java.lang.Integer");
|
||||
internalTestOgnlUtilExclusionsImmutable(ognlUtil);
|
||||
excludedClasses = ognlUtil.getExcludedClasses();
|
||||
assertNotNull("initial exluded classes null?", excludedClasses);
|
||||
assertTrue("initial exluded classes size not 2 after adds?", excludedClasses.size() == 2);
|
||||
assertTrue("String not in exclusions?", excludedClasses.contains(String.class));
|
||||
assertTrue("Integer not in exclusions?", excludedClasses.contains(Integer.class));
|
||||
ognlUtil.setExcludedClasses("java.lang.Boolean,java.lang.Double");
|
||||
internalTestOgnlUtilExclusionsImmutable(ognlUtil);
|
||||
excludedClasses = ognlUtil.getExcludedClasses();
|
||||
assertNotNull("updated exluded classes null?", excludedClasses);
|
||||
assertTrue("updated exluded classes size not 4 after adds?", excludedClasses.size() == 4);
|
||||
assertTrue("String not in exclusions?", excludedClasses.contains(String.class));
|
||||
assertTrue("Integer not in exclusions?", excludedClasses.contains(Integer.class));
|
||||
assertTrue("String not in exclusions?", excludedClasses.contains(Boolean.class));
|
||||
assertTrue("Integer not in exclusions?", excludedClasses.contains(Double.class));
|
||||
|
||||
ognlUtil.setExcludedPackageNamePatterns("fakepackage1.*,fakepackage2.*");
|
||||
internalTestOgnlUtilExclusionsImmutable(ognlUtil);
|
||||
excludedPackageNamePatterns = ognlUtil.getExcludedPackageNamePatterns();
|
||||
assertNotNull("initial exluded package name patterns null?", excludedPackageNamePatterns);
|
||||
assertTrue("initial exluded package name patterns size not 2 after adds?", excludedPackageNamePatterns.size() == 2);
|
||||
excludedPackageNamePatternsIterator = excludedPackageNamePatterns.iterator();
|
||||
patternStrings.clear();
|
||||
while (excludedPackageNamePatternsIterator.hasNext()) {
|
||||
Pattern pattern = excludedPackageNamePatternsIterator.next();
|
||||
patternStrings.add(pattern.pattern());
|
||||
}
|
||||
assertTrue("fakepackage1.* not in exclusions?", patternStrings.contains("fakepackage1.*"));
|
||||
assertTrue("fakepackage2.* not in exclusions?", patternStrings.contains("fakepackage2.*"));
|
||||
ognlUtil.setExcludedPackageNamePatterns("fakepackage3.*,fakepackage4.*");
|
||||
internalTestOgnlUtilExclusionsImmutable(ognlUtil);
|
||||
excludedPackageNamePatterns = ognlUtil.getExcludedPackageNamePatterns();
|
||||
assertNotNull("updated exluded package name patterns null?", excludedPackageNamePatterns);
|
||||
assertTrue("updated exluded package name patterns size not 4 after adds?", excludedPackageNamePatterns.size() == 4);
|
||||
excludedPackageNamePatternsIterator = excludedPackageNamePatterns.iterator();
|
||||
patternStrings.clear();
|
||||
while (excludedPackageNamePatternsIterator.hasNext()) {
|
||||
Pattern pattern = excludedPackageNamePatternsIterator.next();
|
||||
patternStrings.add(pattern.pattern());
|
||||
}
|
||||
assertTrue("fakepackage1.* not in exclusions?", patternStrings.contains("fakepackage1.*"));
|
||||
assertTrue("fakepackage2.* not in exclusions?", patternStrings.contains("fakepackage2.*"));
|
||||
assertTrue("fakepackage3.* not in exclusions?", patternStrings.contains("fakepackage3.*"));
|
||||
assertTrue("fakepackage4.* not in exclusions?", patternStrings.contains("fakepackage4.*"));
|
||||
|
||||
ognlUtil.setExcludedPackageNames("fakepackage1.package,fakepackage2.package");
|
||||
internalTestOgnlUtilExclusionsImmutable(ognlUtil);
|
||||
excludedPackageNames = ognlUtil.getExcludedPackageNames();
|
||||
assertNotNull("initial exluded package names null?", excludedPackageNames);
|
||||
assertTrue("initial exluded package names not 2 after adds?", excludedPackageNames.size() == 2);
|
||||
assertTrue("fakepackage1.package not in exclusions?", excludedPackageNames.contains("fakepackage1.package"));
|
||||
assertTrue("fakepackage2.package not in exclusions?", excludedPackageNames.contains("fakepackage2.package"));
|
||||
ognlUtil.setExcludedPackageNames("fakepackage3.package,fakepackage4.package");
|
||||
internalTestOgnlUtilExclusionsImmutable(ognlUtil);
|
||||
excludedPackageNames = ognlUtil.getExcludedPackageNames();
|
||||
assertNotNull("updated exluded package names null?", excludedPackageNames);
|
||||
assertTrue("updated exluded package names not 4 after adds?", excludedPackageNames.size() == 4);
|
||||
assertTrue("fakepackage1.package not in exclusions?", excludedPackageNames.contains("fakepackage1.package"));
|
||||
assertTrue("fakepackage2.package not in exclusions?", excludedPackageNames.contains("fakepackage2.package"));
|
||||
assertTrue("fakepackage3.package not in exclusions?", excludedPackageNames.contains("fakepackage3.package"));
|
||||
assertTrue("fakepackage4.package not in exclusions?", excludedPackageNames.contains("fakepackage4.package"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure getValue permits public static field access, but prevents non-public static field access
|
||||
*/
|
||||
public void testStaticFieldGetValue() {
|
||||
OgnlContext context = null;
|
||||
Object accessedValue;
|
||||
|
||||
try {
|
||||
reloadTestContainerConfiguration(false, false); // Test with allow static methods false
|
||||
context = (OgnlContext) ognlUtil.createDefaultContext(null);
|
||||
} catch (Exception ex) {
|
||||
fail("unable to reload test configuration? Exception: " + ex);
|
||||
}
|
||||
try {
|
||||
accessedValue = ognlUtil.getValue("@com.opensymphony.xwork2.ognl.OgnlUtilTest@STATIC_FINAL_PUBLIC_ATTRIBUTE", context, null);
|
||||
assertEquals("accessed field value not equal to actual?", accessedValue, STATIC_FINAL_PUBLIC_ATTRIBUTE);
|
||||
} catch (Exception ex) {
|
||||
fail("static final public field access failed ? Exception: " + ex);
|
||||
}
|
||||
try {
|
||||
accessedValue = ognlUtil.getValue("@com.opensymphony.xwork2.ognl.OgnlUtilTest@STATIC_PUBLIC_ATTRIBUTE", context, null);
|
||||
assertEquals("accessed field value not equal to actual?", accessedValue, STATIC_PUBLIC_ATTRIBUTE);
|
||||
} catch (Exception ex) {
|
||||
fail("static public field access failed ? Exception: " + ex);
|
||||
}
|
||||
try {
|
||||
accessedValue = ognlUtil.getValue("@com.opensymphony.xwork2.ognl.OgnlUtilTest@STATIC_FINAL_PACKAGE_ATTRIBUTE", context, null);
|
||||
fail("static final package field access succeeded?");
|
||||
} catch (Exception ex) {
|
||||
assertTrue("Exception not an OgnlException?", ex instanceof OgnlException);
|
||||
}
|
||||
try {
|
||||
accessedValue = ognlUtil.getValue("@com.opensymphony.xwork2.ognl.OgnlUtilTest@STATIC_PACKAGE_ATTRIBUTE", context, null);
|
||||
fail("static package field access succeeded?");
|
||||
} catch (Exception ex) {
|
||||
assertTrue("Exception not an OgnlException?", ex instanceof OgnlException);
|
||||
}
|
||||
try {
|
||||
accessedValue = ognlUtil.getValue("@com.opensymphony.xwork2.ognl.OgnlUtilTest@STATIC_FINAL_PROTECTED_ATTRIBUTE", context, null);
|
||||
fail("static final protected field access succeeded?");
|
||||
} catch (Exception ex) {
|
||||
assertTrue("Exception not an OgnlException?", ex instanceof OgnlException);
|
||||
}
|
||||
try {
|
||||
accessedValue = ognlUtil.getValue("@com.opensymphony.xwork2.ognl.OgnlUtilTest@STATIC_PROTECTED_ATTRIBUTE", context, null);
|
||||
fail("static protected field access succeeded?");
|
||||
} catch (Exception ex) {
|
||||
assertTrue("Exception not an OgnlException?", ex instanceof OgnlException);
|
||||
}
|
||||
try {
|
||||
accessedValue = ognlUtil.getValue("@com.opensymphony.xwork2.ognl.OgnlUtilTest@STATIC_FINAL_PRIVATE_ATTRIBUTE", context, null);
|
||||
fail("static final private field access succeeded?");
|
||||
} catch (Exception ex) {
|
||||
assertTrue("Exception not an OgnlException?", ex instanceof OgnlException);
|
||||
}
|
||||
try {
|
||||
accessedValue = ognlUtil.getValue("@com.opensymphony.xwork2.ognl.OgnlUtilTest@STATIC_PRIVATE_ATTRIBUTE", context, null);
|
||||
fail("static private field access succeeded?");
|
||||
} catch (Exception ex) {
|
||||
assertTrue("Exception not an OgnlException?", ex instanceof OgnlException);
|
||||
}
|
||||
|
||||
try {
|
||||
reloadTestContainerConfiguration(false, true); // Re-test with allow static methods true
|
||||
context = (OgnlContext) ognlUtil.createDefaultContext(null);
|
||||
} catch (Exception ex) {
|
||||
fail("unable to reload test configuration? Exception: " + ex);
|
||||
}
|
||||
try {
|
||||
accessedValue = ognlUtil.getValue("@com.opensymphony.xwork2.ognl.OgnlUtilTest@STATIC_FINAL_PUBLIC_ATTRIBUTE", context, null);
|
||||
assertEquals("accessed value not equal to actual?", accessedValue, STATIC_FINAL_PUBLIC_ATTRIBUTE);
|
||||
} catch (Exception ex) {
|
||||
fail("static final public field access failed ? Exception: " + ex);
|
||||
}
|
||||
try {
|
||||
accessedValue = ognlUtil.getValue("@com.opensymphony.xwork2.ognl.OgnlUtilTest@STATIC_PUBLIC_ATTRIBUTE", context, null);
|
||||
assertEquals("accessed value not equal to actual?", accessedValue, STATIC_PUBLIC_ATTRIBUTE);
|
||||
} catch (Exception ex) {
|
||||
fail("static public field access failed ? Exception: " + ex);
|
||||
}
|
||||
try {
|
||||
accessedValue = ognlUtil.getValue("@com.opensymphony.xwork2.ognl.OgnlUtilTest@STATIC_FINAL_PACKAGE_ATTRIBUTE", context, null);
|
||||
fail("static final package field access succeeded?");
|
||||
} catch (Exception ex) {
|
||||
assertTrue("Exception not an OgnlException?", ex instanceof OgnlException);
|
||||
}
|
||||
try {
|
||||
accessedValue = ognlUtil.getValue("@com.opensymphony.xwork2.ognl.OgnlUtilTest@STATIC_PACKAGE_ATTRIBUTE", context, null);
|
||||
fail("static package field access succeeded?");
|
||||
} catch (Exception ex) {
|
||||
assertTrue("Exception not an OgnlException?", ex instanceof OgnlException);
|
||||
}
|
||||
try {
|
||||
accessedValue = ognlUtil.getValue("@com.opensymphony.xwork2.ognl.OgnlUtilTest@STATIC_FINAL_PROTECTED_ATTRIBUTE", context, null);
|
||||
fail("static final protected field access succeeded?");
|
||||
} catch (Exception ex) {
|
||||
assertTrue("Exception not an OgnlException?", ex instanceof OgnlException);
|
||||
}
|
||||
try {
|
||||
accessedValue = ognlUtil.getValue("@com.opensymphony.xwork2.ognl.OgnlUtilTest@STATIC_PROTECTED_ATTRIBUTE", context, null);
|
||||
fail("static protected field access succeeded?");
|
||||
} catch (Exception ex) {
|
||||
assertTrue("Exception not an OgnlException?", ex instanceof OgnlException);
|
||||
}
|
||||
try {
|
||||
accessedValue = ognlUtil.getValue("@com.opensymphony.xwork2.ognl.OgnlUtilTest@STATIC_FINAL_PRIVATE_ATTRIBUTE", context, null);
|
||||
fail("static final private field access succeeded?");
|
||||
} catch (Exception ex) {
|
||||
assertTrue("Exception not an OgnlException?", ex instanceof OgnlException);
|
||||
}
|
||||
try {
|
||||
accessedValue = ognlUtil.getValue("@com.opensymphony.xwork2.ognl.OgnlUtilTest@STATIC_PRIVATE_ATTRIBUTE", context, null);
|
||||
fail("static private field access succeeded?");
|
||||
} catch (Exception ex) {
|
||||
assertTrue("Exception not an OgnlException?", ex instanceof OgnlException);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test OGNL Expression Max Length feature setting via OgnlUtil.
|
||||
*
|
||||
* @since 2.5.21
|
||||
*/
|
||||
public void testApplyExpressionMaxLength() {
|
||||
try {
|
||||
ognlUtil.applyExpressionMaxLength(null);
|
||||
} catch (Exception ex) {
|
||||
fail ("applyExpressionMaxLength did not accept null maxlength string ?");
|
||||
}
|
||||
try {
|
||||
ognlUtil.applyExpressionMaxLength("");
|
||||
} catch (Exception ex) {
|
||||
fail ("applyExpressionMaxLength did not accept empty maxlength string ?");
|
||||
}
|
||||
try {
|
||||
ognlUtil.applyExpressionMaxLength("-1");
|
||||
fail ("applyExpressionMaxLength accepted negative maxlength string ?");
|
||||
} catch (IllegalArgumentException iae) {
|
||||
// Expected rejection of -ive length.
|
||||
}
|
||||
try {
|
||||
ognlUtil.applyExpressionMaxLength("0");
|
||||
} catch (Exception ex) {
|
||||
fail ("applyExpressionMaxLength did not accept maxlength string 0 ?");
|
||||
}
|
||||
try {
|
||||
ognlUtil.applyExpressionMaxLength(Integer.toString(Integer.MAX_VALUE, 10));
|
||||
} catch (Exception ex) {
|
||||
fail ("applyExpressionMaxLength did not accept MAX_VALUE maxlength string ?");
|
||||
}
|
||||
}
|
||||
|
||||
private void internalTestInitialEmptyOgnlUtilExclusions(OgnlUtil ognlUtilParam) throws Exception {
|
||||
Set<Class<?>> excludedClasses = ognlUtilParam.getExcludedClasses();
|
||||
assertNotNull("parameter (default) exluded classes null?", excludedClasses);
|
||||
assertTrue("parameter (default) exluded classes not empty?", excludedClasses.isEmpty());
|
||||
|
||||
Set<Pattern> excludedPackageNamePatterns = ognlUtilParam.getExcludedPackageNamePatterns();
|
||||
assertNotNull("parameter (default) exluded package name patterns null?", excludedPackageNamePatterns);
|
||||
assertTrue("parameter (default) exluded package name patterns not empty?", excludedPackageNamePatterns.isEmpty());
|
||||
|
||||
Set<String> excludedPackageNames = ognlUtilParam.getExcludedPackageNames();
|
||||
assertNotNull("parameter (default) exluded package names null?", excludedPackageNames);
|
||||
assertTrue("parameter (default) exluded package names not empty?", excludedPackageNames.isEmpty());
|
||||
}
|
||||
|
||||
private void internalTestOgnlUtilExclusionsImmutable(OgnlUtil ognlUtilParam) throws Exception {
|
||||
Pattern somePattern = Pattern.compile("SomeRegexPattern");
|
||||
Set<Class<?>> excludedClasses = ognlUtilParam.getExcludedClasses();
|
||||
assertNotNull("parameter exluded classes null?", excludedClasses);
|
||||
try {
|
||||
excludedClasses.clear();
|
||||
fail("parameter excluded classes modifiable?");
|
||||
} catch (UnsupportedOperationException uoe) {
|
||||
// Expected failure
|
||||
}
|
||||
try {
|
||||
excludedClasses.add(Integer.class);
|
||||
fail("parameter excluded classes modifiable?");
|
||||
} catch (UnsupportedOperationException uoe) {
|
||||
// Expected failure
|
||||
}
|
||||
try {
|
||||
excludedClasses.remove(Integer.class);
|
||||
fail("parameter excluded classes modifiable?");
|
||||
} catch (UnsupportedOperationException uoe) {
|
||||
// Expected failure
|
||||
}
|
||||
|
||||
Set<Pattern> excludedPackageNamePatterns = ognlUtilParam.getExcludedPackageNamePatterns();
|
||||
assertNotNull("parameter exluded package name patterns null?", excludedPackageNamePatterns);
|
||||
try {
|
||||
excludedPackageNamePatterns.clear();
|
||||
fail("parameter excluded package name patterns modifiable?");
|
||||
} catch (UnsupportedOperationException uoe) {
|
||||
// Expected failure
|
||||
}
|
||||
try {
|
||||
excludedPackageNamePatterns.add(somePattern);
|
||||
fail("parameter excluded package name patterns modifiable?");
|
||||
} catch (UnsupportedOperationException uoe) {
|
||||
// Expected failure
|
||||
}
|
||||
try {
|
||||
excludedPackageNamePatterns.remove(somePattern);
|
||||
fail("parameter excluded package name patterns modifiable?");
|
||||
} catch (UnsupportedOperationException uoe) {
|
||||
// Expected failure
|
||||
}
|
||||
|
||||
Set<String> excludedPackageNames = ognlUtilParam.getExcludedPackageNames();
|
||||
assertNotNull("parameter exluded package names null?", excludedPackageNames);
|
||||
try {
|
||||
excludedPackageNames.clear();
|
||||
fail("parameter excluded package names modifiable?");
|
||||
} catch (UnsupportedOperationException uoe) {
|
||||
// Expected failure
|
||||
}
|
||||
try {
|
||||
excludedPackageNames.add("somepackagename");
|
||||
fail("parameter excluded package names modifiable?");
|
||||
} catch (UnsupportedOperationException uoe) {
|
||||
// Expected failure
|
||||
}
|
||||
try {
|
||||
excludedPackageNames.remove("somepackagename");
|
||||
fail("parameter excluded package names modifiable?");
|
||||
} catch (UnsupportedOperationException uoe) {
|
||||
// Expected failure
|
||||
}
|
||||
}
|
||||
|
||||
private void reloadTestContainerConfiguration(final boolean devMode, final boolean allowStatic) throws Exception {
|
||||
loadConfigurationProviders(new StubConfigurationProvider() {
|
||||
@Override
|
||||
public void register(ContainerBuilder builder,
|
||||
LocatableProperties props) throws ConfigurationException {
|
||||
props.setProperty(StrutsConstants.STRUTS_DEVMODE, "" + devMode);
|
||||
props.setProperty(XWorkConstants.DEV_MODE, "" + devMode);
|
||||
props.setProperty(StrutsConstants.STRUTS_ALLOW_STATIC_METHOD_ACCESS, "" + allowStatic);
|
||||
props.setProperty(XWorkConstants.ALLOW_STATIC_METHOD_ACCESS, "" + allowStatic);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static class Email {
|
||||
String address;
|
||||
|
||||
@@ -890,4 +1446,37 @@ public class OgnlUtilTest extends XWorkTestCase {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class TestBean1 {
|
||||
private String testBeanProperty;
|
||||
|
||||
public TestBean1() {
|
||||
testBeanProperty = "defaultTestBean1Property";
|
||||
}
|
||||
|
||||
public String getTestBeanProperty() {
|
||||
return testBeanProperty;
|
||||
}
|
||||
|
||||
public void setTestBeanProperty(String testBeanProperty) {
|
||||
this.testBeanProperty = testBeanProperty;
|
||||
}
|
||||
}
|
||||
|
||||
class TestBean2 {
|
||||
private String testBeanProperty;
|
||||
|
||||
public TestBean2() {
|
||||
testBeanProperty = "defaultTestBean2Property";
|
||||
}
|
||||
|
||||
public String getTestBeanProperty() {
|
||||
return testBeanProperty;
|
||||
}
|
||||
|
||||
public void setTestBeanProperty(String testBeanProperty) {
|
||||
this.testBeanProperty = testBeanProperty;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -19,30 +19,61 @@
|
||||
package com.opensymphony.xwork2.ognl;
|
||||
|
||||
import com.opensymphony.xwork2.*;
|
||||
import com.opensymphony.xwork2.config.ConfigurationException;
|
||||
import com.opensymphony.xwork2.conversion.impl.XWorkConverter;
|
||||
import com.opensymphony.xwork2.inject.Container;
|
||||
import com.opensymphony.xwork2.inject.ContainerBuilder;
|
||||
import com.opensymphony.xwork2.ognl.accessor.CompoundRootAccessor;
|
||||
import com.opensymphony.xwork2.test.StubConfigurationProvider;
|
||||
import com.opensymphony.xwork2.test.TestBean2;
|
||||
import com.opensymphony.xwork2.util.*;
|
||||
import com.opensymphony.xwork2.util.Foo;
|
||||
import com.opensymphony.xwork2.util.location.LocatableProperties;
|
||||
import com.opensymphony.xwork2.util.reflection.ReflectionContextState;
|
||||
import ognl.OgnlException;
|
||||
import ognl.PropertyAccessor;
|
||||
|
||||
import java.io.*;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.core.LogEvent;
|
||||
import org.apache.logging.log4j.core.Logger;
|
||||
import org.apache.logging.log4j.core.appender.AbstractAppender;
|
||||
import org.apache.struts2.StrutsConstants;
|
||||
import org.apache.struts2.config.DefaultPropertiesProvider;
|
||||
|
||||
|
||||
/**
|
||||
* Unit test for OgnlValueStack.
|
||||
*/
|
||||
public class OgnlValueStackTest extends XWorkTestCase {
|
||||
|
||||
// Fields for static field access test
|
||||
public static final String STATIC_FINAL_PUBLIC_ATTRIBUTE = "Static_Final_Public_Attribute";
|
||||
static final String STATIC_FINAL_PACKAGE_ATTRIBUTE = "Static_Final_Package_Attribute";
|
||||
protected static final String STATIC_FINAL_PROTECTED_ATTRIBUTE = "Static_Final_Protected_Attribute";
|
||||
private static final String STATIC_FINAL_PRIVATE_ATTRIBUTE = "Static_Final_Private_Attribute";
|
||||
public static String STATIC_PUBLIC_ATTRIBUTE = "Static_Public_Attribute";
|
||||
static String STATIC_PACKAGE_ATTRIBUTE = "Static_Package_Attribute";
|
||||
protected static String STATIC_PROTECTED_ATTRIBUTE = "Static_Protected_Attribute";
|
||||
private static String STATIC_PRIVATE_ATTRIBUTE = "Static_Private_Attribute";
|
||||
|
||||
|
||||
public static Integer staticNullMethod() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Integer staticInteger100Method() {
|
||||
return 100;
|
||||
}
|
||||
|
||||
private OgnlUtil ognlUtil;
|
||||
|
||||
@Override
|
||||
@@ -65,6 +96,33 @@ public class OgnlValueStackTest extends XWorkTestCase {
|
||||
return stack;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return current OgnlValueStackFactory instance from current container
|
||||
*/
|
||||
private OgnlValueStackFactory getValueStackFactory() {
|
||||
return (OgnlValueStackFactory) container.getInstance(ValueStackFactory.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads container and gets a new OgnlValueStackFactory with specified new configuration.
|
||||
* Intended for testing OgnlValueStack instance(s) that are minimally configured.
|
||||
* This should help ensure no underlying configuration/injection side-effects are responsible
|
||||
* for the behaviour of fundamental access control flags).
|
||||
*
|
||||
* @param allowStaticMethod new allowStaticMethod configuration
|
||||
* @return a new OgnlValueStackFactory with specified new configuration
|
||||
*/
|
||||
private OgnlValueStackFactory reloadValueStackFactory(Boolean allowStaticMethod) {
|
||||
try {
|
||||
reloadTestContainerConfiguration(allowStaticMethod);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
fail("Unable to reload container configuration and configure ognlValueStackFactory - exception: " + ex);
|
||||
}
|
||||
|
||||
return getValueStackFactory();
|
||||
}
|
||||
|
||||
public void testExpOverridesCanStackExpUp() throws Exception {
|
||||
Map expr1 = new LinkedHashMap();
|
||||
expr1.put("expr1", "'expr1value'");
|
||||
@@ -190,6 +248,95 @@ public class OgnlValueStackTest extends XWorkTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* monitors the resolution of WW-4999
|
||||
* @since 2.5.21
|
||||
*/
|
||||
public void testLogMissingProperties() {
|
||||
testLogMissingProperties(true);
|
||||
testLogMissingProperties(false);
|
||||
}
|
||||
|
||||
private void testLogMissingProperties(boolean logMissingProperties) {
|
||||
OgnlValueStack vs = createValueStack();
|
||||
vs.setLogMissingProperties("" + logMissingProperties);
|
||||
|
||||
Dog dog = new Dog();
|
||||
vs.push(dog);
|
||||
|
||||
TestAppender testAppender = new TestAppender();
|
||||
Logger logger = (Logger) LogManager.getLogger(OgnlValueStack.class);
|
||||
logger.addAppender(testAppender);
|
||||
testAppender.start();
|
||||
|
||||
try {
|
||||
vs.setValue("missingProp1", "missingProp1Value", false);
|
||||
vs.findValue("missingProp2", false);
|
||||
vs.findValue("missingProp3", Integer.class, false);
|
||||
|
||||
if (logMissingProperties) {
|
||||
assertEquals(3, testAppender.logEvents.size());
|
||||
assertEquals("Error setting value [missingProp1Value] with expression [missingProp1]",
|
||||
testAppender.logEvents.get(0).getMessage().getFormattedMessage());
|
||||
assertEquals("Could not find property [missingProp2]!",
|
||||
testAppender.logEvents.get(1).getMessage().getFormattedMessage());
|
||||
assertEquals("Could not find property [missingProp3]!",
|
||||
testAppender.logEvents.get(2).getMessage().getFormattedMessage());
|
||||
} else {
|
||||
assertEquals(0, testAppender.logEvents.size());
|
||||
}
|
||||
} finally {
|
||||
testAppender.stop();
|
||||
logger.removeAppender(testAppender);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* tests the correctness of distinguishing between user exception and NoSuchMethodException
|
||||
* @since 2.5.21
|
||||
*/
|
||||
public void testNotLogUserExceptionsAsMissingProperties() {
|
||||
OgnlValueStack vs = createValueStack();
|
||||
vs.setLogMissingProperties("true");
|
||||
|
||||
Dog dog = new Dog();
|
||||
vs.push(dog);
|
||||
|
||||
TestAppender testAppender = new TestAppender();
|
||||
Logger logger = (Logger) LogManager.getLogger(OgnlValueStack.class);
|
||||
logger.addAppender(testAppender);
|
||||
testAppender.start();
|
||||
|
||||
try {
|
||||
vs.setValue("exception", "exceptionValue", false);
|
||||
vs.findValue("exception", false);
|
||||
vs.findValue("exception", String.class, false);
|
||||
vs.findValue("getException()", false);
|
||||
vs.findValue("getException()", String.class, false);
|
||||
vs.findValue("bite", false);
|
||||
vs.findValue("bite", void.class, false);
|
||||
vs.findValue("getBite()", false);
|
||||
vs.findValue("getBite()", void.class, false);
|
||||
|
||||
vs.setLogMissingProperties("false");
|
||||
|
||||
vs.setValue("exception", "exceptionValue", false);
|
||||
vs.findValue("exception", false);
|
||||
vs.findValue("exception", String.class, false);
|
||||
vs.findValue("getException()", false);
|
||||
vs.findValue("getException()", String.class, false);
|
||||
vs.findValue("bite", false);
|
||||
vs.findValue("bite", void.class, false);
|
||||
vs.findValue("getBite()", false);
|
||||
vs.findValue("getBite()", void.class, false);
|
||||
|
||||
assertEquals(0, testAppender.logEvents.size());
|
||||
} finally {
|
||||
testAppender.stop();
|
||||
logger.removeAppender(testAppender);
|
||||
}
|
||||
}
|
||||
|
||||
public void testFailOnMissingMethod() {
|
||||
OgnlValueStack vs = createValueStack();
|
||||
|
||||
@@ -203,6 +350,38 @@ public class OgnlValueStackTest extends XWorkTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
public void testFailOnTooLongExpressionWithDefaultProperties() {
|
||||
loadConfigurationProviders(new DefaultPropertiesProvider());
|
||||
Integer repeat = Integer.parseInt(
|
||||
container.getInstance(String.class, StrutsConstants.STRUTS_OGNL_EXPRESSION_MAX_LENGTH));
|
||||
|
||||
OgnlValueStack vs = createValueStack();
|
||||
try {
|
||||
vs.findValue(StringUtils.repeat('.', repeat + 1), true);
|
||||
fail("Failed to throw exception on too long expression");
|
||||
} catch (Exception ex) {
|
||||
assertTrue(ex.getCause() instanceof OgnlException);
|
||||
assertTrue(((OgnlException) ex.getCause()).getReason() instanceof SecurityException);
|
||||
}
|
||||
}
|
||||
|
||||
public void testNotFailOnTooLongValueWithDefaultProperties() {
|
||||
loadConfigurationProviders(new DefaultPropertiesProvider());
|
||||
Integer repeat = Integer.parseInt(
|
||||
container.getInstance(String.class, StrutsConstants.STRUTS_OGNL_EXPRESSION_MAX_LENGTH));
|
||||
|
||||
OgnlValueStack vs = createValueStack();
|
||||
|
||||
Dog dog = new Dog();
|
||||
vs.push(dog);
|
||||
|
||||
String value = StringUtils.repeat('.', repeat + 1);
|
||||
|
||||
vs.setValue("name", value);
|
||||
|
||||
assertEquals(value, dog.getName());
|
||||
}
|
||||
|
||||
public void testFailsOnMethodThatThrowsException() {
|
||||
SimpleAction action = new SimpleAction();
|
||||
OgnlValueStack stack = createValueStack();
|
||||
@@ -576,7 +755,7 @@ public class OgnlValueStackTest extends XWorkTestCase {
|
||||
OgnlValueStack stack = createValueStack();
|
||||
stack.push(dog);
|
||||
assertNull(stack.findValue("nullMethod()"));
|
||||
assertNull(stack.findValue("@com.opensymphony.xwork2.util.OgnlValueStackTest@staticNullMethod()"));
|
||||
assertNull(stack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@staticNullMethod()"));
|
||||
}
|
||||
|
||||
public void testPetSoarBug() {
|
||||
@@ -594,7 +773,7 @@ public class OgnlValueStackTest extends XWorkTestCase {
|
||||
assertEquals("bar:123", vs.findValue("foo.bar", String.class));
|
||||
}
|
||||
|
||||
public void testPrimitiveSettingWithInvalidValueAddsFieldErrorInDevMode() {
|
||||
public void testPrimitiveSettingWithInvalidValueAddsFieldErrorInDevMode() throws Exception {
|
||||
SimpleAction action = new SimpleAction();
|
||||
OgnlValueStack stack = createValueStack();
|
||||
stack.getContext().put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
|
||||
@@ -613,7 +792,7 @@ public class OgnlValueStackTest extends XWorkTestCase {
|
||||
assertTrue(conversionErrors.containsKey("bar"));
|
||||
}
|
||||
|
||||
public void testPrimitiveSettingWithInvalidValueAddsFieldErrorInNonDevMode() {
|
||||
public void testPrimitiveSettingWithInvalidValueAddsFieldErrorInNonDevMode() throws Exception {
|
||||
SimpleAction action = new SimpleAction();
|
||||
OgnlValueStack stack = createValueStack();
|
||||
stack.getContext().put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
|
||||
@@ -831,6 +1010,49 @@ public class OgnlValueStackTest extends XWorkTestCase {
|
||||
assertNull(vs.findValue("@com.nothing.here.Nothing@BLAH"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Fails on 2.5.20 and earlier - tested on 2.5 (5/5/2016) and failed
|
||||
* @since 2.5.21
|
||||
*/
|
||||
public void testNotThrowExceptionOnTopMissingProperty() {
|
||||
OgnlValueStack vs = createValueStack();
|
||||
|
||||
Dog dog = new Dog();
|
||||
dog.setName("Rover");
|
||||
vs.push(dog);
|
||||
|
||||
Cat cat = new Cat();
|
||||
vs.push(cat);
|
||||
|
||||
vs.setValue("age", 12, true);
|
||||
|
||||
assertEquals(12, vs.findValue("age", true));
|
||||
assertEquals(12, vs.findValue("age", Integer.class, true));
|
||||
assertEquals(12, vs.findValue("getAge()", true));
|
||||
assertEquals(12, vs.findValue("getAge()", Integer.class, true));
|
||||
}
|
||||
|
||||
/**
|
||||
* Fails on 2.5.20 and earlier - tested on 2.5 (5/5/2016) and failed
|
||||
* @since 2.5.21
|
||||
*/
|
||||
public void testNotSkipUserReturnedNullValues() {
|
||||
OgnlValueStack vs = createValueStack();
|
||||
|
||||
Dog dog = new Dog();
|
||||
dog.setName("Rover");
|
||||
vs.push(dog);
|
||||
|
||||
Cat cat = new Cat();
|
||||
vs.push(cat);
|
||||
|
||||
// should not skip returned null values from cat.name
|
||||
assertNull(vs.findValue("name", true));
|
||||
assertNull(vs.findValue("name", String.class, true));
|
||||
assertNull(vs.findValue("getName()", true));
|
||||
assertNull(vs.findValue("getName()", String.class, true));
|
||||
}
|
||||
|
||||
public void testTop() {
|
||||
OgnlValueStack vs = createValueStack();
|
||||
|
||||
@@ -968,6 +1190,173 @@ public class OgnlValueStackTest extends XWorkTestCase {
|
||||
assertEquals(null, stack.findValue("address.country.name", String.class));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test a default OgnlValueStackFactory and OgnlValueStack generated by it
|
||||
* when a default configuration is used.
|
||||
*/
|
||||
public void testOgnlValueStackFromOgnlValueStackFactoryDefaultConfig() {
|
||||
OgnlValueStackFactory ognlValueStackFactory = getValueStackFactory();
|
||||
OgnlValueStack ognlValueStack = (OgnlValueStack) ognlValueStackFactory.createValueStack();
|
||||
Object accessedValue;
|
||||
|
||||
// An OgnlValueStackFactory using a container config with default (from XWorkConfigurationProvider)
|
||||
// static method access flag value present should prevent staticMethodAccess but allow staticFieldAccess.
|
||||
assertFalse("OgnlValueStackFactory staticMethodAccess (default flag) not false?", containerAllowsStaticMethodAccess(ognlValueStackFactory.container));
|
||||
// An OgnlValueStack created from the above OgnlValueStackFactory should allow public field access,
|
||||
// but prevent non-public field access. It should also deny static method access.
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@staticInteger100Method()");
|
||||
assertNull("able to access static method (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_FINAL_PUBLIC_ATTRIBUTE");
|
||||
assertEquals("accessed static final public field value not equal to actual?", accessedValue, STATIC_FINAL_PUBLIC_ATTRIBUTE);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_PUBLIC_ATTRIBUTE");
|
||||
assertEquals("accessed static public field value not equal to actual?", accessedValue, STATIC_PUBLIC_ATTRIBUTE);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_FINAL_PACKAGE_ATTRIBUTE");
|
||||
assertNull("accessed final package field (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_PACKAGE_ATTRIBUTE");
|
||||
assertNull("accessed package field (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_FINAL_PROTECTED_ATTRIBUTE");
|
||||
assertNull("accessed final protected field (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_PROTECTED_ATTRIBUTE");
|
||||
assertNull("accessed protected field (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_FINAL_PRIVATE_ATTRIBUTE");
|
||||
assertNull("accessed final private field (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_PRIVATE_ATTRIBUTE");
|
||||
assertNull("accessed private field (result not null) ?", accessedValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test a raw OgnlValueStackFactory and OgnlValueStack generated by it
|
||||
* when no static method access flag is set (not present in configuration).
|
||||
*/
|
||||
public void testOgnlValueStackFromOgnlValueStackFactoryNoFlagsSet() {
|
||||
OgnlValueStackFactory ognlValueStackFactory = reloadValueStackFactory(null);
|
||||
OgnlValueStack ognlValueStack = (OgnlValueStack) ognlValueStackFactory.createValueStack();
|
||||
Object accessedValue;
|
||||
|
||||
// An OgnlValueStackFactory using a container config with no static method access flag value present
|
||||
// (such as from a DefaultConfiguration vs. XWorkConfigurationProvider) should
|
||||
// prevent staticMethodAccess and allow staticFieldAccess.
|
||||
// Note: Under normal circumstances, explicit static method access configuration flag should be present,
|
||||
// but this specific check verifies what happens if that configuration flags is not present.
|
||||
assertFalse("OgnlValueStackFactory staticMethodAccess (no flag present) not false?", containerAllowsStaticMethodAccess(ognlValueStackFactory.container));
|
||||
// An OgnlValueStack created from the above OgnlValueStackFactory should allow public field access,
|
||||
// and prevent non-public field access. It should also deny static method access.
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@staticInteger100Method()");
|
||||
assertNull("able to access static method (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_FINAL_PUBLIC_ATTRIBUTE");
|
||||
assertEquals("accessed static final public field value not equal to actual?", accessedValue, STATIC_FINAL_PUBLIC_ATTRIBUTE);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_PUBLIC_ATTRIBUTE");
|
||||
assertEquals("accessed static public field value not equal to actual?", accessedValue, STATIC_PUBLIC_ATTRIBUTE);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_FINAL_PACKAGE_ATTRIBUTE");
|
||||
assertNull("accessed final package field (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_PACKAGE_ATTRIBUTE");
|
||||
assertNull("accessed package field (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_FINAL_PROTECTED_ATTRIBUTE");
|
||||
assertNull("accessed final protected field (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_PROTECTED_ATTRIBUTE");
|
||||
assertNull("accessed protected field (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_FINAL_PRIVATE_ATTRIBUTE");
|
||||
assertNull("accessed final private field (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_PRIVATE_ATTRIBUTE");
|
||||
assertNull("accessed private field (result not null) ?", accessedValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test a raw OgnlValueStackFactory and OgnlValueStack generated by it
|
||||
* when static method access flag is set to false.
|
||||
*/
|
||||
public void testOgnlValueStackFromOgnlValueStackFactoryNoStaticMethodAccess() {
|
||||
OgnlValueStackFactory ognlValueStackFactory = reloadValueStackFactory(false);
|
||||
OgnlValueStack ognlValueStack = (OgnlValueStack) ognlValueStackFactory.createValueStack();
|
||||
Object accessedValue;
|
||||
|
||||
// An OgnlValueStackFactory using a container config with static method access flag set false should
|
||||
// prevent staticMethodAccess and allow staticFieldAccess.
|
||||
assertFalse("OgnlValueStackFactory staticMethodAccess (set false) not false?", containerAllowsStaticMethodAccess(ognlValueStackFactory.container));
|
||||
// An OgnlValueStack created from the above OgnlValueStackFactory should allow public field access,
|
||||
// and prevent non-public field access. It should also deny static method access.
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@staticInteger100Method()");
|
||||
assertNull("able to access static method (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_FINAL_PUBLIC_ATTRIBUTE");
|
||||
assertEquals("accessed static final public field value not equal to actual?", accessedValue, STATIC_FINAL_PUBLIC_ATTRIBUTE);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_PUBLIC_ATTRIBUTE");
|
||||
assertEquals("accessed static public field value not equal to actual?", accessedValue, STATIC_PUBLIC_ATTRIBUTE);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_FINAL_PACKAGE_ATTRIBUTE");
|
||||
assertNull("accessed final package field (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_PACKAGE_ATTRIBUTE");
|
||||
assertNull("accessed package field (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_FINAL_PROTECTED_ATTRIBUTE");
|
||||
assertNull("accessed final protected field (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_PROTECTED_ATTRIBUTE");
|
||||
assertNull("accessed protected field (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_FINAL_PRIVATE_ATTRIBUTE");
|
||||
assertNull("accessed final private field (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_PRIVATE_ATTRIBUTE");
|
||||
assertNull("accessed private field (result not null) ?", accessedValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test a raw OgnlValueStackFactory and OgnlValueStack generated by it
|
||||
* when static method access flag set to true.
|
||||
*/
|
||||
public void testOgnlValueStackFromOgnlValueStackFactoryStaticMethodAccess() {
|
||||
OgnlValueStackFactory ognlValueStackFactory = reloadValueStackFactory(true);
|
||||
OgnlValueStack ognlValueStack = (OgnlValueStack) ognlValueStackFactory.createValueStack();
|
||||
Object accessedValue;
|
||||
|
||||
// An OgnlValueStackFactory using a container config with static method access flag set true should
|
||||
// allow both staticMethodAccess and staticFieldAccess.
|
||||
assertTrue("OgnlValueStackFactory staticMethodAccess (set true) not true?", containerAllowsStaticMethodAccess(ognlValueStackFactory.container));
|
||||
// An OgnlValueStack created from the above OgnlValueStackFactory should allow public field access,
|
||||
// but prevent non-public field access. It should also allow static method access.
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@staticInteger100Method()");
|
||||
assertNotNull("unable to access static method (result null) ?", accessedValue);
|
||||
assertEquals("accessed static method result not equal to expected?", accessedValue, staticInteger100Method());
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_FINAL_PUBLIC_ATTRIBUTE");
|
||||
assertEquals("accessed static final public field value not equal to actual?", accessedValue, STATIC_FINAL_PUBLIC_ATTRIBUTE);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_PUBLIC_ATTRIBUTE");
|
||||
assertEquals("accessed static public field value not equal to actual?", accessedValue, STATIC_PUBLIC_ATTRIBUTE);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_FINAL_PACKAGE_ATTRIBUTE");
|
||||
assertNull("accessed final package field (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_PACKAGE_ATTRIBUTE");
|
||||
assertNull("accessed package field (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_FINAL_PROTECTED_ATTRIBUTE");
|
||||
assertNull("accessed final protected field (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_PROTECTED_ATTRIBUTE");
|
||||
assertNull("accessed protected field (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_FINAL_PRIVATE_ATTRIBUTE");
|
||||
assertNull("accessed final private field (result not null) ?", accessedValue);
|
||||
accessedValue = ognlValueStack.findValue("@com.opensymphony.xwork2.ognl.OgnlValueStackTest@STATIC_PRIVATE_ATTRIBUTE");
|
||||
assertNull("accessed private field (result not null) ?", accessedValue);
|
||||
}
|
||||
|
||||
protected boolean containerAllowsStaticMethodAccess(Container checkContainer) {
|
||||
return Boolean.parseBoolean(checkContainer.getInstance(String.class, XWorkConstants.ALLOW_STATIC_METHOD_ACCESS));
|
||||
}
|
||||
|
||||
private void reloadTestContainerConfiguration(final Boolean allowStaticMethod) throws Exception {
|
||||
loadConfigurationProviders(new StubConfigurationProvider() {
|
||||
@Override
|
||||
public void register(ContainerBuilder builder,
|
||||
LocatableProperties props) throws ConfigurationException {
|
||||
// null values simulate undefined (by removing).
|
||||
// undefined values then should be evaluated to false
|
||||
if (props.containsKey(StrutsConstants.STRUTS_ALLOW_STATIC_METHOD_ACCESS)) {
|
||||
props.remove(StrutsConstants.STRUTS_ALLOW_STATIC_METHOD_ACCESS);
|
||||
}
|
||||
if (props.containsKey(XWorkConstants.ALLOW_STATIC_METHOD_ACCESS)) {
|
||||
props.remove(XWorkConstants.ALLOW_STATIC_METHOD_ACCESS);
|
||||
}
|
||||
if (allowStaticMethod != null) {
|
||||
props.setProperty(StrutsConstants.STRUTS_ALLOW_STATIC_METHOD_ACCESS, "" + allowStaticMethod);
|
||||
props.setProperty(XWorkConstants.ALLOW_STATIC_METHOD_ACCESS, "" + allowStaticMethod);
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
ognlUtil = container.getInstance(OgnlUtil.class);
|
||||
}
|
||||
|
||||
class BadJavaBean {
|
||||
private int count;
|
||||
private int count2;
|
||||
@@ -1078,6 +1467,19 @@ public class OgnlValueStackTest extends XWorkTestCase {
|
||||
this.displayName = displayName;
|
||||
}
|
||||
}
|
||||
|
||||
class TestAppender extends AbstractAppender {
|
||||
List<LogEvent> logEvents = new ArrayList<>();
|
||||
|
||||
TestAppender() {
|
||||
super("TestAppender", null, null, false, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void append(LogEvent logEvent) {
|
||||
logEvents.add(logEvent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum MyNumbers {
|
||||
|
||||
@@ -22,7 +22,6 @@ import com.opensymphony.xwork2.util.TextParseUtil;
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import java.lang.reflect.Member;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
@@ -62,7 +61,7 @@ public class SecurityMemberAccessTest extends TestCase {
|
||||
String propertyName = "stringField";
|
||||
Member member = FooBar.class.getDeclaredMethod("get" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1));
|
||||
|
||||
Set<Class<?>> excluded = new HashSet<Class<?>>();
|
||||
Set<Class<?>> excluded = new HashSet<>();
|
||||
excluded.add(FooBar.class);
|
||||
sma.setExcludedClasses(excluded);
|
||||
|
||||
@@ -108,7 +107,7 @@ public class SecurityMemberAccessTest extends TestCase {
|
||||
String propertyName = "barLogic";
|
||||
Member member = BarInterface.class.getMethod(propertyName);
|
||||
|
||||
Set<Class<?>> excluded = new HashSet<Class<?>>();
|
||||
Set<Class<?>> excluded = new HashSet<>();
|
||||
excluded.add(BarInterface.class);
|
||||
sma.setExcludedClasses(excluded);
|
||||
|
||||
@@ -126,7 +125,7 @@ public class SecurityMemberAccessTest extends TestCase {
|
||||
String propertyName = "fooLogic";
|
||||
Member member = FooBar.class.getMethod(propertyName);
|
||||
|
||||
Set<Class<?>> excluded = new HashSet<Class<?>>();
|
||||
Set<Class<?>> excluded = new HashSet<>();
|
||||
excluded.add(BarInterface.class);
|
||||
sma.setExcludedClasses(excluded);
|
||||
|
||||
@@ -158,7 +157,7 @@ public class SecurityMemberAccessTest extends TestCase {
|
||||
String propertyName = "barLogic";
|
||||
Member member = BarInterface.class.getMethod(propertyName);
|
||||
|
||||
Set<Class<?>> excluded = new HashSet<Class<?>>();
|
||||
Set<Class<?>> excluded = new HashSet<>();
|
||||
excluded.add(FooBarInterface.class);
|
||||
sma.setExcludedClasses(excluded);
|
||||
|
||||
@@ -173,7 +172,7 @@ public class SecurityMemberAccessTest extends TestCase {
|
||||
// given
|
||||
SecurityMemberAccess sma = new SecurityMemberAccess(false);
|
||||
|
||||
Set<Pattern> excluded = new HashSet<Pattern>();
|
||||
Set<Pattern> excluded = new HashSet<>();
|
||||
excluded.add(Pattern.compile("^" + FooBar.class.getPackage().getName().replaceAll("\\.", "\\\\.") + ".*"));
|
||||
sma.setExcludedPackageNamePatterns(excluded);
|
||||
|
||||
@@ -191,7 +190,7 @@ public class SecurityMemberAccessTest extends TestCase {
|
||||
// given
|
||||
SecurityMemberAccess sma = new SecurityMemberAccess(false);
|
||||
|
||||
Set<String> excluded = new HashSet<String>();
|
||||
Set<String> excluded = new HashSet<>();
|
||||
excluded.add(FooBar.class.getPackage().getName());
|
||||
sma.setExcludedPackageNames(excluded);
|
||||
|
||||
@@ -205,11 +204,11 @@ public class SecurityMemberAccessTest extends TestCase {
|
||||
assertFalse("stringField is accessible!", actual);
|
||||
}
|
||||
|
||||
public void testDefaultPackageExclusion() throws Exception {
|
||||
public void testDefaultPackageExclusion() {
|
||||
// given
|
||||
SecurityMemberAccess sma = new SecurityMemberAccess(false);
|
||||
|
||||
Set<Pattern> excluded = new HashSet<Pattern>();
|
||||
Set<Pattern> excluded = new HashSet<>();
|
||||
excluded.add(Pattern.compile("^" + FooBar.class.getPackage().getName().replaceAll("\\.", "\\\\.") + ".*"));
|
||||
sma.setExcludedPackageNamePatterns(excluded);
|
||||
|
||||
@@ -220,11 +219,11 @@ public class SecurityMemberAccessTest extends TestCase {
|
||||
assertFalse("default package is excluded!", actual);
|
||||
}
|
||||
|
||||
public void testDefaultPackageExclusion2() throws Exception {
|
||||
public void testDefaultPackageExclusion2() {
|
||||
// given
|
||||
SecurityMemberAccess sma = new SecurityMemberAccess(false);
|
||||
|
||||
Set<Pattern> excluded = new HashSet<Pattern>();
|
||||
Set<Pattern> excluded = new HashSet<>();
|
||||
excluded.add(Pattern.compile("^$"));
|
||||
sma.setExcludedPackageNamePatterns(excluded);
|
||||
|
||||
@@ -317,10 +316,10 @@ public class SecurityMemberAccessTest extends TestCase {
|
||||
public void testAccessPrimitiveDoubleWithNames() throws Exception {
|
||||
// given
|
||||
SecurityMemberAccess sma = new SecurityMemberAccess(false);
|
||||
sma.setExcludedPackageNames(TextParseUtil.commaDelimitedStringToSet("java.lang.,ognl,javax"));
|
||||
sma.setExcludedPackageNames(TextParseUtil.commaDelimitedStringToSet("ognl.,javax."));
|
||||
|
||||
|
||||
Set<Class<?>> excluded = new HashSet<Class<?>>();
|
||||
Set<Class<?>> excluded = new HashSet<>();
|
||||
excluded.add(Object.class);
|
||||
excluded.add(Runtime.class);
|
||||
excluded.add(System.class);
|
||||
@@ -369,7 +368,7 @@ public class SecurityMemberAccessTest extends TestCase {
|
||||
public void testAccessPrimitiveDoubleWithPackageRegExs() throws Exception {
|
||||
// given
|
||||
SecurityMemberAccess sma = new SecurityMemberAccess(false);
|
||||
Set<Pattern> patterns = new HashSet<Pattern>();
|
||||
Set<Pattern> patterns = new HashSet<>();
|
||||
patterns.add(Pattern.compile("^java\\.lang\\..*"));
|
||||
sma.setExcludedPackageNamePatterns(patterns);
|
||||
|
||||
@@ -386,7 +385,7 @@ public class SecurityMemberAccessTest extends TestCase {
|
||||
public void testAccessMemberAccessIsAccessible() throws Exception {
|
||||
// given
|
||||
SecurityMemberAccess sma = new SecurityMemberAccess(false);
|
||||
Set<Class<?>> excluded = new HashSet<Class<?>>();
|
||||
Set<Class<?>> excluded = new HashSet<>();
|
||||
excluded.add(ognl.MemberAccess.class);
|
||||
sma.setExcludedClasses(excluded);
|
||||
|
||||
@@ -404,7 +403,7 @@ public class SecurityMemberAccessTest extends TestCase {
|
||||
public void testAccessMemberAccessIsBlocked() throws Exception {
|
||||
// given
|
||||
SecurityMemberAccess sma = new SecurityMemberAccess(false);
|
||||
Set<Class<?>> excluded = new HashSet<Class<?>>();
|
||||
Set<Class<?>> excluded = new HashSet<>();
|
||||
excluded.add(SecurityMemberAccess.class);
|
||||
sma.setExcludedClasses(excluded);
|
||||
|
||||
@@ -419,6 +418,21 @@ public class SecurityMemberAccessTest extends TestCase {
|
||||
assertFalse(accessible);
|
||||
}
|
||||
|
||||
public void testPackageNameExclusionAsCommaDelimited() {
|
||||
// given
|
||||
SecurityMemberAccess sma = new SecurityMemberAccess(false);
|
||||
|
||||
|
||||
sma.setExcludedPackageNames(TextParseUtil.commaDelimitedStringToSet("java.lang."));
|
||||
|
||||
// when
|
||||
boolean actual = sma.isPackageExcluded(String.class.getPackage(), null);
|
||||
actual &= sma.isPackageExcluded(null, String.class.getPackage());
|
||||
|
||||
// then
|
||||
assertTrue("package java.lang. is accessible!", actual);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class FooBar implements FooBarInterface {
|
||||
|
||||
+62
@@ -22,6 +22,8 @@ import com.opensymphony.xwork2.XWorkTestCase;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class DefaultAcceptedPatternsCheckerTest extends XWorkTestCase {
|
||||
|
||||
@@ -82,4 +84,64 @@ public class DefaultAcceptedPatternsCheckerTest extends XWorkTestCase {
|
||||
assertTrue("Param with underscore wasn't accepted!", actual.isAccepted());
|
||||
}
|
||||
|
||||
public void testAcceptedPatternsImmutable() throws Exception {
|
||||
AcceptedPatternsChecker checker = new DefaultAcceptedPatternsChecker();
|
||||
|
||||
Set<Pattern> acceptedPatternSet = checker.getAcceptedPatterns();
|
||||
assertNotNull("default accepted patterns null?", acceptedPatternSet);
|
||||
assertFalse("default accepted patterns empty?", acceptedPatternSet.isEmpty());
|
||||
try {
|
||||
acceptedPatternSet.add(Pattern.compile("SomeRegexPattern") );
|
||||
fail ("accepted patterns modifiable?");
|
||||
} catch(UnsupportedOperationException uoe) {
|
||||
// Expected result
|
||||
}
|
||||
try {
|
||||
acceptedPatternSet.clear();
|
||||
fail ("accepted patterns modifiable?");
|
||||
} catch(UnsupportedOperationException uoe) {
|
||||
// Expected result
|
||||
}
|
||||
|
||||
checker.setAcceptedPatterns(DefaultAcceptedPatternsChecker.ACCEPTED_PATTERNS);
|
||||
acceptedPatternSet = checker.getAcceptedPatterns();
|
||||
assertNotNull("replaced default accepted patterns null?", acceptedPatternSet);
|
||||
assertFalse("replaced default accepted patterns empty?", acceptedPatternSet.isEmpty());
|
||||
try {
|
||||
acceptedPatternSet.add(Pattern.compile("SomeRegexPattern") );
|
||||
fail ("replaced accepted patterns modifiable?");
|
||||
} catch(UnsupportedOperationException uoe) {
|
||||
// Expected result
|
||||
}
|
||||
try {
|
||||
acceptedPatternSet.clear();
|
||||
fail ("accepted patterns modifiable?");
|
||||
} catch(UnsupportedOperationException uoe) {
|
||||
// Expected result
|
||||
}
|
||||
|
||||
String[] testPatternArray = {"exactmatch1", "exactmatch2", "exactmatch3", "exactmatch4"};
|
||||
checker.setAcceptedPatterns(testPatternArray);
|
||||
acceptedPatternSet = checker.getAcceptedPatterns();
|
||||
assertNotNull("replaced default accepted patterns null?", acceptedPatternSet);
|
||||
assertFalse("replaced default accepted patterns empty?", acceptedPatternSet.isEmpty());
|
||||
assertTrue("replaced default accepted patterns not size " + testPatternArray.length + "?",
|
||||
acceptedPatternSet.size() == testPatternArray.length);
|
||||
for (String testPatternArray1 : testPatternArray) {
|
||||
assertTrue(testPatternArray1 + " not accepted?", checker.isAccepted(testPatternArray1).isAccepted());
|
||||
}
|
||||
try {
|
||||
acceptedPatternSet.add(Pattern.compile("SomeRegexPattern") );
|
||||
fail ("replaced accepted patterns modifiable?");
|
||||
} catch(UnsupportedOperationException uoe) {
|
||||
// Expected result
|
||||
}
|
||||
try {
|
||||
acceptedPatternSet.clear();
|
||||
fail ("accepted patterns modifiable?");
|
||||
} catch(UnsupportedOperationException uoe) {
|
||||
// Expected result
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+63
@@ -23,6 +23,10 @@ import com.opensymphony.xwork2.XWorkTestCase;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
import static junit.framework.TestCase.assertNotNull;
|
||||
import static junit.framework.TestCase.fail;
|
||||
|
||||
public class DefaultExcludedPatternsCheckerTest extends XWorkTestCase {
|
||||
|
||||
@@ -155,4 +159,63 @@ public class DefaultExcludedPatternsCheckerTest extends XWorkTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
public void testExcludedPatternsImmutable() throws Exception {
|
||||
ExcludedPatternsChecker checker = new DefaultExcludedPatternsChecker();
|
||||
|
||||
Set<Pattern> excludedPatternSet = checker.getExcludedPatterns();
|
||||
assertNotNull("default excluded patterns null?", excludedPatternSet);
|
||||
assertFalse("default excluded patterns empty?", excludedPatternSet.isEmpty());
|
||||
try {
|
||||
excludedPatternSet.add(Pattern.compile("SomeRegexPattern") );
|
||||
fail ("excluded patterns modifiable?");
|
||||
} catch(UnsupportedOperationException uoe) {
|
||||
// Expected result
|
||||
}
|
||||
try {
|
||||
excludedPatternSet.clear();
|
||||
fail ("excluded patterns modifiable?");
|
||||
} catch(UnsupportedOperationException uoe) {
|
||||
// Expected result
|
||||
}
|
||||
|
||||
checker.setExcludedPatterns(DefaultExcludedPatternsChecker.EXCLUDED_PATTERNS);
|
||||
excludedPatternSet = checker.getExcludedPatterns();
|
||||
assertNotNull("default excluded patterns null?", excludedPatternSet);
|
||||
assertFalse("default excluded patterns empty?", excludedPatternSet.isEmpty());
|
||||
try {
|
||||
excludedPatternSet.add(Pattern.compile("SomeRegexPattern") );
|
||||
fail ("excluded patterns modifiable?");
|
||||
} catch(UnsupportedOperationException uoe) {
|
||||
// Expected result
|
||||
}
|
||||
try {
|
||||
excludedPatternSet.clear();
|
||||
fail ("excluded patterns modifiable?");
|
||||
} catch(UnsupportedOperationException uoe) {
|
||||
// Expected result
|
||||
}
|
||||
|
||||
String[] testPatternArray = {"exactmatch1", "exactmatch2", "exactmatch3", "exactmatch4"};
|
||||
checker.setExcludedPatterns(testPatternArray);
|
||||
excludedPatternSet = checker.getExcludedPatterns();
|
||||
assertNotNull("default excluded patterns null?", excludedPatternSet);
|
||||
assertFalse("default excluded patterns empty?", excludedPatternSet.isEmpty());
|
||||
assertTrue("replaced default accepted patterns not size " + testPatternArray.length + "?",
|
||||
excludedPatternSet.size() == testPatternArray.length);
|
||||
for (String testPatternArray1 : testPatternArray) {
|
||||
assertTrue(testPatternArray1 + " not excluded?", checker.isExcluded(testPatternArray1).isExcluded());
|
||||
}
|
||||
try {
|
||||
excludedPatternSet.add(Pattern.compile("SomeRegexPattern") );
|
||||
fail ("excluded patterns modifiable?");
|
||||
} catch(UnsupportedOperationException uoe) {
|
||||
// Expected result
|
||||
}
|
||||
try {
|
||||
excludedPatternSet.clear();
|
||||
fail ("excluded patterns modifiable?");
|
||||
} catch(UnsupportedOperationException uoe) {
|
||||
// Expected result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,11 +19,17 @@
|
||||
package com.opensymphony.xwork2.util;
|
||||
|
||||
import com.opensymphony.xwork2.XWorkTestCase;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Vector;
|
||||
|
||||
public class ClassPathFinderTest extends XWorkTestCase {
|
||||
|
||||
|
||||
public void testFinder() {
|
||||
ClassPathFinder finder = new ClassPathFinder();
|
||||
finder.setPattern("**/xwork-test-wildcard-*.xml");
|
||||
@@ -52,4 +58,50 @@ public class ClassPathFinderTest extends XWorkTestCase {
|
||||
|
||||
}
|
||||
|
||||
public void testFinderNotURLClassLoader() throws Exception {
|
||||
NotURLClassLoader loader = new NotURLClassLoader(Thread.currentThread().getContextClassLoader());
|
||||
Thread.currentThread().setContextClassLoader(loader);
|
||||
|
||||
try {
|
||||
Class<?> clazz = loader.loadClass(ClassPathFinderTest.class.getName());
|
||||
Object test = clazz.getConstructor().newInstance();
|
||||
|
||||
clazz.getMethod("testFinder").invoke(test);
|
||||
} finally {
|
||||
Thread.currentThread().setContextClassLoader(loader.parentClassLoader);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private class NotURLClassLoader extends ClassLoader {
|
||||
private Map<String, Class<?>> loadedClasses = new HashMap<>();
|
||||
private ClassLoader parentClassLoader;
|
||||
|
||||
NotURLClassLoader(ClassLoader parentClassLoader) {
|
||||
super(null);
|
||||
this.parentClassLoader = parentClassLoader;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<?> findClass(String name) throws ClassNotFoundException {
|
||||
if (!loadedClasses.containsKey(name)) {
|
||||
try {
|
||||
byte[] classBits = IOUtils.toByteArray(ClassLoader.getSystemResourceAsStream(
|
||||
name.replace('.', '/') + ".class"));
|
||||
loadedClasses.put(name, defineClass(name, classBits, 0, classBits.length));
|
||||
} catch (IOException e) {
|
||||
throw new ClassNotFoundException("class " + name + " is not findable", e);
|
||||
} catch (Exception e) {
|
||||
loadedClasses.put(name, parentClassLoader.loadClass(name));
|
||||
}
|
||||
}
|
||||
|
||||
return loadedClasses.get(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Enumeration<URL> findResources(String name) throws IOException {
|
||||
return parentClassLoader.getResources(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,16 +21,9 @@ package com.opensymphony.xwork2.util;
|
||||
import com.opensymphony.xwork2.FileManager;
|
||||
import com.opensymphony.xwork2.FileManagerFactory;
|
||||
import com.opensymphony.xwork2.XWorkTestCase;
|
||||
import com.opensymphony.xwork2.util.fs.DefaultFileManager;
|
||||
import org.apache.struts2.util.fs.JBossFileManager;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.net.URLStreamHandler;
|
||||
import java.net.URLStreamHandlerFactory;
|
||||
import java.net.*;
|
||||
|
||||
/**
|
||||
* FileManager Tester.
|
||||
@@ -49,23 +42,40 @@ public class DefaultFileManagerTest extends XWorkTestCase {
|
||||
fileManager = container.getInstance(FileManagerFactory.class).getFileManager();
|
||||
}
|
||||
|
||||
public void disabled_testGetFileInJar() throws Exception {
|
||||
testLoadFile("xwork-jar.xml");
|
||||
testLoadFile("xwork - jar.xml");
|
||||
testLoadFile("xwork-zip.xml");
|
||||
testLoadFile("xwork - zip.xml");
|
||||
testLoadFile("xwork-jar2.xml");
|
||||
testLoadFile("xwork - jar2.xml");
|
||||
testLoadFile("xwork-zip2.xml");
|
||||
testLoadFile("xwork - zip2.xml");
|
||||
public void testGetFileInJar() throws Exception {
|
||||
testLoadFile("xwork-jar.xml", false);
|
||||
testLoadFile("xwork - jar.xml", false);
|
||||
testLoadFile("xwork-zip.xml", false);
|
||||
testLoadFile("xwork - zip.xml", false);
|
||||
testLoadFile("xwork-jar2.xml", false);
|
||||
testLoadFile("xwork - jar2.xml", false);
|
||||
testLoadFile("xwork-zip2.xml", false);
|
||||
testLoadFile("xwork - zip2.xml", false);
|
||||
|
||||
testLoadFile("xwork-jar.xml", true);
|
||||
testLoadFile("xwork - jar.xml", true);
|
||||
testLoadFile("xwork-zip.xml", true);
|
||||
testLoadFile("xwork - zip.xml", true);
|
||||
testLoadFile("xwork-jar2.xml", true);
|
||||
testLoadFile("xwork - jar2.xml", true);
|
||||
testLoadFile("xwork-zip2.xml", true);
|
||||
testLoadFile("xwork - zip2.xml", true);
|
||||
}
|
||||
|
||||
private void testLoadFile(String fileName) {
|
||||
fileManager.setReloadingConfigs(true);
|
||||
private void testLoadFile(String fileName, boolean reloadConfigs) throws Exception {
|
||||
fileManager.setReloadingConfigs(reloadConfigs);
|
||||
URL url = ClassLoaderUtil.getResource(fileName, DefaultFileManagerTest.class);
|
||||
InputStream file = fileManager.loadFile(url);
|
||||
assertNotNull(file);
|
||||
assertTrue(fileManager.fileNeedsReloading(fileName));
|
||||
file.close();
|
||||
assertFalse(fileManager.fileNeedsReloading(url.toString()));
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
JarURLConnection conn = (JarURLConnection) url.openConnection();
|
||||
conn.getJarEntry().setTime(now + 60000);
|
||||
conn.getInputStream().close();
|
||||
|
||||
assertEquals(reloadConfigs, fileManager.fileNeedsReloading(url.toString()));
|
||||
}
|
||||
|
||||
public void testReloadingConfigs() throws Exception {
|
||||
|
||||
@@ -249,6 +249,71 @@ public class StrutsLocalizedTextProviderTest extends XWorkTestCase {
|
||||
assertEquals("Hallo", rbGermany.getString("hello"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Unit test to confirm expected behaviour of "clearing methods" provided to
|
||||
* StrutsLocalizedTextProvider (from AbstractLocalizedTextProvider).
|
||||
*/
|
||||
public void testLocalizedTextProviderClearingMethods() {
|
||||
TestStrutsLocalizedTextProvider testStrutsLocalizedTextProvider = new TestStrutsLocalizedTextProvider();
|
||||
assertTrue("testStrutsLocalizedTextProvider not instance of AbstractLocalizedTextProvider ?",
|
||||
testStrutsLocalizedTextProvider instanceof AbstractLocalizedTextProvider);
|
||||
assertEquals("testStrutsLocalizedTextProvider starting default bundle map size not 0 before any retrievals ?",
|
||||
0, testStrutsLocalizedTextProvider.currentBundlesMapSize());
|
||||
|
||||
// Access the two default bundles to populate their cache entries and test bundle map size
|
||||
ResourceBundle tempBundle = testStrutsLocalizedTextProvider.findResourceBundle(
|
||||
TestStrutsLocalizedTextProvider.XWORK_MESSAGES_BUNDLE, Locale.ENGLISH);
|
||||
assertNotNull("XWORK_MESSAGES_BUNDLE retrieval null ?", tempBundle);
|
||||
tempBundle = testStrutsLocalizedTextProvider.findResourceBundle(
|
||||
TestStrutsLocalizedTextProvider.STRUTS_MESSAGES_BUNDLE, Locale.ENGLISH);
|
||||
assertNotNull("STRUTS_MESSAGES_BUNDLE retrieval null ?", tempBundle);
|
||||
assertEquals("testStrutsLocalizedTextProvider bundle map size not 2 after retrievals ?",
|
||||
2, testStrutsLocalizedTextProvider.currentBundlesMapSize());
|
||||
|
||||
// Add and then access four test bundles to populate their cache entries and test bundle map size
|
||||
testStrutsLocalizedTextProvider.addDefaultResourceBundle("com/opensymphony/xwork2/util/LocalizedTextUtilTest");
|
||||
testStrutsLocalizedTextProvider.addDefaultResourceBundle("com/opensymphony/xwork2/util/FindMe");
|
||||
testStrutsLocalizedTextProvider.addDefaultResourceBundle("com/opensymphony/xwork2/SimpleAction");
|
||||
testStrutsLocalizedTextProvider.addDefaultResourceBundle("com/opensymphony/xwork2/test");
|
||||
tempBundle = testStrutsLocalizedTextProvider.findResourceBundle(
|
||||
"com/opensymphony/xwork2/util/LocalizedTextUtilTest", Locale.ENGLISH);
|
||||
assertNotNull("com/opensymphony/xwork2/util/LocalizedTextUtilTest retrieval null ?", tempBundle);
|
||||
tempBundle = testStrutsLocalizedTextProvider.findResourceBundle(
|
||||
"com/opensymphony/xwork2/util/FindMe", Locale.ENGLISH);
|
||||
assertNotNull("com/opensymphony/xwork2/util/FindMe retrieval null ?", tempBundle);
|
||||
tempBundle = testStrutsLocalizedTextProvider.findResourceBundle(
|
||||
"com/opensymphony/xwork2/SimpleAction", Locale.ENGLISH);
|
||||
assertNotNull("com/opensymphony/xwork2/SimpleAction retrieval null ?", tempBundle);
|
||||
tempBundle = testStrutsLocalizedTextProvider.findResourceBundle(
|
||||
"com/opensymphony/xwork2/test", Locale.ENGLISH);
|
||||
assertNotNull("com/opensymphony/xwork2/test retrieval null ?", tempBundle);
|
||||
assertEquals("testStrutsLocalizedTextProvider bundle map size not 6 after retrievals ?",
|
||||
6, testStrutsLocalizedTextProvider.currentBundlesMapSize());
|
||||
|
||||
// Expect the call to be ineffective due to no locale (but shouldn't throw an Exception or cause failure)
|
||||
testStrutsLocalizedTextProvider.callClearBundleNoLocale("com/opensymphony/xwork2/test");
|
||||
assertEquals("testStrutsLocalizedTextProvider bundle map size not 6 after non-locale clear call ?",
|
||||
6, testStrutsLocalizedTextProvider.currentBundlesMapSize());
|
||||
|
||||
// Expect the call to function with bundle name + locale. Remove all four of the non-default
|
||||
// bundles and confirm the bundle map size changes.
|
||||
testStrutsLocalizedTextProvider.callClearBundleWithLocale("com/opensymphony/xwork2/test", Locale.ENGLISH);
|
||||
assertEquals("testStrutsLocalizedTextProvider bundle map size not 5 after locale clear call ?",
|
||||
5, testStrutsLocalizedTextProvider.currentBundlesMapSize());
|
||||
testStrutsLocalizedTextProvider.callClearBundleWithLocale("com/opensymphony/xwork2/SimpleAction", Locale.ENGLISH);
|
||||
assertEquals("testStrutsLocalizedTextProvider bundle map size not 4 after locale clear call ?",
|
||||
4, testStrutsLocalizedTextProvider.currentBundlesMapSize());
|
||||
testStrutsLocalizedTextProvider.callClearBundleWithLocale("com/opensymphony/xwork2/util/FindMe", Locale.ENGLISH);
|
||||
assertEquals("testStrutsLocalizedTextProvider bundle map size not 3 after locale clear call ?",
|
||||
3, testStrutsLocalizedTextProvider.currentBundlesMapSize());
|
||||
testStrutsLocalizedTextProvider.callClearBundleWithLocale("com/opensymphony/xwork2/util/LocalizedTextUtilTest", Locale.ENGLISH);
|
||||
assertEquals("testStrutsLocalizedTextProvider bundle map size not 2 after locale clear call ?",
|
||||
2, testStrutsLocalizedTextProvider.currentBundlesMapSize());
|
||||
|
||||
// Confirm the missing bundles cache clearing method does not produce any Exceptions or failures.
|
||||
testStrutsLocalizedTextProvider.callClearMissingBundlesCache();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
@@ -267,4 +332,25 @@ public class StrutsLocalizedTextProviderTest extends XWorkTestCase {
|
||||
localizedTextProvider = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Basic test class to allow specific testing of StrutsLocalizedTextProvider
|
||||
*/
|
||||
class TestStrutsLocalizedTextProvider extends StrutsLocalizedTextProvider {
|
||||
|
||||
public void callClearBundleNoLocale(String bundleName) {
|
||||
super.clearBundle(bundleName);
|
||||
}
|
||||
|
||||
public void callClearBundleWithLocale(String bundleName, Locale locale) {
|
||||
super.clearBundle(bundleName, locale);
|
||||
}
|
||||
|
||||
public void callClearMissingBundlesCache() {
|
||||
super.clearMissingBundlesCache();
|
||||
}
|
||||
|
||||
public int currentBundlesMapSize() {
|
||||
return super.bundlesMap.size();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,9 @@ package com.opensymphony.xwork2.util.fs;
|
||||
import com.opensymphony.xwork2.FileManager;
|
||||
import com.opensymphony.xwork2.FileManagerFactory;
|
||||
import com.opensymphony.xwork2.XWorkTestCase;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.commons.io.filefilter.WildcardFileFilter;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
@@ -30,6 +32,9 @@ import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.net.URLStreamHandler;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.jar.Attributes;
|
||||
import java.util.jar.JarOutputStream;
|
||||
import java.util.jar.Manifest;
|
||||
@@ -45,10 +50,13 @@ public class JarEntryRevisionTest extends XWorkTestCase {
|
||||
fileManager = container.getInstance(FileManagerFactory.class).getFileManager();
|
||||
}
|
||||
|
||||
private void createJarFile(long time) throws Exception {
|
||||
private String createJarFile(long time) throws Exception {
|
||||
Manifest manifest = new Manifest();
|
||||
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
|
||||
FileOutputStream fos = new FileOutputStream("target/JarEntryRevisionTest_testNeedsReloading.jar", false);
|
||||
Path jarPath = Paths.get(Thread.currentThread().getContextClassLoader()
|
||||
.getResource("xwork-jar.jar").toURI()).getParent();
|
||||
File jarFile = jarPath.resolve("JarEntryRevisionTest_testNeedsReloading.jar").toFile();
|
||||
FileOutputStream fos = new FileOutputStream(jarFile, false);
|
||||
JarOutputStream target = new JarOutputStream(fos, manifest);
|
||||
target.putNextEntry(new ZipEntry("com/opensymphony/xwork2/util/fs/"));
|
||||
ZipEntry entry = new ZipEntry("com/opensymphony/xwork2/util/fs/JarEntryRevisionTest.class");
|
||||
@@ -60,13 +68,14 @@ public class JarEntryRevisionTest extends XWorkTestCase {
|
||||
target.closeEntry();
|
||||
target.close();
|
||||
fos.close();
|
||||
|
||||
return jarFile.toURI().toURL().toExternalForm();
|
||||
}
|
||||
|
||||
public void testNeedsReloading() throws Exception {
|
||||
long now = System.currentTimeMillis();
|
||||
|
||||
createJarFile(now);
|
||||
URL url = new URL("jar:file:target/JarEntryRevisionTest_testNeedsReloading.jar!/com/opensymphony/xwork2/util/fs/JarEntryRevisionTest.class");
|
||||
URL url = new URL("jar:" + createJarFile(now) + "!/com/opensymphony/xwork2/util/fs/JarEntryRevisionTest.class");
|
||||
Revision entry = JarEntryRevision.build(url, fileManager);
|
||||
assert entry != null;
|
||||
assertFalse(entry.needsReloading());
|
||||
@@ -78,9 +87,8 @@ public class JarEntryRevisionTest extends XWorkTestCase {
|
||||
public void testNeedsReloadingWithContainerProvidedURLConnection() throws Exception {
|
||||
long now = System.currentTimeMillis();
|
||||
|
||||
createJarFile(now);
|
||||
URL url = new URL(null,
|
||||
"jar:file:target/JarEntryRevisionTest_testNeedsReloading.jar!/com/opensymphony/xwork2/util/fs/JarEntryRevisionTest.class",
|
||||
"jar:" + createJarFile(now) + "!/com/opensymphony/xwork2/util/fs/JarEntryRevisionTest.class",
|
||||
new ContainerProvidedURLStreamHandler());
|
||||
Revision entry = JarEntryRevision.build(url, fileManager);
|
||||
assert entry != null;
|
||||
@@ -93,9 +101,7 @@ public class JarEntryRevisionTest extends XWorkTestCase {
|
||||
public void testNeedsReloadingWithContainerProvidedURLConnectionEmptyProtocol() throws Exception {
|
||||
long now = System.currentTimeMillis();
|
||||
|
||||
createJarFile(now);
|
||||
File targetDir = new File("target");
|
||||
String targetUrlStr = targetDir.toURI().toURL().toString();
|
||||
String targetUrlStr = createJarFile(now);
|
||||
if (targetUrlStr.startsWith("file:")) {
|
||||
targetUrlStr = targetUrlStr.substring(5);//emptying protocol; we expect framework will fix it
|
||||
}
|
||||
@@ -103,7 +109,7 @@ public class JarEntryRevisionTest extends XWorkTestCase {
|
||||
targetUrlStr = targetUrlStr.substring(1);//we expect framework will fix it also
|
||||
}
|
||||
URL url = new URL(null,
|
||||
"zip:" + targetUrlStr + "JarEntryRevisionTest_testNeedsReloading.jar!/com/opensymphony/xwork2/util/fs/JarEntryRevisionTest.class",
|
||||
"zip:" + targetUrlStr + "!/com/opensymphony/xwork2/util/fs/JarEntryRevisionTest.class",
|
||||
new ContainerProvidedURLStreamHandler());
|
||||
Revision entry = JarEntryRevision.build(url, fileManager);
|
||||
assert entry != null;
|
||||
@@ -113,6 +119,20 @@ public class JarEntryRevisionTest extends XWorkTestCase {
|
||||
assertTrue(entry.needsReloading());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void tearDown() throws Exception {
|
||||
Path tmpFile = Files.createTempFile("jar_cache", null);
|
||||
Path tmpFolder = tmpFile.getParent();
|
||||
int count = FileUtils.listFiles(tmpFolder.toFile(), new WildcardFileFilter("jar_cache*"),
|
||||
null).size();
|
||||
if (tmpFile.toFile().delete()) {
|
||||
count--;
|
||||
}
|
||||
assertEquals(0, count);
|
||||
|
||||
super.tearDown();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* WW-4901 Simulating container implementation of {@link URL#openConnection()}
|
||||
|
||||
@@ -20,6 +20,7 @@ package org.apache.struts2;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
import java.util.StringTokenizer;
|
||||
|
||||
/**
|
||||
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.apache.struts2.dispatcher;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import org.apache.struts2.StrutsInternalTestCase;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.apache.struts2.views.freemarker.FreemarkerManager;
|
||||
import static org.easymock.EasyMock.anyInt;
|
||||
import static org.easymock.EasyMock.anyString;
|
||||
import static org.easymock.EasyMock.createMock;
|
||||
import static org.easymock.EasyMock.expect;
|
||||
import static org.easymock.EasyMock.expectLastCall;
|
||||
import static org.easymock.EasyMock.replay;
|
||||
|
||||
public class DefaultDispatcherErrorHandlerTest extends StrutsInternalTestCase {
|
||||
private HttpServletRequest requestMock;
|
||||
private HttpServletResponse responseMock;
|
||||
|
||||
/**
|
||||
* Test to exercise the code path and prove handleError() will output
|
||||
* the desired log warning when an IOException is thrown with devMode false.
|
||||
*/
|
||||
public void testHandleErrorIOException() {
|
||||
DefaultDispatcherErrorHandler defaultDispatcherErrorHandler = new DefaultDispatcherErrorHandler();
|
||||
defaultDispatcherErrorHandler.setDevMode("false");
|
||||
defaultDispatcherErrorHandler.setFreemarkerManager(dispatcher.getContainer().getInstance(FreemarkerManager.class));
|
||||
defaultDispatcherErrorHandler.init(dispatcher.servletContext);
|
||||
Exception fakeException = new Exception("Fake Exception, devMode false");
|
||||
try {
|
||||
requestMock.setAttribute("javax.servlet.error.exception", fakeException);
|
||||
expectLastCall();
|
||||
requestMock.setAttribute("javax.servlet.jsp.jspException", fakeException);
|
||||
expectLastCall();
|
||||
responseMock.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fakeException.getMessage());
|
||||
expectLastCall().andStubThrow(new IOException("Fake IO Exception (SC_INTERNAL_SERVER_ERROR, devMode false)"));
|
||||
replay(responseMock);
|
||||
} catch (IOException ioe) {
|
||||
fail("Mock sendError call setup failed. Ex: " + ioe);
|
||||
}
|
||||
defaultDispatcherErrorHandler.handleError(requestMock, responseMock, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fakeException);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test to exercise the code path and prove handleError() will output
|
||||
* the desired log warning when an IOException is thrown with devMode true.
|
||||
*/
|
||||
public void testHandleErrorIOExceptionDevMode() {
|
||||
DefaultDispatcherErrorHandler defaultDispatcherErrorHandler = new DefaultDispatcherErrorHandler();
|
||||
defaultDispatcherErrorHandler.setDevMode("true");
|
||||
defaultDispatcherErrorHandler.setFreemarkerManager(dispatcher.getContainer().getInstance(FreemarkerManager.class));
|
||||
defaultDispatcherErrorHandler.init(dispatcher.servletContext);
|
||||
Exception fakeException = new Exception("Fake Exception, devMode true");
|
||||
try {
|
||||
responseMock.setContentType("text/html");
|
||||
expectLastCall().andStubThrow(new IllegalStateException("Fake IllegalState Exception (report write)")); // Fake error during report write
|
||||
responseMock.sendError(anyInt(), anyString());
|
||||
expectLastCall().andStubThrow(new IOException("Fake IO Exception (SC_INTERNAL_SERVER_ERROR, devMode true)"));
|
||||
replay(responseMock);
|
||||
} catch (IOException ioe) {
|
||||
fail("Mock sendError call setup failed. Ex: " + ioe);
|
||||
}
|
||||
defaultDispatcherErrorHandler.handleError(requestMock, responseMock, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fakeException);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test to exercise the code path and prove handleError() will output
|
||||
* the desired log warning when an IllegalStateException is thrown with devMode false.
|
||||
*/
|
||||
public void testHandleErrorIllegalStateException() {
|
||||
DefaultDispatcherErrorHandler defaultDispatcherErrorHandler = new DefaultDispatcherErrorHandler();
|
||||
defaultDispatcherErrorHandler.setDevMode("false");
|
||||
defaultDispatcherErrorHandler.setFreemarkerManager(dispatcher.getContainer().getInstance(FreemarkerManager.class));
|
||||
defaultDispatcherErrorHandler.init(dispatcher.servletContext);
|
||||
Exception fakeException = new Exception("Fake Exception, devMode false");
|
||||
try {
|
||||
requestMock.setAttribute("javax.servlet.error.exception", fakeException);
|
||||
expectLastCall();
|
||||
requestMock.setAttribute("javax.servlet.jsp.jspException", fakeException);
|
||||
expectLastCall();
|
||||
expect(responseMock.isCommitted()).andStubReturn(Boolean.TRUE);
|
||||
responseMock.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fakeException.getMessage());
|
||||
expectLastCall().andStubThrow(new IllegalStateException("Fake IllegalState Exception (SC_INTERNAL_SERVER_ERROR, devMode false)"));
|
||||
replay(responseMock);
|
||||
} catch (IOException ioe) {
|
||||
fail("Mock sendError call setup failed. Ex: " + ioe);
|
||||
}
|
||||
defaultDispatcherErrorHandler.handleError(requestMock, responseMock, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fakeException);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test to exercise the code path and prove handleError() will output
|
||||
* the desired log warning when an IllegalStateException is thrown with devMode true.
|
||||
*/
|
||||
public void testHandleErrorIllegalStateExceptionDevMode() {
|
||||
DefaultDispatcherErrorHandler defaultDispatcherErrorHandler = new DefaultDispatcherErrorHandler();
|
||||
defaultDispatcherErrorHandler.setDevMode("true");
|
||||
defaultDispatcherErrorHandler.setFreemarkerManager(dispatcher.getContainer().getInstance(FreemarkerManager.class));
|
||||
defaultDispatcherErrorHandler.init(dispatcher.servletContext);
|
||||
Exception fakeException = new Exception("Fake Exception, devMode true");
|
||||
try {
|
||||
expect(responseMock.isCommitted()).andStubReturn(Boolean.TRUE);
|
||||
responseMock.setContentType("text/html");
|
||||
expectLastCall().andStubThrow(new IllegalStateException("Fake IllegalState Exception (report write)")); // Fake error during report write
|
||||
responseMock.sendError(anyInt(), anyString());
|
||||
expectLastCall().andStubThrow(new IllegalStateException("Fake IllegalState Exception (SC_INTERNAL_SERVER_ERROR, devMode true)"));
|
||||
replay(responseMock);
|
||||
} catch (IOException ioe) {
|
||||
fail("Mock sendError call setup failed. Ex: " + ioe);
|
||||
}
|
||||
defaultDispatcherErrorHandler.handleError(requestMock, responseMock, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fakeException);
|
||||
}
|
||||
|
||||
protected void setUp() {
|
||||
requestMock = (HttpServletRequest) createMock(HttpServletRequest.class);
|
||||
responseMock = (HttpServletResponse) createMock(HttpServletResponse.class);
|
||||
dispatcher = initDispatcher(Collections.<String, String>emptyMap());
|
||||
}
|
||||
}
|
||||
@@ -18,11 +18,22 @@
|
||||
*/
|
||||
package org.apache.struts2.dispatcher;
|
||||
|
||||
import java.io.IOException;
|
||||
import org.apache.struts2.StrutsInternalTestCase;
|
||||
|
||||
import java.util.List;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import static org.easymock.EasyMock.createMock;
|
||||
import static org.easymock.EasyMock.expect;
|
||||
import static org.easymock.EasyMock.expectLastCall;
|
||||
import static org.easymock.EasyMock.replay;
|
||||
|
||||
public class DefaultStaticContentLoaderTest extends StrutsInternalTestCase {
|
||||
private HttpServletRequest requestMock;
|
||||
private HttpServletResponse responseMock;
|
||||
private HostConfig hostConfigMock;
|
||||
private DefaultStaticContentLoader defaultStaticContentLoader;
|
||||
|
||||
public void testParsePackages() throws Exception {
|
||||
|
||||
@@ -50,4 +61,55 @@ public class DefaultStaticContentLoaderTest extends StrutsInternalTestCase {
|
||||
assertEquals(result4.get(3), "foo/bar/package4/");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test to exercise the code path and prove findStaticResource() will output
|
||||
* the desired log warning when an IOException is thrown.
|
||||
*/
|
||||
public void testFindStaticResourceIOException() {
|
||||
expect(requestMock.getDateHeader("If-Modified-Since")).andStubReturn(0L);
|
||||
try {
|
||||
responseMock.sendError(HttpServletResponse.SC_NOT_FOUND);
|
||||
expectLastCall().andStubThrow(new IOException("Fake IO Exception (SC_NOT_FOUND)"));
|
||||
replay(responseMock);
|
||||
} catch (IOException ioe) {
|
||||
fail("Mock sendError call setup failed. Ex: " + ioe);
|
||||
}
|
||||
try {
|
||||
defaultStaticContentLoader.findStaticResource("/static/fake.html", requestMock, responseMock);
|
||||
} catch (IOException ioe) {
|
||||
fail("DefaultStaticContentLoader.findStaticResource() call failed. Ex: " + ioe);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test to exercise the code path and prove findStaticResource() will output
|
||||
* the desired log warning when an IllegalStateException is thrown.
|
||||
*/
|
||||
public void testFindStaticResourceIllegalStateException() {
|
||||
expect(requestMock.getDateHeader("If-Modified-Since")).andStubReturn(0L);
|
||||
try {
|
||||
expect(responseMock.isCommitted()).andStubReturn(Boolean.TRUE);
|
||||
responseMock.sendError(HttpServletResponse.SC_NOT_FOUND);
|
||||
expectLastCall().andStubThrow(new IllegalStateException("Fake IllegalState Exception (SC_NOT_FOUND)"));
|
||||
replay(responseMock);
|
||||
} catch (IOException ioe) {
|
||||
fail("Mock sendError call setup failed. Ex: " + ioe);
|
||||
}
|
||||
try {
|
||||
defaultStaticContentLoader.findStaticResource("/static/fake.html", requestMock, responseMock);
|
||||
} catch (IOException ioe) {
|
||||
fail("DefaultStaticContentLoader.findStaticResource() call failed. Ex: " + ioe);
|
||||
}
|
||||
}
|
||||
|
||||
protected void setUp() {
|
||||
requestMock = (HttpServletRequest) createMock(HttpServletRequest.class);
|
||||
responseMock = (HttpServletResponse) createMock(HttpServletResponse.class);
|
||||
hostConfigMock = (HostConfig) createMock(HostConfig.class);
|
||||
expect(hostConfigMock.getInitParameter("packages")).andStubReturn(null);
|
||||
expect(hostConfigMock.getInitParameter("loggerFactory")).andStubReturn(null);
|
||||
defaultStaticContentLoader = new DefaultStaticContentLoader();
|
||||
defaultStaticContentLoader.setHostConfig(hostConfigMock);
|
||||
defaultStaticContentLoader.setEncoding("UTF-8");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -319,6 +319,59 @@ public class DispatcherTest extends StrutsInternalTestCase {
|
||||
|
||||
req.setContentType("multipart/form-data; boundary=---------------------------207103069210263;charset=UTF-16LE");
|
||||
assertTrue(du.isMultipartRequest(req));
|
||||
|
||||
req.setContentType("multipart/form-data;boundary=---------------------------207103069210263;charset=UTF-16LE");
|
||||
assertTrue(du.isMultipartRequest(req));
|
||||
|
||||
req.setContentType("multipart/form-data;boundary=---------------------------207103069210263; charset=UTF-16LE");
|
||||
assertTrue(du.isMultipartRequest(req));
|
||||
|
||||
req.setContentType("multipart/form-data;boundary=---------------------------207103069210263 ;charset=UTF-16LE");
|
||||
assertTrue(du.isMultipartRequest(req));
|
||||
|
||||
req.setContentType("multipart/form-data;boundary=---------------------------207103069210263 ; charset=UTF-16LE");
|
||||
assertTrue(du.isMultipartRequest(req));
|
||||
|
||||
req.setContentType("multipart/form-data ;boundary=---------------------------207103069210263;charset=UTF-16LE");
|
||||
assertTrue(du.isMultipartRequest(req));
|
||||
|
||||
req.setContentType("multipart/form-data ; boundary=---------------------------207103069210263;charset=UTF-16LE");
|
||||
assertTrue(du.isMultipartRequest(req));
|
||||
|
||||
req.setContentType("Multipart/Form-Data ; boundary=---------------------------207103069210263;charset=UTF-16LE");
|
||||
assertTrue(du.isMultipartRequest(req));
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify proper default (true) handleExceptionState for Dispatcher and that
|
||||
* it properly reflects a manually configured change to false.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public void testHandleException() throws Exception {
|
||||
Dispatcher du = initDispatcher(new HashMap<String, String>());
|
||||
assertTrue("Default Dispatcher handleException state not true ?", du.isHandleException());
|
||||
|
||||
Dispatcher du2 = initDispatcher(new HashMap<String, String>() {{
|
||||
put(StrutsConstants.STRUTS_HANDLE_EXCEPTION, "false");
|
||||
}});
|
||||
assertFalse("Modified Dispatcher handleException state not false ?", du2.isHandleException());
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify proper default (false) devMode for Dispatcher and that
|
||||
* it properly reflects a manually configured change to true.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public void testDevMode() throws Exception {
|
||||
Dispatcher du = initDispatcher(new HashMap<String, String>());
|
||||
assertFalse("Default Dispatcher devMode state not false ?", du.isDevMode());
|
||||
|
||||
Dispatcher du2 = initDispatcher(new HashMap<String, String>() {{
|
||||
put(StrutsConstants.STRUTS_DEVMODE, "true");
|
||||
}});
|
||||
assertTrue("Modified Dispatcher devMode state not true ?", du2.isDevMode());
|
||||
}
|
||||
|
||||
class InternalConfigurationManager extends ConfigurationManager {
|
||||
|
||||
+111
-86
@@ -27,12 +27,12 @@ import com.opensymphony.xwork2.config.entities.PackageConfig;
|
||||
import com.opensymphony.xwork2.config.impl.DefaultConfiguration;
|
||||
import com.opensymphony.xwork2.inject.Container;
|
||||
import org.apache.struts2.ServletActionContext;
|
||||
import org.apache.struts2.StrutsException;
|
||||
import org.apache.struts2.StrutsInternalTestCase;
|
||||
import org.apache.struts2.result.StrutsResultSupport;
|
||||
import org.apache.struts2.views.jsp.StrutsMockHttpServletRequest;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -65,7 +65,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
};
|
||||
}
|
||||
|
||||
public void testGetMapping() throws Exception {
|
||||
public void testGetMapping() {
|
||||
req.setupGetRequestURI("/my/namespace/actionName.action");
|
||||
req.setupGetServletPath("/my/namespace/actionName.action");
|
||||
req.setupGetAttribute(null);
|
||||
@@ -79,7 +79,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertNull(mapping.getMethod());
|
||||
}
|
||||
|
||||
public void testGetMappingWithMethod() throws Exception {
|
||||
public void testGetMappingWithMethod() {
|
||||
req.setupGetParameterMap(new HashMap());
|
||||
req.setupGetRequestURI("/my/namespace/actionName!add.action");
|
||||
req.setupGetServletPath("/my/namespace/actionName!add.action");
|
||||
@@ -95,7 +95,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("add", mapping.getMethod());
|
||||
}
|
||||
|
||||
public void testGetMappingWithSlashedName() throws Exception {
|
||||
public void testGetMappingWithSlashedName() {
|
||||
|
||||
req.setupGetRequestURI("/my/foo/actionName.action");
|
||||
req.setupGetServletPath("/my/foo/actionName.action");
|
||||
@@ -111,7 +111,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertNull(mapping.getMethod());
|
||||
}
|
||||
|
||||
public void testGetMappingWithSlashedNameAtRootButNoSlashPackage() throws Exception {
|
||||
public void testGetMappingWithSlashedNameAtRootButNoSlashPackage() {
|
||||
|
||||
req.setupGetRequestURI("/foo/actionName.action");
|
||||
req.setupGetServletPath("/foo/actionName.action");
|
||||
@@ -127,7 +127,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertNull(mapping.getMethod());
|
||||
}
|
||||
|
||||
public void testGetMappingWithSlashedNameAtRoot() throws Exception {
|
||||
public void testGetMappingWithSlashedNameAtRoot() {
|
||||
config = new DefaultConfiguration();
|
||||
PackageConfig pkg = new PackageConfig.Builder("myns")
|
||||
.namespace("/my/namespace").build();
|
||||
@@ -158,7 +158,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
|
||||
|
||||
|
||||
public void testGetMappingWithNamespaceSlash() throws Exception {
|
||||
public void testGetMappingWithNamespaceSlash() {
|
||||
|
||||
req.setupGetRequestURI("/my-hh/abc.action");
|
||||
req.setupGetServletPath("/my-hh/abc.action");
|
||||
@@ -181,7 +181,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("my-hh/abc", mapping.getName());
|
||||
}
|
||||
|
||||
public void testGetMappingWithUnknownNamespace() throws Exception {
|
||||
public void testGetMappingWithUnknownNamespace() {
|
||||
req.setupGetRequestURI("/bo/foo/actionName.action");
|
||||
req.setupGetServletPath("/bo/foo/actionName.action");
|
||||
req.setupGetAttribute(null);
|
||||
@@ -195,7 +195,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertNull(mapping.getMethod());
|
||||
}
|
||||
|
||||
public void testGetMappingWithUnknownNamespaceButFullNamespaceSelect() throws Exception {
|
||||
public void testGetMappingWithUnknownNamespaceButFullNamespaceSelect() {
|
||||
req.setupGetRequestURI("/bo/foo/actionName.action");
|
||||
req.setupGetServletPath("/bo/foo/actionName.action");
|
||||
req.setupGetAttribute(null);
|
||||
@@ -210,7 +210,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertNull(mapping.getMethod());
|
||||
}
|
||||
|
||||
public void testGetMappingWithActionName_methodAndName() throws Exception {
|
||||
public void testGetMappingWithActionName_methodAndName() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
mapper.setAllowDynamicMethodCalls("true");
|
||||
ActionMapping mapping = mapper.getMappingFromActionName("actionName!add");
|
||||
@@ -218,24 +218,24 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("add", mapping.getMethod());
|
||||
}
|
||||
|
||||
public void testGetMappingWithActionName_name() throws Exception {
|
||||
public void testGetMappingWithActionName_name() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
ActionMapping mapping = mapper.getMappingFromActionName("actionName");
|
||||
assertEquals("actionName", mapping.getName());
|
||||
assertEquals(null, mapping.getMethod());
|
||||
assertNull(mapping.getMethod());
|
||||
}
|
||||
|
||||
public void testGetMappingWithActionName_noDynamicMethod() throws Exception {
|
||||
public void testGetMappingWithActionName_noDynamicMethod() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
mapper.setAllowDynamicMethodCalls("false");
|
||||
ActionMapping mapping = mapper.getMappingFromActionName("actionName!add");
|
||||
assertEquals("actionName!add", mapping.getName());
|
||||
assertEquals(null, mapping.getMethod());
|
||||
assertNull(mapping.getMethod());
|
||||
}
|
||||
|
||||
public void testGetMappingWithActionName_noDynamicMethodColonPrefix() throws Exception {
|
||||
public void testGetMappingWithActionName_noDynamicMethodColonPrefix() {
|
||||
|
||||
Map parameterMap = new HashMap();
|
||||
Map<String, Object> parameterMap = new HashMap<>();
|
||||
parameterMap.put(DefaultActionMapper.METHOD_PREFIX + "someMethod", "");
|
||||
|
||||
StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest();
|
||||
@@ -247,16 +247,16 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager);
|
||||
|
||||
assertEquals("someServletPath", actionMapping.getName());
|
||||
assertEquals(null, actionMapping.getMethod());
|
||||
assertNull(actionMapping.getMethod());
|
||||
}
|
||||
|
||||
public void testGetMappingWithActionName_null() throws Exception {
|
||||
public void testGetMappingWithActionName_null() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
ActionMapping mapping = mapper.getMappingFromActionName(null);
|
||||
assertNull(mapping);
|
||||
}
|
||||
|
||||
public void testGetUri() throws Exception {
|
||||
public void testGetUri() {
|
||||
req.setupGetParameterMap(new HashMap());
|
||||
req.setupGetRequestURI("/my/namespace/actionName.action");
|
||||
req.setupGetServletPath("/my/namespace/actionName.action");
|
||||
@@ -268,7 +268,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("/my/namespace/actionName.action", mapper.getUriFromActionMapping(mapping));
|
||||
}
|
||||
|
||||
public void testGetUriWithSemicolonPresent() throws Exception {
|
||||
public void testGetUriWithSemicolonPresent() {
|
||||
req.setupGetParameterMap(new HashMap());
|
||||
req.setupGetRequestURI("/my/namespace/actionName.action;abc=123rty56");
|
||||
req.setupGetServletPath("/my/namespace/actionName.action;abc=123rty56");
|
||||
@@ -280,7 +280,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("/my/namespace/actionName.action", mapper.getUriFromActionMapping(mapping));
|
||||
}
|
||||
|
||||
public void testGetUriWithMethod() throws Exception {
|
||||
public void testGetUriWithMethod() {
|
||||
req.setupGetParameterMap(new HashMap());
|
||||
req.setupGetRequestURI("/my/namespace/actionName!add.action");
|
||||
req.setupGetServletPath("/my/namespace/actionName!add.action");
|
||||
@@ -293,8 +293,8 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("/my/namespace/actionName!add.action", mapper.getUriFromActionMapping(mapping));
|
||||
}
|
||||
|
||||
public void testGetUriWithOriginalExtension() throws Exception {
|
||||
ActionMapping mapping = new ActionMapping("actionName", "/ns", null, new HashMap());
|
||||
public void testGetUriWithOriginalExtension() {
|
||||
ActionMapping mapping = new ActionMapping("actionName", "/ns", null, new HashMap<String, Object>());
|
||||
|
||||
ActionMapping orig = new ActionMapping();
|
||||
orig.setExtension("foo");
|
||||
@@ -304,7 +304,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("/ns/actionName.foo", mapper.getUriFromActionMapping(mapping));
|
||||
}
|
||||
|
||||
public void testGetMappingWithNoExtension() throws Exception {
|
||||
public void testGetMappingWithNoExtension() {
|
||||
req.setupGetParameterMap(new HashMap());
|
||||
req.setupGetRequestURI("/my/namespace/actionName");
|
||||
req.setupGetServletPath("/my/namespace/actionName");
|
||||
@@ -320,7 +320,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertNull(mapping.getMethod());
|
||||
}
|
||||
|
||||
public void testGetMappingWithNoExtensionButUriHasExtension() throws Exception {
|
||||
public void testGetMappingWithNoExtensionButUriHasExtension() {
|
||||
req.setupGetParameterMap(new HashMap());
|
||||
req.setupGetRequestURI("/my/namespace/actionName.html");
|
||||
req.setupGetServletPath("/my/namespace/actionName.html");
|
||||
@@ -340,7 +340,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
// === test name & namespace ===
|
||||
// =============================
|
||||
|
||||
public void testParseNameAndNamespace1() throws Exception {
|
||||
public void testParseNameAndNamespace1() {
|
||||
ActionMapping actionMapping = new ActionMapping();
|
||||
|
||||
DefaultActionMapper defaultActionMapper = new DefaultActionMapper();
|
||||
@@ -350,7 +350,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals(actionMapping.getNamespace(), "");
|
||||
}
|
||||
|
||||
public void testParseNameAndNamespace2() throws Exception {
|
||||
public void testParseNameAndNamespace2() {
|
||||
ActionMapping actionMapping = new ActionMapping();
|
||||
|
||||
DefaultActionMapper defaultActionMapper = new DefaultActionMapper();
|
||||
@@ -360,7 +360,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals(actionMapping.getNamespace(), "/");
|
||||
}
|
||||
|
||||
public void testParseNameAndNamespace3() throws Exception {
|
||||
public void testParseNameAndNamespace3() {
|
||||
ActionMapping actionMapping = new ActionMapping();
|
||||
|
||||
DefaultActionMapper defaultActionMapper = new DefaultActionMapper();
|
||||
@@ -370,7 +370,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals(actionMapping.getNamespace(), "/my");
|
||||
}
|
||||
|
||||
public void testParseNameAndNamespace_NoSlashes() throws Exception {
|
||||
public void testParseNameAndNamespace_NoSlashes() {
|
||||
ActionMapping actionMapping = new ActionMapping();
|
||||
|
||||
DefaultActionMapper defaultActionMapper = new DefaultActionMapper();
|
||||
@@ -381,7 +381,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals(actionMapping.getNamespace(), "");
|
||||
}
|
||||
|
||||
public void testParseNameAndNamespace_AllowSlashes() throws Exception {
|
||||
public void testParseNameAndNamespace_AllowSlashes() {
|
||||
ActionMapping actionMapping = new ActionMapping();
|
||||
|
||||
DefaultActionMapper defaultActionMapper = new DefaultActionMapper();
|
||||
@@ -397,8 +397,8 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
// === test special prefix ===
|
||||
// ===========================
|
||||
|
||||
public void testActionPrefixWhenDisabled() throws Exception {
|
||||
Map parameterMap = new HashMap();
|
||||
public void testActionPrefixWhenDisabled() {
|
||||
Map<String, Object> parameterMap = new HashMap<>();
|
||||
parameterMap.put(DefaultActionMapper.ACTION_PREFIX + "myAction", "");
|
||||
|
||||
StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest();
|
||||
@@ -411,8 +411,8 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("someServletPath", actionMapping.getName());
|
||||
}
|
||||
|
||||
public void testActionPrefixWhenEnabled() throws Exception {
|
||||
Map parameterMap = new HashMap();
|
||||
public void testActionPrefixWhenEnabled() {
|
||||
Map<String, Object> parameterMap = new HashMap<>();
|
||||
parameterMap.put(DefaultActionMapper.ACTION_PREFIX + "myAction", "");
|
||||
|
||||
StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest();
|
||||
@@ -426,8 +426,8 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("myAction", actionMapping.getName());
|
||||
}
|
||||
|
||||
public void testActionPrefixWhenSlashesAndCrossNamespaceDisabled() throws Exception {
|
||||
Map parameterMap = new HashMap();
|
||||
public void testActionPrefixWhenSlashesAndCrossNamespaceDisabled() {
|
||||
Map<String, Object> parameterMap = new HashMap<>();
|
||||
parameterMap.put(DefaultActionMapper.ACTION_PREFIX + "my/Action", "");
|
||||
|
||||
StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest();
|
||||
@@ -442,8 +442,8 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("my/Action", actionMapping.getName());
|
||||
}
|
||||
|
||||
public void testActionPrefixWhenSlashesButSlashesDisabledAndCrossNamespaceDisabled() throws Exception {
|
||||
Map parameterMap = new HashMap();
|
||||
public void testActionPrefixWhenSlashesButSlashesDisabledAndCrossNamespaceDisabled() {
|
||||
Map<String, Object> parameterMap = new HashMap<>();
|
||||
parameterMap.put(DefaultActionMapper.ACTION_PREFIX + "my/Action", "");
|
||||
|
||||
StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest();
|
||||
@@ -458,8 +458,8 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("Action", actionMapping.getName());
|
||||
}
|
||||
|
||||
public void testActionPrefixWhenSlashesButSlashesDisabledAndCrossNamespace() throws Exception {
|
||||
Map parameterMap = new HashMap();
|
||||
public void testActionPrefixWhenSlashesButSlashesDisabledAndCrossNamespace() {
|
||||
Map<String, Object> parameterMap = new HashMap<>();
|
||||
parameterMap.put(DefaultActionMapper.ACTION_PREFIX + "my/Action", "");
|
||||
|
||||
StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest();
|
||||
@@ -475,8 +475,8 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("my/Action", actionMapping.getName());
|
||||
}
|
||||
|
||||
public void testActionPrefixWhenCrossNamespace() throws Exception {
|
||||
Map parameterMap = new HashMap();
|
||||
public void testActionPrefixWhenCrossNamespace() {
|
||||
Map<String, Object> parameterMap = new HashMap<>();
|
||||
parameterMap.put(DefaultActionMapper.ACTION_PREFIX + "/my/Action", "");
|
||||
|
||||
StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest();
|
||||
@@ -491,8 +491,8 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("/my/Action", actionMapping.getName());
|
||||
}
|
||||
|
||||
public void testActionPrefix_fromImageButton() throws Exception {
|
||||
Map parameterMap = new HashMap();
|
||||
public void testActionPrefix_fromImageButton() {
|
||||
Map<String, Object> parameterMap = new HashMap<>();
|
||||
parameterMap.put(DefaultActionMapper.ACTION_PREFIX + "myAction", "");
|
||||
parameterMap.put(DefaultActionMapper.ACTION_PREFIX + "myAction.x", "");
|
||||
parameterMap.put(DefaultActionMapper.ACTION_PREFIX + "myAction.y", "");
|
||||
@@ -508,8 +508,8 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("myAction", actionMapping.getName());
|
||||
}
|
||||
|
||||
public void testActionPrefix_fromIEImageButton() throws Exception {
|
||||
Map parameterMap = new HashMap();
|
||||
public void testActionPrefix_fromIEImageButton() {
|
||||
Map<String, Object> parameterMap = new HashMap<>();
|
||||
parameterMap.put(DefaultActionMapper.ACTION_PREFIX + "myAction.x", "");
|
||||
parameterMap.put(DefaultActionMapper.ACTION_PREFIX + "myAction.y", "");
|
||||
|
||||
@@ -524,8 +524,8 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("myAction", actionMapping.getName());
|
||||
}
|
||||
|
||||
public void testRedirectPrefix() throws Exception {
|
||||
Map parameterMap = new HashMap();
|
||||
public void testRedirectPrefix() {
|
||||
Map<String, Object> parameterMap = new HashMap<>();
|
||||
parameterMap.put("redirect:" + "http://www.google.com", "");
|
||||
|
||||
StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest();
|
||||
@@ -540,8 +540,8 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertNull(result);
|
||||
}
|
||||
|
||||
public void testUnsafeRedirectPrefix() throws Exception {
|
||||
Map parameterMap = new HashMap();
|
||||
public void testUnsafeRedirectPrefix() {
|
||||
Map<String, Object> parameterMap = new HashMap<>();
|
||||
parameterMap.put("redirect:" + "http://%{3*4}", "");
|
||||
|
||||
StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest();
|
||||
@@ -556,8 +556,8 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertNull(result);
|
||||
}
|
||||
|
||||
public void testRedirectActionPrefix() throws Exception {
|
||||
Map parameterMap = new HashMap();
|
||||
public void testRedirectActionPrefix() {
|
||||
Map<String, Object> parameterMap = new HashMap<>();
|
||||
parameterMap.put("redirectAction:" + "myAction", "");
|
||||
|
||||
StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest();
|
||||
@@ -573,8 +573,8 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertNull(result);
|
||||
}
|
||||
|
||||
public void testUnsafeRedirectActionPrefix() throws Exception {
|
||||
Map parameterMap = new HashMap();
|
||||
public void testUnsafeRedirectActionPrefix() {
|
||||
Map<String, Object> parameterMap = new HashMap<>();
|
||||
parameterMap.put("redirectAction:" + "%{3*4}", "");
|
||||
|
||||
StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest();
|
||||
@@ -590,8 +590,8 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertNull(result);
|
||||
}
|
||||
|
||||
public void testRedirectActionPrefixWithEmptyExtension() throws Exception {
|
||||
Map parameterMap = new HashMap();
|
||||
public void testRedirectActionPrefixWithEmptyExtension() {
|
||||
Map<String, Object> parameterMap = new HashMap<>();
|
||||
parameterMap.put("redirectAction:" + "myAction", "");
|
||||
|
||||
StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest();
|
||||
@@ -608,8 +608,8 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertNull(result);
|
||||
}
|
||||
|
||||
public void testCustomActionPrefix() throws Exception {
|
||||
Map parameterMap = new HashMap();
|
||||
public void testCustomActionPrefix() {
|
||||
Map<String, Object> parameterMap = new HashMap<>();
|
||||
parameterMap.put("foo:myAction", "");
|
||||
|
||||
final StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest();
|
||||
@@ -627,39 +627,39 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals(actionMapping.getName(), "myAction");
|
||||
}
|
||||
|
||||
public void testDropExtension() throws Exception {
|
||||
public void testDropExtension() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
String name = mapper.dropExtension("foo.action", new ActionMapping());
|
||||
assertTrue("Name not right: "+name, "foo".equals(name));
|
||||
assertEquals("Name not right: " + name, "foo", name);
|
||||
|
||||
name = mapper.dropExtension("foo.action.action", new ActionMapping());
|
||||
assertTrue("Name not right: "+name, "foo.action".equals(name));
|
||||
assertEquals("Name not right: " + name, "foo.action", name);
|
||||
|
||||
}
|
||||
|
||||
public void testDropExtensionWhenBlank() throws Exception {
|
||||
public void testDropExtensionWhenBlank() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
mapper.setExtensions("action,,");
|
||||
String name = mapper.dropExtension("foo.action", new ActionMapping());
|
||||
assertTrue("Name not right: "+name, "foo".equals(name));
|
||||
assertEquals("Name not right: " + name, "foo", name);
|
||||
name = mapper.dropExtension("foo", new ActionMapping());
|
||||
assertTrue("Name not right: "+name, "foo".equals(name));
|
||||
assertEquals("Name not right: " + name, "foo", name);
|
||||
assertNull(mapper.dropExtension("foo.bar", new ActionMapping()));
|
||||
assertNull(mapper.dropExtension("foo.", new ActionMapping()));
|
||||
}
|
||||
|
||||
public void testDropExtensionEmbeddedDot() throws Exception {
|
||||
public void testDropExtensionEmbeddedDot() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
mapper.setExtensions("action,,");
|
||||
|
||||
String name = mapper.dropExtension("/foo/bar-1.0/baz.action", new ActionMapping());
|
||||
assertTrue("Name not right: "+name, "/foo/bar-1.0/baz".equals(name));
|
||||
assertEquals("Name not right: " + name, "/foo/bar-1.0/baz", name);
|
||||
|
||||
name = mapper.dropExtension("/foo/bar-1.0/baz", new ActionMapping());
|
||||
assertTrue("Name not right: "+name, "/foo/bar-1.0/baz".equals(name));
|
||||
assertEquals("Name not right: " + name, "/foo/bar-1.0/baz", name);
|
||||
}
|
||||
|
||||
public void testGetUriFromActionMapper1() throws Exception {
|
||||
public void testGetUriFromActionMapper1() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
ActionMapping actionMapping = new ActionMapping();
|
||||
actionMapping.setMethod("myMethod");
|
||||
@@ -670,7 +670,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("/myNamespace/myActionName!myMethod.action", uri);
|
||||
}
|
||||
|
||||
public void testGetUriFromActionMapper2() throws Exception {
|
||||
public void testGetUriFromActionMapper2() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
ActionMapping actionMapping = new ActionMapping();
|
||||
actionMapping.setMethod("myMethod");
|
||||
@@ -681,7 +681,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("/myActionName!myMethod.action", uri);
|
||||
}
|
||||
|
||||
public void testGetUriFromActionMapper3() throws Exception {
|
||||
public void testGetUriFromActionMapper3() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
ActionMapping actionMapping = new ActionMapping();
|
||||
actionMapping.setMethod("myMethod");
|
||||
@@ -693,7 +693,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
}
|
||||
|
||||
|
||||
public void testGetUriFromActionMapper4() throws Exception {
|
||||
public void testGetUriFromActionMapper4() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
ActionMapping actionMapping = new ActionMapping();
|
||||
actionMapping.setName("myActionName");
|
||||
@@ -703,7 +703,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("/myActionName.action", uri);
|
||||
}
|
||||
|
||||
public void testGetUriFromActionMapper5() throws Exception {
|
||||
public void testGetUriFromActionMapper5() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
ActionMapping actionMapping = new ActionMapping();
|
||||
actionMapping.setName("myActionName");
|
||||
@@ -714,7 +714,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
}
|
||||
|
||||
//
|
||||
public void testGetUriFromActionMapper6() throws Exception {
|
||||
public void testGetUriFromActionMapper6() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
ActionMapping actionMapping = new ActionMapping();
|
||||
actionMapping.setMethod("myMethod");
|
||||
@@ -725,7 +725,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("/myNamespace/myActionName!myMethod.action?test=bla", uri);
|
||||
}
|
||||
|
||||
public void testGetUriFromActionMapper7() throws Exception {
|
||||
public void testGetUriFromActionMapper7() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
ActionMapping actionMapping = new ActionMapping();
|
||||
actionMapping.setMethod("myMethod");
|
||||
@@ -736,7 +736,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("/myActionName!myMethod.action?test=bla", uri);
|
||||
}
|
||||
|
||||
public void testGetUriFromActionMapper8() throws Exception {
|
||||
public void testGetUriFromActionMapper8() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
ActionMapping actionMapping = new ActionMapping();
|
||||
actionMapping.setMethod("myMethod");
|
||||
@@ -748,7 +748,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
}
|
||||
|
||||
|
||||
public void testGetUriFromActionMapper9() throws Exception {
|
||||
public void testGetUriFromActionMapper9() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
ActionMapping actionMapping = new ActionMapping();
|
||||
actionMapping.setName("myActionName?test=bla");
|
||||
@@ -758,7 +758,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("/myActionName.action?test=bla", uri);
|
||||
}
|
||||
|
||||
public void testGetUriFromActionMapper10() throws Exception {
|
||||
public void testGetUriFromActionMapper10() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
ActionMapping actionMapping = new ActionMapping();
|
||||
actionMapping.setName("myActionName?test=bla");
|
||||
@@ -768,7 +768,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("/myActionName.action?test=bla", uri);
|
||||
}
|
||||
|
||||
public void testGetUriFromActionMapper11() throws Exception {
|
||||
public void testGetUriFromActionMapper11() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
ActionMapping actionMapping = new ActionMapping();
|
||||
actionMapping.setName("myActionName.action");
|
||||
@@ -778,7 +778,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("/myActionName.action", uri);
|
||||
}
|
||||
|
||||
public void testGetUriFromActionMapper12() throws Exception {
|
||||
public void testGetUriFromActionMapper12() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
ActionMapping actionMapping = new ActionMapping();
|
||||
actionMapping.setName("myActionName.action");
|
||||
@@ -788,7 +788,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("/myActionName.action", uri);
|
||||
}
|
||||
|
||||
public void testGetUriFromActionMapper_justActionAndMethod() throws Exception {
|
||||
public void testGetUriFromActionMapper_justActionAndMethod() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
ActionMapping actionMapping = new ActionMapping();
|
||||
actionMapping.setMethod("myMethod");
|
||||
@@ -799,7 +799,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("myActionName!myMethod", uri);
|
||||
}
|
||||
|
||||
public void testGetUriFromActionMapperWhenBlankExtension() throws Exception {
|
||||
public void testGetUriFromActionMapperWhenBlankExtension() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
mapper.setExtensions(",,");
|
||||
ActionMapping actionMapping = new ActionMapping();
|
||||
@@ -811,7 +811,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("/myNamespace/myActionName!myMethod", uri);
|
||||
}
|
||||
|
||||
public void testSetExtension() throws Exception {
|
||||
public void testSetExtension() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
mapper.setExtensions("");
|
||||
assertNull(mapper.extensions);
|
||||
@@ -828,15 +828,40 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals(Arrays.asList("html", "", "xml"), mapper.extensions);
|
||||
|
||||
mapper.setExtensions("xml");
|
||||
assertEquals(Arrays.asList("xml"), mapper.extensions);
|
||||
assertEquals(Collections.singletonList("xml"), mapper.extensions);
|
||||
|
||||
mapper.setExtensions(",");
|
||||
assertEquals(Arrays.asList(""), mapper.extensions);
|
||||
assertEquals(Collections.singletonList(""), mapper.extensions);
|
||||
|
||||
|
||||
}
|
||||
|
||||
public void testAllowedActionNames() throws Exception {
|
||||
public void testAllowedNamespaceNames() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
|
||||
String namespace = "/";
|
||||
assertEquals(namespace, mapper.cleanupNamespaceName(namespace));
|
||||
|
||||
namespace = "${namespace}";
|
||||
assertEquals(mapper.defaultNamespaceName, mapper.cleanupNamespaceName(namespace));
|
||||
|
||||
namespace = "${${%{namespace}}}";
|
||||
assertEquals(mapper.defaultNamespaceName, mapper.cleanupNamespaceName(namespace));
|
||||
|
||||
namespace = "${#foo='namespace',#foo}";
|
||||
assertEquals(mapper.defaultNamespaceName, mapper.cleanupNamespaceName(namespace));
|
||||
|
||||
namespace = "/test-namespace/namespace/";
|
||||
assertEquals("/test-namespace/namespace/", mapper.cleanupNamespaceName(namespace));
|
||||
|
||||
namespace = "/test_namespace/namespace-test/";
|
||||
assertEquals("/test_namespace/namespace-test/", mapper.cleanupNamespaceName(namespace));
|
||||
|
||||
namespace = "/test_namespace/namespace.test/";
|
||||
assertEquals("/test_namespace/namespace.test/", mapper.cleanupActionName(namespace));
|
||||
}
|
||||
|
||||
public void testAllowedActionNames() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
|
||||
String actionName = "action";
|
||||
@@ -861,7 +886,7 @@ public class DefaultActionMapperTest extends StrutsInternalTestCase {
|
||||
assertEquals("test!bar.action", mapper.cleanupActionName(actionName));
|
||||
}
|
||||
|
||||
public void testAllowedMethodNames() throws Exception {
|
||||
public void testAllowedMethodNames() {
|
||||
DefaultActionMapper mapper = new DefaultActionMapper();
|
||||
|
||||
assertEquals("", mapper.cleanupMethodName(""));
|
||||
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.apache.struts2.interceptor;
|
||||
|
||||
import com.opensymphony.xwork2.ActionContext;
|
||||
import com.opensymphony.xwork2.XWorkTestCase;
|
||||
|
||||
import org.apache.struts2.dispatcher.HttpParameters;
|
||||
import org.apache.struts2.ServletActionContext;
|
||||
import org.apache.struts2.dispatcher.Parameter;
|
||||
import org.apache.struts2.dispatcher.mapper.ActionMapping;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
/**
|
||||
* Unit test for {@link ActionMappingParametersInterceptor}.
|
||||
*
|
||||
* Adapted from ParametersInterceptor (@author Jason Carreira)
|
||||
*/
|
||||
public class ActionMappingParametersInterceptorTest extends XWorkTestCase {
|
||||
|
||||
/**
|
||||
* Confirm that ActionMappingParametersInterceptor processing methods avoid
|
||||
* nested wrapping of parameters.
|
||||
*/
|
||||
public void testParametersNoNestedWrapping() {
|
||||
final ActionMappingParametersInterceptor ampi = createActionMappingParametersInterceptor();
|
||||
final ActionContext ac = ActionContext.getContext();
|
||||
final Map<String, Object> parameters = new HashMap<String, Object>() {
|
||||
{
|
||||
put("fooKey", "fooValue");
|
||||
put("barKey", "barValue");
|
||||
}
|
||||
};
|
||||
final Map<String, Object> moreParameters = new HashMap<String, Object>() {
|
||||
{
|
||||
put("fooKey2", "fooValue2");
|
||||
put("barKey2", "barValue3");
|
||||
}
|
||||
};
|
||||
final Map<String, Object> evenMoreParameters = new HashMap<String, Object>() {
|
||||
{
|
||||
put("fooKey3", "fooValue3");
|
||||
put("barKey3", "barValue3");
|
||||
}
|
||||
};
|
||||
// Set up the initial ActionMapping with parameters in the context
|
||||
final HttpParameters wrappedParameters = HttpParameters.create(parameters).build();
|
||||
final ActionMapping actionMapping = new ActionMapping("testAction", "testNameSpace", "testMethod", parameters);
|
||||
ac.put(ServletActionContext.ACTION_MAPPING, actionMapping);
|
||||
|
||||
// Retrieve parameters and confirm both builder result equality and that the contained Object
|
||||
// values of each Parameter element are not of type Parameter (i.e. no double-wrapping).
|
||||
// Note: ampi.retrieveParameters() only ever returns the parameters associated with the ActionContext's
|
||||
// ActionMapping (not changed directly by ampi.addParametersToContext()).
|
||||
final HttpParameters retrievedParameters = ampi.retrieveParameters(ac);
|
||||
assertNotNull("retrievedParameters null ?", retrievedParameters);
|
||||
// Note: Cannot perform equality test on HttpParameters directly as hashCode values differ even
|
||||
// when the contents are equivalent. Instead we compare size and content equality.
|
||||
assertEquals("retrievedParameters size not equal to wrappedParameters size ?",
|
||||
retrievedParameters.size(), wrappedParameters.size());
|
||||
|
||||
for (String parameterName : retrievedParameters.keySet() ) {
|
||||
Parameter retrievedParameter = retrievedParameters.get(parameterName);
|
||||
Parameter wrappedParameter = wrappedParameters.get(parameterName);
|
||||
assertNotNull("retrievedParameter is null ?", retrievedParameter);
|
||||
assertNotNull("wrappedParameter is null ?", wrappedParameter);
|
||||
Object retrievedParameterValue = retrievedParameter.getObject();
|
||||
Object wrappedParameterValue = wrappedParameter.getObject();
|
||||
assertNotNull("retrievedParameterValue is null ?", retrievedParameterValue);
|
||||
assertNotNull("wrappedParameterValue is null ?", wrappedParameterValue);
|
||||
assertFalse("retrievedParameterValue is type Parameter ?", retrievedParameterValue instanceof Parameter);
|
||||
assertEquals("retrievedParameterValue not equal to wrappedParameterValue ?",
|
||||
retrievedParameterValue, wrappedParameterValue);
|
||||
}
|
||||
|
||||
// Set up the initial ActionMapping with (artificially) already-wrapped parameters in the context
|
||||
final Map<String, Object> wrappedParametersMap = new HashMap<>(wrappedParameters.size());
|
||||
for (String parameterName : wrappedParameters.keySet() ) {
|
||||
wrappedParametersMap.put(parameterName, wrappedParameters.get(parameterName));
|
||||
}
|
||||
final ActionMapping actionMappingWrapped = new ActionMapping("testAction", "testNameSpace", "testMethod", wrappedParametersMap);
|
||||
ac.put(ServletActionContext.ACTION_MAPPING, actionMappingWrapped);
|
||||
|
||||
// Retrieve parameters and confirm that the contained Object values of each Parameter
|
||||
// element are not of type Parameter (i.e. no double-wrapping).
|
||||
// Note: ampi.retrieveParameters() only ever returns the parameters associated with the ActionContext's
|
||||
// ActionMapping (not changed directly by ampi.addParametersToContext()).
|
||||
final HttpParameters retrievedWrappedParameters = ampi.retrieveParameters(ac);
|
||||
assertNotNull("retrievedWrappedParameters null ?", retrievedWrappedParameters);
|
||||
// Note: Cannot perform equality test on HttpParameters directly as hashCode values differ even
|
||||
// when the contents are equivalent. Instead we compare size and content equality.
|
||||
assertEquals("retrievedWrappedParameters size not equal to wrappedParametersMap size ?",
|
||||
retrievedWrappedParameters.size(), wrappedParametersMap.size());
|
||||
|
||||
for (String parameterName : retrievedWrappedParameters.keySet() ) {
|
||||
Parameter retrievedParameter = retrievedWrappedParameters.get(parameterName);
|
||||
Object wrappedParameter = wrappedParametersMap.get(parameterName);
|
||||
assertNotNull("retrievedParameter is null ?", retrievedParameter);
|
||||
assertNotNull("wrappedParameter is null ?", wrappedParameter);
|
||||
assertTrue("wrappedParameter is not a Parameter ?", wrappedParameter instanceof Parameter);
|
||||
Object retrievedParameterValue = retrievedParameter.getObject();
|
||||
Object wrappedParameterValue = ((Parameter) wrappedParameter).getObject();
|
||||
assertNotNull("retrievedParameterValue is null ?", retrievedParameterValue);
|
||||
assertNotNull("wrappedParameterValue is null ?", wrappedParameterValue);
|
||||
assertFalse("retrievedParameterValue is type Parameter ?", retrievedParameterValue instanceof Parameter);
|
||||
assertEquals("retrievedParameterValue not equal to wrappedParameterValue ?",
|
||||
retrievedParameterValue, wrappedParameterValue);
|
||||
}
|
||||
|
||||
// Add parameters to the context
|
||||
ampi.addParametersToContext(ac, parameters);
|
||||
|
||||
// Retrieve parameters and confirm the expected size and that the contained Object
|
||||
// values of each Parameter element are not of type Parameter (i.e. no double-wrapping).
|
||||
final HttpParameters retrievedACParameters = ac.getParameters();
|
||||
assertNotNull("retrievedACParameters null ?", retrievedACParameters);
|
||||
assertEquals("retrievedACParameters size not equal to parameters size ?",
|
||||
retrievedACParameters.size(), parameters.size());
|
||||
|
||||
for (String parameterName : retrievedACParameters.keySet() ) {
|
||||
Parameter retrievedACParameter = retrievedACParameters.get(parameterName);
|
||||
assertNotNull("retrievedACParameter is null ?", retrievedACParameter);
|
||||
Object parameterValue = retrievedACParameter.getObject();
|
||||
assertNotNull("parameterValue is null ?", parameterValue);
|
||||
assertFalse("parameterValue is of type Parameter ?", parameterValue instanceof Parameter);
|
||||
}
|
||||
|
||||
// Add additional parameters to the context
|
||||
ampi.addParametersToContext(ac, moreParameters);
|
||||
|
||||
// Retrieve parameters and confirm the expected size and that the contained Object
|
||||
// values of each Parameter element are not of type Parameter (i.e. no double-wrapping).
|
||||
final HttpParameters retrievedACMoreParameters = ac.getParameters();
|
||||
assertNotNull("retrievedACMoreParameters null ?", retrievedACMoreParameters);
|
||||
assertEquals("retrievedACMoreParameters size not equal to combined size (parameters + moreParameters) ?",
|
||||
retrievedACMoreParameters.size(), parameters.size() + moreParameters.size());
|
||||
|
||||
for (String parameterName : retrievedACMoreParameters.keySet() ) {
|
||||
Parameter retrievedACMoreParameter = retrievedACMoreParameters.get(parameterName);
|
||||
assertNotNull("retrievedACMoreParameter is null ?", retrievedACMoreParameter);
|
||||
Object parameterValue = retrievedACMoreParameter.getObject();
|
||||
assertNotNull("parameterValue (more) is null ?", parameterValue);
|
||||
assertFalse("parameterValue (more) is of type Parameter ?", parameterValue instanceof Parameter);
|
||||
}
|
||||
|
||||
// Build some "already wrapped" parameters and attempt to add them to the context
|
||||
final HttpParameters evenMoreWrappedParameters = HttpParameters.create(evenMoreParameters).build();
|
||||
assertNotNull("evenMoreWrappedParameters null ?", evenMoreWrappedParameters);
|
||||
assertEquals("evenMoreWrappedParameters size not equal to evenMoreParameters size ?",
|
||||
evenMoreWrappedParameters.size(), evenMoreParameters.size());
|
||||
ampi.addParametersToContext(ac, evenMoreWrappedParameters);
|
||||
|
||||
// Retrieve parameters and confirm the expected size and that the contained Object
|
||||
// values of each Parameter element are not of type Parameter (i.e. no double-wrapping).
|
||||
final HttpParameters retrievedACEvenMoreParameters = ac.getParameters();
|
||||
assertNotNull("retrievedACEvenMoreParameters null ?", retrievedACEvenMoreParameters);
|
||||
assertEquals("retrievedACEvenMoreParameters size not equal to combined size (parameters + moreParameters + evenMoreParameters) ?",
|
||||
retrievedACEvenMoreParameters.size(), parameters.size() + moreParameters.size() + evenMoreParameters.size());
|
||||
|
||||
for (String parameterName : retrievedACEvenMoreParameters.keySet() ) {
|
||||
Parameter retrievedACEvenMoreParameter = retrievedACEvenMoreParameters.get(parameterName);
|
||||
assertNotNull("retrievedACEvenMoreParameter is null ?", retrievedACEvenMoreParameter);
|
||||
Object parameterValue = retrievedACEvenMoreParameter.getObject();
|
||||
assertNotNull("parameterValue (even more) is null ?", parameterValue);
|
||||
assertFalse("parameterValue (even more) is of type Parameter ?", parameterValue instanceof Parameter);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create and configure an ActionMappingParametersInterceptor instance
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
private ActionMappingParametersInterceptor createActionMappingParametersInterceptor() {
|
||||
ActionMappingParametersInterceptor ampi = new ActionMappingParametersInterceptor();
|
||||
container.inject(ampi);
|
||||
return ampi;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -79,8 +79,8 @@ public class I18nInterceptorTest extends TestCase {
|
||||
|
||||
assertFalse("should have been removed",
|
||||
mai.getInvocationContext().getParameters().get(I18nInterceptor.DEFAULT_PARAMETER).isDefined());
|
||||
assertNull("should not be created", request.getSession(false));
|
||||
assertNull("should not be stored here", session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE));
|
||||
assertNotNull("should be created", request.getSession(false));
|
||||
assertNotNull("should be stored here", session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE));
|
||||
}
|
||||
|
||||
public void testDefaultLocale() throws Exception {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user