You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@struts.apache.org by lu...@apache.org on 2011/12/02 17:33:45 UTC
svn commit: r1209569 [46/50] - in /struts/struts2/branches/STRUTS_3_X:
apps/blank/src/main/java/example/ apps/blank/src/test/java/example/
apps/jboss-blank/src/main/java/example/
apps/jboss-blank/src/test/java/example/ apps/mailreader/src/main/java/mai...
Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/TextParseUtilTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/TextParseUtilTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/TextParseUtilTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/TextParseUtilTest.java Fri Dec 2 16:33:03 2011
@@ -0,0 +1,141 @@
+/*
+ * Copyright 2002-2006,2009 The Apache Software Foundation.
+ *
+ * Licensed 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.xwork2.util;
+
+import org.apache.struts2.xwork2.ActionContext;
+import org.apache.struts2.xwork2.XWorkTestCase;
+
+import java.util.*;
+
+/**
+ * Unit test of {@link TextParseUtil}.
+ *
+ * @author plightbo
+ * @author tm_jee
+ *
+ * @version $Date: 2011-12-02 12:24:48 +0100 (Fri, 02 Dec 2011) $ $Id: TextParseUtilTest.java 1209415 2011-12-02 11:24:48Z lukaszlenart $
+ */
+public class TextParseUtilTest extends XWorkTestCase {
+
+
+ public void testTranslateVariablesWithEvaluator() throws Exception {
+ ValueStack stack = ActionContext.getContext().getValueStack();
+ stack.push(new Object() {
+ public String getMyVariable() {
+ return "My Variable ";
+ }
+ });
+
+ TextParseUtil.ParsedValueEvaluator evaluator = new TextParseUtil.ParsedValueEvaluator() {
+ public Object evaluate(Object parsedValue) {
+ return parsedValue.toString()+"Something";
+ }
+ };
+
+ String result = TextParseUtil.translateVariables("Hello ${myVariable}", stack, evaluator);
+
+ assertEquals(result, "Hello My Variable Something");
+ }
+
+ public void testTranslateVariables() {
+ ValueStack stack = ActionContext.getContext().getValueStack();
+
+ Object s = TextParseUtil.translateVariables("foo: ${{1, 2, 3}}, bar: ${1}", stack);
+ assertEquals("foo: [1, 2, 3], bar: 1", s);
+
+ s = TextParseUtil.translateVariables("foo: %{{1, 2, 3}}, bar: %{1}", stack);
+ assertEquals("foo: [1, 2, 3], bar: 1", s);
+
+ s = TextParseUtil.translateVariables("foo: %{{1, 2, 3}}, bar: %{1}", stack);
+ assertEquals("foo: [1, 2, 3], bar: 1", s);
+
+ s = TextParseUtil.translateVariables("foo: ${#{1 : 2, 3 : 4}}, bar: ${1}", stack);
+ assertEquals("foo: {1=2, 3=4}, bar: 1", s);
+
+ s = TextParseUtil.translateVariables("foo: %{#{1 : 2, 3 : 4}}, bar: %{1}", stack);
+ assertEquals("foo: {1=2, 3=4}, bar: 1", s);
+
+ s = TextParseUtil.translateVariables("foo: 1}", stack);
+ assertEquals("foo: 1}", s);
+
+ s = TextParseUtil.translateVariables("foo: {1}", stack);
+ assertEquals("foo: {1}", s);
+
+ s = TextParseUtil.translateVariables("foo: ${1", stack);
+ assertEquals("foo: ${1", s);
+
+ s = TextParseUtil.translateVariables("foo: %{1", stack);
+ assertEquals("foo: %{1", s);
+
+ s = TextParseUtil.translateVariables('$', "${{1, 2, 3}}", stack, Object.class);
+ assertNotNull(s);
+ assertTrue("List not returned when parsing a 'pure' list", s instanceof List);
+ assertEquals(((List)s).size(), 3);
+
+ s = TextParseUtil.translateVariables('$', "${#{'key1':'value1','key2':'value2','key3':'value3'}}", stack, Object.class);
+ assertNotNull(s);
+ assertTrue("Map not returned when parsing a 'pure' map", s instanceof Map);
+ assertEquals(((Map)s).size(), 3);
+
+ s = TextParseUtil.translateVariables('$', "${1} two ${3}", stack, Object.class);
+ assertEquals("1 two 3", s);
+
+ s = TextParseUtil.translateVariables('$', "count must be between ${123} and ${456}, current value is ${98765}.", stack, Object.class);
+ assertEquals("count must be between 123 and 456, current value is 98765.", s);
+ }
+
+ public void testCommaDelimitedStringToSet() {
+ assertEquals(0, TextParseUtil.commaDelimitedStringToSet("").size());
+ assertEquals(new HashSet<String>(Arrays.asList("foo", "bar", "tee")),
+ TextParseUtil.commaDelimitedStringToSet(" foo, bar,tee"));
+ }
+
+ public void testTranslateVariablesOpenChar() {
+ // just a quick test to see if the open char works
+ // most test are done the methods above
+ ValueStack stack = ActionContext.getContext().getValueStack();
+
+ Object s = TextParseUtil.translateVariables('$', "foo: ${{1, 2, 3}}, bar: ${1}", stack);
+ assertEquals("foo: [1, 2, 3], bar: 1", s);
+
+ Object s2 = TextParseUtil.translateVariables('#', "foo: #{{1, 2, 3}}, bar: #{1}", stack);
+ assertEquals("foo: [1, 2, 3], bar: 1", s2);
+ }
+
+ public void testTranslateNoVariables() {
+ ValueStack stack = ActionContext.getContext().getValueStack();
+
+ Object s = TextParseUtil.translateVariables('$', "foo: ${}", stack);
+ assertEquals("foo: ", s);
+ }
+
+ public void testTranslateVariablesNoRecursive() {
+ ValueStack stack = ActionContext.getContext().getValueStack();
+ stack.push(new HashMap<String, Object>() {{ put("foo", "${1+1}"); }});
+
+ Object s = TextParseUtil.translateVariables('$', "foo: ${foo}", stack, String.class, null, 1);
+ assertEquals("foo: ${1+1}", s);
+ }
+
+ public void testTranslateVariablesRecursive() {
+ ValueStack stack = ActionContext.getContext().getValueStack();
+ stack.push(new HashMap<String, Object>() {{ put("foo", "${1+1}"); }});
+
+ Object s = TextParseUtil.translateVariables('$', "foo: ${foo}", stack, String.class, null, 2);
+ assertEquals("foo: 2", s);
+ }
+
+}
Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/Tiger.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/Tiger.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/Tiger.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/Tiger.java Fri Dec 2 16:33:03 2011
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2002-2003,2009 The Apache Software Foundation.
+ *
+ * Licensed 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.xwork2.util;
+
+import java.util.List;
+
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision: 1209415 $
+ */
+public class Tiger extends Cat {
+
+ List dogs;
+
+
+ public void setDogs(List dogs) {
+ this.dogs = dogs;
+ }
+
+ public List getDogs() {
+ return dogs;
+ }
+}
Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/URLUtilTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/URLUtilTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/URLUtilTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/URLUtilTest.java Fri Dec 2 16:33:03 2011
@@ -0,0 +1,169 @@
+package org.apache.struts2.xwork2.util;
+
+import junit.framework.TestCase;
+
+import java.net.URL;
+import java.net.MalformedURLException;
+import java.net.URLStreamHandlerFactory;
+import java.net.URLStreamHandler;
+import java.net.URLConnection;
+import java.io.IOException;
+
+public class URLUtilTest extends TestCase {
+
+ public void testSimpleFile() throws MalformedURLException {
+ URL url = new URL("file:c:/somefile.txt");
+ URL outputURL = URLUtil.normalizeToFileProtocol(url);
+
+ assertNull(outputURL);
+ }
+
+ public void testJarFile() throws MalformedURLException {
+ URL url = new URL("jar:file:/c:/somefile.jar!/");
+ URL outputURL = URLUtil.normalizeToFileProtocol(url);
+
+ assertNotNull(outputURL);
+ assertEquals("file:/c:/somefile.jar", outputURL.toExternalForm());
+
+ url = new URL("jar:file:/c:/somefile.jar!/somestuf/bla/bla");
+ outputURL = URLUtil.normalizeToFileProtocol(url);
+ assertEquals("file:/c:/somefile.jar", outputURL.toExternalForm());
+
+ url = new URL("jar:file:c:/somefile.jar!/somestuf/bla/bla");
+ outputURL = URLUtil.normalizeToFileProtocol(url);
+ assertEquals("file:c:/somefile.jar", outputURL.toExternalForm());
+ }
+
+ public void testJarFileWithJarWordInsidePath() throws MalformedURLException {
+ URL url = new URL("jar:file:/c:/workspace/projar/somefile.jar!/");
+ URL outputURL = URLUtil.normalizeToFileProtocol(url);
+
+ assertNotNull(outputURL);
+ assertEquals("file:/c:/workspace/projar/somefile.jar", outputURL.toExternalForm());
+
+ url = new URL("jar:file:/c:/workspace/projar/somefile.jar!/somestuf/bla/bla");
+ outputURL = URLUtil.normalizeToFileProtocol(url);
+ assertEquals("file:/c:/workspace/projar/somefile.jar", outputURL.toExternalForm());
+
+ url = new URL("jar:file:c:/workspace/projar/somefile.jar!/somestuf/bla/bla");
+ outputURL = URLUtil.normalizeToFileProtocol(url);
+ assertEquals("file:c:/workspace/projar/somefile.jar", outputURL.toExternalForm());
+ }
+
+ public void testZipFile() throws MalformedURLException {
+ URL url = new URL("zip:/c:/somefile.zip!/");
+ URL outputURL = URLUtil.normalizeToFileProtocol(url);
+
+ assertNotNull(outputURL);
+ assertEquals("file:/c:/somefile.zip", outputURL.toExternalForm());
+
+ url = new URL("zip:/c:/somefile.zip!/somestuf/bla/bla");
+ outputURL = URLUtil.normalizeToFileProtocol(url);
+ assertEquals("file:/c:/somefile.zip", outputURL.toExternalForm());
+
+ url = new URL("zip:c:/somefile.zip!/somestuf/bla/bla");
+ outputURL = URLUtil.normalizeToFileProtocol(url);
+ assertEquals("file:c:/somefile.zip", outputURL.toExternalForm());
+ }
+
+ public void testWSJarFile() throws MalformedURLException {
+ URL url = new URL("wsjar:file:/c:/somefile.jar!/");
+ URL outputURL = URLUtil.normalizeToFileProtocol(url);
+
+ assertNotNull(outputURL);
+ assertEquals("file:/c:/somefile.jar", outputURL.toExternalForm());
+
+ url = new URL("wsjar:file:/c:/somefile.jar!/somestuf/bla/bla");
+ outputURL = URLUtil.normalizeToFileProtocol(url);
+ assertEquals("file:/c:/somefile.jar", outputURL.toExternalForm());
+
+ url = new URL("wsjar:file:c:/somefile.jar!/somestuf/bla/bla");
+ outputURL = URLUtil.normalizeToFileProtocol(url);
+ assertEquals("file:c:/somefile.jar", outputURL.toExternalForm());
+ }
+
+ public void testVsFile() throws MalformedURLException {
+ URL url = new URL("vfsfile:/c:/somefile.jar!/");
+ URL outputURL = URLUtil.normalizeToFileProtocol(url);
+
+ assertNotNull(outputURL);
+ assertEquals("file:/c:/somefile.jar", outputURL.toExternalForm());
+
+ url = new URL("vfsfile:/c:/somefile.jar!/somestuf/bla/bla");
+ outputURL = URLUtil.normalizeToFileProtocol(url);
+ assertEquals("file:/c:/somefile.jar", outputURL.toExternalForm());
+
+ url = new URL("vfsfile:c:/somefile.jar!/somestuf/bla/bla");
+ outputURL = URLUtil.normalizeToFileProtocol(url);
+ assertEquals("file:c:/somefile.jar", outputURL.toExternalForm());
+
+ url = new URL("vfszip:/c:/somefile.war/somelibrary.jar");
+ outputURL = URLUtil.normalizeToFileProtocol(url);
+ assertEquals("file:/c:/somefile.war/somelibrary.jar", outputURL.toExternalForm());
+ }
+
+ public void testJBossFile() throws MalformedURLException {
+ URL url = new URL("vfszip:/c:/somefile.jar!/");
+ URL outputURL = URLUtil.normalizeToFileProtocol(url);
+
+ assertNotNull(outputURL);
+ assertEquals("file:/c:/somefile.jar", outputURL.toExternalForm());
+
+ url = new URL("vfszip:/c:/somefile.jar!/somestuf/bla/bla");
+ outputURL = URLUtil.normalizeToFileProtocol(url);
+ assertEquals("file:/c:/somefile.jar", outputURL.toExternalForm());
+
+ url = new URL("vfsmemory:c:/somefile.jar!/somestuf/bla/bla");
+ outputURL = URLUtil.normalizeToFileProtocol(url);
+ assertEquals("file:c:/somefile.jar", outputURL.toExternalForm());
+
+ url = new URL("vfsmemory:/c:/somefile.war/somelibrary.jar");
+ outputURL = URLUtil.normalizeToFileProtocol(url);
+ assertEquals("file:/c:/somefile.war/somelibrary.jar", outputURL.toExternalForm());
+ }
+
+ protected void setUp() throws Exception {
+ super.setUp();
+
+ try {
+ URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {
+ public URLStreamHandler createURLStreamHandler(String protocol) {
+ return new URLStreamHandler() {
+ protected URLConnection openConnection(URL u) throws IOException {
+ return null;
+ }
+ };
+ }
+ });
+ } catch (Throwable e) {
+ //the factory cant be set multiple times..just ignore exception no biggie
+ }
+ }
+
+ public void testVerifyUrl() {
+ assertEquals(false, URLUtil.verifyUrl(null));
+ assertEquals(false, URLUtil.verifyUrl(""));
+ assertEquals(false, URLUtil.verifyUrl(" "));
+ assertEquals(false, URLUtil.verifyUrl("no url"));
+
+ assertEquals(true, URLUtil.verifyUrl("http://www.opensymphony.com"));
+ assertEquals(true, URLUtil.verifyUrl("https://www.opensymphony.com"));
+ assertEquals(true, URLUtil.verifyUrl("https://www.opensymphony.com:443/login"));
+ assertEquals(true, URLUtil.verifyUrl("http://localhost:8080/myapp"));
+ }
+
+ public void testIsJarURL() throws Exception {
+ assertTrue(URLUtil.isJarURL(new URL("jar:file:/c:/somelibrary.jar!/org/apache/struts2")));
+ assertTrue(URLUtil.isJarURL(new URL("zip:/c:/somelibrary.jar!/org/apache/struts2")));
+ assertTrue(URLUtil.isJarURL(new URL("wsjar:/c:/somelibrary.jar!/org/apache/struts2")));
+ assertTrue(URLUtil.isJarURL(new URL("vfsfile:/c:/somelibrary.jar!/org/apache/struts2")));
+ assertTrue(URLUtil.isJarURL(new URL("vfszip:/c:/somelibrary.jar/org/apache/struts2")));
+ }
+
+ public void testIsJBoss5Url() throws Exception {
+ assertTrue(URLUtil.isJBoss5Url(new URL("vfszip:/c:/somewar.war/somelibrary.jar")));
+ assertFalse(URLUtil.isJBoss5Url(new URL("vfsfile:/c:/somewar.war/somelibrary.jar")));
+ assertFalse(URLUtil.isJBoss5Url(new URL("jar:file:/c:/somelibrary.jar")));
+ assertTrue(URLUtil.isJBoss5Url(new URL("vfsmemory:/c:/somewar.war/somelibrary.jar")));
+ }
+}
Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/UnknownHandlerManagerTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/UnknownHandlerManagerTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/UnknownHandlerManagerTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/UnknownHandlerManagerTest.java Fri Dec 2 16:33:03 2011
@@ -0,0 +1,82 @@
+package org.apache.struts2.xwork2.util;
+
+import java.util.List;
+
+import org.apache.struts2.xwork2.DefaultUnknownHandlerManager;
+import org.apache.struts2.xwork2.UnknownHandler;
+import org.apache.struts2.xwork2.UnknownHandlerManager;
+import org.apache.struts2.xwork2.UnknownHandlerManagerMock;
+import org.apache.struts2.xwork2.config.ConfigurationException;
+import org.apache.struts2.xwork2.config.ConfigurationProvider;
+import org.apache.struts2.xwork2.config.providers.ConfigurationTestBase;
+import org.apache.struts2.xwork2.config.providers.SomeUnknownHandler;
+
+/**
+ * Test UnknownHandlerUtil
+ */
+public class UnknownHandlerManagerTest extends ConfigurationTestBase {
+
+ public void testStack() throws ConfigurationException {
+ final String filename = "org/apache/struts2/xwork2/config/providers/xwork-unknownhandler-stack.xml";
+ ConfigurationProvider provider = buildConfigurationProvider(filename);
+ loadConfigurationProviders(provider);
+ configurationManager.reload();
+
+ UnknownHandlerManager unknownHandlerManager = new DefaultUnknownHandlerManager();
+ container.inject(unknownHandlerManager);
+ List<UnknownHandler> unknownHandlers = unknownHandlerManager.getUnknownHandlers();
+
+ assertNotNull(unknownHandlers);
+ assertEquals(2, unknownHandlers.size());
+
+ UnknownHandler uh1 = unknownHandlers.get(0);
+ UnknownHandler uh2 = unknownHandlers.get(1);
+
+ assertTrue(uh1 instanceof SomeUnknownHandler);
+ assertTrue(uh2 instanceof SomeUnknownHandler);
+ }
+
+ public void testEmptyStack() throws ConfigurationException {
+ final String filename = "org/apache/struts2/xwork2/config/providers/xwork-unknownhandler-stack-empty.xml";
+ ConfigurationProvider provider = buildConfigurationProvider(filename);
+ loadConfigurationProviders(provider);
+ configurationManager.reload();
+
+ UnknownHandlerManager unknownHandlerManager = new DefaultUnknownHandlerManager();
+ container.inject(unknownHandlerManager);
+ List<UnknownHandler> unknownHandlers = unknownHandlerManager.getUnknownHandlers();
+
+ assertNotNull(unknownHandlers);
+ assertEquals(2, unknownHandlers.size());
+
+ UnknownHandler uh1 = unknownHandlers.get(0);
+ UnknownHandler uh2 = unknownHandlers.get(1);
+
+ assertTrue(uh1 instanceof SomeUnknownHandler);
+ assertTrue(uh2 instanceof SomeUnknownHandler);
+ }
+
+ public void testInvocationOrder() throws ConfigurationException, NoSuchMethodException {
+ SomeUnknownHandler uh1 = new SomeUnknownHandler();
+ uh1.setActionMethodResult("uh1");
+
+ SomeUnknownHandler uh2 = new SomeUnknownHandler();
+ uh2.setActionMethodResult("uh2");
+
+ UnknownHandlerManagerMock uhm = new UnknownHandlerManagerMock();
+ uhm.addUnknownHandler(uh1);
+ uhm.addUnknownHandler(uh2);
+
+ //should pick the first one
+ assertEquals("uh1", uhm.handleUnknownMethod(null, null));
+
+ //should pick the second one
+ uh1.setActionMethodResult(null);
+ assertEquals("uh2", uhm.handleUnknownMethod(null, null));
+
+ //should not pick any
+ uh1.setActionMethodResult(null);
+ uh2.setActionMethodResult(null);
+ assertEquals(null, uhm.handleUnknownMethod(null, null));
+ }
+}
Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/UrlUtilTest2.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/UrlUtilTest2.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/UrlUtilTest2.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/UrlUtilTest2.java Fri Dec 2 16:33:03 2011
@@ -0,0 +1,35 @@
+package org.apache.struts2.xwork2.util;
+
+import junit.framework.TestCase;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.jar.JarInputStream;
+
+/**
+ * Keep these test on a separate class, they can't be in UrlUtilTest because the
+ * registered URLStreamHandlerFactory would make them fail
+ */
+public class UrlUtilTest2 extends TestCase {
+ public void testOpenWithJarProtocol() throws IOException {
+ URL url = ClassLoaderUtil.getResource("xwork-jar.jar", URLUtil.class);
+ URL jarUrl = new URL("jar", "", url.toExternalForm() + "!/");
+ URL outputURL = URLUtil.normalizeToFileProtocol(jarUrl);
+ assertNotNull(outputURL);
+ assertUrlCanBeOpened(outputURL);
+ }
+
+ private void assertUrlCanBeOpened(URL url) throws IOException {
+ InputStream is = url.openStream();
+ JarInputStream jarStream = null;
+ try {
+ jarStream = new JarInputStream(is);
+ assertNotNull(jarStream);
+ } finally {
+ if (jarStream != null)
+ jarStream.close();
+
+ }
+ }
+}
Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/WildcardHelperTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/WildcardHelperTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/WildcardHelperTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/WildcardHelperTest.java Fri Dec 2 16:33:03 2011
@@ -0,0 +1,56 @@
+/*
+ * $Id: WildcardHelperTest.java 1209415 2011-12-02 11:24:48Z lukaszlenart $
+ *
+ * Copyright 2003-2004 The Apache Software Foundation.
+ *
+ * Licensed 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.xwork2.util;
+
+import org.apache.struts2.xwork2.XWorkTestCase;
+
+import java.util.HashMap;
+
+public class WildcardHelperTest extends XWorkTestCase {
+
+ public void testMatch() {
+
+ WildcardHelper wild = new WildcardHelper();
+ HashMap<String,String> matchedPatterns = new HashMap<String,String>();
+ int[] pattern = wild.compilePattern("wes-rules");
+ assertEquals(wild.match(matchedPatterns,"wes-rules", pattern), true);
+ assertEquals(wild.match(matchedPatterns, "rules-wes", pattern), false);
+
+ pattern = wild.compilePattern("wes-*");
+ assertEquals(wild.match(matchedPatterns,"wes-rules", pattern), true);
+ assertEquals("rules".equals(matchedPatterns.get("1")), true);
+ assertEquals(wild.match(matchedPatterns, "rules-wes", pattern), false);
+
+ pattern = wild.compilePattern("path/**/file");
+ assertEquals(wild.match(matchedPatterns, "path/to/file", pattern), true);
+ assertEquals("to".equals(matchedPatterns.get("1")), true);
+ assertEquals(wild.match(matchedPatterns, "path/to/another/location/of/file", pattern), true);
+ assertEquals("to/another/location/of".equals(matchedPatterns.get("1")), true);
+
+ pattern = wild.compilePattern("path/*/file");
+ assertEquals(wild.match(matchedPatterns, "path/to/file", pattern), true);
+ assertEquals("to".equals(matchedPatterns.get("1")), true);
+ assertEquals(wild.match(matchedPatterns, "path/to/another/location/of/file", pattern), false);
+
+ pattern = wild.compilePattern("path/*/another/**/file");
+ assertEquals(wild.match(matchedPatterns, "path/to/another/location/of/file", pattern), true);
+ assertEquals("to".equals(matchedPatterns.get("1")), true);
+ assertEquals("location/of".equals(matchedPatterns.get("2")), true);
+ }
+
+}
Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/WildcardUtilTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/WildcardUtilTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/WildcardUtilTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/WildcardUtilTest.java Fri Dec 2 16:33:03 2011
@@ -0,0 +1,56 @@
+/*
+ * $Id: WildcardUtilTest.java 1209415 2011-12-02 11:24:48Z lukaszlenart $
+ *
+ * Copyright 2003-2004 The Apache Software Foundation.
+ *
+ * Licensed 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.xwork2.util;
+
+import org.apache.struts2.xwork2.XWorkTestCase;
+
+import java.util.regex.Pattern;
+
+public class WildcardUtilTest extends XWorkTestCase {
+
+ public void testPattern() {
+
+ Pattern p = WildcardUtil.compileWildcardPattern("a*b");
+ assertTrue(p.matcher("ab").matches());
+ assertTrue(p.matcher("axyb").matches());
+ assertFalse(p.matcher("bxyb").matches());
+
+ p = WildcardUtil.compileWildcardPattern("a\\*b");
+ assertFalse(p.matcher("ab").matches());
+ assertTrue(p.matcher("a*b").matches());
+
+ p = WildcardUtil.compileWildcardPattern("a.*");
+ assertFalse(p.matcher("ab").matches());
+ assertFalse(p.matcher("ab.b").matches());
+ assertTrue(p.matcher("a.b").matches());
+ assertTrue(p.matcher("a.bc").matches());
+ assertTrue(p.matcher("a.b.c").matches());
+
+ p = WildcardUtil.compileWildcardPattern("a[*]");
+ assertFalse(p.matcher("ab").matches());
+ assertFalse(p.matcher("ab[b]").matches());
+ assertTrue(p.matcher("a[b]").matches());
+ assertTrue(p.matcher("a[bc]").matches());
+ assertFalse(p.matcher("a[b].c").matches());
+
+ p = WildcardUtil.compileWildcardPattern("a[*].*");
+ assertTrue(p.matcher("a[b].c").matches());
+ assertTrue(p.matcher("a[bc].cd").matches());
+ }
+
+}
Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/XWorkListTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/XWorkListTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/XWorkListTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/XWorkListTest.java Fri Dec 2 16:33:03 2011
@@ -0,0 +1,90 @@
+/*
+ * Copyright 2002-2003,2009 The Apache Software Foundation.
+ *
+ * Licensed 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.xwork2.util;
+
+import org.apache.struts2.xwork2.ObjectFactory;
+import org.apache.struts2.xwork2.XWorkTestCase;
+import org.apache.struts2.xwork2.conversion.impl.XWorkConverter;
+
+import java.util.ArrayList;
+
+
+/**
+ * Test cases for {@link XWorkList}.
+ *
+ * @author Mark Woon
+ */
+public class XWorkListTest extends XWorkTestCase {
+
+ public void testAddAllIndex() {
+ XWorkConverter conv = container.getInstance(XWorkConverter.class);
+ ObjectFactory of = container.getInstance(ObjectFactory.class);
+ XWorkList xworkList = new XWorkList(of, conv, String.class);
+ xworkList.add(new String[]{"a"});
+ xworkList.add("b");
+
+ ArrayList addList = new ArrayList();
+ addList.add(new String[]{"1"});
+ addList.add(new String[]{"2"});
+ addList.add(new String[]{"3"});
+
+ // trim
+ xworkList.addAll(3, addList);
+ assertEquals(6, xworkList.size());
+ assertEquals("a", xworkList.get(0));
+ assertEquals("b", xworkList.get(1));
+ assertEquals("", xworkList.get(2));
+ assertEquals("1", xworkList.get(3));
+ assertEquals("2", xworkList.get(4));
+ assertEquals("3", xworkList.get(5));
+
+ // take 2, no trim
+ xworkList = new XWorkList(of, conv,String.class);
+ xworkList.add(new String[]{"a"});
+ xworkList.add("b");
+
+ addList = new ArrayList();
+ addList.add(new String[]{"1"});
+ addList.add(new String[]{"2"});
+ addList.add(new String[]{"3"});
+
+ xworkList.addAll(2, addList);
+ assertEquals(5, xworkList.size());
+ assertEquals("a", xworkList.get(0));
+ assertEquals("b", xworkList.get(1));
+ assertEquals("1", xworkList.get(2));
+ assertEquals("2", xworkList.get(3));
+ assertEquals("3", xworkList.get(4));
+
+ // take 3, insert
+ xworkList = new XWorkList(of, conv,String.class);
+ xworkList.add(new String[]{"a"});
+ xworkList.add("b");
+
+ addList = new ArrayList();
+ addList.add(new String[]{"1"});
+ addList.add(new String[]{"2"});
+ addList.add(new String[]{"3"});
+
+ xworkList.addAll(1, addList);
+ assertEquals(5, xworkList.size());
+ assertEquals("a", xworkList.get(0));
+ assertEquals("1", xworkList.get(1));
+ assertEquals("2", xworkList.get(2));
+ assertEquals("3", xworkList.get(3));
+ assertEquals("b", xworkList.get(4));
+ }
+}
Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/location/LocationAttributesTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/location/LocationAttributesTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/location/LocationAttributesTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/location/LocationAttributesTest.java Fri Dec 2 16:33:03 2011
@@ -0,0 +1,87 @@
+/*
+ * Copyright 2006,2009 The Apache Software Foundation.
+ *
+ * Licensed 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.xwork2.util.location;
+
+import junit.framework.TestCase;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.xml.sax.Locator;
+import org.xml.sax.helpers.AttributesImpl;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+public class LocationAttributesTest extends TestCase {
+
+ public LocationAttributesTest(String name) {
+ super(name);
+ }
+
+ public void testAddLocationAttributes() throws Exception {
+ AttributesImpl attrs = new AttributesImpl();
+ LocationAttributes.addLocationAttributes(new Locator() {
+ public int getColumnNumber() { return 40; }
+ public int getLineNumber() { return 1; }
+ public String getSystemId() { return "path/to/file.xml"; }
+ public String getPublicId() { return "path/to/file.xml"; }
+ }, attrs);
+
+ assertTrue("path/to/file.xml".equals(attrs.getValue("loc:src")));
+ assertTrue("1".equals(attrs.getValue("loc:line")));
+ assertTrue("40".equals(attrs.getValue("loc:column")));
+ }
+
+ public void testRecursiveRemove() throws Exception {
+ Document doc = getDoc("xml-with-location.xml");
+
+ Element root = doc.getDocumentElement();
+ LocationAttributes.remove(root, true);
+
+ assertNull(root.getAttributeNode("loc:line"));
+ assertNull(root.getAttributeNode("loc:column"));
+ assertNull(root.getAttributeNode("loc:src"));
+
+ Element kid = (Element)doc.getElementsByTagName("bar").item(0);
+ assertNull(kid.getAttributeNode("loc:line"));
+ assertNull(kid.getAttributeNode("loc:column"));
+ assertNull(kid.getAttributeNode("loc:src"));
+ }
+
+ public void testNonRecursiveRemove() throws Exception {
+ Document doc = getDoc("xml-with-location.xml");
+
+ Element root = doc.getDocumentElement();
+ LocationAttributes.remove(root, false);
+
+ assertNull(root.getAttributeNode("loc:line"));
+ assertNull(root.getAttributeNode("loc:column"));
+ assertNull(root.getAttributeNode("loc:src"));
+
+ Element kid = (Element)doc.getElementsByTagName("bar").item(0);
+ assertNotNull(kid.getAttributeNode("loc:line"));
+ assertNotNull(kid.getAttributeNode("loc:column"));
+ assertNotNull(kid.getAttributeNode("loc:src"));
+ }
+
+ private Document getDoc(String path) throws Exception {
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ factory.setNamespaceAware(true);
+ DocumentBuilder builder = factory.newDocumentBuilder();
+ return builder.parse(LocationAttributesTest.class.getResourceAsStream(path));
+
+
+ }
+}
Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/location/LocationImplTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/location/LocationImplTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/location/LocationImplTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/location/LocationImplTest.java Fri Dec 2 16:33:03 2011
@@ -0,0 +1,87 @@
+/*
+ * Copyright 2005 The Apache Software Foundation.
+ *
+ * Licensed 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.xwork2.util.location;
+
+import org.apache.struts2.xwork2.util.ClassLoaderUtil;
+import junit.framework.TestCase;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.net.URL;
+import java.util.List;
+
+public class LocationImplTest extends TestCase {
+
+ public LocationImplTest(String name) {
+ super(name);
+ }
+
+ static final String str = "path/to/file.xml:1:40";
+
+ public void testEquals() throws Exception {
+ Location loc1 = LocationUtils.parse(str);
+ Location loc2 = new LocationImpl(null, "path/to/file.xml", 1, 40);
+
+ assertEquals("locations", loc1, loc2);
+ assertEquals("hashcode", loc1.hashCode(), loc2.hashCode());
+ assertEquals("string representation", loc1.toString(), loc2.toString());
+ }
+
+ /**
+ * Test that Location.UNKNOWN is kept identical on deserialization
+ */
+ public void testSerializeUnknown() throws Exception {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream(bos);
+
+ oos.writeObject(Location.UNKNOWN);
+ oos.close();
+ bos.close();
+
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ ObjectInputStream ois = new ObjectInputStream(bis);
+
+ Object obj = ois.readObject();
+
+ assertSame("unknown location", Location.UNKNOWN, obj);
+ }
+
+ public void testGetSnippet() throws Exception {
+ URL url = ClassLoaderUtil.getResource("org/apache/struts2/xwork2/somefile.txt", getClass());
+ Location loc = new LocationImpl("foo", url.toString(), 3, 2);
+
+ List snippet = loc.getSnippet(1);
+ assertNotNull(snippet);
+ assertTrue("Wrong length: "+snippet.size(), 3 == snippet.size());
+
+ assertTrue("is".equals(snippet.get(0)));
+ assertTrue("a".equals(snippet.get(1)));
+ assertTrue("file".equals(snippet.get(2)));
+ }
+
+ public void testGetSnippetNoPadding() throws Exception {
+ URL url = ClassLoaderUtil.getResource("org/apache/struts2/xwork2/somefile.txt", getClass());
+ Location loc = new LocationImpl("foo", url.toString(), 3, 2);
+
+ List snippet = loc.getSnippet(0);
+ assertNotNull(snippet);
+ assertTrue("Wrong length: "+snippet.size(), 1 == snippet.size());
+
+ assertTrue("a".equals(snippet.get(0)));
+ }
+}
Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/location/LocationUtilsTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/location/LocationUtilsTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/location/LocationUtilsTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/location/LocationUtilsTest.java Fri Dec 2 16:33:03 2011
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2005 The Apache Software Foundation.
+ *
+ * Licensed 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.xwork2.util.location;
+
+import junit.framework.TestCase;
+
+public class LocationUtilsTest extends TestCase {
+
+ public LocationUtilsTest(String name) {
+ super(name);
+ }
+
+ static final String str = "path/to/file.xml:1:40";
+
+ public void testParse() throws Exception {
+ String str = "<map:generate> - path/to/file.xml:1:40";
+ Location loc = LocationUtils.parse(str);
+
+ assertEquals("<map:generate>", loc.getDescription());
+ assertEquals("URI", "path/to/file.xml", loc.getURI());
+ assertEquals("line", 1, loc.getLineNumber());
+ assertEquals("column", 40, loc.getColumnNumber());
+ assertEquals("string representation", str, loc.toString());
+ }
+
+ public void testGetLocation_location() throws Exception {
+ Location loc = new LocationImpl("desc", "sysId", 10, 4);
+ assertTrue("Location should be the same",
+ loc == LocationUtils.getLocation(loc, null));
+ }
+
+ public void testGetLocation_exception() throws Exception {
+ Exception e = new Exception();
+ Location loc = LocationUtils.getLocation(e, null);
+
+ assertTrue("Wrong sysId: "+loc.getURI(),
+ "org/apache/struts2/xwork2/util/location/LocationUtilsTest.java"
+ .equals(loc.getURI()));
+ }
+}
Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/logging/LoggerUtilsTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/logging/LoggerUtilsTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/logging/LoggerUtilsTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/logging/LoggerUtilsTest.java Fri Dec 2 16:33:03 2011
@@ -0,0 +1,22 @@
+package org.apache.struts2.xwork2.util.logging;
+
+
+import junit.framework.TestCase;
+
+public class LoggerUtilsTest extends TestCase {
+
+ public void testFormatMessage() {
+ assertEquals("foo", LoggerUtils.format("foo"));
+ assertEquals("foo #", LoggerUtils.format("foo #"));
+ assertEquals("#foo", LoggerUtils.format("#foo"));
+ assertEquals("foo #1", LoggerUtils.format("foo #1"));
+ assertEquals("foo bob", LoggerUtils.format("foo #0", "bob"));
+ assertEquals("foo bob joe", LoggerUtils.format("foo #0 #1", "bob", "joe"));
+ assertEquals("foo bob joe #8", LoggerUtils.format("foo #0 #1 #8", "bob", "joe"));
+
+ assertEquals(null, LoggerUtils.format(null));
+ assertEquals("", LoggerUtils.format(""));
+
+ }
+
+}
Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/profiling/ProfilingTimerBeanTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/profiling/ProfilingTimerBeanTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/profiling/ProfilingTimerBeanTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/profiling/ProfilingTimerBeanTest.java Fri Dec 2 16:33:03 2011
@@ -0,0 +1,124 @@
+/*
+ * Copyright 2002-2006,2009 The Apache Software Foundation.
+ *
+ * Licensed 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.xwork2.util.profiling;
+
+import junit.framework.TestCase;
+
+/**
+ *
+ * @author tm_jee
+ * @version $Date: 2011-12-02 12:24:48 +0100 (Fri, 02 Dec 2011) $ $Id: ProfilingTimerBeanTest.java 1209415 2011-12-02 11:24:48Z lukaszlenart $
+ */
+public class ProfilingTimerBeanTest extends TestCase {
+
+ public void testAddChild() throws Exception {
+ ProfilingTimerBean bean0 = new ProfilingTimerBean("bean0");
+ ProfilingTimerBean bean1 = new ProfilingTimerBean("bean1");
+ ProfilingTimerBean bean2 = new ProfilingTimerBean("bean2");
+ ProfilingTimerBean bean3 = new ProfilingTimerBean("bean3");
+ ProfilingTimerBean bean4 = new ProfilingTimerBean("bean4");
+ ProfilingTimerBean bean5 = new ProfilingTimerBean("bean5");
+ ProfilingTimerBean bean6 = new ProfilingTimerBean("bean6");
+ ProfilingTimerBean bean7 = new ProfilingTimerBean("bean7");
+ ProfilingTimerBean bean8 = new ProfilingTimerBean("bean8");
+
+ /* bean0
+ * + bean1
+ * + bean2
+ * + bean3
+ * + bean4
+ * + bean5
+ * + bean6
+ * +bean7
+ * + bean8
+ */
+
+ bean0.addChild(bean1);
+ bean0.addChild(bean3);
+ bean0.addChild(bean8);
+
+ bean1.addChild(bean2);
+
+ bean3.addChild(bean4);
+ bean3.addChild(bean7);
+
+ bean4.addChild(bean5);
+
+ bean5.addChild(bean6);
+
+
+ // bean0
+ assertNull(bean0.getParent());
+ assertEquals(bean0.children.size(), 3);
+ assertTrue(bean0.children.contains(bean1));
+ assertTrue(bean0.children.contains(bean3));
+ assertTrue(bean0.children.contains(bean8));
+
+ // bean1
+ assertEquals(bean1.getParent(), bean0);
+ assertEquals(bean1.children.size(), 1);
+ assertTrue(bean1.children.contains(bean2));
+
+ // bean2
+ assertEquals(bean2.getParent(), bean1);
+ assertEquals(bean2.children.size(), 0);
+
+ // bean3
+ assertEquals(bean3.getParent(), bean0);
+ assertEquals(bean3.children.size(), 2);
+ assertTrue(bean3.children.contains(bean4));
+ assertTrue(bean3.children.contains(bean7));
+
+ // bean4
+ assertEquals(bean4.getParent(), bean3);
+ assertEquals(bean4.children.size(), 1);
+ assertTrue(bean4.children.contains(bean5));
+
+ // bean5
+ assertEquals(bean5.getParent(), bean4);
+ assertEquals(bean5.children.size(), 1);
+ assertTrue(bean5.children.contains(bean6));
+
+ // bean6
+ assertEquals(bean6.getParent(), bean5);
+ assertEquals(bean6.children.size(), 0);
+
+ // bean7
+ assertEquals(bean7.getParent(), bean3);
+ assertEquals(bean7.children.size(), 0);
+
+ // bean8
+ assertEquals(bean8.getParent(), bean0);
+ assertEquals(bean8.children.size(), 0);
+ }
+
+ public void testTime() throws Exception {
+ ProfilingTimerBean bean0 = new ProfilingTimerBean("bean0");
+ bean0.setStartTime();
+ Thread.sleep(1050);
+ bean0.setEndTime();
+ assertTrue(bean0.totalTime >= 1000);
+ }
+
+ public void testPrint() throws Exception {
+ ProfilingTimerBean bean0 = new ProfilingTimerBean("bean0");
+ bean0.setStartTime();
+ Thread.sleep(1050);
+ bean0.setEndTime();
+ assertEquals(bean0.getPrintable(2000), "");
+ assertTrue(bean0.getPrintable(500).length() > 0);
+ }
+}
Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/profiling/UtilTimerStackTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/profiling/UtilTimerStackTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/profiling/UtilTimerStackTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/util/profiling/UtilTimerStackTest.java Fri Dec 2 16:33:03 2011
@@ -0,0 +1,133 @@
+/*
+ * Copyright 2002-2006,2009 The Apache Software Foundation.
+ *
+ * Licensed 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.xwork2.util.profiling;
+
+import junit.framework.TestCase;
+
+/**
+ * @author tmjee
+ * @version $Date: 2011-12-02 12:24:48 +0100 (Fri, 02 Dec 2011) $ $Id: UtilTimerStackTest.java 1209415 2011-12-02 11:24:48Z lukaszlenart $
+ */
+public class UtilTimerStackTest extends TestCase {
+
+ protected String activateProp;
+ protected String minTimeProp;
+
+
+ public void testActivateInactivate() throws Exception {
+ UtilTimerStack.setActive(true);
+ assertTrue(UtilTimerStack.isActive());
+ UtilTimerStack.setActive(false);
+ assertFalse(UtilTimerStack.isActive());
+ }
+
+
+ public void testPushPop() throws Exception {
+ UtilTimerStack.push("p1");
+ Thread.sleep(1050);
+ ProfilingTimerBean bean = UtilTimerStack.current.get();
+ assertTrue(bean.startTime > 0);
+ UtilTimerStack.pop("p1");
+ assertTrue(bean.totalTime > 1000);
+ }
+
+
+ public void testProfileCallback() throws Exception {
+
+ MockProfilingBlock<String> block = new MockProfilingBlock<String>() {
+ @Override
+ public String performProfiling() throws Exception {
+ Thread.sleep(1050);
+ return "OK";
+ }
+ };
+ String result = UtilTimerStack.profile("p1", block);
+ assertEquals(result, "OK");
+ assertNotNull(block.getProfilingTimerBean());
+ assertTrue(block.getProfilingTimerBean().totalTime >= 1000);
+
+ }
+
+
+ public void testProfileCallbackThrowsException() throws Exception {
+ try {
+ UtilTimerStack.profile("p1",
+ new UtilTimerStack.ProfilingBlock<String>() {
+ public String doProfiling() throws Exception {
+ throw new RuntimeException("test");
+ }
+ });
+ fail("exception should have been thrown");
+ }
+ catch (Exception e) {
+ assertTrue(true);
+ }
+ }
+
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+
+ activateProp = System.getProperty(UtilTimerStack.ACTIVATE_PROPERTY);
+ minTimeProp = System.getProperty(UtilTimerStack.MIN_TIME);
+
+ System.setProperty(UtilTimerStack.ACTIVATE_PROPERTY, "true");
+ UtilTimerStack.setActive(true);
+ System.setProperty(UtilTimerStack.MIN_TIME, "0");
+ }
+
+
+ @Override
+ protected void tearDown() throws Exception {
+
+ if (activateProp != null) {
+ System.setProperty(UtilTimerStack.ACTIVATE_PROPERTY, activateProp);
+ } else {
+ System.clearProperty(UtilTimerStack.ACTIVATE_PROPERTY);
+ }
+ if (minTimeProp != null) {
+ System.setProperty(UtilTimerStack.MIN_TIME, minTimeProp);
+ } else {
+ System.clearProperty(UtilTimerStack.ACTIVATE_PROPERTY);
+ }
+
+
+ activateProp = null;
+ minTimeProp = null;
+
+ super.tearDown();
+ }
+
+
+ public abstract class MockProfilingBlock<T> implements UtilTimerStack.ProfilingBlock<T> {
+
+ private ProfilingTimerBean bean;
+
+ public T doProfiling() throws Exception {
+ bean = UtilTimerStack.current.get();
+ return performProfiling();
+ }
+
+ public ProfilingTimerBean getProfilingTimerBean() {
+ return bean;
+ }
+
+ public abstract T performProfiling() throws Exception;
+ }
+}
+
+
Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/ActionValidatorManagerTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/ActionValidatorManagerTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/ActionValidatorManagerTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/ActionValidatorManagerTest.java Fri Dec 2 16:33:03 2011
@@ -0,0 +1,216 @@
+package org.apache.struts2.xwork2.validator;
+
+import org.apache.struts2.xwork2.ActionSupport;
+import org.apache.struts2.xwork2.XWorkTestCase;
+import org.apache.struts2.xwork2.util.ValueStack;
+import org.apache.struts2.xwork2.util.ValueStackFactory;
+import org.apache.struts2.xwork2.validator.validators.RequiredFieldValidator;
+import org.apache.struts2.xwork2.validator.validators.RequiredStringValidator;
+import org.apache.struts2.xwork2.validator.validators.VisitorFieldValidator;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * A test case for ActionValidatorManager.
+ *
+ * @author tmjee
+ * @version $Date: 2011-12-02 12:24:48 +0100 (Fri, 02 Dec 2011) $ $Id: ActionValidatorManagerTest.java 1209415 2011-12-02 11:24:48Z lukaszlenart $
+ */
+public class ActionValidatorManagerTest extends XWorkTestCase {
+
+
+
+ public void testValidate() throws Exception {
+ /* MockAction.class */
+ // reference number
+ ValueStack stack = container.getInstance(ValueStackFactory.class).createValueStack();
+ final RequiredStringValidator referenceNumberRequiredStringValidator = new RequiredStringValidator();
+ referenceNumberRequiredStringValidator.setFieldName("referenceNumber");
+ referenceNumberRequiredStringValidator.setDefaultMessage("Reference number is required");
+ referenceNumberRequiredStringValidator.setValueStack(stack);
+
+ // order
+ final RequiredFieldValidator orderRequiredValidator = new RequiredFieldValidator();
+ orderRequiredValidator.setFieldName("order");
+ orderRequiredValidator.setDefaultMessage("Order is required");
+ orderRequiredValidator.setValueStack(stack);
+
+ // customer
+ final RequiredFieldValidator customerRequiredValidator = new RequiredFieldValidator();
+ customerRequiredValidator.setFieldName("customer");
+ customerRequiredValidator.setDefaultMessage("Customer is required");
+ customerRequiredValidator.setValueStack(stack);
+ final VisitorFieldValidator customerVisitorValidator = new VisitorFieldValidator();
+ customerVisitorValidator.setAppendPrefix(true);
+ customerVisitorValidator.setFieldName("customer");
+ customerVisitorValidator.setValueStack(stack);
+
+ /* Customer.class */
+ // customer -> name
+ final RequiredStringValidator customerNameRequiredStringValidator = new RequiredStringValidator();
+ customerNameRequiredStringValidator.setFieldName("name");
+ customerNameRequiredStringValidator.setDefaultMessage("Name is required");
+ customerNameRequiredStringValidator.setValueStack(stack);
+
+ // customer -> age
+ final RequiredFieldValidator customerAgeRequiredValidator = new RequiredFieldValidator();
+ customerAgeRequiredValidator.setFieldName("age");
+ customerAgeRequiredValidator.setDefaultMessage("Age is required");
+ customerAgeRequiredValidator.setValueStack(stack);
+
+ // customer -> Address
+ final RequiredFieldValidator customerAddressRequiredFieldValidator = new RequiredFieldValidator();
+ customerAddressRequiredFieldValidator.setFieldName("address");
+ customerAddressRequiredFieldValidator.setDefaultMessage("Address is required");
+ customerAddressRequiredFieldValidator.setValueStack(stack);
+
+ final VisitorFieldValidator customerAddressVisitorFieldValidator = new VisitorFieldValidator();
+ customerAddressVisitorFieldValidator.setFieldName("address");
+ customerAddressVisitorFieldValidator.setAppendPrefix(true);
+ //customerAddressVisitorFieldValidator.setDefaultMessage("");
+ customerAddressVisitorFieldValidator.setValueStack(stack);
+
+
+
+ /* Address.class */
+ // customer -> Address -> street
+ final RequiredStringValidator customerAddressStreetRequiredFieldValidator = new RequiredStringValidator();
+ customerAddressStreetRequiredFieldValidator.setFieldName("street");
+ customerAddressStreetRequiredFieldValidator.setDefaultMessage("Street is required");
+ customerAddressStreetRequiredFieldValidator.setShortCircuit(true);
+ customerAddressStreetRequiredFieldValidator.setValueStack(stack);
+
+ final RequiredStringValidator customerAddressStreetRequiredFieldValidator2 = new RequiredStringValidator();
+ customerAddressStreetRequiredFieldValidator2.setFieldName("street");
+ customerAddressStreetRequiredFieldValidator2.setDefaultMessage("Street is required 2");
+ customerAddressStreetRequiredFieldValidator2.setShortCircuit(true);
+ customerAddressStreetRequiredFieldValidator2.setValueStack(stack);
+
+ // customer -> Address -> pobox
+ final RequiredStringValidator customerAddressPoboxRequiredFieldValidator = new RequiredStringValidator();
+ customerAddressPoboxRequiredFieldValidator.setFieldName("pobox");
+ customerAddressPoboxRequiredFieldValidator.setDefaultMessage("PO Box is required");
+ customerAddressPoboxRequiredFieldValidator.setShortCircuit(false);
+ customerAddressPoboxRequiredFieldValidator.setValueStack(stack);
+
+ final RequiredStringValidator customerAddressPoboxRequiredFieldValidator2 = new RequiredStringValidator();
+ customerAddressPoboxRequiredFieldValidator2.setFieldName("pobox");
+ customerAddressPoboxRequiredFieldValidator2.setDefaultMessage("PO Box is required 2");
+ customerAddressPoboxRequiredFieldValidator2.setShortCircuit(false);
+ customerAddressPoboxRequiredFieldValidator2.setValueStack(stack);
+
+
+
+ final List<Validator> validatorsForMockAction = new ArrayList<Validator>() {
+ {
+ add(referenceNumberRequiredStringValidator);
+ add(orderRequiredValidator);
+ add(customerRequiredValidator);
+ add(customerVisitorValidator);
+ }
+ };
+
+ final List<Validator> validatorsForCustomer = new ArrayList<Validator>() {
+ {
+ add(customerNameRequiredStringValidator);
+ add(customerAgeRequiredValidator);
+ add(customerAddressRequiredFieldValidator);
+ add(customerAddressVisitorFieldValidator);
+ }
+ };
+
+ final List<Validator> validatorsForAddress = new ArrayList<Validator>() {
+ {
+ add(customerAddressStreetRequiredFieldValidator);
+ add(customerAddressStreetRequiredFieldValidator2);
+ add(customerAddressPoboxRequiredFieldValidator);
+ add(customerAddressPoboxRequiredFieldValidator2);
+ }
+ };
+
+
+ DefaultActionValidatorManager validatorManager = new DefaultActionValidatorManager() {
+ @Override
+ public List<Validator> getValidators(Class clazz, String context, String method) {
+ if (clazz.isAssignableFrom(MockAction.class)) {
+ return validatorsForMockAction;
+ }
+ else if (clazz.isAssignableFrom(Customer.class)) {
+ return validatorsForCustomer;
+ }
+ else if (clazz.isAssignableFrom(Address.class)) {
+ return validatorsForAddress;
+ }
+ return Collections.emptyList();
+ }
+ };
+ customerVisitorValidator.setActionValidatorManager(validatorManager);
+ customerAddressVisitorFieldValidator.setActionValidatorManager(validatorManager);
+
+ MockAction action = new MockAction();
+ stack.push(action);
+ validatorManager.validate(action, "ctx");
+
+ assertFalse(action.hasActionErrors());
+ assertFalse(action.hasActionMessages());
+ assertTrue(action.hasFieldErrors());
+ assertTrue(action.getFieldErrors().containsKey("referenceNumber"));
+ assertEquals((action.getFieldErrors().get("referenceNumber")).size(), 1);
+ assertTrue(action.getFieldErrors().containsKey("order"));
+ assertEquals((action.getFieldErrors().get("order")).size(), 1);
+ assertTrue(action.getFieldErrors().containsKey("customer.name"));
+ assertEquals((action.getFieldErrors().get("customer.name")).size(), 1);
+ assertTrue(action.getFieldErrors().containsKey("customer.age"));
+ assertEquals((action.getFieldErrors().get("customer.age")).size(), 1);
+ assertTrue(action.getFieldErrors().containsKey("customer.address.street"));
+ assertEquals((action.getFieldErrors().get("customer.address.street")).size(), 1);
+ assertTrue(action.getFieldErrors().containsKey("customer.address.pobox"));
+ assertEquals((action.getFieldErrors().get("customer.address.pobox")).size(), 2);
+ }
+
+ private class MockAction extends ActionSupport {
+
+ private String referenceNumber;
+ private Integer order;
+ private Customer customer = new Customer();
+
+
+ public String getReferenceNumber() { return referenceNumber; }
+ public void setReferenceNumber(String referenceNumber) { this.referenceNumber = referenceNumber; }
+
+ public Integer getOrder() { return order; }
+ public void setOrder(Integer order) { this.order = order; }
+
+ public Customer getCustomer() { return customer; }
+ public void setCustomer(Customer customer) { this.customer = customer; }
+ }
+
+
+ private class Customer {
+ private String name;
+ private Integer age;
+ private Address address = new Address();
+
+ public String getName() { return name; }
+ public void setName(String name) { this.name = name; }
+
+ public Integer getAge() { return age; }
+ public void setAge(Integer age) { this.age = age; }
+
+ public Address getAddress() { return address; }
+ public void setAddress(Address address) { this.address = address; }
+ }
+
+ private class Address {
+ private String street;
+ private String pobox;
+
+ public String getStreet() { return street; }
+ public void setStreet(String street) { this.street = street; }
+
+ public String getPobox() { return pobox; }
+ public void setPobox(String pobox) { this.pobox = pobox; }
+ }
+}
\ No newline at end of file
Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/AnnotationActionValidatorManagerTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/AnnotationActionValidatorManagerTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/AnnotationActionValidatorManagerTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/AnnotationActionValidatorManagerTest.java Fri Dec 2 16:33:03 2011
@@ -0,0 +1,410 @@
+/*
+ * Copyright 2002-2006,2009 The Apache Software Foundation.
+ *
+ * Licensed 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.xwork2.validator;
+
+import org.apache.struts2.xwork2.Action;
+import org.apache.struts2.xwork2.ActionContext;
+import org.apache.struts2.xwork2.ActionInvocation;
+import org.apache.struts2.xwork2.ActionProxy;
+import org.apache.struts2.xwork2.config.entities.ActionConfig;
+import org.apache.struts2.xwork2.AnnotatedTestBean;
+import org.apache.struts2.xwork2.test.AnnotationDataAware2;
+import org.apache.struts2.xwork2.test.AnnotationUser;
+import org.apache.struts2.xwork2.test.SimpleAnnotationAction2;
+import org.apache.struts2.xwork2.test.SimpleAnnotationAction3;
+import org.apache.struts2.xwork2.util.FileManager;
+import org.apache.struts2.xwork2.XWorkTestCase;
+import org.apache.struts2.xwork2.validator.validators.DateRangeFieldValidator;
+import org.apache.struts2.xwork2.validator.validators.DoubleRangeFieldValidator;
+import org.apache.struts2.xwork2.validator.validators.EmailValidator;
+import org.apache.struts2.xwork2.validator.validators.ExpressionValidator;
+import org.apache.struts2.xwork2.validator.validators.IntRangeFieldValidator;
+import org.apache.struts2.xwork2.validator.validators.RequiredFieldValidator;
+import org.apache.struts2.xwork2.validator.validators.RequiredStringValidator;
+import org.apache.struts2.xwork2.validator.validators.StringLengthFieldValidator;
+import org.apache.struts2.xwork2.validator.validators.URLValidator;
+import org.apache.struts2.xwork2.SimpleAction;
+import org.apache.struts2.xwork2.SimpleAnnotationAction;
+import org.easymock.EasyMock;
+
+import java.util.List;
+
+
+
+/**
+ * AnnotationActionValidatorManagerTest
+ *
+ * @author Rainer Hermanns
+ * @author Jason Carreira
+ * @author tm_jee ( tm_jee (at) yahoo.co.uk )
+ * Created Jun 9, 2003 11:03:01 AM
+ */
+public class AnnotationActionValidatorManagerTest extends XWorkTestCase {
+
+ protected final String alias = "annotationValidationAlias";
+
+ AnnotationActionValidatorManager annotationActionValidatorManager;
+
+ @Override protected void setUp() throws Exception {
+ super.setUp();
+ annotationActionValidatorManager = (AnnotationActionValidatorManager) container.getInstance(ActionValidatorManager.class);
+
+ ActionConfig config = new ActionConfig.Builder("packageName", "name", "").build();
+ ActionInvocation invocation = EasyMock.createNiceMock(ActionInvocation.class);
+ ActionProxy proxy = EasyMock.createNiceMock(ActionProxy.class);
+
+ EasyMock.expect(invocation.getProxy()).andReturn(proxy).anyTimes();
+ EasyMock.expect(invocation.getAction()).andReturn(null).anyTimes();
+ EasyMock.expect(invocation.invoke()).andReturn(Action.SUCCESS).anyTimes();
+ EasyMock.expect(proxy.getMethod()).andReturn("execute").anyTimes();
+ EasyMock.expect(proxy.getConfig()).andReturn(config).anyTimes();
+
+
+ EasyMock.replay(invocation);
+ EasyMock.replay(proxy);
+
+ ActionContext.getContext().setActionInvocation(invocation);
+ }
+
+ @Override protected void tearDown() throws Exception {
+ annotationActionValidatorManager = null;
+ super.tearDown();
+ }
+
+ public void testBuildValidatorKey() {
+ String validatorKey = AnnotationActionValidatorManager.buildValidatorKey(SimpleAnnotationAction.class);
+ assertEquals(SimpleAnnotationAction.class.getName() + "/packageName/name|execute", validatorKey);
+ }
+
+ public void testBuildsValidatorsForAlias() {
+ List validatorList = annotationActionValidatorManager.getValidators(SimpleAnnotationAction.class, alias);
+
+ // 17 in the class level + 0 in the alias
+ // TODO: add alias tests
+ assertEquals(17, validatorList.size());
+ }
+
+ public void testGetValidatorsForGivenMethodNameWithoutReloading() throws ValidationException {
+ List validatorList = annotationActionValidatorManager.getValidators(SimpleAnnotationAction.class, alias, "execute");
+
+ //disable configuration reload/devmode
+ FileManager.setReloadingConfigs(false);
+
+ //17 in the class level + 0 in the alias
+ assertEquals(12, validatorList.size());
+
+ validatorList = annotationActionValidatorManager.getValidators(SimpleAnnotationAction.class, alias, "execute");
+
+ //expect same number of validators
+ assertEquals(12, validatorList.size());
+ }
+
+ public void testDefaultMessageInterpolation() {
+ // get validators
+ List validatorList = annotationActionValidatorManager.getValidators(AnnotatedTestBean.class, "beanMessageBundle");
+ assertEquals(3, validatorList.size());
+
+ try {
+ AnnotatedTestBean bean = new AnnotatedTestBean();
+ bean.setName("foo");
+ bean.setCount(99);
+
+ ValidatorContext context = new GenericValidatorContext(bean);
+ annotationActionValidatorManager.validate(bean, "beanMessageBundle", context);
+ assertTrue(context.hasErrors());
+ assertTrue(context.hasFieldErrors());
+
+ List<String> l = context.getFieldErrors().get("count");
+ assertNotNull(l);
+ assertEquals(1, l.size());
+ assertEquals("Smaller Invalid Count: 99", l.get(0));
+ } catch (ValidationException ex) {
+ ex.printStackTrace();
+ fail("Validation error: " + ex.getMessage());
+ }
+ }
+
+ public void testGetValidatorsForInterface() {
+ List validatorList = annotationActionValidatorManager.getValidators(AnnotationDataAware2.class, alias);
+
+ // 1 in interface hierarchy, 2 from parent interface (1 default + 1 context)
+ assertEquals(3, validatorList.size());
+
+ final FieldValidator dataValidator1 = (FieldValidator) validatorList.get(0);
+ assertEquals("data", dataValidator1.getFieldName());
+ assertTrue(dataValidator1 instanceof RequiredFieldValidator);
+
+ final FieldValidator dataValidator2 = (FieldValidator) validatorList.get(1);
+ assertEquals("data", dataValidator2.getFieldName());
+ assertTrue(dataValidator2 instanceof RequiredStringValidator);
+
+ final FieldValidator blingValidator = (FieldValidator) validatorList.get(2);
+ assertEquals("bling", blingValidator.getFieldName());
+ assertTrue(blingValidator instanceof RequiredStringValidator);
+ }
+
+ public void no_testGetValidatorsFromInterface() {
+ List validatorList = annotationActionValidatorManager.getValidators(SimpleAnnotationAction3.class, alias);
+
+ // 17 in the class hierarchy + 1 in the interface + 1 in interface alias
+ assertEquals(19, validatorList.size());
+
+ final FieldValidator v = (FieldValidator) validatorList.get(0);
+ assertEquals("bar", v.getFieldName());
+ assertTrue(v instanceof RequiredFieldValidator);
+
+ final FieldValidator v1 = (FieldValidator) validatorList.get(1);
+ assertEquals("bar", v1.getFieldName());
+ assertTrue(v1 instanceof IntRangeFieldValidator);
+
+ final FieldValidator vdouble = (FieldValidator) validatorList.get(2);
+ assertEquals("percentage", vdouble.getFieldName());
+ assertTrue(vdouble instanceof DoubleRangeFieldValidator);
+
+ final FieldValidator v2 = (FieldValidator) validatorList.get(3);
+ assertEquals("baz", v2.getFieldName());
+ assertTrue(v2 instanceof IntRangeFieldValidator);
+
+ final FieldValidator v3 = (FieldValidator) validatorList.get(4);
+ assertEquals("date", v3.getFieldName());
+ assertTrue(v3 instanceof DateRangeFieldValidator);
+
+ // action-level validator comes first
+ final Validator v4 = (Validator) validatorList.get(5);
+ assertTrue(v4 instanceof ExpressionValidator);
+
+ // action-level validator comes first
+ final Validator v5 = (Validator) validatorList.get(6);
+ assertTrue(v5 instanceof ExpressionValidator);
+
+ // action-level validator comes first
+ final Validator v6 = (Validator) validatorList.get(7);
+ assertTrue(v6 instanceof ExpressionValidator);
+
+ // action-level validator comes first
+ final Validator v7 = (Validator) validatorList.get(8);
+ assertTrue(v7 instanceof ExpressionValidator);
+
+ // action-level validator comes first
+ final Validator v8 = (Validator) validatorList.get(9);
+ assertTrue(v8 instanceof ExpressionValidator);
+
+ final FieldValidator v9 = (FieldValidator) validatorList.get(10);
+ assertEquals("datefield", v9.getFieldName());
+ assertTrue(v9 instanceof DateRangeFieldValidator);
+
+ final FieldValidator v10 = (FieldValidator) validatorList.get(11);
+ assertEquals("emailaddress", v10.getFieldName());
+ assertTrue(v10 instanceof EmailValidator);
+
+ final FieldValidator v11 = (FieldValidator) validatorList.get(12);
+ assertEquals("intfield", v11.getFieldName());
+ assertTrue(v11 instanceof IntRangeFieldValidator);
+
+ final FieldValidator v12 = (FieldValidator) validatorList.get(13);
+ assertEquals("customfield", v12.getFieldName());
+ assertTrue(v12 instanceof RequiredFieldValidator);
+
+ final FieldValidator v13 = (FieldValidator) validatorList.get(14);
+ assertEquals("stringisrequired", v13.getFieldName());
+ assertTrue(v13 instanceof RequiredStringValidator);
+
+ final FieldValidator v14 = (FieldValidator) validatorList.get(15);
+ assertEquals("needstringlength", v14.getFieldName());
+ assertTrue(v14 instanceof StringLengthFieldValidator);
+
+ final FieldValidator v15 = (FieldValidator) validatorList.get(16);
+ assertEquals("hreflocation", v15.getFieldName());
+ assertTrue(v15 instanceof URLValidator);
+
+ final FieldValidator v16 = (FieldValidator) validatorList.get(17);
+ assertEquals("data", v16.getFieldName());
+ assertTrue(v16 instanceof RequiredFieldValidator);
+
+ final FieldValidator v17 = (FieldValidator) validatorList.get(18);
+ assertEquals("data", v17.getFieldName());
+ assertTrue(v17 instanceof RequiredStringValidator);
+
+ }
+
+ public void testMessageInterpolation() {
+ // get validators
+ List validatorList = annotationActionValidatorManager.getValidators(AnnotatedTestBean.class, "beanMessageBundle");
+ assertEquals(3, validatorList.size());
+
+ try {
+ AnnotatedTestBean bean = new AnnotatedTestBean();
+ bean.setName("foo");
+ bean.setCount(150);
+
+ ValidatorContext context = new GenericValidatorContext(bean);
+ annotationActionValidatorManager.validate(bean, "beanMessageBundle", context);
+ assertTrue(context.hasErrors());
+ assertTrue(context.hasFieldErrors());
+
+ List<String> l = context.getFieldErrors().get("count");
+ assertNotNull(l);
+ assertEquals(1, l.size());
+ assertEquals("Count must be between 1 and 100, current value is 150.", l.get(0));
+ } catch (ValidationException ex) {
+ ex.printStackTrace();
+ fail("Validation error: " + ex.getMessage());
+ }
+ }
+
+ public void testSameAliasWithDifferentClass() {
+ List validatorList = annotationActionValidatorManager.getValidators(SimpleAnnotationAction.class, alias);
+ List validatorList2 = annotationActionValidatorManager.getValidators(SimpleAnnotationAction2.class, alias);
+ assertFalse(validatorList.size() == validatorList2.size());
+ }
+
+ public void testSameAliasWithAliasWithSlashes() {
+ List validatorList = annotationActionValidatorManager.getValidators(SimpleAction.class, "some/alias");
+ assertNotNull(validatorList);
+ assertEquals(11, validatorList.size());
+ }
+
+ public void testSkipUserMarkerActionLevelShortCircuit() {
+ // get validators
+ List validatorList = annotationActionValidatorManager.getValidators(AnnotationUser.class, null);
+ assertEquals(10, validatorList.size());
+
+ try {
+ AnnotationUser user = new AnnotationUser();
+ user.setName("Mark");
+ user.setEmail("bad_email");
+ user.setEmail2("bad_email");
+
+ ValidatorContext context = new GenericValidatorContext(user);
+ annotationActionValidatorManager.validate(user, null, context);
+ assertTrue(context.hasFieldErrors());
+
+ // check field errors
+ List<String> l = context.getFieldErrors().get("email");
+ assertNotNull(l);
+ assertEquals(1, l.size());
+ assertEquals("Not a valid e-mail.", l.get(0));
+ l = context.getFieldErrors().get("email2");
+ assertNotNull(l);
+ assertEquals(2, l.size());
+ assertEquals("Not a valid e-mail2.", l.get(0));
+ assertEquals("Email2 not from the right company.", l.get(1));
+
+ // check action errors
+ assertTrue(context.hasActionErrors());
+ l = (List<String>) context.getActionErrors();
+ assertNotNull(l);
+ assertEquals(2, l.size()); // both expression test failed see AnnotationUser-validation.xml
+ assertEquals("Email does not start with mark", l.get(0));
+ } catch (ValidationException ex) {
+ ex.printStackTrace();
+ fail("Validation error: " + ex.getMessage());
+ }
+ }
+
+ public void testSkipAllActionLevelShortCircuit2() {
+ // get validators
+ List validatorList = annotationActionValidatorManager.getValidators(AnnotationUser.class, null);
+ assertEquals(10, validatorList.size());
+
+ try {
+ AnnotationUser user = new AnnotationUser();
+ user.setName("Mark");
+ // * mark both email to starts with mark to get pass the action-level validator,
+ // so we could concentrate on testing the field-level validators (AnnotationUser-validation.xml)
+ // * make both email the same to pass the action-level validator at
+ // AnnotationUserMarker-validation.xml
+ user.setEmail("mark_bad_email_for_field_val@foo.com");
+ user.setEmail2("mark_bad_email_for_field_val@foo.com");
+
+ ValidatorContext context = new GenericValidatorContext(user);
+ annotationActionValidatorManager.validate(user, null, context);
+ assertTrue(context.hasFieldErrors());
+
+ // check field errors
+ // we have an error in this field level, email does not ends with mycompany.com
+ List l = (List) context.getFieldErrors().get("email");
+ assertNotNull(l);
+ assertEquals(1, l.size()); // because email-field-val is short-circuit
+ assertEquals("Email not from the right company.", l.get(0));
+
+
+ // check action errors
+ l = (List) context.getActionErrors();
+ assertFalse(context.hasActionErrors());
+ assertEquals(0, l.size());
+
+
+ } catch (ValidationException ex) {
+ ex.printStackTrace();
+ fail("Validation error: " + ex.getMessage());
+ }
+ }
+
+
+ public void testActionLevelShortCircuit() throws Exception {
+
+ List validatorList = annotationActionValidatorManager.getValidators(AnnotationUser.class, null);
+ assertEquals(10, validatorList.size());
+
+ AnnotationUser user = new AnnotationUser();
+ // all fields will trigger error, but sc of action-level, cause it to not appear
+ user.setName(null);
+
+ user.setEmail("rainerh(at)example.com");
+ user.setEmail("rainer_h(at)example.com");
+
+
+ ValidatorContext context = new GenericValidatorContext(user);
+ annotationActionValidatorManager.validate(user, null, context);
+
+ // check field level errors
+ // shouldn't have any because action error prevents validation of anything else
+ List l = (List) context.getFieldErrors().get("email2");
+ assertNull(l);
+
+
+ // check action errors
+ assertTrue(context.hasActionErrors());
+ l = (List) context.getActionErrors();
+ assertNotNull(l);
+ // we only get one, because AnnotationUserMarker-validation.xml action-level validator
+ // already sc it :-)
+ assertEquals(1, l.size());
+ assertEquals("Email not the same as email2", l.get(0));
+ }
+
+
+ public void testShortCircuitNoErrors() {
+ // get validators
+ List validatorList = annotationActionValidatorManager.getValidators(AnnotationUser.class, null);
+ assertEquals(10, validatorList.size());
+
+ try {
+ AnnotationUser user = new AnnotationUser();
+ user.setName("Mark");
+ user.setEmail("mark@mycompany.com");
+ user.setEmail2("mark@mycompany.com");
+
+ ValidatorContext context = new GenericValidatorContext(user);
+ annotationActionValidatorManager.validate(user, null, context);
+ assertFalse(context.hasErrors());
+ } catch (ValidationException ex) {
+ ex.printStackTrace();
+ fail("Validation error: " + ex.getMessage());
+ }
+ }
+}
Added: struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/ConversionErrorFieldValidatorTest.java
URL: http://svn.apache.org/viewvc/struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/ConversionErrorFieldValidatorTest.java?rev=1209569&view=auto
==============================================================================
--- struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/ConversionErrorFieldValidatorTest.java (added)
+++ struts/struts2/branches/STRUTS_3_X/xwork-core/src/test/java/org/apache/struts2/xwork2/validator/ConversionErrorFieldValidatorTest.java Fri Dec 2 16:33:03 2011
@@ -0,0 +1,84 @@
+/*
+ * Copyright 2002-2003,2009 The Apache Software Foundation.
+ *
+ * Licensed 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.xwork2.validator;
+
+import org.apache.struts2.xwork2.ActionContext;
+import org.apache.struts2.xwork2.ValidationAware;
+import org.apache.struts2.xwork2.ValidationAwareSupport;
+import org.apache.struts2.xwork2.XWorkTestCase;
+import org.apache.struts2.xwork2.util.ValueStack;
+import org.apache.struts2.xwork2.validator.validators.ConversionErrorFieldValidator;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+
+/**
+ * ConversionErrorFieldValidatorTest
+ *
+ * @author Jason Carreira
+ * Date: Nov 28, 2003 3:45:37 PM
+ */
+public class ConversionErrorFieldValidatorTest extends XWorkTestCase {
+
+ private static final String defaultFooMessage = "Invalid field value for field \"foo\".";
+
+
+ private ConversionErrorFieldValidator validator;
+ private ValidationAware validationAware;
+
+
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ ValueStack stack = ActionContext.getContext().getValueStack();
+ ActionContext context = new ActionContext(stack.getContext());
+
+ Map<String, Object> conversionErrors = new HashMap<String, Object>();
+ conversionErrors.put("foo", "bar");
+ context.setConversionErrors(conversionErrors);
+ validator = new ConversionErrorFieldValidator();
+ validationAware = new ValidationAwareSupport();
+
+ DelegatingValidatorContext validatorContext = new DelegatingValidatorContext(validationAware);
+ stack.push(validatorContext);
+ validator.setValidatorContext(validatorContext);
+ validator.setFieldName("foo");
+ validator.setValueStack(ActionContext.getContext().getValueStack());
+ assertEquals(0, validationAware.getFieldErrors().size());
+ }
+
+ public void testConversionErrorMessageUsesProvidedMessage() throws ValidationException {
+ String message = "default message";
+ validator.setDefaultMessage(message);
+ validator.validate(validationAware);
+
+
+ Map fieldErrors = validationAware.getFieldErrors();
+ assertTrue(fieldErrors.containsKey("foo"));
+ assertEquals(message, ((List) fieldErrors.get("foo")).get(0));
+ }
+
+ public void testConversionErrorsAreAddedToFieldErrors() throws ValidationException {
+ validator.validate(validationAware);
+
+ Map fieldErrors = validationAware.getFieldErrors();
+ assertTrue(fieldErrors.containsKey("foo"));
+ assertEquals(defaultFooMessage, ((List) fieldErrors.get("foo")).get(0));
+ }
+
+}